InstCombineCompares.cpp 245 KB

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