InstCombineCompares.cpp 262 KB

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