SelectionDAG.cpp 341 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418
  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. SDValue SelectionDAG::getPtrExtOrTrunc(SDValue Op, const SDLoc &DL, EVT VT) {
  1019. // Only unsigned pointer semantics are supported right now. In the future this
  1020. // might delegate to TLI to check pointer signedness.
  1021. return getZExtOrTrunc(Op, DL, VT);
  1022. }
  1023. SDValue SelectionDAG::getPtrExtendInReg(SDValue Op, const SDLoc &DL, EVT VT) {
  1024. // Only unsigned pointer semantics are supported right now. In the future this
  1025. // might delegate to TLI to check pointer signedness.
  1026. return getZeroExtendInReg(Op, DL, VT);
  1027. }
  1028. /// getNOT - Create a bitwise NOT operation as (XOR Val, -1).
  1029. SDValue SelectionDAG::getNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1030. EVT EltVT = VT.getScalarType();
  1031. SDValue NegOne =
  1032. getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), DL, VT);
  1033. return getNode(ISD::XOR, DL, VT, Val, NegOne);
  1034. }
  1035. SDValue SelectionDAG::getLogicalNOT(const SDLoc &DL, SDValue Val, EVT VT) {
  1036. SDValue TrueValue = getBoolConstant(true, DL, VT, VT);
  1037. return getNode(ISD::XOR, DL, VT, Val, TrueValue);
  1038. }
  1039. SDValue SelectionDAG::getBoolConstant(bool V, const SDLoc &DL, EVT VT,
  1040. EVT OpVT) {
  1041. if (!V)
  1042. return getConstant(0, DL, VT);
  1043. switch (TLI->getBooleanContents(OpVT)) {
  1044. case TargetLowering::ZeroOrOneBooleanContent:
  1045. case TargetLowering::UndefinedBooleanContent:
  1046. return getConstant(1, DL, VT);
  1047. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  1048. return getAllOnesConstant(DL, VT);
  1049. }
  1050. llvm_unreachable("Unexpected boolean content enum!");
  1051. }
  1052. SDValue SelectionDAG::getConstant(uint64_t Val, const SDLoc &DL, EVT VT,
  1053. bool isT, bool isO) {
  1054. EVT EltVT = VT.getScalarType();
  1055. assert((EltVT.getSizeInBits() >= 64 ||
  1056. (uint64_t)((int64_t)Val >> EltVT.getSizeInBits()) + 1 < 2) &&
  1057. "getConstant with a uint64_t value that doesn't fit in the type!");
  1058. return getConstant(APInt(EltVT.getSizeInBits(), Val), DL, VT, isT, isO);
  1059. }
  1060. SDValue SelectionDAG::getConstant(const APInt &Val, const SDLoc &DL, EVT VT,
  1061. bool isT, bool isO) {
  1062. return getConstant(*ConstantInt::get(*Context, Val), DL, VT, isT, isO);
  1063. }
  1064. SDValue SelectionDAG::getConstant(const ConstantInt &Val, const SDLoc &DL,
  1065. EVT VT, bool isT, bool isO) {
  1066. assert(VT.isInteger() && "Cannot create FP integer constant!");
  1067. EVT EltVT = VT.getScalarType();
  1068. const ConstantInt *Elt = &Val;
  1069. // In some cases the vector type is legal but the element type is illegal and
  1070. // needs to be promoted, for example v8i8 on ARM. In this case, promote the
  1071. // inserted value (the type does not need to match the vector element type).
  1072. // Any extra bits introduced will be truncated away.
  1073. if (VT.isVector() && TLI->getTypeAction(*getContext(), EltVT) ==
  1074. TargetLowering::TypePromoteInteger) {
  1075. EltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1076. APInt NewVal = Elt->getValue().zextOrTrunc(EltVT.getSizeInBits());
  1077. Elt = ConstantInt::get(*getContext(), NewVal);
  1078. }
  1079. // In other cases the element type is illegal and needs to be expanded, for
  1080. // example v2i64 on MIPS32. In this case, find the nearest legal type, split
  1081. // the value into n parts and use a vector type with n-times the elements.
  1082. // Then bitcast to the type requested.
  1083. // Legalizing constants too early makes the DAGCombiner's job harder so we
  1084. // only legalize if the DAG tells us we must produce legal types.
  1085. else if (NewNodesMustHaveLegalTypes && VT.isVector() &&
  1086. TLI->getTypeAction(*getContext(), EltVT) ==
  1087. TargetLowering::TypeExpandInteger) {
  1088. const APInt &NewVal = Elt->getValue();
  1089. EVT ViaEltVT = TLI->getTypeToTransformTo(*getContext(), EltVT);
  1090. unsigned ViaEltSizeInBits = ViaEltVT.getSizeInBits();
  1091. unsigned ViaVecNumElts = VT.getSizeInBits() / ViaEltSizeInBits;
  1092. EVT ViaVecVT = EVT::getVectorVT(*getContext(), ViaEltVT, ViaVecNumElts);
  1093. // Check the temporary vector is the correct size. If this fails then
  1094. // getTypeToTransformTo() probably returned a type whose size (in bits)
  1095. // isn't a power-of-2 factor of the requested type size.
  1096. assert(ViaVecVT.getSizeInBits() == VT.getSizeInBits());
  1097. SmallVector<SDValue, 2> EltParts;
  1098. for (unsigned i = 0; i < ViaVecNumElts / VT.getVectorNumElements(); ++i) {
  1099. EltParts.push_back(getConstant(NewVal.lshr(i * ViaEltSizeInBits)
  1100. .zextOrTrunc(ViaEltSizeInBits), DL,
  1101. ViaEltVT, isT, isO));
  1102. }
  1103. // EltParts is currently in little endian order. If we actually want
  1104. // big-endian order then reverse it now.
  1105. if (getDataLayout().isBigEndian())
  1106. std::reverse(EltParts.begin(), EltParts.end());
  1107. // The elements must be reversed when the element order is different
  1108. // to the endianness of the elements (because the BITCAST is itself a
  1109. // vector shuffle in this situation). However, we do not need any code to
  1110. // perform this reversal because getConstant() is producing a vector
  1111. // splat.
  1112. // This situation occurs in MIPS MSA.
  1113. SmallVector<SDValue, 8> Ops;
  1114. for (unsigned i = 0, e = VT.getVectorNumElements(); i != e; ++i)
  1115. Ops.insert(Ops.end(), EltParts.begin(), EltParts.end());
  1116. SDValue V = getNode(ISD::BITCAST, DL, VT, getBuildVector(ViaVecVT, DL, Ops));
  1117. return V;
  1118. }
  1119. assert(Elt->getBitWidth() == EltVT.getSizeInBits() &&
  1120. "APInt size does not match type size!");
  1121. unsigned Opc = isT ? ISD::TargetConstant : ISD::Constant;
  1122. FoldingSetNodeID ID;
  1123. AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
  1124. ID.AddPointer(Elt);
  1125. ID.AddBoolean(isO);
  1126. void *IP = nullptr;
  1127. SDNode *N = nullptr;
  1128. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1129. if (!VT.isVector())
  1130. return SDValue(N, 0);
  1131. if (!N) {
  1132. N = newSDNode<ConstantSDNode>(isT, isO, Elt, EltVT);
  1133. CSEMap.InsertNode(N, IP);
  1134. InsertNode(N);
  1135. NewSDValueDbgMsg(SDValue(N, 0), "Creating constant: ", this);
  1136. }
  1137. SDValue Result(N, 0);
  1138. if (VT.isVector())
  1139. Result = getSplatBuildVector(VT, DL, Result);
  1140. return Result;
  1141. }
  1142. SDValue SelectionDAG::getIntPtrConstant(uint64_t Val, const SDLoc &DL,
  1143. bool isTarget) {
  1144. return getConstant(Val, DL, TLI->getPointerTy(getDataLayout()), isTarget);
  1145. }
  1146. SDValue SelectionDAG::getShiftAmountConstant(uint64_t Val, EVT VT,
  1147. const SDLoc &DL, bool LegalTypes) {
  1148. EVT ShiftVT = TLI->getShiftAmountTy(VT, getDataLayout(), LegalTypes);
  1149. return getConstant(Val, DL, ShiftVT);
  1150. }
  1151. SDValue SelectionDAG::getConstantFP(const APFloat &V, const SDLoc &DL, EVT VT,
  1152. bool isTarget) {
  1153. return getConstantFP(*ConstantFP::get(*getContext(), V), DL, VT, isTarget);
  1154. }
  1155. SDValue SelectionDAG::getConstantFP(const ConstantFP &V, const SDLoc &DL,
  1156. EVT VT, bool isTarget) {
  1157. assert(VT.isFloatingPoint() && "Cannot create integer FP constant!");
  1158. EVT EltVT = VT.getScalarType();
  1159. // Do the map lookup using the actual bit pattern for the floating point
  1160. // value, so that we don't have problems with 0.0 comparing equal to -0.0, and
  1161. // we don't have issues with SNANs.
  1162. unsigned Opc = isTarget ? ISD::TargetConstantFP : ISD::ConstantFP;
  1163. FoldingSetNodeID ID;
  1164. AddNodeIDNode(ID, Opc, getVTList(EltVT), None);
  1165. ID.AddPointer(&V);
  1166. void *IP = nullptr;
  1167. SDNode *N = nullptr;
  1168. if ((N = FindNodeOrInsertPos(ID, DL, IP)))
  1169. if (!VT.isVector())
  1170. return SDValue(N, 0);
  1171. if (!N) {
  1172. N = newSDNode<ConstantFPSDNode>(isTarget, &V, EltVT);
  1173. CSEMap.InsertNode(N, IP);
  1174. InsertNode(N);
  1175. }
  1176. SDValue Result(N, 0);
  1177. if (VT.isVector())
  1178. Result = getSplatBuildVector(VT, DL, Result);
  1179. NewSDValueDbgMsg(Result, "Creating fp constant: ", this);
  1180. return Result;
  1181. }
  1182. SDValue SelectionDAG::getConstantFP(double Val, const SDLoc &DL, EVT VT,
  1183. bool isTarget) {
  1184. EVT EltVT = VT.getScalarType();
  1185. if (EltVT == MVT::f32)
  1186. return getConstantFP(APFloat((float)Val), DL, VT, isTarget);
  1187. else if (EltVT == MVT::f64)
  1188. return getConstantFP(APFloat(Val), DL, VT, isTarget);
  1189. else if (EltVT == MVT::f80 || EltVT == MVT::f128 || EltVT == MVT::ppcf128 ||
  1190. EltVT == MVT::f16) {
  1191. bool Ignored;
  1192. APFloat APF = APFloat(Val);
  1193. APF.convert(EVTToAPFloatSemantics(EltVT), APFloat::rmNearestTiesToEven,
  1194. &Ignored);
  1195. return getConstantFP(APF, DL, VT, isTarget);
  1196. } else
  1197. llvm_unreachable("Unsupported type in getConstantFP");
  1198. }
  1199. SDValue SelectionDAG::getGlobalAddress(const GlobalValue *GV, const SDLoc &DL,
  1200. EVT VT, int64_t Offset, bool isTargetGA,
  1201. unsigned char TargetFlags) {
  1202. assert((TargetFlags == 0 || isTargetGA) &&
  1203. "Cannot set target flags on target-independent globals");
  1204. // Truncate (with sign-extension) the offset value to the pointer size.
  1205. unsigned BitWidth = getDataLayout().getPointerTypeSizeInBits(GV->getType());
  1206. if (BitWidth < 64)
  1207. Offset = SignExtend64(Offset, BitWidth);
  1208. unsigned Opc;
  1209. if (GV->isThreadLocal())
  1210. Opc = isTargetGA ? ISD::TargetGlobalTLSAddress : ISD::GlobalTLSAddress;
  1211. else
  1212. Opc = isTargetGA ? ISD::TargetGlobalAddress : ISD::GlobalAddress;
  1213. FoldingSetNodeID ID;
  1214. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1215. ID.AddPointer(GV);
  1216. ID.AddInteger(Offset);
  1217. ID.AddInteger(TargetFlags);
  1218. void *IP = nullptr;
  1219. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  1220. return SDValue(E, 0);
  1221. auto *N = newSDNode<GlobalAddressSDNode>(
  1222. Opc, DL.getIROrder(), DL.getDebugLoc(), GV, VT, Offset, TargetFlags);
  1223. CSEMap.InsertNode(N, IP);
  1224. InsertNode(N);
  1225. return SDValue(N, 0);
  1226. }
  1227. SDValue SelectionDAG::getFrameIndex(int FI, EVT VT, bool isTarget) {
  1228. unsigned Opc = isTarget ? ISD::TargetFrameIndex : ISD::FrameIndex;
  1229. FoldingSetNodeID ID;
  1230. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1231. ID.AddInteger(FI);
  1232. void *IP = nullptr;
  1233. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1234. return SDValue(E, 0);
  1235. auto *N = newSDNode<FrameIndexSDNode>(FI, VT, isTarget);
  1236. CSEMap.InsertNode(N, IP);
  1237. InsertNode(N);
  1238. return SDValue(N, 0);
  1239. }
  1240. SDValue SelectionDAG::getJumpTable(int JTI, EVT VT, bool isTarget,
  1241. unsigned char TargetFlags) {
  1242. assert((TargetFlags == 0 || isTarget) &&
  1243. "Cannot set target flags on target-independent jump tables");
  1244. unsigned Opc = isTarget ? ISD::TargetJumpTable : ISD::JumpTable;
  1245. FoldingSetNodeID ID;
  1246. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1247. ID.AddInteger(JTI);
  1248. ID.AddInteger(TargetFlags);
  1249. void *IP = nullptr;
  1250. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1251. return SDValue(E, 0);
  1252. auto *N = newSDNode<JumpTableSDNode>(JTI, VT, isTarget, TargetFlags);
  1253. CSEMap.InsertNode(N, IP);
  1254. InsertNode(N);
  1255. return SDValue(N, 0);
  1256. }
  1257. SDValue SelectionDAG::getConstantPool(const Constant *C, EVT VT,
  1258. unsigned Alignment, int Offset,
  1259. bool isTarget,
  1260. unsigned char TargetFlags) {
  1261. assert((TargetFlags == 0 || isTarget) &&
  1262. "Cannot set target flags on target-independent globals");
  1263. if (Alignment == 0)
  1264. Alignment = MF->getFunction().hasOptSize()
  1265. ? getDataLayout().getABITypeAlignment(C->getType())
  1266. : getDataLayout().getPrefTypeAlignment(C->getType());
  1267. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1268. FoldingSetNodeID ID;
  1269. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1270. ID.AddInteger(Alignment);
  1271. ID.AddInteger(Offset);
  1272. ID.AddPointer(C);
  1273. ID.AddInteger(TargetFlags);
  1274. void *IP = nullptr;
  1275. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1276. return SDValue(E, 0);
  1277. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
  1278. TargetFlags);
  1279. CSEMap.InsertNode(N, IP);
  1280. InsertNode(N);
  1281. return SDValue(N, 0);
  1282. }
  1283. SDValue SelectionDAG::getConstantPool(MachineConstantPoolValue *C, EVT VT,
  1284. unsigned Alignment, int Offset,
  1285. bool isTarget,
  1286. unsigned char TargetFlags) {
  1287. assert((TargetFlags == 0 || isTarget) &&
  1288. "Cannot set target flags on target-independent globals");
  1289. if (Alignment == 0)
  1290. Alignment = getDataLayout().getPrefTypeAlignment(C->getType());
  1291. unsigned Opc = isTarget ? ISD::TargetConstantPool : ISD::ConstantPool;
  1292. FoldingSetNodeID ID;
  1293. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1294. ID.AddInteger(Alignment);
  1295. ID.AddInteger(Offset);
  1296. C->addSelectionDAGCSEId(ID);
  1297. ID.AddInteger(TargetFlags);
  1298. void *IP = nullptr;
  1299. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1300. return SDValue(E, 0);
  1301. auto *N = newSDNode<ConstantPoolSDNode>(isTarget, C, VT, Offset, Alignment,
  1302. TargetFlags);
  1303. CSEMap.InsertNode(N, IP);
  1304. InsertNode(N);
  1305. return SDValue(N, 0);
  1306. }
  1307. SDValue SelectionDAG::getTargetIndex(int Index, EVT VT, int64_t Offset,
  1308. unsigned char TargetFlags) {
  1309. FoldingSetNodeID ID;
  1310. AddNodeIDNode(ID, ISD::TargetIndex, getVTList(VT), None);
  1311. ID.AddInteger(Index);
  1312. ID.AddInteger(Offset);
  1313. ID.AddInteger(TargetFlags);
  1314. void *IP = nullptr;
  1315. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1316. return SDValue(E, 0);
  1317. auto *N = newSDNode<TargetIndexSDNode>(Index, VT, Offset, TargetFlags);
  1318. CSEMap.InsertNode(N, IP);
  1319. InsertNode(N);
  1320. return SDValue(N, 0);
  1321. }
  1322. SDValue SelectionDAG::getBasicBlock(MachineBasicBlock *MBB) {
  1323. FoldingSetNodeID ID;
  1324. AddNodeIDNode(ID, ISD::BasicBlock, getVTList(MVT::Other), None);
  1325. ID.AddPointer(MBB);
  1326. void *IP = nullptr;
  1327. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1328. return SDValue(E, 0);
  1329. auto *N = newSDNode<BasicBlockSDNode>(MBB);
  1330. CSEMap.InsertNode(N, IP);
  1331. InsertNode(N);
  1332. return SDValue(N, 0);
  1333. }
  1334. SDValue SelectionDAG::getValueType(EVT VT) {
  1335. if (VT.isSimple() && (unsigned)VT.getSimpleVT().SimpleTy >=
  1336. ValueTypeNodes.size())
  1337. ValueTypeNodes.resize(VT.getSimpleVT().SimpleTy+1);
  1338. SDNode *&N = VT.isExtended() ?
  1339. ExtendedValueTypeNodes[VT] : ValueTypeNodes[VT.getSimpleVT().SimpleTy];
  1340. if (N) return SDValue(N, 0);
  1341. N = newSDNode<VTSDNode>(VT);
  1342. InsertNode(N);
  1343. return SDValue(N, 0);
  1344. }
  1345. SDValue SelectionDAG::getExternalSymbol(const char *Sym, EVT VT) {
  1346. SDNode *&N = ExternalSymbols[Sym];
  1347. if (N) return SDValue(N, 0);
  1348. N = newSDNode<ExternalSymbolSDNode>(false, Sym, 0, VT);
  1349. InsertNode(N);
  1350. return SDValue(N, 0);
  1351. }
  1352. SDValue SelectionDAG::getMCSymbol(MCSymbol *Sym, EVT VT) {
  1353. SDNode *&N = MCSymbols[Sym];
  1354. if (N)
  1355. return SDValue(N, 0);
  1356. N = newSDNode<MCSymbolSDNode>(Sym, VT);
  1357. InsertNode(N);
  1358. return SDValue(N, 0);
  1359. }
  1360. SDValue SelectionDAG::getTargetExternalSymbol(const char *Sym, EVT VT,
  1361. unsigned char TargetFlags) {
  1362. SDNode *&N =
  1363. TargetExternalSymbols[std::pair<std::string,unsigned char>(Sym,
  1364. TargetFlags)];
  1365. if (N) return SDValue(N, 0);
  1366. N = newSDNode<ExternalSymbolSDNode>(true, Sym, TargetFlags, VT);
  1367. InsertNode(N);
  1368. return SDValue(N, 0);
  1369. }
  1370. SDValue SelectionDAG::getCondCode(ISD::CondCode Cond) {
  1371. if ((unsigned)Cond >= CondCodeNodes.size())
  1372. CondCodeNodes.resize(Cond+1);
  1373. if (!CondCodeNodes[Cond]) {
  1374. auto *N = newSDNode<CondCodeSDNode>(Cond);
  1375. CondCodeNodes[Cond] = N;
  1376. InsertNode(N);
  1377. }
  1378. return SDValue(CondCodeNodes[Cond], 0);
  1379. }
  1380. /// Swaps the values of N1 and N2. Swaps all indices in the shuffle mask M that
  1381. /// point at N1 to point at N2 and indices that point at N2 to point at N1.
  1382. static void commuteShuffle(SDValue &N1, SDValue &N2, MutableArrayRef<int> M) {
  1383. std::swap(N1, N2);
  1384. ShuffleVectorSDNode::commuteMask(M);
  1385. }
  1386. SDValue SelectionDAG::getVectorShuffle(EVT VT, const SDLoc &dl, SDValue N1,
  1387. SDValue N2, ArrayRef<int> Mask) {
  1388. assert(VT.getVectorNumElements() == Mask.size() &&
  1389. "Must have the same number of vector elements as mask elements!");
  1390. assert(VT == N1.getValueType() && VT == N2.getValueType() &&
  1391. "Invalid VECTOR_SHUFFLE");
  1392. // Canonicalize shuffle undef, undef -> undef
  1393. if (N1.isUndef() && N2.isUndef())
  1394. return getUNDEF(VT);
  1395. // Validate that all indices in Mask are within the range of the elements
  1396. // input to the shuffle.
  1397. int NElts = Mask.size();
  1398. assert(llvm::all_of(Mask,
  1399. [&](int M) { return M < (NElts * 2) && M >= -1; }) &&
  1400. "Index out of range");
  1401. // Copy the mask so we can do any needed cleanup.
  1402. SmallVector<int, 8> MaskVec(Mask.begin(), Mask.end());
  1403. // Canonicalize shuffle v, v -> v, undef
  1404. if (N1 == N2) {
  1405. N2 = getUNDEF(VT);
  1406. for (int i = 0; i != NElts; ++i)
  1407. if (MaskVec[i] >= NElts) MaskVec[i] -= NElts;
  1408. }
  1409. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  1410. if (N1.isUndef())
  1411. commuteShuffle(N1, N2, MaskVec);
  1412. if (TLI->hasVectorBlend()) {
  1413. // If shuffling a splat, try to blend the splat instead. We do this here so
  1414. // that even when this arises during lowering we don't have to re-handle it.
  1415. auto BlendSplat = [&](BuildVectorSDNode *BV, int Offset) {
  1416. BitVector UndefElements;
  1417. SDValue Splat = BV->getSplatValue(&UndefElements);
  1418. if (!Splat)
  1419. return;
  1420. for (int i = 0; i < NElts; ++i) {
  1421. if (MaskVec[i] < Offset || MaskVec[i] >= (Offset + NElts))
  1422. continue;
  1423. // If this input comes from undef, mark it as such.
  1424. if (UndefElements[MaskVec[i] - Offset]) {
  1425. MaskVec[i] = -1;
  1426. continue;
  1427. }
  1428. // If we can blend a non-undef lane, use that instead.
  1429. if (!UndefElements[i])
  1430. MaskVec[i] = i + Offset;
  1431. }
  1432. };
  1433. if (auto *N1BV = dyn_cast<BuildVectorSDNode>(N1))
  1434. BlendSplat(N1BV, 0);
  1435. if (auto *N2BV = dyn_cast<BuildVectorSDNode>(N2))
  1436. BlendSplat(N2BV, NElts);
  1437. }
  1438. // Canonicalize all index into lhs, -> shuffle lhs, undef
  1439. // Canonicalize all index into rhs, -> shuffle rhs, undef
  1440. bool AllLHS = true, AllRHS = true;
  1441. bool N2Undef = N2.isUndef();
  1442. for (int i = 0; i != NElts; ++i) {
  1443. if (MaskVec[i] >= NElts) {
  1444. if (N2Undef)
  1445. MaskVec[i] = -1;
  1446. else
  1447. AllLHS = false;
  1448. } else if (MaskVec[i] >= 0) {
  1449. AllRHS = false;
  1450. }
  1451. }
  1452. if (AllLHS && AllRHS)
  1453. return getUNDEF(VT);
  1454. if (AllLHS && !N2Undef)
  1455. N2 = getUNDEF(VT);
  1456. if (AllRHS) {
  1457. N1 = getUNDEF(VT);
  1458. commuteShuffle(N1, N2, MaskVec);
  1459. }
  1460. // Reset our undef status after accounting for the mask.
  1461. N2Undef = N2.isUndef();
  1462. // Re-check whether both sides ended up undef.
  1463. if (N1.isUndef() && N2Undef)
  1464. return getUNDEF(VT);
  1465. // If Identity shuffle return that node.
  1466. bool Identity = true, AllSame = true;
  1467. for (int i = 0; i != NElts; ++i) {
  1468. if (MaskVec[i] >= 0 && MaskVec[i] != i) Identity = false;
  1469. if (MaskVec[i] != MaskVec[0]) AllSame = false;
  1470. }
  1471. if (Identity && NElts)
  1472. return N1;
  1473. // Shuffling a constant splat doesn't change the result.
  1474. if (N2Undef) {
  1475. SDValue V = N1;
  1476. // Look through any bitcasts. We check that these don't change the number
  1477. // (and size) of elements and just changes their types.
  1478. while (V.getOpcode() == ISD::BITCAST)
  1479. V = V->getOperand(0);
  1480. // A splat should always show up as a build vector node.
  1481. if (auto *BV = dyn_cast<BuildVectorSDNode>(V)) {
  1482. BitVector UndefElements;
  1483. SDValue Splat = BV->getSplatValue(&UndefElements);
  1484. // If this is a splat of an undef, shuffling it is also undef.
  1485. if (Splat && Splat.isUndef())
  1486. return getUNDEF(VT);
  1487. bool SameNumElts =
  1488. V.getValueType().getVectorNumElements() == VT.getVectorNumElements();
  1489. // We only have a splat which can skip shuffles if there is a splatted
  1490. // value and no undef lanes rearranged by the shuffle.
  1491. if (Splat && UndefElements.none()) {
  1492. // Splat of <x, x, ..., x>, return <x, x, ..., x>, provided that the
  1493. // number of elements match or the value splatted is a zero constant.
  1494. if (SameNumElts)
  1495. return N1;
  1496. if (auto *C = dyn_cast<ConstantSDNode>(Splat))
  1497. if (C->isNullValue())
  1498. return N1;
  1499. }
  1500. // If the shuffle itself creates a splat, build the vector directly.
  1501. if (AllSame && SameNumElts) {
  1502. EVT BuildVT = BV->getValueType(0);
  1503. const SDValue &Splatted = BV->getOperand(MaskVec[0]);
  1504. SDValue NewBV = getSplatBuildVector(BuildVT, dl, Splatted);
  1505. // We may have jumped through bitcasts, so the type of the
  1506. // BUILD_VECTOR may not match the type of the shuffle.
  1507. if (BuildVT != VT)
  1508. NewBV = getNode(ISD::BITCAST, dl, VT, NewBV);
  1509. return NewBV;
  1510. }
  1511. }
  1512. }
  1513. FoldingSetNodeID ID;
  1514. SDValue Ops[2] = { N1, N2 };
  1515. AddNodeIDNode(ID, ISD::VECTOR_SHUFFLE, getVTList(VT), Ops);
  1516. for (int i = 0; i != NElts; ++i)
  1517. ID.AddInteger(MaskVec[i]);
  1518. void* IP = nullptr;
  1519. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1520. return SDValue(E, 0);
  1521. // Allocate the mask array for the node out of the BumpPtrAllocator, since
  1522. // SDNode doesn't have access to it. This memory will be "leaked" when
  1523. // the node is deallocated, but recovered when the NodeAllocator is released.
  1524. int *MaskAlloc = OperandAllocator.Allocate<int>(NElts);
  1525. llvm::copy(MaskVec, MaskAlloc);
  1526. auto *N = newSDNode<ShuffleVectorSDNode>(VT, dl.getIROrder(),
  1527. dl.getDebugLoc(), MaskAlloc);
  1528. createOperands(N, Ops);
  1529. CSEMap.InsertNode(N, IP);
  1530. InsertNode(N);
  1531. SDValue V = SDValue(N, 0);
  1532. NewSDValueDbgMsg(V, "Creating new node: ", this);
  1533. return V;
  1534. }
  1535. SDValue SelectionDAG::getCommutedVectorShuffle(const ShuffleVectorSDNode &SV) {
  1536. EVT VT = SV.getValueType(0);
  1537. SmallVector<int, 8> MaskVec(SV.getMask().begin(), SV.getMask().end());
  1538. ShuffleVectorSDNode::commuteMask(MaskVec);
  1539. SDValue Op0 = SV.getOperand(0);
  1540. SDValue Op1 = SV.getOperand(1);
  1541. return getVectorShuffle(VT, SDLoc(&SV), Op1, Op0, MaskVec);
  1542. }
  1543. SDValue SelectionDAG::getRegister(unsigned RegNo, EVT VT) {
  1544. FoldingSetNodeID ID;
  1545. AddNodeIDNode(ID, ISD::Register, getVTList(VT), None);
  1546. ID.AddInteger(RegNo);
  1547. void *IP = nullptr;
  1548. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1549. return SDValue(E, 0);
  1550. auto *N = newSDNode<RegisterSDNode>(RegNo, VT);
  1551. N->SDNodeBits.IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
  1552. CSEMap.InsertNode(N, IP);
  1553. InsertNode(N);
  1554. return SDValue(N, 0);
  1555. }
  1556. SDValue SelectionDAG::getRegisterMask(const uint32_t *RegMask) {
  1557. FoldingSetNodeID ID;
  1558. AddNodeIDNode(ID, ISD::RegisterMask, getVTList(MVT::Untyped), None);
  1559. ID.AddPointer(RegMask);
  1560. void *IP = nullptr;
  1561. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1562. return SDValue(E, 0);
  1563. auto *N = newSDNode<RegisterMaskSDNode>(RegMask);
  1564. CSEMap.InsertNode(N, IP);
  1565. InsertNode(N);
  1566. return SDValue(N, 0);
  1567. }
  1568. SDValue SelectionDAG::getEHLabel(const SDLoc &dl, SDValue Root,
  1569. MCSymbol *Label) {
  1570. return getLabelNode(ISD::EH_LABEL, dl, Root, Label);
  1571. }
  1572. SDValue SelectionDAG::getLabelNode(unsigned Opcode, const SDLoc &dl,
  1573. SDValue Root, MCSymbol *Label) {
  1574. FoldingSetNodeID ID;
  1575. SDValue Ops[] = { Root };
  1576. AddNodeIDNode(ID, Opcode, getVTList(MVT::Other), Ops);
  1577. ID.AddPointer(Label);
  1578. void *IP = nullptr;
  1579. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1580. return SDValue(E, 0);
  1581. auto *N = newSDNode<LabelSDNode>(dl.getIROrder(), dl.getDebugLoc(), Label);
  1582. createOperands(N, Ops);
  1583. CSEMap.InsertNode(N, IP);
  1584. InsertNode(N);
  1585. return SDValue(N, 0);
  1586. }
  1587. SDValue SelectionDAG::getBlockAddress(const BlockAddress *BA, EVT VT,
  1588. int64_t Offset,
  1589. bool isTarget,
  1590. unsigned char TargetFlags) {
  1591. unsigned Opc = isTarget ? ISD::TargetBlockAddress : ISD::BlockAddress;
  1592. FoldingSetNodeID ID;
  1593. AddNodeIDNode(ID, Opc, getVTList(VT), None);
  1594. ID.AddPointer(BA);
  1595. ID.AddInteger(Offset);
  1596. ID.AddInteger(TargetFlags);
  1597. void *IP = nullptr;
  1598. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1599. return SDValue(E, 0);
  1600. auto *N = newSDNode<BlockAddressSDNode>(Opc, VT, BA, Offset, TargetFlags);
  1601. CSEMap.InsertNode(N, IP);
  1602. InsertNode(N);
  1603. return SDValue(N, 0);
  1604. }
  1605. SDValue SelectionDAG::getSrcValue(const Value *V) {
  1606. assert((!V || V->getType()->isPointerTy()) &&
  1607. "SrcValue is not a pointer?");
  1608. FoldingSetNodeID ID;
  1609. AddNodeIDNode(ID, ISD::SRCVALUE, getVTList(MVT::Other), None);
  1610. ID.AddPointer(V);
  1611. void *IP = nullptr;
  1612. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1613. return SDValue(E, 0);
  1614. auto *N = newSDNode<SrcValueSDNode>(V);
  1615. CSEMap.InsertNode(N, IP);
  1616. InsertNode(N);
  1617. return SDValue(N, 0);
  1618. }
  1619. SDValue SelectionDAG::getMDNode(const MDNode *MD) {
  1620. FoldingSetNodeID ID;
  1621. AddNodeIDNode(ID, ISD::MDNODE_SDNODE, getVTList(MVT::Other), None);
  1622. ID.AddPointer(MD);
  1623. void *IP = nullptr;
  1624. if (SDNode *E = FindNodeOrInsertPos(ID, IP))
  1625. return SDValue(E, 0);
  1626. auto *N = newSDNode<MDNodeSDNode>(MD);
  1627. CSEMap.InsertNode(N, IP);
  1628. InsertNode(N);
  1629. return SDValue(N, 0);
  1630. }
  1631. SDValue SelectionDAG::getBitcast(EVT VT, SDValue V) {
  1632. if (VT == V.getValueType())
  1633. return V;
  1634. return getNode(ISD::BITCAST, SDLoc(V), VT, V);
  1635. }
  1636. SDValue SelectionDAG::getAddrSpaceCast(const SDLoc &dl, EVT VT, SDValue Ptr,
  1637. unsigned SrcAS, unsigned DestAS) {
  1638. SDValue Ops[] = {Ptr};
  1639. FoldingSetNodeID ID;
  1640. AddNodeIDNode(ID, ISD::ADDRSPACECAST, getVTList(VT), Ops);
  1641. ID.AddInteger(SrcAS);
  1642. ID.AddInteger(DestAS);
  1643. void *IP = nullptr;
  1644. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  1645. return SDValue(E, 0);
  1646. auto *N = newSDNode<AddrSpaceCastSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  1647. VT, SrcAS, DestAS);
  1648. createOperands(N, Ops);
  1649. CSEMap.InsertNode(N, IP);
  1650. InsertNode(N);
  1651. return SDValue(N, 0);
  1652. }
  1653. /// getShiftAmountOperand - Return the specified value casted to
  1654. /// the target's desired shift amount type.
  1655. SDValue SelectionDAG::getShiftAmountOperand(EVT LHSTy, SDValue Op) {
  1656. EVT OpTy = Op.getValueType();
  1657. EVT ShTy = TLI->getShiftAmountTy(LHSTy, getDataLayout());
  1658. if (OpTy == ShTy || OpTy.isVector()) return Op;
  1659. return getZExtOrTrunc(Op, SDLoc(Op), ShTy);
  1660. }
  1661. SDValue SelectionDAG::expandVAArg(SDNode *Node) {
  1662. SDLoc dl(Node);
  1663. const TargetLowering &TLI = getTargetLoweringInfo();
  1664. const Value *V = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
  1665. EVT VT = Node->getValueType(0);
  1666. SDValue Tmp1 = Node->getOperand(0);
  1667. SDValue Tmp2 = Node->getOperand(1);
  1668. unsigned Align = Node->getConstantOperandVal(3);
  1669. SDValue VAListLoad = getLoad(TLI.getPointerTy(getDataLayout()), dl, Tmp1,
  1670. Tmp2, MachinePointerInfo(V));
  1671. SDValue VAList = VAListLoad;
  1672. if (Align > TLI.getMinStackArgumentAlignment()) {
  1673. assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
  1674. VAList = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  1675. getConstant(Align - 1, dl, VAList.getValueType()));
  1676. VAList = getNode(ISD::AND, dl, VAList.getValueType(), VAList,
  1677. getConstant(-(int64_t)Align, dl, VAList.getValueType()));
  1678. }
  1679. // Increment the pointer, VAList, to the next vaarg
  1680. Tmp1 = getNode(ISD::ADD, dl, VAList.getValueType(), VAList,
  1681. getConstant(getDataLayout().getTypeAllocSize(
  1682. VT.getTypeForEVT(*getContext())),
  1683. dl, VAList.getValueType()));
  1684. // Store the incremented VAList to the legalized pointer
  1685. Tmp1 =
  1686. getStore(VAListLoad.getValue(1), dl, Tmp1, Tmp2, MachinePointerInfo(V));
  1687. // Load the actual argument out of the pointer VAList
  1688. return getLoad(VT, dl, Tmp1, VAList, MachinePointerInfo());
  1689. }
  1690. SDValue SelectionDAG::expandVACopy(SDNode *Node) {
  1691. SDLoc dl(Node);
  1692. const TargetLowering &TLI = getTargetLoweringInfo();
  1693. // This defaults to loading a pointer from the input and storing it to the
  1694. // output, returning the chain.
  1695. const Value *VD = cast<SrcValueSDNode>(Node->getOperand(3))->getValue();
  1696. const Value *VS = cast<SrcValueSDNode>(Node->getOperand(4))->getValue();
  1697. SDValue Tmp1 =
  1698. getLoad(TLI.getPointerTy(getDataLayout()), dl, Node->getOperand(0),
  1699. Node->getOperand(2), MachinePointerInfo(VS));
  1700. return getStore(Tmp1.getValue(1), dl, Tmp1, Node->getOperand(1),
  1701. MachinePointerInfo(VD));
  1702. }
  1703. SDValue SelectionDAG::CreateStackTemporary(EVT VT, unsigned minAlign) {
  1704. MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  1705. unsigned ByteSize = VT.getStoreSize();
  1706. Type *Ty = VT.getTypeForEVT(*getContext());
  1707. unsigned StackAlign =
  1708. std::max((unsigned)getDataLayout().getPrefTypeAlignment(Ty), minAlign);
  1709. int FrameIdx = MFI.CreateStackObject(ByteSize, StackAlign, false);
  1710. return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
  1711. }
  1712. SDValue SelectionDAG::CreateStackTemporary(EVT VT1, EVT VT2) {
  1713. unsigned Bytes = std::max(VT1.getStoreSize(), VT2.getStoreSize());
  1714. Type *Ty1 = VT1.getTypeForEVT(*getContext());
  1715. Type *Ty2 = VT2.getTypeForEVT(*getContext());
  1716. const DataLayout &DL = getDataLayout();
  1717. unsigned Align =
  1718. std::max(DL.getPrefTypeAlignment(Ty1), DL.getPrefTypeAlignment(Ty2));
  1719. MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  1720. int FrameIdx = MFI.CreateStackObject(Bytes, Align, false);
  1721. return getFrameIndex(FrameIdx, TLI->getFrameIndexTy(getDataLayout()));
  1722. }
  1723. SDValue SelectionDAG::FoldSetCC(EVT VT, SDValue N1, SDValue N2,
  1724. ISD::CondCode Cond, const SDLoc &dl) {
  1725. EVT OpVT = N1.getValueType();
  1726. // These setcc operations always fold.
  1727. switch (Cond) {
  1728. default: break;
  1729. case ISD::SETFALSE:
  1730. case ISD::SETFALSE2: return getBoolConstant(false, dl, VT, OpVT);
  1731. case ISD::SETTRUE:
  1732. case ISD::SETTRUE2: return getBoolConstant(true, dl, VT, OpVT);
  1733. case ISD::SETOEQ:
  1734. case ISD::SETOGT:
  1735. case ISD::SETOGE:
  1736. case ISD::SETOLT:
  1737. case ISD::SETOLE:
  1738. case ISD::SETONE:
  1739. case ISD::SETO:
  1740. case ISD::SETUO:
  1741. case ISD::SETUEQ:
  1742. case ISD::SETUNE:
  1743. assert(!OpVT.isInteger() && "Illegal setcc for integer!");
  1744. break;
  1745. }
  1746. if (OpVT.isInteger()) {
  1747. // For EQ and NE, we can always pick a value for the undef to make the
  1748. // predicate pass or fail, so we can return undef.
  1749. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  1750. // icmp eq/ne X, undef -> undef.
  1751. if ((N1.isUndef() || N2.isUndef()) &&
  1752. (Cond == ISD::SETEQ || Cond == ISD::SETNE))
  1753. return getUNDEF(VT);
  1754. // If both operands are undef, we can return undef for int comparison.
  1755. // icmp undef, undef -> undef.
  1756. if (N1.isUndef() && N2.isUndef())
  1757. return getUNDEF(VT);
  1758. // icmp X, X -> true/false
  1759. // icmp X, undef -> true/false because undef could be X.
  1760. if (N1 == N2)
  1761. return getBoolConstant(ISD::isTrueWhenEqual(Cond), dl, VT, OpVT);
  1762. }
  1763. if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2)) {
  1764. const APInt &C2 = N2C->getAPIntValue();
  1765. if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1)) {
  1766. const APInt &C1 = N1C->getAPIntValue();
  1767. switch (Cond) {
  1768. default: llvm_unreachable("Unknown integer setcc!");
  1769. case ISD::SETEQ: return getBoolConstant(C1 == C2, dl, VT, OpVT);
  1770. case ISD::SETNE: return getBoolConstant(C1 != C2, dl, VT, OpVT);
  1771. case ISD::SETULT: return getBoolConstant(C1.ult(C2), dl, VT, OpVT);
  1772. case ISD::SETUGT: return getBoolConstant(C1.ugt(C2), dl, VT, OpVT);
  1773. case ISD::SETULE: return getBoolConstant(C1.ule(C2), dl, VT, OpVT);
  1774. case ISD::SETUGE: return getBoolConstant(C1.uge(C2), dl, VT, OpVT);
  1775. case ISD::SETLT: return getBoolConstant(C1.slt(C2), dl, VT, OpVT);
  1776. case ISD::SETGT: return getBoolConstant(C1.sgt(C2), dl, VT, OpVT);
  1777. case ISD::SETLE: return getBoolConstant(C1.sle(C2), dl, VT, OpVT);
  1778. case ISD::SETGE: return getBoolConstant(C1.sge(C2), dl, VT, OpVT);
  1779. }
  1780. }
  1781. }
  1782. auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  1783. auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  1784. if (N1CFP && N2CFP) {
  1785. APFloat::cmpResult R = N1CFP->getValueAPF().compare(N2CFP->getValueAPF());
  1786. switch (Cond) {
  1787. default: break;
  1788. case ISD::SETEQ: if (R==APFloat::cmpUnordered)
  1789. return getUNDEF(VT);
  1790. LLVM_FALLTHROUGH;
  1791. case ISD::SETOEQ: return getBoolConstant(R==APFloat::cmpEqual, dl, VT,
  1792. OpVT);
  1793. case ISD::SETNE: if (R==APFloat::cmpUnordered)
  1794. return getUNDEF(VT);
  1795. LLVM_FALLTHROUGH;
  1796. case ISD::SETONE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  1797. R==APFloat::cmpLessThan, dl, VT,
  1798. OpVT);
  1799. case ISD::SETLT: if (R==APFloat::cmpUnordered)
  1800. return getUNDEF(VT);
  1801. LLVM_FALLTHROUGH;
  1802. case ISD::SETOLT: return getBoolConstant(R==APFloat::cmpLessThan, dl, VT,
  1803. OpVT);
  1804. case ISD::SETGT: if (R==APFloat::cmpUnordered)
  1805. return getUNDEF(VT);
  1806. LLVM_FALLTHROUGH;
  1807. case ISD::SETOGT: return getBoolConstant(R==APFloat::cmpGreaterThan, dl,
  1808. VT, OpVT);
  1809. case ISD::SETLE: if (R==APFloat::cmpUnordered)
  1810. return getUNDEF(VT);
  1811. LLVM_FALLTHROUGH;
  1812. case ISD::SETOLE: return getBoolConstant(R==APFloat::cmpLessThan ||
  1813. R==APFloat::cmpEqual, dl, VT,
  1814. OpVT);
  1815. case ISD::SETGE: if (R==APFloat::cmpUnordered)
  1816. return getUNDEF(VT);
  1817. LLVM_FALLTHROUGH;
  1818. case ISD::SETOGE: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  1819. R==APFloat::cmpEqual, dl, VT, OpVT);
  1820. case ISD::SETO: return getBoolConstant(R!=APFloat::cmpUnordered, dl, VT,
  1821. OpVT);
  1822. case ISD::SETUO: return getBoolConstant(R==APFloat::cmpUnordered, dl, VT,
  1823. OpVT);
  1824. case ISD::SETUEQ: return getBoolConstant(R==APFloat::cmpUnordered ||
  1825. R==APFloat::cmpEqual, dl, VT,
  1826. OpVT);
  1827. case ISD::SETUNE: return getBoolConstant(R!=APFloat::cmpEqual, dl, VT,
  1828. OpVT);
  1829. case ISD::SETULT: return getBoolConstant(R==APFloat::cmpUnordered ||
  1830. R==APFloat::cmpLessThan, dl, VT,
  1831. OpVT);
  1832. case ISD::SETUGT: return getBoolConstant(R==APFloat::cmpGreaterThan ||
  1833. R==APFloat::cmpUnordered, dl, VT,
  1834. OpVT);
  1835. case ISD::SETULE: return getBoolConstant(R!=APFloat::cmpGreaterThan, dl,
  1836. VT, OpVT);
  1837. case ISD::SETUGE: return getBoolConstant(R!=APFloat::cmpLessThan, dl, VT,
  1838. OpVT);
  1839. }
  1840. } else if (N1CFP && OpVT.isSimple() && !N2.isUndef()) {
  1841. // Ensure that the constant occurs on the RHS.
  1842. ISD::CondCode SwappedCond = ISD::getSetCCSwappedOperands(Cond);
  1843. if (!TLI->isCondCodeLegal(SwappedCond, OpVT.getSimpleVT()))
  1844. return SDValue();
  1845. return getSetCC(dl, VT, N2, N1, SwappedCond);
  1846. } else if ((N2CFP && N2CFP->getValueAPF().isNaN()) ||
  1847. (OpVT.isFloatingPoint() && (N1.isUndef() || N2.isUndef()))) {
  1848. // If an operand is known to be a nan (or undef that could be a nan), we can
  1849. // fold it.
  1850. // Choosing NaN for the undef will always make unordered comparison succeed
  1851. // and ordered comparison fails.
  1852. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  1853. switch (ISD::getUnorderedFlavor(Cond)) {
  1854. default:
  1855. llvm_unreachable("Unknown flavor!");
  1856. case 0: // Known false.
  1857. return getBoolConstant(false, dl, VT, OpVT);
  1858. case 1: // Known true.
  1859. return getBoolConstant(true, dl, VT, OpVT);
  1860. case 2: // Undefined.
  1861. return getUNDEF(VT);
  1862. }
  1863. }
  1864. // Could not fold it.
  1865. return SDValue();
  1866. }
  1867. /// See if the specified operand can be simplified with the knowledge that only
  1868. /// the bits specified by Mask are used.
  1869. SDValue SelectionDAG::GetDemandedBits(SDValue V, const APInt &Mask) {
  1870. switch (V.getOpcode()) {
  1871. default:
  1872. break;
  1873. case ISD::Constant: {
  1874. const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
  1875. assert(CV && "Const value should be ConstSDNode.");
  1876. const APInt &CVal = CV->getAPIntValue();
  1877. APInt NewVal = CVal & Mask;
  1878. if (NewVal != CVal)
  1879. return getConstant(NewVal, SDLoc(V), V.getValueType());
  1880. break;
  1881. }
  1882. case ISD::OR:
  1883. case ISD::XOR:
  1884. // If the LHS or RHS don't contribute bits to the or, drop them.
  1885. if (MaskedValueIsZero(V.getOperand(0), Mask))
  1886. return V.getOperand(1);
  1887. if (MaskedValueIsZero(V.getOperand(1), Mask))
  1888. return V.getOperand(0);
  1889. break;
  1890. case ISD::SRL:
  1891. // Only look at single-use SRLs.
  1892. if (!V.getNode()->hasOneUse())
  1893. break;
  1894. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
  1895. // See if we can recursively simplify the LHS.
  1896. unsigned Amt = RHSC->getZExtValue();
  1897. // Watch out for shift count overflow though.
  1898. if (Amt >= Mask.getBitWidth())
  1899. break;
  1900. APInt NewMask = Mask << Amt;
  1901. if (SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask))
  1902. return getNode(ISD::SRL, SDLoc(V), V.getValueType(), SimplifyLHS,
  1903. V.getOperand(1));
  1904. }
  1905. break;
  1906. case ISD::AND: {
  1907. // X & -1 -> X (ignoring bits which aren't demanded).
  1908. // Also handle the case where masked out bits in X are known to be zero.
  1909. if (ConstantSDNode *RHSC = isConstOrConstSplat(V.getOperand(1))) {
  1910. const APInt &AndVal = RHSC->getAPIntValue();
  1911. if (Mask.isSubsetOf(AndVal) ||
  1912. Mask.isSubsetOf(computeKnownBits(V.getOperand(0)).Zero | AndVal))
  1913. return V.getOperand(0);
  1914. }
  1915. break;
  1916. }
  1917. case ISD::ANY_EXTEND: {
  1918. SDValue Src = V.getOperand(0);
  1919. unsigned SrcBitWidth = Src.getScalarValueSizeInBits();
  1920. // Being conservative here - only peek through if we only demand bits in the
  1921. // non-extended source (even though the extended bits are technically undef).
  1922. if (Mask.getActiveBits() > SrcBitWidth)
  1923. break;
  1924. APInt SrcMask = Mask.trunc(SrcBitWidth);
  1925. if (SDValue DemandedSrc = GetDemandedBits(Src, SrcMask))
  1926. return getNode(ISD::ANY_EXTEND, SDLoc(V), V.getValueType(), DemandedSrc);
  1927. break;
  1928. }
  1929. case ISD::SIGN_EXTEND_INREG:
  1930. EVT ExVT = cast<VTSDNode>(V.getOperand(1))->getVT();
  1931. unsigned ExVTBits = ExVT.getScalarSizeInBits();
  1932. // If none of the extended bits are demanded, eliminate the sextinreg.
  1933. if (Mask.getActiveBits() <= ExVTBits)
  1934. return V.getOperand(0);
  1935. break;
  1936. }
  1937. return SDValue();
  1938. }
  1939. /// SignBitIsZero - Return true if the sign bit of Op is known to be zero. We
  1940. /// use this predicate to simplify operations downstream.
  1941. bool SelectionDAG::SignBitIsZero(SDValue Op, unsigned Depth) const {
  1942. unsigned BitWidth = Op.getScalarValueSizeInBits();
  1943. return MaskedValueIsZero(Op, APInt::getSignMask(BitWidth), Depth);
  1944. }
  1945. /// MaskedValueIsZero - Return true if 'V & Mask' is known to be zero. We use
  1946. /// this predicate to simplify operations downstream. Mask is known to be zero
  1947. /// for bits that V cannot have.
  1948. bool SelectionDAG::MaskedValueIsZero(SDValue Op, const APInt &Mask,
  1949. unsigned Depth) const {
  1950. return Mask.isSubsetOf(computeKnownBits(Op, Depth).Zero);
  1951. }
  1952. /// isSplatValue - Return true if the vector V has the same value
  1953. /// across all DemandedElts.
  1954. bool SelectionDAG::isSplatValue(SDValue V, const APInt &DemandedElts,
  1955. APInt &UndefElts) {
  1956. if (!DemandedElts)
  1957. return false; // No demanded elts, better to assume we don't know anything.
  1958. EVT VT = V.getValueType();
  1959. assert(VT.isVector() && "Vector type expected");
  1960. unsigned NumElts = VT.getVectorNumElements();
  1961. assert(NumElts == DemandedElts.getBitWidth() && "Vector size mismatch");
  1962. UndefElts = APInt::getNullValue(NumElts);
  1963. switch (V.getOpcode()) {
  1964. case ISD::BUILD_VECTOR: {
  1965. SDValue Scl;
  1966. for (unsigned i = 0; i != NumElts; ++i) {
  1967. SDValue Op = V.getOperand(i);
  1968. if (Op.isUndef()) {
  1969. UndefElts.setBit(i);
  1970. continue;
  1971. }
  1972. if (!DemandedElts[i])
  1973. continue;
  1974. if (Scl && Scl != Op)
  1975. return false;
  1976. Scl = Op;
  1977. }
  1978. return true;
  1979. }
  1980. case ISD::VECTOR_SHUFFLE: {
  1981. // Check if this is a shuffle node doing a splat.
  1982. // TODO: Do we need to handle shuffle(splat, undef, mask)?
  1983. int SplatIndex = -1;
  1984. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(V)->getMask();
  1985. for (int i = 0; i != (int)NumElts; ++i) {
  1986. int M = Mask[i];
  1987. if (M < 0) {
  1988. UndefElts.setBit(i);
  1989. continue;
  1990. }
  1991. if (!DemandedElts[i])
  1992. continue;
  1993. if (0 <= SplatIndex && SplatIndex != M)
  1994. return false;
  1995. SplatIndex = M;
  1996. }
  1997. return true;
  1998. }
  1999. case ISD::EXTRACT_SUBVECTOR: {
  2000. SDValue Src = V.getOperand(0);
  2001. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(V.getOperand(1));
  2002. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2003. if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
  2004. // Offset the demanded elts by the subvector index.
  2005. uint64_t Idx = SubIdx->getZExtValue();
  2006. APInt UndefSrcElts;
  2007. APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  2008. if (isSplatValue(Src, DemandedSrc, UndefSrcElts)) {
  2009. UndefElts = UndefSrcElts.extractBits(NumElts, Idx);
  2010. return true;
  2011. }
  2012. }
  2013. break;
  2014. }
  2015. case ISD::ADD:
  2016. case ISD::SUB:
  2017. case ISD::AND: {
  2018. APInt UndefLHS, UndefRHS;
  2019. SDValue LHS = V.getOperand(0);
  2020. SDValue RHS = V.getOperand(1);
  2021. if (isSplatValue(LHS, DemandedElts, UndefLHS) &&
  2022. isSplatValue(RHS, DemandedElts, UndefRHS)) {
  2023. UndefElts = UndefLHS | UndefRHS;
  2024. return true;
  2025. }
  2026. break;
  2027. }
  2028. }
  2029. return false;
  2030. }
  2031. /// Helper wrapper to main isSplatValue function.
  2032. bool SelectionDAG::isSplatValue(SDValue V, bool AllowUndefs) {
  2033. EVT VT = V.getValueType();
  2034. assert(VT.isVector() && "Vector type expected");
  2035. unsigned NumElts = VT.getVectorNumElements();
  2036. APInt UndefElts;
  2037. APInt DemandedElts = APInt::getAllOnesValue(NumElts);
  2038. return isSplatValue(V, DemandedElts, UndefElts) &&
  2039. (AllowUndefs || !UndefElts);
  2040. }
  2041. SDValue SelectionDAG::getSplatSourceVector(SDValue V, int &SplatIdx) {
  2042. V = peekThroughExtractSubvectors(V);
  2043. EVT VT = V.getValueType();
  2044. unsigned Opcode = V.getOpcode();
  2045. switch (Opcode) {
  2046. default: {
  2047. APInt UndefElts;
  2048. APInt DemandedElts = APInt::getAllOnesValue(VT.getVectorNumElements());
  2049. if (isSplatValue(V, DemandedElts, UndefElts)) {
  2050. // Handle case where all demanded elements are UNDEF.
  2051. if (DemandedElts.isSubsetOf(UndefElts)) {
  2052. SplatIdx = 0;
  2053. return getUNDEF(VT);
  2054. }
  2055. SplatIdx = (UndefElts & DemandedElts).countTrailingOnes();
  2056. return V;
  2057. }
  2058. break;
  2059. }
  2060. case ISD::VECTOR_SHUFFLE: {
  2061. // Check if this is a shuffle node doing a splat.
  2062. // TODO - remove this and rely purely on SelectionDAG::isSplatValue,
  2063. // getTargetVShiftNode currently struggles without the splat source.
  2064. auto *SVN = cast<ShuffleVectorSDNode>(V);
  2065. if (!SVN->isSplat())
  2066. break;
  2067. int Idx = SVN->getSplatIndex();
  2068. int NumElts = V.getValueType().getVectorNumElements();
  2069. SplatIdx = Idx % NumElts;
  2070. return V.getOperand(Idx / NumElts);
  2071. }
  2072. }
  2073. return SDValue();
  2074. }
  2075. SDValue SelectionDAG::getSplatValue(SDValue V) {
  2076. int SplatIdx;
  2077. if (SDValue SrcVector = getSplatSourceVector(V, SplatIdx))
  2078. return getNode(ISD::EXTRACT_VECTOR_ELT, SDLoc(V),
  2079. SrcVector.getValueType().getScalarType(), SrcVector,
  2080. getIntPtrConstant(SplatIdx, SDLoc(V)));
  2081. return SDValue();
  2082. }
  2083. /// If a SHL/SRA/SRL node has a constant or splat constant shift amount that
  2084. /// is less than the element bit-width of the shift node, return it.
  2085. static const APInt *getValidShiftAmountConstant(SDValue V) {
  2086. if (ConstantSDNode *SA = isConstOrConstSplat(V.getOperand(1))) {
  2087. // Shifting more than the bitwidth is not valid.
  2088. const APInt &ShAmt = SA->getAPIntValue();
  2089. if (ShAmt.ult(V.getScalarValueSizeInBits()))
  2090. return &ShAmt;
  2091. }
  2092. return nullptr;
  2093. }
  2094. /// Determine which bits of Op are known to be either zero or one and return
  2095. /// them in Known. For vectors, the known bits are those that are shared by
  2096. /// every vector element.
  2097. KnownBits SelectionDAG::computeKnownBits(SDValue Op, unsigned Depth) const {
  2098. EVT VT = Op.getValueType();
  2099. APInt DemandedElts = VT.isVector()
  2100. ? APInt::getAllOnesValue(VT.getVectorNumElements())
  2101. : APInt(1, 1);
  2102. return computeKnownBits(Op, DemandedElts, Depth);
  2103. }
  2104. /// Determine which bits of Op are known to be either zero or one and return
  2105. /// them in Known. The DemandedElts argument allows us to only collect the known
  2106. /// bits that are shared by the requested vector elements.
  2107. KnownBits SelectionDAG::computeKnownBits(SDValue Op, const APInt &DemandedElts,
  2108. unsigned Depth) const {
  2109. unsigned BitWidth = Op.getScalarValueSizeInBits();
  2110. KnownBits Known(BitWidth); // Don't know anything.
  2111. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  2112. // We know all of the bits for a constant!
  2113. Known.One = C->getAPIntValue();
  2114. Known.Zero = ~Known.One;
  2115. return Known;
  2116. }
  2117. if (auto *C = dyn_cast<ConstantFPSDNode>(Op)) {
  2118. // We know all of the bits for a constant fp!
  2119. Known.One = C->getValueAPF().bitcastToAPInt();
  2120. Known.Zero = ~Known.One;
  2121. return Known;
  2122. }
  2123. if (Depth == 6)
  2124. return Known; // Limit search depth.
  2125. KnownBits Known2;
  2126. unsigned NumElts = DemandedElts.getBitWidth();
  2127. assert((!Op.getValueType().isVector() ||
  2128. NumElts == Op.getValueType().getVectorNumElements()) &&
  2129. "Unexpected vector size");
  2130. if (!DemandedElts)
  2131. return Known; // No demanded elts, better to assume we don't know anything.
  2132. unsigned Opcode = Op.getOpcode();
  2133. switch (Opcode) {
  2134. case ISD::BUILD_VECTOR:
  2135. // Collect the known bits that are shared by every demanded vector element.
  2136. Known.Zero.setAllBits(); Known.One.setAllBits();
  2137. for (unsigned i = 0, e = Op.getNumOperands(); i != e; ++i) {
  2138. if (!DemandedElts[i])
  2139. continue;
  2140. SDValue SrcOp = Op.getOperand(i);
  2141. Known2 = computeKnownBits(SrcOp, Depth + 1);
  2142. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  2143. if (SrcOp.getValueSizeInBits() != BitWidth) {
  2144. assert(SrcOp.getValueSizeInBits() > BitWidth &&
  2145. "Expected BUILD_VECTOR implicit truncation");
  2146. Known2 = Known2.trunc(BitWidth);
  2147. }
  2148. // Known bits are the values that are shared by every demanded element.
  2149. Known.One &= Known2.One;
  2150. Known.Zero &= Known2.Zero;
  2151. // If we don't know any bits, early out.
  2152. if (Known.isUnknown())
  2153. break;
  2154. }
  2155. break;
  2156. case ISD::VECTOR_SHUFFLE: {
  2157. // Collect the known bits that are shared by every vector element referenced
  2158. // by the shuffle.
  2159. APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
  2160. Known.Zero.setAllBits(); Known.One.setAllBits();
  2161. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  2162. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  2163. for (unsigned i = 0; i != NumElts; ++i) {
  2164. if (!DemandedElts[i])
  2165. continue;
  2166. int M = SVN->getMaskElt(i);
  2167. if (M < 0) {
  2168. // For UNDEF elements, we don't know anything about the common state of
  2169. // the shuffle result.
  2170. Known.resetAll();
  2171. DemandedLHS.clearAllBits();
  2172. DemandedRHS.clearAllBits();
  2173. break;
  2174. }
  2175. if ((unsigned)M < NumElts)
  2176. DemandedLHS.setBit((unsigned)M % NumElts);
  2177. else
  2178. DemandedRHS.setBit((unsigned)M % NumElts);
  2179. }
  2180. // Known bits are the values that are shared by every demanded element.
  2181. if (!!DemandedLHS) {
  2182. SDValue LHS = Op.getOperand(0);
  2183. Known2 = computeKnownBits(LHS, DemandedLHS, Depth + 1);
  2184. Known.One &= Known2.One;
  2185. Known.Zero &= Known2.Zero;
  2186. }
  2187. // If we don't know any bits, early out.
  2188. if (Known.isUnknown())
  2189. break;
  2190. if (!!DemandedRHS) {
  2191. SDValue RHS = Op.getOperand(1);
  2192. Known2 = computeKnownBits(RHS, DemandedRHS, Depth + 1);
  2193. Known.One &= Known2.One;
  2194. Known.Zero &= Known2.Zero;
  2195. }
  2196. break;
  2197. }
  2198. case ISD::CONCAT_VECTORS: {
  2199. // Split DemandedElts and test each of the demanded subvectors.
  2200. Known.Zero.setAllBits(); Known.One.setAllBits();
  2201. EVT SubVectorVT = Op.getOperand(0).getValueType();
  2202. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  2203. unsigned NumSubVectors = Op.getNumOperands();
  2204. for (unsigned i = 0; i != NumSubVectors; ++i) {
  2205. APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
  2206. DemandedSub = DemandedSub.trunc(NumSubVectorElts);
  2207. if (!!DemandedSub) {
  2208. SDValue Sub = Op.getOperand(i);
  2209. Known2 = computeKnownBits(Sub, DemandedSub, Depth + 1);
  2210. Known.One &= Known2.One;
  2211. Known.Zero &= Known2.Zero;
  2212. }
  2213. // If we don't know any bits, early out.
  2214. if (Known.isUnknown())
  2215. break;
  2216. }
  2217. break;
  2218. }
  2219. case ISD::INSERT_SUBVECTOR: {
  2220. // If we know the element index, demand any elements from the subvector and
  2221. // the remainder from the src its inserted into, otherwise demand them all.
  2222. SDValue Src = Op.getOperand(0);
  2223. SDValue Sub = Op.getOperand(1);
  2224. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  2225. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  2226. if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
  2227. Known.One.setAllBits();
  2228. Known.Zero.setAllBits();
  2229. uint64_t Idx = SubIdx->getZExtValue();
  2230. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  2231. if (!!DemandedSubElts) {
  2232. Known = computeKnownBits(Sub, DemandedSubElts, Depth + 1);
  2233. if (Known.isUnknown())
  2234. break; // early-out.
  2235. }
  2236. APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
  2237. APInt DemandedSrcElts = DemandedElts & ~SubMask;
  2238. if (!!DemandedSrcElts) {
  2239. Known2 = computeKnownBits(Src, DemandedSrcElts, Depth + 1);
  2240. Known.One &= Known2.One;
  2241. Known.Zero &= Known2.Zero;
  2242. }
  2243. } else {
  2244. Known = computeKnownBits(Sub, Depth + 1);
  2245. if (Known.isUnknown())
  2246. break; // early-out.
  2247. Known2 = computeKnownBits(Src, Depth + 1);
  2248. Known.One &= Known2.One;
  2249. Known.Zero &= Known2.Zero;
  2250. }
  2251. break;
  2252. }
  2253. case ISD::EXTRACT_SUBVECTOR: {
  2254. // If we know the element index, just demand that subvector elements,
  2255. // otherwise demand them all.
  2256. SDValue Src = Op.getOperand(0);
  2257. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  2258. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  2259. if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
  2260. // Offset the demanded elts by the subvector index.
  2261. uint64_t Idx = SubIdx->getZExtValue();
  2262. APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  2263. Known = computeKnownBits(Src, DemandedSrc, Depth + 1);
  2264. } else {
  2265. Known = computeKnownBits(Src, Depth + 1);
  2266. }
  2267. break;
  2268. }
  2269. case ISD::SCALAR_TO_VECTOR: {
  2270. // We know about scalar_to_vector as much as we know about it source,
  2271. // which becomes the first element of otherwise unknown vector.
  2272. if (DemandedElts != 1)
  2273. break;
  2274. SDValue N0 = Op.getOperand(0);
  2275. Known = computeKnownBits(N0, Depth + 1);
  2276. if (N0.getValueSizeInBits() != BitWidth)
  2277. Known = Known.trunc(BitWidth);
  2278. break;
  2279. }
  2280. case ISD::BITCAST: {
  2281. SDValue N0 = Op.getOperand(0);
  2282. EVT SubVT = N0.getValueType();
  2283. unsigned SubBitWidth = SubVT.getScalarSizeInBits();
  2284. // Ignore bitcasts from unsupported types.
  2285. if (!(SubVT.isInteger() || SubVT.isFloatingPoint()))
  2286. break;
  2287. // Fast handling of 'identity' bitcasts.
  2288. if (BitWidth == SubBitWidth) {
  2289. Known = computeKnownBits(N0, DemandedElts, Depth + 1);
  2290. break;
  2291. }
  2292. bool IsLE = getDataLayout().isLittleEndian();
  2293. // Bitcast 'small element' vector to 'large element' scalar/vector.
  2294. if ((BitWidth % SubBitWidth) == 0) {
  2295. assert(N0.getValueType().isVector() && "Expected bitcast from vector");
  2296. // Collect known bits for the (larger) output by collecting the known
  2297. // bits from each set of sub elements and shift these into place.
  2298. // We need to separately call computeKnownBits for each set of
  2299. // sub elements as the knownbits for each is likely to be different.
  2300. unsigned SubScale = BitWidth / SubBitWidth;
  2301. APInt SubDemandedElts(NumElts * SubScale, 0);
  2302. for (unsigned i = 0; i != NumElts; ++i)
  2303. if (DemandedElts[i])
  2304. SubDemandedElts.setBit(i * SubScale);
  2305. for (unsigned i = 0; i != SubScale; ++i) {
  2306. Known2 = computeKnownBits(N0, SubDemandedElts.shl(i),
  2307. Depth + 1);
  2308. unsigned Shifts = IsLE ? i : SubScale - 1 - i;
  2309. Known.One |= Known2.One.zext(BitWidth).shl(SubBitWidth * Shifts);
  2310. Known.Zero |= Known2.Zero.zext(BitWidth).shl(SubBitWidth * Shifts);
  2311. }
  2312. }
  2313. // Bitcast 'large element' scalar/vector to 'small element' vector.
  2314. if ((SubBitWidth % BitWidth) == 0) {
  2315. assert(Op.getValueType().isVector() && "Expected bitcast to vector");
  2316. // Collect known bits for the (smaller) output by collecting the known
  2317. // bits from the overlapping larger input elements and extracting the
  2318. // sub sections we actually care about.
  2319. unsigned SubScale = SubBitWidth / BitWidth;
  2320. APInt SubDemandedElts(NumElts / SubScale, 0);
  2321. for (unsigned i = 0; i != NumElts; ++i)
  2322. if (DemandedElts[i])
  2323. SubDemandedElts.setBit(i / SubScale);
  2324. Known2 = computeKnownBits(N0, SubDemandedElts, Depth + 1);
  2325. Known.Zero.setAllBits(); Known.One.setAllBits();
  2326. for (unsigned i = 0; i != NumElts; ++i)
  2327. if (DemandedElts[i]) {
  2328. unsigned Shifts = IsLE ? i : NumElts - 1 - i;
  2329. unsigned Offset = (Shifts % SubScale) * BitWidth;
  2330. Known.One &= Known2.One.lshr(Offset).trunc(BitWidth);
  2331. Known.Zero &= Known2.Zero.lshr(Offset).trunc(BitWidth);
  2332. // If we don't know any bits, early out.
  2333. if (Known.isUnknown())
  2334. break;
  2335. }
  2336. }
  2337. break;
  2338. }
  2339. case ISD::AND:
  2340. // If either the LHS or the RHS are Zero, the result is zero.
  2341. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2342. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2343. // Output known-1 bits are only known if set in both the LHS & RHS.
  2344. Known.One &= Known2.One;
  2345. // Output known-0 are known to be clear if zero in either the LHS | RHS.
  2346. Known.Zero |= Known2.Zero;
  2347. break;
  2348. case ISD::OR:
  2349. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2350. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2351. // Output known-0 bits are only known if clear in both the LHS & RHS.
  2352. Known.Zero &= Known2.Zero;
  2353. // Output known-1 are known to be set if set in either the LHS | RHS.
  2354. Known.One |= Known2.One;
  2355. break;
  2356. case ISD::XOR: {
  2357. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2358. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2359. // Output known-0 bits are known if clear or set in both the LHS & RHS.
  2360. APInt KnownZeroOut = (Known.Zero & Known2.Zero) | (Known.One & Known2.One);
  2361. // Output known-1 are known to be set if set in only one of the LHS, RHS.
  2362. Known.One = (Known.Zero & Known2.One) | (Known.One & Known2.Zero);
  2363. Known.Zero = KnownZeroOut;
  2364. break;
  2365. }
  2366. case ISD::MUL: {
  2367. Known = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2368. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2369. // If low bits are zero in either operand, output low known-0 bits.
  2370. // Also compute a conservative estimate for high known-0 bits.
  2371. // More trickiness is possible, but this is sufficient for the
  2372. // interesting case of alignment computation.
  2373. unsigned TrailZ = Known.countMinTrailingZeros() +
  2374. Known2.countMinTrailingZeros();
  2375. unsigned LeadZ = std::max(Known.countMinLeadingZeros() +
  2376. Known2.countMinLeadingZeros(),
  2377. BitWidth) - BitWidth;
  2378. Known.resetAll();
  2379. Known.Zero.setLowBits(std::min(TrailZ, BitWidth));
  2380. Known.Zero.setHighBits(std::min(LeadZ, BitWidth));
  2381. break;
  2382. }
  2383. case ISD::UDIV: {
  2384. // For the purposes of computing leading zeros we can conservatively
  2385. // treat a udiv as a logical right shift by the power of 2 known to
  2386. // be less than the denominator.
  2387. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2388. unsigned LeadZ = Known2.countMinLeadingZeros();
  2389. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2390. unsigned RHSMaxLeadingZeros = Known2.countMaxLeadingZeros();
  2391. if (RHSMaxLeadingZeros != BitWidth)
  2392. LeadZ = std::min(BitWidth, LeadZ + BitWidth - RHSMaxLeadingZeros - 1);
  2393. Known.Zero.setHighBits(LeadZ);
  2394. break;
  2395. }
  2396. case ISD::SELECT:
  2397. case ISD::VSELECT:
  2398. Known = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2399. // If we don't know any bits, early out.
  2400. if (Known.isUnknown())
  2401. break;
  2402. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth+1);
  2403. // Only known if known in both the LHS and RHS.
  2404. Known.One &= Known2.One;
  2405. Known.Zero &= Known2.Zero;
  2406. break;
  2407. case ISD::SELECT_CC:
  2408. Known = computeKnownBits(Op.getOperand(3), DemandedElts, Depth+1);
  2409. // If we don't know any bits, early out.
  2410. if (Known.isUnknown())
  2411. break;
  2412. Known2 = computeKnownBits(Op.getOperand(2), DemandedElts, Depth+1);
  2413. // Only known if known in both the LHS and RHS.
  2414. Known.One &= Known2.One;
  2415. Known.Zero &= Known2.Zero;
  2416. break;
  2417. case ISD::SMULO:
  2418. case ISD::UMULO:
  2419. case ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS:
  2420. if (Op.getResNo() != 1)
  2421. break;
  2422. // The boolean result conforms to getBooleanContents.
  2423. // If we know the result of a setcc has the top bits zero, use this info.
  2424. // We know that we have an integer-based boolean since these operations
  2425. // are only available for integer.
  2426. if (TLI->getBooleanContents(Op.getValueType().isVector(), false) ==
  2427. TargetLowering::ZeroOrOneBooleanContent &&
  2428. BitWidth > 1)
  2429. Known.Zero.setBitsFrom(1);
  2430. break;
  2431. case ISD::SETCC:
  2432. // If we know the result of a setcc has the top bits zero, use this info.
  2433. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  2434. TargetLowering::ZeroOrOneBooleanContent &&
  2435. BitWidth > 1)
  2436. Known.Zero.setBitsFrom(1);
  2437. break;
  2438. case ISD::SHL:
  2439. if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
  2440. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2441. unsigned Shift = ShAmt->getZExtValue();
  2442. Known.Zero <<= Shift;
  2443. Known.One <<= Shift;
  2444. // Low bits are known zero.
  2445. Known.Zero.setLowBits(Shift);
  2446. }
  2447. break;
  2448. case ISD::SRL:
  2449. if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
  2450. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2451. unsigned Shift = ShAmt->getZExtValue();
  2452. Known.Zero.lshrInPlace(Shift);
  2453. Known.One.lshrInPlace(Shift);
  2454. // High bits are known zero.
  2455. Known.Zero.setHighBits(Shift);
  2456. } else if (auto *BV = dyn_cast<BuildVectorSDNode>(Op.getOperand(1))) {
  2457. // If the shift amount is a vector of constants see if we can bound
  2458. // the number of upper zero bits.
  2459. unsigned ShiftAmountMin = BitWidth;
  2460. for (unsigned i = 0; i != BV->getNumOperands(); ++i) {
  2461. if (auto *C = dyn_cast<ConstantSDNode>(BV->getOperand(i))) {
  2462. const APInt &ShAmt = C->getAPIntValue();
  2463. if (ShAmt.ult(BitWidth)) {
  2464. ShiftAmountMin = std::min<unsigned>(ShiftAmountMin,
  2465. ShAmt.getZExtValue());
  2466. continue;
  2467. }
  2468. }
  2469. // Don't know anything.
  2470. ShiftAmountMin = 0;
  2471. break;
  2472. }
  2473. Known.Zero.setHighBits(ShiftAmountMin);
  2474. }
  2475. break;
  2476. case ISD::SRA:
  2477. if (const APInt *ShAmt = getValidShiftAmountConstant(Op)) {
  2478. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2479. unsigned Shift = ShAmt->getZExtValue();
  2480. // Sign extend known zero/one bit (else is unknown).
  2481. Known.Zero.ashrInPlace(Shift);
  2482. Known.One.ashrInPlace(Shift);
  2483. }
  2484. break;
  2485. case ISD::FSHL:
  2486. case ISD::FSHR:
  2487. if (ConstantSDNode *C = isConstOrConstSplat(Op.getOperand(2), DemandedElts)) {
  2488. unsigned Amt = C->getAPIntValue().urem(BitWidth);
  2489. // For fshl, 0-shift returns the 1st arg.
  2490. // For fshr, 0-shift returns the 2nd arg.
  2491. if (Amt == 0) {
  2492. Known = computeKnownBits(Op.getOperand(Opcode == ISD::FSHL ? 0 : 1),
  2493. DemandedElts, Depth + 1);
  2494. break;
  2495. }
  2496. // fshl: (X << (Z % BW)) | (Y >> (BW - (Z % BW)))
  2497. // fshr: (X << (BW - (Z % BW))) | (Y >> (Z % BW))
  2498. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2499. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2500. if (Opcode == ISD::FSHL) {
  2501. Known.One <<= Amt;
  2502. Known.Zero <<= Amt;
  2503. Known2.One.lshrInPlace(BitWidth - Amt);
  2504. Known2.Zero.lshrInPlace(BitWidth - Amt);
  2505. } else {
  2506. Known.One <<= BitWidth - Amt;
  2507. Known.Zero <<= BitWidth - Amt;
  2508. Known2.One.lshrInPlace(Amt);
  2509. Known2.Zero.lshrInPlace(Amt);
  2510. }
  2511. Known.One |= Known2.One;
  2512. Known.Zero |= Known2.Zero;
  2513. }
  2514. break;
  2515. case ISD::SIGN_EXTEND_INREG: {
  2516. EVT EVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  2517. unsigned EBits = EVT.getScalarSizeInBits();
  2518. // Sign extension. Compute the demanded bits in the result that are not
  2519. // present in the input.
  2520. APInt NewBits = APInt::getHighBitsSet(BitWidth, BitWidth - EBits);
  2521. APInt InSignMask = APInt::getSignMask(EBits);
  2522. APInt InputDemandedBits = APInt::getLowBitsSet(BitWidth, EBits);
  2523. // If the sign extended bits are demanded, we know that the sign
  2524. // bit is demanded.
  2525. InSignMask = InSignMask.zext(BitWidth);
  2526. if (NewBits.getBoolValue())
  2527. InputDemandedBits |= InSignMask;
  2528. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2529. Known.One &= InputDemandedBits;
  2530. Known.Zero &= InputDemandedBits;
  2531. // If the sign bit of the input is known set or clear, then we know the
  2532. // top bits of the result.
  2533. if (Known.Zero.intersects(InSignMask)) { // Input sign bit known clear
  2534. Known.Zero |= NewBits;
  2535. Known.One &= ~NewBits;
  2536. } else if (Known.One.intersects(InSignMask)) { // Input sign bit known set
  2537. Known.One |= NewBits;
  2538. Known.Zero &= ~NewBits;
  2539. } else { // Input sign bit unknown
  2540. Known.Zero &= ~NewBits;
  2541. Known.One &= ~NewBits;
  2542. }
  2543. break;
  2544. }
  2545. case ISD::CTTZ:
  2546. case ISD::CTTZ_ZERO_UNDEF: {
  2547. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2548. // If we have a known 1, its position is our upper bound.
  2549. unsigned PossibleTZ = Known2.countMaxTrailingZeros();
  2550. unsigned LowBits = Log2_32(PossibleTZ) + 1;
  2551. Known.Zero.setBitsFrom(LowBits);
  2552. break;
  2553. }
  2554. case ISD::CTLZ:
  2555. case ISD::CTLZ_ZERO_UNDEF: {
  2556. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2557. // If we have a known 1, its position is our upper bound.
  2558. unsigned PossibleLZ = Known2.countMaxLeadingZeros();
  2559. unsigned LowBits = Log2_32(PossibleLZ) + 1;
  2560. Known.Zero.setBitsFrom(LowBits);
  2561. break;
  2562. }
  2563. case ISD::CTPOP: {
  2564. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2565. // If we know some of the bits are zero, they can't be one.
  2566. unsigned PossibleOnes = Known2.countMaxPopulation();
  2567. Known.Zero.setBitsFrom(Log2_32(PossibleOnes) + 1);
  2568. break;
  2569. }
  2570. case ISD::LOAD: {
  2571. LoadSDNode *LD = cast<LoadSDNode>(Op);
  2572. // If this is a ZEXTLoad and we are looking at the loaded value.
  2573. if (ISD::isZEXTLoad(Op.getNode()) && Op.getResNo() == 0) {
  2574. EVT VT = LD->getMemoryVT();
  2575. unsigned MemBits = VT.getScalarSizeInBits();
  2576. Known.Zero.setBitsFrom(MemBits);
  2577. } else if (const MDNode *Ranges = LD->getRanges()) {
  2578. if (LD->getExtensionType() == ISD::NON_EXTLOAD)
  2579. computeKnownBitsFromRangeMetadata(*Ranges, Known);
  2580. }
  2581. break;
  2582. }
  2583. case ISD::ZERO_EXTEND_VECTOR_INREG: {
  2584. EVT InVT = Op.getOperand(0).getValueType();
  2585. APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
  2586. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  2587. Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
  2588. break;
  2589. }
  2590. case ISD::ZERO_EXTEND: {
  2591. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2592. Known = Known.zext(BitWidth, true /* ExtendedBitsAreKnownZero */);
  2593. break;
  2594. }
  2595. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  2596. EVT InVT = Op.getOperand(0).getValueType();
  2597. APInt InDemandedElts = DemandedElts.zextOrSelf(InVT.getVectorNumElements());
  2598. Known = computeKnownBits(Op.getOperand(0), InDemandedElts, Depth + 1);
  2599. // If the sign bit is known to be zero or one, then sext will extend
  2600. // it to the top bits, else it will just zext.
  2601. Known = Known.sext(BitWidth);
  2602. break;
  2603. }
  2604. case ISD::SIGN_EXTEND: {
  2605. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2606. // If the sign bit is known to be zero or one, then sext will extend
  2607. // it to the top bits, else it will just zext.
  2608. Known = Known.sext(BitWidth);
  2609. break;
  2610. }
  2611. case ISD::ANY_EXTEND: {
  2612. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  2613. Known = Known.zext(BitWidth, false /* ExtendedBitsAreKnownZero */);
  2614. break;
  2615. }
  2616. case ISD::TRUNCATE: {
  2617. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2618. Known = Known.trunc(BitWidth);
  2619. break;
  2620. }
  2621. case ISD::AssertZext: {
  2622. EVT VT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  2623. APInt InMask = APInt::getLowBitsSet(BitWidth, VT.getSizeInBits());
  2624. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  2625. Known.Zero |= (~InMask);
  2626. Known.One &= (~Known.Zero);
  2627. break;
  2628. }
  2629. case ISD::FGETSIGN:
  2630. // All bits are zero except the low bit.
  2631. Known.Zero.setBitsFrom(1);
  2632. break;
  2633. case ISD::USUBO:
  2634. case ISD::SSUBO:
  2635. if (Op.getResNo() == 1) {
  2636. // If we know the result of a setcc has the top bits zero, use this info.
  2637. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  2638. TargetLowering::ZeroOrOneBooleanContent &&
  2639. BitWidth > 1)
  2640. Known.Zero.setBitsFrom(1);
  2641. break;
  2642. }
  2643. LLVM_FALLTHROUGH;
  2644. case ISD::SUB:
  2645. case ISD::SUBC: {
  2646. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2647. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2648. Known = KnownBits::computeForAddSub(/* Add */ false, /* NSW */ false,
  2649. Known, Known2);
  2650. break;
  2651. }
  2652. case ISD::UADDO:
  2653. case ISD::SADDO:
  2654. case ISD::ADDCARRY:
  2655. if (Op.getResNo() == 1) {
  2656. // If we know the result of a setcc has the top bits zero, use this info.
  2657. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  2658. TargetLowering::ZeroOrOneBooleanContent &&
  2659. BitWidth > 1)
  2660. Known.Zero.setBitsFrom(1);
  2661. break;
  2662. }
  2663. LLVM_FALLTHROUGH;
  2664. case ISD::ADD:
  2665. case ISD::ADDC:
  2666. case ISD::ADDE: {
  2667. assert(Op.getResNo() == 0 && "We only compute knownbits for the sum here.");
  2668. // With ADDE and ADDCARRY, a carry bit may be added in.
  2669. KnownBits Carry(1);
  2670. if (Opcode == ISD::ADDE)
  2671. // Can't track carry from glue, set carry to unknown.
  2672. Carry.resetAll();
  2673. else if (Opcode == ISD::ADDCARRY)
  2674. // TODO: Compute known bits for the carry operand. Not sure if it is worth
  2675. // the trouble (how often will we find a known carry bit). And I haven't
  2676. // tested this very much yet, but something like this might work:
  2677. // Carry = computeKnownBits(Op.getOperand(2), DemandedElts, Depth + 1);
  2678. // Carry = Carry.zextOrTrunc(1, false);
  2679. Carry.resetAll();
  2680. else
  2681. Carry.setAllZero();
  2682. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2683. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2684. Known = KnownBits::computeForAddCarry(Known, Known2, Carry);
  2685. break;
  2686. }
  2687. case ISD::SREM:
  2688. if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
  2689. const APInt &RA = Rem->getAPIntValue().abs();
  2690. if (RA.isPowerOf2()) {
  2691. APInt LowBits = RA - 1;
  2692. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2693. // The low bits of the first operand are unchanged by the srem.
  2694. Known.Zero = Known2.Zero & LowBits;
  2695. Known.One = Known2.One & LowBits;
  2696. // If the first operand is non-negative or has all low bits zero, then
  2697. // the upper bits are all zero.
  2698. if (Known2.Zero[BitWidth-1] || ((Known2.Zero & LowBits) == LowBits))
  2699. Known.Zero |= ~LowBits;
  2700. // If the first operand is negative and not all low bits are zero, then
  2701. // the upper bits are all one.
  2702. if (Known2.One[BitWidth-1] && ((Known2.One & LowBits) != 0))
  2703. Known.One |= ~LowBits;
  2704. assert((Known.Zero & Known.One) == 0&&"Bits known to be one AND zero?");
  2705. }
  2706. }
  2707. break;
  2708. case ISD::UREM: {
  2709. if (ConstantSDNode *Rem = isConstOrConstSplat(Op.getOperand(1))) {
  2710. const APInt &RA = Rem->getAPIntValue();
  2711. if (RA.isPowerOf2()) {
  2712. APInt LowBits = (RA - 1);
  2713. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2714. // The upper bits are all zero, the lower ones are unchanged.
  2715. Known.Zero = Known2.Zero | ~LowBits;
  2716. Known.One = Known2.One & LowBits;
  2717. break;
  2718. }
  2719. }
  2720. // Since the result is less than or equal to either operand, any leading
  2721. // zero bits in either operand must also exist in the result.
  2722. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2723. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2724. uint32_t Leaders =
  2725. std::max(Known.countMinLeadingZeros(), Known2.countMinLeadingZeros());
  2726. Known.resetAll();
  2727. Known.Zero.setHighBits(Leaders);
  2728. break;
  2729. }
  2730. case ISD::EXTRACT_ELEMENT: {
  2731. Known = computeKnownBits(Op.getOperand(0), Depth+1);
  2732. const unsigned Index = Op.getConstantOperandVal(1);
  2733. const unsigned BitWidth = Op.getValueSizeInBits();
  2734. // Remove low part of known bits mask
  2735. Known.Zero = Known.Zero.getHiBits(Known.Zero.getBitWidth() - Index * BitWidth);
  2736. Known.One = Known.One.getHiBits(Known.One.getBitWidth() - Index * BitWidth);
  2737. // Remove high part of known bit mask
  2738. Known = Known.trunc(BitWidth);
  2739. break;
  2740. }
  2741. case ISD::EXTRACT_VECTOR_ELT: {
  2742. SDValue InVec = Op.getOperand(0);
  2743. SDValue EltNo = Op.getOperand(1);
  2744. EVT VecVT = InVec.getValueType();
  2745. const unsigned BitWidth = Op.getValueSizeInBits();
  2746. const unsigned EltBitWidth = VecVT.getScalarSizeInBits();
  2747. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  2748. // If BitWidth > EltBitWidth the value is anyext:ed. So we do not know
  2749. // anything about the extended bits.
  2750. if (BitWidth > EltBitWidth)
  2751. Known = Known.trunc(EltBitWidth);
  2752. ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  2753. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts)) {
  2754. // If we know the element index, just demand that vector element.
  2755. unsigned Idx = ConstEltNo->getZExtValue();
  2756. APInt DemandedElt = APInt::getOneBitSet(NumSrcElts, Idx);
  2757. Known = computeKnownBits(InVec, DemandedElt, Depth + 1);
  2758. } else {
  2759. // Unknown element index, so ignore DemandedElts and demand them all.
  2760. Known = computeKnownBits(InVec, Depth + 1);
  2761. }
  2762. if (BitWidth > EltBitWidth)
  2763. Known = Known.zext(BitWidth, false /* => any extend */);
  2764. break;
  2765. }
  2766. case ISD::INSERT_VECTOR_ELT: {
  2767. SDValue InVec = Op.getOperand(0);
  2768. SDValue InVal = Op.getOperand(1);
  2769. SDValue EltNo = Op.getOperand(2);
  2770. ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  2771. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  2772. // If we know the element index, split the demand between the
  2773. // source vector and the inserted element.
  2774. Known.Zero = Known.One = APInt::getAllOnesValue(BitWidth);
  2775. unsigned EltIdx = CEltNo->getZExtValue();
  2776. // If we demand the inserted element then add its common known bits.
  2777. if (DemandedElts[EltIdx]) {
  2778. Known2 = computeKnownBits(InVal, Depth + 1);
  2779. Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
  2780. Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
  2781. }
  2782. // If we demand the source vector then add its common known bits, ensuring
  2783. // that we don't demand the inserted element.
  2784. APInt VectorElts = DemandedElts & ~(APInt::getOneBitSet(NumElts, EltIdx));
  2785. if (!!VectorElts) {
  2786. Known2 = computeKnownBits(InVec, VectorElts, Depth + 1);
  2787. Known.One &= Known2.One;
  2788. Known.Zero &= Known2.Zero;
  2789. }
  2790. } else {
  2791. // Unknown element index, so ignore DemandedElts and demand them all.
  2792. Known = computeKnownBits(InVec, Depth + 1);
  2793. Known2 = computeKnownBits(InVal, Depth + 1);
  2794. Known.One &= Known2.One.zextOrTrunc(Known.One.getBitWidth());
  2795. Known.Zero &= Known2.Zero.zextOrTrunc(Known.Zero.getBitWidth());
  2796. }
  2797. break;
  2798. }
  2799. case ISD::BITREVERSE: {
  2800. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2801. Known.Zero = Known2.Zero.reverseBits();
  2802. Known.One = Known2.One.reverseBits();
  2803. break;
  2804. }
  2805. case ISD::BSWAP: {
  2806. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2807. Known.Zero = Known2.Zero.byteSwap();
  2808. Known.One = Known2.One.byteSwap();
  2809. break;
  2810. }
  2811. case ISD::ABS: {
  2812. Known2 = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2813. // If the source's MSB is zero then we know the rest of the bits already.
  2814. if (Known2.isNonNegative()) {
  2815. Known.Zero = Known2.Zero;
  2816. Known.One = Known2.One;
  2817. break;
  2818. }
  2819. // We only know that the absolute values's MSB will be zero iff there is
  2820. // a set bit that isn't the sign bit (otherwise it could be INT_MIN).
  2821. Known2.One.clearSignBit();
  2822. if (Known2.One.getBoolValue()) {
  2823. Known.Zero = APInt::getSignMask(BitWidth);
  2824. break;
  2825. }
  2826. break;
  2827. }
  2828. case ISD::UMIN: {
  2829. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2830. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2831. // UMIN - we know that the result will have the maximum of the
  2832. // known zero leading bits of the inputs.
  2833. unsigned LeadZero = Known.countMinLeadingZeros();
  2834. LeadZero = std::max(LeadZero, Known2.countMinLeadingZeros());
  2835. Known.Zero &= Known2.Zero;
  2836. Known.One &= Known2.One;
  2837. Known.Zero.setHighBits(LeadZero);
  2838. break;
  2839. }
  2840. case ISD::UMAX: {
  2841. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2842. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2843. // UMAX - we know that the result will have the maximum of the
  2844. // known one leading bits of the inputs.
  2845. unsigned LeadOne = Known.countMinLeadingOnes();
  2846. LeadOne = std::max(LeadOne, Known2.countMinLeadingOnes());
  2847. Known.Zero &= Known2.Zero;
  2848. Known.One &= Known2.One;
  2849. Known.One.setHighBits(LeadOne);
  2850. break;
  2851. }
  2852. case ISD::SMIN:
  2853. case ISD::SMAX: {
  2854. // If we have a clamp pattern, we know that the number of sign bits will be
  2855. // the minimum of the clamp min/max range.
  2856. bool IsMax = (Opcode == ISD::SMAX);
  2857. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  2858. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  2859. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  2860. CstHigh =
  2861. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  2862. if (CstLow && CstHigh) {
  2863. if (!IsMax)
  2864. std::swap(CstLow, CstHigh);
  2865. const APInt &ValueLow = CstLow->getAPIntValue();
  2866. const APInt &ValueHigh = CstHigh->getAPIntValue();
  2867. if (ValueLow.sle(ValueHigh)) {
  2868. unsigned LowSignBits = ValueLow.getNumSignBits();
  2869. unsigned HighSignBits = ValueHigh.getNumSignBits();
  2870. unsigned MinSignBits = std::min(LowSignBits, HighSignBits);
  2871. if (ValueLow.isNegative() && ValueHigh.isNegative()) {
  2872. Known.One.setHighBits(MinSignBits);
  2873. break;
  2874. }
  2875. if (ValueLow.isNonNegative() && ValueHigh.isNonNegative()) {
  2876. Known.Zero.setHighBits(MinSignBits);
  2877. break;
  2878. }
  2879. }
  2880. }
  2881. // Fallback - just get the shared known bits of the operands.
  2882. Known = computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  2883. if (Known.isUnknown()) break; // Early-out
  2884. Known2 = computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  2885. Known.Zero &= Known2.Zero;
  2886. Known.One &= Known2.One;
  2887. break;
  2888. }
  2889. case ISD::FrameIndex:
  2890. case ISD::TargetFrameIndex:
  2891. TLI->computeKnownBitsForFrameIndex(Op, Known, DemandedElts, *this, Depth);
  2892. break;
  2893. default:
  2894. if (Opcode < ISD::BUILTIN_OP_END)
  2895. break;
  2896. LLVM_FALLTHROUGH;
  2897. case ISD::INTRINSIC_WO_CHAIN:
  2898. case ISD::INTRINSIC_W_CHAIN:
  2899. case ISD::INTRINSIC_VOID:
  2900. // Allow the target to implement this method for its nodes.
  2901. TLI->computeKnownBitsForTargetNode(Op, Known, DemandedElts, *this, Depth);
  2902. break;
  2903. }
  2904. assert(!Known.hasConflict() && "Bits known to be one AND zero?");
  2905. return Known;
  2906. }
  2907. SelectionDAG::OverflowKind SelectionDAG::computeOverflowKind(SDValue N0,
  2908. SDValue N1) const {
  2909. // X + 0 never overflow
  2910. if (isNullConstant(N1))
  2911. return OFK_Never;
  2912. KnownBits N1Known = computeKnownBits(N1);
  2913. if (N1Known.Zero.getBoolValue()) {
  2914. KnownBits N0Known = computeKnownBits(N0);
  2915. bool overflow;
  2916. (void)(~N0Known.Zero).uadd_ov(~N1Known.Zero, overflow);
  2917. if (!overflow)
  2918. return OFK_Never;
  2919. }
  2920. // mulhi + 1 never overflow
  2921. if (N0.getOpcode() == ISD::UMUL_LOHI && N0.getResNo() == 1 &&
  2922. (~N1Known.Zero & 0x01) == ~N1Known.Zero)
  2923. return OFK_Never;
  2924. if (N1.getOpcode() == ISD::UMUL_LOHI && N1.getResNo() == 1) {
  2925. KnownBits N0Known = computeKnownBits(N0);
  2926. if ((~N0Known.Zero & 0x01) == ~N0Known.Zero)
  2927. return OFK_Never;
  2928. }
  2929. return OFK_Sometime;
  2930. }
  2931. bool SelectionDAG::isKnownToBeAPowerOfTwo(SDValue Val) const {
  2932. EVT OpVT = Val.getValueType();
  2933. unsigned BitWidth = OpVT.getScalarSizeInBits();
  2934. // Is the constant a known power of 2?
  2935. if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Val))
  2936. return Const->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  2937. // A left-shift of a constant one will have exactly one bit set because
  2938. // shifting the bit off the end is undefined.
  2939. if (Val.getOpcode() == ISD::SHL) {
  2940. auto *C = isConstOrConstSplat(Val.getOperand(0));
  2941. if (C && C->getAPIntValue() == 1)
  2942. return true;
  2943. }
  2944. // Similarly, a logical right-shift of a constant sign-bit will have exactly
  2945. // one bit set.
  2946. if (Val.getOpcode() == ISD::SRL) {
  2947. auto *C = isConstOrConstSplat(Val.getOperand(0));
  2948. if (C && C->getAPIntValue().isSignMask())
  2949. return true;
  2950. }
  2951. // Are all operands of a build vector constant powers of two?
  2952. if (Val.getOpcode() == ISD::BUILD_VECTOR)
  2953. if (llvm::all_of(Val->ops(), [BitWidth](SDValue E) {
  2954. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(E))
  2955. return C->getAPIntValue().zextOrTrunc(BitWidth).isPowerOf2();
  2956. return false;
  2957. }))
  2958. return true;
  2959. // More could be done here, though the above checks are enough
  2960. // to handle some common cases.
  2961. // Fall back to computeKnownBits to catch other known cases.
  2962. KnownBits Known = computeKnownBits(Val);
  2963. return (Known.countMaxPopulation() == 1) && (Known.countMinPopulation() == 1);
  2964. }
  2965. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, unsigned Depth) const {
  2966. EVT VT = Op.getValueType();
  2967. APInt DemandedElts = VT.isVector()
  2968. ? APInt::getAllOnesValue(VT.getVectorNumElements())
  2969. : APInt(1, 1);
  2970. return ComputeNumSignBits(Op, DemandedElts, Depth);
  2971. }
  2972. unsigned SelectionDAG::ComputeNumSignBits(SDValue Op, const APInt &DemandedElts,
  2973. unsigned Depth) const {
  2974. EVT VT = Op.getValueType();
  2975. assert((VT.isInteger() || VT.isFloatingPoint()) && "Invalid VT!");
  2976. unsigned VTBits = VT.getScalarSizeInBits();
  2977. unsigned NumElts = DemandedElts.getBitWidth();
  2978. unsigned Tmp, Tmp2;
  2979. unsigned FirstAnswer = 1;
  2980. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  2981. const APInt &Val = C->getAPIntValue();
  2982. return Val.getNumSignBits();
  2983. }
  2984. if (Depth == 6)
  2985. return 1; // Limit search depth.
  2986. if (!DemandedElts)
  2987. return 1; // No demanded elts, better to assume we don't know anything.
  2988. unsigned Opcode = Op.getOpcode();
  2989. switch (Opcode) {
  2990. default: break;
  2991. case ISD::AssertSext:
  2992. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  2993. return VTBits-Tmp+1;
  2994. case ISD::AssertZext:
  2995. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getSizeInBits();
  2996. return VTBits-Tmp;
  2997. case ISD::BUILD_VECTOR:
  2998. Tmp = VTBits;
  2999. for (unsigned i = 0, e = Op.getNumOperands(); (i < e) && (Tmp > 1); ++i) {
  3000. if (!DemandedElts[i])
  3001. continue;
  3002. SDValue SrcOp = Op.getOperand(i);
  3003. Tmp2 = ComputeNumSignBits(Op.getOperand(i), Depth + 1);
  3004. // BUILD_VECTOR can implicitly truncate sources, we must handle this.
  3005. if (SrcOp.getValueSizeInBits() != VTBits) {
  3006. assert(SrcOp.getValueSizeInBits() > VTBits &&
  3007. "Expected BUILD_VECTOR implicit truncation");
  3008. unsigned ExtraBits = SrcOp.getValueSizeInBits() - VTBits;
  3009. Tmp2 = (Tmp2 > ExtraBits ? Tmp2 - ExtraBits : 1);
  3010. }
  3011. Tmp = std::min(Tmp, Tmp2);
  3012. }
  3013. return Tmp;
  3014. case ISD::VECTOR_SHUFFLE: {
  3015. // Collect the minimum number of sign bits that are shared by every vector
  3016. // element referenced by the shuffle.
  3017. APInt DemandedLHS(NumElts, 0), DemandedRHS(NumElts, 0);
  3018. const ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op);
  3019. assert(NumElts == SVN->getMask().size() && "Unexpected vector size");
  3020. for (unsigned i = 0; i != NumElts; ++i) {
  3021. int M = SVN->getMaskElt(i);
  3022. if (!DemandedElts[i])
  3023. continue;
  3024. // For UNDEF elements, we don't know anything about the common state of
  3025. // the shuffle result.
  3026. if (M < 0)
  3027. return 1;
  3028. if ((unsigned)M < NumElts)
  3029. DemandedLHS.setBit((unsigned)M % NumElts);
  3030. else
  3031. DemandedRHS.setBit((unsigned)M % NumElts);
  3032. }
  3033. Tmp = std::numeric_limits<unsigned>::max();
  3034. if (!!DemandedLHS)
  3035. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedLHS, Depth + 1);
  3036. if (!!DemandedRHS) {
  3037. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedRHS, Depth + 1);
  3038. Tmp = std::min(Tmp, Tmp2);
  3039. }
  3040. // If we don't know anything, early out and try computeKnownBits fall-back.
  3041. if (Tmp == 1)
  3042. break;
  3043. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3044. return Tmp;
  3045. }
  3046. case ISD::BITCAST: {
  3047. SDValue N0 = Op.getOperand(0);
  3048. EVT SrcVT = N0.getValueType();
  3049. unsigned SrcBits = SrcVT.getScalarSizeInBits();
  3050. // Ignore bitcasts from unsupported types..
  3051. if (!(SrcVT.isInteger() || SrcVT.isFloatingPoint()))
  3052. break;
  3053. // Fast handling of 'identity' bitcasts.
  3054. if (VTBits == SrcBits)
  3055. return ComputeNumSignBits(N0, DemandedElts, Depth + 1);
  3056. bool IsLE = getDataLayout().isLittleEndian();
  3057. // Bitcast 'large element' scalar/vector to 'small element' vector.
  3058. if ((SrcBits % VTBits) == 0) {
  3059. assert(VT.isVector() && "Expected bitcast to vector");
  3060. unsigned Scale = SrcBits / VTBits;
  3061. APInt SrcDemandedElts(NumElts / Scale, 0);
  3062. for (unsigned i = 0; i != NumElts; ++i)
  3063. if (DemandedElts[i])
  3064. SrcDemandedElts.setBit(i / Scale);
  3065. // Fast case - sign splat can be simply split across the small elements.
  3066. Tmp = ComputeNumSignBits(N0, SrcDemandedElts, Depth + 1);
  3067. if (Tmp == SrcBits)
  3068. return VTBits;
  3069. // Slow case - determine how far the sign extends into each sub-element.
  3070. Tmp2 = VTBits;
  3071. for (unsigned i = 0; i != NumElts; ++i)
  3072. if (DemandedElts[i]) {
  3073. unsigned SubOffset = i % Scale;
  3074. SubOffset = (IsLE ? ((Scale - 1) - SubOffset) : SubOffset);
  3075. SubOffset = SubOffset * VTBits;
  3076. if (Tmp <= SubOffset)
  3077. return 1;
  3078. Tmp2 = std::min(Tmp2, Tmp - SubOffset);
  3079. }
  3080. return Tmp2;
  3081. }
  3082. break;
  3083. }
  3084. case ISD::SIGN_EXTEND:
  3085. Tmp = VTBits - Op.getOperand(0).getScalarValueSizeInBits();
  3086. return ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1) + Tmp;
  3087. case ISD::SIGN_EXTEND_INREG:
  3088. // Max of the input and what this extends.
  3089. Tmp = cast<VTSDNode>(Op.getOperand(1))->getVT().getScalarSizeInBits();
  3090. Tmp = VTBits-Tmp+1;
  3091. Tmp2 = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3092. return std::max(Tmp, Tmp2);
  3093. case ISD::SIGN_EXTEND_VECTOR_INREG: {
  3094. SDValue Src = Op.getOperand(0);
  3095. EVT SrcVT = Src.getValueType();
  3096. APInt DemandedSrcElts = DemandedElts.zextOrSelf(SrcVT.getVectorNumElements());
  3097. Tmp = VTBits - SrcVT.getScalarSizeInBits();
  3098. return ComputeNumSignBits(Src, DemandedSrcElts, Depth+1) + Tmp;
  3099. }
  3100. case ISD::SRA:
  3101. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3102. // SRA X, C -> adds C sign bits.
  3103. if (ConstantSDNode *C =
  3104. isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
  3105. APInt ShiftVal = C->getAPIntValue();
  3106. ShiftVal += Tmp;
  3107. Tmp = ShiftVal.uge(VTBits) ? VTBits : ShiftVal.getZExtValue();
  3108. }
  3109. return Tmp;
  3110. case ISD::SHL:
  3111. if (ConstantSDNode *C =
  3112. isConstOrConstSplat(Op.getOperand(1), DemandedElts)) {
  3113. // shl destroys sign bits.
  3114. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3115. if (C->getAPIntValue().uge(VTBits) || // Bad shift.
  3116. C->getAPIntValue().uge(Tmp)) break; // Shifted all sign bits out.
  3117. return Tmp - C->getZExtValue();
  3118. }
  3119. break;
  3120. case ISD::AND:
  3121. case ISD::OR:
  3122. case ISD::XOR: // NOT is handled here.
  3123. // Logical binary ops preserve the number of sign bits at the worst.
  3124. Tmp = ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth+1);
  3125. if (Tmp != 1) {
  3126. Tmp2 = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3127. FirstAnswer = std::min(Tmp, Tmp2);
  3128. // We computed what we know about the sign bits as our first
  3129. // answer. Now proceed to the generic code that uses
  3130. // computeKnownBits, and pick whichever answer is better.
  3131. }
  3132. break;
  3133. case ISD::SELECT:
  3134. case ISD::VSELECT:
  3135. Tmp = ComputeNumSignBits(Op.getOperand(1), DemandedElts, Depth+1);
  3136. if (Tmp == 1) return 1; // Early out.
  3137. Tmp2 = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3138. return std::min(Tmp, Tmp2);
  3139. case ISD::SELECT_CC:
  3140. Tmp = ComputeNumSignBits(Op.getOperand(2), DemandedElts, Depth+1);
  3141. if (Tmp == 1) return 1; // Early out.
  3142. Tmp2 = ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth+1);
  3143. return std::min(Tmp, Tmp2);
  3144. case ISD::SMIN:
  3145. case ISD::SMAX: {
  3146. // If we have a clamp pattern, we know that the number of sign bits will be
  3147. // the minimum of the clamp min/max range.
  3148. bool IsMax = (Opcode == ISD::SMAX);
  3149. ConstantSDNode *CstLow = nullptr, *CstHigh = nullptr;
  3150. if ((CstLow = isConstOrConstSplat(Op.getOperand(1), DemandedElts)))
  3151. if (Op.getOperand(0).getOpcode() == (IsMax ? ISD::SMIN : ISD::SMAX))
  3152. CstHigh =
  3153. isConstOrConstSplat(Op.getOperand(0).getOperand(1), DemandedElts);
  3154. if (CstLow && CstHigh) {
  3155. if (!IsMax)
  3156. std::swap(CstLow, CstHigh);
  3157. if (CstLow->getAPIntValue().sle(CstHigh->getAPIntValue())) {
  3158. Tmp = CstLow->getAPIntValue().getNumSignBits();
  3159. Tmp2 = CstHigh->getAPIntValue().getNumSignBits();
  3160. return std::min(Tmp, Tmp2);
  3161. }
  3162. }
  3163. // Fallback - just get the minimum number of sign bits of the operands.
  3164. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3165. if (Tmp == 1)
  3166. return 1; // Early out.
  3167. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
  3168. return std::min(Tmp, Tmp2);
  3169. }
  3170. case ISD::UMIN:
  3171. case ISD::UMAX:
  3172. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3173. if (Tmp == 1)
  3174. return 1; // Early out.
  3175. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth + 1);
  3176. return std::min(Tmp, Tmp2);
  3177. case ISD::SADDO:
  3178. case ISD::UADDO:
  3179. case ISD::SSUBO:
  3180. case ISD::USUBO:
  3181. case ISD::SMULO:
  3182. case ISD::UMULO:
  3183. if (Op.getResNo() != 1)
  3184. break;
  3185. // The boolean result conforms to getBooleanContents. Fall through.
  3186. // If setcc returns 0/-1, all bits are sign bits.
  3187. // We know that we have an integer-based boolean since these operations
  3188. // are only available for integer.
  3189. if (TLI->getBooleanContents(VT.isVector(), false) ==
  3190. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3191. return VTBits;
  3192. break;
  3193. case ISD::SETCC:
  3194. // If setcc returns 0/-1, all bits are sign bits.
  3195. if (TLI->getBooleanContents(Op.getOperand(0).getValueType()) ==
  3196. TargetLowering::ZeroOrNegativeOneBooleanContent)
  3197. return VTBits;
  3198. break;
  3199. case ISD::ROTL:
  3200. case ISD::ROTR:
  3201. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  3202. unsigned RotAmt = C->getAPIntValue().urem(VTBits);
  3203. // Handle rotate right by N like a rotate left by 32-N.
  3204. if (Opcode == ISD::ROTR)
  3205. RotAmt = (VTBits - RotAmt) % VTBits;
  3206. // If we aren't rotating out all of the known-in sign bits, return the
  3207. // number that are left. This handles rotl(sext(x), 1) for example.
  3208. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3209. if (Tmp > (RotAmt + 1)) return (Tmp - RotAmt);
  3210. }
  3211. break;
  3212. case ISD::ADD:
  3213. case ISD::ADDC:
  3214. // Add can have at most one carry bit. Thus we know that the output
  3215. // is, at worst, one more bit than the inputs.
  3216. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3217. if (Tmp == 1) return 1; // Early out.
  3218. // Special case decrementing a value (ADD X, -1):
  3219. if (ConstantSDNode *CRHS = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
  3220. if (CRHS->isAllOnesValue()) {
  3221. KnownBits Known = computeKnownBits(Op.getOperand(0), Depth+1);
  3222. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3223. // sign bits set.
  3224. if ((Known.Zero | 1).isAllOnesValue())
  3225. return VTBits;
  3226. // If we are subtracting one from a positive number, there is no carry
  3227. // out of the result.
  3228. if (Known.isNonNegative())
  3229. return Tmp;
  3230. }
  3231. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  3232. if (Tmp2 == 1) return 1;
  3233. return std::min(Tmp, Tmp2)-1;
  3234. case ISD::SUB:
  3235. Tmp2 = ComputeNumSignBits(Op.getOperand(1), Depth+1);
  3236. if (Tmp2 == 1) return 1;
  3237. // Handle NEG.
  3238. if (ConstantSDNode *CLHS = isConstOrConstSplat(Op.getOperand(0)))
  3239. if (CLHS->isNullValue()) {
  3240. KnownBits Known = computeKnownBits(Op.getOperand(1), Depth+1);
  3241. // If the input is known to be 0 or 1, the output is 0/-1, which is all
  3242. // sign bits set.
  3243. if ((Known.Zero | 1).isAllOnesValue())
  3244. return VTBits;
  3245. // If the input is known to be positive (the sign bit is known clear),
  3246. // the output of the NEG has the same number of sign bits as the input.
  3247. if (Known.isNonNegative())
  3248. return Tmp2;
  3249. // Otherwise, we treat this like a SUB.
  3250. }
  3251. // Sub can have at most one carry bit. Thus we know that the output
  3252. // is, at worst, one more bit than the inputs.
  3253. Tmp = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3254. if (Tmp == 1) return 1; // Early out.
  3255. return std::min(Tmp, Tmp2)-1;
  3256. case ISD::TRUNCATE: {
  3257. // Check if the sign bits of source go down as far as the truncated value.
  3258. unsigned NumSrcBits = Op.getOperand(0).getScalarValueSizeInBits();
  3259. unsigned NumSrcSignBits = ComputeNumSignBits(Op.getOperand(0), Depth + 1);
  3260. if (NumSrcSignBits > (NumSrcBits - VTBits))
  3261. return NumSrcSignBits - (NumSrcBits - VTBits);
  3262. break;
  3263. }
  3264. case ISD::EXTRACT_ELEMENT: {
  3265. const int KnownSign = ComputeNumSignBits(Op.getOperand(0), Depth+1);
  3266. const int BitWidth = Op.getValueSizeInBits();
  3267. const int Items = Op.getOperand(0).getValueSizeInBits() / BitWidth;
  3268. // Get reverse index (starting from 1), Op1 value indexes elements from
  3269. // little end. Sign starts at big end.
  3270. const int rIndex = Items - 1 - Op.getConstantOperandVal(1);
  3271. // If the sign portion ends in our element the subtraction gives correct
  3272. // result. Otherwise it gives either negative or > bitwidth result
  3273. return std::max(std::min(KnownSign - rIndex * BitWidth, BitWidth), 0);
  3274. }
  3275. case ISD::INSERT_VECTOR_ELT: {
  3276. SDValue InVec = Op.getOperand(0);
  3277. SDValue InVal = Op.getOperand(1);
  3278. SDValue EltNo = Op.getOperand(2);
  3279. unsigned NumElts = InVec.getValueType().getVectorNumElements();
  3280. ConstantSDNode *CEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3281. if (CEltNo && CEltNo->getAPIntValue().ult(NumElts)) {
  3282. // If we know the element index, split the demand between the
  3283. // source vector and the inserted element.
  3284. unsigned EltIdx = CEltNo->getZExtValue();
  3285. // If we demand the inserted element then get its sign bits.
  3286. Tmp = std::numeric_limits<unsigned>::max();
  3287. if (DemandedElts[EltIdx]) {
  3288. // TODO - handle implicit truncation of inserted elements.
  3289. if (InVal.getScalarValueSizeInBits() != VTBits)
  3290. break;
  3291. Tmp = ComputeNumSignBits(InVal, Depth + 1);
  3292. }
  3293. // If we demand the source vector then get its sign bits, and determine
  3294. // the minimum.
  3295. APInt VectorElts = DemandedElts;
  3296. VectorElts.clearBit(EltIdx);
  3297. if (!!VectorElts) {
  3298. Tmp2 = ComputeNumSignBits(InVec, VectorElts, Depth + 1);
  3299. Tmp = std::min(Tmp, Tmp2);
  3300. }
  3301. } else {
  3302. // Unknown element index, so ignore DemandedElts and demand them all.
  3303. Tmp = ComputeNumSignBits(InVec, Depth + 1);
  3304. Tmp2 = ComputeNumSignBits(InVal, Depth + 1);
  3305. Tmp = std::min(Tmp, Tmp2);
  3306. }
  3307. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3308. return Tmp;
  3309. }
  3310. case ISD::EXTRACT_VECTOR_ELT: {
  3311. SDValue InVec = Op.getOperand(0);
  3312. SDValue EltNo = Op.getOperand(1);
  3313. EVT VecVT = InVec.getValueType();
  3314. const unsigned BitWidth = Op.getValueSizeInBits();
  3315. const unsigned EltBitWidth = Op.getOperand(0).getScalarValueSizeInBits();
  3316. const unsigned NumSrcElts = VecVT.getVectorNumElements();
  3317. // If BitWidth > EltBitWidth the value is anyext:ed, and we do not know
  3318. // anything about sign bits. But if the sizes match we can derive knowledge
  3319. // about sign bits from the vector operand.
  3320. if (BitWidth != EltBitWidth)
  3321. break;
  3322. // If we know the element index, just demand that vector element, else for
  3323. // an unknown element index, ignore DemandedElts and demand them all.
  3324. APInt DemandedSrcElts = APInt::getAllOnesValue(NumSrcElts);
  3325. ConstantSDNode *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo);
  3326. if (ConstEltNo && ConstEltNo->getAPIntValue().ult(NumSrcElts))
  3327. DemandedSrcElts =
  3328. APInt::getOneBitSet(NumSrcElts, ConstEltNo->getZExtValue());
  3329. return ComputeNumSignBits(InVec, DemandedSrcElts, Depth + 1);
  3330. }
  3331. case ISD::EXTRACT_SUBVECTOR: {
  3332. // If we know the element index, just demand that subvector elements,
  3333. // otherwise demand them all.
  3334. SDValue Src = Op.getOperand(0);
  3335. ConstantSDNode *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  3336. unsigned NumSrcElts = Src.getValueType().getVectorNumElements();
  3337. if (SubIdx && SubIdx->getAPIntValue().ule(NumSrcElts - NumElts)) {
  3338. // Offset the demanded elts by the subvector index.
  3339. uint64_t Idx = SubIdx->getZExtValue();
  3340. APInt DemandedSrc = DemandedElts.zextOrSelf(NumSrcElts).shl(Idx);
  3341. return ComputeNumSignBits(Src, DemandedSrc, Depth + 1);
  3342. }
  3343. return ComputeNumSignBits(Src, Depth + 1);
  3344. }
  3345. case ISD::CONCAT_VECTORS: {
  3346. // Determine the minimum number of sign bits across all demanded
  3347. // elts of the input vectors. Early out if the result is already 1.
  3348. Tmp = std::numeric_limits<unsigned>::max();
  3349. EVT SubVectorVT = Op.getOperand(0).getValueType();
  3350. unsigned NumSubVectorElts = SubVectorVT.getVectorNumElements();
  3351. unsigned NumSubVectors = Op.getNumOperands();
  3352. for (unsigned i = 0; (i < NumSubVectors) && (Tmp > 1); ++i) {
  3353. APInt DemandedSub = DemandedElts.lshr(i * NumSubVectorElts);
  3354. DemandedSub = DemandedSub.trunc(NumSubVectorElts);
  3355. if (!DemandedSub)
  3356. continue;
  3357. Tmp2 = ComputeNumSignBits(Op.getOperand(i), DemandedSub, Depth + 1);
  3358. Tmp = std::min(Tmp, Tmp2);
  3359. }
  3360. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3361. return Tmp;
  3362. }
  3363. case ISD::INSERT_SUBVECTOR: {
  3364. // If we know the element index, demand any elements from the subvector and
  3365. // the remainder from the src its inserted into, otherwise demand them all.
  3366. SDValue Src = Op.getOperand(0);
  3367. SDValue Sub = Op.getOperand(1);
  3368. auto *SubIdx = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  3369. unsigned NumSubElts = Sub.getValueType().getVectorNumElements();
  3370. if (SubIdx && SubIdx->getAPIntValue().ule(NumElts - NumSubElts)) {
  3371. Tmp = std::numeric_limits<unsigned>::max();
  3372. uint64_t Idx = SubIdx->getZExtValue();
  3373. APInt DemandedSubElts = DemandedElts.extractBits(NumSubElts, Idx);
  3374. if (!!DemandedSubElts) {
  3375. Tmp = ComputeNumSignBits(Sub, DemandedSubElts, Depth + 1);
  3376. if (Tmp == 1) return 1; // early-out
  3377. }
  3378. APInt SubMask = APInt::getBitsSet(NumElts, Idx, Idx + NumSubElts);
  3379. APInt DemandedSrcElts = DemandedElts & ~SubMask;
  3380. if (!!DemandedSrcElts) {
  3381. Tmp2 = ComputeNumSignBits(Src, DemandedSrcElts, Depth + 1);
  3382. Tmp = std::min(Tmp, Tmp2);
  3383. }
  3384. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3385. return Tmp;
  3386. }
  3387. // Not able to determine the index so just assume worst case.
  3388. Tmp = ComputeNumSignBits(Sub, Depth + 1);
  3389. if (Tmp == 1) return 1; // early-out
  3390. Tmp2 = ComputeNumSignBits(Src, Depth + 1);
  3391. Tmp = std::min(Tmp, Tmp2);
  3392. assert(Tmp <= VTBits && "Failed to determine minimum sign bits");
  3393. return Tmp;
  3394. }
  3395. }
  3396. // If we are looking at the loaded value of the SDNode.
  3397. if (Op.getResNo() == 0) {
  3398. // Handle LOADX separately here. EXTLOAD case will fallthrough.
  3399. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
  3400. unsigned ExtType = LD->getExtensionType();
  3401. switch (ExtType) {
  3402. default: break;
  3403. case ISD::SEXTLOAD: // '17' bits known
  3404. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  3405. return VTBits-Tmp+1;
  3406. case ISD::ZEXTLOAD: // '16' bits known
  3407. Tmp = LD->getMemoryVT().getScalarSizeInBits();
  3408. return VTBits-Tmp;
  3409. }
  3410. }
  3411. }
  3412. // Allow the target to implement this method for its nodes.
  3413. if (Opcode >= ISD::BUILTIN_OP_END ||
  3414. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  3415. Opcode == ISD::INTRINSIC_W_CHAIN ||
  3416. Opcode == ISD::INTRINSIC_VOID) {
  3417. unsigned NumBits =
  3418. TLI->ComputeNumSignBitsForTargetNode(Op, DemandedElts, *this, Depth);
  3419. if (NumBits > 1)
  3420. FirstAnswer = std::max(FirstAnswer, NumBits);
  3421. }
  3422. // Finally, if we can prove that the top bits of the result are 0's or 1's,
  3423. // use this information.
  3424. KnownBits Known = computeKnownBits(Op, DemandedElts, Depth);
  3425. APInt Mask;
  3426. if (Known.isNonNegative()) { // sign bit is 0
  3427. Mask = Known.Zero;
  3428. } else if (Known.isNegative()) { // sign bit is 1;
  3429. Mask = Known.One;
  3430. } else {
  3431. // Nothing known.
  3432. return FirstAnswer;
  3433. }
  3434. // Okay, we know that the sign bit in Mask is set. Use CLZ to determine
  3435. // the number of identical bits in the top of the input value.
  3436. Mask = ~Mask;
  3437. Mask <<= Mask.getBitWidth()-VTBits;
  3438. // Return # leading zeros. We use 'min' here in case Val was zero before
  3439. // shifting. We don't want to return '64' as for an i32 "0".
  3440. return std::max(FirstAnswer, std::min(VTBits, Mask.countLeadingZeros()));
  3441. }
  3442. bool SelectionDAG::isBaseWithConstantOffset(SDValue Op) const {
  3443. if ((Op.getOpcode() != ISD::ADD && Op.getOpcode() != ISD::OR) ||
  3444. !isa<ConstantSDNode>(Op.getOperand(1)))
  3445. return false;
  3446. if (Op.getOpcode() == ISD::OR &&
  3447. !MaskedValueIsZero(Op.getOperand(0), Op.getConstantOperandAPInt(1)))
  3448. return false;
  3449. return true;
  3450. }
  3451. bool SelectionDAG::isKnownNeverNaN(SDValue Op, bool SNaN, unsigned Depth) const {
  3452. // If we're told that NaNs won't happen, assume they won't.
  3453. if (getTarget().Options.NoNaNsFPMath || Op->getFlags().hasNoNaNs())
  3454. return true;
  3455. if (Depth == 6)
  3456. return false; // Limit search depth.
  3457. // TODO: Handle vectors.
  3458. // If the value is a constant, we can obviously see if it is a NaN or not.
  3459. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op)) {
  3460. return !C->getValueAPF().isNaN() ||
  3461. (SNaN && !C->getValueAPF().isSignaling());
  3462. }
  3463. unsigned Opcode = Op.getOpcode();
  3464. switch (Opcode) {
  3465. case ISD::FADD:
  3466. case ISD::FSUB:
  3467. case ISD::FMUL:
  3468. case ISD::FDIV:
  3469. case ISD::FREM:
  3470. case ISD::FSIN:
  3471. case ISD::FCOS: {
  3472. if (SNaN)
  3473. return true;
  3474. // TODO: Need isKnownNeverInfinity
  3475. return false;
  3476. }
  3477. case ISD::FCANONICALIZE:
  3478. case ISD::FEXP:
  3479. case ISD::FEXP2:
  3480. case ISD::FTRUNC:
  3481. case ISD::FFLOOR:
  3482. case ISD::FCEIL:
  3483. case ISD::FROUND:
  3484. case ISD::FRINT:
  3485. case ISD::FNEARBYINT: {
  3486. if (SNaN)
  3487. return true;
  3488. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3489. }
  3490. case ISD::FABS:
  3491. case ISD::FNEG:
  3492. case ISD::FCOPYSIGN: {
  3493. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3494. }
  3495. case ISD::SELECT:
  3496. return isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
  3497. isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
  3498. case ISD::FP_EXTEND:
  3499. case ISD::FP_ROUND: {
  3500. if (SNaN)
  3501. return true;
  3502. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3503. }
  3504. case ISD::SINT_TO_FP:
  3505. case ISD::UINT_TO_FP:
  3506. return true;
  3507. case ISD::FMA:
  3508. case ISD::FMAD: {
  3509. if (SNaN)
  3510. return true;
  3511. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
  3512. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1) &&
  3513. isKnownNeverNaN(Op.getOperand(2), SNaN, Depth + 1);
  3514. }
  3515. case ISD::FSQRT: // Need is known positive
  3516. case ISD::FLOG:
  3517. case ISD::FLOG2:
  3518. case ISD::FLOG10:
  3519. case ISD::FPOWI:
  3520. case ISD::FPOW: {
  3521. if (SNaN)
  3522. return true;
  3523. // TODO: Refine on operand
  3524. return false;
  3525. }
  3526. case ISD::FMINNUM:
  3527. case ISD::FMAXNUM: {
  3528. // Only one needs to be known not-nan, since it will be returned if the
  3529. // other ends up being one.
  3530. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) ||
  3531. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  3532. }
  3533. case ISD::FMINNUM_IEEE:
  3534. case ISD::FMAXNUM_IEEE: {
  3535. if (SNaN)
  3536. return true;
  3537. // This can return a NaN if either operand is an sNaN, or if both operands
  3538. // are NaN.
  3539. return (isKnownNeverNaN(Op.getOperand(0), false, Depth + 1) &&
  3540. isKnownNeverSNaN(Op.getOperand(1), Depth + 1)) ||
  3541. (isKnownNeverNaN(Op.getOperand(1), false, Depth + 1) &&
  3542. isKnownNeverSNaN(Op.getOperand(0), Depth + 1));
  3543. }
  3544. case ISD::FMINIMUM:
  3545. case ISD::FMAXIMUM: {
  3546. // TODO: Does this quiet or return the origina NaN as-is?
  3547. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1) &&
  3548. isKnownNeverNaN(Op.getOperand(1), SNaN, Depth + 1);
  3549. }
  3550. case ISD::EXTRACT_VECTOR_ELT: {
  3551. return isKnownNeverNaN(Op.getOperand(0), SNaN, Depth + 1);
  3552. }
  3553. default:
  3554. if (Opcode >= ISD::BUILTIN_OP_END ||
  3555. Opcode == ISD::INTRINSIC_WO_CHAIN ||
  3556. Opcode == ISD::INTRINSIC_W_CHAIN ||
  3557. Opcode == ISD::INTRINSIC_VOID) {
  3558. return TLI->isKnownNeverNaNForTargetNode(Op, *this, SNaN, Depth);
  3559. }
  3560. return false;
  3561. }
  3562. }
  3563. bool SelectionDAG::isKnownNeverZeroFloat(SDValue Op) const {
  3564. assert(Op.getValueType().isFloatingPoint() &&
  3565. "Floating point type expected");
  3566. // If the value is a constant, we can obviously see if it is a zero or not.
  3567. // TODO: Add BuildVector support.
  3568. if (const ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op))
  3569. return !C->isZero();
  3570. return false;
  3571. }
  3572. bool SelectionDAG::isKnownNeverZero(SDValue Op) const {
  3573. assert(!Op.getValueType().isFloatingPoint() &&
  3574. "Floating point types unsupported - use isKnownNeverZeroFloat");
  3575. // If the value is a constant, we can obviously see if it is a zero or not.
  3576. if (ISD::matchUnaryPredicate(
  3577. Op, [](ConstantSDNode *C) { return !C->isNullValue(); }))
  3578. return true;
  3579. // TODO: Recognize more cases here.
  3580. switch (Op.getOpcode()) {
  3581. default: break;
  3582. case ISD::OR:
  3583. if (isKnownNeverZero(Op.getOperand(1)) ||
  3584. isKnownNeverZero(Op.getOperand(0)))
  3585. return true;
  3586. break;
  3587. }
  3588. return false;
  3589. }
  3590. bool SelectionDAG::isEqualTo(SDValue A, SDValue B) const {
  3591. // Check the obvious case.
  3592. if (A == B) return true;
  3593. // For for negative and positive zero.
  3594. if (const ConstantFPSDNode *CA = dyn_cast<ConstantFPSDNode>(A))
  3595. if (const ConstantFPSDNode *CB = dyn_cast<ConstantFPSDNode>(B))
  3596. if (CA->isZero() && CB->isZero()) return true;
  3597. // Otherwise they may not be equal.
  3598. return false;
  3599. }
  3600. // FIXME: unify with llvm::haveNoCommonBitsSet.
  3601. // FIXME: could also handle masked merge pattern (X & ~M) op (Y & M)
  3602. bool SelectionDAG::haveNoCommonBitsSet(SDValue A, SDValue B) const {
  3603. assert(A.getValueType() == B.getValueType() &&
  3604. "Values must have the same type");
  3605. return (computeKnownBits(A).Zero | computeKnownBits(B).Zero).isAllOnesValue();
  3606. }
  3607. static SDValue FoldBUILD_VECTOR(const SDLoc &DL, EVT VT,
  3608. ArrayRef<SDValue> Ops,
  3609. SelectionDAG &DAG) {
  3610. int NumOps = Ops.size();
  3611. assert(NumOps != 0 && "Can't build an empty vector!");
  3612. assert(VT.getVectorNumElements() == (unsigned)NumOps &&
  3613. "Incorrect element count in BUILD_VECTOR!");
  3614. // BUILD_VECTOR of UNDEFs is UNDEF.
  3615. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  3616. return DAG.getUNDEF(VT);
  3617. // BUILD_VECTOR of seq extract/insert from the same vector + type is Identity.
  3618. SDValue IdentitySrc;
  3619. bool IsIdentity = true;
  3620. for (int i = 0; i != NumOps; ++i) {
  3621. if (Ops[i].getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  3622. Ops[i].getOperand(0).getValueType() != VT ||
  3623. (IdentitySrc && Ops[i].getOperand(0) != IdentitySrc) ||
  3624. !isa<ConstantSDNode>(Ops[i].getOperand(1)) ||
  3625. cast<ConstantSDNode>(Ops[i].getOperand(1))->getAPIntValue() != i) {
  3626. IsIdentity = false;
  3627. break;
  3628. }
  3629. IdentitySrc = Ops[i].getOperand(0);
  3630. }
  3631. if (IsIdentity)
  3632. return IdentitySrc;
  3633. return SDValue();
  3634. }
  3635. static SDValue FoldCONCAT_VECTORS(const SDLoc &DL, EVT VT,
  3636. ArrayRef<SDValue> Ops,
  3637. SelectionDAG &DAG) {
  3638. assert(!Ops.empty() && "Can't concatenate an empty list of vectors!");
  3639. assert(llvm::all_of(Ops,
  3640. [Ops](SDValue Op) {
  3641. return Ops[0].getValueType() == Op.getValueType();
  3642. }) &&
  3643. "Concatenation of vectors with inconsistent value types!");
  3644. assert((Ops.size() * Ops[0].getValueType().getVectorNumElements()) ==
  3645. VT.getVectorNumElements() &&
  3646. "Incorrect element count in vector concatenation!");
  3647. if (Ops.size() == 1)
  3648. return Ops[0];
  3649. // Concat of UNDEFs is UNDEF.
  3650. if (llvm::all_of(Ops, [](SDValue Op) { return Op.isUndef(); }))
  3651. return DAG.getUNDEF(VT);
  3652. // A CONCAT_VECTOR with all UNDEF/BUILD_VECTOR operands can be
  3653. // simplified to one big BUILD_VECTOR.
  3654. // FIXME: Add support for SCALAR_TO_VECTOR as well.
  3655. EVT SVT = VT.getScalarType();
  3656. SmallVector<SDValue, 16> Elts;
  3657. for (SDValue Op : Ops) {
  3658. EVT OpVT = Op.getValueType();
  3659. if (Op.isUndef())
  3660. Elts.append(OpVT.getVectorNumElements(), DAG.getUNDEF(SVT));
  3661. else if (Op.getOpcode() == ISD::BUILD_VECTOR)
  3662. Elts.append(Op->op_begin(), Op->op_end());
  3663. else
  3664. return SDValue();
  3665. }
  3666. // BUILD_VECTOR requires all inputs to be of the same type, find the
  3667. // maximum type and extend them all.
  3668. for (SDValue Op : Elts)
  3669. SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
  3670. if (SVT.bitsGT(VT.getScalarType()))
  3671. for (SDValue &Op : Elts)
  3672. Op = DAG.getTargetLoweringInfo().isZExtFree(Op.getValueType(), SVT)
  3673. ? DAG.getZExtOrTrunc(Op, DL, SVT)
  3674. : DAG.getSExtOrTrunc(Op, DL, SVT);
  3675. SDValue V = DAG.getBuildVector(VT, DL, Elts);
  3676. NewSDValueDbgMsg(V, "New node fold concat vectors: ", &DAG);
  3677. return V;
  3678. }
  3679. /// Gets or creates the specified node.
  3680. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT) {
  3681. FoldingSetNodeID ID;
  3682. AddNodeIDNode(ID, Opcode, getVTList(VT), None);
  3683. void *IP = nullptr;
  3684. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  3685. return SDValue(E, 0);
  3686. auto *N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(),
  3687. getVTList(VT));
  3688. CSEMap.InsertNode(N, IP);
  3689. InsertNode(N);
  3690. SDValue V = SDValue(N, 0);
  3691. NewSDValueDbgMsg(V, "Creating new node: ", this);
  3692. return V;
  3693. }
  3694. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  3695. SDValue Operand, const SDNodeFlags Flags) {
  3696. // Constant fold unary operations with an integer constant operand. Even
  3697. // opaque constant will be folded, because the folding of unary operations
  3698. // doesn't create new constants with different values. Nevertheless, the
  3699. // opaque flag is preserved during folding to prevent future folding with
  3700. // other constants.
  3701. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Operand)) {
  3702. const APInt &Val = C->getAPIntValue();
  3703. switch (Opcode) {
  3704. default: break;
  3705. case ISD::SIGN_EXTEND:
  3706. return getConstant(Val.sextOrTrunc(VT.getSizeInBits()), DL, VT,
  3707. C->isTargetOpcode(), C->isOpaque());
  3708. case ISD::TRUNCATE:
  3709. if (C->isOpaque())
  3710. break;
  3711. LLVM_FALLTHROUGH;
  3712. case ISD::ANY_EXTEND:
  3713. case ISD::ZERO_EXTEND:
  3714. return getConstant(Val.zextOrTrunc(VT.getSizeInBits()), DL, VT,
  3715. C->isTargetOpcode(), C->isOpaque());
  3716. case ISD::UINT_TO_FP:
  3717. case ISD::SINT_TO_FP: {
  3718. APFloat apf(EVTToAPFloatSemantics(VT),
  3719. APInt::getNullValue(VT.getSizeInBits()));
  3720. (void)apf.convertFromAPInt(Val,
  3721. Opcode==ISD::SINT_TO_FP,
  3722. APFloat::rmNearestTiesToEven);
  3723. return getConstantFP(apf, DL, VT);
  3724. }
  3725. case ISD::BITCAST:
  3726. if (VT == MVT::f16 && C->getValueType(0) == MVT::i16)
  3727. return getConstantFP(APFloat(APFloat::IEEEhalf(), Val), DL, VT);
  3728. if (VT == MVT::f32 && C->getValueType(0) == MVT::i32)
  3729. return getConstantFP(APFloat(APFloat::IEEEsingle(), Val), DL, VT);
  3730. if (VT == MVT::f64 && C->getValueType(0) == MVT::i64)
  3731. return getConstantFP(APFloat(APFloat::IEEEdouble(), Val), DL, VT);
  3732. if (VT == MVT::f128 && C->getValueType(0) == MVT::i128)
  3733. return getConstantFP(APFloat(APFloat::IEEEquad(), Val), DL, VT);
  3734. break;
  3735. case ISD::ABS:
  3736. return getConstant(Val.abs(), DL, VT, C->isTargetOpcode(),
  3737. C->isOpaque());
  3738. case ISD::BITREVERSE:
  3739. return getConstant(Val.reverseBits(), DL, VT, C->isTargetOpcode(),
  3740. C->isOpaque());
  3741. case ISD::BSWAP:
  3742. return getConstant(Val.byteSwap(), DL, VT, C->isTargetOpcode(),
  3743. C->isOpaque());
  3744. case ISD::CTPOP:
  3745. return getConstant(Val.countPopulation(), DL, VT, C->isTargetOpcode(),
  3746. C->isOpaque());
  3747. case ISD::CTLZ:
  3748. case ISD::CTLZ_ZERO_UNDEF:
  3749. return getConstant(Val.countLeadingZeros(), DL, VT, C->isTargetOpcode(),
  3750. C->isOpaque());
  3751. case ISD::CTTZ:
  3752. case ISD::CTTZ_ZERO_UNDEF:
  3753. return getConstant(Val.countTrailingZeros(), DL, VT, C->isTargetOpcode(),
  3754. C->isOpaque());
  3755. case ISD::FP16_TO_FP: {
  3756. bool Ignored;
  3757. APFloat FPV(APFloat::IEEEhalf(),
  3758. (Val.getBitWidth() == 16) ? Val : Val.trunc(16));
  3759. // This can return overflow, underflow, or inexact; we don't care.
  3760. // FIXME need to be more flexible about rounding mode.
  3761. (void)FPV.convert(EVTToAPFloatSemantics(VT),
  3762. APFloat::rmNearestTiesToEven, &Ignored);
  3763. return getConstantFP(FPV, DL, VT);
  3764. }
  3765. }
  3766. }
  3767. // Constant fold unary operations with a floating point constant operand.
  3768. if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Operand)) {
  3769. APFloat V = C->getValueAPF(); // make copy
  3770. switch (Opcode) {
  3771. case ISD::FNEG:
  3772. V.changeSign();
  3773. return getConstantFP(V, DL, VT);
  3774. case ISD::FABS:
  3775. V.clearSign();
  3776. return getConstantFP(V, DL, VT);
  3777. case ISD::FCEIL: {
  3778. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardPositive);
  3779. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  3780. return getConstantFP(V, DL, VT);
  3781. break;
  3782. }
  3783. case ISD::FTRUNC: {
  3784. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardZero);
  3785. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  3786. return getConstantFP(V, DL, VT);
  3787. break;
  3788. }
  3789. case ISD::FFLOOR: {
  3790. APFloat::opStatus fs = V.roundToIntegral(APFloat::rmTowardNegative);
  3791. if (fs == APFloat::opOK || fs == APFloat::opInexact)
  3792. return getConstantFP(V, DL, VT);
  3793. break;
  3794. }
  3795. case ISD::FP_EXTEND: {
  3796. bool ignored;
  3797. // This can return overflow, underflow, or inexact; we don't care.
  3798. // FIXME need to be more flexible about rounding mode.
  3799. (void)V.convert(EVTToAPFloatSemantics(VT),
  3800. APFloat::rmNearestTiesToEven, &ignored);
  3801. return getConstantFP(V, DL, VT);
  3802. }
  3803. case ISD::FP_TO_SINT:
  3804. case ISD::FP_TO_UINT: {
  3805. bool ignored;
  3806. APSInt IntVal(VT.getSizeInBits(), Opcode == ISD::FP_TO_UINT);
  3807. // FIXME need to be more flexible about rounding mode.
  3808. APFloat::opStatus s =
  3809. V.convertToInteger(IntVal, APFloat::rmTowardZero, &ignored);
  3810. if (s == APFloat::opInvalidOp) // inexact is OK, in fact usual
  3811. break;
  3812. return getConstant(IntVal, DL, VT);
  3813. }
  3814. case ISD::BITCAST:
  3815. if (VT == MVT::i16 && C->getValueType(0) == MVT::f16)
  3816. return getConstant((uint16_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  3817. else if (VT == MVT::i32 && C->getValueType(0) == MVT::f32)
  3818. return getConstant((uint32_t)V.bitcastToAPInt().getZExtValue(), DL, VT);
  3819. else if (VT == MVT::i64 && C->getValueType(0) == MVT::f64)
  3820. return getConstant(V.bitcastToAPInt().getZExtValue(), DL, VT);
  3821. break;
  3822. case ISD::FP_TO_FP16: {
  3823. bool Ignored;
  3824. // This can return overflow, underflow, or inexact; we don't care.
  3825. // FIXME need to be more flexible about rounding mode.
  3826. (void)V.convert(APFloat::IEEEhalf(),
  3827. APFloat::rmNearestTiesToEven, &Ignored);
  3828. return getConstant(V.bitcastToAPInt(), DL, VT);
  3829. }
  3830. }
  3831. }
  3832. // Constant fold unary operations with a vector integer or float operand.
  3833. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Operand)) {
  3834. if (BV->isConstant()) {
  3835. switch (Opcode) {
  3836. default:
  3837. // FIXME: Entirely reasonable to perform folding of other unary
  3838. // operations here as the need arises.
  3839. break;
  3840. case ISD::FNEG:
  3841. case ISD::FABS:
  3842. case ISD::FCEIL:
  3843. case ISD::FTRUNC:
  3844. case ISD::FFLOOR:
  3845. case ISD::FP_EXTEND:
  3846. case ISD::FP_TO_SINT:
  3847. case ISD::FP_TO_UINT:
  3848. case ISD::TRUNCATE:
  3849. case ISD::ANY_EXTEND:
  3850. case ISD::ZERO_EXTEND:
  3851. case ISD::SIGN_EXTEND:
  3852. case ISD::UINT_TO_FP:
  3853. case ISD::SINT_TO_FP:
  3854. case ISD::ABS:
  3855. case ISD::BITREVERSE:
  3856. case ISD::BSWAP:
  3857. case ISD::CTLZ:
  3858. case ISD::CTLZ_ZERO_UNDEF:
  3859. case ISD::CTTZ:
  3860. case ISD::CTTZ_ZERO_UNDEF:
  3861. case ISD::CTPOP: {
  3862. SDValue Ops = { Operand };
  3863. if (SDValue Fold = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops))
  3864. return Fold;
  3865. }
  3866. }
  3867. }
  3868. }
  3869. unsigned OpOpcode = Operand.getNode()->getOpcode();
  3870. switch (Opcode) {
  3871. case ISD::TokenFactor:
  3872. case ISD::MERGE_VALUES:
  3873. case ISD::CONCAT_VECTORS:
  3874. return Operand; // Factor, merge or concat of one node? No need.
  3875. case ISD::BUILD_VECTOR: {
  3876. // Attempt to simplify BUILD_VECTOR.
  3877. SDValue Ops[] = {Operand};
  3878. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  3879. return V;
  3880. break;
  3881. }
  3882. case ISD::FP_ROUND: llvm_unreachable("Invalid method to make FP_ROUND node");
  3883. case ISD::FP_EXTEND:
  3884. assert(VT.isFloatingPoint() &&
  3885. Operand.getValueType().isFloatingPoint() && "Invalid FP cast!");
  3886. if (Operand.getValueType() == VT) return Operand; // noop conversion.
  3887. assert((!VT.isVector() ||
  3888. VT.getVectorNumElements() ==
  3889. Operand.getValueType().getVectorNumElements()) &&
  3890. "Vector element count mismatch!");
  3891. assert(Operand.getValueType().bitsLT(VT) &&
  3892. "Invalid fpext node, dst < src!");
  3893. if (Operand.isUndef())
  3894. return getUNDEF(VT);
  3895. break;
  3896. case ISD::SIGN_EXTEND:
  3897. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3898. "Invalid SIGN_EXTEND!");
  3899. if (Operand.getValueType() == VT) return Operand; // noop extension
  3900. assert((!VT.isVector() ||
  3901. VT.getVectorNumElements() ==
  3902. Operand.getValueType().getVectorNumElements()) &&
  3903. "Vector element count mismatch!");
  3904. assert(Operand.getValueType().bitsLT(VT) &&
  3905. "Invalid sext node, dst < src!");
  3906. if (OpOpcode == ISD::SIGN_EXTEND || OpOpcode == ISD::ZERO_EXTEND)
  3907. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  3908. else if (OpOpcode == ISD::UNDEF)
  3909. // sext(undef) = 0, because the top bits will all be the same.
  3910. return getConstant(0, DL, VT);
  3911. break;
  3912. case ISD::ZERO_EXTEND:
  3913. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3914. "Invalid ZERO_EXTEND!");
  3915. if (Operand.getValueType() == VT) return Operand; // noop extension
  3916. assert((!VT.isVector() ||
  3917. VT.getVectorNumElements() ==
  3918. Operand.getValueType().getVectorNumElements()) &&
  3919. "Vector element count mismatch!");
  3920. assert(Operand.getValueType().bitsLT(VT) &&
  3921. "Invalid zext node, dst < src!");
  3922. if (OpOpcode == ISD::ZERO_EXTEND) // (zext (zext x)) -> (zext x)
  3923. return getNode(ISD::ZERO_EXTEND, DL, VT, Operand.getOperand(0));
  3924. else if (OpOpcode == ISD::UNDEF)
  3925. // zext(undef) = 0, because the top bits will be zero.
  3926. return getConstant(0, DL, VT);
  3927. break;
  3928. case ISD::ANY_EXTEND:
  3929. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3930. "Invalid ANY_EXTEND!");
  3931. if (Operand.getValueType() == VT) return Operand; // noop extension
  3932. assert((!VT.isVector() ||
  3933. VT.getVectorNumElements() ==
  3934. Operand.getValueType().getVectorNumElements()) &&
  3935. "Vector element count mismatch!");
  3936. assert(Operand.getValueType().bitsLT(VT) &&
  3937. "Invalid anyext node, dst < src!");
  3938. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  3939. OpOpcode == ISD::ANY_EXTEND)
  3940. // (ext (zext x)) -> (zext x) and (ext (sext x)) -> (sext x)
  3941. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  3942. else if (OpOpcode == ISD::UNDEF)
  3943. return getUNDEF(VT);
  3944. // (ext (trunc x)) -> x
  3945. if (OpOpcode == ISD::TRUNCATE) {
  3946. SDValue OpOp = Operand.getOperand(0);
  3947. if (OpOp.getValueType() == VT) {
  3948. transferDbgValues(Operand, OpOp);
  3949. return OpOp;
  3950. }
  3951. }
  3952. break;
  3953. case ISD::TRUNCATE:
  3954. assert(VT.isInteger() && Operand.getValueType().isInteger() &&
  3955. "Invalid TRUNCATE!");
  3956. if (Operand.getValueType() == VT) return Operand; // noop truncate
  3957. assert((!VT.isVector() ||
  3958. VT.getVectorNumElements() ==
  3959. Operand.getValueType().getVectorNumElements()) &&
  3960. "Vector element count mismatch!");
  3961. assert(Operand.getValueType().bitsGT(VT) &&
  3962. "Invalid truncate node, src < dst!");
  3963. if (OpOpcode == ISD::TRUNCATE)
  3964. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  3965. if (OpOpcode == ISD::ZERO_EXTEND || OpOpcode == ISD::SIGN_EXTEND ||
  3966. OpOpcode == ISD::ANY_EXTEND) {
  3967. // If the source is smaller than the dest, we still need an extend.
  3968. if (Operand.getOperand(0).getValueType().getScalarType()
  3969. .bitsLT(VT.getScalarType()))
  3970. return getNode(OpOpcode, DL, VT, Operand.getOperand(0));
  3971. if (Operand.getOperand(0).getValueType().bitsGT(VT))
  3972. return getNode(ISD::TRUNCATE, DL, VT, Operand.getOperand(0));
  3973. return Operand.getOperand(0);
  3974. }
  3975. if (OpOpcode == ISD::UNDEF)
  3976. return getUNDEF(VT);
  3977. break;
  3978. case ISD::ANY_EXTEND_VECTOR_INREG:
  3979. case ISD::ZERO_EXTEND_VECTOR_INREG:
  3980. case ISD::SIGN_EXTEND_VECTOR_INREG:
  3981. assert(VT.isVector() && "This DAG node is restricted to vector types.");
  3982. assert(Operand.getValueType().bitsLE(VT) &&
  3983. "The input must be the same size or smaller than the result.");
  3984. assert(VT.getVectorNumElements() <
  3985. Operand.getValueType().getVectorNumElements() &&
  3986. "The destination vector type must have fewer lanes than the input.");
  3987. break;
  3988. case ISD::ABS:
  3989. assert(VT.isInteger() && VT == Operand.getValueType() &&
  3990. "Invalid ABS!");
  3991. if (OpOpcode == ISD::UNDEF)
  3992. return getUNDEF(VT);
  3993. break;
  3994. case ISD::BSWAP:
  3995. assert(VT.isInteger() && VT == Operand.getValueType() &&
  3996. "Invalid BSWAP!");
  3997. assert((VT.getScalarSizeInBits() % 16 == 0) &&
  3998. "BSWAP types must be a multiple of 16 bits!");
  3999. if (OpOpcode == ISD::UNDEF)
  4000. return getUNDEF(VT);
  4001. break;
  4002. case ISD::BITREVERSE:
  4003. assert(VT.isInteger() && VT == Operand.getValueType() &&
  4004. "Invalid BITREVERSE!");
  4005. if (OpOpcode == ISD::UNDEF)
  4006. return getUNDEF(VT);
  4007. break;
  4008. case ISD::BITCAST:
  4009. // Basic sanity checking.
  4010. assert(VT.getSizeInBits() == Operand.getValueSizeInBits() &&
  4011. "Cannot BITCAST between types of different sizes!");
  4012. if (VT == Operand.getValueType()) return Operand; // noop conversion.
  4013. if (OpOpcode == ISD::BITCAST) // bitconv(bitconv(x)) -> bitconv(x)
  4014. return getNode(ISD::BITCAST, DL, VT, Operand.getOperand(0));
  4015. if (OpOpcode == ISD::UNDEF)
  4016. return getUNDEF(VT);
  4017. break;
  4018. case ISD::SCALAR_TO_VECTOR:
  4019. assert(VT.isVector() && !Operand.getValueType().isVector() &&
  4020. (VT.getVectorElementType() == Operand.getValueType() ||
  4021. (VT.getVectorElementType().isInteger() &&
  4022. Operand.getValueType().isInteger() &&
  4023. VT.getVectorElementType().bitsLE(Operand.getValueType()))) &&
  4024. "Illegal SCALAR_TO_VECTOR node!");
  4025. if (OpOpcode == ISD::UNDEF)
  4026. return getUNDEF(VT);
  4027. // scalar_to_vector(extract_vector_elt V, 0) -> V, top bits are undefined.
  4028. if (OpOpcode == ISD::EXTRACT_VECTOR_ELT &&
  4029. isa<ConstantSDNode>(Operand.getOperand(1)) &&
  4030. Operand.getConstantOperandVal(1) == 0 &&
  4031. Operand.getOperand(0).getValueType() == VT)
  4032. return Operand.getOperand(0);
  4033. break;
  4034. case ISD::FNEG:
  4035. // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
  4036. if ((getTarget().Options.UnsafeFPMath || Flags.hasNoSignedZeros()) &&
  4037. OpOpcode == ISD::FSUB)
  4038. return getNode(ISD::FSUB, DL, VT, Operand.getOperand(1),
  4039. Operand.getOperand(0), Flags);
  4040. if (OpOpcode == ISD::FNEG) // --X -> X
  4041. return Operand.getOperand(0);
  4042. break;
  4043. case ISD::FABS:
  4044. if (OpOpcode == ISD::FNEG) // abs(-X) -> abs(X)
  4045. return getNode(ISD::FABS, DL, VT, Operand.getOperand(0));
  4046. break;
  4047. }
  4048. SDNode *N;
  4049. SDVTList VTs = getVTList(VT);
  4050. SDValue Ops[] = {Operand};
  4051. if (VT != MVT::Glue) { // Don't CSE flag producing nodes
  4052. FoldingSetNodeID ID;
  4053. AddNodeIDNode(ID, Opcode, VTs, Ops);
  4054. void *IP = nullptr;
  4055. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  4056. E->intersectFlagsWith(Flags);
  4057. return SDValue(E, 0);
  4058. }
  4059. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4060. N->setFlags(Flags);
  4061. createOperands(N, Ops);
  4062. CSEMap.InsertNode(N, IP);
  4063. } else {
  4064. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4065. createOperands(N, Ops);
  4066. }
  4067. InsertNode(N);
  4068. SDValue V = SDValue(N, 0);
  4069. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4070. return V;
  4071. }
  4072. static std::pair<APInt, bool> FoldValue(unsigned Opcode, const APInt &C1,
  4073. const APInt &C2) {
  4074. switch (Opcode) {
  4075. case ISD::ADD: return std::make_pair(C1 + C2, true);
  4076. case ISD::SUB: return std::make_pair(C1 - C2, true);
  4077. case ISD::MUL: return std::make_pair(C1 * C2, true);
  4078. case ISD::AND: return std::make_pair(C1 & C2, true);
  4079. case ISD::OR: return std::make_pair(C1 | C2, true);
  4080. case ISD::XOR: return std::make_pair(C1 ^ C2, true);
  4081. case ISD::SHL: return std::make_pair(C1 << C2, true);
  4082. case ISD::SRL: return std::make_pair(C1.lshr(C2), true);
  4083. case ISD::SRA: return std::make_pair(C1.ashr(C2), true);
  4084. case ISD::ROTL: return std::make_pair(C1.rotl(C2), true);
  4085. case ISD::ROTR: return std::make_pair(C1.rotr(C2), true);
  4086. case ISD::SMIN: return std::make_pair(C1.sle(C2) ? C1 : C2, true);
  4087. case ISD::SMAX: return std::make_pair(C1.sge(C2) ? C1 : C2, true);
  4088. case ISD::UMIN: return std::make_pair(C1.ule(C2) ? C1 : C2, true);
  4089. case ISD::UMAX: return std::make_pair(C1.uge(C2) ? C1 : C2, true);
  4090. case ISD::SADDSAT: return std::make_pair(C1.sadd_sat(C2), true);
  4091. case ISD::UADDSAT: return std::make_pair(C1.uadd_sat(C2), true);
  4092. case ISD::SSUBSAT: return std::make_pair(C1.ssub_sat(C2), true);
  4093. case ISD::USUBSAT: return std::make_pair(C1.usub_sat(C2), true);
  4094. case ISD::UDIV:
  4095. if (!C2.getBoolValue())
  4096. break;
  4097. return std::make_pair(C1.udiv(C2), true);
  4098. case ISD::UREM:
  4099. if (!C2.getBoolValue())
  4100. break;
  4101. return std::make_pair(C1.urem(C2), true);
  4102. case ISD::SDIV:
  4103. if (!C2.getBoolValue())
  4104. break;
  4105. return std::make_pair(C1.sdiv(C2), true);
  4106. case ISD::SREM:
  4107. if (!C2.getBoolValue())
  4108. break;
  4109. return std::make_pair(C1.srem(C2), true);
  4110. }
  4111. return std::make_pair(APInt(1, 0), false);
  4112. }
  4113. SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
  4114. EVT VT, const ConstantSDNode *C1,
  4115. const ConstantSDNode *C2) {
  4116. if (C1->isOpaque() || C2->isOpaque())
  4117. return SDValue();
  4118. std::pair<APInt, bool> Folded = FoldValue(Opcode, C1->getAPIntValue(),
  4119. C2->getAPIntValue());
  4120. if (!Folded.second)
  4121. return SDValue();
  4122. return getConstant(Folded.first, DL, VT);
  4123. }
  4124. SDValue SelectionDAG::FoldSymbolOffset(unsigned Opcode, EVT VT,
  4125. const GlobalAddressSDNode *GA,
  4126. const SDNode *N2) {
  4127. if (GA->getOpcode() != ISD::GlobalAddress)
  4128. return SDValue();
  4129. if (!TLI->isOffsetFoldingLegal(GA))
  4130. return SDValue();
  4131. auto *C2 = dyn_cast<ConstantSDNode>(N2);
  4132. if (!C2)
  4133. return SDValue();
  4134. int64_t Offset = C2->getSExtValue();
  4135. switch (Opcode) {
  4136. case ISD::ADD: break;
  4137. case ISD::SUB: Offset = -uint64_t(Offset); break;
  4138. default: return SDValue();
  4139. }
  4140. return getGlobalAddress(GA->getGlobal(), SDLoc(C2), VT,
  4141. GA->getOffset() + uint64_t(Offset));
  4142. }
  4143. bool SelectionDAG::isUndef(unsigned Opcode, ArrayRef<SDValue> Ops) {
  4144. switch (Opcode) {
  4145. case ISD::SDIV:
  4146. case ISD::UDIV:
  4147. case ISD::SREM:
  4148. case ISD::UREM: {
  4149. // If a divisor is zero/undef or any element of a divisor vector is
  4150. // zero/undef, the whole op is undef.
  4151. assert(Ops.size() == 2 && "Div/rem should have 2 operands");
  4152. SDValue Divisor = Ops[1];
  4153. if (Divisor.isUndef() || isNullConstant(Divisor))
  4154. return true;
  4155. return ISD::isBuildVectorOfConstantSDNodes(Divisor.getNode()) &&
  4156. llvm::any_of(Divisor->op_values(),
  4157. [](SDValue V) { return V.isUndef() ||
  4158. isNullConstant(V); });
  4159. // TODO: Handle signed overflow.
  4160. }
  4161. // TODO: Handle oversized shifts.
  4162. default:
  4163. return false;
  4164. }
  4165. }
  4166. SDValue SelectionDAG::FoldConstantArithmetic(unsigned Opcode, const SDLoc &DL,
  4167. EVT VT, SDNode *N1, SDNode *N2) {
  4168. // If the opcode is a target-specific ISD node, there's nothing we can
  4169. // do here and the operand rules may not line up with the below, so
  4170. // bail early.
  4171. if (Opcode >= ISD::BUILTIN_OP_END)
  4172. return SDValue();
  4173. if (isUndef(Opcode, {SDValue(N1, 0), SDValue(N2, 0)}))
  4174. return getUNDEF(VT);
  4175. // Handle the case of two scalars.
  4176. if (auto *C1 = dyn_cast<ConstantSDNode>(N1)) {
  4177. if (auto *C2 = dyn_cast<ConstantSDNode>(N2)) {
  4178. SDValue Folded = FoldConstantArithmetic(Opcode, DL, VT, C1, C2);
  4179. assert((!Folded || !VT.isVector()) &&
  4180. "Can't fold vectors ops with scalar operands");
  4181. return Folded;
  4182. }
  4183. }
  4184. // fold (add Sym, c) -> Sym+c
  4185. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N1))
  4186. return FoldSymbolOffset(Opcode, VT, GA, N2);
  4187. if (TLI->isCommutativeBinOp(Opcode))
  4188. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N2))
  4189. return FoldSymbolOffset(Opcode, VT, GA, N1);
  4190. // For vectors, extract each constant element and fold them individually.
  4191. // Either input may be an undef value.
  4192. auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
  4193. if (!BV1 && !N1->isUndef())
  4194. return SDValue();
  4195. auto *BV2 = dyn_cast<BuildVectorSDNode>(N2);
  4196. if (!BV2 && !N2->isUndef())
  4197. return SDValue();
  4198. // If both operands are undef, that's handled the same way as scalars.
  4199. if (!BV1 && !BV2)
  4200. return SDValue();
  4201. assert((!BV1 || !BV2 || BV1->getNumOperands() == BV2->getNumOperands()) &&
  4202. "Vector binop with different number of elements in operands?");
  4203. EVT SVT = VT.getScalarType();
  4204. EVT LegalSVT = SVT;
  4205. if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
  4206. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  4207. if (LegalSVT.bitsLT(SVT))
  4208. return SDValue();
  4209. }
  4210. SmallVector<SDValue, 4> Outputs;
  4211. unsigned NumOps = BV1 ? BV1->getNumOperands() : BV2->getNumOperands();
  4212. for (unsigned I = 0; I != NumOps; ++I) {
  4213. SDValue V1 = BV1 ? BV1->getOperand(I) : getUNDEF(SVT);
  4214. SDValue V2 = BV2 ? BV2->getOperand(I) : getUNDEF(SVT);
  4215. if (SVT.isInteger()) {
  4216. if (V1->getValueType(0).bitsGT(SVT))
  4217. V1 = getNode(ISD::TRUNCATE, DL, SVT, V1);
  4218. if (V2->getValueType(0).bitsGT(SVT))
  4219. V2 = getNode(ISD::TRUNCATE, DL, SVT, V2);
  4220. }
  4221. if (V1->getValueType(0) != SVT || V2->getValueType(0) != SVT)
  4222. return SDValue();
  4223. // Fold one vector element.
  4224. SDValue ScalarResult = getNode(Opcode, DL, SVT, V1, V2);
  4225. if (LegalSVT != SVT)
  4226. ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
  4227. // Scalar folding only succeeded if the result is a constant or UNDEF.
  4228. if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
  4229. ScalarResult.getOpcode() != ISD::ConstantFP)
  4230. return SDValue();
  4231. Outputs.push_back(ScalarResult);
  4232. }
  4233. assert(VT.getVectorNumElements() == Outputs.size() &&
  4234. "Vector size mismatch!");
  4235. // We may have a vector type but a scalar result. Create a splat.
  4236. Outputs.resize(VT.getVectorNumElements(), Outputs.back());
  4237. // Build a big vector out of the scalar elements we generated.
  4238. return getBuildVector(VT, SDLoc(), Outputs);
  4239. }
  4240. // TODO: Merge with FoldConstantArithmetic
  4241. SDValue SelectionDAG::FoldConstantVectorArithmetic(unsigned Opcode,
  4242. const SDLoc &DL, EVT VT,
  4243. ArrayRef<SDValue> Ops,
  4244. const SDNodeFlags Flags) {
  4245. // If the opcode is a target-specific ISD node, there's nothing we can
  4246. // do here and the operand rules may not line up with the below, so
  4247. // bail early.
  4248. if (Opcode >= ISD::BUILTIN_OP_END)
  4249. return SDValue();
  4250. if (isUndef(Opcode, Ops))
  4251. return getUNDEF(VT);
  4252. // We can only fold vectors - maybe merge with FoldConstantArithmetic someday?
  4253. if (!VT.isVector())
  4254. return SDValue();
  4255. unsigned NumElts = VT.getVectorNumElements();
  4256. auto IsScalarOrSameVectorSize = [&](const SDValue &Op) {
  4257. return !Op.getValueType().isVector() ||
  4258. Op.getValueType().getVectorNumElements() == NumElts;
  4259. };
  4260. auto IsConstantBuildVectorOrUndef = [&](const SDValue &Op) {
  4261. BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(Op);
  4262. return (Op.isUndef()) || (Op.getOpcode() == ISD::CONDCODE) ||
  4263. (BV && BV->isConstant());
  4264. };
  4265. // All operands must be vector types with the same number of elements as
  4266. // the result type and must be either UNDEF or a build vector of constant
  4267. // or UNDEF scalars.
  4268. if (!llvm::all_of(Ops, IsConstantBuildVectorOrUndef) ||
  4269. !llvm::all_of(Ops, IsScalarOrSameVectorSize))
  4270. return SDValue();
  4271. // If we are comparing vectors, then the result needs to be a i1 boolean
  4272. // that is then sign-extended back to the legal result type.
  4273. EVT SVT = (Opcode == ISD::SETCC ? MVT::i1 : VT.getScalarType());
  4274. // Find legal integer scalar type for constant promotion and
  4275. // ensure that its scalar size is at least as large as source.
  4276. EVT LegalSVT = VT.getScalarType();
  4277. if (NewNodesMustHaveLegalTypes && LegalSVT.isInteger()) {
  4278. LegalSVT = TLI->getTypeToTransformTo(*getContext(), LegalSVT);
  4279. if (LegalSVT.bitsLT(VT.getScalarType()))
  4280. return SDValue();
  4281. }
  4282. // Constant fold each scalar lane separately.
  4283. SmallVector<SDValue, 4> ScalarResults;
  4284. for (unsigned i = 0; i != NumElts; i++) {
  4285. SmallVector<SDValue, 4> ScalarOps;
  4286. for (SDValue Op : Ops) {
  4287. EVT InSVT = Op.getValueType().getScalarType();
  4288. BuildVectorSDNode *InBV = dyn_cast<BuildVectorSDNode>(Op);
  4289. if (!InBV) {
  4290. // We've checked that this is UNDEF or a constant of some kind.
  4291. if (Op.isUndef())
  4292. ScalarOps.push_back(getUNDEF(InSVT));
  4293. else
  4294. ScalarOps.push_back(Op);
  4295. continue;
  4296. }
  4297. SDValue ScalarOp = InBV->getOperand(i);
  4298. EVT ScalarVT = ScalarOp.getValueType();
  4299. // Build vector (integer) scalar operands may need implicit
  4300. // truncation - do this before constant folding.
  4301. if (ScalarVT.isInteger() && ScalarVT.bitsGT(InSVT))
  4302. ScalarOp = getNode(ISD::TRUNCATE, DL, InSVT, ScalarOp);
  4303. ScalarOps.push_back(ScalarOp);
  4304. }
  4305. // Constant fold the scalar operands.
  4306. SDValue ScalarResult = getNode(Opcode, DL, SVT, ScalarOps, Flags);
  4307. // Legalize the (integer) scalar constant if necessary.
  4308. if (LegalSVT != SVT)
  4309. ScalarResult = getNode(ISD::SIGN_EXTEND, DL, LegalSVT, ScalarResult);
  4310. // Scalar folding only succeeded if the result is a constant or UNDEF.
  4311. if (!ScalarResult.isUndef() && ScalarResult.getOpcode() != ISD::Constant &&
  4312. ScalarResult.getOpcode() != ISD::ConstantFP)
  4313. return SDValue();
  4314. ScalarResults.push_back(ScalarResult);
  4315. }
  4316. SDValue V = getBuildVector(VT, DL, ScalarResults);
  4317. NewSDValueDbgMsg(V, "New node fold constant vector: ", this);
  4318. return V;
  4319. }
  4320. SDValue SelectionDAG::foldConstantFPMath(unsigned Opcode, const SDLoc &DL,
  4321. EVT VT, SDValue N1, SDValue N2) {
  4322. // TODO: We don't do any constant folding for strict FP opcodes here, but we
  4323. // should. That will require dealing with a potentially non-default
  4324. // rounding mode, checking the "opStatus" return value from the APFloat
  4325. // math calculations, and possibly other variations.
  4326. auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1.getNode());
  4327. auto *N2CFP = dyn_cast<ConstantFPSDNode>(N2.getNode());
  4328. if (N1CFP && N2CFP) {
  4329. APFloat C1 = N1CFP->getValueAPF(), C2 = N2CFP->getValueAPF();
  4330. switch (Opcode) {
  4331. case ISD::FADD:
  4332. C1.add(C2, APFloat::rmNearestTiesToEven);
  4333. return getConstantFP(C1, DL, VT);
  4334. case ISD::FSUB:
  4335. C1.subtract(C2, APFloat::rmNearestTiesToEven);
  4336. return getConstantFP(C1, DL, VT);
  4337. case ISD::FMUL:
  4338. C1.multiply(C2, APFloat::rmNearestTiesToEven);
  4339. return getConstantFP(C1, DL, VT);
  4340. case ISD::FDIV:
  4341. C1.divide(C2, APFloat::rmNearestTiesToEven);
  4342. return getConstantFP(C1, DL, VT);
  4343. case ISD::FREM:
  4344. C1.mod(C2);
  4345. return getConstantFP(C1, DL, VT);
  4346. case ISD::FCOPYSIGN:
  4347. C1.copySign(C2);
  4348. return getConstantFP(C1, DL, VT);
  4349. default: break;
  4350. }
  4351. }
  4352. if (N1CFP && Opcode == ISD::FP_ROUND) {
  4353. APFloat C1 = N1CFP->getValueAPF(); // make copy
  4354. bool Unused;
  4355. // This can return overflow, underflow, or inexact; we don't care.
  4356. // FIXME need to be more flexible about rounding mode.
  4357. (void) C1.convert(EVTToAPFloatSemantics(VT), APFloat::rmNearestTiesToEven,
  4358. &Unused);
  4359. return getConstantFP(C1, DL, VT);
  4360. }
  4361. switch (Opcode) {
  4362. case ISD::FADD:
  4363. case ISD::FSUB:
  4364. case ISD::FMUL:
  4365. case ISD::FDIV:
  4366. case ISD::FREM:
  4367. // If both operands are undef, the result is undef. If 1 operand is undef,
  4368. // the result is NaN. This should match the behavior of the IR optimizer.
  4369. if (N1.isUndef() && N2.isUndef())
  4370. return getUNDEF(VT);
  4371. if (N1.isUndef() || N2.isUndef())
  4372. return getConstantFP(APFloat::getNaN(EVTToAPFloatSemantics(VT)), DL, VT);
  4373. }
  4374. return SDValue();
  4375. }
  4376. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4377. SDValue N1, SDValue N2, const SDNodeFlags Flags) {
  4378. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  4379. ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
  4380. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  4381. ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  4382. // Canonicalize constant to RHS if commutative.
  4383. if (TLI->isCommutativeBinOp(Opcode)) {
  4384. if (N1C && !N2C) {
  4385. std::swap(N1C, N2C);
  4386. std::swap(N1, N2);
  4387. } else if (N1CFP && !N2CFP) {
  4388. std::swap(N1CFP, N2CFP);
  4389. std::swap(N1, N2);
  4390. }
  4391. }
  4392. switch (Opcode) {
  4393. default: break;
  4394. case ISD::TokenFactor:
  4395. assert(VT == MVT::Other && N1.getValueType() == MVT::Other &&
  4396. N2.getValueType() == MVT::Other && "Invalid token factor!");
  4397. // Fold trivial token factors.
  4398. if (N1.getOpcode() == ISD::EntryToken) return N2;
  4399. if (N2.getOpcode() == ISD::EntryToken) return N1;
  4400. if (N1 == N2) return N1;
  4401. break;
  4402. case ISD::BUILD_VECTOR: {
  4403. // Attempt to simplify BUILD_VECTOR.
  4404. SDValue Ops[] = {N1, N2};
  4405. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  4406. return V;
  4407. break;
  4408. }
  4409. case ISD::CONCAT_VECTORS: {
  4410. // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
  4411. SDValue Ops[] = {N1, N2};
  4412. if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
  4413. return V;
  4414. break;
  4415. }
  4416. case ISD::AND:
  4417. assert(VT.isInteger() && "This operator does not apply to FP types!");
  4418. assert(N1.getValueType() == N2.getValueType() &&
  4419. N1.getValueType() == VT && "Binary operator types must match!");
  4420. // (X & 0) -> 0. This commonly occurs when legalizing i64 values, so it's
  4421. // worth handling here.
  4422. if (N2C && N2C->isNullValue())
  4423. return N2;
  4424. if (N2C && N2C->isAllOnesValue()) // X & -1 -> X
  4425. return N1;
  4426. break;
  4427. case ISD::OR:
  4428. case ISD::XOR:
  4429. case ISD::ADD:
  4430. case ISD::SUB:
  4431. assert(VT.isInteger() && "This operator does not apply to FP types!");
  4432. assert(N1.getValueType() == N2.getValueType() &&
  4433. N1.getValueType() == VT && "Binary operator types must match!");
  4434. // (X ^|+- 0) -> X. This commonly occurs when legalizing i64 values, so
  4435. // it's worth handling here.
  4436. if (N2C && N2C->isNullValue())
  4437. return N1;
  4438. break;
  4439. case ISD::UDIV:
  4440. case ISD::UREM:
  4441. case ISD::MULHU:
  4442. case ISD::MULHS:
  4443. case ISD::MUL:
  4444. case ISD::SDIV:
  4445. case ISD::SREM:
  4446. case ISD::SMIN:
  4447. case ISD::SMAX:
  4448. case ISD::UMIN:
  4449. case ISD::UMAX:
  4450. case ISD::SADDSAT:
  4451. case ISD::SSUBSAT:
  4452. case ISD::UADDSAT:
  4453. case ISD::USUBSAT:
  4454. assert(VT.isInteger() && "This operator does not apply to FP types!");
  4455. assert(N1.getValueType() == N2.getValueType() &&
  4456. N1.getValueType() == VT && "Binary operator types must match!");
  4457. break;
  4458. case ISD::FADD:
  4459. case ISD::FSUB:
  4460. case ISD::FMUL:
  4461. case ISD::FDIV:
  4462. case ISD::FREM:
  4463. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  4464. assert(N1.getValueType() == N2.getValueType() &&
  4465. N1.getValueType() == VT && "Binary operator types must match!");
  4466. if (SDValue V = simplifyFPBinop(Opcode, N1, N2))
  4467. return V;
  4468. break;
  4469. case ISD::FCOPYSIGN: // N1 and result must match. N1/N2 need not match.
  4470. assert(N1.getValueType() == VT &&
  4471. N1.getValueType().isFloatingPoint() &&
  4472. N2.getValueType().isFloatingPoint() &&
  4473. "Invalid FCOPYSIGN!");
  4474. break;
  4475. case ISD::SHL:
  4476. case ISD::SRA:
  4477. case ISD::SRL:
  4478. if (SDValue V = simplifyShift(N1, N2))
  4479. return V;
  4480. LLVM_FALLTHROUGH;
  4481. case ISD::ROTL:
  4482. case ISD::ROTR:
  4483. assert(VT == N1.getValueType() &&
  4484. "Shift operators return type must be the same as their first arg");
  4485. assert(VT.isInteger() && N2.getValueType().isInteger() &&
  4486. "Shifts only work on integers");
  4487. assert((!VT.isVector() || VT == N2.getValueType()) &&
  4488. "Vector shift amounts must be in the same as their first arg");
  4489. // Verify that the shift amount VT is big enough to hold valid shift
  4490. // amounts. This catches things like trying to shift an i1024 value by an
  4491. // i8, which is easy to fall into in generic code that uses
  4492. // TLI.getShiftAmount().
  4493. assert(N2.getValueSizeInBits() >= Log2_32_Ceil(N1.getValueSizeInBits()) &&
  4494. "Invalid use of small shift amount with oversized value!");
  4495. // Always fold shifts of i1 values so the code generator doesn't need to
  4496. // handle them. Since we know the size of the shift has to be less than the
  4497. // size of the value, the shift/rotate count is guaranteed to be zero.
  4498. if (VT == MVT::i1)
  4499. return N1;
  4500. if (N2C && N2C->isNullValue())
  4501. return N1;
  4502. break;
  4503. case ISD::FP_ROUND_INREG: {
  4504. EVT EVT = cast<VTSDNode>(N2)->getVT();
  4505. assert(VT == N1.getValueType() && "Not an inreg round!");
  4506. assert(VT.isFloatingPoint() && EVT.isFloatingPoint() &&
  4507. "Cannot FP_ROUND_INREG integer types");
  4508. assert(EVT.isVector() == VT.isVector() &&
  4509. "FP_ROUND_INREG type should be vector iff the operand "
  4510. "type is vector!");
  4511. assert((!EVT.isVector() ||
  4512. EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
  4513. "Vector element counts must match in FP_ROUND_INREG");
  4514. assert(EVT.bitsLE(VT) && "Not rounding down!");
  4515. (void)EVT;
  4516. if (cast<VTSDNode>(N2)->getVT() == VT) return N1; // Not actually rounding.
  4517. break;
  4518. }
  4519. case ISD::FP_ROUND:
  4520. assert(VT.isFloatingPoint() &&
  4521. N1.getValueType().isFloatingPoint() &&
  4522. VT.bitsLE(N1.getValueType()) &&
  4523. N2C && (N2C->getZExtValue() == 0 || N2C->getZExtValue() == 1) &&
  4524. "Invalid FP_ROUND!");
  4525. if (N1.getValueType() == VT) return N1; // noop conversion.
  4526. break;
  4527. case ISD::AssertSext:
  4528. case ISD::AssertZext: {
  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() &&
  4534. "AssertSExt/AssertZExt type should be the vector element type "
  4535. "rather than the vector type!");
  4536. assert(EVT.bitsLE(VT.getScalarType()) && "Not extending!");
  4537. if (VT.getScalarType() == EVT) return N1; // noop assertion.
  4538. break;
  4539. }
  4540. case ISD::SIGN_EXTEND_INREG: {
  4541. EVT EVT = cast<VTSDNode>(N2)->getVT();
  4542. assert(VT == N1.getValueType() && "Not an inreg extend!");
  4543. assert(VT.isInteger() && EVT.isInteger() &&
  4544. "Cannot *_EXTEND_INREG FP types");
  4545. assert(EVT.isVector() == VT.isVector() &&
  4546. "SIGN_EXTEND_INREG type should be vector iff the operand "
  4547. "type is vector!");
  4548. assert((!EVT.isVector() ||
  4549. EVT.getVectorNumElements() == VT.getVectorNumElements()) &&
  4550. "Vector element counts must match in SIGN_EXTEND_INREG");
  4551. assert(EVT.bitsLE(VT) && "Not extending!");
  4552. if (EVT == VT) return N1; // Not actually extending
  4553. auto SignExtendInReg = [&](APInt Val, llvm::EVT ConstantVT) {
  4554. unsigned FromBits = EVT.getScalarSizeInBits();
  4555. Val <<= Val.getBitWidth() - FromBits;
  4556. Val.ashrInPlace(Val.getBitWidth() - FromBits);
  4557. return getConstant(Val, DL, ConstantVT);
  4558. };
  4559. if (N1C) {
  4560. const APInt &Val = N1C->getAPIntValue();
  4561. return SignExtendInReg(Val, VT);
  4562. }
  4563. if (ISD::isBuildVectorOfConstantSDNodes(N1.getNode())) {
  4564. SmallVector<SDValue, 8> Ops;
  4565. llvm::EVT OpVT = N1.getOperand(0).getValueType();
  4566. for (int i = 0, e = VT.getVectorNumElements(); i != e; ++i) {
  4567. SDValue Op = N1.getOperand(i);
  4568. if (Op.isUndef()) {
  4569. Ops.push_back(getUNDEF(OpVT));
  4570. continue;
  4571. }
  4572. ConstantSDNode *C = cast<ConstantSDNode>(Op);
  4573. APInt Val = C->getAPIntValue();
  4574. Ops.push_back(SignExtendInReg(Val, OpVT));
  4575. }
  4576. return getBuildVector(VT, DL, Ops);
  4577. }
  4578. break;
  4579. }
  4580. case ISD::EXTRACT_VECTOR_ELT:
  4581. assert(VT.getSizeInBits() >= N1.getValueType().getScalarSizeInBits() &&
  4582. "The result of EXTRACT_VECTOR_ELT must be at least as wide as the \
  4583. element type of the vector.");
  4584. // EXTRACT_VECTOR_ELT of an UNDEF is an UNDEF.
  4585. if (N1.isUndef())
  4586. return getUNDEF(VT);
  4587. // EXTRACT_VECTOR_ELT of out-of-bounds element is an UNDEF
  4588. if (N2C && N2C->getAPIntValue().uge(N1.getValueType().getVectorNumElements()))
  4589. return getUNDEF(VT);
  4590. // EXTRACT_VECTOR_ELT of CONCAT_VECTORS is often formed while lowering is
  4591. // expanding copies of large vectors from registers.
  4592. if (N2C &&
  4593. N1.getOpcode() == ISD::CONCAT_VECTORS &&
  4594. N1.getNumOperands() > 0) {
  4595. unsigned Factor =
  4596. N1.getOperand(0).getValueType().getVectorNumElements();
  4597. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
  4598. N1.getOperand(N2C->getZExtValue() / Factor),
  4599. getConstant(N2C->getZExtValue() % Factor, DL,
  4600. N2.getValueType()));
  4601. }
  4602. // EXTRACT_VECTOR_ELT of BUILD_VECTOR is often formed while lowering is
  4603. // expanding large vector constants.
  4604. if (N2C && N1.getOpcode() == ISD::BUILD_VECTOR) {
  4605. SDValue Elt = N1.getOperand(N2C->getZExtValue());
  4606. if (VT != Elt.getValueType())
  4607. // If the vector element type is not legal, the BUILD_VECTOR operands
  4608. // are promoted and implicitly truncated, and the result implicitly
  4609. // extended. Make that explicit here.
  4610. Elt = getAnyExtOrTrunc(Elt, DL, VT);
  4611. return Elt;
  4612. }
  4613. // EXTRACT_VECTOR_ELT of INSERT_VECTOR_ELT is often formed when vector
  4614. // operations are lowered to scalars.
  4615. if (N1.getOpcode() == ISD::INSERT_VECTOR_ELT) {
  4616. // If the indices are the same, return the inserted element else
  4617. // if the indices are known different, extract the element from
  4618. // the original vector.
  4619. SDValue N1Op2 = N1.getOperand(2);
  4620. ConstantSDNode *N1Op2C = dyn_cast<ConstantSDNode>(N1Op2);
  4621. if (N1Op2C && N2C) {
  4622. if (N1Op2C->getZExtValue() == N2C->getZExtValue()) {
  4623. if (VT == N1.getOperand(1).getValueType())
  4624. return N1.getOperand(1);
  4625. else
  4626. return getSExtOrTrunc(N1.getOperand(1), DL, VT);
  4627. }
  4628. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0), N2);
  4629. }
  4630. }
  4631. // EXTRACT_VECTOR_ELT of v1iX EXTRACT_SUBVECTOR could be formed
  4632. // when vector types are scalarized and v1iX is legal.
  4633. // vextract (v1iX extract_subvector(vNiX, Idx)) -> vextract(vNiX,Idx)
  4634. if (N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  4635. N1.getValueType().getVectorNumElements() == 1) {
  4636. return getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, N1.getOperand(0),
  4637. N1.getOperand(1));
  4638. }
  4639. break;
  4640. case ISD::EXTRACT_ELEMENT:
  4641. assert(N2C && (unsigned)N2C->getZExtValue() < 2 && "Bad EXTRACT_ELEMENT!");
  4642. assert(!N1.getValueType().isVector() && !VT.isVector() &&
  4643. (N1.getValueType().isInteger() == VT.isInteger()) &&
  4644. N1.getValueType() != VT &&
  4645. "Wrong types for EXTRACT_ELEMENT!");
  4646. // EXTRACT_ELEMENT of BUILD_PAIR is often formed while legalize is expanding
  4647. // 64-bit integers into 32-bit parts. Instead of building the extract of
  4648. // the BUILD_PAIR, only to have legalize rip it apart, just do it now.
  4649. if (N1.getOpcode() == ISD::BUILD_PAIR)
  4650. return N1.getOperand(N2C->getZExtValue());
  4651. // EXTRACT_ELEMENT of a constant int is also very common.
  4652. if (N1C) {
  4653. unsigned ElementSize = VT.getSizeInBits();
  4654. unsigned Shift = ElementSize * N2C->getZExtValue();
  4655. APInt ShiftedVal = N1C->getAPIntValue().lshr(Shift);
  4656. return getConstant(ShiftedVal.trunc(ElementSize), DL, VT);
  4657. }
  4658. break;
  4659. case ISD::EXTRACT_SUBVECTOR:
  4660. if (VT.isSimple() && N1.getValueType().isSimple()) {
  4661. assert(VT.isVector() && N1.getValueType().isVector() &&
  4662. "Extract subvector VTs must be a vectors!");
  4663. assert(VT.getVectorElementType() ==
  4664. N1.getValueType().getVectorElementType() &&
  4665. "Extract subvector VTs must have the same element type!");
  4666. assert(VT.getSimpleVT() <= N1.getSimpleValueType() &&
  4667. "Extract subvector must be from larger vector to smaller vector!");
  4668. if (N2C) {
  4669. assert((VT.getVectorNumElements() + N2C->getZExtValue()
  4670. <= N1.getValueType().getVectorNumElements())
  4671. && "Extract subvector overflow!");
  4672. }
  4673. // Trivial extraction.
  4674. if (VT.getSimpleVT() == N1.getSimpleValueType())
  4675. return N1;
  4676. // EXTRACT_SUBVECTOR of an UNDEF is an UNDEF.
  4677. if (N1.isUndef())
  4678. return getUNDEF(VT);
  4679. // EXTRACT_SUBVECTOR of CONCAT_VECTOR can be simplified if the pieces of
  4680. // the concat have the same type as the extract.
  4681. if (N2C && N1.getOpcode() == ISD::CONCAT_VECTORS &&
  4682. N1.getNumOperands() > 0 &&
  4683. VT == N1.getOperand(0).getValueType()) {
  4684. unsigned Factor = VT.getVectorNumElements();
  4685. return N1.getOperand(N2C->getZExtValue() / Factor);
  4686. }
  4687. // EXTRACT_SUBVECTOR of INSERT_SUBVECTOR is often created
  4688. // during shuffle legalization.
  4689. if (N1.getOpcode() == ISD::INSERT_SUBVECTOR && N2 == N1.getOperand(2) &&
  4690. VT == N1.getOperand(1).getValueType())
  4691. return N1.getOperand(1);
  4692. }
  4693. break;
  4694. }
  4695. // Perform trivial constant folding.
  4696. if (SDValue SV =
  4697. FoldConstantArithmetic(Opcode, DL, VT, N1.getNode(), N2.getNode()))
  4698. return SV;
  4699. if (SDValue V = foldConstantFPMath(Opcode, DL, VT, N1, N2))
  4700. return V;
  4701. // Canonicalize an UNDEF to the RHS, even over a constant.
  4702. if (N1.isUndef()) {
  4703. if (TLI->isCommutativeBinOp(Opcode)) {
  4704. std::swap(N1, N2);
  4705. } else {
  4706. switch (Opcode) {
  4707. case ISD::FP_ROUND_INREG:
  4708. case ISD::SIGN_EXTEND_INREG:
  4709. case ISD::SUB:
  4710. return getUNDEF(VT); // fold op(undef, arg2) -> undef
  4711. case ISD::UDIV:
  4712. case ISD::SDIV:
  4713. case ISD::UREM:
  4714. case ISD::SREM:
  4715. case ISD::SSUBSAT:
  4716. case ISD::USUBSAT:
  4717. return getConstant(0, DL, VT); // fold op(undef, arg2) -> 0
  4718. }
  4719. }
  4720. }
  4721. // Fold a bunch of operators when the RHS is undef.
  4722. if (N2.isUndef()) {
  4723. switch (Opcode) {
  4724. case ISD::XOR:
  4725. if (N1.isUndef())
  4726. // Handle undef ^ undef -> 0 special case. This is a common
  4727. // idiom (misuse).
  4728. return getConstant(0, DL, VT);
  4729. LLVM_FALLTHROUGH;
  4730. case ISD::ADD:
  4731. case ISD::SUB:
  4732. case ISD::UDIV:
  4733. case ISD::SDIV:
  4734. case ISD::UREM:
  4735. case ISD::SREM:
  4736. return getUNDEF(VT); // fold op(arg1, undef) -> undef
  4737. case ISD::MUL:
  4738. case ISD::AND:
  4739. case ISD::SSUBSAT:
  4740. case ISD::USUBSAT:
  4741. return getConstant(0, DL, VT); // fold op(arg1, undef) -> 0
  4742. case ISD::OR:
  4743. case ISD::SADDSAT:
  4744. case ISD::UADDSAT:
  4745. return getAllOnesConstant(DL, VT);
  4746. }
  4747. }
  4748. // Memoize this node if possible.
  4749. SDNode *N;
  4750. SDVTList VTs = getVTList(VT);
  4751. SDValue Ops[] = {N1, N2};
  4752. if (VT != MVT::Glue) {
  4753. FoldingSetNodeID ID;
  4754. AddNodeIDNode(ID, Opcode, VTs, Ops);
  4755. void *IP = nullptr;
  4756. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  4757. E->intersectFlagsWith(Flags);
  4758. return SDValue(E, 0);
  4759. }
  4760. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4761. N->setFlags(Flags);
  4762. createOperands(N, Ops);
  4763. CSEMap.InsertNode(N, IP);
  4764. } else {
  4765. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4766. createOperands(N, Ops);
  4767. }
  4768. InsertNode(N);
  4769. SDValue V = SDValue(N, 0);
  4770. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4771. return V;
  4772. }
  4773. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4774. SDValue N1, SDValue N2, SDValue N3,
  4775. const SDNodeFlags Flags) {
  4776. // Perform various simplifications.
  4777. switch (Opcode) {
  4778. case ISD::FMA: {
  4779. assert(VT.isFloatingPoint() && "This operator only applies to FP types!");
  4780. assert(N1.getValueType() == VT && N2.getValueType() == VT &&
  4781. N3.getValueType() == VT && "FMA types must match!");
  4782. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  4783. ConstantFPSDNode *N2CFP = dyn_cast<ConstantFPSDNode>(N2);
  4784. ConstantFPSDNode *N3CFP = dyn_cast<ConstantFPSDNode>(N3);
  4785. if (N1CFP && N2CFP && N3CFP) {
  4786. APFloat V1 = N1CFP->getValueAPF();
  4787. const APFloat &V2 = N2CFP->getValueAPF();
  4788. const APFloat &V3 = N3CFP->getValueAPF();
  4789. V1.fusedMultiplyAdd(V2, V3, APFloat::rmNearestTiesToEven);
  4790. return getConstantFP(V1, DL, VT);
  4791. }
  4792. break;
  4793. }
  4794. case ISD::BUILD_VECTOR: {
  4795. // Attempt to simplify BUILD_VECTOR.
  4796. SDValue Ops[] = {N1, N2, N3};
  4797. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  4798. return V;
  4799. break;
  4800. }
  4801. case ISD::CONCAT_VECTORS: {
  4802. // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
  4803. SDValue Ops[] = {N1, N2, N3};
  4804. if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
  4805. return V;
  4806. break;
  4807. }
  4808. case ISD::SETCC: {
  4809. assert(VT.isInteger() && "SETCC result type must be an integer!");
  4810. assert(N1.getValueType() == N2.getValueType() &&
  4811. "SETCC operands must have the same type!");
  4812. assert(VT.isVector() == N1.getValueType().isVector() &&
  4813. "SETCC type should be vector iff the operand type is vector!");
  4814. assert((!VT.isVector() ||
  4815. VT.getVectorNumElements() == N1.getValueType().getVectorNumElements()) &&
  4816. "SETCC vector element counts must match!");
  4817. // Use FoldSetCC to simplify SETCC's.
  4818. if (SDValue V = FoldSetCC(VT, N1, N2, cast<CondCodeSDNode>(N3)->get(), DL))
  4819. return V;
  4820. // Vector constant folding.
  4821. SDValue Ops[] = {N1, N2, N3};
  4822. if (SDValue V = FoldConstantVectorArithmetic(Opcode, DL, VT, Ops)) {
  4823. NewSDValueDbgMsg(V, "New node vector constant folding: ", this);
  4824. return V;
  4825. }
  4826. break;
  4827. }
  4828. case ISD::SELECT:
  4829. case ISD::VSELECT:
  4830. if (SDValue V = simplifySelect(N1, N2, N3))
  4831. return V;
  4832. break;
  4833. case ISD::VECTOR_SHUFFLE:
  4834. llvm_unreachable("should use getVectorShuffle constructor!");
  4835. case ISD::INSERT_VECTOR_ELT: {
  4836. ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3);
  4837. // INSERT_VECTOR_ELT into out-of-bounds element is an UNDEF
  4838. if (N3C && N3C->getZExtValue() >= N1.getValueType().getVectorNumElements())
  4839. return getUNDEF(VT);
  4840. break;
  4841. }
  4842. case ISD::INSERT_SUBVECTOR: {
  4843. SDValue Index = N3;
  4844. if (VT.isSimple() && N1.getValueType().isSimple()
  4845. && N2.getValueType().isSimple()) {
  4846. assert(VT.isVector() && N1.getValueType().isVector() &&
  4847. N2.getValueType().isVector() &&
  4848. "Insert subvector VTs must be a vectors");
  4849. assert(VT == N1.getValueType() &&
  4850. "Dest and insert subvector source types must match!");
  4851. assert(N2.getSimpleValueType() <= N1.getSimpleValueType() &&
  4852. "Insert subvector must be from smaller vector to larger vector!");
  4853. if (isa<ConstantSDNode>(Index)) {
  4854. assert((N2.getValueType().getVectorNumElements() +
  4855. cast<ConstantSDNode>(Index)->getZExtValue()
  4856. <= VT.getVectorNumElements())
  4857. && "Insert subvector overflow!");
  4858. }
  4859. // Trivial insertion.
  4860. if (VT.getSimpleVT() == N2.getSimpleValueType())
  4861. return N2;
  4862. }
  4863. break;
  4864. }
  4865. case ISD::BITCAST:
  4866. // Fold bit_convert nodes from a type to themselves.
  4867. if (N1.getValueType() == VT)
  4868. return N1;
  4869. break;
  4870. }
  4871. // Memoize node if it doesn't produce a flag.
  4872. SDNode *N;
  4873. SDVTList VTs = getVTList(VT);
  4874. SDValue Ops[] = {N1, N2, N3};
  4875. if (VT != MVT::Glue) {
  4876. FoldingSetNodeID ID;
  4877. AddNodeIDNode(ID, Opcode, VTs, Ops);
  4878. void *IP = nullptr;
  4879. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  4880. E->intersectFlagsWith(Flags);
  4881. return SDValue(E, 0);
  4882. }
  4883. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4884. N->setFlags(Flags);
  4885. createOperands(N, Ops);
  4886. CSEMap.InsertNode(N, IP);
  4887. } else {
  4888. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  4889. createOperands(N, Ops);
  4890. }
  4891. InsertNode(N);
  4892. SDValue V = SDValue(N, 0);
  4893. NewSDValueDbgMsg(V, "Creating new node: ", this);
  4894. return V;
  4895. }
  4896. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4897. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  4898. SDValue Ops[] = { N1, N2, N3, N4 };
  4899. return getNode(Opcode, DL, VT, Ops);
  4900. }
  4901. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  4902. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  4903. SDValue N5) {
  4904. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  4905. return getNode(Opcode, DL, VT, Ops);
  4906. }
  4907. /// getStackArgumentTokenFactor - Compute a TokenFactor to force all
  4908. /// the incoming stack arguments to be loaded from the stack.
  4909. SDValue SelectionDAG::getStackArgumentTokenFactor(SDValue Chain) {
  4910. SmallVector<SDValue, 8> ArgChains;
  4911. // Include the original chain at the beginning of the list. When this is
  4912. // used by target LowerCall hooks, this helps legalize find the
  4913. // CALLSEQ_BEGIN node.
  4914. ArgChains.push_back(Chain);
  4915. // Add a chain value for each stack argument.
  4916. for (SDNode::use_iterator U = getEntryNode().getNode()->use_begin(),
  4917. UE = getEntryNode().getNode()->use_end(); U != UE; ++U)
  4918. if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
  4919. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
  4920. if (FI->getIndex() < 0)
  4921. ArgChains.push_back(SDValue(L, 1));
  4922. // Build a tokenfactor for all the chains.
  4923. return getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
  4924. }
  4925. /// getMemsetValue - Vectorized representation of the memset value
  4926. /// operand.
  4927. static SDValue getMemsetValue(SDValue Value, EVT VT, SelectionDAG &DAG,
  4928. const SDLoc &dl) {
  4929. assert(!Value.isUndef());
  4930. unsigned NumBits = VT.getScalarSizeInBits();
  4931. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Value)) {
  4932. assert(C->getAPIntValue().getBitWidth() == 8);
  4933. APInt Val = APInt::getSplat(NumBits, C->getAPIntValue());
  4934. if (VT.isInteger()) {
  4935. bool IsOpaque = VT.getSizeInBits() > 64 ||
  4936. !DAG.getTargetLoweringInfo().isLegalStoreImmediate(C->getSExtValue());
  4937. return DAG.getConstant(Val, dl, VT, false, IsOpaque);
  4938. }
  4939. return DAG.getConstantFP(APFloat(DAG.EVTToAPFloatSemantics(VT), Val), dl,
  4940. VT);
  4941. }
  4942. assert(Value.getValueType() == MVT::i8 && "memset with non-byte fill value?");
  4943. EVT IntVT = VT.getScalarType();
  4944. if (!IntVT.isInteger())
  4945. IntVT = EVT::getIntegerVT(*DAG.getContext(), IntVT.getSizeInBits());
  4946. Value = DAG.getNode(ISD::ZERO_EXTEND, dl, IntVT, Value);
  4947. if (NumBits > 8) {
  4948. // Use a multiplication with 0x010101... to extend the input to the
  4949. // required length.
  4950. APInt Magic = APInt::getSplat(NumBits, APInt(8, 0x01));
  4951. Value = DAG.getNode(ISD::MUL, dl, IntVT, Value,
  4952. DAG.getConstant(Magic, dl, IntVT));
  4953. }
  4954. if (VT != Value.getValueType() && !VT.isInteger())
  4955. Value = DAG.getBitcast(VT.getScalarType(), Value);
  4956. if (VT != Value.getValueType())
  4957. Value = DAG.getSplatBuildVector(VT, dl, Value);
  4958. return Value;
  4959. }
  4960. /// getMemsetStringVal - Similar to getMemsetValue. Except this is only
  4961. /// used when a memcpy is turned into a memset when the source is a constant
  4962. /// string ptr.
  4963. static SDValue getMemsetStringVal(EVT VT, const SDLoc &dl, SelectionDAG &DAG,
  4964. const TargetLowering &TLI,
  4965. const ConstantDataArraySlice &Slice) {
  4966. // Handle vector with all elements zero.
  4967. if (Slice.Array == nullptr) {
  4968. if (VT.isInteger())
  4969. return DAG.getConstant(0, dl, VT);
  4970. else if (VT == MVT::f32 || VT == MVT::f64 || VT == MVT::f128)
  4971. return DAG.getConstantFP(0.0, dl, VT);
  4972. else if (VT.isVector()) {
  4973. unsigned NumElts = VT.getVectorNumElements();
  4974. MVT EltVT = (VT.getVectorElementType() == MVT::f32) ? MVT::i32 : MVT::i64;
  4975. return DAG.getNode(ISD::BITCAST, dl, VT,
  4976. DAG.getConstant(0, dl,
  4977. EVT::getVectorVT(*DAG.getContext(),
  4978. EltVT, NumElts)));
  4979. } else
  4980. llvm_unreachable("Expected type!");
  4981. }
  4982. assert(!VT.isVector() && "Can't handle vector type here!");
  4983. unsigned NumVTBits = VT.getSizeInBits();
  4984. unsigned NumVTBytes = NumVTBits / 8;
  4985. unsigned NumBytes = std::min(NumVTBytes, unsigned(Slice.Length));
  4986. APInt Val(NumVTBits, 0);
  4987. if (DAG.getDataLayout().isLittleEndian()) {
  4988. for (unsigned i = 0; i != NumBytes; ++i)
  4989. Val |= (uint64_t)(unsigned char)Slice[i] << i*8;
  4990. } else {
  4991. for (unsigned i = 0; i != NumBytes; ++i)
  4992. Val |= (uint64_t)(unsigned char)Slice[i] << (NumVTBytes-i-1)*8;
  4993. }
  4994. // If the "cost" of materializing the integer immediate is less than the cost
  4995. // of a load, then it is cost effective to turn the load into the immediate.
  4996. Type *Ty = VT.getTypeForEVT(*DAG.getContext());
  4997. if (TLI.shouldConvertConstantLoadToIntImm(Val, Ty))
  4998. return DAG.getConstant(Val, dl, VT);
  4999. return SDValue(nullptr, 0);
  5000. }
  5001. SDValue SelectionDAG::getMemBasePlusOffset(SDValue Base, unsigned Offset,
  5002. const SDLoc &DL) {
  5003. EVT VT = Base.getValueType();
  5004. return getNode(ISD::ADD, DL, VT, Base, getConstant(Offset, DL, VT));
  5005. }
  5006. /// Returns true if memcpy source is constant data.
  5007. static bool isMemSrcFromConstant(SDValue Src, ConstantDataArraySlice &Slice) {
  5008. uint64_t SrcDelta = 0;
  5009. GlobalAddressSDNode *G = nullptr;
  5010. if (Src.getOpcode() == ISD::GlobalAddress)
  5011. G = cast<GlobalAddressSDNode>(Src);
  5012. else if (Src.getOpcode() == ISD::ADD &&
  5013. Src.getOperand(0).getOpcode() == ISD::GlobalAddress &&
  5014. Src.getOperand(1).getOpcode() == ISD::Constant) {
  5015. G = cast<GlobalAddressSDNode>(Src.getOperand(0));
  5016. SrcDelta = cast<ConstantSDNode>(Src.getOperand(1))->getZExtValue();
  5017. }
  5018. if (!G)
  5019. return false;
  5020. return getConstantDataArrayInfo(G->getGlobal(), Slice, 8,
  5021. SrcDelta + G->getOffset());
  5022. }
  5023. static bool shouldLowerMemFuncForSize(const MachineFunction &MF) {
  5024. // On Darwin, -Os means optimize for size without hurting performance, so
  5025. // only really optimize for size when -Oz (MinSize) is used.
  5026. if (MF.getTarget().getTargetTriple().isOSDarwin())
  5027. return MF.getFunction().hasMinSize();
  5028. return MF.getFunction().hasOptSize();
  5029. }
  5030. static void chainLoadsAndStoresForMemcpy(SelectionDAG &DAG, const SDLoc &dl,
  5031. SmallVector<SDValue, 32> &OutChains, unsigned From,
  5032. unsigned To, SmallVector<SDValue, 16> &OutLoadChains,
  5033. SmallVector<SDValue, 16> &OutStoreChains) {
  5034. assert(OutLoadChains.size() && "Missing loads in memcpy inlining");
  5035. assert(OutStoreChains.size() && "Missing stores in memcpy inlining");
  5036. SmallVector<SDValue, 16> GluedLoadChains;
  5037. for (unsigned i = From; i < To; ++i) {
  5038. OutChains.push_back(OutLoadChains[i]);
  5039. GluedLoadChains.push_back(OutLoadChains[i]);
  5040. }
  5041. // Chain for all loads.
  5042. SDValue LoadToken = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
  5043. GluedLoadChains);
  5044. for (unsigned i = From; i < To; ++i) {
  5045. StoreSDNode *ST = dyn_cast<StoreSDNode>(OutStoreChains[i]);
  5046. SDValue NewStore = DAG.getTruncStore(LoadToken, dl, ST->getValue(),
  5047. ST->getBasePtr(), ST->getMemoryVT(),
  5048. ST->getMemOperand());
  5049. OutChains.push_back(NewStore);
  5050. }
  5051. }
  5052. static SDValue getMemcpyLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  5053. SDValue Chain, SDValue Dst, SDValue Src,
  5054. uint64_t Size, unsigned Align,
  5055. bool isVol, bool AlwaysInline,
  5056. MachinePointerInfo DstPtrInfo,
  5057. MachinePointerInfo SrcPtrInfo) {
  5058. // Turn a memcpy of undef to nop.
  5059. if (Src.isUndef())
  5060. return Chain;
  5061. // Expand memcpy to a series of load and store ops if the size operand falls
  5062. // below a certain threshold.
  5063. // TODO: In the AlwaysInline case, if the size is big then generate a loop
  5064. // rather than maybe a humongous number of loads and stores.
  5065. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5066. const DataLayout &DL = DAG.getDataLayout();
  5067. LLVMContext &C = *DAG.getContext();
  5068. std::vector<EVT> MemOps;
  5069. bool DstAlignCanChange = false;
  5070. MachineFunction &MF = DAG.getMachineFunction();
  5071. MachineFrameInfo &MFI = MF.getFrameInfo();
  5072. bool OptSize = shouldLowerMemFuncForSize(MF);
  5073. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  5074. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  5075. DstAlignCanChange = true;
  5076. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5077. if (Align > SrcAlign)
  5078. SrcAlign = Align;
  5079. ConstantDataArraySlice Slice;
  5080. bool CopyFromConstant = isMemSrcFromConstant(Src, Slice);
  5081. bool isZeroConstant = CopyFromConstant && Slice.Array == nullptr;
  5082. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemcpy(OptSize);
  5083. if (!TLI.findOptimalMemOpLowering(MemOps, Limit, Size,
  5084. (DstAlignCanChange ? 0 : Align),
  5085. (isZeroConstant ? 0 : SrcAlign),
  5086. false, false, CopyFromConstant, true,
  5087. DstPtrInfo.getAddrSpace(),
  5088. SrcPtrInfo.getAddrSpace(),
  5089. MF.getFunction().getAttributes()))
  5090. return SDValue();
  5091. if (DstAlignCanChange) {
  5092. Type *Ty = MemOps[0].getTypeForEVT(C);
  5093. unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
  5094. // Don't promote to an alignment that would require dynamic stack
  5095. // realignment.
  5096. const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo();
  5097. if (!TRI->needsStackRealignment(MF))
  5098. while (NewAlign > Align &&
  5099. DL.exceedsNaturalStackAlignment(NewAlign))
  5100. NewAlign /= 2;
  5101. if (NewAlign > Align) {
  5102. // Give the stack frame object a larger alignment if needed.
  5103. if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
  5104. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  5105. Align = NewAlign;
  5106. }
  5107. }
  5108. MachineMemOperand::Flags MMOFlags =
  5109. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  5110. SmallVector<SDValue, 16> OutLoadChains;
  5111. SmallVector<SDValue, 16> OutStoreChains;
  5112. SmallVector<SDValue, 32> OutChains;
  5113. unsigned NumMemOps = MemOps.size();
  5114. uint64_t SrcOff = 0, DstOff = 0;
  5115. for (unsigned i = 0; i != NumMemOps; ++i) {
  5116. EVT VT = MemOps[i];
  5117. unsigned VTSize = VT.getSizeInBits() / 8;
  5118. SDValue Value, Store;
  5119. if (VTSize > Size) {
  5120. // Issuing an unaligned load / store pair that overlaps with the previous
  5121. // pair. Adjust the offset accordingly.
  5122. assert(i == NumMemOps-1 && i != 0);
  5123. SrcOff -= VTSize - Size;
  5124. DstOff -= VTSize - Size;
  5125. }
  5126. if (CopyFromConstant &&
  5127. (isZeroConstant || (VT.isInteger() && !VT.isVector()))) {
  5128. // It's unlikely a store of a vector immediate can be done in a single
  5129. // instruction. It would require a load from a constantpool first.
  5130. // We only handle zero vectors here.
  5131. // FIXME: Handle other cases where store of vector immediate is done in
  5132. // a single instruction.
  5133. ConstantDataArraySlice SubSlice;
  5134. if (SrcOff < Slice.Length) {
  5135. SubSlice = Slice;
  5136. SubSlice.move(SrcOff);
  5137. } else {
  5138. // This is an out-of-bounds access and hence UB. Pretend we read zero.
  5139. SubSlice.Array = nullptr;
  5140. SubSlice.Offset = 0;
  5141. SubSlice.Length = VTSize;
  5142. }
  5143. Value = getMemsetStringVal(VT, dl, DAG, TLI, SubSlice);
  5144. if (Value.getNode()) {
  5145. Store = DAG.getStore(Chain, dl, Value,
  5146. DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5147. DstPtrInfo.getWithOffset(DstOff), Align,
  5148. MMOFlags);
  5149. OutChains.push_back(Store);
  5150. }
  5151. }
  5152. if (!Store.getNode()) {
  5153. // The type might not be legal for the target. This should only happen
  5154. // if the type is smaller than a legal type, as on PPC, so the right
  5155. // thing to do is generate a LoadExt/StoreTrunc pair. These simplify
  5156. // to Load/Store if NVT==VT.
  5157. // FIXME does the case above also need this?
  5158. EVT NVT = TLI.getTypeToTransformTo(C, VT);
  5159. assert(NVT.bitsGE(VT));
  5160. bool isDereferenceable =
  5161. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  5162. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  5163. if (isDereferenceable)
  5164. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  5165. Value = DAG.getExtLoad(ISD::EXTLOAD, dl, NVT, Chain,
  5166. DAG.getMemBasePlusOffset(Src, SrcOff, dl),
  5167. SrcPtrInfo.getWithOffset(SrcOff), VT,
  5168. MinAlign(SrcAlign, SrcOff), SrcMMOFlags);
  5169. OutLoadChains.push_back(Value.getValue(1));
  5170. Store = DAG.getTruncStore(
  5171. Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5172. DstPtrInfo.getWithOffset(DstOff), VT, Align, MMOFlags);
  5173. OutStoreChains.push_back(Store);
  5174. }
  5175. SrcOff += VTSize;
  5176. DstOff += VTSize;
  5177. Size -= VTSize;
  5178. }
  5179. unsigned GluedLdStLimit = MaxLdStGlue == 0 ?
  5180. TLI.getMaxGluedStoresPerMemcpy() : MaxLdStGlue;
  5181. unsigned NumLdStInMemcpy = OutStoreChains.size();
  5182. if (NumLdStInMemcpy) {
  5183. // It may be that memcpy might be converted to memset if it's memcpy
  5184. // of constants. In such a case, we won't have loads and stores, but
  5185. // just stores. In the absence of loads, there is nothing to gang up.
  5186. if ((GluedLdStLimit <= 1) || !EnableMemCpyDAGOpt) {
  5187. // If target does not care, just leave as it.
  5188. for (unsigned i = 0; i < NumLdStInMemcpy; ++i) {
  5189. OutChains.push_back(OutLoadChains[i]);
  5190. OutChains.push_back(OutStoreChains[i]);
  5191. }
  5192. } else {
  5193. // Ld/St less than/equal limit set by target.
  5194. if (NumLdStInMemcpy <= GluedLdStLimit) {
  5195. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  5196. NumLdStInMemcpy, OutLoadChains,
  5197. OutStoreChains);
  5198. } else {
  5199. unsigned NumberLdChain = NumLdStInMemcpy / GluedLdStLimit;
  5200. unsigned RemainingLdStInMemcpy = NumLdStInMemcpy % GluedLdStLimit;
  5201. unsigned GlueIter = 0;
  5202. for (unsigned cnt = 0; cnt < NumberLdChain; ++cnt) {
  5203. unsigned IndexFrom = NumLdStInMemcpy - GlueIter - GluedLdStLimit;
  5204. unsigned IndexTo = NumLdStInMemcpy - GlueIter;
  5205. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, IndexFrom, IndexTo,
  5206. OutLoadChains, OutStoreChains);
  5207. GlueIter += GluedLdStLimit;
  5208. }
  5209. // Residual ld/st.
  5210. if (RemainingLdStInMemcpy) {
  5211. chainLoadsAndStoresForMemcpy(DAG, dl, OutChains, 0,
  5212. RemainingLdStInMemcpy, OutLoadChains,
  5213. OutStoreChains);
  5214. }
  5215. }
  5216. }
  5217. }
  5218. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  5219. }
  5220. static SDValue getMemmoveLoadsAndStores(SelectionDAG &DAG, const SDLoc &dl,
  5221. SDValue Chain, SDValue Dst, SDValue Src,
  5222. uint64_t Size, unsigned Align,
  5223. bool isVol, bool AlwaysInline,
  5224. MachinePointerInfo DstPtrInfo,
  5225. MachinePointerInfo SrcPtrInfo) {
  5226. // Turn a memmove of undef to nop.
  5227. if (Src.isUndef())
  5228. return Chain;
  5229. // Expand memmove to a series of load and store ops if the size operand falls
  5230. // below a certain threshold.
  5231. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5232. const DataLayout &DL = DAG.getDataLayout();
  5233. LLVMContext &C = *DAG.getContext();
  5234. std::vector<EVT> MemOps;
  5235. bool DstAlignCanChange = false;
  5236. MachineFunction &MF = DAG.getMachineFunction();
  5237. MachineFrameInfo &MFI = MF.getFrameInfo();
  5238. bool OptSize = shouldLowerMemFuncForSize(MF);
  5239. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  5240. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  5241. DstAlignCanChange = true;
  5242. unsigned SrcAlign = DAG.InferPtrAlignment(Src);
  5243. if (Align > SrcAlign)
  5244. SrcAlign = Align;
  5245. unsigned Limit = AlwaysInline ? ~0U : TLI.getMaxStoresPerMemmove(OptSize);
  5246. if (!TLI.findOptimalMemOpLowering(MemOps, Limit, Size,
  5247. (DstAlignCanChange ? 0 : Align), SrcAlign,
  5248. false, false, false, false,
  5249. DstPtrInfo.getAddrSpace(),
  5250. SrcPtrInfo.getAddrSpace(),
  5251. MF.getFunction().getAttributes()))
  5252. return SDValue();
  5253. if (DstAlignCanChange) {
  5254. Type *Ty = MemOps[0].getTypeForEVT(C);
  5255. unsigned NewAlign = (unsigned)DL.getABITypeAlignment(Ty);
  5256. if (NewAlign > Align) {
  5257. // Give the stack frame object a larger alignment if needed.
  5258. if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
  5259. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  5260. Align = NewAlign;
  5261. }
  5262. }
  5263. MachineMemOperand::Flags MMOFlags =
  5264. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone;
  5265. uint64_t SrcOff = 0, DstOff = 0;
  5266. SmallVector<SDValue, 8> LoadValues;
  5267. SmallVector<SDValue, 8> LoadChains;
  5268. SmallVector<SDValue, 8> OutChains;
  5269. unsigned NumMemOps = MemOps.size();
  5270. for (unsigned i = 0; i < NumMemOps; i++) {
  5271. EVT VT = MemOps[i];
  5272. unsigned VTSize = VT.getSizeInBits() / 8;
  5273. SDValue Value;
  5274. bool isDereferenceable =
  5275. SrcPtrInfo.getWithOffset(SrcOff).isDereferenceable(VTSize, C, DL);
  5276. MachineMemOperand::Flags SrcMMOFlags = MMOFlags;
  5277. if (isDereferenceable)
  5278. SrcMMOFlags |= MachineMemOperand::MODereferenceable;
  5279. Value =
  5280. DAG.getLoad(VT, dl, Chain, DAG.getMemBasePlusOffset(Src, SrcOff, dl),
  5281. SrcPtrInfo.getWithOffset(SrcOff), SrcAlign, SrcMMOFlags);
  5282. LoadValues.push_back(Value);
  5283. LoadChains.push_back(Value.getValue(1));
  5284. SrcOff += VTSize;
  5285. }
  5286. Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, LoadChains);
  5287. OutChains.clear();
  5288. for (unsigned i = 0; i < NumMemOps; i++) {
  5289. EVT VT = MemOps[i];
  5290. unsigned VTSize = VT.getSizeInBits() / 8;
  5291. SDValue Store;
  5292. Store = DAG.getStore(Chain, dl, LoadValues[i],
  5293. DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5294. DstPtrInfo.getWithOffset(DstOff), Align, MMOFlags);
  5295. OutChains.push_back(Store);
  5296. DstOff += VTSize;
  5297. }
  5298. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  5299. }
  5300. /// Lower the call to 'memset' intrinsic function into a series of store
  5301. /// operations.
  5302. ///
  5303. /// \param DAG Selection DAG where lowered code is placed.
  5304. /// \param dl Link to corresponding IR location.
  5305. /// \param Chain Control flow dependency.
  5306. /// \param Dst Pointer to destination memory location.
  5307. /// \param Src Value of byte to write into the memory.
  5308. /// \param Size Number of bytes to write.
  5309. /// \param Align Alignment of the destination in bytes.
  5310. /// \param isVol True if destination is volatile.
  5311. /// \param DstPtrInfo IR information on the memory pointer.
  5312. /// \returns New head in the control flow, if lowering was successful, empty
  5313. /// SDValue otherwise.
  5314. ///
  5315. /// The function tries to replace 'llvm.memset' intrinsic with several store
  5316. /// operations and value calculation code. This is usually profitable for small
  5317. /// memory size.
  5318. static SDValue getMemsetStores(SelectionDAG &DAG, const SDLoc &dl,
  5319. SDValue Chain, SDValue Dst, SDValue Src,
  5320. uint64_t Size, unsigned Align, bool isVol,
  5321. MachinePointerInfo DstPtrInfo) {
  5322. // Turn a memset of undef to nop.
  5323. if (Src.isUndef())
  5324. return Chain;
  5325. // Expand memset to a series of load/store ops if the size operand
  5326. // falls below a certain threshold.
  5327. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5328. std::vector<EVT> MemOps;
  5329. bool DstAlignCanChange = false;
  5330. MachineFunction &MF = DAG.getMachineFunction();
  5331. MachineFrameInfo &MFI = MF.getFrameInfo();
  5332. bool OptSize = shouldLowerMemFuncForSize(MF);
  5333. FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Dst);
  5334. if (FI && !MFI.isFixedObjectIndex(FI->getIndex()))
  5335. DstAlignCanChange = true;
  5336. bool IsZeroVal =
  5337. isa<ConstantSDNode>(Src) && cast<ConstantSDNode>(Src)->isNullValue();
  5338. if (!TLI.findOptimalMemOpLowering(MemOps, TLI.getMaxStoresPerMemset(OptSize),
  5339. Size, (DstAlignCanChange ? 0 : Align), 0,
  5340. true, IsZeroVal, false, true,
  5341. DstPtrInfo.getAddrSpace(), ~0u,
  5342. MF.getFunction().getAttributes()))
  5343. return SDValue();
  5344. if (DstAlignCanChange) {
  5345. Type *Ty = MemOps[0].getTypeForEVT(*DAG.getContext());
  5346. unsigned NewAlign = (unsigned)DAG.getDataLayout().getABITypeAlignment(Ty);
  5347. if (NewAlign > Align) {
  5348. // Give the stack frame object a larger alignment if needed.
  5349. if (MFI.getObjectAlignment(FI->getIndex()) < NewAlign)
  5350. MFI.setObjectAlignment(FI->getIndex(), NewAlign);
  5351. Align = NewAlign;
  5352. }
  5353. }
  5354. SmallVector<SDValue, 8> OutChains;
  5355. uint64_t DstOff = 0;
  5356. unsigned NumMemOps = MemOps.size();
  5357. // Find the largest store and generate the bit pattern for it.
  5358. EVT LargestVT = MemOps[0];
  5359. for (unsigned i = 1; i < NumMemOps; i++)
  5360. if (MemOps[i].bitsGT(LargestVT))
  5361. LargestVT = MemOps[i];
  5362. SDValue MemSetValue = getMemsetValue(Src, LargestVT, DAG, dl);
  5363. for (unsigned i = 0; i < NumMemOps; i++) {
  5364. EVT VT = MemOps[i];
  5365. unsigned VTSize = VT.getSizeInBits() / 8;
  5366. if (VTSize > Size) {
  5367. // Issuing an unaligned load / store pair that overlaps with the previous
  5368. // pair. Adjust the offset accordingly.
  5369. assert(i == NumMemOps-1 && i != 0);
  5370. DstOff -= VTSize - Size;
  5371. }
  5372. // If this store is smaller than the largest store see whether we can get
  5373. // the smaller value for free with a truncate.
  5374. SDValue Value = MemSetValue;
  5375. if (VT.bitsLT(LargestVT)) {
  5376. if (!LargestVT.isVector() && !VT.isVector() &&
  5377. TLI.isTruncateFree(LargestVT, VT))
  5378. Value = DAG.getNode(ISD::TRUNCATE, dl, VT, MemSetValue);
  5379. else
  5380. Value = getMemsetValue(Src, VT, DAG, dl);
  5381. }
  5382. assert(Value.getValueType() == VT && "Value with wrong type.");
  5383. SDValue Store = DAG.getStore(
  5384. Chain, dl, Value, DAG.getMemBasePlusOffset(Dst, DstOff, dl),
  5385. DstPtrInfo.getWithOffset(DstOff), Align,
  5386. isVol ? MachineMemOperand::MOVolatile : MachineMemOperand::MONone);
  5387. OutChains.push_back(Store);
  5388. DstOff += VT.getSizeInBits() / 8;
  5389. Size -= VTSize;
  5390. }
  5391. return DAG.getNode(ISD::TokenFactor, dl, MVT::Other, OutChains);
  5392. }
  5393. static void checkAddrSpaceIsValidForLibcall(const TargetLowering *TLI,
  5394. unsigned AS) {
  5395. // Lowering memcpy / memset / memmove intrinsics to calls is only valid if all
  5396. // pointer operands can be losslessly bitcasted to pointers of address space 0
  5397. if (AS != 0 && !TLI->isNoopAddrSpaceCast(AS, 0)) {
  5398. report_fatal_error("cannot lower memory intrinsic in address space " +
  5399. Twine(AS));
  5400. }
  5401. }
  5402. SDValue SelectionDAG::getMemcpy(SDValue Chain, const SDLoc &dl, SDValue Dst,
  5403. SDValue Src, SDValue Size, unsigned Align,
  5404. bool isVol, bool AlwaysInline, bool isTailCall,
  5405. MachinePointerInfo DstPtrInfo,
  5406. MachinePointerInfo SrcPtrInfo) {
  5407. assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
  5408. // Check to see if we should lower the memcpy to loads and stores first.
  5409. // For cases within the target-specified limits, this is the best choice.
  5410. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  5411. if (ConstantSize) {
  5412. // Memcpy with size zero? Just return the original chain.
  5413. if (ConstantSize->isNullValue())
  5414. return Chain;
  5415. SDValue Result = getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
  5416. ConstantSize->getZExtValue(),Align,
  5417. isVol, false, DstPtrInfo, SrcPtrInfo);
  5418. if (Result.getNode())
  5419. return Result;
  5420. }
  5421. // Then check to see if we should lower the memcpy with target-specific
  5422. // code. If the target chooses to do this, this is the next best.
  5423. if (TSI) {
  5424. SDValue Result = TSI->EmitTargetCodeForMemcpy(
  5425. *this, dl, Chain, Dst, Src, Size, Align, isVol, AlwaysInline,
  5426. DstPtrInfo, SrcPtrInfo);
  5427. if (Result.getNode())
  5428. return Result;
  5429. }
  5430. // If we really need inline code and the target declined to provide it,
  5431. // use a (potentially long) sequence of loads and stores.
  5432. if (AlwaysInline) {
  5433. assert(ConstantSize && "AlwaysInline requires a constant size!");
  5434. return getMemcpyLoadsAndStores(*this, dl, Chain, Dst, Src,
  5435. ConstantSize->getZExtValue(), Align, isVol,
  5436. true, DstPtrInfo, SrcPtrInfo);
  5437. }
  5438. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  5439. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  5440. // FIXME: If the memcpy is volatile (isVol), lowering it to a plain libc
  5441. // memcpy is not guaranteed to be safe. libc memcpys aren't required to
  5442. // respect volatile, so they may do things like read or write memory
  5443. // beyond the given memory regions. But fixing this isn't easy, and most
  5444. // people don't care.
  5445. // Emit a library call.
  5446. TargetLowering::ArgListTy Args;
  5447. TargetLowering::ArgListEntry Entry;
  5448. Entry.Ty = Type::getInt8PtrTy(*getContext());
  5449. Entry.Node = Dst; Args.push_back(Entry);
  5450. Entry.Node = Src; Args.push_back(Entry);
  5451. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5452. Entry.Node = Size; Args.push_back(Entry);
  5453. // FIXME: pass in SDLoc
  5454. TargetLowering::CallLoweringInfo CLI(*this);
  5455. CLI.setDebugLoc(dl)
  5456. .setChain(Chain)
  5457. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMCPY),
  5458. Dst.getValueType().getTypeForEVT(*getContext()),
  5459. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMCPY),
  5460. TLI->getPointerTy(getDataLayout())),
  5461. std::move(Args))
  5462. .setDiscardResult()
  5463. .setTailCall(isTailCall);
  5464. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  5465. return CallResult.second;
  5466. }
  5467. SDValue SelectionDAG::getAtomicMemcpy(SDValue Chain, const SDLoc &dl,
  5468. SDValue Dst, unsigned DstAlign,
  5469. SDValue Src, unsigned SrcAlign,
  5470. SDValue Size, Type *SizeTy,
  5471. unsigned ElemSz, bool isTailCall,
  5472. MachinePointerInfo DstPtrInfo,
  5473. MachinePointerInfo SrcPtrInfo) {
  5474. // Emit a library call.
  5475. TargetLowering::ArgListTy Args;
  5476. TargetLowering::ArgListEntry Entry;
  5477. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5478. Entry.Node = Dst;
  5479. Args.push_back(Entry);
  5480. Entry.Node = Src;
  5481. Args.push_back(Entry);
  5482. Entry.Ty = SizeTy;
  5483. Entry.Node = Size;
  5484. Args.push_back(Entry);
  5485. RTLIB::Libcall LibraryCall =
  5486. RTLIB::getMEMCPY_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  5487. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  5488. report_fatal_error("Unsupported element size");
  5489. TargetLowering::CallLoweringInfo CLI(*this);
  5490. CLI.setDebugLoc(dl)
  5491. .setChain(Chain)
  5492. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  5493. Type::getVoidTy(*getContext()),
  5494. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  5495. TLI->getPointerTy(getDataLayout())),
  5496. std::move(Args))
  5497. .setDiscardResult()
  5498. .setTailCall(isTailCall);
  5499. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  5500. return CallResult.second;
  5501. }
  5502. SDValue SelectionDAG::getMemmove(SDValue Chain, const SDLoc &dl, SDValue Dst,
  5503. SDValue Src, SDValue Size, unsigned Align,
  5504. bool isVol, bool isTailCall,
  5505. MachinePointerInfo DstPtrInfo,
  5506. MachinePointerInfo SrcPtrInfo) {
  5507. assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
  5508. // Check to see if we should lower the memmove to loads and stores first.
  5509. // For cases within the target-specified limits, this is the best choice.
  5510. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  5511. if (ConstantSize) {
  5512. // Memmove with size zero? Just return the original chain.
  5513. if (ConstantSize->isNullValue())
  5514. return Chain;
  5515. SDValue Result =
  5516. getMemmoveLoadsAndStores(*this, dl, Chain, Dst, Src,
  5517. ConstantSize->getZExtValue(), Align, isVol,
  5518. false, DstPtrInfo, SrcPtrInfo);
  5519. if (Result.getNode())
  5520. return Result;
  5521. }
  5522. // Then check to see if we should lower the memmove with target-specific
  5523. // code. If the target chooses to do this, this is the next best.
  5524. if (TSI) {
  5525. SDValue Result = TSI->EmitTargetCodeForMemmove(
  5526. *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo, SrcPtrInfo);
  5527. if (Result.getNode())
  5528. return Result;
  5529. }
  5530. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  5531. checkAddrSpaceIsValidForLibcall(TLI, SrcPtrInfo.getAddrSpace());
  5532. // FIXME: If the memmove is volatile, lowering it to plain libc memmove may
  5533. // not be safe. See memcpy above for more details.
  5534. // Emit a library call.
  5535. TargetLowering::ArgListTy Args;
  5536. TargetLowering::ArgListEntry Entry;
  5537. Entry.Ty = Type::getInt8PtrTy(*getContext());
  5538. Entry.Node = Dst; Args.push_back(Entry);
  5539. Entry.Node = Src; Args.push_back(Entry);
  5540. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5541. Entry.Node = Size; Args.push_back(Entry);
  5542. // FIXME: pass in SDLoc
  5543. TargetLowering::CallLoweringInfo CLI(*this);
  5544. CLI.setDebugLoc(dl)
  5545. .setChain(Chain)
  5546. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMMOVE),
  5547. Dst.getValueType().getTypeForEVT(*getContext()),
  5548. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMMOVE),
  5549. TLI->getPointerTy(getDataLayout())),
  5550. std::move(Args))
  5551. .setDiscardResult()
  5552. .setTailCall(isTailCall);
  5553. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  5554. return CallResult.second;
  5555. }
  5556. SDValue SelectionDAG::getAtomicMemmove(SDValue Chain, const SDLoc &dl,
  5557. SDValue Dst, unsigned DstAlign,
  5558. SDValue Src, unsigned SrcAlign,
  5559. SDValue Size, Type *SizeTy,
  5560. unsigned ElemSz, bool isTailCall,
  5561. MachinePointerInfo DstPtrInfo,
  5562. MachinePointerInfo SrcPtrInfo) {
  5563. // Emit a library call.
  5564. TargetLowering::ArgListTy Args;
  5565. TargetLowering::ArgListEntry Entry;
  5566. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5567. Entry.Node = Dst;
  5568. Args.push_back(Entry);
  5569. Entry.Node = Src;
  5570. Args.push_back(Entry);
  5571. Entry.Ty = SizeTy;
  5572. Entry.Node = Size;
  5573. Args.push_back(Entry);
  5574. RTLIB::Libcall LibraryCall =
  5575. RTLIB::getMEMMOVE_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  5576. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  5577. report_fatal_error("Unsupported element size");
  5578. TargetLowering::CallLoweringInfo CLI(*this);
  5579. CLI.setDebugLoc(dl)
  5580. .setChain(Chain)
  5581. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  5582. Type::getVoidTy(*getContext()),
  5583. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  5584. TLI->getPointerTy(getDataLayout())),
  5585. std::move(Args))
  5586. .setDiscardResult()
  5587. .setTailCall(isTailCall);
  5588. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  5589. return CallResult.second;
  5590. }
  5591. SDValue SelectionDAG::getMemset(SDValue Chain, const SDLoc &dl, SDValue Dst,
  5592. SDValue Src, SDValue Size, unsigned Align,
  5593. bool isVol, bool isTailCall,
  5594. MachinePointerInfo DstPtrInfo) {
  5595. assert(Align && "The SDAG layer expects explicit alignment and reserves 0");
  5596. // Check to see if we should lower the memset to stores first.
  5597. // For cases within the target-specified limits, this is the best choice.
  5598. ConstantSDNode *ConstantSize = dyn_cast<ConstantSDNode>(Size);
  5599. if (ConstantSize) {
  5600. // Memset with size zero? Just return the original chain.
  5601. if (ConstantSize->isNullValue())
  5602. return Chain;
  5603. SDValue Result =
  5604. getMemsetStores(*this, dl, Chain, Dst, Src, ConstantSize->getZExtValue(),
  5605. Align, isVol, DstPtrInfo);
  5606. if (Result.getNode())
  5607. return Result;
  5608. }
  5609. // Then check to see if we should lower the memset with target-specific
  5610. // code. If the target chooses to do this, this is the next best.
  5611. if (TSI) {
  5612. SDValue Result = TSI->EmitTargetCodeForMemset(
  5613. *this, dl, Chain, Dst, Src, Size, Align, isVol, DstPtrInfo);
  5614. if (Result.getNode())
  5615. return Result;
  5616. }
  5617. checkAddrSpaceIsValidForLibcall(TLI, DstPtrInfo.getAddrSpace());
  5618. // Emit a library call.
  5619. TargetLowering::ArgListTy Args;
  5620. TargetLowering::ArgListEntry Entry;
  5621. Entry.Node = Dst; Entry.Ty = Type::getInt8PtrTy(*getContext());
  5622. Args.push_back(Entry);
  5623. Entry.Node = Src;
  5624. Entry.Ty = Src.getValueType().getTypeForEVT(*getContext());
  5625. Args.push_back(Entry);
  5626. Entry.Node = Size;
  5627. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5628. Args.push_back(Entry);
  5629. // FIXME: pass in SDLoc
  5630. TargetLowering::CallLoweringInfo CLI(*this);
  5631. CLI.setDebugLoc(dl)
  5632. .setChain(Chain)
  5633. .setLibCallee(TLI->getLibcallCallingConv(RTLIB::MEMSET),
  5634. Dst.getValueType().getTypeForEVT(*getContext()),
  5635. getExternalSymbol(TLI->getLibcallName(RTLIB::MEMSET),
  5636. TLI->getPointerTy(getDataLayout())),
  5637. std::move(Args))
  5638. .setDiscardResult()
  5639. .setTailCall(isTailCall);
  5640. std::pair<SDValue,SDValue> CallResult = TLI->LowerCallTo(CLI);
  5641. return CallResult.second;
  5642. }
  5643. SDValue SelectionDAG::getAtomicMemset(SDValue Chain, const SDLoc &dl,
  5644. SDValue Dst, unsigned DstAlign,
  5645. SDValue Value, SDValue Size, Type *SizeTy,
  5646. unsigned ElemSz, bool isTailCall,
  5647. MachinePointerInfo DstPtrInfo) {
  5648. // Emit a library call.
  5649. TargetLowering::ArgListTy Args;
  5650. TargetLowering::ArgListEntry Entry;
  5651. Entry.Ty = getDataLayout().getIntPtrType(*getContext());
  5652. Entry.Node = Dst;
  5653. Args.push_back(Entry);
  5654. Entry.Ty = Type::getInt8Ty(*getContext());
  5655. Entry.Node = Value;
  5656. Args.push_back(Entry);
  5657. Entry.Ty = SizeTy;
  5658. Entry.Node = Size;
  5659. Args.push_back(Entry);
  5660. RTLIB::Libcall LibraryCall =
  5661. RTLIB::getMEMSET_ELEMENT_UNORDERED_ATOMIC(ElemSz);
  5662. if (LibraryCall == RTLIB::UNKNOWN_LIBCALL)
  5663. report_fatal_error("Unsupported element size");
  5664. TargetLowering::CallLoweringInfo CLI(*this);
  5665. CLI.setDebugLoc(dl)
  5666. .setChain(Chain)
  5667. .setLibCallee(TLI->getLibcallCallingConv(LibraryCall),
  5668. Type::getVoidTy(*getContext()),
  5669. getExternalSymbol(TLI->getLibcallName(LibraryCall),
  5670. TLI->getPointerTy(getDataLayout())),
  5671. std::move(Args))
  5672. .setDiscardResult()
  5673. .setTailCall(isTailCall);
  5674. std::pair<SDValue, SDValue> CallResult = TLI->LowerCallTo(CLI);
  5675. return CallResult.second;
  5676. }
  5677. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  5678. SDVTList VTList, ArrayRef<SDValue> Ops,
  5679. MachineMemOperand *MMO) {
  5680. FoldingSetNodeID ID;
  5681. ID.AddInteger(MemVT.getRawBits());
  5682. AddNodeIDNode(ID, Opcode, VTList, Ops);
  5683. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  5684. void* IP = nullptr;
  5685. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  5686. cast<AtomicSDNode>(E)->refineAlignment(MMO);
  5687. return SDValue(E, 0);
  5688. }
  5689. auto *N = newSDNode<AtomicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  5690. VTList, MemVT, MMO);
  5691. createOperands(N, Ops);
  5692. CSEMap.InsertNode(N, IP);
  5693. InsertNode(N);
  5694. return SDValue(N, 0);
  5695. }
  5696. SDValue SelectionDAG::getAtomicCmpSwap(unsigned Opcode, const SDLoc &dl,
  5697. EVT MemVT, SDVTList VTs, SDValue Chain,
  5698. SDValue Ptr, SDValue Cmp, SDValue Swp,
  5699. MachineMemOperand *MMO) {
  5700. assert(Opcode == ISD::ATOMIC_CMP_SWAP ||
  5701. Opcode == ISD::ATOMIC_CMP_SWAP_WITH_SUCCESS);
  5702. assert(Cmp.getValueType() == Swp.getValueType() && "Invalid Atomic Op Types");
  5703. SDValue Ops[] = {Chain, Ptr, Cmp, Swp};
  5704. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  5705. }
  5706. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  5707. SDValue Chain, SDValue Ptr, SDValue Val,
  5708. MachineMemOperand *MMO) {
  5709. assert((Opcode == ISD::ATOMIC_LOAD_ADD ||
  5710. Opcode == ISD::ATOMIC_LOAD_SUB ||
  5711. Opcode == ISD::ATOMIC_LOAD_AND ||
  5712. Opcode == ISD::ATOMIC_LOAD_CLR ||
  5713. Opcode == ISD::ATOMIC_LOAD_OR ||
  5714. Opcode == ISD::ATOMIC_LOAD_XOR ||
  5715. Opcode == ISD::ATOMIC_LOAD_NAND ||
  5716. Opcode == ISD::ATOMIC_LOAD_MIN ||
  5717. Opcode == ISD::ATOMIC_LOAD_MAX ||
  5718. Opcode == ISD::ATOMIC_LOAD_UMIN ||
  5719. Opcode == ISD::ATOMIC_LOAD_UMAX ||
  5720. Opcode == ISD::ATOMIC_LOAD_FADD ||
  5721. Opcode == ISD::ATOMIC_LOAD_FSUB ||
  5722. Opcode == ISD::ATOMIC_SWAP ||
  5723. Opcode == ISD::ATOMIC_STORE) &&
  5724. "Invalid Atomic Op");
  5725. EVT VT = Val.getValueType();
  5726. SDVTList VTs = Opcode == ISD::ATOMIC_STORE ? getVTList(MVT::Other) :
  5727. getVTList(VT, MVT::Other);
  5728. SDValue Ops[] = {Chain, Ptr, Val};
  5729. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  5730. }
  5731. SDValue SelectionDAG::getAtomic(unsigned Opcode, const SDLoc &dl, EVT MemVT,
  5732. EVT VT, SDValue Chain, SDValue Ptr,
  5733. MachineMemOperand *MMO) {
  5734. assert(Opcode == ISD::ATOMIC_LOAD && "Invalid Atomic Op");
  5735. SDVTList VTs = getVTList(VT, MVT::Other);
  5736. SDValue Ops[] = {Chain, Ptr};
  5737. return getAtomic(Opcode, dl, MemVT, VTs, Ops, MMO);
  5738. }
  5739. /// getMergeValues - Create a MERGE_VALUES node from the given operands.
  5740. SDValue SelectionDAG::getMergeValues(ArrayRef<SDValue> Ops, const SDLoc &dl) {
  5741. if (Ops.size() == 1)
  5742. return Ops[0];
  5743. SmallVector<EVT, 4> VTs;
  5744. VTs.reserve(Ops.size());
  5745. for (unsigned i = 0; i < Ops.size(); ++i)
  5746. VTs.push_back(Ops[i].getValueType());
  5747. return getNode(ISD::MERGE_VALUES, dl, getVTList(VTs), Ops);
  5748. }
  5749. SDValue SelectionDAG::getMemIntrinsicNode(
  5750. unsigned Opcode, const SDLoc &dl, SDVTList VTList, ArrayRef<SDValue> Ops,
  5751. EVT MemVT, MachinePointerInfo PtrInfo, unsigned Align,
  5752. MachineMemOperand::Flags Flags, unsigned Size) {
  5753. if (Align == 0) // Ensure that codegen never sees alignment 0
  5754. Align = getEVTAlignment(MemVT);
  5755. if (!Size)
  5756. Size = MemVT.getStoreSize();
  5757. MachineFunction &MF = getMachineFunction();
  5758. MachineMemOperand *MMO =
  5759. MF.getMachineMemOperand(PtrInfo, Flags, Size, Align);
  5760. return getMemIntrinsicNode(Opcode, dl, VTList, Ops, MemVT, MMO);
  5761. }
  5762. SDValue SelectionDAG::getMemIntrinsicNode(unsigned Opcode, const SDLoc &dl,
  5763. SDVTList VTList,
  5764. ArrayRef<SDValue> Ops, EVT MemVT,
  5765. MachineMemOperand *MMO) {
  5766. assert((Opcode == ISD::INTRINSIC_VOID ||
  5767. Opcode == ISD::INTRINSIC_W_CHAIN ||
  5768. Opcode == ISD::PREFETCH ||
  5769. Opcode == ISD::LIFETIME_START ||
  5770. Opcode == ISD::LIFETIME_END ||
  5771. ((int)Opcode <= std::numeric_limits<int>::max() &&
  5772. (int)Opcode >= ISD::FIRST_TARGET_MEMORY_OPCODE)) &&
  5773. "Opcode is not a memory-accessing opcode!");
  5774. // Memoize the node unless it returns a flag.
  5775. MemIntrinsicSDNode *N;
  5776. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  5777. FoldingSetNodeID ID;
  5778. AddNodeIDNode(ID, Opcode, VTList, Ops);
  5779. ID.AddInteger(getSyntheticNodeSubclassData<MemIntrinsicSDNode>(
  5780. Opcode, dl.getIROrder(), VTList, MemVT, MMO));
  5781. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  5782. void *IP = nullptr;
  5783. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  5784. cast<MemIntrinsicSDNode>(E)->refineAlignment(MMO);
  5785. return SDValue(E, 0);
  5786. }
  5787. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  5788. VTList, MemVT, MMO);
  5789. createOperands(N, Ops);
  5790. CSEMap.InsertNode(N, IP);
  5791. } else {
  5792. N = newSDNode<MemIntrinsicSDNode>(Opcode, dl.getIROrder(), dl.getDebugLoc(),
  5793. VTList, MemVT, MMO);
  5794. createOperands(N, Ops);
  5795. }
  5796. InsertNode(N);
  5797. return SDValue(N, 0);
  5798. }
  5799. SDValue SelectionDAG::getLifetimeNode(bool IsStart, const SDLoc &dl,
  5800. SDValue Chain, int FrameIndex,
  5801. int64_t Size, int64_t Offset) {
  5802. const unsigned Opcode = IsStart ? ISD::LIFETIME_START : ISD::LIFETIME_END;
  5803. const auto VTs = getVTList(MVT::Other);
  5804. SDValue Ops[2] = {
  5805. Chain,
  5806. getFrameIndex(FrameIndex,
  5807. getTargetLoweringInfo().getFrameIndexTy(getDataLayout()),
  5808. true)};
  5809. FoldingSetNodeID ID;
  5810. AddNodeIDNode(ID, Opcode, VTs, Ops);
  5811. ID.AddInteger(FrameIndex);
  5812. ID.AddInteger(Size);
  5813. ID.AddInteger(Offset);
  5814. void *IP = nullptr;
  5815. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  5816. return SDValue(E, 0);
  5817. LifetimeSDNode *N = newSDNode<LifetimeSDNode>(
  5818. Opcode, dl.getIROrder(), dl.getDebugLoc(), VTs, Size, Offset);
  5819. createOperands(N, Ops);
  5820. CSEMap.InsertNode(N, IP);
  5821. InsertNode(N);
  5822. SDValue V(N, 0);
  5823. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5824. return V;
  5825. }
  5826. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  5827. /// MachinePointerInfo record from it. This is particularly useful because the
  5828. /// code generator has many cases where it doesn't bother passing in a
  5829. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  5830. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  5831. SelectionDAG &DAG, SDValue Ptr,
  5832. int64_t Offset = 0) {
  5833. // If this is FI+Offset, we can model it.
  5834. if (const FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr))
  5835. return MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
  5836. FI->getIndex(), Offset);
  5837. // If this is (FI+Offset1)+Offset2, we can model it.
  5838. if (Ptr.getOpcode() != ISD::ADD ||
  5839. !isa<ConstantSDNode>(Ptr.getOperand(1)) ||
  5840. !isa<FrameIndexSDNode>(Ptr.getOperand(0)))
  5841. return Info;
  5842. int FI = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  5843. return MachinePointerInfo::getFixedStack(
  5844. DAG.getMachineFunction(), FI,
  5845. Offset + cast<ConstantSDNode>(Ptr.getOperand(1))->getSExtValue());
  5846. }
  5847. /// InferPointerInfo - If the specified ptr/offset is a frame index, infer a
  5848. /// MachinePointerInfo record from it. This is particularly useful because the
  5849. /// code generator has many cases where it doesn't bother passing in a
  5850. /// MachinePointerInfo to getLoad or getStore when it has "FI+Cst".
  5851. static MachinePointerInfo InferPointerInfo(const MachinePointerInfo &Info,
  5852. SelectionDAG &DAG, SDValue Ptr,
  5853. SDValue OffsetOp) {
  5854. // If the 'Offset' value isn't a constant, we can't handle this.
  5855. if (ConstantSDNode *OffsetNode = dyn_cast<ConstantSDNode>(OffsetOp))
  5856. return InferPointerInfo(Info, DAG, Ptr, OffsetNode->getSExtValue());
  5857. if (OffsetOp.isUndef())
  5858. return InferPointerInfo(Info, DAG, Ptr);
  5859. return Info;
  5860. }
  5861. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  5862. EVT VT, const SDLoc &dl, SDValue Chain,
  5863. SDValue Ptr, SDValue Offset,
  5864. MachinePointerInfo PtrInfo, EVT MemVT,
  5865. unsigned Alignment,
  5866. MachineMemOperand::Flags MMOFlags,
  5867. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  5868. assert(Chain.getValueType() == MVT::Other &&
  5869. "Invalid chain type");
  5870. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  5871. Alignment = getEVTAlignment(MemVT);
  5872. MMOFlags |= MachineMemOperand::MOLoad;
  5873. assert((MMOFlags & MachineMemOperand::MOStore) == 0);
  5874. // If we don't have a PtrInfo, infer the trivial frame index case to simplify
  5875. // clients.
  5876. if (PtrInfo.V.isNull())
  5877. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr, Offset);
  5878. MachineFunction &MF = getMachineFunction();
  5879. MachineMemOperand *MMO = MF.getMachineMemOperand(
  5880. PtrInfo, MMOFlags, MemVT.getStoreSize(), Alignment, AAInfo, Ranges);
  5881. return getLoad(AM, ExtType, VT, dl, Chain, Ptr, Offset, MemVT, MMO);
  5882. }
  5883. SDValue SelectionDAG::getLoad(ISD::MemIndexedMode AM, ISD::LoadExtType ExtType,
  5884. EVT VT, const SDLoc &dl, SDValue Chain,
  5885. SDValue Ptr, SDValue Offset, EVT MemVT,
  5886. MachineMemOperand *MMO) {
  5887. if (VT == MemVT) {
  5888. ExtType = ISD::NON_EXTLOAD;
  5889. } else if (ExtType == ISD::NON_EXTLOAD) {
  5890. assert(VT == MemVT && "Non-extending load from different memory type!");
  5891. } else {
  5892. // Extending load.
  5893. assert(MemVT.getScalarType().bitsLT(VT.getScalarType()) &&
  5894. "Should only be an extending load, not truncating!");
  5895. assert(VT.isInteger() == MemVT.isInteger() &&
  5896. "Cannot convert from FP to Int or Int -> FP!");
  5897. assert(VT.isVector() == MemVT.isVector() &&
  5898. "Cannot use an ext load to convert to or from a vector!");
  5899. assert((!VT.isVector() ||
  5900. VT.getVectorNumElements() == MemVT.getVectorNumElements()) &&
  5901. "Cannot use an ext load to change the number of vector elements!");
  5902. }
  5903. bool Indexed = AM != ISD::UNINDEXED;
  5904. assert((Indexed || Offset.isUndef()) && "Unindexed load with an offset!");
  5905. SDVTList VTs = Indexed ?
  5906. getVTList(VT, Ptr.getValueType(), MVT::Other) : getVTList(VT, MVT::Other);
  5907. SDValue Ops[] = { Chain, Ptr, Offset };
  5908. FoldingSetNodeID ID;
  5909. AddNodeIDNode(ID, ISD::LOAD, VTs, Ops);
  5910. ID.AddInteger(MemVT.getRawBits());
  5911. ID.AddInteger(getSyntheticNodeSubclassData<LoadSDNode>(
  5912. dl.getIROrder(), VTs, AM, ExtType, MemVT, MMO));
  5913. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  5914. void *IP = nullptr;
  5915. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  5916. cast<LoadSDNode>(E)->refineAlignment(MMO);
  5917. return SDValue(E, 0);
  5918. }
  5919. auto *N = newSDNode<LoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  5920. ExtType, MemVT, MMO);
  5921. createOperands(N, Ops);
  5922. CSEMap.InsertNode(N, IP);
  5923. InsertNode(N);
  5924. SDValue V(N, 0);
  5925. NewSDValueDbgMsg(V, "Creating new node: ", this);
  5926. return V;
  5927. }
  5928. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  5929. SDValue Ptr, MachinePointerInfo PtrInfo,
  5930. unsigned Alignment,
  5931. MachineMemOperand::Flags MMOFlags,
  5932. const AAMDNodes &AAInfo, const MDNode *Ranges) {
  5933. SDValue Undef = getUNDEF(Ptr.getValueType());
  5934. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  5935. PtrInfo, VT, Alignment, MMOFlags, AAInfo, Ranges);
  5936. }
  5937. SDValue SelectionDAG::getLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  5938. SDValue Ptr, MachineMemOperand *MMO) {
  5939. SDValue Undef = getUNDEF(Ptr.getValueType());
  5940. return getLoad(ISD::UNINDEXED, ISD::NON_EXTLOAD, VT, dl, Chain, Ptr, Undef,
  5941. VT, MMO);
  5942. }
  5943. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  5944. EVT VT, SDValue Chain, SDValue Ptr,
  5945. MachinePointerInfo PtrInfo, EVT MemVT,
  5946. unsigned Alignment,
  5947. MachineMemOperand::Flags MMOFlags,
  5948. const AAMDNodes &AAInfo) {
  5949. SDValue Undef = getUNDEF(Ptr.getValueType());
  5950. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef, PtrInfo,
  5951. MemVT, Alignment, MMOFlags, AAInfo);
  5952. }
  5953. SDValue SelectionDAG::getExtLoad(ISD::LoadExtType ExtType, const SDLoc &dl,
  5954. EVT VT, SDValue Chain, SDValue Ptr, EVT MemVT,
  5955. MachineMemOperand *MMO) {
  5956. SDValue Undef = getUNDEF(Ptr.getValueType());
  5957. return getLoad(ISD::UNINDEXED, ExtType, VT, dl, Chain, Ptr, Undef,
  5958. MemVT, MMO);
  5959. }
  5960. SDValue SelectionDAG::getIndexedLoad(SDValue OrigLoad, const SDLoc &dl,
  5961. SDValue Base, SDValue Offset,
  5962. ISD::MemIndexedMode AM) {
  5963. LoadSDNode *LD = cast<LoadSDNode>(OrigLoad);
  5964. assert(LD->getOffset().isUndef() && "Load is already a indexed load!");
  5965. // Don't propagate the invariant or dereferenceable flags.
  5966. auto MMOFlags =
  5967. LD->getMemOperand()->getFlags() &
  5968. ~(MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  5969. return getLoad(AM, LD->getExtensionType(), OrigLoad.getValueType(), dl,
  5970. LD->getChain(), Base, Offset, LD->getPointerInfo(),
  5971. LD->getMemoryVT(), LD->getAlignment(), MMOFlags,
  5972. LD->getAAInfo());
  5973. }
  5974. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  5975. SDValue Ptr, MachinePointerInfo PtrInfo,
  5976. unsigned Alignment,
  5977. MachineMemOperand::Flags MMOFlags,
  5978. const AAMDNodes &AAInfo) {
  5979. assert(Chain.getValueType() == MVT::Other && "Invalid chain type");
  5980. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  5981. Alignment = getEVTAlignment(Val.getValueType());
  5982. MMOFlags |= MachineMemOperand::MOStore;
  5983. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  5984. if (PtrInfo.V.isNull())
  5985. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  5986. MachineFunction &MF = getMachineFunction();
  5987. MachineMemOperand *MMO = MF.getMachineMemOperand(
  5988. PtrInfo, MMOFlags, Val.getValueType().getStoreSize(), Alignment, AAInfo);
  5989. return getStore(Chain, dl, Val, Ptr, MMO);
  5990. }
  5991. SDValue SelectionDAG::getStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  5992. SDValue Ptr, MachineMemOperand *MMO) {
  5993. assert(Chain.getValueType() == MVT::Other &&
  5994. "Invalid chain type");
  5995. EVT VT = Val.getValueType();
  5996. SDVTList VTs = getVTList(MVT::Other);
  5997. SDValue Undef = getUNDEF(Ptr.getValueType());
  5998. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  5999. FoldingSetNodeID ID;
  6000. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6001. ID.AddInteger(VT.getRawBits());
  6002. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  6003. dl.getIROrder(), VTs, ISD::UNINDEXED, false, VT, MMO));
  6004. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6005. void *IP = nullptr;
  6006. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6007. cast<StoreSDNode>(E)->refineAlignment(MMO);
  6008. return SDValue(E, 0);
  6009. }
  6010. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6011. ISD::UNINDEXED, false, VT, MMO);
  6012. createOperands(N, Ops);
  6013. CSEMap.InsertNode(N, IP);
  6014. InsertNode(N);
  6015. SDValue V(N, 0);
  6016. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6017. return V;
  6018. }
  6019. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6020. SDValue Ptr, MachinePointerInfo PtrInfo,
  6021. EVT SVT, unsigned Alignment,
  6022. MachineMemOperand::Flags MMOFlags,
  6023. const AAMDNodes &AAInfo) {
  6024. assert(Chain.getValueType() == MVT::Other &&
  6025. "Invalid chain type");
  6026. if (Alignment == 0) // Ensure that codegen never sees alignment 0
  6027. Alignment = getEVTAlignment(SVT);
  6028. MMOFlags |= MachineMemOperand::MOStore;
  6029. assert((MMOFlags & MachineMemOperand::MOLoad) == 0);
  6030. if (PtrInfo.V.isNull())
  6031. PtrInfo = InferPointerInfo(PtrInfo, *this, Ptr);
  6032. MachineFunction &MF = getMachineFunction();
  6033. MachineMemOperand *MMO = MF.getMachineMemOperand(
  6034. PtrInfo, MMOFlags, SVT.getStoreSize(), Alignment, AAInfo);
  6035. return getTruncStore(Chain, dl, Val, Ptr, SVT, MMO);
  6036. }
  6037. SDValue SelectionDAG::getTruncStore(SDValue Chain, const SDLoc &dl, SDValue Val,
  6038. SDValue Ptr, EVT SVT,
  6039. MachineMemOperand *MMO) {
  6040. EVT VT = Val.getValueType();
  6041. assert(Chain.getValueType() == MVT::Other &&
  6042. "Invalid chain type");
  6043. if (VT == SVT)
  6044. return getStore(Chain, dl, Val, Ptr, MMO);
  6045. assert(SVT.getScalarType().bitsLT(VT.getScalarType()) &&
  6046. "Should only be a truncating store, not extending!");
  6047. assert(VT.isInteger() == SVT.isInteger() &&
  6048. "Can't do FP-INT conversion!");
  6049. assert(VT.isVector() == SVT.isVector() &&
  6050. "Cannot use trunc store to convert to or from a vector!");
  6051. assert((!VT.isVector() ||
  6052. VT.getVectorNumElements() == SVT.getVectorNumElements()) &&
  6053. "Cannot use trunc store to change the number of vector elements!");
  6054. SDVTList VTs = getVTList(MVT::Other);
  6055. SDValue Undef = getUNDEF(Ptr.getValueType());
  6056. SDValue Ops[] = { Chain, Val, Ptr, Undef };
  6057. FoldingSetNodeID ID;
  6058. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6059. ID.AddInteger(SVT.getRawBits());
  6060. ID.AddInteger(getSyntheticNodeSubclassData<StoreSDNode>(
  6061. dl.getIROrder(), VTs, ISD::UNINDEXED, true, SVT, MMO));
  6062. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6063. void *IP = nullptr;
  6064. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6065. cast<StoreSDNode>(E)->refineAlignment(MMO);
  6066. return SDValue(E, 0);
  6067. }
  6068. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6069. ISD::UNINDEXED, true, SVT, MMO);
  6070. createOperands(N, Ops);
  6071. CSEMap.InsertNode(N, IP);
  6072. InsertNode(N);
  6073. SDValue V(N, 0);
  6074. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6075. return V;
  6076. }
  6077. SDValue SelectionDAG::getIndexedStore(SDValue OrigStore, const SDLoc &dl,
  6078. SDValue Base, SDValue Offset,
  6079. ISD::MemIndexedMode AM) {
  6080. StoreSDNode *ST = cast<StoreSDNode>(OrigStore);
  6081. assert(ST->getOffset().isUndef() && "Store is already a indexed store!");
  6082. SDVTList VTs = getVTList(Base.getValueType(), MVT::Other);
  6083. SDValue Ops[] = { ST->getChain(), ST->getValue(), Base, Offset };
  6084. FoldingSetNodeID ID;
  6085. AddNodeIDNode(ID, ISD::STORE, VTs, Ops);
  6086. ID.AddInteger(ST->getMemoryVT().getRawBits());
  6087. ID.AddInteger(ST->getRawSubclassData());
  6088. ID.AddInteger(ST->getPointerInfo().getAddrSpace());
  6089. void *IP = nullptr;
  6090. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP))
  6091. return SDValue(E, 0);
  6092. auto *N = newSDNode<StoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs, AM,
  6093. ST->isTruncatingStore(), ST->getMemoryVT(),
  6094. ST->getMemOperand());
  6095. createOperands(N, Ops);
  6096. CSEMap.InsertNode(N, IP);
  6097. InsertNode(N);
  6098. SDValue V(N, 0);
  6099. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6100. return V;
  6101. }
  6102. SDValue SelectionDAG::getMaskedLoad(EVT VT, const SDLoc &dl, SDValue Chain,
  6103. SDValue Ptr, SDValue Mask, SDValue PassThru,
  6104. EVT MemVT, MachineMemOperand *MMO,
  6105. ISD::LoadExtType ExtTy, bool isExpanding) {
  6106. SDVTList VTs = getVTList(VT, MVT::Other);
  6107. SDValue Ops[] = { Chain, Ptr, Mask, PassThru };
  6108. FoldingSetNodeID ID;
  6109. AddNodeIDNode(ID, ISD::MLOAD, VTs, Ops);
  6110. ID.AddInteger(VT.getRawBits());
  6111. ID.AddInteger(getSyntheticNodeSubclassData<MaskedLoadSDNode>(
  6112. dl.getIROrder(), VTs, ExtTy, isExpanding, MemVT, MMO));
  6113. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6114. void *IP = nullptr;
  6115. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6116. cast<MaskedLoadSDNode>(E)->refineAlignment(MMO);
  6117. return SDValue(E, 0);
  6118. }
  6119. auto *N = newSDNode<MaskedLoadSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6120. ExtTy, isExpanding, MemVT, MMO);
  6121. createOperands(N, Ops);
  6122. CSEMap.InsertNode(N, IP);
  6123. InsertNode(N);
  6124. SDValue V(N, 0);
  6125. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6126. return V;
  6127. }
  6128. SDValue SelectionDAG::getMaskedStore(SDValue Chain, const SDLoc &dl,
  6129. SDValue Val, SDValue Ptr, SDValue Mask,
  6130. EVT MemVT, MachineMemOperand *MMO,
  6131. bool IsTruncating, bool IsCompressing) {
  6132. assert(Chain.getValueType() == MVT::Other &&
  6133. "Invalid chain type");
  6134. EVT VT = Val.getValueType();
  6135. SDVTList VTs = getVTList(MVT::Other);
  6136. SDValue Ops[] = { Chain, Val, Ptr, Mask };
  6137. FoldingSetNodeID ID;
  6138. AddNodeIDNode(ID, ISD::MSTORE, VTs, Ops);
  6139. ID.AddInteger(VT.getRawBits());
  6140. ID.AddInteger(getSyntheticNodeSubclassData<MaskedStoreSDNode>(
  6141. dl.getIROrder(), VTs, IsTruncating, IsCompressing, MemVT, MMO));
  6142. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6143. void *IP = nullptr;
  6144. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6145. cast<MaskedStoreSDNode>(E)->refineAlignment(MMO);
  6146. return SDValue(E, 0);
  6147. }
  6148. auto *N = newSDNode<MaskedStoreSDNode>(dl.getIROrder(), dl.getDebugLoc(), VTs,
  6149. IsTruncating, IsCompressing, MemVT, MMO);
  6150. createOperands(N, Ops);
  6151. CSEMap.InsertNode(N, IP);
  6152. InsertNode(N);
  6153. SDValue V(N, 0);
  6154. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6155. return V;
  6156. }
  6157. SDValue SelectionDAG::getMaskedGather(SDVTList VTs, EVT VT, const SDLoc &dl,
  6158. ArrayRef<SDValue> Ops,
  6159. MachineMemOperand *MMO) {
  6160. assert(Ops.size() == 6 && "Incompatible number of operands");
  6161. FoldingSetNodeID ID;
  6162. AddNodeIDNode(ID, ISD::MGATHER, VTs, Ops);
  6163. ID.AddInteger(VT.getRawBits());
  6164. ID.AddInteger(getSyntheticNodeSubclassData<MaskedGatherSDNode>(
  6165. dl.getIROrder(), VTs, VT, MMO));
  6166. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6167. void *IP = nullptr;
  6168. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6169. cast<MaskedGatherSDNode>(E)->refineAlignment(MMO);
  6170. return SDValue(E, 0);
  6171. }
  6172. auto *N = newSDNode<MaskedGatherSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  6173. VTs, VT, MMO);
  6174. createOperands(N, Ops);
  6175. assert(N->getPassThru().getValueType() == N->getValueType(0) &&
  6176. "Incompatible type of the PassThru value in MaskedGatherSDNode");
  6177. assert(N->getMask().getValueType().getVectorNumElements() ==
  6178. N->getValueType(0).getVectorNumElements() &&
  6179. "Vector width mismatch between mask and data");
  6180. assert(N->getIndex().getValueType().getVectorNumElements() >=
  6181. N->getValueType(0).getVectorNumElements() &&
  6182. "Vector width mismatch between index and data");
  6183. assert(isa<ConstantSDNode>(N->getScale()) &&
  6184. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  6185. "Scale should be a constant power of 2");
  6186. CSEMap.InsertNode(N, IP);
  6187. InsertNode(N);
  6188. SDValue V(N, 0);
  6189. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6190. return V;
  6191. }
  6192. SDValue SelectionDAG::getMaskedScatter(SDVTList VTs, EVT VT, const SDLoc &dl,
  6193. ArrayRef<SDValue> Ops,
  6194. MachineMemOperand *MMO) {
  6195. assert(Ops.size() == 6 && "Incompatible number of operands");
  6196. FoldingSetNodeID ID;
  6197. AddNodeIDNode(ID, ISD::MSCATTER, VTs, Ops);
  6198. ID.AddInteger(VT.getRawBits());
  6199. ID.AddInteger(getSyntheticNodeSubclassData<MaskedScatterSDNode>(
  6200. dl.getIROrder(), VTs, VT, MMO));
  6201. ID.AddInteger(MMO->getPointerInfo().getAddrSpace());
  6202. void *IP = nullptr;
  6203. if (SDNode *E = FindNodeOrInsertPos(ID, dl, IP)) {
  6204. cast<MaskedScatterSDNode>(E)->refineAlignment(MMO);
  6205. return SDValue(E, 0);
  6206. }
  6207. auto *N = newSDNode<MaskedScatterSDNode>(dl.getIROrder(), dl.getDebugLoc(),
  6208. VTs, VT, MMO);
  6209. createOperands(N, Ops);
  6210. assert(N->getMask().getValueType().getVectorNumElements() ==
  6211. N->getValue().getValueType().getVectorNumElements() &&
  6212. "Vector width mismatch between mask and data");
  6213. assert(N->getIndex().getValueType().getVectorNumElements() >=
  6214. N->getValue().getValueType().getVectorNumElements() &&
  6215. "Vector width mismatch between index and data");
  6216. assert(isa<ConstantSDNode>(N->getScale()) &&
  6217. cast<ConstantSDNode>(N->getScale())->getAPIntValue().isPowerOf2() &&
  6218. "Scale should be a constant power of 2");
  6219. CSEMap.InsertNode(N, IP);
  6220. InsertNode(N);
  6221. SDValue V(N, 0);
  6222. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6223. return V;
  6224. }
  6225. SDValue SelectionDAG::simplifySelect(SDValue Cond, SDValue T, SDValue F) {
  6226. // select undef, T, F --> T (if T is a constant), otherwise F
  6227. // select, ?, undef, F --> F
  6228. // select, ?, T, undef --> T
  6229. if (Cond.isUndef())
  6230. return isConstantValueOfAnyType(T) ? T : F;
  6231. if (T.isUndef())
  6232. return F;
  6233. if (F.isUndef())
  6234. return T;
  6235. // select true, T, F --> T
  6236. // select false, T, F --> F
  6237. if (auto *CondC = dyn_cast<ConstantSDNode>(Cond))
  6238. return CondC->isNullValue() ? F : T;
  6239. // TODO: This should simplify VSELECT with constant condition using something
  6240. // like this (but check boolean contents to be complete?):
  6241. // if (ISD::isBuildVectorAllOnes(Cond.getNode()))
  6242. // return T;
  6243. // if (ISD::isBuildVectorAllZeros(Cond.getNode()))
  6244. // return F;
  6245. // select ?, T, T --> T
  6246. if (T == F)
  6247. return T;
  6248. return SDValue();
  6249. }
  6250. SDValue SelectionDAG::simplifyShift(SDValue X, SDValue Y) {
  6251. // shift undef, Y --> 0 (can always assume that the undef value is 0)
  6252. if (X.isUndef())
  6253. return getConstant(0, SDLoc(X.getNode()), X.getValueType());
  6254. // shift X, undef --> undef (because it may shift by the bitwidth)
  6255. if (Y.isUndef())
  6256. return getUNDEF(X.getValueType());
  6257. // shift 0, Y --> 0
  6258. // shift X, 0 --> X
  6259. if (isNullOrNullSplat(X) || isNullOrNullSplat(Y))
  6260. return X;
  6261. // shift X, C >= bitwidth(X) --> undef
  6262. // All vector elements must be too big (or undef) to avoid partial undefs.
  6263. auto isShiftTooBig = [X](ConstantSDNode *Val) {
  6264. return !Val || Val->getAPIntValue().uge(X.getScalarValueSizeInBits());
  6265. };
  6266. if (ISD::matchUnaryPredicate(Y, isShiftTooBig, true))
  6267. return getUNDEF(X.getValueType());
  6268. return SDValue();
  6269. }
  6270. // TODO: Use fast-math-flags to enable more simplifications.
  6271. SDValue SelectionDAG::simplifyFPBinop(unsigned Opcode, SDValue X, SDValue Y) {
  6272. ConstantFPSDNode *YC = isConstOrConstSplatFP(Y, /* AllowUndefs */ true);
  6273. if (!YC)
  6274. return SDValue();
  6275. // X + -0.0 --> X
  6276. if (Opcode == ISD::FADD)
  6277. if (YC->getValueAPF().isNegZero())
  6278. return X;
  6279. // X - +0.0 --> X
  6280. if (Opcode == ISD::FSUB)
  6281. if (YC->getValueAPF().isPosZero())
  6282. return X;
  6283. // X * 1.0 --> X
  6284. // X / 1.0 --> X
  6285. if (Opcode == ISD::FMUL || Opcode == ISD::FDIV)
  6286. if (YC->getValueAPF().isExactlyValue(1.0))
  6287. return X;
  6288. return SDValue();
  6289. }
  6290. SDValue SelectionDAG::getVAArg(EVT VT, const SDLoc &dl, SDValue Chain,
  6291. SDValue Ptr, SDValue SV, unsigned Align) {
  6292. SDValue Ops[] = { Chain, Ptr, SV, getTargetConstant(Align, dl, MVT::i32) };
  6293. return getNode(ISD::VAARG, dl, getVTList(VT, MVT::Other), Ops);
  6294. }
  6295. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6296. ArrayRef<SDUse> Ops) {
  6297. switch (Ops.size()) {
  6298. case 0: return getNode(Opcode, DL, VT);
  6299. case 1: return getNode(Opcode, DL, VT, static_cast<const SDValue>(Ops[0]));
  6300. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1]);
  6301. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2]);
  6302. default: break;
  6303. }
  6304. // Copy from an SDUse array into an SDValue array for use with
  6305. // the regular getNode logic.
  6306. SmallVector<SDValue, 8> NewOps(Ops.begin(), Ops.end());
  6307. return getNode(Opcode, DL, VT, NewOps);
  6308. }
  6309. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, EVT VT,
  6310. ArrayRef<SDValue> Ops, const SDNodeFlags Flags) {
  6311. unsigned NumOps = Ops.size();
  6312. switch (NumOps) {
  6313. case 0: return getNode(Opcode, DL, VT);
  6314. case 1: return getNode(Opcode, DL, VT, Ops[0], Flags);
  6315. case 2: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Flags);
  6316. case 3: return getNode(Opcode, DL, VT, Ops[0], Ops[1], Ops[2], Flags);
  6317. default: break;
  6318. }
  6319. switch (Opcode) {
  6320. default: break;
  6321. case ISD::BUILD_VECTOR:
  6322. // Attempt to simplify BUILD_VECTOR.
  6323. if (SDValue V = FoldBUILD_VECTOR(DL, VT, Ops, *this))
  6324. return V;
  6325. break;
  6326. case ISD::CONCAT_VECTORS:
  6327. // Attempt to fold CONCAT_VECTORS into BUILD_VECTOR or UNDEF.
  6328. if (SDValue V = FoldCONCAT_VECTORS(DL, VT, Ops, *this))
  6329. return V;
  6330. break;
  6331. case ISD::SELECT_CC:
  6332. assert(NumOps == 5 && "SELECT_CC takes 5 operands!");
  6333. assert(Ops[0].getValueType() == Ops[1].getValueType() &&
  6334. "LHS and RHS of condition must have same type!");
  6335. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  6336. "True and False arms of SelectCC must have same type!");
  6337. assert(Ops[2].getValueType() == VT &&
  6338. "select_cc node must be of same type as true and false value!");
  6339. break;
  6340. case ISD::BR_CC:
  6341. assert(NumOps == 5 && "BR_CC takes 5 operands!");
  6342. assert(Ops[2].getValueType() == Ops[3].getValueType() &&
  6343. "LHS/RHS of comparison should match types!");
  6344. break;
  6345. }
  6346. // Memoize nodes.
  6347. SDNode *N;
  6348. SDVTList VTs = getVTList(VT);
  6349. if (VT != MVT::Glue) {
  6350. FoldingSetNodeID ID;
  6351. AddNodeIDNode(ID, Opcode, VTs, Ops);
  6352. void *IP = nullptr;
  6353. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  6354. return SDValue(E, 0);
  6355. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  6356. createOperands(N, Ops);
  6357. CSEMap.InsertNode(N, IP);
  6358. } else {
  6359. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  6360. createOperands(N, Ops);
  6361. }
  6362. InsertNode(N);
  6363. SDValue V(N, 0);
  6364. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6365. return V;
  6366. }
  6367. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  6368. ArrayRef<EVT> ResultTys, ArrayRef<SDValue> Ops) {
  6369. return getNode(Opcode, DL, getVTList(ResultTys), Ops);
  6370. }
  6371. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6372. ArrayRef<SDValue> Ops) {
  6373. if (VTList.NumVTs == 1)
  6374. return getNode(Opcode, DL, VTList.VTs[0], Ops);
  6375. #if 0
  6376. switch (Opcode) {
  6377. // FIXME: figure out how to safely handle things like
  6378. // int foo(int x) { return 1 << (x & 255); }
  6379. // int bar() { return foo(256); }
  6380. case ISD::SRA_PARTS:
  6381. case ISD::SRL_PARTS:
  6382. case ISD::SHL_PARTS:
  6383. if (N3.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  6384. cast<VTSDNode>(N3.getOperand(1))->getVT() != MVT::i1)
  6385. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  6386. else if (N3.getOpcode() == ISD::AND)
  6387. if (ConstantSDNode *AndRHS = dyn_cast<ConstantSDNode>(N3.getOperand(1))) {
  6388. // If the and is only masking out bits that cannot effect the shift,
  6389. // eliminate the and.
  6390. unsigned NumBits = VT.getScalarSizeInBits()*2;
  6391. if ((AndRHS->getValue() & (NumBits-1)) == NumBits-1)
  6392. return getNode(Opcode, DL, VT, N1, N2, N3.getOperand(0));
  6393. }
  6394. break;
  6395. }
  6396. #endif
  6397. // Memoize the node unless it returns a flag.
  6398. SDNode *N;
  6399. if (VTList.VTs[VTList.NumVTs-1] != MVT::Glue) {
  6400. FoldingSetNodeID ID;
  6401. AddNodeIDNode(ID, Opcode, VTList, Ops);
  6402. void *IP = nullptr;
  6403. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP))
  6404. return SDValue(E, 0);
  6405. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  6406. createOperands(N, Ops);
  6407. CSEMap.InsertNode(N, IP);
  6408. } else {
  6409. N = newSDNode<SDNode>(Opcode, DL.getIROrder(), DL.getDebugLoc(), VTList);
  6410. createOperands(N, Ops);
  6411. }
  6412. InsertNode(N);
  6413. SDValue V(N, 0);
  6414. NewSDValueDbgMsg(V, "Creating new node: ", this);
  6415. return V;
  6416. }
  6417. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL,
  6418. SDVTList VTList) {
  6419. return getNode(Opcode, DL, VTList, None);
  6420. }
  6421. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6422. SDValue N1) {
  6423. SDValue Ops[] = { N1 };
  6424. return getNode(Opcode, DL, VTList, Ops);
  6425. }
  6426. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6427. SDValue N1, SDValue N2) {
  6428. SDValue Ops[] = { N1, N2 };
  6429. return getNode(Opcode, DL, VTList, Ops);
  6430. }
  6431. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6432. SDValue N1, SDValue N2, SDValue N3) {
  6433. SDValue Ops[] = { N1, N2, N3 };
  6434. return getNode(Opcode, DL, VTList, Ops);
  6435. }
  6436. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6437. SDValue N1, SDValue N2, SDValue N3, SDValue N4) {
  6438. SDValue Ops[] = { N1, N2, N3, N4 };
  6439. return getNode(Opcode, DL, VTList, Ops);
  6440. }
  6441. SDValue SelectionDAG::getNode(unsigned Opcode, const SDLoc &DL, SDVTList VTList,
  6442. SDValue N1, SDValue N2, SDValue N3, SDValue N4,
  6443. SDValue N5) {
  6444. SDValue Ops[] = { N1, N2, N3, N4, N5 };
  6445. return getNode(Opcode, DL, VTList, Ops);
  6446. }
  6447. SDVTList SelectionDAG::getVTList(EVT VT) {
  6448. return makeVTList(SDNode::getValueTypeList(VT), 1);
  6449. }
  6450. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2) {
  6451. FoldingSetNodeID ID;
  6452. ID.AddInteger(2U);
  6453. ID.AddInteger(VT1.getRawBits());
  6454. ID.AddInteger(VT2.getRawBits());
  6455. void *IP = nullptr;
  6456. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6457. if (!Result) {
  6458. EVT *Array = Allocator.Allocate<EVT>(2);
  6459. Array[0] = VT1;
  6460. Array[1] = VT2;
  6461. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 2);
  6462. VTListMap.InsertNode(Result, IP);
  6463. }
  6464. return Result->getSDVTList();
  6465. }
  6466. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3) {
  6467. FoldingSetNodeID ID;
  6468. ID.AddInteger(3U);
  6469. ID.AddInteger(VT1.getRawBits());
  6470. ID.AddInteger(VT2.getRawBits());
  6471. ID.AddInteger(VT3.getRawBits());
  6472. void *IP = nullptr;
  6473. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6474. if (!Result) {
  6475. EVT *Array = Allocator.Allocate<EVT>(3);
  6476. Array[0] = VT1;
  6477. Array[1] = VT2;
  6478. Array[2] = VT3;
  6479. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 3);
  6480. VTListMap.InsertNode(Result, IP);
  6481. }
  6482. return Result->getSDVTList();
  6483. }
  6484. SDVTList SelectionDAG::getVTList(EVT VT1, EVT VT2, EVT VT3, EVT VT4) {
  6485. FoldingSetNodeID ID;
  6486. ID.AddInteger(4U);
  6487. ID.AddInteger(VT1.getRawBits());
  6488. ID.AddInteger(VT2.getRawBits());
  6489. ID.AddInteger(VT3.getRawBits());
  6490. ID.AddInteger(VT4.getRawBits());
  6491. void *IP = nullptr;
  6492. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6493. if (!Result) {
  6494. EVT *Array = Allocator.Allocate<EVT>(4);
  6495. Array[0] = VT1;
  6496. Array[1] = VT2;
  6497. Array[2] = VT3;
  6498. Array[3] = VT4;
  6499. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, 4);
  6500. VTListMap.InsertNode(Result, IP);
  6501. }
  6502. return Result->getSDVTList();
  6503. }
  6504. SDVTList SelectionDAG::getVTList(ArrayRef<EVT> VTs) {
  6505. unsigned NumVTs = VTs.size();
  6506. FoldingSetNodeID ID;
  6507. ID.AddInteger(NumVTs);
  6508. for (unsigned index = 0; index < NumVTs; index++) {
  6509. ID.AddInteger(VTs[index].getRawBits());
  6510. }
  6511. void *IP = nullptr;
  6512. SDVTListNode *Result = VTListMap.FindNodeOrInsertPos(ID, IP);
  6513. if (!Result) {
  6514. EVT *Array = Allocator.Allocate<EVT>(NumVTs);
  6515. llvm::copy(VTs, Array);
  6516. Result = new (Allocator) SDVTListNode(ID.Intern(Allocator), Array, NumVTs);
  6517. VTListMap.InsertNode(Result, IP);
  6518. }
  6519. return Result->getSDVTList();
  6520. }
  6521. /// UpdateNodeOperands - *Mutate* the specified node in-place to have the
  6522. /// specified operands. If the resultant node already exists in the DAG,
  6523. /// this does not modify the specified node, instead it returns the node that
  6524. /// already exists. If the resultant node does not exist in the DAG, the
  6525. /// input node is returned. As a degenerate case, if you specify the same
  6526. /// input operands as the node already has, the input node is returned.
  6527. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op) {
  6528. assert(N->getNumOperands() == 1 && "Update with wrong number of operands");
  6529. // Check to see if there is no change.
  6530. if (Op == N->getOperand(0)) return N;
  6531. // See if the modified node already exists.
  6532. void *InsertPos = nullptr;
  6533. if (SDNode *Existing = FindModifiedNodeSlot(N, Op, InsertPos))
  6534. return Existing;
  6535. // Nope it doesn't. Remove the node from its current place in the maps.
  6536. if (InsertPos)
  6537. if (!RemoveNodeFromCSEMaps(N))
  6538. InsertPos = nullptr;
  6539. // Now we update the operands.
  6540. N->OperandList[0].set(Op);
  6541. updateDivergence(N);
  6542. // If this gets put into a CSE map, add it.
  6543. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  6544. return N;
  6545. }
  6546. SDNode *SelectionDAG::UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2) {
  6547. assert(N->getNumOperands() == 2 && "Update with wrong number of operands");
  6548. // Check to see if there is no change.
  6549. if (Op1 == N->getOperand(0) && Op2 == N->getOperand(1))
  6550. return N; // No operands changed, just return the input node.
  6551. // See if the modified node already exists.
  6552. void *InsertPos = nullptr;
  6553. if (SDNode *Existing = FindModifiedNodeSlot(N, Op1, Op2, InsertPos))
  6554. return Existing;
  6555. // Nope it doesn't. Remove the node from its current place in the maps.
  6556. if (InsertPos)
  6557. if (!RemoveNodeFromCSEMaps(N))
  6558. InsertPos = nullptr;
  6559. // Now we update the operands.
  6560. if (N->OperandList[0] != Op1)
  6561. N->OperandList[0].set(Op1);
  6562. if (N->OperandList[1] != Op2)
  6563. N->OperandList[1].set(Op2);
  6564. updateDivergence(N);
  6565. // If this gets put into a CSE map, add it.
  6566. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  6567. return N;
  6568. }
  6569. SDNode *SelectionDAG::
  6570. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2, SDValue Op3) {
  6571. SDValue Ops[] = { Op1, Op2, Op3 };
  6572. return UpdateNodeOperands(N, Ops);
  6573. }
  6574. SDNode *SelectionDAG::
  6575. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  6576. SDValue Op3, SDValue Op4) {
  6577. SDValue Ops[] = { Op1, Op2, Op3, Op4 };
  6578. return UpdateNodeOperands(N, Ops);
  6579. }
  6580. SDNode *SelectionDAG::
  6581. UpdateNodeOperands(SDNode *N, SDValue Op1, SDValue Op2,
  6582. SDValue Op3, SDValue Op4, SDValue Op5) {
  6583. SDValue Ops[] = { Op1, Op2, Op3, Op4, Op5 };
  6584. return UpdateNodeOperands(N, Ops);
  6585. }
  6586. SDNode *SelectionDAG::
  6587. UpdateNodeOperands(SDNode *N, ArrayRef<SDValue> Ops) {
  6588. unsigned NumOps = Ops.size();
  6589. assert(N->getNumOperands() == NumOps &&
  6590. "Update with wrong number of operands");
  6591. // If no operands changed just return the input node.
  6592. if (std::equal(Ops.begin(), Ops.end(), N->op_begin()))
  6593. return N;
  6594. // See if the modified node already exists.
  6595. void *InsertPos = nullptr;
  6596. if (SDNode *Existing = FindModifiedNodeSlot(N, Ops, InsertPos))
  6597. return Existing;
  6598. // Nope it doesn't. Remove the node from its current place in the maps.
  6599. if (InsertPos)
  6600. if (!RemoveNodeFromCSEMaps(N))
  6601. InsertPos = nullptr;
  6602. // Now we update the operands.
  6603. for (unsigned i = 0; i != NumOps; ++i)
  6604. if (N->OperandList[i] != Ops[i])
  6605. N->OperandList[i].set(Ops[i]);
  6606. updateDivergence(N);
  6607. // If this gets put into a CSE map, add it.
  6608. if (InsertPos) CSEMap.InsertNode(N, InsertPos);
  6609. return N;
  6610. }
  6611. /// DropOperands - Release the operands and set this node to have
  6612. /// zero operands.
  6613. void SDNode::DropOperands() {
  6614. // Unlike the code in MorphNodeTo that does this, we don't need to
  6615. // watch for dead nodes here.
  6616. for (op_iterator I = op_begin(), E = op_end(); I != E; ) {
  6617. SDUse &Use = *I++;
  6618. Use.set(SDValue());
  6619. }
  6620. }
  6621. void SelectionDAG::setNodeMemRefs(MachineSDNode *N,
  6622. ArrayRef<MachineMemOperand *> NewMemRefs) {
  6623. if (NewMemRefs.empty()) {
  6624. N->clearMemRefs();
  6625. return;
  6626. }
  6627. // Check if we can avoid allocating by storing a single reference directly.
  6628. if (NewMemRefs.size() == 1) {
  6629. N->MemRefs = NewMemRefs[0];
  6630. N->NumMemRefs = 1;
  6631. return;
  6632. }
  6633. MachineMemOperand **MemRefsBuffer =
  6634. Allocator.template Allocate<MachineMemOperand *>(NewMemRefs.size());
  6635. llvm::copy(NewMemRefs, MemRefsBuffer);
  6636. N->MemRefs = MemRefsBuffer;
  6637. N->NumMemRefs = static_cast<int>(NewMemRefs.size());
  6638. }
  6639. /// SelectNodeTo - These are wrappers around MorphNodeTo that accept a
  6640. /// machine opcode.
  6641. ///
  6642. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6643. EVT VT) {
  6644. SDVTList VTs = getVTList(VT);
  6645. return SelectNodeTo(N, MachineOpc, VTs, None);
  6646. }
  6647. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6648. EVT VT, SDValue Op1) {
  6649. SDVTList VTs = getVTList(VT);
  6650. SDValue Ops[] = { Op1 };
  6651. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6652. }
  6653. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6654. EVT VT, SDValue Op1,
  6655. SDValue Op2) {
  6656. SDVTList VTs = getVTList(VT);
  6657. SDValue Ops[] = { Op1, Op2 };
  6658. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6659. }
  6660. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6661. EVT VT, SDValue Op1,
  6662. SDValue Op2, SDValue Op3) {
  6663. SDVTList VTs = getVTList(VT);
  6664. SDValue Ops[] = { Op1, Op2, Op3 };
  6665. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6666. }
  6667. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6668. EVT VT, ArrayRef<SDValue> Ops) {
  6669. SDVTList VTs = getVTList(VT);
  6670. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6671. }
  6672. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6673. EVT VT1, EVT VT2, ArrayRef<SDValue> Ops) {
  6674. SDVTList VTs = getVTList(VT1, VT2);
  6675. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6676. }
  6677. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6678. EVT VT1, EVT VT2) {
  6679. SDVTList VTs = getVTList(VT1, VT2);
  6680. return SelectNodeTo(N, MachineOpc, VTs, None);
  6681. }
  6682. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6683. EVT VT1, EVT VT2, EVT VT3,
  6684. ArrayRef<SDValue> Ops) {
  6685. SDVTList VTs = getVTList(VT1, VT2, VT3);
  6686. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6687. }
  6688. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6689. EVT VT1, EVT VT2,
  6690. SDValue Op1, SDValue Op2) {
  6691. SDVTList VTs = getVTList(VT1, VT2);
  6692. SDValue Ops[] = { Op1, Op2 };
  6693. return SelectNodeTo(N, MachineOpc, VTs, Ops);
  6694. }
  6695. SDNode *SelectionDAG::SelectNodeTo(SDNode *N, unsigned MachineOpc,
  6696. SDVTList VTs,ArrayRef<SDValue> Ops) {
  6697. SDNode *New = MorphNodeTo(N, ~MachineOpc, VTs, Ops);
  6698. // Reset the NodeID to -1.
  6699. New->setNodeId(-1);
  6700. if (New != N) {
  6701. ReplaceAllUsesWith(N, New);
  6702. RemoveDeadNode(N);
  6703. }
  6704. return New;
  6705. }
  6706. /// UpdateSDLocOnMergeSDNode - If the opt level is -O0 then it throws away
  6707. /// the line number information on the merged node since it is not possible to
  6708. /// preserve the information that operation is associated with multiple lines.
  6709. /// This will make the debugger working better at -O0, were there is a higher
  6710. /// probability having other instructions associated with that line.
  6711. ///
  6712. /// For IROrder, we keep the smaller of the two
  6713. SDNode *SelectionDAG::UpdateSDLocOnMergeSDNode(SDNode *N, const SDLoc &OLoc) {
  6714. DebugLoc NLoc = N->getDebugLoc();
  6715. if (NLoc && OptLevel == CodeGenOpt::None && OLoc.getDebugLoc() != NLoc) {
  6716. N->setDebugLoc(DebugLoc());
  6717. }
  6718. unsigned Order = std::min(N->getIROrder(), OLoc.getIROrder());
  6719. N->setIROrder(Order);
  6720. return N;
  6721. }
  6722. /// MorphNodeTo - This *mutates* the specified node to have the specified
  6723. /// return type, opcode, and operands.
  6724. ///
  6725. /// Note that MorphNodeTo returns the resultant node. If there is already a
  6726. /// node of the specified opcode and operands, it returns that node instead of
  6727. /// the current one. Note that the SDLoc need not be the same.
  6728. ///
  6729. /// Using MorphNodeTo is faster than creating a new node and swapping it in
  6730. /// with ReplaceAllUsesWith both because it often avoids allocating a new
  6731. /// node, and because it doesn't require CSE recalculation for any of
  6732. /// the node's users.
  6733. ///
  6734. /// However, note that MorphNodeTo recursively deletes dead nodes from the DAG.
  6735. /// As a consequence it isn't appropriate to use from within the DAG combiner or
  6736. /// the legalizer which maintain worklists that would need to be updated when
  6737. /// deleting things.
  6738. SDNode *SelectionDAG::MorphNodeTo(SDNode *N, unsigned Opc,
  6739. SDVTList VTs, ArrayRef<SDValue> Ops) {
  6740. // If an identical node already exists, use it.
  6741. void *IP = nullptr;
  6742. if (VTs.VTs[VTs.NumVTs-1] != MVT::Glue) {
  6743. FoldingSetNodeID ID;
  6744. AddNodeIDNode(ID, Opc, VTs, Ops);
  6745. if (SDNode *ON = FindNodeOrInsertPos(ID, SDLoc(N), IP))
  6746. return UpdateSDLocOnMergeSDNode(ON, SDLoc(N));
  6747. }
  6748. if (!RemoveNodeFromCSEMaps(N))
  6749. IP = nullptr;
  6750. // Start the morphing.
  6751. N->NodeType = Opc;
  6752. N->ValueList = VTs.VTs;
  6753. N->NumValues = VTs.NumVTs;
  6754. // Clear the operands list, updating used nodes to remove this from their
  6755. // use list. Keep track of any operands that become dead as a result.
  6756. SmallPtrSet<SDNode*, 16> DeadNodeSet;
  6757. for (SDNode::op_iterator I = N->op_begin(), E = N->op_end(); I != E; ) {
  6758. SDUse &Use = *I++;
  6759. SDNode *Used = Use.getNode();
  6760. Use.set(SDValue());
  6761. if (Used->use_empty())
  6762. DeadNodeSet.insert(Used);
  6763. }
  6764. // For MachineNode, initialize the memory references information.
  6765. if (MachineSDNode *MN = dyn_cast<MachineSDNode>(N))
  6766. MN->clearMemRefs();
  6767. // Swap for an appropriately sized array from the recycler.
  6768. removeOperands(N);
  6769. createOperands(N, Ops);
  6770. // Delete any nodes that are still dead after adding the uses for the
  6771. // new operands.
  6772. if (!DeadNodeSet.empty()) {
  6773. SmallVector<SDNode *, 16> DeadNodes;
  6774. for (SDNode *N : DeadNodeSet)
  6775. if (N->use_empty())
  6776. DeadNodes.push_back(N);
  6777. RemoveDeadNodes(DeadNodes);
  6778. }
  6779. if (IP)
  6780. CSEMap.InsertNode(N, IP); // Memoize the new node.
  6781. return N;
  6782. }
  6783. SDNode* SelectionDAG::mutateStrictFPToFP(SDNode *Node) {
  6784. unsigned OrigOpc = Node->getOpcode();
  6785. unsigned NewOpc;
  6786. bool IsUnary = false;
  6787. bool IsTernary = false;
  6788. switch (OrigOpc) {
  6789. default:
  6790. llvm_unreachable("mutateStrictFPToFP called with unexpected opcode!");
  6791. case ISD::STRICT_FADD: NewOpc = ISD::FADD; break;
  6792. case ISD::STRICT_FSUB: NewOpc = ISD::FSUB; break;
  6793. case ISD::STRICT_FMUL: NewOpc = ISD::FMUL; break;
  6794. case ISD::STRICT_FDIV: NewOpc = ISD::FDIV; break;
  6795. case ISD::STRICT_FREM: NewOpc = ISD::FREM; break;
  6796. case ISD::STRICT_FMA: NewOpc = ISD::FMA; IsTernary = true; break;
  6797. case ISD::STRICT_FSQRT: NewOpc = ISD::FSQRT; IsUnary = true; break;
  6798. case ISD::STRICT_FPOW: NewOpc = ISD::FPOW; break;
  6799. case ISD::STRICT_FPOWI: NewOpc = ISD::FPOWI; break;
  6800. case ISD::STRICT_FSIN: NewOpc = ISD::FSIN; IsUnary = true; break;
  6801. case ISD::STRICT_FCOS: NewOpc = ISD::FCOS; IsUnary = true; break;
  6802. case ISD::STRICT_FEXP: NewOpc = ISD::FEXP; IsUnary = true; break;
  6803. case ISD::STRICT_FEXP2: NewOpc = ISD::FEXP2; IsUnary = true; break;
  6804. case ISD::STRICT_FLOG: NewOpc = ISD::FLOG; IsUnary = true; break;
  6805. case ISD::STRICT_FLOG10: NewOpc = ISD::FLOG10; IsUnary = true; break;
  6806. case ISD::STRICT_FLOG2: NewOpc = ISD::FLOG2; IsUnary = true; break;
  6807. case ISD::STRICT_FRINT: NewOpc = ISD::FRINT; IsUnary = true; break;
  6808. case ISD::STRICT_FNEARBYINT:
  6809. NewOpc = ISD::FNEARBYINT;
  6810. IsUnary = true;
  6811. break;
  6812. case ISD::STRICT_FMAXNUM: NewOpc = ISD::FMAXNUM; break;
  6813. case ISD::STRICT_FMINNUM: NewOpc = ISD::FMINNUM; break;
  6814. case ISD::STRICT_FCEIL: NewOpc = ISD::FCEIL; IsUnary = true; break;
  6815. case ISD::STRICT_FFLOOR: NewOpc = ISD::FFLOOR; IsUnary = true; break;
  6816. case ISD::STRICT_FROUND: NewOpc = ISD::FROUND; IsUnary = true; break;
  6817. case ISD::STRICT_FTRUNC: NewOpc = ISD::FTRUNC; IsUnary = true; break;
  6818. }
  6819. // We're taking this node out of the chain, so we need to re-link things.
  6820. SDValue InputChain = Node->getOperand(0);
  6821. SDValue OutputChain = SDValue(Node, 1);
  6822. ReplaceAllUsesOfValueWith(OutputChain, InputChain);
  6823. SDVTList VTs = getVTList(Node->getOperand(1).getValueType());
  6824. SDNode *Res = nullptr;
  6825. if (IsUnary)
  6826. Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1) });
  6827. else if (IsTernary)
  6828. Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
  6829. Node->getOperand(2),
  6830. Node->getOperand(3)});
  6831. else
  6832. Res = MorphNodeTo(Node, NewOpc, VTs, { Node->getOperand(1),
  6833. Node->getOperand(2) });
  6834. // MorphNodeTo can operate in two ways: if an existing node with the
  6835. // specified operands exists, it can just return it. Otherwise, it
  6836. // updates the node in place to have the requested operands.
  6837. if (Res == Node) {
  6838. // If we updated the node in place, reset the node ID. To the isel,
  6839. // this should be just like a newly allocated machine node.
  6840. Res->setNodeId(-1);
  6841. } else {
  6842. ReplaceAllUsesWith(Node, Res);
  6843. RemoveDeadNode(Node);
  6844. }
  6845. return Res;
  6846. }
  6847. /// getMachineNode - These are used for target selectors to create a new node
  6848. /// with specified return type(s), MachineInstr opcode, and operands.
  6849. ///
  6850. /// Note that getMachineNode returns the resultant node. If there is already a
  6851. /// node of the specified opcode and operands, it returns that node instead of
  6852. /// the current one.
  6853. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6854. EVT VT) {
  6855. SDVTList VTs = getVTList(VT);
  6856. return getMachineNode(Opcode, dl, VTs, None);
  6857. }
  6858. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6859. EVT VT, SDValue Op1) {
  6860. SDVTList VTs = getVTList(VT);
  6861. SDValue Ops[] = { Op1 };
  6862. return getMachineNode(Opcode, dl, VTs, Ops);
  6863. }
  6864. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6865. EVT VT, SDValue Op1, SDValue Op2) {
  6866. SDVTList VTs = getVTList(VT);
  6867. SDValue Ops[] = { Op1, Op2 };
  6868. return getMachineNode(Opcode, dl, VTs, Ops);
  6869. }
  6870. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6871. EVT VT, SDValue Op1, SDValue Op2,
  6872. SDValue Op3) {
  6873. SDVTList VTs = getVTList(VT);
  6874. SDValue Ops[] = { Op1, Op2, Op3 };
  6875. return getMachineNode(Opcode, dl, VTs, Ops);
  6876. }
  6877. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6878. EVT VT, ArrayRef<SDValue> Ops) {
  6879. SDVTList VTs = getVTList(VT);
  6880. return getMachineNode(Opcode, dl, VTs, Ops);
  6881. }
  6882. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6883. EVT VT1, EVT VT2, SDValue Op1,
  6884. SDValue Op2) {
  6885. SDVTList VTs = getVTList(VT1, VT2);
  6886. SDValue Ops[] = { Op1, Op2 };
  6887. return getMachineNode(Opcode, dl, VTs, Ops);
  6888. }
  6889. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6890. EVT VT1, EVT VT2, SDValue Op1,
  6891. SDValue Op2, SDValue Op3) {
  6892. SDVTList VTs = getVTList(VT1, VT2);
  6893. SDValue Ops[] = { Op1, Op2, Op3 };
  6894. return getMachineNode(Opcode, dl, VTs, Ops);
  6895. }
  6896. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6897. EVT VT1, EVT VT2,
  6898. ArrayRef<SDValue> Ops) {
  6899. SDVTList VTs = getVTList(VT1, VT2);
  6900. return getMachineNode(Opcode, dl, VTs, Ops);
  6901. }
  6902. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6903. EVT VT1, EVT VT2, EVT VT3,
  6904. SDValue Op1, SDValue Op2) {
  6905. SDVTList VTs = getVTList(VT1, VT2, VT3);
  6906. SDValue Ops[] = { Op1, Op2 };
  6907. return getMachineNode(Opcode, dl, VTs, Ops);
  6908. }
  6909. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6910. EVT VT1, EVT VT2, EVT VT3,
  6911. SDValue Op1, SDValue Op2,
  6912. SDValue Op3) {
  6913. SDVTList VTs = getVTList(VT1, VT2, VT3);
  6914. SDValue Ops[] = { Op1, Op2, Op3 };
  6915. return getMachineNode(Opcode, dl, VTs, Ops);
  6916. }
  6917. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6918. EVT VT1, EVT VT2, EVT VT3,
  6919. ArrayRef<SDValue> Ops) {
  6920. SDVTList VTs = getVTList(VT1, VT2, VT3);
  6921. return getMachineNode(Opcode, dl, VTs, Ops);
  6922. }
  6923. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &dl,
  6924. ArrayRef<EVT> ResultTys,
  6925. ArrayRef<SDValue> Ops) {
  6926. SDVTList VTs = getVTList(ResultTys);
  6927. return getMachineNode(Opcode, dl, VTs, Ops);
  6928. }
  6929. MachineSDNode *SelectionDAG::getMachineNode(unsigned Opcode, const SDLoc &DL,
  6930. SDVTList VTs,
  6931. ArrayRef<SDValue> Ops) {
  6932. bool DoCSE = VTs.VTs[VTs.NumVTs-1] != MVT::Glue;
  6933. MachineSDNode *N;
  6934. void *IP = nullptr;
  6935. if (DoCSE) {
  6936. FoldingSetNodeID ID;
  6937. AddNodeIDNode(ID, ~Opcode, VTs, Ops);
  6938. IP = nullptr;
  6939. if (SDNode *E = FindNodeOrInsertPos(ID, DL, IP)) {
  6940. return cast<MachineSDNode>(UpdateSDLocOnMergeSDNode(E, DL));
  6941. }
  6942. }
  6943. // Allocate a new MachineSDNode.
  6944. N = newSDNode<MachineSDNode>(~Opcode, DL.getIROrder(), DL.getDebugLoc(), VTs);
  6945. createOperands(N, Ops);
  6946. if (DoCSE)
  6947. CSEMap.InsertNode(N, IP);
  6948. InsertNode(N);
  6949. return N;
  6950. }
  6951. /// getTargetExtractSubreg - A convenience function for creating
  6952. /// TargetOpcode::EXTRACT_SUBREG nodes.
  6953. SDValue SelectionDAG::getTargetExtractSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  6954. SDValue Operand) {
  6955. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  6956. SDNode *Subreg = getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL,
  6957. VT, Operand, SRIdxVal);
  6958. return SDValue(Subreg, 0);
  6959. }
  6960. /// getTargetInsertSubreg - A convenience function for creating
  6961. /// TargetOpcode::INSERT_SUBREG nodes.
  6962. SDValue SelectionDAG::getTargetInsertSubreg(int SRIdx, const SDLoc &DL, EVT VT,
  6963. SDValue Operand, SDValue Subreg) {
  6964. SDValue SRIdxVal = getTargetConstant(SRIdx, DL, MVT::i32);
  6965. SDNode *Result = getMachineNode(TargetOpcode::INSERT_SUBREG, DL,
  6966. VT, Operand, Subreg, SRIdxVal);
  6967. return SDValue(Result, 0);
  6968. }
  6969. /// getNodeIfExists - Get the specified node if it's already available, or
  6970. /// else return NULL.
  6971. SDNode *SelectionDAG::getNodeIfExists(unsigned Opcode, SDVTList VTList,
  6972. ArrayRef<SDValue> Ops,
  6973. const SDNodeFlags Flags) {
  6974. if (VTList.VTs[VTList.NumVTs - 1] != MVT::Glue) {
  6975. FoldingSetNodeID ID;
  6976. AddNodeIDNode(ID, Opcode, VTList, Ops);
  6977. void *IP = nullptr;
  6978. if (SDNode *E = FindNodeOrInsertPos(ID, SDLoc(), IP)) {
  6979. E->intersectFlagsWith(Flags);
  6980. return E;
  6981. }
  6982. }
  6983. return nullptr;
  6984. }
  6985. /// getDbgValue - Creates a SDDbgValue node.
  6986. ///
  6987. /// SDNode
  6988. SDDbgValue *SelectionDAG::getDbgValue(DIVariable *Var, DIExpression *Expr,
  6989. SDNode *N, unsigned R, bool IsIndirect,
  6990. const DebugLoc &DL, unsigned O) {
  6991. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  6992. "Expected inlined-at fields to agree");
  6993. return new (DbgInfo->getAlloc())
  6994. SDDbgValue(Var, Expr, N, R, IsIndirect, DL, O);
  6995. }
  6996. /// Constant
  6997. SDDbgValue *SelectionDAG::getConstantDbgValue(DIVariable *Var,
  6998. DIExpression *Expr,
  6999. const Value *C,
  7000. const DebugLoc &DL, unsigned O) {
  7001. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  7002. "Expected inlined-at fields to agree");
  7003. return new (DbgInfo->getAlloc()) SDDbgValue(Var, Expr, C, DL, O);
  7004. }
  7005. /// FrameIndex
  7006. SDDbgValue *SelectionDAG::getFrameIndexDbgValue(DIVariable *Var,
  7007. DIExpression *Expr, unsigned FI,
  7008. bool IsIndirect,
  7009. const DebugLoc &DL,
  7010. unsigned O) {
  7011. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  7012. "Expected inlined-at fields to agree");
  7013. return new (DbgInfo->getAlloc())
  7014. SDDbgValue(Var, Expr, FI, IsIndirect, DL, O, SDDbgValue::FRAMEIX);
  7015. }
  7016. /// VReg
  7017. SDDbgValue *SelectionDAG::getVRegDbgValue(DIVariable *Var,
  7018. DIExpression *Expr,
  7019. unsigned VReg, bool IsIndirect,
  7020. const DebugLoc &DL, unsigned O) {
  7021. assert(cast<DILocalVariable>(Var)->isValidLocationForIntrinsic(DL) &&
  7022. "Expected inlined-at fields to agree");
  7023. return new (DbgInfo->getAlloc())
  7024. SDDbgValue(Var, Expr, VReg, IsIndirect, DL, O, SDDbgValue::VREG);
  7025. }
  7026. void SelectionDAG::transferDbgValues(SDValue From, SDValue To,
  7027. unsigned OffsetInBits, unsigned SizeInBits,
  7028. bool InvalidateDbg) {
  7029. SDNode *FromNode = From.getNode();
  7030. SDNode *ToNode = To.getNode();
  7031. assert(FromNode && ToNode && "Can't modify dbg values");
  7032. // PR35338
  7033. // TODO: assert(From != To && "Redundant dbg value transfer");
  7034. // TODO: assert(FromNode != ToNode && "Intranode dbg value transfer");
  7035. if (From == To || FromNode == ToNode)
  7036. return;
  7037. if (!FromNode->getHasDebugValue())
  7038. return;
  7039. SmallVector<SDDbgValue *, 2> ClonedDVs;
  7040. for (SDDbgValue *Dbg : GetDbgValues(FromNode)) {
  7041. if (Dbg->getKind() != SDDbgValue::SDNODE || Dbg->isInvalidated())
  7042. continue;
  7043. // TODO: assert(!Dbg->isInvalidated() && "Transfer of invalid dbg value");
  7044. // Just transfer the dbg value attached to From.
  7045. if (Dbg->getResNo() != From.getResNo())
  7046. continue;
  7047. DIVariable *Var = Dbg->getVariable();
  7048. auto *Expr = Dbg->getExpression();
  7049. // If a fragment is requested, update the expression.
  7050. if (SizeInBits) {
  7051. // When splitting a larger (e.g., sign-extended) value whose
  7052. // lower bits are described with an SDDbgValue, do not attempt
  7053. // to transfer the SDDbgValue to the upper bits.
  7054. if (auto FI = Expr->getFragmentInfo())
  7055. if (OffsetInBits + SizeInBits > FI->SizeInBits)
  7056. continue;
  7057. auto Fragment = DIExpression::createFragmentExpression(Expr, OffsetInBits,
  7058. SizeInBits);
  7059. if (!Fragment)
  7060. continue;
  7061. Expr = *Fragment;
  7062. }
  7063. // Clone the SDDbgValue and move it to To.
  7064. SDDbgValue *Clone =
  7065. getDbgValue(Var, Expr, ToNode, To.getResNo(), Dbg->isIndirect(),
  7066. Dbg->getDebugLoc(), Dbg->getOrder());
  7067. ClonedDVs.push_back(Clone);
  7068. if (InvalidateDbg) {
  7069. // Invalidate value and indicate the SDDbgValue should not be emitted.
  7070. Dbg->setIsInvalidated();
  7071. Dbg->setIsEmitted();
  7072. }
  7073. }
  7074. for (SDDbgValue *Dbg : ClonedDVs)
  7075. AddDbgValue(Dbg, ToNode, false);
  7076. }
  7077. void SelectionDAG::salvageDebugInfo(SDNode &N) {
  7078. if (!N.getHasDebugValue())
  7079. return;
  7080. SmallVector<SDDbgValue *, 2> ClonedDVs;
  7081. for (auto DV : GetDbgValues(&N)) {
  7082. if (DV->isInvalidated())
  7083. continue;
  7084. switch (N.getOpcode()) {
  7085. default:
  7086. break;
  7087. case ISD::ADD:
  7088. SDValue N0 = N.getOperand(0);
  7089. SDValue N1 = N.getOperand(1);
  7090. if (!isConstantIntBuildVectorOrConstantInt(N0) &&
  7091. isConstantIntBuildVectorOrConstantInt(N1)) {
  7092. uint64_t Offset = N.getConstantOperandVal(1);
  7093. // Rewrite an ADD constant node into a DIExpression. Since we are
  7094. // performing arithmetic to compute the variable's *value* in the
  7095. // DIExpression, we need to mark the expression with a
  7096. // DW_OP_stack_value.
  7097. auto *DIExpr = DV->getExpression();
  7098. DIExpr = DIExpression::prepend(DIExpr, DIExpression::NoDeref, Offset,
  7099. DIExpression::NoDeref,
  7100. DIExpression::WithStackValue);
  7101. SDDbgValue *Clone =
  7102. getDbgValue(DV->getVariable(), DIExpr, N0.getNode(), N0.getResNo(),
  7103. DV->isIndirect(), DV->getDebugLoc(), DV->getOrder());
  7104. ClonedDVs.push_back(Clone);
  7105. DV->setIsInvalidated();
  7106. DV->setIsEmitted();
  7107. LLVM_DEBUG(dbgs() << "SALVAGE: Rewriting";
  7108. N0.getNode()->dumprFull(this);
  7109. dbgs() << " into " << *DIExpr << '\n');
  7110. }
  7111. }
  7112. }
  7113. for (SDDbgValue *Dbg : ClonedDVs)
  7114. AddDbgValue(Dbg, Dbg->getSDNode(), false);
  7115. }
  7116. /// Creates a SDDbgLabel node.
  7117. SDDbgLabel *SelectionDAG::getDbgLabel(DILabel *Label,
  7118. const DebugLoc &DL, unsigned O) {
  7119. assert(cast<DILabel>(Label)->isValidLocationForIntrinsic(DL) &&
  7120. "Expected inlined-at fields to agree");
  7121. return new (DbgInfo->getAlloc()) SDDbgLabel(Label, DL, O);
  7122. }
  7123. namespace {
  7124. /// RAUWUpdateListener - Helper for ReplaceAllUsesWith - When the node
  7125. /// pointed to by a use iterator is deleted, increment the use iterator
  7126. /// so that it doesn't dangle.
  7127. ///
  7128. class RAUWUpdateListener : public SelectionDAG::DAGUpdateListener {
  7129. SDNode::use_iterator &UI;
  7130. SDNode::use_iterator &UE;
  7131. void NodeDeleted(SDNode *N, SDNode *E) override {
  7132. // Increment the iterator as needed.
  7133. while (UI != UE && N == *UI)
  7134. ++UI;
  7135. }
  7136. public:
  7137. RAUWUpdateListener(SelectionDAG &d,
  7138. SDNode::use_iterator &ui,
  7139. SDNode::use_iterator &ue)
  7140. : SelectionDAG::DAGUpdateListener(d), UI(ui), UE(ue) {}
  7141. };
  7142. } // end anonymous namespace
  7143. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  7144. /// This can cause recursive merging of nodes in the DAG.
  7145. ///
  7146. /// This version assumes From has a single result value.
  7147. ///
  7148. void SelectionDAG::ReplaceAllUsesWith(SDValue FromN, SDValue To) {
  7149. SDNode *From = FromN.getNode();
  7150. assert(From->getNumValues() == 1 && FromN.getResNo() == 0 &&
  7151. "Cannot replace with this method!");
  7152. assert(From != To.getNode() && "Cannot replace uses of with self");
  7153. // Preserve Debug Values
  7154. transferDbgValues(FromN, To);
  7155. // Iterate over all the existing uses of From. New uses will be added
  7156. // to the beginning of the use list, which we avoid visiting.
  7157. // This specifically avoids visiting uses of From that arise while the
  7158. // replacement is happening, because any such uses would be the result
  7159. // of CSE: If an existing node looks like From after one of its operands
  7160. // is replaced by To, we don't want to replace of all its users with To
  7161. // too. See PR3018 for more info.
  7162. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  7163. RAUWUpdateListener Listener(*this, UI, UE);
  7164. while (UI != UE) {
  7165. SDNode *User = *UI;
  7166. // This node is about to morph, remove its old self from the CSE maps.
  7167. RemoveNodeFromCSEMaps(User);
  7168. // A user can appear in a use list multiple times, and when this
  7169. // happens the uses are usually next to each other in the list.
  7170. // To help reduce the number of CSE recomputations, process all
  7171. // the uses of this user that we can find this way.
  7172. do {
  7173. SDUse &Use = UI.getUse();
  7174. ++UI;
  7175. Use.set(To);
  7176. if (To->isDivergent() != From->isDivergent())
  7177. updateDivergence(User);
  7178. } while (UI != UE && *UI == User);
  7179. // Now that we have modified User, add it back to the CSE maps. If it
  7180. // already exists there, recursively merge the results together.
  7181. AddModifiedNodeToCSEMaps(User);
  7182. }
  7183. // If we just RAUW'd the root, take note.
  7184. if (FromN == getRoot())
  7185. setRoot(To);
  7186. }
  7187. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  7188. /// This can cause recursive merging of nodes in the DAG.
  7189. ///
  7190. /// This version assumes that for each value of From, there is a
  7191. /// corresponding value in To in the same position with the same type.
  7192. ///
  7193. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, SDNode *To) {
  7194. #ifndef NDEBUG
  7195. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  7196. assert((!From->hasAnyUseOfValue(i) ||
  7197. From->getValueType(i) == To->getValueType(i)) &&
  7198. "Cannot use this version of ReplaceAllUsesWith!");
  7199. #endif
  7200. // Handle the trivial case.
  7201. if (From == To)
  7202. return;
  7203. // Preserve Debug Info. Only do this if there's a use.
  7204. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  7205. if (From->hasAnyUseOfValue(i)) {
  7206. assert((i < To->getNumValues()) && "Invalid To location");
  7207. transferDbgValues(SDValue(From, i), SDValue(To, i));
  7208. }
  7209. // Iterate over just the existing users of From. See the comments in
  7210. // the ReplaceAllUsesWith above.
  7211. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  7212. RAUWUpdateListener Listener(*this, UI, UE);
  7213. while (UI != UE) {
  7214. SDNode *User = *UI;
  7215. // This node is about to morph, remove its old self from the CSE maps.
  7216. RemoveNodeFromCSEMaps(User);
  7217. // A user can appear in a use list multiple times, and when this
  7218. // happens the uses are usually next to each other in the list.
  7219. // To help reduce the number of CSE recomputations, process all
  7220. // the uses of this user that we can find this way.
  7221. do {
  7222. SDUse &Use = UI.getUse();
  7223. ++UI;
  7224. Use.setNode(To);
  7225. if (To->isDivergent() != From->isDivergent())
  7226. updateDivergence(User);
  7227. } while (UI != UE && *UI == User);
  7228. // Now that we have modified User, add it back to the CSE maps. If it
  7229. // already exists there, recursively merge the results together.
  7230. AddModifiedNodeToCSEMaps(User);
  7231. }
  7232. // If we just RAUW'd the root, take note.
  7233. if (From == getRoot().getNode())
  7234. setRoot(SDValue(To, getRoot().getResNo()));
  7235. }
  7236. /// ReplaceAllUsesWith - Modify anything using 'From' to use 'To' instead.
  7237. /// This can cause recursive merging of nodes in the DAG.
  7238. ///
  7239. /// This version can replace From with any result values. To must match the
  7240. /// number and types of values returned by From.
  7241. void SelectionDAG::ReplaceAllUsesWith(SDNode *From, const SDValue *To) {
  7242. if (From->getNumValues() == 1) // Handle the simple case efficiently.
  7243. return ReplaceAllUsesWith(SDValue(From, 0), To[0]);
  7244. // Preserve Debug Info.
  7245. for (unsigned i = 0, e = From->getNumValues(); i != e; ++i)
  7246. transferDbgValues(SDValue(From, i), To[i]);
  7247. // Iterate over just the existing users of From. See the comments in
  7248. // the ReplaceAllUsesWith above.
  7249. SDNode::use_iterator UI = From->use_begin(), UE = From->use_end();
  7250. RAUWUpdateListener Listener(*this, UI, UE);
  7251. while (UI != UE) {
  7252. SDNode *User = *UI;
  7253. // This node is about to morph, remove its old self from the CSE maps.
  7254. RemoveNodeFromCSEMaps(User);
  7255. // A user can appear in a use list multiple times, and when this happens the
  7256. // uses are usually next to each other in the list. To help reduce the
  7257. // number of CSE and divergence recomputations, process all the uses of this
  7258. // user that we can find this way.
  7259. bool To_IsDivergent = false;
  7260. do {
  7261. SDUse &Use = UI.getUse();
  7262. const SDValue &ToOp = To[Use.getResNo()];
  7263. ++UI;
  7264. Use.set(ToOp);
  7265. To_IsDivergent |= ToOp->isDivergent();
  7266. } while (UI != UE && *UI == User);
  7267. if (To_IsDivergent != From->isDivergent())
  7268. updateDivergence(User);
  7269. // Now that we have modified User, add it back to the CSE maps. If it
  7270. // already exists there, recursively merge the results together.
  7271. AddModifiedNodeToCSEMaps(User);
  7272. }
  7273. // If we just RAUW'd the root, take note.
  7274. if (From == getRoot().getNode())
  7275. setRoot(SDValue(To[getRoot().getResNo()]));
  7276. }
  7277. /// ReplaceAllUsesOfValueWith - Replace any uses of From with To, leaving
  7278. /// uses of other values produced by From.getNode() alone. The Deleted
  7279. /// vector is handled the same way as for ReplaceAllUsesWith.
  7280. void SelectionDAG::ReplaceAllUsesOfValueWith(SDValue From, SDValue To){
  7281. // Handle the really simple, really trivial case efficiently.
  7282. if (From == To) return;
  7283. // Handle the simple, trivial, case efficiently.
  7284. if (From.getNode()->getNumValues() == 1) {
  7285. ReplaceAllUsesWith(From, To);
  7286. return;
  7287. }
  7288. // Preserve Debug Info.
  7289. transferDbgValues(From, To);
  7290. // Iterate over just the existing users of From. See the comments in
  7291. // the ReplaceAllUsesWith above.
  7292. SDNode::use_iterator UI = From.getNode()->use_begin(),
  7293. UE = From.getNode()->use_end();
  7294. RAUWUpdateListener Listener(*this, UI, UE);
  7295. while (UI != UE) {
  7296. SDNode *User = *UI;
  7297. bool UserRemovedFromCSEMaps = false;
  7298. // A user can appear in a use list multiple times, and when this
  7299. // happens the uses are usually next to each other in the list.
  7300. // To help reduce the number of CSE recomputations, process all
  7301. // the uses of this user that we can find this way.
  7302. do {
  7303. SDUse &Use = UI.getUse();
  7304. // Skip uses of different values from the same node.
  7305. if (Use.getResNo() != From.getResNo()) {
  7306. ++UI;
  7307. continue;
  7308. }
  7309. // If this node hasn't been modified yet, it's still in the CSE maps,
  7310. // so remove its old self from the CSE maps.
  7311. if (!UserRemovedFromCSEMaps) {
  7312. RemoveNodeFromCSEMaps(User);
  7313. UserRemovedFromCSEMaps = true;
  7314. }
  7315. ++UI;
  7316. Use.set(To);
  7317. if (To->isDivergent() != From->isDivergent())
  7318. updateDivergence(User);
  7319. } while (UI != UE && *UI == User);
  7320. // We are iterating over all uses of the From node, so if a use
  7321. // doesn't use the specific value, no changes are made.
  7322. if (!UserRemovedFromCSEMaps)
  7323. continue;
  7324. // Now that we have modified User, add it back to the CSE maps. If it
  7325. // already exists there, recursively merge the results together.
  7326. AddModifiedNodeToCSEMaps(User);
  7327. }
  7328. // If we just RAUW'd the root, take note.
  7329. if (From == getRoot())
  7330. setRoot(To);
  7331. }
  7332. namespace {
  7333. /// UseMemo - This class is used by SelectionDAG::ReplaceAllUsesOfValuesWith
  7334. /// to record information about a use.
  7335. struct UseMemo {
  7336. SDNode *User;
  7337. unsigned Index;
  7338. SDUse *Use;
  7339. };
  7340. /// operator< - Sort Memos by User.
  7341. bool operator<(const UseMemo &L, const UseMemo &R) {
  7342. return (intptr_t)L.User < (intptr_t)R.User;
  7343. }
  7344. } // end anonymous namespace
  7345. void SelectionDAG::updateDivergence(SDNode * N)
  7346. {
  7347. if (TLI->isSDNodeAlwaysUniform(N))
  7348. return;
  7349. bool IsDivergent = TLI->isSDNodeSourceOfDivergence(N, FLI, DA);
  7350. for (auto &Op : N->ops()) {
  7351. if (Op.Val.getValueType() != MVT::Other)
  7352. IsDivergent |= Op.getNode()->isDivergent();
  7353. }
  7354. if (N->SDNodeBits.IsDivergent != IsDivergent) {
  7355. N->SDNodeBits.IsDivergent = IsDivergent;
  7356. for (auto U : N->uses()) {
  7357. updateDivergence(U);
  7358. }
  7359. }
  7360. }
  7361. void SelectionDAG::CreateTopologicalOrder(std::vector<SDNode*>& Order) {
  7362. DenseMap<SDNode *, unsigned> Degree;
  7363. Order.reserve(AllNodes.size());
  7364. for (auto & N : allnodes()) {
  7365. unsigned NOps = N.getNumOperands();
  7366. Degree[&N] = NOps;
  7367. if (0 == NOps)
  7368. Order.push_back(&N);
  7369. }
  7370. for (std::vector<SDNode *>::iterator I = Order.begin();
  7371. I!=Order.end();++I) {
  7372. SDNode * N = *I;
  7373. for (auto U : N->uses()) {
  7374. unsigned &UnsortedOps = Degree[U];
  7375. if (0 == --UnsortedOps)
  7376. Order.push_back(U);
  7377. }
  7378. }
  7379. }
  7380. #ifndef NDEBUG
  7381. void SelectionDAG::VerifyDAGDiverence()
  7382. {
  7383. std::vector<SDNode*> TopoOrder;
  7384. CreateTopologicalOrder(TopoOrder);
  7385. const TargetLowering &TLI = getTargetLoweringInfo();
  7386. DenseMap<const SDNode *, bool> DivergenceMap;
  7387. for (auto &N : allnodes()) {
  7388. DivergenceMap[&N] = false;
  7389. }
  7390. for (auto N : TopoOrder) {
  7391. bool IsDivergent = DivergenceMap[N];
  7392. bool IsSDNodeDivergent = TLI.isSDNodeSourceOfDivergence(N, FLI, DA);
  7393. for (auto &Op : N->ops()) {
  7394. if (Op.Val.getValueType() != MVT::Other)
  7395. IsSDNodeDivergent |= DivergenceMap[Op.getNode()];
  7396. }
  7397. if (!IsDivergent && IsSDNodeDivergent && !TLI.isSDNodeAlwaysUniform(N)) {
  7398. DivergenceMap[N] = true;
  7399. }
  7400. }
  7401. for (auto &N : allnodes()) {
  7402. (void)N;
  7403. assert(DivergenceMap[&N] == N.isDivergent() &&
  7404. "Divergence bit inconsistency detected\n");
  7405. }
  7406. }
  7407. #endif
  7408. /// ReplaceAllUsesOfValuesWith - Replace any uses of From with To, leaving
  7409. /// uses of other values produced by From.getNode() alone. The same value
  7410. /// may appear in both the From and To list. The Deleted vector is
  7411. /// handled the same way as for ReplaceAllUsesWith.
  7412. void SelectionDAG::ReplaceAllUsesOfValuesWith(const SDValue *From,
  7413. const SDValue *To,
  7414. unsigned Num){
  7415. // Handle the simple, trivial case efficiently.
  7416. if (Num == 1)
  7417. return ReplaceAllUsesOfValueWith(*From, *To);
  7418. transferDbgValues(*From, *To);
  7419. // Read up all the uses and make records of them. This helps
  7420. // processing new uses that are introduced during the
  7421. // replacement process.
  7422. SmallVector<UseMemo, 4> Uses;
  7423. for (unsigned i = 0; i != Num; ++i) {
  7424. unsigned FromResNo = From[i].getResNo();
  7425. SDNode *FromNode = From[i].getNode();
  7426. for (SDNode::use_iterator UI = FromNode->use_begin(),
  7427. E = FromNode->use_end(); UI != E; ++UI) {
  7428. SDUse &Use = UI.getUse();
  7429. if (Use.getResNo() == FromResNo) {
  7430. UseMemo Memo = { *UI, i, &Use };
  7431. Uses.push_back(Memo);
  7432. }
  7433. }
  7434. }
  7435. // Sort the uses, so that all the uses from a given User are together.
  7436. llvm::sort(Uses);
  7437. for (unsigned UseIndex = 0, UseIndexEnd = Uses.size();
  7438. UseIndex != UseIndexEnd; ) {
  7439. // We know that this user uses some value of From. If it is the right
  7440. // value, update it.
  7441. SDNode *User = Uses[UseIndex].User;
  7442. // This node is about to morph, remove its old self from the CSE maps.
  7443. RemoveNodeFromCSEMaps(User);
  7444. // The Uses array is sorted, so all the uses for a given User
  7445. // are next to each other in the list.
  7446. // To help reduce the number of CSE recomputations, process all
  7447. // the uses of this user that we can find this way.
  7448. do {
  7449. unsigned i = Uses[UseIndex].Index;
  7450. SDUse &Use = *Uses[UseIndex].Use;
  7451. ++UseIndex;
  7452. Use.set(To[i]);
  7453. } while (UseIndex != UseIndexEnd && Uses[UseIndex].User == User);
  7454. // Now that we have modified User, add it back to the CSE maps. If it
  7455. // already exists there, recursively merge the results together.
  7456. AddModifiedNodeToCSEMaps(User);
  7457. }
  7458. }
  7459. /// AssignTopologicalOrder - Assign a unique node id for each node in the DAG
  7460. /// based on their topological order. It returns the maximum id and a vector
  7461. /// of the SDNodes* in assigned order by reference.
  7462. unsigned SelectionDAG::AssignTopologicalOrder() {
  7463. unsigned DAGSize = 0;
  7464. // SortedPos tracks the progress of the algorithm. Nodes before it are
  7465. // sorted, nodes after it are unsorted. When the algorithm completes
  7466. // it is at the end of the list.
  7467. allnodes_iterator SortedPos = allnodes_begin();
  7468. // Visit all the nodes. Move nodes with no operands to the front of
  7469. // the list immediately. Annotate nodes that do have operands with their
  7470. // operand count. Before we do this, the Node Id fields of the nodes
  7471. // may contain arbitrary values. After, the Node Id fields for nodes
  7472. // before SortedPos will contain the topological sort index, and the
  7473. // Node Id fields for nodes At SortedPos and after will contain the
  7474. // count of outstanding operands.
  7475. for (allnodes_iterator I = allnodes_begin(),E = allnodes_end(); I != E; ) {
  7476. SDNode *N = &*I++;
  7477. checkForCycles(N, this);
  7478. unsigned Degree = N->getNumOperands();
  7479. if (Degree == 0) {
  7480. // A node with no uses, add it to the result array immediately.
  7481. N->setNodeId(DAGSize++);
  7482. allnodes_iterator Q(N);
  7483. if (Q != SortedPos)
  7484. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(Q));
  7485. assert(SortedPos != AllNodes.end() && "Overran node list");
  7486. ++SortedPos;
  7487. } else {
  7488. // Temporarily use the Node Id as scratch space for the degree count.
  7489. N->setNodeId(Degree);
  7490. }
  7491. }
  7492. // Visit all the nodes. As we iterate, move nodes into sorted order,
  7493. // such that by the time the end is reached all nodes will be sorted.
  7494. for (SDNode &Node : allnodes()) {
  7495. SDNode *N = &Node;
  7496. checkForCycles(N, this);
  7497. // N is in sorted position, so all its uses have one less operand
  7498. // that needs to be sorted.
  7499. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  7500. UI != UE; ++UI) {
  7501. SDNode *P = *UI;
  7502. unsigned Degree = P->getNodeId();
  7503. assert(Degree != 0 && "Invalid node degree");
  7504. --Degree;
  7505. if (Degree == 0) {
  7506. // All of P's operands are sorted, so P may sorted now.
  7507. P->setNodeId(DAGSize++);
  7508. if (P->getIterator() != SortedPos)
  7509. SortedPos = AllNodes.insert(SortedPos, AllNodes.remove(P));
  7510. assert(SortedPos != AllNodes.end() && "Overran node list");
  7511. ++SortedPos;
  7512. } else {
  7513. // Update P's outstanding operand count.
  7514. P->setNodeId(Degree);
  7515. }
  7516. }
  7517. if (Node.getIterator() == SortedPos) {
  7518. #ifndef NDEBUG
  7519. allnodes_iterator I(N);
  7520. SDNode *S = &*++I;
  7521. dbgs() << "Overran sorted position:\n";
  7522. S->dumprFull(this); dbgs() << "\n";
  7523. dbgs() << "Checking if this is due to cycles\n";
  7524. checkForCycles(this, true);
  7525. #endif
  7526. llvm_unreachable(nullptr);
  7527. }
  7528. }
  7529. assert(SortedPos == AllNodes.end() &&
  7530. "Topological sort incomplete!");
  7531. assert(AllNodes.front().getOpcode() == ISD::EntryToken &&
  7532. "First node in topological sort is not the entry token!");
  7533. assert(AllNodes.front().getNodeId() == 0 &&
  7534. "First node in topological sort has non-zero id!");
  7535. assert(AllNodes.front().getNumOperands() == 0 &&
  7536. "First node in topological sort has operands!");
  7537. assert(AllNodes.back().getNodeId() == (int)DAGSize-1 &&
  7538. "Last node in topologic sort has unexpected id!");
  7539. assert(AllNodes.back().use_empty() &&
  7540. "Last node in topologic sort has users!");
  7541. assert(DAGSize == allnodes_size() && "Node count mismatch!");
  7542. return DAGSize;
  7543. }
  7544. /// AddDbgValue - Add a dbg_value SDNode. If SD is non-null that means the
  7545. /// value is produced by SD.
  7546. void SelectionDAG::AddDbgValue(SDDbgValue *DB, SDNode *SD, bool isParameter) {
  7547. if (SD) {
  7548. assert(DbgInfo->getSDDbgValues(SD).empty() || SD->getHasDebugValue());
  7549. SD->setHasDebugValue(true);
  7550. }
  7551. DbgInfo->add(DB, SD, isParameter);
  7552. }
  7553. void SelectionDAG::AddDbgLabel(SDDbgLabel *DB) {
  7554. DbgInfo->add(DB);
  7555. }
  7556. SDValue SelectionDAG::makeEquivalentMemoryOrdering(LoadSDNode *OldLoad,
  7557. SDValue NewMemOp) {
  7558. assert(isa<MemSDNode>(NewMemOp.getNode()) && "Expected a memop node");
  7559. // The new memory operation must have the same position as the old load in
  7560. // terms of memory dependency. Create a TokenFactor for the old load and new
  7561. // memory operation and update uses of the old load's output chain to use that
  7562. // TokenFactor.
  7563. SDValue OldChain = SDValue(OldLoad, 1);
  7564. SDValue NewChain = SDValue(NewMemOp.getNode(), 1);
  7565. if (!OldLoad->hasAnyUseOfValue(1))
  7566. return NewChain;
  7567. SDValue TokenFactor =
  7568. getNode(ISD::TokenFactor, SDLoc(OldLoad), MVT::Other, OldChain, NewChain);
  7569. ReplaceAllUsesOfValueWith(OldChain, TokenFactor);
  7570. UpdateNodeOperands(TokenFactor.getNode(), OldChain, NewChain);
  7571. return TokenFactor;
  7572. }
  7573. SDValue SelectionDAG::getSymbolFunctionGlobalAddress(SDValue Op,
  7574. Function **OutFunction) {
  7575. assert(isa<ExternalSymbolSDNode>(Op) && "Node should be an ExternalSymbol");
  7576. auto *Symbol = cast<ExternalSymbolSDNode>(Op)->getSymbol();
  7577. auto *Module = MF->getFunction().getParent();
  7578. auto *Function = Module->getFunction(Symbol);
  7579. if (OutFunction != nullptr)
  7580. *OutFunction = Function;
  7581. if (Function != nullptr) {
  7582. auto PtrTy = TLI->getPointerTy(getDataLayout(), Function->getAddressSpace());
  7583. return getGlobalAddress(Function, SDLoc(Op), PtrTy);
  7584. }
  7585. std::string ErrorStr;
  7586. raw_string_ostream ErrorFormatter(ErrorStr);
  7587. ErrorFormatter << "Undefined external symbol ";
  7588. ErrorFormatter << '"' << Symbol << '"';
  7589. ErrorFormatter.flush();
  7590. report_fatal_error(ErrorStr);
  7591. }
  7592. //===----------------------------------------------------------------------===//
  7593. // SDNode Class
  7594. //===----------------------------------------------------------------------===//
  7595. bool llvm::isNullConstant(SDValue V) {
  7596. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  7597. return Const != nullptr && Const->isNullValue();
  7598. }
  7599. bool llvm::isNullFPConstant(SDValue V) {
  7600. ConstantFPSDNode *Const = dyn_cast<ConstantFPSDNode>(V);
  7601. return Const != nullptr && Const->isZero() && !Const->isNegative();
  7602. }
  7603. bool llvm::isAllOnesConstant(SDValue V) {
  7604. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  7605. return Const != nullptr && Const->isAllOnesValue();
  7606. }
  7607. bool llvm::isOneConstant(SDValue V) {
  7608. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(V);
  7609. return Const != nullptr && Const->isOne();
  7610. }
  7611. SDValue llvm::peekThroughBitcasts(SDValue V) {
  7612. while (V.getOpcode() == ISD::BITCAST)
  7613. V = V.getOperand(0);
  7614. return V;
  7615. }
  7616. SDValue llvm::peekThroughOneUseBitcasts(SDValue V) {
  7617. while (V.getOpcode() == ISD::BITCAST && V.getOperand(0).hasOneUse())
  7618. V = V.getOperand(0);
  7619. return V;
  7620. }
  7621. SDValue llvm::peekThroughExtractSubvectors(SDValue V) {
  7622. while (V.getOpcode() == ISD::EXTRACT_SUBVECTOR)
  7623. V = V.getOperand(0);
  7624. return V;
  7625. }
  7626. bool llvm::isBitwiseNot(SDValue V) {
  7627. if (V.getOpcode() != ISD::XOR)
  7628. return false;
  7629. ConstantSDNode *C = isConstOrConstSplat(peekThroughBitcasts(V.getOperand(1)));
  7630. return C && C->isAllOnesValue();
  7631. }
  7632. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, bool AllowUndefs) {
  7633. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
  7634. return CN;
  7635. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7636. BitVector UndefElements;
  7637. ConstantSDNode *CN = BV->getConstantSplatNode(&UndefElements);
  7638. // BuildVectors can truncate their operands. Ignore that case here.
  7639. if (CN && (UndefElements.none() || AllowUndefs) &&
  7640. CN->getValueType(0) == N.getValueType().getScalarType())
  7641. return CN;
  7642. }
  7643. return nullptr;
  7644. }
  7645. ConstantSDNode *llvm::isConstOrConstSplat(SDValue N, const APInt &DemandedElts,
  7646. bool AllowUndefs) {
  7647. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N))
  7648. return CN;
  7649. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7650. BitVector UndefElements;
  7651. ConstantSDNode *CN = BV->getConstantSplatNode(DemandedElts, &UndefElements);
  7652. // BuildVectors can truncate their operands. Ignore that case here.
  7653. if (CN && (UndefElements.none() || AllowUndefs) &&
  7654. CN->getValueType(0) == N.getValueType().getScalarType())
  7655. return CN;
  7656. }
  7657. return nullptr;
  7658. }
  7659. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N, bool AllowUndefs) {
  7660. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
  7661. return CN;
  7662. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7663. BitVector UndefElements;
  7664. ConstantFPSDNode *CN = BV->getConstantFPSplatNode(&UndefElements);
  7665. if (CN && (UndefElements.none() || AllowUndefs))
  7666. return CN;
  7667. }
  7668. return nullptr;
  7669. }
  7670. ConstantFPSDNode *llvm::isConstOrConstSplatFP(SDValue N,
  7671. const APInt &DemandedElts,
  7672. bool AllowUndefs) {
  7673. if (ConstantFPSDNode *CN = dyn_cast<ConstantFPSDNode>(N))
  7674. return CN;
  7675. if (BuildVectorSDNode *BV = dyn_cast<BuildVectorSDNode>(N)) {
  7676. BitVector UndefElements;
  7677. ConstantFPSDNode *CN =
  7678. BV->getConstantFPSplatNode(DemandedElts, &UndefElements);
  7679. if (CN && (UndefElements.none() || AllowUndefs))
  7680. return CN;
  7681. }
  7682. return nullptr;
  7683. }
  7684. bool llvm::isNullOrNullSplat(SDValue N, bool AllowUndefs) {
  7685. // TODO: may want to use peekThroughBitcast() here.
  7686. ConstantSDNode *C = isConstOrConstSplat(N, AllowUndefs);
  7687. return C && C->isNullValue();
  7688. }
  7689. bool llvm::isOneOrOneSplat(SDValue N) {
  7690. // TODO: may want to use peekThroughBitcast() here.
  7691. unsigned BitWidth = N.getScalarValueSizeInBits();
  7692. ConstantSDNode *C = isConstOrConstSplat(N);
  7693. return C && C->isOne() && C->getValueSizeInBits(0) == BitWidth;
  7694. }
  7695. bool llvm::isAllOnesOrAllOnesSplat(SDValue N) {
  7696. N = peekThroughBitcasts(N);
  7697. unsigned BitWidth = N.getScalarValueSizeInBits();
  7698. ConstantSDNode *C = isConstOrConstSplat(N);
  7699. return C && C->isAllOnesValue() && C->getValueSizeInBits(0) == BitWidth;
  7700. }
  7701. HandleSDNode::~HandleSDNode() {
  7702. DropOperands();
  7703. }
  7704. GlobalAddressSDNode::GlobalAddressSDNode(unsigned Opc, unsigned Order,
  7705. const DebugLoc &DL,
  7706. const GlobalValue *GA, EVT VT,
  7707. int64_t o, unsigned char TF)
  7708. : SDNode(Opc, Order, DL, getSDVTList(VT)), Offset(o), TargetFlags(TF) {
  7709. TheGlobal = GA;
  7710. }
  7711. AddrSpaceCastSDNode::AddrSpaceCastSDNode(unsigned Order, const DebugLoc &dl,
  7712. EVT VT, unsigned SrcAS,
  7713. unsigned DestAS)
  7714. : SDNode(ISD::ADDRSPACECAST, Order, dl, getSDVTList(VT)),
  7715. SrcAddrSpace(SrcAS), DestAddrSpace(DestAS) {}
  7716. MemSDNode::MemSDNode(unsigned Opc, unsigned Order, const DebugLoc &dl,
  7717. SDVTList VTs, EVT memvt, MachineMemOperand *mmo)
  7718. : SDNode(Opc, Order, dl, VTs), MemoryVT(memvt), MMO(mmo) {
  7719. MemSDNodeBits.IsVolatile = MMO->isVolatile();
  7720. MemSDNodeBits.IsNonTemporal = MMO->isNonTemporal();
  7721. MemSDNodeBits.IsDereferenceable = MMO->isDereferenceable();
  7722. MemSDNodeBits.IsInvariant = MMO->isInvariant();
  7723. // We check here that the size of the memory operand fits within the size of
  7724. // the MMO. This is because the MMO might indicate only a possible address
  7725. // range instead of specifying the affected memory addresses precisely.
  7726. assert(memvt.getStoreSize() <= MMO->getSize() && "Size mismatch!");
  7727. }
  7728. /// Profile - Gather unique data for the node.
  7729. ///
  7730. void SDNode::Profile(FoldingSetNodeID &ID) const {
  7731. AddNodeIDNode(ID, this);
  7732. }
  7733. namespace {
  7734. struct EVTArray {
  7735. std::vector<EVT> VTs;
  7736. EVTArray() {
  7737. VTs.reserve(MVT::LAST_VALUETYPE);
  7738. for (unsigned i = 0; i < MVT::LAST_VALUETYPE; ++i)
  7739. VTs.push_back(MVT((MVT::SimpleValueType)i));
  7740. }
  7741. };
  7742. } // end anonymous namespace
  7743. static ManagedStatic<std::set<EVT, EVT::compareRawBits>> EVTs;
  7744. static ManagedStatic<EVTArray> SimpleVTArray;
  7745. static ManagedStatic<sys::SmartMutex<true>> VTMutex;
  7746. /// getValueTypeList - Return a pointer to the specified value type.
  7747. ///
  7748. const EVT *SDNode::getValueTypeList(EVT VT) {
  7749. if (VT.isExtended()) {
  7750. sys::SmartScopedLock<true> Lock(*VTMutex);
  7751. return &(*EVTs->insert(VT).first);
  7752. } else {
  7753. assert(VT.getSimpleVT() < MVT::LAST_VALUETYPE &&
  7754. "Value type out of range!");
  7755. return &SimpleVTArray->VTs[VT.getSimpleVT().SimpleTy];
  7756. }
  7757. }
  7758. /// hasNUsesOfValue - Return true if there are exactly NUSES uses of the
  7759. /// indicated value. This method ignores uses of other values defined by this
  7760. /// operation.
  7761. bool SDNode::hasNUsesOfValue(unsigned NUses, unsigned Value) const {
  7762. assert(Value < getNumValues() && "Bad value!");
  7763. // TODO: Only iterate over uses of a given value of the node
  7764. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI) {
  7765. if (UI.getUse().getResNo() == Value) {
  7766. if (NUses == 0)
  7767. return false;
  7768. --NUses;
  7769. }
  7770. }
  7771. // Found exactly the right number of uses?
  7772. return NUses == 0;
  7773. }
  7774. /// hasAnyUseOfValue - Return true if there are any use of the indicated
  7775. /// value. This method ignores uses of other values defined by this operation.
  7776. bool SDNode::hasAnyUseOfValue(unsigned Value) const {
  7777. assert(Value < getNumValues() && "Bad value!");
  7778. for (SDNode::use_iterator UI = use_begin(), E = use_end(); UI != E; ++UI)
  7779. if (UI.getUse().getResNo() == Value)
  7780. return true;
  7781. return false;
  7782. }
  7783. /// isOnlyUserOf - Return true if this node is the only use of N.
  7784. bool SDNode::isOnlyUserOf(const SDNode *N) const {
  7785. bool Seen = false;
  7786. for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
  7787. SDNode *User = *I;
  7788. if (User == this)
  7789. Seen = true;
  7790. else
  7791. return false;
  7792. }
  7793. return Seen;
  7794. }
  7795. /// Return true if the only users of N are contained in Nodes.
  7796. bool SDNode::areOnlyUsersOf(ArrayRef<const SDNode *> Nodes, const SDNode *N) {
  7797. bool Seen = false;
  7798. for (SDNode::use_iterator I = N->use_begin(), E = N->use_end(); I != E; ++I) {
  7799. SDNode *User = *I;
  7800. if (llvm::any_of(Nodes,
  7801. [&User](const SDNode *Node) { return User == Node; }))
  7802. Seen = true;
  7803. else
  7804. return false;
  7805. }
  7806. return Seen;
  7807. }
  7808. /// isOperand - Return true if this node is an operand of N.
  7809. bool SDValue::isOperandOf(const SDNode *N) const {
  7810. for (const SDValue &Op : N->op_values())
  7811. if (*this == Op)
  7812. return true;
  7813. return false;
  7814. }
  7815. bool SDNode::isOperandOf(const SDNode *N) const {
  7816. for (const SDValue &Op : N->op_values())
  7817. if (this == Op.getNode())
  7818. return true;
  7819. return false;
  7820. }
  7821. /// reachesChainWithoutSideEffects - Return true if this operand (which must
  7822. /// be a chain) reaches the specified operand without crossing any
  7823. /// side-effecting instructions on any chain path. In practice, this looks
  7824. /// through token factors and non-volatile loads. In order to remain efficient,
  7825. /// this only looks a couple of nodes in, it does not do an exhaustive search.
  7826. ///
  7827. /// Note that we only need to examine chains when we're searching for
  7828. /// side-effects; SelectionDAG requires that all side-effects are represented
  7829. /// by chains, even if another operand would force a specific ordering. This
  7830. /// constraint is necessary to allow transformations like splitting loads.
  7831. bool SDValue::reachesChainWithoutSideEffects(SDValue Dest,
  7832. unsigned Depth) const {
  7833. if (*this == Dest) return true;
  7834. // Don't search too deeply, we just want to be able to see through
  7835. // TokenFactor's etc.
  7836. if (Depth == 0) return false;
  7837. // If this is a token factor, all inputs to the TF happen in parallel.
  7838. if (getOpcode() == ISD::TokenFactor) {
  7839. // First, try a shallow search.
  7840. if (is_contained((*this)->ops(), Dest)) {
  7841. // We found the chain we want as an operand of this TokenFactor.
  7842. // Essentially, we reach the chain without side-effects if we could
  7843. // serialize the TokenFactor into a simple chain of operations with
  7844. // Dest as the last operation. This is automatically true if the
  7845. // chain has one use: there are no other ordering constraints.
  7846. // If the chain has more than one use, we give up: some other
  7847. // use of Dest might force a side-effect between Dest and the current
  7848. // node.
  7849. if (Dest.hasOneUse())
  7850. return true;
  7851. }
  7852. // Next, try a deep search: check whether every operand of the TokenFactor
  7853. // reaches Dest.
  7854. return llvm::all_of((*this)->ops(), [=](SDValue Op) {
  7855. return Op.reachesChainWithoutSideEffects(Dest, Depth - 1);
  7856. });
  7857. }
  7858. // Loads don't have side effects, look through them.
  7859. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(*this)) {
  7860. if (!Ld->isVolatile())
  7861. return Ld->getChain().reachesChainWithoutSideEffects(Dest, Depth-1);
  7862. }
  7863. return false;
  7864. }
  7865. bool SDNode::hasPredecessor(const SDNode *N) const {
  7866. SmallPtrSet<const SDNode *, 32> Visited;
  7867. SmallVector<const SDNode *, 16> Worklist;
  7868. Worklist.push_back(this);
  7869. return hasPredecessorHelper(N, Visited, Worklist);
  7870. }
  7871. void SDNode::intersectFlagsWith(const SDNodeFlags Flags) {
  7872. this->Flags.intersectWith(Flags);
  7873. }
  7874. SDValue
  7875. SelectionDAG::matchBinOpReduction(SDNode *Extract, ISD::NodeType &BinOp,
  7876. ArrayRef<ISD::NodeType> CandidateBinOps) {
  7877. // The pattern must end in an extract from index 0.
  7878. if (Extract->getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  7879. !isNullConstant(Extract->getOperand(1)))
  7880. return SDValue();
  7881. SDValue Op = Extract->getOperand(0);
  7882. unsigned Stages = Log2_32(Op.getValueType().getVectorNumElements());
  7883. // Match against one of the candidate binary ops.
  7884. if (llvm::none_of(CandidateBinOps, [Op](ISD::NodeType BinOp) {
  7885. return Op.getOpcode() == unsigned(BinOp);
  7886. }))
  7887. return SDValue();
  7888. // At each stage, we're looking for something that looks like:
  7889. // %s = shufflevector <8 x i32> %op, <8 x i32> undef,
  7890. // <8 x i32> <i32 2, i32 3, i32 undef, i32 undef,
  7891. // i32 undef, i32 undef, i32 undef, i32 undef>
  7892. // %a = binop <8 x i32> %op, %s
  7893. // Where the mask changes according to the stage. E.g. for a 3-stage pyramid,
  7894. // we expect something like:
  7895. // <4,5,6,7,u,u,u,u>
  7896. // <2,3,u,u,u,u,u,u>
  7897. // <1,u,u,u,u,u,u,u>
  7898. unsigned CandidateBinOp = Op.getOpcode();
  7899. for (unsigned i = 0; i < Stages; ++i) {
  7900. if (Op.getOpcode() != CandidateBinOp)
  7901. return SDValue();
  7902. SDValue Op0 = Op.getOperand(0);
  7903. SDValue Op1 = Op.getOperand(1);
  7904. ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(Op0);
  7905. if (Shuffle) {
  7906. Op = Op1;
  7907. } else {
  7908. Shuffle = dyn_cast<ShuffleVectorSDNode>(Op1);
  7909. Op = Op0;
  7910. }
  7911. // The first operand of the shuffle should be the same as the other operand
  7912. // of the binop.
  7913. if (!Shuffle || Shuffle->getOperand(0) != Op)
  7914. return SDValue();
  7915. // Verify the shuffle has the expected (at this stage of the pyramid) mask.
  7916. for (int Index = 0, MaskEnd = 1 << i; Index < MaskEnd; ++Index)
  7917. if (Shuffle->getMaskElt(Index) != MaskEnd + Index)
  7918. return SDValue();
  7919. }
  7920. BinOp = (ISD::NodeType)CandidateBinOp;
  7921. return Op;
  7922. }
  7923. SDValue SelectionDAG::UnrollVectorOp(SDNode *N, unsigned ResNE) {
  7924. assert(N->getNumValues() == 1 &&
  7925. "Can't unroll a vector with multiple results!");
  7926. EVT VT = N->getValueType(0);
  7927. unsigned NE = VT.getVectorNumElements();
  7928. EVT EltVT = VT.getVectorElementType();
  7929. SDLoc dl(N);
  7930. SmallVector<SDValue, 8> Scalars;
  7931. SmallVector<SDValue, 4> Operands(N->getNumOperands());
  7932. // If ResNE is 0, fully unroll the vector op.
  7933. if (ResNE == 0)
  7934. ResNE = NE;
  7935. else if (NE > ResNE)
  7936. NE = ResNE;
  7937. unsigned i;
  7938. for (i= 0; i != NE; ++i) {
  7939. for (unsigned j = 0, e = N->getNumOperands(); j != e; ++j) {
  7940. SDValue Operand = N->getOperand(j);
  7941. EVT OperandVT = Operand.getValueType();
  7942. if (OperandVT.isVector()) {
  7943. // A vector operand; extract a single element.
  7944. EVT OperandEltVT = OperandVT.getVectorElementType();
  7945. Operands[j] =
  7946. getNode(ISD::EXTRACT_VECTOR_ELT, dl, OperandEltVT, Operand,
  7947. getConstant(i, dl, TLI->getVectorIdxTy(getDataLayout())));
  7948. } else {
  7949. // A scalar operand; just use it as is.
  7950. Operands[j] = Operand;
  7951. }
  7952. }
  7953. switch (N->getOpcode()) {
  7954. default: {
  7955. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands,
  7956. N->getFlags()));
  7957. break;
  7958. }
  7959. case ISD::VSELECT:
  7960. Scalars.push_back(getNode(ISD::SELECT, dl, EltVT, Operands));
  7961. break;
  7962. case ISD::SHL:
  7963. case ISD::SRA:
  7964. case ISD::SRL:
  7965. case ISD::ROTL:
  7966. case ISD::ROTR:
  7967. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT, Operands[0],
  7968. getShiftAmountOperand(Operands[0].getValueType(),
  7969. Operands[1])));
  7970. break;
  7971. case ISD::SIGN_EXTEND_INREG:
  7972. case ISD::FP_ROUND_INREG: {
  7973. EVT ExtVT = cast<VTSDNode>(Operands[1])->getVT().getVectorElementType();
  7974. Scalars.push_back(getNode(N->getOpcode(), dl, EltVT,
  7975. Operands[0],
  7976. getValueType(ExtVT)));
  7977. }
  7978. }
  7979. }
  7980. for (; i < ResNE; ++i)
  7981. Scalars.push_back(getUNDEF(EltVT));
  7982. EVT VecVT = EVT::getVectorVT(*getContext(), EltVT, ResNE);
  7983. return getBuildVector(VecVT, dl, Scalars);
  7984. }
  7985. std::pair<SDValue, SDValue> SelectionDAG::UnrollVectorOverflowOp(
  7986. SDNode *N, unsigned ResNE) {
  7987. unsigned Opcode = N->getOpcode();
  7988. assert((Opcode == ISD::UADDO || Opcode == ISD::SADDO ||
  7989. Opcode == ISD::USUBO || Opcode == ISD::SSUBO ||
  7990. Opcode == ISD::UMULO || Opcode == ISD::SMULO) &&
  7991. "Expected an overflow opcode");
  7992. EVT ResVT = N->getValueType(0);
  7993. EVT OvVT = N->getValueType(1);
  7994. EVT ResEltVT = ResVT.getVectorElementType();
  7995. EVT OvEltVT = OvVT.getVectorElementType();
  7996. SDLoc dl(N);
  7997. // If ResNE is 0, fully unroll the vector op.
  7998. unsigned NE = ResVT.getVectorNumElements();
  7999. if (ResNE == 0)
  8000. ResNE = NE;
  8001. else if (NE > ResNE)
  8002. NE = ResNE;
  8003. SmallVector<SDValue, 8> LHSScalars;
  8004. SmallVector<SDValue, 8> RHSScalars;
  8005. ExtractVectorElements(N->getOperand(0), LHSScalars, 0, NE);
  8006. ExtractVectorElements(N->getOperand(1), RHSScalars, 0, NE);
  8007. EVT SVT = TLI->getSetCCResultType(getDataLayout(), *getContext(), ResEltVT);
  8008. SDVTList VTs = getVTList(ResEltVT, SVT);
  8009. SmallVector<SDValue, 8> ResScalars;
  8010. SmallVector<SDValue, 8> OvScalars;
  8011. for (unsigned i = 0; i < NE; ++i) {
  8012. SDValue Res = getNode(Opcode, dl, VTs, LHSScalars[i], RHSScalars[i]);
  8013. SDValue Ov =
  8014. getSelect(dl, OvEltVT, Res.getValue(1),
  8015. getBoolConstant(true, dl, OvEltVT, ResVT),
  8016. getConstant(0, dl, OvEltVT));
  8017. ResScalars.push_back(Res);
  8018. OvScalars.push_back(Ov);
  8019. }
  8020. ResScalars.append(ResNE - NE, getUNDEF(ResEltVT));
  8021. OvScalars.append(ResNE - NE, getUNDEF(OvEltVT));
  8022. EVT NewResVT = EVT::getVectorVT(*getContext(), ResEltVT, ResNE);
  8023. EVT NewOvVT = EVT::getVectorVT(*getContext(), OvEltVT, ResNE);
  8024. return std::make_pair(getBuildVector(NewResVT, dl, ResScalars),
  8025. getBuildVector(NewOvVT, dl, OvScalars));
  8026. }
  8027. bool SelectionDAG::areNonVolatileConsecutiveLoads(LoadSDNode *LD,
  8028. LoadSDNode *Base,
  8029. unsigned Bytes,
  8030. int Dist) const {
  8031. if (LD->isVolatile() || Base->isVolatile())
  8032. return false;
  8033. if (LD->isIndexed() || Base->isIndexed())
  8034. return false;
  8035. if (LD->getChain() != Base->getChain())
  8036. return false;
  8037. EVT VT = LD->getValueType(0);
  8038. if (VT.getSizeInBits() / 8 != Bytes)
  8039. return false;
  8040. auto BaseLocDecomp = BaseIndexOffset::match(Base, *this);
  8041. auto LocDecomp = BaseIndexOffset::match(LD, *this);
  8042. int64_t Offset = 0;
  8043. if (BaseLocDecomp.equalBaseIndex(LocDecomp, *this, Offset))
  8044. return (Dist * Bytes == Offset);
  8045. return false;
  8046. }
  8047. /// InferPtrAlignment - Infer alignment of a load / store address. Return 0 if
  8048. /// it cannot be inferred.
  8049. unsigned SelectionDAG::InferPtrAlignment(SDValue Ptr) const {
  8050. // If this is a GlobalAddress + cst, return the alignment.
  8051. const GlobalValue *GV;
  8052. int64_t GVOffset = 0;
  8053. if (TLI->isGAPlusOffset(Ptr.getNode(), GV, GVOffset)) {
  8054. unsigned IdxWidth = getDataLayout().getIndexTypeSizeInBits(GV->getType());
  8055. KnownBits Known(IdxWidth);
  8056. llvm::computeKnownBits(GV, Known, getDataLayout());
  8057. unsigned AlignBits = Known.countMinTrailingZeros();
  8058. unsigned Align = AlignBits ? 1 << std::min(31U, AlignBits) : 0;
  8059. if (Align)
  8060. return MinAlign(Align, GVOffset);
  8061. }
  8062. // If this is a direct reference to a stack slot, use information about the
  8063. // stack slot's alignment.
  8064. int FrameIdx = 1 << 31;
  8065. int64_t FrameOffset = 0;
  8066. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Ptr)) {
  8067. FrameIdx = FI->getIndex();
  8068. } else if (isBaseWithConstantOffset(Ptr) &&
  8069. isa<FrameIndexSDNode>(Ptr.getOperand(0))) {
  8070. // Handle FI+Cst
  8071. FrameIdx = cast<FrameIndexSDNode>(Ptr.getOperand(0))->getIndex();
  8072. FrameOffset = Ptr.getConstantOperandVal(1);
  8073. }
  8074. if (FrameIdx != (1 << 31)) {
  8075. const MachineFrameInfo &MFI = getMachineFunction().getFrameInfo();
  8076. unsigned FIInfoAlign = MinAlign(MFI.getObjectAlignment(FrameIdx),
  8077. FrameOffset);
  8078. return FIInfoAlign;
  8079. }
  8080. return 0;
  8081. }
  8082. /// GetSplitDestVTs - Compute the VTs needed for the low/hi parts of a type
  8083. /// which is split (or expanded) into two not necessarily identical pieces.
  8084. std::pair<EVT, EVT> SelectionDAG::GetSplitDestVTs(const EVT &VT) const {
  8085. // Currently all types are split in half.
  8086. EVT LoVT, HiVT;
  8087. if (!VT.isVector())
  8088. LoVT = HiVT = TLI->getTypeToTransformTo(*getContext(), VT);
  8089. else
  8090. LoVT = HiVT = VT.getHalfNumVectorElementsVT(*getContext());
  8091. return std::make_pair(LoVT, HiVT);
  8092. }
  8093. /// SplitVector - Split the vector with EXTRACT_SUBVECTOR and return the
  8094. /// low/high part.
  8095. std::pair<SDValue, SDValue>
  8096. SelectionDAG::SplitVector(const SDValue &N, const SDLoc &DL, const EVT &LoVT,
  8097. const EVT &HiVT) {
  8098. assert(LoVT.getVectorNumElements() + HiVT.getVectorNumElements() <=
  8099. N.getValueType().getVectorNumElements() &&
  8100. "More vector elements requested than available!");
  8101. SDValue Lo, Hi;
  8102. Lo = getNode(ISD::EXTRACT_SUBVECTOR, DL, LoVT, N,
  8103. getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
  8104. Hi = getNode(ISD::EXTRACT_SUBVECTOR, DL, HiVT, N,
  8105. getConstant(LoVT.getVectorNumElements(), DL,
  8106. TLI->getVectorIdxTy(getDataLayout())));
  8107. return std::make_pair(Lo, Hi);
  8108. }
  8109. /// Widen the vector up to the next power of two using INSERT_SUBVECTOR.
  8110. SDValue SelectionDAG::WidenVector(const SDValue &N, const SDLoc &DL) {
  8111. EVT VT = N.getValueType();
  8112. EVT WideVT = EVT::getVectorVT(*getContext(), VT.getVectorElementType(),
  8113. NextPowerOf2(VT.getVectorNumElements()));
  8114. return getNode(ISD::INSERT_SUBVECTOR, DL, WideVT, getUNDEF(WideVT), N,
  8115. getConstant(0, DL, TLI->getVectorIdxTy(getDataLayout())));
  8116. }
  8117. void SelectionDAG::ExtractVectorElements(SDValue Op,
  8118. SmallVectorImpl<SDValue> &Args,
  8119. unsigned Start, unsigned Count) {
  8120. EVT VT = Op.getValueType();
  8121. if (Count == 0)
  8122. Count = VT.getVectorNumElements();
  8123. EVT EltVT = VT.getVectorElementType();
  8124. EVT IdxTy = TLI->getVectorIdxTy(getDataLayout());
  8125. SDLoc SL(Op);
  8126. for (unsigned i = Start, e = Start + Count; i != e; ++i) {
  8127. Args.push_back(getNode(ISD::EXTRACT_VECTOR_ELT, SL, EltVT,
  8128. Op, getConstant(i, SL, IdxTy)));
  8129. }
  8130. }
  8131. // getAddressSpace - Return the address space this GlobalAddress belongs to.
  8132. unsigned GlobalAddressSDNode::getAddressSpace() const {
  8133. return getGlobal()->getType()->getAddressSpace();
  8134. }
  8135. Type *ConstantPoolSDNode::getType() const {
  8136. if (isMachineConstantPoolEntry())
  8137. return Val.MachineCPVal->getType();
  8138. return Val.ConstVal->getType();
  8139. }
  8140. bool BuildVectorSDNode::isConstantSplat(APInt &SplatValue, APInt &SplatUndef,
  8141. unsigned &SplatBitSize,
  8142. bool &HasAnyUndefs,
  8143. unsigned MinSplatBits,
  8144. bool IsBigEndian) const {
  8145. EVT VT = getValueType(0);
  8146. assert(VT.isVector() && "Expected a vector type");
  8147. unsigned VecWidth = VT.getSizeInBits();
  8148. if (MinSplatBits > VecWidth)
  8149. return false;
  8150. // FIXME: The widths are based on this node's type, but build vectors can
  8151. // truncate their operands.
  8152. SplatValue = APInt(VecWidth, 0);
  8153. SplatUndef = APInt(VecWidth, 0);
  8154. // Get the bits. Bits with undefined values (when the corresponding element
  8155. // of the vector is an ISD::UNDEF value) are set in SplatUndef and cleared
  8156. // in SplatValue. If any of the values are not constant, give up and return
  8157. // false.
  8158. unsigned int NumOps = getNumOperands();
  8159. assert(NumOps > 0 && "isConstantSplat has 0-size build vector");
  8160. unsigned EltWidth = VT.getScalarSizeInBits();
  8161. for (unsigned j = 0; j < NumOps; ++j) {
  8162. unsigned i = IsBigEndian ? NumOps - 1 - j : j;
  8163. SDValue OpVal = getOperand(i);
  8164. unsigned BitPos = j * EltWidth;
  8165. if (OpVal.isUndef())
  8166. SplatUndef.setBits(BitPos, BitPos + EltWidth);
  8167. else if (auto *CN = dyn_cast<ConstantSDNode>(OpVal))
  8168. SplatValue.insertBits(CN->getAPIntValue().zextOrTrunc(EltWidth), BitPos);
  8169. else if (auto *CN = dyn_cast<ConstantFPSDNode>(OpVal))
  8170. SplatValue.insertBits(CN->getValueAPF().bitcastToAPInt(), BitPos);
  8171. else
  8172. return false;
  8173. }
  8174. // The build_vector is all constants or undefs. Find the smallest element
  8175. // size that splats the vector.
  8176. HasAnyUndefs = (SplatUndef != 0);
  8177. // FIXME: This does not work for vectors with elements less than 8 bits.
  8178. while (VecWidth > 8) {
  8179. unsigned HalfSize = VecWidth / 2;
  8180. APInt HighValue = SplatValue.lshr(HalfSize).trunc(HalfSize);
  8181. APInt LowValue = SplatValue.trunc(HalfSize);
  8182. APInt HighUndef = SplatUndef.lshr(HalfSize).trunc(HalfSize);
  8183. APInt LowUndef = SplatUndef.trunc(HalfSize);
  8184. // If the two halves do not match (ignoring undef bits), stop here.
  8185. if ((HighValue & ~LowUndef) != (LowValue & ~HighUndef) ||
  8186. MinSplatBits > HalfSize)
  8187. break;
  8188. SplatValue = HighValue | LowValue;
  8189. SplatUndef = HighUndef & LowUndef;
  8190. VecWidth = HalfSize;
  8191. }
  8192. SplatBitSize = VecWidth;
  8193. return true;
  8194. }
  8195. SDValue BuildVectorSDNode::getSplatValue(const APInt &DemandedElts,
  8196. BitVector *UndefElements) const {
  8197. if (UndefElements) {
  8198. UndefElements->clear();
  8199. UndefElements->resize(getNumOperands());
  8200. }
  8201. assert(getNumOperands() == DemandedElts.getBitWidth() &&
  8202. "Unexpected vector size");
  8203. if (!DemandedElts)
  8204. return SDValue();
  8205. SDValue Splatted;
  8206. for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
  8207. if (!DemandedElts[i])
  8208. continue;
  8209. SDValue Op = getOperand(i);
  8210. if (Op.isUndef()) {
  8211. if (UndefElements)
  8212. (*UndefElements)[i] = true;
  8213. } else if (!Splatted) {
  8214. Splatted = Op;
  8215. } else if (Splatted != Op) {
  8216. return SDValue();
  8217. }
  8218. }
  8219. if (!Splatted) {
  8220. unsigned FirstDemandedIdx = DemandedElts.countTrailingZeros();
  8221. assert(getOperand(FirstDemandedIdx).isUndef() &&
  8222. "Can only have a splat without a constant for all undefs.");
  8223. return getOperand(FirstDemandedIdx);
  8224. }
  8225. return Splatted;
  8226. }
  8227. SDValue BuildVectorSDNode::getSplatValue(BitVector *UndefElements) const {
  8228. APInt DemandedElts = APInt::getAllOnesValue(getNumOperands());
  8229. return getSplatValue(DemandedElts, UndefElements);
  8230. }
  8231. ConstantSDNode *
  8232. BuildVectorSDNode::getConstantSplatNode(const APInt &DemandedElts,
  8233. BitVector *UndefElements) const {
  8234. return dyn_cast_or_null<ConstantSDNode>(
  8235. getSplatValue(DemandedElts, UndefElements));
  8236. }
  8237. ConstantSDNode *
  8238. BuildVectorSDNode::getConstantSplatNode(BitVector *UndefElements) const {
  8239. return dyn_cast_or_null<ConstantSDNode>(getSplatValue(UndefElements));
  8240. }
  8241. ConstantFPSDNode *
  8242. BuildVectorSDNode::getConstantFPSplatNode(const APInt &DemandedElts,
  8243. BitVector *UndefElements) const {
  8244. return dyn_cast_or_null<ConstantFPSDNode>(
  8245. getSplatValue(DemandedElts, UndefElements));
  8246. }
  8247. ConstantFPSDNode *
  8248. BuildVectorSDNode::getConstantFPSplatNode(BitVector *UndefElements) const {
  8249. return dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements));
  8250. }
  8251. int32_t
  8252. BuildVectorSDNode::getConstantFPSplatPow2ToLog2Int(BitVector *UndefElements,
  8253. uint32_t BitWidth) const {
  8254. if (ConstantFPSDNode *CN =
  8255. dyn_cast_or_null<ConstantFPSDNode>(getSplatValue(UndefElements))) {
  8256. bool IsExact;
  8257. APSInt IntVal(BitWidth);
  8258. const APFloat &APF = CN->getValueAPF();
  8259. if (APF.convertToInteger(IntVal, APFloat::rmTowardZero, &IsExact) !=
  8260. APFloat::opOK ||
  8261. !IsExact)
  8262. return -1;
  8263. return IntVal.exactLogBase2();
  8264. }
  8265. return -1;
  8266. }
  8267. bool BuildVectorSDNode::isConstant() const {
  8268. for (const SDValue &Op : op_values()) {
  8269. unsigned Opc = Op.getOpcode();
  8270. if (Opc != ISD::UNDEF && Opc != ISD::Constant && Opc != ISD::ConstantFP)
  8271. return false;
  8272. }
  8273. return true;
  8274. }
  8275. bool ShuffleVectorSDNode::isSplatMask(const int *Mask, EVT VT) {
  8276. // Find the first non-undef value in the shuffle mask.
  8277. unsigned i, e;
  8278. for (i = 0, e = VT.getVectorNumElements(); i != e && Mask[i] < 0; ++i)
  8279. /* search */;
  8280. // If all elements are undefined, this shuffle can be considered a splat
  8281. // (although it should eventually get simplified away completely).
  8282. if (i == e)
  8283. return true;
  8284. // Make sure all remaining elements are either undef or the same as the first
  8285. // non-undef value.
  8286. for (int Idx = Mask[i]; i != e; ++i)
  8287. if (Mask[i] >= 0 && Mask[i] != Idx)
  8288. return false;
  8289. return true;
  8290. }
  8291. // Returns the SDNode if it is a constant integer BuildVector
  8292. // or constant integer.
  8293. SDNode *SelectionDAG::isConstantIntBuildVectorOrConstantInt(SDValue N) {
  8294. if (isa<ConstantSDNode>(N))
  8295. return N.getNode();
  8296. if (ISD::isBuildVectorOfConstantSDNodes(N.getNode()))
  8297. return N.getNode();
  8298. // Treat a GlobalAddress supporting constant offset folding as a
  8299. // constant integer.
  8300. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N))
  8301. if (GA->getOpcode() == ISD::GlobalAddress &&
  8302. TLI->isOffsetFoldingLegal(GA))
  8303. return GA;
  8304. return nullptr;
  8305. }
  8306. SDNode *SelectionDAG::isConstantFPBuildVectorOrConstantFP(SDValue N) {
  8307. if (isa<ConstantFPSDNode>(N))
  8308. return N.getNode();
  8309. if (ISD::isBuildVectorOfConstantFPSDNodes(N.getNode()))
  8310. return N.getNode();
  8311. return nullptr;
  8312. }
  8313. void SelectionDAG::createOperands(SDNode *Node, ArrayRef<SDValue> Vals) {
  8314. assert(!Node->OperandList && "Node already has operands");
  8315. assert(SDNode::getMaxNumOperands() >= Vals.size() &&
  8316. "too many operands to fit into SDNode");
  8317. SDUse *Ops = OperandRecycler.allocate(
  8318. ArrayRecycler<SDUse>::Capacity::get(Vals.size()), OperandAllocator);
  8319. bool IsDivergent = false;
  8320. for (unsigned I = 0; I != Vals.size(); ++I) {
  8321. Ops[I].setUser(Node);
  8322. Ops[I].setInitial(Vals[I]);
  8323. if (Ops[I].Val.getValueType() != MVT::Other) // Skip Chain. It does not carry divergence.
  8324. IsDivergent = IsDivergent || Ops[I].getNode()->isDivergent();
  8325. }
  8326. Node->NumOperands = Vals.size();
  8327. Node->OperandList = Ops;
  8328. IsDivergent |= TLI->isSDNodeSourceOfDivergence(Node, FLI, DA);
  8329. if (!TLI->isSDNodeAlwaysUniform(Node))
  8330. Node->SDNodeBits.IsDivergent = IsDivergent;
  8331. checkForCycles(Node);
  8332. }
  8333. SDValue SelectionDAG::getTokenFactor(const SDLoc &DL,
  8334. SmallVectorImpl<SDValue> &Vals) {
  8335. size_t Limit = SDNode::getMaxNumOperands();
  8336. while (Vals.size() > Limit) {
  8337. unsigned SliceIdx = Vals.size() - Limit;
  8338. auto ExtractedTFs = ArrayRef<SDValue>(Vals).slice(SliceIdx, Limit);
  8339. SDValue NewTF = getNode(ISD::TokenFactor, DL, MVT::Other, ExtractedTFs);
  8340. Vals.erase(Vals.begin() + SliceIdx, Vals.end());
  8341. Vals.emplace_back(NewTF);
  8342. }
  8343. return getNode(ISD::TokenFactor, DL, MVT::Other, Vals);
  8344. }
  8345. #ifndef NDEBUG
  8346. static void checkForCyclesHelper(const SDNode *N,
  8347. SmallPtrSetImpl<const SDNode*> &Visited,
  8348. SmallPtrSetImpl<const SDNode*> &Checked,
  8349. const llvm::SelectionDAG *DAG) {
  8350. // If this node has already been checked, don't check it again.
  8351. if (Checked.count(N))
  8352. return;
  8353. // If a node has already been visited on this depth-first walk, reject it as
  8354. // a cycle.
  8355. if (!Visited.insert(N).second) {
  8356. errs() << "Detected cycle in SelectionDAG\n";
  8357. dbgs() << "Offending node:\n";
  8358. N->dumprFull(DAG); dbgs() << "\n";
  8359. abort();
  8360. }
  8361. for (const SDValue &Op : N->op_values())
  8362. checkForCyclesHelper(Op.getNode(), Visited, Checked, DAG);
  8363. Checked.insert(N);
  8364. Visited.erase(N);
  8365. }
  8366. #endif
  8367. void llvm::checkForCycles(const llvm::SDNode *N,
  8368. const llvm::SelectionDAG *DAG,
  8369. bool force) {
  8370. #ifndef NDEBUG
  8371. bool check = force;
  8372. #ifdef EXPENSIVE_CHECKS
  8373. check = true;
  8374. #endif // EXPENSIVE_CHECKS
  8375. if (check) {
  8376. assert(N && "Checking nonexistent SDNode");
  8377. SmallPtrSet<const SDNode*, 32> visited;
  8378. SmallPtrSet<const SDNode*, 32> checked;
  8379. checkForCyclesHelper(N, visited, checked, DAG);
  8380. }
  8381. #endif // !NDEBUG
  8382. }
  8383. void llvm::checkForCycles(const llvm::SelectionDAG *DAG, bool force) {
  8384. checkForCycles(DAG->getRoot().getNode(), DAG, force);
  8385. }