ScalarEvolution.cpp 580 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182
  1. //===- ScalarEvolution.cpp - Scalar Evolution Analysis --------------------===//
  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 contains the implementation of the scalar evolution analysis
  10. // engine, which is used primarily to analyze expressions involving induction
  11. // variables in loops.
  12. //
  13. // There are several aspects to this library. First is the representation of
  14. // scalar expressions, which are represented as subclasses of the SCEV class.
  15. // These classes are used to represent certain types of subexpressions that we
  16. // can handle. We only create one SCEV of a particular shape, so
  17. // pointer-comparisons for equality are legal.
  18. //
  19. // One important aspect of the SCEV objects is that they are never cyclic, even
  20. // if there is a cycle in the dataflow for an expression (ie, a PHI node). If
  21. // the PHI node is one of the idioms that we can represent (e.g., a polynomial
  22. // recurrence) then we represent it directly as a recurrence node, otherwise we
  23. // represent it as a SCEVUnknown node.
  24. //
  25. // In addition to being able to represent expressions of various types, we also
  26. // have folders that are used to build the *canonical* representation for a
  27. // particular expression. These folders are capable of using a variety of
  28. // rewrite rules to simplify the expressions.
  29. //
  30. // Once the folders are defined, we can implement the more interesting
  31. // higher-level code, such as the code that recognizes PHI nodes of various
  32. // types, computes the execution count of a loop, etc.
  33. //
  34. // TODO: We should use these routines and value representations to implement
  35. // dependence analysis!
  36. //
  37. //===----------------------------------------------------------------------===//
  38. //
  39. // There are several good references for the techniques used in this analysis.
  40. //
  41. // Chains of recurrences -- a method to expedite the evaluation
  42. // of closed-form functions
  43. // Olaf Bachmann, Paul S. Wang, Eugene V. Zima
  44. //
  45. // On computational properties of chains of recurrences
  46. // Eugene V. Zima
  47. //
  48. // Symbolic Evaluation of Chains of Recurrences for Loop Optimization
  49. // Robert A. van Engelen
  50. //
  51. // Efficient Symbolic Analysis for Optimizing Compilers
  52. // Robert A. van Engelen
  53. //
  54. // Using the chains of recurrences algebra for data dependence testing and
  55. // induction variable substitution
  56. // MS Thesis, Johnie Birch
  57. //
  58. //===----------------------------------------------------------------------===//
  59. #include "llvm/Analysis/ScalarEvolution.h"
  60. #include "llvm/ADT/APInt.h"
  61. #include "llvm/ADT/ArrayRef.h"
  62. #include "llvm/ADT/DenseMap.h"
  63. #include "llvm/ADT/DepthFirstIterator.h"
  64. #include "llvm/ADT/EquivalenceClasses.h"
  65. #include "llvm/ADT/FoldingSet.h"
  66. #include "llvm/ADT/STLExtras.h"
  67. #include "llvm/ADT/ScopeExit.h"
  68. #include "llvm/ADT/Sequence.h"
  69. #include "llvm/ADT/SmallPtrSet.h"
  70. #include "llvm/ADT/SmallSet.h"
  71. #include "llvm/ADT/SmallVector.h"
  72. #include "llvm/ADT/Statistic.h"
  73. #include "llvm/ADT/StringRef.h"
  74. #include "llvm/Analysis/AssumptionCache.h"
  75. #include "llvm/Analysis/ConstantFolding.h"
  76. #include "llvm/Analysis/InstructionSimplify.h"
  77. #include "llvm/Analysis/LoopInfo.h"
  78. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  79. #include "llvm/Analysis/TargetLibraryInfo.h"
  80. #include "llvm/Analysis/ValueTracking.h"
  81. #include "llvm/Config/llvm-config.h"
  82. #include "llvm/IR/Argument.h"
  83. #include "llvm/IR/BasicBlock.h"
  84. #include "llvm/IR/CFG.h"
  85. #include "llvm/IR/Constant.h"
  86. #include "llvm/IR/ConstantRange.h"
  87. #include "llvm/IR/Constants.h"
  88. #include "llvm/IR/DataLayout.h"
  89. #include "llvm/IR/DerivedTypes.h"
  90. #include "llvm/IR/Dominators.h"
  91. #include "llvm/IR/Function.h"
  92. #include "llvm/IR/GlobalAlias.h"
  93. #include "llvm/IR/GlobalValue.h"
  94. #include "llvm/IR/InstIterator.h"
  95. #include "llvm/IR/InstrTypes.h"
  96. #include "llvm/IR/Instruction.h"
  97. #include "llvm/IR/Instructions.h"
  98. #include "llvm/IR/IntrinsicInst.h"
  99. #include "llvm/IR/Intrinsics.h"
  100. #include "llvm/IR/LLVMContext.h"
  101. #include "llvm/IR/Operator.h"
  102. #include "llvm/IR/PatternMatch.h"
  103. #include "llvm/IR/Type.h"
  104. #include "llvm/IR/Use.h"
  105. #include "llvm/IR/User.h"
  106. #include "llvm/IR/Value.h"
  107. #include "llvm/IR/Verifier.h"
  108. #include "llvm/InitializePasses.h"
  109. #include "llvm/Pass.h"
  110. #include "llvm/Support/Casting.h"
  111. #include "llvm/Support/CommandLine.h"
  112. #include "llvm/Support/Compiler.h"
  113. #include "llvm/Support/Debug.h"
  114. #include "llvm/Support/ErrorHandling.h"
  115. #include "llvm/Support/KnownBits.h"
  116. #include "llvm/Support/SaveAndRestore.h"
  117. #include "llvm/Support/raw_ostream.h"
  118. #include <algorithm>
  119. #include <cassert>
  120. #include <climits>
  121. #include <cstdint>
  122. #include <cstdlib>
  123. #include <map>
  124. #include <memory>
  125. #include <numeric>
  126. #include <optional>
  127. #include <tuple>
  128. #include <utility>
  129. #include <vector>
  130. using namespace llvm;
  131. using namespace PatternMatch;
  132. #define DEBUG_TYPE "scalar-evolution"
  133. STATISTIC(NumTripCountsComputed,
  134. "Number of loops with predictable loop counts");
  135. STATISTIC(NumTripCountsNotComputed,
  136. "Number of loops without predictable loop counts");
  137. STATISTIC(NumBruteForceTripCountsComputed,
  138. "Number of loops with trip counts computed by force");
  139. #ifdef EXPENSIVE_CHECKS
  140. bool llvm::VerifySCEV = true;
  141. #else
  142. bool llvm::VerifySCEV = false;
  143. #endif
  144. static cl::opt<unsigned>
  145. MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
  146. cl::desc("Maximum number of iterations SCEV will "
  147. "symbolically execute a constant "
  148. "derived loop"),
  149. cl::init(100));
  150. static cl::opt<bool, true> VerifySCEVOpt(
  151. "verify-scev", cl::Hidden, cl::location(VerifySCEV),
  152. cl::desc("Verify ScalarEvolution's backedge taken counts (slow)"));
  153. static cl::opt<bool> VerifySCEVStrict(
  154. "verify-scev-strict", cl::Hidden,
  155. cl::desc("Enable stricter verification with -verify-scev is passed"));
  156. static cl::opt<bool>
  157. VerifySCEVMap("verify-scev-maps", cl::Hidden,
  158. cl::desc("Verify no dangling value in ScalarEvolution's "
  159. "ExprValueMap (slow)"));
  160. static cl::opt<bool> VerifyIR(
  161. "scev-verify-ir", cl::Hidden,
  162. cl::desc("Verify IR correctness when making sensitive SCEV queries (slow)"),
  163. cl::init(false));
  164. static cl::opt<unsigned> MulOpsInlineThreshold(
  165. "scev-mulops-inline-threshold", cl::Hidden,
  166. cl::desc("Threshold for inlining multiplication operands into a SCEV"),
  167. cl::init(32));
  168. static cl::opt<unsigned> AddOpsInlineThreshold(
  169. "scev-addops-inline-threshold", cl::Hidden,
  170. cl::desc("Threshold for inlining addition operands into a SCEV"),
  171. cl::init(500));
  172. static cl::opt<unsigned> MaxSCEVCompareDepth(
  173. "scalar-evolution-max-scev-compare-depth", cl::Hidden,
  174. cl::desc("Maximum depth of recursive SCEV complexity comparisons"),
  175. cl::init(32));
  176. static cl::opt<unsigned> MaxSCEVOperationsImplicationDepth(
  177. "scalar-evolution-max-scev-operations-implication-depth", cl::Hidden,
  178. cl::desc("Maximum depth of recursive SCEV operations implication analysis"),
  179. cl::init(2));
  180. static cl::opt<unsigned> MaxValueCompareDepth(
  181. "scalar-evolution-max-value-compare-depth", cl::Hidden,
  182. cl::desc("Maximum depth of recursive value complexity comparisons"),
  183. cl::init(2));
  184. static cl::opt<unsigned>
  185. MaxArithDepth("scalar-evolution-max-arith-depth", cl::Hidden,
  186. cl::desc("Maximum depth of recursive arithmetics"),
  187. cl::init(32));
  188. static cl::opt<unsigned> MaxConstantEvolvingDepth(
  189. "scalar-evolution-max-constant-evolving-depth", cl::Hidden,
  190. cl::desc("Maximum depth of recursive constant evolving"), cl::init(32));
  191. static cl::opt<unsigned>
  192. MaxCastDepth("scalar-evolution-max-cast-depth", cl::Hidden,
  193. cl::desc("Maximum depth of recursive SExt/ZExt/Trunc"),
  194. cl::init(8));
  195. static cl::opt<unsigned>
  196. MaxAddRecSize("scalar-evolution-max-add-rec-size", cl::Hidden,
  197. cl::desc("Max coefficients in AddRec during evolving"),
  198. cl::init(8));
  199. static cl::opt<unsigned>
  200. HugeExprThreshold("scalar-evolution-huge-expr-threshold", cl::Hidden,
  201. cl::desc("Size of the expression which is considered huge"),
  202. cl::init(4096));
  203. static cl::opt<unsigned> RangeIterThreshold(
  204. "scev-range-iter-threshold", cl::Hidden,
  205. cl::desc("Threshold for switching to iteratively computing SCEV ranges"),
  206. cl::init(32));
  207. static cl::opt<bool>
  208. ClassifyExpressions("scalar-evolution-classify-expressions",
  209. cl::Hidden, cl::init(true),
  210. cl::desc("When printing analysis, include information on every instruction"));
  211. static cl::opt<bool> UseExpensiveRangeSharpening(
  212. "scalar-evolution-use-expensive-range-sharpening", cl::Hidden,
  213. cl::init(false),
  214. cl::desc("Use more powerful methods of sharpening expression ranges. May "
  215. "be costly in terms of compile time"));
  216. static cl::opt<unsigned> MaxPhiSCCAnalysisSize(
  217. "scalar-evolution-max-scc-analysis-depth", cl::Hidden,
  218. cl::desc("Maximum amount of nodes to process while searching SCEVUnknown "
  219. "Phi strongly connected components"),
  220. cl::init(8));
  221. static cl::opt<bool>
  222. EnableFiniteLoopControl("scalar-evolution-finite-loop", cl::Hidden,
  223. cl::desc("Handle <= and >= in finite loops"),
  224. cl::init(true));
  225. static cl::opt<bool> UseContextForNoWrapFlagInference(
  226. "scalar-evolution-use-context-for-no-wrap-flag-strenghening", cl::Hidden,
  227. cl::desc("Infer nuw/nsw flags using context where suitable"),
  228. cl::init(true));
  229. //===----------------------------------------------------------------------===//
  230. // SCEV class definitions
  231. //===----------------------------------------------------------------------===//
  232. //===----------------------------------------------------------------------===//
  233. // Implementation of the SCEV class.
  234. //
  235. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  236. LLVM_DUMP_METHOD void SCEV::dump() const {
  237. print(dbgs());
  238. dbgs() << '\n';
  239. }
  240. #endif
  241. void SCEV::print(raw_ostream &OS) const {
  242. switch (getSCEVType()) {
  243. case scConstant:
  244. cast<SCEVConstant>(this)->getValue()->printAsOperand(OS, false);
  245. return;
  246. case scPtrToInt: {
  247. const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(this);
  248. const SCEV *Op = PtrToInt->getOperand();
  249. OS << "(ptrtoint " << *Op->getType() << " " << *Op << " to "
  250. << *PtrToInt->getType() << ")";
  251. return;
  252. }
  253. case scTruncate: {
  254. const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(this);
  255. const SCEV *Op = Trunc->getOperand();
  256. OS << "(trunc " << *Op->getType() << " " << *Op << " to "
  257. << *Trunc->getType() << ")";
  258. return;
  259. }
  260. case scZeroExtend: {
  261. const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(this);
  262. const SCEV *Op = ZExt->getOperand();
  263. OS << "(zext " << *Op->getType() << " " << *Op << " to "
  264. << *ZExt->getType() << ")";
  265. return;
  266. }
  267. case scSignExtend: {
  268. const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(this);
  269. const SCEV *Op = SExt->getOperand();
  270. OS << "(sext " << *Op->getType() << " " << *Op << " to "
  271. << *SExt->getType() << ")";
  272. return;
  273. }
  274. case scAddRecExpr: {
  275. const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(this);
  276. OS << "{" << *AR->getOperand(0);
  277. for (unsigned i = 1, e = AR->getNumOperands(); i != e; ++i)
  278. OS << ",+," << *AR->getOperand(i);
  279. OS << "}<";
  280. if (AR->hasNoUnsignedWrap())
  281. OS << "nuw><";
  282. if (AR->hasNoSignedWrap())
  283. OS << "nsw><";
  284. if (AR->hasNoSelfWrap() &&
  285. !AR->getNoWrapFlags((NoWrapFlags)(FlagNUW | FlagNSW)))
  286. OS << "nw><";
  287. AR->getLoop()->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  288. OS << ">";
  289. return;
  290. }
  291. case scAddExpr:
  292. case scMulExpr:
  293. case scUMaxExpr:
  294. case scSMaxExpr:
  295. case scUMinExpr:
  296. case scSMinExpr:
  297. case scSequentialUMinExpr: {
  298. const SCEVNAryExpr *NAry = cast<SCEVNAryExpr>(this);
  299. const char *OpStr = nullptr;
  300. switch (NAry->getSCEVType()) {
  301. case scAddExpr: OpStr = " + "; break;
  302. case scMulExpr: OpStr = " * "; break;
  303. case scUMaxExpr: OpStr = " umax "; break;
  304. case scSMaxExpr: OpStr = " smax "; break;
  305. case scUMinExpr:
  306. OpStr = " umin ";
  307. break;
  308. case scSMinExpr:
  309. OpStr = " smin ";
  310. break;
  311. case scSequentialUMinExpr:
  312. OpStr = " umin_seq ";
  313. break;
  314. default:
  315. llvm_unreachable("There are no other nary expression types.");
  316. }
  317. OS << "(";
  318. ListSeparator LS(OpStr);
  319. for (const SCEV *Op : NAry->operands())
  320. OS << LS << *Op;
  321. OS << ")";
  322. switch (NAry->getSCEVType()) {
  323. case scAddExpr:
  324. case scMulExpr:
  325. if (NAry->hasNoUnsignedWrap())
  326. OS << "<nuw>";
  327. if (NAry->hasNoSignedWrap())
  328. OS << "<nsw>";
  329. break;
  330. default:
  331. // Nothing to print for other nary expressions.
  332. break;
  333. }
  334. return;
  335. }
  336. case scUDivExpr: {
  337. const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(this);
  338. OS << "(" << *UDiv->getLHS() << " /u " << *UDiv->getRHS() << ")";
  339. return;
  340. }
  341. case scUnknown: {
  342. const SCEVUnknown *U = cast<SCEVUnknown>(this);
  343. Type *AllocTy;
  344. if (U->isSizeOf(AllocTy)) {
  345. OS << "sizeof(" << *AllocTy << ")";
  346. return;
  347. }
  348. if (U->isAlignOf(AllocTy)) {
  349. OS << "alignof(" << *AllocTy << ")";
  350. return;
  351. }
  352. Type *CTy;
  353. Constant *FieldNo;
  354. if (U->isOffsetOf(CTy, FieldNo)) {
  355. OS << "offsetof(" << *CTy << ", ";
  356. FieldNo->printAsOperand(OS, false);
  357. OS << ")";
  358. return;
  359. }
  360. // Otherwise just print it normally.
  361. U->getValue()->printAsOperand(OS, false);
  362. return;
  363. }
  364. case scCouldNotCompute:
  365. OS << "***COULDNOTCOMPUTE***";
  366. return;
  367. }
  368. llvm_unreachable("Unknown SCEV kind!");
  369. }
  370. Type *SCEV::getType() const {
  371. switch (getSCEVType()) {
  372. case scConstant:
  373. return cast<SCEVConstant>(this)->getType();
  374. case scPtrToInt:
  375. case scTruncate:
  376. case scZeroExtend:
  377. case scSignExtend:
  378. return cast<SCEVCastExpr>(this)->getType();
  379. case scAddRecExpr:
  380. return cast<SCEVAddRecExpr>(this)->getType();
  381. case scMulExpr:
  382. return cast<SCEVMulExpr>(this)->getType();
  383. case scUMaxExpr:
  384. case scSMaxExpr:
  385. case scUMinExpr:
  386. case scSMinExpr:
  387. return cast<SCEVMinMaxExpr>(this)->getType();
  388. case scSequentialUMinExpr:
  389. return cast<SCEVSequentialMinMaxExpr>(this)->getType();
  390. case scAddExpr:
  391. return cast<SCEVAddExpr>(this)->getType();
  392. case scUDivExpr:
  393. return cast<SCEVUDivExpr>(this)->getType();
  394. case scUnknown:
  395. return cast<SCEVUnknown>(this)->getType();
  396. case scCouldNotCompute:
  397. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  398. }
  399. llvm_unreachable("Unknown SCEV kind!");
  400. }
  401. ArrayRef<const SCEV *> SCEV::operands() const {
  402. switch (getSCEVType()) {
  403. case scConstant:
  404. case scUnknown:
  405. return {};
  406. case scPtrToInt:
  407. case scTruncate:
  408. case scZeroExtend:
  409. case scSignExtend:
  410. return cast<SCEVCastExpr>(this)->operands();
  411. case scAddRecExpr:
  412. case scAddExpr:
  413. case scMulExpr:
  414. case scUMaxExpr:
  415. case scSMaxExpr:
  416. case scUMinExpr:
  417. case scSMinExpr:
  418. case scSequentialUMinExpr:
  419. return cast<SCEVNAryExpr>(this)->operands();
  420. case scUDivExpr:
  421. return cast<SCEVUDivExpr>(this)->operands();
  422. case scCouldNotCompute:
  423. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  424. }
  425. llvm_unreachable("Unknown SCEV kind!");
  426. }
  427. bool SCEV::isZero() const {
  428. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
  429. return SC->getValue()->isZero();
  430. return false;
  431. }
  432. bool SCEV::isOne() const {
  433. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
  434. return SC->getValue()->isOne();
  435. return false;
  436. }
  437. bool SCEV::isAllOnesValue() const {
  438. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
  439. return SC->getValue()->isMinusOne();
  440. return false;
  441. }
  442. bool SCEV::isNonConstantNegative() const {
  443. const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(this);
  444. if (!Mul) return false;
  445. // If there is a constant factor, it will be first.
  446. const SCEVConstant *SC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
  447. if (!SC) return false;
  448. // Return true if the value is negative, this matches things like (-42 * V).
  449. return SC->getAPInt().isNegative();
  450. }
  451. SCEVCouldNotCompute::SCEVCouldNotCompute() :
  452. SCEV(FoldingSetNodeIDRef(), scCouldNotCompute, 0) {}
  453. bool SCEVCouldNotCompute::classof(const SCEV *S) {
  454. return S->getSCEVType() == scCouldNotCompute;
  455. }
  456. const SCEV *ScalarEvolution::getConstant(ConstantInt *V) {
  457. FoldingSetNodeID ID;
  458. ID.AddInteger(scConstant);
  459. ID.AddPointer(V);
  460. void *IP = nullptr;
  461. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
  462. SCEV *S = new (SCEVAllocator) SCEVConstant(ID.Intern(SCEVAllocator), V);
  463. UniqueSCEVs.InsertNode(S, IP);
  464. return S;
  465. }
  466. const SCEV *ScalarEvolution::getConstant(const APInt &Val) {
  467. return getConstant(ConstantInt::get(getContext(), Val));
  468. }
  469. const SCEV *
  470. ScalarEvolution::getConstant(Type *Ty, uint64_t V, bool isSigned) {
  471. IntegerType *ITy = cast<IntegerType>(getEffectiveSCEVType(Ty));
  472. return getConstant(ConstantInt::get(ITy, V, isSigned));
  473. }
  474. SCEVCastExpr::SCEVCastExpr(const FoldingSetNodeIDRef ID, SCEVTypes SCEVTy,
  475. const SCEV *op, Type *ty)
  476. : SCEV(ID, SCEVTy, computeExpressionSize(op)), Op(op), Ty(ty) {}
  477. SCEVPtrToIntExpr::SCEVPtrToIntExpr(const FoldingSetNodeIDRef ID, const SCEV *Op,
  478. Type *ITy)
  479. : SCEVCastExpr(ID, scPtrToInt, Op, ITy) {
  480. assert(getOperand()->getType()->isPointerTy() && Ty->isIntegerTy() &&
  481. "Must be a non-bit-width-changing pointer-to-integer cast!");
  482. }
  483. SCEVIntegralCastExpr::SCEVIntegralCastExpr(const FoldingSetNodeIDRef ID,
  484. SCEVTypes SCEVTy, const SCEV *op,
  485. Type *ty)
  486. : SCEVCastExpr(ID, SCEVTy, op, ty) {}
  487. SCEVTruncateExpr::SCEVTruncateExpr(const FoldingSetNodeIDRef ID, const SCEV *op,
  488. Type *ty)
  489. : SCEVIntegralCastExpr(ID, scTruncate, op, ty) {
  490. assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  491. "Cannot truncate non-integer value!");
  492. }
  493. SCEVZeroExtendExpr::SCEVZeroExtendExpr(const FoldingSetNodeIDRef ID,
  494. const SCEV *op, Type *ty)
  495. : SCEVIntegralCastExpr(ID, scZeroExtend, op, ty) {
  496. assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  497. "Cannot zero extend non-integer value!");
  498. }
  499. SCEVSignExtendExpr::SCEVSignExtendExpr(const FoldingSetNodeIDRef ID,
  500. const SCEV *op, Type *ty)
  501. : SCEVIntegralCastExpr(ID, scSignExtend, op, ty) {
  502. assert(getOperand()->getType()->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  503. "Cannot sign extend non-integer value!");
  504. }
  505. void SCEVUnknown::deleted() {
  506. // Clear this SCEVUnknown from various maps.
  507. SE->forgetMemoizedResults(this);
  508. // Remove this SCEVUnknown from the uniquing map.
  509. SE->UniqueSCEVs.RemoveNode(this);
  510. // Release the value.
  511. setValPtr(nullptr);
  512. }
  513. void SCEVUnknown::allUsesReplacedWith(Value *New) {
  514. // Clear this SCEVUnknown from various maps.
  515. SE->forgetMemoizedResults(this);
  516. // Remove this SCEVUnknown from the uniquing map.
  517. SE->UniqueSCEVs.RemoveNode(this);
  518. // Replace the value pointer in case someone is still using this SCEVUnknown.
  519. setValPtr(New);
  520. }
  521. bool SCEVUnknown::isSizeOf(Type *&AllocTy) const {
  522. if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
  523. if (VCE->getOpcode() == Instruction::PtrToInt)
  524. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
  525. if (CE->getOpcode() == Instruction::GetElementPtr &&
  526. CE->getOperand(0)->isNullValue() &&
  527. CE->getNumOperands() == 2)
  528. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(1)))
  529. if (CI->isOne()) {
  530. AllocTy = cast<GEPOperator>(CE)->getSourceElementType();
  531. return true;
  532. }
  533. return false;
  534. }
  535. bool SCEVUnknown::isAlignOf(Type *&AllocTy) const {
  536. if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
  537. if (VCE->getOpcode() == Instruction::PtrToInt)
  538. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
  539. if (CE->getOpcode() == Instruction::GetElementPtr &&
  540. CE->getOperand(0)->isNullValue()) {
  541. Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
  542. if (StructType *STy = dyn_cast<StructType>(Ty))
  543. if (!STy->isPacked() &&
  544. CE->getNumOperands() == 3 &&
  545. CE->getOperand(1)->isNullValue()) {
  546. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(2)))
  547. if (CI->isOne() &&
  548. STy->getNumElements() == 2 &&
  549. STy->getElementType(0)->isIntegerTy(1)) {
  550. AllocTy = STy->getElementType(1);
  551. return true;
  552. }
  553. }
  554. }
  555. return false;
  556. }
  557. bool SCEVUnknown::isOffsetOf(Type *&CTy, Constant *&FieldNo) const {
  558. if (ConstantExpr *VCE = dyn_cast<ConstantExpr>(getValue()))
  559. if (VCE->getOpcode() == Instruction::PtrToInt)
  560. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(VCE->getOperand(0)))
  561. if (CE->getOpcode() == Instruction::GetElementPtr &&
  562. CE->getNumOperands() == 3 &&
  563. CE->getOperand(0)->isNullValue() &&
  564. CE->getOperand(1)->isNullValue()) {
  565. Type *Ty = cast<GEPOperator>(CE)->getSourceElementType();
  566. // Ignore vector types here so that ScalarEvolutionExpander doesn't
  567. // emit getelementptrs that index into vectors.
  568. if (Ty->isStructTy() || Ty->isArrayTy()) {
  569. CTy = Ty;
  570. FieldNo = CE->getOperand(2);
  571. return true;
  572. }
  573. }
  574. return false;
  575. }
  576. //===----------------------------------------------------------------------===//
  577. // SCEV Utilities
  578. //===----------------------------------------------------------------------===//
  579. /// Compare the two values \p LV and \p RV in terms of their "complexity" where
  580. /// "complexity" is a partial (and somewhat ad-hoc) relation used to order
  581. /// operands in SCEV expressions. \p EqCache is a set of pairs of values that
  582. /// have been previously deemed to be "equally complex" by this routine. It is
  583. /// intended to avoid exponential time complexity in cases like:
  584. ///
  585. /// %a = f(%x, %y)
  586. /// %b = f(%a, %a)
  587. /// %c = f(%b, %b)
  588. ///
  589. /// %d = f(%x, %y)
  590. /// %e = f(%d, %d)
  591. /// %f = f(%e, %e)
  592. ///
  593. /// CompareValueComplexity(%f, %c)
  594. ///
  595. /// Since we do not continue running this routine on expression trees once we
  596. /// have seen unequal values, there is no need to track them in the cache.
  597. static int
  598. CompareValueComplexity(EquivalenceClasses<const Value *> &EqCacheValue,
  599. const LoopInfo *const LI, Value *LV, Value *RV,
  600. unsigned Depth) {
  601. if (Depth > MaxValueCompareDepth || EqCacheValue.isEquivalent(LV, RV))
  602. return 0;
  603. // Order pointer values after integer values. This helps SCEVExpander form
  604. // GEPs.
  605. bool LIsPointer = LV->getType()->isPointerTy(),
  606. RIsPointer = RV->getType()->isPointerTy();
  607. if (LIsPointer != RIsPointer)
  608. return (int)LIsPointer - (int)RIsPointer;
  609. // Compare getValueID values.
  610. unsigned LID = LV->getValueID(), RID = RV->getValueID();
  611. if (LID != RID)
  612. return (int)LID - (int)RID;
  613. // Sort arguments by their position.
  614. if (const auto *LA = dyn_cast<Argument>(LV)) {
  615. const auto *RA = cast<Argument>(RV);
  616. unsigned LArgNo = LA->getArgNo(), RArgNo = RA->getArgNo();
  617. return (int)LArgNo - (int)RArgNo;
  618. }
  619. if (const auto *LGV = dyn_cast<GlobalValue>(LV)) {
  620. const auto *RGV = cast<GlobalValue>(RV);
  621. const auto IsGVNameSemantic = [&](const GlobalValue *GV) {
  622. auto LT = GV->getLinkage();
  623. return !(GlobalValue::isPrivateLinkage(LT) ||
  624. GlobalValue::isInternalLinkage(LT));
  625. };
  626. // Use the names to distinguish the two values, but only if the
  627. // names are semantically important.
  628. if (IsGVNameSemantic(LGV) && IsGVNameSemantic(RGV))
  629. return LGV->getName().compare(RGV->getName());
  630. }
  631. // For instructions, compare their loop depth, and their operand count. This
  632. // is pretty loose.
  633. if (const auto *LInst = dyn_cast<Instruction>(LV)) {
  634. const auto *RInst = cast<Instruction>(RV);
  635. // Compare loop depths.
  636. const BasicBlock *LParent = LInst->getParent(),
  637. *RParent = RInst->getParent();
  638. if (LParent != RParent) {
  639. unsigned LDepth = LI->getLoopDepth(LParent),
  640. RDepth = LI->getLoopDepth(RParent);
  641. if (LDepth != RDepth)
  642. return (int)LDepth - (int)RDepth;
  643. }
  644. // Compare the number of operands.
  645. unsigned LNumOps = LInst->getNumOperands(),
  646. RNumOps = RInst->getNumOperands();
  647. if (LNumOps != RNumOps)
  648. return (int)LNumOps - (int)RNumOps;
  649. for (unsigned Idx : seq(0u, LNumOps)) {
  650. int Result =
  651. CompareValueComplexity(EqCacheValue, LI, LInst->getOperand(Idx),
  652. RInst->getOperand(Idx), Depth + 1);
  653. if (Result != 0)
  654. return Result;
  655. }
  656. }
  657. EqCacheValue.unionSets(LV, RV);
  658. return 0;
  659. }
  660. // Return negative, zero, or positive, if LHS is less than, equal to, or greater
  661. // than RHS, respectively. A three-way result allows recursive comparisons to be
  662. // more efficient.
  663. // If the max analysis depth was reached, return std::nullopt, assuming we do
  664. // not know if they are equivalent for sure.
  665. static std::optional<int>
  666. CompareSCEVComplexity(EquivalenceClasses<const SCEV *> &EqCacheSCEV,
  667. EquivalenceClasses<const Value *> &EqCacheValue,
  668. const LoopInfo *const LI, const SCEV *LHS,
  669. const SCEV *RHS, DominatorTree &DT, unsigned Depth = 0) {
  670. // Fast-path: SCEVs are uniqued so we can do a quick equality check.
  671. if (LHS == RHS)
  672. return 0;
  673. // Primarily, sort the SCEVs by their getSCEVType().
  674. SCEVTypes LType = LHS->getSCEVType(), RType = RHS->getSCEVType();
  675. if (LType != RType)
  676. return (int)LType - (int)RType;
  677. if (EqCacheSCEV.isEquivalent(LHS, RHS))
  678. return 0;
  679. if (Depth > MaxSCEVCompareDepth)
  680. return std::nullopt;
  681. // Aside from the getSCEVType() ordering, the particular ordering
  682. // isn't very important except that it's beneficial to be consistent,
  683. // so that (a + b) and (b + a) don't end up as different expressions.
  684. switch (LType) {
  685. case scUnknown: {
  686. const SCEVUnknown *LU = cast<SCEVUnknown>(LHS);
  687. const SCEVUnknown *RU = cast<SCEVUnknown>(RHS);
  688. int X = CompareValueComplexity(EqCacheValue, LI, LU->getValue(),
  689. RU->getValue(), Depth + 1);
  690. if (X == 0)
  691. EqCacheSCEV.unionSets(LHS, RHS);
  692. return X;
  693. }
  694. case scConstant: {
  695. const SCEVConstant *LC = cast<SCEVConstant>(LHS);
  696. const SCEVConstant *RC = cast<SCEVConstant>(RHS);
  697. // Compare constant values.
  698. const APInt &LA = LC->getAPInt();
  699. const APInt &RA = RC->getAPInt();
  700. unsigned LBitWidth = LA.getBitWidth(), RBitWidth = RA.getBitWidth();
  701. if (LBitWidth != RBitWidth)
  702. return (int)LBitWidth - (int)RBitWidth;
  703. return LA.ult(RA) ? -1 : 1;
  704. }
  705. case scAddRecExpr: {
  706. const SCEVAddRecExpr *LA = cast<SCEVAddRecExpr>(LHS);
  707. const SCEVAddRecExpr *RA = cast<SCEVAddRecExpr>(RHS);
  708. // There is always a dominance between two recs that are used by one SCEV,
  709. // so we can safely sort recs by loop header dominance. We require such
  710. // order in getAddExpr.
  711. const Loop *LLoop = LA->getLoop(), *RLoop = RA->getLoop();
  712. if (LLoop != RLoop) {
  713. const BasicBlock *LHead = LLoop->getHeader(), *RHead = RLoop->getHeader();
  714. assert(LHead != RHead && "Two loops share the same header?");
  715. if (DT.dominates(LHead, RHead))
  716. return 1;
  717. else
  718. assert(DT.dominates(RHead, LHead) &&
  719. "No dominance between recurrences used by one SCEV?");
  720. return -1;
  721. }
  722. [[fallthrough]];
  723. }
  724. case scTruncate:
  725. case scZeroExtend:
  726. case scSignExtend:
  727. case scPtrToInt:
  728. case scAddExpr:
  729. case scMulExpr:
  730. case scUDivExpr:
  731. case scSMaxExpr:
  732. case scUMaxExpr:
  733. case scSMinExpr:
  734. case scUMinExpr:
  735. case scSequentialUMinExpr: {
  736. ArrayRef<const SCEV *> LOps = LHS->operands();
  737. ArrayRef<const SCEV *> ROps = RHS->operands();
  738. // Lexicographically compare n-ary-like expressions.
  739. unsigned LNumOps = LOps.size(), RNumOps = ROps.size();
  740. if (LNumOps != RNumOps)
  741. return (int)LNumOps - (int)RNumOps;
  742. for (unsigned i = 0; i != LNumOps; ++i) {
  743. auto X = CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LOps[i],
  744. ROps[i], DT, Depth + 1);
  745. if (X != 0)
  746. return X;
  747. }
  748. EqCacheSCEV.unionSets(LHS, RHS);
  749. return 0;
  750. }
  751. case scCouldNotCompute:
  752. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  753. }
  754. llvm_unreachable("Unknown SCEV kind!");
  755. }
  756. /// Given a list of SCEV objects, order them by their complexity, and group
  757. /// objects of the same complexity together by value. When this routine is
  758. /// finished, we know that any duplicates in the vector are consecutive and that
  759. /// complexity is monotonically increasing.
  760. ///
  761. /// Note that we go take special precautions to ensure that we get deterministic
  762. /// results from this routine. In other words, we don't want the results of
  763. /// this to depend on where the addresses of various SCEV objects happened to
  764. /// land in memory.
  765. static void GroupByComplexity(SmallVectorImpl<const SCEV *> &Ops,
  766. LoopInfo *LI, DominatorTree &DT) {
  767. if (Ops.size() < 2) return; // Noop
  768. EquivalenceClasses<const SCEV *> EqCacheSCEV;
  769. EquivalenceClasses<const Value *> EqCacheValue;
  770. // Whether LHS has provably less complexity than RHS.
  771. auto IsLessComplex = [&](const SCEV *LHS, const SCEV *RHS) {
  772. auto Complexity =
  773. CompareSCEVComplexity(EqCacheSCEV, EqCacheValue, LI, LHS, RHS, DT);
  774. return Complexity && *Complexity < 0;
  775. };
  776. if (Ops.size() == 2) {
  777. // This is the common case, which also happens to be trivially simple.
  778. // Special case it.
  779. const SCEV *&LHS = Ops[0], *&RHS = Ops[1];
  780. if (IsLessComplex(RHS, LHS))
  781. std::swap(LHS, RHS);
  782. return;
  783. }
  784. // Do the rough sort by complexity.
  785. llvm::stable_sort(Ops, [&](const SCEV *LHS, const SCEV *RHS) {
  786. return IsLessComplex(LHS, RHS);
  787. });
  788. // Now that we are sorted by complexity, group elements of the same
  789. // complexity. Note that this is, at worst, N^2, but the vector is likely to
  790. // be extremely short in practice. Note that we take this approach because we
  791. // do not want to depend on the addresses of the objects we are grouping.
  792. for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
  793. const SCEV *S = Ops[i];
  794. unsigned Complexity = S->getSCEVType();
  795. // If there are any objects of the same complexity and same value as this
  796. // one, group them.
  797. for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
  798. if (Ops[j] == S) { // Found a duplicate.
  799. // Move it to immediately after i'th element.
  800. std::swap(Ops[i+1], Ops[j]);
  801. ++i; // no need to rescan it.
  802. if (i == e-2) return; // Done!
  803. }
  804. }
  805. }
  806. }
  807. /// Returns true if \p Ops contains a huge SCEV (the subtree of S contains at
  808. /// least HugeExprThreshold nodes).
  809. static bool hasHugeExpression(ArrayRef<const SCEV *> Ops) {
  810. return any_of(Ops, [](const SCEV *S) {
  811. return S->getExpressionSize() >= HugeExprThreshold;
  812. });
  813. }
  814. //===----------------------------------------------------------------------===//
  815. // Simple SCEV method implementations
  816. //===----------------------------------------------------------------------===//
  817. /// Compute BC(It, K). The result has width W. Assume, K > 0.
  818. static const SCEV *BinomialCoefficient(const SCEV *It, unsigned K,
  819. ScalarEvolution &SE,
  820. Type *ResultTy) {
  821. // Handle the simplest case efficiently.
  822. if (K == 1)
  823. return SE.getTruncateOrZeroExtend(It, ResultTy);
  824. // We are using the following formula for BC(It, K):
  825. //
  826. // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
  827. //
  828. // Suppose, W is the bitwidth of the return value. We must be prepared for
  829. // overflow. Hence, we must assure that the result of our computation is
  830. // equal to the accurate one modulo 2^W. Unfortunately, division isn't
  831. // safe in modular arithmetic.
  832. //
  833. // However, this code doesn't use exactly that formula; the formula it uses
  834. // is something like the following, where T is the number of factors of 2 in
  835. // K! (i.e. trailing zeros in the binary representation of K!), and ^ is
  836. // exponentiation:
  837. //
  838. // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / 2^T / (K! / 2^T)
  839. //
  840. // This formula is trivially equivalent to the previous formula. However,
  841. // this formula can be implemented much more efficiently. The trick is that
  842. // K! / 2^T is odd, and exact division by an odd number *is* safe in modular
  843. // arithmetic. To do exact division in modular arithmetic, all we have
  844. // to do is multiply by the inverse. Therefore, this step can be done at
  845. // width W.
  846. //
  847. // The next issue is how to safely do the division by 2^T. The way this
  848. // is done is by doing the multiplication step at a width of at least W + T
  849. // bits. This way, the bottom W+T bits of the product are accurate. Then,
  850. // when we perform the division by 2^T (which is equivalent to a right shift
  851. // by T), the bottom W bits are accurate. Extra bits are okay; they'll get
  852. // truncated out after the division by 2^T.
  853. //
  854. // In comparison to just directly using the first formula, this technique
  855. // is much more efficient; using the first formula requires W * K bits,
  856. // but this formula less than W + K bits. Also, the first formula requires
  857. // a division step, whereas this formula only requires multiplies and shifts.
  858. //
  859. // It doesn't matter whether the subtraction step is done in the calculation
  860. // width or the input iteration count's width; if the subtraction overflows,
  861. // the result must be zero anyway. We prefer here to do it in the width of
  862. // the induction variable because it helps a lot for certain cases; CodeGen
  863. // isn't smart enough to ignore the overflow, which leads to much less
  864. // efficient code if the width of the subtraction is wider than the native
  865. // register width.
  866. //
  867. // (It's possible to not widen at all by pulling out factors of 2 before
  868. // the multiplication; for example, K=2 can be calculated as
  869. // It/2*(It+(It*INT_MIN/INT_MIN)+-1). However, it requires
  870. // extra arithmetic, so it's not an obvious win, and it gets
  871. // much more complicated for K > 3.)
  872. // Protection from insane SCEVs; this bound is conservative,
  873. // but it probably doesn't matter.
  874. if (K > 1000)
  875. return SE.getCouldNotCompute();
  876. unsigned W = SE.getTypeSizeInBits(ResultTy);
  877. // Calculate K! / 2^T and T; we divide out the factors of two before
  878. // multiplying for calculating K! / 2^T to avoid overflow.
  879. // Other overflow doesn't matter because we only care about the bottom
  880. // W bits of the result.
  881. APInt OddFactorial(W, 1);
  882. unsigned T = 1;
  883. for (unsigned i = 3; i <= K; ++i) {
  884. APInt Mult(W, i);
  885. unsigned TwoFactors = Mult.countTrailingZeros();
  886. T += TwoFactors;
  887. Mult.lshrInPlace(TwoFactors);
  888. OddFactorial *= Mult;
  889. }
  890. // We need at least W + T bits for the multiplication step
  891. unsigned CalculationBits = W + T;
  892. // Calculate 2^T, at width T+W.
  893. APInt DivFactor = APInt::getOneBitSet(CalculationBits, T);
  894. // Calculate the multiplicative inverse of K! / 2^T;
  895. // this multiplication factor will perform the exact division by
  896. // K! / 2^T.
  897. APInt Mod = APInt::getSignedMinValue(W+1);
  898. APInt MultiplyFactor = OddFactorial.zext(W+1);
  899. MultiplyFactor = MultiplyFactor.multiplicativeInverse(Mod);
  900. MultiplyFactor = MultiplyFactor.trunc(W);
  901. // Calculate the product, at width T+W
  902. IntegerType *CalculationTy = IntegerType::get(SE.getContext(),
  903. CalculationBits);
  904. const SCEV *Dividend = SE.getTruncateOrZeroExtend(It, CalculationTy);
  905. for (unsigned i = 1; i != K; ++i) {
  906. const SCEV *S = SE.getMinusSCEV(It, SE.getConstant(It->getType(), i));
  907. Dividend = SE.getMulExpr(Dividend,
  908. SE.getTruncateOrZeroExtend(S, CalculationTy));
  909. }
  910. // Divide by 2^T
  911. const SCEV *DivResult = SE.getUDivExpr(Dividend, SE.getConstant(DivFactor));
  912. // Truncate the result, and divide by K! / 2^T.
  913. return SE.getMulExpr(SE.getConstant(MultiplyFactor),
  914. SE.getTruncateOrZeroExtend(DivResult, ResultTy));
  915. }
  916. /// Return the value of this chain of recurrences at the specified iteration
  917. /// number. We can evaluate this recurrence by multiplying each element in the
  918. /// chain by the binomial coefficient corresponding to it. In other words, we
  919. /// can evaluate {A,+,B,+,C,+,D} as:
  920. ///
  921. /// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
  922. ///
  923. /// where BC(It, k) stands for binomial coefficient.
  924. const SCEV *SCEVAddRecExpr::evaluateAtIteration(const SCEV *It,
  925. ScalarEvolution &SE) const {
  926. return evaluateAtIteration(operands(), It, SE);
  927. }
  928. const SCEV *
  929. SCEVAddRecExpr::evaluateAtIteration(ArrayRef<const SCEV *> Operands,
  930. const SCEV *It, ScalarEvolution &SE) {
  931. assert(Operands.size() > 0);
  932. const SCEV *Result = Operands[0];
  933. for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
  934. // The computation is correct in the face of overflow provided that the
  935. // multiplication is performed _after_ the evaluation of the binomial
  936. // coefficient.
  937. const SCEV *Coeff = BinomialCoefficient(It, i, SE, Result->getType());
  938. if (isa<SCEVCouldNotCompute>(Coeff))
  939. return Coeff;
  940. Result = SE.getAddExpr(Result, SE.getMulExpr(Operands[i], Coeff));
  941. }
  942. return Result;
  943. }
  944. //===----------------------------------------------------------------------===//
  945. // SCEV Expression folder implementations
  946. //===----------------------------------------------------------------------===//
  947. const SCEV *ScalarEvolution::getLosslessPtrToIntExpr(const SCEV *Op,
  948. unsigned Depth) {
  949. assert(Depth <= 1 &&
  950. "getLosslessPtrToIntExpr() should self-recurse at most once.");
  951. // We could be called with an integer-typed operands during SCEV rewrites.
  952. // Since the operand is an integer already, just perform zext/trunc/self cast.
  953. if (!Op->getType()->isPointerTy())
  954. return Op;
  955. // What would be an ID for such a SCEV cast expression?
  956. FoldingSetNodeID ID;
  957. ID.AddInteger(scPtrToInt);
  958. ID.AddPointer(Op);
  959. void *IP = nullptr;
  960. // Is there already an expression for such a cast?
  961. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
  962. return S;
  963. // It isn't legal for optimizations to construct new ptrtoint expressions
  964. // for non-integral pointers.
  965. if (getDataLayout().isNonIntegralPointerType(Op->getType()))
  966. return getCouldNotCompute();
  967. Type *IntPtrTy = getDataLayout().getIntPtrType(Op->getType());
  968. // We can only trivially model ptrtoint if SCEV's effective (integer) type
  969. // is sufficiently wide to represent all possible pointer values.
  970. // We could theoretically teach SCEV to truncate wider pointers, but
  971. // that isn't implemented for now.
  972. if (getDataLayout().getTypeSizeInBits(getEffectiveSCEVType(Op->getType())) !=
  973. getDataLayout().getTypeSizeInBits(IntPtrTy))
  974. return getCouldNotCompute();
  975. // If not, is this expression something we can't reduce any further?
  976. if (auto *U = dyn_cast<SCEVUnknown>(Op)) {
  977. // Perform some basic constant folding. If the operand of the ptr2int cast
  978. // is a null pointer, don't create a ptr2int SCEV expression (that will be
  979. // left as-is), but produce a zero constant.
  980. // NOTE: We could handle a more general case, but lack motivational cases.
  981. if (isa<ConstantPointerNull>(U->getValue()))
  982. return getZero(IntPtrTy);
  983. // Create an explicit cast node.
  984. // We can reuse the existing insert position since if we get here,
  985. // we won't have made any changes which would invalidate it.
  986. SCEV *S = new (SCEVAllocator)
  987. SCEVPtrToIntExpr(ID.Intern(SCEVAllocator), Op, IntPtrTy);
  988. UniqueSCEVs.InsertNode(S, IP);
  989. registerUser(S, Op);
  990. return S;
  991. }
  992. assert(Depth == 0 && "getLosslessPtrToIntExpr() should not self-recurse for "
  993. "non-SCEVUnknown's.");
  994. // Otherwise, we've got some expression that is more complex than just a
  995. // single SCEVUnknown. But we don't want to have a SCEVPtrToIntExpr of an
  996. // arbitrary expression, we want to have SCEVPtrToIntExpr of an SCEVUnknown
  997. // only, and the expressions must otherwise be integer-typed.
  998. // So sink the cast down to the SCEVUnknown's.
  999. /// The SCEVPtrToIntSinkingRewriter takes a scalar evolution expression,
  1000. /// which computes a pointer-typed value, and rewrites the whole expression
  1001. /// tree so that *all* the computations are done on integers, and the only
  1002. /// pointer-typed operands in the expression are SCEVUnknown.
  1003. class SCEVPtrToIntSinkingRewriter
  1004. : public SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter> {
  1005. using Base = SCEVRewriteVisitor<SCEVPtrToIntSinkingRewriter>;
  1006. public:
  1007. SCEVPtrToIntSinkingRewriter(ScalarEvolution &SE) : SCEVRewriteVisitor(SE) {}
  1008. static const SCEV *rewrite(const SCEV *Scev, ScalarEvolution &SE) {
  1009. SCEVPtrToIntSinkingRewriter Rewriter(SE);
  1010. return Rewriter.visit(Scev);
  1011. }
  1012. const SCEV *visit(const SCEV *S) {
  1013. Type *STy = S->getType();
  1014. // If the expression is not pointer-typed, just keep it as-is.
  1015. if (!STy->isPointerTy())
  1016. return S;
  1017. // Else, recursively sink the cast down into it.
  1018. return Base::visit(S);
  1019. }
  1020. const SCEV *visitAddExpr(const SCEVAddExpr *Expr) {
  1021. SmallVector<const SCEV *, 2> Operands;
  1022. bool Changed = false;
  1023. for (const auto *Op : Expr->operands()) {
  1024. Operands.push_back(visit(Op));
  1025. Changed |= Op != Operands.back();
  1026. }
  1027. return !Changed ? Expr : SE.getAddExpr(Operands, Expr->getNoWrapFlags());
  1028. }
  1029. const SCEV *visitMulExpr(const SCEVMulExpr *Expr) {
  1030. SmallVector<const SCEV *, 2> Operands;
  1031. bool Changed = false;
  1032. for (const auto *Op : Expr->operands()) {
  1033. Operands.push_back(visit(Op));
  1034. Changed |= Op != Operands.back();
  1035. }
  1036. return !Changed ? Expr : SE.getMulExpr(Operands, Expr->getNoWrapFlags());
  1037. }
  1038. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  1039. assert(Expr->getType()->isPointerTy() &&
  1040. "Should only reach pointer-typed SCEVUnknown's.");
  1041. return SE.getLosslessPtrToIntExpr(Expr, /*Depth=*/1);
  1042. }
  1043. };
  1044. // And actually perform the cast sinking.
  1045. const SCEV *IntOp = SCEVPtrToIntSinkingRewriter::rewrite(Op, *this);
  1046. assert(IntOp->getType()->isIntegerTy() &&
  1047. "We must have succeeded in sinking the cast, "
  1048. "and ending up with an integer-typed expression!");
  1049. return IntOp;
  1050. }
  1051. const SCEV *ScalarEvolution::getPtrToIntExpr(const SCEV *Op, Type *Ty) {
  1052. assert(Ty->isIntegerTy() && "Target type must be an integer type!");
  1053. const SCEV *IntOp = getLosslessPtrToIntExpr(Op);
  1054. if (isa<SCEVCouldNotCompute>(IntOp))
  1055. return IntOp;
  1056. return getTruncateOrZeroExtend(IntOp, Ty);
  1057. }
  1058. const SCEV *ScalarEvolution::getTruncateExpr(const SCEV *Op, Type *Ty,
  1059. unsigned Depth) {
  1060. assert(getTypeSizeInBits(Op->getType()) > getTypeSizeInBits(Ty) &&
  1061. "This is not a truncating conversion!");
  1062. assert(isSCEVable(Ty) &&
  1063. "This is not a conversion to a SCEVable type!");
  1064. assert(!Op->getType()->isPointerTy() && "Can't truncate pointer!");
  1065. Ty = getEffectiveSCEVType(Ty);
  1066. FoldingSetNodeID ID;
  1067. ID.AddInteger(scTruncate);
  1068. ID.AddPointer(Op);
  1069. ID.AddPointer(Ty);
  1070. void *IP = nullptr;
  1071. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
  1072. // Fold if the operand is constant.
  1073. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
  1074. return getConstant(
  1075. cast<ConstantInt>(ConstantExpr::getTrunc(SC->getValue(), Ty)));
  1076. // trunc(trunc(x)) --> trunc(x)
  1077. if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op))
  1078. return getTruncateExpr(ST->getOperand(), Ty, Depth + 1);
  1079. // trunc(sext(x)) --> sext(x) if widening or trunc(x) if narrowing
  1080. if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
  1081. return getTruncateOrSignExtend(SS->getOperand(), Ty, Depth + 1);
  1082. // trunc(zext(x)) --> zext(x) if widening or trunc(x) if narrowing
  1083. if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
  1084. return getTruncateOrZeroExtend(SZ->getOperand(), Ty, Depth + 1);
  1085. if (Depth > MaxCastDepth) {
  1086. SCEV *S =
  1087. new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator), Op, Ty);
  1088. UniqueSCEVs.InsertNode(S, IP);
  1089. registerUser(S, Op);
  1090. return S;
  1091. }
  1092. // trunc(x1 + ... + xN) --> trunc(x1) + ... + trunc(xN) and
  1093. // trunc(x1 * ... * xN) --> trunc(x1) * ... * trunc(xN),
  1094. // if after transforming we have at most one truncate, not counting truncates
  1095. // that replace other casts.
  1096. if (isa<SCEVAddExpr>(Op) || isa<SCEVMulExpr>(Op)) {
  1097. auto *CommOp = cast<SCEVCommutativeExpr>(Op);
  1098. SmallVector<const SCEV *, 4> Operands;
  1099. unsigned numTruncs = 0;
  1100. for (unsigned i = 0, e = CommOp->getNumOperands(); i != e && numTruncs < 2;
  1101. ++i) {
  1102. const SCEV *S = getTruncateExpr(CommOp->getOperand(i), Ty, Depth + 1);
  1103. if (!isa<SCEVIntegralCastExpr>(CommOp->getOperand(i)) &&
  1104. isa<SCEVTruncateExpr>(S))
  1105. numTruncs++;
  1106. Operands.push_back(S);
  1107. }
  1108. if (numTruncs < 2) {
  1109. if (isa<SCEVAddExpr>(Op))
  1110. return getAddExpr(Operands);
  1111. else if (isa<SCEVMulExpr>(Op))
  1112. return getMulExpr(Operands);
  1113. else
  1114. llvm_unreachable("Unexpected SCEV type for Op.");
  1115. }
  1116. // Although we checked in the beginning that ID is not in the cache, it is
  1117. // possible that during recursion and different modification ID was inserted
  1118. // into the cache. So if we find it, just return it.
  1119. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
  1120. return S;
  1121. }
  1122. // If the input value is a chrec scev, truncate the chrec's operands.
  1123. if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
  1124. SmallVector<const SCEV *, 4> Operands;
  1125. for (const SCEV *Op : AddRec->operands())
  1126. Operands.push_back(getTruncateExpr(Op, Ty, Depth + 1));
  1127. return getAddRecExpr(Operands, AddRec->getLoop(), SCEV::FlagAnyWrap);
  1128. }
  1129. // Return zero if truncating to known zeros.
  1130. uint32_t MinTrailingZeros = GetMinTrailingZeros(Op);
  1131. if (MinTrailingZeros >= getTypeSizeInBits(Ty))
  1132. return getZero(Ty);
  1133. // The cast wasn't folded; create an explicit cast node. We can reuse
  1134. // the existing insert position since if we get here, we won't have
  1135. // made any changes which would invalidate it.
  1136. SCEV *S = new (SCEVAllocator) SCEVTruncateExpr(ID.Intern(SCEVAllocator),
  1137. Op, Ty);
  1138. UniqueSCEVs.InsertNode(S, IP);
  1139. registerUser(S, Op);
  1140. return S;
  1141. }
  1142. // Get the limit of a recurrence such that incrementing by Step cannot cause
  1143. // signed overflow as long as the value of the recurrence within the
  1144. // loop does not exceed this limit before incrementing.
  1145. static const SCEV *getSignedOverflowLimitForStep(const SCEV *Step,
  1146. ICmpInst::Predicate *Pred,
  1147. ScalarEvolution *SE) {
  1148. unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
  1149. if (SE->isKnownPositive(Step)) {
  1150. *Pred = ICmpInst::ICMP_SLT;
  1151. return SE->getConstant(APInt::getSignedMinValue(BitWidth) -
  1152. SE->getSignedRangeMax(Step));
  1153. }
  1154. if (SE->isKnownNegative(Step)) {
  1155. *Pred = ICmpInst::ICMP_SGT;
  1156. return SE->getConstant(APInt::getSignedMaxValue(BitWidth) -
  1157. SE->getSignedRangeMin(Step));
  1158. }
  1159. return nullptr;
  1160. }
  1161. // Get the limit of a recurrence such that incrementing by Step cannot cause
  1162. // unsigned overflow as long as the value of the recurrence within the loop does
  1163. // not exceed this limit before incrementing.
  1164. static const SCEV *getUnsignedOverflowLimitForStep(const SCEV *Step,
  1165. ICmpInst::Predicate *Pred,
  1166. ScalarEvolution *SE) {
  1167. unsigned BitWidth = SE->getTypeSizeInBits(Step->getType());
  1168. *Pred = ICmpInst::ICMP_ULT;
  1169. return SE->getConstant(APInt::getMinValue(BitWidth) -
  1170. SE->getUnsignedRangeMax(Step));
  1171. }
  1172. namespace {
  1173. struct ExtendOpTraitsBase {
  1174. typedef const SCEV *(ScalarEvolution::*GetExtendExprTy)(const SCEV *, Type *,
  1175. unsigned);
  1176. };
  1177. // Used to make code generic over signed and unsigned overflow.
  1178. template <typename ExtendOp> struct ExtendOpTraits {
  1179. // Members present:
  1180. //
  1181. // static const SCEV::NoWrapFlags WrapType;
  1182. //
  1183. // static const ExtendOpTraitsBase::GetExtendExprTy GetExtendExpr;
  1184. //
  1185. // static const SCEV *getOverflowLimitForStep(const SCEV *Step,
  1186. // ICmpInst::Predicate *Pred,
  1187. // ScalarEvolution *SE);
  1188. };
  1189. template <>
  1190. struct ExtendOpTraits<SCEVSignExtendExpr> : public ExtendOpTraitsBase {
  1191. static const SCEV::NoWrapFlags WrapType = SCEV::FlagNSW;
  1192. static const GetExtendExprTy GetExtendExpr;
  1193. static const SCEV *getOverflowLimitForStep(const SCEV *Step,
  1194. ICmpInst::Predicate *Pred,
  1195. ScalarEvolution *SE) {
  1196. return getSignedOverflowLimitForStep(Step, Pred, SE);
  1197. }
  1198. };
  1199. const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
  1200. SCEVSignExtendExpr>::GetExtendExpr = &ScalarEvolution::getSignExtendExpr;
  1201. template <>
  1202. struct ExtendOpTraits<SCEVZeroExtendExpr> : public ExtendOpTraitsBase {
  1203. static const SCEV::NoWrapFlags WrapType = SCEV::FlagNUW;
  1204. static const GetExtendExprTy GetExtendExpr;
  1205. static const SCEV *getOverflowLimitForStep(const SCEV *Step,
  1206. ICmpInst::Predicate *Pred,
  1207. ScalarEvolution *SE) {
  1208. return getUnsignedOverflowLimitForStep(Step, Pred, SE);
  1209. }
  1210. };
  1211. const ExtendOpTraitsBase::GetExtendExprTy ExtendOpTraits<
  1212. SCEVZeroExtendExpr>::GetExtendExpr = &ScalarEvolution::getZeroExtendExpr;
  1213. } // end anonymous namespace
  1214. // The recurrence AR has been shown to have no signed/unsigned wrap or something
  1215. // close to it. Typically, if we can prove NSW/NUW for AR, then we can just as
  1216. // easily prove NSW/NUW for its preincrement or postincrement sibling. This
  1217. // allows normalizing a sign/zero extended AddRec as such: {sext/zext(Step +
  1218. // Start),+,Step} => {(Step + sext/zext(Start),+,Step} As a result, the
  1219. // expression "Step + sext/zext(PreIncAR)" is congruent with
  1220. // "sext/zext(PostIncAR)"
  1221. template <typename ExtendOpTy>
  1222. static const SCEV *getPreStartForExtend(const SCEVAddRecExpr *AR, Type *Ty,
  1223. ScalarEvolution *SE, unsigned Depth) {
  1224. auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
  1225. auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
  1226. const Loop *L = AR->getLoop();
  1227. const SCEV *Start = AR->getStart();
  1228. const SCEV *Step = AR->getStepRecurrence(*SE);
  1229. // Check for a simple looking step prior to loop entry.
  1230. const SCEVAddExpr *SA = dyn_cast<SCEVAddExpr>(Start);
  1231. if (!SA)
  1232. return nullptr;
  1233. // Create an AddExpr for "PreStart" after subtracting Step. Full SCEV
  1234. // subtraction is expensive. For this purpose, perform a quick and dirty
  1235. // difference, by checking for Step in the operand list.
  1236. SmallVector<const SCEV *, 4> DiffOps;
  1237. for (const SCEV *Op : SA->operands())
  1238. if (Op != Step)
  1239. DiffOps.push_back(Op);
  1240. if (DiffOps.size() == SA->getNumOperands())
  1241. return nullptr;
  1242. // Try to prove `WrapType` (SCEV::FlagNSW or SCEV::FlagNUW) on `PreStart` +
  1243. // `Step`:
  1244. // 1. NSW/NUW flags on the step increment.
  1245. auto PreStartFlags =
  1246. ScalarEvolution::maskFlags(SA->getNoWrapFlags(), SCEV::FlagNUW);
  1247. const SCEV *PreStart = SE->getAddExpr(DiffOps, PreStartFlags);
  1248. const SCEVAddRecExpr *PreAR = dyn_cast<SCEVAddRecExpr>(
  1249. SE->getAddRecExpr(PreStart, Step, L, SCEV::FlagAnyWrap));
  1250. // "{S,+,X} is <nsw>/<nuw>" and "the backedge is taken at least once" implies
  1251. // "S+X does not sign/unsign-overflow".
  1252. //
  1253. const SCEV *BECount = SE->getBackedgeTakenCount(L);
  1254. if (PreAR && PreAR->getNoWrapFlags(WrapType) &&
  1255. !isa<SCEVCouldNotCompute>(BECount) && SE->isKnownPositive(BECount))
  1256. return PreStart;
  1257. // 2. Direct overflow check on the step operation's expression.
  1258. unsigned BitWidth = SE->getTypeSizeInBits(AR->getType());
  1259. Type *WideTy = IntegerType::get(SE->getContext(), BitWidth * 2);
  1260. const SCEV *OperandExtendedStart =
  1261. SE->getAddExpr((SE->*GetExtendExpr)(PreStart, WideTy, Depth),
  1262. (SE->*GetExtendExpr)(Step, WideTy, Depth));
  1263. if ((SE->*GetExtendExpr)(Start, WideTy, Depth) == OperandExtendedStart) {
  1264. if (PreAR && AR->getNoWrapFlags(WrapType)) {
  1265. // If we know `AR` == {`PreStart`+`Step`,+,`Step`} is `WrapType` (FlagNSW
  1266. // or FlagNUW) and that `PreStart` + `Step` is `WrapType` too, then
  1267. // `PreAR` == {`PreStart`,+,`Step`} is also `WrapType`. Cache this fact.
  1268. SE->setNoWrapFlags(const_cast<SCEVAddRecExpr *>(PreAR), WrapType);
  1269. }
  1270. return PreStart;
  1271. }
  1272. // 3. Loop precondition.
  1273. ICmpInst::Predicate Pred;
  1274. const SCEV *OverflowLimit =
  1275. ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(Step, &Pred, SE);
  1276. if (OverflowLimit &&
  1277. SE->isLoopEntryGuardedByCond(L, Pred, PreStart, OverflowLimit))
  1278. return PreStart;
  1279. return nullptr;
  1280. }
  1281. // Get the normalized zero or sign extended expression for this AddRec's Start.
  1282. template <typename ExtendOpTy>
  1283. static const SCEV *getExtendAddRecStart(const SCEVAddRecExpr *AR, Type *Ty,
  1284. ScalarEvolution *SE,
  1285. unsigned Depth) {
  1286. auto GetExtendExpr = ExtendOpTraits<ExtendOpTy>::GetExtendExpr;
  1287. const SCEV *PreStart = getPreStartForExtend<ExtendOpTy>(AR, Ty, SE, Depth);
  1288. if (!PreStart)
  1289. return (SE->*GetExtendExpr)(AR->getStart(), Ty, Depth);
  1290. return SE->getAddExpr((SE->*GetExtendExpr)(AR->getStepRecurrence(*SE), Ty,
  1291. Depth),
  1292. (SE->*GetExtendExpr)(PreStart, Ty, Depth));
  1293. }
  1294. // Try to prove away overflow by looking at "nearby" add recurrences. A
  1295. // motivating example for this rule: if we know `{0,+,4}` is `ult` `-1` and it
  1296. // does not itself wrap then we can conclude that `{1,+,4}` is `nuw`.
  1297. //
  1298. // Formally:
  1299. //
  1300. // {S,+,X} == {S-T,+,X} + T
  1301. // => Ext({S,+,X}) == Ext({S-T,+,X} + T)
  1302. //
  1303. // If ({S-T,+,X} + T) does not overflow ... (1)
  1304. //
  1305. // RHS == Ext({S-T,+,X} + T) == Ext({S-T,+,X}) + Ext(T)
  1306. //
  1307. // If {S-T,+,X} does not overflow ... (2)
  1308. //
  1309. // RHS == Ext({S-T,+,X}) + Ext(T) == {Ext(S-T),+,Ext(X)} + Ext(T)
  1310. // == {Ext(S-T)+Ext(T),+,Ext(X)}
  1311. //
  1312. // If (S-T)+T does not overflow ... (3)
  1313. //
  1314. // RHS == {Ext(S-T)+Ext(T),+,Ext(X)} == {Ext(S-T+T),+,Ext(X)}
  1315. // == {Ext(S),+,Ext(X)} == LHS
  1316. //
  1317. // Thus, if (1), (2) and (3) are true for some T, then
  1318. // Ext({S,+,X}) == {Ext(S),+,Ext(X)}
  1319. //
  1320. // (3) is implied by (1) -- "(S-T)+T does not overflow" is simply "({S-T,+,X}+T)
  1321. // does not overflow" restricted to the 0th iteration. Therefore we only need
  1322. // to check for (1) and (2).
  1323. //
  1324. // In the current context, S is `Start`, X is `Step`, Ext is `ExtendOpTy` and T
  1325. // is `Delta` (defined below).
  1326. template <typename ExtendOpTy>
  1327. bool ScalarEvolution::proveNoWrapByVaryingStart(const SCEV *Start,
  1328. const SCEV *Step,
  1329. const Loop *L) {
  1330. auto WrapType = ExtendOpTraits<ExtendOpTy>::WrapType;
  1331. // We restrict `Start` to a constant to prevent SCEV from spending too much
  1332. // time here. It is correct (but more expensive) to continue with a
  1333. // non-constant `Start` and do a general SCEV subtraction to compute
  1334. // `PreStart` below.
  1335. const SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start);
  1336. if (!StartC)
  1337. return false;
  1338. APInt StartAI = StartC->getAPInt();
  1339. for (unsigned Delta : {-2, -1, 1, 2}) {
  1340. const SCEV *PreStart = getConstant(StartAI - Delta);
  1341. FoldingSetNodeID ID;
  1342. ID.AddInteger(scAddRecExpr);
  1343. ID.AddPointer(PreStart);
  1344. ID.AddPointer(Step);
  1345. ID.AddPointer(L);
  1346. void *IP = nullptr;
  1347. const auto *PreAR =
  1348. static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
  1349. // Give up if we don't already have the add recurrence we need because
  1350. // actually constructing an add recurrence is relatively expensive.
  1351. if (PreAR && PreAR->getNoWrapFlags(WrapType)) { // proves (2)
  1352. const SCEV *DeltaS = getConstant(StartC->getType(), Delta);
  1353. ICmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
  1354. const SCEV *Limit = ExtendOpTraits<ExtendOpTy>::getOverflowLimitForStep(
  1355. DeltaS, &Pred, this);
  1356. if (Limit && isKnownPredicate(Pred, PreAR, Limit)) // proves (1)
  1357. return true;
  1358. }
  1359. }
  1360. return false;
  1361. }
  1362. // Finds an integer D for an expression (C + x + y + ...) such that the top
  1363. // level addition in (D + (C - D + x + y + ...)) would not wrap (signed or
  1364. // unsigned) and the number of trailing zeros of (C - D + x + y + ...) is
  1365. // maximized, where C is the \p ConstantTerm, x, y, ... are arbitrary SCEVs, and
  1366. // the (C + x + y + ...) expression is \p WholeAddExpr.
  1367. static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
  1368. const SCEVConstant *ConstantTerm,
  1369. const SCEVAddExpr *WholeAddExpr) {
  1370. const APInt &C = ConstantTerm->getAPInt();
  1371. const unsigned BitWidth = C.getBitWidth();
  1372. // Find number of trailing zeros of (x + y + ...) w/o the C first:
  1373. uint32_t TZ = BitWidth;
  1374. for (unsigned I = 1, E = WholeAddExpr->getNumOperands(); I < E && TZ; ++I)
  1375. TZ = std::min(TZ, SE.GetMinTrailingZeros(WholeAddExpr->getOperand(I)));
  1376. if (TZ) {
  1377. // Set D to be as many least significant bits of C as possible while still
  1378. // guaranteeing that adding D to (C - D + x + y + ...) won't cause a wrap:
  1379. return TZ < BitWidth ? C.trunc(TZ).zext(BitWidth) : C;
  1380. }
  1381. return APInt(BitWidth, 0);
  1382. }
  1383. // Finds an integer D for an affine AddRec expression {C,+,x} such that the top
  1384. // level addition in (D + {C-D,+,x}) would not wrap (signed or unsigned) and the
  1385. // number of trailing zeros of (C - D + x * n) is maximized, where C is the \p
  1386. // ConstantStart, x is an arbitrary \p Step, and n is the loop trip count.
  1387. static APInt extractConstantWithoutWrapping(ScalarEvolution &SE,
  1388. const APInt &ConstantStart,
  1389. const SCEV *Step) {
  1390. const unsigned BitWidth = ConstantStart.getBitWidth();
  1391. const uint32_t TZ = SE.GetMinTrailingZeros(Step);
  1392. if (TZ)
  1393. return TZ < BitWidth ? ConstantStart.trunc(TZ).zext(BitWidth)
  1394. : ConstantStart;
  1395. return APInt(BitWidth, 0);
  1396. }
  1397. static void insertFoldCacheEntry(
  1398. const ScalarEvolution::FoldID &ID, const SCEV *S,
  1399. DenseMap<ScalarEvolution::FoldID, const SCEV *> &FoldCache,
  1400. DenseMap<const SCEV *, SmallVector<ScalarEvolution::FoldID, 2>>
  1401. &FoldCacheUser) {
  1402. auto I = FoldCache.insert({ID, S});
  1403. if (!I.second) {
  1404. // Remove FoldCacheUser entry for ID when replacing an existing FoldCache
  1405. // entry.
  1406. auto &UserIDs = FoldCacheUser[I.first->second];
  1407. assert(count(UserIDs, ID) == 1 && "unexpected duplicates in UserIDs");
  1408. for (unsigned I = 0; I != UserIDs.size(); ++I)
  1409. if (UserIDs[I] == ID) {
  1410. std::swap(UserIDs[I], UserIDs.back());
  1411. break;
  1412. }
  1413. UserIDs.pop_back();
  1414. I.first->second = S;
  1415. }
  1416. auto R = FoldCacheUser.insert({S, {}});
  1417. R.first->second.push_back(ID);
  1418. }
  1419. const SCEV *
  1420. ScalarEvolution::getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
  1421. assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
  1422. "This is not an extending conversion!");
  1423. assert(isSCEVable(Ty) &&
  1424. "This is not a conversion to a SCEVable type!");
  1425. assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
  1426. Ty = getEffectiveSCEVType(Ty);
  1427. FoldID ID;
  1428. ID.addInteger(scZeroExtend);
  1429. ID.addPointer(Op);
  1430. ID.addPointer(Ty);
  1431. auto Iter = FoldCache.find(ID);
  1432. if (Iter != FoldCache.end())
  1433. return Iter->second;
  1434. const SCEV *S = getZeroExtendExprImpl(Op, Ty, Depth);
  1435. if (!isa<SCEVZeroExtendExpr>(S))
  1436. insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
  1437. return S;
  1438. }
  1439. const SCEV *ScalarEvolution::getZeroExtendExprImpl(const SCEV *Op, Type *Ty,
  1440. unsigned Depth) {
  1441. assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
  1442. "This is not an extending conversion!");
  1443. assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
  1444. assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
  1445. // Fold if the operand is constant.
  1446. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
  1447. return getConstant(
  1448. cast<ConstantInt>(ConstantExpr::getZExt(SC->getValue(), Ty)));
  1449. // zext(zext(x)) --> zext(x)
  1450. if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
  1451. return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
  1452. // Before doing any expensive analysis, check to see if we've already
  1453. // computed a SCEV for this Op and Ty.
  1454. FoldingSetNodeID ID;
  1455. ID.AddInteger(scZeroExtend);
  1456. ID.AddPointer(Op);
  1457. ID.AddPointer(Ty);
  1458. void *IP = nullptr;
  1459. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
  1460. if (Depth > MaxCastDepth) {
  1461. SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
  1462. Op, Ty);
  1463. UniqueSCEVs.InsertNode(S, IP);
  1464. registerUser(S, Op);
  1465. return S;
  1466. }
  1467. // zext(trunc(x)) --> zext(x) or x or trunc(x)
  1468. if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
  1469. // It's possible the bits taken off by the truncate were all zero bits. If
  1470. // so, we should be able to simplify this further.
  1471. const SCEV *X = ST->getOperand();
  1472. ConstantRange CR = getUnsignedRange(X);
  1473. unsigned TruncBits = getTypeSizeInBits(ST->getType());
  1474. unsigned NewBits = getTypeSizeInBits(Ty);
  1475. if (CR.truncate(TruncBits).zeroExtend(NewBits).contains(
  1476. CR.zextOrTrunc(NewBits)))
  1477. return getTruncateOrZeroExtend(X, Ty, Depth);
  1478. }
  1479. // If the input value is a chrec scev, and we can prove that the value
  1480. // did not overflow the old, smaller, value, we can zero extend all of the
  1481. // operands (often constants). This allows analysis of something like
  1482. // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
  1483. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
  1484. if (AR->isAffine()) {
  1485. const SCEV *Start = AR->getStart();
  1486. const SCEV *Step = AR->getStepRecurrence(*this);
  1487. unsigned BitWidth = getTypeSizeInBits(AR->getType());
  1488. const Loop *L = AR->getLoop();
  1489. if (!AR->hasNoUnsignedWrap()) {
  1490. auto NewFlags = proveNoWrapViaConstantRanges(AR);
  1491. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
  1492. }
  1493. // If we have special knowledge that this addrec won't overflow,
  1494. // we don't need to do any further analysis.
  1495. if (AR->hasNoUnsignedWrap()) {
  1496. Start =
  1497. getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
  1498. Step = getZeroExtendExpr(Step, Ty, Depth + 1);
  1499. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1500. }
  1501. // Check whether the backedge-taken count is SCEVCouldNotCompute.
  1502. // Note that this serves two purposes: It filters out loops that are
  1503. // simply not analyzable, and it covers the case where this code is
  1504. // being called from within backedge-taken count analysis, such that
  1505. // attempting to ask for the backedge-taken count would likely result
  1506. // in infinite recursion. In the later case, the analysis code will
  1507. // cope with a conservative value, and it will take care to purge
  1508. // that value once it has finished.
  1509. const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
  1510. if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
  1511. // Manually compute the final value for AR, checking for overflow.
  1512. // Check whether the backedge-taken count can be losslessly casted to
  1513. // the addrec's type. The count is always unsigned.
  1514. const SCEV *CastedMaxBECount =
  1515. getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
  1516. const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
  1517. CastedMaxBECount, MaxBECount->getType(), Depth);
  1518. if (MaxBECount == RecastedMaxBECount) {
  1519. Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
  1520. // Check whether Start+Step*MaxBECount has no unsigned overflow.
  1521. const SCEV *ZMul = getMulExpr(CastedMaxBECount, Step,
  1522. SCEV::FlagAnyWrap, Depth + 1);
  1523. const SCEV *ZAdd = getZeroExtendExpr(getAddExpr(Start, ZMul,
  1524. SCEV::FlagAnyWrap,
  1525. Depth + 1),
  1526. WideTy, Depth + 1);
  1527. const SCEV *WideStart = getZeroExtendExpr(Start, WideTy, Depth + 1);
  1528. const SCEV *WideMaxBECount =
  1529. getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
  1530. const SCEV *OperandExtendedAdd =
  1531. getAddExpr(WideStart,
  1532. getMulExpr(WideMaxBECount,
  1533. getZeroExtendExpr(Step, WideTy, Depth + 1),
  1534. SCEV::FlagAnyWrap, Depth + 1),
  1535. SCEV::FlagAnyWrap, Depth + 1);
  1536. if (ZAdd == OperandExtendedAdd) {
  1537. // Cache knowledge of AR NUW, which is propagated to this AddRec.
  1538. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
  1539. // Return the expression with the addrec on the outside.
  1540. Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
  1541. Depth + 1);
  1542. Step = getZeroExtendExpr(Step, Ty, Depth + 1);
  1543. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1544. }
  1545. // Similar to above, only this time treat the step value as signed.
  1546. // This covers loops that count down.
  1547. OperandExtendedAdd =
  1548. getAddExpr(WideStart,
  1549. getMulExpr(WideMaxBECount,
  1550. getSignExtendExpr(Step, WideTy, Depth + 1),
  1551. SCEV::FlagAnyWrap, Depth + 1),
  1552. SCEV::FlagAnyWrap, Depth + 1);
  1553. if (ZAdd == OperandExtendedAdd) {
  1554. // Cache knowledge of AR NW, which is propagated to this AddRec.
  1555. // Negative step causes unsigned wrap, but it still can't self-wrap.
  1556. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
  1557. // Return the expression with the addrec on the outside.
  1558. Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
  1559. Depth + 1);
  1560. Step = getSignExtendExpr(Step, Ty, Depth + 1);
  1561. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1562. }
  1563. }
  1564. }
  1565. // Normally, in the cases we can prove no-overflow via a
  1566. // backedge guarding condition, we can also compute a backedge
  1567. // taken count for the loop. The exceptions are assumptions and
  1568. // guards present in the loop -- SCEV is not great at exploiting
  1569. // these to compute max backedge taken counts, but can still use
  1570. // these to prove lack of overflow. Use this fact to avoid
  1571. // doing extra work that may not pay off.
  1572. if (!isa<SCEVCouldNotCompute>(MaxBECount) || !AC.assumptions().empty()) {
  1573. auto NewFlags = proveNoUnsignedWrapViaInduction(AR);
  1574. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
  1575. if (AR->hasNoUnsignedWrap()) {
  1576. // Same as nuw case above - duplicated here to avoid a compile time
  1577. // issue. It's not clear that the order of checks does matter, but
  1578. // it's one of two issue possible causes for a change which was
  1579. // reverted. Be conservative for the moment.
  1580. Start =
  1581. getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
  1582. Step = getZeroExtendExpr(Step, Ty, Depth + 1);
  1583. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1584. }
  1585. // For a negative step, we can extend the operands iff doing so only
  1586. // traverses values in the range zext([0,UINT_MAX]).
  1587. if (isKnownNegative(Step)) {
  1588. const SCEV *N = getConstant(APInt::getMaxValue(BitWidth) -
  1589. getSignedRangeMin(Step));
  1590. if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_UGT, AR, N) ||
  1591. isKnownOnEveryIteration(ICmpInst::ICMP_UGT, AR, N)) {
  1592. // Cache knowledge of AR NW, which is propagated to this
  1593. // AddRec. Negative step causes unsigned wrap, but it
  1594. // still can't self-wrap.
  1595. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
  1596. // Return the expression with the addrec on the outside.
  1597. Start = getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this,
  1598. Depth + 1);
  1599. Step = getSignExtendExpr(Step, Ty, Depth + 1);
  1600. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1601. }
  1602. }
  1603. }
  1604. // zext({C,+,Step}) --> (zext(D) + zext({C-D,+,Step}))<nuw><nsw>
  1605. // if D + (C - D + Step * n) could be proven to not unsigned wrap
  1606. // where D maximizes the number of trailing zeros of (C - D + Step * n)
  1607. if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
  1608. const APInt &C = SC->getAPInt();
  1609. const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
  1610. if (D != 0) {
  1611. const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
  1612. const SCEV *SResidual =
  1613. getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
  1614. const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
  1615. return getAddExpr(SZExtD, SZExtR,
  1616. (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
  1617. Depth + 1);
  1618. }
  1619. }
  1620. if (proveNoWrapByVaryingStart<SCEVZeroExtendExpr>(Start, Step, L)) {
  1621. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNUW);
  1622. Start =
  1623. getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, Depth + 1);
  1624. Step = getZeroExtendExpr(Step, Ty, Depth + 1);
  1625. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1626. }
  1627. }
  1628. // zext(A % B) --> zext(A) % zext(B)
  1629. {
  1630. const SCEV *LHS;
  1631. const SCEV *RHS;
  1632. if (matchURem(Op, LHS, RHS))
  1633. return getURemExpr(getZeroExtendExpr(LHS, Ty, Depth + 1),
  1634. getZeroExtendExpr(RHS, Ty, Depth + 1));
  1635. }
  1636. // zext(A / B) --> zext(A) / zext(B).
  1637. if (auto *Div = dyn_cast<SCEVUDivExpr>(Op))
  1638. return getUDivExpr(getZeroExtendExpr(Div->getLHS(), Ty, Depth + 1),
  1639. getZeroExtendExpr(Div->getRHS(), Ty, Depth + 1));
  1640. if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
  1641. // zext((A + B + ...)<nuw>) --> (zext(A) + zext(B) + ...)<nuw>
  1642. if (SA->hasNoUnsignedWrap()) {
  1643. // If the addition does not unsign overflow then we can, by definition,
  1644. // commute the zero extension with the addition operation.
  1645. SmallVector<const SCEV *, 4> Ops;
  1646. for (const auto *Op : SA->operands())
  1647. Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
  1648. return getAddExpr(Ops, SCEV::FlagNUW, Depth + 1);
  1649. }
  1650. // zext(C + x + y + ...) --> (zext(D) + zext((C - D) + x + y + ...))
  1651. // if D + (C - D + x + y + ...) could be proven to not unsigned wrap
  1652. // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
  1653. //
  1654. // Often address arithmetics contain expressions like
  1655. // (zext (add (shl X, C1), C2)), for instance, (zext (5 + (4 * X))).
  1656. // This transformation is useful while proving that such expressions are
  1657. // equal or differ by a small constant amount, see LoadStoreVectorizer pass.
  1658. if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
  1659. const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
  1660. if (D != 0) {
  1661. const SCEV *SZExtD = getZeroExtendExpr(getConstant(D), Ty, Depth);
  1662. const SCEV *SResidual =
  1663. getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
  1664. const SCEV *SZExtR = getZeroExtendExpr(SResidual, Ty, Depth + 1);
  1665. return getAddExpr(SZExtD, SZExtR,
  1666. (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
  1667. Depth + 1);
  1668. }
  1669. }
  1670. }
  1671. if (auto *SM = dyn_cast<SCEVMulExpr>(Op)) {
  1672. // zext((A * B * ...)<nuw>) --> (zext(A) * zext(B) * ...)<nuw>
  1673. if (SM->hasNoUnsignedWrap()) {
  1674. // If the multiply does not unsign overflow then we can, by definition,
  1675. // commute the zero extension with the multiply operation.
  1676. SmallVector<const SCEV *, 4> Ops;
  1677. for (const auto *Op : SM->operands())
  1678. Ops.push_back(getZeroExtendExpr(Op, Ty, Depth + 1));
  1679. return getMulExpr(Ops, SCEV::FlagNUW, Depth + 1);
  1680. }
  1681. // zext(2^K * (trunc X to iN)) to iM ->
  1682. // 2^K * (zext(trunc X to i{N-K}) to iM)<nuw>
  1683. //
  1684. // Proof:
  1685. //
  1686. // zext(2^K * (trunc X to iN)) to iM
  1687. // = zext((trunc X to iN) << K) to iM
  1688. // = zext((trunc X to i{N-K}) << K)<nuw> to iM
  1689. // (because shl removes the top K bits)
  1690. // = zext((2^K * (trunc X to i{N-K}))<nuw>) to iM
  1691. // = (2^K * (zext(trunc X to i{N-K}) to iM))<nuw>.
  1692. //
  1693. if (SM->getNumOperands() == 2)
  1694. if (auto *MulLHS = dyn_cast<SCEVConstant>(SM->getOperand(0)))
  1695. if (MulLHS->getAPInt().isPowerOf2())
  1696. if (auto *TruncRHS = dyn_cast<SCEVTruncateExpr>(SM->getOperand(1))) {
  1697. int NewTruncBits = getTypeSizeInBits(TruncRHS->getType()) -
  1698. MulLHS->getAPInt().logBase2();
  1699. Type *NewTruncTy = IntegerType::get(getContext(), NewTruncBits);
  1700. return getMulExpr(
  1701. getZeroExtendExpr(MulLHS, Ty),
  1702. getZeroExtendExpr(
  1703. getTruncateExpr(TruncRHS->getOperand(), NewTruncTy), Ty),
  1704. SCEV::FlagNUW, Depth + 1);
  1705. }
  1706. }
  1707. // The cast wasn't folded; create an explicit cast node.
  1708. // Recompute the insert position, as it may have been invalidated.
  1709. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
  1710. SCEV *S = new (SCEVAllocator) SCEVZeroExtendExpr(ID.Intern(SCEVAllocator),
  1711. Op, Ty);
  1712. UniqueSCEVs.InsertNode(S, IP);
  1713. registerUser(S, Op);
  1714. return S;
  1715. }
  1716. const SCEV *
  1717. ScalarEvolution::getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth) {
  1718. assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
  1719. "This is not an extending conversion!");
  1720. assert(isSCEVable(Ty) &&
  1721. "This is not a conversion to a SCEVable type!");
  1722. assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
  1723. Ty = getEffectiveSCEVType(Ty);
  1724. FoldID ID;
  1725. ID.addInteger(scSignExtend);
  1726. ID.addPointer(Op);
  1727. ID.addPointer(Ty);
  1728. auto Iter = FoldCache.find(ID);
  1729. if (Iter != FoldCache.end())
  1730. return Iter->second;
  1731. const SCEV *S = getSignExtendExprImpl(Op, Ty, Depth);
  1732. if (!isa<SCEVSignExtendExpr>(S))
  1733. insertFoldCacheEntry(ID, S, FoldCache, FoldCacheUser);
  1734. return S;
  1735. }
  1736. const SCEV *ScalarEvolution::getSignExtendExprImpl(const SCEV *Op, Type *Ty,
  1737. unsigned Depth) {
  1738. assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
  1739. "This is not an extending conversion!");
  1740. assert(isSCEVable(Ty) && "This is not a conversion to a SCEVable type!");
  1741. assert(!Op->getType()->isPointerTy() && "Can't extend pointer!");
  1742. Ty = getEffectiveSCEVType(Ty);
  1743. // Fold if the operand is constant.
  1744. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
  1745. return getConstant(
  1746. cast<ConstantInt>(ConstantExpr::getSExt(SC->getValue(), Ty)));
  1747. // sext(sext(x)) --> sext(x)
  1748. if (const SCEVSignExtendExpr *SS = dyn_cast<SCEVSignExtendExpr>(Op))
  1749. return getSignExtendExpr(SS->getOperand(), Ty, Depth + 1);
  1750. // sext(zext(x)) --> zext(x)
  1751. if (const SCEVZeroExtendExpr *SZ = dyn_cast<SCEVZeroExtendExpr>(Op))
  1752. return getZeroExtendExpr(SZ->getOperand(), Ty, Depth + 1);
  1753. // Before doing any expensive analysis, check to see if we've already
  1754. // computed a SCEV for this Op and Ty.
  1755. FoldingSetNodeID ID;
  1756. ID.AddInteger(scSignExtend);
  1757. ID.AddPointer(Op);
  1758. ID.AddPointer(Ty);
  1759. void *IP = nullptr;
  1760. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
  1761. // Limit recursion depth.
  1762. if (Depth > MaxCastDepth) {
  1763. SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
  1764. Op, Ty);
  1765. UniqueSCEVs.InsertNode(S, IP);
  1766. registerUser(S, Op);
  1767. return S;
  1768. }
  1769. // sext(trunc(x)) --> sext(x) or x or trunc(x)
  1770. if (const SCEVTruncateExpr *ST = dyn_cast<SCEVTruncateExpr>(Op)) {
  1771. // It's possible the bits taken off by the truncate were all sign bits. If
  1772. // so, we should be able to simplify this further.
  1773. const SCEV *X = ST->getOperand();
  1774. ConstantRange CR = getSignedRange(X);
  1775. unsigned TruncBits = getTypeSizeInBits(ST->getType());
  1776. unsigned NewBits = getTypeSizeInBits(Ty);
  1777. if (CR.truncate(TruncBits).signExtend(NewBits).contains(
  1778. CR.sextOrTrunc(NewBits)))
  1779. return getTruncateOrSignExtend(X, Ty, Depth);
  1780. }
  1781. if (auto *SA = dyn_cast<SCEVAddExpr>(Op)) {
  1782. // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
  1783. if (SA->hasNoSignedWrap()) {
  1784. // If the addition does not sign overflow then we can, by definition,
  1785. // commute the sign extension with the addition operation.
  1786. SmallVector<const SCEV *, 4> Ops;
  1787. for (const auto *Op : SA->operands())
  1788. Ops.push_back(getSignExtendExpr(Op, Ty, Depth + 1));
  1789. return getAddExpr(Ops, SCEV::FlagNSW, Depth + 1);
  1790. }
  1791. // sext(C + x + y + ...) --> (sext(D) + sext((C - D) + x + y + ...))
  1792. // if D + (C - D + x + y + ...) could be proven to not signed wrap
  1793. // where D maximizes the number of trailing zeros of (C - D + x + y + ...)
  1794. //
  1795. // For instance, this will bring two seemingly different expressions:
  1796. // 1 + sext(5 + 20 * %x + 24 * %y) and
  1797. // sext(6 + 20 * %x + 24 * %y)
  1798. // to the same form:
  1799. // 2 + sext(4 + 20 * %x + 24 * %y)
  1800. if (const auto *SC = dyn_cast<SCEVConstant>(SA->getOperand(0))) {
  1801. const APInt &D = extractConstantWithoutWrapping(*this, SC, SA);
  1802. if (D != 0) {
  1803. const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
  1804. const SCEV *SResidual =
  1805. getAddExpr(getConstant(-D), SA, SCEV::FlagAnyWrap, Depth);
  1806. const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
  1807. return getAddExpr(SSExtD, SSExtR,
  1808. (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
  1809. Depth + 1);
  1810. }
  1811. }
  1812. }
  1813. // If the input value is a chrec scev, and we can prove that the value
  1814. // did not overflow the old, smaller, value, we can sign extend all of the
  1815. // operands (often constants). This allows analysis of something like
  1816. // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
  1817. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op))
  1818. if (AR->isAffine()) {
  1819. const SCEV *Start = AR->getStart();
  1820. const SCEV *Step = AR->getStepRecurrence(*this);
  1821. unsigned BitWidth = getTypeSizeInBits(AR->getType());
  1822. const Loop *L = AR->getLoop();
  1823. if (!AR->hasNoSignedWrap()) {
  1824. auto NewFlags = proveNoWrapViaConstantRanges(AR);
  1825. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
  1826. }
  1827. // If we have special knowledge that this addrec won't overflow,
  1828. // we don't need to do any further analysis.
  1829. if (AR->hasNoSignedWrap()) {
  1830. Start =
  1831. getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
  1832. Step = getSignExtendExpr(Step, Ty, Depth + 1);
  1833. return getAddRecExpr(Start, Step, L, SCEV::FlagNSW);
  1834. }
  1835. // Check whether the backedge-taken count is SCEVCouldNotCompute.
  1836. // Note that this serves two purposes: It filters out loops that are
  1837. // simply not analyzable, and it covers the case where this code is
  1838. // being called from within backedge-taken count analysis, such that
  1839. // attempting to ask for the backedge-taken count would likely result
  1840. // in infinite recursion. In the later case, the analysis code will
  1841. // cope with a conservative value, and it will take care to purge
  1842. // that value once it has finished.
  1843. const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
  1844. if (!isa<SCEVCouldNotCompute>(MaxBECount)) {
  1845. // Manually compute the final value for AR, checking for
  1846. // overflow.
  1847. // Check whether the backedge-taken count can be losslessly casted to
  1848. // the addrec's type. The count is always unsigned.
  1849. const SCEV *CastedMaxBECount =
  1850. getTruncateOrZeroExtend(MaxBECount, Start->getType(), Depth);
  1851. const SCEV *RecastedMaxBECount = getTruncateOrZeroExtend(
  1852. CastedMaxBECount, MaxBECount->getType(), Depth);
  1853. if (MaxBECount == RecastedMaxBECount) {
  1854. Type *WideTy = IntegerType::get(getContext(), BitWidth * 2);
  1855. // Check whether Start+Step*MaxBECount has no signed overflow.
  1856. const SCEV *SMul = getMulExpr(CastedMaxBECount, Step,
  1857. SCEV::FlagAnyWrap, Depth + 1);
  1858. const SCEV *SAdd = getSignExtendExpr(getAddExpr(Start, SMul,
  1859. SCEV::FlagAnyWrap,
  1860. Depth + 1),
  1861. WideTy, Depth + 1);
  1862. const SCEV *WideStart = getSignExtendExpr(Start, WideTy, Depth + 1);
  1863. const SCEV *WideMaxBECount =
  1864. getZeroExtendExpr(CastedMaxBECount, WideTy, Depth + 1);
  1865. const SCEV *OperandExtendedAdd =
  1866. getAddExpr(WideStart,
  1867. getMulExpr(WideMaxBECount,
  1868. getSignExtendExpr(Step, WideTy, Depth + 1),
  1869. SCEV::FlagAnyWrap, Depth + 1),
  1870. SCEV::FlagAnyWrap, Depth + 1);
  1871. if (SAdd == OperandExtendedAdd) {
  1872. // Cache knowledge of AR NSW, which is propagated to this AddRec.
  1873. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
  1874. // Return the expression with the addrec on the outside.
  1875. Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
  1876. Depth + 1);
  1877. Step = getSignExtendExpr(Step, Ty, Depth + 1);
  1878. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1879. }
  1880. // Similar to above, only this time treat the step value as unsigned.
  1881. // This covers loops that count up with an unsigned step.
  1882. OperandExtendedAdd =
  1883. getAddExpr(WideStart,
  1884. getMulExpr(WideMaxBECount,
  1885. getZeroExtendExpr(Step, WideTy, Depth + 1),
  1886. SCEV::FlagAnyWrap, Depth + 1),
  1887. SCEV::FlagAnyWrap, Depth + 1);
  1888. if (SAdd == OperandExtendedAdd) {
  1889. // If AR wraps around then
  1890. //
  1891. // abs(Step) * MaxBECount > unsigned-max(AR->getType())
  1892. // => SAdd != OperandExtendedAdd
  1893. //
  1894. // Thus (AR is not NW => SAdd != OperandExtendedAdd) <=>
  1895. // (SAdd == OperandExtendedAdd => AR is NW)
  1896. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNW);
  1897. // Return the expression with the addrec on the outside.
  1898. Start = getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this,
  1899. Depth + 1);
  1900. Step = getZeroExtendExpr(Step, Ty, Depth + 1);
  1901. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1902. }
  1903. }
  1904. }
  1905. auto NewFlags = proveNoSignedWrapViaInduction(AR);
  1906. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), NewFlags);
  1907. if (AR->hasNoSignedWrap()) {
  1908. // Same as nsw case above - duplicated here to avoid a compile time
  1909. // issue. It's not clear that the order of checks does matter, but
  1910. // it's one of two issue possible causes for a change which was
  1911. // reverted. Be conservative for the moment.
  1912. Start =
  1913. getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
  1914. Step = getSignExtendExpr(Step, Ty, Depth + 1);
  1915. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1916. }
  1917. // sext({C,+,Step}) --> (sext(D) + sext({C-D,+,Step}))<nuw><nsw>
  1918. // if D + (C - D + Step * n) could be proven to not signed wrap
  1919. // where D maximizes the number of trailing zeros of (C - D + Step * n)
  1920. if (const auto *SC = dyn_cast<SCEVConstant>(Start)) {
  1921. const APInt &C = SC->getAPInt();
  1922. const APInt &D = extractConstantWithoutWrapping(*this, C, Step);
  1923. if (D != 0) {
  1924. const SCEV *SSExtD = getSignExtendExpr(getConstant(D), Ty, Depth);
  1925. const SCEV *SResidual =
  1926. getAddRecExpr(getConstant(C - D), Step, L, AR->getNoWrapFlags());
  1927. const SCEV *SSExtR = getSignExtendExpr(SResidual, Ty, Depth + 1);
  1928. return getAddExpr(SSExtD, SSExtR,
  1929. (SCEV::NoWrapFlags)(SCEV::FlagNSW | SCEV::FlagNUW),
  1930. Depth + 1);
  1931. }
  1932. }
  1933. if (proveNoWrapByVaryingStart<SCEVSignExtendExpr>(Start, Step, L)) {
  1934. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), SCEV::FlagNSW);
  1935. Start =
  1936. getExtendAddRecStart<SCEVSignExtendExpr>(AR, Ty, this, Depth + 1);
  1937. Step = getSignExtendExpr(Step, Ty, Depth + 1);
  1938. return getAddRecExpr(Start, Step, L, AR->getNoWrapFlags());
  1939. }
  1940. }
  1941. // If the input value is provably positive and we could not simplify
  1942. // away the sext build a zext instead.
  1943. if (isKnownNonNegative(Op))
  1944. return getZeroExtendExpr(Op, Ty, Depth + 1);
  1945. // The cast wasn't folded; create an explicit cast node.
  1946. // Recompute the insert position, as it may have been invalidated.
  1947. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
  1948. SCEV *S = new (SCEVAllocator) SCEVSignExtendExpr(ID.Intern(SCEVAllocator),
  1949. Op, Ty);
  1950. UniqueSCEVs.InsertNode(S, IP);
  1951. registerUser(S, { Op });
  1952. return S;
  1953. }
  1954. const SCEV *ScalarEvolution::getCastExpr(SCEVTypes Kind, const SCEV *Op,
  1955. Type *Ty) {
  1956. switch (Kind) {
  1957. case scTruncate:
  1958. return getTruncateExpr(Op, Ty);
  1959. case scZeroExtend:
  1960. return getZeroExtendExpr(Op, Ty);
  1961. case scSignExtend:
  1962. return getSignExtendExpr(Op, Ty);
  1963. case scPtrToInt:
  1964. return getPtrToIntExpr(Op, Ty);
  1965. default:
  1966. llvm_unreachable("Not a SCEV cast expression!");
  1967. }
  1968. }
  1969. /// getAnyExtendExpr - Return a SCEV for the given operand extended with
  1970. /// unspecified bits out to the given type.
  1971. const SCEV *ScalarEvolution::getAnyExtendExpr(const SCEV *Op,
  1972. Type *Ty) {
  1973. assert(getTypeSizeInBits(Op->getType()) < getTypeSizeInBits(Ty) &&
  1974. "This is not an extending conversion!");
  1975. assert(isSCEVable(Ty) &&
  1976. "This is not a conversion to a SCEVable type!");
  1977. Ty = getEffectiveSCEVType(Ty);
  1978. // Sign-extend negative constants.
  1979. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
  1980. if (SC->getAPInt().isNegative())
  1981. return getSignExtendExpr(Op, Ty);
  1982. // Peel off a truncate cast.
  1983. if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Op)) {
  1984. const SCEV *NewOp = T->getOperand();
  1985. if (getTypeSizeInBits(NewOp->getType()) < getTypeSizeInBits(Ty))
  1986. return getAnyExtendExpr(NewOp, Ty);
  1987. return getTruncateOrNoop(NewOp, Ty);
  1988. }
  1989. // Next try a zext cast. If the cast is folded, use it.
  1990. const SCEV *ZExt = getZeroExtendExpr(Op, Ty);
  1991. if (!isa<SCEVZeroExtendExpr>(ZExt))
  1992. return ZExt;
  1993. // Next try a sext cast. If the cast is folded, use it.
  1994. const SCEV *SExt = getSignExtendExpr(Op, Ty);
  1995. if (!isa<SCEVSignExtendExpr>(SExt))
  1996. return SExt;
  1997. // Force the cast to be folded into the operands of an addrec.
  1998. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Op)) {
  1999. SmallVector<const SCEV *, 4> Ops;
  2000. for (const SCEV *Op : AR->operands())
  2001. Ops.push_back(getAnyExtendExpr(Op, Ty));
  2002. return getAddRecExpr(Ops, AR->getLoop(), SCEV::FlagNW);
  2003. }
  2004. // If the expression is obviously signed, use the sext cast value.
  2005. if (isa<SCEVSMaxExpr>(Op))
  2006. return SExt;
  2007. // Absent any other information, use the zext cast value.
  2008. return ZExt;
  2009. }
  2010. /// Process the given Ops list, which is a list of operands to be added under
  2011. /// the given scale, update the given map. This is a helper function for
  2012. /// getAddRecExpr. As an example of what it does, given a sequence of operands
  2013. /// that would form an add expression like this:
  2014. ///
  2015. /// m + n + 13 + (A * (o + p + (B * (q + m + 29)))) + r + (-1 * r)
  2016. ///
  2017. /// where A and B are constants, update the map with these values:
  2018. ///
  2019. /// (m, 1+A*B), (n, 1), (o, A), (p, A), (q, A*B), (r, 0)
  2020. ///
  2021. /// and add 13 + A*B*29 to AccumulatedConstant.
  2022. /// This will allow getAddRecExpr to produce this:
  2023. ///
  2024. /// 13+A*B*29 + n + (m * (1+A*B)) + ((o + p) * A) + (q * A*B)
  2025. ///
  2026. /// This form often exposes folding opportunities that are hidden in
  2027. /// the original operand list.
  2028. ///
  2029. /// Return true iff it appears that any interesting folding opportunities
  2030. /// may be exposed. This helps getAddRecExpr short-circuit extra work in
  2031. /// the common case where no interesting opportunities are present, and
  2032. /// is also used as a check to avoid infinite recursion.
  2033. static bool
  2034. CollectAddOperandsWithScales(DenseMap<const SCEV *, APInt> &M,
  2035. SmallVectorImpl<const SCEV *> &NewOps,
  2036. APInt &AccumulatedConstant,
  2037. ArrayRef<const SCEV *> Ops, const APInt &Scale,
  2038. ScalarEvolution &SE) {
  2039. bool Interesting = false;
  2040. // Iterate over the add operands. They are sorted, with constants first.
  2041. unsigned i = 0;
  2042. while (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
  2043. ++i;
  2044. // Pull a buried constant out to the outside.
  2045. if (Scale != 1 || AccumulatedConstant != 0 || C->getValue()->isZero())
  2046. Interesting = true;
  2047. AccumulatedConstant += Scale * C->getAPInt();
  2048. }
  2049. // Next comes everything else. We're especially interested in multiplies
  2050. // here, but they're in the middle, so just visit the rest with one loop.
  2051. for (; i != Ops.size(); ++i) {
  2052. const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[i]);
  2053. if (Mul && isa<SCEVConstant>(Mul->getOperand(0))) {
  2054. APInt NewScale =
  2055. Scale * cast<SCEVConstant>(Mul->getOperand(0))->getAPInt();
  2056. if (Mul->getNumOperands() == 2 && isa<SCEVAddExpr>(Mul->getOperand(1))) {
  2057. // A multiplication of a constant with another add; recurse.
  2058. const SCEVAddExpr *Add = cast<SCEVAddExpr>(Mul->getOperand(1));
  2059. Interesting |=
  2060. CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
  2061. Add->operands(), NewScale, SE);
  2062. } else {
  2063. // A multiplication of a constant with some other value. Update
  2064. // the map.
  2065. SmallVector<const SCEV *, 4> MulOps(drop_begin(Mul->operands()));
  2066. const SCEV *Key = SE.getMulExpr(MulOps);
  2067. auto Pair = M.insert({Key, NewScale});
  2068. if (Pair.second) {
  2069. NewOps.push_back(Pair.first->first);
  2070. } else {
  2071. Pair.first->second += NewScale;
  2072. // The map already had an entry for this value, which may indicate
  2073. // a folding opportunity.
  2074. Interesting = true;
  2075. }
  2076. }
  2077. } else {
  2078. // An ordinary operand. Update the map.
  2079. std::pair<DenseMap<const SCEV *, APInt>::iterator, bool> Pair =
  2080. M.insert({Ops[i], Scale});
  2081. if (Pair.second) {
  2082. NewOps.push_back(Pair.first->first);
  2083. } else {
  2084. Pair.first->second += Scale;
  2085. // The map already had an entry for this value, which may indicate
  2086. // a folding opportunity.
  2087. Interesting = true;
  2088. }
  2089. }
  2090. }
  2091. return Interesting;
  2092. }
  2093. bool ScalarEvolution::willNotOverflow(Instruction::BinaryOps BinOp, bool Signed,
  2094. const SCEV *LHS, const SCEV *RHS,
  2095. const Instruction *CtxI) {
  2096. const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
  2097. SCEV::NoWrapFlags, unsigned);
  2098. switch (BinOp) {
  2099. default:
  2100. llvm_unreachable("Unsupported binary op");
  2101. case Instruction::Add:
  2102. Operation = &ScalarEvolution::getAddExpr;
  2103. break;
  2104. case Instruction::Sub:
  2105. Operation = &ScalarEvolution::getMinusSCEV;
  2106. break;
  2107. case Instruction::Mul:
  2108. Operation = &ScalarEvolution::getMulExpr;
  2109. break;
  2110. }
  2111. const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
  2112. Signed ? &ScalarEvolution::getSignExtendExpr
  2113. : &ScalarEvolution::getZeroExtendExpr;
  2114. // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
  2115. auto *NarrowTy = cast<IntegerType>(LHS->getType());
  2116. auto *WideTy =
  2117. IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
  2118. const SCEV *A = (this->*Extension)(
  2119. (this->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0), WideTy, 0);
  2120. const SCEV *LHSB = (this->*Extension)(LHS, WideTy, 0);
  2121. const SCEV *RHSB = (this->*Extension)(RHS, WideTy, 0);
  2122. const SCEV *B = (this->*Operation)(LHSB, RHSB, SCEV::FlagAnyWrap, 0);
  2123. if (A == B)
  2124. return true;
  2125. // Can we use context to prove the fact we need?
  2126. if (!CtxI)
  2127. return false;
  2128. // We can prove that add(x, constant) doesn't wrap if isKnownPredicateAt can
  2129. // guarantee that x <= max_int - constant at the given context.
  2130. // TODO: Support other operations.
  2131. if (BinOp != Instruction::Add)
  2132. return false;
  2133. auto *RHSC = dyn_cast<SCEVConstant>(RHS);
  2134. // TODO: Lift this limitation.
  2135. if (!RHSC)
  2136. return false;
  2137. APInt C = RHSC->getAPInt();
  2138. // TODO: Also lift this limitation.
  2139. if (Signed && C.isNegative())
  2140. return false;
  2141. unsigned NumBits = C.getBitWidth();
  2142. APInt Max =
  2143. Signed ? APInt::getSignedMaxValue(NumBits) : APInt::getMaxValue(NumBits);
  2144. APInt Limit = Max - C;
  2145. ICmpInst::Predicate Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
  2146. return isKnownPredicateAt(Pred, LHS, getConstant(Limit), CtxI);
  2147. }
  2148. std::optional<SCEV::NoWrapFlags>
  2149. ScalarEvolution::getStrengthenedNoWrapFlagsFromBinOp(
  2150. const OverflowingBinaryOperator *OBO) {
  2151. // It cannot be done any better.
  2152. if (OBO->hasNoUnsignedWrap() && OBO->hasNoSignedWrap())
  2153. return std::nullopt;
  2154. SCEV::NoWrapFlags Flags = SCEV::NoWrapFlags::FlagAnyWrap;
  2155. if (OBO->hasNoUnsignedWrap())
  2156. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
  2157. if (OBO->hasNoSignedWrap())
  2158. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
  2159. bool Deduced = false;
  2160. if (OBO->getOpcode() != Instruction::Add &&
  2161. OBO->getOpcode() != Instruction::Sub &&
  2162. OBO->getOpcode() != Instruction::Mul)
  2163. return std::nullopt;
  2164. const SCEV *LHS = getSCEV(OBO->getOperand(0));
  2165. const SCEV *RHS = getSCEV(OBO->getOperand(1));
  2166. const Instruction *CtxI =
  2167. UseContextForNoWrapFlagInference ? dyn_cast<Instruction>(OBO) : nullptr;
  2168. if (!OBO->hasNoUnsignedWrap() &&
  2169. willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
  2170. /* Signed */ false, LHS, RHS, CtxI)) {
  2171. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
  2172. Deduced = true;
  2173. }
  2174. if (!OBO->hasNoSignedWrap() &&
  2175. willNotOverflow((Instruction::BinaryOps)OBO->getOpcode(),
  2176. /* Signed */ true, LHS, RHS, CtxI)) {
  2177. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
  2178. Deduced = true;
  2179. }
  2180. if (Deduced)
  2181. return Flags;
  2182. return std::nullopt;
  2183. }
  2184. // We're trying to construct a SCEV of type `Type' with `Ops' as operands and
  2185. // `OldFlags' as can't-wrap behavior. Infer a more aggressive set of
  2186. // can't-overflow flags for the operation if possible.
  2187. static SCEV::NoWrapFlags
  2188. StrengthenNoWrapFlags(ScalarEvolution *SE, SCEVTypes Type,
  2189. const ArrayRef<const SCEV *> Ops,
  2190. SCEV::NoWrapFlags Flags) {
  2191. using namespace std::placeholders;
  2192. using OBO = OverflowingBinaryOperator;
  2193. bool CanAnalyze =
  2194. Type == scAddExpr || Type == scAddRecExpr || Type == scMulExpr;
  2195. (void)CanAnalyze;
  2196. assert(CanAnalyze && "don't call from other places!");
  2197. int SignOrUnsignMask = SCEV::FlagNUW | SCEV::FlagNSW;
  2198. SCEV::NoWrapFlags SignOrUnsignWrap =
  2199. ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
  2200. // If FlagNSW is true and all the operands are non-negative, infer FlagNUW.
  2201. auto IsKnownNonNegative = [&](const SCEV *S) {
  2202. return SE->isKnownNonNegative(S);
  2203. };
  2204. if (SignOrUnsignWrap == SCEV::FlagNSW && all_of(Ops, IsKnownNonNegative))
  2205. Flags =
  2206. ScalarEvolution::setFlags(Flags, (SCEV::NoWrapFlags)SignOrUnsignMask);
  2207. SignOrUnsignWrap = ScalarEvolution::maskFlags(Flags, SignOrUnsignMask);
  2208. if (SignOrUnsignWrap != SignOrUnsignMask &&
  2209. (Type == scAddExpr || Type == scMulExpr) && Ops.size() == 2 &&
  2210. isa<SCEVConstant>(Ops[0])) {
  2211. auto Opcode = [&] {
  2212. switch (Type) {
  2213. case scAddExpr:
  2214. return Instruction::Add;
  2215. case scMulExpr:
  2216. return Instruction::Mul;
  2217. default:
  2218. llvm_unreachable("Unexpected SCEV op.");
  2219. }
  2220. }();
  2221. const APInt &C = cast<SCEVConstant>(Ops[0])->getAPInt();
  2222. // (A <opcode> C) --> (A <opcode> C)<nsw> if the op doesn't sign overflow.
  2223. if (!(SignOrUnsignWrap & SCEV::FlagNSW)) {
  2224. auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
  2225. Opcode, C, OBO::NoSignedWrap);
  2226. if (NSWRegion.contains(SE->getSignedRange(Ops[1])))
  2227. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
  2228. }
  2229. // (A <opcode> C) --> (A <opcode> C)<nuw> if the op doesn't unsign overflow.
  2230. if (!(SignOrUnsignWrap & SCEV::FlagNUW)) {
  2231. auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
  2232. Opcode, C, OBO::NoUnsignedWrap);
  2233. if (NUWRegion.contains(SE->getUnsignedRange(Ops[1])))
  2234. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
  2235. }
  2236. }
  2237. // <0,+,nonnegative><nw> is also nuw
  2238. // TODO: Add corresponding nsw case
  2239. if (Type == scAddRecExpr && ScalarEvolution::hasFlags(Flags, SCEV::FlagNW) &&
  2240. !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) && Ops.size() == 2 &&
  2241. Ops[0]->isZero() && IsKnownNonNegative(Ops[1]))
  2242. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
  2243. // both (udiv X, Y) * Y and Y * (udiv X, Y) are always NUW
  2244. if (Type == scMulExpr && !ScalarEvolution::hasFlags(Flags, SCEV::FlagNUW) &&
  2245. Ops.size() == 2) {
  2246. if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[0]))
  2247. if (UDiv->getOperand(1) == Ops[1])
  2248. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
  2249. if (auto *UDiv = dyn_cast<SCEVUDivExpr>(Ops[1]))
  2250. if (UDiv->getOperand(1) == Ops[0])
  2251. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
  2252. }
  2253. return Flags;
  2254. }
  2255. bool ScalarEvolution::isAvailableAtLoopEntry(const SCEV *S, const Loop *L) {
  2256. return isLoopInvariant(S, L) && properlyDominates(S, L->getHeader());
  2257. }
  2258. /// Get a canonical add expression, or something simpler if possible.
  2259. const SCEV *ScalarEvolution::getAddExpr(SmallVectorImpl<const SCEV *> &Ops,
  2260. SCEV::NoWrapFlags OrigFlags,
  2261. unsigned Depth) {
  2262. assert(!(OrigFlags & ~(SCEV::FlagNUW | SCEV::FlagNSW)) &&
  2263. "only nuw or nsw allowed");
  2264. assert(!Ops.empty() && "Cannot get empty add!");
  2265. if (Ops.size() == 1) return Ops[0];
  2266. #ifndef NDEBUG
  2267. Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
  2268. for (unsigned i = 1, e = Ops.size(); i != e; ++i)
  2269. assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
  2270. "SCEVAddExpr operand types don't match!");
  2271. unsigned NumPtrs = count_if(
  2272. Ops, [](const SCEV *Op) { return Op->getType()->isPointerTy(); });
  2273. assert(NumPtrs <= 1 && "add has at most one pointer operand");
  2274. #endif
  2275. // Sort by complexity, this groups all similar expression types together.
  2276. GroupByComplexity(Ops, &LI, DT);
  2277. // If there are any constants, fold them together.
  2278. unsigned Idx = 0;
  2279. if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
  2280. ++Idx;
  2281. assert(Idx < Ops.size());
  2282. while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
  2283. // We found two constants, fold them together!
  2284. Ops[0] = getConstant(LHSC->getAPInt() + RHSC->getAPInt());
  2285. if (Ops.size() == 2) return Ops[0];
  2286. Ops.erase(Ops.begin()+1); // Erase the folded element
  2287. LHSC = cast<SCEVConstant>(Ops[0]);
  2288. }
  2289. // If we are left with a constant zero being added, strip it off.
  2290. if (LHSC->getValue()->isZero()) {
  2291. Ops.erase(Ops.begin());
  2292. --Idx;
  2293. }
  2294. if (Ops.size() == 1) return Ops[0];
  2295. }
  2296. // Delay expensive flag strengthening until necessary.
  2297. auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
  2298. return StrengthenNoWrapFlags(this, scAddExpr, Ops, OrigFlags);
  2299. };
  2300. // Limit recursion calls depth.
  2301. if (Depth > MaxArithDepth || hasHugeExpression(Ops))
  2302. return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
  2303. if (SCEV *S = findExistingSCEVInCache(scAddExpr, Ops)) {
  2304. // Don't strengthen flags if we have no new information.
  2305. SCEVAddExpr *Add = static_cast<SCEVAddExpr *>(S);
  2306. if (Add->getNoWrapFlags(OrigFlags) != OrigFlags)
  2307. Add->setNoWrapFlags(ComputeFlags(Ops));
  2308. return S;
  2309. }
  2310. // Okay, check to see if the same value occurs in the operand list more than
  2311. // once. If so, merge them together into an multiply expression. Since we
  2312. // sorted the list, these values are required to be adjacent.
  2313. Type *Ty = Ops[0]->getType();
  2314. bool FoundMatch = false;
  2315. for (unsigned i = 0, e = Ops.size(); i != e-1; ++i)
  2316. if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
  2317. // Scan ahead to count how many equal operands there are.
  2318. unsigned Count = 2;
  2319. while (i+Count != e && Ops[i+Count] == Ops[i])
  2320. ++Count;
  2321. // Merge the values into a multiply.
  2322. const SCEV *Scale = getConstant(Ty, Count);
  2323. const SCEV *Mul = getMulExpr(Scale, Ops[i], SCEV::FlagAnyWrap, Depth + 1);
  2324. if (Ops.size() == Count)
  2325. return Mul;
  2326. Ops[i] = Mul;
  2327. Ops.erase(Ops.begin()+i+1, Ops.begin()+i+Count);
  2328. --i; e -= Count - 1;
  2329. FoundMatch = true;
  2330. }
  2331. if (FoundMatch)
  2332. return getAddExpr(Ops, OrigFlags, Depth + 1);
  2333. // Check for truncates. If all the operands are truncated from the same
  2334. // type, see if factoring out the truncate would permit the result to be
  2335. // folded. eg., n*trunc(x) + m*trunc(y) --> trunc(trunc(m)*x + trunc(n)*y)
  2336. // if the contents of the resulting outer trunc fold to something simple.
  2337. auto FindTruncSrcType = [&]() -> Type * {
  2338. // We're ultimately looking to fold an addrec of truncs and muls of only
  2339. // constants and truncs, so if we find any other types of SCEV
  2340. // as operands of the addrec then we bail and return nullptr here.
  2341. // Otherwise, we return the type of the operand of a trunc that we find.
  2342. if (auto *T = dyn_cast<SCEVTruncateExpr>(Ops[Idx]))
  2343. return T->getOperand()->getType();
  2344. if (const auto *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
  2345. const auto *LastOp = Mul->getOperand(Mul->getNumOperands() - 1);
  2346. if (const auto *T = dyn_cast<SCEVTruncateExpr>(LastOp))
  2347. return T->getOperand()->getType();
  2348. }
  2349. return nullptr;
  2350. };
  2351. if (auto *SrcType = FindTruncSrcType()) {
  2352. SmallVector<const SCEV *, 8> LargeOps;
  2353. bool Ok = true;
  2354. // Check all the operands to see if they can be represented in the
  2355. // source type of the truncate.
  2356. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  2357. if (const SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(Ops[i])) {
  2358. if (T->getOperand()->getType() != SrcType) {
  2359. Ok = false;
  2360. break;
  2361. }
  2362. LargeOps.push_back(T->getOperand());
  2363. } else if (const SCEVConstant *C = dyn_cast<SCEVConstant>(Ops[i])) {
  2364. LargeOps.push_back(getAnyExtendExpr(C, SrcType));
  2365. } else if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(Ops[i])) {
  2366. SmallVector<const SCEV *, 8> LargeMulOps;
  2367. for (unsigned j = 0, f = M->getNumOperands(); j != f && Ok; ++j) {
  2368. if (const SCEVTruncateExpr *T =
  2369. dyn_cast<SCEVTruncateExpr>(M->getOperand(j))) {
  2370. if (T->getOperand()->getType() != SrcType) {
  2371. Ok = false;
  2372. break;
  2373. }
  2374. LargeMulOps.push_back(T->getOperand());
  2375. } else if (const auto *C = dyn_cast<SCEVConstant>(M->getOperand(j))) {
  2376. LargeMulOps.push_back(getAnyExtendExpr(C, SrcType));
  2377. } else {
  2378. Ok = false;
  2379. break;
  2380. }
  2381. }
  2382. if (Ok)
  2383. LargeOps.push_back(getMulExpr(LargeMulOps, SCEV::FlagAnyWrap, Depth + 1));
  2384. } else {
  2385. Ok = false;
  2386. break;
  2387. }
  2388. }
  2389. if (Ok) {
  2390. // Evaluate the expression in the larger type.
  2391. const SCEV *Fold = getAddExpr(LargeOps, SCEV::FlagAnyWrap, Depth + 1);
  2392. // If it folds to something simple, use it. Otherwise, don't.
  2393. if (isa<SCEVConstant>(Fold) || isa<SCEVUnknown>(Fold))
  2394. return getTruncateExpr(Fold, Ty);
  2395. }
  2396. }
  2397. if (Ops.size() == 2) {
  2398. // Check if we have an expression of the form ((X + C1) - C2), where C1 and
  2399. // C2 can be folded in a way that allows retaining wrapping flags of (X +
  2400. // C1).
  2401. const SCEV *A = Ops[0];
  2402. const SCEV *B = Ops[1];
  2403. auto *AddExpr = dyn_cast<SCEVAddExpr>(B);
  2404. auto *C = dyn_cast<SCEVConstant>(A);
  2405. if (AddExpr && C && isa<SCEVConstant>(AddExpr->getOperand(0))) {
  2406. auto C1 = cast<SCEVConstant>(AddExpr->getOperand(0))->getAPInt();
  2407. auto C2 = C->getAPInt();
  2408. SCEV::NoWrapFlags PreservedFlags = SCEV::FlagAnyWrap;
  2409. APInt ConstAdd = C1 + C2;
  2410. auto AddFlags = AddExpr->getNoWrapFlags();
  2411. // Adding a smaller constant is NUW if the original AddExpr was NUW.
  2412. if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNUW) &&
  2413. ConstAdd.ule(C1)) {
  2414. PreservedFlags =
  2415. ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNUW);
  2416. }
  2417. // Adding a constant with the same sign and small magnitude is NSW, if the
  2418. // original AddExpr was NSW.
  2419. if (ScalarEvolution::hasFlags(AddFlags, SCEV::FlagNSW) &&
  2420. C1.isSignBitSet() == ConstAdd.isSignBitSet() &&
  2421. ConstAdd.abs().ule(C1.abs())) {
  2422. PreservedFlags =
  2423. ScalarEvolution::setFlags(PreservedFlags, SCEV::FlagNSW);
  2424. }
  2425. if (PreservedFlags != SCEV::FlagAnyWrap) {
  2426. SmallVector<const SCEV *, 4> NewOps(AddExpr->operands());
  2427. NewOps[0] = getConstant(ConstAdd);
  2428. return getAddExpr(NewOps, PreservedFlags);
  2429. }
  2430. }
  2431. }
  2432. // Canonicalize (-1 * urem X, Y) + X --> (Y * X/Y)
  2433. if (Ops.size() == 2) {
  2434. const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[0]);
  2435. if (Mul && Mul->getNumOperands() == 2 &&
  2436. Mul->getOperand(0)->isAllOnesValue()) {
  2437. const SCEV *X;
  2438. const SCEV *Y;
  2439. if (matchURem(Mul->getOperand(1), X, Y) && X == Ops[1]) {
  2440. return getMulExpr(Y, getUDivExpr(X, Y));
  2441. }
  2442. }
  2443. }
  2444. // Skip past any other cast SCEVs.
  2445. while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
  2446. ++Idx;
  2447. // If there are add operands they would be next.
  2448. if (Idx < Ops.size()) {
  2449. bool DeletedAdd = false;
  2450. // If the original flags and all inlined SCEVAddExprs are NUW, use the
  2451. // common NUW flag for expression after inlining. Other flags cannot be
  2452. // preserved, because they may depend on the original order of operations.
  2453. SCEV::NoWrapFlags CommonFlags = maskFlags(OrigFlags, SCEV::FlagNUW);
  2454. while (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
  2455. if (Ops.size() > AddOpsInlineThreshold ||
  2456. Add->getNumOperands() > AddOpsInlineThreshold)
  2457. break;
  2458. // If we have an add, expand the add operands onto the end of the operands
  2459. // list.
  2460. Ops.erase(Ops.begin()+Idx);
  2461. append_range(Ops, Add->operands());
  2462. DeletedAdd = true;
  2463. CommonFlags = maskFlags(CommonFlags, Add->getNoWrapFlags());
  2464. }
  2465. // If we deleted at least one add, we added operands to the end of the list,
  2466. // and they are not necessarily sorted. Recurse to resort and resimplify
  2467. // any operands we just acquired.
  2468. if (DeletedAdd)
  2469. return getAddExpr(Ops, CommonFlags, Depth + 1);
  2470. }
  2471. // Skip over the add expression until we get to a multiply.
  2472. while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
  2473. ++Idx;
  2474. // Check to see if there are any folding opportunities present with
  2475. // operands multiplied by constant values.
  2476. if (Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx])) {
  2477. uint64_t BitWidth = getTypeSizeInBits(Ty);
  2478. DenseMap<const SCEV *, APInt> M;
  2479. SmallVector<const SCEV *, 8> NewOps;
  2480. APInt AccumulatedConstant(BitWidth, 0);
  2481. if (CollectAddOperandsWithScales(M, NewOps, AccumulatedConstant,
  2482. Ops, APInt(BitWidth, 1), *this)) {
  2483. struct APIntCompare {
  2484. bool operator()(const APInt &LHS, const APInt &RHS) const {
  2485. return LHS.ult(RHS);
  2486. }
  2487. };
  2488. // Some interesting folding opportunity is present, so its worthwhile to
  2489. // re-generate the operands list. Group the operands by constant scale,
  2490. // to avoid multiplying by the same constant scale multiple times.
  2491. std::map<APInt, SmallVector<const SCEV *, 4>, APIntCompare> MulOpLists;
  2492. for (const SCEV *NewOp : NewOps)
  2493. MulOpLists[M.find(NewOp)->second].push_back(NewOp);
  2494. // Re-generate the operands list.
  2495. Ops.clear();
  2496. if (AccumulatedConstant != 0)
  2497. Ops.push_back(getConstant(AccumulatedConstant));
  2498. for (auto &MulOp : MulOpLists) {
  2499. if (MulOp.first == 1) {
  2500. Ops.push_back(getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1));
  2501. } else if (MulOp.first != 0) {
  2502. Ops.push_back(getMulExpr(
  2503. getConstant(MulOp.first),
  2504. getAddExpr(MulOp.second, SCEV::FlagAnyWrap, Depth + 1),
  2505. SCEV::FlagAnyWrap, Depth + 1));
  2506. }
  2507. }
  2508. if (Ops.empty())
  2509. return getZero(Ty);
  2510. if (Ops.size() == 1)
  2511. return Ops[0];
  2512. return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  2513. }
  2514. }
  2515. // If we are adding something to a multiply expression, make sure the
  2516. // something is not already an operand of the multiply. If so, merge it into
  2517. // the multiply.
  2518. for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
  2519. const SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
  2520. for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
  2521. const SCEV *MulOpSCEV = Mul->getOperand(MulOp);
  2522. if (isa<SCEVConstant>(MulOpSCEV))
  2523. continue;
  2524. for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
  2525. if (MulOpSCEV == Ops[AddOp]) {
  2526. // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
  2527. const SCEV *InnerMul = Mul->getOperand(MulOp == 0);
  2528. if (Mul->getNumOperands() != 2) {
  2529. // If the multiply has more than two operands, we must get the
  2530. // Y*Z term.
  2531. SmallVector<const SCEV *, 4> MulOps(
  2532. Mul->operands().take_front(MulOp));
  2533. append_range(MulOps, Mul->operands().drop_front(MulOp + 1));
  2534. InnerMul = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
  2535. }
  2536. SmallVector<const SCEV *, 2> TwoOps = {getOne(Ty), InnerMul};
  2537. const SCEV *AddOne = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
  2538. const SCEV *OuterMul = getMulExpr(AddOne, MulOpSCEV,
  2539. SCEV::FlagAnyWrap, Depth + 1);
  2540. if (Ops.size() == 2) return OuterMul;
  2541. if (AddOp < Idx) {
  2542. Ops.erase(Ops.begin()+AddOp);
  2543. Ops.erase(Ops.begin()+Idx-1);
  2544. } else {
  2545. Ops.erase(Ops.begin()+Idx);
  2546. Ops.erase(Ops.begin()+AddOp-1);
  2547. }
  2548. Ops.push_back(OuterMul);
  2549. return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  2550. }
  2551. // Check this multiply against other multiplies being added together.
  2552. for (unsigned OtherMulIdx = Idx+1;
  2553. OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
  2554. ++OtherMulIdx) {
  2555. const SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
  2556. // If MulOp occurs in OtherMul, we can fold the two multiplies
  2557. // together.
  2558. for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
  2559. OMulOp != e; ++OMulOp)
  2560. if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
  2561. // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
  2562. const SCEV *InnerMul1 = Mul->getOperand(MulOp == 0);
  2563. if (Mul->getNumOperands() != 2) {
  2564. SmallVector<const SCEV *, 4> MulOps(
  2565. Mul->operands().take_front(MulOp));
  2566. append_range(MulOps, Mul->operands().drop_front(MulOp+1));
  2567. InnerMul1 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
  2568. }
  2569. const SCEV *InnerMul2 = OtherMul->getOperand(OMulOp == 0);
  2570. if (OtherMul->getNumOperands() != 2) {
  2571. SmallVector<const SCEV *, 4> MulOps(
  2572. OtherMul->operands().take_front(OMulOp));
  2573. append_range(MulOps, OtherMul->operands().drop_front(OMulOp+1));
  2574. InnerMul2 = getMulExpr(MulOps, SCEV::FlagAnyWrap, Depth + 1);
  2575. }
  2576. SmallVector<const SCEV *, 2> TwoOps = {InnerMul1, InnerMul2};
  2577. const SCEV *InnerMulSum =
  2578. getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
  2579. const SCEV *OuterMul = getMulExpr(MulOpSCEV, InnerMulSum,
  2580. SCEV::FlagAnyWrap, Depth + 1);
  2581. if (Ops.size() == 2) return OuterMul;
  2582. Ops.erase(Ops.begin()+Idx);
  2583. Ops.erase(Ops.begin()+OtherMulIdx-1);
  2584. Ops.push_back(OuterMul);
  2585. return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  2586. }
  2587. }
  2588. }
  2589. }
  2590. // If there are any add recurrences in the operands list, see if any other
  2591. // added values are loop invariant. If so, we can fold them into the
  2592. // recurrence.
  2593. while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
  2594. ++Idx;
  2595. // Scan over all recurrences, trying to fold loop invariants into them.
  2596. for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
  2597. // Scan all of the other operands to this add and add them to the vector if
  2598. // they are loop invariant w.r.t. the recurrence.
  2599. SmallVector<const SCEV *, 8> LIOps;
  2600. const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
  2601. const Loop *AddRecLoop = AddRec->getLoop();
  2602. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  2603. if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
  2604. LIOps.push_back(Ops[i]);
  2605. Ops.erase(Ops.begin()+i);
  2606. --i; --e;
  2607. }
  2608. // If we found some loop invariants, fold them into the recurrence.
  2609. if (!LIOps.empty()) {
  2610. // Compute nowrap flags for the addition of the loop-invariant ops and
  2611. // the addrec. Temporarily push it as an operand for that purpose. These
  2612. // flags are valid in the scope of the addrec only.
  2613. LIOps.push_back(AddRec);
  2614. SCEV::NoWrapFlags Flags = ComputeFlags(LIOps);
  2615. LIOps.pop_back();
  2616. // NLI + LI + {Start,+,Step} --> NLI + {LI+Start,+,Step}
  2617. LIOps.push_back(AddRec->getStart());
  2618. SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
  2619. // It is not in general safe to propagate flags valid on an add within
  2620. // the addrec scope to one outside it. We must prove that the inner
  2621. // scope is guaranteed to execute if the outer one does to be able to
  2622. // safely propagate. We know the program is undefined if poison is
  2623. // produced on the inner scoped addrec. We also know that *for this use*
  2624. // the outer scoped add can't overflow (because of the flags we just
  2625. // computed for the inner scoped add) without the program being undefined.
  2626. // Proving that entry to the outer scope neccesitates entry to the inner
  2627. // scope, thus proves the program undefined if the flags would be violated
  2628. // in the outer scope.
  2629. SCEV::NoWrapFlags AddFlags = Flags;
  2630. if (AddFlags != SCEV::FlagAnyWrap) {
  2631. auto *DefI = getDefiningScopeBound(LIOps);
  2632. auto *ReachI = &*AddRecLoop->getHeader()->begin();
  2633. if (!isGuaranteedToTransferExecutionTo(DefI, ReachI))
  2634. AddFlags = SCEV::FlagAnyWrap;
  2635. }
  2636. AddRecOps[0] = getAddExpr(LIOps, AddFlags, Depth + 1);
  2637. // Build the new addrec. Propagate the NUW and NSW flags if both the
  2638. // outer add and the inner addrec are guaranteed to have no overflow.
  2639. // Always propagate NW.
  2640. Flags = AddRec->getNoWrapFlags(setFlags(Flags, SCEV::FlagNW));
  2641. const SCEV *NewRec = getAddRecExpr(AddRecOps, AddRecLoop, Flags);
  2642. // If all of the other operands were loop invariant, we are done.
  2643. if (Ops.size() == 1) return NewRec;
  2644. // Otherwise, add the folded AddRec by the non-invariant parts.
  2645. for (unsigned i = 0;; ++i)
  2646. if (Ops[i] == AddRec) {
  2647. Ops[i] = NewRec;
  2648. break;
  2649. }
  2650. return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  2651. }
  2652. // Okay, if there weren't any loop invariants to be folded, check to see if
  2653. // there are multiple AddRec's with the same loop induction variable being
  2654. // added together. If so, we can fold them.
  2655. for (unsigned OtherIdx = Idx+1;
  2656. OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
  2657. ++OtherIdx) {
  2658. // We expect the AddRecExpr's to be sorted in reverse dominance order,
  2659. // so that the 1st found AddRecExpr is dominated by all others.
  2660. assert(DT.dominates(
  2661. cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()->getHeader(),
  2662. AddRec->getLoop()->getHeader()) &&
  2663. "AddRecExprs are not sorted in reverse dominance order?");
  2664. if (AddRecLoop == cast<SCEVAddRecExpr>(Ops[OtherIdx])->getLoop()) {
  2665. // Other + {A,+,B}<L> + {C,+,D}<L> --> Other + {A+C,+,B+D}<L>
  2666. SmallVector<const SCEV *, 4> AddRecOps(AddRec->operands());
  2667. for (; OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
  2668. ++OtherIdx) {
  2669. const auto *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
  2670. if (OtherAddRec->getLoop() == AddRecLoop) {
  2671. for (unsigned i = 0, e = OtherAddRec->getNumOperands();
  2672. i != e; ++i) {
  2673. if (i >= AddRecOps.size()) {
  2674. append_range(AddRecOps, OtherAddRec->operands().drop_front(i));
  2675. break;
  2676. }
  2677. SmallVector<const SCEV *, 2> TwoOps = {
  2678. AddRecOps[i], OtherAddRec->getOperand(i)};
  2679. AddRecOps[i] = getAddExpr(TwoOps, SCEV::FlagAnyWrap, Depth + 1);
  2680. }
  2681. Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
  2682. }
  2683. }
  2684. // Step size has changed, so we cannot guarantee no self-wraparound.
  2685. Ops[Idx] = getAddRecExpr(AddRecOps, AddRecLoop, SCEV::FlagAnyWrap);
  2686. return getAddExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  2687. }
  2688. }
  2689. // Otherwise couldn't fold anything into this recurrence. Move onto the
  2690. // next one.
  2691. }
  2692. // Okay, it looks like we really DO need an add expr. Check to see if we
  2693. // already have one, otherwise create a new one.
  2694. return getOrCreateAddExpr(Ops, ComputeFlags(Ops));
  2695. }
  2696. const SCEV *
  2697. ScalarEvolution::getOrCreateAddExpr(ArrayRef<const SCEV *> Ops,
  2698. SCEV::NoWrapFlags Flags) {
  2699. FoldingSetNodeID ID;
  2700. ID.AddInteger(scAddExpr);
  2701. for (const SCEV *Op : Ops)
  2702. ID.AddPointer(Op);
  2703. void *IP = nullptr;
  2704. SCEVAddExpr *S =
  2705. static_cast<SCEVAddExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
  2706. if (!S) {
  2707. const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
  2708. std::uninitialized_copy(Ops.begin(), Ops.end(), O);
  2709. S = new (SCEVAllocator)
  2710. SCEVAddExpr(ID.Intern(SCEVAllocator), O, Ops.size());
  2711. UniqueSCEVs.InsertNode(S, IP);
  2712. registerUser(S, Ops);
  2713. }
  2714. S->setNoWrapFlags(Flags);
  2715. return S;
  2716. }
  2717. const SCEV *
  2718. ScalarEvolution::getOrCreateAddRecExpr(ArrayRef<const SCEV *> Ops,
  2719. const Loop *L, SCEV::NoWrapFlags Flags) {
  2720. FoldingSetNodeID ID;
  2721. ID.AddInteger(scAddRecExpr);
  2722. for (const SCEV *Op : Ops)
  2723. ID.AddPointer(Op);
  2724. ID.AddPointer(L);
  2725. void *IP = nullptr;
  2726. SCEVAddRecExpr *S =
  2727. static_cast<SCEVAddRecExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
  2728. if (!S) {
  2729. const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
  2730. std::uninitialized_copy(Ops.begin(), Ops.end(), O);
  2731. S = new (SCEVAllocator)
  2732. SCEVAddRecExpr(ID.Intern(SCEVAllocator), O, Ops.size(), L);
  2733. UniqueSCEVs.InsertNode(S, IP);
  2734. LoopUsers[L].push_back(S);
  2735. registerUser(S, Ops);
  2736. }
  2737. setNoWrapFlags(S, Flags);
  2738. return S;
  2739. }
  2740. const SCEV *
  2741. ScalarEvolution::getOrCreateMulExpr(ArrayRef<const SCEV *> Ops,
  2742. SCEV::NoWrapFlags Flags) {
  2743. FoldingSetNodeID ID;
  2744. ID.AddInteger(scMulExpr);
  2745. for (const SCEV *Op : Ops)
  2746. ID.AddPointer(Op);
  2747. void *IP = nullptr;
  2748. SCEVMulExpr *S =
  2749. static_cast<SCEVMulExpr *>(UniqueSCEVs.FindNodeOrInsertPos(ID, IP));
  2750. if (!S) {
  2751. const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
  2752. std::uninitialized_copy(Ops.begin(), Ops.end(), O);
  2753. S = new (SCEVAllocator) SCEVMulExpr(ID.Intern(SCEVAllocator),
  2754. O, Ops.size());
  2755. UniqueSCEVs.InsertNode(S, IP);
  2756. registerUser(S, Ops);
  2757. }
  2758. S->setNoWrapFlags(Flags);
  2759. return S;
  2760. }
  2761. static uint64_t umul_ov(uint64_t i, uint64_t j, bool &Overflow) {
  2762. uint64_t k = i*j;
  2763. if (j > 1 && k / j != i) Overflow = true;
  2764. return k;
  2765. }
  2766. /// Compute the result of "n choose k", the binomial coefficient. If an
  2767. /// intermediate computation overflows, Overflow will be set and the return will
  2768. /// be garbage. Overflow is not cleared on absence of overflow.
  2769. static uint64_t Choose(uint64_t n, uint64_t k, bool &Overflow) {
  2770. // We use the multiplicative formula:
  2771. // n(n-1)(n-2)...(n-(k-1)) / k(k-1)(k-2)...1 .
  2772. // At each iteration, we take the n-th term of the numeral and divide by the
  2773. // (k-n)th term of the denominator. This division will always produce an
  2774. // integral result, and helps reduce the chance of overflow in the
  2775. // intermediate computations. However, we can still overflow even when the
  2776. // final result would fit.
  2777. if (n == 0 || n == k) return 1;
  2778. if (k > n) return 0;
  2779. if (k > n/2)
  2780. k = n-k;
  2781. uint64_t r = 1;
  2782. for (uint64_t i = 1; i <= k; ++i) {
  2783. r = umul_ov(r, n-(i-1), Overflow);
  2784. r /= i;
  2785. }
  2786. return r;
  2787. }
  2788. /// Determine if any of the operands in this SCEV are a constant or if
  2789. /// any of the add or multiply expressions in this SCEV contain a constant.
  2790. static bool containsConstantInAddMulChain(const SCEV *StartExpr) {
  2791. struct FindConstantInAddMulChain {
  2792. bool FoundConstant = false;
  2793. bool follow(const SCEV *S) {
  2794. FoundConstant |= isa<SCEVConstant>(S);
  2795. return isa<SCEVAddExpr>(S) || isa<SCEVMulExpr>(S);
  2796. }
  2797. bool isDone() const {
  2798. return FoundConstant;
  2799. }
  2800. };
  2801. FindConstantInAddMulChain F;
  2802. SCEVTraversal<FindConstantInAddMulChain> ST(F);
  2803. ST.visitAll(StartExpr);
  2804. return F.FoundConstant;
  2805. }
  2806. /// Get a canonical multiply expression, or something simpler if possible.
  2807. const SCEV *ScalarEvolution::getMulExpr(SmallVectorImpl<const SCEV *> &Ops,
  2808. SCEV::NoWrapFlags OrigFlags,
  2809. unsigned Depth) {
  2810. assert(OrigFlags == maskFlags(OrigFlags, SCEV::FlagNUW | SCEV::FlagNSW) &&
  2811. "only nuw or nsw allowed");
  2812. assert(!Ops.empty() && "Cannot get empty mul!");
  2813. if (Ops.size() == 1) return Ops[0];
  2814. #ifndef NDEBUG
  2815. Type *ETy = Ops[0]->getType();
  2816. assert(!ETy->isPointerTy());
  2817. for (unsigned i = 1, e = Ops.size(); i != e; ++i)
  2818. assert(Ops[i]->getType() == ETy &&
  2819. "SCEVMulExpr operand types don't match!");
  2820. #endif
  2821. // Sort by complexity, this groups all similar expression types together.
  2822. GroupByComplexity(Ops, &LI, DT);
  2823. // If there are any constants, fold them together.
  2824. unsigned Idx = 0;
  2825. if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
  2826. ++Idx;
  2827. assert(Idx < Ops.size());
  2828. while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
  2829. // We found two constants, fold them together!
  2830. Ops[0] = getConstant(LHSC->getAPInt() * RHSC->getAPInt());
  2831. if (Ops.size() == 2) return Ops[0];
  2832. Ops.erase(Ops.begin()+1); // Erase the folded element
  2833. LHSC = cast<SCEVConstant>(Ops[0]);
  2834. }
  2835. // If we have a multiply of zero, it will always be zero.
  2836. if (LHSC->getValue()->isZero())
  2837. return LHSC;
  2838. // If we are left with a constant one being multiplied, strip it off.
  2839. if (LHSC->getValue()->isOne()) {
  2840. Ops.erase(Ops.begin());
  2841. --Idx;
  2842. }
  2843. if (Ops.size() == 1)
  2844. return Ops[0];
  2845. }
  2846. // Delay expensive flag strengthening until necessary.
  2847. auto ComputeFlags = [this, OrigFlags](const ArrayRef<const SCEV *> Ops) {
  2848. return StrengthenNoWrapFlags(this, scMulExpr, Ops, OrigFlags);
  2849. };
  2850. // Limit recursion calls depth.
  2851. if (Depth > MaxArithDepth || hasHugeExpression(Ops))
  2852. return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
  2853. if (SCEV *S = findExistingSCEVInCache(scMulExpr, Ops)) {
  2854. // Don't strengthen flags if we have no new information.
  2855. SCEVMulExpr *Mul = static_cast<SCEVMulExpr *>(S);
  2856. if (Mul->getNoWrapFlags(OrigFlags) != OrigFlags)
  2857. Mul->setNoWrapFlags(ComputeFlags(Ops));
  2858. return S;
  2859. }
  2860. if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
  2861. if (Ops.size() == 2) {
  2862. // C1*(C2+V) -> C1*C2 + C1*V
  2863. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
  2864. // If any of Add's ops are Adds or Muls with a constant, apply this
  2865. // transformation as well.
  2866. //
  2867. // TODO: There are some cases where this transformation is not
  2868. // profitable; for example, Add = (C0 + X) * Y + Z. Maybe the scope of
  2869. // this transformation should be narrowed down.
  2870. if (Add->getNumOperands() == 2 && containsConstantInAddMulChain(Add)) {
  2871. const SCEV *LHS = getMulExpr(LHSC, Add->getOperand(0),
  2872. SCEV::FlagAnyWrap, Depth + 1);
  2873. const SCEV *RHS = getMulExpr(LHSC, Add->getOperand(1),
  2874. SCEV::FlagAnyWrap, Depth + 1);
  2875. return getAddExpr(LHS, RHS, SCEV::FlagAnyWrap, Depth + 1);
  2876. }
  2877. if (Ops[0]->isAllOnesValue()) {
  2878. // If we have a mul by -1 of an add, try distributing the -1 among the
  2879. // add operands.
  2880. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1])) {
  2881. SmallVector<const SCEV *, 4> NewOps;
  2882. bool AnyFolded = false;
  2883. for (const SCEV *AddOp : Add->operands()) {
  2884. const SCEV *Mul = getMulExpr(Ops[0], AddOp, SCEV::FlagAnyWrap,
  2885. Depth + 1);
  2886. if (!isa<SCEVMulExpr>(Mul)) AnyFolded = true;
  2887. NewOps.push_back(Mul);
  2888. }
  2889. if (AnyFolded)
  2890. return getAddExpr(NewOps, SCEV::FlagAnyWrap, Depth + 1);
  2891. } else if (const auto *AddRec = dyn_cast<SCEVAddRecExpr>(Ops[1])) {
  2892. // Negation preserves a recurrence's no self-wrap property.
  2893. SmallVector<const SCEV *, 4> Operands;
  2894. for (const SCEV *AddRecOp : AddRec->operands())
  2895. Operands.push_back(getMulExpr(Ops[0], AddRecOp, SCEV::FlagAnyWrap,
  2896. Depth + 1));
  2897. return getAddRecExpr(Operands, AddRec->getLoop(),
  2898. AddRec->getNoWrapFlags(SCEV::FlagNW));
  2899. }
  2900. }
  2901. }
  2902. }
  2903. // Skip over the add expression until we get to a multiply.
  2904. while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
  2905. ++Idx;
  2906. // If there are mul operands inline them all into this expression.
  2907. if (Idx < Ops.size()) {
  2908. bool DeletedMul = false;
  2909. while (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
  2910. if (Ops.size() > MulOpsInlineThreshold)
  2911. break;
  2912. // If we have an mul, expand the mul operands onto the end of the
  2913. // operands list.
  2914. Ops.erase(Ops.begin()+Idx);
  2915. append_range(Ops, Mul->operands());
  2916. DeletedMul = true;
  2917. }
  2918. // If we deleted at least one mul, we added operands to the end of the
  2919. // list, and they are not necessarily sorted. Recurse to resort and
  2920. // resimplify any operands we just acquired.
  2921. if (DeletedMul)
  2922. return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  2923. }
  2924. // If there are any add recurrences in the operands list, see if any other
  2925. // added values are loop invariant. If so, we can fold them into the
  2926. // recurrence.
  2927. while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
  2928. ++Idx;
  2929. // Scan over all recurrences, trying to fold loop invariants into them.
  2930. for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
  2931. // Scan all of the other operands to this mul and add them to the vector
  2932. // if they are loop invariant w.r.t. the recurrence.
  2933. SmallVector<const SCEV *, 8> LIOps;
  2934. const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
  2935. const Loop *AddRecLoop = AddRec->getLoop();
  2936. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  2937. if (isAvailableAtLoopEntry(Ops[i], AddRecLoop)) {
  2938. LIOps.push_back(Ops[i]);
  2939. Ops.erase(Ops.begin()+i);
  2940. --i; --e;
  2941. }
  2942. // If we found some loop invariants, fold them into the recurrence.
  2943. if (!LIOps.empty()) {
  2944. // NLI * LI * {Start,+,Step} --> NLI * {LI*Start,+,LI*Step}
  2945. SmallVector<const SCEV *, 4> NewOps;
  2946. NewOps.reserve(AddRec->getNumOperands());
  2947. const SCEV *Scale = getMulExpr(LIOps, SCEV::FlagAnyWrap, Depth + 1);
  2948. for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
  2949. NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i),
  2950. SCEV::FlagAnyWrap, Depth + 1));
  2951. // Build the new addrec. Propagate the NUW and NSW flags if both the
  2952. // outer mul and the inner addrec are guaranteed to have no overflow.
  2953. //
  2954. // No self-wrap cannot be guaranteed after changing the step size, but
  2955. // will be inferred if either NUW or NSW is true.
  2956. SCEV::NoWrapFlags Flags = ComputeFlags({Scale, AddRec});
  2957. const SCEV *NewRec = getAddRecExpr(
  2958. NewOps, AddRecLoop, AddRec->getNoWrapFlags(Flags));
  2959. // If all of the other operands were loop invariant, we are done.
  2960. if (Ops.size() == 1) return NewRec;
  2961. // Otherwise, multiply the folded AddRec by the non-invariant parts.
  2962. for (unsigned i = 0;; ++i)
  2963. if (Ops[i] == AddRec) {
  2964. Ops[i] = NewRec;
  2965. break;
  2966. }
  2967. return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  2968. }
  2969. // Okay, if there weren't any loop invariants to be folded, check to see
  2970. // if there are multiple AddRec's with the same loop induction variable
  2971. // being multiplied together. If so, we can fold them.
  2972. // {A1,+,A2,+,...,+,An}<L> * {B1,+,B2,+,...,+,Bn}<L>
  2973. // = {x=1 in [ sum y=x..2x [ sum z=max(y-x, y-n)..min(x,n) [
  2974. // choose(x, 2x)*choose(2x-y, x-z)*A_{y-z}*B_z
  2975. // ]]],+,...up to x=2n}.
  2976. // Note that the arguments to choose() are always integers with values
  2977. // known at compile time, never SCEV objects.
  2978. //
  2979. // The implementation avoids pointless extra computations when the two
  2980. // addrec's are of different length (mathematically, it's equivalent to
  2981. // an infinite stream of zeros on the right).
  2982. bool OpsModified = false;
  2983. for (unsigned OtherIdx = Idx+1;
  2984. OtherIdx != Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);
  2985. ++OtherIdx) {
  2986. const SCEVAddRecExpr *OtherAddRec =
  2987. dyn_cast<SCEVAddRecExpr>(Ops[OtherIdx]);
  2988. if (!OtherAddRec || OtherAddRec->getLoop() != AddRecLoop)
  2989. continue;
  2990. // Limit max number of arguments to avoid creation of unreasonably big
  2991. // SCEVAddRecs with very complex operands.
  2992. if (AddRec->getNumOperands() + OtherAddRec->getNumOperands() - 1 >
  2993. MaxAddRecSize || hasHugeExpression({AddRec, OtherAddRec}))
  2994. continue;
  2995. bool Overflow = false;
  2996. Type *Ty = AddRec->getType();
  2997. bool LargerThan64Bits = getTypeSizeInBits(Ty) > 64;
  2998. SmallVector<const SCEV*, 7> AddRecOps;
  2999. for (int x = 0, xe = AddRec->getNumOperands() +
  3000. OtherAddRec->getNumOperands() - 1; x != xe && !Overflow; ++x) {
  3001. SmallVector <const SCEV *, 7> SumOps;
  3002. for (int y = x, ye = 2*x+1; y != ye && !Overflow; ++y) {
  3003. uint64_t Coeff1 = Choose(x, 2*x - y, Overflow);
  3004. for (int z = std::max(y-x, y-(int)AddRec->getNumOperands()+1),
  3005. ze = std::min(x+1, (int)OtherAddRec->getNumOperands());
  3006. z < ze && !Overflow; ++z) {
  3007. uint64_t Coeff2 = Choose(2*x - y, x-z, Overflow);
  3008. uint64_t Coeff;
  3009. if (LargerThan64Bits)
  3010. Coeff = umul_ov(Coeff1, Coeff2, Overflow);
  3011. else
  3012. Coeff = Coeff1*Coeff2;
  3013. const SCEV *CoeffTerm = getConstant(Ty, Coeff);
  3014. const SCEV *Term1 = AddRec->getOperand(y-z);
  3015. const SCEV *Term2 = OtherAddRec->getOperand(z);
  3016. SumOps.push_back(getMulExpr(CoeffTerm, Term1, Term2,
  3017. SCEV::FlagAnyWrap, Depth + 1));
  3018. }
  3019. }
  3020. if (SumOps.empty())
  3021. SumOps.push_back(getZero(Ty));
  3022. AddRecOps.push_back(getAddExpr(SumOps, SCEV::FlagAnyWrap, Depth + 1));
  3023. }
  3024. if (!Overflow) {
  3025. const SCEV *NewAddRec = getAddRecExpr(AddRecOps, AddRecLoop,
  3026. SCEV::FlagAnyWrap);
  3027. if (Ops.size() == 2) return NewAddRec;
  3028. Ops[Idx] = NewAddRec;
  3029. Ops.erase(Ops.begin() + OtherIdx); --OtherIdx;
  3030. OpsModified = true;
  3031. AddRec = dyn_cast<SCEVAddRecExpr>(NewAddRec);
  3032. if (!AddRec)
  3033. break;
  3034. }
  3035. }
  3036. if (OpsModified)
  3037. return getMulExpr(Ops, SCEV::FlagAnyWrap, Depth + 1);
  3038. // Otherwise couldn't fold anything into this recurrence. Move onto the
  3039. // next one.
  3040. }
  3041. // Okay, it looks like we really DO need an mul expr. Check to see if we
  3042. // already have one, otherwise create a new one.
  3043. return getOrCreateMulExpr(Ops, ComputeFlags(Ops));
  3044. }
  3045. /// Represents an unsigned remainder expression based on unsigned division.
  3046. const SCEV *ScalarEvolution::getURemExpr(const SCEV *LHS,
  3047. const SCEV *RHS) {
  3048. assert(getEffectiveSCEVType(LHS->getType()) ==
  3049. getEffectiveSCEVType(RHS->getType()) &&
  3050. "SCEVURemExpr operand types don't match!");
  3051. // Short-circuit easy cases
  3052. if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
  3053. // If constant is one, the result is trivial
  3054. if (RHSC->getValue()->isOne())
  3055. return getZero(LHS->getType()); // X urem 1 --> 0
  3056. // If constant is a power of two, fold into a zext(trunc(LHS)).
  3057. if (RHSC->getAPInt().isPowerOf2()) {
  3058. Type *FullTy = LHS->getType();
  3059. Type *TruncTy =
  3060. IntegerType::get(getContext(), RHSC->getAPInt().logBase2());
  3061. return getZeroExtendExpr(getTruncateExpr(LHS, TruncTy), FullTy);
  3062. }
  3063. }
  3064. // Fallback to %a == %x urem %y == %x -<nuw> ((%x udiv %y) *<nuw> %y)
  3065. const SCEV *UDiv = getUDivExpr(LHS, RHS);
  3066. const SCEV *Mult = getMulExpr(UDiv, RHS, SCEV::FlagNUW);
  3067. return getMinusSCEV(LHS, Mult, SCEV::FlagNUW);
  3068. }
  3069. /// Get a canonical unsigned division expression, or something simpler if
  3070. /// possible.
  3071. const SCEV *ScalarEvolution::getUDivExpr(const SCEV *LHS,
  3072. const SCEV *RHS) {
  3073. assert(!LHS->getType()->isPointerTy() &&
  3074. "SCEVUDivExpr operand can't be pointer!");
  3075. assert(LHS->getType() == RHS->getType() &&
  3076. "SCEVUDivExpr operand types don't match!");
  3077. FoldingSetNodeID ID;
  3078. ID.AddInteger(scUDivExpr);
  3079. ID.AddPointer(LHS);
  3080. ID.AddPointer(RHS);
  3081. void *IP = nullptr;
  3082. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
  3083. return S;
  3084. // 0 udiv Y == 0
  3085. if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
  3086. if (LHSC->getValue()->isZero())
  3087. return LHS;
  3088. if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
  3089. if (RHSC->getValue()->isOne())
  3090. return LHS; // X udiv 1 --> x
  3091. // If the denominator is zero, the result of the udiv is undefined. Don't
  3092. // try to analyze it, because the resolution chosen here may differ from
  3093. // the resolution chosen in other parts of the compiler.
  3094. if (!RHSC->getValue()->isZero()) {
  3095. // Determine if the division can be folded into the operands of
  3096. // its operands.
  3097. // TODO: Generalize this to non-constants by using known-bits information.
  3098. Type *Ty = LHS->getType();
  3099. unsigned LZ = RHSC->getAPInt().countLeadingZeros();
  3100. unsigned MaxShiftAmt = getTypeSizeInBits(Ty) - LZ - 1;
  3101. // For non-power-of-two values, effectively round the value up to the
  3102. // nearest power of two.
  3103. if (!RHSC->getAPInt().isPowerOf2())
  3104. ++MaxShiftAmt;
  3105. IntegerType *ExtTy =
  3106. IntegerType::get(getContext(), getTypeSizeInBits(Ty) + MaxShiftAmt);
  3107. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS))
  3108. if (const SCEVConstant *Step =
  3109. dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this))) {
  3110. // {X,+,N}/C --> {X/C,+,N/C} if safe and N/C can be folded.
  3111. const APInt &StepInt = Step->getAPInt();
  3112. const APInt &DivInt = RHSC->getAPInt();
  3113. if (!StepInt.urem(DivInt) &&
  3114. getZeroExtendExpr(AR, ExtTy) ==
  3115. getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
  3116. getZeroExtendExpr(Step, ExtTy),
  3117. AR->getLoop(), SCEV::FlagAnyWrap)) {
  3118. SmallVector<const SCEV *, 4> Operands;
  3119. for (const SCEV *Op : AR->operands())
  3120. Operands.push_back(getUDivExpr(Op, RHS));
  3121. return getAddRecExpr(Operands, AR->getLoop(), SCEV::FlagNW);
  3122. }
  3123. /// Get a canonical UDivExpr for a recurrence.
  3124. /// {X,+,N}/C => {Y,+,N}/C where Y=X-(X%N). Safe when C%N=0.
  3125. // We can currently only fold X%N if X is constant.
  3126. const SCEVConstant *StartC = dyn_cast<SCEVConstant>(AR->getStart());
  3127. if (StartC && !DivInt.urem(StepInt) &&
  3128. getZeroExtendExpr(AR, ExtTy) ==
  3129. getAddRecExpr(getZeroExtendExpr(AR->getStart(), ExtTy),
  3130. getZeroExtendExpr(Step, ExtTy),
  3131. AR->getLoop(), SCEV::FlagAnyWrap)) {
  3132. const APInt &StartInt = StartC->getAPInt();
  3133. const APInt &StartRem = StartInt.urem(StepInt);
  3134. if (StartRem != 0) {
  3135. const SCEV *NewLHS =
  3136. getAddRecExpr(getConstant(StartInt - StartRem), Step,
  3137. AR->getLoop(), SCEV::FlagNW);
  3138. if (LHS != NewLHS) {
  3139. LHS = NewLHS;
  3140. // Reset the ID to include the new LHS, and check if it is
  3141. // already cached.
  3142. ID.clear();
  3143. ID.AddInteger(scUDivExpr);
  3144. ID.AddPointer(LHS);
  3145. ID.AddPointer(RHS);
  3146. IP = nullptr;
  3147. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP))
  3148. return S;
  3149. }
  3150. }
  3151. }
  3152. }
  3153. // (A*B)/C --> A*(B/C) if safe and B/C can be folded.
  3154. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(LHS)) {
  3155. SmallVector<const SCEV *, 4> Operands;
  3156. for (const SCEV *Op : M->operands())
  3157. Operands.push_back(getZeroExtendExpr(Op, ExtTy));
  3158. if (getZeroExtendExpr(M, ExtTy) == getMulExpr(Operands))
  3159. // Find an operand that's safely divisible.
  3160. for (unsigned i = 0, e = M->getNumOperands(); i != e; ++i) {
  3161. const SCEV *Op = M->getOperand(i);
  3162. const SCEV *Div = getUDivExpr(Op, RHSC);
  3163. if (!isa<SCEVUDivExpr>(Div) && getMulExpr(Div, RHSC) == Op) {
  3164. Operands = SmallVector<const SCEV *, 4>(M->operands());
  3165. Operands[i] = Div;
  3166. return getMulExpr(Operands);
  3167. }
  3168. }
  3169. }
  3170. // (A/B)/C --> A/(B*C) if safe and B*C can be folded.
  3171. if (const SCEVUDivExpr *OtherDiv = dyn_cast<SCEVUDivExpr>(LHS)) {
  3172. if (auto *DivisorConstant =
  3173. dyn_cast<SCEVConstant>(OtherDiv->getRHS())) {
  3174. bool Overflow = false;
  3175. APInt NewRHS =
  3176. DivisorConstant->getAPInt().umul_ov(RHSC->getAPInt(), Overflow);
  3177. if (Overflow) {
  3178. return getConstant(RHSC->getType(), 0, false);
  3179. }
  3180. return getUDivExpr(OtherDiv->getLHS(), getConstant(NewRHS));
  3181. }
  3182. }
  3183. // (A+B)/C --> (A/C + B/C) if safe and A/C and B/C can be folded.
  3184. if (const SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(LHS)) {
  3185. SmallVector<const SCEV *, 4> Operands;
  3186. for (const SCEV *Op : A->operands())
  3187. Operands.push_back(getZeroExtendExpr(Op, ExtTy));
  3188. if (getZeroExtendExpr(A, ExtTy) == getAddExpr(Operands)) {
  3189. Operands.clear();
  3190. for (unsigned i = 0, e = A->getNumOperands(); i != e; ++i) {
  3191. const SCEV *Op = getUDivExpr(A->getOperand(i), RHS);
  3192. if (isa<SCEVUDivExpr>(Op) ||
  3193. getMulExpr(Op, RHS) != A->getOperand(i))
  3194. break;
  3195. Operands.push_back(Op);
  3196. }
  3197. if (Operands.size() == A->getNumOperands())
  3198. return getAddExpr(Operands);
  3199. }
  3200. }
  3201. // Fold if both operands are constant.
  3202. if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS))
  3203. return getConstant(LHSC->getAPInt().udiv(RHSC->getAPInt()));
  3204. }
  3205. }
  3206. // The Insertion Point (IP) might be invalid by now (due to UniqueSCEVs
  3207. // changes). Make sure we get a new one.
  3208. IP = nullptr;
  3209. if (const SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) return S;
  3210. SCEV *S = new (SCEVAllocator) SCEVUDivExpr(ID.Intern(SCEVAllocator),
  3211. LHS, RHS);
  3212. UniqueSCEVs.InsertNode(S, IP);
  3213. registerUser(S, {LHS, RHS});
  3214. return S;
  3215. }
  3216. APInt gcd(const SCEVConstant *C1, const SCEVConstant *C2) {
  3217. APInt A = C1->getAPInt().abs();
  3218. APInt B = C2->getAPInt().abs();
  3219. uint32_t ABW = A.getBitWidth();
  3220. uint32_t BBW = B.getBitWidth();
  3221. if (ABW > BBW)
  3222. B = B.zext(ABW);
  3223. else if (ABW < BBW)
  3224. A = A.zext(BBW);
  3225. return APIntOps::GreatestCommonDivisor(std::move(A), std::move(B));
  3226. }
  3227. /// Get a canonical unsigned division expression, or something simpler if
  3228. /// possible. There is no representation for an exact udiv in SCEV IR, but we
  3229. /// can attempt to remove factors from the LHS and RHS. We can't do this when
  3230. /// it's not exact because the udiv may be clearing bits.
  3231. const SCEV *ScalarEvolution::getUDivExactExpr(const SCEV *LHS,
  3232. const SCEV *RHS) {
  3233. // TODO: we could try to find factors in all sorts of things, but for now we
  3234. // just deal with u/exact (multiply, constant). See SCEVDivision towards the
  3235. // end of this file for inspiration.
  3236. const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS);
  3237. if (!Mul || !Mul->hasNoUnsignedWrap())
  3238. return getUDivExpr(LHS, RHS);
  3239. if (const SCEVConstant *RHSCst = dyn_cast<SCEVConstant>(RHS)) {
  3240. // If the mulexpr multiplies by a constant, then that constant must be the
  3241. // first element of the mulexpr.
  3242. if (const auto *LHSCst = dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
  3243. if (LHSCst == RHSCst) {
  3244. SmallVector<const SCEV *, 2> Operands(drop_begin(Mul->operands()));
  3245. return getMulExpr(Operands);
  3246. }
  3247. // We can't just assume that LHSCst divides RHSCst cleanly, it could be
  3248. // that there's a factor provided by one of the other terms. We need to
  3249. // check.
  3250. APInt Factor = gcd(LHSCst, RHSCst);
  3251. if (!Factor.isIntN(1)) {
  3252. LHSCst =
  3253. cast<SCEVConstant>(getConstant(LHSCst->getAPInt().udiv(Factor)));
  3254. RHSCst =
  3255. cast<SCEVConstant>(getConstant(RHSCst->getAPInt().udiv(Factor)));
  3256. SmallVector<const SCEV *, 2> Operands;
  3257. Operands.push_back(LHSCst);
  3258. append_range(Operands, Mul->operands().drop_front());
  3259. LHS = getMulExpr(Operands);
  3260. RHS = RHSCst;
  3261. Mul = dyn_cast<SCEVMulExpr>(LHS);
  3262. if (!Mul)
  3263. return getUDivExactExpr(LHS, RHS);
  3264. }
  3265. }
  3266. }
  3267. for (int i = 0, e = Mul->getNumOperands(); i != e; ++i) {
  3268. if (Mul->getOperand(i) == RHS) {
  3269. SmallVector<const SCEV *, 2> Operands;
  3270. append_range(Operands, Mul->operands().take_front(i));
  3271. append_range(Operands, Mul->operands().drop_front(i + 1));
  3272. return getMulExpr(Operands);
  3273. }
  3274. }
  3275. return getUDivExpr(LHS, RHS);
  3276. }
  3277. /// Get an add recurrence expression for the specified loop. Simplify the
  3278. /// expression as much as possible.
  3279. const SCEV *ScalarEvolution::getAddRecExpr(const SCEV *Start, const SCEV *Step,
  3280. const Loop *L,
  3281. SCEV::NoWrapFlags Flags) {
  3282. SmallVector<const SCEV *, 4> Operands;
  3283. Operands.push_back(Start);
  3284. if (const SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
  3285. if (StepChrec->getLoop() == L) {
  3286. append_range(Operands, StepChrec->operands());
  3287. return getAddRecExpr(Operands, L, maskFlags(Flags, SCEV::FlagNW));
  3288. }
  3289. Operands.push_back(Step);
  3290. return getAddRecExpr(Operands, L, Flags);
  3291. }
  3292. /// Get an add recurrence expression for the specified loop. Simplify the
  3293. /// expression as much as possible.
  3294. const SCEV *
  3295. ScalarEvolution::getAddRecExpr(SmallVectorImpl<const SCEV *> &Operands,
  3296. const Loop *L, SCEV::NoWrapFlags Flags) {
  3297. if (Operands.size() == 1) return Operands[0];
  3298. #ifndef NDEBUG
  3299. Type *ETy = getEffectiveSCEVType(Operands[0]->getType());
  3300. for (unsigned i = 1, e = Operands.size(); i != e; ++i) {
  3301. assert(getEffectiveSCEVType(Operands[i]->getType()) == ETy &&
  3302. "SCEVAddRecExpr operand types don't match!");
  3303. assert(!Operands[i]->getType()->isPointerTy() && "Step must be integer");
  3304. }
  3305. for (unsigned i = 0, e = Operands.size(); i != e; ++i)
  3306. assert(isLoopInvariant(Operands[i], L) &&
  3307. "SCEVAddRecExpr operand is not loop-invariant!");
  3308. #endif
  3309. if (Operands.back()->isZero()) {
  3310. Operands.pop_back();
  3311. return getAddRecExpr(Operands, L, SCEV::FlagAnyWrap); // {X,+,0} --> X
  3312. }
  3313. // It's tempting to want to call getConstantMaxBackedgeTakenCount count here and
  3314. // use that information to infer NUW and NSW flags. However, computing a
  3315. // BE count requires calling getAddRecExpr, so we may not yet have a
  3316. // meaningful BE count at this point (and if we don't, we'd be stuck
  3317. // with a SCEVCouldNotCompute as the cached BE count).
  3318. Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
  3319. // Canonicalize nested AddRecs in by nesting them in order of loop depth.
  3320. if (const SCEVAddRecExpr *NestedAR = dyn_cast<SCEVAddRecExpr>(Operands[0])) {
  3321. const Loop *NestedLoop = NestedAR->getLoop();
  3322. if (L->contains(NestedLoop)
  3323. ? (L->getLoopDepth() < NestedLoop->getLoopDepth())
  3324. : (!NestedLoop->contains(L) &&
  3325. DT.dominates(L->getHeader(), NestedLoop->getHeader()))) {
  3326. SmallVector<const SCEV *, 4> NestedOperands(NestedAR->operands());
  3327. Operands[0] = NestedAR->getStart();
  3328. // AddRecs require their operands be loop-invariant with respect to their
  3329. // loops. Don't perform this transformation if it would break this
  3330. // requirement.
  3331. bool AllInvariant = all_of(
  3332. Operands, [&](const SCEV *Op) { return isLoopInvariant(Op, L); });
  3333. if (AllInvariant) {
  3334. // Create a recurrence for the outer loop with the same step size.
  3335. //
  3336. // The outer recurrence keeps its NW flag but only keeps NUW/NSW if the
  3337. // inner recurrence has the same property.
  3338. SCEV::NoWrapFlags OuterFlags =
  3339. maskFlags(Flags, SCEV::FlagNW | NestedAR->getNoWrapFlags());
  3340. NestedOperands[0] = getAddRecExpr(Operands, L, OuterFlags);
  3341. AllInvariant = all_of(NestedOperands, [&](const SCEV *Op) {
  3342. return isLoopInvariant(Op, NestedLoop);
  3343. });
  3344. if (AllInvariant) {
  3345. // Ok, both add recurrences are valid after the transformation.
  3346. //
  3347. // The inner recurrence keeps its NW flag but only keeps NUW/NSW if
  3348. // the outer recurrence has the same property.
  3349. SCEV::NoWrapFlags InnerFlags =
  3350. maskFlags(NestedAR->getNoWrapFlags(), SCEV::FlagNW | Flags);
  3351. return getAddRecExpr(NestedOperands, NestedLoop, InnerFlags);
  3352. }
  3353. }
  3354. // Reset Operands to its original state.
  3355. Operands[0] = NestedAR;
  3356. }
  3357. }
  3358. // Okay, it looks like we really DO need an addrec expr. Check to see if we
  3359. // already have one, otherwise create a new one.
  3360. return getOrCreateAddRecExpr(Operands, L, Flags);
  3361. }
  3362. const SCEV *
  3363. ScalarEvolution::getGEPExpr(GEPOperator *GEP,
  3364. const SmallVectorImpl<const SCEV *> &IndexExprs) {
  3365. const SCEV *BaseExpr = getSCEV(GEP->getPointerOperand());
  3366. // getSCEV(Base)->getType() has the same address space as Base->getType()
  3367. // because SCEV::getType() preserves the address space.
  3368. Type *IntIdxTy = getEffectiveSCEVType(BaseExpr->getType());
  3369. const bool AssumeInBoundsFlags = [&]() {
  3370. if (!GEP->isInBounds())
  3371. return false;
  3372. // We'd like to propagate flags from the IR to the corresponding SCEV nodes,
  3373. // but to do that, we have to ensure that said flag is valid in the entire
  3374. // defined scope of the SCEV.
  3375. auto *GEPI = dyn_cast<Instruction>(GEP);
  3376. // TODO: non-instructions have global scope. We might be able to prove
  3377. // some global scope cases
  3378. return GEPI && isSCEVExprNeverPoison(GEPI);
  3379. }();
  3380. SCEV::NoWrapFlags OffsetWrap =
  3381. AssumeInBoundsFlags ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
  3382. Type *CurTy = GEP->getType();
  3383. bool FirstIter = true;
  3384. SmallVector<const SCEV *, 4> Offsets;
  3385. for (const SCEV *IndexExpr : IndexExprs) {
  3386. // Compute the (potentially symbolic) offset in bytes for this index.
  3387. if (StructType *STy = dyn_cast<StructType>(CurTy)) {
  3388. // For a struct, add the member offset.
  3389. ConstantInt *Index = cast<SCEVConstant>(IndexExpr)->getValue();
  3390. unsigned FieldNo = Index->getZExtValue();
  3391. const SCEV *FieldOffset = getOffsetOfExpr(IntIdxTy, STy, FieldNo);
  3392. Offsets.push_back(FieldOffset);
  3393. // Update CurTy to the type of the field at Index.
  3394. CurTy = STy->getTypeAtIndex(Index);
  3395. } else {
  3396. // Update CurTy to its element type.
  3397. if (FirstIter) {
  3398. assert(isa<PointerType>(CurTy) &&
  3399. "The first index of a GEP indexes a pointer");
  3400. CurTy = GEP->getSourceElementType();
  3401. FirstIter = false;
  3402. } else {
  3403. CurTy = GetElementPtrInst::getTypeAtIndex(CurTy, (uint64_t)0);
  3404. }
  3405. // For an array, add the element offset, explicitly scaled.
  3406. const SCEV *ElementSize = getSizeOfExpr(IntIdxTy, CurTy);
  3407. // Getelementptr indices are signed.
  3408. IndexExpr = getTruncateOrSignExtend(IndexExpr, IntIdxTy);
  3409. // Multiply the index by the element size to compute the element offset.
  3410. const SCEV *LocalOffset = getMulExpr(IndexExpr, ElementSize, OffsetWrap);
  3411. Offsets.push_back(LocalOffset);
  3412. }
  3413. }
  3414. // Handle degenerate case of GEP without offsets.
  3415. if (Offsets.empty())
  3416. return BaseExpr;
  3417. // Add the offsets together, assuming nsw if inbounds.
  3418. const SCEV *Offset = getAddExpr(Offsets, OffsetWrap);
  3419. // Add the base address and the offset. We cannot use the nsw flag, as the
  3420. // base address is unsigned. However, if we know that the offset is
  3421. // non-negative, we can use nuw.
  3422. SCEV::NoWrapFlags BaseWrap = AssumeInBoundsFlags && isKnownNonNegative(Offset)
  3423. ? SCEV::FlagNUW : SCEV::FlagAnyWrap;
  3424. auto *GEPExpr = getAddExpr(BaseExpr, Offset, BaseWrap);
  3425. assert(BaseExpr->getType() == GEPExpr->getType() &&
  3426. "GEP should not change type mid-flight.");
  3427. return GEPExpr;
  3428. }
  3429. SCEV *ScalarEvolution::findExistingSCEVInCache(SCEVTypes SCEVType,
  3430. ArrayRef<const SCEV *> Ops) {
  3431. FoldingSetNodeID ID;
  3432. ID.AddInteger(SCEVType);
  3433. for (const SCEV *Op : Ops)
  3434. ID.AddPointer(Op);
  3435. void *IP = nullptr;
  3436. return UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
  3437. }
  3438. const SCEV *ScalarEvolution::getAbsExpr(const SCEV *Op, bool IsNSW) {
  3439. SCEV::NoWrapFlags Flags = IsNSW ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
  3440. return getSMaxExpr(Op, getNegativeSCEV(Op, Flags));
  3441. }
  3442. const SCEV *ScalarEvolution::getMinMaxExpr(SCEVTypes Kind,
  3443. SmallVectorImpl<const SCEV *> &Ops) {
  3444. assert(SCEVMinMaxExpr::isMinMaxType(Kind) && "Not a SCEVMinMaxExpr!");
  3445. assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
  3446. if (Ops.size() == 1) return Ops[0];
  3447. #ifndef NDEBUG
  3448. Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
  3449. for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
  3450. assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
  3451. "Operand types don't match!");
  3452. assert(Ops[0]->getType()->isPointerTy() ==
  3453. Ops[i]->getType()->isPointerTy() &&
  3454. "min/max should be consistently pointerish");
  3455. }
  3456. #endif
  3457. bool IsSigned = Kind == scSMaxExpr || Kind == scSMinExpr;
  3458. bool IsMax = Kind == scSMaxExpr || Kind == scUMaxExpr;
  3459. // Sort by complexity, this groups all similar expression types together.
  3460. GroupByComplexity(Ops, &LI, DT);
  3461. // Check if we have created the same expression before.
  3462. if (const SCEV *S = findExistingSCEVInCache(Kind, Ops)) {
  3463. return S;
  3464. }
  3465. // If there are any constants, fold them together.
  3466. unsigned Idx = 0;
  3467. if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
  3468. ++Idx;
  3469. assert(Idx < Ops.size());
  3470. auto FoldOp = [&](const APInt &LHS, const APInt &RHS) {
  3471. if (Kind == scSMaxExpr)
  3472. return APIntOps::smax(LHS, RHS);
  3473. else if (Kind == scSMinExpr)
  3474. return APIntOps::smin(LHS, RHS);
  3475. else if (Kind == scUMaxExpr)
  3476. return APIntOps::umax(LHS, RHS);
  3477. else if (Kind == scUMinExpr)
  3478. return APIntOps::umin(LHS, RHS);
  3479. llvm_unreachable("Unknown SCEV min/max opcode");
  3480. };
  3481. while (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
  3482. // We found two constants, fold them together!
  3483. ConstantInt *Fold = ConstantInt::get(
  3484. getContext(), FoldOp(LHSC->getAPInt(), RHSC->getAPInt()));
  3485. Ops[0] = getConstant(Fold);
  3486. Ops.erase(Ops.begin()+1); // Erase the folded element
  3487. if (Ops.size() == 1) return Ops[0];
  3488. LHSC = cast<SCEVConstant>(Ops[0]);
  3489. }
  3490. bool IsMinV = LHSC->getValue()->isMinValue(IsSigned);
  3491. bool IsMaxV = LHSC->getValue()->isMaxValue(IsSigned);
  3492. if (IsMax ? IsMinV : IsMaxV) {
  3493. // If we are left with a constant minimum(/maximum)-int, strip it off.
  3494. Ops.erase(Ops.begin());
  3495. --Idx;
  3496. } else if (IsMax ? IsMaxV : IsMinV) {
  3497. // If we have a max(/min) with a constant maximum(/minimum)-int,
  3498. // it will always be the extremum.
  3499. return LHSC;
  3500. }
  3501. if (Ops.size() == 1) return Ops[0];
  3502. }
  3503. // Find the first operation of the same kind
  3504. while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < Kind)
  3505. ++Idx;
  3506. // Check to see if one of the operands is of the same kind. If so, expand its
  3507. // operands onto our operand list, and recurse to simplify.
  3508. if (Idx < Ops.size()) {
  3509. bool DeletedAny = false;
  3510. while (Ops[Idx]->getSCEVType() == Kind) {
  3511. const SCEVMinMaxExpr *SMME = cast<SCEVMinMaxExpr>(Ops[Idx]);
  3512. Ops.erase(Ops.begin()+Idx);
  3513. append_range(Ops, SMME->operands());
  3514. DeletedAny = true;
  3515. }
  3516. if (DeletedAny)
  3517. return getMinMaxExpr(Kind, Ops);
  3518. }
  3519. // Okay, check to see if the same value occurs in the operand list twice. If
  3520. // so, delete one. Since we sorted the list, these values are required to
  3521. // be adjacent.
  3522. llvm::CmpInst::Predicate GEPred =
  3523. IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
  3524. llvm::CmpInst::Predicate LEPred =
  3525. IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
  3526. llvm::CmpInst::Predicate FirstPred = IsMax ? GEPred : LEPred;
  3527. llvm::CmpInst::Predicate SecondPred = IsMax ? LEPred : GEPred;
  3528. for (unsigned i = 0, e = Ops.size() - 1; i != e; ++i) {
  3529. if (Ops[i] == Ops[i + 1] ||
  3530. isKnownViaNonRecursiveReasoning(FirstPred, Ops[i], Ops[i + 1])) {
  3531. // X op Y op Y --> X op Y
  3532. // X op Y --> X, if we know X, Y are ordered appropriately
  3533. Ops.erase(Ops.begin() + i + 1, Ops.begin() + i + 2);
  3534. --i;
  3535. --e;
  3536. } else if (isKnownViaNonRecursiveReasoning(SecondPred, Ops[i],
  3537. Ops[i + 1])) {
  3538. // X op Y --> Y, if we know X, Y are ordered appropriately
  3539. Ops.erase(Ops.begin() + i, Ops.begin() + i + 1);
  3540. --i;
  3541. --e;
  3542. }
  3543. }
  3544. if (Ops.size() == 1) return Ops[0];
  3545. assert(!Ops.empty() && "Reduced smax down to nothing!");
  3546. // Okay, it looks like we really DO need an expr. Check to see if we
  3547. // already have one, otherwise create a new one.
  3548. FoldingSetNodeID ID;
  3549. ID.AddInteger(Kind);
  3550. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  3551. ID.AddPointer(Ops[i]);
  3552. void *IP = nullptr;
  3553. const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
  3554. if (ExistingSCEV)
  3555. return ExistingSCEV;
  3556. const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
  3557. std::uninitialized_copy(Ops.begin(), Ops.end(), O);
  3558. SCEV *S = new (SCEVAllocator)
  3559. SCEVMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
  3560. UniqueSCEVs.InsertNode(S, IP);
  3561. registerUser(S, Ops);
  3562. return S;
  3563. }
  3564. namespace {
  3565. class SCEVSequentialMinMaxDeduplicatingVisitor final
  3566. : public SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor,
  3567. std::optional<const SCEV *>> {
  3568. using RetVal = std::optional<const SCEV *>;
  3569. using Base = SCEVVisitor<SCEVSequentialMinMaxDeduplicatingVisitor, RetVal>;
  3570. ScalarEvolution &SE;
  3571. const SCEVTypes RootKind; // Must be a sequential min/max expression.
  3572. const SCEVTypes NonSequentialRootKind; // Non-sequential variant of RootKind.
  3573. SmallPtrSet<const SCEV *, 16> SeenOps;
  3574. bool canRecurseInto(SCEVTypes Kind) const {
  3575. // We can only recurse into the SCEV expression of the same effective type
  3576. // as the type of our root SCEV expression.
  3577. return RootKind == Kind || NonSequentialRootKind == Kind;
  3578. };
  3579. RetVal visitAnyMinMaxExpr(const SCEV *S) {
  3580. assert((isa<SCEVMinMaxExpr>(S) || isa<SCEVSequentialMinMaxExpr>(S)) &&
  3581. "Only for min/max expressions.");
  3582. SCEVTypes Kind = S->getSCEVType();
  3583. if (!canRecurseInto(Kind))
  3584. return S;
  3585. auto *NAry = cast<SCEVNAryExpr>(S);
  3586. SmallVector<const SCEV *> NewOps;
  3587. bool Changed = visit(Kind, NAry->operands(), NewOps);
  3588. if (!Changed)
  3589. return S;
  3590. if (NewOps.empty())
  3591. return std::nullopt;
  3592. return isa<SCEVSequentialMinMaxExpr>(S)
  3593. ? SE.getSequentialMinMaxExpr(Kind, NewOps)
  3594. : SE.getMinMaxExpr(Kind, NewOps);
  3595. }
  3596. RetVal visit(const SCEV *S) {
  3597. // Has the whole operand been seen already?
  3598. if (!SeenOps.insert(S).second)
  3599. return std::nullopt;
  3600. return Base::visit(S);
  3601. }
  3602. public:
  3603. SCEVSequentialMinMaxDeduplicatingVisitor(ScalarEvolution &SE,
  3604. SCEVTypes RootKind)
  3605. : SE(SE), RootKind(RootKind),
  3606. NonSequentialRootKind(
  3607. SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
  3608. RootKind)) {}
  3609. bool /*Changed*/ visit(SCEVTypes Kind, ArrayRef<const SCEV *> OrigOps,
  3610. SmallVectorImpl<const SCEV *> &NewOps) {
  3611. bool Changed = false;
  3612. SmallVector<const SCEV *> Ops;
  3613. Ops.reserve(OrigOps.size());
  3614. for (const SCEV *Op : OrigOps) {
  3615. RetVal NewOp = visit(Op);
  3616. if (NewOp != Op)
  3617. Changed = true;
  3618. if (NewOp)
  3619. Ops.emplace_back(*NewOp);
  3620. }
  3621. if (Changed)
  3622. NewOps = std::move(Ops);
  3623. return Changed;
  3624. }
  3625. RetVal visitConstant(const SCEVConstant *Constant) { return Constant; }
  3626. RetVal visitPtrToIntExpr(const SCEVPtrToIntExpr *Expr) { return Expr; }
  3627. RetVal visitTruncateExpr(const SCEVTruncateExpr *Expr) { return Expr; }
  3628. RetVal visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) { return Expr; }
  3629. RetVal visitSignExtendExpr(const SCEVSignExtendExpr *Expr) { return Expr; }
  3630. RetVal visitAddExpr(const SCEVAddExpr *Expr) { return Expr; }
  3631. RetVal visitMulExpr(const SCEVMulExpr *Expr) { return Expr; }
  3632. RetVal visitUDivExpr(const SCEVUDivExpr *Expr) { return Expr; }
  3633. RetVal visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
  3634. RetVal visitSMaxExpr(const SCEVSMaxExpr *Expr) {
  3635. return visitAnyMinMaxExpr(Expr);
  3636. }
  3637. RetVal visitUMaxExpr(const SCEVUMaxExpr *Expr) {
  3638. return visitAnyMinMaxExpr(Expr);
  3639. }
  3640. RetVal visitSMinExpr(const SCEVSMinExpr *Expr) {
  3641. return visitAnyMinMaxExpr(Expr);
  3642. }
  3643. RetVal visitUMinExpr(const SCEVUMinExpr *Expr) {
  3644. return visitAnyMinMaxExpr(Expr);
  3645. }
  3646. RetVal visitSequentialUMinExpr(const SCEVSequentialUMinExpr *Expr) {
  3647. return visitAnyMinMaxExpr(Expr);
  3648. }
  3649. RetVal visitUnknown(const SCEVUnknown *Expr) { return Expr; }
  3650. RetVal visitCouldNotCompute(const SCEVCouldNotCompute *Expr) { return Expr; }
  3651. };
  3652. } // namespace
  3653. static bool scevUnconditionallyPropagatesPoisonFromOperands(SCEVTypes Kind) {
  3654. switch (Kind) {
  3655. case scConstant:
  3656. case scTruncate:
  3657. case scZeroExtend:
  3658. case scSignExtend:
  3659. case scPtrToInt:
  3660. case scAddExpr:
  3661. case scMulExpr:
  3662. case scUDivExpr:
  3663. case scAddRecExpr:
  3664. case scUMaxExpr:
  3665. case scSMaxExpr:
  3666. case scUMinExpr:
  3667. case scSMinExpr:
  3668. case scUnknown:
  3669. // If any operand is poison, the whole expression is poison.
  3670. return true;
  3671. case scSequentialUMinExpr:
  3672. // FIXME: if the *first* operand is poison, the whole expression is poison.
  3673. return false; // Pessimistically, say that it does not propagate poison.
  3674. case scCouldNotCompute:
  3675. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  3676. }
  3677. llvm_unreachable("Unknown SCEV kind!");
  3678. }
  3679. /// Return true if V is poison given that AssumedPoison is already poison.
  3680. static bool impliesPoison(const SCEV *AssumedPoison, const SCEV *S) {
  3681. // The only way poison may be introduced in a SCEV expression is from a
  3682. // poison SCEVUnknown (ConstantExprs are also represented as SCEVUnknown,
  3683. // not SCEVConstant). Notably, nowrap flags in SCEV nodes can *not*
  3684. // introduce poison -- they encode guaranteed, non-speculated knowledge.
  3685. //
  3686. // Additionally, all SCEV nodes propagate poison from inputs to outputs,
  3687. // with the notable exception of umin_seq, where only poison from the first
  3688. // operand is (unconditionally) propagated.
  3689. struct SCEVPoisonCollector {
  3690. bool LookThroughSeq;
  3691. SmallPtrSet<const SCEV *, 4> MaybePoison;
  3692. SCEVPoisonCollector(bool LookThroughSeq) : LookThroughSeq(LookThroughSeq) {}
  3693. bool follow(const SCEV *S) {
  3694. if (!scevUnconditionallyPropagatesPoisonFromOperands(S->getSCEVType())) {
  3695. switch (S->getSCEVType()) {
  3696. case scConstant:
  3697. case scTruncate:
  3698. case scZeroExtend:
  3699. case scSignExtend:
  3700. case scPtrToInt:
  3701. case scAddExpr:
  3702. case scMulExpr:
  3703. case scUDivExpr:
  3704. case scAddRecExpr:
  3705. case scUMaxExpr:
  3706. case scSMaxExpr:
  3707. case scUMinExpr:
  3708. case scSMinExpr:
  3709. case scUnknown:
  3710. llvm_unreachable("These all unconditionally propagate poison.");
  3711. case scSequentialUMinExpr:
  3712. // TODO: We can always follow the first operand,
  3713. // but the SCEVTraversal API doesn't support this.
  3714. if (!LookThroughSeq)
  3715. return false;
  3716. break;
  3717. case scCouldNotCompute:
  3718. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  3719. }
  3720. }
  3721. if (auto *SU = dyn_cast<SCEVUnknown>(S)) {
  3722. if (!isGuaranteedNotToBePoison(SU->getValue()))
  3723. MaybePoison.insert(S);
  3724. }
  3725. return true;
  3726. }
  3727. bool isDone() const { return false; }
  3728. };
  3729. // First collect all SCEVs that might result in AssumedPoison to be poison.
  3730. // We need to look through umin_seq here, because we want to find all SCEVs
  3731. // that *might* result in poison, not only those that are *required* to.
  3732. SCEVPoisonCollector PC1(/* LookThroughSeq */ true);
  3733. visitAll(AssumedPoison, PC1);
  3734. // AssumedPoison is never poison. As the assumption is false, the implication
  3735. // is true. Don't bother walking the other SCEV in this case.
  3736. if (PC1.MaybePoison.empty())
  3737. return true;
  3738. // Collect all SCEVs in S that, if poison, *will* result in S being poison
  3739. // as well. We cannot look through umin_seq here, as its argument only *may*
  3740. // make the result poison.
  3741. SCEVPoisonCollector PC2(/* LookThroughSeq */ false);
  3742. visitAll(S, PC2);
  3743. // Make sure that no matter which SCEV in PC1.MaybePoison is actually poison,
  3744. // it will also make S poison by being part of PC2.MaybePoison.
  3745. return all_of(PC1.MaybePoison,
  3746. [&](const SCEV *S) { return PC2.MaybePoison.contains(S); });
  3747. }
  3748. const SCEV *
  3749. ScalarEvolution::getSequentialMinMaxExpr(SCEVTypes Kind,
  3750. SmallVectorImpl<const SCEV *> &Ops) {
  3751. assert(SCEVSequentialMinMaxExpr::isSequentialMinMaxType(Kind) &&
  3752. "Not a SCEVSequentialMinMaxExpr!");
  3753. assert(!Ops.empty() && "Cannot get empty (u|s)(min|max)!");
  3754. if (Ops.size() == 1)
  3755. return Ops[0];
  3756. #ifndef NDEBUG
  3757. Type *ETy = getEffectiveSCEVType(Ops[0]->getType());
  3758. for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
  3759. assert(getEffectiveSCEVType(Ops[i]->getType()) == ETy &&
  3760. "Operand types don't match!");
  3761. assert(Ops[0]->getType()->isPointerTy() ==
  3762. Ops[i]->getType()->isPointerTy() &&
  3763. "min/max should be consistently pointerish");
  3764. }
  3765. #endif
  3766. // Note that SCEVSequentialMinMaxExpr is *NOT* commutative,
  3767. // so we can *NOT* do any kind of sorting of the expressions!
  3768. // Check if we have created the same expression before.
  3769. if (const SCEV *S = findExistingSCEVInCache(Kind, Ops))
  3770. return S;
  3771. // FIXME: there are *some* simplifications that we can do here.
  3772. // Keep only the first instance of an operand.
  3773. {
  3774. SCEVSequentialMinMaxDeduplicatingVisitor Deduplicator(*this, Kind);
  3775. bool Changed = Deduplicator.visit(Kind, Ops, Ops);
  3776. if (Changed)
  3777. return getSequentialMinMaxExpr(Kind, Ops);
  3778. }
  3779. // Check to see if one of the operands is of the same kind. If so, expand its
  3780. // operands onto our operand list, and recurse to simplify.
  3781. {
  3782. unsigned Idx = 0;
  3783. bool DeletedAny = false;
  3784. while (Idx < Ops.size()) {
  3785. if (Ops[Idx]->getSCEVType() != Kind) {
  3786. ++Idx;
  3787. continue;
  3788. }
  3789. const auto *SMME = cast<SCEVSequentialMinMaxExpr>(Ops[Idx]);
  3790. Ops.erase(Ops.begin() + Idx);
  3791. Ops.insert(Ops.begin() + Idx, SMME->operands().begin(),
  3792. SMME->operands().end());
  3793. DeletedAny = true;
  3794. }
  3795. if (DeletedAny)
  3796. return getSequentialMinMaxExpr(Kind, Ops);
  3797. }
  3798. const SCEV *SaturationPoint;
  3799. ICmpInst::Predicate Pred;
  3800. switch (Kind) {
  3801. case scSequentialUMinExpr:
  3802. SaturationPoint = getZero(Ops[0]->getType());
  3803. Pred = ICmpInst::ICMP_ULE;
  3804. break;
  3805. default:
  3806. llvm_unreachable("Not a sequential min/max type.");
  3807. }
  3808. for (unsigned i = 1, e = Ops.size(); i != e; ++i) {
  3809. // We can replace %x umin_seq %y with %x umin %y if either:
  3810. // * %y being poison implies %x is also poison.
  3811. // * %x cannot be the saturating value (e.g. zero for umin).
  3812. if (::impliesPoison(Ops[i], Ops[i - 1]) ||
  3813. isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_NE, Ops[i - 1],
  3814. SaturationPoint)) {
  3815. SmallVector<const SCEV *> SeqOps = {Ops[i - 1], Ops[i]};
  3816. Ops[i - 1] = getMinMaxExpr(
  3817. SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(Kind),
  3818. SeqOps);
  3819. Ops.erase(Ops.begin() + i);
  3820. return getSequentialMinMaxExpr(Kind, Ops);
  3821. }
  3822. // Fold %x umin_seq %y to %x if %x ule %y.
  3823. // TODO: We might be able to prove the predicate for a later operand.
  3824. if (isKnownViaNonRecursiveReasoning(Pred, Ops[i - 1], Ops[i])) {
  3825. Ops.erase(Ops.begin() + i);
  3826. return getSequentialMinMaxExpr(Kind, Ops);
  3827. }
  3828. }
  3829. // Okay, it looks like we really DO need an expr. Check to see if we
  3830. // already have one, otherwise create a new one.
  3831. FoldingSetNodeID ID;
  3832. ID.AddInteger(Kind);
  3833. for (unsigned i = 0, e = Ops.size(); i != e; ++i)
  3834. ID.AddPointer(Ops[i]);
  3835. void *IP = nullptr;
  3836. const SCEV *ExistingSCEV = UniqueSCEVs.FindNodeOrInsertPos(ID, IP);
  3837. if (ExistingSCEV)
  3838. return ExistingSCEV;
  3839. const SCEV **O = SCEVAllocator.Allocate<const SCEV *>(Ops.size());
  3840. std::uninitialized_copy(Ops.begin(), Ops.end(), O);
  3841. SCEV *S = new (SCEVAllocator)
  3842. SCEVSequentialMinMaxExpr(ID.Intern(SCEVAllocator), Kind, O, Ops.size());
  3843. UniqueSCEVs.InsertNode(S, IP);
  3844. registerUser(S, Ops);
  3845. return S;
  3846. }
  3847. const SCEV *ScalarEvolution::getSMaxExpr(const SCEV *LHS, const SCEV *RHS) {
  3848. SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
  3849. return getSMaxExpr(Ops);
  3850. }
  3851. const SCEV *ScalarEvolution::getSMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
  3852. return getMinMaxExpr(scSMaxExpr, Ops);
  3853. }
  3854. const SCEV *ScalarEvolution::getUMaxExpr(const SCEV *LHS, const SCEV *RHS) {
  3855. SmallVector<const SCEV *, 2> Ops = {LHS, RHS};
  3856. return getUMaxExpr(Ops);
  3857. }
  3858. const SCEV *ScalarEvolution::getUMaxExpr(SmallVectorImpl<const SCEV *> &Ops) {
  3859. return getMinMaxExpr(scUMaxExpr, Ops);
  3860. }
  3861. const SCEV *ScalarEvolution::getSMinExpr(const SCEV *LHS,
  3862. const SCEV *RHS) {
  3863. SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
  3864. return getSMinExpr(Ops);
  3865. }
  3866. const SCEV *ScalarEvolution::getSMinExpr(SmallVectorImpl<const SCEV *> &Ops) {
  3867. return getMinMaxExpr(scSMinExpr, Ops);
  3868. }
  3869. const SCEV *ScalarEvolution::getUMinExpr(const SCEV *LHS, const SCEV *RHS,
  3870. bool Sequential) {
  3871. SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
  3872. return getUMinExpr(Ops, Sequential);
  3873. }
  3874. const SCEV *ScalarEvolution::getUMinExpr(SmallVectorImpl<const SCEV *> &Ops,
  3875. bool Sequential) {
  3876. return Sequential ? getSequentialMinMaxExpr(scSequentialUMinExpr, Ops)
  3877. : getMinMaxExpr(scUMinExpr, Ops);
  3878. }
  3879. const SCEV *
  3880. ScalarEvolution::getSizeOfScalableVectorExpr(Type *IntTy,
  3881. ScalableVectorType *ScalableTy) {
  3882. Constant *NullPtr = Constant::getNullValue(ScalableTy->getPointerTo());
  3883. Constant *One = ConstantInt::get(IntTy, 1);
  3884. Constant *GEP = ConstantExpr::getGetElementPtr(ScalableTy, NullPtr, One);
  3885. // Note that the expression we created is the final expression, we don't
  3886. // want to simplify it any further Also, if we call a normal getSCEV(),
  3887. // we'll end up in an endless recursion. So just create an SCEVUnknown.
  3888. return getUnknown(ConstantExpr::getPtrToInt(GEP, IntTy));
  3889. }
  3890. const SCEV *ScalarEvolution::getSizeOfExpr(Type *IntTy, Type *AllocTy) {
  3891. if (auto *ScalableAllocTy = dyn_cast<ScalableVectorType>(AllocTy))
  3892. return getSizeOfScalableVectorExpr(IntTy, ScalableAllocTy);
  3893. // We can bypass creating a target-independent constant expression and then
  3894. // folding it back into a ConstantInt. This is just a compile-time
  3895. // optimization.
  3896. return getConstant(IntTy, getDataLayout().getTypeAllocSize(AllocTy));
  3897. }
  3898. const SCEV *ScalarEvolution::getStoreSizeOfExpr(Type *IntTy, Type *StoreTy) {
  3899. if (auto *ScalableStoreTy = dyn_cast<ScalableVectorType>(StoreTy))
  3900. return getSizeOfScalableVectorExpr(IntTy, ScalableStoreTy);
  3901. // We can bypass creating a target-independent constant expression and then
  3902. // folding it back into a ConstantInt. This is just a compile-time
  3903. // optimization.
  3904. return getConstant(IntTy, getDataLayout().getTypeStoreSize(StoreTy));
  3905. }
  3906. const SCEV *ScalarEvolution::getOffsetOfExpr(Type *IntTy,
  3907. StructType *STy,
  3908. unsigned FieldNo) {
  3909. // We can bypass creating a target-independent constant expression and then
  3910. // folding it back into a ConstantInt. This is just a compile-time
  3911. // optimization.
  3912. return getConstant(
  3913. IntTy, getDataLayout().getStructLayout(STy)->getElementOffset(FieldNo));
  3914. }
  3915. const SCEV *ScalarEvolution::getUnknown(Value *V) {
  3916. // Don't attempt to do anything other than create a SCEVUnknown object
  3917. // here. createSCEV only calls getUnknown after checking for all other
  3918. // interesting possibilities, and any other code that calls getUnknown
  3919. // is doing so in order to hide a value from SCEV canonicalization.
  3920. FoldingSetNodeID ID;
  3921. ID.AddInteger(scUnknown);
  3922. ID.AddPointer(V);
  3923. void *IP = nullptr;
  3924. if (SCEV *S = UniqueSCEVs.FindNodeOrInsertPos(ID, IP)) {
  3925. assert(cast<SCEVUnknown>(S)->getValue() == V &&
  3926. "Stale SCEVUnknown in uniquing map!");
  3927. return S;
  3928. }
  3929. SCEV *S = new (SCEVAllocator) SCEVUnknown(ID.Intern(SCEVAllocator), V, this,
  3930. FirstUnknown);
  3931. FirstUnknown = cast<SCEVUnknown>(S);
  3932. UniqueSCEVs.InsertNode(S, IP);
  3933. return S;
  3934. }
  3935. //===----------------------------------------------------------------------===//
  3936. // Basic SCEV Analysis and PHI Idiom Recognition Code
  3937. //
  3938. /// Test if values of the given type are analyzable within the SCEV
  3939. /// framework. This primarily includes integer types, and it can optionally
  3940. /// include pointer types if the ScalarEvolution class has access to
  3941. /// target-specific information.
  3942. bool ScalarEvolution::isSCEVable(Type *Ty) const {
  3943. // Integers and pointers are always SCEVable.
  3944. return Ty->isIntOrPtrTy();
  3945. }
  3946. /// Return the size in bits of the specified type, for which isSCEVable must
  3947. /// return true.
  3948. uint64_t ScalarEvolution::getTypeSizeInBits(Type *Ty) const {
  3949. assert(isSCEVable(Ty) && "Type is not SCEVable!");
  3950. if (Ty->isPointerTy())
  3951. return getDataLayout().getIndexTypeSizeInBits(Ty);
  3952. return getDataLayout().getTypeSizeInBits(Ty);
  3953. }
  3954. /// Return a type with the same bitwidth as the given type and which represents
  3955. /// how SCEV will treat the given type, for which isSCEVable must return
  3956. /// true. For pointer types, this is the pointer index sized integer type.
  3957. Type *ScalarEvolution::getEffectiveSCEVType(Type *Ty) const {
  3958. assert(isSCEVable(Ty) && "Type is not SCEVable!");
  3959. if (Ty->isIntegerTy())
  3960. return Ty;
  3961. // The only other support type is pointer.
  3962. assert(Ty->isPointerTy() && "Unexpected non-pointer non-integer type!");
  3963. return getDataLayout().getIndexType(Ty);
  3964. }
  3965. Type *ScalarEvolution::getWiderType(Type *T1, Type *T2) const {
  3966. return getTypeSizeInBits(T1) >= getTypeSizeInBits(T2) ? T1 : T2;
  3967. }
  3968. bool ScalarEvolution::instructionCouldExistWitthOperands(const SCEV *A,
  3969. const SCEV *B) {
  3970. /// For a valid use point to exist, the defining scope of one operand
  3971. /// must dominate the other.
  3972. bool PreciseA, PreciseB;
  3973. auto *ScopeA = getDefiningScopeBound({A}, PreciseA);
  3974. auto *ScopeB = getDefiningScopeBound({B}, PreciseB);
  3975. if (!PreciseA || !PreciseB)
  3976. // Can't tell.
  3977. return false;
  3978. return (ScopeA == ScopeB) || DT.dominates(ScopeA, ScopeB) ||
  3979. DT.dominates(ScopeB, ScopeA);
  3980. }
  3981. const SCEV *ScalarEvolution::getCouldNotCompute() {
  3982. return CouldNotCompute.get();
  3983. }
  3984. bool ScalarEvolution::checkValidity(const SCEV *S) const {
  3985. bool ContainsNulls = SCEVExprContains(S, [](const SCEV *S) {
  3986. auto *SU = dyn_cast<SCEVUnknown>(S);
  3987. return SU && SU->getValue() == nullptr;
  3988. });
  3989. return !ContainsNulls;
  3990. }
  3991. bool ScalarEvolution::containsAddRecurrence(const SCEV *S) {
  3992. HasRecMapType::iterator I = HasRecMap.find(S);
  3993. if (I != HasRecMap.end())
  3994. return I->second;
  3995. bool FoundAddRec =
  3996. SCEVExprContains(S, [](const SCEV *S) { return isa<SCEVAddRecExpr>(S); });
  3997. HasRecMap.insert({S, FoundAddRec});
  3998. return FoundAddRec;
  3999. }
  4000. /// Return the ValueOffsetPair set for \p S. \p S can be represented
  4001. /// by the value and offset from any ValueOffsetPair in the set.
  4002. ArrayRef<Value *> ScalarEvolution::getSCEVValues(const SCEV *S) {
  4003. ExprValueMapType::iterator SI = ExprValueMap.find_as(S);
  4004. if (SI == ExprValueMap.end())
  4005. return std::nullopt;
  4006. #ifndef NDEBUG
  4007. if (VerifySCEVMap) {
  4008. // Check there is no dangling Value in the set returned.
  4009. for (Value *V : SI->second)
  4010. assert(ValueExprMap.count(V));
  4011. }
  4012. #endif
  4013. return SI->second.getArrayRef();
  4014. }
  4015. /// Erase Value from ValueExprMap and ExprValueMap. ValueExprMap.erase(V)
  4016. /// cannot be used separately. eraseValueFromMap should be used to remove
  4017. /// V from ValueExprMap and ExprValueMap at the same time.
  4018. void ScalarEvolution::eraseValueFromMap(Value *V) {
  4019. ValueExprMapType::iterator I = ValueExprMap.find_as(V);
  4020. if (I != ValueExprMap.end()) {
  4021. auto EVIt = ExprValueMap.find(I->second);
  4022. bool Removed = EVIt->second.remove(V);
  4023. (void) Removed;
  4024. assert(Removed && "Value not in ExprValueMap?");
  4025. ValueExprMap.erase(I);
  4026. }
  4027. }
  4028. void ScalarEvolution::insertValueToMap(Value *V, const SCEV *S) {
  4029. // A recursive query may have already computed the SCEV. It should be
  4030. // equivalent, but may not necessarily be exactly the same, e.g. due to lazily
  4031. // inferred nowrap flags.
  4032. auto It = ValueExprMap.find_as(V);
  4033. if (It == ValueExprMap.end()) {
  4034. ValueExprMap.insert({SCEVCallbackVH(V, this), S});
  4035. ExprValueMap[S].insert(V);
  4036. }
  4037. }
  4038. /// Return an existing SCEV if it exists, otherwise analyze the expression and
  4039. /// create a new one.
  4040. const SCEV *ScalarEvolution::getSCEV(Value *V) {
  4041. assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
  4042. if (const SCEV *S = getExistingSCEV(V))
  4043. return S;
  4044. return createSCEVIter(V);
  4045. }
  4046. const SCEV *ScalarEvolution::getExistingSCEV(Value *V) {
  4047. assert(isSCEVable(V->getType()) && "Value is not SCEVable!");
  4048. ValueExprMapType::iterator I = ValueExprMap.find_as(V);
  4049. if (I != ValueExprMap.end()) {
  4050. const SCEV *S = I->second;
  4051. assert(checkValidity(S) &&
  4052. "existing SCEV has not been properly invalidated");
  4053. return S;
  4054. }
  4055. return nullptr;
  4056. }
  4057. /// Return a SCEV corresponding to -V = -1*V
  4058. const SCEV *ScalarEvolution::getNegativeSCEV(const SCEV *V,
  4059. SCEV::NoWrapFlags Flags) {
  4060. if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
  4061. return getConstant(
  4062. cast<ConstantInt>(ConstantExpr::getNeg(VC->getValue())));
  4063. Type *Ty = V->getType();
  4064. Ty = getEffectiveSCEVType(Ty);
  4065. return getMulExpr(V, getMinusOne(Ty), Flags);
  4066. }
  4067. /// If Expr computes ~A, return A else return nullptr
  4068. static const SCEV *MatchNotExpr(const SCEV *Expr) {
  4069. const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Expr);
  4070. if (!Add || Add->getNumOperands() != 2 ||
  4071. !Add->getOperand(0)->isAllOnesValue())
  4072. return nullptr;
  4073. const SCEVMulExpr *AddRHS = dyn_cast<SCEVMulExpr>(Add->getOperand(1));
  4074. if (!AddRHS || AddRHS->getNumOperands() != 2 ||
  4075. !AddRHS->getOperand(0)->isAllOnesValue())
  4076. return nullptr;
  4077. return AddRHS->getOperand(1);
  4078. }
  4079. /// Return a SCEV corresponding to ~V = -1-V
  4080. const SCEV *ScalarEvolution::getNotSCEV(const SCEV *V) {
  4081. assert(!V->getType()->isPointerTy() && "Can't negate pointer");
  4082. if (const SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
  4083. return getConstant(
  4084. cast<ConstantInt>(ConstantExpr::getNot(VC->getValue())));
  4085. // Fold ~(u|s)(min|max)(~x, ~y) to (u|s)(max|min)(x, y)
  4086. if (const SCEVMinMaxExpr *MME = dyn_cast<SCEVMinMaxExpr>(V)) {
  4087. auto MatchMinMaxNegation = [&](const SCEVMinMaxExpr *MME) {
  4088. SmallVector<const SCEV *, 2> MatchedOperands;
  4089. for (const SCEV *Operand : MME->operands()) {
  4090. const SCEV *Matched = MatchNotExpr(Operand);
  4091. if (!Matched)
  4092. return (const SCEV *)nullptr;
  4093. MatchedOperands.push_back(Matched);
  4094. }
  4095. return getMinMaxExpr(SCEVMinMaxExpr::negate(MME->getSCEVType()),
  4096. MatchedOperands);
  4097. };
  4098. if (const SCEV *Replaced = MatchMinMaxNegation(MME))
  4099. return Replaced;
  4100. }
  4101. Type *Ty = V->getType();
  4102. Ty = getEffectiveSCEVType(Ty);
  4103. return getMinusSCEV(getMinusOne(Ty), V);
  4104. }
  4105. const SCEV *ScalarEvolution::removePointerBase(const SCEV *P) {
  4106. assert(P->getType()->isPointerTy());
  4107. if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(P)) {
  4108. // The base of an AddRec is the first operand.
  4109. SmallVector<const SCEV *> Ops{AddRec->operands()};
  4110. Ops[0] = removePointerBase(Ops[0]);
  4111. // Don't try to transfer nowrap flags for now. We could in some cases
  4112. // (for example, if pointer operand of the AddRec is a SCEVUnknown).
  4113. return getAddRecExpr(Ops, AddRec->getLoop(), SCEV::FlagAnyWrap);
  4114. }
  4115. if (auto *Add = dyn_cast<SCEVAddExpr>(P)) {
  4116. // The base of an Add is the pointer operand.
  4117. SmallVector<const SCEV *> Ops{Add->operands()};
  4118. const SCEV **PtrOp = nullptr;
  4119. for (const SCEV *&AddOp : Ops) {
  4120. if (AddOp->getType()->isPointerTy()) {
  4121. assert(!PtrOp && "Cannot have multiple pointer ops");
  4122. PtrOp = &AddOp;
  4123. }
  4124. }
  4125. *PtrOp = removePointerBase(*PtrOp);
  4126. // Don't try to transfer nowrap flags for now. We could in some cases
  4127. // (for example, if the pointer operand of the Add is a SCEVUnknown).
  4128. return getAddExpr(Ops);
  4129. }
  4130. // Any other expression must be a pointer base.
  4131. return getZero(P->getType());
  4132. }
  4133. const SCEV *ScalarEvolution::getMinusSCEV(const SCEV *LHS, const SCEV *RHS,
  4134. SCEV::NoWrapFlags Flags,
  4135. unsigned Depth) {
  4136. // Fast path: X - X --> 0.
  4137. if (LHS == RHS)
  4138. return getZero(LHS->getType());
  4139. // If we subtract two pointers with different pointer bases, bail.
  4140. // Eventually, we're going to add an assertion to getMulExpr that we
  4141. // can't multiply by a pointer.
  4142. if (RHS->getType()->isPointerTy()) {
  4143. if (!LHS->getType()->isPointerTy() ||
  4144. getPointerBase(LHS) != getPointerBase(RHS))
  4145. return getCouldNotCompute();
  4146. LHS = removePointerBase(LHS);
  4147. RHS = removePointerBase(RHS);
  4148. }
  4149. // We represent LHS - RHS as LHS + (-1)*RHS. This transformation
  4150. // makes it so that we cannot make much use of NUW.
  4151. auto AddFlags = SCEV::FlagAnyWrap;
  4152. const bool RHSIsNotMinSigned =
  4153. !getSignedRangeMin(RHS).isMinSignedValue();
  4154. if (hasFlags(Flags, SCEV::FlagNSW)) {
  4155. // Let M be the minimum representable signed value. Then (-1)*RHS
  4156. // signed-wraps if and only if RHS is M. That can happen even for
  4157. // a NSW subtraction because e.g. (-1)*M signed-wraps even though
  4158. // -1 - M does not. So to transfer NSW from LHS - RHS to LHS +
  4159. // (-1)*RHS, we need to prove that RHS != M.
  4160. //
  4161. // If LHS is non-negative and we know that LHS - RHS does not
  4162. // signed-wrap, then RHS cannot be M. So we can rule out signed-wrap
  4163. // either by proving that RHS > M or that LHS >= 0.
  4164. if (RHSIsNotMinSigned || isKnownNonNegative(LHS)) {
  4165. AddFlags = SCEV::FlagNSW;
  4166. }
  4167. }
  4168. // FIXME: Find a correct way to transfer NSW to (-1)*M when LHS -
  4169. // RHS is NSW and LHS >= 0.
  4170. //
  4171. // The difficulty here is that the NSW flag may have been proven
  4172. // relative to a loop that is to be found in a recurrence in LHS and
  4173. // not in RHS. Applying NSW to (-1)*M may then let the NSW have a
  4174. // larger scope than intended.
  4175. auto NegFlags = RHSIsNotMinSigned ? SCEV::FlagNSW : SCEV::FlagAnyWrap;
  4176. return getAddExpr(LHS, getNegativeSCEV(RHS, NegFlags), AddFlags, Depth);
  4177. }
  4178. const SCEV *ScalarEvolution::getTruncateOrZeroExtend(const SCEV *V, Type *Ty,
  4179. unsigned Depth) {
  4180. Type *SrcTy = V->getType();
  4181. assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  4182. "Cannot truncate or zero extend with non-integer arguments!");
  4183. if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
  4184. return V; // No conversion
  4185. if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
  4186. return getTruncateExpr(V, Ty, Depth);
  4187. return getZeroExtendExpr(V, Ty, Depth);
  4188. }
  4189. const SCEV *ScalarEvolution::getTruncateOrSignExtend(const SCEV *V, Type *Ty,
  4190. unsigned Depth) {
  4191. Type *SrcTy = V->getType();
  4192. assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  4193. "Cannot truncate or zero extend with non-integer arguments!");
  4194. if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
  4195. return V; // No conversion
  4196. if (getTypeSizeInBits(SrcTy) > getTypeSizeInBits(Ty))
  4197. return getTruncateExpr(V, Ty, Depth);
  4198. return getSignExtendExpr(V, Ty, Depth);
  4199. }
  4200. const SCEV *
  4201. ScalarEvolution::getNoopOrZeroExtend(const SCEV *V, Type *Ty) {
  4202. Type *SrcTy = V->getType();
  4203. assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  4204. "Cannot noop or zero extend with non-integer arguments!");
  4205. assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
  4206. "getNoopOrZeroExtend cannot truncate!");
  4207. if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
  4208. return V; // No conversion
  4209. return getZeroExtendExpr(V, Ty);
  4210. }
  4211. const SCEV *
  4212. ScalarEvolution::getNoopOrSignExtend(const SCEV *V, Type *Ty) {
  4213. Type *SrcTy = V->getType();
  4214. assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  4215. "Cannot noop or sign extend with non-integer arguments!");
  4216. assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
  4217. "getNoopOrSignExtend cannot truncate!");
  4218. if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
  4219. return V; // No conversion
  4220. return getSignExtendExpr(V, Ty);
  4221. }
  4222. const SCEV *
  4223. ScalarEvolution::getNoopOrAnyExtend(const SCEV *V, Type *Ty) {
  4224. Type *SrcTy = V->getType();
  4225. assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  4226. "Cannot noop or any extend with non-integer arguments!");
  4227. assert(getTypeSizeInBits(SrcTy) <= getTypeSizeInBits(Ty) &&
  4228. "getNoopOrAnyExtend cannot truncate!");
  4229. if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
  4230. return V; // No conversion
  4231. return getAnyExtendExpr(V, Ty);
  4232. }
  4233. const SCEV *
  4234. ScalarEvolution::getTruncateOrNoop(const SCEV *V, Type *Ty) {
  4235. Type *SrcTy = V->getType();
  4236. assert(SrcTy->isIntOrPtrTy() && Ty->isIntOrPtrTy() &&
  4237. "Cannot truncate or noop with non-integer arguments!");
  4238. assert(getTypeSizeInBits(SrcTy) >= getTypeSizeInBits(Ty) &&
  4239. "getTruncateOrNoop cannot extend!");
  4240. if (getTypeSizeInBits(SrcTy) == getTypeSizeInBits(Ty))
  4241. return V; // No conversion
  4242. return getTruncateExpr(V, Ty);
  4243. }
  4244. const SCEV *ScalarEvolution::getUMaxFromMismatchedTypes(const SCEV *LHS,
  4245. const SCEV *RHS) {
  4246. const SCEV *PromotedLHS = LHS;
  4247. const SCEV *PromotedRHS = RHS;
  4248. if (getTypeSizeInBits(LHS->getType()) > getTypeSizeInBits(RHS->getType()))
  4249. PromotedRHS = getZeroExtendExpr(RHS, LHS->getType());
  4250. else
  4251. PromotedLHS = getNoopOrZeroExtend(LHS, RHS->getType());
  4252. return getUMaxExpr(PromotedLHS, PromotedRHS);
  4253. }
  4254. const SCEV *ScalarEvolution::getUMinFromMismatchedTypes(const SCEV *LHS,
  4255. const SCEV *RHS,
  4256. bool Sequential) {
  4257. SmallVector<const SCEV *, 2> Ops = { LHS, RHS };
  4258. return getUMinFromMismatchedTypes(Ops, Sequential);
  4259. }
  4260. const SCEV *
  4261. ScalarEvolution::getUMinFromMismatchedTypes(SmallVectorImpl<const SCEV *> &Ops,
  4262. bool Sequential) {
  4263. assert(!Ops.empty() && "At least one operand must be!");
  4264. // Trivial case.
  4265. if (Ops.size() == 1)
  4266. return Ops[0];
  4267. // Find the max type first.
  4268. Type *MaxType = nullptr;
  4269. for (const auto *S : Ops)
  4270. if (MaxType)
  4271. MaxType = getWiderType(MaxType, S->getType());
  4272. else
  4273. MaxType = S->getType();
  4274. assert(MaxType && "Failed to find maximum type!");
  4275. // Extend all ops to max type.
  4276. SmallVector<const SCEV *, 2> PromotedOps;
  4277. for (const auto *S : Ops)
  4278. PromotedOps.push_back(getNoopOrZeroExtend(S, MaxType));
  4279. // Generate umin.
  4280. return getUMinExpr(PromotedOps, Sequential);
  4281. }
  4282. const SCEV *ScalarEvolution::getPointerBase(const SCEV *V) {
  4283. // A pointer operand may evaluate to a nonpointer expression, such as null.
  4284. if (!V->getType()->isPointerTy())
  4285. return V;
  4286. while (true) {
  4287. if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
  4288. V = AddRec->getStart();
  4289. } else if (auto *Add = dyn_cast<SCEVAddExpr>(V)) {
  4290. const SCEV *PtrOp = nullptr;
  4291. for (const SCEV *AddOp : Add->operands()) {
  4292. if (AddOp->getType()->isPointerTy()) {
  4293. assert(!PtrOp && "Cannot have multiple pointer ops");
  4294. PtrOp = AddOp;
  4295. }
  4296. }
  4297. assert(PtrOp && "Must have pointer op");
  4298. V = PtrOp;
  4299. } else // Not something we can look further into.
  4300. return V;
  4301. }
  4302. }
  4303. /// Push users of the given Instruction onto the given Worklist.
  4304. static void PushDefUseChildren(Instruction *I,
  4305. SmallVectorImpl<Instruction *> &Worklist,
  4306. SmallPtrSetImpl<Instruction *> &Visited) {
  4307. // Push the def-use children onto the Worklist stack.
  4308. for (User *U : I->users()) {
  4309. auto *UserInsn = cast<Instruction>(U);
  4310. if (Visited.insert(UserInsn).second)
  4311. Worklist.push_back(UserInsn);
  4312. }
  4313. }
  4314. namespace {
  4315. /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its start
  4316. /// expression in case its Loop is L. If it is not L then
  4317. /// if IgnoreOtherLoops is true then use AddRec itself
  4318. /// otherwise rewrite cannot be done.
  4319. /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
  4320. class SCEVInitRewriter : public SCEVRewriteVisitor<SCEVInitRewriter> {
  4321. public:
  4322. static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
  4323. bool IgnoreOtherLoops = true) {
  4324. SCEVInitRewriter Rewriter(L, SE);
  4325. const SCEV *Result = Rewriter.visit(S);
  4326. if (Rewriter.hasSeenLoopVariantSCEVUnknown())
  4327. return SE.getCouldNotCompute();
  4328. return Rewriter.hasSeenOtherLoops() && !IgnoreOtherLoops
  4329. ? SE.getCouldNotCompute()
  4330. : Result;
  4331. }
  4332. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  4333. if (!SE.isLoopInvariant(Expr, L))
  4334. SeenLoopVariantSCEVUnknown = true;
  4335. return Expr;
  4336. }
  4337. const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
  4338. // Only re-write AddRecExprs for this loop.
  4339. if (Expr->getLoop() == L)
  4340. return Expr->getStart();
  4341. SeenOtherLoops = true;
  4342. return Expr;
  4343. }
  4344. bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
  4345. bool hasSeenOtherLoops() { return SeenOtherLoops; }
  4346. private:
  4347. explicit SCEVInitRewriter(const Loop *L, ScalarEvolution &SE)
  4348. : SCEVRewriteVisitor(SE), L(L) {}
  4349. const Loop *L;
  4350. bool SeenLoopVariantSCEVUnknown = false;
  4351. bool SeenOtherLoops = false;
  4352. };
  4353. /// Takes SCEV S and Loop L. For each AddRec sub-expression, use its post
  4354. /// increment expression in case its Loop is L. If it is not L then
  4355. /// use AddRec itself.
  4356. /// If SCEV contains non-invariant unknown SCEV rewrite cannot be done.
  4357. class SCEVPostIncRewriter : public SCEVRewriteVisitor<SCEVPostIncRewriter> {
  4358. public:
  4359. static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE) {
  4360. SCEVPostIncRewriter Rewriter(L, SE);
  4361. const SCEV *Result = Rewriter.visit(S);
  4362. return Rewriter.hasSeenLoopVariantSCEVUnknown()
  4363. ? SE.getCouldNotCompute()
  4364. : Result;
  4365. }
  4366. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  4367. if (!SE.isLoopInvariant(Expr, L))
  4368. SeenLoopVariantSCEVUnknown = true;
  4369. return Expr;
  4370. }
  4371. const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
  4372. // Only re-write AddRecExprs for this loop.
  4373. if (Expr->getLoop() == L)
  4374. return Expr->getPostIncExpr(SE);
  4375. SeenOtherLoops = true;
  4376. return Expr;
  4377. }
  4378. bool hasSeenLoopVariantSCEVUnknown() { return SeenLoopVariantSCEVUnknown; }
  4379. bool hasSeenOtherLoops() { return SeenOtherLoops; }
  4380. private:
  4381. explicit SCEVPostIncRewriter(const Loop *L, ScalarEvolution &SE)
  4382. : SCEVRewriteVisitor(SE), L(L) {}
  4383. const Loop *L;
  4384. bool SeenLoopVariantSCEVUnknown = false;
  4385. bool SeenOtherLoops = false;
  4386. };
  4387. /// This class evaluates the compare condition by matching it against the
  4388. /// condition of loop latch. If there is a match we assume a true value
  4389. /// for the condition while building SCEV nodes.
  4390. class SCEVBackedgeConditionFolder
  4391. : public SCEVRewriteVisitor<SCEVBackedgeConditionFolder> {
  4392. public:
  4393. static const SCEV *rewrite(const SCEV *S, const Loop *L,
  4394. ScalarEvolution &SE) {
  4395. bool IsPosBECond = false;
  4396. Value *BECond = nullptr;
  4397. if (BasicBlock *Latch = L->getLoopLatch()) {
  4398. BranchInst *BI = dyn_cast<BranchInst>(Latch->getTerminator());
  4399. if (BI && BI->isConditional()) {
  4400. assert(BI->getSuccessor(0) != BI->getSuccessor(1) &&
  4401. "Both outgoing branches should not target same header!");
  4402. BECond = BI->getCondition();
  4403. IsPosBECond = BI->getSuccessor(0) == L->getHeader();
  4404. } else {
  4405. return S;
  4406. }
  4407. }
  4408. SCEVBackedgeConditionFolder Rewriter(L, BECond, IsPosBECond, SE);
  4409. return Rewriter.visit(S);
  4410. }
  4411. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  4412. const SCEV *Result = Expr;
  4413. bool InvariantF = SE.isLoopInvariant(Expr, L);
  4414. if (!InvariantF) {
  4415. Instruction *I = cast<Instruction>(Expr->getValue());
  4416. switch (I->getOpcode()) {
  4417. case Instruction::Select: {
  4418. SelectInst *SI = cast<SelectInst>(I);
  4419. std::optional<const SCEV *> Res =
  4420. compareWithBackedgeCondition(SI->getCondition());
  4421. if (Res) {
  4422. bool IsOne = cast<SCEVConstant>(*Res)->getValue()->isOne();
  4423. Result = SE.getSCEV(IsOne ? SI->getTrueValue() : SI->getFalseValue());
  4424. }
  4425. break;
  4426. }
  4427. default: {
  4428. std::optional<const SCEV *> Res = compareWithBackedgeCondition(I);
  4429. if (Res)
  4430. Result = *Res;
  4431. break;
  4432. }
  4433. }
  4434. }
  4435. return Result;
  4436. }
  4437. private:
  4438. explicit SCEVBackedgeConditionFolder(const Loop *L, Value *BECond,
  4439. bool IsPosBECond, ScalarEvolution &SE)
  4440. : SCEVRewriteVisitor(SE), L(L), BackedgeCond(BECond),
  4441. IsPositiveBECond(IsPosBECond) {}
  4442. std::optional<const SCEV *> compareWithBackedgeCondition(Value *IC);
  4443. const Loop *L;
  4444. /// Loop back condition.
  4445. Value *BackedgeCond = nullptr;
  4446. /// Set to true if loop back is on positive branch condition.
  4447. bool IsPositiveBECond;
  4448. };
  4449. std::optional<const SCEV *>
  4450. SCEVBackedgeConditionFolder::compareWithBackedgeCondition(Value *IC) {
  4451. // If value matches the backedge condition for loop latch,
  4452. // then return a constant evolution node based on loopback
  4453. // branch taken.
  4454. if (BackedgeCond == IC)
  4455. return IsPositiveBECond ? SE.getOne(Type::getInt1Ty(SE.getContext()))
  4456. : SE.getZero(Type::getInt1Ty(SE.getContext()));
  4457. return std::nullopt;
  4458. }
  4459. class SCEVShiftRewriter : public SCEVRewriteVisitor<SCEVShiftRewriter> {
  4460. public:
  4461. static const SCEV *rewrite(const SCEV *S, const Loop *L,
  4462. ScalarEvolution &SE) {
  4463. SCEVShiftRewriter Rewriter(L, SE);
  4464. const SCEV *Result = Rewriter.visit(S);
  4465. return Rewriter.isValid() ? Result : SE.getCouldNotCompute();
  4466. }
  4467. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  4468. // Only allow AddRecExprs for this loop.
  4469. if (!SE.isLoopInvariant(Expr, L))
  4470. Valid = false;
  4471. return Expr;
  4472. }
  4473. const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) {
  4474. if (Expr->getLoop() == L && Expr->isAffine())
  4475. return SE.getMinusSCEV(Expr, Expr->getStepRecurrence(SE));
  4476. Valid = false;
  4477. return Expr;
  4478. }
  4479. bool isValid() { return Valid; }
  4480. private:
  4481. explicit SCEVShiftRewriter(const Loop *L, ScalarEvolution &SE)
  4482. : SCEVRewriteVisitor(SE), L(L) {}
  4483. const Loop *L;
  4484. bool Valid = true;
  4485. };
  4486. } // end anonymous namespace
  4487. SCEV::NoWrapFlags
  4488. ScalarEvolution::proveNoWrapViaConstantRanges(const SCEVAddRecExpr *AR) {
  4489. if (!AR->isAffine())
  4490. return SCEV::FlagAnyWrap;
  4491. using OBO = OverflowingBinaryOperator;
  4492. SCEV::NoWrapFlags Result = SCEV::FlagAnyWrap;
  4493. if (!AR->hasNoSignedWrap()) {
  4494. ConstantRange AddRecRange = getSignedRange(AR);
  4495. ConstantRange IncRange = getSignedRange(AR->getStepRecurrence(*this));
  4496. auto NSWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
  4497. Instruction::Add, IncRange, OBO::NoSignedWrap);
  4498. if (NSWRegion.contains(AddRecRange))
  4499. Result = ScalarEvolution::setFlags(Result, SCEV::FlagNSW);
  4500. }
  4501. if (!AR->hasNoUnsignedWrap()) {
  4502. ConstantRange AddRecRange = getUnsignedRange(AR);
  4503. ConstantRange IncRange = getUnsignedRange(AR->getStepRecurrence(*this));
  4504. auto NUWRegion = ConstantRange::makeGuaranteedNoWrapRegion(
  4505. Instruction::Add, IncRange, OBO::NoUnsignedWrap);
  4506. if (NUWRegion.contains(AddRecRange))
  4507. Result = ScalarEvolution::setFlags(Result, SCEV::FlagNUW);
  4508. }
  4509. return Result;
  4510. }
  4511. SCEV::NoWrapFlags
  4512. ScalarEvolution::proveNoSignedWrapViaInduction(const SCEVAddRecExpr *AR) {
  4513. SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
  4514. if (AR->hasNoSignedWrap())
  4515. return Result;
  4516. if (!AR->isAffine())
  4517. return Result;
  4518. // This function can be expensive, only try to prove NSW once per AddRec.
  4519. if (!SignedWrapViaInductionTried.insert(AR).second)
  4520. return Result;
  4521. const SCEV *Step = AR->getStepRecurrence(*this);
  4522. const Loop *L = AR->getLoop();
  4523. // Check whether the backedge-taken count is SCEVCouldNotCompute.
  4524. // Note that this serves two purposes: It filters out loops that are
  4525. // simply not analyzable, and it covers the case where this code is
  4526. // being called from within backedge-taken count analysis, such that
  4527. // attempting to ask for the backedge-taken count would likely result
  4528. // in infinite recursion. In the later case, the analysis code will
  4529. // cope with a conservative value, and it will take care to purge
  4530. // that value once it has finished.
  4531. const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
  4532. // Normally, in the cases we can prove no-overflow via a
  4533. // backedge guarding condition, we can also compute a backedge
  4534. // taken count for the loop. The exceptions are assumptions and
  4535. // guards present in the loop -- SCEV is not great at exploiting
  4536. // these to compute max backedge taken counts, but can still use
  4537. // these to prove lack of overflow. Use this fact to avoid
  4538. // doing extra work that may not pay off.
  4539. if (isa<SCEVCouldNotCompute>(MaxBECount) && AC.assumptions().empty())
  4540. return Result;
  4541. // If the backedge is guarded by a comparison with the pre-inc value the
  4542. // addrec is safe. Also, if the entry is guarded by a comparison with the
  4543. // start value and the backedge is guarded by a comparison with the post-inc
  4544. // value, the addrec is safe.
  4545. ICmpInst::Predicate Pred;
  4546. const SCEV *OverflowLimit =
  4547. getSignedOverflowLimitForStep(Step, &Pred, this);
  4548. if (OverflowLimit &&
  4549. (isLoopBackedgeGuardedByCond(L, Pred, AR, OverflowLimit) ||
  4550. isKnownOnEveryIteration(Pred, AR, OverflowLimit))) {
  4551. Result = setFlags(Result, SCEV::FlagNSW);
  4552. }
  4553. return Result;
  4554. }
  4555. SCEV::NoWrapFlags
  4556. ScalarEvolution::proveNoUnsignedWrapViaInduction(const SCEVAddRecExpr *AR) {
  4557. SCEV::NoWrapFlags Result = AR->getNoWrapFlags();
  4558. if (AR->hasNoUnsignedWrap())
  4559. return Result;
  4560. if (!AR->isAffine())
  4561. return Result;
  4562. // This function can be expensive, only try to prove NUW once per AddRec.
  4563. if (!UnsignedWrapViaInductionTried.insert(AR).second)
  4564. return Result;
  4565. const SCEV *Step = AR->getStepRecurrence(*this);
  4566. unsigned BitWidth = getTypeSizeInBits(AR->getType());
  4567. const Loop *L = AR->getLoop();
  4568. // Check whether the backedge-taken count is SCEVCouldNotCompute.
  4569. // Note that this serves two purposes: It filters out loops that are
  4570. // simply not analyzable, and it covers the case where this code is
  4571. // being called from within backedge-taken count analysis, such that
  4572. // attempting to ask for the backedge-taken count would likely result
  4573. // in infinite recursion. In the later case, the analysis code will
  4574. // cope with a conservative value, and it will take care to purge
  4575. // that value once it has finished.
  4576. const SCEV *MaxBECount = getConstantMaxBackedgeTakenCount(L);
  4577. // Normally, in the cases we can prove no-overflow via a
  4578. // backedge guarding condition, we can also compute a backedge
  4579. // taken count for the loop. The exceptions are assumptions and
  4580. // guards present in the loop -- SCEV is not great at exploiting
  4581. // these to compute max backedge taken counts, but can still use
  4582. // these to prove lack of overflow. Use this fact to avoid
  4583. // doing extra work that may not pay off.
  4584. if (isa<SCEVCouldNotCompute>(MaxBECount) && AC.assumptions().empty())
  4585. return Result;
  4586. // If the backedge is guarded by a comparison with the pre-inc value the
  4587. // addrec is safe. Also, if the entry is guarded by a comparison with the
  4588. // start value and the backedge is guarded by a comparison with the post-inc
  4589. // value, the addrec is safe.
  4590. if (isKnownPositive(Step)) {
  4591. const SCEV *N = getConstant(APInt::getMinValue(BitWidth) -
  4592. getUnsignedRangeMax(Step));
  4593. if (isLoopBackedgeGuardedByCond(L, ICmpInst::ICMP_ULT, AR, N) ||
  4594. isKnownOnEveryIteration(ICmpInst::ICMP_ULT, AR, N)) {
  4595. Result = setFlags(Result, SCEV::FlagNUW);
  4596. }
  4597. }
  4598. return Result;
  4599. }
  4600. namespace {
  4601. /// Represents an abstract binary operation. This may exist as a
  4602. /// normal instruction or constant expression, or may have been
  4603. /// derived from an expression tree.
  4604. struct BinaryOp {
  4605. unsigned Opcode;
  4606. Value *LHS;
  4607. Value *RHS;
  4608. bool IsNSW = false;
  4609. bool IsNUW = false;
  4610. /// Op is set if this BinaryOp corresponds to a concrete LLVM instruction or
  4611. /// constant expression.
  4612. Operator *Op = nullptr;
  4613. explicit BinaryOp(Operator *Op)
  4614. : Opcode(Op->getOpcode()), LHS(Op->getOperand(0)), RHS(Op->getOperand(1)),
  4615. Op(Op) {
  4616. if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(Op)) {
  4617. IsNSW = OBO->hasNoSignedWrap();
  4618. IsNUW = OBO->hasNoUnsignedWrap();
  4619. }
  4620. }
  4621. explicit BinaryOp(unsigned Opcode, Value *LHS, Value *RHS, bool IsNSW = false,
  4622. bool IsNUW = false)
  4623. : Opcode(Opcode), LHS(LHS), RHS(RHS), IsNSW(IsNSW), IsNUW(IsNUW) {}
  4624. };
  4625. } // end anonymous namespace
  4626. /// Try to map \p V into a BinaryOp, and return \c std::nullopt on failure.
  4627. static std::optional<BinaryOp> MatchBinaryOp(Value *V, const DataLayout &DL,
  4628. AssumptionCache &AC,
  4629. const DominatorTree &DT,
  4630. const Instruction *CxtI) {
  4631. auto *Op = dyn_cast<Operator>(V);
  4632. if (!Op)
  4633. return std::nullopt;
  4634. // Implementation detail: all the cleverness here should happen without
  4635. // creating new SCEV expressions -- our caller knowns tricks to avoid creating
  4636. // SCEV expressions when possible, and we should not break that.
  4637. switch (Op->getOpcode()) {
  4638. case Instruction::Add:
  4639. case Instruction::Sub:
  4640. case Instruction::Mul:
  4641. case Instruction::UDiv:
  4642. case Instruction::URem:
  4643. case Instruction::And:
  4644. case Instruction::AShr:
  4645. case Instruction::Shl:
  4646. return BinaryOp(Op);
  4647. case Instruction::Or: {
  4648. // LLVM loves to convert `add` of operands with no common bits
  4649. // into an `or`. But SCEV really doesn't deal with `or` that well,
  4650. // so try extra hard to recognize this `or` as an `add`.
  4651. if (haveNoCommonBitsSet(Op->getOperand(0), Op->getOperand(1), DL, &AC, CxtI,
  4652. &DT, /*UseInstrInfo=*/true))
  4653. return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1),
  4654. /*IsNSW=*/true, /*IsNUW=*/true);
  4655. return BinaryOp(Op);
  4656. }
  4657. case Instruction::Xor:
  4658. if (auto *RHSC = dyn_cast<ConstantInt>(Op->getOperand(1)))
  4659. // If the RHS of the xor is a signmask, then this is just an add.
  4660. // Instcombine turns add of signmask into xor as a strength reduction step.
  4661. if (RHSC->getValue().isSignMask())
  4662. return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
  4663. // Binary `xor` is a bit-wise `add`.
  4664. if (V->getType()->isIntegerTy(1))
  4665. return BinaryOp(Instruction::Add, Op->getOperand(0), Op->getOperand(1));
  4666. return BinaryOp(Op);
  4667. case Instruction::LShr:
  4668. // Turn logical shift right of a constant into a unsigned divide.
  4669. if (ConstantInt *SA = dyn_cast<ConstantInt>(Op->getOperand(1))) {
  4670. uint32_t BitWidth = cast<IntegerType>(Op->getType())->getBitWidth();
  4671. // If the shift count is not less than the bitwidth, the result of
  4672. // the shift is undefined. Don't try to analyze it, because the
  4673. // resolution chosen here may differ from the resolution chosen in
  4674. // other parts of the compiler.
  4675. if (SA->getValue().ult(BitWidth)) {
  4676. Constant *X =
  4677. ConstantInt::get(SA->getContext(),
  4678. APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
  4679. return BinaryOp(Instruction::UDiv, Op->getOperand(0), X);
  4680. }
  4681. }
  4682. return BinaryOp(Op);
  4683. case Instruction::ExtractValue: {
  4684. auto *EVI = cast<ExtractValueInst>(Op);
  4685. if (EVI->getNumIndices() != 1 || EVI->getIndices()[0] != 0)
  4686. break;
  4687. auto *WO = dyn_cast<WithOverflowInst>(EVI->getAggregateOperand());
  4688. if (!WO)
  4689. break;
  4690. Instruction::BinaryOps BinOp = WO->getBinaryOp();
  4691. bool Signed = WO->isSigned();
  4692. // TODO: Should add nuw/nsw flags for mul as well.
  4693. if (BinOp == Instruction::Mul || !isOverflowIntrinsicNoWrap(WO, DT))
  4694. return BinaryOp(BinOp, WO->getLHS(), WO->getRHS());
  4695. // Now that we know that all uses of the arithmetic-result component of
  4696. // CI are guarded by the overflow check, we can go ahead and pretend
  4697. // that the arithmetic is non-overflowing.
  4698. return BinaryOp(BinOp, WO->getLHS(), WO->getRHS(),
  4699. /* IsNSW = */ Signed, /* IsNUW = */ !Signed);
  4700. }
  4701. default:
  4702. break;
  4703. }
  4704. // Recognise intrinsic loop.decrement.reg, and as this has exactly the same
  4705. // semantics as a Sub, return a binary sub expression.
  4706. if (auto *II = dyn_cast<IntrinsicInst>(V))
  4707. if (II->getIntrinsicID() == Intrinsic::loop_decrement_reg)
  4708. return BinaryOp(Instruction::Sub, II->getOperand(0), II->getOperand(1));
  4709. return std::nullopt;
  4710. }
  4711. /// Helper function to createAddRecFromPHIWithCasts. We have a phi
  4712. /// node whose symbolic (unknown) SCEV is \p SymbolicPHI, which is updated via
  4713. /// the loop backedge by a SCEVAddExpr, possibly also with a few casts on the
  4714. /// way. This function checks if \p Op, an operand of this SCEVAddExpr,
  4715. /// follows one of the following patterns:
  4716. /// Op == (SExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
  4717. /// Op == (ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy)
  4718. /// If the SCEV expression of \p Op conforms with one of the expected patterns
  4719. /// we return the type of the truncation operation, and indicate whether the
  4720. /// truncated type should be treated as signed/unsigned by setting
  4721. /// \p Signed to true/false, respectively.
  4722. static Type *isSimpleCastedPHI(const SCEV *Op, const SCEVUnknown *SymbolicPHI,
  4723. bool &Signed, ScalarEvolution &SE) {
  4724. // The case where Op == SymbolicPHI (that is, with no type conversions on
  4725. // the way) is handled by the regular add recurrence creating logic and
  4726. // would have already been triggered in createAddRecForPHI. Reaching it here
  4727. // means that createAddRecFromPHI had failed for this PHI before (e.g.,
  4728. // because one of the other operands of the SCEVAddExpr updating this PHI is
  4729. // not invariant).
  4730. //
  4731. // Here we look for the case where Op = (ext(trunc(SymbolicPHI))), and in
  4732. // this case predicates that allow us to prove that Op == SymbolicPHI will
  4733. // be added.
  4734. if (Op == SymbolicPHI)
  4735. return nullptr;
  4736. unsigned SourceBits = SE.getTypeSizeInBits(SymbolicPHI->getType());
  4737. unsigned NewBits = SE.getTypeSizeInBits(Op->getType());
  4738. if (SourceBits != NewBits)
  4739. return nullptr;
  4740. const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(Op);
  4741. const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(Op);
  4742. if (!SExt && !ZExt)
  4743. return nullptr;
  4744. const SCEVTruncateExpr *Trunc =
  4745. SExt ? dyn_cast<SCEVTruncateExpr>(SExt->getOperand())
  4746. : dyn_cast<SCEVTruncateExpr>(ZExt->getOperand());
  4747. if (!Trunc)
  4748. return nullptr;
  4749. const SCEV *X = Trunc->getOperand();
  4750. if (X != SymbolicPHI)
  4751. return nullptr;
  4752. Signed = SExt != nullptr;
  4753. return Trunc->getType();
  4754. }
  4755. static const Loop *isIntegerLoopHeaderPHI(const PHINode *PN, LoopInfo &LI) {
  4756. if (!PN->getType()->isIntegerTy())
  4757. return nullptr;
  4758. const Loop *L = LI.getLoopFor(PN->getParent());
  4759. if (!L || L->getHeader() != PN->getParent())
  4760. return nullptr;
  4761. return L;
  4762. }
  4763. // Analyze \p SymbolicPHI, a SCEV expression of a phi node, and check if the
  4764. // computation that updates the phi follows the following pattern:
  4765. // (SExt/ZExt ix (Trunc iy (%SymbolicPHI) to ix) to iy) + InvariantAccum
  4766. // which correspond to a phi->trunc->sext/zext->add->phi update chain.
  4767. // If so, try to see if it can be rewritten as an AddRecExpr under some
  4768. // Predicates. If successful, return them as a pair. Also cache the results
  4769. // of the analysis.
  4770. //
  4771. // Example usage scenario:
  4772. // Say the Rewriter is called for the following SCEV:
  4773. // 8 * ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
  4774. // where:
  4775. // %X = phi i64 (%Start, %BEValue)
  4776. // It will visitMul->visitAdd->visitSExt->visitTrunc->visitUnknown(%X),
  4777. // and call this function with %SymbolicPHI = %X.
  4778. //
  4779. // The analysis will find that the value coming around the backedge has
  4780. // the following SCEV:
  4781. // BEValue = ((sext i32 (trunc i64 %X to i32) to i64) + %Step)
  4782. // Upon concluding that this matches the desired pattern, the function
  4783. // will return the pair {NewAddRec, SmallPredsVec} where:
  4784. // NewAddRec = {%Start,+,%Step}
  4785. // SmallPredsVec = {P1, P2, P3} as follows:
  4786. // P1(WrapPred): AR: {trunc(%Start),+,(trunc %Step)}<nsw> Flags: <nssw>
  4787. // P2(EqualPred): %Start == (sext i32 (trunc i64 %Start to i32) to i64)
  4788. // P3(EqualPred): %Step == (sext i32 (trunc i64 %Step to i32) to i64)
  4789. // The returned pair means that SymbolicPHI can be rewritten into NewAddRec
  4790. // under the predicates {P1,P2,P3}.
  4791. // This predicated rewrite will be cached in PredicatedSCEVRewrites:
  4792. // PredicatedSCEVRewrites[{%X,L}] = {NewAddRec, {P1,P2,P3)}
  4793. //
  4794. // TODO's:
  4795. //
  4796. // 1) Extend the Induction descriptor to also support inductions that involve
  4797. // casts: When needed (namely, when we are called in the context of the
  4798. // vectorizer induction analysis), a Set of cast instructions will be
  4799. // populated by this method, and provided back to isInductionPHI. This is
  4800. // needed to allow the vectorizer to properly record them to be ignored by
  4801. // the cost model and to avoid vectorizing them (otherwise these casts,
  4802. // which are redundant under the runtime overflow checks, will be
  4803. // vectorized, which can be costly).
  4804. //
  4805. // 2) Support additional induction/PHISCEV patterns: We also want to support
  4806. // inductions where the sext-trunc / zext-trunc operations (partly) occur
  4807. // after the induction update operation (the induction increment):
  4808. //
  4809. // (Trunc iy (SExt/ZExt ix (%SymbolicPHI + InvariantAccum) to iy) to ix)
  4810. // which correspond to a phi->add->trunc->sext/zext->phi update chain.
  4811. //
  4812. // (Trunc iy ((SExt/ZExt ix (%SymbolicPhi) to iy) + InvariantAccum) to ix)
  4813. // which correspond to a phi->trunc->add->sext/zext->phi update chain.
  4814. //
  4815. // 3) Outline common code with createAddRecFromPHI to avoid duplication.
  4816. std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
  4817. ScalarEvolution::createAddRecFromPHIWithCastsImpl(const SCEVUnknown *SymbolicPHI) {
  4818. SmallVector<const SCEVPredicate *, 3> Predicates;
  4819. // *** Part1: Analyze if we have a phi-with-cast pattern for which we can
  4820. // return an AddRec expression under some predicate.
  4821. auto *PN = cast<PHINode>(SymbolicPHI->getValue());
  4822. const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
  4823. assert(L && "Expecting an integer loop header phi");
  4824. // The loop may have multiple entrances or multiple exits; we can analyze
  4825. // this phi as an addrec if it has a unique entry value and a unique
  4826. // backedge value.
  4827. Value *BEValueV = nullptr, *StartValueV = nullptr;
  4828. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  4829. Value *V = PN->getIncomingValue(i);
  4830. if (L->contains(PN->getIncomingBlock(i))) {
  4831. if (!BEValueV) {
  4832. BEValueV = V;
  4833. } else if (BEValueV != V) {
  4834. BEValueV = nullptr;
  4835. break;
  4836. }
  4837. } else if (!StartValueV) {
  4838. StartValueV = V;
  4839. } else if (StartValueV != V) {
  4840. StartValueV = nullptr;
  4841. break;
  4842. }
  4843. }
  4844. if (!BEValueV || !StartValueV)
  4845. return std::nullopt;
  4846. const SCEV *BEValue = getSCEV(BEValueV);
  4847. // If the value coming around the backedge is an add with the symbolic
  4848. // value we just inserted, possibly with casts that we can ignore under
  4849. // an appropriate runtime guard, then we found a simple induction variable!
  4850. const auto *Add = dyn_cast<SCEVAddExpr>(BEValue);
  4851. if (!Add)
  4852. return std::nullopt;
  4853. // If there is a single occurrence of the symbolic value, possibly
  4854. // casted, replace it with a recurrence.
  4855. unsigned FoundIndex = Add->getNumOperands();
  4856. Type *TruncTy = nullptr;
  4857. bool Signed;
  4858. for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
  4859. if ((TruncTy =
  4860. isSimpleCastedPHI(Add->getOperand(i), SymbolicPHI, Signed, *this)))
  4861. if (FoundIndex == e) {
  4862. FoundIndex = i;
  4863. break;
  4864. }
  4865. if (FoundIndex == Add->getNumOperands())
  4866. return std::nullopt;
  4867. // Create an add with everything but the specified operand.
  4868. SmallVector<const SCEV *, 8> Ops;
  4869. for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
  4870. if (i != FoundIndex)
  4871. Ops.push_back(Add->getOperand(i));
  4872. const SCEV *Accum = getAddExpr(Ops);
  4873. // The runtime checks will not be valid if the step amount is
  4874. // varying inside the loop.
  4875. if (!isLoopInvariant(Accum, L))
  4876. return std::nullopt;
  4877. // *** Part2: Create the predicates
  4878. // Analysis was successful: we have a phi-with-cast pattern for which we
  4879. // can return an AddRec expression under the following predicates:
  4880. //
  4881. // P1: A Wrap predicate that guarantees that Trunc(Start) + i*Trunc(Accum)
  4882. // fits within the truncated type (does not overflow) for i = 0 to n-1.
  4883. // P2: An Equal predicate that guarantees that
  4884. // Start = (Ext ix (Trunc iy (Start) to ix) to iy)
  4885. // P3: An Equal predicate that guarantees that
  4886. // Accum = (Ext ix (Trunc iy (Accum) to ix) to iy)
  4887. //
  4888. // As we next prove, the above predicates guarantee that:
  4889. // Start + i*Accum = (Ext ix (Trunc iy ( Start + i*Accum ) to ix) to iy)
  4890. //
  4891. //
  4892. // More formally, we want to prove that:
  4893. // Expr(i+1) = Start + (i+1) * Accum
  4894. // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
  4895. //
  4896. // Given that:
  4897. // 1) Expr(0) = Start
  4898. // 2) Expr(1) = Start + Accum
  4899. // = (Ext ix (Trunc iy (Start) to ix) to iy) + Accum :: from P2
  4900. // 3) Induction hypothesis (step i):
  4901. // Expr(i) = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum
  4902. //
  4903. // Proof:
  4904. // Expr(i+1) =
  4905. // = Start + (i+1)*Accum
  4906. // = (Start + i*Accum) + Accum
  4907. // = Expr(i) + Accum
  4908. // = (Ext ix (Trunc iy (Expr(i-1)) to ix) to iy) + Accum + Accum
  4909. // :: from step i
  4910. //
  4911. // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy) + Accum + Accum
  4912. //
  4913. // = (Ext ix (Trunc iy (Start + (i-1)*Accum) to ix) to iy)
  4914. // + (Ext ix (Trunc iy (Accum) to ix) to iy)
  4915. // + Accum :: from P3
  4916. //
  4917. // = (Ext ix (Trunc iy ((Start + (i-1)*Accum) + Accum) to ix) to iy)
  4918. // + Accum :: from P1: Ext(x)+Ext(y)=>Ext(x+y)
  4919. //
  4920. // = (Ext ix (Trunc iy (Start + i*Accum) to ix) to iy) + Accum
  4921. // = (Ext ix (Trunc iy (Expr(i)) to ix) to iy) + Accum
  4922. //
  4923. // By induction, the same applies to all iterations 1<=i<n:
  4924. //
  4925. // Create a truncated addrec for which we will add a no overflow check (P1).
  4926. const SCEV *StartVal = getSCEV(StartValueV);
  4927. const SCEV *PHISCEV =
  4928. getAddRecExpr(getTruncateExpr(StartVal, TruncTy),
  4929. getTruncateExpr(Accum, TruncTy), L, SCEV::FlagAnyWrap);
  4930. // PHISCEV can be either a SCEVConstant or a SCEVAddRecExpr.
  4931. // ex: If truncated Accum is 0 and StartVal is a constant, then PHISCEV
  4932. // will be constant.
  4933. //
  4934. // If PHISCEV is a constant, then P1 degenerates into P2 or P3, so we don't
  4935. // add P1.
  4936. if (const auto *AR = dyn_cast<SCEVAddRecExpr>(PHISCEV)) {
  4937. SCEVWrapPredicate::IncrementWrapFlags AddedFlags =
  4938. Signed ? SCEVWrapPredicate::IncrementNSSW
  4939. : SCEVWrapPredicate::IncrementNUSW;
  4940. const SCEVPredicate *AddRecPred = getWrapPredicate(AR, AddedFlags);
  4941. Predicates.push_back(AddRecPred);
  4942. }
  4943. // Create the Equal Predicates P2,P3:
  4944. // It is possible that the predicates P2 and/or P3 are computable at
  4945. // compile time due to StartVal and/or Accum being constants.
  4946. // If either one is, then we can check that now and escape if either P2
  4947. // or P3 is false.
  4948. // Construct the extended SCEV: (Ext ix (Trunc iy (Expr) to ix) to iy)
  4949. // for each of StartVal and Accum
  4950. auto getExtendedExpr = [&](const SCEV *Expr,
  4951. bool CreateSignExtend) -> const SCEV * {
  4952. assert(isLoopInvariant(Expr, L) && "Expr is expected to be invariant");
  4953. const SCEV *TruncatedExpr = getTruncateExpr(Expr, TruncTy);
  4954. const SCEV *ExtendedExpr =
  4955. CreateSignExtend ? getSignExtendExpr(TruncatedExpr, Expr->getType())
  4956. : getZeroExtendExpr(TruncatedExpr, Expr->getType());
  4957. return ExtendedExpr;
  4958. };
  4959. // Given:
  4960. // ExtendedExpr = (Ext ix (Trunc iy (Expr) to ix) to iy
  4961. // = getExtendedExpr(Expr)
  4962. // Determine whether the predicate P: Expr == ExtendedExpr
  4963. // is known to be false at compile time
  4964. auto PredIsKnownFalse = [&](const SCEV *Expr,
  4965. const SCEV *ExtendedExpr) -> bool {
  4966. return Expr != ExtendedExpr &&
  4967. isKnownPredicate(ICmpInst::ICMP_NE, Expr, ExtendedExpr);
  4968. };
  4969. const SCEV *StartExtended = getExtendedExpr(StartVal, Signed);
  4970. if (PredIsKnownFalse(StartVal, StartExtended)) {
  4971. LLVM_DEBUG(dbgs() << "P2 is compile-time false\n";);
  4972. return std::nullopt;
  4973. }
  4974. // The Step is always Signed (because the overflow checks are either
  4975. // NSSW or NUSW)
  4976. const SCEV *AccumExtended = getExtendedExpr(Accum, /*CreateSignExtend=*/true);
  4977. if (PredIsKnownFalse(Accum, AccumExtended)) {
  4978. LLVM_DEBUG(dbgs() << "P3 is compile-time false\n";);
  4979. return std::nullopt;
  4980. }
  4981. auto AppendPredicate = [&](const SCEV *Expr,
  4982. const SCEV *ExtendedExpr) -> void {
  4983. if (Expr != ExtendedExpr &&
  4984. !isKnownPredicate(ICmpInst::ICMP_EQ, Expr, ExtendedExpr)) {
  4985. const SCEVPredicate *Pred = getEqualPredicate(Expr, ExtendedExpr);
  4986. LLVM_DEBUG(dbgs() << "Added Predicate: " << *Pred);
  4987. Predicates.push_back(Pred);
  4988. }
  4989. };
  4990. AppendPredicate(StartVal, StartExtended);
  4991. AppendPredicate(Accum, AccumExtended);
  4992. // *** Part3: Predicates are ready. Now go ahead and create the new addrec in
  4993. // which the casts had been folded away. The caller can rewrite SymbolicPHI
  4994. // into NewAR if it will also add the runtime overflow checks specified in
  4995. // Predicates.
  4996. auto *NewAR = getAddRecExpr(StartVal, Accum, L, SCEV::FlagAnyWrap);
  4997. std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> PredRewrite =
  4998. std::make_pair(NewAR, Predicates);
  4999. // Remember the result of the analysis for this SCEV at this locayyytion.
  5000. PredicatedSCEVRewrites[{SymbolicPHI, L}] = PredRewrite;
  5001. return PredRewrite;
  5002. }
  5003. std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
  5004. ScalarEvolution::createAddRecFromPHIWithCasts(const SCEVUnknown *SymbolicPHI) {
  5005. auto *PN = cast<PHINode>(SymbolicPHI->getValue());
  5006. const Loop *L = isIntegerLoopHeaderPHI(PN, LI);
  5007. if (!L)
  5008. return std::nullopt;
  5009. // Check to see if we already analyzed this PHI.
  5010. auto I = PredicatedSCEVRewrites.find({SymbolicPHI, L});
  5011. if (I != PredicatedSCEVRewrites.end()) {
  5012. std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>> Rewrite =
  5013. I->second;
  5014. // Analysis was done before and failed to create an AddRec:
  5015. if (Rewrite.first == SymbolicPHI)
  5016. return std::nullopt;
  5017. // Analysis was done before and succeeded to create an AddRec under
  5018. // a predicate:
  5019. assert(isa<SCEVAddRecExpr>(Rewrite.first) && "Expected an AddRec");
  5020. assert(!(Rewrite.second).empty() && "Expected to find Predicates");
  5021. return Rewrite;
  5022. }
  5023. std::optional<std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
  5024. Rewrite = createAddRecFromPHIWithCastsImpl(SymbolicPHI);
  5025. // Record in the cache that the analysis failed
  5026. if (!Rewrite) {
  5027. SmallVector<const SCEVPredicate *, 3> Predicates;
  5028. PredicatedSCEVRewrites[{SymbolicPHI, L}] = {SymbolicPHI, Predicates};
  5029. return std::nullopt;
  5030. }
  5031. return Rewrite;
  5032. }
  5033. // FIXME: This utility is currently required because the Rewriter currently
  5034. // does not rewrite this expression:
  5035. // {0, +, (sext ix (trunc iy to ix) to iy)}
  5036. // into {0, +, %step},
  5037. // even when the following Equal predicate exists:
  5038. // "%step == (sext ix (trunc iy to ix) to iy)".
  5039. bool PredicatedScalarEvolution::areAddRecsEqualWithPreds(
  5040. const SCEVAddRecExpr *AR1, const SCEVAddRecExpr *AR2) const {
  5041. if (AR1 == AR2)
  5042. return true;
  5043. auto areExprsEqual = [&](const SCEV *Expr1, const SCEV *Expr2) -> bool {
  5044. if (Expr1 != Expr2 && !Preds->implies(SE.getEqualPredicate(Expr1, Expr2)) &&
  5045. !Preds->implies(SE.getEqualPredicate(Expr2, Expr1)))
  5046. return false;
  5047. return true;
  5048. };
  5049. if (!areExprsEqual(AR1->getStart(), AR2->getStart()) ||
  5050. !areExprsEqual(AR1->getStepRecurrence(SE), AR2->getStepRecurrence(SE)))
  5051. return false;
  5052. return true;
  5053. }
  5054. /// A helper function for createAddRecFromPHI to handle simple cases.
  5055. ///
  5056. /// This function tries to find an AddRec expression for the simplest (yet most
  5057. /// common) cases: PN = PHI(Start, OP(Self, LoopInvariant)).
  5058. /// If it fails, createAddRecFromPHI will use a more general, but slow,
  5059. /// technique for finding the AddRec expression.
  5060. const SCEV *ScalarEvolution::createSimpleAffineAddRec(PHINode *PN,
  5061. Value *BEValueV,
  5062. Value *StartValueV) {
  5063. const Loop *L = LI.getLoopFor(PN->getParent());
  5064. assert(L && L->getHeader() == PN->getParent());
  5065. assert(BEValueV && StartValueV);
  5066. auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN);
  5067. if (!BO)
  5068. return nullptr;
  5069. if (BO->Opcode != Instruction::Add)
  5070. return nullptr;
  5071. const SCEV *Accum = nullptr;
  5072. if (BO->LHS == PN && L->isLoopInvariant(BO->RHS))
  5073. Accum = getSCEV(BO->RHS);
  5074. else if (BO->RHS == PN && L->isLoopInvariant(BO->LHS))
  5075. Accum = getSCEV(BO->LHS);
  5076. if (!Accum)
  5077. return nullptr;
  5078. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
  5079. if (BO->IsNUW)
  5080. Flags = setFlags(Flags, SCEV::FlagNUW);
  5081. if (BO->IsNSW)
  5082. Flags = setFlags(Flags, SCEV::FlagNSW);
  5083. const SCEV *StartVal = getSCEV(StartValueV);
  5084. const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
  5085. insertValueToMap(PN, PHISCEV);
  5086. // We can add Flags to the post-inc expression only if we
  5087. // know that it is *undefined behavior* for BEValueV to
  5088. // overflow.
  5089. if (auto *BEInst = dyn_cast<Instruction>(BEValueV)) {
  5090. assert(isLoopInvariant(Accum, L) &&
  5091. "Accum is defined outside L, but is not invariant?");
  5092. if (isAddRecNeverPoison(BEInst, L))
  5093. (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
  5094. }
  5095. return PHISCEV;
  5096. }
  5097. const SCEV *ScalarEvolution::createAddRecFromPHI(PHINode *PN) {
  5098. const Loop *L = LI.getLoopFor(PN->getParent());
  5099. if (!L || L->getHeader() != PN->getParent())
  5100. return nullptr;
  5101. // The loop may have multiple entrances or multiple exits; we can analyze
  5102. // this phi as an addrec if it has a unique entry value and a unique
  5103. // backedge value.
  5104. Value *BEValueV = nullptr, *StartValueV = nullptr;
  5105. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  5106. Value *V = PN->getIncomingValue(i);
  5107. if (L->contains(PN->getIncomingBlock(i))) {
  5108. if (!BEValueV) {
  5109. BEValueV = V;
  5110. } else if (BEValueV != V) {
  5111. BEValueV = nullptr;
  5112. break;
  5113. }
  5114. } else if (!StartValueV) {
  5115. StartValueV = V;
  5116. } else if (StartValueV != V) {
  5117. StartValueV = nullptr;
  5118. break;
  5119. }
  5120. }
  5121. if (!BEValueV || !StartValueV)
  5122. return nullptr;
  5123. assert(ValueExprMap.find_as(PN) == ValueExprMap.end() &&
  5124. "PHI node already processed?");
  5125. // First, try to find AddRec expression without creating a fictituos symbolic
  5126. // value for PN.
  5127. if (auto *S = createSimpleAffineAddRec(PN, BEValueV, StartValueV))
  5128. return S;
  5129. // Handle PHI node value symbolically.
  5130. const SCEV *SymbolicName = getUnknown(PN);
  5131. insertValueToMap(PN, SymbolicName);
  5132. // Using this symbolic name for the PHI, analyze the value coming around
  5133. // the back-edge.
  5134. const SCEV *BEValue = getSCEV(BEValueV);
  5135. // NOTE: If BEValue is loop invariant, we know that the PHI node just
  5136. // has a special value for the first iteration of the loop.
  5137. // If the value coming around the backedge is an add with the symbolic
  5138. // value we just inserted, then we found a simple induction variable!
  5139. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
  5140. // If there is a single occurrence of the symbolic value, replace it
  5141. // with a recurrence.
  5142. unsigned FoundIndex = Add->getNumOperands();
  5143. for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
  5144. if (Add->getOperand(i) == SymbolicName)
  5145. if (FoundIndex == e) {
  5146. FoundIndex = i;
  5147. break;
  5148. }
  5149. if (FoundIndex != Add->getNumOperands()) {
  5150. // Create an add with everything but the specified operand.
  5151. SmallVector<const SCEV *, 8> Ops;
  5152. for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
  5153. if (i != FoundIndex)
  5154. Ops.push_back(SCEVBackedgeConditionFolder::rewrite(Add->getOperand(i),
  5155. L, *this));
  5156. const SCEV *Accum = getAddExpr(Ops);
  5157. // This is not a valid addrec if the step amount is varying each
  5158. // loop iteration, but is not itself an addrec in this loop.
  5159. if (isLoopInvariant(Accum, L) ||
  5160. (isa<SCEVAddRecExpr>(Accum) &&
  5161. cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
  5162. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
  5163. if (auto BO = MatchBinaryOp(BEValueV, getDataLayout(), AC, DT, PN)) {
  5164. if (BO->Opcode == Instruction::Add && BO->LHS == PN) {
  5165. if (BO->IsNUW)
  5166. Flags = setFlags(Flags, SCEV::FlagNUW);
  5167. if (BO->IsNSW)
  5168. Flags = setFlags(Flags, SCEV::FlagNSW);
  5169. }
  5170. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(BEValueV)) {
  5171. // If the increment is an inbounds GEP, then we know the address
  5172. // space cannot be wrapped around. We cannot make any guarantee
  5173. // about signed or unsigned overflow because pointers are
  5174. // unsigned but we may have a negative index from the base
  5175. // pointer. We can guarantee that no unsigned wrap occurs if the
  5176. // indices form a positive value.
  5177. if (GEP->isInBounds() && GEP->getOperand(0) == PN) {
  5178. Flags = setFlags(Flags, SCEV::FlagNW);
  5179. const SCEV *Ptr = getSCEV(GEP->getPointerOperand());
  5180. if (isKnownPositive(getMinusSCEV(getSCEV(GEP), Ptr)))
  5181. Flags = setFlags(Flags, SCEV::FlagNUW);
  5182. }
  5183. // We cannot transfer nuw and nsw flags from subtraction
  5184. // operations -- sub nuw X, Y is not the same as add nuw X, -Y
  5185. // for instance.
  5186. }
  5187. const SCEV *StartVal = getSCEV(StartValueV);
  5188. const SCEV *PHISCEV = getAddRecExpr(StartVal, Accum, L, Flags);
  5189. // Okay, for the entire analysis of this edge we assumed the PHI
  5190. // to be symbolic. We now need to go back and purge all of the
  5191. // entries for the scalars that use the symbolic expression.
  5192. forgetMemoizedResults(SymbolicName);
  5193. insertValueToMap(PN, PHISCEV);
  5194. // We can add Flags to the post-inc expression only if we
  5195. // know that it is *undefined behavior* for BEValueV to
  5196. // overflow.
  5197. if (auto *BEInst = dyn_cast<Instruction>(BEValueV))
  5198. if (isLoopInvariant(Accum, L) && isAddRecNeverPoison(BEInst, L))
  5199. (void)getAddRecExpr(getAddExpr(StartVal, Accum), Accum, L, Flags);
  5200. return PHISCEV;
  5201. }
  5202. }
  5203. } else {
  5204. // Otherwise, this could be a loop like this:
  5205. // i = 0; for (j = 1; ..; ++j) { .... i = j; }
  5206. // In this case, j = {1,+,1} and BEValue is j.
  5207. // Because the other in-value of i (0) fits the evolution of BEValue
  5208. // i really is an addrec evolution.
  5209. //
  5210. // We can generalize this saying that i is the shifted value of BEValue
  5211. // by one iteration:
  5212. // PHI(f(0), f({1,+,1})) --> f({0,+,1})
  5213. const SCEV *Shifted = SCEVShiftRewriter::rewrite(BEValue, L, *this);
  5214. const SCEV *Start = SCEVInitRewriter::rewrite(Shifted, L, *this, false);
  5215. if (Shifted != getCouldNotCompute() &&
  5216. Start != getCouldNotCompute()) {
  5217. const SCEV *StartVal = getSCEV(StartValueV);
  5218. if (Start == StartVal) {
  5219. // Okay, for the entire analysis of this edge we assumed the PHI
  5220. // to be symbolic. We now need to go back and purge all of the
  5221. // entries for the scalars that use the symbolic expression.
  5222. forgetMemoizedResults(SymbolicName);
  5223. insertValueToMap(PN, Shifted);
  5224. return Shifted;
  5225. }
  5226. }
  5227. }
  5228. // Remove the temporary PHI node SCEV that has been inserted while intending
  5229. // to create an AddRecExpr for this PHI node. We can not keep this temporary
  5230. // as it will prevent later (possibly simpler) SCEV expressions to be added
  5231. // to the ValueExprMap.
  5232. eraseValueFromMap(PN);
  5233. return nullptr;
  5234. }
  5235. // Checks if the SCEV S is available at BB. S is considered available at BB
  5236. // if S can be materialized at BB without introducing a fault.
  5237. static bool IsAvailableOnEntry(const Loop *L, DominatorTree &DT, const SCEV *S,
  5238. BasicBlock *BB) {
  5239. struct CheckAvailable {
  5240. bool TraversalDone = false;
  5241. bool Available = true;
  5242. const Loop *L = nullptr; // The loop BB is in (can be nullptr)
  5243. BasicBlock *BB = nullptr;
  5244. DominatorTree &DT;
  5245. CheckAvailable(const Loop *L, BasicBlock *BB, DominatorTree &DT)
  5246. : L(L), BB(BB), DT(DT) {}
  5247. bool setUnavailable() {
  5248. TraversalDone = true;
  5249. Available = false;
  5250. return false;
  5251. }
  5252. bool follow(const SCEV *S) {
  5253. switch (S->getSCEVType()) {
  5254. case scConstant:
  5255. case scPtrToInt:
  5256. case scTruncate:
  5257. case scZeroExtend:
  5258. case scSignExtend:
  5259. case scAddExpr:
  5260. case scMulExpr:
  5261. case scUMaxExpr:
  5262. case scSMaxExpr:
  5263. case scUMinExpr:
  5264. case scSMinExpr:
  5265. case scSequentialUMinExpr:
  5266. // These expressions are available if their operand(s) is/are.
  5267. return true;
  5268. case scAddRecExpr: {
  5269. // We allow add recurrences that are on the loop BB is in, or some
  5270. // outer loop. This guarantees availability because the value of the
  5271. // add recurrence at BB is simply the "current" value of the induction
  5272. // variable. We can relax this in the future; for instance an add
  5273. // recurrence on a sibling dominating loop is also available at BB.
  5274. const auto *ARLoop = cast<SCEVAddRecExpr>(S)->getLoop();
  5275. if (L && (ARLoop == L || ARLoop->contains(L)))
  5276. return true;
  5277. return setUnavailable();
  5278. }
  5279. case scUnknown: {
  5280. // For SCEVUnknown, we check for simple dominance.
  5281. const auto *SU = cast<SCEVUnknown>(S);
  5282. Value *V = SU->getValue();
  5283. if (isa<Argument>(V))
  5284. return false;
  5285. if (isa<Instruction>(V) && DT.dominates(cast<Instruction>(V), BB))
  5286. return false;
  5287. return setUnavailable();
  5288. }
  5289. case scUDivExpr:
  5290. case scCouldNotCompute:
  5291. // We do not try to smart about these at all.
  5292. return setUnavailable();
  5293. }
  5294. llvm_unreachable("Unknown SCEV kind!");
  5295. }
  5296. bool isDone() { return TraversalDone; }
  5297. };
  5298. CheckAvailable CA(L, BB, DT);
  5299. SCEVTraversal<CheckAvailable> ST(CA);
  5300. ST.visitAll(S);
  5301. return CA.Available;
  5302. }
  5303. // Try to match a control flow sequence that branches out at BI and merges back
  5304. // at Merge into a "C ? LHS : RHS" select pattern. Return true on a successful
  5305. // match.
  5306. static bool BrPHIToSelect(DominatorTree &DT, BranchInst *BI, PHINode *Merge,
  5307. Value *&C, Value *&LHS, Value *&RHS) {
  5308. C = BI->getCondition();
  5309. BasicBlockEdge LeftEdge(BI->getParent(), BI->getSuccessor(0));
  5310. BasicBlockEdge RightEdge(BI->getParent(), BI->getSuccessor(1));
  5311. if (!LeftEdge.isSingleEdge())
  5312. return false;
  5313. assert(RightEdge.isSingleEdge() && "Follows from LeftEdge.isSingleEdge()");
  5314. Use &LeftUse = Merge->getOperandUse(0);
  5315. Use &RightUse = Merge->getOperandUse(1);
  5316. if (DT.dominates(LeftEdge, LeftUse) && DT.dominates(RightEdge, RightUse)) {
  5317. LHS = LeftUse;
  5318. RHS = RightUse;
  5319. return true;
  5320. }
  5321. if (DT.dominates(LeftEdge, RightUse) && DT.dominates(RightEdge, LeftUse)) {
  5322. LHS = RightUse;
  5323. RHS = LeftUse;
  5324. return true;
  5325. }
  5326. return false;
  5327. }
  5328. const SCEV *ScalarEvolution::createNodeFromSelectLikePHI(PHINode *PN) {
  5329. auto IsReachable =
  5330. [&](BasicBlock *BB) { return DT.isReachableFromEntry(BB); };
  5331. if (PN->getNumIncomingValues() == 2 && all_of(PN->blocks(), IsReachable)) {
  5332. const Loop *L = LI.getLoopFor(PN->getParent());
  5333. // We don't want to break LCSSA, even in a SCEV expression tree.
  5334. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  5335. if (LI.getLoopFor(PN->getIncomingBlock(i)) != L)
  5336. return nullptr;
  5337. // Try to match
  5338. //
  5339. // br %cond, label %left, label %right
  5340. // left:
  5341. // br label %merge
  5342. // right:
  5343. // br label %merge
  5344. // merge:
  5345. // V = phi [ %x, %left ], [ %y, %right ]
  5346. //
  5347. // as "select %cond, %x, %y"
  5348. BasicBlock *IDom = DT[PN->getParent()]->getIDom()->getBlock();
  5349. assert(IDom && "At least the entry block should dominate PN");
  5350. auto *BI = dyn_cast<BranchInst>(IDom->getTerminator());
  5351. Value *Cond = nullptr, *LHS = nullptr, *RHS = nullptr;
  5352. if (BI && BI->isConditional() &&
  5353. BrPHIToSelect(DT, BI, PN, Cond, LHS, RHS) &&
  5354. IsAvailableOnEntry(L, DT, getSCEV(LHS), PN->getParent()) &&
  5355. IsAvailableOnEntry(L, DT, getSCEV(RHS), PN->getParent()))
  5356. return createNodeForSelectOrPHI(PN, Cond, LHS, RHS);
  5357. }
  5358. return nullptr;
  5359. }
  5360. const SCEV *ScalarEvolution::createNodeForPHI(PHINode *PN) {
  5361. if (const SCEV *S = createAddRecFromPHI(PN))
  5362. return S;
  5363. if (const SCEV *S = createNodeFromSelectLikePHI(PN))
  5364. return S;
  5365. if (Value *V = simplifyInstruction(PN, {getDataLayout(), &TLI, &DT, &AC}))
  5366. return getSCEV(V);
  5367. // If it's not a loop phi, we can't handle it yet.
  5368. return getUnknown(PN);
  5369. }
  5370. bool SCEVMinMaxExprContains(const SCEV *Root, const SCEV *OperandToFind,
  5371. SCEVTypes RootKind) {
  5372. struct FindClosure {
  5373. const SCEV *OperandToFind;
  5374. const SCEVTypes RootKind; // Must be a sequential min/max expression.
  5375. const SCEVTypes NonSequentialRootKind; // Non-seq variant of RootKind.
  5376. bool Found = false;
  5377. bool canRecurseInto(SCEVTypes Kind) const {
  5378. // We can only recurse into the SCEV expression of the same effective type
  5379. // as the type of our root SCEV expression, and into zero-extensions.
  5380. return RootKind == Kind || NonSequentialRootKind == Kind ||
  5381. scZeroExtend == Kind;
  5382. };
  5383. FindClosure(const SCEV *OperandToFind, SCEVTypes RootKind)
  5384. : OperandToFind(OperandToFind), RootKind(RootKind),
  5385. NonSequentialRootKind(
  5386. SCEVSequentialMinMaxExpr::getEquivalentNonSequentialSCEVType(
  5387. RootKind)) {}
  5388. bool follow(const SCEV *S) {
  5389. Found = S == OperandToFind;
  5390. return !isDone() && canRecurseInto(S->getSCEVType());
  5391. }
  5392. bool isDone() const { return Found; }
  5393. };
  5394. FindClosure FC(OperandToFind, RootKind);
  5395. visitAll(Root, FC);
  5396. return FC.Found;
  5397. }
  5398. std::optional<const SCEV *>
  5399. ScalarEvolution::createNodeForSelectOrPHIInstWithICmpInstCond(Type *Ty,
  5400. ICmpInst *Cond,
  5401. Value *TrueVal,
  5402. Value *FalseVal) {
  5403. // Try to match some simple smax or umax patterns.
  5404. auto *ICI = Cond;
  5405. Value *LHS = ICI->getOperand(0);
  5406. Value *RHS = ICI->getOperand(1);
  5407. switch (ICI->getPredicate()) {
  5408. case ICmpInst::ICMP_SLT:
  5409. case ICmpInst::ICMP_SLE:
  5410. case ICmpInst::ICMP_ULT:
  5411. case ICmpInst::ICMP_ULE:
  5412. std::swap(LHS, RHS);
  5413. [[fallthrough]];
  5414. case ICmpInst::ICMP_SGT:
  5415. case ICmpInst::ICMP_SGE:
  5416. case ICmpInst::ICMP_UGT:
  5417. case ICmpInst::ICMP_UGE:
  5418. // a > b ? a+x : b+x -> max(a, b)+x
  5419. // a > b ? b+x : a+x -> min(a, b)+x
  5420. if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty)) {
  5421. bool Signed = ICI->isSigned();
  5422. const SCEV *LA = getSCEV(TrueVal);
  5423. const SCEV *RA = getSCEV(FalseVal);
  5424. const SCEV *LS = getSCEV(LHS);
  5425. const SCEV *RS = getSCEV(RHS);
  5426. if (LA->getType()->isPointerTy()) {
  5427. // FIXME: Handle cases where LS/RS are pointers not equal to LA/RA.
  5428. // Need to make sure we can't produce weird expressions involving
  5429. // negated pointers.
  5430. if (LA == LS && RA == RS)
  5431. return Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS);
  5432. if (LA == RS && RA == LS)
  5433. return Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS);
  5434. }
  5435. auto CoerceOperand = [&](const SCEV *Op) -> const SCEV * {
  5436. if (Op->getType()->isPointerTy()) {
  5437. Op = getLosslessPtrToIntExpr(Op);
  5438. if (isa<SCEVCouldNotCompute>(Op))
  5439. return Op;
  5440. }
  5441. if (Signed)
  5442. Op = getNoopOrSignExtend(Op, Ty);
  5443. else
  5444. Op = getNoopOrZeroExtend(Op, Ty);
  5445. return Op;
  5446. };
  5447. LS = CoerceOperand(LS);
  5448. RS = CoerceOperand(RS);
  5449. if (isa<SCEVCouldNotCompute>(LS) || isa<SCEVCouldNotCompute>(RS))
  5450. break;
  5451. const SCEV *LDiff = getMinusSCEV(LA, LS);
  5452. const SCEV *RDiff = getMinusSCEV(RA, RS);
  5453. if (LDiff == RDiff)
  5454. return getAddExpr(Signed ? getSMaxExpr(LS, RS) : getUMaxExpr(LS, RS),
  5455. LDiff);
  5456. LDiff = getMinusSCEV(LA, RS);
  5457. RDiff = getMinusSCEV(RA, LS);
  5458. if (LDiff == RDiff)
  5459. return getAddExpr(Signed ? getSMinExpr(LS, RS) : getUMinExpr(LS, RS),
  5460. LDiff);
  5461. }
  5462. break;
  5463. case ICmpInst::ICMP_NE:
  5464. // x != 0 ? x+y : C+y -> x == 0 ? C+y : x+y
  5465. std::swap(TrueVal, FalseVal);
  5466. [[fallthrough]];
  5467. case ICmpInst::ICMP_EQ:
  5468. // x == 0 ? C+y : x+y -> umax(x, C)+y iff C u<= 1
  5469. if (getTypeSizeInBits(LHS->getType()) <= getTypeSizeInBits(Ty) &&
  5470. isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()) {
  5471. const SCEV *X = getNoopOrZeroExtend(getSCEV(LHS), Ty);
  5472. const SCEV *TrueValExpr = getSCEV(TrueVal); // C+y
  5473. const SCEV *FalseValExpr = getSCEV(FalseVal); // x+y
  5474. const SCEV *Y = getMinusSCEV(FalseValExpr, X); // y = (x+y)-x
  5475. const SCEV *C = getMinusSCEV(TrueValExpr, Y); // C = (C+y)-y
  5476. if (isa<SCEVConstant>(C) && cast<SCEVConstant>(C)->getAPInt().ule(1))
  5477. return getAddExpr(getUMaxExpr(X, C), Y);
  5478. }
  5479. // x == 0 ? 0 : umin (..., x, ...) -> umin_seq(x, umin (...))
  5480. // x == 0 ? 0 : umin_seq(..., x, ...) -> umin_seq(x, umin_seq(...))
  5481. // x == 0 ? 0 : umin (..., umin_seq(..., x, ...), ...)
  5482. // -> umin_seq(x, umin (..., umin_seq(...), ...))
  5483. if (isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero() &&
  5484. isa<ConstantInt>(TrueVal) && cast<ConstantInt>(TrueVal)->isZero()) {
  5485. const SCEV *X = getSCEV(LHS);
  5486. while (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(X))
  5487. X = ZExt->getOperand();
  5488. if (getTypeSizeInBits(X->getType()) <= getTypeSizeInBits(Ty)) {
  5489. const SCEV *FalseValExpr = getSCEV(FalseVal);
  5490. if (SCEVMinMaxExprContains(FalseValExpr, X, scSequentialUMinExpr))
  5491. return getUMinExpr(getNoopOrZeroExtend(X, Ty), FalseValExpr,
  5492. /*Sequential=*/true);
  5493. }
  5494. }
  5495. break;
  5496. default:
  5497. break;
  5498. }
  5499. return std::nullopt;
  5500. }
  5501. static std::optional<const SCEV *>
  5502. createNodeForSelectViaUMinSeq(ScalarEvolution *SE, const SCEV *CondExpr,
  5503. const SCEV *TrueExpr, const SCEV *FalseExpr) {
  5504. assert(CondExpr->getType()->isIntegerTy(1) &&
  5505. TrueExpr->getType() == FalseExpr->getType() &&
  5506. TrueExpr->getType()->isIntegerTy(1) &&
  5507. "Unexpected operands of a select.");
  5508. // i1 cond ? i1 x : i1 C --> C + (i1 cond ? (i1 x - i1 C) : i1 0)
  5509. // --> C + (umin_seq cond, x - C)
  5510. //
  5511. // i1 cond ? i1 C : i1 x --> C + (i1 cond ? i1 0 : (i1 x - i1 C))
  5512. // --> C + (i1 ~cond ? (i1 x - i1 C) : i1 0)
  5513. // --> C + (umin_seq ~cond, x - C)
  5514. // FIXME: while we can't legally model the case where both of the hands
  5515. // are fully variable, we only require that the *difference* is constant.
  5516. if (!isa<SCEVConstant>(TrueExpr) && !isa<SCEVConstant>(FalseExpr))
  5517. return std::nullopt;
  5518. const SCEV *X, *C;
  5519. if (isa<SCEVConstant>(TrueExpr)) {
  5520. CondExpr = SE->getNotSCEV(CondExpr);
  5521. X = FalseExpr;
  5522. C = TrueExpr;
  5523. } else {
  5524. X = TrueExpr;
  5525. C = FalseExpr;
  5526. }
  5527. return SE->getAddExpr(C, SE->getUMinExpr(CondExpr, SE->getMinusSCEV(X, C),
  5528. /*Sequential=*/true));
  5529. }
  5530. static std::optional<const SCEV *>
  5531. createNodeForSelectViaUMinSeq(ScalarEvolution *SE, Value *Cond, Value *TrueVal,
  5532. Value *FalseVal) {
  5533. if (!isa<ConstantInt>(TrueVal) && !isa<ConstantInt>(FalseVal))
  5534. return std::nullopt;
  5535. const auto *SECond = SE->getSCEV(Cond);
  5536. const auto *SETrue = SE->getSCEV(TrueVal);
  5537. const auto *SEFalse = SE->getSCEV(FalseVal);
  5538. return createNodeForSelectViaUMinSeq(SE, SECond, SETrue, SEFalse);
  5539. }
  5540. const SCEV *ScalarEvolution::createNodeForSelectOrPHIViaUMinSeq(
  5541. Value *V, Value *Cond, Value *TrueVal, Value *FalseVal) {
  5542. assert(Cond->getType()->isIntegerTy(1) && "Select condition is not an i1?");
  5543. assert(TrueVal->getType() == FalseVal->getType() &&
  5544. V->getType() == TrueVal->getType() &&
  5545. "Types of select hands and of the result must match.");
  5546. // For now, only deal with i1-typed `select`s.
  5547. if (!V->getType()->isIntegerTy(1))
  5548. return getUnknown(V);
  5549. if (std::optional<const SCEV *> S =
  5550. createNodeForSelectViaUMinSeq(this, Cond, TrueVal, FalseVal))
  5551. return *S;
  5552. return getUnknown(V);
  5553. }
  5554. const SCEV *ScalarEvolution::createNodeForSelectOrPHI(Value *V, Value *Cond,
  5555. Value *TrueVal,
  5556. Value *FalseVal) {
  5557. // Handle "constant" branch or select. This can occur for instance when a
  5558. // loop pass transforms an inner loop and moves on to process the outer loop.
  5559. if (auto *CI = dyn_cast<ConstantInt>(Cond))
  5560. return getSCEV(CI->isOne() ? TrueVal : FalseVal);
  5561. if (auto *I = dyn_cast<Instruction>(V)) {
  5562. if (auto *ICI = dyn_cast<ICmpInst>(Cond)) {
  5563. if (std::optional<const SCEV *> S =
  5564. createNodeForSelectOrPHIInstWithICmpInstCond(I->getType(), ICI,
  5565. TrueVal, FalseVal))
  5566. return *S;
  5567. }
  5568. }
  5569. return createNodeForSelectOrPHIViaUMinSeq(V, Cond, TrueVal, FalseVal);
  5570. }
  5571. /// Expand GEP instructions into add and multiply operations. This allows them
  5572. /// to be analyzed by regular SCEV code.
  5573. const SCEV *ScalarEvolution::createNodeForGEP(GEPOperator *GEP) {
  5574. assert(GEP->getSourceElementType()->isSized() &&
  5575. "GEP source element type must be sized");
  5576. SmallVector<const SCEV *, 4> IndexExprs;
  5577. for (Value *Index : GEP->indices())
  5578. IndexExprs.push_back(getSCEV(Index));
  5579. return getGEPExpr(GEP, IndexExprs);
  5580. }
  5581. uint32_t ScalarEvolution::GetMinTrailingZerosImpl(const SCEV *S) {
  5582. switch (S->getSCEVType()) {
  5583. case scConstant:
  5584. return cast<SCEVConstant>(S)->getAPInt().countTrailingZeros();
  5585. case scTruncate: {
  5586. const SCEVTruncateExpr *T = cast<SCEVTruncateExpr>(S);
  5587. return std::min(GetMinTrailingZeros(T->getOperand()),
  5588. (uint32_t)getTypeSizeInBits(T->getType()));
  5589. }
  5590. case scZeroExtend: {
  5591. const SCEVZeroExtendExpr *E = cast<SCEVZeroExtendExpr>(S);
  5592. uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
  5593. return OpRes == getTypeSizeInBits(E->getOperand()->getType())
  5594. ? getTypeSizeInBits(E->getType())
  5595. : OpRes;
  5596. }
  5597. case scSignExtend: {
  5598. const SCEVSignExtendExpr *E = cast<SCEVSignExtendExpr>(S);
  5599. uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
  5600. return OpRes == getTypeSizeInBits(E->getOperand()->getType())
  5601. ? getTypeSizeInBits(E->getType())
  5602. : OpRes;
  5603. }
  5604. case scMulExpr: {
  5605. const SCEVMulExpr *M = cast<SCEVMulExpr>(S);
  5606. // The result is the sum of all operands results.
  5607. uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
  5608. uint32_t BitWidth = getTypeSizeInBits(M->getType());
  5609. for (unsigned i = 1, e = M->getNumOperands();
  5610. SumOpRes != BitWidth && i != e; ++i)
  5611. SumOpRes =
  5612. std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)), BitWidth);
  5613. return SumOpRes;
  5614. }
  5615. case scUDivExpr:
  5616. return 0;
  5617. case scPtrToInt:
  5618. case scAddExpr:
  5619. case scAddRecExpr:
  5620. case scUMaxExpr:
  5621. case scSMaxExpr:
  5622. case scUMinExpr:
  5623. case scSMinExpr:
  5624. case scSequentialUMinExpr: {
  5625. // The result is the min of all operands results.
  5626. ArrayRef<const SCEV *> Ops = S->operands();
  5627. uint32_t MinOpRes = GetMinTrailingZeros(Ops[0]);
  5628. for (unsigned I = 1, E = Ops.size(); MinOpRes && I != E; ++I)
  5629. MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(Ops[I]));
  5630. return MinOpRes;
  5631. }
  5632. case scUnknown: {
  5633. const SCEVUnknown *U = cast<SCEVUnknown>(S);
  5634. // For a SCEVUnknown, ask ValueTracking.
  5635. KnownBits Known =
  5636. computeKnownBits(U->getValue(), getDataLayout(), 0, &AC, nullptr, &DT);
  5637. return Known.countMinTrailingZeros();
  5638. }
  5639. case scCouldNotCompute:
  5640. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  5641. }
  5642. llvm_unreachable("Unknown SCEV kind!");
  5643. }
  5644. uint32_t ScalarEvolution::GetMinTrailingZeros(const SCEV *S) {
  5645. auto I = MinTrailingZerosCache.find(S);
  5646. if (I != MinTrailingZerosCache.end())
  5647. return I->second;
  5648. uint32_t Result = GetMinTrailingZerosImpl(S);
  5649. auto InsertPair = MinTrailingZerosCache.insert({S, Result});
  5650. assert(InsertPair.second && "Should insert a new key");
  5651. return InsertPair.first->second;
  5652. }
  5653. /// Helper method to assign a range to V from metadata present in the IR.
  5654. static std::optional<ConstantRange> GetRangeFromMetadata(Value *V) {
  5655. if (Instruction *I = dyn_cast<Instruction>(V))
  5656. if (MDNode *MD = I->getMetadata(LLVMContext::MD_range))
  5657. return getConstantRangeFromMetadata(*MD);
  5658. return std::nullopt;
  5659. }
  5660. void ScalarEvolution::setNoWrapFlags(SCEVAddRecExpr *AddRec,
  5661. SCEV::NoWrapFlags Flags) {
  5662. if (AddRec->getNoWrapFlags(Flags) != Flags) {
  5663. AddRec->setNoWrapFlags(Flags);
  5664. UnsignedRanges.erase(AddRec);
  5665. SignedRanges.erase(AddRec);
  5666. }
  5667. }
  5668. ConstantRange ScalarEvolution::
  5669. getRangeForUnknownRecurrence(const SCEVUnknown *U) {
  5670. const DataLayout &DL = getDataLayout();
  5671. unsigned BitWidth = getTypeSizeInBits(U->getType());
  5672. const ConstantRange FullSet(BitWidth, /*isFullSet=*/true);
  5673. // Match a simple recurrence of the form: <start, ShiftOp, Step>, and then
  5674. // use information about the trip count to improve our available range. Note
  5675. // that the trip count independent cases are already handled by known bits.
  5676. // WARNING: The definition of recurrence used here is subtly different than
  5677. // the one used by AddRec (and thus most of this file). Step is allowed to
  5678. // be arbitrarily loop varying here, where AddRec allows only loop invariant
  5679. // and other addrecs in the same loop (for non-affine addrecs). The code
  5680. // below intentionally handles the case where step is not loop invariant.
  5681. auto *P = dyn_cast<PHINode>(U->getValue());
  5682. if (!P)
  5683. return FullSet;
  5684. // Make sure that no Phi input comes from an unreachable block. Otherwise,
  5685. // even the values that are not available in these blocks may come from them,
  5686. // and this leads to false-positive recurrence test.
  5687. for (auto *Pred : predecessors(P->getParent()))
  5688. if (!DT.isReachableFromEntry(Pred))
  5689. return FullSet;
  5690. BinaryOperator *BO;
  5691. Value *Start, *Step;
  5692. if (!matchSimpleRecurrence(P, BO, Start, Step))
  5693. return FullSet;
  5694. // If we found a recurrence in reachable code, we must be in a loop. Note
  5695. // that BO might be in some subloop of L, and that's completely okay.
  5696. auto *L = LI.getLoopFor(P->getParent());
  5697. assert(L && L->getHeader() == P->getParent());
  5698. if (!L->contains(BO->getParent()))
  5699. // NOTE: This bailout should be an assert instead. However, asserting
  5700. // the condition here exposes a case where LoopFusion is querying SCEV
  5701. // with malformed loop information during the midst of the transform.
  5702. // There doesn't appear to be an obvious fix, so for the moment bailout
  5703. // until the caller issue can be fixed. PR49566 tracks the bug.
  5704. return FullSet;
  5705. // TODO: Extend to other opcodes such as mul, and div
  5706. switch (BO->getOpcode()) {
  5707. default:
  5708. return FullSet;
  5709. case Instruction::AShr:
  5710. case Instruction::LShr:
  5711. case Instruction::Shl:
  5712. break;
  5713. };
  5714. if (BO->getOperand(0) != P)
  5715. // TODO: Handle the power function forms some day.
  5716. return FullSet;
  5717. unsigned TC = getSmallConstantMaxTripCount(L);
  5718. if (!TC || TC >= BitWidth)
  5719. return FullSet;
  5720. auto KnownStart = computeKnownBits(Start, DL, 0, &AC, nullptr, &DT);
  5721. auto KnownStep = computeKnownBits(Step, DL, 0, &AC, nullptr, &DT);
  5722. assert(KnownStart.getBitWidth() == BitWidth &&
  5723. KnownStep.getBitWidth() == BitWidth);
  5724. // Compute total shift amount, being careful of overflow and bitwidths.
  5725. auto MaxShiftAmt = KnownStep.getMaxValue();
  5726. APInt TCAP(BitWidth, TC-1);
  5727. bool Overflow = false;
  5728. auto TotalShift = MaxShiftAmt.umul_ov(TCAP, Overflow);
  5729. if (Overflow)
  5730. return FullSet;
  5731. switch (BO->getOpcode()) {
  5732. default:
  5733. llvm_unreachable("filtered out above");
  5734. case Instruction::AShr: {
  5735. // For each ashr, three cases:
  5736. // shift = 0 => unchanged value
  5737. // saturation => 0 or -1
  5738. // other => a value closer to zero (of the same sign)
  5739. // Thus, the end value is closer to zero than the start.
  5740. auto KnownEnd = KnownBits::ashr(KnownStart,
  5741. KnownBits::makeConstant(TotalShift));
  5742. if (KnownStart.isNonNegative())
  5743. // Analogous to lshr (simply not yet canonicalized)
  5744. return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
  5745. KnownStart.getMaxValue() + 1);
  5746. if (KnownStart.isNegative())
  5747. // End >=u Start && End <=s Start
  5748. return ConstantRange::getNonEmpty(KnownStart.getMinValue(),
  5749. KnownEnd.getMaxValue() + 1);
  5750. break;
  5751. }
  5752. case Instruction::LShr: {
  5753. // For each lshr, three cases:
  5754. // shift = 0 => unchanged value
  5755. // saturation => 0
  5756. // other => a smaller positive number
  5757. // Thus, the low end of the unsigned range is the last value produced.
  5758. auto KnownEnd = KnownBits::lshr(KnownStart,
  5759. KnownBits::makeConstant(TotalShift));
  5760. return ConstantRange::getNonEmpty(KnownEnd.getMinValue(),
  5761. KnownStart.getMaxValue() + 1);
  5762. }
  5763. case Instruction::Shl: {
  5764. // Iff no bits are shifted out, value increases on every shift.
  5765. auto KnownEnd = KnownBits::shl(KnownStart,
  5766. KnownBits::makeConstant(TotalShift));
  5767. if (TotalShift.ult(KnownStart.countMinLeadingZeros()))
  5768. return ConstantRange(KnownStart.getMinValue(),
  5769. KnownEnd.getMaxValue() + 1);
  5770. break;
  5771. }
  5772. };
  5773. return FullSet;
  5774. }
  5775. const ConstantRange &
  5776. ScalarEvolution::getRangeRefIter(const SCEV *S,
  5777. ScalarEvolution::RangeSignHint SignHint) {
  5778. DenseMap<const SCEV *, ConstantRange> &Cache =
  5779. SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
  5780. : SignedRanges;
  5781. SmallVector<const SCEV *> WorkList;
  5782. SmallPtrSet<const SCEV *, 8> Seen;
  5783. // Add Expr to the worklist, if Expr is either an N-ary expression or a
  5784. // SCEVUnknown PHI node.
  5785. auto AddToWorklist = [&WorkList, &Seen, &Cache](const SCEV *Expr) {
  5786. if (!Seen.insert(Expr).second)
  5787. return;
  5788. if (Cache.find(Expr) != Cache.end())
  5789. return;
  5790. switch (Expr->getSCEVType()) {
  5791. case scUnknown:
  5792. if (!isa<PHINode>(cast<SCEVUnknown>(Expr)->getValue()))
  5793. break;
  5794. [[fallthrough]];
  5795. case scConstant:
  5796. case scTruncate:
  5797. case scZeroExtend:
  5798. case scSignExtend:
  5799. case scPtrToInt:
  5800. case scAddExpr:
  5801. case scMulExpr:
  5802. case scUDivExpr:
  5803. case scAddRecExpr:
  5804. case scUMaxExpr:
  5805. case scSMaxExpr:
  5806. case scUMinExpr:
  5807. case scSMinExpr:
  5808. case scSequentialUMinExpr:
  5809. WorkList.push_back(Expr);
  5810. break;
  5811. case scCouldNotCompute:
  5812. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  5813. }
  5814. };
  5815. AddToWorklist(S);
  5816. // Build worklist by queuing operands of N-ary expressions and phi nodes.
  5817. for (unsigned I = 0; I != WorkList.size(); ++I) {
  5818. const SCEV *P = WorkList[I];
  5819. auto *UnknownS = dyn_cast<SCEVUnknown>(P);
  5820. // If it is not a `SCEVUnknown`, just recurse into operands.
  5821. if (!UnknownS) {
  5822. for (const SCEV *Op : P->operands())
  5823. AddToWorklist(Op);
  5824. continue;
  5825. }
  5826. // `SCEVUnknown`'s require special treatment.
  5827. if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue())) {
  5828. if (!PendingPhiRangesIter.insert(P).second)
  5829. continue;
  5830. for (auto &Op : reverse(P->operands()))
  5831. AddToWorklist(getSCEV(Op));
  5832. }
  5833. }
  5834. if (!WorkList.empty()) {
  5835. // Use getRangeRef to compute ranges for items in the worklist in reverse
  5836. // order. This will force ranges for earlier operands to be computed before
  5837. // their users in most cases.
  5838. for (const SCEV *P :
  5839. reverse(make_range(WorkList.begin() + 1, WorkList.end()))) {
  5840. getRangeRef(P, SignHint);
  5841. if (auto *UnknownS = dyn_cast<SCEVUnknown>(P))
  5842. if (const PHINode *P = dyn_cast<PHINode>(UnknownS->getValue()))
  5843. PendingPhiRangesIter.erase(P);
  5844. }
  5845. }
  5846. return getRangeRef(S, SignHint, 0);
  5847. }
  5848. /// Determine the range for a particular SCEV. If SignHint is
  5849. /// HINT_RANGE_UNSIGNED (resp. HINT_RANGE_SIGNED) then getRange prefers ranges
  5850. /// with a "cleaner" unsigned (resp. signed) representation.
  5851. const ConstantRange &ScalarEvolution::getRangeRef(
  5852. const SCEV *S, ScalarEvolution::RangeSignHint SignHint, unsigned Depth) {
  5853. DenseMap<const SCEV *, ConstantRange> &Cache =
  5854. SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? UnsignedRanges
  5855. : SignedRanges;
  5856. ConstantRange::PreferredRangeType RangeType =
  5857. SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED ? ConstantRange::Unsigned
  5858. : ConstantRange::Signed;
  5859. // See if we've computed this range already.
  5860. DenseMap<const SCEV *, ConstantRange>::iterator I = Cache.find(S);
  5861. if (I != Cache.end())
  5862. return I->second;
  5863. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S))
  5864. return setRange(C, SignHint, ConstantRange(C->getAPInt()));
  5865. // Switch to iteratively computing the range for S, if it is part of a deeply
  5866. // nested expression.
  5867. if (Depth > RangeIterThreshold)
  5868. return getRangeRefIter(S, SignHint);
  5869. unsigned BitWidth = getTypeSizeInBits(S->getType());
  5870. ConstantRange ConservativeResult(BitWidth, /*isFullSet=*/true);
  5871. using OBO = OverflowingBinaryOperator;
  5872. // If the value has known zeros, the maximum value will have those known zeros
  5873. // as well.
  5874. uint32_t TZ = GetMinTrailingZeros(S);
  5875. if (TZ != 0) {
  5876. if (SignHint == ScalarEvolution::HINT_RANGE_UNSIGNED)
  5877. ConservativeResult =
  5878. ConstantRange(APInt::getMinValue(BitWidth),
  5879. APInt::getMaxValue(BitWidth).lshr(TZ).shl(TZ) + 1);
  5880. else
  5881. ConservativeResult = ConstantRange(
  5882. APInt::getSignedMinValue(BitWidth),
  5883. APInt::getSignedMaxValue(BitWidth).ashr(TZ).shl(TZ) + 1);
  5884. }
  5885. switch (S->getSCEVType()) {
  5886. case scConstant:
  5887. llvm_unreachable("Already handled above.");
  5888. case scTruncate: {
  5889. const SCEVTruncateExpr *Trunc = cast<SCEVTruncateExpr>(S);
  5890. ConstantRange X = getRangeRef(Trunc->getOperand(), SignHint, Depth + 1);
  5891. return setRange(
  5892. Trunc, SignHint,
  5893. ConservativeResult.intersectWith(X.truncate(BitWidth), RangeType));
  5894. }
  5895. case scZeroExtend: {
  5896. const SCEVZeroExtendExpr *ZExt = cast<SCEVZeroExtendExpr>(S);
  5897. ConstantRange X = getRangeRef(ZExt->getOperand(), SignHint, Depth + 1);
  5898. return setRange(
  5899. ZExt, SignHint,
  5900. ConservativeResult.intersectWith(X.zeroExtend(BitWidth), RangeType));
  5901. }
  5902. case scSignExtend: {
  5903. const SCEVSignExtendExpr *SExt = cast<SCEVSignExtendExpr>(S);
  5904. ConstantRange X = getRangeRef(SExt->getOperand(), SignHint, Depth + 1);
  5905. return setRange(
  5906. SExt, SignHint,
  5907. ConservativeResult.intersectWith(X.signExtend(BitWidth), RangeType));
  5908. }
  5909. case scPtrToInt: {
  5910. const SCEVPtrToIntExpr *PtrToInt = cast<SCEVPtrToIntExpr>(S);
  5911. ConstantRange X = getRangeRef(PtrToInt->getOperand(), SignHint, Depth + 1);
  5912. return setRange(PtrToInt, SignHint, X);
  5913. }
  5914. case scAddExpr: {
  5915. const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
  5916. ConstantRange X = getRangeRef(Add->getOperand(0), SignHint, Depth + 1);
  5917. unsigned WrapType = OBO::AnyWrap;
  5918. if (Add->hasNoSignedWrap())
  5919. WrapType |= OBO::NoSignedWrap;
  5920. if (Add->hasNoUnsignedWrap())
  5921. WrapType |= OBO::NoUnsignedWrap;
  5922. for (unsigned i = 1, e = Add->getNumOperands(); i != e; ++i)
  5923. X = X.addWithNoWrap(getRangeRef(Add->getOperand(i), SignHint, Depth + 1),
  5924. WrapType, RangeType);
  5925. return setRange(Add, SignHint,
  5926. ConservativeResult.intersectWith(X, RangeType));
  5927. }
  5928. case scMulExpr: {
  5929. const SCEVMulExpr *Mul = cast<SCEVMulExpr>(S);
  5930. ConstantRange X = getRangeRef(Mul->getOperand(0), SignHint, Depth + 1);
  5931. for (unsigned i = 1, e = Mul->getNumOperands(); i != e; ++i)
  5932. X = X.multiply(getRangeRef(Mul->getOperand(i), SignHint, Depth + 1));
  5933. return setRange(Mul, SignHint,
  5934. ConservativeResult.intersectWith(X, RangeType));
  5935. }
  5936. case scUDivExpr: {
  5937. const SCEVUDivExpr *UDiv = cast<SCEVUDivExpr>(S);
  5938. ConstantRange X = getRangeRef(UDiv->getLHS(), SignHint, Depth + 1);
  5939. ConstantRange Y = getRangeRef(UDiv->getRHS(), SignHint, Depth + 1);
  5940. return setRange(UDiv, SignHint,
  5941. ConservativeResult.intersectWith(X.udiv(Y), RangeType));
  5942. }
  5943. case scAddRecExpr: {
  5944. const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(S);
  5945. // If there's no unsigned wrap, the value will never be less than its
  5946. // initial value.
  5947. if (AddRec->hasNoUnsignedWrap()) {
  5948. APInt UnsignedMinValue = getUnsignedRangeMin(AddRec->getStart());
  5949. if (!UnsignedMinValue.isZero())
  5950. ConservativeResult = ConservativeResult.intersectWith(
  5951. ConstantRange(UnsignedMinValue, APInt(BitWidth, 0)), RangeType);
  5952. }
  5953. // If there's no signed wrap, and all the operands except initial value have
  5954. // the same sign or zero, the value won't ever be:
  5955. // 1: smaller than initial value if operands are non negative,
  5956. // 2: bigger than initial value if operands are non positive.
  5957. // For both cases, value can not cross signed min/max boundary.
  5958. if (AddRec->hasNoSignedWrap()) {
  5959. bool AllNonNeg = true;
  5960. bool AllNonPos = true;
  5961. for (unsigned i = 1, e = AddRec->getNumOperands(); i != e; ++i) {
  5962. if (!isKnownNonNegative(AddRec->getOperand(i)))
  5963. AllNonNeg = false;
  5964. if (!isKnownNonPositive(AddRec->getOperand(i)))
  5965. AllNonPos = false;
  5966. }
  5967. if (AllNonNeg)
  5968. ConservativeResult = ConservativeResult.intersectWith(
  5969. ConstantRange::getNonEmpty(getSignedRangeMin(AddRec->getStart()),
  5970. APInt::getSignedMinValue(BitWidth)),
  5971. RangeType);
  5972. else if (AllNonPos)
  5973. ConservativeResult = ConservativeResult.intersectWith(
  5974. ConstantRange::getNonEmpty(APInt::getSignedMinValue(BitWidth),
  5975. getSignedRangeMax(AddRec->getStart()) +
  5976. 1),
  5977. RangeType);
  5978. }
  5979. // TODO: non-affine addrec
  5980. if (AddRec->isAffine()) {
  5981. const SCEV *MaxBECount =
  5982. getConstantMaxBackedgeTakenCount(AddRec->getLoop());
  5983. if (!isa<SCEVCouldNotCompute>(MaxBECount) &&
  5984. getTypeSizeInBits(MaxBECount->getType()) <= BitWidth) {
  5985. auto RangeFromAffine = getRangeForAffineAR(
  5986. AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
  5987. BitWidth);
  5988. ConservativeResult =
  5989. ConservativeResult.intersectWith(RangeFromAffine, RangeType);
  5990. auto RangeFromFactoring = getRangeViaFactoring(
  5991. AddRec->getStart(), AddRec->getStepRecurrence(*this), MaxBECount,
  5992. BitWidth);
  5993. ConservativeResult =
  5994. ConservativeResult.intersectWith(RangeFromFactoring, RangeType);
  5995. }
  5996. // Now try symbolic BE count and more powerful methods.
  5997. if (UseExpensiveRangeSharpening) {
  5998. const SCEV *SymbolicMaxBECount =
  5999. getSymbolicMaxBackedgeTakenCount(AddRec->getLoop());
  6000. if (!isa<SCEVCouldNotCompute>(SymbolicMaxBECount) &&
  6001. getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
  6002. AddRec->hasNoSelfWrap()) {
  6003. auto RangeFromAffineNew = getRangeForAffineNoSelfWrappingAR(
  6004. AddRec, SymbolicMaxBECount, BitWidth, SignHint);
  6005. ConservativeResult =
  6006. ConservativeResult.intersectWith(RangeFromAffineNew, RangeType);
  6007. }
  6008. }
  6009. }
  6010. return setRange(AddRec, SignHint, std::move(ConservativeResult));
  6011. }
  6012. case scUMaxExpr:
  6013. case scSMaxExpr:
  6014. case scUMinExpr:
  6015. case scSMinExpr:
  6016. case scSequentialUMinExpr: {
  6017. Intrinsic::ID ID;
  6018. switch (S->getSCEVType()) {
  6019. case scUMaxExpr:
  6020. ID = Intrinsic::umax;
  6021. break;
  6022. case scSMaxExpr:
  6023. ID = Intrinsic::smax;
  6024. break;
  6025. case scUMinExpr:
  6026. case scSequentialUMinExpr:
  6027. ID = Intrinsic::umin;
  6028. break;
  6029. case scSMinExpr:
  6030. ID = Intrinsic::smin;
  6031. break;
  6032. default:
  6033. llvm_unreachable("Unknown SCEVMinMaxExpr/SCEVSequentialMinMaxExpr.");
  6034. }
  6035. const auto *NAry = cast<SCEVNAryExpr>(S);
  6036. ConstantRange X = getRangeRef(NAry->getOperand(0), SignHint, Depth + 1);
  6037. for (unsigned i = 1, e = NAry->getNumOperands(); i != e; ++i)
  6038. X = X.intrinsic(
  6039. ID, {X, getRangeRef(NAry->getOperand(i), SignHint, Depth + 1)});
  6040. return setRange(S, SignHint,
  6041. ConservativeResult.intersectWith(X, RangeType));
  6042. }
  6043. case scUnknown: {
  6044. const SCEVUnknown *U = cast<SCEVUnknown>(S);
  6045. // Check if the IR explicitly contains !range metadata.
  6046. std::optional<ConstantRange> MDRange = GetRangeFromMetadata(U->getValue());
  6047. if (MDRange)
  6048. ConservativeResult =
  6049. ConservativeResult.intersectWith(*MDRange, RangeType);
  6050. // Use facts about recurrences in the underlying IR. Note that add
  6051. // recurrences are AddRecExprs and thus don't hit this path. This
  6052. // primarily handles shift recurrences.
  6053. auto CR = getRangeForUnknownRecurrence(U);
  6054. ConservativeResult = ConservativeResult.intersectWith(CR);
  6055. // See if ValueTracking can give us a useful range.
  6056. const DataLayout &DL = getDataLayout();
  6057. KnownBits Known = computeKnownBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
  6058. if (Known.getBitWidth() != BitWidth)
  6059. Known = Known.zextOrTrunc(BitWidth);
  6060. // ValueTracking may be able to compute a tighter result for the number of
  6061. // sign bits than for the value of those sign bits.
  6062. unsigned NS = ComputeNumSignBits(U->getValue(), DL, 0, &AC, nullptr, &DT);
  6063. if (U->getType()->isPointerTy()) {
  6064. // If the pointer size is larger than the index size type, this can cause
  6065. // NS to be larger than BitWidth. So compensate for this.
  6066. unsigned ptrSize = DL.getPointerTypeSizeInBits(U->getType());
  6067. int ptrIdxDiff = ptrSize - BitWidth;
  6068. if (ptrIdxDiff > 0 && ptrSize > BitWidth && NS > (unsigned)ptrIdxDiff)
  6069. NS -= ptrIdxDiff;
  6070. }
  6071. if (NS > 1) {
  6072. // If we know any of the sign bits, we know all of the sign bits.
  6073. if (!Known.Zero.getHiBits(NS).isZero())
  6074. Known.Zero.setHighBits(NS);
  6075. if (!Known.One.getHiBits(NS).isZero())
  6076. Known.One.setHighBits(NS);
  6077. }
  6078. if (Known.getMinValue() != Known.getMaxValue() + 1)
  6079. ConservativeResult = ConservativeResult.intersectWith(
  6080. ConstantRange(Known.getMinValue(), Known.getMaxValue() + 1),
  6081. RangeType);
  6082. if (NS > 1)
  6083. ConservativeResult = ConservativeResult.intersectWith(
  6084. ConstantRange(APInt::getSignedMinValue(BitWidth).ashr(NS - 1),
  6085. APInt::getSignedMaxValue(BitWidth).ashr(NS - 1) + 1),
  6086. RangeType);
  6087. // A range of Phi is a subset of union of all ranges of its input.
  6088. if (PHINode *Phi = dyn_cast<PHINode>(U->getValue())) {
  6089. // Make sure that we do not run over cycled Phis.
  6090. if (PendingPhiRanges.insert(Phi).second) {
  6091. ConstantRange RangeFromOps(BitWidth, /*isFullSet=*/false);
  6092. for (const auto &Op : Phi->operands()) {
  6093. auto OpRange = getRangeRef(getSCEV(Op), SignHint, Depth + 1);
  6094. RangeFromOps = RangeFromOps.unionWith(OpRange);
  6095. // No point to continue if we already have a full set.
  6096. if (RangeFromOps.isFullSet())
  6097. break;
  6098. }
  6099. ConservativeResult =
  6100. ConservativeResult.intersectWith(RangeFromOps, RangeType);
  6101. bool Erased = PendingPhiRanges.erase(Phi);
  6102. assert(Erased && "Failed to erase Phi properly?");
  6103. (void)Erased;
  6104. }
  6105. }
  6106. // vscale can't be equal to zero
  6107. if (const auto *II = dyn_cast<IntrinsicInst>(U->getValue()))
  6108. if (II->getIntrinsicID() == Intrinsic::vscale) {
  6109. ConstantRange Disallowed = APInt::getZero(BitWidth);
  6110. ConservativeResult = ConservativeResult.difference(Disallowed);
  6111. }
  6112. return setRange(U, SignHint, std::move(ConservativeResult));
  6113. }
  6114. case scCouldNotCompute:
  6115. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  6116. }
  6117. return setRange(S, SignHint, std::move(ConservativeResult));
  6118. }
  6119. // Given a StartRange, Step and MaxBECount for an expression compute a range of
  6120. // values that the expression can take. Initially, the expression has a value
  6121. // from StartRange and then is changed by Step up to MaxBECount times. Signed
  6122. // argument defines if we treat Step as signed or unsigned.
  6123. static ConstantRange getRangeForAffineARHelper(APInt Step,
  6124. const ConstantRange &StartRange,
  6125. const APInt &MaxBECount,
  6126. unsigned BitWidth, bool Signed) {
  6127. // If either Step or MaxBECount is 0, then the expression won't change, and we
  6128. // just need to return the initial range.
  6129. if (Step == 0 || MaxBECount == 0)
  6130. return StartRange;
  6131. // If we don't know anything about the initial value (i.e. StartRange is
  6132. // FullRange), then we don't know anything about the final range either.
  6133. // Return FullRange.
  6134. if (StartRange.isFullSet())
  6135. return ConstantRange::getFull(BitWidth);
  6136. // If Step is signed and negative, then we use its absolute value, but we also
  6137. // note that we're moving in the opposite direction.
  6138. bool Descending = Signed && Step.isNegative();
  6139. if (Signed)
  6140. // This is correct even for INT_SMIN. Let's look at i8 to illustrate this:
  6141. // abs(INT_SMIN) = abs(-128) = abs(0x80) = -0x80 = 0x80 = 128.
  6142. // This equations hold true due to the well-defined wrap-around behavior of
  6143. // APInt.
  6144. Step = Step.abs();
  6145. // Check if Offset is more than full span of BitWidth. If it is, the
  6146. // expression is guaranteed to overflow.
  6147. if (APInt::getMaxValue(StartRange.getBitWidth()).udiv(Step).ult(MaxBECount))
  6148. return ConstantRange::getFull(BitWidth);
  6149. // Offset is by how much the expression can change. Checks above guarantee no
  6150. // overflow here.
  6151. APInt Offset = Step * MaxBECount;
  6152. // Minimum value of the final range will match the minimal value of StartRange
  6153. // if the expression is increasing and will be decreased by Offset otherwise.
  6154. // Maximum value of the final range will match the maximal value of StartRange
  6155. // if the expression is decreasing and will be increased by Offset otherwise.
  6156. APInt StartLower = StartRange.getLower();
  6157. APInt StartUpper = StartRange.getUpper() - 1;
  6158. APInt MovedBoundary = Descending ? (StartLower - std::move(Offset))
  6159. : (StartUpper + std::move(Offset));
  6160. // It's possible that the new minimum/maximum value will fall into the initial
  6161. // range (due to wrap around). This means that the expression can take any
  6162. // value in this bitwidth, and we have to return full range.
  6163. if (StartRange.contains(MovedBoundary))
  6164. return ConstantRange::getFull(BitWidth);
  6165. APInt NewLower =
  6166. Descending ? std::move(MovedBoundary) : std::move(StartLower);
  6167. APInt NewUpper =
  6168. Descending ? std::move(StartUpper) : std::move(MovedBoundary);
  6169. NewUpper += 1;
  6170. // No overflow detected, return [StartLower, StartUpper + Offset + 1) range.
  6171. return ConstantRange::getNonEmpty(std::move(NewLower), std::move(NewUpper));
  6172. }
  6173. ConstantRange ScalarEvolution::getRangeForAffineAR(const SCEV *Start,
  6174. const SCEV *Step,
  6175. const SCEV *MaxBECount,
  6176. unsigned BitWidth) {
  6177. assert(!isa<SCEVCouldNotCompute>(MaxBECount) &&
  6178. getTypeSizeInBits(MaxBECount->getType()) <= BitWidth &&
  6179. "Precondition!");
  6180. MaxBECount = getNoopOrZeroExtend(MaxBECount, Start->getType());
  6181. APInt MaxBECountValue = getUnsignedRangeMax(MaxBECount);
  6182. // First, consider step signed.
  6183. ConstantRange StartSRange = getSignedRange(Start);
  6184. ConstantRange StepSRange = getSignedRange(Step);
  6185. // If Step can be both positive and negative, we need to find ranges for the
  6186. // maximum absolute step values in both directions and union them.
  6187. ConstantRange SR =
  6188. getRangeForAffineARHelper(StepSRange.getSignedMin(), StartSRange,
  6189. MaxBECountValue, BitWidth, /* Signed = */ true);
  6190. SR = SR.unionWith(getRangeForAffineARHelper(StepSRange.getSignedMax(),
  6191. StartSRange, MaxBECountValue,
  6192. BitWidth, /* Signed = */ true));
  6193. // Next, consider step unsigned.
  6194. ConstantRange UR = getRangeForAffineARHelper(
  6195. getUnsignedRangeMax(Step), getUnsignedRange(Start),
  6196. MaxBECountValue, BitWidth, /* Signed = */ false);
  6197. // Finally, intersect signed and unsigned ranges.
  6198. return SR.intersectWith(UR, ConstantRange::Smallest);
  6199. }
  6200. ConstantRange ScalarEvolution::getRangeForAffineNoSelfWrappingAR(
  6201. const SCEVAddRecExpr *AddRec, const SCEV *MaxBECount, unsigned BitWidth,
  6202. ScalarEvolution::RangeSignHint SignHint) {
  6203. assert(AddRec->isAffine() && "Non-affine AddRecs are not suppored!\n");
  6204. assert(AddRec->hasNoSelfWrap() &&
  6205. "This only works for non-self-wrapping AddRecs!");
  6206. const bool IsSigned = SignHint == HINT_RANGE_SIGNED;
  6207. const SCEV *Step = AddRec->getStepRecurrence(*this);
  6208. // Only deal with constant step to save compile time.
  6209. if (!isa<SCEVConstant>(Step))
  6210. return ConstantRange::getFull(BitWidth);
  6211. // Let's make sure that we can prove that we do not self-wrap during
  6212. // MaxBECount iterations. We need this because MaxBECount is a maximum
  6213. // iteration count estimate, and we might infer nw from some exit for which we
  6214. // do not know max exit count (or any other side reasoning).
  6215. // TODO: Turn into assert at some point.
  6216. if (getTypeSizeInBits(MaxBECount->getType()) >
  6217. getTypeSizeInBits(AddRec->getType()))
  6218. return ConstantRange::getFull(BitWidth);
  6219. MaxBECount = getNoopOrZeroExtend(MaxBECount, AddRec->getType());
  6220. const SCEV *RangeWidth = getMinusOne(AddRec->getType());
  6221. const SCEV *StepAbs = getUMinExpr(Step, getNegativeSCEV(Step));
  6222. const SCEV *MaxItersWithoutWrap = getUDivExpr(RangeWidth, StepAbs);
  6223. if (!isKnownPredicateViaConstantRanges(ICmpInst::ICMP_ULE, MaxBECount,
  6224. MaxItersWithoutWrap))
  6225. return ConstantRange::getFull(BitWidth);
  6226. ICmpInst::Predicate LEPred =
  6227. IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
  6228. ICmpInst::Predicate GEPred =
  6229. IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
  6230. const SCEV *End = AddRec->evaluateAtIteration(MaxBECount, *this);
  6231. // We know that there is no self-wrap. Let's take Start and End values and
  6232. // look at all intermediate values V1, V2, ..., Vn that IndVar takes during
  6233. // the iteration. They either lie inside the range [Min(Start, End),
  6234. // Max(Start, End)] or outside it:
  6235. //
  6236. // Case 1: RangeMin ... Start V1 ... VN End ... RangeMax;
  6237. // Case 2: RangeMin Vk ... V1 Start ... End Vn ... Vk + 1 RangeMax;
  6238. //
  6239. // No self wrap flag guarantees that the intermediate values cannot be BOTH
  6240. // outside and inside the range [Min(Start, End), Max(Start, End)]. Using that
  6241. // knowledge, let's try to prove that we are dealing with Case 1. It is so if
  6242. // Start <= End and step is positive, or Start >= End and step is negative.
  6243. const SCEV *Start = AddRec->getStart();
  6244. ConstantRange StartRange = getRangeRef(Start, SignHint);
  6245. ConstantRange EndRange = getRangeRef(End, SignHint);
  6246. ConstantRange RangeBetween = StartRange.unionWith(EndRange);
  6247. // If they already cover full iteration space, we will know nothing useful
  6248. // even if we prove what we want to prove.
  6249. if (RangeBetween.isFullSet())
  6250. return RangeBetween;
  6251. // Only deal with ranges that do not wrap (i.e. RangeMin < RangeMax).
  6252. bool IsWrappedSet = IsSigned ? RangeBetween.isSignWrappedSet()
  6253. : RangeBetween.isWrappedSet();
  6254. if (IsWrappedSet)
  6255. return ConstantRange::getFull(BitWidth);
  6256. if (isKnownPositive(Step) &&
  6257. isKnownPredicateViaConstantRanges(LEPred, Start, End))
  6258. return RangeBetween;
  6259. else if (isKnownNegative(Step) &&
  6260. isKnownPredicateViaConstantRanges(GEPred, Start, End))
  6261. return RangeBetween;
  6262. return ConstantRange::getFull(BitWidth);
  6263. }
  6264. ConstantRange ScalarEvolution::getRangeViaFactoring(const SCEV *Start,
  6265. const SCEV *Step,
  6266. const SCEV *MaxBECount,
  6267. unsigned BitWidth) {
  6268. // RangeOf({C?A:B,+,C?P:Q}) == RangeOf(C?{A,+,P}:{B,+,Q})
  6269. // == RangeOf({A,+,P}) union RangeOf({B,+,Q})
  6270. struct SelectPattern {
  6271. Value *Condition = nullptr;
  6272. APInt TrueValue;
  6273. APInt FalseValue;
  6274. explicit SelectPattern(ScalarEvolution &SE, unsigned BitWidth,
  6275. const SCEV *S) {
  6276. std::optional<unsigned> CastOp;
  6277. APInt Offset(BitWidth, 0);
  6278. assert(SE.getTypeSizeInBits(S->getType()) == BitWidth &&
  6279. "Should be!");
  6280. // Peel off a constant offset:
  6281. if (auto *SA = dyn_cast<SCEVAddExpr>(S)) {
  6282. // In the future we could consider being smarter here and handle
  6283. // {Start+Step,+,Step} too.
  6284. if (SA->getNumOperands() != 2 || !isa<SCEVConstant>(SA->getOperand(0)))
  6285. return;
  6286. Offset = cast<SCEVConstant>(SA->getOperand(0))->getAPInt();
  6287. S = SA->getOperand(1);
  6288. }
  6289. // Peel off a cast operation
  6290. if (auto *SCast = dyn_cast<SCEVIntegralCastExpr>(S)) {
  6291. CastOp = SCast->getSCEVType();
  6292. S = SCast->getOperand();
  6293. }
  6294. using namespace llvm::PatternMatch;
  6295. auto *SU = dyn_cast<SCEVUnknown>(S);
  6296. const APInt *TrueVal, *FalseVal;
  6297. if (!SU ||
  6298. !match(SU->getValue(), m_Select(m_Value(Condition), m_APInt(TrueVal),
  6299. m_APInt(FalseVal)))) {
  6300. Condition = nullptr;
  6301. return;
  6302. }
  6303. TrueValue = *TrueVal;
  6304. FalseValue = *FalseVal;
  6305. // Re-apply the cast we peeled off earlier
  6306. if (CastOp)
  6307. switch (*CastOp) {
  6308. default:
  6309. llvm_unreachable("Unknown SCEV cast type!");
  6310. case scTruncate:
  6311. TrueValue = TrueValue.trunc(BitWidth);
  6312. FalseValue = FalseValue.trunc(BitWidth);
  6313. break;
  6314. case scZeroExtend:
  6315. TrueValue = TrueValue.zext(BitWidth);
  6316. FalseValue = FalseValue.zext(BitWidth);
  6317. break;
  6318. case scSignExtend:
  6319. TrueValue = TrueValue.sext(BitWidth);
  6320. FalseValue = FalseValue.sext(BitWidth);
  6321. break;
  6322. }
  6323. // Re-apply the constant offset we peeled off earlier
  6324. TrueValue += Offset;
  6325. FalseValue += Offset;
  6326. }
  6327. bool isRecognized() { return Condition != nullptr; }
  6328. };
  6329. SelectPattern StartPattern(*this, BitWidth, Start);
  6330. if (!StartPattern.isRecognized())
  6331. return ConstantRange::getFull(BitWidth);
  6332. SelectPattern StepPattern(*this, BitWidth, Step);
  6333. if (!StepPattern.isRecognized())
  6334. return ConstantRange::getFull(BitWidth);
  6335. if (StartPattern.Condition != StepPattern.Condition) {
  6336. // We don't handle this case today; but we could, by considering four
  6337. // possibilities below instead of two. I'm not sure if there are cases where
  6338. // that will help over what getRange already does, though.
  6339. return ConstantRange::getFull(BitWidth);
  6340. }
  6341. // NB! Calling ScalarEvolution::getConstant is fine, but we should not try to
  6342. // construct arbitrary general SCEV expressions here. This function is called
  6343. // from deep in the call stack, and calling getSCEV (on a sext instruction,
  6344. // say) can end up caching a suboptimal value.
  6345. // FIXME: without the explicit `this` receiver below, MSVC errors out with
  6346. // C2352 and C2512 (otherwise it isn't needed).
  6347. const SCEV *TrueStart = this->getConstant(StartPattern.TrueValue);
  6348. const SCEV *TrueStep = this->getConstant(StepPattern.TrueValue);
  6349. const SCEV *FalseStart = this->getConstant(StartPattern.FalseValue);
  6350. const SCEV *FalseStep = this->getConstant(StepPattern.FalseValue);
  6351. ConstantRange TrueRange =
  6352. this->getRangeForAffineAR(TrueStart, TrueStep, MaxBECount, BitWidth);
  6353. ConstantRange FalseRange =
  6354. this->getRangeForAffineAR(FalseStart, FalseStep, MaxBECount, BitWidth);
  6355. return TrueRange.unionWith(FalseRange);
  6356. }
  6357. SCEV::NoWrapFlags ScalarEvolution::getNoWrapFlagsFromUB(const Value *V) {
  6358. if (isa<ConstantExpr>(V)) return SCEV::FlagAnyWrap;
  6359. const BinaryOperator *BinOp = cast<BinaryOperator>(V);
  6360. // Return early if there are no flags to propagate to the SCEV.
  6361. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
  6362. if (BinOp->hasNoUnsignedWrap())
  6363. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNUW);
  6364. if (BinOp->hasNoSignedWrap())
  6365. Flags = ScalarEvolution::setFlags(Flags, SCEV::FlagNSW);
  6366. if (Flags == SCEV::FlagAnyWrap)
  6367. return SCEV::FlagAnyWrap;
  6368. return isSCEVExprNeverPoison(BinOp) ? Flags : SCEV::FlagAnyWrap;
  6369. }
  6370. const Instruction *
  6371. ScalarEvolution::getNonTrivialDefiningScopeBound(const SCEV *S) {
  6372. if (auto *AddRec = dyn_cast<SCEVAddRecExpr>(S))
  6373. return &*AddRec->getLoop()->getHeader()->begin();
  6374. if (auto *U = dyn_cast<SCEVUnknown>(S))
  6375. if (auto *I = dyn_cast<Instruction>(U->getValue()))
  6376. return I;
  6377. return nullptr;
  6378. }
  6379. const Instruction *
  6380. ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops,
  6381. bool &Precise) {
  6382. Precise = true;
  6383. // Do a bounded search of the def relation of the requested SCEVs.
  6384. SmallSet<const SCEV *, 16> Visited;
  6385. SmallVector<const SCEV *> Worklist;
  6386. auto pushOp = [&](const SCEV *S) {
  6387. if (!Visited.insert(S).second)
  6388. return;
  6389. // Threshold of 30 here is arbitrary.
  6390. if (Visited.size() > 30) {
  6391. Precise = false;
  6392. return;
  6393. }
  6394. Worklist.push_back(S);
  6395. };
  6396. for (const auto *S : Ops)
  6397. pushOp(S);
  6398. const Instruction *Bound = nullptr;
  6399. while (!Worklist.empty()) {
  6400. auto *S = Worklist.pop_back_val();
  6401. if (auto *DefI = getNonTrivialDefiningScopeBound(S)) {
  6402. if (!Bound || DT.dominates(Bound, DefI))
  6403. Bound = DefI;
  6404. } else {
  6405. for (const auto *Op : S->operands())
  6406. pushOp(Op);
  6407. }
  6408. }
  6409. return Bound ? Bound : &*F.getEntryBlock().begin();
  6410. }
  6411. const Instruction *
  6412. ScalarEvolution::getDefiningScopeBound(ArrayRef<const SCEV *> Ops) {
  6413. bool Discard;
  6414. return getDefiningScopeBound(Ops, Discard);
  6415. }
  6416. bool ScalarEvolution::isGuaranteedToTransferExecutionTo(const Instruction *A,
  6417. const Instruction *B) {
  6418. if (A->getParent() == B->getParent() &&
  6419. isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
  6420. B->getIterator()))
  6421. return true;
  6422. auto *BLoop = LI.getLoopFor(B->getParent());
  6423. if (BLoop && BLoop->getHeader() == B->getParent() &&
  6424. BLoop->getLoopPreheader() == A->getParent() &&
  6425. isGuaranteedToTransferExecutionToSuccessor(A->getIterator(),
  6426. A->getParent()->end()) &&
  6427. isGuaranteedToTransferExecutionToSuccessor(B->getParent()->begin(),
  6428. B->getIterator()))
  6429. return true;
  6430. return false;
  6431. }
  6432. bool ScalarEvolution::isSCEVExprNeverPoison(const Instruction *I) {
  6433. // Only proceed if we can prove that I does not yield poison.
  6434. if (!programUndefinedIfPoison(I))
  6435. return false;
  6436. // At this point we know that if I is executed, then it does not wrap
  6437. // according to at least one of NSW or NUW. If I is not executed, then we do
  6438. // not know if the calculation that I represents would wrap. Multiple
  6439. // instructions can map to the same SCEV. If we apply NSW or NUW from I to
  6440. // the SCEV, we must guarantee no wrapping for that SCEV also when it is
  6441. // derived from other instructions that map to the same SCEV. We cannot make
  6442. // that guarantee for cases where I is not executed. So we need to find a
  6443. // upper bound on the defining scope for the SCEV, and prove that I is
  6444. // executed every time we enter that scope. When the bounding scope is a
  6445. // loop (the common case), this is equivalent to proving I executes on every
  6446. // iteration of that loop.
  6447. SmallVector<const SCEV *> SCEVOps;
  6448. for (const Use &Op : I->operands()) {
  6449. // I could be an extractvalue from a call to an overflow intrinsic.
  6450. // TODO: We can do better here in some cases.
  6451. if (isSCEVable(Op->getType()))
  6452. SCEVOps.push_back(getSCEV(Op));
  6453. }
  6454. auto *DefI = getDefiningScopeBound(SCEVOps);
  6455. return isGuaranteedToTransferExecutionTo(DefI, I);
  6456. }
  6457. bool ScalarEvolution::isAddRecNeverPoison(const Instruction *I, const Loop *L) {
  6458. // If we know that \c I can never be poison period, then that's enough.
  6459. if (isSCEVExprNeverPoison(I))
  6460. return true;
  6461. // For an add recurrence specifically, we assume that infinite loops without
  6462. // side effects are undefined behavior, and then reason as follows:
  6463. //
  6464. // If the add recurrence is poison in any iteration, it is poison on all
  6465. // future iterations (since incrementing poison yields poison). If the result
  6466. // of the add recurrence is fed into the loop latch condition and the loop
  6467. // does not contain any throws or exiting blocks other than the latch, we now
  6468. // have the ability to "choose" whether the backedge is taken or not (by
  6469. // choosing a sufficiently evil value for the poison feeding into the branch)
  6470. // for every iteration including and after the one in which \p I first became
  6471. // poison. There are two possibilities (let's call the iteration in which \p
  6472. // I first became poison as K):
  6473. //
  6474. // 1. In the set of iterations including and after K, the loop body executes
  6475. // no side effects. In this case executing the backege an infinte number
  6476. // of times will yield undefined behavior.
  6477. //
  6478. // 2. In the set of iterations including and after K, the loop body executes
  6479. // at least one side effect. In this case, that specific instance of side
  6480. // effect is control dependent on poison, which also yields undefined
  6481. // behavior.
  6482. auto *ExitingBB = L->getExitingBlock();
  6483. auto *LatchBB = L->getLoopLatch();
  6484. if (!ExitingBB || !LatchBB || ExitingBB != LatchBB)
  6485. return false;
  6486. SmallPtrSet<const Instruction *, 16> Pushed;
  6487. SmallVector<const Instruction *, 8> PoisonStack;
  6488. // We start by assuming \c I, the post-inc add recurrence, is poison. Only
  6489. // things that are known to be poison under that assumption go on the
  6490. // PoisonStack.
  6491. Pushed.insert(I);
  6492. PoisonStack.push_back(I);
  6493. bool LatchControlDependentOnPoison = false;
  6494. while (!PoisonStack.empty() && !LatchControlDependentOnPoison) {
  6495. const Instruction *Poison = PoisonStack.pop_back_val();
  6496. for (const Use &U : Poison->uses()) {
  6497. const User *PoisonUser = U.getUser();
  6498. if (propagatesPoison(U)) {
  6499. if (Pushed.insert(cast<Instruction>(PoisonUser)).second)
  6500. PoisonStack.push_back(cast<Instruction>(PoisonUser));
  6501. } else if (auto *BI = dyn_cast<BranchInst>(PoisonUser)) {
  6502. assert(BI->isConditional() && "Only possibility!");
  6503. if (BI->getParent() == LatchBB) {
  6504. LatchControlDependentOnPoison = true;
  6505. break;
  6506. }
  6507. }
  6508. }
  6509. }
  6510. return LatchControlDependentOnPoison && loopHasNoAbnormalExits(L);
  6511. }
  6512. ScalarEvolution::LoopProperties
  6513. ScalarEvolution::getLoopProperties(const Loop *L) {
  6514. using LoopProperties = ScalarEvolution::LoopProperties;
  6515. auto Itr = LoopPropertiesCache.find(L);
  6516. if (Itr == LoopPropertiesCache.end()) {
  6517. auto HasSideEffects = [](Instruction *I) {
  6518. if (auto *SI = dyn_cast<StoreInst>(I))
  6519. return !SI->isSimple();
  6520. return I->mayThrow() || I->mayWriteToMemory();
  6521. };
  6522. LoopProperties LP = {/* HasNoAbnormalExits */ true,
  6523. /*HasNoSideEffects*/ true};
  6524. for (auto *BB : L->getBlocks())
  6525. for (auto &I : *BB) {
  6526. if (!isGuaranteedToTransferExecutionToSuccessor(&I))
  6527. LP.HasNoAbnormalExits = false;
  6528. if (HasSideEffects(&I))
  6529. LP.HasNoSideEffects = false;
  6530. if (!LP.HasNoAbnormalExits && !LP.HasNoSideEffects)
  6531. break; // We're already as pessimistic as we can get.
  6532. }
  6533. auto InsertPair = LoopPropertiesCache.insert({L, LP});
  6534. assert(InsertPair.second && "We just checked!");
  6535. Itr = InsertPair.first;
  6536. }
  6537. return Itr->second;
  6538. }
  6539. bool ScalarEvolution::loopIsFiniteByAssumption(const Loop *L) {
  6540. // A mustprogress loop without side effects must be finite.
  6541. // TODO: The check used here is very conservative. It's only *specific*
  6542. // side effects which are well defined in infinite loops.
  6543. return isFinite(L) || (isMustProgress(L) && loopHasNoSideEffects(L));
  6544. }
  6545. const SCEV *ScalarEvolution::createSCEVIter(Value *V) {
  6546. // Worklist item with a Value and a bool indicating whether all operands have
  6547. // been visited already.
  6548. using PointerTy = PointerIntPair<Value *, 1, bool>;
  6549. SmallVector<PointerTy> Stack;
  6550. Stack.emplace_back(V, true);
  6551. Stack.emplace_back(V, false);
  6552. while (!Stack.empty()) {
  6553. auto E = Stack.pop_back_val();
  6554. Value *CurV = E.getPointer();
  6555. if (getExistingSCEV(CurV))
  6556. continue;
  6557. SmallVector<Value *> Ops;
  6558. const SCEV *CreatedSCEV = nullptr;
  6559. // If all operands have been visited already, create the SCEV.
  6560. if (E.getInt()) {
  6561. CreatedSCEV = createSCEV(CurV);
  6562. } else {
  6563. // Otherwise get the operands we need to create SCEV's for before creating
  6564. // the SCEV for CurV. If the SCEV for CurV can be constructed trivially,
  6565. // just use it.
  6566. CreatedSCEV = getOperandsToCreate(CurV, Ops);
  6567. }
  6568. if (CreatedSCEV) {
  6569. insertValueToMap(CurV, CreatedSCEV);
  6570. } else {
  6571. // Queue CurV for SCEV creation, followed by its's operands which need to
  6572. // be constructed first.
  6573. Stack.emplace_back(CurV, true);
  6574. for (Value *Op : Ops)
  6575. Stack.emplace_back(Op, false);
  6576. }
  6577. }
  6578. return getExistingSCEV(V);
  6579. }
  6580. const SCEV *
  6581. ScalarEvolution::getOperandsToCreate(Value *V, SmallVectorImpl<Value *> &Ops) {
  6582. if (!isSCEVable(V->getType()))
  6583. return getUnknown(V);
  6584. if (Instruction *I = dyn_cast<Instruction>(V)) {
  6585. // Don't attempt to analyze instructions in blocks that aren't
  6586. // reachable. Such instructions don't matter, and they aren't required
  6587. // to obey basic rules for definitions dominating uses which this
  6588. // analysis depends on.
  6589. if (!DT.isReachableFromEntry(I->getParent()))
  6590. return getUnknown(PoisonValue::get(V->getType()));
  6591. } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
  6592. return getConstant(CI);
  6593. else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V)) {
  6594. if (!GA->isInterposable()) {
  6595. Ops.push_back(GA->getAliasee());
  6596. return nullptr;
  6597. }
  6598. return getUnknown(V);
  6599. } else if (!isa<ConstantExpr>(V))
  6600. return getUnknown(V);
  6601. Operator *U = cast<Operator>(V);
  6602. if (auto BO =
  6603. MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
  6604. bool IsConstArg = isa<ConstantInt>(BO->RHS);
  6605. switch (BO->Opcode) {
  6606. case Instruction::Add:
  6607. case Instruction::Mul: {
  6608. // For additions and multiplications, traverse add/mul chains for which we
  6609. // can potentially create a single SCEV, to reduce the number of
  6610. // get{Add,Mul}Expr calls.
  6611. do {
  6612. if (BO->Op) {
  6613. if (BO->Op != V && getExistingSCEV(BO->Op)) {
  6614. Ops.push_back(BO->Op);
  6615. break;
  6616. }
  6617. }
  6618. Ops.push_back(BO->RHS);
  6619. auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
  6620. dyn_cast<Instruction>(V));
  6621. if (!NewBO ||
  6622. (U->getOpcode() == Instruction::Add &&
  6623. (NewBO->Opcode != Instruction::Add &&
  6624. NewBO->Opcode != Instruction::Sub)) ||
  6625. (U->getOpcode() == Instruction::Mul &&
  6626. NewBO->Opcode != Instruction::Mul)) {
  6627. Ops.push_back(BO->LHS);
  6628. break;
  6629. }
  6630. // CreateSCEV calls getNoWrapFlagsFromUB, which under certain conditions
  6631. // requires a SCEV for the LHS.
  6632. if (NewBO->Op && (NewBO->IsNSW || NewBO->IsNUW)) {
  6633. auto *I = dyn_cast<Instruction>(NewBO->Op);
  6634. if (I && programUndefinedIfPoison(I)) {
  6635. Ops.push_back(BO->LHS);
  6636. break;
  6637. }
  6638. }
  6639. BO = NewBO;
  6640. } while (true);
  6641. return nullptr;
  6642. }
  6643. case Instruction::Sub:
  6644. case Instruction::UDiv:
  6645. case Instruction::URem:
  6646. break;
  6647. case Instruction::AShr:
  6648. case Instruction::Shl:
  6649. case Instruction::Xor:
  6650. if (!IsConstArg)
  6651. return nullptr;
  6652. break;
  6653. case Instruction::And:
  6654. case Instruction::Or:
  6655. if (!IsConstArg && BO->LHS->getType()->isIntegerTy(1))
  6656. return nullptr;
  6657. break;
  6658. case Instruction::LShr:
  6659. return getUnknown(V);
  6660. default:
  6661. llvm_unreachable("Unhandled binop");
  6662. break;
  6663. }
  6664. Ops.push_back(BO->LHS);
  6665. Ops.push_back(BO->RHS);
  6666. return nullptr;
  6667. }
  6668. switch (U->getOpcode()) {
  6669. case Instruction::Trunc:
  6670. case Instruction::ZExt:
  6671. case Instruction::SExt:
  6672. case Instruction::PtrToInt:
  6673. Ops.push_back(U->getOperand(0));
  6674. return nullptr;
  6675. case Instruction::BitCast:
  6676. if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType())) {
  6677. Ops.push_back(U->getOperand(0));
  6678. return nullptr;
  6679. }
  6680. return getUnknown(V);
  6681. case Instruction::SDiv:
  6682. case Instruction::SRem:
  6683. Ops.push_back(U->getOperand(0));
  6684. Ops.push_back(U->getOperand(1));
  6685. return nullptr;
  6686. case Instruction::GetElementPtr:
  6687. assert(cast<GEPOperator>(U)->getSourceElementType()->isSized() &&
  6688. "GEP source element type must be sized");
  6689. for (Value *Index : U->operands())
  6690. Ops.push_back(Index);
  6691. return nullptr;
  6692. case Instruction::IntToPtr:
  6693. return getUnknown(V);
  6694. case Instruction::PHI:
  6695. // Keep constructing SCEVs' for phis recursively for now.
  6696. return nullptr;
  6697. case Instruction::Select: {
  6698. // Check if U is a select that can be simplified to a SCEVUnknown.
  6699. auto CanSimplifyToUnknown = [this, U]() {
  6700. if (U->getType()->isIntegerTy(1) || isa<ConstantInt>(U->getOperand(0)))
  6701. return false;
  6702. auto *ICI = dyn_cast<ICmpInst>(U->getOperand(0));
  6703. if (!ICI)
  6704. return false;
  6705. Value *LHS = ICI->getOperand(0);
  6706. Value *RHS = ICI->getOperand(1);
  6707. if (ICI->getPredicate() == CmpInst::ICMP_EQ ||
  6708. ICI->getPredicate() == CmpInst::ICMP_NE) {
  6709. if (!(isa<ConstantInt>(RHS) && cast<ConstantInt>(RHS)->isZero()))
  6710. return true;
  6711. } else if (getTypeSizeInBits(LHS->getType()) >
  6712. getTypeSizeInBits(U->getType()))
  6713. return true;
  6714. return false;
  6715. };
  6716. if (CanSimplifyToUnknown())
  6717. return getUnknown(U);
  6718. for (Value *Inc : U->operands())
  6719. Ops.push_back(Inc);
  6720. return nullptr;
  6721. break;
  6722. }
  6723. case Instruction::Call:
  6724. case Instruction::Invoke:
  6725. if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand()) {
  6726. Ops.push_back(RV);
  6727. return nullptr;
  6728. }
  6729. if (auto *II = dyn_cast<IntrinsicInst>(U)) {
  6730. switch (II->getIntrinsicID()) {
  6731. case Intrinsic::abs:
  6732. Ops.push_back(II->getArgOperand(0));
  6733. return nullptr;
  6734. case Intrinsic::umax:
  6735. case Intrinsic::umin:
  6736. case Intrinsic::smax:
  6737. case Intrinsic::smin:
  6738. case Intrinsic::usub_sat:
  6739. case Intrinsic::uadd_sat:
  6740. Ops.push_back(II->getArgOperand(0));
  6741. Ops.push_back(II->getArgOperand(1));
  6742. return nullptr;
  6743. case Intrinsic::start_loop_iterations:
  6744. case Intrinsic::annotation:
  6745. case Intrinsic::ptr_annotation:
  6746. Ops.push_back(II->getArgOperand(0));
  6747. return nullptr;
  6748. default:
  6749. break;
  6750. }
  6751. }
  6752. break;
  6753. }
  6754. return nullptr;
  6755. }
  6756. const SCEV *ScalarEvolution::createSCEV(Value *V) {
  6757. if (!isSCEVable(V->getType()))
  6758. return getUnknown(V);
  6759. if (Instruction *I = dyn_cast<Instruction>(V)) {
  6760. // Don't attempt to analyze instructions in blocks that aren't
  6761. // reachable. Such instructions don't matter, and they aren't required
  6762. // to obey basic rules for definitions dominating uses which this
  6763. // analysis depends on.
  6764. if (!DT.isReachableFromEntry(I->getParent()))
  6765. return getUnknown(PoisonValue::get(V->getType()));
  6766. } else if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
  6767. return getConstant(CI);
  6768. else if (GlobalAlias *GA = dyn_cast<GlobalAlias>(V))
  6769. return GA->isInterposable() ? getUnknown(V) : getSCEV(GA->getAliasee());
  6770. else if (!isa<ConstantExpr>(V))
  6771. return getUnknown(V);
  6772. const SCEV *LHS;
  6773. const SCEV *RHS;
  6774. Operator *U = cast<Operator>(V);
  6775. if (auto BO =
  6776. MatchBinaryOp(U, getDataLayout(), AC, DT, dyn_cast<Instruction>(V))) {
  6777. switch (BO->Opcode) {
  6778. case Instruction::Add: {
  6779. // The simple thing to do would be to just call getSCEV on both operands
  6780. // and call getAddExpr with the result. However if we're looking at a
  6781. // bunch of things all added together, this can be quite inefficient,
  6782. // because it leads to N-1 getAddExpr calls for N ultimate operands.
  6783. // Instead, gather up all the operands and make a single getAddExpr call.
  6784. // LLVM IR canonical form means we need only traverse the left operands.
  6785. SmallVector<const SCEV *, 4> AddOps;
  6786. do {
  6787. if (BO->Op) {
  6788. if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
  6789. AddOps.push_back(OpSCEV);
  6790. break;
  6791. }
  6792. // If a NUW or NSW flag can be applied to the SCEV for this
  6793. // addition, then compute the SCEV for this addition by itself
  6794. // with a separate call to getAddExpr. We need to do that
  6795. // instead of pushing the operands of the addition onto AddOps,
  6796. // since the flags are only known to apply to this particular
  6797. // addition - they may not apply to other additions that can be
  6798. // formed with operands from AddOps.
  6799. const SCEV *RHS = getSCEV(BO->RHS);
  6800. SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
  6801. if (Flags != SCEV::FlagAnyWrap) {
  6802. const SCEV *LHS = getSCEV(BO->LHS);
  6803. if (BO->Opcode == Instruction::Sub)
  6804. AddOps.push_back(getMinusSCEV(LHS, RHS, Flags));
  6805. else
  6806. AddOps.push_back(getAddExpr(LHS, RHS, Flags));
  6807. break;
  6808. }
  6809. }
  6810. if (BO->Opcode == Instruction::Sub)
  6811. AddOps.push_back(getNegativeSCEV(getSCEV(BO->RHS)));
  6812. else
  6813. AddOps.push_back(getSCEV(BO->RHS));
  6814. auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
  6815. dyn_cast<Instruction>(V));
  6816. if (!NewBO || (NewBO->Opcode != Instruction::Add &&
  6817. NewBO->Opcode != Instruction::Sub)) {
  6818. AddOps.push_back(getSCEV(BO->LHS));
  6819. break;
  6820. }
  6821. BO = NewBO;
  6822. } while (true);
  6823. return getAddExpr(AddOps);
  6824. }
  6825. case Instruction::Mul: {
  6826. SmallVector<const SCEV *, 4> MulOps;
  6827. do {
  6828. if (BO->Op) {
  6829. if (auto *OpSCEV = getExistingSCEV(BO->Op)) {
  6830. MulOps.push_back(OpSCEV);
  6831. break;
  6832. }
  6833. SCEV::NoWrapFlags Flags = getNoWrapFlagsFromUB(BO->Op);
  6834. if (Flags != SCEV::FlagAnyWrap) {
  6835. LHS = getSCEV(BO->LHS);
  6836. RHS = getSCEV(BO->RHS);
  6837. MulOps.push_back(getMulExpr(LHS, RHS, Flags));
  6838. break;
  6839. }
  6840. }
  6841. MulOps.push_back(getSCEV(BO->RHS));
  6842. auto NewBO = MatchBinaryOp(BO->LHS, getDataLayout(), AC, DT,
  6843. dyn_cast<Instruction>(V));
  6844. if (!NewBO || NewBO->Opcode != Instruction::Mul) {
  6845. MulOps.push_back(getSCEV(BO->LHS));
  6846. break;
  6847. }
  6848. BO = NewBO;
  6849. } while (true);
  6850. return getMulExpr(MulOps);
  6851. }
  6852. case Instruction::UDiv:
  6853. LHS = getSCEV(BO->LHS);
  6854. RHS = getSCEV(BO->RHS);
  6855. return getUDivExpr(LHS, RHS);
  6856. case Instruction::URem:
  6857. LHS = getSCEV(BO->LHS);
  6858. RHS = getSCEV(BO->RHS);
  6859. return getURemExpr(LHS, RHS);
  6860. case Instruction::Sub: {
  6861. SCEV::NoWrapFlags Flags = SCEV::FlagAnyWrap;
  6862. if (BO->Op)
  6863. Flags = getNoWrapFlagsFromUB(BO->Op);
  6864. LHS = getSCEV(BO->LHS);
  6865. RHS = getSCEV(BO->RHS);
  6866. return getMinusSCEV(LHS, RHS, Flags);
  6867. }
  6868. case Instruction::And:
  6869. // For an expression like x&255 that merely masks off the high bits,
  6870. // use zext(trunc(x)) as the SCEV expression.
  6871. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
  6872. if (CI->isZero())
  6873. return getSCEV(BO->RHS);
  6874. if (CI->isMinusOne())
  6875. return getSCEV(BO->LHS);
  6876. const APInt &A = CI->getValue();
  6877. // Instcombine's ShrinkDemandedConstant may strip bits out of
  6878. // constants, obscuring what would otherwise be a low-bits mask.
  6879. // Use computeKnownBits to compute what ShrinkDemandedConstant
  6880. // knew about to reconstruct a low-bits mask value.
  6881. unsigned LZ = A.countLeadingZeros();
  6882. unsigned TZ = A.countTrailingZeros();
  6883. unsigned BitWidth = A.getBitWidth();
  6884. KnownBits Known(BitWidth);
  6885. computeKnownBits(BO->LHS, Known, getDataLayout(),
  6886. 0, &AC, nullptr, &DT);
  6887. APInt EffectiveMask =
  6888. APInt::getLowBitsSet(BitWidth, BitWidth - LZ - TZ).shl(TZ);
  6889. if ((LZ != 0 || TZ != 0) && !((~A & ~Known.Zero) & EffectiveMask)) {
  6890. const SCEV *MulCount = getConstant(APInt::getOneBitSet(BitWidth, TZ));
  6891. const SCEV *LHS = getSCEV(BO->LHS);
  6892. const SCEV *ShiftedLHS = nullptr;
  6893. if (auto *LHSMul = dyn_cast<SCEVMulExpr>(LHS)) {
  6894. if (auto *OpC = dyn_cast<SCEVConstant>(LHSMul->getOperand(0))) {
  6895. // For an expression like (x * 8) & 8, simplify the multiply.
  6896. unsigned MulZeros = OpC->getAPInt().countTrailingZeros();
  6897. unsigned GCD = std::min(MulZeros, TZ);
  6898. APInt DivAmt = APInt::getOneBitSet(BitWidth, TZ - GCD);
  6899. SmallVector<const SCEV*, 4> MulOps;
  6900. MulOps.push_back(getConstant(OpC->getAPInt().lshr(GCD)));
  6901. append_range(MulOps, LHSMul->operands().drop_front());
  6902. auto *NewMul = getMulExpr(MulOps, LHSMul->getNoWrapFlags());
  6903. ShiftedLHS = getUDivExpr(NewMul, getConstant(DivAmt));
  6904. }
  6905. }
  6906. if (!ShiftedLHS)
  6907. ShiftedLHS = getUDivExpr(LHS, MulCount);
  6908. return getMulExpr(
  6909. getZeroExtendExpr(
  6910. getTruncateExpr(ShiftedLHS,
  6911. IntegerType::get(getContext(), BitWidth - LZ - TZ)),
  6912. BO->LHS->getType()),
  6913. MulCount);
  6914. }
  6915. }
  6916. // Binary `and` is a bit-wise `umin`.
  6917. if (BO->LHS->getType()->isIntegerTy(1)) {
  6918. LHS = getSCEV(BO->LHS);
  6919. RHS = getSCEV(BO->RHS);
  6920. return getUMinExpr(LHS, RHS);
  6921. }
  6922. break;
  6923. case Instruction::Or:
  6924. // Binary `or` is a bit-wise `umax`.
  6925. if (BO->LHS->getType()->isIntegerTy(1)) {
  6926. LHS = getSCEV(BO->LHS);
  6927. RHS = getSCEV(BO->RHS);
  6928. return getUMaxExpr(LHS, RHS);
  6929. }
  6930. break;
  6931. case Instruction::Xor:
  6932. if (ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS)) {
  6933. // If the RHS of xor is -1, then this is a not operation.
  6934. if (CI->isMinusOne())
  6935. return getNotSCEV(getSCEV(BO->LHS));
  6936. // Model xor(and(x, C), C) as and(~x, C), if C is a low-bits mask.
  6937. // This is a variant of the check for xor with -1, and it handles
  6938. // the case where instcombine has trimmed non-demanded bits out
  6939. // of an xor with -1.
  6940. if (auto *LBO = dyn_cast<BinaryOperator>(BO->LHS))
  6941. if (ConstantInt *LCI = dyn_cast<ConstantInt>(LBO->getOperand(1)))
  6942. if (LBO->getOpcode() == Instruction::And &&
  6943. LCI->getValue() == CI->getValue())
  6944. if (const SCEVZeroExtendExpr *Z =
  6945. dyn_cast<SCEVZeroExtendExpr>(getSCEV(BO->LHS))) {
  6946. Type *UTy = BO->LHS->getType();
  6947. const SCEV *Z0 = Z->getOperand();
  6948. Type *Z0Ty = Z0->getType();
  6949. unsigned Z0TySize = getTypeSizeInBits(Z0Ty);
  6950. // If C is a low-bits mask, the zero extend is serving to
  6951. // mask off the high bits. Complement the operand and
  6952. // re-apply the zext.
  6953. if (CI->getValue().isMask(Z0TySize))
  6954. return getZeroExtendExpr(getNotSCEV(Z0), UTy);
  6955. // If C is a single bit, it may be in the sign-bit position
  6956. // before the zero-extend. In this case, represent the xor
  6957. // using an add, which is equivalent, and re-apply the zext.
  6958. APInt Trunc = CI->getValue().trunc(Z0TySize);
  6959. if (Trunc.zext(getTypeSizeInBits(UTy)) == CI->getValue() &&
  6960. Trunc.isSignMask())
  6961. return getZeroExtendExpr(getAddExpr(Z0, getConstant(Trunc)),
  6962. UTy);
  6963. }
  6964. }
  6965. break;
  6966. case Instruction::Shl:
  6967. // Turn shift left of a constant amount into a multiply.
  6968. if (ConstantInt *SA = dyn_cast<ConstantInt>(BO->RHS)) {
  6969. uint32_t BitWidth = cast<IntegerType>(SA->getType())->getBitWidth();
  6970. // If the shift count is not less than the bitwidth, the result of
  6971. // the shift is undefined. Don't try to analyze it, because the
  6972. // resolution chosen here may differ from the resolution chosen in
  6973. // other parts of the compiler.
  6974. if (SA->getValue().uge(BitWidth))
  6975. break;
  6976. // We can safely preserve the nuw flag in all cases. It's also safe to
  6977. // turn a nuw nsw shl into a nuw nsw mul. However, nsw in isolation
  6978. // requires special handling. It can be preserved as long as we're not
  6979. // left shifting by bitwidth - 1.
  6980. auto Flags = SCEV::FlagAnyWrap;
  6981. if (BO->Op) {
  6982. auto MulFlags = getNoWrapFlagsFromUB(BO->Op);
  6983. if ((MulFlags & SCEV::FlagNSW) &&
  6984. ((MulFlags & SCEV::FlagNUW) || SA->getValue().ult(BitWidth - 1)))
  6985. Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNSW);
  6986. if (MulFlags & SCEV::FlagNUW)
  6987. Flags = (SCEV::NoWrapFlags)(Flags | SCEV::FlagNUW);
  6988. }
  6989. ConstantInt *X = ConstantInt::get(
  6990. getContext(), APInt::getOneBitSet(BitWidth, SA->getZExtValue()));
  6991. return getMulExpr(getSCEV(BO->LHS), getConstant(X), Flags);
  6992. }
  6993. break;
  6994. case Instruction::AShr: {
  6995. // AShr X, C, where C is a constant.
  6996. ConstantInt *CI = dyn_cast<ConstantInt>(BO->RHS);
  6997. if (!CI)
  6998. break;
  6999. Type *OuterTy = BO->LHS->getType();
  7000. uint64_t BitWidth = getTypeSizeInBits(OuterTy);
  7001. // If the shift count is not less than the bitwidth, the result of
  7002. // the shift is undefined. Don't try to analyze it, because the
  7003. // resolution chosen here may differ from the resolution chosen in
  7004. // other parts of the compiler.
  7005. if (CI->getValue().uge(BitWidth))
  7006. break;
  7007. if (CI->isZero())
  7008. return getSCEV(BO->LHS); // shift by zero --> noop
  7009. uint64_t AShrAmt = CI->getZExtValue();
  7010. Type *TruncTy = IntegerType::get(getContext(), BitWidth - AShrAmt);
  7011. Operator *L = dyn_cast<Operator>(BO->LHS);
  7012. if (L && L->getOpcode() == Instruction::Shl) {
  7013. // X = Shl A, n
  7014. // Y = AShr X, m
  7015. // Both n and m are constant.
  7016. const SCEV *ShlOp0SCEV = getSCEV(L->getOperand(0));
  7017. if (L->getOperand(1) == BO->RHS)
  7018. // For a two-shift sext-inreg, i.e. n = m,
  7019. // use sext(trunc(x)) as the SCEV expression.
  7020. return getSignExtendExpr(
  7021. getTruncateExpr(ShlOp0SCEV, TruncTy), OuterTy);
  7022. ConstantInt *ShlAmtCI = dyn_cast<ConstantInt>(L->getOperand(1));
  7023. if (ShlAmtCI && ShlAmtCI->getValue().ult(BitWidth)) {
  7024. uint64_t ShlAmt = ShlAmtCI->getZExtValue();
  7025. if (ShlAmt > AShrAmt) {
  7026. // When n > m, use sext(mul(trunc(x), 2^(n-m)))) as the SCEV
  7027. // expression. We already checked that ShlAmt < BitWidth, so
  7028. // the multiplier, 1 << (ShlAmt - AShrAmt), fits into TruncTy as
  7029. // ShlAmt - AShrAmt < Amt.
  7030. APInt Mul = APInt::getOneBitSet(BitWidth - AShrAmt,
  7031. ShlAmt - AShrAmt);
  7032. return getSignExtendExpr(
  7033. getMulExpr(getTruncateExpr(ShlOp0SCEV, TruncTy),
  7034. getConstant(Mul)), OuterTy);
  7035. }
  7036. }
  7037. }
  7038. break;
  7039. }
  7040. }
  7041. }
  7042. switch (U->getOpcode()) {
  7043. case Instruction::Trunc:
  7044. return getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
  7045. case Instruction::ZExt:
  7046. return getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
  7047. case Instruction::SExt:
  7048. if (auto BO = MatchBinaryOp(U->getOperand(0), getDataLayout(), AC, DT,
  7049. dyn_cast<Instruction>(V))) {
  7050. // The NSW flag of a subtract does not always survive the conversion to
  7051. // A + (-1)*B. By pushing sign extension onto its operands we are much
  7052. // more likely to preserve NSW and allow later AddRec optimisations.
  7053. //
  7054. // NOTE: This is effectively duplicating this logic from getSignExtend:
  7055. // sext((A + B + ...)<nsw>) --> (sext(A) + sext(B) + ...)<nsw>
  7056. // but by that point the NSW information has potentially been lost.
  7057. if (BO->Opcode == Instruction::Sub && BO->IsNSW) {
  7058. Type *Ty = U->getType();
  7059. auto *V1 = getSignExtendExpr(getSCEV(BO->LHS), Ty);
  7060. auto *V2 = getSignExtendExpr(getSCEV(BO->RHS), Ty);
  7061. return getMinusSCEV(V1, V2, SCEV::FlagNSW);
  7062. }
  7063. }
  7064. return getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
  7065. case Instruction::BitCast:
  7066. // BitCasts are no-op casts so we just eliminate the cast.
  7067. if (isSCEVable(U->getType()) && isSCEVable(U->getOperand(0)->getType()))
  7068. return getSCEV(U->getOperand(0));
  7069. break;
  7070. case Instruction::PtrToInt: {
  7071. // Pointer to integer cast is straight-forward, so do model it.
  7072. const SCEV *Op = getSCEV(U->getOperand(0));
  7073. Type *DstIntTy = U->getType();
  7074. // But only if effective SCEV (integer) type is wide enough to represent
  7075. // all possible pointer values.
  7076. const SCEV *IntOp = getPtrToIntExpr(Op, DstIntTy);
  7077. if (isa<SCEVCouldNotCompute>(IntOp))
  7078. return getUnknown(V);
  7079. return IntOp;
  7080. }
  7081. case Instruction::IntToPtr:
  7082. // Just don't deal with inttoptr casts.
  7083. return getUnknown(V);
  7084. case Instruction::SDiv:
  7085. // If both operands are non-negative, this is just an udiv.
  7086. if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
  7087. isKnownNonNegative(getSCEV(U->getOperand(1))))
  7088. return getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
  7089. break;
  7090. case Instruction::SRem:
  7091. // If both operands are non-negative, this is just an urem.
  7092. if (isKnownNonNegative(getSCEV(U->getOperand(0))) &&
  7093. isKnownNonNegative(getSCEV(U->getOperand(1))))
  7094. return getURemExpr(getSCEV(U->getOperand(0)), getSCEV(U->getOperand(1)));
  7095. break;
  7096. case Instruction::GetElementPtr:
  7097. return createNodeForGEP(cast<GEPOperator>(U));
  7098. case Instruction::PHI:
  7099. return createNodeForPHI(cast<PHINode>(U));
  7100. case Instruction::Select:
  7101. return createNodeForSelectOrPHI(U, U->getOperand(0), U->getOperand(1),
  7102. U->getOperand(2));
  7103. case Instruction::Call:
  7104. case Instruction::Invoke:
  7105. if (Value *RV = cast<CallBase>(U)->getReturnedArgOperand())
  7106. return getSCEV(RV);
  7107. if (auto *II = dyn_cast<IntrinsicInst>(U)) {
  7108. switch (II->getIntrinsicID()) {
  7109. case Intrinsic::abs:
  7110. return getAbsExpr(
  7111. getSCEV(II->getArgOperand(0)),
  7112. /*IsNSW=*/cast<ConstantInt>(II->getArgOperand(1))->isOne());
  7113. case Intrinsic::umax:
  7114. LHS = getSCEV(II->getArgOperand(0));
  7115. RHS = getSCEV(II->getArgOperand(1));
  7116. return getUMaxExpr(LHS, RHS);
  7117. case Intrinsic::umin:
  7118. LHS = getSCEV(II->getArgOperand(0));
  7119. RHS = getSCEV(II->getArgOperand(1));
  7120. return getUMinExpr(LHS, RHS);
  7121. case Intrinsic::smax:
  7122. LHS = getSCEV(II->getArgOperand(0));
  7123. RHS = getSCEV(II->getArgOperand(1));
  7124. return getSMaxExpr(LHS, RHS);
  7125. case Intrinsic::smin:
  7126. LHS = getSCEV(II->getArgOperand(0));
  7127. RHS = getSCEV(II->getArgOperand(1));
  7128. return getSMinExpr(LHS, RHS);
  7129. case Intrinsic::usub_sat: {
  7130. const SCEV *X = getSCEV(II->getArgOperand(0));
  7131. const SCEV *Y = getSCEV(II->getArgOperand(1));
  7132. const SCEV *ClampedY = getUMinExpr(X, Y);
  7133. return getMinusSCEV(X, ClampedY, SCEV::FlagNUW);
  7134. }
  7135. case Intrinsic::uadd_sat: {
  7136. const SCEV *X = getSCEV(II->getArgOperand(0));
  7137. const SCEV *Y = getSCEV(II->getArgOperand(1));
  7138. const SCEV *ClampedX = getUMinExpr(X, getNotSCEV(Y));
  7139. return getAddExpr(ClampedX, Y, SCEV::FlagNUW);
  7140. }
  7141. case Intrinsic::start_loop_iterations:
  7142. case Intrinsic::annotation:
  7143. case Intrinsic::ptr_annotation:
  7144. // A start_loop_iterations or llvm.annotation or llvm.prt.annotation is
  7145. // just eqivalent to the first operand for SCEV purposes.
  7146. return getSCEV(II->getArgOperand(0));
  7147. default:
  7148. break;
  7149. }
  7150. }
  7151. break;
  7152. }
  7153. return getUnknown(V);
  7154. }
  7155. //===----------------------------------------------------------------------===//
  7156. // Iteration Count Computation Code
  7157. //
  7158. const SCEV *ScalarEvolution::getTripCountFromExitCount(const SCEV *ExitCount,
  7159. bool Extend) {
  7160. if (isa<SCEVCouldNotCompute>(ExitCount))
  7161. return getCouldNotCompute();
  7162. auto *ExitCountType = ExitCount->getType();
  7163. assert(ExitCountType->isIntegerTy());
  7164. if (!Extend)
  7165. return getAddExpr(ExitCount, getOne(ExitCountType));
  7166. auto *WiderType = Type::getIntNTy(ExitCountType->getContext(),
  7167. 1 + ExitCountType->getScalarSizeInBits());
  7168. return getAddExpr(getNoopOrZeroExtend(ExitCount, WiderType),
  7169. getOne(WiderType));
  7170. }
  7171. static unsigned getConstantTripCount(const SCEVConstant *ExitCount) {
  7172. if (!ExitCount)
  7173. return 0;
  7174. ConstantInt *ExitConst = ExitCount->getValue();
  7175. // Guard against huge trip counts.
  7176. if (ExitConst->getValue().getActiveBits() > 32)
  7177. return 0;
  7178. // In case of integer overflow, this returns 0, which is correct.
  7179. return ((unsigned)ExitConst->getZExtValue()) + 1;
  7180. }
  7181. unsigned ScalarEvolution::getSmallConstantTripCount(const Loop *L) {
  7182. auto *ExitCount = dyn_cast<SCEVConstant>(getBackedgeTakenCount(L, Exact));
  7183. return getConstantTripCount(ExitCount);
  7184. }
  7185. unsigned
  7186. ScalarEvolution::getSmallConstantTripCount(const Loop *L,
  7187. const BasicBlock *ExitingBlock) {
  7188. assert(ExitingBlock && "Must pass a non-null exiting block!");
  7189. assert(L->isLoopExiting(ExitingBlock) &&
  7190. "Exiting block must actually branch out of the loop!");
  7191. const SCEVConstant *ExitCount =
  7192. dyn_cast<SCEVConstant>(getExitCount(L, ExitingBlock));
  7193. return getConstantTripCount(ExitCount);
  7194. }
  7195. unsigned ScalarEvolution::getSmallConstantMaxTripCount(const Loop *L) {
  7196. const auto *MaxExitCount =
  7197. dyn_cast<SCEVConstant>(getConstantMaxBackedgeTakenCount(L));
  7198. return getConstantTripCount(MaxExitCount);
  7199. }
  7200. const SCEV *ScalarEvolution::getConstantMaxTripCountFromArray(const Loop *L) {
  7201. // We can't infer from Array in Irregular Loop.
  7202. // FIXME: It's hard to infer loop bound from array operated in Nested Loop.
  7203. if (!L->isLoopSimplifyForm() || !L->isInnermost())
  7204. return getCouldNotCompute();
  7205. // FIXME: To make the scene more typical, we only analysis loops that have
  7206. // one exiting block and that block must be the latch. To make it easier to
  7207. // capture loops that have memory access and memory access will be executed
  7208. // in each iteration.
  7209. const BasicBlock *LoopLatch = L->getLoopLatch();
  7210. assert(LoopLatch && "See defination of simplify form loop.");
  7211. if (L->getExitingBlock() != LoopLatch)
  7212. return getCouldNotCompute();
  7213. const DataLayout &DL = getDataLayout();
  7214. SmallVector<const SCEV *> InferCountColl;
  7215. for (auto *BB : L->getBlocks()) {
  7216. // Go here, we can know that Loop is a single exiting and simplified form
  7217. // loop. Make sure that infer from Memory Operation in those BBs must be
  7218. // executed in loop. First step, we can make sure that max execution time
  7219. // of MemAccessBB in loop represents latch max excution time.
  7220. // If MemAccessBB does not dom Latch, skip.
  7221. // Entry
  7222. // │
  7223. // ┌─────▼─────┐
  7224. // │Loop Header◄─────┐
  7225. // └──┬──────┬─┘ │
  7226. // │ │ │
  7227. // ┌────────▼──┐ ┌─▼─────┐ │
  7228. // │MemAccessBB│ │OtherBB│ │
  7229. // └────────┬──┘ └─┬─────┘ │
  7230. // │ │ │
  7231. // ┌─▼──────▼─┐ │
  7232. // │Loop Latch├─────┘
  7233. // └────┬─────┘
  7234. // ▼
  7235. // Exit
  7236. if (!DT.dominates(BB, LoopLatch))
  7237. continue;
  7238. for (Instruction &Inst : *BB) {
  7239. // Find Memory Operation Instruction.
  7240. auto *GEP = getLoadStorePointerOperand(&Inst);
  7241. if (!GEP)
  7242. continue;
  7243. auto *ElemSize = dyn_cast<SCEVConstant>(getElementSize(&Inst));
  7244. // Do not infer from scalar type, eg."ElemSize = sizeof()".
  7245. if (!ElemSize)
  7246. continue;
  7247. // Use a existing polynomial recurrence on the trip count.
  7248. auto *AddRec = dyn_cast<SCEVAddRecExpr>(getSCEV(GEP));
  7249. if (!AddRec)
  7250. continue;
  7251. auto *ArrBase = dyn_cast<SCEVUnknown>(getPointerBase(AddRec));
  7252. auto *Step = dyn_cast<SCEVConstant>(AddRec->getStepRecurrence(*this));
  7253. if (!ArrBase || !Step)
  7254. continue;
  7255. assert(isLoopInvariant(ArrBase, L) && "See addrec definition");
  7256. // Only handle { %array + step },
  7257. // FIXME: {(SCEVAddRecExpr) + step } could not be analysed here.
  7258. if (AddRec->getStart() != ArrBase)
  7259. continue;
  7260. // Memory operation pattern which have gaps.
  7261. // Or repeat memory opreation.
  7262. // And index of GEP wraps arround.
  7263. if (Step->getAPInt().getActiveBits() > 32 ||
  7264. Step->getAPInt().getZExtValue() !=
  7265. ElemSize->getAPInt().getZExtValue() ||
  7266. Step->isZero() || Step->getAPInt().isNegative())
  7267. continue;
  7268. // Only infer from stack array which has certain size.
  7269. // Make sure alloca instruction is not excuted in loop.
  7270. AllocaInst *AllocateInst = dyn_cast<AllocaInst>(ArrBase->getValue());
  7271. if (!AllocateInst || L->contains(AllocateInst->getParent()))
  7272. continue;
  7273. // Make sure only handle normal array.
  7274. auto *Ty = dyn_cast<ArrayType>(AllocateInst->getAllocatedType());
  7275. auto *ArrSize = dyn_cast<ConstantInt>(AllocateInst->getArraySize());
  7276. if (!Ty || !ArrSize || !ArrSize->isOne())
  7277. continue;
  7278. // FIXME: Since gep indices are silently zext to the indexing type,
  7279. // we will have a narrow gep index which wraps around rather than
  7280. // increasing strictly, we shoule ensure that step is increasing
  7281. // strictly by the loop iteration.
  7282. // Now we can infer a max execution time by MemLength/StepLength.
  7283. const SCEV *MemSize =
  7284. getConstant(Step->getType(), DL.getTypeAllocSize(Ty));
  7285. auto *MaxExeCount =
  7286. dyn_cast<SCEVConstant>(getUDivCeilSCEV(MemSize, Step));
  7287. if (!MaxExeCount || MaxExeCount->getAPInt().getActiveBits() > 32)
  7288. continue;
  7289. // If the loop reaches the maximum number of executions, we can not
  7290. // access bytes starting outside the statically allocated size without
  7291. // being immediate UB. But it is allowed to enter loop header one more
  7292. // time.
  7293. auto *InferCount = dyn_cast<SCEVConstant>(
  7294. getAddExpr(MaxExeCount, getOne(MaxExeCount->getType())));
  7295. // Discard the maximum number of execution times under 32bits.
  7296. if (!InferCount || InferCount->getAPInt().getActiveBits() > 32)
  7297. continue;
  7298. InferCountColl.push_back(InferCount);
  7299. }
  7300. }
  7301. if (InferCountColl.size() == 0)
  7302. return getCouldNotCompute();
  7303. return getUMinFromMismatchedTypes(InferCountColl);
  7304. }
  7305. unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L) {
  7306. SmallVector<BasicBlock *, 8> ExitingBlocks;
  7307. L->getExitingBlocks(ExitingBlocks);
  7308. std::optional<unsigned> Res;
  7309. for (auto *ExitingBB : ExitingBlocks) {
  7310. unsigned Multiple = getSmallConstantTripMultiple(L, ExitingBB);
  7311. if (!Res)
  7312. Res = Multiple;
  7313. Res = (unsigned)std::gcd(*Res, Multiple);
  7314. }
  7315. return Res.value_or(1);
  7316. }
  7317. unsigned ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
  7318. const SCEV *ExitCount) {
  7319. if (ExitCount == getCouldNotCompute())
  7320. return 1;
  7321. // Get the trip count
  7322. const SCEV *TCExpr = getTripCountFromExitCount(ExitCount);
  7323. const SCEVConstant *TC = dyn_cast<SCEVConstant>(TCExpr);
  7324. if (!TC)
  7325. // Attempt to factor more general cases. Returns the greatest power of
  7326. // two divisor. If overflow happens, the trip count expression is still
  7327. // divisible by the greatest power of 2 divisor returned.
  7328. return 1U << std::min((uint32_t)31,
  7329. GetMinTrailingZeros(applyLoopGuards(TCExpr, L)));
  7330. ConstantInt *Result = TC->getValue();
  7331. // Guard against huge trip counts (this requires checking
  7332. // for zero to handle the case where the trip count == -1 and the
  7333. // addition wraps).
  7334. if (!Result || Result->getValue().getActiveBits() > 32 ||
  7335. Result->getValue().getActiveBits() == 0)
  7336. return 1;
  7337. return (unsigned)Result->getZExtValue();
  7338. }
  7339. /// Returns the largest constant divisor of the trip count of this loop as a
  7340. /// normal unsigned value, if possible. This means that the actual trip count is
  7341. /// always a multiple of the returned value (don't forget the trip count could
  7342. /// very well be zero as well!).
  7343. ///
  7344. /// Returns 1 if the trip count is unknown or not guaranteed to be the
  7345. /// multiple of a constant (which is also the case if the trip count is simply
  7346. /// constant, use getSmallConstantTripCount for that case), Will also return 1
  7347. /// if the trip count is very large (>= 2^32).
  7348. ///
  7349. /// As explained in the comments for getSmallConstantTripCount, this assumes
  7350. /// that control exits the loop via ExitingBlock.
  7351. unsigned
  7352. ScalarEvolution::getSmallConstantTripMultiple(const Loop *L,
  7353. const BasicBlock *ExitingBlock) {
  7354. assert(ExitingBlock && "Must pass a non-null exiting block!");
  7355. assert(L->isLoopExiting(ExitingBlock) &&
  7356. "Exiting block must actually branch out of the loop!");
  7357. const SCEV *ExitCount = getExitCount(L, ExitingBlock);
  7358. return getSmallConstantTripMultiple(L, ExitCount);
  7359. }
  7360. const SCEV *ScalarEvolution::getExitCount(const Loop *L,
  7361. const BasicBlock *ExitingBlock,
  7362. ExitCountKind Kind) {
  7363. switch (Kind) {
  7364. case Exact:
  7365. return getBackedgeTakenInfo(L).getExact(ExitingBlock, this);
  7366. case SymbolicMaximum:
  7367. return getBackedgeTakenInfo(L).getSymbolicMax(ExitingBlock, this);
  7368. case ConstantMaximum:
  7369. return getBackedgeTakenInfo(L).getConstantMax(ExitingBlock, this);
  7370. };
  7371. llvm_unreachable("Invalid ExitCountKind!");
  7372. }
  7373. const SCEV *
  7374. ScalarEvolution::getPredicatedBackedgeTakenCount(const Loop *L,
  7375. SmallVector<const SCEVPredicate *, 4> &Preds) {
  7376. return getPredicatedBackedgeTakenInfo(L).getExact(L, this, &Preds);
  7377. }
  7378. const SCEV *ScalarEvolution::getBackedgeTakenCount(const Loop *L,
  7379. ExitCountKind Kind) {
  7380. switch (Kind) {
  7381. case Exact:
  7382. return getBackedgeTakenInfo(L).getExact(L, this);
  7383. case ConstantMaximum:
  7384. return getBackedgeTakenInfo(L).getConstantMax(this);
  7385. case SymbolicMaximum:
  7386. return getBackedgeTakenInfo(L).getSymbolicMax(L, this);
  7387. };
  7388. llvm_unreachable("Invalid ExitCountKind!");
  7389. }
  7390. bool ScalarEvolution::isBackedgeTakenCountMaxOrZero(const Loop *L) {
  7391. return getBackedgeTakenInfo(L).isConstantMaxOrZero(this);
  7392. }
  7393. /// Push PHI nodes in the header of the given loop onto the given Worklist.
  7394. static void PushLoopPHIs(const Loop *L,
  7395. SmallVectorImpl<Instruction *> &Worklist,
  7396. SmallPtrSetImpl<Instruction *> &Visited) {
  7397. BasicBlock *Header = L->getHeader();
  7398. // Push all Loop-header PHIs onto the Worklist stack.
  7399. for (PHINode &PN : Header->phis())
  7400. if (Visited.insert(&PN).second)
  7401. Worklist.push_back(&PN);
  7402. }
  7403. const ScalarEvolution::BackedgeTakenInfo &
  7404. ScalarEvolution::getPredicatedBackedgeTakenInfo(const Loop *L) {
  7405. auto &BTI = getBackedgeTakenInfo(L);
  7406. if (BTI.hasFullInfo())
  7407. return BTI;
  7408. auto Pair = PredicatedBackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
  7409. if (!Pair.second)
  7410. return Pair.first->second;
  7411. BackedgeTakenInfo Result =
  7412. computeBackedgeTakenCount(L, /*AllowPredicates=*/true);
  7413. return PredicatedBackedgeTakenCounts.find(L)->second = std::move(Result);
  7414. }
  7415. ScalarEvolution::BackedgeTakenInfo &
  7416. ScalarEvolution::getBackedgeTakenInfo(const Loop *L) {
  7417. // Initially insert an invalid entry for this loop. If the insertion
  7418. // succeeds, proceed to actually compute a backedge-taken count and
  7419. // update the value. The temporary CouldNotCompute value tells SCEV
  7420. // code elsewhere that it shouldn't attempt to request a new
  7421. // backedge-taken count, which could result in infinite recursion.
  7422. std::pair<DenseMap<const Loop *, BackedgeTakenInfo>::iterator, bool> Pair =
  7423. BackedgeTakenCounts.insert({L, BackedgeTakenInfo()});
  7424. if (!Pair.second)
  7425. return Pair.first->second;
  7426. // computeBackedgeTakenCount may allocate memory for its result. Inserting it
  7427. // into the BackedgeTakenCounts map transfers ownership. Otherwise, the result
  7428. // must be cleared in this scope.
  7429. BackedgeTakenInfo Result = computeBackedgeTakenCount(L);
  7430. // In product build, there are no usage of statistic.
  7431. (void)NumTripCountsComputed;
  7432. (void)NumTripCountsNotComputed;
  7433. #if LLVM_ENABLE_STATS || !defined(NDEBUG)
  7434. const SCEV *BEExact = Result.getExact(L, this);
  7435. if (BEExact != getCouldNotCompute()) {
  7436. assert(isLoopInvariant(BEExact, L) &&
  7437. isLoopInvariant(Result.getConstantMax(this), L) &&
  7438. "Computed backedge-taken count isn't loop invariant for loop!");
  7439. ++NumTripCountsComputed;
  7440. } else if (Result.getConstantMax(this) == getCouldNotCompute() &&
  7441. isa<PHINode>(L->getHeader()->begin())) {
  7442. // Only count loops that have phi nodes as not being computable.
  7443. ++NumTripCountsNotComputed;
  7444. }
  7445. #endif // LLVM_ENABLE_STATS || !defined(NDEBUG)
  7446. // Now that we know more about the trip count for this loop, forget any
  7447. // existing SCEV values for PHI nodes in this loop since they are only
  7448. // conservative estimates made without the benefit of trip count
  7449. // information. This invalidation is not necessary for correctness, and is
  7450. // only done to produce more precise results.
  7451. if (Result.hasAnyInfo()) {
  7452. // Invalidate any expression using an addrec in this loop.
  7453. SmallVector<const SCEV *, 8> ToForget;
  7454. auto LoopUsersIt = LoopUsers.find(L);
  7455. if (LoopUsersIt != LoopUsers.end())
  7456. append_range(ToForget, LoopUsersIt->second);
  7457. forgetMemoizedResults(ToForget);
  7458. // Invalidate constant-evolved loop header phis.
  7459. for (PHINode &PN : L->getHeader()->phis())
  7460. ConstantEvolutionLoopExitValue.erase(&PN);
  7461. }
  7462. // Re-lookup the insert position, since the call to
  7463. // computeBackedgeTakenCount above could result in a
  7464. // recusive call to getBackedgeTakenInfo (on a different
  7465. // loop), which would invalidate the iterator computed
  7466. // earlier.
  7467. return BackedgeTakenCounts.find(L)->second = std::move(Result);
  7468. }
  7469. void ScalarEvolution::forgetAllLoops() {
  7470. // This method is intended to forget all info about loops. It should
  7471. // invalidate caches as if the following happened:
  7472. // - The trip counts of all loops have changed arbitrarily
  7473. // - Every llvm::Value has been updated in place to produce a different
  7474. // result.
  7475. BackedgeTakenCounts.clear();
  7476. PredicatedBackedgeTakenCounts.clear();
  7477. BECountUsers.clear();
  7478. LoopPropertiesCache.clear();
  7479. ConstantEvolutionLoopExitValue.clear();
  7480. ValueExprMap.clear();
  7481. ValuesAtScopes.clear();
  7482. ValuesAtScopesUsers.clear();
  7483. LoopDispositions.clear();
  7484. BlockDispositions.clear();
  7485. UnsignedRanges.clear();
  7486. SignedRanges.clear();
  7487. ExprValueMap.clear();
  7488. HasRecMap.clear();
  7489. MinTrailingZerosCache.clear();
  7490. PredicatedSCEVRewrites.clear();
  7491. FoldCache.clear();
  7492. FoldCacheUser.clear();
  7493. }
  7494. void ScalarEvolution::forgetLoop(const Loop *L) {
  7495. SmallVector<const Loop *, 16> LoopWorklist(1, L);
  7496. SmallVector<Instruction *, 32> Worklist;
  7497. SmallPtrSet<Instruction *, 16> Visited;
  7498. SmallVector<const SCEV *, 16> ToForget;
  7499. // Iterate over all the loops and sub-loops to drop SCEV information.
  7500. while (!LoopWorklist.empty()) {
  7501. auto *CurrL = LoopWorklist.pop_back_val();
  7502. // Drop any stored trip count value.
  7503. forgetBackedgeTakenCounts(CurrL, /* Predicated */ false);
  7504. forgetBackedgeTakenCounts(CurrL, /* Predicated */ true);
  7505. // Drop information about predicated SCEV rewrites for this loop.
  7506. for (auto I = PredicatedSCEVRewrites.begin();
  7507. I != PredicatedSCEVRewrites.end();) {
  7508. std::pair<const SCEV *, const Loop *> Entry = I->first;
  7509. if (Entry.second == CurrL)
  7510. PredicatedSCEVRewrites.erase(I++);
  7511. else
  7512. ++I;
  7513. }
  7514. auto LoopUsersItr = LoopUsers.find(CurrL);
  7515. if (LoopUsersItr != LoopUsers.end()) {
  7516. ToForget.insert(ToForget.end(), LoopUsersItr->second.begin(),
  7517. LoopUsersItr->second.end());
  7518. }
  7519. // Drop information about expressions based on loop-header PHIs.
  7520. PushLoopPHIs(CurrL, Worklist, Visited);
  7521. while (!Worklist.empty()) {
  7522. Instruction *I = Worklist.pop_back_val();
  7523. ValueExprMapType::iterator It =
  7524. ValueExprMap.find_as(static_cast<Value *>(I));
  7525. if (It != ValueExprMap.end()) {
  7526. eraseValueFromMap(It->first);
  7527. ToForget.push_back(It->second);
  7528. if (PHINode *PN = dyn_cast<PHINode>(I))
  7529. ConstantEvolutionLoopExitValue.erase(PN);
  7530. }
  7531. PushDefUseChildren(I, Worklist, Visited);
  7532. }
  7533. LoopPropertiesCache.erase(CurrL);
  7534. // Forget all contained loops too, to avoid dangling entries in the
  7535. // ValuesAtScopes map.
  7536. LoopWorklist.append(CurrL->begin(), CurrL->end());
  7537. }
  7538. forgetMemoizedResults(ToForget);
  7539. }
  7540. void ScalarEvolution::forgetTopmostLoop(const Loop *L) {
  7541. forgetLoop(L->getOutermostLoop());
  7542. }
  7543. void ScalarEvolution::forgetValue(Value *V) {
  7544. Instruction *I = dyn_cast<Instruction>(V);
  7545. if (!I) return;
  7546. // Drop information about expressions based on loop-header PHIs.
  7547. SmallVector<Instruction *, 16> Worklist;
  7548. SmallPtrSet<Instruction *, 8> Visited;
  7549. SmallVector<const SCEV *, 8> ToForget;
  7550. Worklist.push_back(I);
  7551. Visited.insert(I);
  7552. while (!Worklist.empty()) {
  7553. I = Worklist.pop_back_val();
  7554. ValueExprMapType::iterator It =
  7555. ValueExprMap.find_as(static_cast<Value *>(I));
  7556. if (It != ValueExprMap.end()) {
  7557. eraseValueFromMap(It->first);
  7558. ToForget.push_back(It->second);
  7559. if (PHINode *PN = dyn_cast<PHINode>(I))
  7560. ConstantEvolutionLoopExitValue.erase(PN);
  7561. }
  7562. PushDefUseChildren(I, Worklist, Visited);
  7563. }
  7564. forgetMemoizedResults(ToForget);
  7565. }
  7566. void ScalarEvolution::forgetLoopDispositions() { LoopDispositions.clear(); }
  7567. void ScalarEvolution::forgetBlockAndLoopDispositions(Value *V) {
  7568. // Unless a specific value is passed to invalidation, completely clear both
  7569. // caches.
  7570. if (!V) {
  7571. BlockDispositions.clear();
  7572. LoopDispositions.clear();
  7573. return;
  7574. }
  7575. if (!isSCEVable(V->getType()))
  7576. return;
  7577. const SCEV *S = getExistingSCEV(V);
  7578. if (!S)
  7579. return;
  7580. // Invalidate the block and loop dispositions cached for S. Dispositions of
  7581. // S's users may change if S's disposition changes (i.e. a user may change to
  7582. // loop-invariant, if S changes to loop invariant), so also invalidate
  7583. // dispositions of S's users recursively.
  7584. SmallVector<const SCEV *, 8> Worklist = {S};
  7585. SmallPtrSet<const SCEV *, 8> Seen = {S};
  7586. while (!Worklist.empty()) {
  7587. const SCEV *Curr = Worklist.pop_back_val();
  7588. bool LoopDispoRemoved = LoopDispositions.erase(Curr);
  7589. bool BlockDispoRemoved = BlockDispositions.erase(Curr);
  7590. if (!LoopDispoRemoved && !BlockDispoRemoved)
  7591. continue;
  7592. auto Users = SCEVUsers.find(Curr);
  7593. if (Users != SCEVUsers.end())
  7594. for (const auto *User : Users->second)
  7595. if (Seen.insert(User).second)
  7596. Worklist.push_back(User);
  7597. }
  7598. }
  7599. /// Get the exact loop backedge taken count considering all loop exits. A
  7600. /// computable result can only be returned for loops with all exiting blocks
  7601. /// dominating the latch. howFarToZero assumes that the limit of each loop test
  7602. /// is never skipped. This is a valid assumption as long as the loop exits via
  7603. /// that test. For precise results, it is the caller's responsibility to specify
  7604. /// the relevant loop exiting block using getExact(ExitingBlock, SE).
  7605. const SCEV *
  7606. ScalarEvolution::BackedgeTakenInfo::getExact(const Loop *L, ScalarEvolution *SE,
  7607. SmallVector<const SCEVPredicate *, 4> *Preds) const {
  7608. // If any exits were not computable, the loop is not computable.
  7609. if (!isComplete() || ExitNotTaken.empty())
  7610. return SE->getCouldNotCompute();
  7611. const BasicBlock *Latch = L->getLoopLatch();
  7612. // All exiting blocks we have collected must dominate the only backedge.
  7613. if (!Latch)
  7614. return SE->getCouldNotCompute();
  7615. // All exiting blocks we have gathered dominate loop's latch, so exact trip
  7616. // count is simply a minimum out of all these calculated exit counts.
  7617. SmallVector<const SCEV *, 2> Ops;
  7618. for (const auto &ENT : ExitNotTaken) {
  7619. const SCEV *BECount = ENT.ExactNotTaken;
  7620. assert(BECount != SE->getCouldNotCompute() && "Bad exit SCEV!");
  7621. assert(SE->DT.dominates(ENT.ExitingBlock, Latch) &&
  7622. "We should only have known counts for exiting blocks that dominate "
  7623. "latch!");
  7624. Ops.push_back(BECount);
  7625. if (Preds)
  7626. for (const auto *P : ENT.Predicates)
  7627. Preds->push_back(P);
  7628. assert((Preds || ENT.hasAlwaysTruePredicate()) &&
  7629. "Predicate should be always true!");
  7630. }
  7631. // If an earlier exit exits on the first iteration (exit count zero), then
  7632. // a later poison exit count should not propagate into the result. This are
  7633. // exactly the semantics provided by umin_seq.
  7634. return SE->getUMinFromMismatchedTypes(Ops, /* Sequential */ true);
  7635. }
  7636. /// Get the exact not taken count for this loop exit.
  7637. const SCEV *
  7638. ScalarEvolution::BackedgeTakenInfo::getExact(const BasicBlock *ExitingBlock,
  7639. ScalarEvolution *SE) const {
  7640. for (const auto &ENT : ExitNotTaken)
  7641. if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
  7642. return ENT.ExactNotTaken;
  7643. return SE->getCouldNotCompute();
  7644. }
  7645. const SCEV *ScalarEvolution::BackedgeTakenInfo::getConstantMax(
  7646. const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
  7647. for (const auto &ENT : ExitNotTaken)
  7648. if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
  7649. return ENT.ConstantMaxNotTaken;
  7650. return SE->getCouldNotCompute();
  7651. }
  7652. const SCEV *ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(
  7653. const BasicBlock *ExitingBlock, ScalarEvolution *SE) const {
  7654. for (const auto &ENT : ExitNotTaken)
  7655. if (ENT.ExitingBlock == ExitingBlock && ENT.hasAlwaysTruePredicate())
  7656. return ENT.SymbolicMaxNotTaken;
  7657. return SE->getCouldNotCompute();
  7658. }
  7659. /// getConstantMax - Get the constant max backedge taken count for the loop.
  7660. const SCEV *
  7661. ScalarEvolution::BackedgeTakenInfo::getConstantMax(ScalarEvolution *SE) const {
  7662. auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
  7663. return !ENT.hasAlwaysTruePredicate();
  7664. };
  7665. if (!getConstantMax() || any_of(ExitNotTaken, PredicateNotAlwaysTrue))
  7666. return SE->getCouldNotCompute();
  7667. assert((isa<SCEVCouldNotCompute>(getConstantMax()) ||
  7668. isa<SCEVConstant>(getConstantMax())) &&
  7669. "No point in having a non-constant max backedge taken count!");
  7670. return getConstantMax();
  7671. }
  7672. const SCEV *
  7673. ScalarEvolution::BackedgeTakenInfo::getSymbolicMax(const Loop *L,
  7674. ScalarEvolution *SE) {
  7675. if (!SymbolicMax)
  7676. SymbolicMax = SE->computeSymbolicMaxBackedgeTakenCount(L);
  7677. return SymbolicMax;
  7678. }
  7679. bool ScalarEvolution::BackedgeTakenInfo::isConstantMaxOrZero(
  7680. ScalarEvolution *SE) const {
  7681. auto PredicateNotAlwaysTrue = [](const ExitNotTakenInfo &ENT) {
  7682. return !ENT.hasAlwaysTruePredicate();
  7683. };
  7684. return MaxOrZero && !any_of(ExitNotTaken, PredicateNotAlwaysTrue);
  7685. }
  7686. ScalarEvolution::ExitLimit::ExitLimit(const SCEV *E)
  7687. : ExitLimit(E, E, E, false, std::nullopt) {}
  7688. ScalarEvolution::ExitLimit::ExitLimit(
  7689. const SCEV *E, const SCEV *ConstantMaxNotTaken,
  7690. const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
  7691. ArrayRef<const SmallPtrSetImpl<const SCEVPredicate *> *> PredSetList)
  7692. : ExactNotTaken(E), ConstantMaxNotTaken(ConstantMaxNotTaken),
  7693. SymbolicMaxNotTaken(SymbolicMaxNotTaken), MaxOrZero(MaxOrZero) {
  7694. // If we prove the max count is zero, so is the symbolic bound. This happens
  7695. // in practice due to differences in a) how context sensitive we've chosen
  7696. // to be and b) how we reason about bounds implied by UB.
  7697. if (ConstantMaxNotTaken->isZero()) {
  7698. this->ExactNotTaken = E = ConstantMaxNotTaken;
  7699. this->SymbolicMaxNotTaken = SymbolicMaxNotTaken = ConstantMaxNotTaken;
  7700. }
  7701. assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
  7702. !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
  7703. "Exact is not allowed to be less precise than Constant Max");
  7704. assert((isa<SCEVCouldNotCompute>(ExactNotTaken) ||
  7705. !isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken)) &&
  7706. "Exact is not allowed to be less precise than Symbolic Max");
  7707. assert((isa<SCEVCouldNotCompute>(SymbolicMaxNotTaken) ||
  7708. !isa<SCEVCouldNotCompute>(ConstantMaxNotTaken)) &&
  7709. "Symbolic Max is not allowed to be less precise than Constant Max");
  7710. assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
  7711. isa<SCEVConstant>(ConstantMaxNotTaken)) &&
  7712. "No point in having a non-constant max backedge taken count!");
  7713. for (const auto *PredSet : PredSetList)
  7714. for (const auto *P : *PredSet)
  7715. addPredicate(P);
  7716. assert((isa<SCEVCouldNotCompute>(E) || !E->getType()->isPointerTy()) &&
  7717. "Backedge count should be int");
  7718. assert((isa<SCEVCouldNotCompute>(ConstantMaxNotTaken) ||
  7719. !ConstantMaxNotTaken->getType()->isPointerTy()) &&
  7720. "Max backedge count should be int");
  7721. }
  7722. ScalarEvolution::ExitLimit::ExitLimit(
  7723. const SCEV *E, const SCEV *ConstantMaxNotTaken,
  7724. const SCEV *SymbolicMaxNotTaken, bool MaxOrZero,
  7725. const SmallPtrSetImpl<const SCEVPredicate *> &PredSet)
  7726. : ExitLimit(E, ConstantMaxNotTaken, SymbolicMaxNotTaken, MaxOrZero,
  7727. { &PredSet }) {}
  7728. /// Allocate memory for BackedgeTakenInfo and copy the not-taken count of each
  7729. /// computable exit into a persistent ExitNotTakenInfo array.
  7730. ScalarEvolution::BackedgeTakenInfo::BackedgeTakenInfo(
  7731. ArrayRef<ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo> ExitCounts,
  7732. bool IsComplete, const SCEV *ConstantMax, bool MaxOrZero)
  7733. : ConstantMax(ConstantMax), IsComplete(IsComplete), MaxOrZero(MaxOrZero) {
  7734. using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
  7735. ExitNotTaken.reserve(ExitCounts.size());
  7736. std::transform(ExitCounts.begin(), ExitCounts.end(),
  7737. std::back_inserter(ExitNotTaken),
  7738. [&](const EdgeExitInfo &EEI) {
  7739. BasicBlock *ExitBB = EEI.first;
  7740. const ExitLimit &EL = EEI.second;
  7741. return ExitNotTakenInfo(ExitBB, EL.ExactNotTaken,
  7742. EL.ConstantMaxNotTaken, EL.SymbolicMaxNotTaken,
  7743. EL.Predicates);
  7744. });
  7745. assert((isa<SCEVCouldNotCompute>(ConstantMax) ||
  7746. isa<SCEVConstant>(ConstantMax)) &&
  7747. "No point in having a non-constant max backedge taken count!");
  7748. }
  7749. /// Compute the number of times the backedge of the specified loop will execute.
  7750. ScalarEvolution::BackedgeTakenInfo
  7751. ScalarEvolution::computeBackedgeTakenCount(const Loop *L,
  7752. bool AllowPredicates) {
  7753. SmallVector<BasicBlock *, 8> ExitingBlocks;
  7754. L->getExitingBlocks(ExitingBlocks);
  7755. using EdgeExitInfo = ScalarEvolution::BackedgeTakenInfo::EdgeExitInfo;
  7756. SmallVector<EdgeExitInfo, 4> ExitCounts;
  7757. bool CouldComputeBECount = true;
  7758. BasicBlock *Latch = L->getLoopLatch(); // may be NULL.
  7759. const SCEV *MustExitMaxBECount = nullptr;
  7760. const SCEV *MayExitMaxBECount = nullptr;
  7761. bool MustExitMaxOrZero = false;
  7762. // Compute the ExitLimit for each loop exit. Use this to populate ExitCounts
  7763. // and compute maxBECount.
  7764. // Do a union of all the predicates here.
  7765. for (unsigned i = 0, e = ExitingBlocks.size(); i != e; ++i) {
  7766. BasicBlock *ExitBB = ExitingBlocks[i];
  7767. // We canonicalize untaken exits to br (constant), ignore them so that
  7768. // proving an exit untaken doesn't negatively impact our ability to reason
  7769. // about the loop as whole.
  7770. if (auto *BI = dyn_cast<BranchInst>(ExitBB->getTerminator()))
  7771. if (auto *CI = dyn_cast<ConstantInt>(BI->getCondition())) {
  7772. bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
  7773. if (ExitIfTrue == CI->isZero())
  7774. continue;
  7775. }
  7776. ExitLimit EL = computeExitLimit(L, ExitBB, AllowPredicates);
  7777. assert((AllowPredicates || EL.Predicates.empty()) &&
  7778. "Predicated exit limit when predicates are not allowed!");
  7779. // 1. For each exit that can be computed, add an entry to ExitCounts.
  7780. // CouldComputeBECount is true only if all exits can be computed.
  7781. if (EL.ExactNotTaken == getCouldNotCompute())
  7782. // We couldn't compute an exact value for this exit, so
  7783. // we won't be able to compute an exact value for the loop.
  7784. CouldComputeBECount = false;
  7785. // Remember exit count if either exact or symbolic is known. Because
  7786. // Exact always implies symbolic, only check symbolic.
  7787. if (EL.SymbolicMaxNotTaken != getCouldNotCompute())
  7788. ExitCounts.emplace_back(ExitBB, EL);
  7789. else
  7790. assert(EL.ExactNotTaken == getCouldNotCompute() &&
  7791. "Exact is known but symbolic isn't?");
  7792. // 2. Derive the loop's MaxBECount from each exit's max number of
  7793. // non-exiting iterations. Partition the loop exits into two kinds:
  7794. // LoopMustExits and LoopMayExits.
  7795. //
  7796. // If the exit dominates the loop latch, it is a LoopMustExit otherwise it
  7797. // is a LoopMayExit. If any computable LoopMustExit is found, then
  7798. // MaxBECount is the minimum EL.ConstantMaxNotTaken of computable
  7799. // LoopMustExits. Otherwise, MaxBECount is conservatively the maximum
  7800. // EL.ConstantMaxNotTaken, where CouldNotCompute is considered greater than
  7801. // any
  7802. // computable EL.ConstantMaxNotTaken.
  7803. if (EL.ConstantMaxNotTaken != getCouldNotCompute() && Latch &&
  7804. DT.dominates(ExitBB, Latch)) {
  7805. if (!MustExitMaxBECount) {
  7806. MustExitMaxBECount = EL.ConstantMaxNotTaken;
  7807. MustExitMaxOrZero = EL.MaxOrZero;
  7808. } else {
  7809. MustExitMaxBECount = getUMinFromMismatchedTypes(MustExitMaxBECount,
  7810. EL.ConstantMaxNotTaken);
  7811. }
  7812. } else if (MayExitMaxBECount != getCouldNotCompute()) {
  7813. if (!MayExitMaxBECount || EL.ConstantMaxNotTaken == getCouldNotCompute())
  7814. MayExitMaxBECount = EL.ConstantMaxNotTaken;
  7815. else {
  7816. MayExitMaxBECount = getUMaxFromMismatchedTypes(MayExitMaxBECount,
  7817. EL.ConstantMaxNotTaken);
  7818. }
  7819. }
  7820. }
  7821. const SCEV *MaxBECount = MustExitMaxBECount ? MustExitMaxBECount :
  7822. (MayExitMaxBECount ? MayExitMaxBECount : getCouldNotCompute());
  7823. // The loop backedge will be taken the maximum or zero times if there's
  7824. // a single exit that must be taken the maximum or zero times.
  7825. bool MaxOrZero = (MustExitMaxOrZero && ExitingBlocks.size() == 1);
  7826. // Remember which SCEVs are used in exit limits for invalidation purposes.
  7827. // We only care about non-constant SCEVs here, so we can ignore
  7828. // EL.ConstantMaxNotTaken
  7829. // and MaxBECount, which must be SCEVConstant.
  7830. for (const auto &Pair : ExitCounts) {
  7831. if (!isa<SCEVConstant>(Pair.second.ExactNotTaken))
  7832. BECountUsers[Pair.second.ExactNotTaken].insert({L, AllowPredicates});
  7833. if (!isa<SCEVConstant>(Pair.second.SymbolicMaxNotTaken))
  7834. BECountUsers[Pair.second.SymbolicMaxNotTaken].insert(
  7835. {L, AllowPredicates});
  7836. }
  7837. return BackedgeTakenInfo(std::move(ExitCounts), CouldComputeBECount,
  7838. MaxBECount, MaxOrZero);
  7839. }
  7840. ScalarEvolution::ExitLimit
  7841. ScalarEvolution::computeExitLimit(const Loop *L, BasicBlock *ExitingBlock,
  7842. bool AllowPredicates) {
  7843. assert(L->contains(ExitingBlock) && "Exit count for non-loop block?");
  7844. // If our exiting block does not dominate the latch, then its connection with
  7845. // loop's exit limit may be far from trivial.
  7846. const BasicBlock *Latch = L->getLoopLatch();
  7847. if (!Latch || !DT.dominates(ExitingBlock, Latch))
  7848. return getCouldNotCompute();
  7849. bool IsOnlyExit = (L->getExitingBlock() != nullptr);
  7850. Instruction *Term = ExitingBlock->getTerminator();
  7851. if (BranchInst *BI = dyn_cast<BranchInst>(Term)) {
  7852. assert(BI->isConditional() && "If unconditional, it can't be in loop!");
  7853. bool ExitIfTrue = !L->contains(BI->getSuccessor(0));
  7854. assert(ExitIfTrue == L->contains(BI->getSuccessor(1)) &&
  7855. "It should have one successor in loop and one exit block!");
  7856. // Proceed to the next level to examine the exit condition expression.
  7857. return computeExitLimitFromCond(
  7858. L, BI->getCondition(), ExitIfTrue,
  7859. /*ControlsExit=*/IsOnlyExit, AllowPredicates);
  7860. }
  7861. if (SwitchInst *SI = dyn_cast<SwitchInst>(Term)) {
  7862. // For switch, make sure that there is a single exit from the loop.
  7863. BasicBlock *Exit = nullptr;
  7864. for (auto *SBB : successors(ExitingBlock))
  7865. if (!L->contains(SBB)) {
  7866. if (Exit) // Multiple exit successors.
  7867. return getCouldNotCompute();
  7868. Exit = SBB;
  7869. }
  7870. assert(Exit && "Exiting block must have at least one exit");
  7871. return computeExitLimitFromSingleExitSwitch(L, SI, Exit,
  7872. /*ControlsExit=*/IsOnlyExit);
  7873. }
  7874. return getCouldNotCompute();
  7875. }
  7876. ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCond(
  7877. const Loop *L, Value *ExitCond, bool ExitIfTrue,
  7878. bool ControlsExit, bool AllowPredicates) {
  7879. ScalarEvolution::ExitLimitCacheTy Cache(L, ExitIfTrue, AllowPredicates);
  7880. return computeExitLimitFromCondCached(Cache, L, ExitCond, ExitIfTrue,
  7881. ControlsExit, AllowPredicates);
  7882. }
  7883. std::optional<ScalarEvolution::ExitLimit>
  7884. ScalarEvolution::ExitLimitCache::find(const Loop *L, Value *ExitCond,
  7885. bool ExitIfTrue, bool ControlsExit,
  7886. bool AllowPredicates) {
  7887. (void)this->L;
  7888. (void)this->ExitIfTrue;
  7889. (void)this->AllowPredicates;
  7890. assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
  7891. this->AllowPredicates == AllowPredicates &&
  7892. "Variance in assumed invariant key components!");
  7893. auto Itr = TripCountMap.find({ExitCond, ControlsExit});
  7894. if (Itr == TripCountMap.end())
  7895. return std::nullopt;
  7896. return Itr->second;
  7897. }
  7898. void ScalarEvolution::ExitLimitCache::insert(const Loop *L, Value *ExitCond,
  7899. bool ExitIfTrue,
  7900. bool ControlsExit,
  7901. bool AllowPredicates,
  7902. const ExitLimit &EL) {
  7903. assert(this->L == L && this->ExitIfTrue == ExitIfTrue &&
  7904. this->AllowPredicates == AllowPredicates &&
  7905. "Variance in assumed invariant key components!");
  7906. auto InsertResult = TripCountMap.insert({{ExitCond, ControlsExit}, EL});
  7907. assert(InsertResult.second && "Expected successful insertion!");
  7908. (void)InsertResult;
  7909. (void)ExitIfTrue;
  7910. }
  7911. ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondCached(
  7912. ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
  7913. bool ControlsExit, bool AllowPredicates) {
  7914. if (auto MaybeEL =
  7915. Cache.find(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
  7916. return *MaybeEL;
  7917. ExitLimit EL = computeExitLimitFromCondImpl(Cache, L, ExitCond, ExitIfTrue,
  7918. ControlsExit, AllowPredicates);
  7919. Cache.insert(L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates, EL);
  7920. return EL;
  7921. }
  7922. ScalarEvolution::ExitLimit ScalarEvolution::computeExitLimitFromCondImpl(
  7923. ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
  7924. bool ControlsExit, bool AllowPredicates) {
  7925. // Handle BinOp conditions (And, Or).
  7926. if (auto LimitFromBinOp = computeExitLimitFromCondFromBinOp(
  7927. Cache, L, ExitCond, ExitIfTrue, ControlsExit, AllowPredicates))
  7928. return *LimitFromBinOp;
  7929. // With an icmp, it may be feasible to compute an exact backedge-taken count.
  7930. // Proceed to the next level to examine the icmp.
  7931. if (ICmpInst *ExitCondICmp = dyn_cast<ICmpInst>(ExitCond)) {
  7932. ExitLimit EL =
  7933. computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit);
  7934. if (EL.hasFullInfo() || !AllowPredicates)
  7935. return EL;
  7936. // Try again, but use SCEV predicates this time.
  7937. return computeExitLimitFromICmp(L, ExitCondICmp, ExitIfTrue, ControlsExit,
  7938. /*AllowPredicates=*/true);
  7939. }
  7940. // Check for a constant condition. These are normally stripped out by
  7941. // SimplifyCFG, but ScalarEvolution may be used by a pass which wishes to
  7942. // preserve the CFG and is temporarily leaving constant conditions
  7943. // in place.
  7944. if (ConstantInt *CI = dyn_cast<ConstantInt>(ExitCond)) {
  7945. if (ExitIfTrue == !CI->getZExtValue())
  7946. // The backedge is always taken.
  7947. return getCouldNotCompute();
  7948. else
  7949. // The backedge is never taken.
  7950. return getZero(CI->getType());
  7951. }
  7952. // If we're exiting based on the overflow flag of an x.with.overflow intrinsic
  7953. // with a constant step, we can form an equivalent icmp predicate and figure
  7954. // out how many iterations will be taken before we exit.
  7955. const WithOverflowInst *WO;
  7956. const APInt *C;
  7957. if (match(ExitCond, m_ExtractValue<1>(m_WithOverflowInst(WO))) &&
  7958. match(WO->getRHS(), m_APInt(C))) {
  7959. ConstantRange NWR =
  7960. ConstantRange::makeExactNoWrapRegion(WO->getBinaryOp(), *C,
  7961. WO->getNoWrapKind());
  7962. CmpInst::Predicate Pred;
  7963. APInt NewRHSC, Offset;
  7964. NWR.getEquivalentICmp(Pred, NewRHSC, Offset);
  7965. if (!ExitIfTrue)
  7966. Pred = ICmpInst::getInversePredicate(Pred);
  7967. auto *LHS = getSCEV(WO->getLHS());
  7968. if (Offset != 0)
  7969. LHS = getAddExpr(LHS, getConstant(Offset));
  7970. auto EL = computeExitLimitFromICmp(L, Pred, LHS, getConstant(NewRHSC),
  7971. ControlsExit, AllowPredicates);
  7972. if (EL.hasAnyInfo()) return EL;
  7973. }
  7974. // If it's not an integer or pointer comparison then compute it the hard way.
  7975. return computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
  7976. }
  7977. std::optional<ScalarEvolution::ExitLimit>
  7978. ScalarEvolution::computeExitLimitFromCondFromBinOp(
  7979. ExitLimitCacheTy &Cache, const Loop *L, Value *ExitCond, bool ExitIfTrue,
  7980. bool ControlsExit, bool AllowPredicates) {
  7981. // Check if the controlling expression for this loop is an And or Or.
  7982. Value *Op0, *Op1;
  7983. bool IsAnd = false;
  7984. if (match(ExitCond, m_LogicalAnd(m_Value(Op0), m_Value(Op1))))
  7985. IsAnd = true;
  7986. else if (match(ExitCond, m_LogicalOr(m_Value(Op0), m_Value(Op1))))
  7987. IsAnd = false;
  7988. else
  7989. return std::nullopt;
  7990. // EitherMayExit is true in these two cases:
  7991. // br (and Op0 Op1), loop, exit
  7992. // br (or Op0 Op1), exit, loop
  7993. bool EitherMayExit = IsAnd ^ ExitIfTrue;
  7994. ExitLimit EL0 = computeExitLimitFromCondCached(Cache, L, Op0, ExitIfTrue,
  7995. ControlsExit && !EitherMayExit,
  7996. AllowPredicates);
  7997. ExitLimit EL1 = computeExitLimitFromCondCached(Cache, L, Op1, ExitIfTrue,
  7998. ControlsExit && !EitherMayExit,
  7999. AllowPredicates);
  8000. // Be robust against unsimplified IR for the form "op i1 X, NeutralElement"
  8001. const Constant *NeutralElement = ConstantInt::get(ExitCond->getType(), IsAnd);
  8002. if (isa<ConstantInt>(Op1))
  8003. return Op1 == NeutralElement ? EL0 : EL1;
  8004. if (isa<ConstantInt>(Op0))
  8005. return Op0 == NeutralElement ? EL1 : EL0;
  8006. const SCEV *BECount = getCouldNotCompute();
  8007. const SCEV *ConstantMaxBECount = getCouldNotCompute();
  8008. const SCEV *SymbolicMaxBECount = getCouldNotCompute();
  8009. if (EitherMayExit) {
  8010. bool UseSequentialUMin = !isa<BinaryOperator>(ExitCond);
  8011. // Both conditions must be same for the loop to continue executing.
  8012. // Choose the less conservative count.
  8013. if (EL0.ExactNotTaken != getCouldNotCompute() &&
  8014. EL1.ExactNotTaken != getCouldNotCompute()) {
  8015. BECount = getUMinFromMismatchedTypes(EL0.ExactNotTaken, EL1.ExactNotTaken,
  8016. UseSequentialUMin);
  8017. }
  8018. if (EL0.ConstantMaxNotTaken == getCouldNotCompute())
  8019. ConstantMaxBECount = EL1.ConstantMaxNotTaken;
  8020. else if (EL1.ConstantMaxNotTaken == getCouldNotCompute())
  8021. ConstantMaxBECount = EL0.ConstantMaxNotTaken;
  8022. else
  8023. ConstantMaxBECount = getUMinFromMismatchedTypes(EL0.ConstantMaxNotTaken,
  8024. EL1.ConstantMaxNotTaken);
  8025. if (EL0.SymbolicMaxNotTaken == getCouldNotCompute())
  8026. SymbolicMaxBECount = EL1.SymbolicMaxNotTaken;
  8027. else if (EL1.SymbolicMaxNotTaken == getCouldNotCompute())
  8028. SymbolicMaxBECount = EL0.SymbolicMaxNotTaken;
  8029. else
  8030. SymbolicMaxBECount = getUMinFromMismatchedTypes(
  8031. EL0.SymbolicMaxNotTaken, EL1.SymbolicMaxNotTaken, UseSequentialUMin);
  8032. } else {
  8033. // Both conditions must be same at the same time for the loop to exit.
  8034. // For now, be conservative.
  8035. if (EL0.ExactNotTaken == EL1.ExactNotTaken)
  8036. BECount = EL0.ExactNotTaken;
  8037. }
  8038. // There are cases (e.g. PR26207) where computeExitLimitFromCond is able
  8039. // to be more aggressive when computing BECount than when computing
  8040. // ConstantMaxBECount. In these cases it is possible for EL0.ExactNotTaken
  8041. // and
  8042. // EL1.ExactNotTaken to match, but for EL0.ConstantMaxNotTaken and
  8043. // EL1.ConstantMaxNotTaken to not.
  8044. if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
  8045. !isa<SCEVCouldNotCompute>(BECount))
  8046. ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
  8047. if (isa<SCEVCouldNotCompute>(SymbolicMaxBECount))
  8048. SymbolicMaxBECount =
  8049. isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
  8050. return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
  8051. { &EL0.Predicates, &EL1.Predicates });
  8052. }
  8053. ScalarEvolution::ExitLimit
  8054. ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
  8055. ICmpInst *ExitCond,
  8056. bool ExitIfTrue,
  8057. bool ControlsExit,
  8058. bool AllowPredicates) {
  8059. // If the condition was exit on true, convert the condition to exit on false
  8060. ICmpInst::Predicate Pred;
  8061. if (!ExitIfTrue)
  8062. Pred = ExitCond->getPredicate();
  8063. else
  8064. Pred = ExitCond->getInversePredicate();
  8065. const ICmpInst::Predicate OriginalPred = Pred;
  8066. const SCEV *LHS = getSCEV(ExitCond->getOperand(0));
  8067. const SCEV *RHS = getSCEV(ExitCond->getOperand(1));
  8068. ExitLimit EL = computeExitLimitFromICmp(L, Pred, LHS, RHS, ControlsExit,
  8069. AllowPredicates);
  8070. if (EL.hasAnyInfo()) return EL;
  8071. auto *ExhaustiveCount =
  8072. computeExitCountExhaustively(L, ExitCond, ExitIfTrue);
  8073. if (!isa<SCEVCouldNotCompute>(ExhaustiveCount))
  8074. return ExhaustiveCount;
  8075. return computeShiftCompareExitLimit(ExitCond->getOperand(0),
  8076. ExitCond->getOperand(1), L, OriginalPred);
  8077. }
  8078. ScalarEvolution::ExitLimit
  8079. ScalarEvolution::computeExitLimitFromICmp(const Loop *L,
  8080. ICmpInst::Predicate Pred,
  8081. const SCEV *LHS, const SCEV *RHS,
  8082. bool ControlsExit,
  8083. bool AllowPredicates) {
  8084. // Try to evaluate any dependencies out of the loop.
  8085. LHS = getSCEVAtScope(LHS, L);
  8086. RHS = getSCEVAtScope(RHS, L);
  8087. // At this point, we would like to compute how many iterations of the
  8088. // loop the predicate will return true for these inputs.
  8089. if (isLoopInvariant(LHS, L) && !isLoopInvariant(RHS, L)) {
  8090. // If there is a loop-invariant, force it into the RHS.
  8091. std::swap(LHS, RHS);
  8092. Pred = ICmpInst::getSwappedPredicate(Pred);
  8093. }
  8094. bool ControllingFiniteLoop =
  8095. ControlsExit && loopHasNoAbnormalExits(L) && loopIsFiniteByAssumption(L);
  8096. // Simplify the operands before analyzing them.
  8097. (void)SimplifyICmpOperands(Pred, LHS, RHS, /*Depth=*/0,
  8098. (EnableFiniteLoopControl ? ControllingFiniteLoop
  8099. : false));
  8100. // If we have a comparison of a chrec against a constant, try to use value
  8101. // ranges to answer this query.
  8102. if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
  8103. if (const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
  8104. if (AddRec->getLoop() == L) {
  8105. // Form the constant range.
  8106. ConstantRange CompRange =
  8107. ConstantRange::makeExactICmpRegion(Pred, RHSC->getAPInt());
  8108. const SCEV *Ret = AddRec->getNumIterationsInRange(CompRange, *this);
  8109. if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
  8110. }
  8111. // If this loop must exit based on this condition (or execute undefined
  8112. // behaviour), and we can prove the test sequence produced must repeat
  8113. // the same values on self-wrap of the IV, then we can infer that IV
  8114. // doesn't self wrap because if it did, we'd have an infinite (undefined)
  8115. // loop.
  8116. if (ControllingFiniteLoop && isLoopInvariant(RHS, L)) {
  8117. // TODO: We can peel off any functions which are invertible *in L*. Loop
  8118. // invariant terms are effectively constants for our purposes here.
  8119. auto *InnerLHS = LHS;
  8120. if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS))
  8121. InnerLHS = ZExt->getOperand();
  8122. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(InnerLHS)) {
  8123. auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
  8124. if (!AR->hasNoSelfWrap() && AR->getLoop() == L && AR->isAffine() &&
  8125. StrideC && StrideC->getAPInt().isPowerOf2()) {
  8126. auto Flags = AR->getNoWrapFlags();
  8127. Flags = setFlags(Flags, SCEV::FlagNW);
  8128. SmallVector<const SCEV*> Operands{AR->operands()};
  8129. Flags = StrengthenNoWrapFlags(this, scAddRecExpr, Operands, Flags);
  8130. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
  8131. }
  8132. }
  8133. }
  8134. switch (Pred) {
  8135. case ICmpInst::ICMP_NE: { // while (X != Y)
  8136. // Convert to: while (X-Y != 0)
  8137. if (LHS->getType()->isPointerTy()) {
  8138. LHS = getLosslessPtrToIntExpr(LHS);
  8139. if (isa<SCEVCouldNotCompute>(LHS))
  8140. return LHS;
  8141. }
  8142. if (RHS->getType()->isPointerTy()) {
  8143. RHS = getLosslessPtrToIntExpr(RHS);
  8144. if (isa<SCEVCouldNotCompute>(RHS))
  8145. return RHS;
  8146. }
  8147. ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit,
  8148. AllowPredicates);
  8149. if (EL.hasAnyInfo()) return EL;
  8150. break;
  8151. }
  8152. case ICmpInst::ICMP_EQ: { // while (X == Y)
  8153. // Convert to: while (X-Y == 0)
  8154. if (LHS->getType()->isPointerTy()) {
  8155. LHS = getLosslessPtrToIntExpr(LHS);
  8156. if (isa<SCEVCouldNotCompute>(LHS))
  8157. return LHS;
  8158. }
  8159. if (RHS->getType()->isPointerTy()) {
  8160. RHS = getLosslessPtrToIntExpr(RHS);
  8161. if (isa<SCEVCouldNotCompute>(RHS))
  8162. return RHS;
  8163. }
  8164. ExitLimit EL = howFarToNonZero(getMinusSCEV(LHS, RHS), L);
  8165. if (EL.hasAnyInfo()) return EL;
  8166. break;
  8167. }
  8168. case ICmpInst::ICMP_SLT:
  8169. case ICmpInst::ICMP_ULT: { // while (X < Y)
  8170. bool IsSigned = Pred == ICmpInst::ICMP_SLT;
  8171. ExitLimit EL = howManyLessThans(LHS, RHS, L, IsSigned, ControlsExit,
  8172. AllowPredicates);
  8173. if (EL.hasAnyInfo()) return EL;
  8174. break;
  8175. }
  8176. case ICmpInst::ICMP_SGT:
  8177. case ICmpInst::ICMP_UGT: { // while (X > Y)
  8178. bool IsSigned = Pred == ICmpInst::ICMP_SGT;
  8179. ExitLimit EL =
  8180. howManyGreaterThans(LHS, RHS, L, IsSigned, ControlsExit,
  8181. AllowPredicates);
  8182. if (EL.hasAnyInfo()) return EL;
  8183. break;
  8184. }
  8185. default:
  8186. break;
  8187. }
  8188. return getCouldNotCompute();
  8189. }
  8190. ScalarEvolution::ExitLimit
  8191. ScalarEvolution::computeExitLimitFromSingleExitSwitch(const Loop *L,
  8192. SwitchInst *Switch,
  8193. BasicBlock *ExitingBlock,
  8194. bool ControlsExit) {
  8195. assert(!L->contains(ExitingBlock) && "Not an exiting block!");
  8196. // Give up if the exit is the default dest of a switch.
  8197. if (Switch->getDefaultDest() == ExitingBlock)
  8198. return getCouldNotCompute();
  8199. assert(L->contains(Switch->getDefaultDest()) &&
  8200. "Default case must not exit the loop!");
  8201. const SCEV *LHS = getSCEVAtScope(Switch->getCondition(), L);
  8202. const SCEV *RHS = getConstant(Switch->findCaseDest(ExitingBlock));
  8203. // while (X != Y) --> while (X-Y != 0)
  8204. ExitLimit EL = howFarToZero(getMinusSCEV(LHS, RHS), L, ControlsExit);
  8205. if (EL.hasAnyInfo())
  8206. return EL;
  8207. return getCouldNotCompute();
  8208. }
  8209. static ConstantInt *
  8210. EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
  8211. ScalarEvolution &SE) {
  8212. const SCEV *InVal = SE.getConstant(C);
  8213. const SCEV *Val = AddRec->evaluateAtIteration(InVal, SE);
  8214. assert(isa<SCEVConstant>(Val) &&
  8215. "Evaluation of SCEV at constant didn't fold correctly?");
  8216. return cast<SCEVConstant>(Val)->getValue();
  8217. }
  8218. ScalarEvolution::ExitLimit ScalarEvolution::computeShiftCompareExitLimit(
  8219. Value *LHS, Value *RHSV, const Loop *L, ICmpInst::Predicate Pred) {
  8220. ConstantInt *RHS = dyn_cast<ConstantInt>(RHSV);
  8221. if (!RHS)
  8222. return getCouldNotCompute();
  8223. const BasicBlock *Latch = L->getLoopLatch();
  8224. if (!Latch)
  8225. return getCouldNotCompute();
  8226. const BasicBlock *Predecessor = L->getLoopPredecessor();
  8227. if (!Predecessor)
  8228. return getCouldNotCompute();
  8229. // Return true if V is of the form "LHS `shift_op` <positive constant>".
  8230. // Return LHS in OutLHS and shift_opt in OutOpCode.
  8231. auto MatchPositiveShift =
  8232. [](Value *V, Value *&OutLHS, Instruction::BinaryOps &OutOpCode) {
  8233. using namespace PatternMatch;
  8234. ConstantInt *ShiftAmt;
  8235. if (match(V, m_LShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
  8236. OutOpCode = Instruction::LShr;
  8237. else if (match(V, m_AShr(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
  8238. OutOpCode = Instruction::AShr;
  8239. else if (match(V, m_Shl(m_Value(OutLHS), m_ConstantInt(ShiftAmt))))
  8240. OutOpCode = Instruction::Shl;
  8241. else
  8242. return false;
  8243. return ShiftAmt->getValue().isStrictlyPositive();
  8244. };
  8245. // Recognize a "shift recurrence" either of the form %iv or of %iv.shifted in
  8246. //
  8247. // loop:
  8248. // %iv = phi i32 [ %iv.shifted, %loop ], [ %val, %preheader ]
  8249. // %iv.shifted = lshr i32 %iv, <positive constant>
  8250. //
  8251. // Return true on a successful match. Return the corresponding PHI node (%iv
  8252. // above) in PNOut and the opcode of the shift operation in OpCodeOut.
  8253. auto MatchShiftRecurrence =
  8254. [&](Value *V, PHINode *&PNOut, Instruction::BinaryOps &OpCodeOut) {
  8255. std::optional<Instruction::BinaryOps> PostShiftOpCode;
  8256. {
  8257. Instruction::BinaryOps OpC;
  8258. Value *V;
  8259. // If we encounter a shift instruction, "peel off" the shift operation,
  8260. // and remember that we did so. Later when we inspect %iv's backedge
  8261. // value, we will make sure that the backedge value uses the same
  8262. // operation.
  8263. //
  8264. // Note: the peeled shift operation does not have to be the same
  8265. // instruction as the one feeding into the PHI's backedge value. We only
  8266. // really care about it being the same *kind* of shift instruction --
  8267. // that's all that is required for our later inferences to hold.
  8268. if (MatchPositiveShift(LHS, V, OpC)) {
  8269. PostShiftOpCode = OpC;
  8270. LHS = V;
  8271. }
  8272. }
  8273. PNOut = dyn_cast<PHINode>(LHS);
  8274. if (!PNOut || PNOut->getParent() != L->getHeader())
  8275. return false;
  8276. Value *BEValue = PNOut->getIncomingValueForBlock(Latch);
  8277. Value *OpLHS;
  8278. return
  8279. // The backedge value for the PHI node must be a shift by a positive
  8280. // amount
  8281. MatchPositiveShift(BEValue, OpLHS, OpCodeOut) &&
  8282. // of the PHI node itself
  8283. OpLHS == PNOut &&
  8284. // and the kind of shift should be match the kind of shift we peeled
  8285. // off, if any.
  8286. (!PostShiftOpCode || *PostShiftOpCode == OpCodeOut);
  8287. };
  8288. PHINode *PN;
  8289. Instruction::BinaryOps OpCode;
  8290. if (!MatchShiftRecurrence(LHS, PN, OpCode))
  8291. return getCouldNotCompute();
  8292. const DataLayout &DL = getDataLayout();
  8293. // The key rationale for this optimization is that for some kinds of shift
  8294. // recurrences, the value of the recurrence "stabilizes" to either 0 or -1
  8295. // within a finite number of iterations. If the condition guarding the
  8296. // backedge (in the sense that the backedge is taken if the condition is true)
  8297. // is false for the value the shift recurrence stabilizes to, then we know
  8298. // that the backedge is taken only a finite number of times.
  8299. ConstantInt *StableValue = nullptr;
  8300. switch (OpCode) {
  8301. default:
  8302. llvm_unreachable("Impossible case!");
  8303. case Instruction::AShr: {
  8304. // {K,ashr,<positive-constant>} stabilizes to signum(K) in at most
  8305. // bitwidth(K) iterations.
  8306. Value *FirstValue = PN->getIncomingValueForBlock(Predecessor);
  8307. KnownBits Known = computeKnownBits(FirstValue, DL, 0, &AC,
  8308. Predecessor->getTerminator(), &DT);
  8309. auto *Ty = cast<IntegerType>(RHS->getType());
  8310. if (Known.isNonNegative())
  8311. StableValue = ConstantInt::get(Ty, 0);
  8312. else if (Known.isNegative())
  8313. StableValue = ConstantInt::get(Ty, -1, true);
  8314. else
  8315. return getCouldNotCompute();
  8316. break;
  8317. }
  8318. case Instruction::LShr:
  8319. case Instruction::Shl:
  8320. // Both {K,lshr,<positive-constant>} and {K,shl,<positive-constant>}
  8321. // stabilize to 0 in at most bitwidth(K) iterations.
  8322. StableValue = ConstantInt::get(cast<IntegerType>(RHS->getType()), 0);
  8323. break;
  8324. }
  8325. auto *Result =
  8326. ConstantFoldCompareInstOperands(Pred, StableValue, RHS, DL, &TLI);
  8327. assert(Result->getType()->isIntegerTy(1) &&
  8328. "Otherwise cannot be an operand to a branch instruction");
  8329. if (Result->isZeroValue()) {
  8330. unsigned BitWidth = getTypeSizeInBits(RHS->getType());
  8331. const SCEV *UpperBound =
  8332. getConstant(getEffectiveSCEVType(RHS->getType()), BitWidth);
  8333. return ExitLimit(getCouldNotCompute(), UpperBound, UpperBound, false);
  8334. }
  8335. return getCouldNotCompute();
  8336. }
  8337. /// Return true if we can constant fold an instruction of the specified type,
  8338. /// assuming that all operands were constants.
  8339. static bool CanConstantFold(const Instruction *I) {
  8340. if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
  8341. isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
  8342. isa<LoadInst>(I) || isa<ExtractValueInst>(I))
  8343. return true;
  8344. if (const CallInst *CI = dyn_cast<CallInst>(I))
  8345. if (const Function *F = CI->getCalledFunction())
  8346. return canConstantFoldCallTo(CI, F);
  8347. return false;
  8348. }
  8349. /// Determine whether this instruction can constant evolve within this loop
  8350. /// assuming its operands can all constant evolve.
  8351. static bool canConstantEvolve(Instruction *I, const Loop *L) {
  8352. // An instruction outside of the loop can't be derived from a loop PHI.
  8353. if (!L->contains(I)) return false;
  8354. if (isa<PHINode>(I)) {
  8355. // We don't currently keep track of the control flow needed to evaluate
  8356. // PHIs, so we cannot handle PHIs inside of loops.
  8357. return L->getHeader() == I->getParent();
  8358. }
  8359. // If we won't be able to constant fold this expression even if the operands
  8360. // are constants, bail early.
  8361. return CanConstantFold(I);
  8362. }
  8363. /// getConstantEvolvingPHIOperands - Implement getConstantEvolvingPHI by
  8364. /// recursing through each instruction operand until reaching a loop header phi.
  8365. static PHINode *
  8366. getConstantEvolvingPHIOperands(Instruction *UseInst, const Loop *L,
  8367. DenseMap<Instruction *, PHINode *> &PHIMap,
  8368. unsigned Depth) {
  8369. if (Depth > MaxConstantEvolvingDepth)
  8370. return nullptr;
  8371. // Otherwise, we can evaluate this instruction if all of its operands are
  8372. // constant or derived from a PHI node themselves.
  8373. PHINode *PHI = nullptr;
  8374. for (Value *Op : UseInst->operands()) {
  8375. if (isa<Constant>(Op)) continue;
  8376. Instruction *OpInst = dyn_cast<Instruction>(Op);
  8377. if (!OpInst || !canConstantEvolve(OpInst, L)) return nullptr;
  8378. PHINode *P = dyn_cast<PHINode>(OpInst);
  8379. if (!P)
  8380. // If this operand is already visited, reuse the prior result.
  8381. // We may have P != PHI if this is the deepest point at which the
  8382. // inconsistent paths meet.
  8383. P = PHIMap.lookup(OpInst);
  8384. if (!P) {
  8385. // Recurse and memoize the results, whether a phi is found or not.
  8386. // This recursive call invalidates pointers into PHIMap.
  8387. P = getConstantEvolvingPHIOperands(OpInst, L, PHIMap, Depth + 1);
  8388. PHIMap[OpInst] = P;
  8389. }
  8390. if (!P)
  8391. return nullptr; // Not evolving from PHI
  8392. if (PHI && PHI != P)
  8393. return nullptr; // Evolving from multiple different PHIs.
  8394. PHI = P;
  8395. }
  8396. // This is a expression evolving from a constant PHI!
  8397. return PHI;
  8398. }
  8399. /// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
  8400. /// in the loop that V is derived from. We allow arbitrary operations along the
  8401. /// way, but the operands of an operation must either be constants or a value
  8402. /// derived from a constant PHI. If this expression does not fit with these
  8403. /// constraints, return null.
  8404. static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
  8405. Instruction *I = dyn_cast<Instruction>(V);
  8406. if (!I || !canConstantEvolve(I, L)) return nullptr;
  8407. if (PHINode *PN = dyn_cast<PHINode>(I))
  8408. return PN;
  8409. // Record non-constant instructions contained by the loop.
  8410. DenseMap<Instruction *, PHINode *> PHIMap;
  8411. return getConstantEvolvingPHIOperands(I, L, PHIMap, 0);
  8412. }
  8413. /// EvaluateExpression - Given an expression that passes the
  8414. /// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
  8415. /// in the loop has the value PHIVal. If we can't fold this expression for some
  8416. /// reason, return null.
  8417. static Constant *EvaluateExpression(Value *V, const Loop *L,
  8418. DenseMap<Instruction *, Constant *> &Vals,
  8419. const DataLayout &DL,
  8420. const TargetLibraryInfo *TLI) {
  8421. // Convenient constant check, but redundant for recursive calls.
  8422. if (Constant *C = dyn_cast<Constant>(V)) return C;
  8423. Instruction *I = dyn_cast<Instruction>(V);
  8424. if (!I) return nullptr;
  8425. if (Constant *C = Vals.lookup(I)) return C;
  8426. // An instruction inside the loop depends on a value outside the loop that we
  8427. // weren't given a mapping for, or a value such as a call inside the loop.
  8428. if (!canConstantEvolve(I, L)) return nullptr;
  8429. // An unmapped PHI can be due to a branch or another loop inside this loop,
  8430. // or due to this not being the initial iteration through a loop where we
  8431. // couldn't compute the evolution of this particular PHI last time.
  8432. if (isa<PHINode>(I)) return nullptr;
  8433. std::vector<Constant*> Operands(I->getNumOperands());
  8434. for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
  8435. Instruction *Operand = dyn_cast<Instruction>(I->getOperand(i));
  8436. if (!Operand) {
  8437. Operands[i] = dyn_cast<Constant>(I->getOperand(i));
  8438. if (!Operands[i]) return nullptr;
  8439. continue;
  8440. }
  8441. Constant *C = EvaluateExpression(Operand, L, Vals, DL, TLI);
  8442. Vals[Operand] = C;
  8443. if (!C) return nullptr;
  8444. Operands[i] = C;
  8445. }
  8446. return ConstantFoldInstOperands(I, Operands, DL, TLI);
  8447. }
  8448. // If every incoming value to PN except the one for BB is a specific Constant,
  8449. // return that, else return nullptr.
  8450. static Constant *getOtherIncomingValue(PHINode *PN, BasicBlock *BB) {
  8451. Constant *IncomingVal = nullptr;
  8452. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  8453. if (PN->getIncomingBlock(i) == BB)
  8454. continue;
  8455. auto *CurrentVal = dyn_cast<Constant>(PN->getIncomingValue(i));
  8456. if (!CurrentVal)
  8457. return nullptr;
  8458. if (IncomingVal != CurrentVal) {
  8459. if (IncomingVal)
  8460. return nullptr;
  8461. IncomingVal = CurrentVal;
  8462. }
  8463. }
  8464. return IncomingVal;
  8465. }
  8466. /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
  8467. /// in the header of its containing loop, we know the loop executes a
  8468. /// constant number of times, and the PHI node is just a recurrence
  8469. /// involving constants, fold it.
  8470. Constant *
  8471. ScalarEvolution::getConstantEvolutionLoopExitValue(PHINode *PN,
  8472. const APInt &BEs,
  8473. const Loop *L) {
  8474. auto I = ConstantEvolutionLoopExitValue.find(PN);
  8475. if (I != ConstantEvolutionLoopExitValue.end())
  8476. return I->second;
  8477. if (BEs.ugt(MaxBruteForceIterations))
  8478. return ConstantEvolutionLoopExitValue[PN] = nullptr; // Not going to evaluate it.
  8479. Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
  8480. DenseMap<Instruction *, Constant *> CurrentIterVals;
  8481. BasicBlock *Header = L->getHeader();
  8482. assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
  8483. BasicBlock *Latch = L->getLoopLatch();
  8484. if (!Latch)
  8485. return nullptr;
  8486. for (PHINode &PHI : Header->phis()) {
  8487. if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
  8488. CurrentIterVals[&PHI] = StartCST;
  8489. }
  8490. if (!CurrentIterVals.count(PN))
  8491. return RetVal = nullptr;
  8492. Value *BEValue = PN->getIncomingValueForBlock(Latch);
  8493. // Execute the loop symbolically to determine the exit value.
  8494. assert(BEs.getActiveBits() < CHAR_BIT * sizeof(unsigned) &&
  8495. "BEs is <= MaxBruteForceIterations which is an 'unsigned'!");
  8496. unsigned NumIterations = BEs.getZExtValue(); // must be in range
  8497. unsigned IterationNum = 0;
  8498. const DataLayout &DL = getDataLayout();
  8499. for (; ; ++IterationNum) {
  8500. if (IterationNum == NumIterations)
  8501. return RetVal = CurrentIterVals[PN]; // Got exit value!
  8502. // Compute the value of the PHIs for the next iteration.
  8503. // EvaluateExpression adds non-phi values to the CurrentIterVals map.
  8504. DenseMap<Instruction *, Constant *> NextIterVals;
  8505. Constant *NextPHI =
  8506. EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
  8507. if (!NextPHI)
  8508. return nullptr; // Couldn't evaluate!
  8509. NextIterVals[PN] = NextPHI;
  8510. bool StoppedEvolving = NextPHI == CurrentIterVals[PN];
  8511. // Also evaluate the other PHI nodes. However, we don't get to stop if we
  8512. // cease to be able to evaluate one of them or if they stop evolving,
  8513. // because that doesn't necessarily prevent us from computing PN.
  8514. SmallVector<std::pair<PHINode *, Constant *>, 8> PHIsToCompute;
  8515. for (const auto &I : CurrentIterVals) {
  8516. PHINode *PHI = dyn_cast<PHINode>(I.first);
  8517. if (!PHI || PHI == PN || PHI->getParent() != Header) continue;
  8518. PHIsToCompute.emplace_back(PHI, I.second);
  8519. }
  8520. // We use two distinct loops because EvaluateExpression may invalidate any
  8521. // iterators into CurrentIterVals.
  8522. for (const auto &I : PHIsToCompute) {
  8523. PHINode *PHI = I.first;
  8524. Constant *&NextPHI = NextIterVals[PHI];
  8525. if (!NextPHI) { // Not already computed.
  8526. Value *BEValue = PHI->getIncomingValueForBlock(Latch);
  8527. NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
  8528. }
  8529. if (NextPHI != I.second)
  8530. StoppedEvolving = false;
  8531. }
  8532. // If all entries in CurrentIterVals == NextIterVals then we can stop
  8533. // iterating, the loop can't continue to change.
  8534. if (StoppedEvolving)
  8535. return RetVal = CurrentIterVals[PN];
  8536. CurrentIterVals.swap(NextIterVals);
  8537. }
  8538. }
  8539. const SCEV *ScalarEvolution::computeExitCountExhaustively(const Loop *L,
  8540. Value *Cond,
  8541. bool ExitWhen) {
  8542. PHINode *PN = getConstantEvolvingPHI(Cond, L);
  8543. if (!PN) return getCouldNotCompute();
  8544. // If the loop is canonicalized, the PHI will have exactly two entries.
  8545. // That's the only form we support here.
  8546. if (PN->getNumIncomingValues() != 2) return getCouldNotCompute();
  8547. DenseMap<Instruction *, Constant *> CurrentIterVals;
  8548. BasicBlock *Header = L->getHeader();
  8549. assert(PN->getParent() == Header && "Can't evaluate PHI not in loop header!");
  8550. BasicBlock *Latch = L->getLoopLatch();
  8551. assert(Latch && "Should follow from NumIncomingValues == 2!");
  8552. for (PHINode &PHI : Header->phis()) {
  8553. if (auto *StartCST = getOtherIncomingValue(&PHI, Latch))
  8554. CurrentIterVals[&PHI] = StartCST;
  8555. }
  8556. if (!CurrentIterVals.count(PN))
  8557. return getCouldNotCompute();
  8558. // Okay, we find a PHI node that defines the trip count of this loop. Execute
  8559. // the loop symbolically to determine when the condition gets a value of
  8560. // "ExitWhen".
  8561. unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
  8562. const DataLayout &DL = getDataLayout();
  8563. for (unsigned IterationNum = 0; IterationNum != MaxIterations;++IterationNum){
  8564. auto *CondVal = dyn_cast_or_null<ConstantInt>(
  8565. EvaluateExpression(Cond, L, CurrentIterVals, DL, &TLI));
  8566. // Couldn't symbolically evaluate.
  8567. if (!CondVal) return getCouldNotCompute();
  8568. if (CondVal->getValue() == uint64_t(ExitWhen)) {
  8569. ++NumBruteForceTripCountsComputed;
  8570. return getConstant(Type::getInt32Ty(getContext()), IterationNum);
  8571. }
  8572. // Update all the PHI nodes for the next iteration.
  8573. DenseMap<Instruction *, Constant *> NextIterVals;
  8574. // Create a list of which PHIs we need to compute. We want to do this before
  8575. // calling EvaluateExpression on them because that may invalidate iterators
  8576. // into CurrentIterVals.
  8577. SmallVector<PHINode *, 8> PHIsToCompute;
  8578. for (const auto &I : CurrentIterVals) {
  8579. PHINode *PHI = dyn_cast<PHINode>(I.first);
  8580. if (!PHI || PHI->getParent() != Header) continue;
  8581. PHIsToCompute.push_back(PHI);
  8582. }
  8583. for (PHINode *PHI : PHIsToCompute) {
  8584. Constant *&NextPHI = NextIterVals[PHI];
  8585. if (NextPHI) continue; // Already computed!
  8586. Value *BEValue = PHI->getIncomingValueForBlock(Latch);
  8587. NextPHI = EvaluateExpression(BEValue, L, CurrentIterVals, DL, &TLI);
  8588. }
  8589. CurrentIterVals.swap(NextIterVals);
  8590. }
  8591. // Too many iterations were needed to evaluate.
  8592. return getCouldNotCompute();
  8593. }
  8594. const SCEV *ScalarEvolution::getSCEVAtScope(const SCEV *V, const Loop *L) {
  8595. SmallVector<std::pair<const Loop *, const SCEV *>, 2> &Values =
  8596. ValuesAtScopes[V];
  8597. // Check to see if we've folded this expression at this loop before.
  8598. for (auto &LS : Values)
  8599. if (LS.first == L)
  8600. return LS.second ? LS.second : V;
  8601. Values.emplace_back(L, nullptr);
  8602. // Otherwise compute it.
  8603. const SCEV *C = computeSCEVAtScope(V, L);
  8604. for (auto &LS : reverse(ValuesAtScopes[V]))
  8605. if (LS.first == L) {
  8606. LS.second = C;
  8607. if (!isa<SCEVConstant>(C))
  8608. ValuesAtScopesUsers[C].push_back({L, V});
  8609. break;
  8610. }
  8611. return C;
  8612. }
  8613. /// This builds up a Constant using the ConstantExpr interface. That way, we
  8614. /// will return Constants for objects which aren't represented by a
  8615. /// SCEVConstant, because SCEVConstant is restricted to ConstantInt.
  8616. /// Returns NULL if the SCEV isn't representable as a Constant.
  8617. static Constant *BuildConstantFromSCEV(const SCEV *V) {
  8618. switch (V->getSCEVType()) {
  8619. case scCouldNotCompute:
  8620. case scAddRecExpr:
  8621. return nullptr;
  8622. case scConstant:
  8623. return cast<SCEVConstant>(V)->getValue();
  8624. case scUnknown:
  8625. return dyn_cast<Constant>(cast<SCEVUnknown>(V)->getValue());
  8626. case scSignExtend: {
  8627. const SCEVSignExtendExpr *SS = cast<SCEVSignExtendExpr>(V);
  8628. if (Constant *CastOp = BuildConstantFromSCEV(SS->getOperand()))
  8629. return ConstantExpr::getSExt(CastOp, SS->getType());
  8630. return nullptr;
  8631. }
  8632. case scZeroExtend: {
  8633. const SCEVZeroExtendExpr *SZ = cast<SCEVZeroExtendExpr>(V);
  8634. if (Constant *CastOp = BuildConstantFromSCEV(SZ->getOperand()))
  8635. return ConstantExpr::getZExt(CastOp, SZ->getType());
  8636. return nullptr;
  8637. }
  8638. case scPtrToInt: {
  8639. const SCEVPtrToIntExpr *P2I = cast<SCEVPtrToIntExpr>(V);
  8640. if (Constant *CastOp = BuildConstantFromSCEV(P2I->getOperand()))
  8641. return ConstantExpr::getPtrToInt(CastOp, P2I->getType());
  8642. return nullptr;
  8643. }
  8644. case scTruncate: {
  8645. const SCEVTruncateExpr *ST = cast<SCEVTruncateExpr>(V);
  8646. if (Constant *CastOp = BuildConstantFromSCEV(ST->getOperand()))
  8647. return ConstantExpr::getTrunc(CastOp, ST->getType());
  8648. return nullptr;
  8649. }
  8650. case scAddExpr: {
  8651. const SCEVAddExpr *SA = cast<SCEVAddExpr>(V);
  8652. Constant *C = nullptr;
  8653. for (const SCEV *Op : SA->operands()) {
  8654. Constant *OpC = BuildConstantFromSCEV(Op);
  8655. if (!OpC)
  8656. return nullptr;
  8657. if (!C) {
  8658. C = OpC;
  8659. continue;
  8660. }
  8661. assert(!C->getType()->isPointerTy() &&
  8662. "Can only have one pointer, and it must be last");
  8663. if (auto *PT = dyn_cast<PointerType>(OpC->getType())) {
  8664. // The offsets have been converted to bytes. We can add bytes to an
  8665. // i8* by GEP with the byte count in the first index.
  8666. Type *DestPtrTy =
  8667. Type::getInt8PtrTy(PT->getContext(), PT->getAddressSpace());
  8668. OpC = ConstantExpr::getBitCast(OpC, DestPtrTy);
  8669. C = ConstantExpr::getGetElementPtr(Type::getInt8Ty(C->getContext()),
  8670. OpC, C);
  8671. } else {
  8672. C = ConstantExpr::getAdd(C, OpC);
  8673. }
  8674. }
  8675. return C;
  8676. }
  8677. case scMulExpr: {
  8678. const SCEVMulExpr *SM = cast<SCEVMulExpr>(V);
  8679. Constant *C = nullptr;
  8680. for (const SCEV *Op : SM->operands()) {
  8681. assert(!Op->getType()->isPointerTy() && "Can't multiply pointers");
  8682. Constant *OpC = BuildConstantFromSCEV(Op);
  8683. if (!OpC)
  8684. return nullptr;
  8685. C = C ? ConstantExpr::getMul(C, OpC) : OpC;
  8686. }
  8687. return C;
  8688. }
  8689. case scUDivExpr:
  8690. case scSMaxExpr:
  8691. case scUMaxExpr:
  8692. case scSMinExpr:
  8693. case scUMinExpr:
  8694. case scSequentialUMinExpr:
  8695. return nullptr; // TODO: smax, umax, smin, umax, umin_seq.
  8696. }
  8697. llvm_unreachable("Unknown SCEV kind!");
  8698. }
  8699. const SCEV *ScalarEvolution::computeSCEVAtScope(const SCEV *V, const Loop *L) {
  8700. switch (V->getSCEVType()) {
  8701. case scConstant:
  8702. return V;
  8703. case scAddRecExpr: {
  8704. // If this is a loop recurrence for a loop that does not contain L, then we
  8705. // are dealing with the final value computed by the loop.
  8706. const SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(V);
  8707. // First, attempt to evaluate each operand.
  8708. // Avoid performing the look-up in the common case where the specified
  8709. // expression has no loop-variant portions.
  8710. for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
  8711. const SCEV *OpAtScope = getSCEVAtScope(AddRec->getOperand(i), L);
  8712. if (OpAtScope == AddRec->getOperand(i))
  8713. continue;
  8714. // Okay, at least one of these operands is loop variant but might be
  8715. // foldable. Build a new instance of the folded commutative expression.
  8716. SmallVector<const SCEV *, 8> NewOps;
  8717. NewOps.reserve(AddRec->getNumOperands());
  8718. append_range(NewOps, AddRec->operands().take_front(i));
  8719. NewOps.push_back(OpAtScope);
  8720. for (++i; i != e; ++i)
  8721. NewOps.push_back(getSCEVAtScope(AddRec->getOperand(i), L));
  8722. const SCEV *FoldedRec = getAddRecExpr(
  8723. NewOps, AddRec->getLoop(), AddRec->getNoWrapFlags(SCEV::FlagNW));
  8724. AddRec = dyn_cast<SCEVAddRecExpr>(FoldedRec);
  8725. // The addrec may be folded to a nonrecurrence, for example, if the
  8726. // induction variable is multiplied by zero after constant folding. Go
  8727. // ahead and return the folded value.
  8728. if (!AddRec)
  8729. return FoldedRec;
  8730. break;
  8731. }
  8732. // If the scope is outside the addrec's loop, evaluate it by using the
  8733. // loop exit value of the addrec.
  8734. if (!AddRec->getLoop()->contains(L)) {
  8735. // To evaluate this recurrence, we need to know how many times the AddRec
  8736. // loop iterates. Compute this now.
  8737. const SCEV *BackedgeTakenCount = getBackedgeTakenCount(AddRec->getLoop());
  8738. if (BackedgeTakenCount == getCouldNotCompute())
  8739. return AddRec;
  8740. // Then, evaluate the AddRec.
  8741. return AddRec->evaluateAtIteration(BackedgeTakenCount, *this);
  8742. }
  8743. return AddRec;
  8744. }
  8745. case scTruncate:
  8746. case scZeroExtend:
  8747. case scSignExtend:
  8748. case scPtrToInt:
  8749. case scAddExpr:
  8750. case scMulExpr:
  8751. case scUDivExpr:
  8752. case scUMaxExpr:
  8753. case scSMaxExpr:
  8754. case scUMinExpr:
  8755. case scSMinExpr:
  8756. case scSequentialUMinExpr: {
  8757. ArrayRef<const SCEV *> Ops = V->operands();
  8758. // Avoid performing the look-up in the common case where the specified
  8759. // expression has no loop-variant portions.
  8760. for (unsigned i = 0, e = Ops.size(); i != e; ++i) {
  8761. const SCEV *OpAtScope = getSCEVAtScope(Ops[i], L);
  8762. if (OpAtScope != Ops[i]) {
  8763. // Okay, at least one of these operands is loop variant but might be
  8764. // foldable. Build a new instance of the folded commutative expression.
  8765. SmallVector<const SCEV *, 8> NewOps;
  8766. NewOps.reserve(Ops.size());
  8767. append_range(NewOps, Ops.take_front(i));
  8768. NewOps.push_back(OpAtScope);
  8769. for (++i; i != e; ++i) {
  8770. OpAtScope = getSCEVAtScope(Ops[i], L);
  8771. NewOps.push_back(OpAtScope);
  8772. }
  8773. switch (V->getSCEVType()) {
  8774. case scTruncate:
  8775. case scZeroExtend:
  8776. case scSignExtend:
  8777. case scPtrToInt:
  8778. return getCastExpr(V->getSCEVType(), NewOps[0], V->getType());
  8779. case scAddExpr:
  8780. return getAddExpr(NewOps, cast<SCEVAddExpr>(V)->getNoWrapFlags());
  8781. case scMulExpr:
  8782. return getMulExpr(NewOps, cast<SCEVMulExpr>(V)->getNoWrapFlags());
  8783. case scUDivExpr:
  8784. return getUDivExpr(NewOps[0], NewOps[1]);
  8785. case scUMaxExpr:
  8786. case scSMaxExpr:
  8787. case scUMinExpr:
  8788. case scSMinExpr:
  8789. return getMinMaxExpr(V->getSCEVType(), NewOps);
  8790. case scSequentialUMinExpr:
  8791. return getSequentialMinMaxExpr(V->getSCEVType(), NewOps);
  8792. case scConstant:
  8793. case scAddRecExpr:
  8794. case scUnknown:
  8795. case scCouldNotCompute:
  8796. llvm_unreachable("Can not get those expressions here.");
  8797. }
  8798. llvm_unreachable("Unknown n-ary-like SCEV type!");
  8799. }
  8800. }
  8801. // If we got here, all operands are loop invariant.
  8802. return V;
  8803. }
  8804. case scUnknown: {
  8805. // If this instruction is evolved from a constant-evolving PHI, compute the
  8806. // exit value from the loop without using SCEVs.
  8807. const SCEVUnknown *SU = cast<SCEVUnknown>(V);
  8808. Instruction *I = dyn_cast<Instruction>(SU->getValue());
  8809. if (!I)
  8810. return V; // This is some other type of SCEVUnknown, just return it.
  8811. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  8812. const Loop *CurrLoop = this->LI[I->getParent()];
  8813. // Looking for loop exit value.
  8814. if (CurrLoop && CurrLoop->getParentLoop() == L &&
  8815. PN->getParent() == CurrLoop->getHeader()) {
  8816. // Okay, there is no closed form solution for the PHI node. Check
  8817. // to see if the loop that contains it has a known backedge-taken
  8818. // count. If so, we may be able to force computation of the exit
  8819. // value.
  8820. const SCEV *BackedgeTakenCount = getBackedgeTakenCount(CurrLoop);
  8821. // This trivial case can show up in some degenerate cases where
  8822. // the incoming IR has not yet been fully simplified.
  8823. if (BackedgeTakenCount->isZero()) {
  8824. Value *InitValue = nullptr;
  8825. bool MultipleInitValues = false;
  8826. for (unsigned i = 0; i < PN->getNumIncomingValues(); i++) {
  8827. if (!CurrLoop->contains(PN->getIncomingBlock(i))) {
  8828. if (!InitValue)
  8829. InitValue = PN->getIncomingValue(i);
  8830. else if (InitValue != PN->getIncomingValue(i)) {
  8831. MultipleInitValues = true;
  8832. break;
  8833. }
  8834. }
  8835. }
  8836. if (!MultipleInitValues && InitValue)
  8837. return getSCEV(InitValue);
  8838. }
  8839. // Do we have a loop invariant value flowing around the backedge
  8840. // for a loop which must execute the backedge?
  8841. if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) &&
  8842. isKnownPositive(BackedgeTakenCount) &&
  8843. PN->getNumIncomingValues() == 2) {
  8844. unsigned InLoopPred =
  8845. CurrLoop->contains(PN->getIncomingBlock(0)) ? 0 : 1;
  8846. Value *BackedgeVal = PN->getIncomingValue(InLoopPred);
  8847. if (CurrLoop->isLoopInvariant(BackedgeVal))
  8848. return getSCEV(BackedgeVal);
  8849. }
  8850. if (auto *BTCC = dyn_cast<SCEVConstant>(BackedgeTakenCount)) {
  8851. // Okay, we know how many times the containing loop executes. If
  8852. // this is a constant evolving PHI node, get the final value at
  8853. // the specified iteration number.
  8854. Constant *RV =
  8855. getConstantEvolutionLoopExitValue(PN, BTCC->getAPInt(), CurrLoop);
  8856. if (RV)
  8857. return getSCEV(RV);
  8858. }
  8859. }
  8860. // If there is a single-input Phi, evaluate it at our scope. If we can
  8861. // prove that this replacement does not break LCSSA form, use new value.
  8862. if (PN->getNumOperands() == 1) {
  8863. const SCEV *Input = getSCEV(PN->getOperand(0));
  8864. const SCEV *InputAtScope = getSCEVAtScope(Input, L);
  8865. // TODO: We can generalize it using LI.replacementPreservesLCSSAForm,
  8866. // for the simplest case just support constants.
  8867. if (isa<SCEVConstant>(InputAtScope))
  8868. return InputAtScope;
  8869. }
  8870. }
  8871. // Okay, this is an expression that we cannot symbolically evaluate
  8872. // into a SCEV. Check to see if it's possible to symbolically evaluate
  8873. // the arguments into constants, and if so, try to constant propagate the
  8874. // result. This is particularly useful for computing loop exit values.
  8875. if (!CanConstantFold(I))
  8876. return V; // This is some other type of SCEVUnknown, just return it.
  8877. SmallVector<Constant *, 4> Operands;
  8878. Operands.reserve(I->getNumOperands());
  8879. bool MadeImprovement = false;
  8880. for (Value *Op : I->operands()) {
  8881. if (Constant *C = dyn_cast<Constant>(Op)) {
  8882. Operands.push_back(C);
  8883. continue;
  8884. }
  8885. // If any of the operands is non-constant and if they are
  8886. // non-integer and non-pointer, don't even try to analyze them
  8887. // with scev techniques.
  8888. if (!isSCEVable(Op->getType()))
  8889. return V;
  8890. const SCEV *OrigV = getSCEV(Op);
  8891. const SCEV *OpV = getSCEVAtScope(OrigV, L);
  8892. MadeImprovement |= OrigV != OpV;
  8893. Constant *C = BuildConstantFromSCEV(OpV);
  8894. if (!C)
  8895. return V;
  8896. if (C->getType() != Op->getType())
  8897. C = ConstantExpr::getCast(
  8898. CastInst::getCastOpcode(C, false, Op->getType(), false), C,
  8899. Op->getType());
  8900. Operands.push_back(C);
  8901. }
  8902. // Check to see if getSCEVAtScope actually made an improvement.
  8903. if (!MadeImprovement)
  8904. return V; // This is some other type of SCEVUnknown, just return it.
  8905. Constant *C = nullptr;
  8906. const DataLayout &DL = getDataLayout();
  8907. C = ConstantFoldInstOperands(I, Operands, DL, &TLI);
  8908. if (!C)
  8909. return V;
  8910. return getSCEV(C);
  8911. }
  8912. case scCouldNotCompute:
  8913. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  8914. }
  8915. llvm_unreachable("Unknown SCEV type!");
  8916. }
  8917. const SCEV *ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) {
  8918. return getSCEVAtScope(getSCEV(V), L);
  8919. }
  8920. const SCEV *ScalarEvolution::stripInjectiveFunctions(const SCEV *S) const {
  8921. if (const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(S))
  8922. return stripInjectiveFunctions(ZExt->getOperand());
  8923. if (const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(S))
  8924. return stripInjectiveFunctions(SExt->getOperand());
  8925. return S;
  8926. }
  8927. /// Finds the minimum unsigned root of the following equation:
  8928. ///
  8929. /// A * X = B (mod N)
  8930. ///
  8931. /// where N = 2^BW and BW is the common bit width of A and B. The signedness of
  8932. /// A and B isn't important.
  8933. ///
  8934. /// If the equation does not have a solution, SCEVCouldNotCompute is returned.
  8935. static const SCEV *SolveLinEquationWithOverflow(const APInt &A, const SCEV *B,
  8936. ScalarEvolution &SE) {
  8937. uint32_t BW = A.getBitWidth();
  8938. assert(BW == SE.getTypeSizeInBits(B->getType()));
  8939. assert(A != 0 && "A must be non-zero.");
  8940. // 1. D = gcd(A, N)
  8941. //
  8942. // The gcd of A and N may have only one prime factor: 2. The number of
  8943. // trailing zeros in A is its multiplicity
  8944. uint32_t Mult2 = A.countTrailingZeros();
  8945. // D = 2^Mult2
  8946. // 2. Check if B is divisible by D.
  8947. //
  8948. // B is divisible by D if and only if the multiplicity of prime factor 2 for B
  8949. // is not less than multiplicity of this prime factor for D.
  8950. if (SE.GetMinTrailingZeros(B) < Mult2)
  8951. return SE.getCouldNotCompute();
  8952. // 3. Compute I: the multiplicative inverse of (A / D) in arithmetic
  8953. // modulo (N / D).
  8954. //
  8955. // If D == 1, (N / D) == N == 2^BW, so we need one extra bit to represent
  8956. // (N / D) in general. The inverse itself always fits into BW bits, though,
  8957. // so we immediately truncate it.
  8958. APInt AD = A.lshr(Mult2).zext(BW + 1); // AD = A / D
  8959. APInt Mod(BW + 1, 0);
  8960. Mod.setBit(BW - Mult2); // Mod = N / D
  8961. APInt I = AD.multiplicativeInverse(Mod).trunc(BW);
  8962. // 4. Compute the minimum unsigned root of the equation:
  8963. // I * (B / D) mod (N / D)
  8964. // To simplify the computation, we factor out the divide by D:
  8965. // (I * B mod N) / D
  8966. const SCEV *D = SE.getConstant(APInt::getOneBitSet(BW, Mult2));
  8967. return SE.getUDivExactExpr(SE.getMulExpr(B, SE.getConstant(I)), D);
  8968. }
  8969. /// For a given quadratic addrec, generate coefficients of the corresponding
  8970. /// quadratic equation, multiplied by a common value to ensure that they are
  8971. /// integers.
  8972. /// The returned value is a tuple { A, B, C, M, BitWidth }, where
  8973. /// Ax^2 + Bx + C is the quadratic function, M is the value that A, B and C
  8974. /// were multiplied by, and BitWidth is the bit width of the original addrec
  8975. /// coefficients.
  8976. /// This function returns std::nullopt if the addrec coefficients are not
  8977. /// compile- time constants.
  8978. static std::optional<std::tuple<APInt, APInt, APInt, APInt, unsigned>>
  8979. GetQuadraticEquation(const SCEVAddRecExpr *AddRec) {
  8980. assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
  8981. const SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
  8982. const SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
  8983. const SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
  8984. LLVM_DEBUG(dbgs() << __func__ << ": analyzing quadratic addrec: "
  8985. << *AddRec << '\n');
  8986. // We currently can only solve this if the coefficients are constants.
  8987. if (!LC || !MC || !NC) {
  8988. LLVM_DEBUG(dbgs() << __func__ << ": coefficients are not constant\n");
  8989. return std::nullopt;
  8990. }
  8991. APInt L = LC->getAPInt();
  8992. APInt M = MC->getAPInt();
  8993. APInt N = NC->getAPInt();
  8994. assert(!N.isZero() && "This is not a quadratic addrec");
  8995. unsigned BitWidth = LC->getAPInt().getBitWidth();
  8996. unsigned NewWidth = BitWidth + 1;
  8997. LLVM_DEBUG(dbgs() << __func__ << ": addrec coeff bw: "
  8998. << BitWidth << '\n');
  8999. // The sign-extension (as opposed to a zero-extension) here matches the
  9000. // extension used in SolveQuadraticEquationWrap (with the same motivation).
  9001. N = N.sext(NewWidth);
  9002. M = M.sext(NewWidth);
  9003. L = L.sext(NewWidth);
  9004. // The increments are M, M+N, M+2N, ..., so the accumulated values are
  9005. // L+M, (L+M)+(M+N), (L+M)+(M+N)+(M+2N), ..., that is,
  9006. // L+M, L+2M+N, L+3M+3N, ...
  9007. // After n iterations the accumulated value Acc is L + nM + n(n-1)/2 N.
  9008. //
  9009. // The equation Acc = 0 is then
  9010. // L + nM + n(n-1)/2 N = 0, or 2L + 2M n + n(n-1) N = 0.
  9011. // In a quadratic form it becomes:
  9012. // N n^2 + (2M-N) n + 2L = 0.
  9013. APInt A = N;
  9014. APInt B = 2 * M - A;
  9015. APInt C = 2 * L;
  9016. APInt T = APInt(NewWidth, 2);
  9017. LLVM_DEBUG(dbgs() << __func__ << ": equation " << A << "x^2 + " << B
  9018. << "x + " << C << ", coeff bw: " << NewWidth
  9019. << ", multiplied by " << T << '\n');
  9020. return std::make_tuple(A, B, C, T, BitWidth);
  9021. }
  9022. /// Helper function to compare optional APInts:
  9023. /// (a) if X and Y both exist, return min(X, Y),
  9024. /// (b) if neither X nor Y exist, return std::nullopt,
  9025. /// (c) if exactly one of X and Y exists, return that value.
  9026. static std::optional<APInt> MinOptional(std::optional<APInt> X,
  9027. std::optional<APInt> Y) {
  9028. if (X && Y) {
  9029. unsigned W = std::max(X->getBitWidth(), Y->getBitWidth());
  9030. APInt XW = X->sext(W);
  9031. APInt YW = Y->sext(W);
  9032. return XW.slt(YW) ? *X : *Y;
  9033. }
  9034. if (!X && !Y)
  9035. return std::nullopt;
  9036. return X ? *X : *Y;
  9037. }
  9038. /// Helper function to truncate an optional APInt to a given BitWidth.
  9039. /// When solving addrec-related equations, it is preferable to return a value
  9040. /// that has the same bit width as the original addrec's coefficients. If the
  9041. /// solution fits in the original bit width, truncate it (except for i1).
  9042. /// Returning a value of a different bit width may inhibit some optimizations.
  9043. ///
  9044. /// In general, a solution to a quadratic equation generated from an addrec
  9045. /// may require BW+1 bits, where BW is the bit width of the addrec's
  9046. /// coefficients. The reason is that the coefficients of the quadratic
  9047. /// equation are BW+1 bits wide (to avoid truncation when converting from
  9048. /// the addrec to the equation).
  9049. static std::optional<APInt> TruncIfPossible(std::optional<APInt> X,
  9050. unsigned BitWidth) {
  9051. if (!X)
  9052. return std::nullopt;
  9053. unsigned W = X->getBitWidth();
  9054. if (BitWidth > 1 && BitWidth < W && X->isIntN(BitWidth))
  9055. return X->trunc(BitWidth);
  9056. return X;
  9057. }
  9058. /// Let c(n) be the value of the quadratic chrec {L,+,M,+,N} after n
  9059. /// iterations. The values L, M, N are assumed to be signed, and they
  9060. /// should all have the same bit widths.
  9061. /// Find the least n >= 0 such that c(n) = 0 in the arithmetic modulo 2^BW,
  9062. /// where BW is the bit width of the addrec's coefficients.
  9063. /// If the calculated value is a BW-bit integer (for BW > 1), it will be
  9064. /// returned as such, otherwise the bit width of the returned value may
  9065. /// be greater than BW.
  9066. ///
  9067. /// This function returns std::nullopt if
  9068. /// (a) the addrec coefficients are not constant, or
  9069. /// (b) SolveQuadraticEquationWrap was unable to find a solution. For cases
  9070. /// like x^2 = 5, no integer solutions exist, in other cases an integer
  9071. /// solution may exist, but SolveQuadraticEquationWrap may fail to find it.
  9072. static std::optional<APInt>
  9073. SolveQuadraticAddRecExact(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
  9074. APInt A, B, C, M;
  9075. unsigned BitWidth;
  9076. auto T = GetQuadraticEquation(AddRec);
  9077. if (!T)
  9078. return std::nullopt;
  9079. std::tie(A, B, C, M, BitWidth) = *T;
  9080. LLVM_DEBUG(dbgs() << __func__ << ": solving for unsigned overflow\n");
  9081. std::optional<APInt> X =
  9082. APIntOps::SolveQuadraticEquationWrap(A, B, C, BitWidth + 1);
  9083. if (!X)
  9084. return std::nullopt;
  9085. ConstantInt *CX = ConstantInt::get(SE.getContext(), *X);
  9086. ConstantInt *V = EvaluateConstantChrecAtConstant(AddRec, CX, SE);
  9087. if (!V->isZero())
  9088. return std::nullopt;
  9089. return TruncIfPossible(X, BitWidth);
  9090. }
  9091. /// Let c(n) be the value of the quadratic chrec {0,+,M,+,N} after n
  9092. /// iterations. The values M, N are assumed to be signed, and they
  9093. /// should all have the same bit widths.
  9094. /// Find the least n such that c(n) does not belong to the given range,
  9095. /// while c(n-1) does.
  9096. ///
  9097. /// This function returns std::nullopt if
  9098. /// (a) the addrec coefficients are not constant, or
  9099. /// (b) SolveQuadraticEquationWrap was unable to find a solution for the
  9100. /// bounds of the range.
  9101. static std::optional<APInt>
  9102. SolveQuadraticAddRecRange(const SCEVAddRecExpr *AddRec,
  9103. const ConstantRange &Range, ScalarEvolution &SE) {
  9104. assert(AddRec->getOperand(0)->isZero() &&
  9105. "Starting value of addrec should be 0");
  9106. LLVM_DEBUG(dbgs() << __func__ << ": solving boundary crossing for range "
  9107. << Range << ", addrec " << *AddRec << '\n');
  9108. // This case is handled in getNumIterationsInRange. Here we can assume that
  9109. // we start in the range.
  9110. assert(Range.contains(APInt(SE.getTypeSizeInBits(AddRec->getType()), 0)) &&
  9111. "Addrec's initial value should be in range");
  9112. APInt A, B, C, M;
  9113. unsigned BitWidth;
  9114. auto T = GetQuadraticEquation(AddRec);
  9115. if (!T)
  9116. return std::nullopt;
  9117. // Be careful about the return value: there can be two reasons for not
  9118. // returning an actual number. First, if no solutions to the equations
  9119. // were found, and second, if the solutions don't leave the given range.
  9120. // The first case means that the actual solution is "unknown", the second
  9121. // means that it's known, but not valid. If the solution is unknown, we
  9122. // cannot make any conclusions.
  9123. // Return a pair: the optional solution and a flag indicating if the
  9124. // solution was found.
  9125. auto SolveForBoundary =
  9126. [&](APInt Bound) -> std::pair<std::optional<APInt>, bool> {
  9127. // Solve for signed overflow and unsigned overflow, pick the lower
  9128. // solution.
  9129. LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: checking boundary "
  9130. << Bound << " (before multiplying by " << M << ")\n");
  9131. Bound *= M; // The quadratic equation multiplier.
  9132. std::optional<APInt> SO;
  9133. if (BitWidth > 1) {
  9134. LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
  9135. "signed overflow\n");
  9136. SO = APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth);
  9137. }
  9138. LLVM_DEBUG(dbgs() << "SolveQuadraticAddRecRange: solving for "
  9139. "unsigned overflow\n");
  9140. std::optional<APInt> UO =
  9141. APIntOps::SolveQuadraticEquationWrap(A, B, -Bound, BitWidth + 1);
  9142. auto LeavesRange = [&] (const APInt &X) {
  9143. ConstantInt *C0 = ConstantInt::get(SE.getContext(), X);
  9144. ConstantInt *V0 = EvaluateConstantChrecAtConstant(AddRec, C0, SE);
  9145. if (Range.contains(V0->getValue()))
  9146. return false;
  9147. // X should be at least 1, so X-1 is non-negative.
  9148. ConstantInt *C1 = ConstantInt::get(SE.getContext(), X-1);
  9149. ConstantInt *V1 = EvaluateConstantChrecAtConstant(AddRec, C1, SE);
  9150. if (Range.contains(V1->getValue()))
  9151. return true;
  9152. return false;
  9153. };
  9154. // If SolveQuadraticEquationWrap returns std::nullopt, it means that there
  9155. // can be a solution, but the function failed to find it. We cannot treat it
  9156. // as "no solution".
  9157. if (!SO || !UO)
  9158. return {std::nullopt, false};
  9159. // Check the smaller value first to see if it leaves the range.
  9160. // At this point, both SO and UO must have values.
  9161. std::optional<APInt> Min = MinOptional(SO, UO);
  9162. if (LeavesRange(*Min))
  9163. return { Min, true };
  9164. std::optional<APInt> Max = Min == SO ? UO : SO;
  9165. if (LeavesRange(*Max))
  9166. return { Max, true };
  9167. // Solutions were found, but were eliminated, hence the "true".
  9168. return {std::nullopt, true};
  9169. };
  9170. std::tie(A, B, C, M, BitWidth) = *T;
  9171. // Lower bound is inclusive, subtract 1 to represent the exiting value.
  9172. APInt Lower = Range.getLower().sext(A.getBitWidth()) - 1;
  9173. APInt Upper = Range.getUpper().sext(A.getBitWidth());
  9174. auto SL = SolveForBoundary(Lower);
  9175. auto SU = SolveForBoundary(Upper);
  9176. // If any of the solutions was unknown, no meaninigful conclusions can
  9177. // be made.
  9178. if (!SL.second || !SU.second)
  9179. return std::nullopt;
  9180. // Claim: The correct solution is not some value between Min and Max.
  9181. //
  9182. // Justification: Assuming that Min and Max are different values, one of
  9183. // them is when the first signed overflow happens, the other is when the
  9184. // first unsigned overflow happens. Crossing the range boundary is only
  9185. // possible via an overflow (treating 0 as a special case of it, modeling
  9186. // an overflow as crossing k*2^W for some k).
  9187. //
  9188. // The interesting case here is when Min was eliminated as an invalid
  9189. // solution, but Max was not. The argument is that if there was another
  9190. // overflow between Min and Max, it would also have been eliminated if
  9191. // it was considered.
  9192. //
  9193. // For a given boundary, it is possible to have two overflows of the same
  9194. // type (signed/unsigned) without having the other type in between: this
  9195. // can happen when the vertex of the parabola is between the iterations
  9196. // corresponding to the overflows. This is only possible when the two
  9197. // overflows cross k*2^W for the same k. In such case, if the second one
  9198. // left the range (and was the first one to do so), the first overflow
  9199. // would have to enter the range, which would mean that either we had left
  9200. // the range before or that we started outside of it. Both of these cases
  9201. // are contradictions.
  9202. //
  9203. // Claim: In the case where SolveForBoundary returns std::nullopt, the correct
  9204. // solution is not some value between the Max for this boundary and the
  9205. // Min of the other boundary.
  9206. //
  9207. // Justification: Assume that we had such Max_A and Min_B corresponding
  9208. // to range boundaries A and B and such that Max_A < Min_B. If there was
  9209. // a solution between Max_A and Min_B, it would have to be caused by an
  9210. // overflow corresponding to either A or B. It cannot correspond to B,
  9211. // since Min_B is the first occurrence of such an overflow. If it
  9212. // corresponded to A, it would have to be either a signed or an unsigned
  9213. // overflow that is larger than both eliminated overflows for A. But
  9214. // between the eliminated overflows and this overflow, the values would
  9215. // cover the entire value space, thus crossing the other boundary, which
  9216. // is a contradiction.
  9217. return TruncIfPossible(MinOptional(SL.first, SU.first), BitWidth);
  9218. }
  9219. ScalarEvolution::ExitLimit
  9220. ScalarEvolution::howFarToZero(const SCEV *V, const Loop *L, bool ControlsExit,
  9221. bool AllowPredicates) {
  9222. // This is only used for loops with a "x != y" exit test. The exit condition
  9223. // is now expressed as a single expression, V = x-y. So the exit test is
  9224. // effectively V != 0. We know and take advantage of the fact that this
  9225. // expression only being used in a comparison by zero context.
  9226. SmallPtrSet<const SCEVPredicate *, 4> Predicates;
  9227. // If the value is a constant
  9228. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
  9229. // If the value is already zero, the branch will execute zero times.
  9230. if (C->getValue()->isZero()) return C;
  9231. return getCouldNotCompute(); // Otherwise it will loop infinitely.
  9232. }
  9233. const SCEVAddRecExpr *AddRec =
  9234. dyn_cast<SCEVAddRecExpr>(stripInjectiveFunctions(V));
  9235. if (!AddRec && AllowPredicates)
  9236. // Try to make this an AddRec using runtime tests, in the first X
  9237. // iterations of this loop, where X is the SCEV expression found by the
  9238. // algorithm below.
  9239. AddRec = convertSCEVToAddRecWithPredicates(V, L, Predicates);
  9240. if (!AddRec || AddRec->getLoop() != L)
  9241. return getCouldNotCompute();
  9242. // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
  9243. // the quadratic equation to solve it.
  9244. if (AddRec->isQuadratic() && AddRec->getType()->isIntegerTy()) {
  9245. // We can only use this value if the chrec ends up with an exact zero
  9246. // value at this index. When solving for "X*X != 5", for example, we
  9247. // should not accept a root of 2.
  9248. if (auto S = SolveQuadraticAddRecExact(AddRec, *this)) {
  9249. const auto *R = cast<SCEVConstant>(getConstant(*S));
  9250. return ExitLimit(R, R, R, false, Predicates);
  9251. }
  9252. return getCouldNotCompute();
  9253. }
  9254. // Otherwise we can only handle this if it is affine.
  9255. if (!AddRec->isAffine())
  9256. return getCouldNotCompute();
  9257. // If this is an affine expression, the execution count of this branch is
  9258. // the minimum unsigned root of the following equation:
  9259. //
  9260. // Start + Step*N = 0 (mod 2^BW)
  9261. //
  9262. // equivalent to:
  9263. //
  9264. // Step*N = -Start (mod 2^BW)
  9265. //
  9266. // where BW is the common bit width of Start and Step.
  9267. // Get the initial value for the loop.
  9268. const SCEV *Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
  9269. const SCEV *Step = getSCEVAtScope(AddRec->getOperand(1), L->getParentLoop());
  9270. // For now we handle only constant steps.
  9271. //
  9272. // TODO: Handle a nonconstant Step given AddRec<NUW>. If the
  9273. // AddRec is NUW, then (in an unsigned sense) it cannot be counting up to wrap
  9274. // to 0, it must be counting down to equal 0. Consequently, N = Start / -Step.
  9275. // We have not yet seen any such cases.
  9276. const SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step);
  9277. if (!StepC || StepC->getValue()->isZero())
  9278. return getCouldNotCompute();
  9279. // For positive steps (counting up until unsigned overflow):
  9280. // N = -Start/Step (as unsigned)
  9281. // For negative steps (counting down to zero):
  9282. // N = Start/-Step
  9283. // First compute the unsigned distance from zero in the direction of Step.
  9284. bool CountDown = StepC->getAPInt().isNegative();
  9285. const SCEV *Distance = CountDown ? Start : getNegativeSCEV(Start);
  9286. // Handle unitary steps, which cannot wraparound.
  9287. // 1*N = -Start; -1*N = Start (mod 2^BW), so:
  9288. // N = Distance (as unsigned)
  9289. if (StepC->getValue()->isOne() || StepC->getValue()->isMinusOne()) {
  9290. APInt MaxBECount = getUnsignedRangeMax(applyLoopGuards(Distance, L));
  9291. MaxBECount = APIntOps::umin(MaxBECount, getUnsignedRangeMax(Distance));
  9292. // When a loop like "for (int i = 0; i != n; ++i) { /* body */ }" is rotated,
  9293. // we end up with a loop whose backedge-taken count is n - 1. Detect this
  9294. // case, and see if we can improve the bound.
  9295. //
  9296. // Explicitly handling this here is necessary because getUnsignedRange
  9297. // isn't context-sensitive; it doesn't know that we only care about the
  9298. // range inside the loop.
  9299. const SCEV *Zero = getZero(Distance->getType());
  9300. const SCEV *One = getOne(Distance->getType());
  9301. const SCEV *DistancePlusOne = getAddExpr(Distance, One);
  9302. if (isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, DistancePlusOne, Zero)) {
  9303. // If Distance + 1 doesn't overflow, we can compute the maximum distance
  9304. // as "unsigned_max(Distance + 1) - 1".
  9305. ConstantRange CR = getUnsignedRange(DistancePlusOne);
  9306. MaxBECount = APIntOps::umin(MaxBECount, CR.getUnsignedMax() - 1);
  9307. }
  9308. return ExitLimit(Distance, getConstant(MaxBECount), Distance, false,
  9309. Predicates);
  9310. }
  9311. // If the condition controls loop exit (the loop exits only if the expression
  9312. // is true) and the addition is no-wrap we can use unsigned divide to
  9313. // compute the backedge count. In this case, the step may not divide the
  9314. // distance, but we don't care because if the condition is "missed" the loop
  9315. // will have undefined behavior due to wrapping.
  9316. if (ControlsExit && AddRec->hasNoSelfWrap() &&
  9317. loopHasNoAbnormalExits(AddRec->getLoop())) {
  9318. const SCEV *Exact =
  9319. getUDivExpr(Distance, CountDown ? getNegativeSCEV(Step) : Step);
  9320. const SCEV *ConstantMax = getCouldNotCompute();
  9321. if (Exact != getCouldNotCompute()) {
  9322. APInt MaxInt = getUnsignedRangeMax(applyLoopGuards(Exact, L));
  9323. ConstantMax =
  9324. getConstant(APIntOps::umin(MaxInt, getUnsignedRangeMax(Exact)));
  9325. }
  9326. const SCEV *SymbolicMax =
  9327. isa<SCEVCouldNotCompute>(Exact) ? ConstantMax : Exact;
  9328. return ExitLimit(Exact, ConstantMax, SymbolicMax, false, Predicates);
  9329. }
  9330. // Solve the general equation.
  9331. const SCEV *E = SolveLinEquationWithOverflow(StepC->getAPInt(),
  9332. getNegativeSCEV(Start), *this);
  9333. const SCEV *M = E;
  9334. if (E != getCouldNotCompute()) {
  9335. APInt MaxWithGuards = getUnsignedRangeMax(applyLoopGuards(E, L));
  9336. M = getConstant(APIntOps::umin(MaxWithGuards, getUnsignedRangeMax(E)));
  9337. }
  9338. auto *S = isa<SCEVCouldNotCompute>(E) ? M : E;
  9339. return ExitLimit(E, M, S, false, Predicates);
  9340. }
  9341. ScalarEvolution::ExitLimit
  9342. ScalarEvolution::howFarToNonZero(const SCEV *V, const Loop *L) {
  9343. // Loops that look like: while (X == 0) are very strange indeed. We don't
  9344. // handle them yet except for the trivial case. This could be expanded in the
  9345. // future as needed.
  9346. // If the value is a constant, check to see if it is known to be non-zero
  9347. // already. If so, the backedge will execute zero times.
  9348. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
  9349. if (!C->getValue()->isZero())
  9350. return getZero(C->getType());
  9351. return getCouldNotCompute(); // Otherwise it will loop infinitely.
  9352. }
  9353. // We could implement others, but I really doubt anyone writes loops like
  9354. // this, and if they did, they would already be constant folded.
  9355. return getCouldNotCompute();
  9356. }
  9357. std::pair<const BasicBlock *, const BasicBlock *>
  9358. ScalarEvolution::getPredecessorWithUniqueSuccessorForBB(const BasicBlock *BB)
  9359. const {
  9360. // If the block has a unique predecessor, then there is no path from the
  9361. // predecessor to the block that does not go through the direct edge
  9362. // from the predecessor to the block.
  9363. if (const BasicBlock *Pred = BB->getSinglePredecessor())
  9364. return {Pred, BB};
  9365. // A loop's header is defined to be a block that dominates the loop.
  9366. // If the header has a unique predecessor outside the loop, it must be
  9367. // a block that has exactly one successor that can reach the loop.
  9368. if (const Loop *L = LI.getLoopFor(BB))
  9369. return {L->getLoopPredecessor(), L->getHeader()};
  9370. return {nullptr, nullptr};
  9371. }
  9372. /// SCEV structural equivalence is usually sufficient for testing whether two
  9373. /// expressions are equal, however for the purposes of looking for a condition
  9374. /// guarding a loop, it can be useful to be a little more general, since a
  9375. /// front-end may have replicated the controlling expression.
  9376. static bool HasSameValue(const SCEV *A, const SCEV *B) {
  9377. // Quick check to see if they are the same SCEV.
  9378. if (A == B) return true;
  9379. auto ComputesEqualValues = [](const Instruction *A, const Instruction *B) {
  9380. // Not all instructions that are "identical" compute the same value. For
  9381. // instance, two distinct alloca instructions allocating the same type are
  9382. // identical and do not read memory; but compute distinct values.
  9383. return A->isIdenticalTo(B) && (isa<BinaryOperator>(A) || isa<GetElementPtrInst>(A));
  9384. };
  9385. // Otherwise, if they're both SCEVUnknown, it's possible that they hold
  9386. // two different instructions with the same value. Check for this case.
  9387. if (const SCEVUnknown *AU = dyn_cast<SCEVUnknown>(A))
  9388. if (const SCEVUnknown *BU = dyn_cast<SCEVUnknown>(B))
  9389. if (const Instruction *AI = dyn_cast<Instruction>(AU->getValue()))
  9390. if (const Instruction *BI = dyn_cast<Instruction>(BU->getValue()))
  9391. if (ComputesEqualValues(AI, BI))
  9392. return true;
  9393. // Otherwise assume they may have a different value.
  9394. return false;
  9395. }
  9396. bool ScalarEvolution::SimplifyICmpOperands(ICmpInst::Predicate &Pred,
  9397. const SCEV *&LHS, const SCEV *&RHS,
  9398. unsigned Depth,
  9399. bool ControllingFiniteLoop) {
  9400. bool Changed = false;
  9401. // Simplifies ICMP to trivial true or false by turning it into '0 == 0' or
  9402. // '0 != 0'.
  9403. auto TrivialCase = [&](bool TriviallyTrue) {
  9404. LHS = RHS = getConstant(ConstantInt::getFalse(getContext()));
  9405. Pred = TriviallyTrue ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE;
  9406. return true;
  9407. };
  9408. // If we hit the max recursion limit bail out.
  9409. if (Depth >= 3)
  9410. return false;
  9411. // Canonicalize a constant to the right side.
  9412. if (const SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
  9413. // Check for both operands constant.
  9414. if (const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
  9415. if (ConstantExpr::getICmp(Pred,
  9416. LHSC->getValue(),
  9417. RHSC->getValue())->isNullValue())
  9418. return TrivialCase(false);
  9419. else
  9420. return TrivialCase(true);
  9421. }
  9422. // Otherwise swap the operands to put the constant on the right.
  9423. std::swap(LHS, RHS);
  9424. Pred = ICmpInst::getSwappedPredicate(Pred);
  9425. Changed = true;
  9426. }
  9427. // If we're comparing an addrec with a value which is loop-invariant in the
  9428. // addrec's loop, put the addrec on the left. Also make a dominance check,
  9429. // as both operands could be addrecs loop-invariant in each other's loop.
  9430. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(RHS)) {
  9431. const Loop *L = AR->getLoop();
  9432. if (isLoopInvariant(LHS, L) && properlyDominates(LHS, L->getHeader())) {
  9433. std::swap(LHS, RHS);
  9434. Pred = ICmpInst::getSwappedPredicate(Pred);
  9435. Changed = true;
  9436. }
  9437. }
  9438. // If there's a constant operand, canonicalize comparisons with boundary
  9439. // cases, and canonicalize *-or-equal comparisons to regular comparisons.
  9440. if (const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS)) {
  9441. const APInt &RA = RC->getAPInt();
  9442. bool SimplifiedByConstantRange = false;
  9443. if (!ICmpInst::isEquality(Pred)) {
  9444. ConstantRange ExactCR = ConstantRange::makeExactICmpRegion(Pred, RA);
  9445. if (ExactCR.isFullSet())
  9446. return TrivialCase(true);
  9447. else if (ExactCR.isEmptySet())
  9448. return TrivialCase(false);
  9449. APInt NewRHS;
  9450. CmpInst::Predicate NewPred;
  9451. if (ExactCR.getEquivalentICmp(NewPred, NewRHS) &&
  9452. ICmpInst::isEquality(NewPred)) {
  9453. // We were able to convert an inequality to an equality.
  9454. Pred = NewPred;
  9455. RHS = getConstant(NewRHS);
  9456. Changed = SimplifiedByConstantRange = true;
  9457. }
  9458. }
  9459. if (!SimplifiedByConstantRange) {
  9460. switch (Pred) {
  9461. default:
  9462. break;
  9463. case ICmpInst::ICMP_EQ:
  9464. case ICmpInst::ICMP_NE:
  9465. // Fold ((-1) * %a) + %b == 0 (equivalent to %b-%a == 0) into %a == %b.
  9466. if (!RA)
  9467. if (const SCEVAddExpr *AE = dyn_cast<SCEVAddExpr>(LHS))
  9468. if (const SCEVMulExpr *ME =
  9469. dyn_cast<SCEVMulExpr>(AE->getOperand(0)))
  9470. if (AE->getNumOperands() == 2 && ME->getNumOperands() == 2 &&
  9471. ME->getOperand(0)->isAllOnesValue()) {
  9472. RHS = AE->getOperand(1);
  9473. LHS = ME->getOperand(1);
  9474. Changed = true;
  9475. }
  9476. break;
  9477. // The "Should have been caught earlier!" messages refer to the fact
  9478. // that the ExactCR.isFullSet() or ExactCR.isEmptySet() check above
  9479. // should have fired on the corresponding cases, and canonicalized the
  9480. // check to trivial case.
  9481. case ICmpInst::ICMP_UGE:
  9482. assert(!RA.isMinValue() && "Should have been caught earlier!");
  9483. Pred = ICmpInst::ICMP_UGT;
  9484. RHS = getConstant(RA - 1);
  9485. Changed = true;
  9486. break;
  9487. case ICmpInst::ICMP_ULE:
  9488. assert(!RA.isMaxValue() && "Should have been caught earlier!");
  9489. Pred = ICmpInst::ICMP_ULT;
  9490. RHS = getConstant(RA + 1);
  9491. Changed = true;
  9492. break;
  9493. case ICmpInst::ICMP_SGE:
  9494. assert(!RA.isMinSignedValue() && "Should have been caught earlier!");
  9495. Pred = ICmpInst::ICMP_SGT;
  9496. RHS = getConstant(RA - 1);
  9497. Changed = true;
  9498. break;
  9499. case ICmpInst::ICMP_SLE:
  9500. assert(!RA.isMaxSignedValue() && "Should have been caught earlier!");
  9501. Pred = ICmpInst::ICMP_SLT;
  9502. RHS = getConstant(RA + 1);
  9503. Changed = true;
  9504. break;
  9505. }
  9506. }
  9507. }
  9508. // Check for obvious equality.
  9509. if (HasSameValue(LHS, RHS)) {
  9510. if (ICmpInst::isTrueWhenEqual(Pred))
  9511. return TrivialCase(true);
  9512. if (ICmpInst::isFalseWhenEqual(Pred))
  9513. return TrivialCase(false);
  9514. }
  9515. // If possible, canonicalize GE/LE comparisons to GT/LT comparisons, by
  9516. // adding or subtracting 1 from one of the operands. This can be done for
  9517. // one of two reasons:
  9518. // 1) The range of the RHS does not include the (signed/unsigned) boundaries
  9519. // 2) The loop is finite, with this comparison controlling the exit. Since the
  9520. // loop is finite, the bound cannot include the corresponding boundary
  9521. // (otherwise it would loop forever).
  9522. switch (Pred) {
  9523. case ICmpInst::ICMP_SLE:
  9524. if (ControllingFiniteLoop || !getSignedRangeMax(RHS).isMaxSignedValue()) {
  9525. RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
  9526. SCEV::FlagNSW);
  9527. Pred = ICmpInst::ICMP_SLT;
  9528. Changed = true;
  9529. } else if (!getSignedRangeMin(LHS).isMinSignedValue()) {
  9530. LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS,
  9531. SCEV::FlagNSW);
  9532. Pred = ICmpInst::ICMP_SLT;
  9533. Changed = true;
  9534. }
  9535. break;
  9536. case ICmpInst::ICMP_SGE:
  9537. if (ControllingFiniteLoop || !getSignedRangeMin(RHS).isMinSignedValue()) {
  9538. RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS,
  9539. SCEV::FlagNSW);
  9540. Pred = ICmpInst::ICMP_SGT;
  9541. Changed = true;
  9542. } else if (!getSignedRangeMax(LHS).isMaxSignedValue()) {
  9543. LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
  9544. SCEV::FlagNSW);
  9545. Pred = ICmpInst::ICMP_SGT;
  9546. Changed = true;
  9547. }
  9548. break;
  9549. case ICmpInst::ICMP_ULE:
  9550. if (ControllingFiniteLoop || !getUnsignedRangeMax(RHS).isMaxValue()) {
  9551. RHS = getAddExpr(getConstant(RHS->getType(), 1, true), RHS,
  9552. SCEV::FlagNUW);
  9553. Pred = ICmpInst::ICMP_ULT;
  9554. Changed = true;
  9555. } else if (!getUnsignedRangeMin(LHS).isMinValue()) {
  9556. LHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), LHS);
  9557. Pred = ICmpInst::ICMP_ULT;
  9558. Changed = true;
  9559. }
  9560. break;
  9561. case ICmpInst::ICMP_UGE:
  9562. if (ControllingFiniteLoop || !getUnsignedRangeMin(RHS).isMinValue()) {
  9563. RHS = getAddExpr(getConstant(RHS->getType(), (uint64_t)-1, true), RHS);
  9564. Pred = ICmpInst::ICMP_UGT;
  9565. Changed = true;
  9566. } else if (!getUnsignedRangeMax(LHS).isMaxValue()) {
  9567. LHS = getAddExpr(getConstant(RHS->getType(), 1, true), LHS,
  9568. SCEV::FlagNUW);
  9569. Pred = ICmpInst::ICMP_UGT;
  9570. Changed = true;
  9571. }
  9572. break;
  9573. default:
  9574. break;
  9575. }
  9576. // TODO: More simplifications are possible here.
  9577. // Recursively simplify until we either hit a recursion limit or nothing
  9578. // changes.
  9579. if (Changed)
  9580. return SimplifyICmpOperands(Pred, LHS, RHS, Depth + 1,
  9581. ControllingFiniteLoop);
  9582. return Changed;
  9583. }
  9584. bool ScalarEvolution::isKnownNegative(const SCEV *S) {
  9585. return getSignedRangeMax(S).isNegative();
  9586. }
  9587. bool ScalarEvolution::isKnownPositive(const SCEV *S) {
  9588. return getSignedRangeMin(S).isStrictlyPositive();
  9589. }
  9590. bool ScalarEvolution::isKnownNonNegative(const SCEV *S) {
  9591. return !getSignedRangeMin(S).isNegative();
  9592. }
  9593. bool ScalarEvolution::isKnownNonPositive(const SCEV *S) {
  9594. return !getSignedRangeMax(S).isStrictlyPositive();
  9595. }
  9596. bool ScalarEvolution::isKnownNonZero(const SCEV *S) {
  9597. return getUnsignedRangeMin(S) != 0;
  9598. }
  9599. std::pair<const SCEV *, const SCEV *>
  9600. ScalarEvolution::SplitIntoInitAndPostInc(const Loop *L, const SCEV *S) {
  9601. // Compute SCEV on entry of loop L.
  9602. const SCEV *Start = SCEVInitRewriter::rewrite(S, L, *this);
  9603. if (Start == getCouldNotCompute())
  9604. return { Start, Start };
  9605. // Compute post increment SCEV for loop L.
  9606. const SCEV *PostInc = SCEVPostIncRewriter::rewrite(S, L, *this);
  9607. assert(PostInc != getCouldNotCompute() && "Unexpected could not compute");
  9608. return { Start, PostInc };
  9609. }
  9610. bool ScalarEvolution::isKnownViaInduction(ICmpInst::Predicate Pred,
  9611. const SCEV *LHS, const SCEV *RHS) {
  9612. // First collect all loops.
  9613. SmallPtrSet<const Loop *, 8> LoopsUsed;
  9614. getUsedLoops(LHS, LoopsUsed);
  9615. getUsedLoops(RHS, LoopsUsed);
  9616. if (LoopsUsed.empty())
  9617. return false;
  9618. // Domination relationship must be a linear order on collected loops.
  9619. #ifndef NDEBUG
  9620. for (const auto *L1 : LoopsUsed)
  9621. for (const auto *L2 : LoopsUsed)
  9622. assert((DT.dominates(L1->getHeader(), L2->getHeader()) ||
  9623. DT.dominates(L2->getHeader(), L1->getHeader())) &&
  9624. "Domination relationship is not a linear order");
  9625. #endif
  9626. const Loop *MDL =
  9627. *std::max_element(LoopsUsed.begin(), LoopsUsed.end(),
  9628. [&](const Loop *L1, const Loop *L2) {
  9629. return DT.properlyDominates(L1->getHeader(), L2->getHeader());
  9630. });
  9631. // Get init and post increment value for LHS.
  9632. auto SplitLHS = SplitIntoInitAndPostInc(MDL, LHS);
  9633. // if LHS contains unknown non-invariant SCEV then bail out.
  9634. if (SplitLHS.first == getCouldNotCompute())
  9635. return false;
  9636. assert (SplitLHS.second != getCouldNotCompute() && "Unexpected CNC");
  9637. // Get init and post increment value for RHS.
  9638. auto SplitRHS = SplitIntoInitAndPostInc(MDL, RHS);
  9639. // if RHS contains unknown non-invariant SCEV then bail out.
  9640. if (SplitRHS.first == getCouldNotCompute())
  9641. return false;
  9642. assert (SplitRHS.second != getCouldNotCompute() && "Unexpected CNC");
  9643. // It is possible that init SCEV contains an invariant load but it does
  9644. // not dominate MDL and is not available at MDL loop entry, so we should
  9645. // check it here.
  9646. if (!isAvailableAtLoopEntry(SplitLHS.first, MDL) ||
  9647. !isAvailableAtLoopEntry(SplitRHS.first, MDL))
  9648. return false;
  9649. // It seems backedge guard check is faster than entry one so in some cases
  9650. // it can speed up whole estimation by short circuit
  9651. return isLoopBackedgeGuardedByCond(MDL, Pred, SplitLHS.second,
  9652. SplitRHS.second) &&
  9653. isLoopEntryGuardedByCond(MDL, Pred, SplitLHS.first, SplitRHS.first);
  9654. }
  9655. bool ScalarEvolution::isKnownPredicate(ICmpInst::Predicate Pred,
  9656. const SCEV *LHS, const SCEV *RHS) {
  9657. // Canonicalize the inputs first.
  9658. (void)SimplifyICmpOperands(Pred, LHS, RHS);
  9659. if (isKnownViaInduction(Pred, LHS, RHS))
  9660. return true;
  9661. if (isKnownPredicateViaSplitting(Pred, LHS, RHS))
  9662. return true;
  9663. // Otherwise see what can be done with some simple reasoning.
  9664. return isKnownViaNonRecursiveReasoning(Pred, LHS, RHS);
  9665. }
  9666. std::optional<bool> ScalarEvolution::evaluatePredicate(ICmpInst::Predicate Pred,
  9667. const SCEV *LHS,
  9668. const SCEV *RHS) {
  9669. if (isKnownPredicate(Pred, LHS, RHS))
  9670. return true;
  9671. else if (isKnownPredicate(ICmpInst::getInversePredicate(Pred), LHS, RHS))
  9672. return false;
  9673. return std::nullopt;
  9674. }
  9675. bool ScalarEvolution::isKnownPredicateAt(ICmpInst::Predicate Pred,
  9676. const SCEV *LHS, const SCEV *RHS,
  9677. const Instruction *CtxI) {
  9678. // TODO: Analyze guards and assumes from Context's block.
  9679. return isKnownPredicate(Pred, LHS, RHS) ||
  9680. isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS);
  9681. }
  9682. std::optional<bool>
  9683. ScalarEvolution::evaluatePredicateAt(ICmpInst::Predicate Pred, const SCEV *LHS,
  9684. const SCEV *RHS, const Instruction *CtxI) {
  9685. std::optional<bool> KnownWithoutContext = evaluatePredicate(Pred, LHS, RHS);
  9686. if (KnownWithoutContext)
  9687. return KnownWithoutContext;
  9688. if (isBasicBlockEntryGuardedByCond(CtxI->getParent(), Pred, LHS, RHS))
  9689. return true;
  9690. else if (isBasicBlockEntryGuardedByCond(CtxI->getParent(),
  9691. ICmpInst::getInversePredicate(Pred),
  9692. LHS, RHS))
  9693. return false;
  9694. return std::nullopt;
  9695. }
  9696. bool ScalarEvolution::isKnownOnEveryIteration(ICmpInst::Predicate Pred,
  9697. const SCEVAddRecExpr *LHS,
  9698. const SCEV *RHS) {
  9699. const Loop *L = LHS->getLoop();
  9700. return isLoopEntryGuardedByCond(L, Pred, LHS->getStart(), RHS) &&
  9701. isLoopBackedgeGuardedByCond(L, Pred, LHS->getPostIncExpr(*this), RHS);
  9702. }
  9703. std::optional<ScalarEvolution::MonotonicPredicateType>
  9704. ScalarEvolution::getMonotonicPredicateType(const SCEVAddRecExpr *LHS,
  9705. ICmpInst::Predicate Pred) {
  9706. auto Result = getMonotonicPredicateTypeImpl(LHS, Pred);
  9707. #ifndef NDEBUG
  9708. // Verify an invariant: inverting the predicate should turn a monotonically
  9709. // increasing change to a monotonically decreasing one, and vice versa.
  9710. if (Result) {
  9711. auto ResultSwapped =
  9712. getMonotonicPredicateTypeImpl(LHS, ICmpInst::getSwappedPredicate(Pred));
  9713. assert(*ResultSwapped != *Result &&
  9714. "monotonicity should flip as we flip the predicate");
  9715. }
  9716. #endif
  9717. return Result;
  9718. }
  9719. std::optional<ScalarEvolution::MonotonicPredicateType>
  9720. ScalarEvolution::getMonotonicPredicateTypeImpl(const SCEVAddRecExpr *LHS,
  9721. ICmpInst::Predicate Pred) {
  9722. // A zero step value for LHS means the induction variable is essentially a
  9723. // loop invariant value. We don't really depend on the predicate actually
  9724. // flipping from false to true (for increasing predicates, and the other way
  9725. // around for decreasing predicates), all we care about is that *if* the
  9726. // predicate changes then it only changes from false to true.
  9727. //
  9728. // A zero step value in itself is not very useful, but there may be places
  9729. // where SCEV can prove X >= 0 but not prove X > 0, so it is helpful to be
  9730. // as general as possible.
  9731. // Only handle LE/LT/GE/GT predicates.
  9732. if (!ICmpInst::isRelational(Pred))
  9733. return std::nullopt;
  9734. bool IsGreater = ICmpInst::isGE(Pred) || ICmpInst::isGT(Pred);
  9735. assert((IsGreater || ICmpInst::isLE(Pred) || ICmpInst::isLT(Pred)) &&
  9736. "Should be greater or less!");
  9737. // Check that AR does not wrap.
  9738. if (ICmpInst::isUnsigned(Pred)) {
  9739. if (!LHS->hasNoUnsignedWrap())
  9740. return std::nullopt;
  9741. return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
  9742. } else {
  9743. assert(ICmpInst::isSigned(Pred) &&
  9744. "Relational predicate is either signed or unsigned!");
  9745. if (!LHS->hasNoSignedWrap())
  9746. return std::nullopt;
  9747. const SCEV *Step = LHS->getStepRecurrence(*this);
  9748. if (isKnownNonNegative(Step))
  9749. return IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
  9750. if (isKnownNonPositive(Step))
  9751. return !IsGreater ? MonotonicallyIncreasing : MonotonicallyDecreasing;
  9752. return std::nullopt;
  9753. }
  9754. }
  9755. std::optional<ScalarEvolution::LoopInvariantPredicate>
  9756. ScalarEvolution::getLoopInvariantPredicate(ICmpInst::Predicate Pred,
  9757. const SCEV *LHS, const SCEV *RHS,
  9758. const Loop *L,
  9759. const Instruction *CtxI) {
  9760. // If there is a loop-invariant, force it into the RHS, otherwise bail out.
  9761. if (!isLoopInvariant(RHS, L)) {
  9762. if (!isLoopInvariant(LHS, L))
  9763. return std::nullopt;
  9764. std::swap(LHS, RHS);
  9765. Pred = ICmpInst::getSwappedPredicate(Pred);
  9766. }
  9767. const SCEVAddRecExpr *ArLHS = dyn_cast<SCEVAddRecExpr>(LHS);
  9768. if (!ArLHS || ArLHS->getLoop() != L)
  9769. return std::nullopt;
  9770. auto MonotonicType = getMonotonicPredicateType(ArLHS, Pred);
  9771. if (!MonotonicType)
  9772. return std::nullopt;
  9773. // If the predicate "ArLHS `Pred` RHS" monotonically increases from false to
  9774. // true as the loop iterates, and the backedge is control dependent on
  9775. // "ArLHS `Pred` RHS" == true then we can reason as follows:
  9776. //
  9777. // * if the predicate was false in the first iteration then the predicate
  9778. // is never evaluated again, since the loop exits without taking the
  9779. // backedge.
  9780. // * if the predicate was true in the first iteration then it will
  9781. // continue to be true for all future iterations since it is
  9782. // monotonically increasing.
  9783. //
  9784. // For both the above possibilities, we can replace the loop varying
  9785. // predicate with its value on the first iteration of the loop (which is
  9786. // loop invariant).
  9787. //
  9788. // A similar reasoning applies for a monotonically decreasing predicate, by
  9789. // replacing true with false and false with true in the above two bullets.
  9790. bool Increasing = *MonotonicType == ScalarEvolution::MonotonicallyIncreasing;
  9791. auto P = Increasing ? Pred : ICmpInst::getInversePredicate(Pred);
  9792. if (isLoopBackedgeGuardedByCond(L, P, LHS, RHS))
  9793. return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
  9794. RHS);
  9795. if (!CtxI)
  9796. return std::nullopt;
  9797. // Try to prove via context.
  9798. // TODO: Support other cases.
  9799. switch (Pred) {
  9800. default:
  9801. break;
  9802. case ICmpInst::ICMP_ULE:
  9803. case ICmpInst::ICMP_ULT: {
  9804. assert(ArLHS->hasNoUnsignedWrap() && "Is a requirement of monotonicity!");
  9805. // Given preconditions
  9806. // (1) ArLHS does not cross the border of positive and negative parts of
  9807. // range because of:
  9808. // - Positive step; (TODO: lift this limitation)
  9809. // - nuw - does not cross zero boundary;
  9810. // - nsw - does not cross SINT_MAX boundary;
  9811. // (2) ArLHS <s RHS
  9812. // (3) RHS >=s 0
  9813. // we can replace the loop variant ArLHS <u RHS condition with loop
  9814. // invariant Start(ArLHS) <u RHS.
  9815. //
  9816. // Because of (1) there are two options:
  9817. // - ArLHS is always negative. It means that ArLHS <u RHS is always false;
  9818. // - ArLHS is always non-negative. Because of (3) RHS is also non-negative.
  9819. // It means that ArLHS <s RHS <=> ArLHS <u RHS.
  9820. // Because of (2) ArLHS <u RHS is trivially true.
  9821. // All together it means that ArLHS <u RHS <=> Start(ArLHS) >=s 0.
  9822. // We can strengthen this to Start(ArLHS) <u RHS.
  9823. auto SignFlippedPred = ICmpInst::getFlippedSignednessPredicate(Pred);
  9824. if (ArLHS->hasNoSignedWrap() && ArLHS->isAffine() &&
  9825. isKnownPositive(ArLHS->getStepRecurrence(*this)) &&
  9826. isKnownNonNegative(RHS) &&
  9827. isKnownPredicateAt(SignFlippedPred, ArLHS, RHS, CtxI))
  9828. return ScalarEvolution::LoopInvariantPredicate(Pred, ArLHS->getStart(),
  9829. RHS);
  9830. }
  9831. }
  9832. return std::nullopt;
  9833. }
  9834. std::optional<ScalarEvolution::LoopInvariantPredicate>
  9835. ScalarEvolution::getLoopInvariantExitCondDuringFirstIterations(
  9836. ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
  9837. const Instruction *CtxI, const SCEV *MaxIter) {
  9838. if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
  9839. Pred, LHS, RHS, L, CtxI, MaxIter))
  9840. return LIP;
  9841. if (auto *UMin = dyn_cast<SCEVUMinExpr>(MaxIter))
  9842. // Number of iterations expressed as UMIN isn't always great for expressing
  9843. // the value on the last iteration. If the straightforward approach didn't
  9844. // work, try the following trick: if the a predicate is invariant for X, it
  9845. // is also invariant for umin(X, ...). So try to find something that works
  9846. // among subexpressions of MaxIter expressed as umin.
  9847. for (auto *Op : UMin->operands())
  9848. if (auto LIP = getLoopInvariantExitCondDuringFirstIterationsImpl(
  9849. Pred, LHS, RHS, L, CtxI, Op))
  9850. return LIP;
  9851. return std::nullopt;
  9852. }
  9853. std::optional<ScalarEvolution::LoopInvariantPredicate>
  9854. ScalarEvolution::getLoopInvariantExitCondDuringFirstIterationsImpl(
  9855. ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS, const Loop *L,
  9856. const Instruction *CtxI, const SCEV *MaxIter) {
  9857. // Try to prove the following set of facts:
  9858. // - The predicate is monotonic in the iteration space.
  9859. // - If the check does not fail on the 1st iteration:
  9860. // - No overflow will happen during first MaxIter iterations;
  9861. // - It will not fail on the MaxIter'th iteration.
  9862. // If the check does fail on the 1st iteration, we leave the loop and no
  9863. // other checks matter.
  9864. // If there is a loop-invariant, force it into the RHS, otherwise bail out.
  9865. if (!isLoopInvariant(RHS, L)) {
  9866. if (!isLoopInvariant(LHS, L))
  9867. return std::nullopt;
  9868. std::swap(LHS, RHS);
  9869. Pred = ICmpInst::getSwappedPredicate(Pred);
  9870. }
  9871. auto *AR = dyn_cast<SCEVAddRecExpr>(LHS);
  9872. if (!AR || AR->getLoop() != L)
  9873. return std::nullopt;
  9874. // The predicate must be relational (i.e. <, <=, >=, >).
  9875. if (!ICmpInst::isRelational(Pred))
  9876. return std::nullopt;
  9877. // TODO: Support steps other than +/- 1.
  9878. const SCEV *Step = AR->getStepRecurrence(*this);
  9879. auto *One = getOne(Step->getType());
  9880. auto *MinusOne = getNegativeSCEV(One);
  9881. if (Step != One && Step != MinusOne)
  9882. return std::nullopt;
  9883. // Type mismatch here means that MaxIter is potentially larger than max
  9884. // unsigned value in start type, which mean we cannot prove no wrap for the
  9885. // indvar.
  9886. if (AR->getType() != MaxIter->getType())
  9887. return std::nullopt;
  9888. // Value of IV on suggested last iteration.
  9889. const SCEV *Last = AR->evaluateAtIteration(MaxIter, *this);
  9890. // Does it still meet the requirement?
  9891. if (!isLoopBackedgeGuardedByCond(L, Pred, Last, RHS))
  9892. return std::nullopt;
  9893. // Because step is +/- 1 and MaxIter has same type as Start (i.e. it does
  9894. // not exceed max unsigned value of this type), this effectively proves
  9895. // that there is no wrap during the iteration. To prove that there is no
  9896. // signed/unsigned wrap, we need to check that
  9897. // Start <= Last for step = 1 or Start >= Last for step = -1.
  9898. ICmpInst::Predicate NoOverflowPred =
  9899. CmpInst::isSigned(Pred) ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
  9900. if (Step == MinusOne)
  9901. NoOverflowPred = CmpInst::getSwappedPredicate(NoOverflowPred);
  9902. const SCEV *Start = AR->getStart();
  9903. if (!isKnownPredicateAt(NoOverflowPred, Start, Last, CtxI))
  9904. return std::nullopt;
  9905. // Everything is fine.
  9906. return ScalarEvolution::LoopInvariantPredicate(Pred, Start, RHS);
  9907. }
  9908. bool ScalarEvolution::isKnownPredicateViaConstantRanges(
  9909. ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS) {
  9910. if (HasSameValue(LHS, RHS))
  9911. return ICmpInst::isTrueWhenEqual(Pred);
  9912. // This code is split out from isKnownPredicate because it is called from
  9913. // within isLoopEntryGuardedByCond.
  9914. auto CheckRanges = [&](const ConstantRange &RangeLHS,
  9915. const ConstantRange &RangeRHS) {
  9916. return RangeLHS.icmp(Pred, RangeRHS);
  9917. };
  9918. // The check at the top of the function catches the case where the values are
  9919. // known to be equal.
  9920. if (Pred == CmpInst::ICMP_EQ)
  9921. return false;
  9922. if (Pred == CmpInst::ICMP_NE) {
  9923. auto SL = getSignedRange(LHS);
  9924. auto SR = getSignedRange(RHS);
  9925. if (CheckRanges(SL, SR))
  9926. return true;
  9927. auto UL = getUnsignedRange(LHS);
  9928. auto UR = getUnsignedRange(RHS);
  9929. if (CheckRanges(UL, UR))
  9930. return true;
  9931. auto *Diff = getMinusSCEV(LHS, RHS);
  9932. return !isa<SCEVCouldNotCompute>(Diff) && isKnownNonZero(Diff);
  9933. }
  9934. if (CmpInst::isSigned(Pred)) {
  9935. auto SL = getSignedRange(LHS);
  9936. auto SR = getSignedRange(RHS);
  9937. return CheckRanges(SL, SR);
  9938. }
  9939. auto UL = getUnsignedRange(LHS);
  9940. auto UR = getUnsignedRange(RHS);
  9941. return CheckRanges(UL, UR);
  9942. }
  9943. bool ScalarEvolution::isKnownPredicateViaNoOverflow(ICmpInst::Predicate Pred,
  9944. const SCEV *LHS,
  9945. const SCEV *RHS) {
  9946. // Match X to (A + C1)<ExpectedFlags> and Y to (A + C2)<ExpectedFlags>, where
  9947. // C1 and C2 are constant integers. If either X or Y are not add expressions,
  9948. // consider them as X + 0 and Y + 0 respectively. C1 and C2 are returned via
  9949. // OutC1 and OutC2.
  9950. auto MatchBinaryAddToConst = [this](const SCEV *X, const SCEV *Y,
  9951. APInt &OutC1, APInt &OutC2,
  9952. SCEV::NoWrapFlags ExpectedFlags) {
  9953. const SCEV *XNonConstOp, *XConstOp;
  9954. const SCEV *YNonConstOp, *YConstOp;
  9955. SCEV::NoWrapFlags XFlagsPresent;
  9956. SCEV::NoWrapFlags YFlagsPresent;
  9957. if (!splitBinaryAdd(X, XConstOp, XNonConstOp, XFlagsPresent)) {
  9958. XConstOp = getZero(X->getType());
  9959. XNonConstOp = X;
  9960. XFlagsPresent = ExpectedFlags;
  9961. }
  9962. if (!isa<SCEVConstant>(XConstOp) ||
  9963. (XFlagsPresent & ExpectedFlags) != ExpectedFlags)
  9964. return false;
  9965. if (!splitBinaryAdd(Y, YConstOp, YNonConstOp, YFlagsPresent)) {
  9966. YConstOp = getZero(Y->getType());
  9967. YNonConstOp = Y;
  9968. YFlagsPresent = ExpectedFlags;
  9969. }
  9970. if (!isa<SCEVConstant>(YConstOp) ||
  9971. (YFlagsPresent & ExpectedFlags) != ExpectedFlags)
  9972. return false;
  9973. if (YNonConstOp != XNonConstOp)
  9974. return false;
  9975. OutC1 = cast<SCEVConstant>(XConstOp)->getAPInt();
  9976. OutC2 = cast<SCEVConstant>(YConstOp)->getAPInt();
  9977. return true;
  9978. };
  9979. APInt C1;
  9980. APInt C2;
  9981. switch (Pred) {
  9982. default:
  9983. break;
  9984. case ICmpInst::ICMP_SGE:
  9985. std::swap(LHS, RHS);
  9986. [[fallthrough]];
  9987. case ICmpInst::ICMP_SLE:
  9988. // (X + C1)<nsw> s<= (X + C2)<nsw> if C1 s<= C2.
  9989. if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.sle(C2))
  9990. return true;
  9991. break;
  9992. case ICmpInst::ICMP_SGT:
  9993. std::swap(LHS, RHS);
  9994. [[fallthrough]];
  9995. case ICmpInst::ICMP_SLT:
  9996. // (X + C1)<nsw> s< (X + C2)<nsw> if C1 s< C2.
  9997. if (MatchBinaryAddToConst(LHS, RHS, C1, C2, SCEV::FlagNSW) && C1.slt(C2))
  9998. return true;
  9999. break;
  10000. case ICmpInst::ICMP_UGE:
  10001. std::swap(LHS, RHS);
  10002. [[fallthrough]];
  10003. case ICmpInst::ICMP_ULE:
  10004. // (X + C1)<nuw> u<= (X + C2)<nuw> for C1 u<= C2.
  10005. if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ule(C2))
  10006. return true;
  10007. break;
  10008. case ICmpInst::ICMP_UGT:
  10009. std::swap(LHS, RHS);
  10010. [[fallthrough]];
  10011. case ICmpInst::ICMP_ULT:
  10012. // (X + C1)<nuw> u< (X + C2)<nuw> if C1 u< C2.
  10013. if (MatchBinaryAddToConst(RHS, LHS, C2, C1, SCEV::FlagNUW) && C1.ult(C2))
  10014. return true;
  10015. break;
  10016. }
  10017. return false;
  10018. }
  10019. bool ScalarEvolution::isKnownPredicateViaSplitting(ICmpInst::Predicate Pred,
  10020. const SCEV *LHS,
  10021. const SCEV *RHS) {
  10022. if (Pred != ICmpInst::ICMP_ULT || ProvingSplitPredicate)
  10023. return false;
  10024. // Allowing arbitrary number of activations of isKnownPredicateViaSplitting on
  10025. // the stack can result in exponential time complexity.
  10026. SaveAndRestore Restore(ProvingSplitPredicate, true);
  10027. // If L >= 0 then I `ult` L <=> I >= 0 && I `slt` L
  10028. //
  10029. // To prove L >= 0 we use isKnownNonNegative whereas to prove I >= 0 we use
  10030. // isKnownPredicate. isKnownPredicate is more powerful, but also more
  10031. // expensive; and using isKnownNonNegative(RHS) is sufficient for most of the
  10032. // interesting cases seen in practice. We can consider "upgrading" L >= 0 to
  10033. // use isKnownPredicate later if needed.
  10034. return isKnownNonNegative(RHS) &&
  10035. isKnownPredicate(CmpInst::ICMP_SGE, LHS, getZero(LHS->getType())) &&
  10036. isKnownPredicate(CmpInst::ICMP_SLT, LHS, RHS);
  10037. }
  10038. bool ScalarEvolution::isImpliedViaGuard(const BasicBlock *BB,
  10039. ICmpInst::Predicate Pred,
  10040. const SCEV *LHS, const SCEV *RHS) {
  10041. // No need to even try if we know the module has no guards.
  10042. if (AC.assumptions().empty())
  10043. return false;
  10044. return any_of(*BB, [&](const Instruction &I) {
  10045. using namespace llvm::PatternMatch;
  10046. Value *Condition;
  10047. return match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
  10048. m_Value(Condition))) &&
  10049. isImpliedCond(Pred, LHS, RHS, Condition, false);
  10050. });
  10051. }
  10052. /// isLoopBackedgeGuardedByCond - Test whether the backedge of the loop is
  10053. /// protected by a conditional between LHS and RHS. This is used to
  10054. /// to eliminate casts.
  10055. bool
  10056. ScalarEvolution::isLoopBackedgeGuardedByCond(const Loop *L,
  10057. ICmpInst::Predicate Pred,
  10058. const SCEV *LHS, const SCEV *RHS) {
  10059. // Interpret a null as meaning no loop, where there is obviously no guard
  10060. // (interprocedural conditions notwithstanding). Do not bother about
  10061. // unreachable loops.
  10062. if (!L || !DT.isReachableFromEntry(L->getHeader()))
  10063. return true;
  10064. if (VerifyIR)
  10065. assert(!verifyFunction(*L->getHeader()->getParent(), &dbgs()) &&
  10066. "This cannot be done on broken IR!");
  10067. if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
  10068. return true;
  10069. BasicBlock *Latch = L->getLoopLatch();
  10070. if (!Latch)
  10071. return false;
  10072. BranchInst *LoopContinuePredicate =
  10073. dyn_cast<BranchInst>(Latch->getTerminator());
  10074. if (LoopContinuePredicate && LoopContinuePredicate->isConditional() &&
  10075. isImpliedCond(Pred, LHS, RHS,
  10076. LoopContinuePredicate->getCondition(),
  10077. LoopContinuePredicate->getSuccessor(0) != L->getHeader()))
  10078. return true;
  10079. // We don't want more than one activation of the following loops on the stack
  10080. // -- that can lead to O(n!) time complexity.
  10081. if (WalkingBEDominatingConds)
  10082. return false;
  10083. SaveAndRestore ClearOnExit(WalkingBEDominatingConds, true);
  10084. // See if we can exploit a trip count to prove the predicate.
  10085. const auto &BETakenInfo = getBackedgeTakenInfo(L);
  10086. const SCEV *LatchBECount = BETakenInfo.getExact(Latch, this);
  10087. if (LatchBECount != getCouldNotCompute()) {
  10088. // We know that Latch branches back to the loop header exactly
  10089. // LatchBECount times. This means the backdege condition at Latch is
  10090. // equivalent to "{0,+,1} u< LatchBECount".
  10091. Type *Ty = LatchBECount->getType();
  10092. auto NoWrapFlags = SCEV::NoWrapFlags(SCEV::FlagNUW | SCEV::FlagNW);
  10093. const SCEV *LoopCounter =
  10094. getAddRecExpr(getZero(Ty), getOne(Ty), L, NoWrapFlags);
  10095. if (isImpliedCond(Pred, LHS, RHS, ICmpInst::ICMP_ULT, LoopCounter,
  10096. LatchBECount))
  10097. return true;
  10098. }
  10099. // Check conditions due to any @llvm.assume intrinsics.
  10100. for (auto &AssumeVH : AC.assumptions()) {
  10101. if (!AssumeVH)
  10102. continue;
  10103. auto *CI = cast<CallInst>(AssumeVH);
  10104. if (!DT.dominates(CI, Latch->getTerminator()))
  10105. continue;
  10106. if (isImpliedCond(Pred, LHS, RHS, CI->getArgOperand(0), false))
  10107. return true;
  10108. }
  10109. if (isImpliedViaGuard(Latch, Pred, LHS, RHS))
  10110. return true;
  10111. for (DomTreeNode *DTN = DT[Latch], *HeaderDTN = DT[L->getHeader()];
  10112. DTN != HeaderDTN; DTN = DTN->getIDom()) {
  10113. assert(DTN && "should reach the loop header before reaching the root!");
  10114. BasicBlock *BB = DTN->getBlock();
  10115. if (isImpliedViaGuard(BB, Pred, LHS, RHS))
  10116. return true;
  10117. BasicBlock *PBB = BB->getSinglePredecessor();
  10118. if (!PBB)
  10119. continue;
  10120. BranchInst *ContinuePredicate = dyn_cast<BranchInst>(PBB->getTerminator());
  10121. if (!ContinuePredicate || !ContinuePredicate->isConditional())
  10122. continue;
  10123. Value *Condition = ContinuePredicate->getCondition();
  10124. // If we have an edge `E` within the loop body that dominates the only
  10125. // latch, the condition guarding `E` also guards the backedge. This
  10126. // reasoning works only for loops with a single latch.
  10127. BasicBlockEdge DominatingEdge(PBB, BB);
  10128. if (DominatingEdge.isSingleEdge()) {
  10129. // We're constructively (and conservatively) enumerating edges within the
  10130. // loop body that dominate the latch. The dominator tree better agree
  10131. // with us on this:
  10132. assert(DT.dominates(DominatingEdge, Latch) && "should be!");
  10133. if (isImpliedCond(Pred, LHS, RHS, Condition,
  10134. BB != ContinuePredicate->getSuccessor(0)))
  10135. return true;
  10136. }
  10137. }
  10138. return false;
  10139. }
  10140. bool ScalarEvolution::isBasicBlockEntryGuardedByCond(const BasicBlock *BB,
  10141. ICmpInst::Predicate Pred,
  10142. const SCEV *LHS,
  10143. const SCEV *RHS) {
  10144. // Do not bother proving facts for unreachable code.
  10145. if (!DT.isReachableFromEntry(BB))
  10146. return true;
  10147. if (VerifyIR)
  10148. assert(!verifyFunction(*BB->getParent(), &dbgs()) &&
  10149. "This cannot be done on broken IR!");
  10150. // If we cannot prove strict comparison (e.g. a > b), maybe we can prove
  10151. // the facts (a >= b && a != b) separately. A typical situation is when the
  10152. // non-strict comparison is known from ranges and non-equality is known from
  10153. // dominating predicates. If we are proving strict comparison, we always try
  10154. // to prove non-equality and non-strict comparison separately.
  10155. auto NonStrictPredicate = ICmpInst::getNonStrictPredicate(Pred);
  10156. const bool ProvingStrictComparison = (Pred != NonStrictPredicate);
  10157. bool ProvedNonStrictComparison = false;
  10158. bool ProvedNonEquality = false;
  10159. auto SplitAndProve =
  10160. [&](std::function<bool(ICmpInst::Predicate)> Fn) -> bool {
  10161. if (!ProvedNonStrictComparison)
  10162. ProvedNonStrictComparison = Fn(NonStrictPredicate);
  10163. if (!ProvedNonEquality)
  10164. ProvedNonEquality = Fn(ICmpInst::ICMP_NE);
  10165. if (ProvedNonStrictComparison && ProvedNonEquality)
  10166. return true;
  10167. return false;
  10168. };
  10169. if (ProvingStrictComparison) {
  10170. auto ProofFn = [&](ICmpInst::Predicate P) {
  10171. return isKnownViaNonRecursiveReasoning(P, LHS, RHS);
  10172. };
  10173. if (SplitAndProve(ProofFn))
  10174. return true;
  10175. }
  10176. // Try to prove (Pred, LHS, RHS) using isImpliedCond.
  10177. auto ProveViaCond = [&](const Value *Condition, bool Inverse) {
  10178. const Instruction *CtxI = &BB->front();
  10179. if (isImpliedCond(Pred, LHS, RHS, Condition, Inverse, CtxI))
  10180. return true;
  10181. if (ProvingStrictComparison) {
  10182. auto ProofFn = [&](ICmpInst::Predicate P) {
  10183. return isImpliedCond(P, LHS, RHS, Condition, Inverse, CtxI);
  10184. };
  10185. if (SplitAndProve(ProofFn))
  10186. return true;
  10187. }
  10188. return false;
  10189. };
  10190. // Starting at the block's predecessor, climb up the predecessor chain, as long
  10191. // as there are predecessors that can be found that have unique successors
  10192. // leading to the original block.
  10193. const Loop *ContainingLoop = LI.getLoopFor(BB);
  10194. const BasicBlock *PredBB;
  10195. if (ContainingLoop && ContainingLoop->getHeader() == BB)
  10196. PredBB = ContainingLoop->getLoopPredecessor();
  10197. else
  10198. PredBB = BB->getSinglePredecessor();
  10199. for (std::pair<const BasicBlock *, const BasicBlock *> Pair(PredBB, BB);
  10200. Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
  10201. const BranchInst *BlockEntryPredicate =
  10202. dyn_cast<BranchInst>(Pair.first->getTerminator());
  10203. if (!BlockEntryPredicate || BlockEntryPredicate->isUnconditional())
  10204. continue;
  10205. if (ProveViaCond(BlockEntryPredicate->getCondition(),
  10206. BlockEntryPredicate->getSuccessor(0) != Pair.second))
  10207. return true;
  10208. }
  10209. // Check conditions due to any @llvm.assume intrinsics.
  10210. for (auto &AssumeVH : AC.assumptions()) {
  10211. if (!AssumeVH)
  10212. continue;
  10213. auto *CI = cast<CallInst>(AssumeVH);
  10214. if (!DT.dominates(CI, BB))
  10215. continue;
  10216. if (ProveViaCond(CI->getArgOperand(0), false))
  10217. return true;
  10218. }
  10219. return false;
  10220. }
  10221. bool ScalarEvolution::isLoopEntryGuardedByCond(const Loop *L,
  10222. ICmpInst::Predicate Pred,
  10223. const SCEV *LHS,
  10224. const SCEV *RHS) {
  10225. // Interpret a null as meaning no loop, where there is obviously no guard
  10226. // (interprocedural conditions notwithstanding).
  10227. if (!L)
  10228. return false;
  10229. // Both LHS and RHS must be available at loop entry.
  10230. assert(isAvailableAtLoopEntry(LHS, L) &&
  10231. "LHS is not available at Loop Entry");
  10232. assert(isAvailableAtLoopEntry(RHS, L) &&
  10233. "RHS is not available at Loop Entry");
  10234. if (isKnownViaNonRecursiveReasoning(Pred, LHS, RHS))
  10235. return true;
  10236. return isBasicBlockEntryGuardedByCond(L->getHeader(), Pred, LHS, RHS);
  10237. }
  10238. bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
  10239. const SCEV *RHS,
  10240. const Value *FoundCondValue, bool Inverse,
  10241. const Instruction *CtxI) {
  10242. // False conditions implies anything. Do not bother analyzing it further.
  10243. if (FoundCondValue ==
  10244. ConstantInt::getBool(FoundCondValue->getContext(), Inverse))
  10245. return true;
  10246. if (!PendingLoopPredicates.insert(FoundCondValue).second)
  10247. return false;
  10248. auto ClearOnExit =
  10249. make_scope_exit([&]() { PendingLoopPredicates.erase(FoundCondValue); });
  10250. // Recursively handle And and Or conditions.
  10251. const Value *Op0, *Op1;
  10252. if (match(FoundCondValue, m_LogicalAnd(m_Value(Op0), m_Value(Op1)))) {
  10253. if (!Inverse)
  10254. return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
  10255. isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
  10256. } else if (match(FoundCondValue, m_LogicalOr(m_Value(Op0), m_Value(Op1)))) {
  10257. if (Inverse)
  10258. return isImpliedCond(Pred, LHS, RHS, Op0, Inverse, CtxI) ||
  10259. isImpliedCond(Pred, LHS, RHS, Op1, Inverse, CtxI);
  10260. }
  10261. const ICmpInst *ICI = dyn_cast<ICmpInst>(FoundCondValue);
  10262. if (!ICI) return false;
  10263. // Now that we found a conditional branch that dominates the loop or controls
  10264. // the loop latch. Check to see if it is the comparison we are looking for.
  10265. ICmpInst::Predicate FoundPred;
  10266. if (Inverse)
  10267. FoundPred = ICI->getInversePredicate();
  10268. else
  10269. FoundPred = ICI->getPredicate();
  10270. const SCEV *FoundLHS = getSCEV(ICI->getOperand(0));
  10271. const SCEV *FoundRHS = getSCEV(ICI->getOperand(1));
  10272. return isImpliedCond(Pred, LHS, RHS, FoundPred, FoundLHS, FoundRHS, CtxI);
  10273. }
  10274. bool ScalarEvolution::isImpliedCond(ICmpInst::Predicate Pred, const SCEV *LHS,
  10275. const SCEV *RHS,
  10276. ICmpInst::Predicate FoundPred,
  10277. const SCEV *FoundLHS, const SCEV *FoundRHS,
  10278. const Instruction *CtxI) {
  10279. // Balance the types.
  10280. if (getTypeSizeInBits(LHS->getType()) <
  10281. getTypeSizeInBits(FoundLHS->getType())) {
  10282. // For unsigned and equality predicates, try to prove that both found
  10283. // operands fit into narrow unsigned range. If so, try to prove facts in
  10284. // narrow types.
  10285. if (!CmpInst::isSigned(FoundPred) && !FoundLHS->getType()->isPointerTy() &&
  10286. !FoundRHS->getType()->isPointerTy()) {
  10287. auto *NarrowType = LHS->getType();
  10288. auto *WideType = FoundLHS->getType();
  10289. auto BitWidth = getTypeSizeInBits(NarrowType);
  10290. const SCEV *MaxValue = getZeroExtendExpr(
  10291. getConstant(APInt::getMaxValue(BitWidth)), WideType);
  10292. if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundLHS,
  10293. MaxValue) &&
  10294. isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, FoundRHS,
  10295. MaxValue)) {
  10296. const SCEV *TruncFoundLHS = getTruncateExpr(FoundLHS, NarrowType);
  10297. const SCEV *TruncFoundRHS = getTruncateExpr(FoundRHS, NarrowType);
  10298. if (isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, TruncFoundLHS,
  10299. TruncFoundRHS, CtxI))
  10300. return true;
  10301. }
  10302. }
  10303. if (LHS->getType()->isPointerTy() || RHS->getType()->isPointerTy())
  10304. return false;
  10305. if (CmpInst::isSigned(Pred)) {
  10306. LHS = getSignExtendExpr(LHS, FoundLHS->getType());
  10307. RHS = getSignExtendExpr(RHS, FoundLHS->getType());
  10308. } else {
  10309. LHS = getZeroExtendExpr(LHS, FoundLHS->getType());
  10310. RHS = getZeroExtendExpr(RHS, FoundLHS->getType());
  10311. }
  10312. } else if (getTypeSizeInBits(LHS->getType()) >
  10313. getTypeSizeInBits(FoundLHS->getType())) {
  10314. if (FoundLHS->getType()->isPointerTy() || FoundRHS->getType()->isPointerTy())
  10315. return false;
  10316. if (CmpInst::isSigned(FoundPred)) {
  10317. FoundLHS = getSignExtendExpr(FoundLHS, LHS->getType());
  10318. FoundRHS = getSignExtendExpr(FoundRHS, LHS->getType());
  10319. } else {
  10320. FoundLHS = getZeroExtendExpr(FoundLHS, LHS->getType());
  10321. FoundRHS = getZeroExtendExpr(FoundRHS, LHS->getType());
  10322. }
  10323. }
  10324. return isImpliedCondBalancedTypes(Pred, LHS, RHS, FoundPred, FoundLHS,
  10325. FoundRHS, CtxI);
  10326. }
  10327. bool ScalarEvolution::isImpliedCondBalancedTypes(
  10328. ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
  10329. ICmpInst::Predicate FoundPred, const SCEV *FoundLHS, const SCEV *FoundRHS,
  10330. const Instruction *CtxI) {
  10331. assert(getTypeSizeInBits(LHS->getType()) ==
  10332. getTypeSizeInBits(FoundLHS->getType()) &&
  10333. "Types should be balanced!");
  10334. // Canonicalize the query to match the way instcombine will have
  10335. // canonicalized the comparison.
  10336. if (SimplifyICmpOperands(Pred, LHS, RHS))
  10337. if (LHS == RHS)
  10338. return CmpInst::isTrueWhenEqual(Pred);
  10339. if (SimplifyICmpOperands(FoundPred, FoundLHS, FoundRHS))
  10340. if (FoundLHS == FoundRHS)
  10341. return CmpInst::isFalseWhenEqual(FoundPred);
  10342. // Check to see if we can make the LHS or RHS match.
  10343. if (LHS == FoundRHS || RHS == FoundLHS) {
  10344. if (isa<SCEVConstant>(RHS)) {
  10345. std::swap(FoundLHS, FoundRHS);
  10346. FoundPred = ICmpInst::getSwappedPredicate(FoundPred);
  10347. } else {
  10348. std::swap(LHS, RHS);
  10349. Pred = ICmpInst::getSwappedPredicate(Pred);
  10350. }
  10351. }
  10352. // Check whether the found predicate is the same as the desired predicate.
  10353. if (FoundPred == Pred)
  10354. return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
  10355. // Check whether swapping the found predicate makes it the same as the
  10356. // desired predicate.
  10357. if (ICmpInst::getSwappedPredicate(FoundPred) == Pred) {
  10358. // We can write the implication
  10359. // 0. LHS Pred RHS <- FoundLHS SwapPred FoundRHS
  10360. // using one of the following ways:
  10361. // 1. LHS Pred RHS <- FoundRHS Pred FoundLHS
  10362. // 2. RHS SwapPred LHS <- FoundLHS SwapPred FoundRHS
  10363. // 3. LHS Pred RHS <- ~FoundLHS Pred ~FoundRHS
  10364. // 4. ~LHS SwapPred ~RHS <- FoundLHS SwapPred FoundRHS
  10365. // Forms 1. and 2. require swapping the operands of one condition. Don't
  10366. // do this if it would break canonical constant/addrec ordering.
  10367. if (!isa<SCEVConstant>(RHS) && !isa<SCEVAddRecExpr>(LHS))
  10368. return isImpliedCondOperands(FoundPred, RHS, LHS, FoundLHS, FoundRHS,
  10369. CtxI);
  10370. if (!isa<SCEVConstant>(FoundRHS) && !isa<SCEVAddRecExpr>(FoundLHS))
  10371. return isImpliedCondOperands(Pred, LHS, RHS, FoundRHS, FoundLHS, CtxI);
  10372. // There's no clear preference between forms 3. and 4., try both. Avoid
  10373. // forming getNotSCEV of pointer values as the resulting subtract is
  10374. // not legal.
  10375. if (!LHS->getType()->isPointerTy() && !RHS->getType()->isPointerTy() &&
  10376. isImpliedCondOperands(FoundPred, getNotSCEV(LHS), getNotSCEV(RHS),
  10377. FoundLHS, FoundRHS, CtxI))
  10378. return true;
  10379. if (!FoundLHS->getType()->isPointerTy() &&
  10380. !FoundRHS->getType()->isPointerTy() &&
  10381. isImpliedCondOperands(Pred, LHS, RHS, getNotSCEV(FoundLHS),
  10382. getNotSCEV(FoundRHS), CtxI))
  10383. return true;
  10384. return false;
  10385. }
  10386. auto IsSignFlippedPredicate = [](CmpInst::Predicate P1,
  10387. CmpInst::Predicate P2) {
  10388. assert(P1 != P2 && "Handled earlier!");
  10389. return CmpInst::isRelational(P2) &&
  10390. P1 == CmpInst::getFlippedSignednessPredicate(P2);
  10391. };
  10392. if (IsSignFlippedPredicate(Pred, FoundPred)) {
  10393. // Unsigned comparison is the same as signed comparison when both the
  10394. // operands are non-negative or negative.
  10395. if ((isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) ||
  10396. (isKnownNegative(FoundLHS) && isKnownNegative(FoundRHS)))
  10397. return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI);
  10398. // Create local copies that we can freely swap and canonicalize our
  10399. // conditions to "le/lt".
  10400. ICmpInst::Predicate CanonicalPred = Pred, CanonicalFoundPred = FoundPred;
  10401. const SCEV *CanonicalLHS = LHS, *CanonicalRHS = RHS,
  10402. *CanonicalFoundLHS = FoundLHS, *CanonicalFoundRHS = FoundRHS;
  10403. if (ICmpInst::isGT(CanonicalPred) || ICmpInst::isGE(CanonicalPred)) {
  10404. CanonicalPred = ICmpInst::getSwappedPredicate(CanonicalPred);
  10405. CanonicalFoundPred = ICmpInst::getSwappedPredicate(CanonicalFoundPred);
  10406. std::swap(CanonicalLHS, CanonicalRHS);
  10407. std::swap(CanonicalFoundLHS, CanonicalFoundRHS);
  10408. }
  10409. assert((ICmpInst::isLT(CanonicalPred) || ICmpInst::isLE(CanonicalPred)) &&
  10410. "Must be!");
  10411. assert((ICmpInst::isLT(CanonicalFoundPred) ||
  10412. ICmpInst::isLE(CanonicalFoundPred)) &&
  10413. "Must be!");
  10414. if (ICmpInst::isSigned(CanonicalPred) && isKnownNonNegative(CanonicalRHS))
  10415. // Use implication:
  10416. // x <u y && y >=s 0 --> x <s y.
  10417. // If we can prove the left part, the right part is also proven.
  10418. return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
  10419. CanonicalRHS, CanonicalFoundLHS,
  10420. CanonicalFoundRHS);
  10421. if (ICmpInst::isUnsigned(CanonicalPred) && isKnownNegative(CanonicalRHS))
  10422. // Use implication:
  10423. // x <s y && y <s 0 --> x <u y.
  10424. // If we can prove the left part, the right part is also proven.
  10425. return isImpliedCondOperands(CanonicalFoundPred, CanonicalLHS,
  10426. CanonicalRHS, CanonicalFoundLHS,
  10427. CanonicalFoundRHS);
  10428. }
  10429. // Check if we can make progress by sharpening ranges.
  10430. if (FoundPred == ICmpInst::ICMP_NE &&
  10431. (isa<SCEVConstant>(FoundLHS) || isa<SCEVConstant>(FoundRHS))) {
  10432. const SCEVConstant *C = nullptr;
  10433. const SCEV *V = nullptr;
  10434. if (isa<SCEVConstant>(FoundLHS)) {
  10435. C = cast<SCEVConstant>(FoundLHS);
  10436. V = FoundRHS;
  10437. } else {
  10438. C = cast<SCEVConstant>(FoundRHS);
  10439. V = FoundLHS;
  10440. }
  10441. // The guarding predicate tells us that C != V. If the known range
  10442. // of V is [C, t), we can sharpen the range to [C + 1, t). The
  10443. // range we consider has to correspond to same signedness as the
  10444. // predicate we're interested in folding.
  10445. APInt Min = ICmpInst::isSigned(Pred) ?
  10446. getSignedRangeMin(V) : getUnsignedRangeMin(V);
  10447. if (Min == C->getAPInt()) {
  10448. // Given (V >= Min && V != Min) we conclude V >= (Min + 1).
  10449. // This is true even if (Min + 1) wraps around -- in case of
  10450. // wraparound, (Min + 1) < Min, so (V >= Min => V >= (Min + 1)).
  10451. APInt SharperMin = Min + 1;
  10452. switch (Pred) {
  10453. case ICmpInst::ICMP_SGE:
  10454. case ICmpInst::ICMP_UGE:
  10455. // We know V `Pred` SharperMin. If this implies LHS `Pred`
  10456. // RHS, we're done.
  10457. if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(SharperMin),
  10458. CtxI))
  10459. return true;
  10460. [[fallthrough]];
  10461. case ICmpInst::ICMP_SGT:
  10462. case ICmpInst::ICMP_UGT:
  10463. // We know from the range information that (V `Pred` Min ||
  10464. // V == Min). We know from the guarding condition that !(V
  10465. // == Min). This gives us
  10466. //
  10467. // V `Pred` Min || V == Min && !(V == Min)
  10468. // => V `Pred` Min
  10469. //
  10470. // If V `Pred` Min implies LHS `Pred` RHS, we're done.
  10471. if (isImpliedCondOperands(Pred, LHS, RHS, V, getConstant(Min), CtxI))
  10472. return true;
  10473. break;
  10474. // `LHS < RHS` and `LHS <= RHS` are handled in the same way as `RHS > LHS` and `RHS >= LHS` respectively.
  10475. case ICmpInst::ICMP_SLE:
  10476. case ICmpInst::ICMP_ULE:
  10477. if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
  10478. LHS, V, getConstant(SharperMin), CtxI))
  10479. return true;
  10480. [[fallthrough]];
  10481. case ICmpInst::ICMP_SLT:
  10482. case ICmpInst::ICMP_ULT:
  10483. if (isImpliedCondOperands(CmpInst::getSwappedPredicate(Pred), RHS,
  10484. LHS, V, getConstant(Min), CtxI))
  10485. return true;
  10486. break;
  10487. default:
  10488. // No change
  10489. break;
  10490. }
  10491. }
  10492. }
  10493. // Check whether the actual condition is beyond sufficient.
  10494. if (FoundPred == ICmpInst::ICMP_EQ)
  10495. if (ICmpInst::isTrueWhenEqual(Pred))
  10496. if (isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
  10497. return true;
  10498. if (Pred == ICmpInst::ICMP_NE)
  10499. if (!ICmpInst::isTrueWhenEqual(FoundPred))
  10500. if (isImpliedCondOperands(FoundPred, LHS, RHS, FoundLHS, FoundRHS, CtxI))
  10501. return true;
  10502. // Otherwise assume the worst.
  10503. return false;
  10504. }
  10505. bool ScalarEvolution::splitBinaryAdd(const SCEV *Expr,
  10506. const SCEV *&L, const SCEV *&R,
  10507. SCEV::NoWrapFlags &Flags) {
  10508. const auto *AE = dyn_cast<SCEVAddExpr>(Expr);
  10509. if (!AE || AE->getNumOperands() != 2)
  10510. return false;
  10511. L = AE->getOperand(0);
  10512. R = AE->getOperand(1);
  10513. Flags = AE->getNoWrapFlags();
  10514. return true;
  10515. }
  10516. std::optional<APInt>
  10517. ScalarEvolution::computeConstantDifference(const SCEV *More, const SCEV *Less) {
  10518. // We avoid subtracting expressions here because this function is usually
  10519. // fairly deep in the call stack (i.e. is called many times).
  10520. // X - X = 0.
  10521. if (More == Less)
  10522. return APInt(getTypeSizeInBits(More->getType()), 0);
  10523. if (isa<SCEVAddRecExpr>(Less) && isa<SCEVAddRecExpr>(More)) {
  10524. const auto *LAR = cast<SCEVAddRecExpr>(Less);
  10525. const auto *MAR = cast<SCEVAddRecExpr>(More);
  10526. if (LAR->getLoop() != MAR->getLoop())
  10527. return std::nullopt;
  10528. // We look at affine expressions only; not for correctness but to keep
  10529. // getStepRecurrence cheap.
  10530. if (!LAR->isAffine() || !MAR->isAffine())
  10531. return std::nullopt;
  10532. if (LAR->getStepRecurrence(*this) != MAR->getStepRecurrence(*this))
  10533. return std::nullopt;
  10534. Less = LAR->getStart();
  10535. More = MAR->getStart();
  10536. // fall through
  10537. }
  10538. if (isa<SCEVConstant>(Less) && isa<SCEVConstant>(More)) {
  10539. const auto &M = cast<SCEVConstant>(More)->getAPInt();
  10540. const auto &L = cast<SCEVConstant>(Less)->getAPInt();
  10541. return M - L;
  10542. }
  10543. SCEV::NoWrapFlags Flags;
  10544. const SCEV *LLess = nullptr, *RLess = nullptr;
  10545. const SCEV *LMore = nullptr, *RMore = nullptr;
  10546. const SCEVConstant *C1 = nullptr, *C2 = nullptr;
  10547. // Compare (X + C1) vs X.
  10548. if (splitBinaryAdd(Less, LLess, RLess, Flags))
  10549. if ((C1 = dyn_cast<SCEVConstant>(LLess)))
  10550. if (RLess == More)
  10551. return -(C1->getAPInt());
  10552. // Compare X vs (X + C2).
  10553. if (splitBinaryAdd(More, LMore, RMore, Flags))
  10554. if ((C2 = dyn_cast<SCEVConstant>(LMore)))
  10555. if (RMore == Less)
  10556. return C2->getAPInt();
  10557. // Compare (X + C1) vs (X + C2).
  10558. if (C1 && C2 && RLess == RMore)
  10559. return C2->getAPInt() - C1->getAPInt();
  10560. return std::nullopt;
  10561. }
  10562. bool ScalarEvolution::isImpliedCondOperandsViaAddRecStart(
  10563. ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
  10564. const SCEV *FoundLHS, const SCEV *FoundRHS, const Instruction *CtxI) {
  10565. // Try to recognize the following pattern:
  10566. //
  10567. // FoundRHS = ...
  10568. // ...
  10569. // loop:
  10570. // FoundLHS = {Start,+,W}
  10571. // context_bb: // Basic block from the same loop
  10572. // known(Pred, FoundLHS, FoundRHS)
  10573. //
  10574. // If some predicate is known in the context of a loop, it is also known on
  10575. // each iteration of this loop, including the first iteration. Therefore, in
  10576. // this case, `FoundLHS Pred FoundRHS` implies `Start Pred FoundRHS`. Try to
  10577. // prove the original pred using this fact.
  10578. if (!CtxI)
  10579. return false;
  10580. const BasicBlock *ContextBB = CtxI->getParent();
  10581. // Make sure AR varies in the context block.
  10582. if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundLHS)) {
  10583. const Loop *L = AR->getLoop();
  10584. // Make sure that context belongs to the loop and executes on 1st iteration
  10585. // (if it ever executes at all).
  10586. if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
  10587. return false;
  10588. if (!isAvailableAtLoopEntry(FoundRHS, AR->getLoop()))
  10589. return false;
  10590. return isImpliedCondOperands(Pred, LHS, RHS, AR->getStart(), FoundRHS);
  10591. }
  10592. if (auto *AR = dyn_cast<SCEVAddRecExpr>(FoundRHS)) {
  10593. const Loop *L = AR->getLoop();
  10594. // Make sure that context belongs to the loop and executes on 1st iteration
  10595. // (if it ever executes at all).
  10596. if (!L->contains(ContextBB) || !DT.dominates(ContextBB, L->getLoopLatch()))
  10597. return false;
  10598. if (!isAvailableAtLoopEntry(FoundLHS, AR->getLoop()))
  10599. return false;
  10600. return isImpliedCondOperands(Pred, LHS, RHS, FoundLHS, AR->getStart());
  10601. }
  10602. return false;
  10603. }
  10604. bool ScalarEvolution::isImpliedCondOperandsViaNoOverflow(
  10605. ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
  10606. const SCEV *FoundLHS, const SCEV *FoundRHS) {
  10607. if (Pred != CmpInst::ICMP_SLT && Pred != CmpInst::ICMP_ULT)
  10608. return false;
  10609. const auto *AddRecLHS = dyn_cast<SCEVAddRecExpr>(LHS);
  10610. if (!AddRecLHS)
  10611. return false;
  10612. const auto *AddRecFoundLHS = dyn_cast<SCEVAddRecExpr>(FoundLHS);
  10613. if (!AddRecFoundLHS)
  10614. return false;
  10615. // We'd like to let SCEV reason about control dependencies, so we constrain
  10616. // both the inequalities to be about add recurrences on the same loop. This
  10617. // way we can use isLoopEntryGuardedByCond later.
  10618. const Loop *L = AddRecFoundLHS->getLoop();
  10619. if (L != AddRecLHS->getLoop())
  10620. return false;
  10621. // FoundLHS u< FoundRHS u< -C => (FoundLHS + C) u< (FoundRHS + C) ... (1)
  10622. //
  10623. // FoundLHS s< FoundRHS s< INT_MIN - C => (FoundLHS + C) s< (FoundRHS + C)
  10624. // ... (2)
  10625. //
  10626. // Informal proof for (2), assuming (1) [*]:
  10627. //
  10628. // We'll also assume (A s< B) <=> ((A + INT_MIN) u< (B + INT_MIN)) ... (3)[**]
  10629. //
  10630. // Then
  10631. //
  10632. // FoundLHS s< FoundRHS s< INT_MIN - C
  10633. // <=> (FoundLHS + INT_MIN) u< (FoundRHS + INT_MIN) u< -C [ using (3) ]
  10634. // <=> (FoundLHS + INT_MIN + C) u< (FoundRHS + INT_MIN + C) [ using (1) ]
  10635. // <=> (FoundLHS + INT_MIN + C + INT_MIN) s<
  10636. // (FoundRHS + INT_MIN + C + INT_MIN) [ using (3) ]
  10637. // <=> FoundLHS + C s< FoundRHS + C
  10638. //
  10639. // [*]: (1) can be proved by ruling out overflow.
  10640. //
  10641. // [**]: This can be proved by analyzing all the four possibilities:
  10642. // (A s< 0, B s< 0), (A s< 0, B s>= 0), (A s>= 0, B s< 0) and
  10643. // (A s>= 0, B s>= 0).
  10644. //
  10645. // Note:
  10646. // Despite (2), "FoundRHS s< INT_MIN - C" does not mean that "FoundRHS + C"
  10647. // will not sign underflow. For instance, say FoundLHS = (i8 -128), FoundRHS
  10648. // = (i8 -127) and C = (i8 -100). Then INT_MIN - C = (i8 -28), and FoundRHS
  10649. // s< (INT_MIN - C). Lack of sign overflow / underflow in "FoundRHS + C" is
  10650. // neither necessary nor sufficient to prove "(FoundLHS + C) s< (FoundRHS +
  10651. // C)".
  10652. std::optional<APInt> LDiff = computeConstantDifference(LHS, FoundLHS);
  10653. std::optional<APInt> RDiff = computeConstantDifference(RHS, FoundRHS);
  10654. if (!LDiff || !RDiff || *LDiff != *RDiff)
  10655. return false;
  10656. if (LDiff->isMinValue())
  10657. return true;
  10658. APInt FoundRHSLimit;
  10659. if (Pred == CmpInst::ICMP_ULT) {
  10660. FoundRHSLimit = -(*RDiff);
  10661. } else {
  10662. assert(Pred == CmpInst::ICMP_SLT && "Checked above!");
  10663. FoundRHSLimit = APInt::getSignedMinValue(getTypeSizeInBits(RHS->getType())) - *RDiff;
  10664. }
  10665. // Try to prove (1) or (2), as needed.
  10666. return isAvailableAtLoopEntry(FoundRHS, L) &&
  10667. isLoopEntryGuardedByCond(L, Pred, FoundRHS,
  10668. getConstant(FoundRHSLimit));
  10669. }
  10670. bool ScalarEvolution::isImpliedViaMerge(ICmpInst::Predicate Pred,
  10671. const SCEV *LHS, const SCEV *RHS,
  10672. const SCEV *FoundLHS,
  10673. const SCEV *FoundRHS, unsigned Depth) {
  10674. const PHINode *LPhi = nullptr, *RPhi = nullptr;
  10675. auto ClearOnExit = make_scope_exit([&]() {
  10676. if (LPhi) {
  10677. bool Erased = PendingMerges.erase(LPhi);
  10678. assert(Erased && "Failed to erase LPhi!");
  10679. (void)Erased;
  10680. }
  10681. if (RPhi) {
  10682. bool Erased = PendingMerges.erase(RPhi);
  10683. assert(Erased && "Failed to erase RPhi!");
  10684. (void)Erased;
  10685. }
  10686. });
  10687. // Find respective Phis and check that they are not being pending.
  10688. if (const SCEVUnknown *LU = dyn_cast<SCEVUnknown>(LHS))
  10689. if (auto *Phi = dyn_cast<PHINode>(LU->getValue())) {
  10690. if (!PendingMerges.insert(Phi).second)
  10691. return false;
  10692. LPhi = Phi;
  10693. }
  10694. if (const SCEVUnknown *RU = dyn_cast<SCEVUnknown>(RHS))
  10695. if (auto *Phi = dyn_cast<PHINode>(RU->getValue())) {
  10696. // If we detect a loop of Phi nodes being processed by this method, for
  10697. // example:
  10698. //
  10699. // %a = phi i32 [ %some1, %preheader ], [ %b, %latch ]
  10700. // %b = phi i32 [ %some2, %preheader ], [ %a, %latch ]
  10701. //
  10702. // we don't want to deal with a case that complex, so return conservative
  10703. // answer false.
  10704. if (!PendingMerges.insert(Phi).second)
  10705. return false;
  10706. RPhi = Phi;
  10707. }
  10708. // If none of LHS, RHS is a Phi, nothing to do here.
  10709. if (!LPhi && !RPhi)
  10710. return false;
  10711. // If there is a SCEVUnknown Phi we are interested in, make it left.
  10712. if (!LPhi) {
  10713. std::swap(LHS, RHS);
  10714. std::swap(FoundLHS, FoundRHS);
  10715. std::swap(LPhi, RPhi);
  10716. Pred = ICmpInst::getSwappedPredicate(Pred);
  10717. }
  10718. assert(LPhi && "LPhi should definitely be a SCEVUnknown Phi!");
  10719. const BasicBlock *LBB = LPhi->getParent();
  10720. const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
  10721. auto ProvedEasily = [&](const SCEV *S1, const SCEV *S2) {
  10722. return isKnownViaNonRecursiveReasoning(Pred, S1, S2) ||
  10723. isImpliedCondOperandsViaRanges(Pred, S1, S2, FoundLHS, FoundRHS) ||
  10724. isImpliedViaOperations(Pred, S1, S2, FoundLHS, FoundRHS, Depth);
  10725. };
  10726. if (RPhi && RPhi->getParent() == LBB) {
  10727. // Case one: RHS is also a SCEVUnknown Phi from the same basic block.
  10728. // If we compare two Phis from the same block, and for each entry block
  10729. // the predicate is true for incoming values from this block, then the
  10730. // predicate is also true for the Phis.
  10731. for (const BasicBlock *IncBB : predecessors(LBB)) {
  10732. const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
  10733. const SCEV *R = getSCEV(RPhi->getIncomingValueForBlock(IncBB));
  10734. if (!ProvedEasily(L, R))
  10735. return false;
  10736. }
  10737. } else if (RAR && RAR->getLoop()->getHeader() == LBB) {
  10738. // Case two: RHS is also a Phi from the same basic block, and it is an
  10739. // AddRec. It means that there is a loop which has both AddRec and Unknown
  10740. // PHIs, for it we can compare incoming values of AddRec from above the loop
  10741. // and latch with their respective incoming values of LPhi.
  10742. // TODO: Generalize to handle loops with many inputs in a header.
  10743. if (LPhi->getNumIncomingValues() != 2) return false;
  10744. auto *RLoop = RAR->getLoop();
  10745. auto *Predecessor = RLoop->getLoopPredecessor();
  10746. assert(Predecessor && "Loop with AddRec with no predecessor?");
  10747. const SCEV *L1 = getSCEV(LPhi->getIncomingValueForBlock(Predecessor));
  10748. if (!ProvedEasily(L1, RAR->getStart()))
  10749. return false;
  10750. auto *Latch = RLoop->getLoopLatch();
  10751. assert(Latch && "Loop with AddRec with no latch?");
  10752. const SCEV *L2 = getSCEV(LPhi->getIncomingValueForBlock(Latch));
  10753. if (!ProvedEasily(L2, RAR->getPostIncExpr(*this)))
  10754. return false;
  10755. } else {
  10756. // In all other cases go over inputs of LHS and compare each of them to RHS,
  10757. // the predicate is true for (LHS, RHS) if it is true for all such pairs.
  10758. // At this point RHS is either a non-Phi, or it is a Phi from some block
  10759. // different from LBB.
  10760. for (const BasicBlock *IncBB : predecessors(LBB)) {
  10761. // Check that RHS is available in this block.
  10762. if (!dominates(RHS, IncBB))
  10763. return false;
  10764. const SCEV *L = getSCEV(LPhi->getIncomingValueForBlock(IncBB));
  10765. // Make sure L does not refer to a value from a potentially previous
  10766. // iteration of a loop.
  10767. if (!properlyDominates(L, LBB))
  10768. return false;
  10769. if (!ProvedEasily(L, RHS))
  10770. return false;
  10771. }
  10772. }
  10773. return true;
  10774. }
  10775. bool ScalarEvolution::isImpliedCondOperandsViaShift(ICmpInst::Predicate Pred,
  10776. const SCEV *LHS,
  10777. const SCEV *RHS,
  10778. const SCEV *FoundLHS,
  10779. const SCEV *FoundRHS) {
  10780. // We want to imply LHS < RHS from LHS < (RHS >> shiftvalue). First, make
  10781. // sure that we are dealing with same LHS.
  10782. if (RHS == FoundRHS) {
  10783. std::swap(LHS, RHS);
  10784. std::swap(FoundLHS, FoundRHS);
  10785. Pred = ICmpInst::getSwappedPredicate(Pred);
  10786. }
  10787. if (LHS != FoundLHS)
  10788. return false;
  10789. auto *SUFoundRHS = dyn_cast<SCEVUnknown>(FoundRHS);
  10790. if (!SUFoundRHS)
  10791. return false;
  10792. Value *Shiftee, *ShiftValue;
  10793. using namespace PatternMatch;
  10794. if (match(SUFoundRHS->getValue(),
  10795. m_LShr(m_Value(Shiftee), m_Value(ShiftValue)))) {
  10796. auto *ShifteeS = getSCEV(Shiftee);
  10797. // Prove one of the following:
  10798. // LHS <u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <u RHS
  10799. // LHS <=u (shiftee >> shiftvalue) && shiftee <=u RHS ---> LHS <=u RHS
  10800. // LHS <s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
  10801. // ---> LHS <s RHS
  10802. // LHS <=s (shiftee >> shiftvalue) && shiftee <=s RHS && shiftee >=s 0
  10803. // ---> LHS <=s RHS
  10804. if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_ULE)
  10805. return isKnownPredicate(ICmpInst::ICMP_ULE, ShifteeS, RHS);
  10806. if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SLE)
  10807. if (isKnownNonNegative(ShifteeS))
  10808. return isKnownPredicate(ICmpInst::ICMP_SLE, ShifteeS, RHS);
  10809. }
  10810. return false;
  10811. }
  10812. bool ScalarEvolution::isImpliedCondOperands(ICmpInst::Predicate Pred,
  10813. const SCEV *LHS, const SCEV *RHS,
  10814. const SCEV *FoundLHS,
  10815. const SCEV *FoundRHS,
  10816. const Instruction *CtxI) {
  10817. if (isImpliedCondOperandsViaRanges(Pred, LHS, RHS, FoundLHS, FoundRHS))
  10818. return true;
  10819. if (isImpliedCondOperandsViaNoOverflow(Pred, LHS, RHS, FoundLHS, FoundRHS))
  10820. return true;
  10821. if (isImpliedCondOperandsViaShift(Pred, LHS, RHS, FoundLHS, FoundRHS))
  10822. return true;
  10823. if (isImpliedCondOperandsViaAddRecStart(Pred, LHS, RHS, FoundLHS, FoundRHS,
  10824. CtxI))
  10825. return true;
  10826. return isImpliedCondOperandsHelper(Pred, LHS, RHS,
  10827. FoundLHS, FoundRHS);
  10828. }
  10829. /// Is MaybeMinMaxExpr an (U|S)(Min|Max) of Candidate and some other values?
  10830. template <typename MinMaxExprType>
  10831. static bool IsMinMaxConsistingOf(const SCEV *MaybeMinMaxExpr,
  10832. const SCEV *Candidate) {
  10833. const MinMaxExprType *MinMaxExpr = dyn_cast<MinMaxExprType>(MaybeMinMaxExpr);
  10834. if (!MinMaxExpr)
  10835. return false;
  10836. return is_contained(MinMaxExpr->operands(), Candidate);
  10837. }
  10838. static bool IsKnownPredicateViaAddRecStart(ScalarEvolution &SE,
  10839. ICmpInst::Predicate Pred,
  10840. const SCEV *LHS, const SCEV *RHS) {
  10841. // If both sides are affine addrecs for the same loop, with equal
  10842. // steps, and we know the recurrences don't wrap, then we only
  10843. // need to check the predicate on the starting values.
  10844. if (!ICmpInst::isRelational(Pred))
  10845. return false;
  10846. const SCEVAddRecExpr *LAR = dyn_cast<SCEVAddRecExpr>(LHS);
  10847. if (!LAR)
  10848. return false;
  10849. const SCEVAddRecExpr *RAR = dyn_cast<SCEVAddRecExpr>(RHS);
  10850. if (!RAR)
  10851. return false;
  10852. if (LAR->getLoop() != RAR->getLoop())
  10853. return false;
  10854. if (!LAR->isAffine() || !RAR->isAffine())
  10855. return false;
  10856. if (LAR->getStepRecurrence(SE) != RAR->getStepRecurrence(SE))
  10857. return false;
  10858. SCEV::NoWrapFlags NW = ICmpInst::isSigned(Pred) ?
  10859. SCEV::FlagNSW : SCEV::FlagNUW;
  10860. if (!LAR->getNoWrapFlags(NW) || !RAR->getNoWrapFlags(NW))
  10861. return false;
  10862. return SE.isKnownPredicate(Pred, LAR->getStart(), RAR->getStart());
  10863. }
  10864. /// Is LHS `Pred` RHS true on the virtue of LHS or RHS being a Min or Max
  10865. /// expression?
  10866. static bool IsKnownPredicateViaMinOrMax(ScalarEvolution &SE,
  10867. ICmpInst::Predicate Pred,
  10868. const SCEV *LHS, const SCEV *RHS) {
  10869. switch (Pred) {
  10870. default:
  10871. return false;
  10872. case ICmpInst::ICMP_SGE:
  10873. std::swap(LHS, RHS);
  10874. [[fallthrough]];
  10875. case ICmpInst::ICMP_SLE:
  10876. return
  10877. // min(A, ...) <= A
  10878. IsMinMaxConsistingOf<SCEVSMinExpr>(LHS, RHS) ||
  10879. // A <= max(A, ...)
  10880. IsMinMaxConsistingOf<SCEVSMaxExpr>(RHS, LHS);
  10881. case ICmpInst::ICMP_UGE:
  10882. std::swap(LHS, RHS);
  10883. [[fallthrough]];
  10884. case ICmpInst::ICMP_ULE:
  10885. return
  10886. // min(A, ...) <= A
  10887. // FIXME: what about umin_seq?
  10888. IsMinMaxConsistingOf<SCEVUMinExpr>(LHS, RHS) ||
  10889. // A <= max(A, ...)
  10890. IsMinMaxConsistingOf<SCEVUMaxExpr>(RHS, LHS);
  10891. }
  10892. llvm_unreachable("covered switch fell through?!");
  10893. }
  10894. bool ScalarEvolution::isImpliedViaOperations(ICmpInst::Predicate Pred,
  10895. const SCEV *LHS, const SCEV *RHS,
  10896. const SCEV *FoundLHS,
  10897. const SCEV *FoundRHS,
  10898. unsigned Depth) {
  10899. assert(getTypeSizeInBits(LHS->getType()) ==
  10900. getTypeSizeInBits(RHS->getType()) &&
  10901. "LHS and RHS have different sizes?");
  10902. assert(getTypeSizeInBits(FoundLHS->getType()) ==
  10903. getTypeSizeInBits(FoundRHS->getType()) &&
  10904. "FoundLHS and FoundRHS have different sizes?");
  10905. // We want to avoid hurting the compile time with analysis of too big trees.
  10906. if (Depth > MaxSCEVOperationsImplicationDepth)
  10907. return false;
  10908. // We only want to work with GT comparison so far.
  10909. if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SLT) {
  10910. Pred = CmpInst::getSwappedPredicate(Pred);
  10911. std::swap(LHS, RHS);
  10912. std::swap(FoundLHS, FoundRHS);
  10913. }
  10914. // For unsigned, try to reduce it to corresponding signed comparison.
  10915. if (Pred == ICmpInst::ICMP_UGT)
  10916. // We can replace unsigned predicate with its signed counterpart if all
  10917. // involved values are non-negative.
  10918. // TODO: We could have better support for unsigned.
  10919. if (isKnownNonNegative(FoundLHS) && isKnownNonNegative(FoundRHS)) {
  10920. // Knowing that both FoundLHS and FoundRHS are non-negative, and knowing
  10921. // FoundLHS >u FoundRHS, we also know that FoundLHS >s FoundRHS. Let us
  10922. // use this fact to prove that LHS and RHS are non-negative.
  10923. const SCEV *MinusOne = getMinusOne(LHS->getType());
  10924. if (isImpliedCondOperands(ICmpInst::ICMP_SGT, LHS, MinusOne, FoundLHS,
  10925. FoundRHS) &&
  10926. isImpliedCondOperands(ICmpInst::ICMP_SGT, RHS, MinusOne, FoundLHS,
  10927. FoundRHS))
  10928. Pred = ICmpInst::ICMP_SGT;
  10929. }
  10930. if (Pred != ICmpInst::ICMP_SGT)
  10931. return false;
  10932. auto GetOpFromSExt = [&](const SCEV *S) {
  10933. if (auto *Ext = dyn_cast<SCEVSignExtendExpr>(S))
  10934. return Ext->getOperand();
  10935. // TODO: If S is a SCEVConstant then you can cheaply "strip" the sext off
  10936. // the constant in some cases.
  10937. return S;
  10938. };
  10939. // Acquire values from extensions.
  10940. auto *OrigLHS = LHS;
  10941. auto *OrigFoundLHS = FoundLHS;
  10942. LHS = GetOpFromSExt(LHS);
  10943. FoundLHS = GetOpFromSExt(FoundLHS);
  10944. // Is the SGT predicate can be proved trivially or using the found context.
  10945. auto IsSGTViaContext = [&](const SCEV *S1, const SCEV *S2) {
  10946. return isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGT, S1, S2) ||
  10947. isImpliedViaOperations(ICmpInst::ICMP_SGT, S1, S2, OrigFoundLHS,
  10948. FoundRHS, Depth + 1);
  10949. };
  10950. if (auto *LHSAddExpr = dyn_cast<SCEVAddExpr>(LHS)) {
  10951. // We want to avoid creation of any new non-constant SCEV. Since we are
  10952. // going to compare the operands to RHS, we should be certain that we don't
  10953. // need any size extensions for this. So let's decline all cases when the
  10954. // sizes of types of LHS and RHS do not match.
  10955. // TODO: Maybe try to get RHS from sext to catch more cases?
  10956. if (getTypeSizeInBits(LHS->getType()) != getTypeSizeInBits(RHS->getType()))
  10957. return false;
  10958. // Should not overflow.
  10959. if (!LHSAddExpr->hasNoSignedWrap())
  10960. return false;
  10961. auto *LL = LHSAddExpr->getOperand(0);
  10962. auto *LR = LHSAddExpr->getOperand(1);
  10963. auto *MinusOne = getMinusOne(RHS->getType());
  10964. // Checks that S1 >= 0 && S2 > RHS, trivially or using the found context.
  10965. auto IsSumGreaterThanRHS = [&](const SCEV *S1, const SCEV *S2) {
  10966. return IsSGTViaContext(S1, MinusOne) && IsSGTViaContext(S2, RHS);
  10967. };
  10968. // Try to prove the following rule:
  10969. // (LHS = LL + LR) && (LL >= 0) && (LR > RHS) => (LHS > RHS).
  10970. // (LHS = LL + LR) && (LR >= 0) && (LL > RHS) => (LHS > RHS).
  10971. if (IsSumGreaterThanRHS(LL, LR) || IsSumGreaterThanRHS(LR, LL))
  10972. return true;
  10973. } else if (auto *LHSUnknownExpr = dyn_cast<SCEVUnknown>(LHS)) {
  10974. Value *LL, *LR;
  10975. // FIXME: Once we have SDiv implemented, we can get rid of this matching.
  10976. using namespace llvm::PatternMatch;
  10977. if (match(LHSUnknownExpr->getValue(), m_SDiv(m_Value(LL), m_Value(LR)))) {
  10978. // Rules for division.
  10979. // We are going to perform some comparisons with Denominator and its
  10980. // derivative expressions. In general case, creating a SCEV for it may
  10981. // lead to a complex analysis of the entire graph, and in particular it
  10982. // can request trip count recalculation for the same loop. This would
  10983. // cache as SCEVCouldNotCompute to avoid the infinite recursion. To avoid
  10984. // this, we only want to create SCEVs that are constants in this section.
  10985. // So we bail if Denominator is not a constant.
  10986. if (!isa<ConstantInt>(LR))
  10987. return false;
  10988. auto *Denominator = cast<SCEVConstant>(getSCEV(LR));
  10989. // We want to make sure that LHS = FoundLHS / Denominator. If it is so,
  10990. // then a SCEV for the numerator already exists and matches with FoundLHS.
  10991. auto *Numerator = getExistingSCEV(LL);
  10992. if (!Numerator || Numerator->getType() != FoundLHS->getType())
  10993. return false;
  10994. // Make sure that the numerator matches with FoundLHS and the denominator
  10995. // is positive.
  10996. if (!HasSameValue(Numerator, FoundLHS) || !isKnownPositive(Denominator))
  10997. return false;
  10998. auto *DTy = Denominator->getType();
  10999. auto *FRHSTy = FoundRHS->getType();
  11000. if (DTy->isPointerTy() != FRHSTy->isPointerTy())
  11001. // One of types is a pointer and another one is not. We cannot extend
  11002. // them properly to a wider type, so let us just reject this case.
  11003. // TODO: Usage of getEffectiveSCEVType for DTy, FRHSTy etc should help
  11004. // to avoid this check.
  11005. return false;
  11006. // Given that:
  11007. // FoundLHS > FoundRHS, LHS = FoundLHS / Denominator, Denominator > 0.
  11008. auto *WTy = getWiderType(DTy, FRHSTy);
  11009. auto *DenominatorExt = getNoopOrSignExtend(Denominator, WTy);
  11010. auto *FoundRHSExt = getNoopOrSignExtend(FoundRHS, WTy);
  11011. // Try to prove the following rule:
  11012. // (FoundRHS > Denominator - 2) && (RHS <= 0) => (LHS > RHS).
  11013. // For example, given that FoundLHS > 2. It means that FoundLHS is at
  11014. // least 3. If we divide it by Denominator < 4, we will have at least 1.
  11015. auto *DenomMinusTwo = getMinusSCEV(DenominatorExt, getConstant(WTy, 2));
  11016. if (isKnownNonPositive(RHS) &&
  11017. IsSGTViaContext(FoundRHSExt, DenomMinusTwo))
  11018. return true;
  11019. // Try to prove the following rule:
  11020. // (FoundRHS > -1 - Denominator) && (RHS < 0) => (LHS > RHS).
  11021. // For example, given that FoundLHS > -3. Then FoundLHS is at least -2.
  11022. // If we divide it by Denominator > 2, then:
  11023. // 1. If FoundLHS is negative, then the result is 0.
  11024. // 2. If FoundLHS is non-negative, then the result is non-negative.
  11025. // Anyways, the result is non-negative.
  11026. auto *MinusOne = getMinusOne(WTy);
  11027. auto *NegDenomMinusOne = getMinusSCEV(MinusOne, DenominatorExt);
  11028. if (isKnownNegative(RHS) &&
  11029. IsSGTViaContext(FoundRHSExt, NegDenomMinusOne))
  11030. return true;
  11031. }
  11032. }
  11033. // If our expression contained SCEVUnknown Phis, and we split it down and now
  11034. // need to prove something for them, try to prove the predicate for every
  11035. // possible incoming values of those Phis.
  11036. if (isImpliedViaMerge(Pred, OrigLHS, RHS, OrigFoundLHS, FoundRHS, Depth + 1))
  11037. return true;
  11038. return false;
  11039. }
  11040. static bool isKnownPredicateExtendIdiom(ICmpInst::Predicate Pred,
  11041. const SCEV *LHS, const SCEV *RHS) {
  11042. // zext x u<= sext x, sext x s<= zext x
  11043. switch (Pred) {
  11044. case ICmpInst::ICMP_SGE:
  11045. std::swap(LHS, RHS);
  11046. [[fallthrough]];
  11047. case ICmpInst::ICMP_SLE: {
  11048. // If operand >=s 0 then ZExt == SExt. If operand <s 0 then SExt <s ZExt.
  11049. const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(LHS);
  11050. const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(RHS);
  11051. if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
  11052. return true;
  11053. break;
  11054. }
  11055. case ICmpInst::ICMP_UGE:
  11056. std::swap(LHS, RHS);
  11057. [[fallthrough]];
  11058. case ICmpInst::ICMP_ULE: {
  11059. // If operand >=s 0 then ZExt == SExt. If operand <s 0 then ZExt <u SExt.
  11060. const SCEVZeroExtendExpr *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS);
  11061. const SCEVSignExtendExpr *SExt = dyn_cast<SCEVSignExtendExpr>(RHS);
  11062. if (SExt && ZExt && SExt->getOperand() == ZExt->getOperand())
  11063. return true;
  11064. break;
  11065. }
  11066. default:
  11067. break;
  11068. };
  11069. return false;
  11070. }
  11071. bool
  11072. ScalarEvolution::isKnownViaNonRecursiveReasoning(ICmpInst::Predicate Pred,
  11073. const SCEV *LHS, const SCEV *RHS) {
  11074. return isKnownPredicateExtendIdiom(Pred, LHS, RHS) ||
  11075. isKnownPredicateViaConstantRanges(Pred, LHS, RHS) ||
  11076. IsKnownPredicateViaMinOrMax(*this, Pred, LHS, RHS) ||
  11077. IsKnownPredicateViaAddRecStart(*this, Pred, LHS, RHS) ||
  11078. isKnownPredicateViaNoOverflow(Pred, LHS, RHS);
  11079. }
  11080. bool
  11081. ScalarEvolution::isImpliedCondOperandsHelper(ICmpInst::Predicate Pred,
  11082. const SCEV *LHS, const SCEV *RHS,
  11083. const SCEV *FoundLHS,
  11084. const SCEV *FoundRHS) {
  11085. switch (Pred) {
  11086. default: llvm_unreachable("Unexpected ICmpInst::Predicate value!");
  11087. case ICmpInst::ICMP_EQ:
  11088. case ICmpInst::ICMP_NE:
  11089. if (HasSameValue(LHS, FoundLHS) && HasSameValue(RHS, FoundRHS))
  11090. return true;
  11091. break;
  11092. case ICmpInst::ICMP_SLT:
  11093. case ICmpInst::ICMP_SLE:
  11094. if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, LHS, FoundLHS) &&
  11095. isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, RHS, FoundRHS))
  11096. return true;
  11097. break;
  11098. case ICmpInst::ICMP_SGT:
  11099. case ICmpInst::ICMP_SGE:
  11100. if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SGE, LHS, FoundLHS) &&
  11101. isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_SLE, RHS, FoundRHS))
  11102. return true;
  11103. break;
  11104. case ICmpInst::ICMP_ULT:
  11105. case ICmpInst::ICMP_ULE:
  11106. if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, LHS, FoundLHS) &&
  11107. isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, RHS, FoundRHS))
  11108. return true;
  11109. break;
  11110. case ICmpInst::ICMP_UGT:
  11111. case ICmpInst::ICMP_UGE:
  11112. if (isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_UGE, LHS, FoundLHS) &&
  11113. isKnownViaNonRecursiveReasoning(ICmpInst::ICMP_ULE, RHS, FoundRHS))
  11114. return true;
  11115. break;
  11116. }
  11117. // Maybe it can be proved via operations?
  11118. if (isImpliedViaOperations(Pred, LHS, RHS, FoundLHS, FoundRHS))
  11119. return true;
  11120. return false;
  11121. }
  11122. bool ScalarEvolution::isImpliedCondOperandsViaRanges(ICmpInst::Predicate Pred,
  11123. const SCEV *LHS,
  11124. const SCEV *RHS,
  11125. const SCEV *FoundLHS,
  11126. const SCEV *FoundRHS) {
  11127. if (!isa<SCEVConstant>(RHS) || !isa<SCEVConstant>(FoundRHS))
  11128. // The restriction on `FoundRHS` be lifted easily -- it exists only to
  11129. // reduce the compile time impact of this optimization.
  11130. return false;
  11131. std::optional<APInt> Addend = computeConstantDifference(LHS, FoundLHS);
  11132. if (!Addend)
  11133. return false;
  11134. const APInt &ConstFoundRHS = cast<SCEVConstant>(FoundRHS)->getAPInt();
  11135. // `FoundLHSRange` is the range we know `FoundLHS` to be in by virtue of the
  11136. // antecedent "`FoundLHS` `Pred` `FoundRHS`".
  11137. ConstantRange FoundLHSRange =
  11138. ConstantRange::makeExactICmpRegion(Pred, ConstFoundRHS);
  11139. // Since `LHS` is `FoundLHS` + `Addend`, we can compute a range for `LHS`:
  11140. ConstantRange LHSRange = FoundLHSRange.add(ConstantRange(*Addend));
  11141. // We can also compute the range of values for `LHS` that satisfy the
  11142. // consequent, "`LHS` `Pred` `RHS`":
  11143. const APInt &ConstRHS = cast<SCEVConstant>(RHS)->getAPInt();
  11144. // The antecedent implies the consequent if every value of `LHS` that
  11145. // satisfies the antecedent also satisfies the consequent.
  11146. return LHSRange.icmp(Pred, ConstRHS);
  11147. }
  11148. bool ScalarEvolution::canIVOverflowOnLT(const SCEV *RHS, const SCEV *Stride,
  11149. bool IsSigned) {
  11150. assert(isKnownPositive(Stride) && "Positive stride expected!");
  11151. unsigned BitWidth = getTypeSizeInBits(RHS->getType());
  11152. const SCEV *One = getOne(Stride->getType());
  11153. if (IsSigned) {
  11154. APInt MaxRHS = getSignedRangeMax(RHS);
  11155. APInt MaxValue = APInt::getSignedMaxValue(BitWidth);
  11156. APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
  11157. // SMaxRHS + SMaxStrideMinusOne > SMaxValue => overflow!
  11158. return (std::move(MaxValue) - MaxStrideMinusOne).slt(MaxRHS);
  11159. }
  11160. APInt MaxRHS = getUnsignedRangeMax(RHS);
  11161. APInt MaxValue = APInt::getMaxValue(BitWidth);
  11162. APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
  11163. // UMaxRHS + UMaxStrideMinusOne > UMaxValue => overflow!
  11164. return (std::move(MaxValue) - MaxStrideMinusOne).ult(MaxRHS);
  11165. }
  11166. bool ScalarEvolution::canIVOverflowOnGT(const SCEV *RHS, const SCEV *Stride,
  11167. bool IsSigned) {
  11168. unsigned BitWidth = getTypeSizeInBits(RHS->getType());
  11169. const SCEV *One = getOne(Stride->getType());
  11170. if (IsSigned) {
  11171. APInt MinRHS = getSignedRangeMin(RHS);
  11172. APInt MinValue = APInt::getSignedMinValue(BitWidth);
  11173. APInt MaxStrideMinusOne = getSignedRangeMax(getMinusSCEV(Stride, One));
  11174. // SMinRHS - SMaxStrideMinusOne < SMinValue => overflow!
  11175. return (std::move(MinValue) + MaxStrideMinusOne).sgt(MinRHS);
  11176. }
  11177. APInt MinRHS = getUnsignedRangeMin(RHS);
  11178. APInt MinValue = APInt::getMinValue(BitWidth);
  11179. APInt MaxStrideMinusOne = getUnsignedRangeMax(getMinusSCEV(Stride, One));
  11180. // UMinRHS - UMaxStrideMinusOne < UMinValue => overflow!
  11181. return (std::move(MinValue) + MaxStrideMinusOne).ugt(MinRHS);
  11182. }
  11183. const SCEV *ScalarEvolution::getUDivCeilSCEV(const SCEV *N, const SCEV *D) {
  11184. // umin(N, 1) + floor((N - umin(N, 1)) / D)
  11185. // This is equivalent to "1 + floor((N - 1) / D)" for N != 0. The umin
  11186. // expression fixes the case of N=0.
  11187. const SCEV *MinNOne = getUMinExpr(N, getOne(N->getType()));
  11188. const SCEV *NMinusOne = getMinusSCEV(N, MinNOne);
  11189. return getAddExpr(MinNOne, getUDivExpr(NMinusOne, D));
  11190. }
  11191. const SCEV *ScalarEvolution::computeMaxBECountForLT(const SCEV *Start,
  11192. const SCEV *Stride,
  11193. const SCEV *End,
  11194. unsigned BitWidth,
  11195. bool IsSigned) {
  11196. // The logic in this function assumes we can represent a positive stride.
  11197. // If we can't, the backedge-taken count must be zero.
  11198. if (IsSigned && BitWidth == 1)
  11199. return getZero(Stride->getType());
  11200. // This code below only been closely audited for negative strides in the
  11201. // unsigned comparison case, it may be correct for signed comparison, but
  11202. // that needs to be established.
  11203. if (IsSigned && isKnownNegative(Stride))
  11204. return getCouldNotCompute();
  11205. // Calculate the maximum backedge count based on the range of values
  11206. // permitted by Start, End, and Stride.
  11207. APInt MinStart =
  11208. IsSigned ? getSignedRangeMin(Start) : getUnsignedRangeMin(Start);
  11209. APInt MinStride =
  11210. IsSigned ? getSignedRangeMin(Stride) : getUnsignedRangeMin(Stride);
  11211. // We assume either the stride is positive, or the backedge-taken count
  11212. // is zero. So force StrideForMaxBECount to be at least one.
  11213. APInt One(BitWidth, 1);
  11214. APInt StrideForMaxBECount = IsSigned ? APIntOps::smax(One, MinStride)
  11215. : APIntOps::umax(One, MinStride);
  11216. APInt MaxValue = IsSigned ? APInt::getSignedMaxValue(BitWidth)
  11217. : APInt::getMaxValue(BitWidth);
  11218. APInt Limit = MaxValue - (StrideForMaxBECount - 1);
  11219. // Although End can be a MAX expression we estimate MaxEnd considering only
  11220. // the case End = RHS of the loop termination condition. This is safe because
  11221. // in the other case (End - Start) is zero, leading to a zero maximum backedge
  11222. // taken count.
  11223. APInt MaxEnd = IsSigned ? APIntOps::smin(getSignedRangeMax(End), Limit)
  11224. : APIntOps::umin(getUnsignedRangeMax(End), Limit);
  11225. // MaxBECount = ceil((max(MaxEnd, MinStart) - MinStart) / Stride)
  11226. MaxEnd = IsSigned ? APIntOps::smax(MaxEnd, MinStart)
  11227. : APIntOps::umax(MaxEnd, MinStart);
  11228. return getUDivCeilSCEV(getConstant(MaxEnd - MinStart) /* Delta */,
  11229. getConstant(StrideForMaxBECount) /* Step */);
  11230. }
  11231. ScalarEvolution::ExitLimit
  11232. ScalarEvolution::howManyLessThans(const SCEV *LHS, const SCEV *RHS,
  11233. const Loop *L, bool IsSigned,
  11234. bool ControlsExit, bool AllowPredicates) {
  11235. SmallPtrSet<const SCEVPredicate *, 4> Predicates;
  11236. const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
  11237. bool PredicatedIV = false;
  11238. auto canAssumeNoSelfWrap = [&](const SCEVAddRecExpr *AR) {
  11239. // Can we prove this loop *must* be UB if overflow of IV occurs?
  11240. // Reasoning goes as follows:
  11241. // * Suppose the IV did self wrap.
  11242. // * If Stride evenly divides the iteration space, then once wrap
  11243. // occurs, the loop must revisit the same values.
  11244. // * We know that RHS is invariant, and that none of those values
  11245. // caused this exit to be taken previously. Thus, this exit is
  11246. // dynamically dead.
  11247. // * If this is the sole exit, then a dead exit implies the loop
  11248. // must be infinite if there are no abnormal exits.
  11249. // * If the loop were infinite, then it must either not be mustprogress
  11250. // or have side effects. Otherwise, it must be UB.
  11251. // * It can't (by assumption), be UB so we have contradicted our
  11252. // premise and can conclude the IV did not in fact self-wrap.
  11253. if (!isLoopInvariant(RHS, L))
  11254. return false;
  11255. auto *StrideC = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*this));
  11256. if (!StrideC || !StrideC->getAPInt().isPowerOf2())
  11257. return false;
  11258. if (!ControlsExit || !loopHasNoAbnormalExits(L))
  11259. return false;
  11260. return loopIsFiniteByAssumption(L);
  11261. };
  11262. if (!IV) {
  11263. if (auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(LHS)) {
  11264. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(ZExt->getOperand());
  11265. if (AR && AR->getLoop() == L && AR->isAffine()) {
  11266. auto canProveNUW = [&]() {
  11267. if (!isLoopInvariant(RHS, L))
  11268. return false;
  11269. if (!isKnownNonZero(AR->getStepRecurrence(*this)))
  11270. // We need the sequence defined by AR to strictly increase in the
  11271. // unsigned integer domain for the logic below to hold.
  11272. return false;
  11273. const unsigned InnerBitWidth = getTypeSizeInBits(AR->getType());
  11274. const unsigned OuterBitWidth = getTypeSizeInBits(RHS->getType());
  11275. // If RHS <=u Limit, then there must exist a value V in the sequence
  11276. // defined by AR (e.g. {Start,+,Step}) such that V >u RHS, and
  11277. // V <=u UINT_MAX. Thus, we must exit the loop before unsigned
  11278. // overflow occurs. This limit also implies that a signed comparison
  11279. // (in the wide bitwidth) is equivalent to an unsigned comparison as
  11280. // the high bits on both sides must be zero.
  11281. APInt StrideMax = getUnsignedRangeMax(AR->getStepRecurrence(*this));
  11282. APInt Limit = APInt::getMaxValue(InnerBitWidth) - (StrideMax - 1);
  11283. Limit = Limit.zext(OuterBitWidth);
  11284. return getUnsignedRangeMax(applyLoopGuards(RHS, L)).ule(Limit);
  11285. };
  11286. auto Flags = AR->getNoWrapFlags();
  11287. if (!hasFlags(Flags, SCEV::FlagNUW) && canProveNUW())
  11288. Flags = setFlags(Flags, SCEV::FlagNUW);
  11289. setNoWrapFlags(const_cast<SCEVAddRecExpr *>(AR), Flags);
  11290. if (AR->hasNoUnsignedWrap()) {
  11291. // Emulate what getZeroExtendExpr would have done during construction
  11292. // if we'd been able to infer the fact just above at that time.
  11293. const SCEV *Step = AR->getStepRecurrence(*this);
  11294. Type *Ty = ZExt->getType();
  11295. auto *S = getAddRecExpr(
  11296. getExtendAddRecStart<SCEVZeroExtendExpr>(AR, Ty, this, 0),
  11297. getZeroExtendExpr(Step, Ty, 0), L, AR->getNoWrapFlags());
  11298. IV = dyn_cast<SCEVAddRecExpr>(S);
  11299. }
  11300. }
  11301. }
  11302. }
  11303. if (!IV && AllowPredicates) {
  11304. // Try to make this an AddRec using runtime tests, in the first X
  11305. // iterations of this loop, where X is the SCEV expression found by the
  11306. // algorithm below.
  11307. IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
  11308. PredicatedIV = true;
  11309. }
  11310. // Avoid weird loops
  11311. if (!IV || IV->getLoop() != L || !IV->isAffine())
  11312. return getCouldNotCompute();
  11313. // A precondition of this method is that the condition being analyzed
  11314. // reaches an exiting branch which dominates the latch. Given that, we can
  11315. // assume that an increment which violates the nowrap specification and
  11316. // produces poison must cause undefined behavior when the resulting poison
  11317. // value is branched upon and thus we can conclude that the backedge is
  11318. // taken no more often than would be required to produce that poison value.
  11319. // Note that a well defined loop can exit on the iteration which violates
  11320. // the nowrap specification if there is another exit (either explicit or
  11321. // implicit/exceptional) which causes the loop to execute before the
  11322. // exiting instruction we're analyzing would trigger UB.
  11323. auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
  11324. bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
  11325. ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
  11326. const SCEV *Stride = IV->getStepRecurrence(*this);
  11327. bool PositiveStride = isKnownPositive(Stride);
  11328. // Avoid negative or zero stride values.
  11329. if (!PositiveStride) {
  11330. // We can compute the correct backedge taken count for loops with unknown
  11331. // strides if we can prove that the loop is not an infinite loop with side
  11332. // effects. Here's the loop structure we are trying to handle -
  11333. //
  11334. // i = start
  11335. // do {
  11336. // A[i] = i;
  11337. // i += s;
  11338. // } while (i < end);
  11339. //
  11340. // The backedge taken count for such loops is evaluated as -
  11341. // (max(end, start + stride) - start - 1) /u stride
  11342. //
  11343. // The additional preconditions that we need to check to prove correctness
  11344. // of the above formula is as follows -
  11345. //
  11346. // a) IV is either nuw or nsw depending upon signedness (indicated by the
  11347. // NoWrap flag).
  11348. // b) the loop is guaranteed to be finite (e.g. is mustprogress and has
  11349. // no side effects within the loop)
  11350. // c) loop has a single static exit (with no abnormal exits)
  11351. //
  11352. // Precondition a) implies that if the stride is negative, this is a single
  11353. // trip loop. The backedge taken count formula reduces to zero in this case.
  11354. //
  11355. // Precondition b) and c) combine to imply that if rhs is invariant in L,
  11356. // then a zero stride means the backedge can't be taken without executing
  11357. // undefined behavior.
  11358. //
  11359. // The positive stride case is the same as isKnownPositive(Stride) returning
  11360. // true (original behavior of the function).
  11361. //
  11362. if (PredicatedIV || !NoWrap || !loopIsFiniteByAssumption(L) ||
  11363. !loopHasNoAbnormalExits(L))
  11364. return getCouldNotCompute();
  11365. if (!isKnownNonZero(Stride)) {
  11366. // If we have a step of zero, and RHS isn't invariant in L, we don't know
  11367. // if it might eventually be greater than start and if so, on which
  11368. // iteration. We can't even produce a useful upper bound.
  11369. if (!isLoopInvariant(RHS, L))
  11370. return getCouldNotCompute();
  11371. // We allow a potentially zero stride, but we need to divide by stride
  11372. // below. Since the loop can't be infinite and this check must control
  11373. // the sole exit, we can infer the exit must be taken on the first
  11374. // iteration (e.g. backedge count = 0) if the stride is zero. Given that,
  11375. // we know the numerator in the divides below must be zero, so we can
  11376. // pick an arbitrary non-zero value for the denominator (e.g. stride)
  11377. // and produce the right result.
  11378. // FIXME: Handle the case where Stride is poison?
  11379. auto wouldZeroStrideBeUB = [&]() {
  11380. // Proof by contradiction. Suppose the stride were zero. If we can
  11381. // prove that the backedge *is* taken on the first iteration, then since
  11382. // we know this condition controls the sole exit, we must have an
  11383. // infinite loop. We can't have a (well defined) infinite loop per
  11384. // check just above.
  11385. // Note: The (Start - Stride) term is used to get the start' term from
  11386. // (start' + stride,+,stride). Remember that we only care about the
  11387. // result of this expression when stride == 0 at runtime.
  11388. auto *StartIfZero = getMinusSCEV(IV->getStart(), Stride);
  11389. return isLoopEntryGuardedByCond(L, Cond, StartIfZero, RHS);
  11390. };
  11391. if (!wouldZeroStrideBeUB()) {
  11392. Stride = getUMaxExpr(Stride, getOne(Stride->getType()));
  11393. }
  11394. }
  11395. } else if (!Stride->isOne() && !NoWrap) {
  11396. auto isUBOnWrap = [&]() {
  11397. // From no-self-wrap, we need to then prove no-(un)signed-wrap. This
  11398. // follows trivially from the fact that every (un)signed-wrapped, but
  11399. // not self-wrapped value must be LT than the last value before
  11400. // (un)signed wrap. Since we know that last value didn't exit, nor
  11401. // will any smaller one.
  11402. return canAssumeNoSelfWrap(IV);
  11403. };
  11404. // Avoid proven overflow cases: this will ensure that the backedge taken
  11405. // count will not generate any unsigned overflow. Relaxed no-overflow
  11406. // conditions exploit NoWrapFlags, allowing to optimize in presence of
  11407. // undefined behaviors like the case of C language.
  11408. if (canIVOverflowOnLT(RHS, Stride, IsSigned) && !isUBOnWrap())
  11409. return getCouldNotCompute();
  11410. }
  11411. // On all paths just preceeding, we established the following invariant:
  11412. // IV can be assumed not to overflow up to and including the exiting
  11413. // iteration. We proved this in one of two ways:
  11414. // 1) We can show overflow doesn't occur before the exiting iteration
  11415. // 1a) canIVOverflowOnLT, and b) step of one
  11416. // 2) We can show that if overflow occurs, the loop must execute UB
  11417. // before any possible exit.
  11418. // Note that we have not yet proved RHS invariant (in general).
  11419. const SCEV *Start = IV->getStart();
  11420. // Preserve pointer-typed Start/RHS to pass to isLoopEntryGuardedByCond.
  11421. // If we convert to integers, isLoopEntryGuardedByCond will miss some cases.
  11422. // Use integer-typed versions for actual computation; we can't subtract
  11423. // pointers in general.
  11424. const SCEV *OrigStart = Start;
  11425. const SCEV *OrigRHS = RHS;
  11426. if (Start->getType()->isPointerTy()) {
  11427. Start = getLosslessPtrToIntExpr(Start);
  11428. if (isa<SCEVCouldNotCompute>(Start))
  11429. return Start;
  11430. }
  11431. if (RHS->getType()->isPointerTy()) {
  11432. RHS = getLosslessPtrToIntExpr(RHS);
  11433. if (isa<SCEVCouldNotCompute>(RHS))
  11434. return RHS;
  11435. }
  11436. // When the RHS is not invariant, we do not know the end bound of the loop and
  11437. // cannot calculate the ExactBECount needed by ExitLimit. However, we can
  11438. // calculate the MaxBECount, given the start, stride and max value for the end
  11439. // bound of the loop (RHS), and the fact that IV does not overflow (which is
  11440. // checked above).
  11441. if (!isLoopInvariant(RHS, L)) {
  11442. const SCEV *MaxBECount = computeMaxBECountForLT(
  11443. Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
  11444. return ExitLimit(getCouldNotCompute() /* ExactNotTaken */, MaxBECount,
  11445. MaxBECount, false /*MaxOrZero*/, Predicates);
  11446. }
  11447. // We use the expression (max(End,Start)-Start)/Stride to describe the
  11448. // backedge count, as if the backedge is taken at least once max(End,Start)
  11449. // is End and so the result is as above, and if not max(End,Start) is Start
  11450. // so we get a backedge count of zero.
  11451. const SCEV *BECount = nullptr;
  11452. auto *OrigStartMinusStride = getMinusSCEV(OrigStart, Stride);
  11453. assert(isAvailableAtLoopEntry(OrigStartMinusStride, L) && "Must be!");
  11454. assert(isAvailableAtLoopEntry(OrigStart, L) && "Must be!");
  11455. assert(isAvailableAtLoopEntry(OrigRHS, L) && "Must be!");
  11456. // Can we prove (max(RHS,Start) > Start - Stride?
  11457. if (isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigStart) &&
  11458. isLoopEntryGuardedByCond(L, Cond, OrigStartMinusStride, OrigRHS)) {
  11459. // In this case, we can use a refined formula for computing backedge taken
  11460. // count. The general formula remains:
  11461. // "End-Start /uceiling Stride" where "End = max(RHS,Start)"
  11462. // We want to use the alternate formula:
  11463. // "((End - 1) - (Start - Stride)) /u Stride"
  11464. // Let's do a quick case analysis to show these are equivalent under
  11465. // our precondition that max(RHS,Start) > Start - Stride.
  11466. // * For RHS <= Start, the backedge-taken count must be zero.
  11467. // "((End - 1) - (Start - Stride)) /u Stride" reduces to
  11468. // "((Start - 1) - (Start - Stride)) /u Stride" which simplies to
  11469. // "Stride - 1 /u Stride" which is indeed zero for all non-zero values
  11470. // of Stride. For 0 stride, we've use umin(1,Stride) above, reducing
  11471. // this to the stride of 1 case.
  11472. // * For RHS >= Start, the backedge count must be "RHS-Start /uceil Stride".
  11473. // "((End - 1) - (Start - Stride)) /u Stride" reduces to
  11474. // "((RHS - 1) - (Start - Stride)) /u Stride" reassociates to
  11475. // "((RHS - (Start - Stride) - 1) /u Stride".
  11476. // Our preconditions trivially imply no overflow in that form.
  11477. const SCEV *MinusOne = getMinusOne(Stride->getType());
  11478. const SCEV *Numerator =
  11479. getMinusSCEV(getAddExpr(RHS, MinusOne), getMinusSCEV(Start, Stride));
  11480. BECount = getUDivExpr(Numerator, Stride);
  11481. }
  11482. const SCEV *BECountIfBackedgeTaken = nullptr;
  11483. if (!BECount) {
  11484. auto canProveRHSGreaterThanEqualStart = [&]() {
  11485. auto CondGE = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
  11486. if (isLoopEntryGuardedByCond(L, CondGE, OrigRHS, OrigStart))
  11487. return true;
  11488. // (RHS > Start - 1) implies RHS >= Start.
  11489. // * "RHS >= Start" is trivially equivalent to "RHS > Start - 1" if
  11490. // "Start - 1" doesn't overflow.
  11491. // * For signed comparison, if Start - 1 does overflow, it's equal
  11492. // to INT_MAX, and "RHS >s INT_MAX" is trivially false.
  11493. // * For unsigned comparison, if Start - 1 does overflow, it's equal
  11494. // to UINT_MAX, and "RHS >u UINT_MAX" is trivially false.
  11495. //
  11496. // FIXME: Should isLoopEntryGuardedByCond do this for us?
  11497. auto CondGT = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  11498. auto *StartMinusOne = getAddExpr(OrigStart,
  11499. getMinusOne(OrigStart->getType()));
  11500. return isLoopEntryGuardedByCond(L, CondGT, OrigRHS, StartMinusOne);
  11501. };
  11502. // If we know that RHS >= Start in the context of loop, then we know that
  11503. // max(RHS, Start) = RHS at this point.
  11504. const SCEV *End;
  11505. if (canProveRHSGreaterThanEqualStart()) {
  11506. End = RHS;
  11507. } else {
  11508. // If RHS < Start, the backedge will be taken zero times. So in
  11509. // general, we can write the backedge-taken count as:
  11510. //
  11511. // RHS >= Start ? ceil(RHS - Start) / Stride : 0
  11512. //
  11513. // We convert it to the following to make it more convenient for SCEV:
  11514. //
  11515. // ceil(max(RHS, Start) - Start) / Stride
  11516. End = IsSigned ? getSMaxExpr(RHS, Start) : getUMaxExpr(RHS, Start);
  11517. // See what would happen if we assume the backedge is taken. This is
  11518. // used to compute MaxBECount.
  11519. BECountIfBackedgeTaken = getUDivCeilSCEV(getMinusSCEV(RHS, Start), Stride);
  11520. }
  11521. // At this point, we know:
  11522. //
  11523. // 1. If IsSigned, Start <=s End; otherwise, Start <=u End
  11524. // 2. The index variable doesn't overflow.
  11525. //
  11526. // Therefore, we know N exists such that
  11527. // (Start + Stride * N) >= End, and computing "(Start + Stride * N)"
  11528. // doesn't overflow.
  11529. //
  11530. // Using this information, try to prove whether the addition in
  11531. // "(Start - End) + (Stride - 1)" has unsigned overflow.
  11532. const SCEV *One = getOne(Stride->getType());
  11533. bool MayAddOverflow = [&] {
  11534. if (auto *StrideC = dyn_cast<SCEVConstant>(Stride)) {
  11535. if (StrideC->getAPInt().isPowerOf2()) {
  11536. // Suppose Stride is a power of two, and Start/End are unsigned
  11537. // integers. Let UMAX be the largest representable unsigned
  11538. // integer.
  11539. //
  11540. // By the preconditions of this function, we know
  11541. // "(Start + Stride * N) >= End", and this doesn't overflow.
  11542. // As a formula:
  11543. //
  11544. // End <= (Start + Stride * N) <= UMAX
  11545. //
  11546. // Subtracting Start from all the terms:
  11547. //
  11548. // End - Start <= Stride * N <= UMAX - Start
  11549. //
  11550. // Since Start is unsigned, UMAX - Start <= UMAX. Therefore:
  11551. //
  11552. // End - Start <= Stride * N <= UMAX
  11553. //
  11554. // Stride * N is a multiple of Stride. Therefore,
  11555. //
  11556. // End - Start <= Stride * N <= UMAX - (UMAX mod Stride)
  11557. //
  11558. // Since Stride is a power of two, UMAX + 1 is divisible by Stride.
  11559. // Therefore, UMAX mod Stride == Stride - 1. So we can write:
  11560. //
  11561. // End - Start <= Stride * N <= UMAX - Stride - 1
  11562. //
  11563. // Dropping the middle term:
  11564. //
  11565. // End - Start <= UMAX - Stride - 1
  11566. //
  11567. // Adding Stride - 1 to both sides:
  11568. //
  11569. // (End - Start) + (Stride - 1) <= UMAX
  11570. //
  11571. // In other words, the addition doesn't have unsigned overflow.
  11572. //
  11573. // A similar proof works if we treat Start/End as signed values.
  11574. // Just rewrite steps before "End - Start <= Stride * N <= UMAX" to
  11575. // use signed max instead of unsigned max. Note that we're trying
  11576. // to prove a lack of unsigned overflow in either case.
  11577. return false;
  11578. }
  11579. }
  11580. if (Start == Stride || Start == getMinusSCEV(Stride, One)) {
  11581. // If Start is equal to Stride, (End - Start) + (Stride - 1) == End - 1.
  11582. // If !IsSigned, 0 <u Stride == Start <=u End; so 0 <u End - 1 <u End.
  11583. // If IsSigned, 0 <s Stride == Start <=s End; so 0 <s End - 1 <s End.
  11584. //
  11585. // If Start is equal to Stride - 1, (End - Start) + Stride - 1 == End.
  11586. return false;
  11587. }
  11588. return true;
  11589. }();
  11590. const SCEV *Delta = getMinusSCEV(End, Start);
  11591. if (!MayAddOverflow) {
  11592. // floor((D + (S - 1)) / S)
  11593. // We prefer this formulation if it's legal because it's fewer operations.
  11594. BECount =
  11595. getUDivExpr(getAddExpr(Delta, getMinusSCEV(Stride, One)), Stride);
  11596. } else {
  11597. BECount = getUDivCeilSCEV(Delta, Stride);
  11598. }
  11599. }
  11600. const SCEV *ConstantMaxBECount;
  11601. bool MaxOrZero = false;
  11602. if (isa<SCEVConstant>(BECount)) {
  11603. ConstantMaxBECount = BECount;
  11604. } else if (BECountIfBackedgeTaken &&
  11605. isa<SCEVConstant>(BECountIfBackedgeTaken)) {
  11606. // If we know exactly how many times the backedge will be taken if it's
  11607. // taken at least once, then the backedge count will either be that or
  11608. // zero.
  11609. ConstantMaxBECount = BECountIfBackedgeTaken;
  11610. MaxOrZero = true;
  11611. } else {
  11612. ConstantMaxBECount = computeMaxBECountForLT(
  11613. Start, Stride, RHS, getTypeSizeInBits(LHS->getType()), IsSigned);
  11614. }
  11615. if (isa<SCEVCouldNotCompute>(ConstantMaxBECount) &&
  11616. !isa<SCEVCouldNotCompute>(BECount))
  11617. ConstantMaxBECount = getConstant(getUnsignedRangeMax(BECount));
  11618. const SCEV *SymbolicMaxBECount =
  11619. isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
  11620. return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, MaxOrZero,
  11621. Predicates);
  11622. }
  11623. ScalarEvolution::ExitLimit
  11624. ScalarEvolution::howManyGreaterThans(const SCEV *LHS, const SCEV *RHS,
  11625. const Loop *L, bool IsSigned,
  11626. bool ControlsExit, bool AllowPredicates) {
  11627. SmallPtrSet<const SCEVPredicate *, 4> Predicates;
  11628. // We handle only IV > Invariant
  11629. if (!isLoopInvariant(RHS, L))
  11630. return getCouldNotCompute();
  11631. const SCEVAddRecExpr *IV = dyn_cast<SCEVAddRecExpr>(LHS);
  11632. if (!IV && AllowPredicates)
  11633. // Try to make this an AddRec using runtime tests, in the first X
  11634. // iterations of this loop, where X is the SCEV expression found by the
  11635. // algorithm below.
  11636. IV = convertSCEVToAddRecWithPredicates(LHS, L, Predicates);
  11637. // Avoid weird loops
  11638. if (!IV || IV->getLoop() != L || !IV->isAffine())
  11639. return getCouldNotCompute();
  11640. auto WrapType = IsSigned ? SCEV::FlagNSW : SCEV::FlagNUW;
  11641. bool NoWrap = ControlsExit && IV->getNoWrapFlags(WrapType);
  11642. ICmpInst::Predicate Cond = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
  11643. const SCEV *Stride = getNegativeSCEV(IV->getStepRecurrence(*this));
  11644. // Avoid negative or zero stride values
  11645. if (!isKnownPositive(Stride))
  11646. return getCouldNotCompute();
  11647. // Avoid proven overflow cases: this will ensure that the backedge taken count
  11648. // will not generate any unsigned overflow. Relaxed no-overflow conditions
  11649. // exploit NoWrapFlags, allowing to optimize in presence of undefined
  11650. // behaviors like the case of C language.
  11651. if (!Stride->isOne() && !NoWrap)
  11652. if (canIVOverflowOnGT(RHS, Stride, IsSigned))
  11653. return getCouldNotCompute();
  11654. const SCEV *Start = IV->getStart();
  11655. const SCEV *End = RHS;
  11656. if (!isLoopEntryGuardedByCond(L, Cond, getAddExpr(Start, Stride), RHS)) {
  11657. // If we know that Start >= RHS in the context of loop, then we know that
  11658. // min(RHS, Start) = RHS at this point.
  11659. if (isLoopEntryGuardedByCond(
  11660. L, IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE, Start, RHS))
  11661. End = RHS;
  11662. else
  11663. End = IsSigned ? getSMinExpr(RHS, Start) : getUMinExpr(RHS, Start);
  11664. }
  11665. if (Start->getType()->isPointerTy()) {
  11666. Start = getLosslessPtrToIntExpr(Start);
  11667. if (isa<SCEVCouldNotCompute>(Start))
  11668. return Start;
  11669. }
  11670. if (End->getType()->isPointerTy()) {
  11671. End = getLosslessPtrToIntExpr(End);
  11672. if (isa<SCEVCouldNotCompute>(End))
  11673. return End;
  11674. }
  11675. // Compute ((Start - End) + (Stride - 1)) / Stride.
  11676. // FIXME: This can overflow. Holding off on fixing this for now;
  11677. // howManyGreaterThans will hopefully be gone soon.
  11678. const SCEV *One = getOne(Stride->getType());
  11679. const SCEV *BECount = getUDivExpr(
  11680. getAddExpr(getMinusSCEV(Start, End), getMinusSCEV(Stride, One)), Stride);
  11681. APInt MaxStart = IsSigned ? getSignedRangeMax(Start)
  11682. : getUnsignedRangeMax(Start);
  11683. APInt MinStride = IsSigned ? getSignedRangeMin(Stride)
  11684. : getUnsignedRangeMin(Stride);
  11685. unsigned BitWidth = getTypeSizeInBits(LHS->getType());
  11686. APInt Limit = IsSigned ? APInt::getSignedMinValue(BitWidth) + (MinStride - 1)
  11687. : APInt::getMinValue(BitWidth) + (MinStride - 1);
  11688. // Although End can be a MIN expression we estimate MinEnd considering only
  11689. // the case End = RHS. This is safe because in the other case (Start - End)
  11690. // is zero, leading to a zero maximum backedge taken count.
  11691. APInt MinEnd =
  11692. IsSigned ? APIntOps::smax(getSignedRangeMin(RHS), Limit)
  11693. : APIntOps::umax(getUnsignedRangeMin(RHS), Limit);
  11694. const SCEV *ConstantMaxBECount =
  11695. isa<SCEVConstant>(BECount)
  11696. ? BECount
  11697. : getUDivCeilSCEV(getConstant(MaxStart - MinEnd),
  11698. getConstant(MinStride));
  11699. if (isa<SCEVCouldNotCompute>(ConstantMaxBECount))
  11700. ConstantMaxBECount = BECount;
  11701. const SCEV *SymbolicMaxBECount =
  11702. isa<SCEVCouldNotCompute>(BECount) ? ConstantMaxBECount : BECount;
  11703. return ExitLimit(BECount, ConstantMaxBECount, SymbolicMaxBECount, false,
  11704. Predicates);
  11705. }
  11706. const SCEV *SCEVAddRecExpr::getNumIterationsInRange(const ConstantRange &Range,
  11707. ScalarEvolution &SE) const {
  11708. if (Range.isFullSet()) // Infinite loop.
  11709. return SE.getCouldNotCompute();
  11710. // If the start is a non-zero constant, shift the range to simplify things.
  11711. if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
  11712. if (!SC->getValue()->isZero()) {
  11713. SmallVector<const SCEV *, 4> Operands(operands());
  11714. Operands[0] = SE.getZero(SC->getType());
  11715. const SCEV *Shifted = SE.getAddRecExpr(Operands, getLoop(),
  11716. getNoWrapFlags(FlagNW));
  11717. if (const auto *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
  11718. return ShiftedAddRec->getNumIterationsInRange(
  11719. Range.subtract(SC->getAPInt()), SE);
  11720. // This is strange and shouldn't happen.
  11721. return SE.getCouldNotCompute();
  11722. }
  11723. // The only time we can solve this is when we have all constant indices.
  11724. // Otherwise, we cannot determine the overflow conditions.
  11725. if (any_of(operands(), [](const SCEV *Op) { return !isa<SCEVConstant>(Op); }))
  11726. return SE.getCouldNotCompute();
  11727. // Okay at this point we know that all elements of the chrec are constants and
  11728. // that the start element is zero.
  11729. // First check to see if the range contains zero. If not, the first
  11730. // iteration exits.
  11731. unsigned BitWidth = SE.getTypeSizeInBits(getType());
  11732. if (!Range.contains(APInt(BitWidth, 0)))
  11733. return SE.getZero(getType());
  11734. if (isAffine()) {
  11735. // If this is an affine expression then we have this situation:
  11736. // Solve {0,+,A} in Range === Ax in Range
  11737. // We know that zero is in the range. If A is positive then we know that
  11738. // the upper value of the range must be the first possible exit value.
  11739. // If A is negative then the lower of the range is the last possible loop
  11740. // value. Also note that we already checked for a full range.
  11741. APInt A = cast<SCEVConstant>(getOperand(1))->getAPInt();
  11742. APInt End = A.sge(1) ? (Range.getUpper() - 1) : Range.getLower();
  11743. // The exit value should be (End+A)/A.
  11744. APInt ExitVal = (End + A).udiv(A);
  11745. ConstantInt *ExitValue = ConstantInt::get(SE.getContext(), ExitVal);
  11746. // Evaluate at the exit value. If we really did fall out of the valid
  11747. // range, then we computed our trip count, otherwise wrap around or other
  11748. // things must have happened.
  11749. ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
  11750. if (Range.contains(Val->getValue()))
  11751. return SE.getCouldNotCompute(); // Something strange happened
  11752. // Ensure that the previous value is in the range.
  11753. assert(Range.contains(
  11754. EvaluateConstantChrecAtConstant(this,
  11755. ConstantInt::get(SE.getContext(), ExitVal - 1), SE)->getValue()) &&
  11756. "Linear scev computation is off in a bad way!");
  11757. return SE.getConstant(ExitValue);
  11758. }
  11759. if (isQuadratic()) {
  11760. if (auto S = SolveQuadraticAddRecRange(this, Range, SE))
  11761. return SE.getConstant(*S);
  11762. }
  11763. return SE.getCouldNotCompute();
  11764. }
  11765. const SCEVAddRecExpr *
  11766. SCEVAddRecExpr::getPostIncExpr(ScalarEvolution &SE) const {
  11767. assert(getNumOperands() > 1 && "AddRec with zero step?");
  11768. // There is a temptation to just call getAddExpr(this, getStepRecurrence(SE)),
  11769. // but in this case we cannot guarantee that the value returned will be an
  11770. // AddRec because SCEV does not have a fixed point where it stops
  11771. // simplification: it is legal to return ({rec1} + {rec2}). For example, it
  11772. // may happen if we reach arithmetic depth limit while simplifying. So we
  11773. // construct the returned value explicitly.
  11774. SmallVector<const SCEV *, 3> Ops;
  11775. // If this is {A,+,B,+,C,...,+,N}, then its step is {B,+,C,+,...,+,N}, and
  11776. // (this + Step) is {A+B,+,B+C,+...,+,N}.
  11777. for (unsigned i = 0, e = getNumOperands() - 1; i < e; ++i)
  11778. Ops.push_back(SE.getAddExpr(getOperand(i), getOperand(i + 1)));
  11779. // We know that the last operand is not a constant zero (otherwise it would
  11780. // have been popped out earlier). This guarantees us that if the result has
  11781. // the same last operand, then it will also not be popped out, meaning that
  11782. // the returned value will be an AddRec.
  11783. const SCEV *Last = getOperand(getNumOperands() - 1);
  11784. assert(!Last->isZero() && "Recurrency with zero step?");
  11785. Ops.push_back(Last);
  11786. return cast<SCEVAddRecExpr>(SE.getAddRecExpr(Ops, getLoop(),
  11787. SCEV::FlagAnyWrap));
  11788. }
  11789. // Return true when S contains at least an undef value.
  11790. bool ScalarEvolution::containsUndefs(const SCEV *S) const {
  11791. return SCEVExprContains(S, [](const SCEV *S) {
  11792. if (const auto *SU = dyn_cast<SCEVUnknown>(S))
  11793. return isa<UndefValue>(SU->getValue());
  11794. return false;
  11795. });
  11796. }
  11797. // Return true when S contains a value that is a nullptr.
  11798. bool ScalarEvolution::containsErasedValue(const SCEV *S) const {
  11799. return SCEVExprContains(S, [](const SCEV *S) {
  11800. if (const auto *SU = dyn_cast<SCEVUnknown>(S))
  11801. return SU->getValue() == nullptr;
  11802. return false;
  11803. });
  11804. }
  11805. /// Return the size of an element read or written by Inst.
  11806. const SCEV *ScalarEvolution::getElementSize(Instruction *Inst) {
  11807. Type *Ty;
  11808. if (StoreInst *Store = dyn_cast<StoreInst>(Inst))
  11809. Ty = Store->getValueOperand()->getType();
  11810. else if (LoadInst *Load = dyn_cast<LoadInst>(Inst))
  11811. Ty = Load->getType();
  11812. else
  11813. return nullptr;
  11814. Type *ETy = getEffectiveSCEVType(PointerType::getUnqual(Ty));
  11815. return getSizeOfExpr(ETy, Ty);
  11816. }
  11817. //===----------------------------------------------------------------------===//
  11818. // SCEVCallbackVH Class Implementation
  11819. //===----------------------------------------------------------------------===//
  11820. void ScalarEvolution::SCEVCallbackVH::deleted() {
  11821. assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
  11822. if (PHINode *PN = dyn_cast<PHINode>(getValPtr()))
  11823. SE->ConstantEvolutionLoopExitValue.erase(PN);
  11824. SE->eraseValueFromMap(getValPtr());
  11825. // this now dangles!
  11826. }
  11827. void ScalarEvolution::SCEVCallbackVH::allUsesReplacedWith(Value *V) {
  11828. assert(SE && "SCEVCallbackVH called with a null ScalarEvolution!");
  11829. // Forget all the expressions associated with users of the old value,
  11830. // so that future queries will recompute the expressions using the new
  11831. // value.
  11832. Value *Old = getValPtr();
  11833. SmallVector<User *, 16> Worklist(Old->users());
  11834. SmallPtrSet<User *, 8> Visited;
  11835. while (!Worklist.empty()) {
  11836. User *U = Worklist.pop_back_val();
  11837. // Deleting the Old value will cause this to dangle. Postpone
  11838. // that until everything else is done.
  11839. if (U == Old)
  11840. continue;
  11841. if (!Visited.insert(U).second)
  11842. continue;
  11843. if (PHINode *PN = dyn_cast<PHINode>(U))
  11844. SE->ConstantEvolutionLoopExitValue.erase(PN);
  11845. SE->eraseValueFromMap(U);
  11846. llvm::append_range(Worklist, U->users());
  11847. }
  11848. // Delete the Old value.
  11849. if (PHINode *PN = dyn_cast<PHINode>(Old))
  11850. SE->ConstantEvolutionLoopExitValue.erase(PN);
  11851. SE->eraseValueFromMap(Old);
  11852. // this now dangles!
  11853. }
  11854. ScalarEvolution::SCEVCallbackVH::SCEVCallbackVH(Value *V, ScalarEvolution *se)
  11855. : CallbackVH(V), SE(se) {}
  11856. //===----------------------------------------------------------------------===//
  11857. // ScalarEvolution Class Implementation
  11858. //===----------------------------------------------------------------------===//
  11859. ScalarEvolution::ScalarEvolution(Function &F, TargetLibraryInfo &TLI,
  11860. AssumptionCache &AC, DominatorTree &DT,
  11861. LoopInfo &LI)
  11862. : F(F), TLI(TLI), AC(AC), DT(DT), LI(LI),
  11863. CouldNotCompute(new SCEVCouldNotCompute()), ValuesAtScopes(64),
  11864. LoopDispositions(64), BlockDispositions(64) {}
  11865. ScalarEvolution::ScalarEvolution(ScalarEvolution &&Arg)
  11866. : F(Arg.F), TLI(Arg.TLI), AC(Arg.AC), DT(Arg.DT), LI(Arg.LI),
  11867. CouldNotCompute(std::move(Arg.CouldNotCompute)),
  11868. ValueExprMap(std::move(Arg.ValueExprMap)),
  11869. PendingLoopPredicates(std::move(Arg.PendingLoopPredicates)),
  11870. PendingPhiRanges(std::move(Arg.PendingPhiRanges)),
  11871. PendingMerges(std::move(Arg.PendingMerges)),
  11872. MinTrailingZerosCache(std::move(Arg.MinTrailingZerosCache)),
  11873. BackedgeTakenCounts(std::move(Arg.BackedgeTakenCounts)),
  11874. PredicatedBackedgeTakenCounts(
  11875. std::move(Arg.PredicatedBackedgeTakenCounts)),
  11876. BECountUsers(std::move(Arg.BECountUsers)),
  11877. ConstantEvolutionLoopExitValue(
  11878. std::move(Arg.ConstantEvolutionLoopExitValue)),
  11879. ValuesAtScopes(std::move(Arg.ValuesAtScopes)),
  11880. ValuesAtScopesUsers(std::move(Arg.ValuesAtScopesUsers)),
  11881. LoopDispositions(std::move(Arg.LoopDispositions)),
  11882. LoopPropertiesCache(std::move(Arg.LoopPropertiesCache)),
  11883. BlockDispositions(std::move(Arg.BlockDispositions)),
  11884. SCEVUsers(std::move(Arg.SCEVUsers)),
  11885. UnsignedRanges(std::move(Arg.UnsignedRanges)),
  11886. SignedRanges(std::move(Arg.SignedRanges)),
  11887. UniqueSCEVs(std::move(Arg.UniqueSCEVs)),
  11888. UniquePreds(std::move(Arg.UniquePreds)),
  11889. SCEVAllocator(std::move(Arg.SCEVAllocator)),
  11890. LoopUsers(std::move(Arg.LoopUsers)),
  11891. PredicatedSCEVRewrites(std::move(Arg.PredicatedSCEVRewrites)),
  11892. FirstUnknown(Arg.FirstUnknown) {
  11893. Arg.FirstUnknown = nullptr;
  11894. }
  11895. ScalarEvolution::~ScalarEvolution() {
  11896. // Iterate through all the SCEVUnknown instances and call their
  11897. // destructors, so that they release their references to their values.
  11898. for (SCEVUnknown *U = FirstUnknown; U;) {
  11899. SCEVUnknown *Tmp = U;
  11900. U = U->Next;
  11901. Tmp->~SCEVUnknown();
  11902. }
  11903. FirstUnknown = nullptr;
  11904. ExprValueMap.clear();
  11905. ValueExprMap.clear();
  11906. HasRecMap.clear();
  11907. BackedgeTakenCounts.clear();
  11908. PredicatedBackedgeTakenCounts.clear();
  11909. assert(PendingLoopPredicates.empty() && "isImpliedCond garbage");
  11910. assert(PendingPhiRanges.empty() && "getRangeRef garbage");
  11911. assert(PendingMerges.empty() && "isImpliedViaMerge garbage");
  11912. assert(!WalkingBEDominatingConds && "isLoopBackedgeGuardedByCond garbage!");
  11913. assert(!ProvingSplitPredicate && "ProvingSplitPredicate garbage!");
  11914. }
  11915. bool ScalarEvolution::hasLoopInvariantBackedgeTakenCount(const Loop *L) {
  11916. return !isa<SCEVCouldNotCompute>(getBackedgeTakenCount(L));
  11917. }
  11918. static void PrintLoopInfo(raw_ostream &OS, ScalarEvolution *SE,
  11919. const Loop *L) {
  11920. // Print all inner loops first
  11921. for (Loop *I : *L)
  11922. PrintLoopInfo(OS, SE, I);
  11923. OS << "Loop ";
  11924. L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  11925. OS << ": ";
  11926. SmallVector<BasicBlock *, 8> ExitingBlocks;
  11927. L->getExitingBlocks(ExitingBlocks);
  11928. if (ExitingBlocks.size() != 1)
  11929. OS << "<multiple exits> ";
  11930. if (SE->hasLoopInvariantBackedgeTakenCount(L))
  11931. OS << "backedge-taken count is " << *SE->getBackedgeTakenCount(L) << "\n";
  11932. else
  11933. OS << "Unpredictable backedge-taken count.\n";
  11934. if (ExitingBlocks.size() > 1)
  11935. for (BasicBlock *ExitingBlock : ExitingBlocks) {
  11936. OS << " exit count for " << ExitingBlock->getName() << ": "
  11937. << *SE->getExitCount(L, ExitingBlock) << "\n";
  11938. }
  11939. OS << "Loop ";
  11940. L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  11941. OS << ": ";
  11942. auto *ConstantBTC = SE->getConstantMaxBackedgeTakenCount(L);
  11943. if (!isa<SCEVCouldNotCompute>(ConstantBTC)) {
  11944. OS << "constant max backedge-taken count is " << *ConstantBTC;
  11945. if (SE->isBackedgeTakenCountMaxOrZero(L))
  11946. OS << ", actual taken count either this or zero.";
  11947. } else {
  11948. OS << "Unpredictable constant max backedge-taken count. ";
  11949. }
  11950. OS << "\n"
  11951. "Loop ";
  11952. L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  11953. OS << ": ";
  11954. auto *SymbolicBTC = SE->getSymbolicMaxBackedgeTakenCount(L);
  11955. if (!isa<SCEVCouldNotCompute>(SymbolicBTC)) {
  11956. OS << "symbolic max backedge-taken count is " << *SymbolicBTC;
  11957. if (SE->isBackedgeTakenCountMaxOrZero(L))
  11958. OS << ", actual taken count either this or zero.";
  11959. } else {
  11960. OS << "Unpredictable symbolic max backedge-taken count. ";
  11961. }
  11962. OS << "\n";
  11963. if (ExitingBlocks.size() > 1)
  11964. for (BasicBlock *ExitingBlock : ExitingBlocks) {
  11965. OS << " symbolic max exit count for " << ExitingBlock->getName() << ": "
  11966. << *SE->getExitCount(L, ExitingBlock, ScalarEvolution::SymbolicMaximum)
  11967. << "\n";
  11968. }
  11969. OS << "Loop ";
  11970. L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  11971. OS << ": ";
  11972. SmallVector<const SCEVPredicate *, 4> Preds;
  11973. auto PBT = SE->getPredicatedBackedgeTakenCount(L, Preds);
  11974. if (!isa<SCEVCouldNotCompute>(PBT)) {
  11975. OS << "Predicated backedge-taken count is " << *PBT << "\n";
  11976. OS << " Predicates:\n";
  11977. for (const auto *P : Preds)
  11978. P->print(OS, 4);
  11979. } else {
  11980. OS << "Unpredictable predicated backedge-taken count. ";
  11981. }
  11982. OS << "\n";
  11983. if (SE->hasLoopInvariantBackedgeTakenCount(L)) {
  11984. OS << "Loop ";
  11985. L->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  11986. OS << ": ";
  11987. OS << "Trip multiple is " << SE->getSmallConstantTripMultiple(L) << "\n";
  11988. }
  11989. }
  11990. static StringRef loopDispositionToStr(ScalarEvolution::LoopDisposition LD) {
  11991. switch (LD) {
  11992. case ScalarEvolution::LoopVariant:
  11993. return "Variant";
  11994. case ScalarEvolution::LoopInvariant:
  11995. return "Invariant";
  11996. case ScalarEvolution::LoopComputable:
  11997. return "Computable";
  11998. }
  11999. llvm_unreachable("Unknown ScalarEvolution::LoopDisposition kind!");
  12000. }
  12001. void ScalarEvolution::print(raw_ostream &OS) const {
  12002. // ScalarEvolution's implementation of the print method is to print
  12003. // out SCEV values of all instructions that are interesting. Doing
  12004. // this potentially causes it to create new SCEV objects though,
  12005. // which technically conflicts with the const qualifier. This isn't
  12006. // observable from outside the class though, so casting away the
  12007. // const isn't dangerous.
  12008. ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
  12009. if (ClassifyExpressions) {
  12010. OS << "Classifying expressions for: ";
  12011. F.printAsOperand(OS, /*PrintType=*/false);
  12012. OS << "\n";
  12013. for (Instruction &I : instructions(F))
  12014. if (isSCEVable(I.getType()) && !isa<CmpInst>(I)) {
  12015. OS << I << '\n';
  12016. OS << " --> ";
  12017. const SCEV *SV = SE.getSCEV(&I);
  12018. SV->print(OS);
  12019. if (!isa<SCEVCouldNotCompute>(SV)) {
  12020. OS << " U: ";
  12021. SE.getUnsignedRange(SV).print(OS);
  12022. OS << " S: ";
  12023. SE.getSignedRange(SV).print(OS);
  12024. }
  12025. const Loop *L = LI.getLoopFor(I.getParent());
  12026. const SCEV *AtUse = SE.getSCEVAtScope(SV, L);
  12027. if (AtUse != SV) {
  12028. OS << " --> ";
  12029. AtUse->print(OS);
  12030. if (!isa<SCEVCouldNotCompute>(AtUse)) {
  12031. OS << " U: ";
  12032. SE.getUnsignedRange(AtUse).print(OS);
  12033. OS << " S: ";
  12034. SE.getSignedRange(AtUse).print(OS);
  12035. }
  12036. }
  12037. if (L) {
  12038. OS << "\t\t" "Exits: ";
  12039. const SCEV *ExitValue = SE.getSCEVAtScope(SV, L->getParentLoop());
  12040. if (!SE.isLoopInvariant(ExitValue, L)) {
  12041. OS << "<<Unknown>>";
  12042. } else {
  12043. OS << *ExitValue;
  12044. }
  12045. bool First = true;
  12046. for (const auto *Iter = L; Iter; Iter = Iter->getParentLoop()) {
  12047. if (First) {
  12048. OS << "\t\t" "LoopDispositions: { ";
  12049. First = false;
  12050. } else {
  12051. OS << ", ";
  12052. }
  12053. Iter->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  12054. OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, Iter));
  12055. }
  12056. for (const auto *InnerL : depth_first(L)) {
  12057. if (InnerL == L)
  12058. continue;
  12059. if (First) {
  12060. OS << "\t\t" "LoopDispositions: { ";
  12061. First = false;
  12062. } else {
  12063. OS << ", ";
  12064. }
  12065. InnerL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  12066. OS << ": " << loopDispositionToStr(SE.getLoopDisposition(SV, InnerL));
  12067. }
  12068. OS << " }";
  12069. }
  12070. OS << "\n";
  12071. }
  12072. }
  12073. OS << "Determining loop execution counts for: ";
  12074. F.printAsOperand(OS, /*PrintType=*/false);
  12075. OS << "\n";
  12076. for (Loop *I : LI)
  12077. PrintLoopInfo(OS, &SE, I);
  12078. }
  12079. ScalarEvolution::LoopDisposition
  12080. ScalarEvolution::getLoopDisposition(const SCEV *S, const Loop *L) {
  12081. auto &Values = LoopDispositions[S];
  12082. for (auto &V : Values) {
  12083. if (V.getPointer() == L)
  12084. return V.getInt();
  12085. }
  12086. Values.emplace_back(L, LoopVariant);
  12087. LoopDisposition D = computeLoopDisposition(S, L);
  12088. auto &Values2 = LoopDispositions[S];
  12089. for (auto &V : llvm::reverse(Values2)) {
  12090. if (V.getPointer() == L) {
  12091. V.setInt(D);
  12092. break;
  12093. }
  12094. }
  12095. return D;
  12096. }
  12097. ScalarEvolution::LoopDisposition
  12098. ScalarEvolution::computeLoopDisposition(const SCEV *S, const Loop *L) {
  12099. switch (S->getSCEVType()) {
  12100. case scConstant:
  12101. return LoopInvariant;
  12102. case scAddRecExpr: {
  12103. const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
  12104. // If L is the addrec's loop, it's computable.
  12105. if (AR->getLoop() == L)
  12106. return LoopComputable;
  12107. // Add recurrences are never invariant in the function-body (null loop).
  12108. if (!L)
  12109. return LoopVariant;
  12110. // Everything that is not defined at loop entry is variant.
  12111. if (DT.dominates(L->getHeader(), AR->getLoop()->getHeader()))
  12112. return LoopVariant;
  12113. assert(!L->contains(AR->getLoop()) && "Containing loop's header does not"
  12114. " dominate the contained loop's header?");
  12115. // This recurrence is invariant w.r.t. L if AR's loop contains L.
  12116. if (AR->getLoop()->contains(L))
  12117. return LoopInvariant;
  12118. // This recurrence is variant w.r.t. L if any of its operands
  12119. // are variant.
  12120. for (const auto *Op : AR->operands())
  12121. if (!isLoopInvariant(Op, L))
  12122. return LoopVariant;
  12123. // Otherwise it's loop-invariant.
  12124. return LoopInvariant;
  12125. }
  12126. case scTruncate:
  12127. case scZeroExtend:
  12128. case scSignExtend:
  12129. case scPtrToInt:
  12130. case scAddExpr:
  12131. case scMulExpr:
  12132. case scUDivExpr:
  12133. case scUMaxExpr:
  12134. case scSMaxExpr:
  12135. case scUMinExpr:
  12136. case scSMinExpr:
  12137. case scSequentialUMinExpr: {
  12138. bool HasVarying = false;
  12139. for (const auto *Op : S->operands()) {
  12140. LoopDisposition D = getLoopDisposition(Op, L);
  12141. if (D == LoopVariant)
  12142. return LoopVariant;
  12143. if (D == LoopComputable)
  12144. HasVarying = true;
  12145. }
  12146. return HasVarying ? LoopComputable : LoopInvariant;
  12147. }
  12148. case scUnknown:
  12149. // All non-instruction values are loop invariant. All instructions are loop
  12150. // invariant if they are not contained in the specified loop.
  12151. // Instructions are never considered invariant in the function body
  12152. // (null loop) because they are defined within the "loop".
  12153. if (auto *I = dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue()))
  12154. return (L && !L->contains(I)) ? LoopInvariant : LoopVariant;
  12155. return LoopInvariant;
  12156. case scCouldNotCompute:
  12157. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  12158. }
  12159. llvm_unreachable("Unknown SCEV kind!");
  12160. }
  12161. bool ScalarEvolution::isLoopInvariant(const SCEV *S, const Loop *L) {
  12162. return getLoopDisposition(S, L) == LoopInvariant;
  12163. }
  12164. bool ScalarEvolution::hasComputableLoopEvolution(const SCEV *S, const Loop *L) {
  12165. return getLoopDisposition(S, L) == LoopComputable;
  12166. }
  12167. ScalarEvolution::BlockDisposition
  12168. ScalarEvolution::getBlockDisposition(const SCEV *S, const BasicBlock *BB) {
  12169. auto &Values = BlockDispositions[S];
  12170. for (auto &V : Values) {
  12171. if (V.getPointer() == BB)
  12172. return V.getInt();
  12173. }
  12174. Values.emplace_back(BB, DoesNotDominateBlock);
  12175. BlockDisposition D = computeBlockDisposition(S, BB);
  12176. auto &Values2 = BlockDispositions[S];
  12177. for (auto &V : llvm::reverse(Values2)) {
  12178. if (V.getPointer() == BB) {
  12179. V.setInt(D);
  12180. break;
  12181. }
  12182. }
  12183. return D;
  12184. }
  12185. ScalarEvolution::BlockDisposition
  12186. ScalarEvolution::computeBlockDisposition(const SCEV *S, const BasicBlock *BB) {
  12187. switch (S->getSCEVType()) {
  12188. case scConstant:
  12189. return ProperlyDominatesBlock;
  12190. case scAddRecExpr: {
  12191. // This uses a "dominates" query instead of "properly dominates" query
  12192. // to test for proper dominance too, because the instruction which
  12193. // produces the addrec's value is a PHI, and a PHI effectively properly
  12194. // dominates its entire containing block.
  12195. const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(S);
  12196. if (!DT.dominates(AR->getLoop()->getHeader(), BB))
  12197. return DoesNotDominateBlock;
  12198. // Fall through into SCEVNAryExpr handling.
  12199. [[fallthrough]];
  12200. }
  12201. case scTruncate:
  12202. case scZeroExtend:
  12203. case scSignExtend:
  12204. case scPtrToInt:
  12205. case scAddExpr:
  12206. case scMulExpr:
  12207. case scUDivExpr:
  12208. case scUMaxExpr:
  12209. case scSMaxExpr:
  12210. case scUMinExpr:
  12211. case scSMinExpr:
  12212. case scSequentialUMinExpr: {
  12213. bool Proper = true;
  12214. for (const SCEV *NAryOp : S->operands()) {
  12215. BlockDisposition D = getBlockDisposition(NAryOp, BB);
  12216. if (D == DoesNotDominateBlock)
  12217. return DoesNotDominateBlock;
  12218. if (D == DominatesBlock)
  12219. Proper = false;
  12220. }
  12221. return Proper ? ProperlyDominatesBlock : DominatesBlock;
  12222. }
  12223. case scUnknown:
  12224. if (Instruction *I =
  12225. dyn_cast<Instruction>(cast<SCEVUnknown>(S)->getValue())) {
  12226. if (I->getParent() == BB)
  12227. return DominatesBlock;
  12228. if (DT.properlyDominates(I->getParent(), BB))
  12229. return ProperlyDominatesBlock;
  12230. return DoesNotDominateBlock;
  12231. }
  12232. return ProperlyDominatesBlock;
  12233. case scCouldNotCompute:
  12234. llvm_unreachable("Attempt to use a SCEVCouldNotCompute object!");
  12235. }
  12236. llvm_unreachable("Unknown SCEV kind!");
  12237. }
  12238. bool ScalarEvolution::dominates(const SCEV *S, const BasicBlock *BB) {
  12239. return getBlockDisposition(S, BB) >= DominatesBlock;
  12240. }
  12241. bool ScalarEvolution::properlyDominates(const SCEV *S, const BasicBlock *BB) {
  12242. return getBlockDisposition(S, BB) == ProperlyDominatesBlock;
  12243. }
  12244. bool ScalarEvolution::hasOperand(const SCEV *S, const SCEV *Op) const {
  12245. return SCEVExprContains(S, [&](const SCEV *Expr) { return Expr == Op; });
  12246. }
  12247. void ScalarEvolution::forgetBackedgeTakenCounts(const Loop *L,
  12248. bool Predicated) {
  12249. auto &BECounts =
  12250. Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
  12251. auto It = BECounts.find(L);
  12252. if (It != BECounts.end()) {
  12253. for (const ExitNotTakenInfo &ENT : It->second.ExitNotTaken) {
  12254. for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
  12255. if (!isa<SCEVConstant>(S)) {
  12256. auto UserIt = BECountUsers.find(S);
  12257. assert(UserIt != BECountUsers.end());
  12258. UserIt->second.erase({L, Predicated});
  12259. }
  12260. }
  12261. }
  12262. BECounts.erase(It);
  12263. }
  12264. }
  12265. void ScalarEvolution::forgetMemoizedResults(ArrayRef<const SCEV *> SCEVs) {
  12266. SmallPtrSet<const SCEV *, 8> ToForget(SCEVs.begin(), SCEVs.end());
  12267. SmallVector<const SCEV *, 8> Worklist(ToForget.begin(), ToForget.end());
  12268. while (!Worklist.empty()) {
  12269. const SCEV *Curr = Worklist.pop_back_val();
  12270. auto Users = SCEVUsers.find(Curr);
  12271. if (Users != SCEVUsers.end())
  12272. for (const auto *User : Users->second)
  12273. if (ToForget.insert(User).second)
  12274. Worklist.push_back(User);
  12275. }
  12276. for (const auto *S : ToForget)
  12277. forgetMemoizedResultsImpl(S);
  12278. for (auto I = PredicatedSCEVRewrites.begin();
  12279. I != PredicatedSCEVRewrites.end();) {
  12280. std::pair<const SCEV *, const Loop *> Entry = I->first;
  12281. if (ToForget.count(Entry.first))
  12282. PredicatedSCEVRewrites.erase(I++);
  12283. else
  12284. ++I;
  12285. }
  12286. }
  12287. void ScalarEvolution::forgetMemoizedResultsImpl(const SCEV *S) {
  12288. LoopDispositions.erase(S);
  12289. BlockDispositions.erase(S);
  12290. UnsignedRanges.erase(S);
  12291. SignedRanges.erase(S);
  12292. HasRecMap.erase(S);
  12293. MinTrailingZerosCache.erase(S);
  12294. if (auto *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  12295. UnsignedWrapViaInductionTried.erase(AR);
  12296. SignedWrapViaInductionTried.erase(AR);
  12297. }
  12298. auto ExprIt = ExprValueMap.find(S);
  12299. if (ExprIt != ExprValueMap.end()) {
  12300. for (Value *V : ExprIt->second) {
  12301. auto ValueIt = ValueExprMap.find_as(V);
  12302. if (ValueIt != ValueExprMap.end())
  12303. ValueExprMap.erase(ValueIt);
  12304. }
  12305. ExprValueMap.erase(ExprIt);
  12306. }
  12307. auto ScopeIt = ValuesAtScopes.find(S);
  12308. if (ScopeIt != ValuesAtScopes.end()) {
  12309. for (const auto &Pair : ScopeIt->second)
  12310. if (!isa_and_nonnull<SCEVConstant>(Pair.second))
  12311. erase_value(ValuesAtScopesUsers[Pair.second],
  12312. std::make_pair(Pair.first, S));
  12313. ValuesAtScopes.erase(ScopeIt);
  12314. }
  12315. auto ScopeUserIt = ValuesAtScopesUsers.find(S);
  12316. if (ScopeUserIt != ValuesAtScopesUsers.end()) {
  12317. for (const auto &Pair : ScopeUserIt->second)
  12318. erase_value(ValuesAtScopes[Pair.second], std::make_pair(Pair.first, S));
  12319. ValuesAtScopesUsers.erase(ScopeUserIt);
  12320. }
  12321. auto BEUsersIt = BECountUsers.find(S);
  12322. if (BEUsersIt != BECountUsers.end()) {
  12323. // Work on a copy, as forgetBackedgeTakenCounts() will modify the original.
  12324. auto Copy = BEUsersIt->second;
  12325. for (const auto &Pair : Copy)
  12326. forgetBackedgeTakenCounts(Pair.getPointer(), Pair.getInt());
  12327. BECountUsers.erase(BEUsersIt);
  12328. }
  12329. auto FoldUser = FoldCacheUser.find(S);
  12330. if (FoldUser != FoldCacheUser.end())
  12331. for (auto &KV : FoldUser->second)
  12332. FoldCache.erase(KV);
  12333. FoldCacheUser.erase(S);
  12334. }
  12335. void
  12336. ScalarEvolution::getUsedLoops(const SCEV *S,
  12337. SmallPtrSetImpl<const Loop *> &LoopsUsed) {
  12338. struct FindUsedLoops {
  12339. FindUsedLoops(SmallPtrSetImpl<const Loop *> &LoopsUsed)
  12340. : LoopsUsed(LoopsUsed) {}
  12341. SmallPtrSetImpl<const Loop *> &LoopsUsed;
  12342. bool follow(const SCEV *S) {
  12343. if (auto *AR = dyn_cast<SCEVAddRecExpr>(S))
  12344. LoopsUsed.insert(AR->getLoop());
  12345. return true;
  12346. }
  12347. bool isDone() const { return false; }
  12348. };
  12349. FindUsedLoops F(LoopsUsed);
  12350. SCEVTraversal<FindUsedLoops>(F).visitAll(S);
  12351. }
  12352. void ScalarEvolution::getReachableBlocks(
  12353. SmallPtrSetImpl<BasicBlock *> &Reachable, Function &F) {
  12354. SmallVector<BasicBlock *> Worklist;
  12355. Worklist.push_back(&F.getEntryBlock());
  12356. while (!Worklist.empty()) {
  12357. BasicBlock *BB = Worklist.pop_back_val();
  12358. if (!Reachable.insert(BB).second)
  12359. continue;
  12360. Value *Cond;
  12361. BasicBlock *TrueBB, *FalseBB;
  12362. if (match(BB->getTerminator(), m_Br(m_Value(Cond), m_BasicBlock(TrueBB),
  12363. m_BasicBlock(FalseBB)))) {
  12364. if (auto *C = dyn_cast<ConstantInt>(Cond)) {
  12365. Worklist.push_back(C->isOne() ? TrueBB : FalseBB);
  12366. continue;
  12367. }
  12368. if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
  12369. const SCEV *L = getSCEV(Cmp->getOperand(0));
  12370. const SCEV *R = getSCEV(Cmp->getOperand(1));
  12371. if (isKnownPredicateViaConstantRanges(Cmp->getPredicate(), L, R)) {
  12372. Worklist.push_back(TrueBB);
  12373. continue;
  12374. }
  12375. if (isKnownPredicateViaConstantRanges(Cmp->getInversePredicate(), L,
  12376. R)) {
  12377. Worklist.push_back(FalseBB);
  12378. continue;
  12379. }
  12380. }
  12381. }
  12382. append_range(Worklist, successors(BB));
  12383. }
  12384. }
  12385. void ScalarEvolution::verify() const {
  12386. ScalarEvolution &SE = *const_cast<ScalarEvolution *>(this);
  12387. ScalarEvolution SE2(F, TLI, AC, DT, LI);
  12388. SmallVector<Loop *, 8> LoopStack(LI.begin(), LI.end());
  12389. // Map's SCEV expressions from one ScalarEvolution "universe" to another.
  12390. struct SCEVMapper : public SCEVRewriteVisitor<SCEVMapper> {
  12391. SCEVMapper(ScalarEvolution &SE) : SCEVRewriteVisitor<SCEVMapper>(SE) {}
  12392. const SCEV *visitConstant(const SCEVConstant *Constant) {
  12393. return SE.getConstant(Constant->getAPInt());
  12394. }
  12395. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  12396. return SE.getUnknown(Expr->getValue());
  12397. }
  12398. const SCEV *visitCouldNotCompute(const SCEVCouldNotCompute *Expr) {
  12399. return SE.getCouldNotCompute();
  12400. }
  12401. };
  12402. SCEVMapper SCM(SE2);
  12403. SmallPtrSet<BasicBlock *, 16> ReachableBlocks;
  12404. SE2.getReachableBlocks(ReachableBlocks, F);
  12405. auto GetDelta = [&](const SCEV *Old, const SCEV *New) -> const SCEV * {
  12406. if (containsUndefs(Old) || containsUndefs(New)) {
  12407. // SCEV treats "undef" as an unknown but consistent value (i.e. it does
  12408. // not propagate undef aggressively). This means we can (and do) fail
  12409. // verification in cases where a transform makes a value go from "undef"
  12410. // to "undef+1" (say). The transform is fine, since in both cases the
  12411. // result is "undef", but SCEV thinks the value increased by 1.
  12412. return nullptr;
  12413. }
  12414. // Unless VerifySCEVStrict is set, we only compare constant deltas.
  12415. const SCEV *Delta = SE2.getMinusSCEV(Old, New);
  12416. if (!VerifySCEVStrict && !isa<SCEVConstant>(Delta))
  12417. return nullptr;
  12418. return Delta;
  12419. };
  12420. while (!LoopStack.empty()) {
  12421. auto *L = LoopStack.pop_back_val();
  12422. llvm::append_range(LoopStack, *L);
  12423. // Only verify BECounts in reachable loops. For an unreachable loop,
  12424. // any BECount is legal.
  12425. if (!ReachableBlocks.contains(L->getHeader()))
  12426. continue;
  12427. // Only verify cached BECounts. Computing new BECounts may change the
  12428. // results of subsequent SCEV uses.
  12429. auto It = BackedgeTakenCounts.find(L);
  12430. if (It == BackedgeTakenCounts.end())
  12431. continue;
  12432. auto *CurBECount =
  12433. SCM.visit(It->second.getExact(L, const_cast<ScalarEvolution *>(this)));
  12434. auto *NewBECount = SE2.getBackedgeTakenCount(L);
  12435. if (CurBECount == SE2.getCouldNotCompute() ||
  12436. NewBECount == SE2.getCouldNotCompute()) {
  12437. // NB! This situation is legal, but is very suspicious -- whatever pass
  12438. // change the loop to make a trip count go from could not compute to
  12439. // computable or vice-versa *should have* invalidated SCEV. However, we
  12440. // choose not to assert here (for now) since we don't want false
  12441. // positives.
  12442. continue;
  12443. }
  12444. if (SE.getTypeSizeInBits(CurBECount->getType()) >
  12445. SE.getTypeSizeInBits(NewBECount->getType()))
  12446. NewBECount = SE2.getZeroExtendExpr(NewBECount, CurBECount->getType());
  12447. else if (SE.getTypeSizeInBits(CurBECount->getType()) <
  12448. SE.getTypeSizeInBits(NewBECount->getType()))
  12449. CurBECount = SE2.getZeroExtendExpr(CurBECount, NewBECount->getType());
  12450. const SCEV *Delta = GetDelta(CurBECount, NewBECount);
  12451. if (Delta && !Delta->isZero()) {
  12452. dbgs() << "Trip Count for " << *L << " Changed!\n";
  12453. dbgs() << "Old: " << *CurBECount << "\n";
  12454. dbgs() << "New: " << *NewBECount << "\n";
  12455. dbgs() << "Delta: " << *Delta << "\n";
  12456. std::abort();
  12457. }
  12458. }
  12459. // Collect all valid loops currently in LoopInfo.
  12460. SmallPtrSet<Loop *, 32> ValidLoops;
  12461. SmallVector<Loop *, 32> Worklist(LI.begin(), LI.end());
  12462. while (!Worklist.empty()) {
  12463. Loop *L = Worklist.pop_back_val();
  12464. if (ValidLoops.insert(L).second)
  12465. Worklist.append(L->begin(), L->end());
  12466. }
  12467. for (const auto &KV : ValueExprMap) {
  12468. #ifndef NDEBUG
  12469. // Check for SCEV expressions referencing invalid/deleted loops.
  12470. if (auto *AR = dyn_cast<SCEVAddRecExpr>(KV.second)) {
  12471. assert(ValidLoops.contains(AR->getLoop()) &&
  12472. "AddRec references invalid loop");
  12473. }
  12474. #endif
  12475. // Check that the value is also part of the reverse map.
  12476. auto It = ExprValueMap.find(KV.second);
  12477. if (It == ExprValueMap.end() || !It->second.contains(KV.first)) {
  12478. dbgs() << "Value " << *KV.first
  12479. << " is in ValueExprMap but not in ExprValueMap\n";
  12480. std::abort();
  12481. }
  12482. if (auto *I = dyn_cast<Instruction>(&*KV.first)) {
  12483. if (!ReachableBlocks.contains(I->getParent()))
  12484. continue;
  12485. const SCEV *OldSCEV = SCM.visit(KV.second);
  12486. const SCEV *NewSCEV = SE2.getSCEV(I);
  12487. const SCEV *Delta = GetDelta(OldSCEV, NewSCEV);
  12488. if (Delta && !Delta->isZero()) {
  12489. dbgs() << "SCEV for value " << *I << " changed!\n"
  12490. << "Old: " << *OldSCEV << "\n"
  12491. << "New: " << *NewSCEV << "\n"
  12492. << "Delta: " << *Delta << "\n";
  12493. std::abort();
  12494. }
  12495. }
  12496. }
  12497. for (const auto &KV : ExprValueMap) {
  12498. for (Value *V : KV.second) {
  12499. auto It = ValueExprMap.find_as(V);
  12500. if (It == ValueExprMap.end()) {
  12501. dbgs() << "Value " << *V
  12502. << " is in ExprValueMap but not in ValueExprMap\n";
  12503. std::abort();
  12504. }
  12505. if (It->second != KV.first) {
  12506. dbgs() << "Value " << *V << " mapped to " << *It->second
  12507. << " rather than " << *KV.first << "\n";
  12508. std::abort();
  12509. }
  12510. }
  12511. }
  12512. // Verify integrity of SCEV users.
  12513. for (const auto &S : UniqueSCEVs) {
  12514. for (const auto *Op : S.operands()) {
  12515. // We do not store dependencies of constants.
  12516. if (isa<SCEVConstant>(Op))
  12517. continue;
  12518. auto It = SCEVUsers.find(Op);
  12519. if (It != SCEVUsers.end() && It->second.count(&S))
  12520. continue;
  12521. dbgs() << "Use of operand " << *Op << " by user " << S
  12522. << " is not being tracked!\n";
  12523. std::abort();
  12524. }
  12525. }
  12526. // Verify integrity of ValuesAtScopes users.
  12527. for (const auto &ValueAndVec : ValuesAtScopes) {
  12528. const SCEV *Value = ValueAndVec.first;
  12529. for (const auto &LoopAndValueAtScope : ValueAndVec.second) {
  12530. const Loop *L = LoopAndValueAtScope.first;
  12531. const SCEV *ValueAtScope = LoopAndValueAtScope.second;
  12532. if (!isa<SCEVConstant>(ValueAtScope)) {
  12533. auto It = ValuesAtScopesUsers.find(ValueAtScope);
  12534. if (It != ValuesAtScopesUsers.end() &&
  12535. is_contained(It->second, std::make_pair(L, Value)))
  12536. continue;
  12537. dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
  12538. << *ValueAtScope << " missing in ValuesAtScopesUsers\n";
  12539. std::abort();
  12540. }
  12541. }
  12542. }
  12543. for (const auto &ValueAtScopeAndVec : ValuesAtScopesUsers) {
  12544. const SCEV *ValueAtScope = ValueAtScopeAndVec.first;
  12545. for (const auto &LoopAndValue : ValueAtScopeAndVec.second) {
  12546. const Loop *L = LoopAndValue.first;
  12547. const SCEV *Value = LoopAndValue.second;
  12548. assert(!isa<SCEVConstant>(Value));
  12549. auto It = ValuesAtScopes.find(Value);
  12550. if (It != ValuesAtScopes.end() &&
  12551. is_contained(It->second, std::make_pair(L, ValueAtScope)))
  12552. continue;
  12553. dbgs() << "Value: " << *Value << ", Loop: " << *L << ", ValueAtScope: "
  12554. << *ValueAtScope << " missing in ValuesAtScopes\n";
  12555. std::abort();
  12556. }
  12557. }
  12558. // Verify integrity of BECountUsers.
  12559. auto VerifyBECountUsers = [&](bool Predicated) {
  12560. auto &BECounts =
  12561. Predicated ? PredicatedBackedgeTakenCounts : BackedgeTakenCounts;
  12562. for (const auto &LoopAndBEInfo : BECounts) {
  12563. for (const ExitNotTakenInfo &ENT : LoopAndBEInfo.second.ExitNotTaken) {
  12564. for (const SCEV *S : {ENT.ExactNotTaken, ENT.SymbolicMaxNotTaken}) {
  12565. if (!isa<SCEVConstant>(S)) {
  12566. auto UserIt = BECountUsers.find(S);
  12567. if (UserIt != BECountUsers.end() &&
  12568. UserIt->second.contains({ LoopAndBEInfo.first, Predicated }))
  12569. continue;
  12570. dbgs() << "Value " << *S << " for loop " << *LoopAndBEInfo.first
  12571. << " missing from BECountUsers\n";
  12572. std::abort();
  12573. }
  12574. }
  12575. }
  12576. }
  12577. };
  12578. VerifyBECountUsers(/* Predicated */ false);
  12579. VerifyBECountUsers(/* Predicated */ true);
  12580. // Verify intergity of loop disposition cache.
  12581. for (auto &[S, Values] : LoopDispositions) {
  12582. for (auto [Loop, CachedDisposition] : Values) {
  12583. const auto RecomputedDisposition = SE2.getLoopDisposition(S, Loop);
  12584. if (CachedDisposition != RecomputedDisposition) {
  12585. dbgs() << "Cached disposition of " << *S << " for loop " << *Loop
  12586. << " is incorrect: cached "
  12587. << loopDispositionToStr(CachedDisposition) << ", actual "
  12588. << loopDispositionToStr(RecomputedDisposition) << "\n";
  12589. std::abort();
  12590. }
  12591. }
  12592. }
  12593. // Verify integrity of the block disposition cache.
  12594. for (auto &[S, Values] : BlockDispositions) {
  12595. for (auto [BB, CachedDisposition] : Values) {
  12596. const auto RecomputedDisposition = SE2.getBlockDisposition(S, BB);
  12597. if (CachedDisposition != RecomputedDisposition) {
  12598. dbgs() << "Cached disposition of " << *S << " for block %"
  12599. << BB->getName() << " is incorrect! \n";
  12600. std::abort();
  12601. }
  12602. }
  12603. }
  12604. // Verify FoldCache/FoldCacheUser caches.
  12605. for (auto [FoldID, Expr] : FoldCache) {
  12606. auto I = FoldCacheUser.find(Expr);
  12607. if (I == FoldCacheUser.end()) {
  12608. dbgs() << "Missing entry in FoldCacheUser for cached expression " << *Expr
  12609. << "!\n";
  12610. std::abort();
  12611. }
  12612. if (!is_contained(I->second, FoldID)) {
  12613. dbgs() << "Missing FoldID in cached users of " << *Expr << "!\n";
  12614. std::abort();
  12615. }
  12616. }
  12617. for (auto [Expr, IDs] : FoldCacheUser) {
  12618. for (auto &FoldID : IDs) {
  12619. auto I = FoldCache.find(FoldID);
  12620. if (I == FoldCache.end()) {
  12621. dbgs() << "Missing entry in FoldCache for expression " << *Expr
  12622. << "!\n";
  12623. std::abort();
  12624. }
  12625. if (I->second != Expr) {
  12626. dbgs() << "Entry in FoldCache doesn't match FoldCacheUser: "
  12627. << *I->second << " != " << *Expr << "!\n";
  12628. std::abort();
  12629. }
  12630. }
  12631. }
  12632. }
  12633. bool ScalarEvolution::invalidate(
  12634. Function &F, const PreservedAnalyses &PA,
  12635. FunctionAnalysisManager::Invalidator &Inv) {
  12636. // Invalidate the ScalarEvolution object whenever it isn't preserved or one
  12637. // of its dependencies is invalidated.
  12638. auto PAC = PA.getChecker<ScalarEvolutionAnalysis>();
  12639. return !(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>()) ||
  12640. Inv.invalidate<AssumptionAnalysis>(F, PA) ||
  12641. Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
  12642. Inv.invalidate<LoopAnalysis>(F, PA);
  12643. }
  12644. AnalysisKey ScalarEvolutionAnalysis::Key;
  12645. ScalarEvolution ScalarEvolutionAnalysis::run(Function &F,
  12646. FunctionAnalysisManager &AM) {
  12647. return ScalarEvolution(F, AM.getResult<TargetLibraryAnalysis>(F),
  12648. AM.getResult<AssumptionAnalysis>(F),
  12649. AM.getResult<DominatorTreeAnalysis>(F),
  12650. AM.getResult<LoopAnalysis>(F));
  12651. }
  12652. PreservedAnalyses
  12653. ScalarEvolutionVerifierPass::run(Function &F, FunctionAnalysisManager &AM) {
  12654. AM.getResult<ScalarEvolutionAnalysis>(F).verify();
  12655. return PreservedAnalyses::all();
  12656. }
  12657. PreservedAnalyses
  12658. ScalarEvolutionPrinterPass::run(Function &F, FunctionAnalysisManager &AM) {
  12659. // For compatibility with opt's -analyze feature under legacy pass manager
  12660. // which was not ported to NPM. This keeps tests using
  12661. // update_analyze_test_checks.py working.
  12662. OS << "Printing analysis 'Scalar Evolution Analysis' for function '"
  12663. << F.getName() << "':\n";
  12664. AM.getResult<ScalarEvolutionAnalysis>(F).print(OS);
  12665. return PreservedAnalyses::all();
  12666. }
  12667. INITIALIZE_PASS_BEGIN(ScalarEvolutionWrapperPass, "scalar-evolution",
  12668. "Scalar Evolution Analysis", false, true)
  12669. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  12670. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  12671. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  12672. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  12673. INITIALIZE_PASS_END(ScalarEvolutionWrapperPass, "scalar-evolution",
  12674. "Scalar Evolution Analysis", false, true)
  12675. char ScalarEvolutionWrapperPass::ID = 0;
  12676. ScalarEvolutionWrapperPass::ScalarEvolutionWrapperPass() : FunctionPass(ID) {
  12677. initializeScalarEvolutionWrapperPassPass(*PassRegistry::getPassRegistry());
  12678. }
  12679. bool ScalarEvolutionWrapperPass::runOnFunction(Function &F) {
  12680. SE.reset(new ScalarEvolution(
  12681. F, getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
  12682. getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
  12683. getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
  12684. getAnalysis<LoopInfoWrapperPass>().getLoopInfo()));
  12685. return false;
  12686. }
  12687. void ScalarEvolutionWrapperPass::releaseMemory() { SE.reset(); }
  12688. void ScalarEvolutionWrapperPass::print(raw_ostream &OS, const Module *) const {
  12689. SE->print(OS);
  12690. }
  12691. void ScalarEvolutionWrapperPass::verifyAnalysis() const {
  12692. if (!VerifySCEV)
  12693. return;
  12694. SE->verify();
  12695. }
  12696. void ScalarEvolutionWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
  12697. AU.setPreservesAll();
  12698. AU.addRequiredTransitive<AssumptionCacheTracker>();
  12699. AU.addRequiredTransitive<LoopInfoWrapperPass>();
  12700. AU.addRequiredTransitive<DominatorTreeWrapperPass>();
  12701. AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
  12702. }
  12703. const SCEVPredicate *ScalarEvolution::getEqualPredicate(const SCEV *LHS,
  12704. const SCEV *RHS) {
  12705. return getComparePredicate(ICmpInst::ICMP_EQ, LHS, RHS);
  12706. }
  12707. const SCEVPredicate *
  12708. ScalarEvolution::getComparePredicate(const ICmpInst::Predicate Pred,
  12709. const SCEV *LHS, const SCEV *RHS) {
  12710. FoldingSetNodeID ID;
  12711. assert(LHS->getType() == RHS->getType() &&
  12712. "Type mismatch between LHS and RHS");
  12713. // Unique this node based on the arguments
  12714. ID.AddInteger(SCEVPredicate::P_Compare);
  12715. ID.AddInteger(Pred);
  12716. ID.AddPointer(LHS);
  12717. ID.AddPointer(RHS);
  12718. void *IP = nullptr;
  12719. if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
  12720. return S;
  12721. SCEVComparePredicate *Eq = new (SCEVAllocator)
  12722. SCEVComparePredicate(ID.Intern(SCEVAllocator), Pred, LHS, RHS);
  12723. UniquePreds.InsertNode(Eq, IP);
  12724. return Eq;
  12725. }
  12726. const SCEVPredicate *ScalarEvolution::getWrapPredicate(
  12727. const SCEVAddRecExpr *AR,
  12728. SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
  12729. FoldingSetNodeID ID;
  12730. // Unique this node based on the arguments
  12731. ID.AddInteger(SCEVPredicate::P_Wrap);
  12732. ID.AddPointer(AR);
  12733. ID.AddInteger(AddedFlags);
  12734. void *IP = nullptr;
  12735. if (const auto *S = UniquePreds.FindNodeOrInsertPos(ID, IP))
  12736. return S;
  12737. auto *OF = new (SCEVAllocator)
  12738. SCEVWrapPredicate(ID.Intern(SCEVAllocator), AR, AddedFlags);
  12739. UniquePreds.InsertNode(OF, IP);
  12740. return OF;
  12741. }
  12742. namespace {
  12743. class SCEVPredicateRewriter : public SCEVRewriteVisitor<SCEVPredicateRewriter> {
  12744. public:
  12745. /// Rewrites \p S in the context of a loop L and the SCEV predication
  12746. /// infrastructure.
  12747. ///
  12748. /// If \p Pred is non-null, the SCEV expression is rewritten to respect the
  12749. /// equivalences present in \p Pred.
  12750. ///
  12751. /// If \p NewPreds is non-null, rewrite is free to add further predicates to
  12752. /// \p NewPreds such that the result will be an AddRecExpr.
  12753. static const SCEV *rewrite(const SCEV *S, const Loop *L, ScalarEvolution &SE,
  12754. SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
  12755. const SCEVPredicate *Pred) {
  12756. SCEVPredicateRewriter Rewriter(L, SE, NewPreds, Pred);
  12757. return Rewriter.visit(S);
  12758. }
  12759. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  12760. if (Pred) {
  12761. if (auto *U = dyn_cast<SCEVUnionPredicate>(Pred)) {
  12762. for (const auto *Pred : U->getPredicates())
  12763. if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred))
  12764. if (IPred->getLHS() == Expr &&
  12765. IPred->getPredicate() == ICmpInst::ICMP_EQ)
  12766. return IPred->getRHS();
  12767. } else if (const auto *IPred = dyn_cast<SCEVComparePredicate>(Pred)) {
  12768. if (IPred->getLHS() == Expr &&
  12769. IPred->getPredicate() == ICmpInst::ICMP_EQ)
  12770. return IPred->getRHS();
  12771. }
  12772. }
  12773. return convertToAddRecWithPreds(Expr);
  12774. }
  12775. const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
  12776. const SCEV *Operand = visit(Expr->getOperand());
  12777. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
  12778. if (AR && AR->getLoop() == L && AR->isAffine()) {
  12779. // This couldn't be folded because the operand didn't have the nuw
  12780. // flag. Add the nusw flag as an assumption that we could make.
  12781. const SCEV *Step = AR->getStepRecurrence(SE);
  12782. Type *Ty = Expr->getType();
  12783. if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNUSW))
  12784. return SE.getAddRecExpr(SE.getZeroExtendExpr(AR->getStart(), Ty),
  12785. SE.getSignExtendExpr(Step, Ty), L,
  12786. AR->getNoWrapFlags());
  12787. }
  12788. return SE.getZeroExtendExpr(Operand, Expr->getType());
  12789. }
  12790. const SCEV *visitSignExtendExpr(const SCEVSignExtendExpr *Expr) {
  12791. const SCEV *Operand = visit(Expr->getOperand());
  12792. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Operand);
  12793. if (AR && AR->getLoop() == L && AR->isAffine()) {
  12794. // This couldn't be folded because the operand didn't have the nsw
  12795. // flag. Add the nssw flag as an assumption that we could make.
  12796. const SCEV *Step = AR->getStepRecurrence(SE);
  12797. Type *Ty = Expr->getType();
  12798. if (addOverflowAssumption(AR, SCEVWrapPredicate::IncrementNSSW))
  12799. return SE.getAddRecExpr(SE.getSignExtendExpr(AR->getStart(), Ty),
  12800. SE.getSignExtendExpr(Step, Ty), L,
  12801. AR->getNoWrapFlags());
  12802. }
  12803. return SE.getSignExtendExpr(Operand, Expr->getType());
  12804. }
  12805. private:
  12806. explicit SCEVPredicateRewriter(const Loop *L, ScalarEvolution &SE,
  12807. SmallPtrSetImpl<const SCEVPredicate *> *NewPreds,
  12808. const SCEVPredicate *Pred)
  12809. : SCEVRewriteVisitor(SE), NewPreds(NewPreds), Pred(Pred), L(L) {}
  12810. bool addOverflowAssumption(const SCEVPredicate *P) {
  12811. if (!NewPreds) {
  12812. // Check if we've already made this assumption.
  12813. return Pred && Pred->implies(P);
  12814. }
  12815. NewPreds->insert(P);
  12816. return true;
  12817. }
  12818. bool addOverflowAssumption(const SCEVAddRecExpr *AR,
  12819. SCEVWrapPredicate::IncrementWrapFlags AddedFlags) {
  12820. auto *A = SE.getWrapPredicate(AR, AddedFlags);
  12821. return addOverflowAssumption(A);
  12822. }
  12823. // If \p Expr represents a PHINode, we try to see if it can be represented
  12824. // as an AddRec, possibly under a predicate (PHISCEVPred). If it is possible
  12825. // to add this predicate as a runtime overflow check, we return the AddRec.
  12826. // If \p Expr does not meet these conditions (is not a PHI node, or we
  12827. // couldn't create an AddRec for it, or couldn't add the predicate), we just
  12828. // return \p Expr.
  12829. const SCEV *convertToAddRecWithPreds(const SCEVUnknown *Expr) {
  12830. if (!isa<PHINode>(Expr->getValue()))
  12831. return Expr;
  12832. std::optional<
  12833. std::pair<const SCEV *, SmallVector<const SCEVPredicate *, 3>>>
  12834. PredicatedRewrite = SE.createAddRecFromPHIWithCasts(Expr);
  12835. if (!PredicatedRewrite)
  12836. return Expr;
  12837. for (const auto *P : PredicatedRewrite->second){
  12838. // Wrap predicates from outer loops are not supported.
  12839. if (auto *WP = dyn_cast<const SCEVWrapPredicate>(P)) {
  12840. if (L != WP->getExpr()->getLoop())
  12841. return Expr;
  12842. }
  12843. if (!addOverflowAssumption(P))
  12844. return Expr;
  12845. }
  12846. return PredicatedRewrite->first;
  12847. }
  12848. SmallPtrSetImpl<const SCEVPredicate *> *NewPreds;
  12849. const SCEVPredicate *Pred;
  12850. const Loop *L;
  12851. };
  12852. } // end anonymous namespace
  12853. const SCEV *
  12854. ScalarEvolution::rewriteUsingPredicate(const SCEV *S, const Loop *L,
  12855. const SCEVPredicate &Preds) {
  12856. return SCEVPredicateRewriter::rewrite(S, L, *this, nullptr, &Preds);
  12857. }
  12858. const SCEVAddRecExpr *ScalarEvolution::convertSCEVToAddRecWithPredicates(
  12859. const SCEV *S, const Loop *L,
  12860. SmallPtrSetImpl<const SCEVPredicate *> &Preds) {
  12861. SmallPtrSet<const SCEVPredicate *, 4> TransformPreds;
  12862. S = SCEVPredicateRewriter::rewrite(S, L, *this, &TransformPreds, nullptr);
  12863. auto *AddRec = dyn_cast<SCEVAddRecExpr>(S);
  12864. if (!AddRec)
  12865. return nullptr;
  12866. // Since the transformation was successful, we can now transfer the SCEV
  12867. // predicates.
  12868. for (const auto *P : TransformPreds)
  12869. Preds.insert(P);
  12870. return AddRec;
  12871. }
  12872. /// SCEV predicates
  12873. SCEVPredicate::SCEVPredicate(const FoldingSetNodeIDRef ID,
  12874. SCEVPredicateKind Kind)
  12875. : FastID(ID), Kind(Kind) {}
  12876. SCEVComparePredicate::SCEVComparePredicate(const FoldingSetNodeIDRef ID,
  12877. const ICmpInst::Predicate Pred,
  12878. const SCEV *LHS, const SCEV *RHS)
  12879. : SCEVPredicate(ID, P_Compare), Pred(Pred), LHS(LHS), RHS(RHS) {
  12880. assert(LHS->getType() == RHS->getType() && "LHS and RHS types don't match");
  12881. assert(LHS != RHS && "LHS and RHS are the same SCEV");
  12882. }
  12883. bool SCEVComparePredicate::implies(const SCEVPredicate *N) const {
  12884. const auto *Op = dyn_cast<SCEVComparePredicate>(N);
  12885. if (!Op)
  12886. return false;
  12887. if (Pred != ICmpInst::ICMP_EQ)
  12888. return false;
  12889. return Op->LHS == LHS && Op->RHS == RHS;
  12890. }
  12891. bool SCEVComparePredicate::isAlwaysTrue() const { return false; }
  12892. void SCEVComparePredicate::print(raw_ostream &OS, unsigned Depth) const {
  12893. if (Pred == ICmpInst::ICMP_EQ)
  12894. OS.indent(Depth) << "Equal predicate: " << *LHS << " == " << *RHS << "\n";
  12895. else
  12896. OS.indent(Depth) << "Compare predicate: " << *LHS
  12897. << " " << CmpInst::getPredicateName(Pred) << ") "
  12898. << *RHS << "\n";
  12899. }
  12900. SCEVWrapPredicate::SCEVWrapPredicate(const FoldingSetNodeIDRef ID,
  12901. const SCEVAddRecExpr *AR,
  12902. IncrementWrapFlags Flags)
  12903. : SCEVPredicate(ID, P_Wrap), AR(AR), Flags(Flags) {}
  12904. const SCEVAddRecExpr *SCEVWrapPredicate::getExpr() const { return AR; }
  12905. bool SCEVWrapPredicate::implies(const SCEVPredicate *N) const {
  12906. const auto *Op = dyn_cast<SCEVWrapPredicate>(N);
  12907. return Op && Op->AR == AR && setFlags(Flags, Op->Flags) == Flags;
  12908. }
  12909. bool SCEVWrapPredicate::isAlwaysTrue() const {
  12910. SCEV::NoWrapFlags ScevFlags = AR->getNoWrapFlags();
  12911. IncrementWrapFlags IFlags = Flags;
  12912. if (ScalarEvolution::setFlags(ScevFlags, SCEV::FlagNSW) == ScevFlags)
  12913. IFlags = clearFlags(IFlags, IncrementNSSW);
  12914. return IFlags == IncrementAnyWrap;
  12915. }
  12916. void SCEVWrapPredicate::print(raw_ostream &OS, unsigned Depth) const {
  12917. OS.indent(Depth) << *getExpr() << " Added Flags: ";
  12918. if (SCEVWrapPredicate::IncrementNUSW & getFlags())
  12919. OS << "<nusw>";
  12920. if (SCEVWrapPredicate::IncrementNSSW & getFlags())
  12921. OS << "<nssw>";
  12922. OS << "\n";
  12923. }
  12924. SCEVWrapPredicate::IncrementWrapFlags
  12925. SCEVWrapPredicate::getImpliedFlags(const SCEVAddRecExpr *AR,
  12926. ScalarEvolution &SE) {
  12927. IncrementWrapFlags ImpliedFlags = IncrementAnyWrap;
  12928. SCEV::NoWrapFlags StaticFlags = AR->getNoWrapFlags();
  12929. // We can safely transfer the NSW flag as NSSW.
  12930. if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNSW) == StaticFlags)
  12931. ImpliedFlags = IncrementNSSW;
  12932. if (ScalarEvolution::setFlags(StaticFlags, SCEV::FlagNUW) == StaticFlags) {
  12933. // If the increment is positive, the SCEV NUW flag will also imply the
  12934. // WrapPredicate NUSW flag.
  12935. if (const auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(SE)))
  12936. if (Step->getValue()->getValue().isNonNegative())
  12937. ImpliedFlags = setFlags(ImpliedFlags, IncrementNUSW);
  12938. }
  12939. return ImpliedFlags;
  12940. }
  12941. /// Union predicates don't get cached so create a dummy set ID for it.
  12942. SCEVUnionPredicate::SCEVUnionPredicate(ArrayRef<const SCEVPredicate *> Preds)
  12943. : SCEVPredicate(FoldingSetNodeIDRef(nullptr, 0), P_Union) {
  12944. for (const auto *P : Preds)
  12945. add(P);
  12946. }
  12947. bool SCEVUnionPredicate::isAlwaysTrue() const {
  12948. return all_of(Preds,
  12949. [](const SCEVPredicate *I) { return I->isAlwaysTrue(); });
  12950. }
  12951. bool SCEVUnionPredicate::implies(const SCEVPredicate *N) const {
  12952. if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N))
  12953. return all_of(Set->Preds,
  12954. [this](const SCEVPredicate *I) { return this->implies(I); });
  12955. return any_of(Preds,
  12956. [N](const SCEVPredicate *I) { return I->implies(N); });
  12957. }
  12958. void SCEVUnionPredicate::print(raw_ostream &OS, unsigned Depth) const {
  12959. for (const auto *Pred : Preds)
  12960. Pred->print(OS, Depth);
  12961. }
  12962. void SCEVUnionPredicate::add(const SCEVPredicate *N) {
  12963. if (const auto *Set = dyn_cast<SCEVUnionPredicate>(N)) {
  12964. for (const auto *Pred : Set->Preds)
  12965. add(Pred);
  12966. return;
  12967. }
  12968. Preds.push_back(N);
  12969. }
  12970. PredicatedScalarEvolution::PredicatedScalarEvolution(ScalarEvolution &SE,
  12971. Loop &L)
  12972. : SE(SE), L(L) {
  12973. SmallVector<const SCEVPredicate*, 4> Empty;
  12974. Preds = std::make_unique<SCEVUnionPredicate>(Empty);
  12975. }
  12976. void ScalarEvolution::registerUser(const SCEV *User,
  12977. ArrayRef<const SCEV *> Ops) {
  12978. for (const auto *Op : Ops)
  12979. // We do not expect that forgetting cached data for SCEVConstants will ever
  12980. // open any prospects for sharpening or introduce any correctness issues,
  12981. // so we don't bother storing their dependencies.
  12982. if (!isa<SCEVConstant>(Op))
  12983. SCEVUsers[Op].insert(User);
  12984. }
  12985. const SCEV *PredicatedScalarEvolution::getSCEV(Value *V) {
  12986. const SCEV *Expr = SE.getSCEV(V);
  12987. RewriteEntry &Entry = RewriteMap[Expr];
  12988. // If we already have an entry and the version matches, return it.
  12989. if (Entry.second && Generation == Entry.first)
  12990. return Entry.second;
  12991. // We found an entry but it's stale. Rewrite the stale entry
  12992. // according to the current predicate.
  12993. if (Entry.second)
  12994. Expr = Entry.second;
  12995. const SCEV *NewSCEV = SE.rewriteUsingPredicate(Expr, &L, *Preds);
  12996. Entry = {Generation, NewSCEV};
  12997. return NewSCEV;
  12998. }
  12999. const SCEV *PredicatedScalarEvolution::getBackedgeTakenCount() {
  13000. if (!BackedgeCount) {
  13001. SmallVector<const SCEVPredicate *, 4> Preds;
  13002. BackedgeCount = SE.getPredicatedBackedgeTakenCount(&L, Preds);
  13003. for (const auto *P : Preds)
  13004. addPredicate(*P);
  13005. }
  13006. return BackedgeCount;
  13007. }
  13008. void PredicatedScalarEvolution::addPredicate(const SCEVPredicate &Pred) {
  13009. if (Preds->implies(&Pred))
  13010. return;
  13011. auto &OldPreds = Preds->getPredicates();
  13012. SmallVector<const SCEVPredicate*, 4> NewPreds(OldPreds.begin(), OldPreds.end());
  13013. NewPreds.push_back(&Pred);
  13014. Preds = std::make_unique<SCEVUnionPredicate>(NewPreds);
  13015. updateGeneration();
  13016. }
  13017. const SCEVPredicate &PredicatedScalarEvolution::getPredicate() const {
  13018. return *Preds;
  13019. }
  13020. void PredicatedScalarEvolution::updateGeneration() {
  13021. // If the generation number wrapped recompute everything.
  13022. if (++Generation == 0) {
  13023. for (auto &II : RewriteMap) {
  13024. const SCEV *Rewritten = II.second.second;
  13025. II.second = {Generation, SE.rewriteUsingPredicate(Rewritten, &L, *Preds)};
  13026. }
  13027. }
  13028. }
  13029. void PredicatedScalarEvolution::setNoOverflow(
  13030. Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
  13031. const SCEV *Expr = getSCEV(V);
  13032. const auto *AR = cast<SCEVAddRecExpr>(Expr);
  13033. auto ImpliedFlags = SCEVWrapPredicate::getImpliedFlags(AR, SE);
  13034. // Clear the statically implied flags.
  13035. Flags = SCEVWrapPredicate::clearFlags(Flags, ImpliedFlags);
  13036. addPredicate(*SE.getWrapPredicate(AR, Flags));
  13037. auto II = FlagsMap.insert({V, Flags});
  13038. if (!II.second)
  13039. II.first->second = SCEVWrapPredicate::setFlags(Flags, II.first->second);
  13040. }
  13041. bool PredicatedScalarEvolution::hasNoOverflow(
  13042. Value *V, SCEVWrapPredicate::IncrementWrapFlags Flags) {
  13043. const SCEV *Expr = getSCEV(V);
  13044. const auto *AR = cast<SCEVAddRecExpr>(Expr);
  13045. Flags = SCEVWrapPredicate::clearFlags(
  13046. Flags, SCEVWrapPredicate::getImpliedFlags(AR, SE));
  13047. auto II = FlagsMap.find(V);
  13048. if (II != FlagsMap.end())
  13049. Flags = SCEVWrapPredicate::clearFlags(Flags, II->second);
  13050. return Flags == SCEVWrapPredicate::IncrementAnyWrap;
  13051. }
  13052. const SCEVAddRecExpr *PredicatedScalarEvolution::getAsAddRec(Value *V) {
  13053. const SCEV *Expr = this->getSCEV(V);
  13054. SmallPtrSet<const SCEVPredicate *, 4> NewPreds;
  13055. auto *New = SE.convertSCEVToAddRecWithPredicates(Expr, &L, NewPreds);
  13056. if (!New)
  13057. return nullptr;
  13058. for (const auto *P : NewPreds)
  13059. addPredicate(*P);
  13060. RewriteMap[SE.getSCEV(V)] = {Generation, New};
  13061. return New;
  13062. }
  13063. PredicatedScalarEvolution::PredicatedScalarEvolution(
  13064. const PredicatedScalarEvolution &Init)
  13065. : RewriteMap(Init.RewriteMap), SE(Init.SE), L(Init.L),
  13066. Preds(std::make_unique<SCEVUnionPredicate>(Init.Preds->getPredicates())),
  13067. Generation(Init.Generation), BackedgeCount(Init.BackedgeCount) {
  13068. for (auto I : Init.FlagsMap)
  13069. FlagsMap.insert(I);
  13070. }
  13071. void PredicatedScalarEvolution::print(raw_ostream &OS, unsigned Depth) const {
  13072. // For each block.
  13073. for (auto *BB : L.getBlocks())
  13074. for (auto &I : *BB) {
  13075. if (!SE.isSCEVable(I.getType()))
  13076. continue;
  13077. auto *Expr = SE.getSCEV(&I);
  13078. auto II = RewriteMap.find(Expr);
  13079. if (II == RewriteMap.end())
  13080. continue;
  13081. // Don't print things that are not interesting.
  13082. if (II->second.second == Expr)
  13083. continue;
  13084. OS.indent(Depth) << "[PSE]" << I << ":\n";
  13085. OS.indent(Depth + 2) << *Expr << "\n";
  13086. OS.indent(Depth + 2) << "--> " << *II->second.second << "\n";
  13087. }
  13088. }
  13089. // Match the mathematical pattern A - (A / B) * B, where A and B can be
  13090. // arbitrary expressions. Also match zext (trunc A to iB) to iY, which is used
  13091. // for URem with constant power-of-2 second operands.
  13092. // It's not always easy, as A and B can be folded (imagine A is X / 2, and B is
  13093. // 4, A / B becomes X / 8).
  13094. bool ScalarEvolution::matchURem(const SCEV *Expr, const SCEV *&LHS,
  13095. const SCEV *&RHS) {
  13096. // Try to match 'zext (trunc A to iB) to iY', which is used
  13097. // for URem with constant power-of-2 second operands. Make sure the size of
  13098. // the operand A matches the size of the whole expressions.
  13099. if (const auto *ZExt = dyn_cast<SCEVZeroExtendExpr>(Expr))
  13100. if (const auto *Trunc = dyn_cast<SCEVTruncateExpr>(ZExt->getOperand(0))) {
  13101. LHS = Trunc->getOperand();
  13102. // Bail out if the type of the LHS is larger than the type of the
  13103. // expression for now.
  13104. if (getTypeSizeInBits(LHS->getType()) >
  13105. getTypeSizeInBits(Expr->getType()))
  13106. return false;
  13107. if (LHS->getType() != Expr->getType())
  13108. LHS = getZeroExtendExpr(LHS, Expr->getType());
  13109. RHS = getConstant(APInt(getTypeSizeInBits(Expr->getType()), 1)
  13110. << getTypeSizeInBits(Trunc->getType()));
  13111. return true;
  13112. }
  13113. const auto *Add = dyn_cast<SCEVAddExpr>(Expr);
  13114. if (Add == nullptr || Add->getNumOperands() != 2)
  13115. return false;
  13116. const SCEV *A = Add->getOperand(1);
  13117. const auto *Mul = dyn_cast<SCEVMulExpr>(Add->getOperand(0));
  13118. if (Mul == nullptr)
  13119. return false;
  13120. const auto MatchURemWithDivisor = [&](const SCEV *B) {
  13121. // (SomeExpr + (-(SomeExpr / B) * B)).
  13122. if (Expr == getURemExpr(A, B)) {
  13123. LHS = A;
  13124. RHS = B;
  13125. return true;
  13126. }
  13127. return false;
  13128. };
  13129. // (SomeExpr + (-1 * (SomeExpr / B) * B)).
  13130. if (Mul->getNumOperands() == 3 && isa<SCEVConstant>(Mul->getOperand(0)))
  13131. return MatchURemWithDivisor(Mul->getOperand(1)) ||
  13132. MatchURemWithDivisor(Mul->getOperand(2));
  13133. // (SomeExpr + ((-SomeExpr / B) * B)) or (SomeExpr + ((SomeExpr / B) * -B)).
  13134. if (Mul->getNumOperands() == 2)
  13135. return MatchURemWithDivisor(Mul->getOperand(1)) ||
  13136. MatchURemWithDivisor(Mul->getOperand(0)) ||
  13137. MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(1))) ||
  13138. MatchURemWithDivisor(getNegativeSCEV(Mul->getOperand(0)));
  13139. return false;
  13140. }
  13141. const SCEV *
  13142. ScalarEvolution::computeSymbolicMaxBackedgeTakenCount(const Loop *L) {
  13143. SmallVector<BasicBlock*, 16> ExitingBlocks;
  13144. L->getExitingBlocks(ExitingBlocks);
  13145. // Form an expression for the maximum exit count possible for this loop. We
  13146. // merge the max and exact information to approximate a version of
  13147. // getConstantMaxBackedgeTakenCount which isn't restricted to just constants.
  13148. SmallVector<const SCEV*, 4> ExitCounts;
  13149. for (BasicBlock *ExitingBB : ExitingBlocks) {
  13150. const SCEV *ExitCount =
  13151. getExitCount(L, ExitingBB, ScalarEvolution::SymbolicMaximum);
  13152. if (!isa<SCEVCouldNotCompute>(ExitCount)) {
  13153. assert(DT.dominates(ExitingBB, L->getLoopLatch()) &&
  13154. "We should only have known counts for exiting blocks that "
  13155. "dominate latch!");
  13156. ExitCounts.push_back(ExitCount);
  13157. }
  13158. }
  13159. if (ExitCounts.empty())
  13160. return getCouldNotCompute();
  13161. return getUMinFromMismatchedTypes(ExitCounts, /*Sequential*/ true);
  13162. }
  13163. /// A rewriter to replace SCEV expressions in Map with the corresponding entry
  13164. /// in the map. It skips AddRecExpr because we cannot guarantee that the
  13165. /// replacement is loop invariant in the loop of the AddRec.
  13166. ///
  13167. /// At the moment only rewriting SCEVUnknown and SCEVZeroExtendExpr is
  13168. /// supported.
  13169. class SCEVLoopGuardRewriter : public SCEVRewriteVisitor<SCEVLoopGuardRewriter> {
  13170. const DenseMap<const SCEV *, const SCEV *> &Map;
  13171. public:
  13172. SCEVLoopGuardRewriter(ScalarEvolution &SE,
  13173. DenseMap<const SCEV *, const SCEV *> &M)
  13174. : SCEVRewriteVisitor(SE), Map(M) {}
  13175. const SCEV *visitAddRecExpr(const SCEVAddRecExpr *Expr) { return Expr; }
  13176. const SCEV *visitUnknown(const SCEVUnknown *Expr) {
  13177. auto I = Map.find(Expr);
  13178. if (I == Map.end())
  13179. return Expr;
  13180. return I->second;
  13181. }
  13182. const SCEV *visitZeroExtendExpr(const SCEVZeroExtendExpr *Expr) {
  13183. auto I = Map.find(Expr);
  13184. if (I == Map.end())
  13185. return SCEVRewriteVisitor<SCEVLoopGuardRewriter>::visitZeroExtendExpr(
  13186. Expr);
  13187. return I->second;
  13188. }
  13189. };
  13190. const SCEV *ScalarEvolution::applyLoopGuards(const SCEV *Expr, const Loop *L) {
  13191. SmallVector<const SCEV *> ExprsToRewrite;
  13192. auto CollectCondition = [&](ICmpInst::Predicate Predicate, const SCEV *LHS,
  13193. const SCEV *RHS,
  13194. DenseMap<const SCEV *, const SCEV *>
  13195. &RewriteMap) {
  13196. // WARNING: It is generally unsound to apply any wrap flags to the proposed
  13197. // replacement SCEV which isn't directly implied by the structure of that
  13198. // SCEV. In particular, using contextual facts to imply flags is *NOT*
  13199. // legal. See the scoping rules for flags in the header to understand why.
  13200. // If LHS is a constant, apply information to the other expression.
  13201. if (isa<SCEVConstant>(LHS)) {
  13202. std::swap(LHS, RHS);
  13203. Predicate = CmpInst::getSwappedPredicate(Predicate);
  13204. }
  13205. // Check for a condition of the form (-C1 + X < C2). InstCombine will
  13206. // create this form when combining two checks of the form (X u< C2 + C1) and
  13207. // (X >=u C1).
  13208. auto MatchRangeCheckIdiom = [this, Predicate, LHS, RHS, &RewriteMap,
  13209. &ExprsToRewrite]() {
  13210. auto *AddExpr = dyn_cast<SCEVAddExpr>(LHS);
  13211. if (!AddExpr || AddExpr->getNumOperands() != 2)
  13212. return false;
  13213. auto *C1 = dyn_cast<SCEVConstant>(AddExpr->getOperand(0));
  13214. auto *LHSUnknown = dyn_cast<SCEVUnknown>(AddExpr->getOperand(1));
  13215. auto *C2 = dyn_cast<SCEVConstant>(RHS);
  13216. if (!C1 || !C2 || !LHSUnknown)
  13217. return false;
  13218. auto ExactRegion =
  13219. ConstantRange::makeExactICmpRegion(Predicate, C2->getAPInt())
  13220. .sub(C1->getAPInt());
  13221. // Bail out, unless we have a non-wrapping, monotonic range.
  13222. if (ExactRegion.isWrappedSet() || ExactRegion.isFullSet())
  13223. return false;
  13224. auto I = RewriteMap.find(LHSUnknown);
  13225. const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHSUnknown;
  13226. RewriteMap[LHSUnknown] = getUMaxExpr(
  13227. getConstant(ExactRegion.getUnsignedMin()),
  13228. getUMinExpr(RewrittenLHS, getConstant(ExactRegion.getUnsignedMax())));
  13229. ExprsToRewrite.push_back(LHSUnknown);
  13230. return true;
  13231. };
  13232. if (MatchRangeCheckIdiom())
  13233. return;
  13234. // If we have LHS == 0, check if LHS is computing a property of some unknown
  13235. // SCEV %v which we can rewrite %v to express explicitly.
  13236. const SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS);
  13237. if (Predicate == CmpInst::ICMP_EQ && RHSC &&
  13238. RHSC->getValue()->isNullValue()) {
  13239. // If LHS is A % B, i.e. A % B == 0, rewrite A to (A /u B) * B to
  13240. // explicitly express that.
  13241. const SCEV *URemLHS = nullptr;
  13242. const SCEV *URemRHS = nullptr;
  13243. if (matchURem(LHS, URemLHS, URemRHS)) {
  13244. if (const SCEVUnknown *LHSUnknown = dyn_cast<SCEVUnknown>(URemLHS)) {
  13245. const auto *Multiple = getMulExpr(getUDivExpr(URemLHS, URemRHS), URemRHS);
  13246. RewriteMap[LHSUnknown] = Multiple;
  13247. ExprsToRewrite.push_back(LHSUnknown);
  13248. return;
  13249. }
  13250. }
  13251. }
  13252. // Do not apply information for constants or if RHS contains an AddRec.
  13253. if (isa<SCEVConstant>(LHS) || containsAddRecurrence(RHS))
  13254. return;
  13255. // If RHS is SCEVUnknown, make sure the information is applied to it.
  13256. if (!isa<SCEVUnknown>(LHS) && isa<SCEVUnknown>(RHS)) {
  13257. std::swap(LHS, RHS);
  13258. Predicate = CmpInst::getSwappedPredicate(Predicate);
  13259. }
  13260. // Limit to expressions that can be rewritten.
  13261. if (!isa<SCEVUnknown>(LHS) && !isa<SCEVZeroExtendExpr>(LHS))
  13262. return;
  13263. // Check whether LHS has already been rewritten. In that case we want to
  13264. // chain further rewrites onto the already rewritten value.
  13265. auto I = RewriteMap.find(LHS);
  13266. const SCEV *RewrittenLHS = I != RewriteMap.end() ? I->second : LHS;
  13267. const SCEV *RewrittenRHS = nullptr;
  13268. switch (Predicate) {
  13269. case CmpInst::ICMP_ULT:
  13270. RewrittenRHS =
  13271. getUMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
  13272. break;
  13273. case CmpInst::ICMP_SLT:
  13274. RewrittenRHS =
  13275. getSMinExpr(RewrittenLHS, getMinusSCEV(RHS, getOne(RHS->getType())));
  13276. break;
  13277. case CmpInst::ICMP_ULE:
  13278. RewrittenRHS = getUMinExpr(RewrittenLHS, RHS);
  13279. break;
  13280. case CmpInst::ICMP_SLE:
  13281. RewrittenRHS = getSMinExpr(RewrittenLHS, RHS);
  13282. break;
  13283. case CmpInst::ICMP_UGT:
  13284. RewrittenRHS =
  13285. getUMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
  13286. break;
  13287. case CmpInst::ICMP_SGT:
  13288. RewrittenRHS =
  13289. getSMaxExpr(RewrittenLHS, getAddExpr(RHS, getOne(RHS->getType())));
  13290. break;
  13291. case CmpInst::ICMP_UGE:
  13292. RewrittenRHS = getUMaxExpr(RewrittenLHS, RHS);
  13293. break;
  13294. case CmpInst::ICMP_SGE:
  13295. RewrittenRHS = getSMaxExpr(RewrittenLHS, RHS);
  13296. break;
  13297. case CmpInst::ICMP_EQ:
  13298. if (isa<SCEVConstant>(RHS))
  13299. RewrittenRHS = RHS;
  13300. break;
  13301. case CmpInst::ICMP_NE:
  13302. if (isa<SCEVConstant>(RHS) &&
  13303. cast<SCEVConstant>(RHS)->getValue()->isNullValue())
  13304. RewrittenRHS = getUMaxExpr(RewrittenLHS, getOne(RHS->getType()));
  13305. break;
  13306. default:
  13307. break;
  13308. }
  13309. if (RewrittenRHS) {
  13310. RewriteMap[LHS] = RewrittenRHS;
  13311. if (LHS == RewrittenLHS)
  13312. ExprsToRewrite.push_back(LHS);
  13313. }
  13314. };
  13315. BasicBlock *Header = L->getHeader();
  13316. SmallVector<PointerIntPair<Value *, 1, bool>> Terms;
  13317. // First, collect information from assumptions dominating the loop.
  13318. for (auto &AssumeVH : AC.assumptions()) {
  13319. if (!AssumeVH)
  13320. continue;
  13321. auto *AssumeI = cast<CallInst>(AssumeVH);
  13322. if (!DT.dominates(AssumeI, Header))
  13323. continue;
  13324. Terms.emplace_back(AssumeI->getOperand(0), true);
  13325. }
  13326. // Second, collect conditions from dominating branches. Starting at the loop
  13327. // predecessor, climb up the predecessor chain, as long as there are
  13328. // predecessors that can be found that have unique successors leading to the
  13329. // original header.
  13330. // TODO: share this logic with isLoopEntryGuardedByCond.
  13331. for (std::pair<const BasicBlock *, const BasicBlock *> Pair(
  13332. L->getLoopPredecessor(), Header);
  13333. Pair.first; Pair = getPredecessorWithUniqueSuccessorForBB(Pair.first)) {
  13334. const BranchInst *LoopEntryPredicate =
  13335. dyn_cast<BranchInst>(Pair.first->getTerminator());
  13336. if (!LoopEntryPredicate || LoopEntryPredicate->isUnconditional())
  13337. continue;
  13338. Terms.emplace_back(LoopEntryPredicate->getCondition(),
  13339. LoopEntryPredicate->getSuccessor(0) == Pair.second);
  13340. }
  13341. // Now apply the information from the collected conditions to RewriteMap.
  13342. // Conditions are processed in reverse order, so the earliest conditions is
  13343. // processed first. This ensures the SCEVs with the shortest dependency chains
  13344. // are constructed first.
  13345. DenseMap<const SCEV *, const SCEV *> RewriteMap;
  13346. for (auto [Term, EnterIfTrue] : reverse(Terms)) {
  13347. SmallVector<Value *, 8> Worklist;
  13348. SmallPtrSet<Value *, 8> Visited;
  13349. Worklist.push_back(Term);
  13350. while (!Worklist.empty()) {
  13351. Value *Cond = Worklist.pop_back_val();
  13352. if (!Visited.insert(Cond).second)
  13353. continue;
  13354. if (auto *Cmp = dyn_cast<ICmpInst>(Cond)) {
  13355. auto Predicate =
  13356. EnterIfTrue ? Cmp->getPredicate() : Cmp->getInversePredicate();
  13357. const auto *LHS = getSCEV(Cmp->getOperand(0));
  13358. const auto *RHS = getSCEV(Cmp->getOperand(1));
  13359. CollectCondition(Predicate, LHS, RHS, RewriteMap);
  13360. continue;
  13361. }
  13362. Value *L, *R;
  13363. if (EnterIfTrue ? match(Cond, m_LogicalAnd(m_Value(L), m_Value(R)))
  13364. : match(Cond, m_LogicalOr(m_Value(L), m_Value(R)))) {
  13365. Worklist.push_back(L);
  13366. Worklist.push_back(R);
  13367. }
  13368. }
  13369. }
  13370. if (RewriteMap.empty())
  13371. return Expr;
  13372. // Now that all rewrite information is collect, rewrite the collected
  13373. // expressions with the information in the map. This applies information to
  13374. // sub-expressions.
  13375. if (ExprsToRewrite.size() > 1) {
  13376. for (const SCEV *Expr : ExprsToRewrite) {
  13377. const SCEV *RewriteTo = RewriteMap[Expr];
  13378. RewriteMap.erase(Expr);
  13379. SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
  13380. RewriteMap.insert({Expr, Rewriter.visit(RewriteTo)});
  13381. }
  13382. }
  13383. SCEVLoopGuardRewriter Rewriter(*this, RewriteMap);
  13384. return Rewriter.visit(Expr);
  13385. }