InstCombineCompares.cpp 276 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057
  1. //===- InstCombineCompares.cpp --------------------------------------------===//
  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 file implements the visitICmp and visitFCmp functions.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "InstCombineInternal.h"
  13. #include "llvm/ADT/APSInt.h"
  14. #include "llvm/ADT/SetVector.h"
  15. #include "llvm/ADT/Statistic.h"
  16. #include "llvm/Analysis/CmpInstAnalysis.h"
  17. #include "llvm/Analysis/ConstantFolding.h"
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/Analysis/VectorUtils.h"
  20. #include "llvm/IR/ConstantRange.h"
  21. #include "llvm/IR/DataLayout.h"
  22. #include "llvm/IR/GetElementPtrTypeIterator.h"
  23. #include "llvm/IR/IntrinsicInst.h"
  24. #include "llvm/IR/PatternMatch.h"
  25. #include "llvm/Support/KnownBits.h"
  26. #include "llvm/Transforms/InstCombine/InstCombiner.h"
  27. using namespace llvm;
  28. using namespace PatternMatch;
  29. #define DEBUG_TYPE "instcombine"
  30. // How many times is a select replaced by one of its operands?
  31. STATISTIC(NumSel, "Number of select opts");
  32. /// Compute Result = In1+In2, returning true if the result overflowed for this
  33. /// type.
  34. static bool addWithOverflow(APInt &Result, const APInt &In1,
  35. const APInt &In2, bool IsSigned = false) {
  36. bool Overflow;
  37. if (IsSigned)
  38. Result = In1.sadd_ov(In2, Overflow);
  39. else
  40. Result = In1.uadd_ov(In2, Overflow);
  41. return Overflow;
  42. }
  43. /// Compute Result = In1-In2, returning true if the result overflowed for this
  44. /// type.
  45. static bool subWithOverflow(APInt &Result, const APInt &In1,
  46. const APInt &In2, bool IsSigned = false) {
  47. bool Overflow;
  48. if (IsSigned)
  49. Result = In1.ssub_ov(In2, Overflow);
  50. else
  51. Result = In1.usub_ov(In2, Overflow);
  52. return Overflow;
  53. }
  54. /// Given an icmp instruction, return true if any use of this comparison is a
  55. /// branch on sign bit comparison.
  56. static bool hasBranchUse(ICmpInst &I) {
  57. for (auto *U : I.users())
  58. if (isa<BranchInst>(U))
  59. return true;
  60. return false;
  61. }
  62. /// Returns true if the exploded icmp can be expressed as a signed comparison
  63. /// to zero and updates the predicate accordingly.
  64. /// The signedness of the comparison is preserved.
  65. /// TODO: Refactor with decomposeBitTestICmp()?
  66. static bool isSignTest(ICmpInst::Predicate &Pred, const APInt &C) {
  67. if (!ICmpInst::isSigned(Pred))
  68. return false;
  69. if (C.isZero())
  70. return ICmpInst::isRelational(Pred);
  71. if (C.isOne()) {
  72. if (Pred == ICmpInst::ICMP_SLT) {
  73. Pred = ICmpInst::ICMP_SLE;
  74. return true;
  75. }
  76. } else if (C.isAllOnes()) {
  77. if (Pred == ICmpInst::ICMP_SGT) {
  78. Pred = ICmpInst::ICMP_SGE;
  79. return true;
  80. }
  81. }
  82. return false;
  83. }
  84. /// This is called when we see this pattern:
  85. /// cmp pred (load (gep GV, ...)), cmpcst
  86. /// where GV is a global variable with a constant initializer. Try to simplify
  87. /// this into some simple computation that does not need the load. For example
  88. /// we can optimize "icmp eq (load (gep "foo", 0, i)), 0" into "icmp eq i, 3".
  89. ///
  90. /// If AndCst is non-null, then the loaded value is masked with that constant
  91. /// before doing the comparison. This handles cases like "A[i]&4 == 0".
  92. Instruction *InstCombinerImpl::foldCmpLoadFromIndexedGlobal(
  93. LoadInst *LI, GetElementPtrInst *GEP, GlobalVariable *GV, CmpInst &ICI,
  94. ConstantInt *AndCst) {
  95. if (LI->isVolatile() || LI->getType() != GEP->getResultElementType() ||
  96. GV->getValueType() != GEP->getSourceElementType() ||
  97. !GV->isConstant() || !GV->hasDefinitiveInitializer())
  98. return nullptr;
  99. Constant *Init = GV->getInitializer();
  100. if (!isa<ConstantArray>(Init) && !isa<ConstantDataArray>(Init))
  101. return nullptr;
  102. uint64_t ArrayElementCount = Init->getType()->getArrayNumElements();
  103. // Don't blow up on huge arrays.
  104. if (ArrayElementCount > MaxArraySizeForCombine)
  105. return nullptr;
  106. // There are many forms of this optimization we can handle, for now, just do
  107. // the simple index into a single-dimensional array.
  108. //
  109. // Require: GEP GV, 0, i {{, constant indices}}
  110. if (GEP->getNumOperands() < 3 ||
  111. !isa<ConstantInt>(GEP->getOperand(1)) ||
  112. !cast<ConstantInt>(GEP->getOperand(1))->isZero() ||
  113. isa<Constant>(GEP->getOperand(2)))
  114. return nullptr;
  115. // Check that indices after the variable are constants and in-range for the
  116. // type they index. Collect the indices. This is typically for arrays of
  117. // structs.
  118. SmallVector<unsigned, 4> LaterIndices;
  119. Type *EltTy = Init->getType()->getArrayElementType();
  120. for (unsigned i = 3, e = GEP->getNumOperands(); i != e; ++i) {
  121. ConstantInt *Idx = dyn_cast<ConstantInt>(GEP->getOperand(i));
  122. if (!Idx) return nullptr; // Variable index.
  123. uint64_t IdxVal = Idx->getZExtValue();
  124. if ((unsigned)IdxVal != IdxVal) return nullptr; // Too large array index.
  125. if (StructType *STy = dyn_cast<StructType>(EltTy))
  126. EltTy = STy->getElementType(IdxVal);
  127. else if (ArrayType *ATy = dyn_cast<ArrayType>(EltTy)) {
  128. if (IdxVal >= ATy->getNumElements()) return nullptr;
  129. EltTy = ATy->getElementType();
  130. } else {
  131. return nullptr; // Unknown type.
  132. }
  133. LaterIndices.push_back(IdxVal);
  134. }
  135. enum { Overdefined = -3, Undefined = -2 };
  136. // Variables for our state machines.
  137. // FirstTrueElement/SecondTrueElement - Used to emit a comparison of the form
  138. // "i == 47 | i == 87", where 47 is the first index the condition is true for,
  139. // and 87 is the second (and last) index. FirstTrueElement is -2 when
  140. // undefined, otherwise set to the first true element. SecondTrueElement is
  141. // -2 when undefined, -3 when overdefined and >= 0 when that index is true.
  142. int FirstTrueElement = Undefined, SecondTrueElement = Undefined;
  143. // FirstFalseElement/SecondFalseElement - Used to emit a comparison of the
  144. // form "i != 47 & i != 87". Same state transitions as for true elements.
  145. int FirstFalseElement = Undefined, SecondFalseElement = Undefined;
  146. /// TrueRangeEnd/FalseRangeEnd - In conjunction with First*Element, these
  147. /// define a state machine that triggers for ranges of values that the index
  148. /// is true or false for. This triggers on things like "abbbbc"[i] == 'b'.
  149. /// This is -2 when undefined, -3 when overdefined, and otherwise the last
  150. /// index in the range (inclusive). We use -2 for undefined here because we
  151. /// use relative comparisons and don't want 0-1 to match -1.
  152. int TrueRangeEnd = Undefined, FalseRangeEnd = Undefined;
  153. // MagicBitvector - This is a magic bitvector where we set a bit if the
  154. // comparison is true for element 'i'. If there are 64 elements or less in
  155. // the array, this will fully represent all the comparison results.
  156. uint64_t MagicBitvector = 0;
  157. // Scan the array and see if one of our patterns matches.
  158. Constant *CompareRHS = cast<Constant>(ICI.getOperand(1));
  159. for (unsigned i = 0, e = ArrayElementCount; i != e; ++i) {
  160. Constant *Elt = Init->getAggregateElement(i);
  161. if (!Elt) return nullptr;
  162. // If this is indexing an array of structures, get the structure element.
  163. if (!LaterIndices.empty()) {
  164. Elt = ConstantFoldExtractValueInstruction(Elt, LaterIndices);
  165. if (!Elt)
  166. return nullptr;
  167. }
  168. // If the element is masked, handle it.
  169. if (AndCst) Elt = ConstantExpr::getAnd(Elt, AndCst);
  170. // Find out if the comparison would be true or false for the i'th element.
  171. Constant *C = ConstantFoldCompareInstOperands(ICI.getPredicate(), Elt,
  172. CompareRHS, DL, &TLI);
  173. // If the result is undef for this element, ignore it.
  174. if (isa<UndefValue>(C)) {
  175. // Extend range state machines to cover this element in case there is an
  176. // undef in the middle of the range.
  177. if (TrueRangeEnd == (int)i-1)
  178. TrueRangeEnd = i;
  179. if (FalseRangeEnd == (int)i-1)
  180. FalseRangeEnd = i;
  181. continue;
  182. }
  183. // If we can't compute the result for any of the elements, we have to give
  184. // up evaluating the entire conditional.
  185. if (!isa<ConstantInt>(C)) return nullptr;
  186. // Otherwise, we know if the comparison is true or false for this element,
  187. // update our state machines.
  188. bool IsTrueForElt = !cast<ConstantInt>(C)->isZero();
  189. // State machine for single/double/range index comparison.
  190. if (IsTrueForElt) {
  191. // Update the TrueElement state machine.
  192. if (FirstTrueElement == Undefined)
  193. FirstTrueElement = TrueRangeEnd = i; // First true element.
  194. else {
  195. // Update double-compare state machine.
  196. if (SecondTrueElement == Undefined)
  197. SecondTrueElement = i;
  198. else
  199. SecondTrueElement = Overdefined;
  200. // Update range state machine.
  201. if (TrueRangeEnd == (int)i-1)
  202. TrueRangeEnd = i;
  203. else
  204. TrueRangeEnd = Overdefined;
  205. }
  206. } else {
  207. // Update the FalseElement state machine.
  208. if (FirstFalseElement == Undefined)
  209. FirstFalseElement = FalseRangeEnd = i; // First false element.
  210. else {
  211. // Update double-compare state machine.
  212. if (SecondFalseElement == Undefined)
  213. SecondFalseElement = i;
  214. else
  215. SecondFalseElement = Overdefined;
  216. // Update range state machine.
  217. if (FalseRangeEnd == (int)i-1)
  218. FalseRangeEnd = i;
  219. else
  220. FalseRangeEnd = Overdefined;
  221. }
  222. }
  223. // If this element is in range, update our magic bitvector.
  224. if (i < 64 && IsTrueForElt)
  225. MagicBitvector |= 1ULL << i;
  226. // If all of our states become overdefined, bail out early. Since the
  227. // predicate is expensive, only check it every 8 elements. This is only
  228. // really useful for really huge arrays.
  229. if ((i & 8) == 0 && i >= 64 && SecondTrueElement == Overdefined &&
  230. SecondFalseElement == Overdefined && TrueRangeEnd == Overdefined &&
  231. FalseRangeEnd == Overdefined)
  232. return nullptr;
  233. }
  234. // Now that we've scanned the entire array, emit our new comparison(s). We
  235. // order the state machines in complexity of the generated code.
  236. Value *Idx = GEP->getOperand(2);
  237. // If the index is larger than the pointer size of the target, truncate the
  238. // index down like the GEP would do implicitly. We don't have to do this for
  239. // an inbounds GEP because the index can't be out of range.
  240. if (!GEP->isInBounds()) {
  241. Type *IntPtrTy = DL.getIntPtrType(GEP->getType());
  242. unsigned PtrSize = IntPtrTy->getIntegerBitWidth();
  243. if (Idx->getType()->getPrimitiveSizeInBits().getFixedValue() > PtrSize)
  244. Idx = Builder.CreateTrunc(Idx, IntPtrTy);
  245. }
  246. // If inbounds keyword is not present, Idx * ElementSize can overflow.
  247. // Let's assume that ElementSize is 2 and the wanted value is at offset 0.
  248. // Then, there are two possible values for Idx to match offset 0:
  249. // 0x00..00, 0x80..00.
  250. // Emitting 'icmp eq Idx, 0' isn't correct in this case because the
  251. // comparison is false if Idx was 0x80..00.
  252. // We need to erase the highest countTrailingZeros(ElementSize) bits of Idx.
  253. unsigned ElementSize =
  254. DL.getTypeAllocSize(Init->getType()->getArrayElementType());
  255. auto MaskIdx = [&](Value* Idx){
  256. if (!GEP->isInBounds() && countTrailingZeros(ElementSize) != 0) {
  257. Value *Mask = ConstantInt::get(Idx->getType(), -1);
  258. Mask = Builder.CreateLShr(Mask, countTrailingZeros(ElementSize));
  259. Idx = Builder.CreateAnd(Idx, Mask);
  260. }
  261. return Idx;
  262. };
  263. // If the comparison is only true for one or two elements, emit direct
  264. // comparisons.
  265. if (SecondTrueElement != Overdefined) {
  266. Idx = MaskIdx(Idx);
  267. // None true -> false.
  268. if (FirstTrueElement == Undefined)
  269. return replaceInstUsesWith(ICI, Builder.getFalse());
  270. Value *FirstTrueIdx = ConstantInt::get(Idx->getType(), FirstTrueElement);
  271. // True for one element -> 'i == 47'.
  272. if (SecondTrueElement == Undefined)
  273. return new ICmpInst(ICmpInst::ICMP_EQ, Idx, FirstTrueIdx);
  274. // True for two elements -> 'i == 47 | i == 72'.
  275. Value *C1 = Builder.CreateICmpEQ(Idx, FirstTrueIdx);
  276. Value *SecondTrueIdx = ConstantInt::get(Idx->getType(), SecondTrueElement);
  277. Value *C2 = Builder.CreateICmpEQ(Idx, SecondTrueIdx);
  278. return BinaryOperator::CreateOr(C1, C2);
  279. }
  280. // If the comparison is only false for one or two elements, emit direct
  281. // comparisons.
  282. if (SecondFalseElement != Overdefined) {
  283. Idx = MaskIdx(Idx);
  284. // None false -> true.
  285. if (FirstFalseElement == Undefined)
  286. return replaceInstUsesWith(ICI, Builder.getTrue());
  287. Value *FirstFalseIdx = ConstantInt::get(Idx->getType(), FirstFalseElement);
  288. // False for one element -> 'i != 47'.
  289. if (SecondFalseElement == Undefined)
  290. return new ICmpInst(ICmpInst::ICMP_NE, Idx, FirstFalseIdx);
  291. // False for two elements -> 'i != 47 & i != 72'.
  292. Value *C1 = Builder.CreateICmpNE(Idx, FirstFalseIdx);
  293. Value *SecondFalseIdx = ConstantInt::get(Idx->getType(),SecondFalseElement);
  294. Value *C2 = Builder.CreateICmpNE(Idx, SecondFalseIdx);
  295. return BinaryOperator::CreateAnd(C1, C2);
  296. }
  297. // If the comparison can be replaced with a range comparison for the elements
  298. // where it is true, emit the range check.
  299. if (TrueRangeEnd != Overdefined) {
  300. assert(TrueRangeEnd != FirstTrueElement && "Should emit single compare");
  301. Idx = MaskIdx(Idx);
  302. // Generate (i-FirstTrue) <u (TrueRangeEnd-FirstTrue+1).
  303. if (FirstTrueElement) {
  304. Value *Offs = ConstantInt::get(Idx->getType(), -FirstTrueElement);
  305. Idx = Builder.CreateAdd(Idx, Offs);
  306. }
  307. Value *End = ConstantInt::get(Idx->getType(),
  308. TrueRangeEnd-FirstTrueElement+1);
  309. return new ICmpInst(ICmpInst::ICMP_ULT, Idx, End);
  310. }
  311. // False range check.
  312. if (FalseRangeEnd != Overdefined) {
  313. assert(FalseRangeEnd != FirstFalseElement && "Should emit single compare");
  314. Idx = MaskIdx(Idx);
  315. // Generate (i-FirstFalse) >u (FalseRangeEnd-FirstFalse).
  316. if (FirstFalseElement) {
  317. Value *Offs = ConstantInt::get(Idx->getType(), -FirstFalseElement);
  318. Idx = Builder.CreateAdd(Idx, Offs);
  319. }
  320. Value *End = ConstantInt::get(Idx->getType(),
  321. FalseRangeEnd-FirstFalseElement);
  322. return new ICmpInst(ICmpInst::ICMP_UGT, Idx, End);
  323. }
  324. // If a magic bitvector captures the entire comparison state
  325. // of this load, replace it with computation that does:
  326. // ((magic_cst >> i) & 1) != 0
  327. {
  328. Type *Ty = nullptr;
  329. // Look for an appropriate type:
  330. // - The type of Idx if the magic fits
  331. // - The smallest fitting legal type
  332. if (ArrayElementCount <= Idx->getType()->getIntegerBitWidth())
  333. Ty = Idx->getType();
  334. else
  335. Ty = DL.getSmallestLegalIntType(Init->getContext(), ArrayElementCount);
  336. if (Ty) {
  337. Idx = MaskIdx(Idx);
  338. Value *V = Builder.CreateIntCast(Idx, Ty, false);
  339. V = Builder.CreateLShr(ConstantInt::get(Ty, MagicBitvector), V);
  340. V = Builder.CreateAnd(ConstantInt::get(Ty, 1), V);
  341. return new ICmpInst(ICmpInst::ICMP_NE, V, ConstantInt::get(Ty, 0));
  342. }
  343. }
  344. return nullptr;
  345. }
  346. /// Returns true if we can rewrite Start as a GEP with pointer Base
  347. /// and some integer offset. The nodes that need to be re-written
  348. /// for this transformation will be added to Explored.
  349. static bool canRewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
  350. const DataLayout &DL,
  351. SetVector<Value *> &Explored) {
  352. SmallVector<Value *, 16> WorkList(1, Start);
  353. Explored.insert(Base);
  354. // The following traversal gives us an order which can be used
  355. // when doing the final transformation. Since in the final
  356. // transformation we create the PHI replacement instructions first,
  357. // we don't have to get them in any particular order.
  358. //
  359. // However, for other instructions we will have to traverse the
  360. // operands of an instruction first, which means that we have to
  361. // do a post-order traversal.
  362. while (!WorkList.empty()) {
  363. SetVector<PHINode *> PHIs;
  364. while (!WorkList.empty()) {
  365. if (Explored.size() >= 100)
  366. return false;
  367. Value *V = WorkList.back();
  368. if (Explored.contains(V)) {
  369. WorkList.pop_back();
  370. continue;
  371. }
  372. if (!isa<IntToPtrInst>(V) && !isa<PtrToIntInst>(V) &&
  373. !isa<GetElementPtrInst>(V) && !isa<PHINode>(V))
  374. // We've found some value that we can't explore which is different from
  375. // the base. Therefore we can't do this transformation.
  376. return false;
  377. if (isa<IntToPtrInst>(V) || isa<PtrToIntInst>(V)) {
  378. auto *CI = cast<CastInst>(V);
  379. if (!CI->isNoopCast(DL))
  380. return false;
  381. if (!Explored.contains(CI->getOperand(0)))
  382. WorkList.push_back(CI->getOperand(0));
  383. }
  384. if (auto *GEP = dyn_cast<GEPOperator>(V)) {
  385. // We're limiting the GEP to having one index. This will preserve
  386. // the original pointer type. We could handle more cases in the
  387. // future.
  388. if (GEP->getNumIndices() != 1 || !GEP->isInBounds() ||
  389. GEP->getSourceElementType() != ElemTy)
  390. return false;
  391. if (!Explored.contains(GEP->getOperand(0)))
  392. WorkList.push_back(GEP->getOperand(0));
  393. }
  394. if (WorkList.back() == V) {
  395. WorkList.pop_back();
  396. // We've finished visiting this node, mark it as such.
  397. Explored.insert(V);
  398. }
  399. if (auto *PN = dyn_cast<PHINode>(V)) {
  400. // We cannot transform PHIs on unsplittable basic blocks.
  401. if (isa<CatchSwitchInst>(PN->getParent()->getTerminator()))
  402. return false;
  403. Explored.insert(PN);
  404. PHIs.insert(PN);
  405. }
  406. }
  407. // Explore the PHI nodes further.
  408. for (auto *PN : PHIs)
  409. for (Value *Op : PN->incoming_values())
  410. if (!Explored.contains(Op))
  411. WorkList.push_back(Op);
  412. }
  413. // Make sure that we can do this. Since we can't insert GEPs in a basic
  414. // block before a PHI node, we can't easily do this transformation if
  415. // we have PHI node users of transformed instructions.
  416. for (Value *Val : Explored) {
  417. for (Value *Use : Val->uses()) {
  418. auto *PHI = dyn_cast<PHINode>(Use);
  419. auto *Inst = dyn_cast<Instruction>(Val);
  420. if (Inst == Base || Inst == PHI || !Inst || !PHI ||
  421. !Explored.contains(PHI))
  422. continue;
  423. if (PHI->getParent() == Inst->getParent())
  424. return false;
  425. }
  426. }
  427. return true;
  428. }
  429. // Sets the appropriate insert point on Builder where we can add
  430. // a replacement Instruction for V (if that is possible).
  431. static void setInsertionPoint(IRBuilder<> &Builder, Value *V,
  432. bool Before = true) {
  433. if (auto *PHI = dyn_cast<PHINode>(V)) {
  434. Builder.SetInsertPoint(&*PHI->getParent()->getFirstInsertionPt());
  435. return;
  436. }
  437. if (auto *I = dyn_cast<Instruction>(V)) {
  438. if (!Before)
  439. I = &*std::next(I->getIterator());
  440. Builder.SetInsertPoint(I);
  441. return;
  442. }
  443. if (auto *A = dyn_cast<Argument>(V)) {
  444. // Set the insertion point in the entry block.
  445. BasicBlock &Entry = A->getParent()->getEntryBlock();
  446. Builder.SetInsertPoint(&*Entry.getFirstInsertionPt());
  447. return;
  448. }
  449. // Otherwise, this is a constant and we don't need to set a new
  450. // insertion point.
  451. assert(isa<Constant>(V) && "Setting insertion point for unknown value!");
  452. }
  453. /// Returns a re-written value of Start as an indexed GEP using Base as a
  454. /// pointer.
  455. static Value *rewriteGEPAsOffset(Type *ElemTy, Value *Start, Value *Base,
  456. const DataLayout &DL,
  457. SetVector<Value *> &Explored) {
  458. // Perform all the substitutions. This is a bit tricky because we can
  459. // have cycles in our use-def chains.
  460. // 1. Create the PHI nodes without any incoming values.
  461. // 2. Create all the other values.
  462. // 3. Add the edges for the PHI nodes.
  463. // 4. Emit GEPs to get the original pointers.
  464. // 5. Remove the original instructions.
  465. Type *IndexType = IntegerType::get(
  466. Base->getContext(), DL.getIndexTypeSizeInBits(Start->getType()));
  467. DenseMap<Value *, Value *> NewInsts;
  468. NewInsts[Base] = ConstantInt::getNullValue(IndexType);
  469. // Create the new PHI nodes, without adding any incoming values.
  470. for (Value *Val : Explored) {
  471. if (Val == Base)
  472. continue;
  473. // Create empty phi nodes. This avoids cyclic dependencies when creating
  474. // the remaining instructions.
  475. if (auto *PHI = dyn_cast<PHINode>(Val))
  476. NewInsts[PHI] = PHINode::Create(IndexType, PHI->getNumIncomingValues(),
  477. PHI->getName() + ".idx", PHI);
  478. }
  479. IRBuilder<> Builder(Base->getContext());
  480. // Create all the other instructions.
  481. for (Value *Val : Explored) {
  482. if (NewInsts.find(Val) != NewInsts.end())
  483. continue;
  484. if (auto *CI = dyn_cast<CastInst>(Val)) {
  485. // Don't get rid of the intermediate variable here; the store can grow
  486. // the map which will invalidate the reference to the input value.
  487. Value *V = NewInsts[CI->getOperand(0)];
  488. NewInsts[CI] = V;
  489. continue;
  490. }
  491. if (auto *GEP = dyn_cast<GEPOperator>(Val)) {
  492. Value *Index = NewInsts[GEP->getOperand(1)] ? NewInsts[GEP->getOperand(1)]
  493. : GEP->getOperand(1);
  494. setInsertionPoint(Builder, GEP);
  495. // Indices might need to be sign extended. GEPs will magically do
  496. // this, but we need to do it ourselves here.
  497. if (Index->getType()->getScalarSizeInBits() !=
  498. NewInsts[GEP->getOperand(0)]->getType()->getScalarSizeInBits()) {
  499. Index = Builder.CreateSExtOrTrunc(
  500. Index, NewInsts[GEP->getOperand(0)]->getType(),
  501. GEP->getOperand(0)->getName() + ".sext");
  502. }
  503. auto *Op = NewInsts[GEP->getOperand(0)];
  504. if (isa<ConstantInt>(Op) && cast<ConstantInt>(Op)->isZero())
  505. NewInsts[GEP] = Index;
  506. else
  507. NewInsts[GEP] = Builder.CreateNSWAdd(
  508. Op, Index, GEP->getOperand(0)->getName() + ".add");
  509. continue;
  510. }
  511. if (isa<PHINode>(Val))
  512. continue;
  513. llvm_unreachable("Unexpected instruction type");
  514. }
  515. // Add the incoming values to the PHI nodes.
  516. for (Value *Val : Explored) {
  517. if (Val == Base)
  518. continue;
  519. // All the instructions have been created, we can now add edges to the
  520. // phi nodes.
  521. if (auto *PHI = dyn_cast<PHINode>(Val)) {
  522. PHINode *NewPhi = static_cast<PHINode *>(NewInsts[PHI]);
  523. for (unsigned I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
  524. Value *NewIncoming = PHI->getIncomingValue(I);
  525. if (NewInsts.find(NewIncoming) != NewInsts.end())
  526. NewIncoming = NewInsts[NewIncoming];
  527. NewPhi->addIncoming(NewIncoming, PHI->getIncomingBlock(I));
  528. }
  529. }
  530. }
  531. PointerType *PtrTy =
  532. ElemTy->getPointerTo(Start->getType()->getPointerAddressSpace());
  533. for (Value *Val : Explored) {
  534. if (Val == Base)
  535. continue;
  536. // Depending on the type, for external users we have to emit
  537. // a GEP or a GEP + ptrtoint.
  538. setInsertionPoint(Builder, Val, false);
  539. // Cast base to the expected type.
  540. Value *NewVal = Builder.CreateBitOrPointerCast(
  541. Base, PtrTy, Start->getName() + "to.ptr");
  542. NewVal = Builder.CreateInBoundsGEP(ElemTy, NewVal, ArrayRef(NewInsts[Val]),
  543. Val->getName() + ".ptr");
  544. NewVal = Builder.CreateBitOrPointerCast(
  545. NewVal, Val->getType(), Val->getName() + ".conv");
  546. Val->replaceAllUsesWith(NewVal);
  547. }
  548. return NewInsts[Start];
  549. }
  550. /// Looks through GEPs, IntToPtrInsts and PtrToIntInsts in order to express
  551. /// the input Value as a constant indexed GEP. Returns a pair containing
  552. /// the GEPs Pointer and Index.
  553. static std::pair<Value *, Value *>
  554. getAsConstantIndexedAddress(Type *ElemTy, Value *V, const DataLayout &DL) {
  555. Type *IndexType = IntegerType::get(V->getContext(),
  556. DL.getIndexTypeSizeInBits(V->getType()));
  557. Constant *Index = ConstantInt::getNullValue(IndexType);
  558. while (true) {
  559. if (GEPOperator *GEP = dyn_cast<GEPOperator>(V)) {
  560. // We accept only inbouds GEPs here to exclude the possibility of
  561. // overflow.
  562. if (!GEP->isInBounds())
  563. break;
  564. if (GEP->hasAllConstantIndices() && GEP->getNumIndices() == 1 &&
  565. GEP->getSourceElementType() == ElemTy) {
  566. V = GEP->getOperand(0);
  567. Constant *GEPIndex = static_cast<Constant *>(GEP->getOperand(1));
  568. Index = ConstantExpr::getAdd(
  569. Index, ConstantExpr::getSExtOrTrunc(GEPIndex, IndexType));
  570. continue;
  571. }
  572. break;
  573. }
  574. if (auto *CI = dyn_cast<IntToPtrInst>(V)) {
  575. if (!CI->isNoopCast(DL))
  576. break;
  577. V = CI->getOperand(0);
  578. continue;
  579. }
  580. if (auto *CI = dyn_cast<PtrToIntInst>(V)) {
  581. if (!CI->isNoopCast(DL))
  582. break;
  583. V = CI->getOperand(0);
  584. continue;
  585. }
  586. break;
  587. }
  588. return {V, Index};
  589. }
  590. /// Converts (CMP GEPLHS, RHS) if this change would make RHS a constant.
  591. /// We can look through PHIs, GEPs and casts in order to determine a common base
  592. /// between GEPLHS and RHS.
  593. static Instruction *transformToIndexedCompare(GEPOperator *GEPLHS, Value *RHS,
  594. ICmpInst::Predicate Cond,
  595. const DataLayout &DL) {
  596. // FIXME: Support vector of pointers.
  597. if (GEPLHS->getType()->isVectorTy())
  598. return nullptr;
  599. if (!GEPLHS->hasAllConstantIndices())
  600. return nullptr;
  601. Type *ElemTy = GEPLHS->getSourceElementType();
  602. Value *PtrBase, *Index;
  603. std::tie(PtrBase, Index) = getAsConstantIndexedAddress(ElemTy, GEPLHS, DL);
  604. // The set of nodes that will take part in this transformation.
  605. SetVector<Value *> Nodes;
  606. if (!canRewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes))
  607. return nullptr;
  608. // We know we can re-write this as
  609. // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2)
  610. // Since we've only looked through inbouds GEPs we know that we
  611. // can't have overflow on either side. We can therefore re-write
  612. // this as:
  613. // OFFSET1 cmp OFFSET2
  614. Value *NewRHS = rewriteGEPAsOffset(ElemTy, RHS, PtrBase, DL, Nodes);
  615. // RewriteGEPAsOffset has replaced RHS and all of its uses with a re-written
  616. // GEP having PtrBase as the pointer base, and has returned in NewRHS the
  617. // offset. Since Index is the offset of LHS to the base pointer, we will now
  618. // compare the offsets instead of comparing the pointers.
  619. return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Index, NewRHS);
  620. }
  621. /// Fold comparisons between a GEP instruction and something else. At this point
  622. /// we know that the GEP is on the LHS of the comparison.
  623. Instruction *InstCombinerImpl::foldGEPICmp(GEPOperator *GEPLHS, Value *RHS,
  624. ICmpInst::Predicate Cond,
  625. Instruction &I) {
  626. // Don't transform signed compares of GEPs into index compares. Even if the
  627. // GEP is inbounds, the final add of the base pointer can have signed overflow
  628. // and would change the result of the icmp.
  629. // e.g. "&foo[0] <s &foo[1]" can't be folded to "true" because "foo" could be
  630. // the maximum signed value for the pointer type.
  631. if (ICmpInst::isSigned(Cond))
  632. return nullptr;
  633. // Look through bitcasts and addrspacecasts. We do not however want to remove
  634. // 0 GEPs.
  635. if (!isa<GetElementPtrInst>(RHS))
  636. RHS = RHS->stripPointerCasts();
  637. Value *PtrBase = GEPLHS->getOperand(0);
  638. if (PtrBase == RHS && GEPLHS->isInBounds()) {
  639. // ((gep Ptr, OFFSET) cmp Ptr) ---> (OFFSET cmp 0).
  640. Value *Offset = EmitGEPOffset(GEPLHS);
  641. return new ICmpInst(ICmpInst::getSignedPredicate(Cond), Offset,
  642. Constant::getNullValue(Offset->getType()));
  643. }
  644. if (GEPLHS->isInBounds() && ICmpInst::isEquality(Cond) &&
  645. isa<Constant>(RHS) && cast<Constant>(RHS)->isNullValue() &&
  646. !NullPointerIsDefined(I.getFunction(),
  647. RHS->getType()->getPointerAddressSpace())) {
  648. // For most address spaces, an allocation can't be placed at null, but null
  649. // itself is treated as a 0 size allocation in the in bounds rules. Thus,
  650. // the only valid inbounds address derived from null, is null itself.
  651. // Thus, we have four cases to consider:
  652. // 1) Base == nullptr, Offset == 0 -> inbounds, null
  653. // 2) Base == nullptr, Offset != 0 -> poison as the result is out of bounds
  654. // 3) Base != nullptr, Offset == (-base) -> poison (crossing allocations)
  655. // 4) Base != nullptr, Offset != (-base) -> nonnull (and possibly poison)
  656. //
  657. // (Note if we're indexing a type of size 0, that simply collapses into one
  658. // of the buckets above.)
  659. //
  660. // In general, we're allowed to make values less poison (i.e. remove
  661. // sources of full UB), so in this case, we just select between the two
  662. // non-poison cases (1 and 4 above).
  663. //
  664. // For vectors, we apply the same reasoning on a per-lane basis.
  665. auto *Base = GEPLHS->getPointerOperand();
  666. if (GEPLHS->getType()->isVectorTy() && Base->getType()->isPointerTy()) {
  667. auto EC = cast<VectorType>(GEPLHS->getType())->getElementCount();
  668. Base = Builder.CreateVectorSplat(EC, Base);
  669. }
  670. return new ICmpInst(Cond, Base,
  671. ConstantExpr::getPointerBitCastOrAddrSpaceCast(
  672. cast<Constant>(RHS), Base->getType()));
  673. } else if (GEPOperator *GEPRHS = dyn_cast<GEPOperator>(RHS)) {
  674. // If the base pointers are different, but the indices are the same, just
  675. // compare the base pointer.
  676. if (PtrBase != GEPRHS->getOperand(0)) {
  677. bool IndicesTheSame =
  678. GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
  679. GEPLHS->getPointerOperand()->getType() ==
  680. GEPRHS->getPointerOperand()->getType() &&
  681. GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType();
  682. if (IndicesTheSame)
  683. for (unsigned i = 1, e = GEPLHS->getNumOperands(); i != e; ++i)
  684. if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
  685. IndicesTheSame = false;
  686. break;
  687. }
  688. // If all indices are the same, just compare the base pointers.
  689. Type *BaseType = GEPLHS->getOperand(0)->getType();
  690. if (IndicesTheSame && CmpInst::makeCmpResultType(BaseType) == I.getType())
  691. return new ICmpInst(Cond, GEPLHS->getOperand(0), GEPRHS->getOperand(0));
  692. // If we're comparing GEPs with two base pointers that only differ in type
  693. // and both GEPs have only constant indices or just one use, then fold
  694. // the compare with the adjusted indices.
  695. // FIXME: Support vector of pointers.
  696. if (GEPLHS->isInBounds() && GEPRHS->isInBounds() &&
  697. (GEPLHS->hasAllConstantIndices() || GEPLHS->hasOneUse()) &&
  698. (GEPRHS->hasAllConstantIndices() || GEPRHS->hasOneUse()) &&
  699. PtrBase->stripPointerCasts() ==
  700. GEPRHS->getOperand(0)->stripPointerCasts() &&
  701. !GEPLHS->getType()->isVectorTy()) {
  702. Value *LOffset = EmitGEPOffset(GEPLHS);
  703. Value *ROffset = EmitGEPOffset(GEPRHS);
  704. // If we looked through an addrspacecast between different sized address
  705. // spaces, the LHS and RHS pointers are different sized
  706. // integers. Truncate to the smaller one.
  707. Type *LHSIndexTy = LOffset->getType();
  708. Type *RHSIndexTy = ROffset->getType();
  709. if (LHSIndexTy != RHSIndexTy) {
  710. if (LHSIndexTy->getPrimitiveSizeInBits().getFixedValue() <
  711. RHSIndexTy->getPrimitiveSizeInBits().getFixedValue()) {
  712. ROffset = Builder.CreateTrunc(ROffset, LHSIndexTy);
  713. } else
  714. LOffset = Builder.CreateTrunc(LOffset, RHSIndexTy);
  715. }
  716. Value *Cmp = Builder.CreateICmp(ICmpInst::getSignedPredicate(Cond),
  717. LOffset, ROffset);
  718. return replaceInstUsesWith(I, Cmp);
  719. }
  720. // Otherwise, the base pointers are different and the indices are
  721. // different. Try convert this to an indexed compare by looking through
  722. // PHIs/casts.
  723. return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
  724. }
  725. // If one of the GEPs has all zero indices, recurse.
  726. // FIXME: Handle vector of pointers.
  727. if (!GEPLHS->getType()->isVectorTy() && GEPLHS->hasAllZeroIndices())
  728. return foldGEPICmp(GEPRHS, GEPLHS->getOperand(0),
  729. ICmpInst::getSwappedPredicate(Cond), I);
  730. // If the other GEP has all zero indices, recurse.
  731. // FIXME: Handle vector of pointers.
  732. if (!GEPRHS->getType()->isVectorTy() && GEPRHS->hasAllZeroIndices())
  733. return foldGEPICmp(GEPLHS, GEPRHS->getOperand(0), Cond, I);
  734. bool GEPsInBounds = GEPLHS->isInBounds() && GEPRHS->isInBounds();
  735. if (GEPLHS->getNumOperands() == GEPRHS->getNumOperands() &&
  736. GEPLHS->getSourceElementType() == GEPRHS->getSourceElementType()) {
  737. // If the GEPs only differ by one index, compare it.
  738. unsigned NumDifferences = 0; // Keep track of # differences.
  739. unsigned DiffOperand = 0; // The operand that differs.
  740. for (unsigned i = 1, e = GEPRHS->getNumOperands(); i != e; ++i)
  741. if (GEPLHS->getOperand(i) != GEPRHS->getOperand(i)) {
  742. Type *LHSType = GEPLHS->getOperand(i)->getType();
  743. Type *RHSType = GEPRHS->getOperand(i)->getType();
  744. // FIXME: Better support for vector of pointers.
  745. if (LHSType->getPrimitiveSizeInBits() !=
  746. RHSType->getPrimitiveSizeInBits() ||
  747. (GEPLHS->getType()->isVectorTy() &&
  748. (!LHSType->isVectorTy() || !RHSType->isVectorTy()))) {
  749. // Irreconcilable differences.
  750. NumDifferences = 2;
  751. break;
  752. }
  753. if (NumDifferences++) break;
  754. DiffOperand = i;
  755. }
  756. if (NumDifferences == 0) // SAME GEP?
  757. return replaceInstUsesWith(I, // No comparison is needed here.
  758. ConstantInt::get(I.getType(), ICmpInst::isTrueWhenEqual(Cond)));
  759. else if (NumDifferences == 1 && GEPsInBounds) {
  760. Value *LHSV = GEPLHS->getOperand(DiffOperand);
  761. Value *RHSV = GEPRHS->getOperand(DiffOperand);
  762. // Make sure we do a signed comparison here.
  763. return new ICmpInst(ICmpInst::getSignedPredicate(Cond), LHSV, RHSV);
  764. }
  765. }
  766. // Only lower this if the icmp is the only user of the GEP or if we expect
  767. // the result to fold to a constant!
  768. if (GEPsInBounds && (isa<ConstantExpr>(GEPLHS) || GEPLHS->hasOneUse()) &&
  769. (isa<ConstantExpr>(GEPRHS) || GEPRHS->hasOneUse())) {
  770. // ((gep Ptr, OFFSET1) cmp (gep Ptr, OFFSET2) ---> (OFFSET1 cmp OFFSET2)
  771. Value *L = EmitGEPOffset(GEPLHS);
  772. Value *R = EmitGEPOffset(GEPRHS);
  773. return new ICmpInst(ICmpInst::getSignedPredicate(Cond), L, R);
  774. }
  775. }
  776. // Try convert this to an indexed compare by looking through PHIs/casts as a
  777. // last resort.
  778. return transformToIndexedCompare(GEPLHS, RHS, Cond, DL);
  779. }
  780. Instruction *InstCombinerImpl::foldAllocaCmp(ICmpInst &ICI,
  781. const AllocaInst *Alloca) {
  782. assert(ICI.isEquality() && "Cannot fold non-equality comparison.");
  783. // It would be tempting to fold away comparisons between allocas and any
  784. // pointer not based on that alloca (e.g. an argument). However, even
  785. // though such pointers cannot alias, they can still compare equal.
  786. //
  787. // But LLVM doesn't specify where allocas get their memory, so if the alloca
  788. // doesn't escape we can argue that it's impossible to guess its value, and we
  789. // can therefore act as if any such guesses are wrong.
  790. //
  791. // The code below checks that the alloca doesn't escape, and that it's only
  792. // used in a comparison once (the current instruction). The
  793. // single-comparison-use condition ensures that we're trivially folding all
  794. // comparisons against the alloca consistently, and avoids the risk of
  795. // erroneously folding a comparison of the pointer with itself.
  796. unsigned MaxIter = 32; // Break cycles and bound to constant-time.
  797. SmallVector<const Use *, 32> Worklist;
  798. for (const Use &U : Alloca->uses()) {
  799. if (Worklist.size() >= MaxIter)
  800. return nullptr;
  801. Worklist.push_back(&U);
  802. }
  803. unsigned NumCmps = 0;
  804. while (!Worklist.empty()) {
  805. assert(Worklist.size() <= MaxIter);
  806. const Use *U = Worklist.pop_back_val();
  807. const Value *V = U->getUser();
  808. --MaxIter;
  809. if (isa<BitCastInst>(V) || isa<GetElementPtrInst>(V) || isa<PHINode>(V) ||
  810. isa<SelectInst>(V)) {
  811. // Track the uses.
  812. } else if (isa<LoadInst>(V)) {
  813. // Loading from the pointer doesn't escape it.
  814. continue;
  815. } else if (const auto *SI = dyn_cast<StoreInst>(V)) {
  816. // Storing *to* the pointer is fine, but storing the pointer escapes it.
  817. if (SI->getValueOperand() == U->get())
  818. return nullptr;
  819. continue;
  820. } else if (isa<ICmpInst>(V)) {
  821. if (NumCmps++)
  822. return nullptr; // Found more than one cmp.
  823. continue;
  824. } else if (const auto *Intrin = dyn_cast<IntrinsicInst>(V)) {
  825. switch (Intrin->getIntrinsicID()) {
  826. // These intrinsics don't escape or compare the pointer. Memset is safe
  827. // because we don't allow ptrtoint. Memcpy and memmove are safe because
  828. // we don't allow stores, so src cannot point to V.
  829. case Intrinsic::lifetime_start: case Intrinsic::lifetime_end:
  830. case Intrinsic::memcpy: case Intrinsic::memmove: case Intrinsic::memset:
  831. continue;
  832. default:
  833. return nullptr;
  834. }
  835. } else {
  836. return nullptr;
  837. }
  838. for (const Use &U : V->uses()) {
  839. if (Worklist.size() >= MaxIter)
  840. return nullptr;
  841. Worklist.push_back(&U);
  842. }
  843. }
  844. auto *Res = ConstantInt::get(ICI.getType(),
  845. !CmpInst::isTrueWhenEqual(ICI.getPredicate()));
  846. return replaceInstUsesWith(ICI, Res);
  847. }
  848. /// Fold "icmp pred (X+C), X".
  849. Instruction *InstCombinerImpl::foldICmpAddOpConst(Value *X, const APInt &C,
  850. ICmpInst::Predicate Pred) {
  851. // From this point on, we know that (X+C <= X) --> (X+C < X) because C != 0,
  852. // so the values can never be equal. Similarly for all other "or equals"
  853. // operators.
  854. assert(!!C && "C should not be zero!");
  855. // (X+1) <u X --> X >u (MAXUINT-1) --> X == 255
  856. // (X+2) <u X --> X >u (MAXUINT-2) --> X > 253
  857. // (X+MAXUINT) <u X --> X >u (MAXUINT-MAXUINT) --> X != 0
  858. if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE) {
  859. Constant *R = ConstantInt::get(X->getType(),
  860. APInt::getMaxValue(C.getBitWidth()) - C);
  861. return new ICmpInst(ICmpInst::ICMP_UGT, X, R);
  862. }
  863. // (X+1) >u X --> X <u (0-1) --> X != 255
  864. // (X+2) >u X --> X <u (0-2) --> X <u 254
  865. // (X+MAXUINT) >u X --> X <u (0-MAXUINT) --> X <u 1 --> X == 0
  866. if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_UGE)
  867. return new ICmpInst(ICmpInst::ICMP_ULT, X,
  868. ConstantInt::get(X->getType(), -C));
  869. APInt SMax = APInt::getSignedMaxValue(C.getBitWidth());
  870. // (X+ 1) <s X --> X >s (MAXSINT-1) --> X == 127
  871. // (X+ 2) <s X --> X >s (MAXSINT-2) --> X >s 125
  872. // (X+MAXSINT) <s X --> X >s (MAXSINT-MAXSINT) --> X >s 0
  873. // (X+MINSINT) <s X --> X >s (MAXSINT-MINSINT) --> X >s -1
  874. // (X+ -2) <s X --> X >s (MAXSINT- -2) --> X >s 126
  875. // (X+ -1) <s X --> X >s (MAXSINT- -1) --> X != 127
  876. if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
  877. return new ICmpInst(ICmpInst::ICMP_SGT, X,
  878. ConstantInt::get(X->getType(), SMax - C));
  879. // (X+ 1) >s X --> X <s (MAXSINT-(1-1)) --> X != 127
  880. // (X+ 2) >s X --> X <s (MAXSINT-(2-1)) --> X <s 126
  881. // (X+MAXSINT) >s X --> X <s (MAXSINT-(MAXSINT-1)) --> X <s 1
  882. // (X+MINSINT) >s X --> X <s (MAXSINT-(MINSINT-1)) --> X <s -2
  883. // (X+ -2) >s X --> X <s (MAXSINT-(-2-1)) --> X <s -126
  884. // (X+ -1) >s X --> X <s (MAXSINT-(-1-1)) --> X == -128
  885. assert(Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SGE);
  886. return new ICmpInst(ICmpInst::ICMP_SLT, X,
  887. ConstantInt::get(X->getType(), SMax - (C - 1)));
  888. }
  889. /// Handle "(icmp eq/ne (ashr/lshr AP2, A), AP1)" ->
  890. /// (icmp eq/ne A, Log2(AP2/AP1)) ->
  891. /// (icmp eq/ne A, Log2(AP2) - Log2(AP1)).
  892. Instruction *InstCombinerImpl::foldICmpShrConstConst(ICmpInst &I, Value *A,
  893. const APInt &AP1,
  894. const APInt &AP2) {
  895. assert(I.isEquality() && "Cannot fold icmp gt/lt");
  896. auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
  897. if (I.getPredicate() == I.ICMP_NE)
  898. Pred = CmpInst::getInversePredicate(Pred);
  899. return new ICmpInst(Pred, LHS, RHS);
  900. };
  901. // Don't bother doing any work for cases which InstSimplify handles.
  902. if (AP2.isZero())
  903. return nullptr;
  904. bool IsAShr = isa<AShrOperator>(I.getOperand(0));
  905. if (IsAShr) {
  906. if (AP2.isAllOnes())
  907. return nullptr;
  908. if (AP2.isNegative() != AP1.isNegative())
  909. return nullptr;
  910. if (AP2.sgt(AP1))
  911. return nullptr;
  912. }
  913. if (!AP1)
  914. // 'A' must be large enough to shift out the highest set bit.
  915. return getICmp(I.ICMP_UGT, A,
  916. ConstantInt::get(A->getType(), AP2.logBase2()));
  917. if (AP1 == AP2)
  918. return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
  919. int Shift;
  920. if (IsAShr && AP1.isNegative())
  921. Shift = AP1.countLeadingOnes() - AP2.countLeadingOnes();
  922. else
  923. Shift = AP1.countLeadingZeros() - AP2.countLeadingZeros();
  924. if (Shift > 0) {
  925. if (IsAShr && AP1 == AP2.ashr(Shift)) {
  926. // There are multiple solutions if we are comparing against -1 and the LHS
  927. // of the ashr is not a power of two.
  928. if (AP1.isAllOnes() && !AP2.isPowerOf2())
  929. return getICmp(I.ICMP_UGE, A, ConstantInt::get(A->getType(), Shift));
  930. return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
  931. } else if (AP1 == AP2.lshr(Shift)) {
  932. return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
  933. }
  934. }
  935. // Shifting const2 will never be equal to const1.
  936. // FIXME: This should always be handled by InstSimplify?
  937. auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
  938. return replaceInstUsesWith(I, TorF);
  939. }
  940. /// Handle "(icmp eq/ne (shl AP2, A), AP1)" ->
  941. /// (icmp eq/ne A, TrailingZeros(AP1) - TrailingZeros(AP2)).
  942. Instruction *InstCombinerImpl::foldICmpShlConstConst(ICmpInst &I, Value *A,
  943. const APInt &AP1,
  944. const APInt &AP2) {
  945. assert(I.isEquality() && "Cannot fold icmp gt/lt");
  946. auto getICmp = [&I](CmpInst::Predicate Pred, Value *LHS, Value *RHS) {
  947. if (I.getPredicate() == I.ICMP_NE)
  948. Pred = CmpInst::getInversePredicate(Pred);
  949. return new ICmpInst(Pred, LHS, RHS);
  950. };
  951. // Don't bother doing any work for cases which InstSimplify handles.
  952. if (AP2.isZero())
  953. return nullptr;
  954. unsigned AP2TrailingZeros = AP2.countTrailingZeros();
  955. if (!AP1 && AP2TrailingZeros != 0)
  956. return getICmp(
  957. I.ICMP_UGE, A,
  958. ConstantInt::get(A->getType(), AP2.getBitWidth() - AP2TrailingZeros));
  959. if (AP1 == AP2)
  960. return getICmp(I.ICMP_EQ, A, ConstantInt::getNullValue(A->getType()));
  961. // Get the distance between the lowest bits that are set.
  962. int Shift = AP1.countTrailingZeros() - AP2TrailingZeros;
  963. if (Shift > 0 && AP2.shl(Shift) == AP1)
  964. return getICmp(I.ICMP_EQ, A, ConstantInt::get(A->getType(), Shift));
  965. // Shifting const2 will never be equal to const1.
  966. // FIXME: This should always be handled by InstSimplify?
  967. auto *TorF = ConstantInt::get(I.getType(), I.getPredicate() == I.ICMP_NE);
  968. return replaceInstUsesWith(I, TorF);
  969. }
  970. /// The caller has matched a pattern of the form:
  971. /// I = icmp ugt (add (add A, B), CI2), CI1
  972. /// If this is of the form:
  973. /// sum = a + b
  974. /// if (sum+128 >u 255)
  975. /// Then replace it with llvm.sadd.with.overflow.i8.
  976. ///
  977. static Instruction *processUGT_ADDCST_ADD(ICmpInst &I, Value *A, Value *B,
  978. ConstantInt *CI2, ConstantInt *CI1,
  979. InstCombinerImpl &IC) {
  980. // The transformation we're trying to do here is to transform this into an
  981. // llvm.sadd.with.overflow. To do this, we have to replace the original add
  982. // with a narrower add, and discard the add-with-constant that is part of the
  983. // range check (if we can't eliminate it, this isn't profitable).
  984. // In order to eliminate the add-with-constant, the compare can be its only
  985. // use.
  986. Instruction *AddWithCst = cast<Instruction>(I.getOperand(0));
  987. if (!AddWithCst->hasOneUse())
  988. return nullptr;
  989. // If CI2 is 2^7, 2^15, 2^31, then it might be an sadd.with.overflow.
  990. if (!CI2->getValue().isPowerOf2())
  991. return nullptr;
  992. unsigned NewWidth = CI2->getValue().countTrailingZeros();
  993. if (NewWidth != 7 && NewWidth != 15 && NewWidth != 31)
  994. return nullptr;
  995. // The width of the new add formed is 1 more than the bias.
  996. ++NewWidth;
  997. // Check to see that CI1 is an all-ones value with NewWidth bits.
  998. if (CI1->getBitWidth() == NewWidth ||
  999. CI1->getValue() != APInt::getLowBitsSet(CI1->getBitWidth(), NewWidth))
  1000. return nullptr;
  1001. // This is only really a signed overflow check if the inputs have been
  1002. // sign-extended; check for that condition. For example, if CI2 is 2^31 and
  1003. // the operands of the add are 64 bits wide, we need at least 33 sign bits.
  1004. if (IC.ComputeMaxSignificantBits(A, 0, &I) > NewWidth ||
  1005. IC.ComputeMaxSignificantBits(B, 0, &I) > NewWidth)
  1006. return nullptr;
  1007. // In order to replace the original add with a narrower
  1008. // llvm.sadd.with.overflow, the only uses allowed are the add-with-constant
  1009. // and truncates that discard the high bits of the add. Verify that this is
  1010. // the case.
  1011. Instruction *OrigAdd = cast<Instruction>(AddWithCst->getOperand(0));
  1012. for (User *U : OrigAdd->users()) {
  1013. if (U == AddWithCst)
  1014. continue;
  1015. // Only accept truncates for now. We would really like a nice recursive
  1016. // predicate like SimplifyDemandedBits, but which goes downwards the use-def
  1017. // chain to see which bits of a value are actually demanded. If the
  1018. // original add had another add which was then immediately truncated, we
  1019. // could still do the transformation.
  1020. TruncInst *TI = dyn_cast<TruncInst>(U);
  1021. if (!TI || TI->getType()->getPrimitiveSizeInBits() > NewWidth)
  1022. return nullptr;
  1023. }
  1024. // If the pattern matches, truncate the inputs to the narrower type and
  1025. // use the sadd_with_overflow intrinsic to efficiently compute both the
  1026. // result and the overflow bit.
  1027. Type *NewType = IntegerType::get(OrigAdd->getContext(), NewWidth);
  1028. Function *F = Intrinsic::getDeclaration(
  1029. I.getModule(), Intrinsic::sadd_with_overflow, NewType);
  1030. InstCombiner::BuilderTy &Builder = IC.Builder;
  1031. // Put the new code above the original add, in case there are any uses of the
  1032. // add between the add and the compare.
  1033. Builder.SetInsertPoint(OrigAdd);
  1034. Value *TruncA = Builder.CreateTrunc(A, NewType, A->getName() + ".trunc");
  1035. Value *TruncB = Builder.CreateTrunc(B, NewType, B->getName() + ".trunc");
  1036. CallInst *Call = Builder.CreateCall(F, {TruncA, TruncB}, "sadd");
  1037. Value *Add = Builder.CreateExtractValue(Call, 0, "sadd.result");
  1038. Value *ZExt = Builder.CreateZExt(Add, OrigAdd->getType());
  1039. // The inner add was the result of the narrow add, zero extended to the
  1040. // wider type. Replace it with the result computed by the intrinsic.
  1041. IC.replaceInstUsesWith(*OrigAdd, ZExt);
  1042. IC.eraseInstFromFunction(*OrigAdd);
  1043. // The original icmp gets replaced with the overflow value.
  1044. return ExtractValueInst::Create(Call, 1, "sadd.overflow");
  1045. }
  1046. /// If we have:
  1047. /// icmp eq/ne (urem/srem %x, %y), 0
  1048. /// iff %y is a power-of-two, we can replace this with a bit test:
  1049. /// icmp eq/ne (and %x, (add %y, -1)), 0
  1050. Instruction *InstCombinerImpl::foldIRemByPowerOfTwoToBitTest(ICmpInst &I) {
  1051. // This fold is only valid for equality predicates.
  1052. if (!I.isEquality())
  1053. return nullptr;
  1054. ICmpInst::Predicate Pred;
  1055. Value *X, *Y, *Zero;
  1056. if (!match(&I, m_ICmp(Pred, m_OneUse(m_IRem(m_Value(X), m_Value(Y))),
  1057. m_CombineAnd(m_Zero(), m_Value(Zero)))))
  1058. return nullptr;
  1059. if (!isKnownToBeAPowerOfTwo(Y, /*OrZero*/ true, 0, &I))
  1060. return nullptr;
  1061. // This may increase instruction count, we don't enforce that Y is a constant.
  1062. Value *Mask = Builder.CreateAdd(Y, Constant::getAllOnesValue(Y->getType()));
  1063. Value *Masked = Builder.CreateAnd(X, Mask);
  1064. return ICmpInst::Create(Instruction::ICmp, Pred, Masked, Zero);
  1065. }
  1066. /// Fold equality-comparison between zero and any (maybe truncated) right-shift
  1067. /// by one-less-than-bitwidth into a sign test on the original value.
  1068. Instruction *InstCombinerImpl::foldSignBitTest(ICmpInst &I) {
  1069. Instruction *Val;
  1070. ICmpInst::Predicate Pred;
  1071. if (!I.isEquality() || !match(&I, m_ICmp(Pred, m_Instruction(Val), m_Zero())))
  1072. return nullptr;
  1073. Value *X;
  1074. Type *XTy;
  1075. Constant *C;
  1076. if (match(Val, m_TruncOrSelf(m_Shr(m_Value(X), m_Constant(C))))) {
  1077. XTy = X->getType();
  1078. unsigned XBitWidth = XTy->getScalarSizeInBits();
  1079. if (!match(C, m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_EQ,
  1080. APInt(XBitWidth, XBitWidth - 1))))
  1081. return nullptr;
  1082. } else if (isa<BinaryOperator>(Val) &&
  1083. (X = reassociateShiftAmtsOfTwoSameDirectionShifts(
  1084. cast<BinaryOperator>(Val), SQ.getWithInstruction(Val),
  1085. /*AnalyzeForSignBitExtraction=*/true))) {
  1086. XTy = X->getType();
  1087. } else
  1088. return nullptr;
  1089. return ICmpInst::Create(Instruction::ICmp,
  1090. Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_SGE
  1091. : ICmpInst::ICMP_SLT,
  1092. X, ConstantInt::getNullValue(XTy));
  1093. }
  1094. // Handle icmp pred X, 0
  1095. Instruction *InstCombinerImpl::foldICmpWithZero(ICmpInst &Cmp) {
  1096. CmpInst::Predicate Pred = Cmp.getPredicate();
  1097. if (!match(Cmp.getOperand(1), m_Zero()))
  1098. return nullptr;
  1099. // (icmp sgt smin(PosA, B) 0) -> (icmp sgt B 0)
  1100. if (Pred == ICmpInst::ICMP_SGT) {
  1101. Value *A, *B;
  1102. if (match(Cmp.getOperand(0), m_SMin(m_Value(A), m_Value(B)))) {
  1103. if (isKnownPositive(A, DL, 0, &AC, &Cmp, &DT))
  1104. return new ICmpInst(Pred, B, Cmp.getOperand(1));
  1105. if (isKnownPositive(B, DL, 0, &AC, &Cmp, &DT))
  1106. return new ICmpInst(Pred, A, Cmp.getOperand(1));
  1107. }
  1108. }
  1109. if (Instruction *New = foldIRemByPowerOfTwoToBitTest(Cmp))
  1110. return New;
  1111. // Given:
  1112. // icmp eq/ne (urem %x, %y), 0
  1113. // Iff %x has 0 or 1 bits set, and %y has at least 2 bits set, omit 'urem':
  1114. // icmp eq/ne %x, 0
  1115. Value *X, *Y;
  1116. if (match(Cmp.getOperand(0), m_URem(m_Value(X), m_Value(Y))) &&
  1117. ICmpInst::isEquality(Pred)) {
  1118. KnownBits XKnown = computeKnownBits(X, 0, &Cmp);
  1119. KnownBits YKnown = computeKnownBits(Y, 0, &Cmp);
  1120. if (XKnown.countMaxPopulation() == 1 && YKnown.countMinPopulation() >= 2)
  1121. return new ICmpInst(Pred, X, Cmp.getOperand(1));
  1122. }
  1123. return nullptr;
  1124. }
  1125. /// Fold icmp Pred X, C.
  1126. /// TODO: This code structure does not make sense. The saturating add fold
  1127. /// should be moved to some other helper and extended as noted below (it is also
  1128. /// possible that code has been made unnecessary - do we canonicalize IR to
  1129. /// overflow/saturating intrinsics or not?).
  1130. Instruction *InstCombinerImpl::foldICmpWithConstant(ICmpInst &Cmp) {
  1131. // Match the following pattern, which is a common idiom when writing
  1132. // overflow-safe integer arithmetic functions. The source performs an addition
  1133. // in wider type and explicitly checks for overflow using comparisons against
  1134. // INT_MIN and INT_MAX. Simplify by using the sadd_with_overflow intrinsic.
  1135. //
  1136. // TODO: This could probably be generalized to handle other overflow-safe
  1137. // operations if we worked out the formulas to compute the appropriate magic
  1138. // constants.
  1139. //
  1140. // sum = a + b
  1141. // if (sum+128 >u 255) ... -> llvm.sadd.with.overflow.i8
  1142. CmpInst::Predicate Pred = Cmp.getPredicate();
  1143. Value *Op0 = Cmp.getOperand(0), *Op1 = Cmp.getOperand(1);
  1144. Value *A, *B;
  1145. ConstantInt *CI, *CI2; // I = icmp ugt (add (add A, B), CI2), CI
  1146. if (Pred == ICmpInst::ICMP_UGT && match(Op1, m_ConstantInt(CI)) &&
  1147. match(Op0, m_Add(m_Add(m_Value(A), m_Value(B)), m_ConstantInt(CI2))))
  1148. if (Instruction *Res = processUGT_ADDCST_ADD(Cmp, A, B, CI2, CI, *this))
  1149. return Res;
  1150. // icmp(phi(C1, C2, ...), C) -> phi(icmp(C1, C), icmp(C2, C), ...).
  1151. Constant *C = dyn_cast<Constant>(Op1);
  1152. if (!C)
  1153. return nullptr;
  1154. if (auto *Phi = dyn_cast<PHINode>(Op0))
  1155. if (all_of(Phi->operands(), [](Value *V) { return isa<Constant>(V); })) {
  1156. Type *Ty = Cmp.getType();
  1157. Builder.SetInsertPoint(Phi);
  1158. PHINode *NewPhi =
  1159. Builder.CreatePHI(Ty, Phi->getNumOperands());
  1160. for (BasicBlock *Predecessor : predecessors(Phi->getParent())) {
  1161. auto *Input =
  1162. cast<Constant>(Phi->getIncomingValueForBlock(Predecessor));
  1163. auto *BoolInput = ConstantExpr::getCompare(Pred, Input, C);
  1164. NewPhi->addIncoming(BoolInput, Predecessor);
  1165. }
  1166. NewPhi->takeName(&Cmp);
  1167. return replaceInstUsesWith(Cmp, NewPhi);
  1168. }
  1169. return nullptr;
  1170. }
  1171. /// Canonicalize icmp instructions based on dominating conditions.
  1172. Instruction *InstCombinerImpl::foldICmpWithDominatingICmp(ICmpInst &Cmp) {
  1173. // This is a cheap/incomplete check for dominance - just match a single
  1174. // predecessor with a conditional branch.
  1175. BasicBlock *CmpBB = Cmp.getParent();
  1176. BasicBlock *DomBB = CmpBB->getSinglePredecessor();
  1177. if (!DomBB)
  1178. return nullptr;
  1179. Value *DomCond;
  1180. BasicBlock *TrueBB, *FalseBB;
  1181. if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
  1182. return nullptr;
  1183. assert((TrueBB == CmpBB || FalseBB == CmpBB) &&
  1184. "Predecessor block does not point to successor?");
  1185. // The branch should get simplified. Don't bother simplifying this condition.
  1186. if (TrueBB == FalseBB)
  1187. return nullptr;
  1188. // Try to simplify this compare to T/F based on the dominating condition.
  1189. std::optional<bool> Imp =
  1190. isImpliedCondition(DomCond, &Cmp, DL, TrueBB == CmpBB);
  1191. if (Imp)
  1192. return replaceInstUsesWith(Cmp, ConstantInt::get(Cmp.getType(), *Imp));
  1193. CmpInst::Predicate Pred = Cmp.getPredicate();
  1194. Value *X = Cmp.getOperand(0), *Y = Cmp.getOperand(1);
  1195. ICmpInst::Predicate DomPred;
  1196. const APInt *C, *DomC;
  1197. if (match(DomCond, m_ICmp(DomPred, m_Specific(X), m_APInt(DomC))) &&
  1198. match(Y, m_APInt(C))) {
  1199. // We have 2 compares of a variable with constants. Calculate the constant
  1200. // ranges of those compares to see if we can transform the 2nd compare:
  1201. // DomBB:
  1202. // DomCond = icmp DomPred X, DomC
  1203. // br DomCond, CmpBB, FalseBB
  1204. // CmpBB:
  1205. // Cmp = icmp Pred X, C
  1206. ConstantRange CR = ConstantRange::makeExactICmpRegion(Pred, *C);
  1207. ConstantRange DominatingCR =
  1208. (CmpBB == TrueBB) ? ConstantRange::makeExactICmpRegion(DomPred, *DomC)
  1209. : ConstantRange::makeExactICmpRegion(
  1210. CmpInst::getInversePredicate(DomPred), *DomC);
  1211. ConstantRange Intersection = DominatingCR.intersectWith(CR);
  1212. ConstantRange Difference = DominatingCR.difference(CR);
  1213. if (Intersection.isEmptySet())
  1214. return replaceInstUsesWith(Cmp, Builder.getFalse());
  1215. if (Difference.isEmptySet())
  1216. return replaceInstUsesWith(Cmp, Builder.getTrue());
  1217. // Canonicalizing a sign bit comparison that gets used in a branch,
  1218. // pessimizes codegen by generating branch on zero instruction instead
  1219. // of a test and branch. So we avoid canonicalizing in such situations
  1220. // because test and branch instruction has better branch displacement
  1221. // than compare and branch instruction.
  1222. bool UnusedBit;
  1223. bool IsSignBit = isSignBitCheck(Pred, *C, UnusedBit);
  1224. if (Cmp.isEquality() || (IsSignBit && hasBranchUse(Cmp)))
  1225. return nullptr;
  1226. // Avoid an infinite loop with min/max canonicalization.
  1227. // TODO: This will be unnecessary if we canonicalize to min/max intrinsics.
  1228. if (Cmp.hasOneUse() &&
  1229. match(Cmp.user_back(), m_MaxOrMin(m_Value(), m_Value())))
  1230. return nullptr;
  1231. if (const APInt *EqC = Intersection.getSingleElement())
  1232. return new ICmpInst(ICmpInst::ICMP_EQ, X, Builder.getInt(*EqC));
  1233. if (const APInt *NeC = Difference.getSingleElement())
  1234. return new ICmpInst(ICmpInst::ICMP_NE, X, Builder.getInt(*NeC));
  1235. }
  1236. return nullptr;
  1237. }
  1238. /// Fold icmp (trunc X), C.
  1239. Instruction *InstCombinerImpl::foldICmpTruncConstant(ICmpInst &Cmp,
  1240. TruncInst *Trunc,
  1241. const APInt &C) {
  1242. ICmpInst::Predicate Pred = Cmp.getPredicate();
  1243. Value *X = Trunc->getOperand(0);
  1244. if (C.isOne() && C.getBitWidth() > 1) {
  1245. // icmp slt trunc(signum(V)) 1 --> icmp slt V, 1
  1246. Value *V = nullptr;
  1247. if (Pred == ICmpInst::ICMP_SLT && match(X, m_Signum(m_Value(V))))
  1248. return new ICmpInst(ICmpInst::ICMP_SLT, V,
  1249. ConstantInt::get(V->getType(), 1));
  1250. }
  1251. Type *SrcTy = X->getType();
  1252. unsigned DstBits = Trunc->getType()->getScalarSizeInBits(),
  1253. SrcBits = SrcTy->getScalarSizeInBits();
  1254. // TODO: Handle any shifted constant by subtracting trailing zeros.
  1255. // TODO: Handle non-equality predicates.
  1256. Value *Y;
  1257. if (Cmp.isEquality() && match(X, m_Shl(m_One(), m_Value(Y)))) {
  1258. // (trunc (1 << Y) to iN) == 0 --> Y u>= N
  1259. // (trunc (1 << Y) to iN) != 0 --> Y u< N
  1260. if (C.isZero()) {
  1261. auto NewPred = (Pred == Cmp.ICMP_EQ) ? Cmp.ICMP_UGE : Cmp.ICMP_ULT;
  1262. return new ICmpInst(NewPred, Y, ConstantInt::get(SrcTy, DstBits));
  1263. }
  1264. // (trunc (1 << Y) to iN) == 2**C --> Y == C
  1265. // (trunc (1 << Y) to iN) != 2**C --> Y != C
  1266. if (C.isPowerOf2())
  1267. return new ICmpInst(Pred, Y, ConstantInt::get(SrcTy, C.logBase2()));
  1268. }
  1269. if (Cmp.isEquality() && Trunc->hasOneUse()) {
  1270. // Canonicalize to a mask and wider compare if the wide type is suitable:
  1271. // (trunc X to i8) == C --> (X & 0xff) == (zext C)
  1272. if (!SrcTy->isVectorTy() && shouldChangeType(DstBits, SrcBits)) {
  1273. Constant *Mask =
  1274. ConstantInt::get(SrcTy, APInt::getLowBitsSet(SrcBits, DstBits));
  1275. Value *And = Builder.CreateAnd(X, Mask);
  1276. Constant *WideC = ConstantInt::get(SrcTy, C.zext(SrcBits));
  1277. return new ICmpInst(Pred, And, WideC);
  1278. }
  1279. // Simplify icmp eq (trunc x to i8), 42 -> icmp eq x, 42|highbits if all
  1280. // of the high bits truncated out of x are known.
  1281. KnownBits Known = computeKnownBits(X, 0, &Cmp);
  1282. // If all the high bits are known, we can do this xform.
  1283. if ((Known.Zero | Known.One).countLeadingOnes() >= SrcBits - DstBits) {
  1284. // Pull in the high bits from known-ones set.
  1285. APInt NewRHS = C.zext(SrcBits);
  1286. NewRHS |= Known.One & APInt::getHighBitsSet(SrcBits, SrcBits - DstBits);
  1287. return new ICmpInst(Pred, X, ConstantInt::get(SrcTy, NewRHS));
  1288. }
  1289. }
  1290. // Look through truncated right-shift of the sign-bit for a sign-bit check:
  1291. // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] < 0 --> ShOp < 0
  1292. // trunc iN (ShOp >> ShAmtC) to i[N - ShAmtC] > -1 --> ShOp > -1
  1293. Value *ShOp;
  1294. const APInt *ShAmtC;
  1295. bool TrueIfSigned;
  1296. if (isSignBitCheck(Pred, C, TrueIfSigned) &&
  1297. match(X, m_Shr(m_Value(ShOp), m_APInt(ShAmtC))) &&
  1298. DstBits == SrcBits - ShAmtC->getZExtValue()) {
  1299. return TrueIfSigned ? new ICmpInst(ICmpInst::ICMP_SLT, ShOp,
  1300. ConstantInt::getNullValue(SrcTy))
  1301. : new ICmpInst(ICmpInst::ICMP_SGT, ShOp,
  1302. ConstantInt::getAllOnesValue(SrcTy));
  1303. }
  1304. return nullptr;
  1305. }
  1306. /// Fold icmp (xor X, Y), C.
  1307. Instruction *InstCombinerImpl::foldICmpXorConstant(ICmpInst &Cmp,
  1308. BinaryOperator *Xor,
  1309. const APInt &C) {
  1310. if (Instruction *I = foldICmpXorShiftConst(Cmp, Xor, C))
  1311. return I;
  1312. Value *X = Xor->getOperand(0);
  1313. Value *Y = Xor->getOperand(1);
  1314. const APInt *XorC;
  1315. if (!match(Y, m_APInt(XorC)))
  1316. return nullptr;
  1317. // If this is a comparison that tests the signbit (X < 0) or (x > -1),
  1318. // fold the xor.
  1319. ICmpInst::Predicate Pred = Cmp.getPredicate();
  1320. bool TrueIfSigned = false;
  1321. if (isSignBitCheck(Cmp.getPredicate(), C, TrueIfSigned)) {
  1322. // If the sign bit of the XorCst is not set, there is no change to
  1323. // the operation, just stop using the Xor.
  1324. if (!XorC->isNegative())
  1325. return replaceOperand(Cmp, 0, X);
  1326. // Emit the opposite comparison.
  1327. if (TrueIfSigned)
  1328. return new ICmpInst(ICmpInst::ICMP_SGT, X,
  1329. ConstantInt::getAllOnesValue(X->getType()));
  1330. else
  1331. return new ICmpInst(ICmpInst::ICMP_SLT, X,
  1332. ConstantInt::getNullValue(X->getType()));
  1333. }
  1334. if (Xor->hasOneUse()) {
  1335. // (icmp u/s (xor X SignMask), C) -> (icmp s/u X, (xor C SignMask))
  1336. if (!Cmp.isEquality() && XorC->isSignMask()) {
  1337. Pred = Cmp.getFlippedSignednessPredicate();
  1338. return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
  1339. }
  1340. // (icmp u/s (xor X ~SignMask), C) -> (icmp s/u X, (xor C ~SignMask))
  1341. if (!Cmp.isEquality() && XorC->isMaxSignedValue()) {
  1342. Pred = Cmp.getFlippedSignednessPredicate();
  1343. Pred = Cmp.getSwappedPredicate(Pred);
  1344. return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), C ^ *XorC));
  1345. }
  1346. }
  1347. // Mask constant magic can eliminate an 'xor' with unsigned compares.
  1348. if (Pred == ICmpInst::ICMP_UGT) {
  1349. // (xor X, ~C) >u C --> X <u ~C (when C+1 is a power of 2)
  1350. if (*XorC == ~C && (C + 1).isPowerOf2())
  1351. return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
  1352. // (xor X, C) >u C --> X >u C (when C+1 is a power of 2)
  1353. if (*XorC == C && (C + 1).isPowerOf2())
  1354. return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
  1355. }
  1356. if (Pred == ICmpInst::ICMP_ULT) {
  1357. // (xor X, -C) <u C --> X >u ~C (when C is a power of 2)
  1358. if (*XorC == -C && C.isPowerOf2())
  1359. return new ICmpInst(ICmpInst::ICMP_UGT, X,
  1360. ConstantInt::get(X->getType(), ~C));
  1361. // (xor X, C) <u C --> X >u ~C (when -C is a power of 2)
  1362. if (*XorC == C && (-C).isPowerOf2())
  1363. return new ICmpInst(ICmpInst::ICMP_UGT, X,
  1364. ConstantInt::get(X->getType(), ~C));
  1365. }
  1366. return nullptr;
  1367. }
  1368. /// For power-of-2 C:
  1369. /// ((X s>> ShiftC) ^ X) u< C --> (X + C) u< (C << 1)
  1370. /// ((X s>> ShiftC) ^ X) u> (C - 1) --> (X + C) u> ((C << 1) - 1)
  1371. Instruction *InstCombinerImpl::foldICmpXorShiftConst(ICmpInst &Cmp,
  1372. BinaryOperator *Xor,
  1373. const APInt &C) {
  1374. CmpInst::Predicate Pred = Cmp.getPredicate();
  1375. APInt PowerOf2;
  1376. if (Pred == ICmpInst::ICMP_ULT)
  1377. PowerOf2 = C;
  1378. else if (Pred == ICmpInst::ICMP_UGT && !C.isMaxValue())
  1379. PowerOf2 = C + 1;
  1380. else
  1381. return nullptr;
  1382. if (!PowerOf2.isPowerOf2())
  1383. return nullptr;
  1384. Value *X;
  1385. const APInt *ShiftC;
  1386. if (!match(Xor, m_OneUse(m_c_Xor(m_Value(X),
  1387. m_AShr(m_Deferred(X), m_APInt(ShiftC))))))
  1388. return nullptr;
  1389. uint64_t Shift = ShiftC->getLimitedValue();
  1390. Type *XType = X->getType();
  1391. if (Shift == 0 || PowerOf2.isMinSignedValue())
  1392. return nullptr;
  1393. Value *Add = Builder.CreateAdd(X, ConstantInt::get(XType, PowerOf2));
  1394. APInt Bound =
  1395. Pred == ICmpInst::ICMP_ULT ? PowerOf2 << 1 : ((PowerOf2 << 1) - 1);
  1396. return new ICmpInst(Pred, Add, ConstantInt::get(XType, Bound));
  1397. }
  1398. /// Fold icmp (and (sh X, Y), C2), C1.
  1399. Instruction *InstCombinerImpl::foldICmpAndShift(ICmpInst &Cmp,
  1400. BinaryOperator *And,
  1401. const APInt &C1,
  1402. const APInt &C2) {
  1403. BinaryOperator *Shift = dyn_cast<BinaryOperator>(And->getOperand(0));
  1404. if (!Shift || !Shift->isShift())
  1405. return nullptr;
  1406. // If this is: (X >> C3) & C2 != C1 (where any shift and any compare could
  1407. // exist), turn it into (X & (C2 << C3)) != (C1 << C3). This happens a LOT in
  1408. // code produced by the clang front-end, for bitfield access.
  1409. // This seemingly simple opportunity to fold away a shift turns out to be
  1410. // rather complicated. See PR17827 for details.
  1411. unsigned ShiftOpcode = Shift->getOpcode();
  1412. bool IsShl = ShiftOpcode == Instruction::Shl;
  1413. const APInt *C3;
  1414. if (match(Shift->getOperand(1), m_APInt(C3))) {
  1415. APInt NewAndCst, NewCmpCst;
  1416. bool AnyCmpCstBitsShiftedOut;
  1417. if (ShiftOpcode == Instruction::Shl) {
  1418. // For a left shift, we can fold if the comparison is not signed. We can
  1419. // also fold a signed comparison if the mask value and comparison value
  1420. // are not negative. These constraints may not be obvious, but we can
  1421. // prove that they are correct using an SMT solver.
  1422. if (Cmp.isSigned() && (C2.isNegative() || C1.isNegative()))
  1423. return nullptr;
  1424. NewCmpCst = C1.lshr(*C3);
  1425. NewAndCst = C2.lshr(*C3);
  1426. AnyCmpCstBitsShiftedOut = NewCmpCst.shl(*C3) != C1;
  1427. } else if (ShiftOpcode == Instruction::LShr) {
  1428. // For a logical right shift, we can fold if the comparison is not signed.
  1429. // We can also fold a signed comparison if the shifted mask value and the
  1430. // shifted comparison value are not negative. These constraints may not be
  1431. // obvious, but we can prove that they are correct using an SMT solver.
  1432. NewCmpCst = C1.shl(*C3);
  1433. NewAndCst = C2.shl(*C3);
  1434. AnyCmpCstBitsShiftedOut = NewCmpCst.lshr(*C3) != C1;
  1435. if (Cmp.isSigned() && (NewAndCst.isNegative() || NewCmpCst.isNegative()))
  1436. return nullptr;
  1437. } else {
  1438. // For an arithmetic shift, check that both constants don't use (in a
  1439. // signed sense) the top bits being shifted out.
  1440. assert(ShiftOpcode == Instruction::AShr && "Unknown shift opcode");
  1441. NewCmpCst = C1.shl(*C3);
  1442. NewAndCst = C2.shl(*C3);
  1443. AnyCmpCstBitsShiftedOut = NewCmpCst.ashr(*C3) != C1;
  1444. if (NewAndCst.ashr(*C3) != C2)
  1445. return nullptr;
  1446. }
  1447. if (AnyCmpCstBitsShiftedOut) {
  1448. // If we shifted bits out, the fold is not going to work out. As a
  1449. // special case, check to see if this means that the result is always
  1450. // true or false now.
  1451. if (Cmp.getPredicate() == ICmpInst::ICMP_EQ)
  1452. return replaceInstUsesWith(Cmp, ConstantInt::getFalse(Cmp.getType()));
  1453. if (Cmp.getPredicate() == ICmpInst::ICMP_NE)
  1454. return replaceInstUsesWith(Cmp, ConstantInt::getTrue(Cmp.getType()));
  1455. } else {
  1456. Value *NewAnd = Builder.CreateAnd(
  1457. Shift->getOperand(0), ConstantInt::get(And->getType(), NewAndCst));
  1458. return new ICmpInst(Cmp.getPredicate(),
  1459. NewAnd, ConstantInt::get(And->getType(), NewCmpCst));
  1460. }
  1461. }
  1462. // Turn ((X >> Y) & C2) == 0 into (X & (C2 << Y)) == 0. The latter is
  1463. // preferable because it allows the C2 << Y expression to be hoisted out of a
  1464. // loop if Y is invariant and X is not.
  1465. if (Shift->hasOneUse() && C1.isZero() && Cmp.isEquality() &&
  1466. !Shift->isArithmeticShift() && !isa<Constant>(Shift->getOperand(0))) {
  1467. // Compute C2 << Y.
  1468. Value *NewShift =
  1469. IsShl ? Builder.CreateLShr(And->getOperand(1), Shift->getOperand(1))
  1470. : Builder.CreateShl(And->getOperand(1), Shift->getOperand(1));
  1471. // Compute X & (C2 << Y).
  1472. Value *NewAnd = Builder.CreateAnd(Shift->getOperand(0), NewShift);
  1473. return replaceOperand(Cmp, 0, NewAnd);
  1474. }
  1475. return nullptr;
  1476. }
  1477. /// Fold icmp (and X, C2), C1.
  1478. Instruction *InstCombinerImpl::foldICmpAndConstConst(ICmpInst &Cmp,
  1479. BinaryOperator *And,
  1480. const APInt &C1) {
  1481. bool isICMP_NE = Cmp.getPredicate() == ICmpInst::ICMP_NE;
  1482. // For vectors: icmp ne (and X, 1), 0 --> trunc X to N x i1
  1483. // TODO: We canonicalize to the longer form for scalars because we have
  1484. // better analysis/folds for icmp, and codegen may be better with icmp.
  1485. if (isICMP_NE && Cmp.getType()->isVectorTy() && C1.isZero() &&
  1486. match(And->getOperand(1), m_One()))
  1487. return new TruncInst(And->getOperand(0), Cmp.getType());
  1488. const APInt *C2;
  1489. Value *X;
  1490. if (!match(And, m_And(m_Value(X), m_APInt(C2))))
  1491. return nullptr;
  1492. // Don't perform the following transforms if the AND has multiple uses
  1493. if (!And->hasOneUse())
  1494. return nullptr;
  1495. if (Cmp.isEquality() && C1.isZero()) {
  1496. // Restrict this fold to single-use 'and' (PR10267).
  1497. // Replace (and X, (1 << size(X)-1) != 0) with X s< 0
  1498. if (C2->isSignMask()) {
  1499. Constant *Zero = Constant::getNullValue(X->getType());
  1500. auto NewPred = isICMP_NE ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGE;
  1501. return new ICmpInst(NewPred, X, Zero);
  1502. }
  1503. APInt NewC2 = *C2;
  1504. KnownBits Know = computeKnownBits(And->getOperand(0), 0, And);
  1505. // Set high zeros of C2 to allow matching negated power-of-2.
  1506. NewC2 = *C2 | APInt::getHighBitsSet(C2->getBitWidth(),
  1507. Know.countMinLeadingZeros());
  1508. // Restrict this fold only for single-use 'and' (PR10267).
  1509. // ((%x & C) == 0) --> %x u< (-C) iff (-C) is power of two.
  1510. if (NewC2.isNegatedPowerOf2()) {
  1511. Constant *NegBOC = ConstantInt::get(And->getType(), -NewC2);
  1512. auto NewPred = isICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
  1513. return new ICmpInst(NewPred, X, NegBOC);
  1514. }
  1515. }
  1516. // If the LHS is an 'and' of a truncate and we can widen the and/compare to
  1517. // the input width without changing the value produced, eliminate the cast:
  1518. //
  1519. // icmp (and (trunc W), C2), C1 -> icmp (and W, C2'), C1'
  1520. //
  1521. // We can do this transformation if the constants do not have their sign bits
  1522. // set or if it is an equality comparison. Extending a relational comparison
  1523. // when we're checking the sign bit would not work.
  1524. Value *W;
  1525. if (match(And->getOperand(0), m_OneUse(m_Trunc(m_Value(W)))) &&
  1526. (Cmp.isEquality() || (!C1.isNegative() && !C2->isNegative()))) {
  1527. // TODO: Is this a good transform for vectors? Wider types may reduce
  1528. // throughput. Should this transform be limited (even for scalars) by using
  1529. // shouldChangeType()?
  1530. if (!Cmp.getType()->isVectorTy()) {
  1531. Type *WideType = W->getType();
  1532. unsigned WideScalarBits = WideType->getScalarSizeInBits();
  1533. Constant *ZextC1 = ConstantInt::get(WideType, C1.zext(WideScalarBits));
  1534. Constant *ZextC2 = ConstantInt::get(WideType, C2->zext(WideScalarBits));
  1535. Value *NewAnd = Builder.CreateAnd(W, ZextC2, And->getName());
  1536. return new ICmpInst(Cmp.getPredicate(), NewAnd, ZextC1);
  1537. }
  1538. }
  1539. if (Instruction *I = foldICmpAndShift(Cmp, And, C1, *C2))
  1540. return I;
  1541. // (icmp pred (and (or (lshr A, B), A), 1), 0) -->
  1542. // (icmp pred (and A, (or (shl 1, B), 1), 0))
  1543. //
  1544. // iff pred isn't signed
  1545. if (!Cmp.isSigned() && C1.isZero() && And->getOperand(0)->hasOneUse() &&
  1546. match(And->getOperand(1), m_One())) {
  1547. Constant *One = cast<Constant>(And->getOperand(1));
  1548. Value *Or = And->getOperand(0);
  1549. Value *A, *B, *LShr;
  1550. if (match(Or, m_Or(m_Value(LShr), m_Value(A))) &&
  1551. match(LShr, m_LShr(m_Specific(A), m_Value(B)))) {
  1552. unsigned UsesRemoved = 0;
  1553. if (And->hasOneUse())
  1554. ++UsesRemoved;
  1555. if (Or->hasOneUse())
  1556. ++UsesRemoved;
  1557. if (LShr->hasOneUse())
  1558. ++UsesRemoved;
  1559. // Compute A & ((1 << B) | 1)
  1560. Value *NewOr = nullptr;
  1561. if (auto *C = dyn_cast<Constant>(B)) {
  1562. if (UsesRemoved >= 1)
  1563. NewOr = ConstantExpr::getOr(ConstantExpr::getNUWShl(One, C), One);
  1564. } else {
  1565. if (UsesRemoved >= 3)
  1566. NewOr = Builder.CreateOr(Builder.CreateShl(One, B, LShr->getName(),
  1567. /*HasNUW=*/true),
  1568. One, Or->getName());
  1569. }
  1570. if (NewOr) {
  1571. Value *NewAnd = Builder.CreateAnd(A, NewOr, And->getName());
  1572. return replaceOperand(Cmp, 0, NewAnd);
  1573. }
  1574. }
  1575. }
  1576. return nullptr;
  1577. }
  1578. /// Fold icmp (and X, Y), C.
  1579. Instruction *InstCombinerImpl::foldICmpAndConstant(ICmpInst &Cmp,
  1580. BinaryOperator *And,
  1581. const APInt &C) {
  1582. if (Instruction *I = foldICmpAndConstConst(Cmp, And, C))
  1583. return I;
  1584. const ICmpInst::Predicate Pred = Cmp.getPredicate();
  1585. bool TrueIfNeg;
  1586. if (isSignBitCheck(Pred, C, TrueIfNeg)) {
  1587. // ((X - 1) & ~X) < 0 --> X == 0
  1588. // ((X - 1) & ~X) >= 0 --> X != 0
  1589. Value *X;
  1590. if (match(And->getOperand(0), m_Add(m_Value(X), m_AllOnes())) &&
  1591. match(And->getOperand(1), m_Not(m_Specific(X)))) {
  1592. auto NewPred = TrueIfNeg ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE;
  1593. return new ICmpInst(NewPred, X, ConstantInt::getNullValue(X->getType()));
  1594. }
  1595. }
  1596. // TODO: These all require that Y is constant too, so refactor with the above.
  1597. // Try to optimize things like "A[i] & 42 == 0" to index computations.
  1598. Value *X = And->getOperand(0);
  1599. Value *Y = And->getOperand(1);
  1600. if (auto *C2 = dyn_cast<ConstantInt>(Y))
  1601. if (auto *LI = dyn_cast<LoadInst>(X))
  1602. if (auto *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0)))
  1603. if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
  1604. if (Instruction *Res =
  1605. foldCmpLoadFromIndexedGlobal(LI, GEP, GV, Cmp, C2))
  1606. return Res;
  1607. if (!Cmp.isEquality())
  1608. return nullptr;
  1609. // X & -C == -C -> X > u ~C
  1610. // X & -C != -C -> X <= u ~C
  1611. // iff C is a power of 2
  1612. if (Cmp.getOperand(1) == Y && C.isNegatedPowerOf2()) {
  1613. auto NewPred =
  1614. Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGT : CmpInst::ICMP_ULE;
  1615. return new ICmpInst(NewPred, X, SubOne(cast<Constant>(Cmp.getOperand(1))));
  1616. }
  1617. // ((zext i1 X) & Y) == 0 --> !((trunc Y) & X)
  1618. // ((zext i1 X) & Y) != 0 --> ((trunc Y) & X)
  1619. // ((zext i1 X) & Y) == 1 --> ((trunc Y) & X)
  1620. // ((zext i1 X) & Y) != 1 --> !((trunc Y) & X)
  1621. if (match(And, m_OneUse(m_c_And(m_OneUse(m_ZExt(m_Value(X))), m_Value(Y)))) &&
  1622. X->getType()->isIntOrIntVectorTy(1) && (C.isZero() || C.isOne())) {
  1623. Value *TruncY = Builder.CreateTrunc(Y, X->getType());
  1624. if (C.isZero() ^ (Pred == CmpInst::ICMP_NE)) {
  1625. Value *And = Builder.CreateAnd(TruncY, X);
  1626. return BinaryOperator::CreateNot(And);
  1627. }
  1628. return BinaryOperator::CreateAnd(TruncY, X);
  1629. }
  1630. return nullptr;
  1631. }
  1632. /// Fold icmp (or X, Y), C.
  1633. Instruction *InstCombinerImpl::foldICmpOrConstant(ICmpInst &Cmp,
  1634. BinaryOperator *Or,
  1635. const APInt &C) {
  1636. ICmpInst::Predicate Pred = Cmp.getPredicate();
  1637. if (C.isOne()) {
  1638. // icmp slt signum(V) 1 --> icmp slt V, 1
  1639. Value *V = nullptr;
  1640. if (Pred == ICmpInst::ICMP_SLT && match(Or, m_Signum(m_Value(V))))
  1641. return new ICmpInst(ICmpInst::ICMP_SLT, V,
  1642. ConstantInt::get(V->getType(), 1));
  1643. }
  1644. Value *OrOp0 = Or->getOperand(0), *OrOp1 = Or->getOperand(1);
  1645. const APInt *MaskC;
  1646. if (match(OrOp1, m_APInt(MaskC)) && Cmp.isEquality()) {
  1647. if (*MaskC == C && (C + 1).isPowerOf2()) {
  1648. // X | C == C --> X <=u C
  1649. // X | C != C --> X >u C
  1650. // iff C+1 is a power of 2 (C is a bitmask of the low bits)
  1651. Pred = (Pred == CmpInst::ICMP_EQ) ? CmpInst::ICMP_ULE : CmpInst::ICMP_UGT;
  1652. return new ICmpInst(Pred, OrOp0, OrOp1);
  1653. }
  1654. // More general: canonicalize 'equality with set bits mask' to
  1655. // 'equality with clear bits mask'.
  1656. // (X | MaskC) == C --> (X & ~MaskC) == C ^ MaskC
  1657. // (X | MaskC) != C --> (X & ~MaskC) != C ^ MaskC
  1658. if (Or->hasOneUse()) {
  1659. Value *And = Builder.CreateAnd(OrOp0, ~(*MaskC));
  1660. Constant *NewC = ConstantInt::get(Or->getType(), C ^ (*MaskC));
  1661. return new ICmpInst(Pred, And, NewC);
  1662. }
  1663. }
  1664. // (X | (X-1)) s< 0 --> X s< 1
  1665. // (X | (X-1)) s> -1 --> X s> 0
  1666. Value *X;
  1667. bool TrueIfSigned;
  1668. if (isSignBitCheck(Pred, C, TrueIfSigned) &&
  1669. match(Or, m_c_Or(m_Add(m_Value(X), m_AllOnes()), m_Deferred(X)))) {
  1670. auto NewPred = TrueIfSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_SGT;
  1671. Constant *NewC = ConstantInt::get(X->getType(), TrueIfSigned ? 1 : 0);
  1672. return new ICmpInst(NewPred, X, NewC);
  1673. }
  1674. if (!Cmp.isEquality() || !C.isZero() || !Or->hasOneUse())
  1675. return nullptr;
  1676. Value *P, *Q;
  1677. if (match(Or, m_Or(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Value(Q))))) {
  1678. // Simplify icmp eq (or (ptrtoint P), (ptrtoint Q)), 0
  1679. // -> and (icmp eq P, null), (icmp eq Q, null).
  1680. Value *CmpP =
  1681. Builder.CreateICmp(Pred, P, ConstantInt::getNullValue(P->getType()));
  1682. Value *CmpQ =
  1683. Builder.CreateICmp(Pred, Q, ConstantInt::getNullValue(Q->getType()));
  1684. auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
  1685. return BinaryOperator::Create(BOpc, CmpP, CmpQ);
  1686. }
  1687. // Are we using xors to bitwise check for a pair of (in)equalities? Convert to
  1688. // a shorter form that has more potential to be folded even further.
  1689. Value *X1, *X2, *X3, *X4;
  1690. if (match(OrOp0, m_OneUse(m_Xor(m_Value(X1), m_Value(X2)))) &&
  1691. match(OrOp1, m_OneUse(m_Xor(m_Value(X3), m_Value(X4))))) {
  1692. // ((X1 ^ X2) || (X3 ^ X4)) == 0 --> (X1 == X2) && (X3 == X4)
  1693. // ((X1 ^ X2) || (X3 ^ X4)) != 0 --> (X1 != X2) || (X3 != X4)
  1694. Value *Cmp12 = Builder.CreateICmp(Pred, X1, X2);
  1695. Value *Cmp34 = Builder.CreateICmp(Pred, X3, X4);
  1696. auto BOpc = Pred == CmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
  1697. return BinaryOperator::Create(BOpc, Cmp12, Cmp34);
  1698. }
  1699. return nullptr;
  1700. }
  1701. /// Fold icmp (mul X, Y), C.
  1702. Instruction *InstCombinerImpl::foldICmpMulConstant(ICmpInst &Cmp,
  1703. BinaryOperator *Mul,
  1704. const APInt &C) {
  1705. ICmpInst::Predicate Pred = Cmp.getPredicate();
  1706. Type *MulTy = Mul->getType();
  1707. Value *X = Mul->getOperand(0);
  1708. // If there's no overflow:
  1709. // X * X == 0 --> X == 0
  1710. // X * X != 0 --> X != 0
  1711. if (Cmp.isEquality() && C.isZero() && X == Mul->getOperand(1) &&
  1712. (Mul->hasNoUnsignedWrap() || Mul->hasNoSignedWrap()))
  1713. return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
  1714. const APInt *MulC;
  1715. if (!match(Mul->getOperand(1), m_APInt(MulC)))
  1716. return nullptr;
  1717. // If this is a test of the sign bit and the multiply is sign-preserving with
  1718. // a constant operand, use the multiply LHS operand instead:
  1719. // (X * +MulC) < 0 --> X < 0
  1720. // (X * -MulC) < 0 --> X > 0
  1721. if (isSignTest(Pred, C) && Mul->hasNoSignedWrap()) {
  1722. if (MulC->isNegative())
  1723. Pred = ICmpInst::getSwappedPredicate(Pred);
  1724. return new ICmpInst(Pred, X, ConstantInt::getNullValue(MulTy));
  1725. }
  1726. if (MulC->isZero() || (!Mul->hasNoSignedWrap() && !Mul->hasNoUnsignedWrap()))
  1727. return nullptr;
  1728. // If the multiply does not wrap, try to divide the compare constant by the
  1729. // multiplication factor.
  1730. if (Cmp.isEquality()) {
  1731. // (mul nsw X, MulC) == C --> X == C /s MulC
  1732. if (Mul->hasNoSignedWrap() && C.srem(*MulC).isZero()) {
  1733. Constant *NewC = ConstantInt::get(MulTy, C.sdiv(*MulC));
  1734. return new ICmpInst(Pred, X, NewC);
  1735. }
  1736. // (mul nuw X, MulC) == C --> X == C /u MulC
  1737. if (Mul->hasNoUnsignedWrap() && C.urem(*MulC).isZero()) {
  1738. Constant *NewC = ConstantInt::get(MulTy, C.udiv(*MulC));
  1739. return new ICmpInst(Pred, X, NewC);
  1740. }
  1741. }
  1742. // With a matching no-overflow guarantee, fold the constants:
  1743. // (X * MulC) < C --> X < (C / MulC)
  1744. // (X * MulC) > C --> X > (C / MulC)
  1745. // TODO: Assert that Pred is not equal to SGE, SLE, UGE, ULE?
  1746. Constant *NewC = nullptr;
  1747. if (Mul->hasNoSignedWrap()) {
  1748. // MININT / -1 --> overflow.
  1749. if (C.isMinSignedValue() && MulC->isAllOnes())
  1750. return nullptr;
  1751. if (MulC->isNegative())
  1752. Pred = ICmpInst::getSwappedPredicate(Pred);
  1753. if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE)
  1754. NewC = ConstantInt::get(
  1755. MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::UP));
  1756. if (Pred == ICmpInst::ICMP_SLE || Pred == ICmpInst::ICMP_SGT)
  1757. NewC = ConstantInt::get(
  1758. MulTy, APIntOps::RoundingSDiv(C, *MulC, APInt::Rounding::DOWN));
  1759. } else {
  1760. assert(Mul->hasNoUnsignedWrap() && "Expected mul nuw");
  1761. if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)
  1762. NewC = ConstantInt::get(
  1763. MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::UP));
  1764. if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)
  1765. NewC = ConstantInt::get(
  1766. MulTy, APIntOps::RoundingUDiv(C, *MulC, APInt::Rounding::DOWN));
  1767. }
  1768. return NewC ? new ICmpInst(Pred, X, NewC) : nullptr;
  1769. }
  1770. /// Fold icmp (shl 1, Y), C.
  1771. static Instruction *foldICmpShlOne(ICmpInst &Cmp, Instruction *Shl,
  1772. const APInt &C) {
  1773. Value *Y;
  1774. if (!match(Shl, m_Shl(m_One(), m_Value(Y))))
  1775. return nullptr;
  1776. Type *ShiftType = Shl->getType();
  1777. unsigned TypeBits = C.getBitWidth();
  1778. bool CIsPowerOf2 = C.isPowerOf2();
  1779. ICmpInst::Predicate Pred = Cmp.getPredicate();
  1780. if (Cmp.isUnsigned()) {
  1781. // (1 << Y) pred C -> Y pred Log2(C)
  1782. if (!CIsPowerOf2) {
  1783. // (1 << Y) < 30 -> Y <= 4
  1784. // (1 << Y) <= 30 -> Y <= 4
  1785. // (1 << Y) >= 30 -> Y > 4
  1786. // (1 << Y) > 30 -> Y > 4
  1787. if (Pred == ICmpInst::ICMP_ULT)
  1788. Pred = ICmpInst::ICMP_ULE;
  1789. else if (Pred == ICmpInst::ICMP_UGE)
  1790. Pred = ICmpInst::ICMP_UGT;
  1791. }
  1792. unsigned CLog2 = C.logBase2();
  1793. return new ICmpInst(Pred, Y, ConstantInt::get(ShiftType, CLog2));
  1794. } else if (Cmp.isSigned()) {
  1795. Constant *BitWidthMinusOne = ConstantInt::get(ShiftType, TypeBits - 1);
  1796. // (1 << Y) > 0 -> Y != 31
  1797. // (1 << Y) > C -> Y != 31 if C is negative.
  1798. if (Pred == ICmpInst::ICMP_SGT && C.sle(0))
  1799. return new ICmpInst(ICmpInst::ICMP_NE, Y, BitWidthMinusOne);
  1800. // (1 << Y) < 0 -> Y == 31
  1801. // (1 << Y) < 1 -> Y == 31
  1802. // (1 << Y) < C -> Y == 31 if C is negative and not signed min.
  1803. // Exclude signed min by subtracting 1 and lower the upper bound to 0.
  1804. if (Pred == ICmpInst::ICMP_SLT && (C-1).sle(0))
  1805. return new ICmpInst(ICmpInst::ICMP_EQ, Y, BitWidthMinusOne);
  1806. }
  1807. return nullptr;
  1808. }
  1809. /// Fold icmp (shl X, Y), C.
  1810. Instruction *InstCombinerImpl::foldICmpShlConstant(ICmpInst &Cmp,
  1811. BinaryOperator *Shl,
  1812. const APInt &C) {
  1813. const APInt *ShiftVal;
  1814. if (Cmp.isEquality() && match(Shl->getOperand(0), m_APInt(ShiftVal)))
  1815. return foldICmpShlConstConst(Cmp, Shl->getOperand(1), C, *ShiftVal);
  1816. const APInt *ShiftAmt;
  1817. if (!match(Shl->getOperand(1), m_APInt(ShiftAmt)))
  1818. return foldICmpShlOne(Cmp, Shl, C);
  1819. // Check that the shift amount is in range. If not, don't perform undefined
  1820. // shifts. When the shift is visited, it will be simplified.
  1821. unsigned TypeBits = C.getBitWidth();
  1822. if (ShiftAmt->uge(TypeBits))
  1823. return nullptr;
  1824. ICmpInst::Predicate Pred = Cmp.getPredicate();
  1825. Value *X = Shl->getOperand(0);
  1826. Type *ShType = Shl->getType();
  1827. // NSW guarantees that we are only shifting out sign bits from the high bits,
  1828. // so we can ASHR the compare constant without needing a mask and eliminate
  1829. // the shift.
  1830. if (Shl->hasNoSignedWrap()) {
  1831. if (Pred == ICmpInst::ICMP_SGT) {
  1832. // icmp Pred (shl nsw X, ShiftAmt), C --> icmp Pred X, (C >>s ShiftAmt)
  1833. APInt ShiftedC = C.ashr(*ShiftAmt);
  1834. return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
  1835. }
  1836. if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
  1837. C.ashr(*ShiftAmt).shl(*ShiftAmt) == C) {
  1838. APInt ShiftedC = C.ashr(*ShiftAmt);
  1839. return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
  1840. }
  1841. if (Pred == ICmpInst::ICMP_SLT) {
  1842. // SLE is the same as above, but SLE is canonicalized to SLT, so convert:
  1843. // (X << S) <=s C is equiv to X <=s (C >> S) for all C
  1844. // (X << S) <s (C + 1) is equiv to X <s (C >> S) + 1 if C <s SMAX
  1845. // (X << S) <s C is equiv to X <s ((C - 1) >> S) + 1 if C >s SMIN
  1846. assert(!C.isMinSignedValue() && "Unexpected icmp slt");
  1847. APInt ShiftedC = (C - 1).ashr(*ShiftAmt) + 1;
  1848. return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
  1849. }
  1850. // If this is a signed comparison to 0 and the shift is sign preserving,
  1851. // use the shift LHS operand instead; isSignTest may change 'Pred', so only
  1852. // do that if we're sure to not continue on in this function.
  1853. if (isSignTest(Pred, C))
  1854. return new ICmpInst(Pred, X, Constant::getNullValue(ShType));
  1855. }
  1856. // NUW guarantees that we are only shifting out zero bits from the high bits,
  1857. // so we can LSHR the compare constant without needing a mask and eliminate
  1858. // the shift.
  1859. if (Shl->hasNoUnsignedWrap()) {
  1860. if (Pred == ICmpInst::ICMP_UGT) {
  1861. // icmp Pred (shl nuw X, ShiftAmt), C --> icmp Pred X, (C >>u ShiftAmt)
  1862. APInt ShiftedC = C.lshr(*ShiftAmt);
  1863. return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
  1864. }
  1865. if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
  1866. C.lshr(*ShiftAmt).shl(*ShiftAmt) == C) {
  1867. APInt ShiftedC = C.lshr(*ShiftAmt);
  1868. return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
  1869. }
  1870. if (Pred == ICmpInst::ICMP_ULT) {
  1871. // ULE is the same as above, but ULE is canonicalized to ULT, so convert:
  1872. // (X << S) <=u C is equiv to X <=u (C >> S) for all C
  1873. // (X << S) <u (C + 1) is equiv to X <u (C >> S) + 1 if C <u ~0u
  1874. // (X << S) <u C is equiv to X <u ((C - 1) >> S) + 1 if C >u 0
  1875. assert(C.ugt(0) && "ult 0 should have been eliminated");
  1876. APInt ShiftedC = (C - 1).lshr(*ShiftAmt) + 1;
  1877. return new ICmpInst(Pred, X, ConstantInt::get(ShType, ShiftedC));
  1878. }
  1879. }
  1880. if (Cmp.isEquality() && Shl->hasOneUse()) {
  1881. // Strength-reduce the shift into an 'and'.
  1882. Constant *Mask = ConstantInt::get(
  1883. ShType,
  1884. APInt::getLowBitsSet(TypeBits, TypeBits - ShiftAmt->getZExtValue()));
  1885. Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
  1886. Constant *LShrC = ConstantInt::get(ShType, C.lshr(*ShiftAmt));
  1887. return new ICmpInst(Pred, And, LShrC);
  1888. }
  1889. // Otherwise, if this is a comparison of the sign bit, simplify to and/test.
  1890. bool TrueIfSigned = false;
  1891. if (Shl->hasOneUse() && isSignBitCheck(Pred, C, TrueIfSigned)) {
  1892. // (X << 31) <s 0 --> (X & 1) != 0
  1893. Constant *Mask = ConstantInt::get(
  1894. ShType,
  1895. APInt::getOneBitSet(TypeBits, TypeBits - ShiftAmt->getZExtValue() - 1));
  1896. Value *And = Builder.CreateAnd(X, Mask, Shl->getName() + ".mask");
  1897. return new ICmpInst(TrueIfSigned ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ,
  1898. And, Constant::getNullValue(ShType));
  1899. }
  1900. // Simplify 'shl' inequality test into 'and' equality test.
  1901. if (Cmp.isUnsigned() && Shl->hasOneUse()) {
  1902. // (X l<< C2) u<=/u> C1 iff C1+1 is power of two -> X & (~C1 l>> C2) ==/!= 0
  1903. if ((C + 1).isPowerOf2() &&
  1904. (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT)) {
  1905. Value *And = Builder.CreateAnd(X, (~C).lshr(ShiftAmt->getZExtValue()));
  1906. return new ICmpInst(Pred == ICmpInst::ICMP_ULE ? ICmpInst::ICMP_EQ
  1907. : ICmpInst::ICMP_NE,
  1908. And, Constant::getNullValue(ShType));
  1909. }
  1910. // (X l<< C2) u</u>= C1 iff C1 is power of two -> X & (-C1 l>> C2) ==/!= 0
  1911. if (C.isPowerOf2() &&
  1912. (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
  1913. Value *And =
  1914. Builder.CreateAnd(X, (~(C - 1)).lshr(ShiftAmt->getZExtValue()));
  1915. return new ICmpInst(Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_EQ
  1916. : ICmpInst::ICMP_NE,
  1917. And, Constant::getNullValue(ShType));
  1918. }
  1919. }
  1920. // Transform (icmp pred iM (shl iM %v, N), C)
  1921. // -> (icmp pred i(M-N) (trunc %v iM to i(M-N)), (trunc (C>>N))
  1922. // Transform the shl to a trunc if (trunc (C>>N)) has no loss and M-N.
  1923. // This enables us to get rid of the shift in favor of a trunc that may be
  1924. // free on the target. It has the additional benefit of comparing to a
  1925. // smaller constant that may be more target-friendly.
  1926. unsigned Amt = ShiftAmt->getLimitedValue(TypeBits - 1);
  1927. if (Shl->hasOneUse() && Amt != 0 && C.countTrailingZeros() >= Amt &&
  1928. DL.isLegalInteger(TypeBits - Amt)) {
  1929. Type *TruncTy = IntegerType::get(Cmp.getContext(), TypeBits - Amt);
  1930. if (auto *ShVTy = dyn_cast<VectorType>(ShType))
  1931. TruncTy = VectorType::get(TruncTy, ShVTy->getElementCount());
  1932. Constant *NewC =
  1933. ConstantInt::get(TruncTy, C.ashr(*ShiftAmt).trunc(TypeBits - Amt));
  1934. return new ICmpInst(Pred, Builder.CreateTrunc(X, TruncTy), NewC);
  1935. }
  1936. return nullptr;
  1937. }
  1938. /// Fold icmp ({al}shr X, Y), C.
  1939. Instruction *InstCombinerImpl::foldICmpShrConstant(ICmpInst &Cmp,
  1940. BinaryOperator *Shr,
  1941. const APInt &C) {
  1942. // An exact shr only shifts out zero bits, so:
  1943. // icmp eq/ne (shr X, Y), 0 --> icmp eq/ne X, 0
  1944. Value *X = Shr->getOperand(0);
  1945. CmpInst::Predicate Pred = Cmp.getPredicate();
  1946. if (Cmp.isEquality() && Shr->isExact() && C.isZero())
  1947. return new ICmpInst(Pred, X, Cmp.getOperand(1));
  1948. bool IsAShr = Shr->getOpcode() == Instruction::AShr;
  1949. const APInt *ShiftValC;
  1950. if (match(X, m_APInt(ShiftValC))) {
  1951. if (Cmp.isEquality())
  1952. return foldICmpShrConstConst(Cmp, Shr->getOperand(1), C, *ShiftValC);
  1953. // (ShiftValC >> Y) >s -1 --> Y != 0 with ShiftValC < 0
  1954. // (ShiftValC >> Y) <s 0 --> Y == 0 with ShiftValC < 0
  1955. bool TrueIfSigned;
  1956. if (!IsAShr && ShiftValC->isNegative() &&
  1957. isSignBitCheck(Pred, C, TrueIfSigned))
  1958. return new ICmpInst(TrueIfSigned ? CmpInst::ICMP_EQ : CmpInst::ICMP_NE,
  1959. Shr->getOperand(1),
  1960. ConstantInt::getNullValue(X->getType()));
  1961. // If the shifted constant is a power-of-2, test the shift amount directly:
  1962. // (ShiftValC >> Y) >u C --> X <u (LZ(C) - LZ(ShiftValC))
  1963. // (ShiftValC >> Y) <u C --> X >=u (LZ(C-1) - LZ(ShiftValC))
  1964. if (!IsAShr && ShiftValC->isPowerOf2() &&
  1965. (Pred == CmpInst::ICMP_UGT || Pred == CmpInst::ICMP_ULT)) {
  1966. bool IsUGT = Pred == CmpInst::ICMP_UGT;
  1967. assert(ShiftValC->uge(C) && "Expected simplify of compare");
  1968. assert((IsUGT || !C.isZero()) && "Expected X u< 0 to simplify");
  1969. unsigned CmpLZ =
  1970. IsUGT ? C.countLeadingZeros() : (C - 1).countLeadingZeros();
  1971. unsigned ShiftLZ = ShiftValC->countLeadingZeros();
  1972. Constant *NewC = ConstantInt::get(Shr->getType(), CmpLZ - ShiftLZ);
  1973. auto NewPred = IsUGT ? CmpInst::ICMP_ULT : CmpInst::ICMP_UGE;
  1974. return new ICmpInst(NewPred, Shr->getOperand(1), NewC);
  1975. }
  1976. }
  1977. const APInt *ShiftAmtC;
  1978. if (!match(Shr->getOperand(1), m_APInt(ShiftAmtC)))
  1979. return nullptr;
  1980. // Check that the shift amount is in range. If not, don't perform undefined
  1981. // shifts. When the shift is visited it will be simplified.
  1982. unsigned TypeBits = C.getBitWidth();
  1983. unsigned ShAmtVal = ShiftAmtC->getLimitedValue(TypeBits);
  1984. if (ShAmtVal >= TypeBits || ShAmtVal == 0)
  1985. return nullptr;
  1986. bool IsExact = Shr->isExact();
  1987. Type *ShrTy = Shr->getType();
  1988. // TODO: If we could guarantee that InstSimplify would handle all of the
  1989. // constant-value-based preconditions in the folds below, then we could assert
  1990. // those conditions rather than checking them. This is difficult because of
  1991. // undef/poison (PR34838).
  1992. if (IsAShr) {
  1993. if (IsExact || Pred == CmpInst::ICMP_SLT || Pred == CmpInst::ICMP_ULT) {
  1994. // When ShAmtC can be shifted losslessly:
  1995. // icmp PRED (ashr exact X, ShAmtC), C --> icmp PRED X, (C << ShAmtC)
  1996. // icmp slt/ult (ashr X, ShAmtC), C --> icmp slt/ult X, (C << ShAmtC)
  1997. APInt ShiftedC = C.shl(ShAmtVal);
  1998. if (ShiftedC.ashr(ShAmtVal) == C)
  1999. return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
  2000. }
  2001. if (Pred == CmpInst::ICMP_SGT) {
  2002. // icmp sgt (ashr X, ShAmtC), C --> icmp sgt X, ((C + 1) << ShAmtC) - 1
  2003. APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
  2004. if (!C.isMaxSignedValue() && !(C + 1).shl(ShAmtVal).isMinSignedValue() &&
  2005. (ShiftedC + 1).ashr(ShAmtVal) == (C + 1))
  2006. return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
  2007. }
  2008. if (Pred == CmpInst::ICMP_UGT) {
  2009. // icmp ugt (ashr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
  2010. // 'C + 1 << ShAmtC' can overflow as a signed number, so the 2nd
  2011. // clause accounts for that pattern.
  2012. APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
  2013. if ((ShiftedC + 1).ashr(ShAmtVal) == (C + 1) ||
  2014. (C + 1).shl(ShAmtVal).isMinSignedValue())
  2015. return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
  2016. }
  2017. // If the compare constant has significant bits above the lowest sign-bit,
  2018. // then convert an unsigned cmp to a test of the sign-bit:
  2019. // (ashr X, ShiftC) u> C --> X s< 0
  2020. // (ashr X, ShiftC) u< C --> X s> -1
  2021. if (C.getBitWidth() > 2 && C.getNumSignBits() <= ShAmtVal) {
  2022. if (Pred == CmpInst::ICMP_UGT) {
  2023. return new ICmpInst(CmpInst::ICMP_SLT, X,
  2024. ConstantInt::getNullValue(ShrTy));
  2025. }
  2026. if (Pred == CmpInst::ICMP_ULT) {
  2027. return new ICmpInst(CmpInst::ICMP_SGT, X,
  2028. ConstantInt::getAllOnesValue(ShrTy));
  2029. }
  2030. }
  2031. } else {
  2032. if (Pred == CmpInst::ICMP_ULT || (Pred == CmpInst::ICMP_UGT && IsExact)) {
  2033. // icmp ult (lshr X, ShAmtC), C --> icmp ult X, (C << ShAmtC)
  2034. // icmp ugt (lshr exact X, ShAmtC), C --> icmp ugt X, (C << ShAmtC)
  2035. APInt ShiftedC = C.shl(ShAmtVal);
  2036. if (ShiftedC.lshr(ShAmtVal) == C)
  2037. return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
  2038. }
  2039. if (Pred == CmpInst::ICMP_UGT) {
  2040. // icmp ugt (lshr X, ShAmtC), C --> icmp ugt X, ((C + 1) << ShAmtC) - 1
  2041. APInt ShiftedC = (C + 1).shl(ShAmtVal) - 1;
  2042. if ((ShiftedC + 1).lshr(ShAmtVal) == (C + 1))
  2043. return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, ShiftedC));
  2044. }
  2045. }
  2046. if (!Cmp.isEquality())
  2047. return nullptr;
  2048. // Handle equality comparisons of shift-by-constant.
  2049. // If the comparison constant changes with the shift, the comparison cannot
  2050. // succeed (bits of the comparison constant cannot match the shifted value).
  2051. // This should be known by InstSimplify and already be folded to true/false.
  2052. assert(((IsAShr && C.shl(ShAmtVal).ashr(ShAmtVal) == C) ||
  2053. (!IsAShr && C.shl(ShAmtVal).lshr(ShAmtVal) == C)) &&
  2054. "Expected icmp+shr simplify did not occur.");
  2055. // If the bits shifted out are known zero, compare the unshifted value:
  2056. // (X & 4) >> 1 == 2 --> (X & 4) == 4.
  2057. if (Shr->isExact())
  2058. return new ICmpInst(Pred, X, ConstantInt::get(ShrTy, C << ShAmtVal));
  2059. if (C.isZero()) {
  2060. // == 0 is u< 1.
  2061. if (Pred == CmpInst::ICMP_EQ)
  2062. return new ICmpInst(CmpInst::ICMP_ULT, X,
  2063. ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal)));
  2064. else
  2065. return new ICmpInst(CmpInst::ICMP_UGT, X,
  2066. ConstantInt::get(ShrTy, (C + 1).shl(ShAmtVal) - 1));
  2067. }
  2068. if (Shr->hasOneUse()) {
  2069. // Canonicalize the shift into an 'and':
  2070. // icmp eq/ne (shr X, ShAmt), C --> icmp eq/ne (and X, HiMask), (C << ShAmt)
  2071. APInt Val(APInt::getHighBitsSet(TypeBits, TypeBits - ShAmtVal));
  2072. Constant *Mask = ConstantInt::get(ShrTy, Val);
  2073. Value *And = Builder.CreateAnd(X, Mask, Shr->getName() + ".mask");
  2074. return new ICmpInst(Pred, And, ConstantInt::get(ShrTy, C << ShAmtVal));
  2075. }
  2076. return nullptr;
  2077. }
  2078. Instruction *InstCombinerImpl::foldICmpSRemConstant(ICmpInst &Cmp,
  2079. BinaryOperator *SRem,
  2080. const APInt &C) {
  2081. // Match an 'is positive' or 'is negative' comparison of remainder by a
  2082. // constant power-of-2 value:
  2083. // (X % pow2C) sgt/slt 0
  2084. const ICmpInst::Predicate Pred = Cmp.getPredicate();
  2085. if (Pred != ICmpInst::ICMP_SGT && Pred != ICmpInst::ICMP_SLT &&
  2086. Pred != ICmpInst::ICMP_EQ && Pred != ICmpInst::ICMP_NE)
  2087. return nullptr;
  2088. // TODO: The one-use check is standard because we do not typically want to
  2089. // create longer instruction sequences, but this might be a special-case
  2090. // because srem is not good for analysis or codegen.
  2091. if (!SRem->hasOneUse())
  2092. return nullptr;
  2093. const APInt *DivisorC;
  2094. if (!match(SRem->getOperand(1), m_Power2(DivisorC)))
  2095. return nullptr;
  2096. // For cmp_sgt/cmp_slt only zero valued C is handled.
  2097. // For cmp_eq/cmp_ne only positive valued C is handled.
  2098. if (((Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT) &&
  2099. !C.isZero()) ||
  2100. ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE) &&
  2101. !C.isStrictlyPositive()))
  2102. return nullptr;
  2103. // Mask off the sign bit and the modulo bits (low-bits).
  2104. Type *Ty = SRem->getType();
  2105. APInt SignMask = APInt::getSignMask(Ty->getScalarSizeInBits());
  2106. Constant *MaskC = ConstantInt::get(Ty, SignMask | (*DivisorC - 1));
  2107. Value *And = Builder.CreateAnd(SRem->getOperand(0), MaskC);
  2108. if (Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_NE)
  2109. return new ICmpInst(Pred, And, ConstantInt::get(Ty, C));
  2110. // For 'is positive?' check that the sign-bit is clear and at least 1 masked
  2111. // bit is set. Example:
  2112. // (i8 X % 32) s> 0 --> (X & 159) s> 0
  2113. if (Pred == ICmpInst::ICMP_SGT)
  2114. return new ICmpInst(ICmpInst::ICMP_SGT, And, ConstantInt::getNullValue(Ty));
  2115. // For 'is negative?' check that the sign-bit is set and at least 1 masked
  2116. // bit is set. Example:
  2117. // (i16 X % 4) s< 0 --> (X & 32771) u> 32768
  2118. return new ICmpInst(ICmpInst::ICMP_UGT, And, ConstantInt::get(Ty, SignMask));
  2119. }
  2120. /// Fold icmp (udiv X, Y), C.
  2121. Instruction *InstCombinerImpl::foldICmpUDivConstant(ICmpInst &Cmp,
  2122. BinaryOperator *UDiv,
  2123. const APInt &C) {
  2124. ICmpInst::Predicate Pred = Cmp.getPredicate();
  2125. Value *X = UDiv->getOperand(0);
  2126. Value *Y = UDiv->getOperand(1);
  2127. Type *Ty = UDiv->getType();
  2128. const APInt *C2;
  2129. if (!match(X, m_APInt(C2)))
  2130. return nullptr;
  2131. assert(*C2 != 0 && "udiv 0, X should have been simplified already.");
  2132. // (icmp ugt (udiv C2, Y), C) -> (icmp ule Y, C2/(C+1))
  2133. if (Pred == ICmpInst::ICMP_UGT) {
  2134. assert(!C.isMaxValue() &&
  2135. "icmp ugt X, UINT_MAX should have been simplified already.");
  2136. return new ICmpInst(ICmpInst::ICMP_ULE, Y,
  2137. ConstantInt::get(Ty, C2->udiv(C + 1)));
  2138. }
  2139. // (icmp ult (udiv C2, Y), C) -> (icmp ugt Y, C2/C)
  2140. if (Pred == ICmpInst::ICMP_ULT) {
  2141. assert(C != 0 && "icmp ult X, 0 should have been simplified already.");
  2142. return new ICmpInst(ICmpInst::ICMP_UGT, Y,
  2143. ConstantInt::get(Ty, C2->udiv(C)));
  2144. }
  2145. return nullptr;
  2146. }
  2147. /// Fold icmp ({su}div X, Y), C.
  2148. Instruction *InstCombinerImpl::foldICmpDivConstant(ICmpInst &Cmp,
  2149. BinaryOperator *Div,
  2150. const APInt &C) {
  2151. ICmpInst::Predicate Pred = Cmp.getPredicate();
  2152. Value *X = Div->getOperand(0);
  2153. Value *Y = Div->getOperand(1);
  2154. Type *Ty = Div->getType();
  2155. bool DivIsSigned = Div->getOpcode() == Instruction::SDiv;
  2156. // If unsigned division and the compare constant is bigger than
  2157. // UMAX/2 (negative), there's only one pair of values that satisfies an
  2158. // equality check, so eliminate the division:
  2159. // (X u/ Y) == C --> (X == C) && (Y == 1)
  2160. // (X u/ Y) != C --> (X != C) || (Y != 1)
  2161. // Similarly, if signed division and the compare constant is exactly SMIN:
  2162. // (X s/ Y) == SMIN --> (X == SMIN) && (Y == 1)
  2163. // (X s/ Y) != SMIN --> (X != SMIN) || (Y != 1)
  2164. if (Cmp.isEquality() && Div->hasOneUse() && C.isSignBitSet() &&
  2165. (!DivIsSigned || C.isMinSignedValue())) {
  2166. Value *XBig = Builder.CreateICmp(Pred, X, ConstantInt::get(Ty, C));
  2167. Value *YOne = Builder.CreateICmp(Pred, Y, ConstantInt::get(Ty, 1));
  2168. auto Logic = Pred == ICmpInst::ICMP_EQ ? Instruction::And : Instruction::Or;
  2169. return BinaryOperator::Create(Logic, XBig, YOne);
  2170. }
  2171. // Fold: icmp pred ([us]div X, C2), C -> range test
  2172. // Fold this div into the comparison, producing a range check.
  2173. // Determine, based on the divide type, what the range is being
  2174. // checked. If there is an overflow on the low or high side, remember
  2175. // it, otherwise compute the range [low, hi) bounding the new value.
  2176. // See: InsertRangeTest above for the kinds of replacements possible.
  2177. const APInt *C2;
  2178. if (!match(Y, m_APInt(C2)))
  2179. return nullptr;
  2180. // FIXME: If the operand types don't match the type of the divide
  2181. // then don't attempt this transform. The code below doesn't have the
  2182. // logic to deal with a signed divide and an unsigned compare (and
  2183. // vice versa). This is because (x /s C2) <s C produces different
  2184. // results than (x /s C2) <u C or (x /u C2) <s C or even
  2185. // (x /u C2) <u C. Simply casting the operands and result won't
  2186. // work. :( The if statement below tests that condition and bails
  2187. // if it finds it.
  2188. if (!Cmp.isEquality() && DivIsSigned != Cmp.isSigned())
  2189. return nullptr;
  2190. // The ProdOV computation fails on divide by 0 and divide by -1. Cases with
  2191. // INT_MIN will also fail if the divisor is 1. Although folds of all these
  2192. // division-by-constant cases should be present, we can not assert that they
  2193. // have happened before we reach this icmp instruction.
  2194. if (C2->isZero() || C2->isOne() || (DivIsSigned && C2->isAllOnes()))
  2195. return nullptr;
  2196. // Compute Prod = C * C2. We are essentially solving an equation of
  2197. // form X / C2 = C. We solve for X by multiplying C2 and C.
  2198. // By solving for X, we can turn this into a range check instead of computing
  2199. // a divide.
  2200. APInt Prod = C * *C2;
  2201. // Determine if the product overflows by seeing if the product is not equal to
  2202. // the divide. Make sure we do the same kind of divide as in the LHS
  2203. // instruction that we're folding.
  2204. bool ProdOV = (DivIsSigned ? Prod.sdiv(*C2) : Prod.udiv(*C2)) != C;
  2205. // If the division is known to be exact, then there is no remainder from the
  2206. // divide, so the covered range size is unit, otherwise it is the divisor.
  2207. APInt RangeSize = Div->isExact() ? APInt(C2->getBitWidth(), 1) : *C2;
  2208. // Figure out the interval that is being checked. For example, a comparison
  2209. // like "X /u 5 == 0" is really checking that X is in the interval [0, 5).
  2210. // Compute this interval based on the constants involved and the signedness of
  2211. // the compare/divide. This computes a half-open interval, keeping track of
  2212. // whether either value in the interval overflows. After analysis each
  2213. // overflow variable is set to 0 if it's corresponding bound variable is valid
  2214. // -1 if overflowed off the bottom end, or +1 if overflowed off the top end.
  2215. int LoOverflow = 0, HiOverflow = 0;
  2216. APInt LoBound, HiBound;
  2217. if (!DivIsSigned) { // udiv
  2218. // e.g. X/5 op 3 --> [15, 20)
  2219. LoBound = Prod;
  2220. HiOverflow = LoOverflow = ProdOV;
  2221. if (!HiOverflow) {
  2222. // If this is not an exact divide, then many values in the range collapse
  2223. // to the same result value.
  2224. HiOverflow = addWithOverflow(HiBound, LoBound, RangeSize, false);
  2225. }
  2226. } else if (C2->isStrictlyPositive()) { // Divisor is > 0.
  2227. if (C.isZero()) { // (X / pos) op 0
  2228. // Can't overflow. e.g. X/2 op 0 --> [-1, 2)
  2229. LoBound = -(RangeSize - 1);
  2230. HiBound = RangeSize;
  2231. } else if (C.isStrictlyPositive()) { // (X / pos) op pos
  2232. LoBound = Prod; // e.g. X/5 op 3 --> [15, 20)
  2233. HiOverflow = LoOverflow = ProdOV;
  2234. if (!HiOverflow)
  2235. HiOverflow = addWithOverflow(HiBound, Prod, RangeSize, true);
  2236. } else { // (X / pos) op neg
  2237. // e.g. X/5 op -3 --> [-15-4, -15+1) --> [-19, -14)
  2238. HiBound = Prod + 1;
  2239. LoOverflow = HiOverflow = ProdOV ? -1 : 0;
  2240. if (!LoOverflow) {
  2241. APInt DivNeg = -RangeSize;
  2242. LoOverflow = addWithOverflow(LoBound, HiBound, DivNeg, true) ? -1 : 0;
  2243. }
  2244. }
  2245. } else if (C2->isNegative()) { // Divisor is < 0.
  2246. if (Div->isExact())
  2247. RangeSize.negate();
  2248. if (C.isZero()) { // (X / neg) op 0
  2249. // e.g. X/-5 op 0 --> [-4, 5)
  2250. LoBound = RangeSize + 1;
  2251. HiBound = -RangeSize;
  2252. if (HiBound == *C2) { // -INTMIN = INTMIN
  2253. HiOverflow = 1; // [INTMIN+1, overflow)
  2254. HiBound = APInt(); // e.g. X/INTMIN = 0 --> X > INTMIN
  2255. }
  2256. } else if (C.isStrictlyPositive()) { // (X / neg) op pos
  2257. // e.g. X/-5 op 3 --> [-19, -14)
  2258. HiBound = Prod + 1;
  2259. HiOverflow = LoOverflow = ProdOV ? -1 : 0;
  2260. if (!LoOverflow)
  2261. LoOverflow =
  2262. addWithOverflow(LoBound, HiBound, RangeSize, true) ? -1 : 0;
  2263. } else { // (X / neg) op neg
  2264. LoBound = Prod; // e.g. X/-5 op -3 --> [15, 20)
  2265. LoOverflow = HiOverflow = ProdOV;
  2266. if (!HiOverflow)
  2267. HiOverflow = subWithOverflow(HiBound, Prod, RangeSize, true);
  2268. }
  2269. // Dividing by a negative swaps the condition. LT <-> GT
  2270. Pred = ICmpInst::getSwappedPredicate(Pred);
  2271. }
  2272. switch (Pred) {
  2273. default:
  2274. llvm_unreachable("Unhandled icmp predicate!");
  2275. case ICmpInst::ICMP_EQ:
  2276. if (LoOverflow && HiOverflow)
  2277. return replaceInstUsesWith(Cmp, Builder.getFalse());
  2278. if (HiOverflow)
  2279. return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
  2280. X, ConstantInt::get(Ty, LoBound));
  2281. if (LoOverflow)
  2282. return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
  2283. X, ConstantInt::get(Ty, HiBound));
  2284. return replaceInstUsesWith(
  2285. Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, true));
  2286. case ICmpInst::ICMP_NE:
  2287. if (LoOverflow && HiOverflow)
  2288. return replaceInstUsesWith(Cmp, Builder.getTrue());
  2289. if (HiOverflow)
  2290. return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
  2291. X, ConstantInt::get(Ty, LoBound));
  2292. if (LoOverflow)
  2293. return new ICmpInst(DivIsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
  2294. X, ConstantInt::get(Ty, HiBound));
  2295. return replaceInstUsesWith(
  2296. Cmp, insertRangeTest(X, LoBound, HiBound, DivIsSigned, false));
  2297. case ICmpInst::ICMP_ULT:
  2298. case ICmpInst::ICMP_SLT:
  2299. if (LoOverflow == +1) // Low bound is greater than input range.
  2300. return replaceInstUsesWith(Cmp, Builder.getTrue());
  2301. if (LoOverflow == -1) // Low bound is less than input range.
  2302. return replaceInstUsesWith(Cmp, Builder.getFalse());
  2303. return new ICmpInst(Pred, X, ConstantInt::get(Ty, LoBound));
  2304. case ICmpInst::ICMP_UGT:
  2305. case ICmpInst::ICMP_SGT:
  2306. if (HiOverflow == +1) // High bound greater than input range.
  2307. return replaceInstUsesWith(Cmp, Builder.getFalse());
  2308. if (HiOverflow == -1) // High bound less than input range.
  2309. return replaceInstUsesWith(Cmp, Builder.getTrue());
  2310. if (Pred == ICmpInst::ICMP_UGT)
  2311. return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, HiBound));
  2312. return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, HiBound));
  2313. }
  2314. return nullptr;
  2315. }
  2316. /// Fold icmp (sub X, Y), C.
  2317. Instruction *InstCombinerImpl::foldICmpSubConstant(ICmpInst &Cmp,
  2318. BinaryOperator *Sub,
  2319. const APInt &C) {
  2320. Value *X = Sub->getOperand(0), *Y = Sub->getOperand(1);
  2321. ICmpInst::Predicate Pred = Cmp.getPredicate();
  2322. Type *Ty = Sub->getType();
  2323. // (SubC - Y) == C) --> Y == (SubC - C)
  2324. // (SubC - Y) != C) --> Y != (SubC - C)
  2325. Constant *SubC;
  2326. if (Cmp.isEquality() && match(X, m_ImmConstant(SubC))) {
  2327. return new ICmpInst(Pred, Y,
  2328. ConstantExpr::getSub(SubC, ConstantInt::get(Ty, C)));
  2329. }
  2330. // (icmp P (sub nuw|nsw C2, Y), C) -> (icmp swap(P) Y, C2-C)
  2331. const APInt *C2;
  2332. APInt SubResult;
  2333. ICmpInst::Predicate SwappedPred = Cmp.getSwappedPredicate();
  2334. bool HasNSW = Sub->hasNoSignedWrap();
  2335. bool HasNUW = Sub->hasNoUnsignedWrap();
  2336. if (match(X, m_APInt(C2)) &&
  2337. ((Cmp.isUnsigned() && HasNUW) || (Cmp.isSigned() && HasNSW)) &&
  2338. !subWithOverflow(SubResult, *C2, C, Cmp.isSigned()))
  2339. return new ICmpInst(SwappedPred, Y, ConstantInt::get(Ty, SubResult));
  2340. // X - Y == 0 --> X == Y.
  2341. // X - Y != 0 --> X != Y.
  2342. // TODO: We allow this with multiple uses as long as the other uses are not
  2343. // in phis. The phi use check is guarding against a codegen regression
  2344. // for a loop test. If the backend could undo this (and possibly
  2345. // subsequent transforms), we would not need this hack.
  2346. if (Cmp.isEquality() && C.isZero() &&
  2347. none_of((Sub->users()), [](const User *U) { return isa<PHINode>(U); }))
  2348. return new ICmpInst(Pred, X, Y);
  2349. // The following transforms are only worth it if the only user of the subtract
  2350. // is the icmp.
  2351. // TODO: This is an artificial restriction for all of the transforms below
  2352. // that only need a single replacement icmp. Can these use the phi test
  2353. // like the transform above here?
  2354. if (!Sub->hasOneUse())
  2355. return nullptr;
  2356. if (Sub->hasNoSignedWrap()) {
  2357. // (icmp sgt (sub nsw X, Y), -1) -> (icmp sge X, Y)
  2358. if (Pred == ICmpInst::ICMP_SGT && C.isAllOnes())
  2359. return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
  2360. // (icmp sgt (sub nsw X, Y), 0) -> (icmp sgt X, Y)
  2361. if (Pred == ICmpInst::ICMP_SGT && C.isZero())
  2362. return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
  2363. // (icmp slt (sub nsw X, Y), 0) -> (icmp slt X, Y)
  2364. if (Pred == ICmpInst::ICMP_SLT && C.isZero())
  2365. return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
  2366. // (icmp slt (sub nsw X, Y), 1) -> (icmp sle X, Y)
  2367. if (Pred == ICmpInst::ICMP_SLT && C.isOne())
  2368. return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
  2369. }
  2370. if (!match(X, m_APInt(C2)))
  2371. return nullptr;
  2372. // C2 - Y <u C -> (Y | (C - 1)) == C2
  2373. // iff (C2 & (C - 1)) == C - 1 and C is a power of 2
  2374. if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() &&
  2375. (*C2 & (C - 1)) == (C - 1))
  2376. return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateOr(Y, C - 1), X);
  2377. // C2 - Y >u C -> (Y | C) != C2
  2378. // iff C2 & C == C and C + 1 is a power of 2
  2379. if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == C)
  2380. return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateOr(Y, C), X);
  2381. // We have handled special cases that reduce.
  2382. // Canonicalize any remaining sub to add as:
  2383. // (C2 - Y) > C --> (Y + ~C2) < ~C
  2384. Value *Add = Builder.CreateAdd(Y, ConstantInt::get(Ty, ~(*C2)), "notsub",
  2385. HasNUW, HasNSW);
  2386. return new ICmpInst(SwappedPred, Add, ConstantInt::get(Ty, ~C));
  2387. }
  2388. /// Fold icmp (add X, Y), C.
  2389. Instruction *InstCombinerImpl::foldICmpAddConstant(ICmpInst &Cmp,
  2390. BinaryOperator *Add,
  2391. const APInt &C) {
  2392. Value *Y = Add->getOperand(1);
  2393. const APInt *C2;
  2394. if (Cmp.isEquality() || !match(Y, m_APInt(C2)))
  2395. return nullptr;
  2396. // Fold icmp pred (add X, C2), C.
  2397. Value *X = Add->getOperand(0);
  2398. Type *Ty = Add->getType();
  2399. const CmpInst::Predicate Pred = Cmp.getPredicate();
  2400. // If the add does not wrap, we can always adjust the compare by subtracting
  2401. // the constants. Equality comparisons are handled elsewhere. SGE/SLE/UGE/ULE
  2402. // are canonicalized to SGT/SLT/UGT/ULT.
  2403. if ((Add->hasNoSignedWrap() &&
  2404. (Pred == ICmpInst::ICMP_SGT || Pred == ICmpInst::ICMP_SLT)) ||
  2405. (Add->hasNoUnsignedWrap() &&
  2406. (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULT))) {
  2407. bool Overflow;
  2408. APInt NewC =
  2409. Cmp.isSigned() ? C.ssub_ov(*C2, Overflow) : C.usub_ov(*C2, Overflow);
  2410. // If there is overflow, the result must be true or false.
  2411. // TODO: Can we assert there is no overflow because InstSimplify always
  2412. // handles those cases?
  2413. if (!Overflow)
  2414. // icmp Pred (add nsw X, C2), C --> icmp Pred X, (C - C2)
  2415. return new ICmpInst(Pred, X, ConstantInt::get(Ty, NewC));
  2416. }
  2417. auto CR = ConstantRange::makeExactICmpRegion(Pred, C).subtract(*C2);
  2418. const APInt &Upper = CR.getUpper();
  2419. const APInt &Lower = CR.getLower();
  2420. if (Cmp.isSigned()) {
  2421. if (Lower.isSignMask())
  2422. return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, Upper));
  2423. if (Upper.isSignMask())
  2424. return new ICmpInst(ICmpInst::ICMP_SGE, X, ConstantInt::get(Ty, Lower));
  2425. } else {
  2426. if (Lower.isMinValue())
  2427. return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, Upper));
  2428. if (Upper.isMinValue())
  2429. return new ICmpInst(ICmpInst::ICMP_UGE, X, ConstantInt::get(Ty, Lower));
  2430. }
  2431. // This set of folds is intentionally placed after folds that use no-wrapping
  2432. // flags because those folds are likely better for later analysis/codegen.
  2433. const APInt SMax = APInt::getSignedMaxValue(Ty->getScalarSizeInBits());
  2434. const APInt SMin = APInt::getSignedMinValue(Ty->getScalarSizeInBits());
  2435. // Fold compare with offset to opposite sign compare if it eliminates offset:
  2436. // (X + C2) >u C --> X <s -C2 (if C == C2 + SMAX)
  2437. if (Pred == CmpInst::ICMP_UGT && C == *C2 + SMax)
  2438. return new ICmpInst(ICmpInst::ICMP_SLT, X, ConstantInt::get(Ty, -(*C2)));
  2439. // (X + C2) <u C --> X >s ~C2 (if C == C2 + SMIN)
  2440. if (Pred == CmpInst::ICMP_ULT && C == *C2 + SMin)
  2441. return new ICmpInst(ICmpInst::ICMP_SGT, X, ConstantInt::get(Ty, ~(*C2)));
  2442. // (X + C2) >s C --> X <u (SMAX - C) (if C == C2 - 1)
  2443. if (Pred == CmpInst::ICMP_SGT && C == *C2 - 1)
  2444. return new ICmpInst(ICmpInst::ICMP_ULT, X, ConstantInt::get(Ty, SMax - C));
  2445. // (X + C2) <s C --> X >u (C ^ SMAX) (if C == C2)
  2446. if (Pred == CmpInst::ICMP_SLT && C == *C2)
  2447. return new ICmpInst(ICmpInst::ICMP_UGT, X, ConstantInt::get(Ty, C ^ SMax));
  2448. // (X + -1) <u C --> X <=u C (if X is never null)
  2449. if (Pred == CmpInst::ICMP_ULT && C2->isAllOnes()) {
  2450. const SimplifyQuery Q = SQ.getWithInstruction(&Cmp);
  2451. if (llvm::isKnownNonZero(X, DL, 0, Q.AC, Q.CxtI, Q.DT))
  2452. return new ICmpInst(ICmpInst::ICMP_ULE, X, ConstantInt::get(Ty, C));
  2453. }
  2454. if (!Add->hasOneUse())
  2455. return nullptr;
  2456. // X+C <u C2 -> (X & -C2) == C
  2457. // iff C & (C2-1) == 0
  2458. // C2 is a power of 2
  2459. if (Pred == ICmpInst::ICMP_ULT && C.isPowerOf2() && (*C2 & (C - 1)) == 0)
  2460. return new ICmpInst(ICmpInst::ICMP_EQ, Builder.CreateAnd(X, -C),
  2461. ConstantExpr::getNeg(cast<Constant>(Y)));
  2462. // X+C >u C2 -> (X & ~C2) != C
  2463. // iff C & C2 == 0
  2464. // C2+1 is a power of 2
  2465. if (Pred == ICmpInst::ICMP_UGT && (C + 1).isPowerOf2() && (*C2 & C) == 0)
  2466. return new ICmpInst(ICmpInst::ICMP_NE, Builder.CreateAnd(X, ~C),
  2467. ConstantExpr::getNeg(cast<Constant>(Y)));
  2468. // The range test idiom can use either ult or ugt. Arbitrarily canonicalize
  2469. // to the ult form.
  2470. // X+C2 >u C -> X+(C2-C-1) <u ~C
  2471. if (Pred == ICmpInst::ICMP_UGT)
  2472. return new ICmpInst(ICmpInst::ICMP_ULT,
  2473. Builder.CreateAdd(X, ConstantInt::get(Ty, *C2 - C - 1)),
  2474. ConstantInt::get(Ty, ~C));
  2475. return nullptr;
  2476. }
  2477. bool InstCombinerImpl::matchThreeWayIntCompare(SelectInst *SI, Value *&LHS,
  2478. Value *&RHS, ConstantInt *&Less,
  2479. ConstantInt *&Equal,
  2480. ConstantInt *&Greater) {
  2481. // TODO: Generalize this to work with other comparison idioms or ensure
  2482. // they get canonicalized into this form.
  2483. // select i1 (a == b),
  2484. // i32 Equal,
  2485. // i32 (select i1 (a < b), i32 Less, i32 Greater)
  2486. // where Equal, Less and Greater are placeholders for any three constants.
  2487. ICmpInst::Predicate PredA;
  2488. if (!match(SI->getCondition(), m_ICmp(PredA, m_Value(LHS), m_Value(RHS))) ||
  2489. !ICmpInst::isEquality(PredA))
  2490. return false;
  2491. Value *EqualVal = SI->getTrueValue();
  2492. Value *UnequalVal = SI->getFalseValue();
  2493. // We still can get non-canonical predicate here, so canonicalize.
  2494. if (PredA == ICmpInst::ICMP_NE)
  2495. std::swap(EqualVal, UnequalVal);
  2496. if (!match(EqualVal, m_ConstantInt(Equal)))
  2497. return false;
  2498. ICmpInst::Predicate PredB;
  2499. Value *LHS2, *RHS2;
  2500. if (!match(UnequalVal, m_Select(m_ICmp(PredB, m_Value(LHS2), m_Value(RHS2)),
  2501. m_ConstantInt(Less), m_ConstantInt(Greater))))
  2502. return false;
  2503. // We can get predicate mismatch here, so canonicalize if possible:
  2504. // First, ensure that 'LHS' match.
  2505. if (LHS2 != LHS) {
  2506. // x sgt y <--> y slt x
  2507. std::swap(LHS2, RHS2);
  2508. PredB = ICmpInst::getSwappedPredicate(PredB);
  2509. }
  2510. if (LHS2 != LHS)
  2511. return false;
  2512. // We also need to canonicalize 'RHS'.
  2513. if (PredB == ICmpInst::ICMP_SGT && isa<Constant>(RHS2)) {
  2514. // x sgt C-1 <--> x sge C <--> not(x slt C)
  2515. auto FlippedStrictness =
  2516. InstCombiner::getFlippedStrictnessPredicateAndConstant(
  2517. PredB, cast<Constant>(RHS2));
  2518. if (!FlippedStrictness)
  2519. return false;
  2520. assert(FlippedStrictness->first == ICmpInst::ICMP_SGE &&
  2521. "basic correctness failure");
  2522. RHS2 = FlippedStrictness->second;
  2523. // And kind-of perform the result swap.
  2524. std::swap(Less, Greater);
  2525. PredB = ICmpInst::ICMP_SLT;
  2526. }
  2527. return PredB == ICmpInst::ICMP_SLT && RHS == RHS2;
  2528. }
  2529. Instruction *InstCombinerImpl::foldICmpSelectConstant(ICmpInst &Cmp,
  2530. SelectInst *Select,
  2531. ConstantInt *C) {
  2532. assert(C && "Cmp RHS should be a constant int!");
  2533. // If we're testing a constant value against the result of a three way
  2534. // comparison, the result can be expressed directly in terms of the
  2535. // original values being compared. Note: We could possibly be more
  2536. // aggressive here and remove the hasOneUse test. The original select is
  2537. // really likely to simplify or sink when we remove a test of the result.
  2538. Value *OrigLHS, *OrigRHS;
  2539. ConstantInt *C1LessThan, *C2Equal, *C3GreaterThan;
  2540. if (Cmp.hasOneUse() &&
  2541. matchThreeWayIntCompare(Select, OrigLHS, OrigRHS, C1LessThan, C2Equal,
  2542. C3GreaterThan)) {
  2543. assert(C1LessThan && C2Equal && C3GreaterThan);
  2544. bool TrueWhenLessThan =
  2545. ConstantExpr::getCompare(Cmp.getPredicate(), C1LessThan, C)
  2546. ->isAllOnesValue();
  2547. bool TrueWhenEqual =
  2548. ConstantExpr::getCompare(Cmp.getPredicate(), C2Equal, C)
  2549. ->isAllOnesValue();
  2550. bool TrueWhenGreaterThan =
  2551. ConstantExpr::getCompare(Cmp.getPredicate(), C3GreaterThan, C)
  2552. ->isAllOnesValue();
  2553. // This generates the new instruction that will replace the original Cmp
  2554. // Instruction. Instead of enumerating the various combinations when
  2555. // TrueWhenLessThan, TrueWhenEqual and TrueWhenGreaterThan are true versus
  2556. // false, we rely on chaining of ORs and future passes of InstCombine to
  2557. // simplify the OR further (i.e. a s< b || a == b becomes a s<= b).
  2558. // When none of the three constants satisfy the predicate for the RHS (C),
  2559. // the entire original Cmp can be simplified to a false.
  2560. Value *Cond = Builder.getFalse();
  2561. if (TrueWhenLessThan)
  2562. Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SLT,
  2563. OrigLHS, OrigRHS));
  2564. if (TrueWhenEqual)
  2565. Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_EQ,
  2566. OrigLHS, OrigRHS));
  2567. if (TrueWhenGreaterThan)
  2568. Cond = Builder.CreateOr(Cond, Builder.CreateICmp(ICmpInst::ICMP_SGT,
  2569. OrigLHS, OrigRHS));
  2570. return replaceInstUsesWith(Cmp, Cond);
  2571. }
  2572. return nullptr;
  2573. }
  2574. Instruction *InstCombinerImpl::foldICmpBitCast(ICmpInst &Cmp) {
  2575. auto *Bitcast = dyn_cast<BitCastInst>(Cmp.getOperand(0));
  2576. if (!Bitcast)
  2577. return nullptr;
  2578. ICmpInst::Predicate Pred = Cmp.getPredicate();
  2579. Value *Op1 = Cmp.getOperand(1);
  2580. Value *BCSrcOp = Bitcast->getOperand(0);
  2581. Type *SrcType = Bitcast->getSrcTy();
  2582. Type *DstType = Bitcast->getType();
  2583. // Make sure the bitcast doesn't change between scalar and vector and
  2584. // doesn't change the number of vector elements.
  2585. if (SrcType->isVectorTy() == DstType->isVectorTy() &&
  2586. SrcType->getScalarSizeInBits() == DstType->getScalarSizeInBits()) {
  2587. // Zero-equality and sign-bit checks are preserved through sitofp + bitcast.
  2588. Value *X;
  2589. if (match(BCSrcOp, m_SIToFP(m_Value(X)))) {
  2590. // icmp eq (bitcast (sitofp X)), 0 --> icmp eq X, 0
  2591. // icmp ne (bitcast (sitofp X)), 0 --> icmp ne X, 0
  2592. // icmp slt (bitcast (sitofp X)), 0 --> icmp slt X, 0
  2593. // icmp sgt (bitcast (sitofp X)), 0 --> icmp sgt X, 0
  2594. if ((Pred == ICmpInst::ICMP_EQ || Pred == ICmpInst::ICMP_SLT ||
  2595. Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT) &&
  2596. match(Op1, m_Zero()))
  2597. return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
  2598. // icmp slt (bitcast (sitofp X)), 1 --> icmp slt X, 1
  2599. if (Pred == ICmpInst::ICMP_SLT && match(Op1, m_One()))
  2600. return new ICmpInst(Pred, X, ConstantInt::get(X->getType(), 1));
  2601. // icmp sgt (bitcast (sitofp X)), -1 --> icmp sgt X, -1
  2602. if (Pred == ICmpInst::ICMP_SGT && match(Op1, m_AllOnes()))
  2603. return new ICmpInst(Pred, X,
  2604. ConstantInt::getAllOnesValue(X->getType()));
  2605. }
  2606. // Zero-equality checks are preserved through unsigned floating-point casts:
  2607. // icmp eq (bitcast (uitofp X)), 0 --> icmp eq X, 0
  2608. // icmp ne (bitcast (uitofp X)), 0 --> icmp ne X, 0
  2609. if (match(BCSrcOp, m_UIToFP(m_Value(X))))
  2610. if (Cmp.isEquality() && match(Op1, m_Zero()))
  2611. return new ICmpInst(Pred, X, ConstantInt::getNullValue(X->getType()));
  2612. // If this is a sign-bit test of a bitcast of a casted FP value, eliminate
  2613. // the FP extend/truncate because that cast does not change the sign-bit.
  2614. // This is true for all standard IEEE-754 types and the X86 80-bit type.
  2615. // The sign-bit is always the most significant bit in those types.
  2616. const APInt *C;
  2617. bool TrueIfSigned;
  2618. if (match(Op1, m_APInt(C)) && Bitcast->hasOneUse() &&
  2619. isSignBitCheck(Pred, *C, TrueIfSigned)) {
  2620. if (match(BCSrcOp, m_FPExt(m_Value(X))) ||
  2621. match(BCSrcOp, m_FPTrunc(m_Value(X)))) {
  2622. // (bitcast (fpext/fptrunc X)) to iX) < 0 --> (bitcast X to iY) < 0
  2623. // (bitcast (fpext/fptrunc X)) to iX) > -1 --> (bitcast X to iY) > -1
  2624. Type *XType = X->getType();
  2625. // We can't currently handle Power style floating point operations here.
  2626. if (!(XType->isPPC_FP128Ty() || SrcType->isPPC_FP128Ty())) {
  2627. Type *NewType = Builder.getIntNTy(XType->getScalarSizeInBits());
  2628. if (auto *XVTy = dyn_cast<VectorType>(XType))
  2629. NewType = VectorType::get(NewType, XVTy->getElementCount());
  2630. Value *NewBitcast = Builder.CreateBitCast(X, NewType);
  2631. if (TrueIfSigned)
  2632. return new ICmpInst(ICmpInst::ICMP_SLT, NewBitcast,
  2633. ConstantInt::getNullValue(NewType));
  2634. else
  2635. return new ICmpInst(ICmpInst::ICMP_SGT, NewBitcast,
  2636. ConstantInt::getAllOnesValue(NewType));
  2637. }
  2638. }
  2639. }
  2640. }
  2641. // Test to see if the operands of the icmp are casted versions of other
  2642. // values. If the ptr->ptr cast can be stripped off both arguments, do so.
  2643. if (DstType->isPointerTy() && (isa<Constant>(Op1) || isa<BitCastInst>(Op1))) {
  2644. // If operand #1 is a bitcast instruction, it must also be a ptr->ptr cast
  2645. // so eliminate it as well.
  2646. if (auto *BC2 = dyn_cast<BitCastInst>(Op1))
  2647. Op1 = BC2->getOperand(0);
  2648. Op1 = Builder.CreateBitCast(Op1, SrcType);
  2649. return new ICmpInst(Pred, BCSrcOp, Op1);
  2650. }
  2651. const APInt *C;
  2652. if (!match(Cmp.getOperand(1), m_APInt(C)) || !DstType->isIntegerTy() ||
  2653. !SrcType->isIntOrIntVectorTy())
  2654. return nullptr;
  2655. // If this is checking if all elements of a vector compare are set or not,
  2656. // invert the casted vector equality compare and test if all compare
  2657. // elements are clear or not. Compare against zero is generally easier for
  2658. // analysis and codegen.
  2659. // icmp eq/ne (bitcast (not X) to iN), -1 --> icmp eq/ne (bitcast X to iN), 0
  2660. // Example: are all elements equal? --> are zero elements not equal?
  2661. // TODO: Try harder to reduce compare of 2 freely invertible operands?
  2662. if (Cmp.isEquality() && C->isAllOnes() && Bitcast->hasOneUse() &&
  2663. isFreeToInvert(BCSrcOp, BCSrcOp->hasOneUse())) {
  2664. Value *Cast = Builder.CreateBitCast(Builder.CreateNot(BCSrcOp), DstType);
  2665. return new ICmpInst(Pred, Cast, ConstantInt::getNullValue(DstType));
  2666. }
  2667. // If this is checking if all elements of an extended vector are clear or not,
  2668. // compare in a narrow type to eliminate the extend:
  2669. // icmp eq/ne (bitcast (ext X) to iN), 0 --> icmp eq/ne (bitcast X to iM), 0
  2670. Value *X;
  2671. if (Cmp.isEquality() && C->isZero() && Bitcast->hasOneUse() &&
  2672. match(BCSrcOp, m_ZExtOrSExt(m_Value(X)))) {
  2673. if (auto *VecTy = dyn_cast<FixedVectorType>(X->getType())) {
  2674. Type *NewType = Builder.getIntNTy(VecTy->getPrimitiveSizeInBits());
  2675. Value *NewCast = Builder.CreateBitCast(X, NewType);
  2676. return new ICmpInst(Pred, NewCast, ConstantInt::getNullValue(NewType));
  2677. }
  2678. }
  2679. // Folding: icmp <pred> iN X, C
  2680. // where X = bitcast <M x iK> (shufflevector <M x iK> %vec, undef, SC)) to iN
  2681. // and C is a splat of a K-bit pattern
  2682. // and SC is a constant vector = <C', C', C', ..., C'>
  2683. // Into:
  2684. // %E = extractelement <M x iK> %vec, i32 C'
  2685. // icmp <pred> iK %E, trunc(C)
  2686. Value *Vec;
  2687. ArrayRef<int> Mask;
  2688. if (match(BCSrcOp, m_Shuffle(m_Value(Vec), m_Undef(), m_Mask(Mask)))) {
  2689. // Check whether every element of Mask is the same constant
  2690. if (all_equal(Mask)) {
  2691. auto *VecTy = cast<VectorType>(SrcType);
  2692. auto *EltTy = cast<IntegerType>(VecTy->getElementType());
  2693. if (C->isSplat(EltTy->getBitWidth())) {
  2694. // Fold the icmp based on the value of C
  2695. // If C is M copies of an iK sized bit pattern,
  2696. // then:
  2697. // => %E = extractelement <N x iK> %vec, i32 Elem
  2698. // icmp <pred> iK %SplatVal, <pattern>
  2699. Value *Elem = Builder.getInt32(Mask[0]);
  2700. Value *Extract = Builder.CreateExtractElement(Vec, Elem);
  2701. Value *NewC = ConstantInt::get(EltTy, C->trunc(EltTy->getBitWidth()));
  2702. return new ICmpInst(Pred, Extract, NewC);
  2703. }
  2704. }
  2705. }
  2706. return nullptr;
  2707. }
  2708. /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
  2709. /// where X is some kind of instruction.
  2710. Instruction *InstCombinerImpl::foldICmpInstWithConstant(ICmpInst &Cmp) {
  2711. const APInt *C;
  2712. if (match(Cmp.getOperand(1), m_APInt(C))) {
  2713. if (auto *BO = dyn_cast<BinaryOperator>(Cmp.getOperand(0)))
  2714. if (Instruction *I = foldICmpBinOpWithConstant(Cmp, BO, *C))
  2715. return I;
  2716. if (auto *SI = dyn_cast<SelectInst>(Cmp.getOperand(0)))
  2717. // For now, we only support constant integers while folding the
  2718. // ICMP(SELECT)) pattern. We can extend this to support vector of integers
  2719. // similar to the cases handled by binary ops above.
  2720. if (auto *ConstRHS = dyn_cast<ConstantInt>(Cmp.getOperand(1)))
  2721. if (Instruction *I = foldICmpSelectConstant(Cmp, SI, ConstRHS))
  2722. return I;
  2723. if (auto *TI = dyn_cast<TruncInst>(Cmp.getOperand(0)))
  2724. if (Instruction *I = foldICmpTruncConstant(Cmp, TI, *C))
  2725. return I;
  2726. if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0)))
  2727. if (Instruction *I = foldICmpIntrinsicWithConstant(Cmp, II, *C))
  2728. return I;
  2729. // (extractval ([s/u]subo X, Y), 0) == 0 --> X == Y
  2730. // (extractval ([s/u]subo X, Y), 0) != 0 --> X != Y
  2731. // TODO: This checks one-use, but that is not strictly necessary.
  2732. Value *Cmp0 = Cmp.getOperand(0);
  2733. Value *X, *Y;
  2734. if (C->isZero() && Cmp.isEquality() && Cmp0->hasOneUse() &&
  2735. (match(Cmp0,
  2736. m_ExtractValue<0>(m_Intrinsic<Intrinsic::ssub_with_overflow>(
  2737. m_Value(X), m_Value(Y)))) ||
  2738. match(Cmp0,
  2739. m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
  2740. m_Value(X), m_Value(Y))))))
  2741. return new ICmpInst(Cmp.getPredicate(), X, Y);
  2742. }
  2743. if (match(Cmp.getOperand(1), m_APIntAllowUndef(C)))
  2744. return foldICmpInstWithConstantAllowUndef(Cmp, *C);
  2745. return nullptr;
  2746. }
  2747. /// Fold an icmp equality instruction with binary operator LHS and constant RHS:
  2748. /// icmp eq/ne BO, C.
  2749. Instruction *InstCombinerImpl::foldICmpBinOpEqualityWithConstant(
  2750. ICmpInst &Cmp, BinaryOperator *BO, const APInt &C) {
  2751. // TODO: Some of these folds could work with arbitrary constants, but this
  2752. // function is limited to scalar and vector splat constants.
  2753. if (!Cmp.isEquality())
  2754. return nullptr;
  2755. ICmpInst::Predicate Pred = Cmp.getPredicate();
  2756. bool isICMP_NE = Pred == ICmpInst::ICMP_NE;
  2757. Constant *RHS = cast<Constant>(Cmp.getOperand(1));
  2758. Value *BOp0 = BO->getOperand(0), *BOp1 = BO->getOperand(1);
  2759. switch (BO->getOpcode()) {
  2760. case Instruction::SRem:
  2761. // If we have a signed (X % (2^c)) == 0, turn it into an unsigned one.
  2762. if (C.isZero() && BO->hasOneUse()) {
  2763. const APInt *BOC;
  2764. if (match(BOp1, m_APInt(BOC)) && BOC->sgt(1) && BOC->isPowerOf2()) {
  2765. Value *NewRem = Builder.CreateURem(BOp0, BOp1, BO->getName());
  2766. return new ICmpInst(Pred, NewRem,
  2767. Constant::getNullValue(BO->getType()));
  2768. }
  2769. }
  2770. break;
  2771. case Instruction::Add: {
  2772. // (A + C2) == C --> A == (C - C2)
  2773. // (A + C2) != C --> A != (C - C2)
  2774. // TODO: Remove the one-use limitation? See discussion in D58633.
  2775. if (Constant *C2 = dyn_cast<Constant>(BOp1)) {
  2776. if (BO->hasOneUse())
  2777. return new ICmpInst(Pred, BOp0, ConstantExpr::getSub(RHS, C2));
  2778. } else if (C.isZero()) {
  2779. // Replace ((add A, B) != 0) with (A != -B) if A or B is
  2780. // efficiently invertible, or if the add has just this one use.
  2781. if (Value *NegVal = dyn_castNegVal(BOp1))
  2782. return new ICmpInst(Pred, BOp0, NegVal);
  2783. if (Value *NegVal = dyn_castNegVal(BOp0))
  2784. return new ICmpInst(Pred, NegVal, BOp1);
  2785. if (BO->hasOneUse()) {
  2786. Value *Neg = Builder.CreateNeg(BOp1);
  2787. Neg->takeName(BO);
  2788. return new ICmpInst(Pred, BOp0, Neg);
  2789. }
  2790. }
  2791. break;
  2792. }
  2793. case Instruction::Xor:
  2794. if (BO->hasOneUse()) {
  2795. if (Constant *BOC = dyn_cast<Constant>(BOp1)) {
  2796. // For the xor case, we can xor two constants together, eliminating
  2797. // the explicit xor.
  2798. return new ICmpInst(Pred, BOp0, ConstantExpr::getXor(RHS, BOC));
  2799. } else if (C.isZero()) {
  2800. // Replace ((xor A, B) != 0) with (A != B)
  2801. return new ICmpInst(Pred, BOp0, BOp1);
  2802. }
  2803. }
  2804. break;
  2805. case Instruction::Or: {
  2806. const APInt *BOC;
  2807. if (match(BOp1, m_APInt(BOC)) && BO->hasOneUse() && RHS->isAllOnesValue()) {
  2808. // Comparing if all bits outside of a constant mask are set?
  2809. // Replace (X | C) == -1 with (X & ~C) == ~C.
  2810. // This removes the -1 constant.
  2811. Constant *NotBOC = ConstantExpr::getNot(cast<Constant>(BOp1));
  2812. Value *And = Builder.CreateAnd(BOp0, NotBOC);
  2813. return new ICmpInst(Pred, And, NotBOC);
  2814. }
  2815. break;
  2816. }
  2817. case Instruction::And: {
  2818. const APInt *BOC;
  2819. if (match(BOp1, m_APInt(BOC))) {
  2820. // If we have ((X & C) == C), turn it into ((X & C) != 0).
  2821. if (C == *BOC && C.isPowerOf2())
  2822. return new ICmpInst(isICMP_NE ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE,
  2823. BO, Constant::getNullValue(RHS->getType()));
  2824. }
  2825. break;
  2826. }
  2827. case Instruction::UDiv:
  2828. if (C.isZero()) {
  2829. // (icmp eq/ne (udiv A, B), 0) -> (icmp ugt/ule i32 B, A)
  2830. auto NewPred = isICMP_NE ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
  2831. return new ICmpInst(NewPred, BOp1, BOp0);
  2832. }
  2833. break;
  2834. default:
  2835. break;
  2836. }
  2837. return nullptr;
  2838. }
  2839. /// Fold an equality icmp with LLVM intrinsic and constant operand.
  2840. Instruction *InstCombinerImpl::foldICmpEqIntrinsicWithConstant(
  2841. ICmpInst &Cmp, IntrinsicInst *II, const APInt &C) {
  2842. Type *Ty = II->getType();
  2843. unsigned BitWidth = C.getBitWidth();
  2844. const ICmpInst::Predicate Pred = Cmp.getPredicate();
  2845. switch (II->getIntrinsicID()) {
  2846. case Intrinsic::abs:
  2847. // abs(A) == 0 -> A == 0
  2848. // abs(A) == INT_MIN -> A == INT_MIN
  2849. if (C.isZero() || C.isMinSignedValue())
  2850. return new ICmpInst(Pred, II->getArgOperand(0), ConstantInt::get(Ty, C));
  2851. break;
  2852. case Intrinsic::bswap:
  2853. // bswap(A) == C -> A == bswap(C)
  2854. return new ICmpInst(Pred, II->getArgOperand(0),
  2855. ConstantInt::get(Ty, C.byteSwap()));
  2856. case Intrinsic::ctlz:
  2857. case Intrinsic::cttz: {
  2858. // ctz(A) == bitwidth(A) -> A == 0 and likewise for !=
  2859. if (C == BitWidth)
  2860. return new ICmpInst(Pred, II->getArgOperand(0),
  2861. ConstantInt::getNullValue(Ty));
  2862. // ctz(A) == C -> A & Mask1 == Mask2, where Mask2 only has bit C set
  2863. // and Mask1 has bits 0..C+1 set. Similar for ctl, but for high bits.
  2864. // Limit to one use to ensure we don't increase instruction count.
  2865. unsigned Num = C.getLimitedValue(BitWidth);
  2866. if (Num != BitWidth && II->hasOneUse()) {
  2867. bool IsTrailing = II->getIntrinsicID() == Intrinsic::cttz;
  2868. APInt Mask1 = IsTrailing ? APInt::getLowBitsSet(BitWidth, Num + 1)
  2869. : APInt::getHighBitsSet(BitWidth, Num + 1);
  2870. APInt Mask2 = IsTrailing
  2871. ? APInt::getOneBitSet(BitWidth, Num)
  2872. : APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
  2873. return new ICmpInst(Pred, Builder.CreateAnd(II->getArgOperand(0), Mask1),
  2874. ConstantInt::get(Ty, Mask2));
  2875. }
  2876. break;
  2877. }
  2878. case Intrinsic::ctpop: {
  2879. // popcount(A) == 0 -> A == 0 and likewise for !=
  2880. // popcount(A) == bitwidth(A) -> A == -1 and likewise for !=
  2881. bool IsZero = C.isZero();
  2882. if (IsZero || C == BitWidth)
  2883. return new ICmpInst(Pred, II->getArgOperand(0),
  2884. IsZero ? Constant::getNullValue(Ty)
  2885. : Constant::getAllOnesValue(Ty));
  2886. break;
  2887. }
  2888. case Intrinsic::fshl:
  2889. case Intrinsic::fshr:
  2890. if (II->getArgOperand(0) == II->getArgOperand(1)) {
  2891. const APInt *RotAmtC;
  2892. // ror(X, RotAmtC) == C --> X == rol(C, RotAmtC)
  2893. // rol(X, RotAmtC) == C --> X == ror(C, RotAmtC)
  2894. if (match(II->getArgOperand(2), m_APInt(RotAmtC)))
  2895. return new ICmpInst(Pred, II->getArgOperand(0),
  2896. II->getIntrinsicID() == Intrinsic::fshl
  2897. ? ConstantInt::get(Ty, C.rotr(*RotAmtC))
  2898. : ConstantInt::get(Ty, C.rotl(*RotAmtC)));
  2899. }
  2900. break;
  2901. case Intrinsic::uadd_sat: {
  2902. // uadd.sat(a, b) == 0 -> (a | b) == 0
  2903. if (C.isZero()) {
  2904. Value *Or = Builder.CreateOr(II->getArgOperand(0), II->getArgOperand(1));
  2905. return new ICmpInst(Pred, Or, Constant::getNullValue(Ty));
  2906. }
  2907. break;
  2908. }
  2909. case Intrinsic::usub_sat: {
  2910. // usub.sat(a, b) == 0 -> a <= b
  2911. if (C.isZero()) {
  2912. ICmpInst::Predicate NewPred =
  2913. Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_UGT;
  2914. return new ICmpInst(NewPred, II->getArgOperand(0), II->getArgOperand(1));
  2915. }
  2916. break;
  2917. }
  2918. default:
  2919. break;
  2920. }
  2921. return nullptr;
  2922. }
  2923. /// Fold an icmp with LLVM intrinsics
  2924. static Instruction *foldICmpIntrinsicWithIntrinsic(ICmpInst &Cmp) {
  2925. assert(Cmp.isEquality());
  2926. ICmpInst::Predicate Pred = Cmp.getPredicate();
  2927. Value *Op0 = Cmp.getOperand(0);
  2928. Value *Op1 = Cmp.getOperand(1);
  2929. const auto *IIOp0 = dyn_cast<IntrinsicInst>(Op0);
  2930. const auto *IIOp1 = dyn_cast<IntrinsicInst>(Op1);
  2931. if (!IIOp0 || !IIOp1 || IIOp0->getIntrinsicID() != IIOp1->getIntrinsicID())
  2932. return nullptr;
  2933. switch (IIOp0->getIntrinsicID()) {
  2934. case Intrinsic::bswap:
  2935. case Intrinsic::bitreverse:
  2936. // If both operands are byte-swapped or bit-reversed, just compare the
  2937. // original values.
  2938. return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
  2939. case Intrinsic::fshl:
  2940. case Intrinsic::fshr:
  2941. // If both operands are rotated by same amount, just compare the
  2942. // original values.
  2943. if (IIOp0->getOperand(0) != IIOp0->getOperand(1))
  2944. break;
  2945. if (IIOp1->getOperand(0) != IIOp1->getOperand(1))
  2946. break;
  2947. if (IIOp0->getOperand(2) != IIOp1->getOperand(2))
  2948. break;
  2949. return new ICmpInst(Pred, IIOp0->getOperand(0), IIOp1->getOperand(0));
  2950. default:
  2951. break;
  2952. }
  2953. return nullptr;
  2954. }
  2955. /// Try to fold integer comparisons with a constant operand: icmp Pred X, C
  2956. /// where X is some kind of instruction and C is AllowUndef.
  2957. /// TODO: Move more folds which allow undef to this function.
  2958. Instruction *
  2959. InstCombinerImpl::foldICmpInstWithConstantAllowUndef(ICmpInst &Cmp,
  2960. const APInt &C) {
  2961. const ICmpInst::Predicate Pred = Cmp.getPredicate();
  2962. if (auto *II = dyn_cast<IntrinsicInst>(Cmp.getOperand(0))) {
  2963. switch (II->getIntrinsicID()) {
  2964. default:
  2965. break;
  2966. case Intrinsic::fshl:
  2967. case Intrinsic::fshr:
  2968. if (Cmp.isEquality() && II->getArgOperand(0) == II->getArgOperand(1)) {
  2969. // (rot X, ?) == 0/-1 --> X == 0/-1
  2970. if (C.isZero() || C.isAllOnes())
  2971. return new ICmpInst(Pred, II->getArgOperand(0), Cmp.getOperand(1));
  2972. }
  2973. break;
  2974. }
  2975. }
  2976. return nullptr;
  2977. }
  2978. /// Fold an icmp with BinaryOp and constant operand: icmp Pred BO, C.
  2979. Instruction *InstCombinerImpl::foldICmpBinOpWithConstant(ICmpInst &Cmp,
  2980. BinaryOperator *BO,
  2981. const APInt &C) {
  2982. switch (BO->getOpcode()) {
  2983. case Instruction::Xor:
  2984. if (Instruction *I = foldICmpXorConstant(Cmp, BO, C))
  2985. return I;
  2986. break;
  2987. case Instruction::And:
  2988. if (Instruction *I = foldICmpAndConstant(Cmp, BO, C))
  2989. return I;
  2990. break;
  2991. case Instruction::Or:
  2992. if (Instruction *I = foldICmpOrConstant(Cmp, BO, C))
  2993. return I;
  2994. break;
  2995. case Instruction::Mul:
  2996. if (Instruction *I = foldICmpMulConstant(Cmp, BO, C))
  2997. return I;
  2998. break;
  2999. case Instruction::Shl:
  3000. if (Instruction *I = foldICmpShlConstant(Cmp, BO, C))
  3001. return I;
  3002. break;
  3003. case Instruction::LShr:
  3004. case Instruction::AShr:
  3005. if (Instruction *I = foldICmpShrConstant(Cmp, BO, C))
  3006. return I;
  3007. break;
  3008. case Instruction::SRem:
  3009. if (Instruction *I = foldICmpSRemConstant(Cmp, BO, C))
  3010. return I;
  3011. break;
  3012. case Instruction::UDiv:
  3013. if (Instruction *I = foldICmpUDivConstant(Cmp, BO, C))
  3014. return I;
  3015. [[fallthrough]];
  3016. case Instruction::SDiv:
  3017. if (Instruction *I = foldICmpDivConstant(Cmp, BO, C))
  3018. return I;
  3019. break;
  3020. case Instruction::Sub:
  3021. if (Instruction *I = foldICmpSubConstant(Cmp, BO, C))
  3022. return I;
  3023. break;
  3024. case Instruction::Add:
  3025. if (Instruction *I = foldICmpAddConstant(Cmp, BO, C))
  3026. return I;
  3027. break;
  3028. default:
  3029. break;
  3030. }
  3031. // TODO: These folds could be refactored to be part of the above calls.
  3032. return foldICmpBinOpEqualityWithConstant(Cmp, BO, C);
  3033. }
  3034. /// Fold an icmp with LLVM intrinsic and constant operand: icmp Pred II, C.
  3035. Instruction *InstCombinerImpl::foldICmpIntrinsicWithConstant(ICmpInst &Cmp,
  3036. IntrinsicInst *II,
  3037. const APInt &C) {
  3038. if (Cmp.isEquality())
  3039. return foldICmpEqIntrinsicWithConstant(Cmp, II, C);
  3040. Type *Ty = II->getType();
  3041. unsigned BitWidth = C.getBitWidth();
  3042. ICmpInst::Predicate Pred = Cmp.getPredicate();
  3043. switch (II->getIntrinsicID()) {
  3044. case Intrinsic::ctpop: {
  3045. // (ctpop X > BitWidth - 1) --> X == -1
  3046. Value *X = II->getArgOperand(0);
  3047. if (C == BitWidth - 1 && Pred == ICmpInst::ICMP_UGT)
  3048. return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ, X,
  3049. ConstantInt::getAllOnesValue(Ty));
  3050. // (ctpop X < BitWidth) --> X != -1
  3051. if (C == BitWidth && Pred == ICmpInst::ICMP_ULT)
  3052. return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE, X,
  3053. ConstantInt::getAllOnesValue(Ty));
  3054. break;
  3055. }
  3056. case Intrinsic::ctlz: {
  3057. // ctlz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX < 0b00010000
  3058. if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
  3059. unsigned Num = C.getLimitedValue();
  3060. APInt Limit = APInt::getOneBitSet(BitWidth, BitWidth - Num - 1);
  3061. return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_ULT,
  3062. II->getArgOperand(0), ConstantInt::get(Ty, Limit));
  3063. }
  3064. // ctlz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX > 0b00011111
  3065. if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
  3066. unsigned Num = C.getLimitedValue();
  3067. APInt Limit = APInt::getLowBitsSet(BitWidth, BitWidth - Num);
  3068. return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_UGT,
  3069. II->getArgOperand(0), ConstantInt::get(Ty, Limit));
  3070. }
  3071. break;
  3072. }
  3073. case Intrinsic::cttz: {
  3074. // Limit to one use to ensure we don't increase instruction count.
  3075. if (!II->hasOneUse())
  3076. return nullptr;
  3077. // cttz(0bXXXXXXXX) > 3 -> 0bXXXXXXXX & 0b00001111 == 0
  3078. if (Pred == ICmpInst::ICMP_UGT && C.ult(BitWidth)) {
  3079. APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue() + 1);
  3080. return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_EQ,
  3081. Builder.CreateAnd(II->getArgOperand(0), Mask),
  3082. ConstantInt::getNullValue(Ty));
  3083. }
  3084. // cttz(0bXXXXXXXX) < 3 -> 0bXXXXXXXX & 0b00000111 != 0
  3085. if (Pred == ICmpInst::ICMP_ULT && C.uge(1) && C.ule(BitWidth)) {
  3086. APInt Mask = APInt::getLowBitsSet(BitWidth, C.getLimitedValue());
  3087. return CmpInst::Create(Instruction::ICmp, ICmpInst::ICMP_NE,
  3088. Builder.CreateAnd(II->getArgOperand(0), Mask),
  3089. ConstantInt::getNullValue(Ty));
  3090. }
  3091. break;
  3092. }
  3093. default:
  3094. break;
  3095. }
  3096. return nullptr;
  3097. }
  3098. /// Handle icmp with constant (but not simple integer constant) RHS.
  3099. Instruction *InstCombinerImpl::foldICmpInstWithConstantNotInt(ICmpInst &I) {
  3100. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  3101. Constant *RHSC = dyn_cast<Constant>(Op1);
  3102. Instruction *LHSI = dyn_cast<Instruction>(Op0);
  3103. if (!RHSC || !LHSI)
  3104. return nullptr;
  3105. switch (LHSI->getOpcode()) {
  3106. case Instruction::GetElementPtr:
  3107. // icmp pred GEP (P, int 0, int 0, int 0), null -> icmp pred P, null
  3108. if (RHSC->isNullValue() &&
  3109. cast<GetElementPtrInst>(LHSI)->hasAllZeroIndices())
  3110. return new ICmpInst(
  3111. I.getPredicate(), LHSI->getOperand(0),
  3112. Constant::getNullValue(LHSI->getOperand(0)->getType()));
  3113. break;
  3114. case Instruction::PHI:
  3115. // Only fold icmp into the PHI if the phi and icmp are in the same
  3116. // block. If in the same block, we're encouraging jump threading. If
  3117. // not, we are just pessimizing the code by making an i1 phi.
  3118. if (LHSI->getParent() == I.getParent())
  3119. if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
  3120. return NV;
  3121. break;
  3122. case Instruction::IntToPtr:
  3123. // icmp pred inttoptr(X), null -> icmp pred X, 0
  3124. if (RHSC->isNullValue() &&
  3125. DL.getIntPtrType(RHSC->getType()) == LHSI->getOperand(0)->getType())
  3126. return new ICmpInst(
  3127. I.getPredicate(), LHSI->getOperand(0),
  3128. Constant::getNullValue(LHSI->getOperand(0)->getType()));
  3129. break;
  3130. case Instruction::Load:
  3131. // Try to optimize things like "A[i] > 4" to index computations.
  3132. if (GetElementPtrInst *GEP =
  3133. dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
  3134. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
  3135. if (Instruction *Res =
  3136. foldCmpLoadFromIndexedGlobal(cast<LoadInst>(LHSI), GEP, GV, I))
  3137. return Res;
  3138. break;
  3139. }
  3140. return nullptr;
  3141. }
  3142. Instruction *InstCombinerImpl::foldSelectICmp(ICmpInst::Predicate Pred,
  3143. SelectInst *SI, Value *RHS,
  3144. const ICmpInst &I) {
  3145. // Try to fold the comparison into the select arms, which will cause the
  3146. // select to be converted into a logical and/or.
  3147. auto SimplifyOp = [&](Value *Op, bool SelectCondIsTrue) -> Value * {
  3148. if (Value *Res = simplifyICmpInst(Pred, Op, RHS, SQ))
  3149. return Res;
  3150. if (std::optional<bool> Impl = isImpliedCondition(
  3151. SI->getCondition(), Pred, Op, RHS, DL, SelectCondIsTrue))
  3152. return ConstantInt::get(I.getType(), *Impl);
  3153. return nullptr;
  3154. };
  3155. ConstantInt *CI = nullptr;
  3156. Value *Op1 = SimplifyOp(SI->getOperand(1), true);
  3157. if (Op1)
  3158. CI = dyn_cast<ConstantInt>(Op1);
  3159. Value *Op2 = SimplifyOp(SI->getOperand(2), false);
  3160. if (Op2)
  3161. CI = dyn_cast<ConstantInt>(Op2);
  3162. // We only want to perform this transformation if it will not lead to
  3163. // additional code. This is true if either both sides of the select
  3164. // fold to a constant (in which case the icmp is replaced with a select
  3165. // which will usually simplify) or this is the only user of the
  3166. // select (in which case we are trading a select+icmp for a simpler
  3167. // select+icmp) or all uses of the select can be replaced based on
  3168. // dominance information ("Global cases").
  3169. bool Transform = false;
  3170. if (Op1 && Op2)
  3171. Transform = true;
  3172. else if (Op1 || Op2) {
  3173. // Local case
  3174. if (SI->hasOneUse())
  3175. Transform = true;
  3176. // Global cases
  3177. else if (CI && !CI->isZero())
  3178. // When Op1 is constant try replacing select with second operand.
  3179. // Otherwise Op2 is constant and try replacing select with first
  3180. // operand.
  3181. Transform = replacedSelectWithOperand(SI, &I, Op1 ? 2 : 1);
  3182. }
  3183. if (Transform) {
  3184. if (!Op1)
  3185. Op1 = Builder.CreateICmp(Pred, SI->getOperand(1), RHS, I.getName());
  3186. if (!Op2)
  3187. Op2 = Builder.CreateICmp(Pred, SI->getOperand(2), RHS, I.getName());
  3188. return SelectInst::Create(SI->getOperand(0), Op1, Op2);
  3189. }
  3190. return nullptr;
  3191. }
  3192. /// Some comparisons can be simplified.
  3193. /// In this case, we are looking for comparisons that look like
  3194. /// a check for a lossy truncation.
  3195. /// Folds:
  3196. /// icmp SrcPred (x & Mask), x to icmp DstPred x, Mask
  3197. /// Where Mask is some pattern that produces all-ones in low bits:
  3198. /// (-1 >> y)
  3199. /// ((-1 << y) >> y) <- non-canonical, has extra uses
  3200. /// ~(-1 << y)
  3201. /// ((1 << y) + (-1)) <- non-canonical, has extra uses
  3202. /// The Mask can be a constant, too.
  3203. /// For some predicates, the operands are commutative.
  3204. /// For others, x can only be on a specific side.
  3205. static Value *foldICmpWithLowBitMaskedVal(ICmpInst &I,
  3206. InstCombiner::BuilderTy &Builder) {
  3207. ICmpInst::Predicate SrcPred;
  3208. Value *X, *M, *Y;
  3209. auto m_VariableMask = m_CombineOr(
  3210. m_CombineOr(m_Not(m_Shl(m_AllOnes(), m_Value())),
  3211. m_Add(m_Shl(m_One(), m_Value()), m_AllOnes())),
  3212. m_CombineOr(m_LShr(m_AllOnes(), m_Value()),
  3213. m_LShr(m_Shl(m_AllOnes(), m_Value(Y)), m_Deferred(Y))));
  3214. auto m_Mask = m_CombineOr(m_VariableMask, m_LowBitMask());
  3215. if (!match(&I, m_c_ICmp(SrcPred,
  3216. m_c_And(m_CombineAnd(m_Mask, m_Value(M)), m_Value(X)),
  3217. m_Deferred(X))))
  3218. return nullptr;
  3219. ICmpInst::Predicate DstPred;
  3220. switch (SrcPred) {
  3221. case ICmpInst::Predicate::ICMP_EQ:
  3222. // x & (-1 >> y) == x -> x u<= (-1 >> y)
  3223. DstPred = ICmpInst::Predicate::ICMP_ULE;
  3224. break;
  3225. case ICmpInst::Predicate::ICMP_NE:
  3226. // x & (-1 >> y) != x -> x u> (-1 >> y)
  3227. DstPred = ICmpInst::Predicate::ICMP_UGT;
  3228. break;
  3229. case ICmpInst::Predicate::ICMP_ULT:
  3230. // x & (-1 >> y) u< x -> x u> (-1 >> y)
  3231. // x u> x & (-1 >> y) -> x u> (-1 >> y)
  3232. DstPred = ICmpInst::Predicate::ICMP_UGT;
  3233. break;
  3234. case ICmpInst::Predicate::ICMP_UGE:
  3235. // x & (-1 >> y) u>= x -> x u<= (-1 >> y)
  3236. // x u<= x & (-1 >> y) -> x u<= (-1 >> y)
  3237. DstPred = ICmpInst::Predicate::ICMP_ULE;
  3238. break;
  3239. case ICmpInst::Predicate::ICMP_SLT:
  3240. // x & (-1 >> y) s< x -> x s> (-1 >> y)
  3241. // x s> x & (-1 >> y) -> x s> (-1 >> y)
  3242. if (!match(M, m_Constant())) // Can not do this fold with non-constant.
  3243. return nullptr;
  3244. if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
  3245. return nullptr;
  3246. DstPred = ICmpInst::Predicate::ICMP_SGT;
  3247. break;
  3248. case ICmpInst::Predicate::ICMP_SGE:
  3249. // x & (-1 >> y) s>= x -> x s<= (-1 >> y)
  3250. // x s<= x & (-1 >> y) -> x s<= (-1 >> y)
  3251. if (!match(M, m_Constant())) // Can not do this fold with non-constant.
  3252. return nullptr;
  3253. if (!match(M, m_NonNegative())) // Must not have any -1 vector elements.
  3254. return nullptr;
  3255. DstPred = ICmpInst::Predicate::ICMP_SLE;
  3256. break;
  3257. case ICmpInst::Predicate::ICMP_SGT:
  3258. case ICmpInst::Predicate::ICMP_SLE:
  3259. return nullptr;
  3260. case ICmpInst::Predicate::ICMP_UGT:
  3261. case ICmpInst::Predicate::ICMP_ULE:
  3262. llvm_unreachable("Instsimplify took care of commut. variant");
  3263. break;
  3264. default:
  3265. llvm_unreachable("All possible folds are handled.");
  3266. }
  3267. // The mask value may be a vector constant that has undefined elements. But it
  3268. // may not be safe to propagate those undefs into the new compare, so replace
  3269. // those elements by copying an existing, defined, and safe scalar constant.
  3270. Type *OpTy = M->getType();
  3271. auto *VecC = dyn_cast<Constant>(M);
  3272. auto *OpVTy = dyn_cast<FixedVectorType>(OpTy);
  3273. if (OpVTy && VecC && VecC->containsUndefOrPoisonElement()) {
  3274. Constant *SafeReplacementConstant = nullptr;
  3275. for (unsigned i = 0, e = OpVTy->getNumElements(); i != e; ++i) {
  3276. if (!isa<UndefValue>(VecC->getAggregateElement(i))) {
  3277. SafeReplacementConstant = VecC->getAggregateElement(i);
  3278. break;
  3279. }
  3280. }
  3281. assert(SafeReplacementConstant && "Failed to find undef replacement");
  3282. M = Constant::replaceUndefsWith(VecC, SafeReplacementConstant);
  3283. }
  3284. return Builder.CreateICmp(DstPred, X, M);
  3285. }
  3286. /// Some comparisons can be simplified.
  3287. /// In this case, we are looking for comparisons that look like
  3288. /// a check for a lossy signed truncation.
  3289. /// Folds: (MaskedBits is a constant.)
  3290. /// ((%x << MaskedBits) a>> MaskedBits) SrcPred %x
  3291. /// Into:
  3292. /// (add %x, (1 << (KeptBits-1))) DstPred (1 << KeptBits)
  3293. /// Where KeptBits = bitwidth(%x) - MaskedBits
  3294. static Value *
  3295. foldICmpWithTruncSignExtendedVal(ICmpInst &I,
  3296. InstCombiner::BuilderTy &Builder) {
  3297. ICmpInst::Predicate SrcPred;
  3298. Value *X;
  3299. const APInt *C0, *C1; // FIXME: non-splats, potentially with undef.
  3300. // We are ok with 'shl' having multiple uses, but 'ashr' must be one-use.
  3301. if (!match(&I, m_c_ICmp(SrcPred,
  3302. m_OneUse(m_AShr(m_Shl(m_Value(X), m_APInt(C0)),
  3303. m_APInt(C1))),
  3304. m_Deferred(X))))
  3305. return nullptr;
  3306. // Potential handling of non-splats: for each element:
  3307. // * if both are undef, replace with constant 0.
  3308. // Because (1<<0) is OK and is 1, and ((1<<0)>>1) is also OK and is 0.
  3309. // * if both are not undef, and are different, bailout.
  3310. // * else, only one is undef, then pick the non-undef one.
  3311. // The shift amount must be equal.
  3312. if (*C0 != *C1)
  3313. return nullptr;
  3314. const APInt &MaskedBits = *C0;
  3315. assert(MaskedBits != 0 && "shift by zero should be folded away already.");
  3316. ICmpInst::Predicate DstPred;
  3317. switch (SrcPred) {
  3318. case ICmpInst::Predicate::ICMP_EQ:
  3319. // ((%x << MaskedBits) a>> MaskedBits) == %x
  3320. // =>
  3321. // (add %x, (1 << (KeptBits-1))) u< (1 << KeptBits)
  3322. DstPred = ICmpInst::Predicate::ICMP_ULT;
  3323. break;
  3324. case ICmpInst::Predicate::ICMP_NE:
  3325. // ((%x << MaskedBits) a>> MaskedBits) != %x
  3326. // =>
  3327. // (add %x, (1 << (KeptBits-1))) u>= (1 << KeptBits)
  3328. DstPred = ICmpInst::Predicate::ICMP_UGE;
  3329. break;
  3330. // FIXME: are more folds possible?
  3331. default:
  3332. return nullptr;
  3333. }
  3334. auto *XType = X->getType();
  3335. const unsigned XBitWidth = XType->getScalarSizeInBits();
  3336. const APInt BitWidth = APInt(XBitWidth, XBitWidth);
  3337. assert(BitWidth.ugt(MaskedBits) && "shifts should leave some bits untouched");
  3338. // KeptBits = bitwidth(%x) - MaskedBits
  3339. const APInt KeptBits = BitWidth - MaskedBits;
  3340. assert(KeptBits.ugt(0) && KeptBits.ult(BitWidth) && "unreachable");
  3341. // ICmpCst = (1 << KeptBits)
  3342. const APInt ICmpCst = APInt(XBitWidth, 1).shl(KeptBits);
  3343. assert(ICmpCst.isPowerOf2());
  3344. // AddCst = (1 << (KeptBits-1))
  3345. const APInt AddCst = ICmpCst.lshr(1);
  3346. assert(AddCst.ult(ICmpCst) && AddCst.isPowerOf2());
  3347. // T0 = add %x, AddCst
  3348. Value *T0 = Builder.CreateAdd(X, ConstantInt::get(XType, AddCst));
  3349. // T1 = T0 DstPred ICmpCst
  3350. Value *T1 = Builder.CreateICmp(DstPred, T0, ConstantInt::get(XType, ICmpCst));
  3351. return T1;
  3352. }
  3353. // Given pattern:
  3354. // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
  3355. // we should move shifts to the same hand of 'and', i.e. rewrite as
  3356. // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
  3357. // We are only interested in opposite logical shifts here.
  3358. // One of the shifts can be truncated.
  3359. // If we can, we want to end up creating 'lshr' shift.
  3360. static Value *
  3361. foldShiftIntoShiftInAnotherHandOfAndInICmp(ICmpInst &I, const SimplifyQuery SQ,
  3362. InstCombiner::BuilderTy &Builder) {
  3363. if (!I.isEquality() || !match(I.getOperand(1), m_Zero()) ||
  3364. !I.getOperand(0)->hasOneUse())
  3365. return nullptr;
  3366. auto m_AnyLogicalShift = m_LogicalShift(m_Value(), m_Value());
  3367. // Look for an 'and' of two logical shifts, one of which may be truncated.
  3368. // We use m_TruncOrSelf() on the RHS to correctly handle commutative case.
  3369. Instruction *XShift, *MaybeTruncation, *YShift;
  3370. if (!match(
  3371. I.getOperand(0),
  3372. m_c_And(m_CombineAnd(m_AnyLogicalShift, m_Instruction(XShift)),
  3373. m_CombineAnd(m_TruncOrSelf(m_CombineAnd(
  3374. m_AnyLogicalShift, m_Instruction(YShift))),
  3375. m_Instruction(MaybeTruncation)))))
  3376. return nullptr;
  3377. // We potentially looked past 'trunc', but only when matching YShift,
  3378. // therefore YShift must have the widest type.
  3379. Instruction *WidestShift = YShift;
  3380. // Therefore XShift must have the shallowest type.
  3381. // Or they both have identical types if there was no truncation.
  3382. Instruction *NarrowestShift = XShift;
  3383. Type *WidestTy = WidestShift->getType();
  3384. Type *NarrowestTy = NarrowestShift->getType();
  3385. assert(NarrowestTy == I.getOperand(0)->getType() &&
  3386. "We did not look past any shifts while matching XShift though.");
  3387. bool HadTrunc = WidestTy != I.getOperand(0)->getType();
  3388. // If YShift is a 'lshr', swap the shifts around.
  3389. if (match(YShift, m_LShr(m_Value(), m_Value())))
  3390. std::swap(XShift, YShift);
  3391. // The shifts must be in opposite directions.
  3392. auto XShiftOpcode = XShift->getOpcode();
  3393. if (XShiftOpcode == YShift->getOpcode())
  3394. return nullptr; // Do not care about same-direction shifts here.
  3395. Value *X, *XShAmt, *Y, *YShAmt;
  3396. match(XShift, m_BinOp(m_Value(X), m_ZExtOrSelf(m_Value(XShAmt))));
  3397. match(YShift, m_BinOp(m_Value(Y), m_ZExtOrSelf(m_Value(YShAmt))));
  3398. // If one of the values being shifted is a constant, then we will end with
  3399. // and+icmp, and [zext+]shift instrs will be constant-folded. If they are not,
  3400. // however, we will need to ensure that we won't increase instruction count.
  3401. if (!isa<Constant>(X) && !isa<Constant>(Y)) {
  3402. // At least one of the hands of the 'and' should be one-use shift.
  3403. if (!match(I.getOperand(0),
  3404. m_c_And(m_OneUse(m_AnyLogicalShift), m_Value())))
  3405. return nullptr;
  3406. if (HadTrunc) {
  3407. // Due to the 'trunc', we will need to widen X. For that either the old
  3408. // 'trunc' or the shift amt in the non-truncated shift should be one-use.
  3409. if (!MaybeTruncation->hasOneUse() &&
  3410. !NarrowestShift->getOperand(1)->hasOneUse())
  3411. return nullptr;
  3412. }
  3413. }
  3414. // We have two shift amounts from two different shifts. The types of those
  3415. // shift amounts may not match. If that's the case let's bailout now.
  3416. if (XShAmt->getType() != YShAmt->getType())
  3417. return nullptr;
  3418. // As input, we have the following pattern:
  3419. // icmp eq/ne (and ((x shift Q), (y oppositeshift K))), 0
  3420. // We want to rewrite that as:
  3421. // icmp eq/ne (and (x shift (Q+K)), y), 0 iff (Q+K) u< bitwidth(x)
  3422. // While we know that originally (Q+K) would not overflow
  3423. // (because 2 * (N-1) u<= iN -1), we have looked past extensions of
  3424. // shift amounts. so it may now overflow in smaller bitwidth.
  3425. // To ensure that does not happen, we need to ensure that the total maximal
  3426. // shift amount is still representable in that smaller bit width.
  3427. unsigned MaximalPossibleTotalShiftAmount =
  3428. (WidestTy->getScalarSizeInBits() - 1) +
  3429. (NarrowestTy->getScalarSizeInBits() - 1);
  3430. APInt MaximalRepresentableShiftAmount =
  3431. APInt::getAllOnes(XShAmt->getType()->getScalarSizeInBits());
  3432. if (MaximalRepresentableShiftAmount.ult(MaximalPossibleTotalShiftAmount))
  3433. return nullptr;
  3434. // Can we fold (XShAmt+YShAmt) ?
  3435. auto *NewShAmt = dyn_cast_or_null<Constant>(
  3436. simplifyAddInst(XShAmt, YShAmt, /*isNSW=*/false,
  3437. /*isNUW=*/false, SQ.getWithInstruction(&I)));
  3438. if (!NewShAmt)
  3439. return nullptr;
  3440. NewShAmt = ConstantExpr::getZExtOrBitCast(NewShAmt, WidestTy);
  3441. unsigned WidestBitWidth = WidestTy->getScalarSizeInBits();
  3442. // Is the new shift amount smaller than the bit width?
  3443. // FIXME: could also rely on ConstantRange.
  3444. if (!match(NewShAmt,
  3445. m_SpecificInt_ICMP(ICmpInst::Predicate::ICMP_ULT,
  3446. APInt(WidestBitWidth, WidestBitWidth))))
  3447. return nullptr;
  3448. // An extra legality check is needed if we had trunc-of-lshr.
  3449. if (HadTrunc && match(WidestShift, m_LShr(m_Value(), m_Value()))) {
  3450. auto CanFold = [NewShAmt, WidestBitWidth, NarrowestShift, SQ,
  3451. WidestShift]() {
  3452. // It isn't obvious whether it's worth it to analyze non-constants here.
  3453. // Also, let's basically give up on non-splat cases, pessimizing vectors.
  3454. // If *any* of these preconditions matches we can perform the fold.
  3455. Constant *NewShAmtSplat = NewShAmt->getType()->isVectorTy()
  3456. ? NewShAmt->getSplatValue()
  3457. : NewShAmt;
  3458. // If it's edge-case shift (by 0 or by WidestBitWidth-1) we can fold.
  3459. if (NewShAmtSplat &&
  3460. (NewShAmtSplat->isNullValue() ||
  3461. NewShAmtSplat->getUniqueInteger() == WidestBitWidth - 1))
  3462. return true;
  3463. // We consider *min* leading zeros so a single outlier
  3464. // blocks the transform as opposed to allowing it.
  3465. if (auto *C = dyn_cast<Constant>(NarrowestShift->getOperand(0))) {
  3466. KnownBits Known = computeKnownBits(C, SQ.DL);
  3467. unsigned MinLeadZero = Known.countMinLeadingZeros();
  3468. // If the value being shifted has at most lowest bit set we can fold.
  3469. unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
  3470. if (MaxActiveBits <= 1)
  3471. return true;
  3472. // Precondition: NewShAmt u<= countLeadingZeros(C)
  3473. if (NewShAmtSplat && NewShAmtSplat->getUniqueInteger().ule(MinLeadZero))
  3474. return true;
  3475. }
  3476. if (auto *C = dyn_cast<Constant>(WidestShift->getOperand(0))) {
  3477. KnownBits Known = computeKnownBits(C, SQ.DL);
  3478. unsigned MinLeadZero = Known.countMinLeadingZeros();
  3479. // If the value being shifted has at most lowest bit set we can fold.
  3480. unsigned MaxActiveBits = Known.getBitWidth() - MinLeadZero;
  3481. if (MaxActiveBits <= 1)
  3482. return true;
  3483. // Precondition: ((WidestBitWidth-1)-NewShAmt) u<= countLeadingZeros(C)
  3484. if (NewShAmtSplat) {
  3485. APInt AdjNewShAmt =
  3486. (WidestBitWidth - 1) - NewShAmtSplat->getUniqueInteger();
  3487. if (AdjNewShAmt.ule(MinLeadZero))
  3488. return true;
  3489. }
  3490. }
  3491. return false; // Can't tell if it's ok.
  3492. };
  3493. if (!CanFold())
  3494. return nullptr;
  3495. }
  3496. // All good, we can do this fold.
  3497. X = Builder.CreateZExt(X, WidestTy);
  3498. Y = Builder.CreateZExt(Y, WidestTy);
  3499. // The shift is the same that was for X.
  3500. Value *T0 = XShiftOpcode == Instruction::BinaryOps::LShr
  3501. ? Builder.CreateLShr(X, NewShAmt)
  3502. : Builder.CreateShl(X, NewShAmt);
  3503. Value *T1 = Builder.CreateAnd(T0, Y);
  3504. return Builder.CreateICmp(I.getPredicate(), T1,
  3505. Constant::getNullValue(WidestTy));
  3506. }
  3507. /// Fold
  3508. /// (-1 u/ x) u< y
  3509. /// ((x * y) ?/ x) != y
  3510. /// to
  3511. /// @llvm.?mul.with.overflow(x, y) plus extraction of overflow bit
  3512. /// Note that the comparison is commutative, while inverted (u>=, ==) predicate
  3513. /// will mean that we are looking for the opposite answer.
  3514. Value *InstCombinerImpl::foldMultiplicationOverflowCheck(ICmpInst &I) {
  3515. ICmpInst::Predicate Pred;
  3516. Value *X, *Y;
  3517. Instruction *Mul;
  3518. Instruction *Div;
  3519. bool NeedNegation;
  3520. // Look for: (-1 u/ x) u</u>= y
  3521. if (!I.isEquality() &&
  3522. match(&I, m_c_ICmp(Pred,
  3523. m_CombineAnd(m_OneUse(m_UDiv(m_AllOnes(), m_Value(X))),
  3524. m_Instruction(Div)),
  3525. m_Value(Y)))) {
  3526. Mul = nullptr;
  3527. // Are we checking that overflow does not happen, or does happen?
  3528. switch (Pred) {
  3529. case ICmpInst::Predicate::ICMP_ULT:
  3530. NeedNegation = false;
  3531. break; // OK
  3532. case ICmpInst::Predicate::ICMP_UGE:
  3533. NeedNegation = true;
  3534. break; // OK
  3535. default:
  3536. return nullptr; // Wrong predicate.
  3537. }
  3538. } else // Look for: ((x * y) / x) !=/== y
  3539. if (I.isEquality() &&
  3540. match(&I,
  3541. m_c_ICmp(Pred, m_Value(Y),
  3542. m_CombineAnd(
  3543. m_OneUse(m_IDiv(m_CombineAnd(m_c_Mul(m_Deferred(Y),
  3544. m_Value(X)),
  3545. m_Instruction(Mul)),
  3546. m_Deferred(X))),
  3547. m_Instruction(Div))))) {
  3548. NeedNegation = Pred == ICmpInst::Predicate::ICMP_EQ;
  3549. } else
  3550. return nullptr;
  3551. BuilderTy::InsertPointGuard Guard(Builder);
  3552. // If the pattern included (x * y), we'll want to insert new instructions
  3553. // right before that original multiplication so that we can replace it.
  3554. bool MulHadOtherUses = Mul && !Mul->hasOneUse();
  3555. if (MulHadOtherUses)
  3556. Builder.SetInsertPoint(Mul);
  3557. Function *F = Intrinsic::getDeclaration(I.getModule(),
  3558. Div->getOpcode() == Instruction::UDiv
  3559. ? Intrinsic::umul_with_overflow
  3560. : Intrinsic::smul_with_overflow,
  3561. X->getType());
  3562. CallInst *Call = Builder.CreateCall(F, {X, Y}, "mul");
  3563. // If the multiplication was used elsewhere, to ensure that we don't leave
  3564. // "duplicate" instructions, replace uses of that original multiplication
  3565. // with the multiplication result from the with.overflow intrinsic.
  3566. if (MulHadOtherUses)
  3567. replaceInstUsesWith(*Mul, Builder.CreateExtractValue(Call, 0, "mul.val"));
  3568. Value *Res = Builder.CreateExtractValue(Call, 1, "mul.ov");
  3569. if (NeedNegation) // This technically increases instruction count.
  3570. Res = Builder.CreateNot(Res, "mul.not.ov");
  3571. // If we replaced the mul, erase it. Do this after all uses of Builder,
  3572. // as the mul is used as insertion point.
  3573. if (MulHadOtherUses)
  3574. eraseInstFromFunction(*Mul);
  3575. return Res;
  3576. }
  3577. static Instruction *foldICmpXNegX(ICmpInst &I) {
  3578. CmpInst::Predicate Pred;
  3579. Value *X;
  3580. if (!match(&I, m_c_ICmp(Pred, m_NSWNeg(m_Value(X)), m_Deferred(X))))
  3581. return nullptr;
  3582. if (ICmpInst::isSigned(Pred))
  3583. Pred = ICmpInst::getSwappedPredicate(Pred);
  3584. else if (ICmpInst::isUnsigned(Pred))
  3585. Pred = ICmpInst::getSignedPredicate(Pred);
  3586. // else for equality-comparisons just keep the predicate.
  3587. return ICmpInst::Create(Instruction::ICmp, Pred, X,
  3588. Constant::getNullValue(X->getType()), I.getName());
  3589. }
  3590. /// Try to fold icmp (binop), X or icmp X, (binop).
  3591. /// TODO: A large part of this logic is duplicated in InstSimplify's
  3592. /// simplifyICmpWithBinOp(). We should be able to share that and avoid the code
  3593. /// duplication.
  3594. Instruction *InstCombinerImpl::foldICmpBinOp(ICmpInst &I,
  3595. const SimplifyQuery &SQ) {
  3596. const SimplifyQuery Q = SQ.getWithInstruction(&I);
  3597. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  3598. // Special logic for binary operators.
  3599. BinaryOperator *BO0 = dyn_cast<BinaryOperator>(Op0);
  3600. BinaryOperator *BO1 = dyn_cast<BinaryOperator>(Op1);
  3601. if (!BO0 && !BO1)
  3602. return nullptr;
  3603. if (Instruction *NewICmp = foldICmpXNegX(I))
  3604. return NewICmp;
  3605. const CmpInst::Predicate Pred = I.getPredicate();
  3606. Value *X;
  3607. // Convert add-with-unsigned-overflow comparisons into a 'not' with compare.
  3608. // (Op1 + X) u</u>= Op1 --> ~Op1 u</u>= X
  3609. if (match(Op0, m_OneUse(m_c_Add(m_Specific(Op1), m_Value(X)))) &&
  3610. (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
  3611. return new ICmpInst(Pred, Builder.CreateNot(Op1), X);
  3612. // Op0 u>/u<= (Op0 + X) --> X u>/u<= ~Op0
  3613. if (match(Op1, m_OneUse(m_c_Add(m_Specific(Op0), m_Value(X)))) &&
  3614. (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
  3615. return new ICmpInst(Pred, X, Builder.CreateNot(Op0));
  3616. {
  3617. // (Op1 + X) + C u</u>= Op1 --> ~C - X u</u>= Op1
  3618. Constant *C;
  3619. if (match(Op0, m_OneUse(m_Add(m_c_Add(m_Specific(Op1), m_Value(X)),
  3620. m_ImmConstant(C)))) &&
  3621. (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE)) {
  3622. Constant *C2 = ConstantExpr::getNot(C);
  3623. return new ICmpInst(Pred, Builder.CreateSub(C2, X), Op1);
  3624. }
  3625. // Op0 u>/u<= (Op0 + X) + C --> Op0 u>/u<= ~C - X
  3626. if (match(Op1, m_OneUse(m_Add(m_c_Add(m_Specific(Op0), m_Value(X)),
  3627. m_ImmConstant(C)))) &&
  3628. (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE)) {
  3629. Constant *C2 = ConstantExpr::getNot(C);
  3630. return new ICmpInst(Pred, Op0, Builder.CreateSub(C2, X));
  3631. }
  3632. }
  3633. {
  3634. // Similar to above: an unsigned overflow comparison may use offset + mask:
  3635. // ((Op1 + C) & C) u< Op1 --> Op1 != 0
  3636. // ((Op1 + C) & C) u>= Op1 --> Op1 == 0
  3637. // Op0 u> ((Op0 + C) & C) --> Op0 != 0
  3638. // Op0 u<= ((Op0 + C) & C) --> Op0 == 0
  3639. BinaryOperator *BO;
  3640. const APInt *C;
  3641. if ((Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE) &&
  3642. match(Op0, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
  3643. match(BO, m_Add(m_Specific(Op1), m_SpecificIntAllowUndef(*C)))) {
  3644. CmpInst::Predicate NewPred =
  3645. Pred == ICmpInst::ICMP_ULT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
  3646. Constant *Zero = ConstantInt::getNullValue(Op1->getType());
  3647. return new ICmpInst(NewPred, Op1, Zero);
  3648. }
  3649. if ((Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE) &&
  3650. match(Op1, m_And(m_BinOp(BO), m_LowBitMask(C))) &&
  3651. match(BO, m_Add(m_Specific(Op0), m_SpecificIntAllowUndef(*C)))) {
  3652. CmpInst::Predicate NewPred =
  3653. Pred == ICmpInst::ICMP_UGT ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
  3654. Constant *Zero = ConstantInt::getNullValue(Op1->getType());
  3655. return new ICmpInst(NewPred, Op0, Zero);
  3656. }
  3657. }
  3658. bool NoOp0WrapProblem = false, NoOp1WrapProblem = false;
  3659. if (BO0 && isa<OverflowingBinaryOperator>(BO0))
  3660. NoOp0WrapProblem =
  3661. ICmpInst::isEquality(Pred) ||
  3662. (CmpInst::isUnsigned(Pred) && BO0->hasNoUnsignedWrap()) ||
  3663. (CmpInst::isSigned(Pred) && BO0->hasNoSignedWrap());
  3664. if (BO1 && isa<OverflowingBinaryOperator>(BO1))
  3665. NoOp1WrapProblem =
  3666. ICmpInst::isEquality(Pred) ||
  3667. (CmpInst::isUnsigned(Pred) && BO1->hasNoUnsignedWrap()) ||
  3668. (CmpInst::isSigned(Pred) && BO1->hasNoSignedWrap());
  3669. // Analyze the case when either Op0 or Op1 is an add instruction.
  3670. // Op0 = A + B (or A and B are null); Op1 = C + D (or C and D are null).
  3671. Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
  3672. if (BO0 && BO0->getOpcode() == Instruction::Add) {
  3673. A = BO0->getOperand(0);
  3674. B = BO0->getOperand(1);
  3675. }
  3676. if (BO1 && BO1->getOpcode() == Instruction::Add) {
  3677. C = BO1->getOperand(0);
  3678. D = BO1->getOperand(1);
  3679. }
  3680. // icmp (A+B), A -> icmp B, 0 for equalities or if there is no overflow.
  3681. // icmp (A+B), B -> icmp A, 0 for equalities or if there is no overflow.
  3682. if ((A == Op1 || B == Op1) && NoOp0WrapProblem)
  3683. return new ICmpInst(Pred, A == Op1 ? B : A,
  3684. Constant::getNullValue(Op1->getType()));
  3685. // icmp C, (C+D) -> icmp 0, D for equalities or if there is no overflow.
  3686. // icmp D, (C+D) -> icmp 0, C for equalities or if there is no overflow.
  3687. if ((C == Op0 || D == Op0) && NoOp1WrapProblem)
  3688. return new ICmpInst(Pred, Constant::getNullValue(Op0->getType()),
  3689. C == Op0 ? D : C);
  3690. // icmp (A+B), (A+D) -> icmp B, D for equalities or if there is no overflow.
  3691. if (A && C && (A == C || A == D || B == C || B == D) && NoOp0WrapProblem &&
  3692. NoOp1WrapProblem) {
  3693. // Determine Y and Z in the form icmp (X+Y), (X+Z).
  3694. Value *Y, *Z;
  3695. if (A == C) {
  3696. // C + B == C + D -> B == D
  3697. Y = B;
  3698. Z = D;
  3699. } else if (A == D) {
  3700. // D + B == C + D -> B == C
  3701. Y = B;
  3702. Z = C;
  3703. } else if (B == C) {
  3704. // A + C == C + D -> A == D
  3705. Y = A;
  3706. Z = D;
  3707. } else {
  3708. assert(B == D);
  3709. // A + D == C + D -> A == C
  3710. Y = A;
  3711. Z = C;
  3712. }
  3713. return new ICmpInst(Pred, Y, Z);
  3714. }
  3715. // icmp slt (A + -1), Op1 -> icmp sle A, Op1
  3716. if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLT &&
  3717. match(B, m_AllOnes()))
  3718. return new ICmpInst(CmpInst::ICMP_SLE, A, Op1);
  3719. // icmp sge (A + -1), Op1 -> icmp sgt A, Op1
  3720. if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGE &&
  3721. match(B, m_AllOnes()))
  3722. return new ICmpInst(CmpInst::ICMP_SGT, A, Op1);
  3723. // icmp sle (A + 1), Op1 -> icmp slt A, Op1
  3724. if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SLE && match(B, m_One()))
  3725. return new ICmpInst(CmpInst::ICMP_SLT, A, Op1);
  3726. // icmp sgt (A + 1), Op1 -> icmp sge A, Op1
  3727. if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_SGT && match(B, m_One()))
  3728. return new ICmpInst(CmpInst::ICMP_SGE, A, Op1);
  3729. // icmp sgt Op0, (C + -1) -> icmp sge Op0, C
  3730. if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGT &&
  3731. match(D, m_AllOnes()))
  3732. return new ICmpInst(CmpInst::ICMP_SGE, Op0, C);
  3733. // icmp sle Op0, (C + -1) -> icmp slt Op0, C
  3734. if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLE &&
  3735. match(D, m_AllOnes()))
  3736. return new ICmpInst(CmpInst::ICMP_SLT, Op0, C);
  3737. // icmp sge Op0, (C + 1) -> icmp sgt Op0, C
  3738. if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SGE && match(D, m_One()))
  3739. return new ICmpInst(CmpInst::ICMP_SGT, Op0, C);
  3740. // icmp slt Op0, (C + 1) -> icmp sle Op0, C
  3741. if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_SLT && match(D, m_One()))
  3742. return new ICmpInst(CmpInst::ICMP_SLE, Op0, C);
  3743. // TODO: The subtraction-related identities shown below also hold, but
  3744. // canonicalization from (X -nuw 1) to (X + -1) means that the combinations
  3745. // wouldn't happen even if they were implemented.
  3746. //
  3747. // icmp ult (A - 1), Op1 -> icmp ule A, Op1
  3748. // icmp uge (A - 1), Op1 -> icmp ugt A, Op1
  3749. // icmp ugt Op0, (C - 1) -> icmp uge Op0, C
  3750. // icmp ule Op0, (C - 1) -> icmp ult Op0, C
  3751. // icmp ule (A + 1), Op0 -> icmp ult A, Op1
  3752. if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_ULE && match(B, m_One()))
  3753. return new ICmpInst(CmpInst::ICMP_ULT, A, Op1);
  3754. // icmp ugt (A + 1), Op0 -> icmp uge A, Op1
  3755. if (A && NoOp0WrapProblem && Pred == CmpInst::ICMP_UGT && match(B, m_One()))
  3756. return new ICmpInst(CmpInst::ICMP_UGE, A, Op1);
  3757. // icmp uge Op0, (C + 1) -> icmp ugt Op0, C
  3758. if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_UGE && match(D, m_One()))
  3759. return new ICmpInst(CmpInst::ICMP_UGT, Op0, C);
  3760. // icmp ult Op0, (C + 1) -> icmp ule Op0, C
  3761. if (C && NoOp1WrapProblem && Pred == CmpInst::ICMP_ULT && match(D, m_One()))
  3762. return new ICmpInst(CmpInst::ICMP_ULE, Op0, C);
  3763. // if C1 has greater magnitude than C2:
  3764. // icmp (A + C1), (C + C2) -> icmp (A + C3), C
  3765. // s.t. C3 = C1 - C2
  3766. //
  3767. // if C2 has greater magnitude than C1:
  3768. // icmp (A + C1), (C + C2) -> icmp A, (C + C3)
  3769. // s.t. C3 = C2 - C1
  3770. if (A && C && NoOp0WrapProblem && NoOp1WrapProblem &&
  3771. (BO0->hasOneUse() || BO1->hasOneUse()) && !I.isUnsigned()) {
  3772. const APInt *AP1, *AP2;
  3773. // TODO: Support non-uniform vectors.
  3774. // TODO: Allow undef passthrough if B AND D's element is undef.
  3775. if (match(B, m_APIntAllowUndef(AP1)) && match(D, m_APIntAllowUndef(AP2)) &&
  3776. AP1->isNegative() == AP2->isNegative()) {
  3777. APInt AP1Abs = AP1->abs();
  3778. APInt AP2Abs = AP2->abs();
  3779. if (AP1Abs.uge(AP2Abs)) {
  3780. APInt Diff = *AP1 - *AP2;
  3781. bool HasNUW = BO0->hasNoUnsignedWrap() && Diff.ule(*AP1);
  3782. bool HasNSW = BO0->hasNoSignedWrap();
  3783. Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
  3784. Value *NewAdd = Builder.CreateAdd(A, C3, "", HasNUW, HasNSW);
  3785. return new ICmpInst(Pred, NewAdd, C);
  3786. } else {
  3787. APInt Diff = *AP2 - *AP1;
  3788. bool HasNUW = BO1->hasNoUnsignedWrap() && Diff.ule(*AP2);
  3789. bool HasNSW = BO1->hasNoSignedWrap();
  3790. Constant *C3 = Constant::getIntegerValue(BO0->getType(), Diff);
  3791. Value *NewAdd = Builder.CreateAdd(C, C3, "", HasNUW, HasNSW);
  3792. return new ICmpInst(Pred, A, NewAdd);
  3793. }
  3794. }
  3795. Constant *Cst1, *Cst2;
  3796. if (match(B, m_ImmConstant(Cst1)) && match(D, m_ImmConstant(Cst2)) &&
  3797. ICmpInst::isEquality(Pred)) {
  3798. Constant *Diff = ConstantExpr::getSub(Cst2, Cst1);
  3799. Value *NewAdd = Builder.CreateAdd(C, Diff);
  3800. return new ICmpInst(Pred, A, NewAdd);
  3801. }
  3802. }
  3803. // Analyze the case when either Op0 or Op1 is a sub instruction.
  3804. // Op0 = A - B (or A and B are null); Op1 = C - D (or C and D are null).
  3805. A = nullptr;
  3806. B = nullptr;
  3807. C = nullptr;
  3808. D = nullptr;
  3809. if (BO0 && BO0->getOpcode() == Instruction::Sub) {
  3810. A = BO0->getOperand(0);
  3811. B = BO0->getOperand(1);
  3812. }
  3813. if (BO1 && BO1->getOpcode() == Instruction::Sub) {
  3814. C = BO1->getOperand(0);
  3815. D = BO1->getOperand(1);
  3816. }
  3817. // icmp (A-B), A -> icmp 0, B for equalities or if there is no overflow.
  3818. if (A == Op1 && NoOp0WrapProblem)
  3819. return new ICmpInst(Pred, Constant::getNullValue(Op1->getType()), B);
  3820. // icmp C, (C-D) -> icmp D, 0 for equalities or if there is no overflow.
  3821. if (C == Op0 && NoOp1WrapProblem)
  3822. return new ICmpInst(Pred, D, Constant::getNullValue(Op0->getType()));
  3823. // Convert sub-with-unsigned-overflow comparisons into a comparison of args.
  3824. // (A - B) u>/u<= A --> B u>/u<= A
  3825. if (A == Op1 && (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_ULE))
  3826. return new ICmpInst(Pred, B, A);
  3827. // C u</u>= (C - D) --> C u</u>= D
  3828. if (C == Op0 && (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_UGE))
  3829. return new ICmpInst(Pred, C, D);
  3830. // (A - B) u>=/u< A --> B u>/u<= A iff B != 0
  3831. if (A == Op1 && (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_ULT) &&
  3832. isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
  3833. return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), B, A);
  3834. // C u<=/u> (C - D) --> C u</u>= D iff B != 0
  3835. if (C == Op0 && (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_UGT) &&
  3836. isKnownNonZero(D, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
  3837. return new ICmpInst(CmpInst::getFlippedStrictnessPredicate(Pred), C, D);
  3838. // icmp (A-B), (C-B) -> icmp A, C for equalities or if there is no overflow.
  3839. if (B && D && B == D && NoOp0WrapProblem && NoOp1WrapProblem)
  3840. return new ICmpInst(Pred, A, C);
  3841. // icmp (A-B), (A-D) -> icmp D, B for equalities or if there is no overflow.
  3842. if (A && C && A == C && NoOp0WrapProblem && NoOp1WrapProblem)
  3843. return new ICmpInst(Pred, D, B);
  3844. // icmp (0-X) < cst --> x > -cst
  3845. if (NoOp0WrapProblem && ICmpInst::isSigned(Pred)) {
  3846. Value *X;
  3847. if (match(BO0, m_Neg(m_Value(X))))
  3848. if (Constant *RHSC = dyn_cast<Constant>(Op1))
  3849. if (RHSC->isNotMinSignedValue())
  3850. return new ICmpInst(I.getSwappedPredicate(), X,
  3851. ConstantExpr::getNeg(RHSC));
  3852. }
  3853. {
  3854. // Try to remove shared constant multiplier from equality comparison:
  3855. // X * C == Y * C (with no overflowing/aliasing) --> X == Y
  3856. Value *X, *Y;
  3857. const APInt *C;
  3858. if (match(Op0, m_Mul(m_Value(X), m_APInt(C))) && *C != 0 &&
  3859. match(Op1, m_Mul(m_Value(Y), m_SpecificInt(*C))) && I.isEquality())
  3860. if (!C->countTrailingZeros() ||
  3861. (BO0 && BO1 && BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap()) ||
  3862. (BO0 && BO1 && BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap()))
  3863. return new ICmpInst(Pred, X, Y);
  3864. }
  3865. BinaryOperator *SRem = nullptr;
  3866. // icmp (srem X, Y), Y
  3867. if (BO0 && BO0->getOpcode() == Instruction::SRem && Op1 == BO0->getOperand(1))
  3868. SRem = BO0;
  3869. // icmp Y, (srem X, Y)
  3870. else if (BO1 && BO1->getOpcode() == Instruction::SRem &&
  3871. Op0 == BO1->getOperand(1))
  3872. SRem = BO1;
  3873. if (SRem) {
  3874. // We don't check hasOneUse to avoid increasing register pressure because
  3875. // the value we use is the same value this instruction was already using.
  3876. switch (SRem == BO0 ? ICmpInst::getSwappedPredicate(Pred) : Pred) {
  3877. default:
  3878. break;
  3879. case ICmpInst::ICMP_EQ:
  3880. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  3881. case ICmpInst::ICMP_NE:
  3882. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  3883. case ICmpInst::ICMP_SGT:
  3884. case ICmpInst::ICMP_SGE:
  3885. return new ICmpInst(ICmpInst::ICMP_SGT, SRem->getOperand(1),
  3886. Constant::getAllOnesValue(SRem->getType()));
  3887. case ICmpInst::ICMP_SLT:
  3888. case ICmpInst::ICMP_SLE:
  3889. return new ICmpInst(ICmpInst::ICMP_SLT, SRem->getOperand(1),
  3890. Constant::getNullValue(SRem->getType()));
  3891. }
  3892. }
  3893. if (BO0 && BO1 && BO0->getOpcode() == BO1->getOpcode() && BO0->hasOneUse() &&
  3894. BO1->hasOneUse() && BO0->getOperand(1) == BO1->getOperand(1)) {
  3895. switch (BO0->getOpcode()) {
  3896. default:
  3897. break;
  3898. case Instruction::Add:
  3899. case Instruction::Sub:
  3900. case Instruction::Xor: {
  3901. if (I.isEquality()) // a+x icmp eq/ne b+x --> a icmp b
  3902. return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
  3903. const APInt *C;
  3904. if (match(BO0->getOperand(1), m_APInt(C))) {
  3905. // icmp u/s (a ^ signmask), (b ^ signmask) --> icmp s/u a, b
  3906. if (C->isSignMask()) {
  3907. ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
  3908. return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
  3909. }
  3910. // icmp u/s (a ^ maxsignval), (b ^ maxsignval) --> icmp s/u' a, b
  3911. if (BO0->getOpcode() == Instruction::Xor && C->isMaxSignedValue()) {
  3912. ICmpInst::Predicate NewPred = I.getFlippedSignednessPredicate();
  3913. NewPred = I.getSwappedPredicate(NewPred);
  3914. return new ICmpInst(NewPred, BO0->getOperand(0), BO1->getOperand(0));
  3915. }
  3916. }
  3917. break;
  3918. }
  3919. case Instruction::Mul: {
  3920. if (!I.isEquality())
  3921. break;
  3922. const APInt *C;
  3923. if (match(BO0->getOperand(1), m_APInt(C)) && !C->isZero() &&
  3924. !C->isOne()) {
  3925. // icmp eq/ne (X * C), (Y * C) --> icmp (X & Mask), (Y & Mask)
  3926. // Mask = -1 >> count-trailing-zeros(C).
  3927. if (unsigned TZs = C->countTrailingZeros()) {
  3928. Constant *Mask = ConstantInt::get(
  3929. BO0->getType(),
  3930. APInt::getLowBitsSet(C->getBitWidth(), C->getBitWidth() - TZs));
  3931. Value *And1 = Builder.CreateAnd(BO0->getOperand(0), Mask);
  3932. Value *And2 = Builder.CreateAnd(BO1->getOperand(0), Mask);
  3933. return new ICmpInst(Pred, And1, And2);
  3934. }
  3935. }
  3936. break;
  3937. }
  3938. case Instruction::UDiv:
  3939. case Instruction::LShr:
  3940. if (I.isSigned() || !BO0->isExact() || !BO1->isExact())
  3941. break;
  3942. return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
  3943. case Instruction::SDiv:
  3944. if (!I.isEquality() || !BO0->isExact() || !BO1->isExact())
  3945. break;
  3946. return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
  3947. case Instruction::AShr:
  3948. if (!BO0->isExact() || !BO1->isExact())
  3949. break;
  3950. return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
  3951. case Instruction::Shl: {
  3952. bool NUW = BO0->hasNoUnsignedWrap() && BO1->hasNoUnsignedWrap();
  3953. bool NSW = BO0->hasNoSignedWrap() && BO1->hasNoSignedWrap();
  3954. if (!NUW && !NSW)
  3955. break;
  3956. if (!NSW && I.isSigned())
  3957. break;
  3958. return new ICmpInst(Pred, BO0->getOperand(0), BO1->getOperand(0));
  3959. }
  3960. }
  3961. }
  3962. if (BO0) {
  3963. // Transform A & (L - 1) `ult` L --> L != 0
  3964. auto LSubOne = m_Add(m_Specific(Op1), m_AllOnes());
  3965. auto BitwiseAnd = m_c_And(m_Value(), LSubOne);
  3966. if (match(BO0, BitwiseAnd) && Pred == ICmpInst::ICMP_ULT) {
  3967. auto *Zero = Constant::getNullValue(BO0->getType());
  3968. return new ICmpInst(ICmpInst::ICMP_NE, Op1, Zero);
  3969. }
  3970. }
  3971. // For unsigned predicates / eq / ne:
  3972. // icmp pred (x << 1), x --> icmp getSignedPredicate(pred) x, 0
  3973. // icmp pred x, (x << 1) --> icmp getSignedPredicate(pred) 0, x
  3974. if (!ICmpInst::isSigned(Pred)) {
  3975. if (match(Op0, m_Shl(m_Specific(Op1), m_One())))
  3976. return new ICmpInst(ICmpInst::getSignedPredicate(Pred), Op1,
  3977. Constant::getNullValue(Op1->getType()));
  3978. else if (match(Op1, m_Shl(m_Specific(Op0), m_One())))
  3979. return new ICmpInst(ICmpInst::getSignedPredicate(Pred),
  3980. Constant::getNullValue(Op0->getType()), Op0);
  3981. }
  3982. if (Value *V = foldMultiplicationOverflowCheck(I))
  3983. return replaceInstUsesWith(I, V);
  3984. if (Value *V = foldICmpWithLowBitMaskedVal(I, Builder))
  3985. return replaceInstUsesWith(I, V);
  3986. if (Value *V = foldICmpWithTruncSignExtendedVal(I, Builder))
  3987. return replaceInstUsesWith(I, V);
  3988. if (Value *V = foldShiftIntoShiftInAnotherHandOfAndInICmp(I, SQ, Builder))
  3989. return replaceInstUsesWith(I, V);
  3990. return nullptr;
  3991. }
  3992. /// Fold icmp Pred min|max(X, Y), X.
  3993. static Instruction *foldICmpWithMinMax(ICmpInst &Cmp) {
  3994. ICmpInst::Predicate Pred = Cmp.getPredicate();
  3995. Value *Op0 = Cmp.getOperand(0);
  3996. Value *X = Cmp.getOperand(1);
  3997. // Canonicalize minimum or maximum operand to LHS of the icmp.
  3998. if (match(X, m_c_SMin(m_Specific(Op0), m_Value())) ||
  3999. match(X, m_c_SMax(m_Specific(Op0), m_Value())) ||
  4000. match(X, m_c_UMin(m_Specific(Op0), m_Value())) ||
  4001. match(X, m_c_UMax(m_Specific(Op0), m_Value()))) {
  4002. std::swap(Op0, X);
  4003. Pred = Cmp.getSwappedPredicate();
  4004. }
  4005. Value *Y;
  4006. if (match(Op0, m_c_SMin(m_Specific(X), m_Value(Y)))) {
  4007. // smin(X, Y) == X --> X s<= Y
  4008. // smin(X, Y) s>= X --> X s<= Y
  4009. if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SGE)
  4010. return new ICmpInst(ICmpInst::ICMP_SLE, X, Y);
  4011. // smin(X, Y) != X --> X s> Y
  4012. // smin(X, Y) s< X --> X s> Y
  4013. if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SLT)
  4014. return new ICmpInst(ICmpInst::ICMP_SGT, X, Y);
  4015. // These cases should be handled in InstSimplify:
  4016. // smin(X, Y) s<= X --> true
  4017. // smin(X, Y) s> X --> false
  4018. return nullptr;
  4019. }
  4020. if (match(Op0, m_c_SMax(m_Specific(X), m_Value(Y)))) {
  4021. // smax(X, Y) == X --> X s>= Y
  4022. // smax(X, Y) s<= X --> X s>= Y
  4023. if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_SLE)
  4024. return new ICmpInst(ICmpInst::ICMP_SGE, X, Y);
  4025. // smax(X, Y) != X --> X s< Y
  4026. // smax(X, Y) s> X --> X s< Y
  4027. if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_SGT)
  4028. return new ICmpInst(ICmpInst::ICMP_SLT, X, Y);
  4029. // These cases should be handled in InstSimplify:
  4030. // smax(X, Y) s>= X --> true
  4031. // smax(X, Y) s< X --> false
  4032. return nullptr;
  4033. }
  4034. if (match(Op0, m_c_UMin(m_Specific(X), m_Value(Y)))) {
  4035. // umin(X, Y) == X --> X u<= Y
  4036. // umin(X, Y) u>= X --> X u<= Y
  4037. if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_UGE)
  4038. return new ICmpInst(ICmpInst::ICMP_ULE, X, Y);
  4039. // umin(X, Y) != X --> X u> Y
  4040. // umin(X, Y) u< X --> X u> Y
  4041. if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_ULT)
  4042. return new ICmpInst(ICmpInst::ICMP_UGT, X, Y);
  4043. // These cases should be handled in InstSimplify:
  4044. // umin(X, Y) u<= X --> true
  4045. // umin(X, Y) u> X --> false
  4046. return nullptr;
  4047. }
  4048. if (match(Op0, m_c_UMax(m_Specific(X), m_Value(Y)))) {
  4049. // umax(X, Y) == X --> X u>= Y
  4050. // umax(X, Y) u<= X --> X u>= Y
  4051. if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_ULE)
  4052. return new ICmpInst(ICmpInst::ICMP_UGE, X, Y);
  4053. // umax(X, Y) != X --> X u< Y
  4054. // umax(X, Y) u> X --> X u< Y
  4055. if (Pred == CmpInst::ICMP_NE || Pred == CmpInst::ICMP_UGT)
  4056. return new ICmpInst(ICmpInst::ICMP_ULT, X, Y);
  4057. // These cases should be handled in InstSimplify:
  4058. // umax(X, Y) u>= X --> true
  4059. // umax(X, Y) u< X --> false
  4060. return nullptr;
  4061. }
  4062. return nullptr;
  4063. }
  4064. Instruction *InstCombinerImpl::foldICmpEquality(ICmpInst &I) {
  4065. if (!I.isEquality())
  4066. return nullptr;
  4067. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  4068. const CmpInst::Predicate Pred = I.getPredicate();
  4069. Value *A, *B, *C, *D;
  4070. if (match(Op0, m_Xor(m_Value(A), m_Value(B)))) {
  4071. if (A == Op1 || B == Op1) { // (A^B) == A -> B == 0
  4072. Value *OtherVal = A == Op1 ? B : A;
  4073. return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
  4074. }
  4075. if (match(Op1, m_Xor(m_Value(C), m_Value(D)))) {
  4076. // A^c1 == C^c2 --> A == C^(c1^c2)
  4077. ConstantInt *C1, *C2;
  4078. if (match(B, m_ConstantInt(C1)) && match(D, m_ConstantInt(C2)) &&
  4079. Op1->hasOneUse()) {
  4080. Constant *NC = Builder.getInt(C1->getValue() ^ C2->getValue());
  4081. Value *Xor = Builder.CreateXor(C, NC);
  4082. return new ICmpInst(Pred, A, Xor);
  4083. }
  4084. // A^B == A^D -> B == D
  4085. if (A == C)
  4086. return new ICmpInst(Pred, B, D);
  4087. if (A == D)
  4088. return new ICmpInst(Pred, B, C);
  4089. if (B == C)
  4090. return new ICmpInst(Pred, A, D);
  4091. if (B == D)
  4092. return new ICmpInst(Pred, A, C);
  4093. }
  4094. }
  4095. if (match(Op1, m_Xor(m_Value(A), m_Value(B))) && (A == Op0 || B == Op0)) {
  4096. // A == (A^B) -> B == 0
  4097. Value *OtherVal = A == Op0 ? B : A;
  4098. return new ICmpInst(Pred, OtherVal, Constant::getNullValue(A->getType()));
  4099. }
  4100. // (X&Z) == (Y&Z) -> (X^Y) & Z == 0
  4101. if (match(Op0, m_OneUse(m_And(m_Value(A), m_Value(B)))) &&
  4102. match(Op1, m_OneUse(m_And(m_Value(C), m_Value(D))))) {
  4103. Value *X = nullptr, *Y = nullptr, *Z = nullptr;
  4104. if (A == C) {
  4105. X = B;
  4106. Y = D;
  4107. Z = A;
  4108. } else if (A == D) {
  4109. X = B;
  4110. Y = C;
  4111. Z = A;
  4112. } else if (B == C) {
  4113. X = A;
  4114. Y = D;
  4115. Z = B;
  4116. } else if (B == D) {
  4117. X = A;
  4118. Y = C;
  4119. Z = B;
  4120. }
  4121. if (X) { // Build (X^Y) & Z
  4122. Op1 = Builder.CreateXor(X, Y);
  4123. Op1 = Builder.CreateAnd(Op1, Z);
  4124. return new ICmpInst(Pred, Op1, Constant::getNullValue(Op1->getType()));
  4125. }
  4126. }
  4127. {
  4128. // Similar to above, but specialized for constant because invert is needed:
  4129. // (X | C) == (Y | C) --> (X ^ Y) & ~C == 0
  4130. Value *X, *Y;
  4131. Constant *C;
  4132. if (match(Op0, m_OneUse(m_Or(m_Value(X), m_Constant(C)))) &&
  4133. match(Op1, m_OneUse(m_Or(m_Value(Y), m_Specific(C))))) {
  4134. Value *Xor = Builder.CreateXor(X, Y);
  4135. Value *And = Builder.CreateAnd(Xor, ConstantExpr::getNot(C));
  4136. return new ICmpInst(Pred, And, Constant::getNullValue(And->getType()));
  4137. }
  4138. }
  4139. if (match(Op1, m_ZExt(m_Value(A))) &&
  4140. (Op0->hasOneUse() || Op1->hasOneUse())) {
  4141. // (B & (Pow2C-1)) == zext A --> A == trunc B
  4142. // (B & (Pow2C-1)) != zext A --> A != trunc B
  4143. const APInt *MaskC;
  4144. if (match(Op0, m_And(m_Value(B), m_LowBitMask(MaskC))) &&
  4145. MaskC->countTrailingOnes() == A->getType()->getScalarSizeInBits())
  4146. return new ICmpInst(Pred, A, Builder.CreateTrunc(B, A->getType()));
  4147. // Test if 2 values have different or same signbits:
  4148. // (X u>> BitWidth - 1) == zext (Y s> -1) --> (X ^ Y) < 0
  4149. // (X u>> BitWidth - 1) != zext (Y s> -1) --> (X ^ Y) > -1
  4150. unsigned OpWidth = Op0->getType()->getScalarSizeInBits();
  4151. Value *X, *Y;
  4152. ICmpInst::Predicate Pred2;
  4153. if (match(Op0, m_LShr(m_Value(X), m_SpecificIntAllowUndef(OpWidth - 1))) &&
  4154. match(A, m_ICmp(Pred2, m_Value(Y), m_AllOnes())) &&
  4155. Pred2 == ICmpInst::ICMP_SGT && X->getType() == Y->getType()) {
  4156. Value *Xor = Builder.CreateXor(X, Y, "xor.signbits");
  4157. Value *R = (Pred == ICmpInst::ICMP_EQ) ? Builder.CreateIsNeg(Xor) :
  4158. Builder.CreateIsNotNeg(Xor);
  4159. return replaceInstUsesWith(I, R);
  4160. }
  4161. }
  4162. // (A >> C) == (B >> C) --> (A^B) u< (1 << C)
  4163. // For lshr and ashr pairs.
  4164. const APInt *AP1, *AP2;
  4165. if ((match(Op0, m_OneUse(m_LShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
  4166. match(Op1, m_OneUse(m_LShr(m_Value(B), m_APIntAllowUndef(AP2))))) ||
  4167. (match(Op0, m_OneUse(m_AShr(m_Value(A), m_APIntAllowUndef(AP1)))) &&
  4168. match(Op1, m_OneUse(m_AShr(m_Value(B), m_APIntAllowUndef(AP2)))))) {
  4169. if (AP1 != AP2)
  4170. return nullptr;
  4171. unsigned TypeBits = AP1->getBitWidth();
  4172. unsigned ShAmt = AP1->getLimitedValue(TypeBits);
  4173. if (ShAmt < TypeBits && ShAmt != 0) {
  4174. ICmpInst::Predicate NewPred =
  4175. Pred == ICmpInst::ICMP_NE ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_ULT;
  4176. Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
  4177. APInt CmpVal = APInt::getOneBitSet(TypeBits, ShAmt);
  4178. return new ICmpInst(NewPred, Xor, ConstantInt::get(A->getType(), CmpVal));
  4179. }
  4180. }
  4181. // (A << C) == (B << C) --> ((A^B) & (~0U >> C)) == 0
  4182. ConstantInt *Cst1;
  4183. if (match(Op0, m_OneUse(m_Shl(m_Value(A), m_ConstantInt(Cst1)))) &&
  4184. match(Op1, m_OneUse(m_Shl(m_Value(B), m_Specific(Cst1))))) {
  4185. unsigned TypeBits = Cst1->getBitWidth();
  4186. unsigned ShAmt = (unsigned)Cst1->getLimitedValue(TypeBits);
  4187. if (ShAmt < TypeBits && ShAmt != 0) {
  4188. Value *Xor = Builder.CreateXor(A, B, I.getName() + ".unshifted");
  4189. APInt AndVal = APInt::getLowBitsSet(TypeBits, TypeBits - ShAmt);
  4190. Value *And = Builder.CreateAnd(Xor, Builder.getInt(AndVal),
  4191. I.getName() + ".mask");
  4192. return new ICmpInst(Pred, And, Constant::getNullValue(Cst1->getType()));
  4193. }
  4194. }
  4195. // Transform "icmp eq (trunc (lshr(X, cst1)), cst" to
  4196. // "icmp (and X, mask), cst"
  4197. uint64_t ShAmt = 0;
  4198. if (Op0->hasOneUse() &&
  4199. match(Op0, m_Trunc(m_OneUse(m_LShr(m_Value(A), m_ConstantInt(ShAmt))))) &&
  4200. match(Op1, m_ConstantInt(Cst1)) &&
  4201. // Only do this when A has multiple uses. This is most important to do
  4202. // when it exposes other optimizations.
  4203. !A->hasOneUse()) {
  4204. unsigned ASize = cast<IntegerType>(A->getType())->getPrimitiveSizeInBits();
  4205. if (ShAmt < ASize) {
  4206. APInt MaskV =
  4207. APInt::getLowBitsSet(ASize, Op0->getType()->getPrimitiveSizeInBits());
  4208. MaskV <<= ShAmt;
  4209. APInt CmpV = Cst1->getValue().zext(ASize);
  4210. CmpV <<= ShAmt;
  4211. Value *Mask = Builder.CreateAnd(A, Builder.getInt(MaskV));
  4212. return new ICmpInst(Pred, Mask, Builder.getInt(CmpV));
  4213. }
  4214. }
  4215. if (Instruction *ICmp = foldICmpIntrinsicWithIntrinsic(I))
  4216. return ICmp;
  4217. // Canonicalize checking for a power-of-2-or-zero value:
  4218. // (A & (A-1)) == 0 --> ctpop(A) < 2 (two commuted variants)
  4219. // ((A-1) & A) != 0 --> ctpop(A) > 1 (two commuted variants)
  4220. if (!match(Op0, m_OneUse(m_c_And(m_Add(m_Value(A), m_AllOnes()),
  4221. m_Deferred(A)))) ||
  4222. !match(Op1, m_ZeroInt()))
  4223. A = nullptr;
  4224. // (A & -A) == A --> ctpop(A) < 2 (four commuted variants)
  4225. // (-A & A) != A --> ctpop(A) > 1 (four commuted variants)
  4226. if (match(Op0, m_OneUse(m_c_And(m_Neg(m_Specific(Op1)), m_Specific(Op1)))))
  4227. A = Op1;
  4228. else if (match(Op1,
  4229. m_OneUse(m_c_And(m_Neg(m_Specific(Op0)), m_Specific(Op0)))))
  4230. A = Op0;
  4231. if (A) {
  4232. Type *Ty = A->getType();
  4233. CallInst *CtPop = Builder.CreateUnaryIntrinsic(Intrinsic::ctpop, A);
  4234. return Pred == ICmpInst::ICMP_EQ
  4235. ? new ICmpInst(ICmpInst::ICMP_ULT, CtPop, ConstantInt::get(Ty, 2))
  4236. : new ICmpInst(ICmpInst::ICMP_UGT, CtPop, ConstantInt::get(Ty, 1));
  4237. }
  4238. // Match icmp eq (trunc (lshr A, BW), (ashr (trunc A), BW-1)), which checks the
  4239. // top BW/2 + 1 bits are all the same. Create "A >=s INT_MIN && A <=s INT_MAX",
  4240. // which we generate as "icmp ult (add A, 2^(BW-1)), 2^BW" to skip a few steps
  4241. // of instcombine.
  4242. unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
  4243. if (match(Op0, m_AShr(m_Trunc(m_Value(A)), m_SpecificInt(BitWidth - 1))) &&
  4244. match(Op1, m_Trunc(m_LShr(m_Specific(A), m_SpecificInt(BitWidth)))) &&
  4245. A->getType()->getScalarSizeInBits() == BitWidth * 2 &&
  4246. (I.getOperand(0)->hasOneUse() || I.getOperand(1)->hasOneUse())) {
  4247. APInt C = APInt::getOneBitSet(BitWidth * 2, BitWidth - 1);
  4248. Value *Add = Builder.CreateAdd(A, ConstantInt::get(A->getType(), C));
  4249. return new ICmpInst(Pred == ICmpInst::ICMP_EQ ? ICmpInst::ICMP_ULT
  4250. : ICmpInst::ICMP_UGE,
  4251. Add, ConstantInt::get(A->getType(), C.shl(1)));
  4252. }
  4253. // Canonicalize:
  4254. // Assume B_Pow2 != 0
  4255. // 1. A & B_Pow2 != B_Pow2 -> A & B_Pow2 == 0
  4256. // 2. A & B_Pow2 == B_Pow2 -> A & B_Pow2 != 0
  4257. if (match(Op0, m_c_And(m_Specific(Op1), m_Value())) &&
  4258. isKnownToBeAPowerOfTwo(Op1, /* OrZero */ false, 0, &I))
  4259. return new ICmpInst(CmpInst::getInversePredicate(Pred), Op0,
  4260. ConstantInt::getNullValue(Op0->getType()));
  4261. if (match(Op1, m_c_And(m_Specific(Op0), m_Value())) &&
  4262. isKnownToBeAPowerOfTwo(Op0, /* OrZero */ false, 0, &I))
  4263. return new ICmpInst(CmpInst::getInversePredicate(Pred), Op1,
  4264. ConstantInt::getNullValue(Op1->getType()));
  4265. return nullptr;
  4266. }
  4267. static Instruction *foldICmpWithTrunc(ICmpInst &ICmp,
  4268. InstCombiner::BuilderTy &Builder) {
  4269. ICmpInst::Predicate Pred = ICmp.getPredicate();
  4270. Value *Op0 = ICmp.getOperand(0), *Op1 = ICmp.getOperand(1);
  4271. // Try to canonicalize trunc + compare-to-constant into a mask + cmp.
  4272. // The trunc masks high bits while the compare may effectively mask low bits.
  4273. Value *X;
  4274. const APInt *C;
  4275. if (!match(Op0, m_OneUse(m_Trunc(m_Value(X)))) || !match(Op1, m_APInt(C)))
  4276. return nullptr;
  4277. // This matches patterns corresponding to tests of the signbit as well as:
  4278. // (trunc X) u< C --> (X & -C) == 0 (are all masked-high-bits clear?)
  4279. // (trunc X) u> C --> (X & ~C) != 0 (are any masked-high-bits set?)
  4280. APInt Mask;
  4281. if (decomposeBitTestICmp(Op0, Op1, Pred, X, Mask, true /* WithTrunc */)) {
  4282. Value *And = Builder.CreateAnd(X, Mask);
  4283. Constant *Zero = ConstantInt::getNullValue(X->getType());
  4284. return new ICmpInst(Pred, And, Zero);
  4285. }
  4286. unsigned SrcBits = X->getType()->getScalarSizeInBits();
  4287. if (Pred == ICmpInst::ICMP_ULT && C->isNegatedPowerOf2()) {
  4288. // If C is a negative power-of-2 (high-bit mask):
  4289. // (trunc X) u< C --> (X & C) != C (are any masked-high-bits clear?)
  4290. Constant *MaskC = ConstantInt::get(X->getType(), C->zext(SrcBits));
  4291. Value *And = Builder.CreateAnd(X, MaskC);
  4292. return new ICmpInst(ICmpInst::ICMP_NE, And, MaskC);
  4293. }
  4294. if (Pred == ICmpInst::ICMP_UGT && (~*C).isPowerOf2()) {
  4295. // If C is not-of-power-of-2 (one clear bit):
  4296. // (trunc X) u> C --> (X & (C+1)) == C+1 (are all masked-high-bits set?)
  4297. Constant *MaskC = ConstantInt::get(X->getType(), (*C + 1).zext(SrcBits));
  4298. Value *And = Builder.CreateAnd(X, MaskC);
  4299. return new ICmpInst(ICmpInst::ICMP_EQ, And, MaskC);
  4300. }
  4301. return nullptr;
  4302. }
  4303. Instruction *InstCombinerImpl::foldICmpWithZextOrSext(ICmpInst &ICmp) {
  4304. assert(isa<CastInst>(ICmp.getOperand(0)) && "Expected cast for operand 0");
  4305. auto *CastOp0 = cast<CastInst>(ICmp.getOperand(0));
  4306. Value *X;
  4307. if (!match(CastOp0, m_ZExtOrSExt(m_Value(X))))
  4308. return nullptr;
  4309. bool IsSignedExt = CastOp0->getOpcode() == Instruction::SExt;
  4310. bool IsSignedCmp = ICmp.isSigned();
  4311. // icmp Pred (ext X), (ext Y)
  4312. Value *Y;
  4313. if (match(ICmp.getOperand(1), m_ZExtOrSExt(m_Value(Y)))) {
  4314. bool IsZext0 = isa<ZExtOperator>(ICmp.getOperand(0));
  4315. bool IsZext1 = isa<ZExtOperator>(ICmp.getOperand(1));
  4316. // If we have mismatched casts, treat the zext of a non-negative source as
  4317. // a sext to simulate matching casts. Otherwise, we are done.
  4318. // TODO: Can we handle some predicates (equality) without non-negative?
  4319. if (IsZext0 != IsZext1) {
  4320. if ((IsZext0 && isKnownNonNegative(X, DL, 0, &AC, &ICmp, &DT)) ||
  4321. (IsZext1 && isKnownNonNegative(Y, DL, 0, &AC, &ICmp, &DT)))
  4322. IsSignedExt = true;
  4323. else
  4324. return nullptr;
  4325. }
  4326. // Not an extension from the same type?
  4327. Type *XTy = X->getType(), *YTy = Y->getType();
  4328. if (XTy != YTy) {
  4329. // One of the casts must have one use because we are creating a new cast.
  4330. if (!ICmp.getOperand(0)->hasOneUse() && !ICmp.getOperand(1)->hasOneUse())
  4331. return nullptr;
  4332. // Extend the narrower operand to the type of the wider operand.
  4333. CastInst::CastOps CastOpcode =
  4334. IsSignedExt ? Instruction::SExt : Instruction::ZExt;
  4335. if (XTy->getScalarSizeInBits() < YTy->getScalarSizeInBits())
  4336. X = Builder.CreateCast(CastOpcode, X, YTy);
  4337. else if (YTy->getScalarSizeInBits() < XTy->getScalarSizeInBits())
  4338. Y = Builder.CreateCast(CastOpcode, Y, XTy);
  4339. else
  4340. return nullptr;
  4341. }
  4342. // (zext X) == (zext Y) --> X == Y
  4343. // (sext X) == (sext Y) --> X == Y
  4344. if (ICmp.isEquality())
  4345. return new ICmpInst(ICmp.getPredicate(), X, Y);
  4346. // A signed comparison of sign extended values simplifies into a
  4347. // signed comparison.
  4348. if (IsSignedCmp && IsSignedExt)
  4349. return new ICmpInst(ICmp.getPredicate(), X, Y);
  4350. // The other three cases all fold into an unsigned comparison.
  4351. return new ICmpInst(ICmp.getUnsignedPredicate(), X, Y);
  4352. }
  4353. // Below here, we are only folding a compare with constant.
  4354. auto *C = dyn_cast<Constant>(ICmp.getOperand(1));
  4355. if (!C)
  4356. return nullptr;
  4357. // Compute the constant that would happen if we truncated to SrcTy then
  4358. // re-extended to DestTy.
  4359. Type *SrcTy = CastOp0->getSrcTy();
  4360. Type *DestTy = CastOp0->getDestTy();
  4361. Constant *Res1 = ConstantExpr::getTrunc(C, SrcTy);
  4362. Constant *Res2 = ConstantExpr::getCast(CastOp0->getOpcode(), Res1, DestTy);
  4363. // If the re-extended constant didn't change...
  4364. if (Res2 == C) {
  4365. if (ICmp.isEquality())
  4366. return new ICmpInst(ICmp.getPredicate(), X, Res1);
  4367. // A signed comparison of sign extended values simplifies into a
  4368. // signed comparison.
  4369. if (IsSignedExt && IsSignedCmp)
  4370. return new ICmpInst(ICmp.getPredicate(), X, Res1);
  4371. // The other three cases all fold into an unsigned comparison.
  4372. return new ICmpInst(ICmp.getUnsignedPredicate(), X, Res1);
  4373. }
  4374. // The re-extended constant changed, partly changed (in the case of a vector),
  4375. // or could not be determined to be equal (in the case of a constant
  4376. // expression), so the constant cannot be represented in the shorter type.
  4377. // All the cases that fold to true or false will have already been handled
  4378. // by simplifyICmpInst, so only deal with the tricky case.
  4379. if (IsSignedCmp || !IsSignedExt || !isa<ConstantInt>(C))
  4380. return nullptr;
  4381. // Is source op positive?
  4382. // icmp ult (sext X), C --> icmp sgt X, -1
  4383. if (ICmp.getPredicate() == ICmpInst::ICMP_ULT)
  4384. return new ICmpInst(CmpInst::ICMP_SGT, X, Constant::getAllOnesValue(SrcTy));
  4385. // Is source op negative?
  4386. // icmp ugt (sext X), C --> icmp slt X, 0
  4387. assert(ICmp.getPredicate() == ICmpInst::ICMP_UGT && "ICmp should be folded!");
  4388. return new ICmpInst(CmpInst::ICMP_SLT, X, Constant::getNullValue(SrcTy));
  4389. }
  4390. /// Handle icmp (cast x), (cast or constant).
  4391. Instruction *InstCombinerImpl::foldICmpWithCastOp(ICmpInst &ICmp) {
  4392. // If any operand of ICmp is a inttoptr roundtrip cast then remove it as
  4393. // icmp compares only pointer's value.
  4394. // icmp (inttoptr (ptrtoint p1)), p2 --> icmp p1, p2.
  4395. Value *SimplifiedOp0 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(0));
  4396. Value *SimplifiedOp1 = simplifyIntToPtrRoundTripCast(ICmp.getOperand(1));
  4397. if (SimplifiedOp0 || SimplifiedOp1)
  4398. return new ICmpInst(ICmp.getPredicate(),
  4399. SimplifiedOp0 ? SimplifiedOp0 : ICmp.getOperand(0),
  4400. SimplifiedOp1 ? SimplifiedOp1 : ICmp.getOperand(1));
  4401. auto *CastOp0 = dyn_cast<CastInst>(ICmp.getOperand(0));
  4402. if (!CastOp0)
  4403. return nullptr;
  4404. if (!isa<Constant>(ICmp.getOperand(1)) && !isa<CastInst>(ICmp.getOperand(1)))
  4405. return nullptr;
  4406. Value *Op0Src = CastOp0->getOperand(0);
  4407. Type *SrcTy = CastOp0->getSrcTy();
  4408. Type *DestTy = CastOp0->getDestTy();
  4409. // Turn icmp (ptrtoint x), (ptrtoint/c) into a compare of the input if the
  4410. // integer type is the same size as the pointer type.
  4411. auto CompatibleSizes = [&](Type *SrcTy, Type *DestTy) {
  4412. if (isa<VectorType>(SrcTy)) {
  4413. SrcTy = cast<VectorType>(SrcTy)->getElementType();
  4414. DestTy = cast<VectorType>(DestTy)->getElementType();
  4415. }
  4416. return DL.getPointerTypeSizeInBits(SrcTy) == DestTy->getIntegerBitWidth();
  4417. };
  4418. if (CastOp0->getOpcode() == Instruction::PtrToInt &&
  4419. CompatibleSizes(SrcTy, DestTy)) {
  4420. Value *NewOp1 = nullptr;
  4421. if (auto *PtrToIntOp1 = dyn_cast<PtrToIntOperator>(ICmp.getOperand(1))) {
  4422. Value *PtrSrc = PtrToIntOp1->getOperand(0);
  4423. if (PtrSrc->getType()->getPointerAddressSpace() ==
  4424. Op0Src->getType()->getPointerAddressSpace()) {
  4425. NewOp1 = PtrToIntOp1->getOperand(0);
  4426. // If the pointer types don't match, insert a bitcast.
  4427. if (Op0Src->getType() != NewOp1->getType())
  4428. NewOp1 = Builder.CreateBitCast(NewOp1, Op0Src->getType());
  4429. }
  4430. } else if (auto *RHSC = dyn_cast<Constant>(ICmp.getOperand(1))) {
  4431. NewOp1 = ConstantExpr::getIntToPtr(RHSC, SrcTy);
  4432. }
  4433. if (NewOp1)
  4434. return new ICmpInst(ICmp.getPredicate(), Op0Src, NewOp1);
  4435. }
  4436. if (Instruction *R = foldICmpWithTrunc(ICmp, Builder))
  4437. return R;
  4438. return foldICmpWithZextOrSext(ICmp);
  4439. }
  4440. static bool isNeutralValue(Instruction::BinaryOps BinaryOp, Value *RHS, bool IsSigned) {
  4441. switch (BinaryOp) {
  4442. default:
  4443. llvm_unreachable("Unsupported binary op");
  4444. case Instruction::Add:
  4445. case Instruction::Sub:
  4446. return match(RHS, m_Zero());
  4447. case Instruction::Mul:
  4448. return !(RHS->getType()->isIntOrIntVectorTy(1) && IsSigned) &&
  4449. match(RHS, m_One());
  4450. }
  4451. }
  4452. OverflowResult
  4453. InstCombinerImpl::computeOverflow(Instruction::BinaryOps BinaryOp,
  4454. bool IsSigned, Value *LHS, Value *RHS,
  4455. Instruction *CxtI) const {
  4456. switch (BinaryOp) {
  4457. default:
  4458. llvm_unreachable("Unsupported binary op");
  4459. case Instruction::Add:
  4460. if (IsSigned)
  4461. return computeOverflowForSignedAdd(LHS, RHS, CxtI);
  4462. else
  4463. return computeOverflowForUnsignedAdd(LHS, RHS, CxtI);
  4464. case Instruction::Sub:
  4465. if (IsSigned)
  4466. return computeOverflowForSignedSub(LHS, RHS, CxtI);
  4467. else
  4468. return computeOverflowForUnsignedSub(LHS, RHS, CxtI);
  4469. case Instruction::Mul:
  4470. if (IsSigned)
  4471. return computeOverflowForSignedMul(LHS, RHS, CxtI);
  4472. else
  4473. return computeOverflowForUnsignedMul(LHS, RHS, CxtI);
  4474. }
  4475. }
  4476. bool InstCombinerImpl::OptimizeOverflowCheck(Instruction::BinaryOps BinaryOp,
  4477. bool IsSigned, Value *LHS,
  4478. Value *RHS, Instruction &OrigI,
  4479. Value *&Result,
  4480. Constant *&Overflow) {
  4481. if (OrigI.isCommutative() && isa<Constant>(LHS) && !isa<Constant>(RHS))
  4482. std::swap(LHS, RHS);
  4483. // If the overflow check was an add followed by a compare, the insertion point
  4484. // may be pointing to the compare. We want to insert the new instructions
  4485. // before the add in case there are uses of the add between the add and the
  4486. // compare.
  4487. Builder.SetInsertPoint(&OrigI);
  4488. Type *OverflowTy = Type::getInt1Ty(LHS->getContext());
  4489. if (auto *LHSTy = dyn_cast<VectorType>(LHS->getType()))
  4490. OverflowTy = VectorType::get(OverflowTy, LHSTy->getElementCount());
  4491. if (isNeutralValue(BinaryOp, RHS, IsSigned)) {
  4492. Result = LHS;
  4493. Overflow = ConstantInt::getFalse(OverflowTy);
  4494. return true;
  4495. }
  4496. switch (computeOverflow(BinaryOp, IsSigned, LHS, RHS, &OrigI)) {
  4497. case OverflowResult::MayOverflow:
  4498. return false;
  4499. case OverflowResult::AlwaysOverflowsLow:
  4500. case OverflowResult::AlwaysOverflowsHigh:
  4501. Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
  4502. Result->takeName(&OrigI);
  4503. Overflow = ConstantInt::getTrue(OverflowTy);
  4504. return true;
  4505. case OverflowResult::NeverOverflows:
  4506. Result = Builder.CreateBinOp(BinaryOp, LHS, RHS);
  4507. Result->takeName(&OrigI);
  4508. Overflow = ConstantInt::getFalse(OverflowTy);
  4509. if (auto *Inst = dyn_cast<Instruction>(Result)) {
  4510. if (IsSigned)
  4511. Inst->setHasNoSignedWrap();
  4512. else
  4513. Inst->setHasNoUnsignedWrap();
  4514. }
  4515. return true;
  4516. }
  4517. llvm_unreachable("Unexpected overflow result");
  4518. }
  4519. /// Recognize and process idiom involving test for multiplication
  4520. /// overflow.
  4521. ///
  4522. /// The caller has matched a pattern of the form:
  4523. /// I = cmp u (mul(zext A, zext B), V
  4524. /// The function checks if this is a test for overflow and if so replaces
  4525. /// multiplication with call to 'mul.with.overflow' intrinsic.
  4526. ///
  4527. /// \param I Compare instruction.
  4528. /// \param MulVal Result of 'mult' instruction. It is one of the arguments of
  4529. /// the compare instruction. Must be of integer type.
  4530. /// \param OtherVal The other argument of compare instruction.
  4531. /// \returns Instruction which must replace the compare instruction, NULL if no
  4532. /// replacement required.
  4533. static Instruction *processUMulZExtIdiom(ICmpInst &I, Value *MulVal,
  4534. Value *OtherVal,
  4535. InstCombinerImpl &IC) {
  4536. // Don't bother doing this transformation for pointers, don't do it for
  4537. // vectors.
  4538. if (!isa<IntegerType>(MulVal->getType()))
  4539. return nullptr;
  4540. assert(I.getOperand(0) == MulVal || I.getOperand(1) == MulVal);
  4541. assert(I.getOperand(0) == OtherVal || I.getOperand(1) == OtherVal);
  4542. auto *MulInstr = dyn_cast<Instruction>(MulVal);
  4543. if (!MulInstr)
  4544. return nullptr;
  4545. assert(MulInstr->getOpcode() == Instruction::Mul);
  4546. auto *LHS = cast<ZExtOperator>(MulInstr->getOperand(0)),
  4547. *RHS = cast<ZExtOperator>(MulInstr->getOperand(1));
  4548. assert(LHS->getOpcode() == Instruction::ZExt);
  4549. assert(RHS->getOpcode() == Instruction::ZExt);
  4550. Value *A = LHS->getOperand(0), *B = RHS->getOperand(0);
  4551. // Calculate type and width of the result produced by mul.with.overflow.
  4552. Type *TyA = A->getType(), *TyB = B->getType();
  4553. unsigned WidthA = TyA->getPrimitiveSizeInBits(),
  4554. WidthB = TyB->getPrimitiveSizeInBits();
  4555. unsigned MulWidth;
  4556. Type *MulType;
  4557. if (WidthB > WidthA) {
  4558. MulWidth = WidthB;
  4559. MulType = TyB;
  4560. } else {
  4561. MulWidth = WidthA;
  4562. MulType = TyA;
  4563. }
  4564. // In order to replace the original mul with a narrower mul.with.overflow,
  4565. // all uses must ignore upper bits of the product. The number of used low
  4566. // bits must be not greater than the width of mul.with.overflow.
  4567. if (MulVal->hasNUsesOrMore(2))
  4568. for (User *U : MulVal->users()) {
  4569. if (U == &I)
  4570. continue;
  4571. if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
  4572. // Check if truncation ignores bits above MulWidth.
  4573. unsigned TruncWidth = TI->getType()->getPrimitiveSizeInBits();
  4574. if (TruncWidth > MulWidth)
  4575. return nullptr;
  4576. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
  4577. // Check if AND ignores bits above MulWidth.
  4578. if (BO->getOpcode() != Instruction::And)
  4579. return nullptr;
  4580. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
  4581. const APInt &CVal = CI->getValue();
  4582. if (CVal.getBitWidth() - CVal.countLeadingZeros() > MulWidth)
  4583. return nullptr;
  4584. } else {
  4585. // In this case we could have the operand of the binary operation
  4586. // being defined in another block, and performing the replacement
  4587. // could break the dominance relation.
  4588. return nullptr;
  4589. }
  4590. } else {
  4591. // Other uses prohibit this transformation.
  4592. return nullptr;
  4593. }
  4594. }
  4595. // Recognize patterns
  4596. switch (I.getPredicate()) {
  4597. case ICmpInst::ICMP_EQ:
  4598. case ICmpInst::ICMP_NE:
  4599. // Recognize pattern:
  4600. // mulval = mul(zext A, zext B)
  4601. // cmp eq/neq mulval, and(mulval, mask), mask selects low MulWidth bits.
  4602. ConstantInt *CI;
  4603. Value *ValToMask;
  4604. if (match(OtherVal, m_And(m_Value(ValToMask), m_ConstantInt(CI)))) {
  4605. if (ValToMask != MulVal)
  4606. return nullptr;
  4607. const APInt &CVal = CI->getValue() + 1;
  4608. if (CVal.isPowerOf2()) {
  4609. unsigned MaskWidth = CVal.logBase2();
  4610. if (MaskWidth == MulWidth)
  4611. break; // Recognized
  4612. }
  4613. }
  4614. return nullptr;
  4615. case ICmpInst::ICMP_UGT:
  4616. // Recognize pattern:
  4617. // mulval = mul(zext A, zext B)
  4618. // cmp ugt mulval, max
  4619. if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
  4620. APInt MaxVal = APInt::getMaxValue(MulWidth);
  4621. MaxVal = MaxVal.zext(CI->getBitWidth());
  4622. if (MaxVal.eq(CI->getValue()))
  4623. break; // Recognized
  4624. }
  4625. return nullptr;
  4626. case ICmpInst::ICMP_UGE:
  4627. // Recognize pattern:
  4628. // mulval = mul(zext A, zext B)
  4629. // cmp uge mulval, max+1
  4630. if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
  4631. APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
  4632. if (MaxVal.eq(CI->getValue()))
  4633. break; // Recognized
  4634. }
  4635. return nullptr;
  4636. case ICmpInst::ICMP_ULE:
  4637. // Recognize pattern:
  4638. // mulval = mul(zext A, zext B)
  4639. // cmp ule mulval, max
  4640. if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
  4641. APInt MaxVal = APInt::getMaxValue(MulWidth);
  4642. MaxVal = MaxVal.zext(CI->getBitWidth());
  4643. if (MaxVal.eq(CI->getValue()))
  4644. break; // Recognized
  4645. }
  4646. return nullptr;
  4647. case ICmpInst::ICMP_ULT:
  4648. // Recognize pattern:
  4649. // mulval = mul(zext A, zext B)
  4650. // cmp ule mulval, max + 1
  4651. if (ConstantInt *CI = dyn_cast<ConstantInt>(OtherVal)) {
  4652. APInt MaxVal = APInt::getOneBitSet(CI->getBitWidth(), MulWidth);
  4653. if (MaxVal.eq(CI->getValue()))
  4654. break; // Recognized
  4655. }
  4656. return nullptr;
  4657. default:
  4658. return nullptr;
  4659. }
  4660. InstCombiner::BuilderTy &Builder = IC.Builder;
  4661. Builder.SetInsertPoint(MulInstr);
  4662. // Replace: mul(zext A, zext B) --> mul.with.overflow(A, B)
  4663. Value *MulA = A, *MulB = B;
  4664. if (WidthA < MulWidth)
  4665. MulA = Builder.CreateZExt(A, MulType);
  4666. if (WidthB < MulWidth)
  4667. MulB = Builder.CreateZExt(B, MulType);
  4668. Function *F = Intrinsic::getDeclaration(
  4669. I.getModule(), Intrinsic::umul_with_overflow, MulType);
  4670. CallInst *Call = Builder.CreateCall(F, {MulA, MulB}, "umul");
  4671. IC.addToWorklist(MulInstr);
  4672. // If there are uses of mul result other than the comparison, we know that
  4673. // they are truncation or binary AND. Change them to use result of
  4674. // mul.with.overflow and adjust properly mask/size.
  4675. if (MulVal->hasNUsesOrMore(2)) {
  4676. Value *Mul = Builder.CreateExtractValue(Call, 0, "umul.value");
  4677. for (User *U : make_early_inc_range(MulVal->users())) {
  4678. if (U == &I || U == OtherVal)
  4679. continue;
  4680. if (TruncInst *TI = dyn_cast<TruncInst>(U)) {
  4681. if (TI->getType()->getPrimitiveSizeInBits() == MulWidth)
  4682. IC.replaceInstUsesWith(*TI, Mul);
  4683. else
  4684. TI->setOperand(0, Mul);
  4685. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(U)) {
  4686. assert(BO->getOpcode() == Instruction::And);
  4687. // Replace (mul & mask) --> zext (mul.with.overflow & short_mask)
  4688. ConstantInt *CI = cast<ConstantInt>(BO->getOperand(1));
  4689. APInt ShortMask = CI->getValue().trunc(MulWidth);
  4690. Value *ShortAnd = Builder.CreateAnd(Mul, ShortMask);
  4691. Value *Zext = Builder.CreateZExt(ShortAnd, BO->getType());
  4692. IC.replaceInstUsesWith(*BO, Zext);
  4693. } else {
  4694. llvm_unreachable("Unexpected Binary operation");
  4695. }
  4696. IC.addToWorklist(cast<Instruction>(U));
  4697. }
  4698. }
  4699. if (isa<Instruction>(OtherVal))
  4700. IC.addToWorklist(cast<Instruction>(OtherVal));
  4701. // The original icmp gets replaced with the overflow value, maybe inverted
  4702. // depending on predicate.
  4703. bool Inverse = false;
  4704. switch (I.getPredicate()) {
  4705. case ICmpInst::ICMP_NE:
  4706. break;
  4707. case ICmpInst::ICMP_EQ:
  4708. Inverse = true;
  4709. break;
  4710. case ICmpInst::ICMP_UGT:
  4711. case ICmpInst::ICMP_UGE:
  4712. if (I.getOperand(0) == MulVal)
  4713. break;
  4714. Inverse = true;
  4715. break;
  4716. case ICmpInst::ICMP_ULT:
  4717. case ICmpInst::ICMP_ULE:
  4718. if (I.getOperand(1) == MulVal)
  4719. break;
  4720. Inverse = true;
  4721. break;
  4722. default:
  4723. llvm_unreachable("Unexpected predicate");
  4724. }
  4725. if (Inverse) {
  4726. Value *Res = Builder.CreateExtractValue(Call, 1);
  4727. return BinaryOperator::CreateNot(Res);
  4728. }
  4729. return ExtractValueInst::Create(Call, 1);
  4730. }
  4731. /// When performing a comparison against a constant, it is possible that not all
  4732. /// the bits in the LHS are demanded. This helper method computes the mask that
  4733. /// IS demanded.
  4734. static APInt getDemandedBitsLHSMask(ICmpInst &I, unsigned BitWidth) {
  4735. const APInt *RHS;
  4736. if (!match(I.getOperand(1), m_APInt(RHS)))
  4737. return APInt::getAllOnes(BitWidth);
  4738. // If this is a normal comparison, it demands all bits. If it is a sign bit
  4739. // comparison, it only demands the sign bit.
  4740. bool UnusedBit;
  4741. if (InstCombiner::isSignBitCheck(I.getPredicate(), *RHS, UnusedBit))
  4742. return APInt::getSignMask(BitWidth);
  4743. switch (I.getPredicate()) {
  4744. // For a UGT comparison, we don't care about any bits that
  4745. // correspond to the trailing ones of the comparand. The value of these
  4746. // bits doesn't impact the outcome of the comparison, because any value
  4747. // greater than the RHS must differ in a bit higher than these due to carry.
  4748. case ICmpInst::ICMP_UGT:
  4749. return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingOnes());
  4750. // Similarly, for a ULT comparison, we don't care about the trailing zeros.
  4751. // Any value less than the RHS must differ in a higher bit because of carries.
  4752. case ICmpInst::ICMP_ULT:
  4753. return APInt::getBitsSetFrom(BitWidth, RHS->countTrailingZeros());
  4754. default:
  4755. return APInt::getAllOnes(BitWidth);
  4756. }
  4757. }
  4758. /// Check if the order of \p Op0 and \p Op1 as operands in an ICmpInst
  4759. /// should be swapped.
  4760. /// The decision is based on how many times these two operands are reused
  4761. /// as subtract operands and their positions in those instructions.
  4762. /// The rationale is that several architectures use the same instruction for
  4763. /// both subtract and cmp. Thus, it is better if the order of those operands
  4764. /// match.
  4765. /// \return true if Op0 and Op1 should be swapped.
  4766. static bool swapMayExposeCSEOpportunities(const Value *Op0, const Value *Op1) {
  4767. // Filter out pointer values as those cannot appear directly in subtract.
  4768. // FIXME: we may want to go through inttoptrs or bitcasts.
  4769. if (Op0->getType()->isPointerTy())
  4770. return false;
  4771. // If a subtract already has the same operands as a compare, swapping would be
  4772. // bad. If a subtract has the same operands as a compare but in reverse order,
  4773. // then swapping is good.
  4774. int GoodToSwap = 0;
  4775. for (const User *U : Op0->users()) {
  4776. if (match(U, m_Sub(m_Specific(Op1), m_Specific(Op0))))
  4777. GoodToSwap++;
  4778. else if (match(U, m_Sub(m_Specific(Op0), m_Specific(Op1))))
  4779. GoodToSwap--;
  4780. }
  4781. return GoodToSwap > 0;
  4782. }
  4783. /// Check that one use is in the same block as the definition and all
  4784. /// other uses are in blocks dominated by a given block.
  4785. ///
  4786. /// \param DI Definition
  4787. /// \param UI Use
  4788. /// \param DB Block that must dominate all uses of \p DI outside
  4789. /// the parent block
  4790. /// \return true when \p UI is the only use of \p DI in the parent block
  4791. /// and all other uses of \p DI are in blocks dominated by \p DB.
  4792. ///
  4793. bool InstCombinerImpl::dominatesAllUses(const Instruction *DI,
  4794. const Instruction *UI,
  4795. const BasicBlock *DB) const {
  4796. assert(DI && UI && "Instruction not defined\n");
  4797. // Ignore incomplete definitions.
  4798. if (!DI->getParent())
  4799. return false;
  4800. // DI and UI must be in the same block.
  4801. if (DI->getParent() != UI->getParent())
  4802. return false;
  4803. // Protect from self-referencing blocks.
  4804. if (DI->getParent() == DB)
  4805. return false;
  4806. for (const User *U : DI->users()) {
  4807. auto *Usr = cast<Instruction>(U);
  4808. if (Usr != UI && !DT.dominates(DB, Usr->getParent()))
  4809. return false;
  4810. }
  4811. return true;
  4812. }
  4813. /// Return true when the instruction sequence within a block is select-cmp-br.
  4814. static bool isChainSelectCmpBranch(const SelectInst *SI) {
  4815. const BasicBlock *BB = SI->getParent();
  4816. if (!BB)
  4817. return false;
  4818. auto *BI = dyn_cast_or_null<BranchInst>(BB->getTerminator());
  4819. if (!BI || BI->getNumSuccessors() != 2)
  4820. return false;
  4821. auto *IC = dyn_cast<ICmpInst>(BI->getCondition());
  4822. if (!IC || (IC->getOperand(0) != SI && IC->getOperand(1) != SI))
  4823. return false;
  4824. return true;
  4825. }
  4826. /// True when a select result is replaced by one of its operands
  4827. /// in select-icmp sequence. This will eventually result in the elimination
  4828. /// of the select.
  4829. ///
  4830. /// \param SI Select instruction
  4831. /// \param Icmp Compare instruction
  4832. /// \param SIOpd Operand that replaces the select
  4833. ///
  4834. /// Notes:
  4835. /// - The replacement is global and requires dominator information
  4836. /// - The caller is responsible for the actual replacement
  4837. ///
  4838. /// Example:
  4839. ///
  4840. /// entry:
  4841. /// %4 = select i1 %3, %C* %0, %C* null
  4842. /// %5 = icmp eq %C* %4, null
  4843. /// br i1 %5, label %9, label %7
  4844. /// ...
  4845. /// ; <label>:7 ; preds = %entry
  4846. /// %8 = getelementptr inbounds %C* %4, i64 0, i32 0
  4847. /// ...
  4848. ///
  4849. /// can be transformed to
  4850. ///
  4851. /// %5 = icmp eq %C* %0, null
  4852. /// %6 = select i1 %3, i1 %5, i1 true
  4853. /// br i1 %6, label %9, label %7
  4854. /// ...
  4855. /// ; <label>:7 ; preds = %entry
  4856. /// %8 = getelementptr inbounds %C* %0, i64 0, i32 0 // replace by %0!
  4857. ///
  4858. /// Similar when the first operand of the select is a constant or/and
  4859. /// the compare is for not equal rather than equal.
  4860. ///
  4861. /// NOTE: The function is only called when the select and compare constants
  4862. /// are equal, the optimization can work only for EQ predicates. This is not a
  4863. /// major restriction since a NE compare should be 'normalized' to an equal
  4864. /// compare, which usually happens in the combiner and test case
  4865. /// select-cmp-br.ll checks for it.
  4866. bool InstCombinerImpl::replacedSelectWithOperand(SelectInst *SI,
  4867. const ICmpInst *Icmp,
  4868. const unsigned SIOpd) {
  4869. assert((SIOpd == 1 || SIOpd == 2) && "Invalid select operand!");
  4870. if (isChainSelectCmpBranch(SI) && Icmp->getPredicate() == ICmpInst::ICMP_EQ) {
  4871. BasicBlock *Succ = SI->getParent()->getTerminator()->getSuccessor(1);
  4872. // The check for the single predecessor is not the best that can be
  4873. // done. But it protects efficiently against cases like when SI's
  4874. // home block has two successors, Succ and Succ1, and Succ1 predecessor
  4875. // of Succ. Then SI can't be replaced by SIOpd because the use that gets
  4876. // replaced can be reached on either path. So the uniqueness check
  4877. // guarantees that the path all uses of SI (outside SI's parent) are on
  4878. // is disjoint from all other paths out of SI. But that information
  4879. // is more expensive to compute, and the trade-off here is in favor
  4880. // of compile-time. It should also be noticed that we check for a single
  4881. // predecessor and not only uniqueness. This to handle the situation when
  4882. // Succ and Succ1 points to the same basic block.
  4883. if (Succ->getSinglePredecessor() && dominatesAllUses(SI, Icmp, Succ)) {
  4884. NumSel++;
  4885. SI->replaceUsesOutsideBlock(SI->getOperand(SIOpd), SI->getParent());
  4886. return true;
  4887. }
  4888. }
  4889. return false;
  4890. }
  4891. /// Try to fold the comparison based on range information we can get by checking
  4892. /// whether bits are known to be zero or one in the inputs.
  4893. Instruction *InstCombinerImpl::foldICmpUsingKnownBits(ICmpInst &I) {
  4894. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  4895. Type *Ty = Op0->getType();
  4896. ICmpInst::Predicate Pred = I.getPredicate();
  4897. // Get scalar or pointer size.
  4898. unsigned BitWidth = Ty->isIntOrIntVectorTy()
  4899. ? Ty->getScalarSizeInBits()
  4900. : DL.getPointerTypeSizeInBits(Ty->getScalarType());
  4901. if (!BitWidth)
  4902. return nullptr;
  4903. KnownBits Op0Known(BitWidth);
  4904. KnownBits Op1Known(BitWidth);
  4905. if (SimplifyDemandedBits(&I, 0,
  4906. getDemandedBitsLHSMask(I, BitWidth),
  4907. Op0Known, 0))
  4908. return &I;
  4909. if (SimplifyDemandedBits(&I, 1, APInt::getAllOnes(BitWidth), Op1Known, 0))
  4910. return &I;
  4911. // Given the known and unknown bits, compute a range that the LHS could be
  4912. // in. Compute the Min, Max and RHS values based on the known bits. For the
  4913. // EQ and NE we use unsigned values.
  4914. APInt Op0Min(BitWidth, 0), Op0Max(BitWidth, 0);
  4915. APInt Op1Min(BitWidth, 0), Op1Max(BitWidth, 0);
  4916. if (I.isSigned()) {
  4917. Op0Min = Op0Known.getSignedMinValue();
  4918. Op0Max = Op0Known.getSignedMaxValue();
  4919. Op1Min = Op1Known.getSignedMinValue();
  4920. Op1Max = Op1Known.getSignedMaxValue();
  4921. } else {
  4922. Op0Min = Op0Known.getMinValue();
  4923. Op0Max = Op0Known.getMaxValue();
  4924. Op1Min = Op1Known.getMinValue();
  4925. Op1Max = Op1Known.getMaxValue();
  4926. }
  4927. // If Min and Max are known to be the same, then SimplifyDemandedBits figured
  4928. // out that the LHS or RHS is a constant. Constant fold this now, so that
  4929. // code below can assume that Min != Max.
  4930. if (!isa<Constant>(Op0) && Op0Min == Op0Max)
  4931. return new ICmpInst(Pred, ConstantExpr::getIntegerValue(Ty, Op0Min), Op1);
  4932. if (!isa<Constant>(Op1) && Op1Min == Op1Max)
  4933. return new ICmpInst(Pred, Op0, ConstantExpr::getIntegerValue(Ty, Op1Min));
  4934. // Don't break up a clamp pattern -- (min(max X, Y), Z) -- by replacing a
  4935. // min/max canonical compare with some other compare. That could lead to
  4936. // conflict with select canonicalization and infinite looping.
  4937. // FIXME: This constraint may go away if min/max intrinsics are canonical.
  4938. auto isMinMaxCmp = [&](Instruction &Cmp) {
  4939. if (!Cmp.hasOneUse())
  4940. return false;
  4941. Value *A, *B;
  4942. SelectPatternFlavor SPF = matchSelectPattern(Cmp.user_back(), A, B).Flavor;
  4943. if (!SelectPatternResult::isMinOrMax(SPF))
  4944. return false;
  4945. return match(Op0, m_MaxOrMin(m_Value(), m_Value())) ||
  4946. match(Op1, m_MaxOrMin(m_Value(), m_Value()));
  4947. };
  4948. if (!isMinMaxCmp(I)) {
  4949. switch (Pred) {
  4950. default:
  4951. break;
  4952. case ICmpInst::ICMP_ULT: {
  4953. if (Op1Min == Op0Max) // A <u B -> A != B if max(A) == min(B)
  4954. return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
  4955. const APInt *CmpC;
  4956. if (match(Op1, m_APInt(CmpC))) {
  4957. // A <u C -> A == C-1 if min(A)+1 == C
  4958. if (*CmpC == Op0Min + 1)
  4959. return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
  4960. ConstantInt::get(Op1->getType(), *CmpC - 1));
  4961. // X <u C --> X == 0, if the number of zero bits in the bottom of X
  4962. // exceeds the log2 of C.
  4963. if (Op0Known.countMinTrailingZeros() >= CmpC->ceilLogBase2())
  4964. return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
  4965. Constant::getNullValue(Op1->getType()));
  4966. }
  4967. break;
  4968. }
  4969. case ICmpInst::ICMP_UGT: {
  4970. if (Op1Max == Op0Min) // A >u B -> A != B if min(A) == max(B)
  4971. return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
  4972. const APInt *CmpC;
  4973. if (match(Op1, m_APInt(CmpC))) {
  4974. // A >u C -> A == C+1 if max(a)-1 == C
  4975. if (*CmpC == Op0Max - 1)
  4976. return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
  4977. ConstantInt::get(Op1->getType(), *CmpC + 1));
  4978. // X >u C --> X != 0, if the number of zero bits in the bottom of X
  4979. // exceeds the log2 of C.
  4980. if (Op0Known.countMinTrailingZeros() >= CmpC->getActiveBits())
  4981. return new ICmpInst(ICmpInst::ICMP_NE, Op0,
  4982. Constant::getNullValue(Op1->getType()));
  4983. }
  4984. break;
  4985. }
  4986. case ICmpInst::ICMP_SLT: {
  4987. if (Op1Min == Op0Max) // A <s B -> A != B if max(A) == min(B)
  4988. return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
  4989. const APInt *CmpC;
  4990. if (match(Op1, m_APInt(CmpC))) {
  4991. if (*CmpC == Op0Min + 1) // A <s C -> A == C-1 if min(A)+1 == C
  4992. return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
  4993. ConstantInt::get(Op1->getType(), *CmpC - 1));
  4994. }
  4995. break;
  4996. }
  4997. case ICmpInst::ICMP_SGT: {
  4998. if (Op1Max == Op0Min) // A >s B -> A != B if min(A) == max(B)
  4999. return new ICmpInst(ICmpInst::ICMP_NE, Op0, Op1);
  5000. const APInt *CmpC;
  5001. if (match(Op1, m_APInt(CmpC))) {
  5002. if (*CmpC == Op0Max - 1) // A >s C -> A == C+1 if max(A)-1 == C
  5003. return new ICmpInst(ICmpInst::ICMP_EQ, Op0,
  5004. ConstantInt::get(Op1->getType(), *CmpC + 1));
  5005. }
  5006. break;
  5007. }
  5008. }
  5009. }
  5010. // Based on the range information we know about the LHS, see if we can
  5011. // simplify this comparison. For example, (x&4) < 8 is always true.
  5012. switch (Pred) {
  5013. default:
  5014. llvm_unreachable("Unknown icmp opcode!");
  5015. case ICmpInst::ICMP_EQ:
  5016. case ICmpInst::ICMP_NE: {
  5017. if (Op0Max.ult(Op1Min) || Op0Min.ugt(Op1Max))
  5018. return replaceInstUsesWith(
  5019. I, ConstantInt::getBool(I.getType(), Pred == CmpInst::ICMP_NE));
  5020. // If all bits are known zero except for one, then we know at most one bit
  5021. // is set. If the comparison is against zero, then this is a check to see if
  5022. // *that* bit is set.
  5023. APInt Op0KnownZeroInverted = ~Op0Known.Zero;
  5024. if (Op1Known.isZero()) {
  5025. // If the LHS is an AND with the same constant, look through it.
  5026. Value *LHS = nullptr;
  5027. const APInt *LHSC;
  5028. if (!match(Op0, m_And(m_Value(LHS), m_APInt(LHSC))) ||
  5029. *LHSC != Op0KnownZeroInverted)
  5030. LHS = Op0;
  5031. Value *X;
  5032. const APInt *C1;
  5033. if (match(LHS, m_Shl(m_Power2(C1), m_Value(X)))) {
  5034. Type *XTy = X->getType();
  5035. unsigned Log2C1 = C1->countTrailingZeros();
  5036. APInt C2 = Op0KnownZeroInverted;
  5037. APInt C2Pow2 = (C2 & ~(*C1 - 1)) + *C1;
  5038. if (C2Pow2.isPowerOf2()) {
  5039. // iff (C1 is pow2) & ((C2 & ~(C1-1)) + C1) is pow2):
  5040. // ((C1 << X) & C2) == 0 -> X >= (Log2(C2+C1) - Log2(C1))
  5041. // ((C1 << X) & C2) != 0 -> X < (Log2(C2+C1) - Log2(C1))
  5042. unsigned Log2C2 = C2Pow2.countTrailingZeros();
  5043. auto *CmpC = ConstantInt::get(XTy, Log2C2 - Log2C1);
  5044. auto NewPred =
  5045. Pred == CmpInst::ICMP_EQ ? CmpInst::ICMP_UGE : CmpInst::ICMP_ULT;
  5046. return new ICmpInst(NewPred, X, CmpC);
  5047. }
  5048. }
  5049. }
  5050. break;
  5051. }
  5052. case ICmpInst::ICMP_ULT: {
  5053. if (Op0Max.ult(Op1Min)) // A <u B -> true if max(A) < min(B)
  5054. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5055. if (Op0Min.uge(Op1Max)) // A <u B -> false if min(A) >= max(B)
  5056. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5057. break;
  5058. }
  5059. case ICmpInst::ICMP_UGT: {
  5060. if (Op0Min.ugt(Op1Max)) // A >u B -> true if min(A) > max(B)
  5061. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5062. if (Op0Max.ule(Op1Min)) // A >u B -> false if max(A) <= max(B)
  5063. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5064. break;
  5065. }
  5066. case ICmpInst::ICMP_SLT: {
  5067. if (Op0Max.slt(Op1Min)) // A <s B -> true if max(A) < min(C)
  5068. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5069. if (Op0Min.sge(Op1Max)) // A <s B -> false if min(A) >= max(C)
  5070. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5071. break;
  5072. }
  5073. case ICmpInst::ICMP_SGT: {
  5074. if (Op0Min.sgt(Op1Max)) // A >s B -> true if min(A) > max(B)
  5075. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5076. if (Op0Max.sle(Op1Min)) // A >s B -> false if max(A) <= min(B)
  5077. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5078. break;
  5079. }
  5080. case ICmpInst::ICMP_SGE:
  5081. assert(!isa<ConstantInt>(Op1) && "ICMP_SGE with ConstantInt not folded!");
  5082. if (Op0Min.sge(Op1Max)) // A >=s B -> true if min(A) >= max(B)
  5083. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5084. if (Op0Max.slt(Op1Min)) // A >=s B -> false if max(A) < min(B)
  5085. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5086. if (Op1Min == Op0Max) // A >=s B -> A == B if max(A) == min(B)
  5087. return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
  5088. break;
  5089. case ICmpInst::ICMP_SLE:
  5090. assert(!isa<ConstantInt>(Op1) && "ICMP_SLE with ConstantInt not folded!");
  5091. if (Op0Max.sle(Op1Min)) // A <=s B -> true if max(A) <= min(B)
  5092. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5093. if (Op0Min.sgt(Op1Max)) // A <=s B -> false if min(A) > max(B)
  5094. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5095. if (Op1Max == Op0Min) // A <=s B -> A == B if min(A) == max(B)
  5096. return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
  5097. break;
  5098. case ICmpInst::ICMP_UGE:
  5099. assert(!isa<ConstantInt>(Op1) && "ICMP_UGE with ConstantInt not folded!");
  5100. if (Op0Min.uge(Op1Max)) // A >=u B -> true if min(A) >= max(B)
  5101. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5102. if (Op0Max.ult(Op1Min)) // A >=u B -> false if max(A) < min(B)
  5103. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5104. if (Op1Min == Op0Max) // A >=u B -> A == B if max(A) == min(B)
  5105. return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
  5106. break;
  5107. case ICmpInst::ICMP_ULE:
  5108. assert(!isa<ConstantInt>(Op1) && "ICMP_ULE with ConstantInt not folded!");
  5109. if (Op0Max.ule(Op1Min)) // A <=u B -> true if max(A) <= min(B)
  5110. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  5111. if (Op0Min.ugt(Op1Max)) // A <=u B -> false if min(A) > max(B)
  5112. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  5113. if (Op1Max == Op0Min) // A <=u B -> A == B if min(A) == max(B)
  5114. return new ICmpInst(ICmpInst::ICMP_EQ, Op0, Op1);
  5115. break;
  5116. }
  5117. // Turn a signed comparison into an unsigned one if both operands are known to
  5118. // have the same sign.
  5119. if (I.isSigned() &&
  5120. ((Op0Known.Zero.isNegative() && Op1Known.Zero.isNegative()) ||
  5121. (Op0Known.One.isNegative() && Op1Known.One.isNegative())))
  5122. return new ICmpInst(I.getUnsignedPredicate(), Op0, Op1);
  5123. return nullptr;
  5124. }
  5125. /// If one operand of an icmp is effectively a bool (value range of {0,1}),
  5126. /// then try to reduce patterns based on that limit.
  5127. static Instruction *foldICmpUsingBoolRange(ICmpInst &I,
  5128. InstCombiner::BuilderTy &Builder) {
  5129. Value *X, *Y;
  5130. ICmpInst::Predicate Pred;
  5131. // X must be 0 and bool must be true for "ULT":
  5132. // X <u (zext i1 Y) --> (X == 0) & Y
  5133. if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_ZExt(m_Value(Y))))) &&
  5134. Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULT)
  5135. return BinaryOperator::CreateAnd(Builder.CreateIsNull(X), Y);
  5136. // X must be 0 or bool must be true for "ULE":
  5137. // X <=u (sext i1 Y) --> (X == 0) | Y
  5138. if (match(&I, m_c_ICmp(Pred, m_Value(X), m_OneUse(m_SExt(m_Value(Y))))) &&
  5139. Y->getType()->isIntOrIntVectorTy(1) && Pred == ICmpInst::ICMP_ULE)
  5140. return BinaryOperator::CreateOr(Builder.CreateIsNull(X), Y);
  5141. return nullptr;
  5142. }
  5143. std::optional<std::pair<CmpInst::Predicate, Constant *>>
  5144. InstCombiner::getFlippedStrictnessPredicateAndConstant(CmpInst::Predicate Pred,
  5145. Constant *C) {
  5146. assert(ICmpInst::isRelational(Pred) && ICmpInst::isIntPredicate(Pred) &&
  5147. "Only for relational integer predicates.");
  5148. Type *Type = C->getType();
  5149. bool IsSigned = ICmpInst::isSigned(Pred);
  5150. CmpInst::Predicate UnsignedPred = ICmpInst::getUnsignedPredicate(Pred);
  5151. bool WillIncrement =
  5152. UnsignedPred == ICmpInst::ICMP_ULE || UnsignedPred == ICmpInst::ICMP_UGT;
  5153. // Check if the constant operand can be safely incremented/decremented
  5154. // without overflowing/underflowing.
  5155. auto ConstantIsOk = [WillIncrement, IsSigned](ConstantInt *C) {
  5156. return WillIncrement ? !C->isMaxValue(IsSigned) : !C->isMinValue(IsSigned);
  5157. };
  5158. Constant *SafeReplacementConstant = nullptr;
  5159. if (auto *CI = dyn_cast<ConstantInt>(C)) {
  5160. // Bail out if the constant can't be safely incremented/decremented.
  5161. if (!ConstantIsOk(CI))
  5162. return std::nullopt;
  5163. } else if (auto *FVTy = dyn_cast<FixedVectorType>(Type)) {
  5164. unsigned NumElts = FVTy->getNumElements();
  5165. for (unsigned i = 0; i != NumElts; ++i) {
  5166. Constant *Elt = C->getAggregateElement(i);
  5167. if (!Elt)
  5168. return std::nullopt;
  5169. if (isa<UndefValue>(Elt))
  5170. continue;
  5171. // Bail out if we can't determine if this constant is min/max or if we
  5172. // know that this constant is min/max.
  5173. auto *CI = dyn_cast<ConstantInt>(Elt);
  5174. if (!CI || !ConstantIsOk(CI))
  5175. return std::nullopt;
  5176. if (!SafeReplacementConstant)
  5177. SafeReplacementConstant = CI;
  5178. }
  5179. } else {
  5180. // ConstantExpr?
  5181. return std::nullopt;
  5182. }
  5183. // It may not be safe to change a compare predicate in the presence of
  5184. // undefined elements, so replace those elements with the first safe constant
  5185. // that we found.
  5186. // TODO: in case of poison, it is safe; let's replace undefs only.
  5187. if (C->containsUndefOrPoisonElement()) {
  5188. assert(SafeReplacementConstant && "Replacement constant not set");
  5189. C = Constant::replaceUndefsWith(C, SafeReplacementConstant);
  5190. }
  5191. CmpInst::Predicate NewPred = CmpInst::getFlippedStrictnessPredicate(Pred);
  5192. // Increment or decrement the constant.
  5193. Constant *OneOrNegOne = ConstantInt::get(Type, WillIncrement ? 1 : -1, true);
  5194. Constant *NewC = ConstantExpr::getAdd(C, OneOrNegOne);
  5195. return std::make_pair(NewPred, NewC);
  5196. }
  5197. /// If we have an icmp le or icmp ge instruction with a constant operand, turn
  5198. /// it into the appropriate icmp lt or icmp gt instruction. This transform
  5199. /// allows them to be folded in visitICmpInst.
  5200. static ICmpInst *canonicalizeCmpWithConstant(ICmpInst &I) {
  5201. ICmpInst::Predicate Pred = I.getPredicate();
  5202. if (ICmpInst::isEquality(Pred) || !ICmpInst::isIntPredicate(Pred) ||
  5203. InstCombiner::isCanonicalPredicate(Pred))
  5204. return nullptr;
  5205. Value *Op0 = I.getOperand(0);
  5206. Value *Op1 = I.getOperand(1);
  5207. auto *Op1C = dyn_cast<Constant>(Op1);
  5208. if (!Op1C)
  5209. return nullptr;
  5210. auto FlippedStrictness =
  5211. InstCombiner::getFlippedStrictnessPredicateAndConstant(Pred, Op1C);
  5212. if (!FlippedStrictness)
  5213. return nullptr;
  5214. return new ICmpInst(FlippedStrictness->first, Op0, FlippedStrictness->second);
  5215. }
  5216. /// If we have a comparison with a non-canonical predicate, if we can update
  5217. /// all the users, invert the predicate and adjust all the users.
  5218. CmpInst *InstCombinerImpl::canonicalizeICmpPredicate(CmpInst &I) {
  5219. // Is the predicate already canonical?
  5220. CmpInst::Predicate Pred = I.getPredicate();
  5221. if (InstCombiner::isCanonicalPredicate(Pred))
  5222. return nullptr;
  5223. // Can all users be adjusted to predicate inversion?
  5224. if (!InstCombiner::canFreelyInvertAllUsersOf(&I, /*IgnoredUser=*/nullptr))
  5225. return nullptr;
  5226. // Ok, we can canonicalize comparison!
  5227. // Let's first invert the comparison's predicate.
  5228. I.setPredicate(CmpInst::getInversePredicate(Pred));
  5229. I.setName(I.getName() + ".not");
  5230. // And, adapt users.
  5231. freelyInvertAllUsersOf(&I);
  5232. return &I;
  5233. }
  5234. /// Integer compare with boolean values can always be turned into bitwise ops.
  5235. static Instruction *canonicalizeICmpBool(ICmpInst &I,
  5236. InstCombiner::BuilderTy &Builder) {
  5237. Value *A = I.getOperand(0), *B = I.getOperand(1);
  5238. assert(A->getType()->isIntOrIntVectorTy(1) && "Bools only");
  5239. // A boolean compared to true/false can be simplified to Op0/true/false in
  5240. // 14 out of the 20 (10 predicates * 2 constants) possible combinations.
  5241. // Cases not handled by InstSimplify are always 'not' of Op0.
  5242. if (match(B, m_Zero())) {
  5243. switch (I.getPredicate()) {
  5244. case CmpInst::ICMP_EQ: // A == 0 -> !A
  5245. case CmpInst::ICMP_ULE: // A <=u 0 -> !A
  5246. case CmpInst::ICMP_SGE: // A >=s 0 -> !A
  5247. return BinaryOperator::CreateNot(A);
  5248. default:
  5249. llvm_unreachable("ICmp i1 X, C not simplified as expected.");
  5250. }
  5251. } else if (match(B, m_One())) {
  5252. switch (I.getPredicate()) {
  5253. case CmpInst::ICMP_NE: // A != 1 -> !A
  5254. case CmpInst::ICMP_ULT: // A <u 1 -> !A
  5255. case CmpInst::ICMP_SGT: // A >s -1 -> !A
  5256. return BinaryOperator::CreateNot(A);
  5257. default:
  5258. llvm_unreachable("ICmp i1 X, C not simplified as expected.");
  5259. }
  5260. }
  5261. switch (I.getPredicate()) {
  5262. default:
  5263. llvm_unreachable("Invalid icmp instruction!");
  5264. case ICmpInst::ICMP_EQ:
  5265. // icmp eq i1 A, B -> ~(A ^ B)
  5266. return BinaryOperator::CreateNot(Builder.CreateXor(A, B));
  5267. case ICmpInst::ICMP_NE:
  5268. // icmp ne i1 A, B -> A ^ B
  5269. return BinaryOperator::CreateXor(A, B);
  5270. case ICmpInst::ICMP_UGT:
  5271. // icmp ugt -> icmp ult
  5272. std::swap(A, B);
  5273. [[fallthrough]];
  5274. case ICmpInst::ICMP_ULT:
  5275. // icmp ult i1 A, B -> ~A & B
  5276. return BinaryOperator::CreateAnd(Builder.CreateNot(A), B);
  5277. case ICmpInst::ICMP_SGT:
  5278. // icmp sgt -> icmp slt
  5279. std::swap(A, B);
  5280. [[fallthrough]];
  5281. case ICmpInst::ICMP_SLT:
  5282. // icmp slt i1 A, B -> A & ~B
  5283. return BinaryOperator::CreateAnd(Builder.CreateNot(B), A);
  5284. case ICmpInst::ICMP_UGE:
  5285. // icmp uge -> icmp ule
  5286. std::swap(A, B);
  5287. [[fallthrough]];
  5288. case ICmpInst::ICMP_ULE:
  5289. // icmp ule i1 A, B -> ~A | B
  5290. return BinaryOperator::CreateOr(Builder.CreateNot(A), B);
  5291. case ICmpInst::ICMP_SGE:
  5292. // icmp sge -> icmp sle
  5293. std::swap(A, B);
  5294. [[fallthrough]];
  5295. case ICmpInst::ICMP_SLE:
  5296. // icmp sle i1 A, B -> A | ~B
  5297. return BinaryOperator::CreateOr(Builder.CreateNot(B), A);
  5298. }
  5299. }
  5300. // Transform pattern like:
  5301. // (1 << Y) u<= X or ~(-1 << Y) u< X or ((1 << Y)+(-1)) u< X
  5302. // (1 << Y) u> X or ~(-1 << Y) u>= X or ((1 << Y)+(-1)) u>= X
  5303. // Into:
  5304. // (X l>> Y) != 0
  5305. // (X l>> Y) == 0
  5306. static Instruction *foldICmpWithHighBitMask(ICmpInst &Cmp,
  5307. InstCombiner::BuilderTy &Builder) {
  5308. ICmpInst::Predicate Pred, NewPred;
  5309. Value *X, *Y;
  5310. if (match(&Cmp,
  5311. m_c_ICmp(Pred, m_OneUse(m_Shl(m_One(), m_Value(Y))), m_Value(X)))) {
  5312. switch (Pred) {
  5313. case ICmpInst::ICMP_ULE:
  5314. NewPred = ICmpInst::ICMP_NE;
  5315. break;
  5316. case ICmpInst::ICMP_UGT:
  5317. NewPred = ICmpInst::ICMP_EQ;
  5318. break;
  5319. default:
  5320. return nullptr;
  5321. }
  5322. } else if (match(&Cmp, m_c_ICmp(Pred,
  5323. m_OneUse(m_CombineOr(
  5324. m_Not(m_Shl(m_AllOnes(), m_Value(Y))),
  5325. m_Add(m_Shl(m_One(), m_Value(Y)),
  5326. m_AllOnes()))),
  5327. m_Value(X)))) {
  5328. // The variant with 'add' is not canonical, (the variant with 'not' is)
  5329. // we only get it because it has extra uses, and can't be canonicalized,
  5330. switch (Pred) {
  5331. case ICmpInst::ICMP_ULT:
  5332. NewPred = ICmpInst::ICMP_NE;
  5333. break;
  5334. case ICmpInst::ICMP_UGE:
  5335. NewPred = ICmpInst::ICMP_EQ;
  5336. break;
  5337. default:
  5338. return nullptr;
  5339. }
  5340. } else
  5341. return nullptr;
  5342. Value *NewX = Builder.CreateLShr(X, Y, X->getName() + ".highbits");
  5343. Constant *Zero = Constant::getNullValue(NewX->getType());
  5344. return CmpInst::Create(Instruction::ICmp, NewPred, NewX, Zero);
  5345. }
  5346. static Instruction *foldVectorCmp(CmpInst &Cmp,
  5347. InstCombiner::BuilderTy &Builder) {
  5348. const CmpInst::Predicate Pred = Cmp.getPredicate();
  5349. Value *LHS = Cmp.getOperand(0), *RHS = Cmp.getOperand(1);
  5350. Value *V1, *V2;
  5351. auto createCmpReverse = [&](CmpInst::Predicate Pred, Value *X, Value *Y) {
  5352. Value *V = Builder.CreateCmp(Pred, X, Y, Cmp.getName());
  5353. if (auto *I = dyn_cast<Instruction>(V))
  5354. I->copyIRFlags(&Cmp);
  5355. Module *M = Cmp.getModule();
  5356. Function *F = Intrinsic::getDeclaration(
  5357. M, Intrinsic::experimental_vector_reverse, V->getType());
  5358. return CallInst::Create(F, V);
  5359. };
  5360. if (match(LHS, m_VecReverse(m_Value(V1)))) {
  5361. // cmp Pred, rev(V1), rev(V2) --> rev(cmp Pred, V1, V2)
  5362. if (match(RHS, m_VecReverse(m_Value(V2))) &&
  5363. (LHS->hasOneUse() || RHS->hasOneUse()))
  5364. return createCmpReverse(Pred, V1, V2);
  5365. // cmp Pred, rev(V1), RHSSplat --> rev(cmp Pred, V1, RHSSplat)
  5366. if (LHS->hasOneUse() && isSplatValue(RHS))
  5367. return createCmpReverse(Pred, V1, RHS);
  5368. }
  5369. // cmp Pred, LHSSplat, rev(V2) --> rev(cmp Pred, LHSSplat, V2)
  5370. else if (isSplatValue(LHS) && match(RHS, m_OneUse(m_VecReverse(m_Value(V2)))))
  5371. return createCmpReverse(Pred, LHS, V2);
  5372. ArrayRef<int> M;
  5373. if (!match(LHS, m_Shuffle(m_Value(V1), m_Undef(), m_Mask(M))))
  5374. return nullptr;
  5375. // If both arguments of the cmp are shuffles that use the same mask and
  5376. // shuffle within a single vector, move the shuffle after the cmp:
  5377. // cmp (shuffle V1, M), (shuffle V2, M) --> shuffle (cmp V1, V2), M
  5378. Type *V1Ty = V1->getType();
  5379. if (match(RHS, m_Shuffle(m_Value(V2), m_Undef(), m_SpecificMask(M))) &&
  5380. V1Ty == V2->getType() && (LHS->hasOneUse() || RHS->hasOneUse())) {
  5381. Value *NewCmp = Builder.CreateCmp(Pred, V1, V2);
  5382. return new ShuffleVectorInst(NewCmp, M);
  5383. }
  5384. // Try to canonicalize compare with splatted operand and splat constant.
  5385. // TODO: We could generalize this for more than splats. See/use the code in
  5386. // InstCombiner::foldVectorBinop().
  5387. Constant *C;
  5388. if (!LHS->hasOneUse() || !match(RHS, m_Constant(C)))
  5389. return nullptr;
  5390. // Length-changing splats are ok, so adjust the constants as needed:
  5391. // cmp (shuffle V1, M), C --> shuffle (cmp V1, C'), M
  5392. Constant *ScalarC = C->getSplatValue(/* AllowUndefs */ true);
  5393. int MaskSplatIndex;
  5394. if (ScalarC && match(M, m_SplatOrUndefMask(MaskSplatIndex))) {
  5395. // We allow undefs in matching, but this transform removes those for safety.
  5396. // Demanded elements analysis should be able to recover some/all of that.
  5397. C = ConstantVector::getSplat(cast<VectorType>(V1Ty)->getElementCount(),
  5398. ScalarC);
  5399. SmallVector<int, 8> NewM(M.size(), MaskSplatIndex);
  5400. Value *NewCmp = Builder.CreateCmp(Pred, V1, C);
  5401. return new ShuffleVectorInst(NewCmp, NewM);
  5402. }
  5403. return nullptr;
  5404. }
  5405. // extract(uadd.with.overflow(A, B), 0) ult A
  5406. // -> extract(uadd.with.overflow(A, B), 1)
  5407. static Instruction *foldICmpOfUAddOv(ICmpInst &I) {
  5408. CmpInst::Predicate Pred = I.getPredicate();
  5409. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  5410. Value *UAddOv;
  5411. Value *A, *B;
  5412. auto UAddOvResultPat = m_ExtractValue<0>(
  5413. m_Intrinsic<Intrinsic::uadd_with_overflow>(m_Value(A), m_Value(B)));
  5414. if (match(Op0, UAddOvResultPat) &&
  5415. ((Pred == ICmpInst::ICMP_ULT && (Op1 == A || Op1 == B)) ||
  5416. (Pred == ICmpInst::ICMP_EQ && match(Op1, m_ZeroInt()) &&
  5417. (match(A, m_One()) || match(B, m_One()))) ||
  5418. (Pred == ICmpInst::ICMP_NE && match(Op1, m_AllOnes()) &&
  5419. (match(A, m_AllOnes()) || match(B, m_AllOnes())))))
  5420. // extract(uadd.with.overflow(A, B), 0) < A
  5421. // extract(uadd.with.overflow(A, 1), 0) == 0
  5422. // extract(uadd.with.overflow(A, -1), 0) != -1
  5423. UAddOv = cast<ExtractValueInst>(Op0)->getAggregateOperand();
  5424. else if (match(Op1, UAddOvResultPat) &&
  5425. Pred == ICmpInst::ICMP_UGT && (Op0 == A || Op0 == B))
  5426. // A > extract(uadd.with.overflow(A, B), 0)
  5427. UAddOv = cast<ExtractValueInst>(Op1)->getAggregateOperand();
  5428. else
  5429. return nullptr;
  5430. return ExtractValueInst::Create(UAddOv, 1);
  5431. }
  5432. static Instruction *foldICmpInvariantGroup(ICmpInst &I) {
  5433. if (!I.getOperand(0)->getType()->isPointerTy() ||
  5434. NullPointerIsDefined(
  5435. I.getParent()->getParent(),
  5436. I.getOperand(0)->getType()->getPointerAddressSpace())) {
  5437. return nullptr;
  5438. }
  5439. Instruction *Op;
  5440. if (match(I.getOperand(0), m_Instruction(Op)) &&
  5441. match(I.getOperand(1), m_Zero()) &&
  5442. Op->isLaunderOrStripInvariantGroup()) {
  5443. return ICmpInst::Create(Instruction::ICmp, I.getPredicate(),
  5444. Op->getOperand(0), I.getOperand(1));
  5445. }
  5446. return nullptr;
  5447. }
  5448. /// This function folds patterns produced by lowering of reduce idioms, such as
  5449. /// llvm.vector.reduce.and which are lowered into instruction chains. This code
  5450. /// attempts to generate fewer number of scalar comparisons instead of vector
  5451. /// comparisons when possible.
  5452. static Instruction *foldReductionIdiom(ICmpInst &I,
  5453. InstCombiner::BuilderTy &Builder,
  5454. const DataLayout &DL) {
  5455. if (I.getType()->isVectorTy())
  5456. return nullptr;
  5457. ICmpInst::Predicate OuterPred, InnerPred;
  5458. Value *LHS, *RHS;
  5459. // Match lowering of @llvm.vector.reduce.and. Turn
  5460. /// %vec_ne = icmp ne <8 x i8> %lhs, %rhs
  5461. /// %scalar_ne = bitcast <8 x i1> %vec_ne to i8
  5462. /// %res = icmp <pred> i8 %scalar_ne, 0
  5463. ///
  5464. /// into
  5465. ///
  5466. /// %lhs.scalar = bitcast <8 x i8> %lhs to i64
  5467. /// %rhs.scalar = bitcast <8 x i8> %rhs to i64
  5468. /// %res = icmp <pred> i64 %lhs.scalar, %rhs.scalar
  5469. ///
  5470. /// for <pred> in {ne, eq}.
  5471. if (!match(&I, m_ICmp(OuterPred,
  5472. m_OneUse(m_BitCast(m_OneUse(
  5473. m_ICmp(InnerPred, m_Value(LHS), m_Value(RHS))))),
  5474. m_Zero())))
  5475. return nullptr;
  5476. auto *LHSTy = dyn_cast<FixedVectorType>(LHS->getType());
  5477. if (!LHSTy || !LHSTy->getElementType()->isIntegerTy())
  5478. return nullptr;
  5479. unsigned NumBits =
  5480. LHSTy->getNumElements() * LHSTy->getElementType()->getIntegerBitWidth();
  5481. // TODO: Relax this to "not wider than max legal integer type"?
  5482. if (!DL.isLegalInteger(NumBits))
  5483. return nullptr;
  5484. if (ICmpInst::isEquality(OuterPred) && InnerPred == ICmpInst::ICMP_NE) {
  5485. auto *ScalarTy = Builder.getIntNTy(NumBits);
  5486. LHS = Builder.CreateBitCast(LHS, ScalarTy, LHS->getName() + ".scalar");
  5487. RHS = Builder.CreateBitCast(RHS, ScalarTy, RHS->getName() + ".scalar");
  5488. return ICmpInst::Create(Instruction::ICmp, OuterPred, LHS, RHS,
  5489. I.getName());
  5490. }
  5491. return nullptr;
  5492. }
  5493. Instruction *InstCombinerImpl::visitICmpInst(ICmpInst &I) {
  5494. bool Changed = false;
  5495. const SimplifyQuery Q = SQ.getWithInstruction(&I);
  5496. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  5497. unsigned Op0Cplxity = getComplexity(Op0);
  5498. unsigned Op1Cplxity = getComplexity(Op1);
  5499. /// Orders the operands of the compare so that they are listed from most
  5500. /// complex to least complex. This puts constants before unary operators,
  5501. /// before binary operators.
  5502. if (Op0Cplxity < Op1Cplxity ||
  5503. (Op0Cplxity == Op1Cplxity && swapMayExposeCSEOpportunities(Op0, Op1))) {
  5504. I.swapOperands();
  5505. std::swap(Op0, Op1);
  5506. Changed = true;
  5507. }
  5508. if (Value *V = simplifyICmpInst(I.getPredicate(), Op0, Op1, Q))
  5509. return replaceInstUsesWith(I, V);
  5510. // Comparing -val or val with non-zero is the same as just comparing val
  5511. // ie, abs(val) != 0 -> val != 0
  5512. if (I.getPredicate() == ICmpInst::ICMP_NE && match(Op1, m_Zero())) {
  5513. Value *Cond, *SelectTrue, *SelectFalse;
  5514. if (match(Op0, m_Select(m_Value(Cond), m_Value(SelectTrue),
  5515. m_Value(SelectFalse)))) {
  5516. if (Value *V = dyn_castNegVal(SelectTrue)) {
  5517. if (V == SelectFalse)
  5518. return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
  5519. }
  5520. else if (Value *V = dyn_castNegVal(SelectFalse)) {
  5521. if (V == SelectTrue)
  5522. return CmpInst::Create(Instruction::ICmp, I.getPredicate(), V, Op1);
  5523. }
  5524. }
  5525. }
  5526. if (Op0->getType()->isIntOrIntVectorTy(1))
  5527. if (Instruction *Res = canonicalizeICmpBool(I, Builder))
  5528. return Res;
  5529. if (Instruction *Res = canonicalizeCmpWithConstant(I))
  5530. return Res;
  5531. if (Instruction *Res = canonicalizeICmpPredicate(I))
  5532. return Res;
  5533. if (Instruction *Res = foldICmpWithConstant(I))
  5534. return Res;
  5535. if (Instruction *Res = foldICmpWithDominatingICmp(I))
  5536. return Res;
  5537. if (Instruction *Res = foldICmpUsingBoolRange(I, Builder))
  5538. return Res;
  5539. if (Instruction *Res = foldICmpUsingKnownBits(I))
  5540. return Res;
  5541. // Test if the ICmpInst instruction is used exclusively by a select as
  5542. // part of a minimum or maximum operation. If so, refrain from doing
  5543. // any other folding. This helps out other analyses which understand
  5544. // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
  5545. // and CodeGen. And in this case, at least one of the comparison
  5546. // operands has at least one user besides the compare (the select),
  5547. // which would often largely negate the benefit of folding anyway.
  5548. //
  5549. // Do the same for the other patterns recognized by matchSelectPattern.
  5550. if (I.hasOneUse())
  5551. if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
  5552. Value *A, *B;
  5553. SelectPatternResult SPR = matchSelectPattern(SI, A, B);
  5554. if (SPR.Flavor != SPF_UNKNOWN)
  5555. return nullptr;
  5556. }
  5557. // Do this after checking for min/max to prevent infinite looping.
  5558. if (Instruction *Res = foldICmpWithZero(I))
  5559. return Res;
  5560. // FIXME: We only do this after checking for min/max to prevent infinite
  5561. // looping caused by a reverse canonicalization of these patterns for min/max.
  5562. // FIXME: The organization of folds is a mess. These would naturally go into
  5563. // canonicalizeCmpWithConstant(), but we can't move all of the above folds
  5564. // down here after the min/max restriction.
  5565. ICmpInst::Predicate Pred = I.getPredicate();
  5566. const APInt *C;
  5567. if (match(Op1, m_APInt(C))) {
  5568. // For i32: x >u 2147483647 -> x <s 0 -> true if sign bit set
  5569. if (Pred == ICmpInst::ICMP_UGT && C->isMaxSignedValue()) {
  5570. Constant *Zero = Constant::getNullValue(Op0->getType());
  5571. return new ICmpInst(ICmpInst::ICMP_SLT, Op0, Zero);
  5572. }
  5573. // For i32: x <u 2147483648 -> x >s -1 -> true if sign bit clear
  5574. if (Pred == ICmpInst::ICMP_ULT && C->isMinSignedValue()) {
  5575. Constant *AllOnes = Constant::getAllOnesValue(Op0->getType());
  5576. return new ICmpInst(ICmpInst::ICMP_SGT, Op0, AllOnes);
  5577. }
  5578. }
  5579. // The folds in here may rely on wrapping flags and special constants, so
  5580. // they can break up min/max idioms in some cases but not seemingly similar
  5581. // patterns.
  5582. // FIXME: It may be possible to enhance select folding to make this
  5583. // unnecessary. It may also be moot if we canonicalize to min/max
  5584. // intrinsics.
  5585. if (Instruction *Res = foldICmpBinOp(I, Q))
  5586. return Res;
  5587. if (Instruction *Res = foldICmpInstWithConstant(I))
  5588. return Res;
  5589. // Try to match comparison as a sign bit test. Intentionally do this after
  5590. // foldICmpInstWithConstant() to potentially let other folds to happen first.
  5591. if (Instruction *New = foldSignBitTest(I))
  5592. return New;
  5593. if (Instruction *Res = foldICmpInstWithConstantNotInt(I))
  5594. return Res;
  5595. // Try to optimize 'icmp GEP, P' or 'icmp P, GEP'.
  5596. if (auto *GEP = dyn_cast<GEPOperator>(Op0))
  5597. if (Instruction *NI = foldGEPICmp(GEP, Op1, I.getPredicate(), I))
  5598. return NI;
  5599. if (auto *GEP = dyn_cast<GEPOperator>(Op1))
  5600. if (Instruction *NI = foldGEPICmp(GEP, Op0, I.getSwappedPredicate(), I))
  5601. return NI;
  5602. if (auto *SI = dyn_cast<SelectInst>(Op0))
  5603. if (Instruction *NI = foldSelectICmp(I.getPredicate(), SI, Op1, I))
  5604. return NI;
  5605. if (auto *SI = dyn_cast<SelectInst>(Op1))
  5606. if (Instruction *NI = foldSelectICmp(I.getSwappedPredicate(), SI, Op0, I))
  5607. return NI;
  5608. // Try to optimize equality comparisons against alloca-based pointers.
  5609. if (Op0->getType()->isPointerTy() && I.isEquality()) {
  5610. assert(Op1->getType()->isPointerTy() && "Comparing pointer with non-pointer?");
  5611. if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op0)))
  5612. if (Instruction *New = foldAllocaCmp(I, Alloca))
  5613. return New;
  5614. if (auto *Alloca = dyn_cast<AllocaInst>(getUnderlyingObject(Op1)))
  5615. if (Instruction *New = foldAllocaCmp(I, Alloca))
  5616. return New;
  5617. }
  5618. if (Instruction *Res = foldICmpBitCast(I))
  5619. return Res;
  5620. // TODO: Hoist this above the min/max bailout.
  5621. if (Instruction *R = foldICmpWithCastOp(I))
  5622. return R;
  5623. if (Instruction *Res = foldICmpWithMinMax(I))
  5624. return Res;
  5625. {
  5626. Value *A, *B;
  5627. // Transform (A & ~B) == 0 --> (A & B) != 0
  5628. // and (A & ~B) != 0 --> (A & B) == 0
  5629. // if A is a power of 2.
  5630. if (match(Op0, m_And(m_Value(A), m_Not(m_Value(B)))) &&
  5631. match(Op1, m_Zero()) &&
  5632. isKnownToBeAPowerOfTwo(A, false, 0, &I) && I.isEquality())
  5633. return new ICmpInst(I.getInversePredicate(), Builder.CreateAnd(A, B),
  5634. Op1);
  5635. // ~X < ~Y --> Y < X
  5636. // ~X < C --> X > ~C
  5637. if (match(Op0, m_Not(m_Value(A)))) {
  5638. if (match(Op1, m_Not(m_Value(B))))
  5639. return new ICmpInst(I.getPredicate(), B, A);
  5640. const APInt *C;
  5641. if (match(Op1, m_APInt(C)))
  5642. return new ICmpInst(I.getSwappedPredicate(), A,
  5643. ConstantInt::get(Op1->getType(), ~(*C)));
  5644. }
  5645. Instruction *AddI = nullptr;
  5646. if (match(&I, m_UAddWithOverflow(m_Value(A), m_Value(B),
  5647. m_Instruction(AddI))) &&
  5648. isa<IntegerType>(A->getType())) {
  5649. Value *Result;
  5650. Constant *Overflow;
  5651. // m_UAddWithOverflow can match patterns that do not include an explicit
  5652. // "add" instruction, so check the opcode of the matched op.
  5653. if (AddI->getOpcode() == Instruction::Add &&
  5654. OptimizeOverflowCheck(Instruction::Add, /*Signed*/ false, A, B, *AddI,
  5655. Result, Overflow)) {
  5656. replaceInstUsesWith(*AddI, Result);
  5657. eraseInstFromFunction(*AddI);
  5658. return replaceInstUsesWith(I, Overflow);
  5659. }
  5660. }
  5661. // (zext a) * (zext b) --> llvm.umul.with.overflow.
  5662. if (match(Op0, m_NUWMul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
  5663. if (Instruction *R = processUMulZExtIdiom(I, Op0, Op1, *this))
  5664. return R;
  5665. }
  5666. if (match(Op1, m_NUWMul(m_ZExt(m_Value(A)), m_ZExt(m_Value(B))))) {
  5667. if (Instruction *R = processUMulZExtIdiom(I, Op1, Op0, *this))
  5668. return R;
  5669. }
  5670. }
  5671. if (Instruction *Res = foldICmpEquality(I))
  5672. return Res;
  5673. if (Instruction *Res = foldICmpOfUAddOv(I))
  5674. return Res;
  5675. // The 'cmpxchg' instruction returns an aggregate containing the old value and
  5676. // an i1 which indicates whether or not we successfully did the swap.
  5677. //
  5678. // Replace comparisons between the old value and the expected value with the
  5679. // indicator that 'cmpxchg' returns.
  5680. //
  5681. // N.B. This transform is only valid when the 'cmpxchg' is not permitted to
  5682. // spuriously fail. In those cases, the old value may equal the expected
  5683. // value but it is possible for the swap to not occur.
  5684. if (I.getPredicate() == ICmpInst::ICMP_EQ)
  5685. if (auto *EVI = dyn_cast<ExtractValueInst>(Op0))
  5686. if (auto *ACXI = dyn_cast<AtomicCmpXchgInst>(EVI->getAggregateOperand()))
  5687. if (EVI->getIndices()[0] == 0 && ACXI->getCompareOperand() == Op1 &&
  5688. !ACXI->isWeak())
  5689. return ExtractValueInst::Create(ACXI, 1);
  5690. {
  5691. Value *X;
  5692. const APInt *C;
  5693. // icmp X+Cst, X
  5694. if (match(Op0, m_Add(m_Value(X), m_APInt(C))) && Op1 == X)
  5695. return foldICmpAddOpConst(X, *C, I.getPredicate());
  5696. // icmp X, X+Cst
  5697. if (match(Op1, m_Add(m_Value(X), m_APInt(C))) && Op0 == X)
  5698. return foldICmpAddOpConst(X, *C, I.getSwappedPredicate());
  5699. }
  5700. if (Instruction *Res = foldICmpWithHighBitMask(I, Builder))
  5701. return Res;
  5702. if (I.getType()->isVectorTy())
  5703. if (Instruction *Res = foldVectorCmp(I, Builder))
  5704. return Res;
  5705. if (Instruction *Res = foldICmpInvariantGroup(I))
  5706. return Res;
  5707. if (Instruction *Res = foldReductionIdiom(I, Builder, DL))
  5708. return Res;
  5709. return Changed ? &I : nullptr;
  5710. }
  5711. /// Fold fcmp ([us]itofp x, cst) if possible.
  5712. Instruction *InstCombinerImpl::foldFCmpIntToFPConst(FCmpInst &I,
  5713. Instruction *LHSI,
  5714. Constant *RHSC) {
  5715. if (!isa<ConstantFP>(RHSC)) return nullptr;
  5716. const APFloat &RHS = cast<ConstantFP>(RHSC)->getValueAPF();
  5717. // Get the width of the mantissa. We don't want to hack on conversions that
  5718. // might lose information from the integer, e.g. "i64 -> float"
  5719. int MantissaWidth = LHSI->getType()->getFPMantissaWidth();
  5720. if (MantissaWidth == -1) return nullptr; // Unknown.
  5721. IntegerType *IntTy = cast<IntegerType>(LHSI->getOperand(0)->getType());
  5722. bool LHSUnsigned = isa<UIToFPInst>(LHSI);
  5723. if (I.isEquality()) {
  5724. FCmpInst::Predicate P = I.getPredicate();
  5725. bool IsExact = false;
  5726. APSInt RHSCvt(IntTy->getBitWidth(), LHSUnsigned);
  5727. RHS.convertToInteger(RHSCvt, APFloat::rmNearestTiesToEven, &IsExact);
  5728. // If the floating point constant isn't an integer value, we know if we will
  5729. // ever compare equal / not equal to it.
  5730. if (!IsExact) {
  5731. // TODO: Can never be -0.0 and other non-representable values
  5732. APFloat RHSRoundInt(RHS);
  5733. RHSRoundInt.roundToIntegral(APFloat::rmNearestTiesToEven);
  5734. if (RHS != RHSRoundInt) {
  5735. if (P == FCmpInst::FCMP_OEQ || P == FCmpInst::FCMP_UEQ)
  5736. return replaceInstUsesWith(I, Builder.getFalse());
  5737. assert(P == FCmpInst::FCMP_ONE || P == FCmpInst::FCMP_UNE);
  5738. return replaceInstUsesWith(I, Builder.getTrue());
  5739. }
  5740. }
  5741. // TODO: If the constant is exactly representable, is it always OK to do
  5742. // equality compares as integer?
  5743. }
  5744. // Check to see that the input is converted from an integer type that is small
  5745. // enough that preserves all bits. TODO: check here for "known" sign bits.
  5746. // This would allow us to handle (fptosi (x >>s 62) to float) if x is i64 f.e.
  5747. unsigned InputSize = IntTy->getScalarSizeInBits();
  5748. // Following test does NOT adjust InputSize downwards for signed inputs,
  5749. // because the most negative value still requires all the mantissa bits
  5750. // to distinguish it from one less than that value.
  5751. if ((int)InputSize > MantissaWidth) {
  5752. // Conversion would lose accuracy. Check if loss can impact comparison.
  5753. int Exp = ilogb(RHS);
  5754. if (Exp == APFloat::IEK_Inf) {
  5755. int MaxExponent = ilogb(APFloat::getLargest(RHS.getSemantics()));
  5756. if (MaxExponent < (int)InputSize - !LHSUnsigned)
  5757. // Conversion could create infinity.
  5758. return nullptr;
  5759. } else {
  5760. // Note that if RHS is zero or NaN, then Exp is negative
  5761. // and first condition is trivially false.
  5762. if (MantissaWidth <= Exp && Exp <= (int)InputSize - !LHSUnsigned)
  5763. // Conversion could affect comparison.
  5764. return nullptr;
  5765. }
  5766. }
  5767. // Otherwise, we can potentially simplify the comparison. We know that it
  5768. // will always come through as an integer value and we know the constant is
  5769. // not a NAN (it would have been previously simplified).
  5770. assert(!RHS.isNaN() && "NaN comparison not already folded!");
  5771. ICmpInst::Predicate Pred;
  5772. switch (I.getPredicate()) {
  5773. default: llvm_unreachable("Unexpected predicate!");
  5774. case FCmpInst::FCMP_UEQ:
  5775. case FCmpInst::FCMP_OEQ:
  5776. Pred = ICmpInst::ICMP_EQ;
  5777. break;
  5778. case FCmpInst::FCMP_UGT:
  5779. case FCmpInst::FCMP_OGT:
  5780. Pred = LHSUnsigned ? ICmpInst::ICMP_UGT : ICmpInst::ICMP_SGT;
  5781. break;
  5782. case FCmpInst::FCMP_UGE:
  5783. case FCmpInst::FCMP_OGE:
  5784. Pred = LHSUnsigned ? ICmpInst::ICMP_UGE : ICmpInst::ICMP_SGE;
  5785. break;
  5786. case FCmpInst::FCMP_ULT:
  5787. case FCmpInst::FCMP_OLT:
  5788. Pred = LHSUnsigned ? ICmpInst::ICMP_ULT : ICmpInst::ICMP_SLT;
  5789. break;
  5790. case FCmpInst::FCMP_ULE:
  5791. case FCmpInst::FCMP_OLE:
  5792. Pred = LHSUnsigned ? ICmpInst::ICMP_ULE : ICmpInst::ICMP_SLE;
  5793. break;
  5794. case FCmpInst::FCMP_UNE:
  5795. case FCmpInst::FCMP_ONE:
  5796. Pred = ICmpInst::ICMP_NE;
  5797. break;
  5798. case FCmpInst::FCMP_ORD:
  5799. return replaceInstUsesWith(I, Builder.getTrue());
  5800. case FCmpInst::FCMP_UNO:
  5801. return replaceInstUsesWith(I, Builder.getFalse());
  5802. }
  5803. // Now we know that the APFloat is a normal number, zero or inf.
  5804. // See if the FP constant is too large for the integer. For example,
  5805. // comparing an i8 to 300.0.
  5806. unsigned IntWidth = IntTy->getScalarSizeInBits();
  5807. if (!LHSUnsigned) {
  5808. // If the RHS value is > SignedMax, fold the comparison. This handles +INF
  5809. // and large values.
  5810. APFloat SMax(RHS.getSemantics());
  5811. SMax.convertFromAPInt(APInt::getSignedMaxValue(IntWidth), true,
  5812. APFloat::rmNearestTiesToEven);
  5813. if (SMax < RHS) { // smax < 13123.0
  5814. if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SLT ||
  5815. Pred == ICmpInst::ICMP_SLE)
  5816. return replaceInstUsesWith(I, Builder.getTrue());
  5817. return replaceInstUsesWith(I, Builder.getFalse());
  5818. }
  5819. } else {
  5820. // If the RHS value is > UnsignedMax, fold the comparison. This handles
  5821. // +INF and large values.
  5822. APFloat UMax(RHS.getSemantics());
  5823. UMax.convertFromAPInt(APInt::getMaxValue(IntWidth), false,
  5824. APFloat::rmNearestTiesToEven);
  5825. if (UMax < RHS) { // umax < 13123.0
  5826. if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_ULT ||
  5827. Pred == ICmpInst::ICMP_ULE)
  5828. return replaceInstUsesWith(I, Builder.getTrue());
  5829. return replaceInstUsesWith(I, Builder.getFalse());
  5830. }
  5831. }
  5832. if (!LHSUnsigned) {
  5833. // See if the RHS value is < SignedMin.
  5834. APFloat SMin(RHS.getSemantics());
  5835. SMin.convertFromAPInt(APInt::getSignedMinValue(IntWidth), true,
  5836. APFloat::rmNearestTiesToEven);
  5837. if (SMin > RHS) { // smin > 12312.0
  5838. if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_SGT ||
  5839. Pred == ICmpInst::ICMP_SGE)
  5840. return replaceInstUsesWith(I, Builder.getTrue());
  5841. return replaceInstUsesWith(I, Builder.getFalse());
  5842. }
  5843. } else {
  5844. // See if the RHS value is < UnsignedMin.
  5845. APFloat UMin(RHS.getSemantics());
  5846. UMin.convertFromAPInt(APInt::getMinValue(IntWidth), false,
  5847. APFloat::rmNearestTiesToEven);
  5848. if (UMin > RHS) { // umin > 12312.0
  5849. if (Pred == ICmpInst::ICMP_NE || Pred == ICmpInst::ICMP_UGT ||
  5850. Pred == ICmpInst::ICMP_UGE)
  5851. return replaceInstUsesWith(I, Builder.getTrue());
  5852. return replaceInstUsesWith(I, Builder.getFalse());
  5853. }
  5854. }
  5855. // Okay, now we know that the FP constant fits in the range [SMIN, SMAX] or
  5856. // [0, UMAX], but it may still be fractional. See if it is fractional by
  5857. // casting the FP value to the integer value and back, checking for equality.
  5858. // Don't do this for zero, because -0.0 is not fractional.
  5859. Constant *RHSInt = LHSUnsigned
  5860. ? ConstantExpr::getFPToUI(RHSC, IntTy)
  5861. : ConstantExpr::getFPToSI(RHSC, IntTy);
  5862. if (!RHS.isZero()) {
  5863. bool Equal = LHSUnsigned
  5864. ? ConstantExpr::getUIToFP(RHSInt, RHSC->getType()) == RHSC
  5865. : ConstantExpr::getSIToFP(RHSInt, RHSC->getType()) == RHSC;
  5866. if (!Equal) {
  5867. // If we had a comparison against a fractional value, we have to adjust
  5868. // the compare predicate and sometimes the value. RHSC is rounded towards
  5869. // zero at this point.
  5870. switch (Pred) {
  5871. default: llvm_unreachable("Unexpected integer comparison!");
  5872. case ICmpInst::ICMP_NE: // (float)int != 4.4 --> true
  5873. return replaceInstUsesWith(I, Builder.getTrue());
  5874. case ICmpInst::ICMP_EQ: // (float)int == 4.4 --> false
  5875. return replaceInstUsesWith(I, Builder.getFalse());
  5876. case ICmpInst::ICMP_ULE:
  5877. // (float)int <= 4.4 --> int <= 4
  5878. // (float)int <= -4.4 --> false
  5879. if (RHS.isNegative())
  5880. return replaceInstUsesWith(I, Builder.getFalse());
  5881. break;
  5882. case ICmpInst::ICMP_SLE:
  5883. // (float)int <= 4.4 --> int <= 4
  5884. // (float)int <= -4.4 --> int < -4
  5885. if (RHS.isNegative())
  5886. Pred = ICmpInst::ICMP_SLT;
  5887. break;
  5888. case ICmpInst::ICMP_ULT:
  5889. // (float)int < -4.4 --> false
  5890. // (float)int < 4.4 --> int <= 4
  5891. if (RHS.isNegative())
  5892. return replaceInstUsesWith(I, Builder.getFalse());
  5893. Pred = ICmpInst::ICMP_ULE;
  5894. break;
  5895. case ICmpInst::ICMP_SLT:
  5896. // (float)int < -4.4 --> int < -4
  5897. // (float)int < 4.4 --> int <= 4
  5898. if (!RHS.isNegative())
  5899. Pred = ICmpInst::ICMP_SLE;
  5900. break;
  5901. case ICmpInst::ICMP_UGT:
  5902. // (float)int > 4.4 --> int > 4
  5903. // (float)int > -4.4 --> true
  5904. if (RHS.isNegative())
  5905. return replaceInstUsesWith(I, Builder.getTrue());
  5906. break;
  5907. case ICmpInst::ICMP_SGT:
  5908. // (float)int > 4.4 --> int > 4
  5909. // (float)int > -4.4 --> int >= -4
  5910. if (RHS.isNegative())
  5911. Pred = ICmpInst::ICMP_SGE;
  5912. break;
  5913. case ICmpInst::ICMP_UGE:
  5914. // (float)int >= -4.4 --> true
  5915. // (float)int >= 4.4 --> int > 4
  5916. if (RHS.isNegative())
  5917. return replaceInstUsesWith(I, Builder.getTrue());
  5918. Pred = ICmpInst::ICMP_UGT;
  5919. break;
  5920. case ICmpInst::ICMP_SGE:
  5921. // (float)int >= -4.4 --> int >= -4
  5922. // (float)int >= 4.4 --> int > 4
  5923. if (!RHS.isNegative())
  5924. Pred = ICmpInst::ICMP_SGT;
  5925. break;
  5926. }
  5927. }
  5928. }
  5929. // Lower this FP comparison into an appropriate integer version of the
  5930. // comparison.
  5931. return new ICmpInst(Pred, LHSI->getOperand(0), RHSInt);
  5932. }
  5933. /// Fold (C / X) < 0.0 --> X < 0.0 if possible. Swap predicate if necessary.
  5934. static Instruction *foldFCmpReciprocalAndZero(FCmpInst &I, Instruction *LHSI,
  5935. Constant *RHSC) {
  5936. // When C is not 0.0 and infinities are not allowed:
  5937. // (C / X) < 0.0 is a sign-bit test of X
  5938. // (C / X) < 0.0 --> X < 0.0 (if C is positive)
  5939. // (C / X) < 0.0 --> X > 0.0 (if C is negative, swap the predicate)
  5940. //
  5941. // Proof:
  5942. // Multiply (C / X) < 0.0 by X * X / C.
  5943. // - X is non zero, if it is the flag 'ninf' is violated.
  5944. // - C defines the sign of X * X * C. Thus it also defines whether to swap
  5945. // the predicate. C is also non zero by definition.
  5946. //
  5947. // Thus X * X / C is non zero and the transformation is valid. [qed]
  5948. FCmpInst::Predicate Pred = I.getPredicate();
  5949. // Check that predicates are valid.
  5950. if ((Pred != FCmpInst::FCMP_OGT) && (Pred != FCmpInst::FCMP_OLT) &&
  5951. (Pred != FCmpInst::FCMP_OGE) && (Pred != FCmpInst::FCMP_OLE))
  5952. return nullptr;
  5953. // Check that RHS operand is zero.
  5954. if (!match(RHSC, m_AnyZeroFP()))
  5955. return nullptr;
  5956. // Check fastmath flags ('ninf').
  5957. if (!LHSI->hasNoInfs() || !I.hasNoInfs())
  5958. return nullptr;
  5959. // Check the properties of the dividend. It must not be zero to avoid a
  5960. // division by zero (see Proof).
  5961. const APFloat *C;
  5962. if (!match(LHSI->getOperand(0), m_APFloat(C)))
  5963. return nullptr;
  5964. if (C->isZero())
  5965. return nullptr;
  5966. // Get swapped predicate if necessary.
  5967. if (C->isNegative())
  5968. Pred = I.getSwappedPredicate();
  5969. return new FCmpInst(Pred, LHSI->getOperand(1), RHSC, "", &I);
  5970. }
  5971. /// Optimize fabs(X) compared with zero.
  5972. static Instruction *foldFabsWithFcmpZero(FCmpInst &I, InstCombinerImpl &IC) {
  5973. Value *X;
  5974. if (!match(I.getOperand(0), m_FAbs(m_Value(X))))
  5975. return nullptr;
  5976. const APFloat *C;
  5977. if (!match(I.getOperand(1), m_APFloat(C)))
  5978. return nullptr;
  5979. if (!C->isPosZero()) {
  5980. if (!C->isSmallestNormalized())
  5981. return nullptr;
  5982. const Function *F = I.getFunction();
  5983. DenormalMode Mode = F->getDenormalMode(C->getSemantics());
  5984. if (Mode.Input == DenormalMode::PreserveSign ||
  5985. Mode.Input == DenormalMode::PositiveZero) {
  5986. auto replaceFCmp = [](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
  5987. Constant *Zero = ConstantFP::getNullValue(X->getType());
  5988. return new FCmpInst(P, X, Zero, "", I);
  5989. };
  5990. switch (I.getPredicate()) {
  5991. case FCmpInst::FCMP_OLT:
  5992. // fcmp olt fabs(x), smallest_normalized_number -> fcmp oeq x, 0.0
  5993. return replaceFCmp(&I, FCmpInst::FCMP_OEQ, X);
  5994. case FCmpInst::FCMP_UGE:
  5995. // fcmp uge fabs(x), smallest_normalized_number -> fcmp une x, 0.0
  5996. return replaceFCmp(&I, FCmpInst::FCMP_UNE, X);
  5997. case FCmpInst::FCMP_OGE:
  5998. // fcmp oge fabs(x), smallest_normalized_number -> fcmp one x, 0.0
  5999. return replaceFCmp(&I, FCmpInst::FCMP_ONE, X);
  6000. case FCmpInst::FCMP_ULT:
  6001. // fcmp ult fabs(x), smallest_normalized_number -> fcmp ueq x, 0.0
  6002. return replaceFCmp(&I, FCmpInst::FCMP_UEQ, X);
  6003. default:
  6004. break;
  6005. }
  6006. }
  6007. return nullptr;
  6008. }
  6009. auto replacePredAndOp0 = [&IC](FCmpInst *I, FCmpInst::Predicate P, Value *X) {
  6010. I->setPredicate(P);
  6011. return IC.replaceOperand(*I, 0, X);
  6012. };
  6013. switch (I.getPredicate()) {
  6014. case FCmpInst::FCMP_UGE:
  6015. case FCmpInst::FCMP_OLT:
  6016. // fabs(X) >= 0.0 --> true
  6017. // fabs(X) < 0.0 --> false
  6018. llvm_unreachable("fcmp should have simplified");
  6019. case FCmpInst::FCMP_OGT:
  6020. // fabs(X) > 0.0 --> X != 0.0
  6021. return replacePredAndOp0(&I, FCmpInst::FCMP_ONE, X);
  6022. case FCmpInst::FCMP_UGT:
  6023. // fabs(X) u> 0.0 --> X u!= 0.0
  6024. return replacePredAndOp0(&I, FCmpInst::FCMP_UNE, X);
  6025. case FCmpInst::FCMP_OLE:
  6026. // fabs(X) <= 0.0 --> X == 0.0
  6027. return replacePredAndOp0(&I, FCmpInst::FCMP_OEQ, X);
  6028. case FCmpInst::FCMP_ULE:
  6029. // fabs(X) u<= 0.0 --> X u== 0.0
  6030. return replacePredAndOp0(&I, FCmpInst::FCMP_UEQ, X);
  6031. case FCmpInst::FCMP_OGE:
  6032. // fabs(X) >= 0.0 --> !isnan(X)
  6033. assert(!I.hasNoNaNs() && "fcmp should have simplified");
  6034. return replacePredAndOp0(&I, FCmpInst::FCMP_ORD, X);
  6035. case FCmpInst::FCMP_ULT:
  6036. // fabs(X) u< 0.0 --> isnan(X)
  6037. assert(!I.hasNoNaNs() && "fcmp should have simplified");
  6038. return replacePredAndOp0(&I, FCmpInst::FCMP_UNO, X);
  6039. case FCmpInst::FCMP_OEQ:
  6040. case FCmpInst::FCMP_UEQ:
  6041. case FCmpInst::FCMP_ONE:
  6042. case FCmpInst::FCMP_UNE:
  6043. case FCmpInst::FCMP_ORD:
  6044. case FCmpInst::FCMP_UNO:
  6045. // Look through the fabs() because it doesn't change anything but the sign.
  6046. // fabs(X) == 0.0 --> X == 0.0,
  6047. // fabs(X) != 0.0 --> X != 0.0
  6048. // isnan(fabs(X)) --> isnan(X)
  6049. // !isnan(fabs(X) --> !isnan(X)
  6050. return replacePredAndOp0(&I, I.getPredicate(), X);
  6051. default:
  6052. return nullptr;
  6053. }
  6054. }
  6055. static Instruction *foldFCmpFNegCommonOp(FCmpInst &I) {
  6056. CmpInst::Predicate Pred = I.getPredicate();
  6057. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  6058. // Canonicalize fneg as Op1.
  6059. if (match(Op0, m_FNeg(m_Value())) && !match(Op1, m_FNeg(m_Value()))) {
  6060. std::swap(Op0, Op1);
  6061. Pred = I.getSwappedPredicate();
  6062. }
  6063. if (!match(Op1, m_FNeg(m_Specific(Op0))))
  6064. return nullptr;
  6065. // Replace the negated operand with 0.0:
  6066. // fcmp Pred Op0, -Op0 --> fcmp Pred Op0, 0.0
  6067. Constant *Zero = ConstantFP::getNullValue(Op0->getType());
  6068. return new FCmpInst(Pred, Op0, Zero, "", &I);
  6069. }
  6070. Instruction *InstCombinerImpl::visitFCmpInst(FCmpInst &I) {
  6071. bool Changed = false;
  6072. /// Orders the operands of the compare so that they are listed from most
  6073. /// complex to least complex. This puts constants before unary operators,
  6074. /// before binary operators.
  6075. if (getComplexity(I.getOperand(0)) < getComplexity(I.getOperand(1))) {
  6076. I.swapOperands();
  6077. Changed = true;
  6078. }
  6079. const CmpInst::Predicate Pred = I.getPredicate();
  6080. Value *Op0 = I.getOperand(0), *Op1 = I.getOperand(1);
  6081. if (Value *V = simplifyFCmpInst(Pred, Op0, Op1, I.getFastMathFlags(),
  6082. SQ.getWithInstruction(&I)))
  6083. return replaceInstUsesWith(I, V);
  6084. // Simplify 'fcmp pred X, X'
  6085. Type *OpType = Op0->getType();
  6086. assert(OpType == Op1->getType() && "fcmp with different-typed operands?");
  6087. if (Op0 == Op1) {
  6088. switch (Pred) {
  6089. default: break;
  6090. case FCmpInst::FCMP_UNO: // True if unordered: isnan(X) | isnan(Y)
  6091. case FCmpInst::FCMP_ULT: // True if unordered or less than
  6092. case FCmpInst::FCMP_UGT: // True if unordered or greater than
  6093. case FCmpInst::FCMP_UNE: // True if unordered or not equal
  6094. // Canonicalize these to be 'fcmp uno %X, 0.0'.
  6095. I.setPredicate(FCmpInst::FCMP_UNO);
  6096. I.setOperand(1, Constant::getNullValue(OpType));
  6097. return &I;
  6098. case FCmpInst::FCMP_ORD: // True if ordered (no nans)
  6099. case FCmpInst::FCMP_OEQ: // True if ordered and equal
  6100. case FCmpInst::FCMP_OGE: // True if ordered and greater than or equal
  6101. case FCmpInst::FCMP_OLE: // True if ordered and less than or equal
  6102. // Canonicalize these to be 'fcmp ord %X, 0.0'.
  6103. I.setPredicate(FCmpInst::FCMP_ORD);
  6104. I.setOperand(1, Constant::getNullValue(OpType));
  6105. return &I;
  6106. }
  6107. }
  6108. // If we're just checking for a NaN (ORD/UNO) and have a non-NaN operand,
  6109. // then canonicalize the operand to 0.0.
  6110. if (Pred == CmpInst::FCMP_ORD || Pred == CmpInst::FCMP_UNO) {
  6111. if (!match(Op0, m_PosZeroFP()) && isKnownNeverNaN(Op0, &TLI))
  6112. return replaceOperand(I, 0, ConstantFP::getNullValue(OpType));
  6113. if (!match(Op1, m_PosZeroFP()) && isKnownNeverNaN(Op1, &TLI))
  6114. return replaceOperand(I, 1, ConstantFP::getNullValue(OpType));
  6115. }
  6116. // fcmp pred (fneg X), (fneg Y) -> fcmp swap(pred) X, Y
  6117. Value *X, *Y;
  6118. if (match(Op0, m_FNeg(m_Value(X))) && match(Op1, m_FNeg(m_Value(Y))))
  6119. return new FCmpInst(I.getSwappedPredicate(), X, Y, "", &I);
  6120. if (Instruction *R = foldFCmpFNegCommonOp(I))
  6121. return R;
  6122. // Test if the FCmpInst instruction is used exclusively by a select as
  6123. // part of a minimum or maximum operation. If so, refrain from doing
  6124. // any other folding. This helps out other analyses which understand
  6125. // non-obfuscated minimum and maximum idioms, such as ScalarEvolution
  6126. // and CodeGen. And in this case, at least one of the comparison
  6127. // operands has at least one user besides the compare (the select),
  6128. // which would often largely negate the benefit of folding anyway.
  6129. if (I.hasOneUse())
  6130. if (SelectInst *SI = dyn_cast<SelectInst>(I.user_back())) {
  6131. Value *A, *B;
  6132. SelectPatternResult SPR = matchSelectPattern(SI, A, B);
  6133. if (SPR.Flavor != SPF_UNKNOWN)
  6134. return nullptr;
  6135. }
  6136. // The sign of 0.0 is ignored by fcmp, so canonicalize to +0.0:
  6137. // fcmp Pred X, -0.0 --> fcmp Pred X, 0.0
  6138. if (match(Op1, m_AnyZeroFP()) && !match(Op1, m_PosZeroFP()))
  6139. return replaceOperand(I, 1, ConstantFP::getNullValue(OpType));
  6140. // Ignore signbit of bitcasted int when comparing equality to FP 0.0:
  6141. // fcmp oeq/une (bitcast X), 0.0 --> (and X, SignMaskC) ==/!= 0
  6142. if (match(Op1, m_PosZeroFP()) &&
  6143. match(Op0, m_OneUse(m_BitCast(m_Value(X)))) &&
  6144. X->getType()->isVectorTy() == OpType->isVectorTy() &&
  6145. X->getType()->getScalarSizeInBits() == OpType->getScalarSizeInBits()) {
  6146. ICmpInst::Predicate IntPred = ICmpInst::BAD_ICMP_PREDICATE;
  6147. if (Pred == FCmpInst::FCMP_OEQ)
  6148. IntPred = ICmpInst::ICMP_EQ;
  6149. else if (Pred == FCmpInst::FCMP_UNE)
  6150. IntPred = ICmpInst::ICMP_NE;
  6151. if (IntPred != ICmpInst::BAD_ICMP_PREDICATE) {
  6152. Type *IntTy = X->getType();
  6153. const APInt &SignMask = ~APInt::getSignMask(IntTy->getScalarSizeInBits());
  6154. Value *MaskX = Builder.CreateAnd(X, ConstantInt::get(IntTy, SignMask));
  6155. return new ICmpInst(IntPred, MaskX, ConstantInt::getNullValue(IntTy));
  6156. }
  6157. }
  6158. // Handle fcmp with instruction LHS and constant RHS.
  6159. Instruction *LHSI;
  6160. Constant *RHSC;
  6161. if (match(Op0, m_Instruction(LHSI)) && match(Op1, m_Constant(RHSC))) {
  6162. switch (LHSI->getOpcode()) {
  6163. case Instruction::PHI:
  6164. // Only fold fcmp into the PHI if the phi and fcmp are in the same
  6165. // block. If in the same block, we're encouraging jump threading. If
  6166. // not, we are just pessimizing the code by making an i1 phi.
  6167. if (LHSI->getParent() == I.getParent())
  6168. if (Instruction *NV = foldOpIntoPhi(I, cast<PHINode>(LHSI)))
  6169. return NV;
  6170. break;
  6171. case Instruction::SIToFP:
  6172. case Instruction::UIToFP:
  6173. if (Instruction *NV = foldFCmpIntToFPConst(I, LHSI, RHSC))
  6174. return NV;
  6175. break;
  6176. case Instruction::FDiv:
  6177. if (Instruction *NV = foldFCmpReciprocalAndZero(I, LHSI, RHSC))
  6178. return NV;
  6179. break;
  6180. case Instruction::Load:
  6181. if (auto *GEP = dyn_cast<GetElementPtrInst>(LHSI->getOperand(0)))
  6182. if (auto *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0)))
  6183. if (Instruction *Res = foldCmpLoadFromIndexedGlobal(
  6184. cast<LoadInst>(LHSI), GEP, GV, I))
  6185. return Res;
  6186. break;
  6187. }
  6188. }
  6189. if (Instruction *R = foldFabsWithFcmpZero(I, *this))
  6190. return R;
  6191. if (match(Op0, m_FNeg(m_Value(X)))) {
  6192. // fcmp pred (fneg X), C --> fcmp swap(pred) X, -C
  6193. Constant *C;
  6194. if (match(Op1, m_Constant(C)))
  6195. if (Constant *NegC = ConstantFoldUnaryOpOperand(Instruction::FNeg, C, DL))
  6196. return new FCmpInst(I.getSwappedPredicate(), X, NegC, "", &I);
  6197. }
  6198. if (match(Op0, m_FPExt(m_Value(X)))) {
  6199. // fcmp (fpext X), (fpext Y) -> fcmp X, Y
  6200. if (match(Op1, m_FPExt(m_Value(Y))) && X->getType() == Y->getType())
  6201. return new FCmpInst(Pred, X, Y, "", &I);
  6202. const APFloat *C;
  6203. if (match(Op1, m_APFloat(C))) {
  6204. const fltSemantics &FPSem =
  6205. X->getType()->getScalarType()->getFltSemantics();
  6206. bool Lossy;
  6207. APFloat TruncC = *C;
  6208. TruncC.convert(FPSem, APFloat::rmNearestTiesToEven, &Lossy);
  6209. if (Lossy) {
  6210. // X can't possibly equal the higher-precision constant, so reduce any
  6211. // equality comparison.
  6212. // TODO: Other predicates can be handled via getFCmpCode().
  6213. switch (Pred) {
  6214. case FCmpInst::FCMP_OEQ:
  6215. // X is ordered and equal to an impossible constant --> false
  6216. return replaceInstUsesWith(I, ConstantInt::getFalse(I.getType()));
  6217. case FCmpInst::FCMP_ONE:
  6218. // X is ordered and not equal to an impossible constant --> ordered
  6219. return new FCmpInst(FCmpInst::FCMP_ORD, X,
  6220. ConstantFP::getNullValue(X->getType()));
  6221. case FCmpInst::FCMP_UEQ:
  6222. // X is unordered or equal to an impossible constant --> unordered
  6223. return new FCmpInst(FCmpInst::FCMP_UNO, X,
  6224. ConstantFP::getNullValue(X->getType()));
  6225. case FCmpInst::FCMP_UNE:
  6226. // X is unordered or not equal to an impossible constant --> true
  6227. return replaceInstUsesWith(I, ConstantInt::getTrue(I.getType()));
  6228. default:
  6229. break;
  6230. }
  6231. }
  6232. // fcmp (fpext X), C -> fcmp X, (fptrunc C) if fptrunc is lossless
  6233. // Avoid lossy conversions and denormals.
  6234. // Zero is a special case that's OK to convert.
  6235. APFloat Fabs = TruncC;
  6236. Fabs.clearSign();
  6237. if (!Lossy &&
  6238. (Fabs.isZero() || !(Fabs < APFloat::getSmallestNormalized(FPSem)))) {
  6239. Constant *NewC = ConstantFP::get(X->getType(), TruncC);
  6240. return new FCmpInst(Pred, X, NewC, "", &I);
  6241. }
  6242. }
  6243. }
  6244. // Convert a sign-bit test of an FP value into a cast and integer compare.
  6245. // TODO: Simplify if the copysign constant is 0.0 or NaN.
  6246. // TODO: Handle non-zero compare constants.
  6247. // TODO: Handle other predicates.
  6248. const APFloat *C;
  6249. if (match(Op0, m_OneUse(m_Intrinsic<Intrinsic::copysign>(m_APFloat(C),
  6250. m_Value(X)))) &&
  6251. match(Op1, m_AnyZeroFP()) && !C->isZero() && !C->isNaN()) {
  6252. Type *IntType = Builder.getIntNTy(X->getType()->getScalarSizeInBits());
  6253. if (auto *VecTy = dyn_cast<VectorType>(OpType))
  6254. IntType = VectorType::get(IntType, VecTy->getElementCount());
  6255. // copysign(non-zero constant, X) < 0.0 --> (bitcast X) < 0
  6256. if (Pred == FCmpInst::FCMP_OLT) {
  6257. Value *IntX = Builder.CreateBitCast(X, IntType);
  6258. return new ICmpInst(ICmpInst::ICMP_SLT, IntX,
  6259. ConstantInt::getNullValue(IntType));
  6260. }
  6261. }
  6262. {
  6263. Value *CanonLHS = nullptr, *CanonRHS = nullptr;
  6264. match(Op0, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonLHS)));
  6265. match(Op1, m_Intrinsic<Intrinsic::canonicalize>(m_Value(CanonRHS)));
  6266. // (canonicalize(x) == x) => (x == x)
  6267. if (CanonLHS == Op1)
  6268. return new FCmpInst(Pred, Op1, Op1, "", &I);
  6269. // (x == canonicalize(x)) => (x == x)
  6270. if (CanonRHS == Op0)
  6271. return new FCmpInst(Pred, Op0, Op0, "", &I);
  6272. // (canonicalize(x) == canonicalize(y)) => (x == y)
  6273. if (CanonLHS && CanonRHS)
  6274. return new FCmpInst(Pred, CanonLHS, CanonRHS, "", &I);
  6275. }
  6276. if (I.getType()->isVectorTy())
  6277. if (Instruction *Res = foldVectorCmp(I, Builder))
  6278. return Res;
  6279. return Changed ? &I : nullptr;
  6280. }