CodeGenPrepare.cpp 273 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  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 pass munges the code in the input function to better prepare it for
  10. // SelectionDAG-based code generation. This works around limitations in it's
  11. // basic-block-at-a-time approach. It should eventually be removed.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/MapVector.h"
  18. #include "llvm/ADT/PointerIntPair.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/BlockFrequencyInfo.h"
  24. #include "llvm/Analysis/BranchProbabilityInfo.h"
  25. #include "llvm/Analysis/ConstantFolding.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/LoopInfo.h"
  28. #include "llvm/Analysis/MemoryBuiltins.h"
  29. #include "llvm/Analysis/ProfileSummaryInfo.h"
  30. #include "llvm/Analysis/TargetLibraryInfo.h"
  31. #include "llvm/Analysis/TargetTransformInfo.h"
  32. #include "llvm/Transforms/Utils/Local.h"
  33. #include "llvm/Analysis/ValueTracking.h"
  34. #include "llvm/Analysis/VectorUtils.h"
  35. #include "llvm/CodeGen/Analysis.h"
  36. #include "llvm/CodeGen/ISDOpcodes.h"
  37. #include "llvm/CodeGen/SelectionDAGNodes.h"
  38. #include "llvm/CodeGen/TargetLowering.h"
  39. #include "llvm/CodeGen/TargetPassConfig.h"
  40. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  41. #include "llvm/CodeGen/ValueTypes.h"
  42. #include "llvm/Config/llvm-config.h"
  43. #include "llvm/IR/Argument.h"
  44. #include "llvm/IR/Attributes.h"
  45. #include "llvm/IR/BasicBlock.h"
  46. #include "llvm/IR/CallSite.h"
  47. #include "llvm/IR/Constant.h"
  48. #include "llvm/IR/Constants.h"
  49. #include "llvm/IR/DataLayout.h"
  50. #include "llvm/IR/DerivedTypes.h"
  51. #include "llvm/IR/Dominators.h"
  52. #include "llvm/IR/Function.h"
  53. #include "llvm/IR/GetElementPtrTypeIterator.h"
  54. #include "llvm/IR/GlobalValue.h"
  55. #include "llvm/IR/GlobalVariable.h"
  56. #include "llvm/IR/IRBuilder.h"
  57. #include "llvm/IR/InlineAsm.h"
  58. #include "llvm/IR/InstrTypes.h"
  59. #include "llvm/IR/Instruction.h"
  60. #include "llvm/IR/Instructions.h"
  61. #include "llvm/IR/IntrinsicInst.h"
  62. #include "llvm/IR/Intrinsics.h"
  63. #include "llvm/IR/LLVMContext.h"
  64. #include "llvm/IR/MDBuilder.h"
  65. #include "llvm/IR/Module.h"
  66. #include "llvm/IR/Operator.h"
  67. #include "llvm/IR/PatternMatch.h"
  68. #include "llvm/IR/Statepoint.h"
  69. #include "llvm/IR/Type.h"
  70. #include "llvm/IR/Use.h"
  71. #include "llvm/IR/User.h"
  72. #include "llvm/IR/Value.h"
  73. #include "llvm/IR/ValueHandle.h"
  74. #include "llvm/IR/ValueMap.h"
  75. #include "llvm/Pass.h"
  76. #include "llvm/Support/BlockFrequency.h"
  77. #include "llvm/Support/BranchProbability.h"
  78. #include "llvm/Support/Casting.h"
  79. #include "llvm/Support/CommandLine.h"
  80. #include "llvm/Support/Compiler.h"
  81. #include "llvm/Support/Debug.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/MachineValueType.h"
  84. #include "llvm/Support/MathExtras.h"
  85. #include "llvm/Support/raw_ostream.h"
  86. #include "llvm/Target/TargetMachine.h"
  87. #include "llvm/Target/TargetOptions.h"
  88. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  89. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  90. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  91. #include <algorithm>
  92. #include <cassert>
  93. #include <cstdint>
  94. #include <iterator>
  95. #include <limits>
  96. #include <memory>
  97. #include <utility>
  98. #include <vector>
  99. using namespace llvm;
  100. using namespace llvm::PatternMatch;
  101. #define DEBUG_TYPE "codegenprepare"
  102. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  103. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  104. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  105. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  106. "sunken Cmps");
  107. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  108. "of sunken Casts");
  109. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  110. "computations were sunk");
  111. STATISTIC(NumMemoryInstsPhiCreated,
  112. "Number of phis created when address "
  113. "computations were sunk to memory instructions");
  114. STATISTIC(NumMemoryInstsSelectCreated,
  115. "Number of select created when address "
  116. "computations were sunk to memory instructions");
  117. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  118. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  119. STATISTIC(NumAndsAdded,
  120. "Number of and mask instructions added to form ext loads");
  121. STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
  122. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  123. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  124. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  125. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  126. static cl::opt<bool> DisableBranchOpts(
  127. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  128. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  129. static cl::opt<bool>
  130. DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
  131. cl::desc("Disable GC optimizations in CodeGenPrepare"));
  132. static cl::opt<bool> DisableSelectToBranch(
  133. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  134. cl::desc("Disable select to branch conversion."));
  135. static cl::opt<bool> AddrSinkUsingGEPs(
  136. "addr-sink-using-gep", cl::Hidden, cl::init(true),
  137. cl::desc("Address sinking in CGP using GEPs."));
  138. static cl::opt<bool> EnableAndCmpSinking(
  139. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  140. cl::desc("Enable sinkinig and/cmp into branches."));
  141. static cl::opt<bool> DisableStoreExtract(
  142. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  143. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  144. static cl::opt<bool> StressStoreExtract(
  145. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  146. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  147. static cl::opt<bool> DisableExtLdPromotion(
  148. "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  149. cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
  150. "CodeGenPrepare"));
  151. static cl::opt<bool> StressExtLdPromotion(
  152. "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  153. cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
  154. "optimization in CodeGenPrepare"));
  155. static cl::opt<bool> DisablePreheaderProtect(
  156. "disable-preheader-prot", cl::Hidden, cl::init(false),
  157. cl::desc("Disable protection against removing loop preheaders"));
  158. static cl::opt<bool> ProfileGuidedSectionPrefix(
  159. "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
  160. cl::desc("Use profile info to add section prefix for hot/cold functions"));
  161. static cl::opt<unsigned> FreqRatioToSkipMerge(
  162. "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
  163. cl::desc("Skip merging empty blocks if (frequency of empty block) / "
  164. "(frequency of destination block) is greater than this ratio"));
  165. static cl::opt<bool> ForceSplitStore(
  166. "force-split-store", cl::Hidden, cl::init(false),
  167. cl::desc("Force store splitting no matter what the target query says."));
  168. static cl::opt<bool>
  169. EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
  170. cl::desc("Enable merging of redundant sexts when one is dominating"
  171. " the other."), cl::init(true));
  172. static cl::opt<bool> DisableComplexAddrModes(
  173. "disable-complex-addr-modes", cl::Hidden, cl::init(false),
  174. cl::desc("Disables combining addressing modes with different parts "
  175. "in optimizeMemoryInst."));
  176. static cl::opt<bool>
  177. AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
  178. cl::desc("Allow creation of Phis in Address sinking."));
  179. static cl::opt<bool>
  180. AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
  181. cl::desc("Allow creation of selects in Address sinking."));
  182. static cl::opt<bool> AddrSinkCombineBaseReg(
  183. "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
  184. cl::desc("Allow combining of BaseReg field in Address sinking."));
  185. static cl::opt<bool> AddrSinkCombineBaseGV(
  186. "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
  187. cl::desc("Allow combining of BaseGV field in Address sinking."));
  188. static cl::opt<bool> AddrSinkCombineBaseOffs(
  189. "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
  190. cl::desc("Allow combining of BaseOffs field in Address sinking."));
  191. static cl::opt<bool> AddrSinkCombineScaledReg(
  192. "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
  193. cl::desc("Allow combining of ScaledReg field in Address sinking."));
  194. static cl::opt<bool>
  195. EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
  196. cl::init(true),
  197. cl::desc("Enable splitting large offset of GEP."));
  198. namespace {
  199. enum ExtType {
  200. ZeroExtension, // Zero extension has been seen.
  201. SignExtension, // Sign extension has been seen.
  202. BothExtension // This extension type is used if we saw sext after
  203. // ZeroExtension had been set, or if we saw zext after
  204. // SignExtension had been set. It makes the type
  205. // information of a promoted instruction invalid.
  206. };
  207. using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
  208. using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
  209. using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
  210. using SExts = SmallVector<Instruction *, 16>;
  211. using ValueToSExts = DenseMap<Value *, SExts>;
  212. class TypePromotionTransaction;
  213. class CodeGenPrepare : public FunctionPass {
  214. const TargetMachine *TM = nullptr;
  215. const TargetSubtargetInfo *SubtargetInfo;
  216. const TargetLowering *TLI = nullptr;
  217. const TargetRegisterInfo *TRI;
  218. const TargetTransformInfo *TTI = nullptr;
  219. const TargetLibraryInfo *TLInfo;
  220. const LoopInfo *LI;
  221. std::unique_ptr<BlockFrequencyInfo> BFI;
  222. std::unique_ptr<BranchProbabilityInfo> BPI;
  223. /// As we scan instructions optimizing them, this is the next instruction
  224. /// to optimize. Transforms that can invalidate this should update it.
  225. BasicBlock::iterator CurInstIterator;
  226. /// Keeps track of non-local addresses that have been sunk into a block.
  227. /// This allows us to avoid inserting duplicate code for blocks with
  228. /// multiple load/stores of the same address. The usage of WeakTrackingVH
  229. /// enables SunkAddrs to be treated as a cache whose entries can be
  230. /// invalidated if a sunken address computation has been erased.
  231. ValueMap<Value*, WeakTrackingVH> SunkAddrs;
  232. /// Keeps track of all instructions inserted for the current function.
  233. SetOfInstrs InsertedInsts;
  234. /// Keeps track of the type of the related instruction before their
  235. /// promotion for the current function.
  236. InstrToOrigTy PromotedInsts;
  237. /// Keep track of instructions removed during promotion.
  238. SetOfInstrs RemovedInsts;
  239. /// Keep track of sext chains based on their initial value.
  240. DenseMap<Value *, Instruction *> SeenChainsForSExt;
  241. /// Keep track of GEPs accessing the same data structures such as structs or
  242. /// arrays that are candidates to be split later because of their large
  243. /// size.
  244. MapVector<
  245. AssertingVH<Value>,
  246. SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
  247. LargeOffsetGEPMap;
  248. /// Keep track of new GEP base after splitting the GEPs having large offset.
  249. SmallSet<AssertingVH<Value>, 2> NewGEPBases;
  250. /// Map serial numbers to Large offset GEPs.
  251. DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
  252. /// Keep track of SExt promoted.
  253. ValueToSExts ValToSExtendedUses;
  254. /// True if optimizing for size.
  255. bool OptSize;
  256. /// DataLayout for the Function being processed.
  257. const DataLayout *DL = nullptr;
  258. /// Building the dominator tree can be expensive, so we only build it
  259. /// lazily and update it when required.
  260. std::unique_ptr<DominatorTree> DT;
  261. public:
  262. static char ID; // Pass identification, replacement for typeid
  263. CodeGenPrepare() : FunctionPass(ID) {
  264. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  265. }
  266. bool runOnFunction(Function &F) override;
  267. StringRef getPassName() const override { return "CodeGen Prepare"; }
  268. void getAnalysisUsage(AnalysisUsage &AU) const override {
  269. // FIXME: When we can selectively preserve passes, preserve the domtree.
  270. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  271. AU.addRequired<TargetLibraryInfoWrapperPass>();
  272. AU.addRequired<TargetTransformInfoWrapperPass>();
  273. AU.addRequired<LoopInfoWrapperPass>();
  274. }
  275. private:
  276. template <typename F>
  277. void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
  278. // Substituting can cause recursive simplifications, which can invalidate
  279. // our iterator. Use a WeakTrackingVH to hold onto it in case this
  280. // happens.
  281. Value *CurValue = &*CurInstIterator;
  282. WeakTrackingVH IterHandle(CurValue);
  283. f();
  284. // If the iterator instruction was recursively deleted, start over at the
  285. // start of the block.
  286. if (IterHandle != CurValue) {
  287. CurInstIterator = BB->begin();
  288. SunkAddrs.clear();
  289. }
  290. }
  291. // Get the DominatorTree, building if necessary.
  292. DominatorTree &getDT(Function &F) {
  293. if (!DT)
  294. DT = std::make_unique<DominatorTree>(F);
  295. return *DT;
  296. }
  297. bool eliminateFallThrough(Function &F);
  298. bool eliminateMostlyEmptyBlocks(Function &F);
  299. BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
  300. bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  301. void eliminateMostlyEmptyBlock(BasicBlock *BB);
  302. bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
  303. bool isPreheader);
  304. bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
  305. bool optimizeInst(Instruction *I, bool &ModifiedDT);
  306. bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  307. Type *AccessTy, unsigned AddrSpace);
  308. bool optimizeInlineAsmInst(CallInst *CS);
  309. bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
  310. bool optimizeExt(Instruction *&I);
  311. bool optimizeExtUses(Instruction *I);
  312. bool optimizeLoadExt(LoadInst *Load);
  313. bool optimizeShiftInst(BinaryOperator *BO);
  314. bool optimizeSelectInst(SelectInst *SI);
  315. bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
  316. bool optimizeSwitchInst(SwitchInst *SI);
  317. bool optimizeExtractElementInst(Instruction *Inst);
  318. bool dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT);
  319. bool placeDbgValues(Function &F);
  320. bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
  321. LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
  322. bool tryToPromoteExts(TypePromotionTransaction &TPT,
  323. const SmallVectorImpl<Instruction *> &Exts,
  324. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  325. unsigned CreatedInstsCost = 0);
  326. bool mergeSExts(Function &F);
  327. bool splitLargeGEPOffsets();
  328. bool performAddressTypePromotion(
  329. Instruction *&Inst,
  330. bool AllowPromotionWithoutCommonHeader,
  331. bool HasPromoted, TypePromotionTransaction &TPT,
  332. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
  333. bool splitBranchCondition(Function &F, bool &ModifiedDT);
  334. bool simplifyOffsetableRelocate(Instruction &I);
  335. bool tryToSinkFreeOperands(Instruction *I);
  336. bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, CmpInst *Cmp,
  337. Intrinsic::ID IID);
  338. bool optimizeCmp(CmpInst *Cmp, bool &ModifiedDT);
  339. bool combineToUSubWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
  340. bool combineToUAddWithOverflow(CmpInst *Cmp, bool &ModifiedDT);
  341. };
  342. } // end anonymous namespace
  343. char CodeGenPrepare::ID = 0;
  344. INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
  345. "Optimize for code generation", false, false)
  346. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  347. INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
  348. "Optimize for code generation", false, false)
  349. FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
  350. bool CodeGenPrepare::runOnFunction(Function &F) {
  351. if (skipFunction(F))
  352. return false;
  353. DL = &F.getParent()->getDataLayout();
  354. bool EverMadeChange = false;
  355. // Clear per function information.
  356. InsertedInsts.clear();
  357. PromotedInsts.clear();
  358. if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
  359. TM = &TPC->getTM<TargetMachine>();
  360. SubtargetInfo = TM->getSubtargetImpl(F);
  361. TLI = SubtargetInfo->getTargetLowering();
  362. TRI = SubtargetInfo->getRegisterInfo();
  363. }
  364. TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  365. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  366. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  367. BPI.reset(new BranchProbabilityInfo(F, *LI));
  368. BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
  369. OptSize = F.hasOptSize();
  370. ProfileSummaryInfo *PSI =
  371. &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  372. if (ProfileGuidedSectionPrefix) {
  373. if (PSI->isFunctionHotInCallGraph(&F, *BFI))
  374. F.setSectionPrefix(".hot");
  375. else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
  376. F.setSectionPrefix(".unlikely");
  377. }
  378. /// This optimization identifies DIV instructions that can be
  379. /// profitably bypassed and carried out with a shorter, faster divide.
  380. if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
  381. TLI->isSlowDivBypassed()) {
  382. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  383. TLI->getBypassSlowDivWidths();
  384. BasicBlock* BB = &*F.begin();
  385. while (BB != nullptr) {
  386. // bypassSlowDivision may create new BBs, but we don't want to reapply the
  387. // optimization to those blocks.
  388. BasicBlock* Next = BB->getNextNode();
  389. EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
  390. BB = Next;
  391. }
  392. }
  393. // Eliminate blocks that contain only PHI nodes and an
  394. // unconditional branch.
  395. EverMadeChange |= eliminateMostlyEmptyBlocks(F);
  396. bool ModifiedDT = false;
  397. if (!DisableBranchOpts)
  398. EverMadeChange |= splitBranchCondition(F, ModifiedDT);
  399. // Split some critical edges where one of the sources is an indirect branch,
  400. // to help generate sane code for PHIs involving such edges.
  401. EverMadeChange |= SplitIndirectBrCriticalEdges(F);
  402. bool MadeChange = true;
  403. while (MadeChange) {
  404. MadeChange = false;
  405. DT.reset();
  406. for (Function::iterator I = F.begin(); I != F.end(); ) {
  407. BasicBlock *BB = &*I++;
  408. bool ModifiedDTOnIteration = false;
  409. MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
  410. // Restart BB iteration if the dominator tree of the Function was changed
  411. if (ModifiedDTOnIteration)
  412. break;
  413. }
  414. if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
  415. MadeChange |= mergeSExts(F);
  416. if (!LargeOffsetGEPMap.empty())
  417. MadeChange |= splitLargeGEPOffsets();
  418. // Really free removed instructions during promotion.
  419. for (Instruction *I : RemovedInsts)
  420. I->deleteValue();
  421. EverMadeChange |= MadeChange;
  422. SeenChainsForSExt.clear();
  423. ValToSExtendedUses.clear();
  424. RemovedInsts.clear();
  425. LargeOffsetGEPMap.clear();
  426. LargeOffsetGEPID.clear();
  427. }
  428. SunkAddrs.clear();
  429. if (!DisableBranchOpts) {
  430. MadeChange = false;
  431. // Use a set vector to get deterministic iteration order. The order the
  432. // blocks are removed may affect whether or not PHI nodes in successors
  433. // are removed.
  434. SmallSetVector<BasicBlock*, 8> WorkList;
  435. for (BasicBlock &BB : F) {
  436. SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
  437. MadeChange |= ConstantFoldTerminator(&BB, true);
  438. if (!MadeChange) continue;
  439. for (SmallVectorImpl<BasicBlock*>::iterator
  440. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  441. if (pred_begin(*II) == pred_end(*II))
  442. WorkList.insert(*II);
  443. }
  444. // Delete the dead blocks and any of their dead successors.
  445. MadeChange |= !WorkList.empty();
  446. while (!WorkList.empty()) {
  447. BasicBlock *BB = WorkList.pop_back_val();
  448. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  449. DeleteDeadBlock(BB);
  450. for (SmallVectorImpl<BasicBlock*>::iterator
  451. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  452. if (pred_begin(*II) == pred_end(*II))
  453. WorkList.insert(*II);
  454. }
  455. // Merge pairs of basic blocks with unconditional branches, connected by
  456. // a single edge.
  457. if (EverMadeChange || MadeChange)
  458. MadeChange |= eliminateFallThrough(F);
  459. EverMadeChange |= MadeChange;
  460. }
  461. if (!DisableGCOpts) {
  462. SmallVector<Instruction *, 2> Statepoints;
  463. for (BasicBlock &BB : F)
  464. for (Instruction &I : BB)
  465. if (isStatepoint(I))
  466. Statepoints.push_back(&I);
  467. for (auto &I : Statepoints)
  468. EverMadeChange |= simplifyOffsetableRelocate(*I);
  469. }
  470. // Do this last to clean up use-before-def scenarios introduced by other
  471. // preparatory transforms.
  472. EverMadeChange |= placeDbgValues(F);
  473. return EverMadeChange;
  474. }
  475. /// Merge basic blocks which are connected by a single edge, where one of the
  476. /// basic blocks has a single successor pointing to the other basic block,
  477. /// which has a single predecessor.
  478. bool CodeGenPrepare::eliminateFallThrough(Function &F) {
  479. bool Changed = false;
  480. // Scan all of the blocks in the function, except for the entry block.
  481. // Use a temporary array to avoid iterator being invalidated when
  482. // deleting blocks.
  483. SmallVector<WeakTrackingVH, 16> Blocks;
  484. for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
  485. Blocks.push_back(&Block);
  486. for (auto &Block : Blocks) {
  487. auto *BB = cast_or_null<BasicBlock>(Block);
  488. if (!BB)
  489. continue;
  490. // If the destination block has a single pred, then this is a trivial
  491. // edge, just collapse it.
  492. BasicBlock *SinglePred = BB->getSinglePredecessor();
  493. // Don't merge if BB's address is taken.
  494. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  495. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  496. if (Term && !Term->isConditional()) {
  497. Changed = true;
  498. LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
  499. // Merge BB into SinglePred and delete it.
  500. MergeBlockIntoPredecessor(BB);
  501. }
  502. }
  503. return Changed;
  504. }
  505. /// Find a destination block from BB if BB is mergeable empty block.
  506. BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
  507. // If this block doesn't end with an uncond branch, ignore it.
  508. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  509. if (!BI || !BI->isUnconditional())
  510. return nullptr;
  511. // If the instruction before the branch (skipping debug info) isn't a phi
  512. // node, then other stuff is happening here.
  513. BasicBlock::iterator BBI = BI->getIterator();
  514. if (BBI != BB->begin()) {
  515. --BBI;
  516. while (isa<DbgInfoIntrinsic>(BBI)) {
  517. if (BBI == BB->begin())
  518. break;
  519. --BBI;
  520. }
  521. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  522. return nullptr;
  523. }
  524. // Do not break infinite loops.
  525. BasicBlock *DestBB = BI->getSuccessor(0);
  526. if (DestBB == BB)
  527. return nullptr;
  528. if (!canMergeBlocks(BB, DestBB))
  529. DestBB = nullptr;
  530. return DestBB;
  531. }
  532. /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
  533. /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
  534. /// edges in ways that are non-optimal for isel. Start by eliminating these
  535. /// blocks so we can split them the way we want them.
  536. bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
  537. SmallPtrSet<BasicBlock *, 16> Preheaders;
  538. SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
  539. while (!LoopList.empty()) {
  540. Loop *L = LoopList.pop_back_val();
  541. LoopList.insert(LoopList.end(), L->begin(), L->end());
  542. if (BasicBlock *Preheader = L->getLoopPreheader())
  543. Preheaders.insert(Preheader);
  544. }
  545. bool MadeChange = false;
  546. // Copy blocks into a temporary array to avoid iterator invalidation issues
  547. // as we remove them.
  548. // Note that this intentionally skips the entry block.
  549. SmallVector<WeakTrackingVH, 16> Blocks;
  550. for (auto &Block : llvm::make_range(std::next(F.begin()), F.end()))
  551. Blocks.push_back(&Block);
  552. for (auto &Block : Blocks) {
  553. BasicBlock *BB = cast_or_null<BasicBlock>(Block);
  554. if (!BB)
  555. continue;
  556. BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
  557. if (!DestBB ||
  558. !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
  559. continue;
  560. eliminateMostlyEmptyBlock(BB);
  561. MadeChange = true;
  562. }
  563. return MadeChange;
  564. }
  565. bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
  566. BasicBlock *DestBB,
  567. bool isPreheader) {
  568. // Do not delete loop preheaders if doing so would create a critical edge.
  569. // Loop preheaders can be good locations to spill registers. If the
  570. // preheader is deleted and we create a critical edge, registers may be
  571. // spilled in the loop body instead.
  572. if (!DisablePreheaderProtect && isPreheader &&
  573. !(BB->getSinglePredecessor() &&
  574. BB->getSinglePredecessor()->getSingleSuccessor()))
  575. return false;
  576. // Skip merging if the block's successor is also a successor to any callbr
  577. // that leads to this block.
  578. // FIXME: Is this really needed? Is this a correctness issue?
  579. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  580. if (auto *CBI = dyn_cast<CallBrInst>((*PI)->getTerminator()))
  581. for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
  582. if (DestBB == CBI->getSuccessor(i))
  583. return false;
  584. }
  585. // Try to skip merging if the unique predecessor of BB is terminated by a
  586. // switch or indirect branch instruction, and BB is used as an incoming block
  587. // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
  588. // add COPY instructions in the predecessor of BB instead of BB (if it is not
  589. // merged). Note that the critical edge created by merging such blocks wont be
  590. // split in MachineSink because the jump table is not analyzable. By keeping
  591. // such empty block (BB), ISel will place COPY instructions in BB, not in the
  592. // predecessor of BB.
  593. BasicBlock *Pred = BB->getUniquePredecessor();
  594. if (!Pred ||
  595. !(isa<SwitchInst>(Pred->getTerminator()) ||
  596. isa<IndirectBrInst>(Pred->getTerminator())))
  597. return true;
  598. if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
  599. return true;
  600. // We use a simple cost heuristic which determine skipping merging is
  601. // profitable if the cost of skipping merging is less than the cost of
  602. // merging : Cost(skipping merging) < Cost(merging BB), where the
  603. // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
  604. // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
  605. // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
  606. // Freq(Pred) / Freq(BB) > 2.
  607. // Note that if there are multiple empty blocks sharing the same incoming
  608. // value for the PHIs in the DestBB, we consider them together. In such
  609. // case, Cost(merging BB) will be the sum of their frequencies.
  610. if (!isa<PHINode>(DestBB->begin()))
  611. return true;
  612. SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
  613. // Find all other incoming blocks from which incoming values of all PHIs in
  614. // DestBB are the same as the ones from BB.
  615. for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
  616. ++PI) {
  617. BasicBlock *DestBBPred = *PI;
  618. if (DestBBPred == BB)
  619. continue;
  620. if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
  621. return DestPN.getIncomingValueForBlock(BB) ==
  622. DestPN.getIncomingValueForBlock(DestBBPred);
  623. }))
  624. SameIncomingValueBBs.insert(DestBBPred);
  625. }
  626. // See if all BB's incoming values are same as the value from Pred. In this
  627. // case, no reason to skip merging because COPYs are expected to be place in
  628. // Pred already.
  629. if (SameIncomingValueBBs.count(Pred))
  630. return true;
  631. BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
  632. BlockFrequency BBFreq = BFI->getBlockFreq(BB);
  633. for (auto SameValueBB : SameIncomingValueBBs)
  634. if (SameValueBB->getUniquePredecessor() == Pred &&
  635. DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
  636. BBFreq += BFI->getBlockFreq(SameValueBB);
  637. return PredFreq.getFrequency() <=
  638. BBFreq.getFrequency() * FreqRatioToSkipMerge;
  639. }
  640. /// Return true if we can merge BB into DestBB if there is a single
  641. /// unconditional branch between them, and BB contains no other non-phi
  642. /// instructions.
  643. bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
  644. const BasicBlock *DestBB) const {
  645. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  646. // the successor. If there are more complex condition (e.g. preheaders),
  647. // don't mess around with them.
  648. for (const PHINode &PN : BB->phis()) {
  649. for (const User *U : PN.users()) {
  650. const Instruction *UI = cast<Instruction>(U);
  651. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  652. return false;
  653. // If User is inside DestBB block and it is a PHINode then check
  654. // incoming value. If incoming value is not from BB then this is
  655. // a complex condition (e.g. preheaders) we want to avoid here.
  656. if (UI->getParent() == DestBB) {
  657. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  658. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  659. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  660. if (Insn && Insn->getParent() == BB &&
  661. Insn->getParent() != UPN->getIncomingBlock(I))
  662. return false;
  663. }
  664. }
  665. }
  666. }
  667. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  668. // and DestBB may have conflicting incoming values for the block. If so, we
  669. // can't merge the block.
  670. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  671. if (!DestBBPN) return true; // no conflict.
  672. // Collect the preds of BB.
  673. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  674. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  675. // It is faster to get preds from a PHI than with pred_iterator.
  676. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  677. BBPreds.insert(BBPN->getIncomingBlock(i));
  678. } else {
  679. BBPreds.insert(pred_begin(BB), pred_end(BB));
  680. }
  681. // Walk the preds of DestBB.
  682. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  683. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  684. if (BBPreds.count(Pred)) { // Common predecessor?
  685. for (const PHINode &PN : DestBB->phis()) {
  686. const Value *V1 = PN.getIncomingValueForBlock(Pred);
  687. const Value *V2 = PN.getIncomingValueForBlock(BB);
  688. // If V2 is a phi node in BB, look up what the mapped value will be.
  689. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  690. if (V2PN->getParent() == BB)
  691. V2 = V2PN->getIncomingValueForBlock(Pred);
  692. // If there is a conflict, bail out.
  693. if (V1 != V2) return false;
  694. }
  695. }
  696. }
  697. return true;
  698. }
  699. /// Eliminate a basic block that has only phi's and an unconditional branch in
  700. /// it.
  701. void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
  702. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  703. BasicBlock *DestBB = BI->getSuccessor(0);
  704. LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
  705. << *BB << *DestBB);
  706. // If the destination block has a single pred, then this is a trivial edge,
  707. // just collapse it.
  708. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  709. if (SinglePred != DestBB) {
  710. assert(SinglePred == BB &&
  711. "Single predecessor not the same as predecessor");
  712. // Merge DestBB into SinglePred/BB and delete it.
  713. MergeBlockIntoPredecessor(DestBB);
  714. // Note: BB(=SinglePred) will not be deleted on this path.
  715. // DestBB(=its single successor) is the one that was deleted.
  716. LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
  717. return;
  718. }
  719. }
  720. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  721. // to handle the new incoming edges it is about to have.
  722. for (PHINode &PN : DestBB->phis()) {
  723. // Remove the incoming value for BB, and remember it.
  724. Value *InVal = PN.removeIncomingValue(BB, false);
  725. // Two options: either the InVal is a phi node defined in BB or it is some
  726. // value that dominates BB.
  727. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  728. if (InValPhi && InValPhi->getParent() == BB) {
  729. // Add all of the input values of the input PHI as inputs of this phi.
  730. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  731. PN.addIncoming(InValPhi->getIncomingValue(i),
  732. InValPhi->getIncomingBlock(i));
  733. } else {
  734. // Otherwise, add one instance of the dominating value for each edge that
  735. // we will be adding.
  736. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  737. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  738. PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
  739. } else {
  740. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  741. PN.addIncoming(InVal, *PI);
  742. }
  743. }
  744. }
  745. // The PHIs are now updated, change everything that refers to BB to use
  746. // DestBB and remove BB.
  747. BB->replaceAllUsesWith(DestBB);
  748. BB->eraseFromParent();
  749. ++NumBlocksElim;
  750. LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  751. }
  752. // Computes a map of base pointer relocation instructions to corresponding
  753. // derived pointer relocation instructions given a vector of all relocate calls
  754. static void computeBaseDerivedRelocateMap(
  755. const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
  756. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
  757. &RelocateInstMap) {
  758. // Collect information in two maps: one primarily for locating the base object
  759. // while filling the second map; the second map is the final structure holding
  760. // a mapping between Base and corresponding Derived relocate calls
  761. DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
  762. for (auto *ThisRelocate : AllRelocateCalls) {
  763. auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
  764. ThisRelocate->getDerivedPtrIndex());
  765. RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
  766. }
  767. for (auto &Item : RelocateIdxMap) {
  768. std::pair<unsigned, unsigned> Key = Item.first;
  769. if (Key.first == Key.second)
  770. // Base relocation: nothing to insert
  771. continue;
  772. GCRelocateInst *I = Item.second;
  773. auto BaseKey = std::make_pair(Key.first, Key.first);
  774. // We're iterating over RelocateIdxMap so we cannot modify it.
  775. auto MaybeBase = RelocateIdxMap.find(BaseKey);
  776. if (MaybeBase == RelocateIdxMap.end())
  777. // TODO: We might want to insert a new base object relocate and gep off
  778. // that, if there are enough derived object relocates.
  779. continue;
  780. RelocateInstMap[MaybeBase->second].push_back(I);
  781. }
  782. }
  783. // Accepts a GEP and extracts the operands into a vector provided they're all
  784. // small integer constants
  785. static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
  786. SmallVectorImpl<Value *> &OffsetV) {
  787. for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
  788. // Only accept small constant integer operands
  789. auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
  790. if (!Op || Op->getZExtValue() > 20)
  791. return false;
  792. }
  793. for (unsigned i = 1; i < GEP->getNumOperands(); i++)
  794. OffsetV.push_back(GEP->getOperand(i));
  795. return true;
  796. }
  797. // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
  798. // replace, computes a replacement, and affects it.
  799. static bool
  800. simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
  801. const SmallVectorImpl<GCRelocateInst *> &Targets) {
  802. bool MadeChange = false;
  803. // We must ensure the relocation of derived pointer is defined after
  804. // relocation of base pointer. If we find a relocation corresponding to base
  805. // defined earlier than relocation of base then we move relocation of base
  806. // right before found relocation. We consider only relocation in the same
  807. // basic block as relocation of base. Relocations from other basic block will
  808. // be skipped by optimization and we do not care about them.
  809. for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
  810. &*R != RelocatedBase; ++R)
  811. if (auto RI = dyn_cast<GCRelocateInst>(R))
  812. if (RI->getStatepoint() == RelocatedBase->getStatepoint())
  813. if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
  814. RelocatedBase->moveBefore(RI);
  815. break;
  816. }
  817. for (GCRelocateInst *ToReplace : Targets) {
  818. assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
  819. "Not relocating a derived object of the original base object");
  820. if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
  821. // A duplicate relocate call. TODO: coalesce duplicates.
  822. continue;
  823. }
  824. if (RelocatedBase->getParent() != ToReplace->getParent()) {
  825. // Base and derived relocates are in different basic blocks.
  826. // In this case transform is only valid when base dominates derived
  827. // relocate. However it would be too expensive to check dominance
  828. // for each such relocate, so we skip the whole transformation.
  829. continue;
  830. }
  831. Value *Base = ToReplace->getBasePtr();
  832. auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
  833. if (!Derived || Derived->getPointerOperand() != Base)
  834. continue;
  835. SmallVector<Value *, 2> OffsetV;
  836. if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
  837. continue;
  838. // Create a Builder and replace the target callsite with a gep
  839. assert(RelocatedBase->getNextNode() &&
  840. "Should always have one since it's not a terminator");
  841. // Insert after RelocatedBase
  842. IRBuilder<> Builder(RelocatedBase->getNextNode());
  843. Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
  844. // If gc_relocate does not match the actual type, cast it to the right type.
  845. // In theory, there must be a bitcast after gc_relocate if the type does not
  846. // match, and we should reuse it to get the derived pointer. But it could be
  847. // cases like this:
  848. // bb1:
  849. // ...
  850. // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  851. // br label %merge
  852. //
  853. // bb2:
  854. // ...
  855. // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  856. // br label %merge
  857. //
  858. // merge:
  859. // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
  860. // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
  861. //
  862. // In this case, we can not find the bitcast any more. So we insert a new bitcast
  863. // no matter there is already one or not. In this way, we can handle all cases, and
  864. // the extra bitcast should be optimized away in later passes.
  865. Value *ActualRelocatedBase = RelocatedBase;
  866. if (RelocatedBase->getType() != Base->getType()) {
  867. ActualRelocatedBase =
  868. Builder.CreateBitCast(RelocatedBase, Base->getType());
  869. }
  870. Value *Replacement = Builder.CreateGEP(
  871. Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
  872. Replacement->takeName(ToReplace);
  873. // If the newly generated derived pointer's type does not match the original derived
  874. // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
  875. Value *ActualReplacement = Replacement;
  876. if (Replacement->getType() != ToReplace->getType()) {
  877. ActualReplacement =
  878. Builder.CreateBitCast(Replacement, ToReplace->getType());
  879. }
  880. ToReplace->replaceAllUsesWith(ActualReplacement);
  881. ToReplace->eraseFromParent();
  882. MadeChange = true;
  883. }
  884. return MadeChange;
  885. }
  886. // Turns this:
  887. //
  888. // %base = ...
  889. // %ptr = gep %base + 15
  890. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  891. // %base' = relocate(%tok, i32 4, i32 4)
  892. // %ptr' = relocate(%tok, i32 4, i32 5)
  893. // %val = load %ptr'
  894. //
  895. // into this:
  896. //
  897. // %base = ...
  898. // %ptr = gep %base + 15
  899. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  900. // %base' = gc.relocate(%tok, i32 4, i32 4)
  901. // %ptr' = gep %base' + 15
  902. // %val = load %ptr'
  903. bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
  904. bool MadeChange = false;
  905. SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
  906. for (auto *U : I.users())
  907. if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
  908. // Collect all the relocate calls associated with a statepoint
  909. AllRelocateCalls.push_back(Relocate);
  910. // We need atleast one base pointer relocation + one derived pointer
  911. // relocation to mangle
  912. if (AllRelocateCalls.size() < 2)
  913. return false;
  914. // RelocateInstMap is a mapping from the base relocate instruction to the
  915. // corresponding derived relocate instructions
  916. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
  917. computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
  918. if (RelocateInstMap.empty())
  919. return false;
  920. for (auto &Item : RelocateInstMap)
  921. // Item.first is the RelocatedBase to offset against
  922. // Item.second is the vector of Targets to replace
  923. MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
  924. return MadeChange;
  925. }
  926. /// Sink the specified cast instruction into its user blocks.
  927. static bool SinkCast(CastInst *CI) {
  928. BasicBlock *DefBB = CI->getParent();
  929. /// InsertedCasts - Only insert a cast in each block once.
  930. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  931. bool MadeChange = false;
  932. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  933. UI != E; ) {
  934. Use &TheUse = UI.getUse();
  935. Instruction *User = cast<Instruction>(*UI);
  936. // Figure out which BB this cast is used in. For PHI's this is the
  937. // appropriate predecessor block.
  938. BasicBlock *UserBB = User->getParent();
  939. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  940. UserBB = PN->getIncomingBlock(TheUse);
  941. }
  942. // Preincrement use iterator so we don't invalidate it.
  943. ++UI;
  944. // The first insertion point of a block containing an EH pad is after the
  945. // pad. If the pad is the user, we cannot sink the cast past the pad.
  946. if (User->isEHPad())
  947. continue;
  948. // If the block selected to receive the cast is an EH pad that does not
  949. // allow non-PHI instructions before the terminator, we can't sink the
  950. // cast.
  951. if (UserBB->getTerminator()->isEHPad())
  952. continue;
  953. // If this user is in the same block as the cast, don't change the cast.
  954. if (UserBB == DefBB) continue;
  955. // If we have already inserted a cast into this block, use it.
  956. CastInst *&InsertedCast = InsertedCasts[UserBB];
  957. if (!InsertedCast) {
  958. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  959. assert(InsertPt != UserBB->end());
  960. InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
  961. CI->getType(), "", &*InsertPt);
  962. InsertedCast->setDebugLoc(CI->getDebugLoc());
  963. }
  964. // Replace a use of the cast with a use of the new cast.
  965. TheUse = InsertedCast;
  966. MadeChange = true;
  967. ++NumCastUses;
  968. }
  969. // If we removed all uses, nuke the cast.
  970. if (CI->use_empty()) {
  971. salvageDebugInfo(*CI);
  972. CI->eraseFromParent();
  973. MadeChange = true;
  974. }
  975. return MadeChange;
  976. }
  977. /// If the specified cast instruction is a noop copy (e.g. it's casting from
  978. /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
  979. /// reduce the number of virtual registers that must be created and coalesced.
  980. ///
  981. /// Return true if any changes are made.
  982. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
  983. const DataLayout &DL) {
  984. // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
  985. // than sinking only nop casts, but is helpful on some platforms.
  986. if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
  987. if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
  988. ASC->getDestAddressSpace()))
  989. return false;
  990. }
  991. // If this is a noop copy,
  992. EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  993. EVT DstVT = TLI.getValueType(DL, CI->getType());
  994. // This is an fp<->int conversion?
  995. if (SrcVT.isInteger() != DstVT.isInteger())
  996. return false;
  997. // If this is an extension, it will be a zero or sign extension, which
  998. // isn't a noop.
  999. if (SrcVT.bitsLT(DstVT)) return false;
  1000. // If these values will be promoted, find out what they will be promoted
  1001. // to. This helps us consider truncates on PPC as noop copies when they
  1002. // are.
  1003. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  1004. TargetLowering::TypePromoteInteger)
  1005. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  1006. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  1007. TargetLowering::TypePromoteInteger)
  1008. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  1009. // If, after promotion, these are the same types, this is a noop copy.
  1010. if (SrcVT != DstVT)
  1011. return false;
  1012. return SinkCast(CI);
  1013. }
  1014. bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
  1015. CmpInst *Cmp,
  1016. Intrinsic::ID IID) {
  1017. if (BO->getParent() != Cmp->getParent()) {
  1018. // We used to use a dominator tree here to allow multi-block optimization.
  1019. // But that was problematic because:
  1020. // 1. It could cause a perf regression by hoisting the math op into the
  1021. // critical path.
  1022. // 2. It could cause a perf regression by creating a value that was live
  1023. // across multiple blocks and increasing register pressure.
  1024. // 3. Use of a dominator tree could cause large compile-time regression.
  1025. // This is because we recompute the DT on every change in the main CGP
  1026. // run-loop. The recomputing is probably unnecessary in many cases, so if
  1027. // that was fixed, using a DT here would be ok.
  1028. return false;
  1029. }
  1030. // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
  1031. Value *Arg0 = BO->getOperand(0);
  1032. Value *Arg1 = BO->getOperand(1);
  1033. if (BO->getOpcode() == Instruction::Add &&
  1034. IID == Intrinsic::usub_with_overflow) {
  1035. assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
  1036. Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
  1037. }
  1038. // Insert at the first instruction of the pair.
  1039. Instruction *InsertPt = nullptr;
  1040. for (Instruction &Iter : *Cmp->getParent()) {
  1041. if (&Iter == BO || &Iter == Cmp) {
  1042. InsertPt = &Iter;
  1043. break;
  1044. }
  1045. }
  1046. assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
  1047. IRBuilder<> Builder(InsertPt);
  1048. Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
  1049. Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
  1050. Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
  1051. BO->replaceAllUsesWith(Math);
  1052. Cmp->replaceAllUsesWith(OV);
  1053. BO->eraseFromParent();
  1054. Cmp->eraseFromParent();
  1055. return true;
  1056. }
  1057. /// Match special-case patterns that check for unsigned add overflow.
  1058. static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
  1059. BinaryOperator *&Add) {
  1060. // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
  1061. // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
  1062. Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
  1063. // We are not expecting non-canonical/degenerate code. Just bail out.
  1064. if (isa<Constant>(A))
  1065. return false;
  1066. ICmpInst::Predicate Pred = Cmp->getPredicate();
  1067. if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
  1068. B = ConstantInt::get(B->getType(), 1);
  1069. else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
  1070. B = ConstantInt::get(B->getType(), -1);
  1071. else
  1072. return false;
  1073. // Check the users of the variable operand of the compare looking for an add
  1074. // with the adjusted constant.
  1075. for (User *U : A->users()) {
  1076. if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
  1077. Add = cast<BinaryOperator>(U);
  1078. return true;
  1079. }
  1080. }
  1081. return false;
  1082. }
  1083. /// Try to combine the compare into a call to the llvm.uadd.with.overflow
  1084. /// intrinsic. Return true if any changes were made.
  1085. bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
  1086. bool &ModifiedDT) {
  1087. Value *A, *B;
  1088. BinaryOperator *Add;
  1089. if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add))))
  1090. if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
  1091. return false;
  1092. if (!TLI->shouldFormOverflowOp(ISD::UADDO,
  1093. TLI->getValueType(*DL, Add->getType())))
  1094. return false;
  1095. // We don't want to move around uses of condition values this late, so we
  1096. // check if it is legal to create the call to the intrinsic in the basic
  1097. // block containing the icmp.
  1098. if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
  1099. return false;
  1100. if (!replaceMathCmpWithIntrinsic(Add, Cmp, Intrinsic::uadd_with_overflow))
  1101. return false;
  1102. // Reset callers - do not crash by iterating over a dead instruction.
  1103. ModifiedDT = true;
  1104. return true;
  1105. }
  1106. bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
  1107. bool &ModifiedDT) {
  1108. // We are not expecting non-canonical/degenerate code. Just bail out.
  1109. Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
  1110. if (isa<Constant>(A) && isa<Constant>(B))
  1111. return false;
  1112. // Convert (A u> B) to (A u< B) to simplify pattern matching.
  1113. ICmpInst::Predicate Pred = Cmp->getPredicate();
  1114. if (Pred == ICmpInst::ICMP_UGT) {
  1115. std::swap(A, B);
  1116. Pred = ICmpInst::ICMP_ULT;
  1117. }
  1118. // Convert special-case: (A == 0) is the same as (A u< 1).
  1119. if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
  1120. B = ConstantInt::get(B->getType(), 1);
  1121. Pred = ICmpInst::ICMP_ULT;
  1122. }
  1123. // Convert special-case: (A != 0) is the same as (0 u< A).
  1124. if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
  1125. std::swap(A, B);
  1126. Pred = ICmpInst::ICMP_ULT;
  1127. }
  1128. if (Pred != ICmpInst::ICMP_ULT)
  1129. return false;
  1130. // Walk the users of a variable operand of a compare looking for a subtract or
  1131. // add with that same operand. Also match the 2nd operand of the compare to
  1132. // the add/sub, but that may be a negated constant operand of an add.
  1133. Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
  1134. BinaryOperator *Sub = nullptr;
  1135. for (User *U : CmpVariableOperand->users()) {
  1136. // A - B, A u< B --> usubo(A, B)
  1137. if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
  1138. Sub = cast<BinaryOperator>(U);
  1139. break;
  1140. }
  1141. // A + (-C), A u< C (canonicalized form of (sub A, C))
  1142. const APInt *CmpC, *AddC;
  1143. if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
  1144. match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
  1145. Sub = cast<BinaryOperator>(U);
  1146. break;
  1147. }
  1148. }
  1149. if (!Sub)
  1150. return false;
  1151. if (!TLI->shouldFormOverflowOp(ISD::USUBO,
  1152. TLI->getValueType(*DL, Sub->getType())))
  1153. return false;
  1154. if (!replaceMathCmpWithIntrinsic(Sub, Cmp, Intrinsic::usub_with_overflow))
  1155. return false;
  1156. // Reset callers - do not crash by iterating over a dead instruction.
  1157. ModifiedDT = true;
  1158. return true;
  1159. }
  1160. /// Sink the given CmpInst into user blocks to reduce the number of virtual
  1161. /// registers that must be created and coalesced. This is a clear win except on
  1162. /// targets with multiple condition code registers (PowerPC), where it might
  1163. /// lose; some adjustment may be wanted there.
  1164. ///
  1165. /// Return true if any changes are made.
  1166. static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
  1167. if (TLI.hasMultipleConditionRegisters())
  1168. return false;
  1169. // Avoid sinking soft-FP comparisons, since this can move them into a loop.
  1170. if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
  1171. return false;
  1172. // Only insert a cmp in each block once.
  1173. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  1174. bool MadeChange = false;
  1175. for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
  1176. UI != E; ) {
  1177. Use &TheUse = UI.getUse();
  1178. Instruction *User = cast<Instruction>(*UI);
  1179. // Preincrement use iterator so we don't invalidate it.
  1180. ++UI;
  1181. // Don't bother for PHI nodes.
  1182. if (isa<PHINode>(User))
  1183. continue;
  1184. // Figure out which BB this cmp is used in.
  1185. BasicBlock *UserBB = User->getParent();
  1186. BasicBlock *DefBB = Cmp->getParent();
  1187. // If this user is in the same block as the cmp, don't change the cmp.
  1188. if (UserBB == DefBB) continue;
  1189. // If we have already inserted a cmp into this block, use it.
  1190. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  1191. if (!InsertedCmp) {
  1192. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1193. assert(InsertPt != UserBB->end());
  1194. InsertedCmp =
  1195. CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
  1196. Cmp->getOperand(0), Cmp->getOperand(1), "",
  1197. &*InsertPt);
  1198. // Propagate the debug info.
  1199. InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
  1200. }
  1201. // Replace a use of the cmp with a use of the new cmp.
  1202. TheUse = InsertedCmp;
  1203. MadeChange = true;
  1204. ++NumCmpUses;
  1205. }
  1206. // If we removed all uses, nuke the cmp.
  1207. if (Cmp->use_empty()) {
  1208. Cmp->eraseFromParent();
  1209. MadeChange = true;
  1210. }
  1211. return MadeChange;
  1212. }
  1213. bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, bool &ModifiedDT) {
  1214. if (sinkCmpExpression(Cmp, *TLI))
  1215. return true;
  1216. if (combineToUAddWithOverflow(Cmp, ModifiedDT))
  1217. return true;
  1218. if (combineToUSubWithOverflow(Cmp, ModifiedDT))
  1219. return true;
  1220. return false;
  1221. }
  1222. /// Duplicate and sink the given 'and' instruction into user blocks where it is
  1223. /// used in a compare to allow isel to generate better code for targets where
  1224. /// this operation can be combined.
  1225. ///
  1226. /// Return true if any changes are made.
  1227. static bool sinkAndCmp0Expression(Instruction *AndI,
  1228. const TargetLowering &TLI,
  1229. SetOfInstrs &InsertedInsts) {
  1230. // Double-check that we're not trying to optimize an instruction that was
  1231. // already optimized by some other part of this pass.
  1232. assert(!InsertedInsts.count(AndI) &&
  1233. "Attempting to optimize already optimized and instruction");
  1234. (void) InsertedInsts;
  1235. // Nothing to do for single use in same basic block.
  1236. if (AndI->hasOneUse() &&
  1237. AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
  1238. return false;
  1239. // Try to avoid cases where sinking/duplicating is likely to increase register
  1240. // pressure.
  1241. if (!isa<ConstantInt>(AndI->getOperand(0)) &&
  1242. !isa<ConstantInt>(AndI->getOperand(1)) &&
  1243. AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
  1244. return false;
  1245. for (auto *U : AndI->users()) {
  1246. Instruction *User = cast<Instruction>(U);
  1247. // Only sink 'and' feeding icmp with 0.
  1248. if (!isa<ICmpInst>(User))
  1249. return false;
  1250. auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
  1251. if (!CmpC || !CmpC->isZero())
  1252. return false;
  1253. }
  1254. if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
  1255. return false;
  1256. LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
  1257. LLVM_DEBUG(AndI->getParent()->dump());
  1258. // Push the 'and' into the same block as the icmp 0. There should only be
  1259. // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
  1260. // others, so we don't need to keep track of which BBs we insert into.
  1261. for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
  1262. UI != E; ) {
  1263. Use &TheUse = UI.getUse();
  1264. Instruction *User = cast<Instruction>(*UI);
  1265. // Preincrement use iterator so we don't invalidate it.
  1266. ++UI;
  1267. LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
  1268. // Keep the 'and' in the same place if the use is already in the same block.
  1269. Instruction *InsertPt =
  1270. User->getParent() == AndI->getParent() ? AndI : User;
  1271. Instruction *InsertedAnd =
  1272. BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
  1273. AndI->getOperand(1), "", InsertPt);
  1274. // Propagate the debug info.
  1275. InsertedAnd->setDebugLoc(AndI->getDebugLoc());
  1276. // Replace a use of the 'and' with a use of the new 'and'.
  1277. TheUse = InsertedAnd;
  1278. ++NumAndUses;
  1279. LLVM_DEBUG(User->getParent()->dump());
  1280. }
  1281. // We removed all uses, nuke the and.
  1282. AndI->eraseFromParent();
  1283. return true;
  1284. }
  1285. /// Check if the candidates could be combined with a shift instruction, which
  1286. /// includes:
  1287. /// 1. Truncate instruction
  1288. /// 2. And instruction and the imm is a mask of the low bits:
  1289. /// imm & (imm+1) == 0
  1290. static bool isExtractBitsCandidateUse(Instruction *User) {
  1291. if (!isa<TruncInst>(User)) {
  1292. if (User->getOpcode() != Instruction::And ||
  1293. !isa<ConstantInt>(User->getOperand(1)))
  1294. return false;
  1295. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  1296. if ((Cimm & (Cimm + 1)).getBoolValue())
  1297. return false;
  1298. }
  1299. return true;
  1300. }
  1301. /// Sink both shift and truncate instruction to the use of truncate's BB.
  1302. static bool
  1303. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  1304. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  1305. const TargetLowering &TLI, const DataLayout &DL) {
  1306. BasicBlock *UserBB = User->getParent();
  1307. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  1308. auto *TruncI = cast<TruncInst>(User);
  1309. bool MadeChange = false;
  1310. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  1311. TruncE = TruncI->user_end();
  1312. TruncUI != TruncE;) {
  1313. Use &TruncTheUse = TruncUI.getUse();
  1314. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  1315. // Preincrement use iterator so we don't invalidate it.
  1316. ++TruncUI;
  1317. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  1318. if (!ISDOpcode)
  1319. continue;
  1320. // If the use is actually a legal node, there will not be an
  1321. // implicit truncate.
  1322. // FIXME: always querying the result type is just an
  1323. // approximation; some nodes' legality is determined by the
  1324. // operand or other means. There's no good way to find out though.
  1325. if (TLI.isOperationLegalOrCustom(
  1326. ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
  1327. continue;
  1328. // Don't bother for PHI nodes.
  1329. if (isa<PHINode>(TruncUser))
  1330. continue;
  1331. BasicBlock *TruncUserBB = TruncUser->getParent();
  1332. if (UserBB == TruncUserBB)
  1333. continue;
  1334. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  1335. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  1336. if (!InsertedShift && !InsertedTrunc) {
  1337. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  1338. assert(InsertPt != TruncUserBB->end());
  1339. // Sink the shift
  1340. if (ShiftI->getOpcode() == Instruction::AShr)
  1341. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1342. "", &*InsertPt);
  1343. else
  1344. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1345. "", &*InsertPt);
  1346. InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
  1347. // Sink the trunc
  1348. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  1349. TruncInsertPt++;
  1350. assert(TruncInsertPt != TruncUserBB->end());
  1351. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  1352. TruncI->getType(), "", &*TruncInsertPt);
  1353. InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
  1354. MadeChange = true;
  1355. TruncTheUse = InsertedTrunc;
  1356. }
  1357. }
  1358. return MadeChange;
  1359. }
  1360. /// Sink the shift *right* instruction into user blocks if the uses could
  1361. /// potentially be combined with this shift instruction and generate BitExtract
  1362. /// instruction. It will only be applied if the architecture supports BitExtract
  1363. /// instruction. Here is an example:
  1364. /// BB1:
  1365. /// %x.extract.shift = lshr i64 %arg1, 32
  1366. /// BB2:
  1367. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  1368. /// ==>
  1369. ///
  1370. /// BB2:
  1371. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  1372. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  1373. ///
  1374. /// CodeGen will recognize the pattern in BB2 and generate BitExtract
  1375. /// instruction.
  1376. /// Return true if any changes are made.
  1377. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  1378. const TargetLowering &TLI,
  1379. const DataLayout &DL) {
  1380. BasicBlock *DefBB = ShiftI->getParent();
  1381. /// Only insert instructions in each block once.
  1382. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  1383. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
  1384. bool MadeChange = false;
  1385. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  1386. UI != E;) {
  1387. Use &TheUse = UI.getUse();
  1388. Instruction *User = cast<Instruction>(*UI);
  1389. // Preincrement use iterator so we don't invalidate it.
  1390. ++UI;
  1391. // Don't bother for PHI nodes.
  1392. if (isa<PHINode>(User))
  1393. continue;
  1394. if (!isExtractBitsCandidateUse(User))
  1395. continue;
  1396. BasicBlock *UserBB = User->getParent();
  1397. if (UserBB == DefBB) {
  1398. // If the shift and truncate instruction are in the same BB. The use of
  1399. // the truncate(TruncUse) may still introduce another truncate if not
  1400. // legal. In this case, we would like to sink both shift and truncate
  1401. // instruction to the BB of TruncUse.
  1402. // for example:
  1403. // BB1:
  1404. // i64 shift.result = lshr i64 opnd, imm
  1405. // trunc.result = trunc shift.result to i16
  1406. //
  1407. // BB2:
  1408. // ----> We will have an implicit truncate here if the architecture does
  1409. // not have i16 compare.
  1410. // cmp i16 trunc.result, opnd2
  1411. //
  1412. if (isa<TruncInst>(User) && shiftIsLegal
  1413. // If the type of the truncate is legal, no truncate will be
  1414. // introduced in other basic blocks.
  1415. &&
  1416. (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
  1417. MadeChange =
  1418. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
  1419. continue;
  1420. }
  1421. // If we have already inserted a shift into this block, use it.
  1422. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  1423. if (!InsertedShift) {
  1424. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1425. assert(InsertPt != UserBB->end());
  1426. if (ShiftI->getOpcode() == Instruction::AShr)
  1427. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1428. "", &*InsertPt);
  1429. else
  1430. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1431. "", &*InsertPt);
  1432. InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
  1433. MadeChange = true;
  1434. }
  1435. // Replace a use of the shift with a use of the new shift.
  1436. TheUse = InsertedShift;
  1437. }
  1438. // If we removed all uses, or there are none, nuke the shift.
  1439. if (ShiftI->use_empty()) {
  1440. salvageDebugInfo(*ShiftI);
  1441. ShiftI->eraseFromParent();
  1442. MadeChange = true;
  1443. }
  1444. return MadeChange;
  1445. }
  1446. /// If counting leading or trailing zeros is an expensive operation and a zero
  1447. /// input is defined, add a check for zero to avoid calling the intrinsic.
  1448. ///
  1449. /// We want to transform:
  1450. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
  1451. ///
  1452. /// into:
  1453. /// entry:
  1454. /// %cmpz = icmp eq i64 %A, 0
  1455. /// br i1 %cmpz, label %cond.end, label %cond.false
  1456. /// cond.false:
  1457. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
  1458. /// br label %cond.end
  1459. /// cond.end:
  1460. /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
  1461. ///
  1462. /// If the transform is performed, return true and set ModifiedDT to true.
  1463. static bool despeculateCountZeros(IntrinsicInst *CountZeros,
  1464. const TargetLowering *TLI,
  1465. const DataLayout *DL,
  1466. bool &ModifiedDT) {
  1467. if (!TLI || !DL)
  1468. return false;
  1469. // If a zero input is undefined, it doesn't make sense to despeculate that.
  1470. if (match(CountZeros->getOperand(1), m_One()))
  1471. return false;
  1472. // If it's cheap to speculate, there's nothing to do.
  1473. auto IntrinsicID = CountZeros->getIntrinsicID();
  1474. if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
  1475. (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
  1476. return false;
  1477. // Only handle legal scalar cases. Anything else requires too much work.
  1478. Type *Ty = CountZeros->getType();
  1479. unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
  1480. if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
  1481. return false;
  1482. // The intrinsic will be sunk behind a compare against zero and branch.
  1483. BasicBlock *StartBlock = CountZeros->getParent();
  1484. BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
  1485. // Create another block after the count zero intrinsic. A PHI will be added
  1486. // in this block to select the result of the intrinsic or the bit-width
  1487. // constant if the input to the intrinsic is zero.
  1488. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
  1489. BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
  1490. // Set up a builder to create a compare, conditional branch, and PHI.
  1491. IRBuilder<> Builder(CountZeros->getContext());
  1492. Builder.SetInsertPoint(StartBlock->getTerminator());
  1493. Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
  1494. // Replace the unconditional branch that was created by the first split with
  1495. // a compare against zero and a conditional branch.
  1496. Value *Zero = Constant::getNullValue(Ty);
  1497. Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
  1498. Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
  1499. StartBlock->getTerminator()->eraseFromParent();
  1500. // Create a PHI in the end block to select either the output of the intrinsic
  1501. // or the bit width of the operand.
  1502. Builder.SetInsertPoint(&EndBlock->front());
  1503. PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
  1504. CountZeros->replaceAllUsesWith(PN);
  1505. Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
  1506. PN->addIncoming(BitWidth, StartBlock);
  1507. PN->addIncoming(CountZeros, CallBlock);
  1508. // We are explicitly handling the zero case, so we can set the intrinsic's
  1509. // undefined zero argument to 'true'. This will also prevent reprocessing the
  1510. // intrinsic; we only despeculate when a zero input is defined.
  1511. CountZeros->setArgOperand(1, Builder.getTrue());
  1512. ModifiedDT = true;
  1513. return true;
  1514. }
  1515. bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
  1516. BasicBlock *BB = CI->getParent();
  1517. // Lower inline assembly if we can.
  1518. // If we found an inline asm expession, and if the target knows how to
  1519. // lower it to normal LLVM code, do so now.
  1520. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  1521. if (TLI->ExpandInlineAsm(CI)) {
  1522. // Avoid invalidating the iterator.
  1523. CurInstIterator = BB->begin();
  1524. // Avoid processing instructions out of order, which could cause
  1525. // reuse before a value is defined.
  1526. SunkAddrs.clear();
  1527. return true;
  1528. }
  1529. // Sink address computing for memory operands into the block.
  1530. if (optimizeInlineAsmInst(CI))
  1531. return true;
  1532. }
  1533. // Align the pointer arguments to this call if the target thinks it's a good
  1534. // idea
  1535. unsigned MinSize, PrefAlign;
  1536. if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
  1537. for (auto &Arg : CI->arg_operands()) {
  1538. // We want to align both objects whose address is used directly and
  1539. // objects whose address is used in casts and GEPs, though it only makes
  1540. // sense for GEPs if the offset is a multiple of the desired alignment and
  1541. // if size - offset meets the size threshold.
  1542. if (!Arg->getType()->isPointerTy())
  1543. continue;
  1544. APInt Offset(DL->getIndexSizeInBits(
  1545. cast<PointerType>(Arg->getType())->getAddressSpace()),
  1546. 0);
  1547. Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
  1548. uint64_t Offset2 = Offset.getLimitedValue();
  1549. if ((Offset2 & (PrefAlign-1)) != 0)
  1550. continue;
  1551. AllocaInst *AI;
  1552. if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
  1553. DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
  1554. AI->setAlignment(MaybeAlign(PrefAlign));
  1555. // Global variables can only be aligned if they are defined in this
  1556. // object (i.e. they are uniquely initialized in this object), and
  1557. // over-aligning global variables that have an explicit section is
  1558. // forbidden.
  1559. GlobalVariable *GV;
  1560. if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
  1561. GV->getPointerAlignment(*DL) < PrefAlign &&
  1562. DL->getTypeAllocSize(GV->getValueType()) >=
  1563. MinSize + Offset2)
  1564. GV->setAlignment(PrefAlign);
  1565. }
  1566. // If this is a memcpy (or similar) then we may be able to improve the
  1567. // alignment
  1568. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
  1569. unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
  1570. if (DestAlign > MI->getDestAlignment())
  1571. MI->setDestAlignment(DestAlign);
  1572. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
  1573. unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
  1574. if (SrcAlign > MTI->getSourceAlignment())
  1575. MTI->setSourceAlignment(SrcAlign);
  1576. }
  1577. }
  1578. }
  1579. // If we have a cold call site, try to sink addressing computation into the
  1580. // cold block. This interacts with our handling for loads and stores to
  1581. // ensure that we can fold all uses of a potential addressing computation
  1582. // into their uses. TODO: generalize this to work over profiling data
  1583. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  1584. for (auto &Arg : CI->arg_operands()) {
  1585. if (!Arg->getType()->isPointerTy())
  1586. continue;
  1587. unsigned AS = Arg->getType()->getPointerAddressSpace();
  1588. return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
  1589. }
  1590. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  1591. if (II) {
  1592. switch (II->getIntrinsicID()) {
  1593. default: break;
  1594. case Intrinsic::experimental_widenable_condition: {
  1595. // Give up on future widening oppurtunties so that we can fold away dead
  1596. // paths and merge blocks before going into block-local instruction
  1597. // selection.
  1598. if (II->use_empty()) {
  1599. II->eraseFromParent();
  1600. return true;
  1601. }
  1602. Constant *RetVal = ConstantInt::getTrue(II->getContext());
  1603. resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
  1604. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1605. });
  1606. return true;
  1607. }
  1608. case Intrinsic::objectsize:
  1609. llvm_unreachable("llvm.objectsize.* should have been lowered already");
  1610. case Intrinsic::is_constant:
  1611. llvm_unreachable("llvm.is.constant.* should have been lowered already");
  1612. case Intrinsic::aarch64_stlxr:
  1613. case Intrinsic::aarch64_stxr: {
  1614. ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
  1615. if (!ExtVal || !ExtVal->hasOneUse() ||
  1616. ExtVal->getParent() == CI->getParent())
  1617. return false;
  1618. // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
  1619. ExtVal->moveBefore(CI);
  1620. // Mark this instruction as "inserted by CGP", so that other
  1621. // optimizations don't touch it.
  1622. InsertedInsts.insert(ExtVal);
  1623. return true;
  1624. }
  1625. case Intrinsic::launder_invariant_group:
  1626. case Intrinsic::strip_invariant_group: {
  1627. Value *ArgVal = II->getArgOperand(0);
  1628. auto it = LargeOffsetGEPMap.find(II);
  1629. if (it != LargeOffsetGEPMap.end()) {
  1630. // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
  1631. // Make sure not to have to deal with iterator invalidation
  1632. // after possibly adding ArgVal to LargeOffsetGEPMap.
  1633. auto GEPs = std::move(it->second);
  1634. LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
  1635. LargeOffsetGEPMap.erase(II);
  1636. }
  1637. II->replaceAllUsesWith(ArgVal);
  1638. II->eraseFromParent();
  1639. return true;
  1640. }
  1641. case Intrinsic::cttz:
  1642. case Intrinsic::ctlz:
  1643. // If counting zeros is expensive, try to avoid it.
  1644. return despeculateCountZeros(II, TLI, DL, ModifiedDT);
  1645. }
  1646. if (TLI) {
  1647. SmallVector<Value*, 2> PtrOps;
  1648. Type *AccessTy;
  1649. if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
  1650. while (!PtrOps.empty()) {
  1651. Value *PtrVal = PtrOps.pop_back_val();
  1652. unsigned AS = PtrVal->getType()->getPointerAddressSpace();
  1653. if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
  1654. return true;
  1655. }
  1656. }
  1657. }
  1658. // From here on out we're working with named functions.
  1659. if (!CI->getCalledFunction()) return false;
  1660. // Lower all default uses of _chk calls. This is very similar
  1661. // to what InstCombineCalls does, but here we are only lowering calls
  1662. // to fortified library functions (e.g. __memcpy_chk) that have the default
  1663. // "don't know" as the objectsize. Anything else should be left alone.
  1664. FortifiedLibCallSimplifier Simplifier(TLInfo, true);
  1665. if (Value *V = Simplifier.optimizeCall(CI)) {
  1666. CI->replaceAllUsesWith(V);
  1667. CI->eraseFromParent();
  1668. return true;
  1669. }
  1670. return false;
  1671. }
  1672. /// Look for opportunities to duplicate return instructions to the predecessor
  1673. /// to enable tail call optimizations. The case it is currently looking for is:
  1674. /// @code
  1675. /// bb0:
  1676. /// %tmp0 = tail call i32 @f0()
  1677. /// br label %return
  1678. /// bb1:
  1679. /// %tmp1 = tail call i32 @f1()
  1680. /// br label %return
  1681. /// bb2:
  1682. /// %tmp2 = tail call i32 @f2()
  1683. /// br label %return
  1684. /// return:
  1685. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  1686. /// ret i32 %retval
  1687. /// @endcode
  1688. ///
  1689. /// =>
  1690. ///
  1691. /// @code
  1692. /// bb0:
  1693. /// %tmp0 = tail call i32 @f0()
  1694. /// ret i32 %tmp0
  1695. /// bb1:
  1696. /// %tmp1 = tail call i32 @f1()
  1697. /// ret i32 %tmp1
  1698. /// bb2:
  1699. /// %tmp2 = tail call i32 @f2()
  1700. /// ret i32 %tmp2
  1701. /// @endcode
  1702. bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB, bool &ModifiedDT) {
  1703. if (!TLI)
  1704. return false;
  1705. ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
  1706. if (!RetI)
  1707. return false;
  1708. PHINode *PN = nullptr;
  1709. BitCastInst *BCI = nullptr;
  1710. Value *V = RetI->getReturnValue();
  1711. if (V) {
  1712. BCI = dyn_cast<BitCastInst>(V);
  1713. if (BCI)
  1714. V = BCI->getOperand(0);
  1715. PN = dyn_cast<PHINode>(V);
  1716. if (!PN)
  1717. return false;
  1718. }
  1719. if (PN && PN->getParent() != BB)
  1720. return false;
  1721. // Make sure there are no instructions between the PHI and return, or that the
  1722. // return is the first instruction in the block.
  1723. if (PN) {
  1724. BasicBlock::iterator BI = BB->begin();
  1725. // Skip over debug and the bitcast.
  1726. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI) || &*BI == BCI);
  1727. if (&*BI != RetI)
  1728. return false;
  1729. } else {
  1730. BasicBlock::iterator BI = BB->begin();
  1731. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  1732. if (&*BI != RetI)
  1733. return false;
  1734. }
  1735. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  1736. /// call.
  1737. const Function *F = BB->getParent();
  1738. SmallVector<BasicBlock*, 4> TailCallBBs;
  1739. if (PN) {
  1740. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  1741. // Look through bitcasts.
  1742. Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
  1743. CallInst *CI = dyn_cast<CallInst>(IncomingVal);
  1744. BasicBlock *PredBB = PN->getIncomingBlock(I);
  1745. // Make sure the phi value is indeed produced by the tail call.
  1746. if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
  1747. TLI->mayBeEmittedAsTailCall(CI) &&
  1748. attributesPermitTailCall(F, CI, RetI, *TLI))
  1749. TailCallBBs.push_back(PredBB);
  1750. }
  1751. } else {
  1752. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  1753. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  1754. if (!VisitedBBs.insert(*PI).second)
  1755. continue;
  1756. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  1757. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  1758. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  1759. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  1760. if (RI == RE)
  1761. continue;
  1762. CallInst *CI = dyn_cast<CallInst>(&*RI);
  1763. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
  1764. attributesPermitTailCall(F, CI, RetI, *TLI))
  1765. TailCallBBs.push_back(*PI);
  1766. }
  1767. }
  1768. bool Changed = false;
  1769. for (auto const &TailCallBB : TailCallBBs) {
  1770. // Make sure the call instruction is followed by an unconditional branch to
  1771. // the return block.
  1772. BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
  1773. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  1774. continue;
  1775. // Duplicate the return into TailCallBB.
  1776. (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
  1777. ModifiedDT = Changed = true;
  1778. ++NumRetsDup;
  1779. }
  1780. // If we eliminated all predecessors of the block, delete the block now.
  1781. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  1782. BB->eraseFromParent();
  1783. return Changed;
  1784. }
  1785. //===----------------------------------------------------------------------===//
  1786. // Memory Optimization
  1787. //===----------------------------------------------------------------------===//
  1788. namespace {
  1789. /// This is an extended version of TargetLowering::AddrMode
  1790. /// which holds actual Value*'s for register values.
  1791. struct ExtAddrMode : public TargetLowering::AddrMode {
  1792. Value *BaseReg = nullptr;
  1793. Value *ScaledReg = nullptr;
  1794. Value *OriginalValue = nullptr;
  1795. bool InBounds = true;
  1796. enum FieldName {
  1797. NoField = 0x00,
  1798. BaseRegField = 0x01,
  1799. BaseGVField = 0x02,
  1800. BaseOffsField = 0x04,
  1801. ScaledRegField = 0x08,
  1802. ScaleField = 0x10,
  1803. MultipleFields = 0xff
  1804. };
  1805. ExtAddrMode() = default;
  1806. void print(raw_ostream &OS) const;
  1807. void dump() const;
  1808. FieldName compare(const ExtAddrMode &other) {
  1809. // First check that the types are the same on each field, as differing types
  1810. // is something we can't cope with later on.
  1811. if (BaseReg && other.BaseReg &&
  1812. BaseReg->getType() != other.BaseReg->getType())
  1813. return MultipleFields;
  1814. if (BaseGV && other.BaseGV &&
  1815. BaseGV->getType() != other.BaseGV->getType())
  1816. return MultipleFields;
  1817. if (ScaledReg && other.ScaledReg &&
  1818. ScaledReg->getType() != other.ScaledReg->getType())
  1819. return MultipleFields;
  1820. // Conservatively reject 'inbounds' mismatches.
  1821. if (InBounds != other.InBounds)
  1822. return MultipleFields;
  1823. // Check each field to see if it differs.
  1824. unsigned Result = NoField;
  1825. if (BaseReg != other.BaseReg)
  1826. Result |= BaseRegField;
  1827. if (BaseGV != other.BaseGV)
  1828. Result |= BaseGVField;
  1829. if (BaseOffs != other.BaseOffs)
  1830. Result |= BaseOffsField;
  1831. if (ScaledReg != other.ScaledReg)
  1832. Result |= ScaledRegField;
  1833. // Don't count 0 as being a different scale, because that actually means
  1834. // unscaled (which will already be counted by having no ScaledReg).
  1835. if (Scale && other.Scale && Scale != other.Scale)
  1836. Result |= ScaleField;
  1837. if (countPopulation(Result) > 1)
  1838. return MultipleFields;
  1839. else
  1840. return static_cast<FieldName>(Result);
  1841. }
  1842. // An AddrMode is trivial if it involves no calculation i.e. it is just a base
  1843. // with no offset.
  1844. bool isTrivial() {
  1845. // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
  1846. // trivial if at most one of these terms is nonzero, except that BaseGV and
  1847. // BaseReg both being zero actually means a null pointer value, which we
  1848. // consider to be 'non-zero' here.
  1849. return !BaseOffs && !Scale && !(BaseGV && BaseReg);
  1850. }
  1851. Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
  1852. switch (Field) {
  1853. default:
  1854. return nullptr;
  1855. case BaseRegField:
  1856. return BaseReg;
  1857. case BaseGVField:
  1858. return BaseGV;
  1859. case ScaledRegField:
  1860. return ScaledReg;
  1861. case BaseOffsField:
  1862. return ConstantInt::get(IntPtrTy, BaseOffs);
  1863. }
  1864. }
  1865. void SetCombinedField(FieldName Field, Value *V,
  1866. const SmallVectorImpl<ExtAddrMode> &AddrModes) {
  1867. switch (Field) {
  1868. default:
  1869. llvm_unreachable("Unhandled fields are expected to be rejected earlier");
  1870. break;
  1871. case ExtAddrMode::BaseRegField:
  1872. BaseReg = V;
  1873. break;
  1874. case ExtAddrMode::BaseGVField:
  1875. // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
  1876. // in the BaseReg field.
  1877. assert(BaseReg == nullptr);
  1878. BaseReg = V;
  1879. BaseGV = nullptr;
  1880. break;
  1881. case ExtAddrMode::ScaledRegField:
  1882. ScaledReg = V;
  1883. // If we have a mix of scaled and unscaled addrmodes then we want scale
  1884. // to be the scale and not zero.
  1885. if (!Scale)
  1886. for (const ExtAddrMode &AM : AddrModes)
  1887. if (AM.Scale) {
  1888. Scale = AM.Scale;
  1889. break;
  1890. }
  1891. break;
  1892. case ExtAddrMode::BaseOffsField:
  1893. // The offset is no longer a constant, so it goes in ScaledReg with a
  1894. // scale of 1.
  1895. assert(ScaledReg == nullptr);
  1896. ScaledReg = V;
  1897. Scale = 1;
  1898. BaseOffs = 0;
  1899. break;
  1900. }
  1901. }
  1902. };
  1903. } // end anonymous namespace
  1904. #ifndef NDEBUG
  1905. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  1906. AM.print(OS);
  1907. return OS;
  1908. }
  1909. #endif
  1910. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1911. void ExtAddrMode::print(raw_ostream &OS) const {
  1912. bool NeedPlus = false;
  1913. OS << "[";
  1914. if (InBounds)
  1915. OS << "inbounds ";
  1916. if (BaseGV) {
  1917. OS << (NeedPlus ? " + " : "")
  1918. << "GV:";
  1919. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  1920. NeedPlus = true;
  1921. }
  1922. if (BaseOffs) {
  1923. OS << (NeedPlus ? " + " : "")
  1924. << BaseOffs;
  1925. NeedPlus = true;
  1926. }
  1927. if (BaseReg) {
  1928. OS << (NeedPlus ? " + " : "")
  1929. << "Base:";
  1930. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  1931. NeedPlus = true;
  1932. }
  1933. if (Scale) {
  1934. OS << (NeedPlus ? " + " : "")
  1935. << Scale << "*";
  1936. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  1937. }
  1938. OS << ']';
  1939. }
  1940. LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
  1941. print(dbgs());
  1942. dbgs() << '\n';
  1943. }
  1944. #endif
  1945. namespace {
  1946. /// This class provides transaction based operation on the IR.
  1947. /// Every change made through this class is recorded in the internal state and
  1948. /// can be undone (rollback) until commit is called.
  1949. class TypePromotionTransaction {
  1950. /// This represents the common interface of the individual transaction.
  1951. /// Each class implements the logic for doing one specific modification on
  1952. /// the IR via the TypePromotionTransaction.
  1953. class TypePromotionAction {
  1954. protected:
  1955. /// The Instruction modified.
  1956. Instruction *Inst;
  1957. public:
  1958. /// Constructor of the action.
  1959. /// The constructor performs the related action on the IR.
  1960. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  1961. virtual ~TypePromotionAction() = default;
  1962. /// Undo the modification done by this action.
  1963. /// When this method is called, the IR must be in the same state as it was
  1964. /// before this action was applied.
  1965. /// \pre Undoing the action works if and only if the IR is in the exact same
  1966. /// state as it was directly after this action was applied.
  1967. virtual void undo() = 0;
  1968. /// Advocate every change made by this action.
  1969. /// When the results on the IR of the action are to be kept, it is important
  1970. /// to call this function, otherwise hidden information may be kept forever.
  1971. virtual void commit() {
  1972. // Nothing to be done, this action is not doing anything.
  1973. }
  1974. };
  1975. /// Utility to remember the position of an instruction.
  1976. class InsertionHandler {
  1977. /// Position of an instruction.
  1978. /// Either an instruction:
  1979. /// - Is the first in a basic block: BB is used.
  1980. /// - Has a previous instruction: PrevInst is used.
  1981. union {
  1982. Instruction *PrevInst;
  1983. BasicBlock *BB;
  1984. } Point;
  1985. /// Remember whether or not the instruction had a previous instruction.
  1986. bool HasPrevInstruction;
  1987. public:
  1988. /// Record the position of \p Inst.
  1989. InsertionHandler(Instruction *Inst) {
  1990. BasicBlock::iterator It = Inst->getIterator();
  1991. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  1992. if (HasPrevInstruction)
  1993. Point.PrevInst = &*--It;
  1994. else
  1995. Point.BB = Inst->getParent();
  1996. }
  1997. /// Insert \p Inst at the recorded position.
  1998. void insert(Instruction *Inst) {
  1999. if (HasPrevInstruction) {
  2000. if (Inst->getParent())
  2001. Inst->removeFromParent();
  2002. Inst->insertAfter(Point.PrevInst);
  2003. } else {
  2004. Instruction *Position = &*Point.BB->getFirstInsertionPt();
  2005. if (Inst->getParent())
  2006. Inst->moveBefore(Position);
  2007. else
  2008. Inst->insertBefore(Position);
  2009. }
  2010. }
  2011. };
  2012. /// Move an instruction before another.
  2013. class InstructionMoveBefore : public TypePromotionAction {
  2014. /// Original position of the instruction.
  2015. InsertionHandler Position;
  2016. public:
  2017. /// Move \p Inst before \p Before.
  2018. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  2019. : TypePromotionAction(Inst), Position(Inst) {
  2020. LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
  2021. << "\n");
  2022. Inst->moveBefore(Before);
  2023. }
  2024. /// Move the instruction back to its original position.
  2025. void undo() override {
  2026. LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  2027. Position.insert(Inst);
  2028. }
  2029. };
  2030. /// Set the operand of an instruction with a new value.
  2031. class OperandSetter : public TypePromotionAction {
  2032. /// Original operand of the instruction.
  2033. Value *Origin;
  2034. /// Index of the modified instruction.
  2035. unsigned Idx;
  2036. public:
  2037. /// Set \p Idx operand of \p Inst with \p NewVal.
  2038. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  2039. : TypePromotionAction(Inst), Idx(Idx) {
  2040. LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  2041. << "for:" << *Inst << "\n"
  2042. << "with:" << *NewVal << "\n");
  2043. Origin = Inst->getOperand(Idx);
  2044. Inst->setOperand(Idx, NewVal);
  2045. }
  2046. /// Restore the original value of the instruction.
  2047. void undo() override {
  2048. LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  2049. << "for: " << *Inst << "\n"
  2050. << "with: " << *Origin << "\n");
  2051. Inst->setOperand(Idx, Origin);
  2052. }
  2053. };
  2054. /// Hide the operands of an instruction.
  2055. /// Do as if this instruction was not using any of its operands.
  2056. class OperandsHider : public TypePromotionAction {
  2057. /// The list of original operands.
  2058. SmallVector<Value *, 4> OriginalValues;
  2059. public:
  2060. /// Remove \p Inst from the uses of the operands of \p Inst.
  2061. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  2062. LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  2063. unsigned NumOpnds = Inst->getNumOperands();
  2064. OriginalValues.reserve(NumOpnds);
  2065. for (unsigned It = 0; It < NumOpnds; ++It) {
  2066. // Save the current operand.
  2067. Value *Val = Inst->getOperand(It);
  2068. OriginalValues.push_back(Val);
  2069. // Set a dummy one.
  2070. // We could use OperandSetter here, but that would imply an overhead
  2071. // that we are not willing to pay.
  2072. Inst->setOperand(It, UndefValue::get(Val->getType()));
  2073. }
  2074. }
  2075. /// Restore the original list of uses.
  2076. void undo() override {
  2077. LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  2078. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  2079. Inst->setOperand(It, OriginalValues[It]);
  2080. }
  2081. };
  2082. /// Build a truncate instruction.
  2083. class TruncBuilder : public TypePromotionAction {
  2084. Value *Val;
  2085. public:
  2086. /// Build a truncate instruction of \p Opnd producing a \p Ty
  2087. /// result.
  2088. /// trunc Opnd to Ty.
  2089. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  2090. IRBuilder<> Builder(Opnd);
  2091. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  2092. LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  2093. }
  2094. /// Get the built value.
  2095. Value *getBuiltValue() { return Val; }
  2096. /// Remove the built instruction.
  2097. void undo() override {
  2098. LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  2099. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2100. IVal->eraseFromParent();
  2101. }
  2102. };
  2103. /// Build a sign extension instruction.
  2104. class SExtBuilder : public TypePromotionAction {
  2105. Value *Val;
  2106. public:
  2107. /// Build a sign extension instruction of \p Opnd producing a \p Ty
  2108. /// result.
  2109. /// sext Opnd to Ty.
  2110. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2111. : TypePromotionAction(InsertPt) {
  2112. IRBuilder<> Builder(InsertPt);
  2113. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  2114. LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  2115. }
  2116. /// Get the built value.
  2117. Value *getBuiltValue() { return Val; }
  2118. /// Remove the built instruction.
  2119. void undo() override {
  2120. LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  2121. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2122. IVal->eraseFromParent();
  2123. }
  2124. };
  2125. /// Build a zero extension instruction.
  2126. class ZExtBuilder : public TypePromotionAction {
  2127. Value *Val;
  2128. public:
  2129. /// Build a zero extension instruction of \p Opnd producing a \p Ty
  2130. /// result.
  2131. /// zext Opnd to Ty.
  2132. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2133. : TypePromotionAction(InsertPt) {
  2134. IRBuilder<> Builder(InsertPt);
  2135. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  2136. LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  2137. }
  2138. /// Get the built value.
  2139. Value *getBuiltValue() { return Val; }
  2140. /// Remove the built instruction.
  2141. void undo() override {
  2142. LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  2143. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2144. IVal->eraseFromParent();
  2145. }
  2146. };
  2147. /// Mutate an instruction to another type.
  2148. class TypeMutator : public TypePromotionAction {
  2149. /// Record the original type.
  2150. Type *OrigTy;
  2151. public:
  2152. /// Mutate the type of \p Inst into \p NewTy.
  2153. TypeMutator(Instruction *Inst, Type *NewTy)
  2154. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  2155. LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  2156. << "\n");
  2157. Inst->mutateType(NewTy);
  2158. }
  2159. /// Mutate the instruction back to its original type.
  2160. void undo() override {
  2161. LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  2162. << "\n");
  2163. Inst->mutateType(OrigTy);
  2164. }
  2165. };
  2166. /// Replace the uses of an instruction by another instruction.
  2167. class UsesReplacer : public TypePromotionAction {
  2168. /// Helper structure to keep track of the replaced uses.
  2169. struct InstructionAndIdx {
  2170. /// The instruction using the instruction.
  2171. Instruction *Inst;
  2172. /// The index where this instruction is used for Inst.
  2173. unsigned Idx;
  2174. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  2175. : Inst(Inst), Idx(Idx) {}
  2176. };
  2177. /// Keep track of the original uses (pair Instruction, Index).
  2178. SmallVector<InstructionAndIdx, 4> OriginalUses;
  2179. /// Keep track of the debug users.
  2180. SmallVector<DbgValueInst *, 1> DbgValues;
  2181. using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
  2182. public:
  2183. /// Replace all the use of \p Inst by \p New.
  2184. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  2185. LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  2186. << "\n");
  2187. // Record the original uses.
  2188. for (Use &U : Inst->uses()) {
  2189. Instruction *UserI = cast<Instruction>(U.getUser());
  2190. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  2191. }
  2192. // Record the debug uses separately. They are not in the instruction's
  2193. // use list, but they are replaced by RAUW.
  2194. findDbgValues(DbgValues, Inst);
  2195. // Now, we can replace the uses.
  2196. Inst->replaceAllUsesWith(New);
  2197. }
  2198. /// Reassign the original uses of Inst to Inst.
  2199. void undo() override {
  2200. LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  2201. for (use_iterator UseIt = OriginalUses.begin(),
  2202. EndIt = OriginalUses.end();
  2203. UseIt != EndIt; ++UseIt) {
  2204. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  2205. }
  2206. // RAUW has replaced all original uses with references to the new value,
  2207. // including the debug uses. Since we are undoing the replacements,
  2208. // the original debug uses must also be reinstated to maintain the
  2209. // correctness and utility of debug value instructions.
  2210. for (auto *DVI: DbgValues) {
  2211. LLVMContext &Ctx = Inst->getType()->getContext();
  2212. auto *MV = MetadataAsValue::get(Ctx, ValueAsMetadata::get(Inst));
  2213. DVI->setOperand(0, MV);
  2214. }
  2215. }
  2216. };
  2217. /// Remove an instruction from the IR.
  2218. class InstructionRemover : public TypePromotionAction {
  2219. /// Original position of the instruction.
  2220. InsertionHandler Inserter;
  2221. /// Helper structure to hide all the link to the instruction. In other
  2222. /// words, this helps to do as if the instruction was removed.
  2223. OperandsHider Hider;
  2224. /// Keep track of the uses replaced, if any.
  2225. UsesReplacer *Replacer = nullptr;
  2226. /// Keep track of instructions removed.
  2227. SetOfInstrs &RemovedInsts;
  2228. public:
  2229. /// Remove all reference of \p Inst and optionally replace all its
  2230. /// uses with New.
  2231. /// \p RemovedInsts Keep track of the instructions removed by this Action.
  2232. /// \pre If !Inst->use_empty(), then New != nullptr
  2233. InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
  2234. Value *New = nullptr)
  2235. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  2236. RemovedInsts(RemovedInsts) {
  2237. if (New)
  2238. Replacer = new UsesReplacer(Inst, New);
  2239. LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  2240. RemovedInsts.insert(Inst);
  2241. /// The instructions removed here will be freed after completing
  2242. /// optimizeBlock() for all blocks as we need to keep track of the
  2243. /// removed instructions during promotion.
  2244. Inst->removeFromParent();
  2245. }
  2246. ~InstructionRemover() override { delete Replacer; }
  2247. /// Resurrect the instruction and reassign it to the proper uses if
  2248. /// new value was provided when build this action.
  2249. void undo() override {
  2250. LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  2251. Inserter.insert(Inst);
  2252. if (Replacer)
  2253. Replacer->undo();
  2254. Hider.undo();
  2255. RemovedInsts.erase(Inst);
  2256. }
  2257. };
  2258. public:
  2259. /// Restoration point.
  2260. /// The restoration point is a pointer to an action instead of an iterator
  2261. /// because the iterator may be invalidated but not the pointer.
  2262. using ConstRestorationPt = const TypePromotionAction *;
  2263. TypePromotionTransaction(SetOfInstrs &RemovedInsts)
  2264. : RemovedInsts(RemovedInsts) {}
  2265. /// Advocate every changes made in that transaction.
  2266. void commit();
  2267. /// Undo all the changes made after the given point.
  2268. void rollback(ConstRestorationPt Point);
  2269. /// Get the current restoration point.
  2270. ConstRestorationPt getRestorationPoint() const;
  2271. /// \name API for IR modification with state keeping to support rollback.
  2272. /// @{
  2273. /// Same as Instruction::setOperand.
  2274. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  2275. /// Same as Instruction::eraseFromParent.
  2276. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  2277. /// Same as Value::replaceAllUsesWith.
  2278. void replaceAllUsesWith(Instruction *Inst, Value *New);
  2279. /// Same as Value::mutateType.
  2280. void mutateType(Instruction *Inst, Type *NewTy);
  2281. /// Same as IRBuilder::createTrunc.
  2282. Value *createTrunc(Instruction *Opnd, Type *Ty);
  2283. /// Same as IRBuilder::createSExt.
  2284. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2285. /// Same as IRBuilder::createZExt.
  2286. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2287. /// Same as Instruction::moveBefore.
  2288. void moveBefore(Instruction *Inst, Instruction *Before);
  2289. /// @}
  2290. private:
  2291. /// The ordered list of actions made so far.
  2292. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  2293. using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
  2294. SetOfInstrs &RemovedInsts;
  2295. };
  2296. } // end anonymous namespace
  2297. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  2298. Value *NewVal) {
  2299. Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
  2300. Inst, Idx, NewVal));
  2301. }
  2302. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  2303. Value *NewVal) {
  2304. Actions.push_back(
  2305. std::make_unique<TypePromotionTransaction::InstructionRemover>(
  2306. Inst, RemovedInsts, NewVal));
  2307. }
  2308. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  2309. Value *New) {
  2310. Actions.push_back(
  2311. std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  2312. }
  2313. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  2314. Actions.push_back(
  2315. std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  2316. }
  2317. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  2318. Type *Ty) {
  2319. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  2320. Value *Val = Ptr->getBuiltValue();
  2321. Actions.push_back(std::move(Ptr));
  2322. return Val;
  2323. }
  2324. Value *TypePromotionTransaction::createSExt(Instruction *Inst,
  2325. Value *Opnd, Type *Ty) {
  2326. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  2327. Value *Val = Ptr->getBuiltValue();
  2328. Actions.push_back(std::move(Ptr));
  2329. return Val;
  2330. }
  2331. Value *TypePromotionTransaction::createZExt(Instruction *Inst,
  2332. Value *Opnd, Type *Ty) {
  2333. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  2334. Value *Val = Ptr->getBuiltValue();
  2335. Actions.push_back(std::move(Ptr));
  2336. return Val;
  2337. }
  2338. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  2339. Instruction *Before) {
  2340. Actions.push_back(
  2341. std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
  2342. Inst, Before));
  2343. }
  2344. TypePromotionTransaction::ConstRestorationPt
  2345. TypePromotionTransaction::getRestorationPoint() const {
  2346. return !Actions.empty() ? Actions.back().get() : nullptr;
  2347. }
  2348. void TypePromotionTransaction::commit() {
  2349. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  2350. ++It)
  2351. (*It)->commit();
  2352. Actions.clear();
  2353. }
  2354. void TypePromotionTransaction::rollback(
  2355. TypePromotionTransaction::ConstRestorationPt Point) {
  2356. while (!Actions.empty() && Point != Actions.back().get()) {
  2357. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  2358. Curr->undo();
  2359. }
  2360. }
  2361. namespace {
  2362. /// A helper class for matching addressing modes.
  2363. ///
  2364. /// This encapsulates the logic for matching the target-legal addressing modes.
  2365. class AddressingModeMatcher {
  2366. SmallVectorImpl<Instruction*> &AddrModeInsts;
  2367. const TargetLowering &TLI;
  2368. const TargetRegisterInfo &TRI;
  2369. const DataLayout &DL;
  2370. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  2371. /// the memory instruction that we're computing this address for.
  2372. Type *AccessTy;
  2373. unsigned AddrSpace;
  2374. Instruction *MemoryInst;
  2375. /// This is the addressing mode that we're building up. This is
  2376. /// part of the return value of this addressing mode matching stuff.
  2377. ExtAddrMode &AddrMode;
  2378. /// The instructions inserted by other CodeGenPrepare optimizations.
  2379. const SetOfInstrs &InsertedInsts;
  2380. /// A map from the instructions to their type before promotion.
  2381. InstrToOrigTy &PromotedInsts;
  2382. /// The ongoing transaction where every action should be registered.
  2383. TypePromotionTransaction &TPT;
  2384. // A GEP which has too large offset to be folded into the addressing mode.
  2385. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
  2386. /// This is set to true when we should not do profitability checks.
  2387. /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
  2388. bool IgnoreProfitability;
  2389. AddressingModeMatcher(
  2390. SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
  2391. const TargetRegisterInfo &TRI, Type *AT, unsigned AS, Instruction *MI,
  2392. ExtAddrMode &AM, const SetOfInstrs &InsertedInsts,
  2393. InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
  2394. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP)
  2395. : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
  2396. DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
  2397. MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
  2398. PromotedInsts(PromotedInsts), TPT(TPT), LargeOffsetGEP(LargeOffsetGEP) {
  2399. IgnoreProfitability = false;
  2400. }
  2401. public:
  2402. /// Find the maximal addressing mode that a load/store of V can fold,
  2403. /// give an access type of AccessTy. This returns a list of involved
  2404. /// instructions in AddrModeInsts.
  2405. /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
  2406. /// optimizations.
  2407. /// \p PromotedInsts maps the instructions to their type before promotion.
  2408. /// \p The ongoing transaction where every action should be registered.
  2409. static ExtAddrMode
  2410. Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
  2411. SmallVectorImpl<Instruction *> &AddrModeInsts,
  2412. const TargetLowering &TLI, const TargetRegisterInfo &TRI,
  2413. const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
  2414. TypePromotionTransaction &TPT,
  2415. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP) {
  2416. ExtAddrMode Result;
  2417. bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, AccessTy, AS,
  2418. MemoryInst, Result, InsertedInsts,
  2419. PromotedInsts, TPT, LargeOffsetGEP)
  2420. .matchAddr(V, 0);
  2421. (void)Success; assert(Success && "Couldn't select *anything*?");
  2422. return Result;
  2423. }
  2424. private:
  2425. bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  2426. bool matchAddr(Value *Addr, unsigned Depth);
  2427. bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
  2428. bool *MovedAway = nullptr);
  2429. bool isProfitableToFoldIntoAddressingMode(Instruction *I,
  2430. ExtAddrMode &AMBefore,
  2431. ExtAddrMode &AMAfter);
  2432. bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  2433. bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
  2434. Value *PromotedOperand) const;
  2435. };
  2436. class PhiNodeSet;
  2437. /// An iterator for PhiNodeSet.
  2438. class PhiNodeSetIterator {
  2439. PhiNodeSet * const Set;
  2440. size_t CurrentIndex = 0;
  2441. public:
  2442. /// The constructor. Start should point to either a valid element, or be equal
  2443. /// to the size of the underlying SmallVector of the PhiNodeSet.
  2444. PhiNodeSetIterator(PhiNodeSet * const Set, size_t Start);
  2445. PHINode * operator*() const;
  2446. PhiNodeSetIterator& operator++();
  2447. bool operator==(const PhiNodeSetIterator &RHS) const;
  2448. bool operator!=(const PhiNodeSetIterator &RHS) const;
  2449. };
  2450. /// Keeps a set of PHINodes.
  2451. ///
  2452. /// This is a minimal set implementation for a specific use case:
  2453. /// It is very fast when there are very few elements, but also provides good
  2454. /// performance when there are many. It is similar to SmallPtrSet, but also
  2455. /// provides iteration by insertion order, which is deterministic and stable
  2456. /// across runs. It is also similar to SmallSetVector, but provides removing
  2457. /// elements in O(1) time. This is achieved by not actually removing the element
  2458. /// from the underlying vector, so comes at the cost of using more memory, but
  2459. /// that is fine, since PhiNodeSets are used as short lived objects.
  2460. class PhiNodeSet {
  2461. friend class PhiNodeSetIterator;
  2462. using MapType = SmallDenseMap<PHINode *, size_t, 32>;
  2463. using iterator = PhiNodeSetIterator;
  2464. /// Keeps the elements in the order of their insertion in the underlying
  2465. /// vector. To achieve constant time removal, it never deletes any element.
  2466. SmallVector<PHINode *, 32> NodeList;
  2467. /// Keeps the elements in the underlying set implementation. This (and not the
  2468. /// NodeList defined above) is the source of truth on whether an element
  2469. /// is actually in the collection.
  2470. MapType NodeMap;
  2471. /// Points to the first valid (not deleted) element when the set is not empty
  2472. /// and the value is not zero. Equals to the size of the underlying vector
  2473. /// when the set is empty. When the value is 0, as in the beginning, the
  2474. /// first element may or may not be valid.
  2475. size_t FirstValidElement = 0;
  2476. public:
  2477. /// Inserts a new element to the collection.
  2478. /// \returns true if the element is actually added, i.e. was not in the
  2479. /// collection before the operation.
  2480. bool insert(PHINode *Ptr) {
  2481. if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
  2482. NodeList.push_back(Ptr);
  2483. return true;
  2484. }
  2485. return false;
  2486. }
  2487. /// Removes the element from the collection.
  2488. /// \returns whether the element is actually removed, i.e. was in the
  2489. /// collection before the operation.
  2490. bool erase(PHINode *Ptr) {
  2491. auto it = NodeMap.find(Ptr);
  2492. if (it != NodeMap.end()) {
  2493. NodeMap.erase(Ptr);
  2494. SkipRemovedElements(FirstValidElement);
  2495. return true;
  2496. }
  2497. return false;
  2498. }
  2499. /// Removes all elements and clears the collection.
  2500. void clear() {
  2501. NodeMap.clear();
  2502. NodeList.clear();
  2503. FirstValidElement = 0;
  2504. }
  2505. /// \returns an iterator that will iterate the elements in the order of
  2506. /// insertion.
  2507. iterator begin() {
  2508. if (FirstValidElement == 0)
  2509. SkipRemovedElements(FirstValidElement);
  2510. return PhiNodeSetIterator(this, FirstValidElement);
  2511. }
  2512. /// \returns an iterator that points to the end of the collection.
  2513. iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
  2514. /// Returns the number of elements in the collection.
  2515. size_t size() const {
  2516. return NodeMap.size();
  2517. }
  2518. /// \returns 1 if the given element is in the collection, and 0 if otherwise.
  2519. size_t count(PHINode *Ptr) const {
  2520. return NodeMap.count(Ptr);
  2521. }
  2522. private:
  2523. /// Updates the CurrentIndex so that it will point to a valid element.
  2524. ///
  2525. /// If the element of NodeList at CurrentIndex is valid, it does not
  2526. /// change it. If there are no more valid elements, it updates CurrentIndex
  2527. /// to point to the end of the NodeList.
  2528. void SkipRemovedElements(size_t &CurrentIndex) {
  2529. while (CurrentIndex < NodeList.size()) {
  2530. auto it = NodeMap.find(NodeList[CurrentIndex]);
  2531. // If the element has been deleted and added again later, NodeMap will
  2532. // point to a different index, so CurrentIndex will still be invalid.
  2533. if (it != NodeMap.end() && it->second == CurrentIndex)
  2534. break;
  2535. ++CurrentIndex;
  2536. }
  2537. }
  2538. };
  2539. PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
  2540. : Set(Set), CurrentIndex(Start) {}
  2541. PHINode * PhiNodeSetIterator::operator*() const {
  2542. assert(CurrentIndex < Set->NodeList.size() &&
  2543. "PhiNodeSet access out of range");
  2544. return Set->NodeList[CurrentIndex];
  2545. }
  2546. PhiNodeSetIterator& PhiNodeSetIterator::operator++() {
  2547. assert(CurrentIndex < Set->NodeList.size() &&
  2548. "PhiNodeSet access out of range");
  2549. ++CurrentIndex;
  2550. Set->SkipRemovedElements(CurrentIndex);
  2551. return *this;
  2552. }
  2553. bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
  2554. return CurrentIndex == RHS.CurrentIndex;
  2555. }
  2556. bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
  2557. return !((*this) == RHS);
  2558. }
  2559. /// Keep track of simplification of Phi nodes.
  2560. /// Accept the set of all phi nodes and erase phi node from this set
  2561. /// if it is simplified.
  2562. class SimplificationTracker {
  2563. DenseMap<Value *, Value *> Storage;
  2564. const SimplifyQuery &SQ;
  2565. // Tracks newly created Phi nodes. The elements are iterated by insertion
  2566. // order.
  2567. PhiNodeSet AllPhiNodes;
  2568. // Tracks newly created Select nodes.
  2569. SmallPtrSet<SelectInst *, 32> AllSelectNodes;
  2570. public:
  2571. SimplificationTracker(const SimplifyQuery &sq)
  2572. : SQ(sq) {}
  2573. Value *Get(Value *V) {
  2574. do {
  2575. auto SV = Storage.find(V);
  2576. if (SV == Storage.end())
  2577. return V;
  2578. V = SV->second;
  2579. } while (true);
  2580. }
  2581. Value *Simplify(Value *Val) {
  2582. SmallVector<Value *, 32> WorkList;
  2583. SmallPtrSet<Value *, 32> Visited;
  2584. WorkList.push_back(Val);
  2585. while (!WorkList.empty()) {
  2586. auto P = WorkList.pop_back_val();
  2587. if (!Visited.insert(P).second)
  2588. continue;
  2589. if (auto *PI = dyn_cast<Instruction>(P))
  2590. if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
  2591. for (auto *U : PI->users())
  2592. WorkList.push_back(cast<Value>(U));
  2593. Put(PI, V);
  2594. PI->replaceAllUsesWith(V);
  2595. if (auto *PHI = dyn_cast<PHINode>(PI))
  2596. AllPhiNodes.erase(PHI);
  2597. if (auto *Select = dyn_cast<SelectInst>(PI))
  2598. AllSelectNodes.erase(Select);
  2599. PI->eraseFromParent();
  2600. }
  2601. }
  2602. return Get(Val);
  2603. }
  2604. void Put(Value *From, Value *To) {
  2605. Storage.insert({ From, To });
  2606. }
  2607. void ReplacePhi(PHINode *From, PHINode *To) {
  2608. Value* OldReplacement = Get(From);
  2609. while (OldReplacement != From) {
  2610. From = To;
  2611. To = dyn_cast<PHINode>(OldReplacement);
  2612. OldReplacement = Get(From);
  2613. }
  2614. assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
  2615. Put(From, To);
  2616. From->replaceAllUsesWith(To);
  2617. AllPhiNodes.erase(From);
  2618. From->eraseFromParent();
  2619. }
  2620. PhiNodeSet& newPhiNodes() { return AllPhiNodes; }
  2621. void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
  2622. void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
  2623. unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
  2624. unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
  2625. void destroyNewNodes(Type *CommonType) {
  2626. // For safe erasing, replace the uses with dummy value first.
  2627. auto Dummy = UndefValue::get(CommonType);
  2628. for (auto I : AllPhiNodes) {
  2629. I->replaceAllUsesWith(Dummy);
  2630. I->eraseFromParent();
  2631. }
  2632. AllPhiNodes.clear();
  2633. for (auto I : AllSelectNodes) {
  2634. I->replaceAllUsesWith(Dummy);
  2635. I->eraseFromParent();
  2636. }
  2637. AllSelectNodes.clear();
  2638. }
  2639. };
  2640. /// A helper class for combining addressing modes.
  2641. class AddressingModeCombiner {
  2642. typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
  2643. typedef std::pair<PHINode *, PHINode *> PHIPair;
  2644. private:
  2645. /// The addressing modes we've collected.
  2646. SmallVector<ExtAddrMode, 16> AddrModes;
  2647. /// The field in which the AddrModes differ, when we have more than one.
  2648. ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
  2649. /// Are the AddrModes that we have all just equal to their original values?
  2650. bool AllAddrModesTrivial = true;
  2651. /// Common Type for all different fields in addressing modes.
  2652. Type *CommonType;
  2653. /// SimplifyQuery for simplifyInstruction utility.
  2654. const SimplifyQuery &SQ;
  2655. /// Original Address.
  2656. Value *Original;
  2657. public:
  2658. AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
  2659. : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
  2660. /// Get the combined AddrMode
  2661. const ExtAddrMode &getAddrMode() const {
  2662. return AddrModes[0];
  2663. }
  2664. /// Add a new AddrMode if it's compatible with the AddrModes we already
  2665. /// have.
  2666. /// \return True iff we succeeded in doing so.
  2667. bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
  2668. // Take note of if we have any non-trivial AddrModes, as we need to detect
  2669. // when all AddrModes are trivial as then we would introduce a phi or select
  2670. // which just duplicates what's already there.
  2671. AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
  2672. // If this is the first addrmode then everything is fine.
  2673. if (AddrModes.empty()) {
  2674. AddrModes.emplace_back(NewAddrMode);
  2675. return true;
  2676. }
  2677. // Figure out how different this is from the other address modes, which we
  2678. // can do just by comparing against the first one given that we only care
  2679. // about the cumulative difference.
  2680. ExtAddrMode::FieldName ThisDifferentField =
  2681. AddrModes[0].compare(NewAddrMode);
  2682. if (DifferentField == ExtAddrMode::NoField)
  2683. DifferentField = ThisDifferentField;
  2684. else if (DifferentField != ThisDifferentField)
  2685. DifferentField = ExtAddrMode::MultipleFields;
  2686. // If NewAddrMode differs in more than one dimension we cannot handle it.
  2687. bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
  2688. // If Scale Field is different then we reject.
  2689. CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
  2690. // We also must reject the case when base offset is different and
  2691. // scale reg is not null, we cannot handle this case due to merge of
  2692. // different offsets will be used as ScaleReg.
  2693. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
  2694. !NewAddrMode.ScaledReg);
  2695. // We also must reject the case when GV is different and BaseReg installed
  2696. // due to we want to use base reg as a merge of GV values.
  2697. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
  2698. !NewAddrMode.HasBaseReg);
  2699. // Even if NewAddMode is the same we still need to collect it due to
  2700. // original value is different. And later we will need all original values
  2701. // as anchors during finding the common Phi node.
  2702. if (CanHandle)
  2703. AddrModes.emplace_back(NewAddrMode);
  2704. else
  2705. AddrModes.clear();
  2706. return CanHandle;
  2707. }
  2708. /// Combine the addressing modes we've collected into a single
  2709. /// addressing mode.
  2710. /// \return True iff we successfully combined them or we only had one so
  2711. /// didn't need to combine them anyway.
  2712. bool combineAddrModes() {
  2713. // If we have no AddrModes then they can't be combined.
  2714. if (AddrModes.size() == 0)
  2715. return false;
  2716. // A single AddrMode can trivially be combined.
  2717. if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
  2718. return true;
  2719. // If the AddrModes we collected are all just equal to the value they are
  2720. // derived from then combining them wouldn't do anything useful.
  2721. if (AllAddrModesTrivial)
  2722. return false;
  2723. if (!addrModeCombiningAllowed())
  2724. return false;
  2725. // Build a map between <original value, basic block where we saw it> to
  2726. // value of base register.
  2727. // Bail out if there is no common type.
  2728. FoldAddrToValueMapping Map;
  2729. if (!initializeMap(Map))
  2730. return false;
  2731. Value *CommonValue = findCommon(Map);
  2732. if (CommonValue)
  2733. AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
  2734. return CommonValue != nullptr;
  2735. }
  2736. private:
  2737. /// Initialize Map with anchor values. For address seen
  2738. /// we set the value of different field saw in this address.
  2739. /// At the same time we find a common type for different field we will
  2740. /// use to create new Phi/Select nodes. Keep it in CommonType field.
  2741. /// Return false if there is no common type found.
  2742. bool initializeMap(FoldAddrToValueMapping &Map) {
  2743. // Keep track of keys where the value is null. We will need to replace it
  2744. // with constant null when we know the common type.
  2745. SmallVector<Value *, 2> NullValue;
  2746. Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
  2747. for (auto &AM : AddrModes) {
  2748. Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
  2749. if (DV) {
  2750. auto *Type = DV->getType();
  2751. if (CommonType && CommonType != Type)
  2752. return false;
  2753. CommonType = Type;
  2754. Map[AM.OriginalValue] = DV;
  2755. } else {
  2756. NullValue.push_back(AM.OriginalValue);
  2757. }
  2758. }
  2759. assert(CommonType && "At least one non-null value must be!");
  2760. for (auto *V : NullValue)
  2761. Map[V] = Constant::getNullValue(CommonType);
  2762. return true;
  2763. }
  2764. /// We have mapping between value A and other value B where B was a field in
  2765. /// addressing mode represented by A. Also we have an original value C
  2766. /// representing an address we start with. Traversing from C through phi and
  2767. /// selects we ended up with A's in a map. This utility function tries to find
  2768. /// a value V which is a field in addressing mode C and traversing through phi
  2769. /// nodes and selects we will end up in corresponded values B in a map.
  2770. /// The utility will create a new Phi/Selects if needed.
  2771. // The simple example looks as follows:
  2772. // BB1:
  2773. // p1 = b1 + 40
  2774. // br cond BB2, BB3
  2775. // BB2:
  2776. // p2 = b2 + 40
  2777. // br BB3
  2778. // BB3:
  2779. // p = phi [p1, BB1], [p2, BB2]
  2780. // v = load p
  2781. // Map is
  2782. // p1 -> b1
  2783. // p2 -> b2
  2784. // Request is
  2785. // p -> ?
  2786. // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
  2787. Value *findCommon(FoldAddrToValueMapping &Map) {
  2788. // Tracks the simplification of newly created phi nodes. The reason we use
  2789. // this mapping is because we will add new created Phi nodes in AddrToBase.
  2790. // Simplification of Phi nodes is recursive, so some Phi node may
  2791. // be simplified after we added it to AddrToBase. In reality this
  2792. // simplification is possible only if original phi/selects were not
  2793. // simplified yet.
  2794. // Using this mapping we can find the current value in AddrToBase.
  2795. SimplificationTracker ST(SQ);
  2796. // First step, DFS to create PHI nodes for all intermediate blocks.
  2797. // Also fill traverse order for the second step.
  2798. SmallVector<Value *, 32> TraverseOrder;
  2799. InsertPlaceholders(Map, TraverseOrder, ST);
  2800. // Second Step, fill new nodes by merged values and simplify if possible.
  2801. FillPlaceholders(Map, TraverseOrder, ST);
  2802. if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
  2803. ST.destroyNewNodes(CommonType);
  2804. return nullptr;
  2805. }
  2806. // Now we'd like to match New Phi nodes to existed ones.
  2807. unsigned PhiNotMatchedCount = 0;
  2808. if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
  2809. ST.destroyNewNodes(CommonType);
  2810. return nullptr;
  2811. }
  2812. auto *Result = ST.Get(Map.find(Original)->second);
  2813. if (Result) {
  2814. NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
  2815. NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
  2816. }
  2817. return Result;
  2818. }
  2819. /// Try to match PHI node to Candidate.
  2820. /// Matcher tracks the matched Phi nodes.
  2821. bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
  2822. SmallSetVector<PHIPair, 8> &Matcher,
  2823. PhiNodeSet &PhiNodesToMatch) {
  2824. SmallVector<PHIPair, 8> WorkList;
  2825. Matcher.insert({ PHI, Candidate });
  2826. SmallSet<PHINode *, 8> MatchedPHIs;
  2827. MatchedPHIs.insert(PHI);
  2828. WorkList.push_back({ PHI, Candidate });
  2829. SmallSet<PHIPair, 8> Visited;
  2830. while (!WorkList.empty()) {
  2831. auto Item = WorkList.pop_back_val();
  2832. if (!Visited.insert(Item).second)
  2833. continue;
  2834. // We iterate over all incoming values to Phi to compare them.
  2835. // If values are different and both of them Phi and the first one is a
  2836. // Phi we added (subject to match) and both of them is in the same basic
  2837. // block then we can match our pair if values match. So we state that
  2838. // these values match and add it to work list to verify that.
  2839. for (auto B : Item.first->blocks()) {
  2840. Value *FirstValue = Item.first->getIncomingValueForBlock(B);
  2841. Value *SecondValue = Item.second->getIncomingValueForBlock(B);
  2842. if (FirstValue == SecondValue)
  2843. continue;
  2844. PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
  2845. PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
  2846. // One of them is not Phi or
  2847. // The first one is not Phi node from the set we'd like to match or
  2848. // Phi nodes from different basic blocks then
  2849. // we will not be able to match.
  2850. if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
  2851. FirstPhi->getParent() != SecondPhi->getParent())
  2852. return false;
  2853. // If we already matched them then continue.
  2854. if (Matcher.count({ FirstPhi, SecondPhi }))
  2855. continue;
  2856. // So the values are different and does not match. So we need them to
  2857. // match. (But we register no more than one match per PHI node, so that
  2858. // we won't later try to replace them twice.)
  2859. if (MatchedPHIs.insert(FirstPhi).second)
  2860. Matcher.insert({ FirstPhi, SecondPhi });
  2861. // But me must check it.
  2862. WorkList.push_back({ FirstPhi, SecondPhi });
  2863. }
  2864. }
  2865. return true;
  2866. }
  2867. /// For the given set of PHI nodes (in the SimplificationTracker) try
  2868. /// to find their equivalents.
  2869. /// Returns false if this matching fails and creation of new Phi is disabled.
  2870. bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
  2871. unsigned &PhiNotMatchedCount) {
  2872. // Matched and PhiNodesToMatch iterate their elements in a deterministic
  2873. // order, so the replacements (ReplacePhi) are also done in a deterministic
  2874. // order.
  2875. SmallSetVector<PHIPair, 8> Matched;
  2876. SmallPtrSet<PHINode *, 8> WillNotMatch;
  2877. PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
  2878. while (PhiNodesToMatch.size()) {
  2879. PHINode *PHI = *PhiNodesToMatch.begin();
  2880. // Add us, if no Phi nodes in the basic block we do not match.
  2881. WillNotMatch.clear();
  2882. WillNotMatch.insert(PHI);
  2883. // Traverse all Phis until we found equivalent or fail to do that.
  2884. bool IsMatched = false;
  2885. for (auto &P : PHI->getParent()->phis()) {
  2886. if (&P == PHI)
  2887. continue;
  2888. if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
  2889. break;
  2890. // If it does not match, collect all Phi nodes from matcher.
  2891. // if we end up with no match, them all these Phi nodes will not match
  2892. // later.
  2893. for (auto M : Matched)
  2894. WillNotMatch.insert(M.first);
  2895. Matched.clear();
  2896. }
  2897. if (IsMatched) {
  2898. // Replace all matched values and erase them.
  2899. for (auto MV : Matched)
  2900. ST.ReplacePhi(MV.first, MV.second);
  2901. Matched.clear();
  2902. continue;
  2903. }
  2904. // If we are not allowed to create new nodes then bail out.
  2905. if (!AllowNewPhiNodes)
  2906. return false;
  2907. // Just remove all seen values in matcher. They will not match anything.
  2908. PhiNotMatchedCount += WillNotMatch.size();
  2909. for (auto *P : WillNotMatch)
  2910. PhiNodesToMatch.erase(P);
  2911. }
  2912. return true;
  2913. }
  2914. /// Fill the placeholders with values from predecessors and simplify them.
  2915. void FillPlaceholders(FoldAddrToValueMapping &Map,
  2916. SmallVectorImpl<Value *> &TraverseOrder,
  2917. SimplificationTracker &ST) {
  2918. while (!TraverseOrder.empty()) {
  2919. Value *Current = TraverseOrder.pop_back_val();
  2920. assert(Map.find(Current) != Map.end() && "No node to fill!!!");
  2921. Value *V = Map[Current];
  2922. if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
  2923. // CurrentValue also must be Select.
  2924. auto *CurrentSelect = cast<SelectInst>(Current);
  2925. auto *TrueValue = CurrentSelect->getTrueValue();
  2926. assert(Map.find(TrueValue) != Map.end() && "No True Value!");
  2927. Select->setTrueValue(ST.Get(Map[TrueValue]));
  2928. auto *FalseValue = CurrentSelect->getFalseValue();
  2929. assert(Map.find(FalseValue) != Map.end() && "No False Value!");
  2930. Select->setFalseValue(ST.Get(Map[FalseValue]));
  2931. } else {
  2932. // Must be a Phi node then.
  2933. auto *PHI = cast<PHINode>(V);
  2934. // Fill the Phi node with values from predecessors.
  2935. for (auto B : predecessors(PHI->getParent())) {
  2936. Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
  2937. assert(Map.find(PV) != Map.end() && "No predecessor Value!");
  2938. PHI->addIncoming(ST.Get(Map[PV]), B);
  2939. }
  2940. }
  2941. Map[Current] = ST.Simplify(V);
  2942. }
  2943. }
  2944. /// Starting from original value recursively iterates over def-use chain up to
  2945. /// known ending values represented in a map. For each traversed phi/select
  2946. /// inserts a placeholder Phi or Select.
  2947. /// Reports all new created Phi/Select nodes by adding them to set.
  2948. /// Also reports and order in what values have been traversed.
  2949. void InsertPlaceholders(FoldAddrToValueMapping &Map,
  2950. SmallVectorImpl<Value *> &TraverseOrder,
  2951. SimplificationTracker &ST) {
  2952. SmallVector<Value *, 32> Worklist;
  2953. assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
  2954. "Address must be a Phi or Select node");
  2955. auto *Dummy = UndefValue::get(CommonType);
  2956. Worklist.push_back(Original);
  2957. while (!Worklist.empty()) {
  2958. Value *Current = Worklist.pop_back_val();
  2959. // if it is already visited or it is an ending value then skip it.
  2960. if (Map.find(Current) != Map.end())
  2961. continue;
  2962. TraverseOrder.push_back(Current);
  2963. // CurrentValue must be a Phi node or select. All others must be covered
  2964. // by anchors.
  2965. if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
  2966. // Is it OK to get metadata from OrigSelect?!
  2967. // Create a Select placeholder with dummy value.
  2968. SelectInst *Select = SelectInst::Create(
  2969. CurrentSelect->getCondition(), Dummy, Dummy,
  2970. CurrentSelect->getName(), CurrentSelect, CurrentSelect);
  2971. Map[Current] = Select;
  2972. ST.insertNewSelect(Select);
  2973. // We are interested in True and False values.
  2974. Worklist.push_back(CurrentSelect->getTrueValue());
  2975. Worklist.push_back(CurrentSelect->getFalseValue());
  2976. } else {
  2977. // It must be a Phi node then.
  2978. PHINode *CurrentPhi = cast<PHINode>(Current);
  2979. unsigned PredCount = CurrentPhi->getNumIncomingValues();
  2980. PHINode *PHI =
  2981. PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
  2982. Map[Current] = PHI;
  2983. ST.insertNewPhi(PHI);
  2984. for (Value *P : CurrentPhi->incoming_values())
  2985. Worklist.push_back(P);
  2986. }
  2987. }
  2988. }
  2989. bool addrModeCombiningAllowed() {
  2990. if (DisableComplexAddrModes)
  2991. return false;
  2992. switch (DifferentField) {
  2993. default:
  2994. return false;
  2995. case ExtAddrMode::BaseRegField:
  2996. return AddrSinkCombineBaseReg;
  2997. case ExtAddrMode::BaseGVField:
  2998. return AddrSinkCombineBaseGV;
  2999. case ExtAddrMode::BaseOffsField:
  3000. return AddrSinkCombineBaseOffs;
  3001. case ExtAddrMode::ScaledRegField:
  3002. return AddrSinkCombineScaledReg;
  3003. }
  3004. }
  3005. };
  3006. } // end anonymous namespace
  3007. /// Try adding ScaleReg*Scale to the current addressing mode.
  3008. /// Return true and update AddrMode if this addr mode is legal for the target,
  3009. /// false if not.
  3010. bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
  3011. unsigned Depth) {
  3012. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  3013. // mode. Just process that directly.
  3014. if (Scale == 1)
  3015. return matchAddr(ScaleReg, Depth);
  3016. // If the scale is 0, it takes nothing to add this.
  3017. if (Scale == 0)
  3018. return true;
  3019. // If we already have a scale of this value, we can add to it, otherwise, we
  3020. // need an available scale field.
  3021. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  3022. return false;
  3023. ExtAddrMode TestAddrMode = AddrMode;
  3024. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  3025. // [A+B + A*7] -> [B+A*8].
  3026. TestAddrMode.Scale += Scale;
  3027. TestAddrMode.ScaledReg = ScaleReg;
  3028. // If the new address isn't legal, bail out.
  3029. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  3030. return false;
  3031. // It was legal, so commit it.
  3032. AddrMode = TestAddrMode;
  3033. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  3034. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  3035. // X*Scale + C*Scale to addr mode.
  3036. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  3037. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  3038. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  3039. TestAddrMode.InBounds = false;
  3040. TestAddrMode.ScaledReg = AddLHS;
  3041. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  3042. // If this addressing mode is legal, commit it and remember that we folded
  3043. // this instruction.
  3044. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  3045. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  3046. AddrMode = TestAddrMode;
  3047. return true;
  3048. }
  3049. }
  3050. // Otherwise, not (x+c)*scale, just return what we have.
  3051. return true;
  3052. }
  3053. /// This is a little filter, which returns true if an addressing computation
  3054. /// involving I might be folded into a load/store accessing it.
  3055. /// This doesn't need to be perfect, but needs to accept at least
  3056. /// the set of instructions that MatchOperationAddr can.
  3057. static bool MightBeFoldableInst(Instruction *I) {
  3058. switch (I->getOpcode()) {
  3059. case Instruction::BitCast:
  3060. case Instruction::AddrSpaceCast:
  3061. // Don't touch identity bitcasts.
  3062. if (I->getType() == I->getOperand(0)->getType())
  3063. return false;
  3064. return I->getType()->isIntOrPtrTy();
  3065. case Instruction::PtrToInt:
  3066. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3067. return true;
  3068. case Instruction::IntToPtr:
  3069. // We know the input is intptr_t, so this is foldable.
  3070. return true;
  3071. case Instruction::Add:
  3072. return true;
  3073. case Instruction::Mul:
  3074. case Instruction::Shl:
  3075. // Can only handle X*C and X << C.
  3076. return isa<ConstantInt>(I->getOperand(1));
  3077. case Instruction::GetElementPtr:
  3078. return true;
  3079. default:
  3080. return false;
  3081. }
  3082. }
  3083. /// Check whether or not \p Val is a legal instruction for \p TLI.
  3084. /// \note \p Val is assumed to be the product of some type promotion.
  3085. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  3086. /// to be legal, as the non-promoted value would have had the same state.
  3087. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  3088. const DataLayout &DL, Value *Val) {
  3089. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  3090. if (!PromotedInst)
  3091. return false;
  3092. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  3093. // If the ISDOpcode is undefined, it was undefined before the promotion.
  3094. if (!ISDOpcode)
  3095. return true;
  3096. // Otherwise, check if the promoted instruction is legal or not.
  3097. return TLI.isOperationLegalOrCustom(
  3098. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  3099. }
  3100. namespace {
  3101. /// Hepler class to perform type promotion.
  3102. class TypePromotionHelper {
  3103. /// Utility function to add a promoted instruction \p ExtOpnd to
  3104. /// \p PromotedInsts and record the type of extension we have seen.
  3105. static void addPromotedInst(InstrToOrigTy &PromotedInsts,
  3106. Instruction *ExtOpnd,
  3107. bool IsSExt) {
  3108. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3109. InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
  3110. if (It != PromotedInsts.end()) {
  3111. // If the new extension is same as original, the information in
  3112. // PromotedInsts[ExtOpnd] is still correct.
  3113. if (It->second.getInt() == ExtTy)
  3114. return;
  3115. // Now the new extension is different from old extension, we make
  3116. // the type information invalid by setting extension type to
  3117. // BothExtension.
  3118. ExtTy = BothExtension;
  3119. }
  3120. PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
  3121. }
  3122. /// Utility function to query the original type of instruction \p Opnd
  3123. /// with a matched extension type. If the extension doesn't match, we
  3124. /// cannot use the information we had on the original type.
  3125. /// BothExtension doesn't match any extension type.
  3126. static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
  3127. Instruction *Opnd,
  3128. bool IsSExt) {
  3129. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3130. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  3131. if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
  3132. return It->second.getPointer();
  3133. return nullptr;
  3134. }
  3135. /// Utility function to check whether or not a sign or zero extension
  3136. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  3137. /// either using the operands of \p Inst or promoting \p Inst.
  3138. /// The type of the extension is defined by \p IsSExt.
  3139. /// In other words, check if:
  3140. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  3141. /// #1 Promotion applies:
  3142. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  3143. /// #2 Operand reuses:
  3144. /// ext opnd1 to ConsideredExtType.
  3145. /// \p PromotedInsts maps the instructions to their type before promotion.
  3146. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  3147. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  3148. /// Utility function to determine if \p OpIdx should be promoted when
  3149. /// promoting \p Inst.
  3150. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  3151. return !(isa<SelectInst>(Inst) && OpIdx == 0);
  3152. }
  3153. /// Utility function to promote the operand of \p Ext when this
  3154. /// operand is a promotable trunc or sext or zext.
  3155. /// \p PromotedInsts maps the instructions to their type before promotion.
  3156. /// \p CreatedInstsCost[out] contains the cost of all instructions
  3157. /// created to promote the operand of Ext.
  3158. /// Newly added extensions are inserted in \p Exts.
  3159. /// Newly added truncates are inserted in \p Truncs.
  3160. /// Should never be called directly.
  3161. /// \return The promoted value which is used instead of Ext.
  3162. static Value *promoteOperandForTruncAndAnyExt(
  3163. Instruction *Ext, TypePromotionTransaction &TPT,
  3164. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3165. SmallVectorImpl<Instruction *> *Exts,
  3166. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  3167. /// Utility function to promote the operand of \p Ext when this
  3168. /// operand is promotable and is not a supported trunc or sext.
  3169. /// \p PromotedInsts maps the instructions to their type before promotion.
  3170. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  3171. /// created to promote the operand of Ext.
  3172. /// Newly added extensions are inserted in \p Exts.
  3173. /// Newly added truncates are inserted in \p Truncs.
  3174. /// Should never be called directly.
  3175. /// \return The promoted value which is used instead of Ext.
  3176. static Value *promoteOperandForOther(Instruction *Ext,
  3177. TypePromotionTransaction &TPT,
  3178. InstrToOrigTy &PromotedInsts,
  3179. unsigned &CreatedInstsCost,
  3180. SmallVectorImpl<Instruction *> *Exts,
  3181. SmallVectorImpl<Instruction *> *Truncs,
  3182. const TargetLowering &TLI, bool IsSExt);
  3183. /// \see promoteOperandForOther.
  3184. static Value *signExtendOperandForOther(
  3185. Instruction *Ext, TypePromotionTransaction &TPT,
  3186. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3187. SmallVectorImpl<Instruction *> *Exts,
  3188. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3189. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3190. Exts, Truncs, TLI, true);
  3191. }
  3192. /// \see promoteOperandForOther.
  3193. static Value *zeroExtendOperandForOther(
  3194. Instruction *Ext, TypePromotionTransaction &TPT,
  3195. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3196. SmallVectorImpl<Instruction *> *Exts,
  3197. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3198. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3199. Exts, Truncs, TLI, false);
  3200. }
  3201. public:
  3202. /// Type for the utility function that promotes the operand of Ext.
  3203. using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
  3204. InstrToOrigTy &PromotedInsts,
  3205. unsigned &CreatedInstsCost,
  3206. SmallVectorImpl<Instruction *> *Exts,
  3207. SmallVectorImpl<Instruction *> *Truncs,
  3208. const TargetLowering &TLI);
  3209. /// Given a sign/zero extend instruction \p Ext, return the appropriate
  3210. /// action to promote the operand of \p Ext instead of using Ext.
  3211. /// \return NULL if no promotable action is possible with the current
  3212. /// sign extension.
  3213. /// \p InsertedInsts keeps track of all the instructions inserted by the
  3214. /// other CodeGenPrepare optimizations. This information is important
  3215. /// because we do not want to promote these instructions as CodeGenPrepare
  3216. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  3217. /// \p PromotedInsts maps the instructions to their type before promotion.
  3218. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3219. const TargetLowering &TLI,
  3220. const InstrToOrigTy &PromotedInsts);
  3221. };
  3222. } // end anonymous namespace
  3223. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  3224. Type *ConsideredExtType,
  3225. const InstrToOrigTy &PromotedInsts,
  3226. bool IsSExt) {
  3227. // The promotion helper does not know how to deal with vector types yet.
  3228. // To be able to fix that, we would need to fix the places where we
  3229. // statically extend, e.g., constants and such.
  3230. if (Inst->getType()->isVectorTy())
  3231. return false;
  3232. // We can always get through zext.
  3233. if (isa<ZExtInst>(Inst))
  3234. return true;
  3235. // sext(sext) is ok too.
  3236. if (IsSExt && isa<SExtInst>(Inst))
  3237. return true;
  3238. // We can get through binary operator, if it is legal. In other words, the
  3239. // binary operator must have a nuw or nsw flag.
  3240. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  3241. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  3242. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  3243. (IsSExt && BinOp->hasNoSignedWrap())))
  3244. return true;
  3245. // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
  3246. if ((Inst->getOpcode() == Instruction::And ||
  3247. Inst->getOpcode() == Instruction::Or))
  3248. return true;
  3249. // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
  3250. if (Inst->getOpcode() == Instruction::Xor) {
  3251. const ConstantInt *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1));
  3252. // Make sure it is not a NOT.
  3253. if (Cst && !Cst->getValue().isAllOnesValue())
  3254. return true;
  3255. }
  3256. // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
  3257. // It may change a poisoned value into a regular value, like
  3258. // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
  3259. // poisoned value regular value
  3260. // It should be OK since undef covers valid value.
  3261. if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
  3262. return true;
  3263. // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
  3264. // It may change a poisoned value into a regular value, like
  3265. // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
  3266. // poisoned value regular value
  3267. // It should be OK since undef covers valid value.
  3268. if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
  3269. const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
  3270. if (ExtInst->hasOneUse()) {
  3271. const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
  3272. if (AndInst && AndInst->getOpcode() == Instruction::And) {
  3273. const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
  3274. if (Cst &&
  3275. Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
  3276. return true;
  3277. }
  3278. }
  3279. }
  3280. // Check if we can do the following simplification.
  3281. // ext(trunc(opnd)) --> ext(opnd)
  3282. if (!isa<TruncInst>(Inst))
  3283. return false;
  3284. Value *OpndVal = Inst->getOperand(0);
  3285. // Check if we can use this operand in the extension.
  3286. // If the type is larger than the result type of the extension, we cannot.
  3287. if (!OpndVal->getType()->isIntegerTy() ||
  3288. OpndVal->getType()->getIntegerBitWidth() >
  3289. ConsideredExtType->getIntegerBitWidth())
  3290. return false;
  3291. // If the operand of the truncate is not an instruction, we will not have
  3292. // any information on the dropped bits.
  3293. // (Actually we could for constant but it is not worth the extra logic).
  3294. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  3295. if (!Opnd)
  3296. return false;
  3297. // Check if the source of the type is narrow enough.
  3298. // I.e., check that trunc just drops extended bits of the same kind of
  3299. // the extension.
  3300. // #1 get the type of the operand and check the kind of the extended bits.
  3301. const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
  3302. if (OpndType)
  3303. ;
  3304. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  3305. OpndType = Opnd->getOperand(0)->getType();
  3306. else
  3307. return false;
  3308. // #2 check that the truncate just drops extended bits.
  3309. return Inst->getType()->getIntegerBitWidth() >=
  3310. OpndType->getIntegerBitWidth();
  3311. }
  3312. TypePromotionHelper::Action TypePromotionHelper::getAction(
  3313. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3314. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  3315. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  3316. "Unexpected instruction type");
  3317. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  3318. Type *ExtTy = Ext->getType();
  3319. bool IsSExt = isa<SExtInst>(Ext);
  3320. // If the operand of the extension is not an instruction, we cannot
  3321. // get through.
  3322. // If it, check we can get through.
  3323. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  3324. return nullptr;
  3325. // Do not promote if the operand has been added by codegenprepare.
  3326. // Otherwise, it means we are undoing an optimization that is likely to be
  3327. // redone, thus causing potential infinite loop.
  3328. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  3329. return nullptr;
  3330. // SExt or Trunc instructions.
  3331. // Return the related handler.
  3332. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  3333. isa<ZExtInst>(ExtOpnd))
  3334. return promoteOperandForTruncAndAnyExt;
  3335. // Regular instruction.
  3336. // Abort early if we will have to insert non-free instructions.
  3337. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  3338. return nullptr;
  3339. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  3340. }
  3341. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  3342. Instruction *SExt, TypePromotionTransaction &TPT,
  3343. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3344. SmallVectorImpl<Instruction *> *Exts,
  3345. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3346. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  3347. // get through it and this method should not be called.
  3348. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  3349. Value *ExtVal = SExt;
  3350. bool HasMergedNonFreeExt = false;
  3351. if (isa<ZExtInst>(SExtOpnd)) {
  3352. // Replace s|zext(zext(opnd))
  3353. // => zext(opnd).
  3354. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  3355. Value *ZExt =
  3356. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  3357. TPT.replaceAllUsesWith(SExt, ZExt);
  3358. TPT.eraseInstruction(SExt);
  3359. ExtVal = ZExt;
  3360. } else {
  3361. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  3362. // => z|sext(opnd).
  3363. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  3364. }
  3365. CreatedInstsCost = 0;
  3366. // Remove dead code.
  3367. if (SExtOpnd->use_empty())
  3368. TPT.eraseInstruction(SExtOpnd);
  3369. // Check if the extension is still needed.
  3370. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  3371. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  3372. if (ExtInst) {
  3373. if (Exts)
  3374. Exts->push_back(ExtInst);
  3375. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  3376. }
  3377. return ExtVal;
  3378. }
  3379. // At this point we have: ext ty opnd to ty.
  3380. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  3381. Value *NextVal = ExtInst->getOperand(0);
  3382. TPT.eraseInstruction(ExtInst, NextVal);
  3383. return NextVal;
  3384. }
  3385. Value *TypePromotionHelper::promoteOperandForOther(
  3386. Instruction *Ext, TypePromotionTransaction &TPT,
  3387. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3388. SmallVectorImpl<Instruction *> *Exts,
  3389. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  3390. bool IsSExt) {
  3391. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  3392. // get through it and this method should not be called.
  3393. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  3394. CreatedInstsCost = 0;
  3395. if (!ExtOpnd->hasOneUse()) {
  3396. // ExtOpnd will be promoted.
  3397. // All its uses, but Ext, will need to use a truncated value of the
  3398. // promoted version.
  3399. // Create the truncate now.
  3400. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  3401. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  3402. // Insert it just after the definition.
  3403. ITrunc->moveAfter(ExtOpnd);
  3404. if (Truncs)
  3405. Truncs->push_back(ITrunc);
  3406. }
  3407. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  3408. // Restore the operand of Ext (which has been replaced by the previous call
  3409. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  3410. TPT.setOperand(Ext, 0, ExtOpnd);
  3411. }
  3412. // Get through the Instruction:
  3413. // 1. Update its type.
  3414. // 2. Replace the uses of Ext by Inst.
  3415. // 3. Extend each operand that needs to be extended.
  3416. // Remember the original type of the instruction before promotion.
  3417. // This is useful to know that the high bits are sign extended bits.
  3418. addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
  3419. // Step #1.
  3420. TPT.mutateType(ExtOpnd, Ext->getType());
  3421. // Step #2.
  3422. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  3423. // Step #3.
  3424. Instruction *ExtForOpnd = Ext;
  3425. LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
  3426. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  3427. ++OpIdx) {
  3428. LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  3429. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  3430. !shouldExtOperand(ExtOpnd, OpIdx)) {
  3431. LLVM_DEBUG(dbgs() << "No need to propagate\n");
  3432. continue;
  3433. }
  3434. // Check if we can statically extend the operand.
  3435. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  3436. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  3437. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3438. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  3439. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  3440. : Cst->getValue().zext(BitWidth);
  3441. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  3442. continue;
  3443. }
  3444. // UndefValue are typed, so we have to statically sign extend them.
  3445. if (isa<UndefValue>(Opnd)) {
  3446. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3447. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  3448. continue;
  3449. }
  3450. // Otherwise we have to explicitly sign extend the operand.
  3451. // Check if Ext was reused to extend an operand.
  3452. if (!ExtForOpnd) {
  3453. // If yes, create a new one.
  3454. LLVM_DEBUG(dbgs() << "More operands to ext\n");
  3455. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  3456. : TPT.createZExt(Ext, Opnd, Ext->getType());
  3457. if (!isa<Instruction>(ValForExtOpnd)) {
  3458. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  3459. continue;
  3460. }
  3461. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  3462. }
  3463. if (Exts)
  3464. Exts->push_back(ExtForOpnd);
  3465. TPT.setOperand(ExtForOpnd, 0, Opnd);
  3466. // Move the sign extension before the insertion point.
  3467. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  3468. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  3469. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  3470. // If more sext are required, new instructions will have to be created.
  3471. ExtForOpnd = nullptr;
  3472. }
  3473. if (ExtForOpnd == Ext) {
  3474. LLVM_DEBUG(dbgs() << "Extension is useless now\n");
  3475. TPT.eraseInstruction(Ext);
  3476. }
  3477. return ExtOpnd;
  3478. }
  3479. /// Check whether or not promoting an instruction to a wider type is profitable.
  3480. /// \p NewCost gives the cost of extension instructions created by the
  3481. /// promotion.
  3482. /// \p OldCost gives the cost of extension instructions before the promotion
  3483. /// plus the number of instructions that have been
  3484. /// matched in the addressing mode the promotion.
  3485. /// \p PromotedOperand is the value that has been promoted.
  3486. /// \return True if the promotion is profitable, false otherwise.
  3487. bool AddressingModeMatcher::isPromotionProfitable(
  3488. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  3489. LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
  3490. << '\n');
  3491. // The cost of the new extensions is greater than the cost of the
  3492. // old extension plus what we folded.
  3493. // This is not profitable.
  3494. if (NewCost > OldCost)
  3495. return false;
  3496. if (NewCost < OldCost)
  3497. return true;
  3498. // The promotion is neutral but it may help folding the sign extension in
  3499. // loads for instance.
  3500. // Check that we did not create an illegal instruction.
  3501. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  3502. }
  3503. /// Given an instruction or constant expr, see if we can fold the operation
  3504. /// into the addressing mode. If so, update the addressing mode and return
  3505. /// true, otherwise return false without modifying AddrMode.
  3506. /// If \p MovedAway is not NULL, it contains the information of whether or
  3507. /// not AddrInst has to be folded into the addressing mode on success.
  3508. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  3509. /// because it has been moved away.
  3510. /// Thus AddrInst must not be added in the matched instructions.
  3511. /// This state can happen when AddrInst is a sext, since it may be moved away.
  3512. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  3513. /// not be referenced anymore.
  3514. bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
  3515. unsigned Depth,
  3516. bool *MovedAway) {
  3517. // Avoid exponential behavior on extremely deep expression trees.
  3518. if (Depth >= 5) return false;
  3519. // By default, all matched instructions stay in place.
  3520. if (MovedAway)
  3521. *MovedAway = false;
  3522. switch (Opcode) {
  3523. case Instruction::PtrToInt:
  3524. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3525. return matchAddr(AddrInst->getOperand(0), Depth);
  3526. case Instruction::IntToPtr: {
  3527. auto AS = AddrInst->getType()->getPointerAddressSpace();
  3528. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  3529. // This inttoptr is a no-op if the integer type is pointer sized.
  3530. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  3531. return matchAddr(AddrInst->getOperand(0), Depth);
  3532. return false;
  3533. }
  3534. case Instruction::BitCast:
  3535. // BitCast is always a noop, and we can handle it as long as it is
  3536. // int->int or pointer->pointer (we don't want int<->fp or something).
  3537. if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
  3538. // Don't touch identity bitcasts. These were probably put here by LSR,
  3539. // and we don't want to mess around with them. Assume it knows what it
  3540. // is doing.
  3541. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  3542. return matchAddr(AddrInst->getOperand(0), Depth);
  3543. return false;
  3544. case Instruction::AddrSpaceCast: {
  3545. unsigned SrcAS
  3546. = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  3547. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  3548. if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3549. return matchAddr(AddrInst->getOperand(0), Depth);
  3550. return false;
  3551. }
  3552. case Instruction::Add: {
  3553. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  3554. ExtAddrMode BackupAddrMode = AddrMode;
  3555. unsigned OldSize = AddrModeInsts.size();
  3556. // Start a transaction at this point.
  3557. // The LHS may match but not the RHS.
  3558. // Therefore, we need a higher level restoration point to undo partially
  3559. // matched operation.
  3560. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3561. TPT.getRestorationPoint();
  3562. AddrMode.InBounds = false;
  3563. if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
  3564. matchAddr(AddrInst->getOperand(0), Depth+1))
  3565. return true;
  3566. // Restore the old addr mode info.
  3567. AddrMode = BackupAddrMode;
  3568. AddrModeInsts.resize(OldSize);
  3569. TPT.rollback(LastKnownGood);
  3570. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  3571. if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
  3572. matchAddr(AddrInst->getOperand(1), Depth+1))
  3573. return true;
  3574. // Otherwise we definitely can't merge the ADD in.
  3575. AddrMode = BackupAddrMode;
  3576. AddrModeInsts.resize(OldSize);
  3577. TPT.rollback(LastKnownGood);
  3578. break;
  3579. }
  3580. //case Instruction::Or:
  3581. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  3582. //break;
  3583. case Instruction::Mul:
  3584. case Instruction::Shl: {
  3585. // Can only handle X*C and X << C.
  3586. AddrMode.InBounds = false;
  3587. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  3588. if (!RHS || RHS->getBitWidth() > 64)
  3589. return false;
  3590. int64_t Scale = RHS->getSExtValue();
  3591. if (Opcode == Instruction::Shl)
  3592. Scale = 1LL << Scale;
  3593. return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  3594. }
  3595. case Instruction::GetElementPtr: {
  3596. // Scan the GEP. We check it if it contains constant offsets and at most
  3597. // one variable offset.
  3598. int VariableOperand = -1;
  3599. unsigned VariableScale = 0;
  3600. int64_t ConstantOffset = 0;
  3601. gep_type_iterator GTI = gep_type_begin(AddrInst);
  3602. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  3603. if (StructType *STy = GTI.getStructTypeOrNull()) {
  3604. const StructLayout *SL = DL.getStructLayout(STy);
  3605. unsigned Idx =
  3606. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  3607. ConstantOffset += SL->getElementOffset(Idx);
  3608. } else {
  3609. uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
  3610. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  3611. const APInt &CVal = CI->getValue();
  3612. if (CVal.getMinSignedBits() <= 64) {
  3613. ConstantOffset += CVal.getSExtValue() * TypeSize;
  3614. continue;
  3615. }
  3616. }
  3617. if (TypeSize) { // Scales of zero don't do anything.
  3618. // We only allow one variable index at the moment.
  3619. if (VariableOperand != -1)
  3620. return false;
  3621. // Remember the variable index.
  3622. VariableOperand = i;
  3623. VariableScale = TypeSize;
  3624. }
  3625. }
  3626. }
  3627. // A common case is for the GEP to only do a constant offset. In this case,
  3628. // just add it to the disp field and check validity.
  3629. if (VariableOperand == -1) {
  3630. AddrMode.BaseOffs += ConstantOffset;
  3631. if (ConstantOffset == 0 ||
  3632. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  3633. // Check to see if we can fold the base pointer in too.
  3634. if (matchAddr(AddrInst->getOperand(0), Depth+1)) {
  3635. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  3636. AddrMode.InBounds = false;
  3637. return true;
  3638. }
  3639. } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
  3640. TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
  3641. ConstantOffset > 0) {
  3642. // Record GEPs with non-zero offsets as candidates for splitting in the
  3643. // event that the offset cannot fit into the r+i addressing mode.
  3644. // Simple and common case that only one GEP is used in calculating the
  3645. // address for the memory access.
  3646. Value *Base = AddrInst->getOperand(0);
  3647. auto *BaseI = dyn_cast<Instruction>(Base);
  3648. auto *GEP = cast<GetElementPtrInst>(AddrInst);
  3649. if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
  3650. (BaseI && !isa<CastInst>(BaseI) &&
  3651. !isa<GetElementPtrInst>(BaseI))) {
  3652. // Make sure the parent block allows inserting non-PHI instructions
  3653. // before the terminator.
  3654. BasicBlock *Parent =
  3655. BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
  3656. if (!Parent->getTerminator()->isEHPad())
  3657. LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
  3658. }
  3659. }
  3660. AddrMode.BaseOffs -= ConstantOffset;
  3661. return false;
  3662. }
  3663. // Save the valid addressing mode in case we can't match.
  3664. ExtAddrMode BackupAddrMode = AddrMode;
  3665. unsigned OldSize = AddrModeInsts.size();
  3666. // See if the scale and offset amount is valid for this target.
  3667. AddrMode.BaseOffs += ConstantOffset;
  3668. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  3669. AddrMode.InBounds = false;
  3670. // Match the base operand of the GEP.
  3671. if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
  3672. // If it couldn't be matched, just stuff the value in a register.
  3673. if (AddrMode.HasBaseReg) {
  3674. AddrMode = BackupAddrMode;
  3675. AddrModeInsts.resize(OldSize);
  3676. return false;
  3677. }
  3678. AddrMode.HasBaseReg = true;
  3679. AddrMode.BaseReg = AddrInst->getOperand(0);
  3680. }
  3681. // Match the remaining variable portion of the GEP.
  3682. if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  3683. Depth)) {
  3684. // If it couldn't be matched, try stuffing the base into a register
  3685. // instead of matching it, and retrying the match of the scale.
  3686. AddrMode = BackupAddrMode;
  3687. AddrModeInsts.resize(OldSize);
  3688. if (AddrMode.HasBaseReg)
  3689. return false;
  3690. AddrMode.HasBaseReg = true;
  3691. AddrMode.BaseReg = AddrInst->getOperand(0);
  3692. AddrMode.BaseOffs += ConstantOffset;
  3693. if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
  3694. VariableScale, Depth)) {
  3695. // If even that didn't work, bail.
  3696. AddrMode = BackupAddrMode;
  3697. AddrModeInsts.resize(OldSize);
  3698. return false;
  3699. }
  3700. }
  3701. return true;
  3702. }
  3703. case Instruction::SExt:
  3704. case Instruction::ZExt: {
  3705. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  3706. if (!Ext)
  3707. return false;
  3708. // Try to move this ext out of the way of the addressing mode.
  3709. // Ask for a method for doing so.
  3710. TypePromotionHelper::Action TPH =
  3711. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  3712. if (!TPH)
  3713. return false;
  3714. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3715. TPT.getRestorationPoint();
  3716. unsigned CreatedInstsCost = 0;
  3717. unsigned ExtCost = !TLI.isExtFree(Ext);
  3718. Value *PromotedOperand =
  3719. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  3720. // SExt has been moved away.
  3721. // Thus either it will be rematched later in the recursive calls or it is
  3722. // gone. Anyway, we must not fold it into the addressing mode at this point.
  3723. // E.g.,
  3724. // op = add opnd, 1
  3725. // idx = ext op
  3726. // addr = gep base, idx
  3727. // is now:
  3728. // promotedOpnd = ext opnd <- no match here
  3729. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  3730. // addr = gep base, op <- match
  3731. if (MovedAway)
  3732. *MovedAway = true;
  3733. assert(PromotedOperand &&
  3734. "TypePromotionHelper should have filtered out those cases");
  3735. ExtAddrMode BackupAddrMode = AddrMode;
  3736. unsigned OldSize = AddrModeInsts.size();
  3737. if (!matchAddr(PromotedOperand, Depth) ||
  3738. // The total of the new cost is equal to the cost of the created
  3739. // instructions.
  3740. // The total of the old cost is equal to the cost of the extension plus
  3741. // what we have saved in the addressing mode.
  3742. !isPromotionProfitable(CreatedInstsCost,
  3743. ExtCost + (AddrModeInsts.size() - OldSize),
  3744. PromotedOperand)) {
  3745. AddrMode = BackupAddrMode;
  3746. AddrModeInsts.resize(OldSize);
  3747. LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  3748. TPT.rollback(LastKnownGood);
  3749. return false;
  3750. }
  3751. return true;
  3752. }
  3753. }
  3754. return false;
  3755. }
  3756. /// If we can, try to add the value of 'Addr' into the current addressing mode.
  3757. /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
  3758. /// unmodified. This assumes that Addr is either a pointer type or intptr_t
  3759. /// for the target.
  3760. ///
  3761. bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
  3762. // Start a transaction at this point that we will rollback if the matching
  3763. // fails.
  3764. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3765. TPT.getRestorationPoint();
  3766. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  3767. // Fold in immediates if legal for the target.
  3768. AddrMode.BaseOffs += CI->getSExtValue();
  3769. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3770. return true;
  3771. AddrMode.BaseOffs -= CI->getSExtValue();
  3772. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  3773. // If this is a global variable, try to fold it into the addressing mode.
  3774. if (!AddrMode.BaseGV) {
  3775. AddrMode.BaseGV = GV;
  3776. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3777. return true;
  3778. AddrMode.BaseGV = nullptr;
  3779. }
  3780. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  3781. ExtAddrMode BackupAddrMode = AddrMode;
  3782. unsigned OldSize = AddrModeInsts.size();
  3783. // Check to see if it is possible to fold this operation.
  3784. bool MovedAway = false;
  3785. if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  3786. // This instruction may have been moved away. If so, there is nothing
  3787. // to check here.
  3788. if (MovedAway)
  3789. return true;
  3790. // Okay, it's possible to fold this. Check to see if it is actually
  3791. // *profitable* to do so. We use a simple cost model to avoid increasing
  3792. // register pressure too much.
  3793. if (I->hasOneUse() ||
  3794. isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  3795. AddrModeInsts.push_back(I);
  3796. return true;
  3797. }
  3798. // It isn't profitable to do this, roll back.
  3799. //cerr << "NOT FOLDING: " << *I;
  3800. AddrMode = BackupAddrMode;
  3801. AddrModeInsts.resize(OldSize);
  3802. TPT.rollback(LastKnownGood);
  3803. }
  3804. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  3805. if (matchOperationAddr(CE, CE->getOpcode(), Depth))
  3806. return true;
  3807. TPT.rollback(LastKnownGood);
  3808. } else if (isa<ConstantPointerNull>(Addr)) {
  3809. // Null pointer gets folded without affecting the addressing mode.
  3810. return true;
  3811. }
  3812. // Worse case, the target should support [reg] addressing modes. :)
  3813. if (!AddrMode.HasBaseReg) {
  3814. AddrMode.HasBaseReg = true;
  3815. AddrMode.BaseReg = Addr;
  3816. // Still check for legality in case the target supports [imm] but not [i+r].
  3817. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3818. return true;
  3819. AddrMode.HasBaseReg = false;
  3820. AddrMode.BaseReg = nullptr;
  3821. }
  3822. // If the base register is already taken, see if we can do [r+r].
  3823. if (AddrMode.Scale == 0) {
  3824. AddrMode.Scale = 1;
  3825. AddrMode.ScaledReg = Addr;
  3826. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3827. return true;
  3828. AddrMode.Scale = 0;
  3829. AddrMode.ScaledReg = nullptr;
  3830. }
  3831. // Couldn't match.
  3832. TPT.rollback(LastKnownGood);
  3833. return false;
  3834. }
  3835. /// Check to see if all uses of OpVal by the specified inline asm call are due
  3836. /// to memory operands. If so, return true, otherwise return false.
  3837. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  3838. const TargetLowering &TLI,
  3839. const TargetRegisterInfo &TRI) {
  3840. const Function *F = CI->getFunction();
  3841. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3842. TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
  3843. ImmutableCallSite(CI));
  3844. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3845. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3846. // Compute the constraint code and ConstraintType to use.
  3847. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  3848. // If this asm operand is our Value*, and if it isn't an indirect memory
  3849. // operand, we can't fold it!
  3850. if (OpInfo.CallOperandVal == OpVal &&
  3851. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  3852. !OpInfo.isIndirect))
  3853. return false;
  3854. }
  3855. return true;
  3856. }
  3857. // Max number of memory uses to look at before aborting the search to conserve
  3858. // compile time.
  3859. static constexpr int MaxMemoryUsesToScan = 20;
  3860. /// Recursively walk all the uses of I until we find a memory use.
  3861. /// If we find an obviously non-foldable instruction, return true.
  3862. /// Add the ultimately found memory instructions to MemoryUses.
  3863. static bool FindAllMemoryUses(
  3864. Instruction *I,
  3865. SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
  3866. SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
  3867. const TargetRegisterInfo &TRI, int SeenInsts = 0) {
  3868. // If we already considered this instruction, we're done.
  3869. if (!ConsideredInsts.insert(I).second)
  3870. return false;
  3871. // If this is an obviously unfoldable instruction, bail out.
  3872. if (!MightBeFoldableInst(I))
  3873. return true;
  3874. const bool OptSize = I->getFunction()->hasOptSize();
  3875. // Loop over all the uses, recursively processing them.
  3876. for (Use &U : I->uses()) {
  3877. // Conservatively return true if we're seeing a large number or a deep chain
  3878. // of users. This avoids excessive compilation times in pathological cases.
  3879. if (SeenInsts++ >= MaxMemoryUsesToScan)
  3880. return true;
  3881. Instruction *UserI = cast<Instruction>(U.getUser());
  3882. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  3883. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  3884. continue;
  3885. }
  3886. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  3887. unsigned opNo = U.getOperandNo();
  3888. if (opNo != StoreInst::getPointerOperandIndex())
  3889. return true; // Storing addr, not into addr.
  3890. MemoryUses.push_back(std::make_pair(SI, opNo));
  3891. continue;
  3892. }
  3893. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
  3894. unsigned opNo = U.getOperandNo();
  3895. if (opNo != AtomicRMWInst::getPointerOperandIndex())
  3896. return true; // Storing addr, not into addr.
  3897. MemoryUses.push_back(std::make_pair(RMW, opNo));
  3898. continue;
  3899. }
  3900. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
  3901. unsigned opNo = U.getOperandNo();
  3902. if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
  3903. return true; // Storing addr, not into addr.
  3904. MemoryUses.push_back(std::make_pair(CmpX, opNo));
  3905. continue;
  3906. }
  3907. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  3908. // If this is a cold call, we can sink the addressing calculation into
  3909. // the cold path. See optimizeCallInst
  3910. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  3911. continue;
  3912. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  3913. if (!IA) return true;
  3914. // If this is a memory operand, we're cool, otherwise bail out.
  3915. if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
  3916. return true;
  3917. continue;
  3918. }
  3919. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
  3920. SeenInsts))
  3921. return true;
  3922. }
  3923. return false;
  3924. }
  3925. /// Return true if Val is already known to be live at the use site that we're
  3926. /// folding it into. If so, there is no cost to include it in the addressing
  3927. /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
  3928. /// instruction already.
  3929. bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  3930. Value *KnownLive2) {
  3931. // If Val is either of the known-live values, we know it is live!
  3932. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  3933. return true;
  3934. // All values other than instructions and arguments (e.g. constants) are live.
  3935. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  3936. // If Val is a constant sized alloca in the entry block, it is live, this is
  3937. // true because it is just a reference to the stack/frame pointer, which is
  3938. // live for the whole function.
  3939. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  3940. if (AI->isStaticAlloca())
  3941. return true;
  3942. // Check to see if this value is already used in the memory instruction's
  3943. // block. If so, it's already live into the block at the very least, so we
  3944. // can reasonably fold it.
  3945. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  3946. }
  3947. /// It is possible for the addressing mode of the machine to fold the specified
  3948. /// instruction into a load or store that ultimately uses it.
  3949. /// However, the specified instruction has multiple uses.
  3950. /// Given this, it may actually increase register pressure to fold it
  3951. /// into the load. For example, consider this code:
  3952. ///
  3953. /// X = ...
  3954. /// Y = X+1
  3955. /// use(Y) -> nonload/store
  3956. /// Z = Y+1
  3957. /// load Z
  3958. ///
  3959. /// In this case, Y has multiple uses, and can be folded into the load of Z
  3960. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  3961. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  3962. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  3963. /// number of computations either.
  3964. ///
  3965. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  3966. /// X was live across 'load Z' for other reasons, we actually *would* want to
  3967. /// fold the addressing mode in the Z case. This would make Y die earlier.
  3968. bool AddressingModeMatcher::
  3969. isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  3970. ExtAddrMode &AMAfter) {
  3971. if (IgnoreProfitability) return true;
  3972. // AMBefore is the addressing mode before this instruction was folded into it,
  3973. // and AMAfter is the addressing mode after the instruction was folded. Get
  3974. // the set of registers referenced by AMAfter and subtract out those
  3975. // referenced by AMBefore: this is the set of values which folding in this
  3976. // address extends the lifetime of.
  3977. //
  3978. // Note that there are only two potential values being referenced here,
  3979. // BaseReg and ScaleReg (global addresses are always available, as are any
  3980. // folded immediates).
  3981. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  3982. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  3983. // lifetime wasn't extended by adding this instruction.
  3984. if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3985. BaseReg = nullptr;
  3986. if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3987. ScaledReg = nullptr;
  3988. // If folding this instruction (and it's subexprs) didn't extend any live
  3989. // ranges, we're ok with it.
  3990. if (!BaseReg && !ScaledReg)
  3991. return true;
  3992. // If all uses of this instruction can have the address mode sunk into them,
  3993. // we can remove the addressing mode and effectively trade one live register
  3994. // for another (at worst.) In this context, folding an addressing mode into
  3995. // the use is just a particularly nice way of sinking it.
  3996. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  3997. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  3998. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
  3999. return false; // Has a non-memory, non-foldable use!
  4000. // Now that we know that all uses of this instruction are part of a chain of
  4001. // computation involving only operations that could theoretically be folded
  4002. // into a memory use, loop over each of these memory operation uses and see
  4003. // if they could *actually* fold the instruction. The assumption is that
  4004. // addressing modes are cheap and that duplicating the computation involved
  4005. // many times is worthwhile, even on a fastpath. For sinking candidates
  4006. // (i.e. cold call sites), this serves as a way to prevent excessive code
  4007. // growth since most architectures have some reasonable small and fast way to
  4008. // compute an effective address. (i.e LEA on x86)
  4009. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  4010. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  4011. Instruction *User = MemoryUses[i].first;
  4012. unsigned OpNo = MemoryUses[i].second;
  4013. // Get the access type of this use. If the use isn't a pointer, we don't
  4014. // know what it accesses.
  4015. Value *Address = User->getOperand(OpNo);
  4016. PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
  4017. if (!AddrTy)
  4018. return false;
  4019. Type *AddressAccessTy = AddrTy->getElementType();
  4020. unsigned AS = AddrTy->getAddressSpace();
  4021. // Do a match against the root of this address, ignoring profitability. This
  4022. // will tell us if the addressing mode for the memory operation will
  4023. // *actually* cover the shared instruction.
  4024. ExtAddrMode Result;
  4025. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4026. 0);
  4027. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4028. TPT.getRestorationPoint();
  4029. AddressingModeMatcher Matcher(
  4030. MatchedAddrModeInsts, TLI, TRI, AddressAccessTy, AS, MemoryInst, Result,
  4031. InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
  4032. Matcher.IgnoreProfitability = true;
  4033. bool Success = Matcher.matchAddr(Address, 0);
  4034. (void)Success; assert(Success && "Couldn't select *anything*?");
  4035. // The match was to check the profitability, the changes made are not
  4036. // part of the original matcher. Therefore, they should be dropped
  4037. // otherwise the original matcher will not present the right state.
  4038. TPT.rollback(LastKnownGood);
  4039. // If the match didn't cover I, then it won't be shared by it.
  4040. if (!is_contained(MatchedAddrModeInsts, I))
  4041. return false;
  4042. MatchedAddrModeInsts.clear();
  4043. }
  4044. return true;
  4045. }
  4046. /// Return true if the specified values are defined in a
  4047. /// different basic block than BB.
  4048. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  4049. if (Instruction *I = dyn_cast<Instruction>(V))
  4050. return I->getParent() != BB;
  4051. return false;
  4052. }
  4053. /// Sink addressing mode computation immediate before MemoryInst if doing so
  4054. /// can be done without increasing register pressure. The need for the
  4055. /// register pressure constraint means this can end up being an all or nothing
  4056. /// decision for all uses of the same addressing computation.
  4057. ///
  4058. /// Load and Store Instructions often have addressing modes that can do
  4059. /// significant amounts of computation. As such, instruction selection will try
  4060. /// to get the load or store to do as much computation as possible for the
  4061. /// program. The problem is that isel can only see within a single block. As
  4062. /// such, we sink as much legal addressing mode work into the block as possible.
  4063. ///
  4064. /// This method is used to optimize both load/store and inline asms with memory
  4065. /// operands. It's also used to sink addressing computations feeding into cold
  4066. /// call sites into their (cold) basic block.
  4067. ///
  4068. /// The motivation for handling sinking into cold blocks is that doing so can
  4069. /// both enable other address mode sinking (by satisfying the register pressure
  4070. /// constraint above), and reduce register pressure globally (by removing the
  4071. /// addressing mode computation from the fast path entirely.).
  4072. bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  4073. Type *AccessTy, unsigned AddrSpace) {
  4074. Value *Repl = Addr;
  4075. // Try to collapse single-value PHI nodes. This is necessary to undo
  4076. // unprofitable PRE transformations.
  4077. SmallVector<Value*, 8> worklist;
  4078. SmallPtrSet<Value*, 16> Visited;
  4079. worklist.push_back(Addr);
  4080. // Use a worklist to iteratively look through PHI and select nodes, and
  4081. // ensure that the addressing mode obtained from the non-PHI/select roots of
  4082. // the graph are compatible.
  4083. bool PhiOrSelectSeen = false;
  4084. SmallVector<Instruction*, 16> AddrModeInsts;
  4085. const SimplifyQuery SQ(*DL, TLInfo);
  4086. AddressingModeCombiner AddrModes(SQ, Addr);
  4087. TypePromotionTransaction TPT(RemovedInsts);
  4088. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4089. TPT.getRestorationPoint();
  4090. while (!worklist.empty()) {
  4091. Value *V = worklist.back();
  4092. worklist.pop_back();
  4093. // We allow traversing cyclic Phi nodes.
  4094. // In case of success after this loop we ensure that traversing through
  4095. // Phi nodes ends up with all cases to compute address of the form
  4096. // BaseGV + Base + Scale * Index + Offset
  4097. // where Scale and Offset are constans and BaseGV, Base and Index
  4098. // are exactly the same Values in all cases.
  4099. // It means that BaseGV, Scale and Offset dominate our memory instruction
  4100. // and have the same value as they had in address computation represented
  4101. // as Phi. So we can safely sink address computation to memory instruction.
  4102. if (!Visited.insert(V).second)
  4103. continue;
  4104. // For a PHI node, push all of its incoming values.
  4105. if (PHINode *P = dyn_cast<PHINode>(V)) {
  4106. for (Value *IncValue : P->incoming_values())
  4107. worklist.push_back(IncValue);
  4108. PhiOrSelectSeen = true;
  4109. continue;
  4110. }
  4111. // Similar for select.
  4112. if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  4113. worklist.push_back(SI->getFalseValue());
  4114. worklist.push_back(SI->getTrueValue());
  4115. PhiOrSelectSeen = true;
  4116. continue;
  4117. }
  4118. // For non-PHIs, determine the addressing mode being computed. Note that
  4119. // the result may differ depending on what other uses our candidate
  4120. // addressing instructions might have.
  4121. AddrModeInsts.clear();
  4122. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4123. 0);
  4124. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  4125. V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
  4126. InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP);
  4127. GetElementPtrInst *GEP = LargeOffsetGEP.first;
  4128. if (GEP && !NewGEPBases.count(GEP)) {
  4129. // If splitting the underlying data structure can reduce the offset of a
  4130. // GEP, collect the GEP. Skip the GEPs that are the new bases of
  4131. // previously split data structures.
  4132. LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
  4133. if (LargeOffsetGEPID.find(GEP) == LargeOffsetGEPID.end())
  4134. LargeOffsetGEPID[GEP] = LargeOffsetGEPID.size();
  4135. }
  4136. NewAddrMode.OriginalValue = V;
  4137. if (!AddrModes.addNewAddrMode(NewAddrMode))
  4138. break;
  4139. }
  4140. // Try to combine the AddrModes we've collected. If we couldn't collect any,
  4141. // or we have multiple but either couldn't combine them or combining them
  4142. // wouldn't do anything useful, bail out now.
  4143. if (!AddrModes.combineAddrModes()) {
  4144. TPT.rollback(LastKnownGood);
  4145. return false;
  4146. }
  4147. TPT.commit();
  4148. // Get the combined AddrMode (or the only AddrMode, if we only had one).
  4149. ExtAddrMode AddrMode = AddrModes.getAddrMode();
  4150. // If all the instructions matched are already in this BB, don't do anything.
  4151. // If we saw a Phi node then it is not local definitely, and if we saw a select
  4152. // then we want to push the address calculation past it even if it's already
  4153. // in this BB.
  4154. if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
  4155. return IsNonLocalValue(V, MemoryInst->getParent());
  4156. })) {
  4157. LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
  4158. << "\n");
  4159. return false;
  4160. }
  4161. // Insert this computation right after this user. Since our caller is
  4162. // scanning from the top of the BB to the bottom, reuse of the expr are
  4163. // guaranteed to happen later.
  4164. IRBuilder<> Builder(MemoryInst);
  4165. // Now that we determined the addressing expression we want to use and know
  4166. // that we have to sink it into this block. Check to see if we have already
  4167. // done this for some other load/store instr in this block. If so, reuse
  4168. // the computation. Before attempting reuse, check if the address is valid
  4169. // as it may have been erased.
  4170. WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
  4171. Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
  4172. if (SunkAddr) {
  4173. LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
  4174. << " for " << *MemoryInst << "\n");
  4175. if (SunkAddr->getType() != Addr->getType())
  4176. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4177. } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
  4178. TM && SubtargetInfo->addrSinkUsingGEPs())) {
  4179. // By default, we use the GEP-based method when AA is used later. This
  4180. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  4181. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4182. << " for " << *MemoryInst << "\n");
  4183. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4184. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  4185. // First, find the pointer.
  4186. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  4187. ResultPtr = AddrMode.BaseReg;
  4188. AddrMode.BaseReg = nullptr;
  4189. }
  4190. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  4191. // We can't add more than one pointer together, nor can we scale a
  4192. // pointer (both of which seem meaningless).
  4193. if (ResultPtr || AddrMode.Scale != 1)
  4194. return false;
  4195. ResultPtr = AddrMode.ScaledReg;
  4196. AddrMode.Scale = 0;
  4197. }
  4198. // It is only safe to sign extend the BaseReg if we know that the math
  4199. // required to create it did not overflow before we extend it. Since
  4200. // the original IR value was tossed in favor of a constant back when
  4201. // the AddrMode was created we need to bail out gracefully if widths
  4202. // do not match instead of extending it.
  4203. //
  4204. // (See below for code to add the scale.)
  4205. if (AddrMode.Scale) {
  4206. Type *ScaledRegTy = AddrMode.ScaledReg->getType();
  4207. if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
  4208. cast<IntegerType>(ScaledRegTy)->getBitWidth())
  4209. return false;
  4210. }
  4211. if (AddrMode.BaseGV) {
  4212. if (ResultPtr)
  4213. return false;
  4214. ResultPtr = AddrMode.BaseGV;
  4215. }
  4216. // If the real base value actually came from an inttoptr, then the matcher
  4217. // will look through it and provide only the integer value. In that case,
  4218. // use it here.
  4219. if (!DL->isNonIntegralPointerType(Addr->getType())) {
  4220. if (!ResultPtr && AddrMode.BaseReg) {
  4221. ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
  4222. "sunkaddr");
  4223. AddrMode.BaseReg = nullptr;
  4224. } else if (!ResultPtr && AddrMode.Scale == 1) {
  4225. ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
  4226. "sunkaddr");
  4227. AddrMode.Scale = 0;
  4228. }
  4229. }
  4230. if (!ResultPtr &&
  4231. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  4232. SunkAddr = Constant::getNullValue(Addr->getType());
  4233. } else if (!ResultPtr) {
  4234. return false;
  4235. } else {
  4236. Type *I8PtrTy =
  4237. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  4238. Type *I8Ty = Builder.getInt8Ty();
  4239. // Start with the base register. Do this first so that subsequent address
  4240. // matching finds it last, which will prevent it from trying to match it
  4241. // as the scaled value in case it happens to be a mul. That would be
  4242. // problematic if we've sunk a different mul for the scale, because then
  4243. // we'd end up sinking both muls.
  4244. if (AddrMode.BaseReg) {
  4245. Value *V = AddrMode.BaseReg;
  4246. if (V->getType() != IntPtrTy)
  4247. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4248. ResultIndex = V;
  4249. }
  4250. // Add the scale value.
  4251. if (AddrMode.Scale) {
  4252. Value *V = AddrMode.ScaledReg;
  4253. if (V->getType() == IntPtrTy) {
  4254. // done.
  4255. } else {
  4256. assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4257. cast<IntegerType>(V->getType())->getBitWidth() &&
  4258. "We can't transform if ScaledReg is too narrow");
  4259. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4260. }
  4261. if (AddrMode.Scale != 1)
  4262. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4263. "sunkaddr");
  4264. if (ResultIndex)
  4265. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  4266. else
  4267. ResultIndex = V;
  4268. }
  4269. // Add in the Base Offset if present.
  4270. if (AddrMode.BaseOffs) {
  4271. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4272. if (ResultIndex) {
  4273. // We need to add this separately from the scale above to help with
  4274. // SDAG consecutive load/store merging.
  4275. if (ResultPtr->getType() != I8PtrTy)
  4276. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4277. ResultPtr =
  4278. AddrMode.InBounds
  4279. ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
  4280. "sunkaddr")
  4281. : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  4282. }
  4283. ResultIndex = V;
  4284. }
  4285. if (!ResultIndex) {
  4286. SunkAddr = ResultPtr;
  4287. } else {
  4288. if (ResultPtr->getType() != I8PtrTy)
  4289. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4290. SunkAddr =
  4291. AddrMode.InBounds
  4292. ? Builder.CreateInBoundsGEP(I8Ty, ResultPtr, ResultIndex,
  4293. "sunkaddr")
  4294. : Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  4295. }
  4296. if (SunkAddr->getType() != Addr->getType())
  4297. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4298. }
  4299. } else {
  4300. // We'd require a ptrtoint/inttoptr down the line, which we can't do for
  4301. // non-integral pointers, so in that case bail out now.
  4302. Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
  4303. Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
  4304. PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
  4305. PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
  4306. if (DL->isNonIntegralPointerType(Addr->getType()) ||
  4307. (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
  4308. (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
  4309. (AddrMode.BaseGV &&
  4310. DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
  4311. return false;
  4312. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4313. << " for " << *MemoryInst << "\n");
  4314. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4315. Value *Result = nullptr;
  4316. // Start with the base register. Do this first so that subsequent address
  4317. // matching finds it last, which will prevent it from trying to match it
  4318. // as the scaled value in case it happens to be a mul. That would be
  4319. // problematic if we've sunk a different mul for the scale, because then
  4320. // we'd end up sinking both muls.
  4321. if (AddrMode.BaseReg) {
  4322. Value *V = AddrMode.BaseReg;
  4323. if (V->getType()->isPointerTy())
  4324. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4325. if (V->getType() != IntPtrTy)
  4326. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4327. Result = V;
  4328. }
  4329. // Add the scale value.
  4330. if (AddrMode.Scale) {
  4331. Value *V = AddrMode.ScaledReg;
  4332. if (V->getType() == IntPtrTy) {
  4333. // done.
  4334. } else if (V->getType()->isPointerTy()) {
  4335. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4336. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4337. cast<IntegerType>(V->getType())->getBitWidth()) {
  4338. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4339. } else {
  4340. // It is only safe to sign extend the BaseReg if we know that the math
  4341. // required to create it did not overflow before we extend it. Since
  4342. // the original IR value was tossed in favor of a constant back when
  4343. // the AddrMode was created we need to bail out gracefully if widths
  4344. // do not match instead of extending it.
  4345. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  4346. if (I && (Result != AddrMode.BaseReg))
  4347. I->eraseFromParent();
  4348. return false;
  4349. }
  4350. if (AddrMode.Scale != 1)
  4351. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4352. "sunkaddr");
  4353. if (Result)
  4354. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4355. else
  4356. Result = V;
  4357. }
  4358. // Add in the BaseGV if present.
  4359. if (AddrMode.BaseGV) {
  4360. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  4361. if (Result)
  4362. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4363. else
  4364. Result = V;
  4365. }
  4366. // Add in the Base Offset if present.
  4367. if (AddrMode.BaseOffs) {
  4368. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4369. if (Result)
  4370. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4371. else
  4372. Result = V;
  4373. }
  4374. if (!Result)
  4375. SunkAddr = Constant::getNullValue(Addr->getType());
  4376. else
  4377. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  4378. }
  4379. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  4380. // Store the newly computed address into the cache. In the case we reused a
  4381. // value, this should be idempotent.
  4382. SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
  4383. // If we have no uses, recursively delete the value and all dead instructions
  4384. // using it.
  4385. if (Repl->use_empty()) {
  4386. // This can cause recursive deletion, which can invalidate our iterator.
  4387. // Use a WeakTrackingVH to hold onto it in case this happens.
  4388. Value *CurValue = &*CurInstIterator;
  4389. WeakTrackingVH IterHandle(CurValue);
  4390. BasicBlock *BB = CurInstIterator->getParent();
  4391. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  4392. if (IterHandle != CurValue) {
  4393. // If the iterator instruction was recursively deleted, start over at the
  4394. // start of the block.
  4395. CurInstIterator = BB->begin();
  4396. SunkAddrs.clear();
  4397. }
  4398. }
  4399. ++NumMemoryInsts;
  4400. return true;
  4401. }
  4402. /// If there are any memory operands, use OptimizeMemoryInst to sink their
  4403. /// address computing into the block when possible / profitable.
  4404. bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
  4405. bool MadeChange = false;
  4406. const TargetRegisterInfo *TRI =
  4407. TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
  4408. TargetLowering::AsmOperandInfoVector TargetConstraints =
  4409. TLI->ParseConstraints(*DL, TRI, CS);
  4410. unsigned ArgNo = 0;
  4411. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  4412. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  4413. // Compute the constraint code and ConstraintType to use.
  4414. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  4415. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  4416. OpInfo.isIndirect) {
  4417. Value *OpVal = CS->getArgOperand(ArgNo++);
  4418. MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  4419. } else if (OpInfo.Type == InlineAsm::isInput)
  4420. ArgNo++;
  4421. }
  4422. return MadeChange;
  4423. }
  4424. /// Check if all the uses of \p Val are equivalent (or free) zero or
  4425. /// sign extensions.
  4426. static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
  4427. assert(!Val->use_empty() && "Input must have at least one use");
  4428. const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
  4429. bool IsSExt = isa<SExtInst>(FirstUser);
  4430. Type *ExtTy = FirstUser->getType();
  4431. for (const User *U : Val->users()) {
  4432. const Instruction *UI = cast<Instruction>(U);
  4433. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  4434. return false;
  4435. Type *CurTy = UI->getType();
  4436. // Same input and output types: Same instruction after CSE.
  4437. if (CurTy == ExtTy)
  4438. continue;
  4439. // If IsSExt is true, we are in this situation:
  4440. // a = Val
  4441. // b = sext ty1 a to ty2
  4442. // c = sext ty1 a to ty3
  4443. // Assuming ty2 is shorter than ty3, this could be turned into:
  4444. // a = Val
  4445. // b = sext ty1 a to ty2
  4446. // c = sext ty2 b to ty3
  4447. // However, the last sext is not free.
  4448. if (IsSExt)
  4449. return false;
  4450. // This is a ZExt, maybe this is free to extend from one type to another.
  4451. // In that case, we would not account for a different use.
  4452. Type *NarrowTy;
  4453. Type *LargeTy;
  4454. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  4455. CurTy->getScalarType()->getIntegerBitWidth()) {
  4456. NarrowTy = CurTy;
  4457. LargeTy = ExtTy;
  4458. } else {
  4459. NarrowTy = ExtTy;
  4460. LargeTy = CurTy;
  4461. }
  4462. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  4463. return false;
  4464. }
  4465. // All uses are the same or can be derived from one another for free.
  4466. return true;
  4467. }
  4468. /// Try to speculatively promote extensions in \p Exts and continue
  4469. /// promoting through newly promoted operands recursively as far as doing so is
  4470. /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
  4471. /// When some promotion happened, \p TPT contains the proper state to revert
  4472. /// them.
  4473. ///
  4474. /// \return true if some promotion happened, false otherwise.
  4475. bool CodeGenPrepare::tryToPromoteExts(
  4476. TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
  4477. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  4478. unsigned CreatedInstsCost) {
  4479. bool Promoted = false;
  4480. // Iterate over all the extensions to try to promote them.
  4481. for (auto I : Exts) {
  4482. // Early check if we directly have ext(load).
  4483. if (isa<LoadInst>(I->getOperand(0))) {
  4484. ProfitablyMovedExts.push_back(I);
  4485. continue;
  4486. }
  4487. // Check whether or not we want to do any promotion. The reason we have
  4488. // this check inside the for loop is to catch the case where an extension
  4489. // is directly fed by a load because in such case the extension can be moved
  4490. // up without any promotion on its operands.
  4491. if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  4492. return false;
  4493. // Get the action to perform the promotion.
  4494. TypePromotionHelper::Action TPH =
  4495. TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
  4496. // Check if we can promote.
  4497. if (!TPH) {
  4498. // Save the current extension as we cannot move up through its operand.
  4499. ProfitablyMovedExts.push_back(I);
  4500. continue;
  4501. }
  4502. // Save the current state.
  4503. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4504. TPT.getRestorationPoint();
  4505. SmallVector<Instruction *, 4> NewExts;
  4506. unsigned NewCreatedInstsCost = 0;
  4507. unsigned ExtCost = !TLI->isExtFree(I);
  4508. // Promote.
  4509. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  4510. &NewExts, nullptr, *TLI);
  4511. assert(PromotedVal &&
  4512. "TypePromotionHelper should have filtered out those cases");
  4513. // We would be able to merge only one extension in a load.
  4514. // Therefore, if we have more than 1 new extension we heuristically
  4515. // cut this search path, because it means we degrade the code quality.
  4516. // With exactly 2, the transformation is neutral, because we will merge
  4517. // one extension but leave one. However, we optimistically keep going,
  4518. // because the new extension may be removed too.
  4519. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  4520. // FIXME: It would be possible to propagate a negative value instead of
  4521. // conservatively ceiling it to 0.
  4522. TotalCreatedInstsCost =
  4523. std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
  4524. if (!StressExtLdPromotion &&
  4525. (TotalCreatedInstsCost > 1 ||
  4526. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  4527. // This promotion is not profitable, rollback to the previous state, and
  4528. // save the current extension in ProfitablyMovedExts as the latest
  4529. // speculative promotion turned out to be unprofitable.
  4530. TPT.rollback(LastKnownGood);
  4531. ProfitablyMovedExts.push_back(I);
  4532. continue;
  4533. }
  4534. // Continue promoting NewExts as far as doing so is profitable.
  4535. SmallVector<Instruction *, 2> NewlyMovedExts;
  4536. (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
  4537. bool NewPromoted = false;
  4538. for (auto ExtInst : NewlyMovedExts) {
  4539. Instruction *MovedExt = cast<Instruction>(ExtInst);
  4540. Value *ExtOperand = MovedExt->getOperand(0);
  4541. // If we have reached to a load, we need this extra profitability check
  4542. // as it could potentially be merged into an ext(load).
  4543. if (isa<LoadInst>(ExtOperand) &&
  4544. !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  4545. (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
  4546. continue;
  4547. ProfitablyMovedExts.push_back(MovedExt);
  4548. NewPromoted = true;
  4549. }
  4550. // If none of speculative promotions for NewExts is profitable, rollback
  4551. // and save the current extension (I) as the last profitable extension.
  4552. if (!NewPromoted) {
  4553. TPT.rollback(LastKnownGood);
  4554. ProfitablyMovedExts.push_back(I);
  4555. continue;
  4556. }
  4557. // The promotion is profitable.
  4558. Promoted = true;
  4559. }
  4560. return Promoted;
  4561. }
  4562. /// Merging redundant sexts when one is dominating the other.
  4563. bool CodeGenPrepare::mergeSExts(Function &F) {
  4564. bool Changed = false;
  4565. for (auto &Entry : ValToSExtendedUses) {
  4566. SExts &Insts = Entry.second;
  4567. SExts CurPts;
  4568. for (Instruction *Inst : Insts) {
  4569. if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
  4570. Inst->getOperand(0) != Entry.first)
  4571. continue;
  4572. bool inserted = false;
  4573. for (auto &Pt : CurPts) {
  4574. if (getDT(F).dominates(Inst, Pt)) {
  4575. Pt->replaceAllUsesWith(Inst);
  4576. RemovedInsts.insert(Pt);
  4577. Pt->removeFromParent();
  4578. Pt = Inst;
  4579. inserted = true;
  4580. Changed = true;
  4581. break;
  4582. }
  4583. if (!getDT(F).dominates(Pt, Inst))
  4584. // Give up if we need to merge in a common dominator as the
  4585. // experiments show it is not profitable.
  4586. continue;
  4587. Inst->replaceAllUsesWith(Pt);
  4588. RemovedInsts.insert(Inst);
  4589. Inst->removeFromParent();
  4590. inserted = true;
  4591. Changed = true;
  4592. break;
  4593. }
  4594. if (!inserted)
  4595. CurPts.push_back(Inst);
  4596. }
  4597. }
  4598. return Changed;
  4599. }
  4600. // Spliting large data structures so that the GEPs accessing them can have
  4601. // smaller offsets so that they can be sunk to the same blocks as their users.
  4602. // For example, a large struct starting from %base is splitted into two parts
  4603. // where the second part starts from %new_base.
  4604. //
  4605. // Before:
  4606. // BB0:
  4607. // %base =
  4608. //
  4609. // BB1:
  4610. // %gep0 = gep %base, off0
  4611. // %gep1 = gep %base, off1
  4612. // %gep2 = gep %base, off2
  4613. //
  4614. // BB2:
  4615. // %load1 = load %gep0
  4616. // %load2 = load %gep1
  4617. // %load3 = load %gep2
  4618. //
  4619. // After:
  4620. // BB0:
  4621. // %base =
  4622. // %new_base = gep %base, off0
  4623. //
  4624. // BB1:
  4625. // %new_gep0 = %new_base
  4626. // %new_gep1 = gep %new_base, off1 - off0
  4627. // %new_gep2 = gep %new_base, off2 - off0
  4628. //
  4629. // BB2:
  4630. // %load1 = load i32, i32* %new_gep0
  4631. // %load2 = load i32, i32* %new_gep1
  4632. // %load3 = load i32, i32* %new_gep2
  4633. //
  4634. // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
  4635. // their offsets are smaller enough to fit into the addressing mode.
  4636. bool CodeGenPrepare::splitLargeGEPOffsets() {
  4637. bool Changed = false;
  4638. for (auto &Entry : LargeOffsetGEPMap) {
  4639. Value *OldBase = Entry.first;
  4640. SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
  4641. &LargeOffsetGEPs = Entry.second;
  4642. auto compareGEPOffset =
  4643. [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
  4644. const std::pair<GetElementPtrInst *, int64_t> &RHS) {
  4645. if (LHS.first == RHS.first)
  4646. return false;
  4647. if (LHS.second != RHS.second)
  4648. return LHS.second < RHS.second;
  4649. return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
  4650. };
  4651. // Sorting all the GEPs of the same data structures based on the offsets.
  4652. llvm::sort(LargeOffsetGEPs, compareGEPOffset);
  4653. LargeOffsetGEPs.erase(
  4654. std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
  4655. LargeOffsetGEPs.end());
  4656. // Skip if all the GEPs have the same offsets.
  4657. if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
  4658. continue;
  4659. GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
  4660. int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
  4661. Value *NewBaseGEP = nullptr;
  4662. auto LargeOffsetGEP = LargeOffsetGEPs.begin();
  4663. while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
  4664. GetElementPtrInst *GEP = LargeOffsetGEP->first;
  4665. int64_t Offset = LargeOffsetGEP->second;
  4666. if (Offset != BaseOffset) {
  4667. TargetLowering::AddrMode AddrMode;
  4668. AddrMode.BaseOffs = Offset - BaseOffset;
  4669. // The result type of the GEP might not be the type of the memory
  4670. // access.
  4671. if (!TLI->isLegalAddressingMode(*DL, AddrMode,
  4672. GEP->getResultElementType(),
  4673. GEP->getAddressSpace())) {
  4674. // We need to create a new base if the offset to the current base is
  4675. // too large to fit into the addressing mode. So, a very large struct
  4676. // may be splitted into several parts.
  4677. BaseGEP = GEP;
  4678. BaseOffset = Offset;
  4679. NewBaseGEP = nullptr;
  4680. }
  4681. }
  4682. // Generate a new GEP to replace the current one.
  4683. LLVMContext &Ctx = GEP->getContext();
  4684. Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
  4685. Type *I8PtrTy =
  4686. Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
  4687. Type *I8Ty = Type::getInt8Ty(Ctx);
  4688. if (!NewBaseGEP) {
  4689. // Create a new base if we don't have one yet. Find the insertion
  4690. // pointer for the new base first.
  4691. BasicBlock::iterator NewBaseInsertPt;
  4692. BasicBlock *NewBaseInsertBB;
  4693. if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
  4694. // If the base of the struct is an instruction, the new base will be
  4695. // inserted close to it.
  4696. NewBaseInsertBB = BaseI->getParent();
  4697. if (isa<PHINode>(BaseI))
  4698. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4699. else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
  4700. NewBaseInsertBB =
  4701. SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
  4702. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4703. } else
  4704. NewBaseInsertPt = std::next(BaseI->getIterator());
  4705. } else {
  4706. // If the current base is an argument or global value, the new base
  4707. // will be inserted to the entry block.
  4708. NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
  4709. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  4710. }
  4711. IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
  4712. // Create a new base.
  4713. Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
  4714. NewBaseGEP = OldBase;
  4715. if (NewBaseGEP->getType() != I8PtrTy)
  4716. NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
  4717. NewBaseGEP =
  4718. NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
  4719. NewGEPBases.insert(NewBaseGEP);
  4720. }
  4721. IRBuilder<> Builder(GEP);
  4722. Value *NewGEP = NewBaseGEP;
  4723. if (Offset == BaseOffset) {
  4724. if (GEP->getType() != I8PtrTy)
  4725. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  4726. } else {
  4727. // Calculate the new offset for the new GEP.
  4728. Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
  4729. NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
  4730. if (GEP->getType() != I8PtrTy)
  4731. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  4732. }
  4733. GEP->replaceAllUsesWith(NewGEP);
  4734. LargeOffsetGEPID.erase(GEP);
  4735. LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
  4736. GEP->eraseFromParent();
  4737. Changed = true;
  4738. }
  4739. }
  4740. return Changed;
  4741. }
  4742. /// Return true, if an ext(load) can be formed from an extension in
  4743. /// \p MovedExts.
  4744. bool CodeGenPrepare::canFormExtLd(
  4745. const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
  4746. Instruction *&Inst, bool HasPromoted) {
  4747. for (auto *MovedExtInst : MovedExts) {
  4748. if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
  4749. LI = cast<LoadInst>(MovedExtInst->getOperand(0));
  4750. Inst = MovedExtInst;
  4751. break;
  4752. }
  4753. }
  4754. if (!LI)
  4755. return false;
  4756. // If they're already in the same block, there's nothing to do.
  4757. // Make the cheap checks first if we did not promote.
  4758. // If we promoted, we need to check if it is indeed profitable.
  4759. if (!HasPromoted && LI->getParent() == Inst->getParent())
  4760. return false;
  4761. return TLI->isExtLoad(LI, Inst, *DL);
  4762. }
  4763. /// Move a zext or sext fed by a load into the same basic block as the load,
  4764. /// unless conditions are unfavorable. This allows SelectionDAG to fold the
  4765. /// extend into the load.
  4766. ///
  4767. /// E.g.,
  4768. /// \code
  4769. /// %ld = load i32* %addr
  4770. /// %add = add nuw i32 %ld, 4
  4771. /// %zext = zext i32 %add to i64
  4772. // \endcode
  4773. /// =>
  4774. /// \code
  4775. /// %ld = load i32* %addr
  4776. /// %zext = zext i32 %ld to i64
  4777. /// %add = add nuw i64 %zext, 4
  4778. /// \encode
  4779. /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
  4780. /// allow us to match zext(load i32*) to i64.
  4781. ///
  4782. /// Also, try to promote the computations used to obtain a sign extended
  4783. /// value used into memory accesses.
  4784. /// E.g.,
  4785. /// \code
  4786. /// a = add nsw i32 b, 3
  4787. /// d = sext i32 a to i64
  4788. /// e = getelementptr ..., i64 d
  4789. /// \endcode
  4790. /// =>
  4791. /// \code
  4792. /// f = sext i32 b to i64
  4793. /// a = add nsw i64 f, 3
  4794. /// e = getelementptr ..., i64 a
  4795. /// \endcode
  4796. ///
  4797. /// \p Inst[in/out] the extension may be modified during the process if some
  4798. /// promotions apply.
  4799. bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
  4800. // ExtLoad formation and address type promotion infrastructure requires TLI to
  4801. // be effective.
  4802. if (!TLI)
  4803. return false;
  4804. bool AllowPromotionWithoutCommonHeader = false;
  4805. /// See if it is an interesting sext operations for the address type
  4806. /// promotion before trying to promote it, e.g., the ones with the right
  4807. /// type and used in memory accesses.
  4808. bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
  4809. *Inst, AllowPromotionWithoutCommonHeader);
  4810. TypePromotionTransaction TPT(RemovedInsts);
  4811. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4812. TPT.getRestorationPoint();
  4813. SmallVector<Instruction *, 1> Exts;
  4814. SmallVector<Instruction *, 2> SpeculativelyMovedExts;
  4815. Exts.push_back(Inst);
  4816. bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
  4817. // Look for a load being extended.
  4818. LoadInst *LI = nullptr;
  4819. Instruction *ExtFedByLoad;
  4820. // Try to promote a chain of computation if it allows to form an extended
  4821. // load.
  4822. if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
  4823. assert(LI && ExtFedByLoad && "Expect a valid load and extension");
  4824. TPT.commit();
  4825. // Move the extend into the same block as the load
  4826. ExtFedByLoad->moveAfter(LI);
  4827. // CGP does not check if the zext would be speculatively executed when moved
  4828. // to the same basic block as the load. Preserving its original location
  4829. // would pessimize the debugging experience, as well as negatively impact
  4830. // the quality of sample pgo. We don't want to use "line 0" as that has a
  4831. // size cost in the line-table section and logically the zext can be seen as
  4832. // part of the load. Therefore we conservatively reuse the same debug
  4833. // location for the load and the zext.
  4834. ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
  4835. ++NumExtsMoved;
  4836. Inst = ExtFedByLoad;
  4837. return true;
  4838. }
  4839. // Continue promoting SExts if known as considerable depending on targets.
  4840. if (ATPConsiderable &&
  4841. performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
  4842. HasPromoted, TPT, SpeculativelyMovedExts))
  4843. return true;
  4844. TPT.rollback(LastKnownGood);
  4845. return false;
  4846. }
  4847. // Perform address type promotion if doing so is profitable.
  4848. // If AllowPromotionWithoutCommonHeader == false, we should find other sext
  4849. // instructions that sign extended the same initial value. However, if
  4850. // AllowPromotionWithoutCommonHeader == true, we expect promoting the
  4851. // extension is just profitable.
  4852. bool CodeGenPrepare::performAddressTypePromotion(
  4853. Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
  4854. bool HasPromoted, TypePromotionTransaction &TPT,
  4855. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
  4856. bool Promoted = false;
  4857. SmallPtrSet<Instruction *, 1> UnhandledExts;
  4858. bool AllSeenFirst = true;
  4859. for (auto I : SpeculativelyMovedExts) {
  4860. Value *HeadOfChain = I->getOperand(0);
  4861. DenseMap<Value *, Instruction *>::iterator AlreadySeen =
  4862. SeenChainsForSExt.find(HeadOfChain);
  4863. // If there is an unhandled SExt which has the same header, try to promote
  4864. // it as well.
  4865. if (AlreadySeen != SeenChainsForSExt.end()) {
  4866. if (AlreadySeen->second != nullptr)
  4867. UnhandledExts.insert(AlreadySeen->second);
  4868. AllSeenFirst = false;
  4869. }
  4870. }
  4871. if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
  4872. SpeculativelyMovedExts.size() == 1)) {
  4873. TPT.commit();
  4874. if (HasPromoted)
  4875. Promoted = true;
  4876. for (auto I : SpeculativelyMovedExts) {
  4877. Value *HeadOfChain = I->getOperand(0);
  4878. SeenChainsForSExt[HeadOfChain] = nullptr;
  4879. ValToSExtendedUses[HeadOfChain].push_back(I);
  4880. }
  4881. // Update Inst as promotion happen.
  4882. Inst = SpeculativelyMovedExts.pop_back_val();
  4883. } else {
  4884. // This is the first chain visited from the header, keep the current chain
  4885. // as unhandled. Defer to promote this until we encounter another SExt
  4886. // chain derived from the same header.
  4887. for (auto I : SpeculativelyMovedExts) {
  4888. Value *HeadOfChain = I->getOperand(0);
  4889. SeenChainsForSExt[HeadOfChain] = Inst;
  4890. }
  4891. return false;
  4892. }
  4893. if (!AllSeenFirst && !UnhandledExts.empty())
  4894. for (auto VisitedSExt : UnhandledExts) {
  4895. if (RemovedInsts.count(VisitedSExt))
  4896. continue;
  4897. TypePromotionTransaction TPT(RemovedInsts);
  4898. SmallVector<Instruction *, 1> Exts;
  4899. SmallVector<Instruction *, 2> Chains;
  4900. Exts.push_back(VisitedSExt);
  4901. bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
  4902. TPT.commit();
  4903. if (HasPromoted)
  4904. Promoted = true;
  4905. for (auto I : Chains) {
  4906. Value *HeadOfChain = I->getOperand(0);
  4907. // Mark this as handled.
  4908. SeenChainsForSExt[HeadOfChain] = nullptr;
  4909. ValToSExtendedUses[HeadOfChain].push_back(I);
  4910. }
  4911. }
  4912. return Promoted;
  4913. }
  4914. bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
  4915. BasicBlock *DefBB = I->getParent();
  4916. // If the result of a {s|z}ext and its source are both live out, rewrite all
  4917. // other uses of the source with result of extension.
  4918. Value *Src = I->getOperand(0);
  4919. if (Src->hasOneUse())
  4920. return false;
  4921. // Only do this xform if truncating is free.
  4922. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  4923. return false;
  4924. // Only safe to perform the optimization if the source is also defined in
  4925. // this block.
  4926. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  4927. return false;
  4928. bool DefIsLiveOut = false;
  4929. for (User *U : I->users()) {
  4930. Instruction *UI = cast<Instruction>(U);
  4931. // Figure out which BB this ext is used in.
  4932. BasicBlock *UserBB = UI->getParent();
  4933. if (UserBB == DefBB) continue;
  4934. DefIsLiveOut = true;
  4935. break;
  4936. }
  4937. if (!DefIsLiveOut)
  4938. return false;
  4939. // Make sure none of the uses are PHI nodes.
  4940. for (User *U : Src->users()) {
  4941. Instruction *UI = cast<Instruction>(U);
  4942. BasicBlock *UserBB = UI->getParent();
  4943. if (UserBB == DefBB) continue;
  4944. // Be conservative. We don't want this xform to end up introducing
  4945. // reloads just before load / store instructions.
  4946. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  4947. return false;
  4948. }
  4949. // InsertedTruncs - Only insert one trunc in each block once.
  4950. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  4951. bool MadeChange = false;
  4952. for (Use &U : Src->uses()) {
  4953. Instruction *User = cast<Instruction>(U.getUser());
  4954. // Figure out which BB this ext is used in.
  4955. BasicBlock *UserBB = User->getParent();
  4956. if (UserBB == DefBB) continue;
  4957. // Both src and def are live in this block. Rewrite the use.
  4958. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  4959. if (!InsertedTrunc) {
  4960. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  4961. assert(InsertPt != UserBB->end());
  4962. InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
  4963. InsertedInsts.insert(InsertedTrunc);
  4964. }
  4965. // Replace a use of the {s|z}ext source with a use of the result.
  4966. U = InsertedTrunc;
  4967. ++NumExtUses;
  4968. MadeChange = true;
  4969. }
  4970. return MadeChange;
  4971. }
  4972. // Find loads whose uses only use some of the loaded value's bits. Add an "and"
  4973. // just after the load if the target can fold this into one extload instruction,
  4974. // with the hope of eliminating some of the other later "and" instructions using
  4975. // the loaded value. "and"s that are made trivially redundant by the insertion
  4976. // of the new "and" are removed by this function, while others (e.g. those whose
  4977. // path from the load goes through a phi) are left for isel to potentially
  4978. // remove.
  4979. //
  4980. // For example:
  4981. //
  4982. // b0:
  4983. // x = load i32
  4984. // ...
  4985. // b1:
  4986. // y = and x, 0xff
  4987. // z = use y
  4988. //
  4989. // becomes:
  4990. //
  4991. // b0:
  4992. // x = load i32
  4993. // x' = and x, 0xff
  4994. // ...
  4995. // b1:
  4996. // z = use x'
  4997. //
  4998. // whereas:
  4999. //
  5000. // b0:
  5001. // x1 = load i32
  5002. // ...
  5003. // b1:
  5004. // x2 = load i32
  5005. // ...
  5006. // b2:
  5007. // x = phi x1, x2
  5008. // y = and x, 0xff
  5009. //
  5010. // becomes (after a call to optimizeLoadExt for each load):
  5011. //
  5012. // b0:
  5013. // x1 = load i32
  5014. // x1' = and x1, 0xff
  5015. // ...
  5016. // b1:
  5017. // x2 = load i32
  5018. // x2' = and x2, 0xff
  5019. // ...
  5020. // b2:
  5021. // x = phi x1', x2'
  5022. // y = and x, 0xff
  5023. bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
  5024. if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
  5025. return false;
  5026. // Skip loads we've already transformed.
  5027. if (Load->hasOneUse() &&
  5028. InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
  5029. return false;
  5030. // Look at all uses of Load, looking through phis, to determine how many bits
  5031. // of the loaded value are needed.
  5032. SmallVector<Instruction *, 8> WorkList;
  5033. SmallPtrSet<Instruction *, 16> Visited;
  5034. SmallVector<Instruction *, 8> AndsToMaybeRemove;
  5035. for (auto *U : Load->users())
  5036. WorkList.push_back(cast<Instruction>(U));
  5037. EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
  5038. unsigned BitWidth = LoadResultVT.getSizeInBits();
  5039. APInt DemandBits(BitWidth, 0);
  5040. APInt WidestAndBits(BitWidth, 0);
  5041. while (!WorkList.empty()) {
  5042. Instruction *I = WorkList.back();
  5043. WorkList.pop_back();
  5044. // Break use-def graph loops.
  5045. if (!Visited.insert(I).second)
  5046. continue;
  5047. // For a PHI node, push all of its users.
  5048. if (auto *Phi = dyn_cast<PHINode>(I)) {
  5049. for (auto *U : Phi->users())
  5050. WorkList.push_back(cast<Instruction>(U));
  5051. continue;
  5052. }
  5053. switch (I->getOpcode()) {
  5054. case Instruction::And: {
  5055. auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
  5056. if (!AndC)
  5057. return false;
  5058. APInt AndBits = AndC->getValue();
  5059. DemandBits |= AndBits;
  5060. // Keep track of the widest and mask we see.
  5061. if (AndBits.ugt(WidestAndBits))
  5062. WidestAndBits = AndBits;
  5063. if (AndBits == WidestAndBits && I->getOperand(0) == Load)
  5064. AndsToMaybeRemove.push_back(I);
  5065. break;
  5066. }
  5067. case Instruction::Shl: {
  5068. auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
  5069. if (!ShlC)
  5070. return false;
  5071. uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
  5072. DemandBits.setLowBits(BitWidth - ShiftAmt);
  5073. break;
  5074. }
  5075. case Instruction::Trunc: {
  5076. EVT TruncVT = TLI->getValueType(*DL, I->getType());
  5077. unsigned TruncBitWidth = TruncVT.getSizeInBits();
  5078. DemandBits.setLowBits(TruncBitWidth);
  5079. break;
  5080. }
  5081. default:
  5082. return false;
  5083. }
  5084. }
  5085. uint32_t ActiveBits = DemandBits.getActiveBits();
  5086. // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
  5087. // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
  5088. // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
  5089. // (and (load x) 1) is not matched as a single instruction, rather as a LDR
  5090. // followed by an AND.
  5091. // TODO: Look into removing this restriction by fixing backends to either
  5092. // return false for isLoadExtLegal for i1 or have them select this pattern to
  5093. // a single instruction.
  5094. //
  5095. // Also avoid hoisting if we didn't see any ands with the exact DemandBits
  5096. // mask, since these are the only ands that will be removed by isel.
  5097. if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
  5098. WidestAndBits != DemandBits)
  5099. return false;
  5100. LLVMContext &Ctx = Load->getType()->getContext();
  5101. Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
  5102. EVT TruncVT = TLI->getValueType(*DL, TruncTy);
  5103. // Reject cases that won't be matched as extloads.
  5104. if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
  5105. !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
  5106. return false;
  5107. IRBuilder<> Builder(Load->getNextNode());
  5108. auto *NewAnd = cast<Instruction>(
  5109. Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
  5110. // Mark this instruction as "inserted by CGP", so that other
  5111. // optimizations don't touch it.
  5112. InsertedInsts.insert(NewAnd);
  5113. // Replace all uses of load with new and (except for the use of load in the
  5114. // new and itself).
  5115. Load->replaceAllUsesWith(NewAnd);
  5116. NewAnd->setOperand(0, Load);
  5117. // Remove any and instructions that are now redundant.
  5118. for (auto *And : AndsToMaybeRemove)
  5119. // Check that the and mask is the same as the one we decided to put on the
  5120. // new and.
  5121. if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
  5122. And->replaceAllUsesWith(NewAnd);
  5123. if (&*CurInstIterator == And)
  5124. CurInstIterator = std::next(And->getIterator());
  5125. And->eraseFromParent();
  5126. ++NumAndUses;
  5127. }
  5128. ++NumAndsAdded;
  5129. return true;
  5130. }
  5131. /// Check if V (an operand of a select instruction) is an expensive instruction
  5132. /// that is only used once.
  5133. static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
  5134. auto *I = dyn_cast<Instruction>(V);
  5135. // If it's safe to speculatively execute, then it should not have side
  5136. // effects; therefore, it's safe to sink and possibly *not* execute.
  5137. return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
  5138. TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
  5139. }
  5140. /// Returns true if a SelectInst should be turned into an explicit branch.
  5141. static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
  5142. const TargetLowering *TLI,
  5143. SelectInst *SI) {
  5144. // If even a predictable select is cheap, then a branch can't be cheaper.
  5145. if (!TLI->isPredictableSelectExpensive())
  5146. return false;
  5147. // FIXME: This should use the same heuristics as IfConversion to determine
  5148. // whether a select is better represented as a branch.
  5149. // If metadata tells us that the select condition is obviously predictable,
  5150. // then we want to replace the select with a branch.
  5151. uint64_t TrueWeight, FalseWeight;
  5152. if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
  5153. uint64_t Max = std::max(TrueWeight, FalseWeight);
  5154. uint64_t Sum = TrueWeight + FalseWeight;
  5155. if (Sum != 0) {
  5156. auto Probability = BranchProbability::getBranchProbability(Max, Sum);
  5157. if (Probability > TLI->getPredictableBranchThreshold())
  5158. return true;
  5159. }
  5160. }
  5161. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  5162. // If a branch is predictable, an out-of-order CPU can avoid blocking on its
  5163. // comparison condition. If the compare has more than one use, there's
  5164. // probably another cmov or setcc around, so it's not worth emitting a branch.
  5165. if (!Cmp || !Cmp->hasOneUse())
  5166. return false;
  5167. // If either operand of the select is expensive and only needed on one side
  5168. // of the select, we should form a branch.
  5169. if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
  5170. sinkSelectOperand(TTI, SI->getFalseValue()))
  5171. return true;
  5172. return false;
  5173. }
  5174. /// If \p isTrue is true, return the true value of \p SI, otherwise return
  5175. /// false value of \p SI. If the true/false value of \p SI is defined by any
  5176. /// select instructions in \p Selects, look through the defining select
  5177. /// instruction until the true/false value is not defined in \p Selects.
  5178. static Value *getTrueOrFalseValue(
  5179. SelectInst *SI, bool isTrue,
  5180. const SmallPtrSet<const Instruction *, 2> &Selects) {
  5181. Value *V = nullptr;
  5182. for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
  5183. DefSI = dyn_cast<SelectInst>(V)) {
  5184. assert(DefSI->getCondition() == SI->getCondition() &&
  5185. "The condition of DefSI does not match with SI");
  5186. V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
  5187. }
  5188. assert(V && "Failed to get select true/false value");
  5189. return V;
  5190. }
  5191. bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
  5192. assert(Shift->isShift() && "Expected a shift");
  5193. // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
  5194. // general vector shifts, and (3) the shift amount is a select-of-splatted
  5195. // values, hoist the shifts before the select:
  5196. // shift Op0, (select Cond, TVal, FVal) -->
  5197. // select Cond, (shift Op0, TVal), (shift Op0, FVal)
  5198. //
  5199. // This is inverting a generic IR transform when we know that the cost of a
  5200. // general vector shift is more than the cost of 2 shift-by-scalars.
  5201. // We can't do this effectively in SDAG because we may not be able to
  5202. // determine if the select operands are splats from within a basic block.
  5203. Type *Ty = Shift->getType();
  5204. if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty))
  5205. return false;
  5206. Value *Cond, *TVal, *FVal;
  5207. if (!match(Shift->getOperand(1),
  5208. m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
  5209. return false;
  5210. if (!isSplatValue(TVal) || !isSplatValue(FVal))
  5211. return false;
  5212. IRBuilder<> Builder(Shift);
  5213. BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
  5214. Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
  5215. Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
  5216. Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
  5217. Shift->replaceAllUsesWith(NewSel);
  5218. Shift->eraseFromParent();
  5219. return true;
  5220. }
  5221. /// If we have a SelectInst that will likely profit from branch prediction,
  5222. /// turn it into a branch.
  5223. bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
  5224. // If branch conversion isn't desirable, exit early.
  5225. if (DisableSelectToBranch || OptSize || !TLI)
  5226. return false;
  5227. // Find all consecutive select instructions that share the same condition.
  5228. SmallVector<SelectInst *, 2> ASI;
  5229. ASI.push_back(SI);
  5230. for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
  5231. It != SI->getParent()->end(); ++It) {
  5232. SelectInst *I = dyn_cast<SelectInst>(&*It);
  5233. if (I && SI->getCondition() == I->getCondition()) {
  5234. ASI.push_back(I);
  5235. } else {
  5236. break;
  5237. }
  5238. }
  5239. SelectInst *LastSI = ASI.back();
  5240. // Increment the current iterator to skip all the rest of select instructions
  5241. // because they will be either "not lowered" or "all lowered" to branch.
  5242. CurInstIterator = std::next(LastSI->getIterator());
  5243. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  5244. // Can we convert the 'select' to CF ?
  5245. if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
  5246. return false;
  5247. TargetLowering::SelectSupportKind SelectKind;
  5248. if (VectorCond)
  5249. SelectKind = TargetLowering::VectorMaskSelect;
  5250. else if (SI->getType()->isVectorTy())
  5251. SelectKind = TargetLowering::ScalarCondVectorVal;
  5252. else
  5253. SelectKind = TargetLowering::ScalarValSelect;
  5254. if (TLI->isSelectSupported(SelectKind) &&
  5255. !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
  5256. return false;
  5257. // The DominatorTree needs to be rebuilt by any consumers after this
  5258. // transformation. We simply reset here rather than setting the ModifiedDT
  5259. // flag to avoid restarting the function walk in runOnFunction for each
  5260. // select optimized.
  5261. DT.reset();
  5262. // Transform a sequence like this:
  5263. // start:
  5264. // %cmp = cmp uge i32 %a, %b
  5265. // %sel = select i1 %cmp, i32 %c, i32 %d
  5266. //
  5267. // Into:
  5268. // start:
  5269. // %cmp = cmp uge i32 %a, %b
  5270. // br i1 %cmp, label %select.true, label %select.false
  5271. // select.true:
  5272. // br label %select.end
  5273. // select.false:
  5274. // br label %select.end
  5275. // select.end:
  5276. // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
  5277. //
  5278. // In addition, we may sink instructions that produce %c or %d from
  5279. // the entry block into the destination(s) of the new branch.
  5280. // If the true or false blocks do not contain a sunken instruction, that
  5281. // block and its branch may be optimized away. In that case, one side of the
  5282. // first branch will point directly to select.end, and the corresponding PHI
  5283. // predecessor block will be the start block.
  5284. // First, we split the block containing the select into 2 blocks.
  5285. BasicBlock *StartBlock = SI->getParent();
  5286. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
  5287. BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  5288. // Delete the unconditional branch that was just created by the split.
  5289. StartBlock->getTerminator()->eraseFromParent();
  5290. // These are the new basic blocks for the conditional branch.
  5291. // At least one will become an actual new basic block.
  5292. BasicBlock *TrueBlock = nullptr;
  5293. BasicBlock *FalseBlock = nullptr;
  5294. BranchInst *TrueBranch = nullptr;
  5295. BranchInst *FalseBranch = nullptr;
  5296. // Sink expensive instructions into the conditional blocks to avoid executing
  5297. // them speculatively.
  5298. for (SelectInst *SI : ASI) {
  5299. if (sinkSelectOperand(TTI, SI->getTrueValue())) {
  5300. if (TrueBlock == nullptr) {
  5301. TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
  5302. EndBlock->getParent(), EndBlock);
  5303. TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
  5304. TrueBranch->setDebugLoc(SI->getDebugLoc());
  5305. }
  5306. auto *TrueInst = cast<Instruction>(SI->getTrueValue());
  5307. TrueInst->moveBefore(TrueBranch);
  5308. }
  5309. if (sinkSelectOperand(TTI, SI->getFalseValue())) {
  5310. if (FalseBlock == nullptr) {
  5311. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
  5312. EndBlock->getParent(), EndBlock);
  5313. FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  5314. FalseBranch->setDebugLoc(SI->getDebugLoc());
  5315. }
  5316. auto *FalseInst = cast<Instruction>(SI->getFalseValue());
  5317. FalseInst->moveBefore(FalseBranch);
  5318. }
  5319. }
  5320. // If there was nothing to sink, then arbitrarily choose the 'false' side
  5321. // for a new input value to the PHI.
  5322. if (TrueBlock == FalseBlock) {
  5323. assert(TrueBlock == nullptr &&
  5324. "Unexpected basic block transform while optimizing select");
  5325. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
  5326. EndBlock->getParent(), EndBlock);
  5327. auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  5328. FalseBranch->setDebugLoc(SI->getDebugLoc());
  5329. }
  5330. // Insert the real conditional branch based on the original condition.
  5331. // If we did not create a new block for one of the 'true' or 'false' paths
  5332. // of the condition, it means that side of the branch goes to the end block
  5333. // directly and the path originates from the start block from the point of
  5334. // view of the new PHI.
  5335. BasicBlock *TT, *FT;
  5336. if (TrueBlock == nullptr) {
  5337. TT = EndBlock;
  5338. FT = FalseBlock;
  5339. TrueBlock = StartBlock;
  5340. } else if (FalseBlock == nullptr) {
  5341. TT = TrueBlock;
  5342. FT = EndBlock;
  5343. FalseBlock = StartBlock;
  5344. } else {
  5345. TT = TrueBlock;
  5346. FT = FalseBlock;
  5347. }
  5348. IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
  5349. SmallPtrSet<const Instruction *, 2> INS;
  5350. INS.insert(ASI.begin(), ASI.end());
  5351. // Use reverse iterator because later select may use the value of the
  5352. // earlier select, and we need to propagate value through earlier select
  5353. // to get the PHI operand.
  5354. for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
  5355. SelectInst *SI = *It;
  5356. // The select itself is replaced with a PHI Node.
  5357. PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
  5358. PN->takeName(SI);
  5359. PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
  5360. PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
  5361. PN->setDebugLoc(SI->getDebugLoc());
  5362. SI->replaceAllUsesWith(PN);
  5363. SI->eraseFromParent();
  5364. INS.erase(SI);
  5365. ++NumSelectsExpanded;
  5366. }
  5367. // Instruct OptimizeBlock to skip to the next block.
  5368. CurInstIterator = StartBlock->end();
  5369. return true;
  5370. }
  5371. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  5372. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  5373. int SplatElem = -1;
  5374. for (unsigned i = 0; i < Mask.size(); ++i) {
  5375. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  5376. return false;
  5377. SplatElem = Mask[i];
  5378. }
  5379. return true;
  5380. }
  5381. /// Some targets have expensive vector shifts if the lanes aren't all the same
  5382. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  5383. /// it's often worth sinking a shufflevector splat down to its use so that
  5384. /// codegen can spot all lanes are identical.
  5385. bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  5386. BasicBlock *DefBB = SVI->getParent();
  5387. // Only do this xform if variable vector shifts are particularly expensive.
  5388. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  5389. return false;
  5390. // We only expect better codegen by sinking a shuffle if we can recognise a
  5391. // constant splat.
  5392. if (!isBroadcastShuffle(SVI))
  5393. return false;
  5394. // InsertedShuffles - Only insert a shuffle in each block once.
  5395. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  5396. bool MadeChange = false;
  5397. for (User *U : SVI->users()) {
  5398. Instruction *UI = cast<Instruction>(U);
  5399. // Figure out which BB this ext is used in.
  5400. BasicBlock *UserBB = UI->getParent();
  5401. if (UserBB == DefBB) continue;
  5402. // For now only apply this when the splat is used by a shift instruction.
  5403. if (!UI->isShift()) continue;
  5404. // Everything checks out, sink the shuffle if the user's block doesn't
  5405. // already have a copy.
  5406. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  5407. if (!InsertedShuffle) {
  5408. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  5409. assert(InsertPt != UserBB->end());
  5410. InsertedShuffle =
  5411. new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
  5412. SVI->getOperand(2), "", &*InsertPt);
  5413. InsertedShuffle->setDebugLoc(SVI->getDebugLoc());
  5414. }
  5415. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  5416. MadeChange = true;
  5417. }
  5418. // If we removed all uses, nuke the shuffle.
  5419. if (SVI->use_empty()) {
  5420. SVI->eraseFromParent();
  5421. MadeChange = true;
  5422. }
  5423. return MadeChange;
  5424. }
  5425. bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
  5426. // If the operands of I can be folded into a target instruction together with
  5427. // I, duplicate and sink them.
  5428. SmallVector<Use *, 4> OpsToSink;
  5429. if (!TLI || !TLI->shouldSinkOperands(I, OpsToSink))
  5430. return false;
  5431. // OpsToSink can contain multiple uses in a use chain (e.g.
  5432. // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
  5433. // uses must come first, so we process the ops in reverse order so as to not
  5434. // create invalid IR.
  5435. BasicBlock *TargetBB = I->getParent();
  5436. bool Changed = false;
  5437. SmallVector<Use *, 4> ToReplace;
  5438. for (Use *U : reverse(OpsToSink)) {
  5439. auto *UI = cast<Instruction>(U->get());
  5440. if (UI->getParent() == TargetBB || isa<PHINode>(UI))
  5441. continue;
  5442. ToReplace.push_back(U);
  5443. }
  5444. SetVector<Instruction *> MaybeDead;
  5445. DenseMap<Instruction *, Instruction *> NewInstructions;
  5446. Instruction *InsertPoint = I;
  5447. for (Use *U : ToReplace) {
  5448. auto *UI = cast<Instruction>(U->get());
  5449. Instruction *NI = UI->clone();
  5450. NewInstructions[UI] = NI;
  5451. MaybeDead.insert(UI);
  5452. LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
  5453. NI->insertBefore(InsertPoint);
  5454. InsertPoint = NI;
  5455. InsertedInsts.insert(NI);
  5456. // Update the use for the new instruction, making sure that we update the
  5457. // sunk instruction uses, if it is part of a chain that has already been
  5458. // sunk.
  5459. Instruction *OldI = cast<Instruction>(U->getUser());
  5460. if (NewInstructions.count(OldI))
  5461. NewInstructions[OldI]->setOperand(U->getOperandNo(), NI);
  5462. else
  5463. U->set(NI);
  5464. Changed = true;
  5465. }
  5466. // Remove instructions that are dead after sinking.
  5467. for (auto *I : MaybeDead) {
  5468. if (!I->hasNUsesOrMore(1)) {
  5469. LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
  5470. I->eraseFromParent();
  5471. }
  5472. }
  5473. return Changed;
  5474. }
  5475. bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
  5476. if (!TLI || !DL)
  5477. return false;
  5478. Value *Cond = SI->getCondition();
  5479. Type *OldType = Cond->getType();
  5480. LLVMContext &Context = Cond->getContext();
  5481. MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
  5482. unsigned RegWidth = RegType.getSizeInBits();
  5483. if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
  5484. return false;
  5485. // If the register width is greater than the type width, expand the condition
  5486. // of the switch instruction and each case constant to the width of the
  5487. // register. By widening the type of the switch condition, subsequent
  5488. // comparisons (for case comparisons) will not need to be extended to the
  5489. // preferred register width, so we will potentially eliminate N-1 extends,
  5490. // where N is the number of cases in the switch.
  5491. auto *NewType = Type::getIntNTy(Context, RegWidth);
  5492. // Zero-extend the switch condition and case constants unless the switch
  5493. // condition is a function argument that is already being sign-extended.
  5494. // In that case, we can avoid an unnecessary mask/extension by sign-extending
  5495. // everything instead.
  5496. Instruction::CastOps ExtType = Instruction::ZExt;
  5497. if (auto *Arg = dyn_cast<Argument>(Cond))
  5498. if (Arg->hasSExtAttr())
  5499. ExtType = Instruction::SExt;
  5500. auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
  5501. ExtInst->insertBefore(SI);
  5502. ExtInst->setDebugLoc(SI->getDebugLoc());
  5503. SI->setCondition(ExtInst);
  5504. for (auto Case : SI->cases()) {
  5505. APInt NarrowConst = Case.getCaseValue()->getValue();
  5506. APInt WideConst = (ExtType == Instruction::ZExt) ?
  5507. NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
  5508. Case.setValue(ConstantInt::get(Context, WideConst));
  5509. }
  5510. return true;
  5511. }
  5512. namespace {
  5513. /// Helper class to promote a scalar operation to a vector one.
  5514. /// This class is used to move downward extractelement transition.
  5515. /// E.g.,
  5516. /// a = vector_op <2 x i32>
  5517. /// b = extractelement <2 x i32> a, i32 0
  5518. /// c = scalar_op b
  5519. /// store c
  5520. ///
  5521. /// =>
  5522. /// a = vector_op <2 x i32>
  5523. /// c = vector_op a (equivalent to scalar_op on the related lane)
  5524. /// * d = extractelement <2 x i32> c, i32 0
  5525. /// * store d
  5526. /// Assuming both extractelement and store can be combine, we get rid of the
  5527. /// transition.
  5528. class VectorPromoteHelper {
  5529. /// DataLayout associated with the current module.
  5530. const DataLayout &DL;
  5531. /// Used to perform some checks on the legality of vector operations.
  5532. const TargetLowering &TLI;
  5533. /// Used to estimated the cost of the promoted chain.
  5534. const TargetTransformInfo &TTI;
  5535. /// The transition being moved downwards.
  5536. Instruction *Transition;
  5537. /// The sequence of instructions to be promoted.
  5538. SmallVector<Instruction *, 4> InstsToBePromoted;
  5539. /// Cost of combining a store and an extract.
  5540. unsigned StoreExtractCombineCost;
  5541. /// Instruction that will be combined with the transition.
  5542. Instruction *CombineInst = nullptr;
  5543. /// The instruction that represents the current end of the transition.
  5544. /// Since we are faking the promotion until we reach the end of the chain
  5545. /// of computation, we need a way to get the current end of the transition.
  5546. Instruction *getEndOfTransition() const {
  5547. if (InstsToBePromoted.empty())
  5548. return Transition;
  5549. return InstsToBePromoted.back();
  5550. }
  5551. /// Return the index of the original value in the transition.
  5552. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  5553. /// c, is at index 0.
  5554. unsigned getTransitionOriginalValueIdx() const {
  5555. assert(isa<ExtractElementInst>(Transition) &&
  5556. "Other kind of transitions are not supported yet");
  5557. return 0;
  5558. }
  5559. /// Return the index of the index in the transition.
  5560. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  5561. /// is at index 1.
  5562. unsigned getTransitionIdx() const {
  5563. assert(isa<ExtractElementInst>(Transition) &&
  5564. "Other kind of transitions are not supported yet");
  5565. return 1;
  5566. }
  5567. /// Get the type of the transition.
  5568. /// This is the type of the original value.
  5569. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  5570. /// transition is <2 x i32>.
  5571. Type *getTransitionType() const {
  5572. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  5573. }
  5574. /// Promote \p ToBePromoted by moving \p Def downward through.
  5575. /// I.e., we have the following sequence:
  5576. /// Def = Transition <ty1> a to <ty2>
  5577. /// b = ToBePromoted <ty2> Def, ...
  5578. /// =>
  5579. /// b = ToBePromoted <ty1> a, ...
  5580. /// Def = Transition <ty1> ToBePromoted to <ty2>
  5581. void promoteImpl(Instruction *ToBePromoted);
  5582. /// Check whether or not it is profitable to promote all the
  5583. /// instructions enqueued to be promoted.
  5584. bool isProfitableToPromote() {
  5585. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  5586. unsigned Index = isa<ConstantInt>(ValIdx)
  5587. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  5588. : -1;
  5589. Type *PromotedType = getTransitionType();
  5590. StoreInst *ST = cast<StoreInst>(CombineInst);
  5591. unsigned AS = ST->getPointerAddressSpace();
  5592. unsigned Align = ST->getAlignment();
  5593. // Check if this store is supported.
  5594. if (!TLI.allowsMisalignedMemoryAccesses(
  5595. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  5596. Align)) {
  5597. // If this is not supported, there is no way we can combine
  5598. // the extract with the store.
  5599. return false;
  5600. }
  5601. // The scalar chain of computation has to pay for the transition
  5602. // scalar to vector.
  5603. // The vector chain has to account for the combining cost.
  5604. uint64_t ScalarCost =
  5605. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  5606. uint64_t VectorCost = StoreExtractCombineCost;
  5607. for (const auto &Inst : InstsToBePromoted) {
  5608. // Compute the cost.
  5609. // By construction, all instructions being promoted are arithmetic ones.
  5610. // Moreover, one argument is a constant that can be viewed as a splat
  5611. // constant.
  5612. Value *Arg0 = Inst->getOperand(0);
  5613. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  5614. isa<ConstantFP>(Arg0);
  5615. TargetTransformInfo::OperandValueKind Arg0OVK =
  5616. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  5617. : TargetTransformInfo::OK_AnyValue;
  5618. TargetTransformInfo::OperandValueKind Arg1OVK =
  5619. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  5620. : TargetTransformInfo::OK_AnyValue;
  5621. ScalarCost += TTI.getArithmeticInstrCost(
  5622. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  5623. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  5624. Arg0OVK, Arg1OVK);
  5625. }
  5626. LLVM_DEBUG(
  5627. dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  5628. << ScalarCost << "\nVector: " << VectorCost << '\n');
  5629. return ScalarCost > VectorCost;
  5630. }
  5631. /// Generate a constant vector with \p Val with the same
  5632. /// number of elements as the transition.
  5633. /// \p UseSplat defines whether or not \p Val should be replicated
  5634. /// across the whole vector.
  5635. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  5636. /// otherwise we generate a vector with as many undef as possible:
  5637. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  5638. /// used at the index of the extract.
  5639. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  5640. unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
  5641. if (!UseSplat) {
  5642. // If we cannot determine where the constant must be, we have to
  5643. // use a splat constant.
  5644. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  5645. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  5646. ExtractIdx = CstVal->getSExtValue();
  5647. else
  5648. UseSplat = true;
  5649. }
  5650. unsigned End = getTransitionType()->getVectorNumElements();
  5651. if (UseSplat)
  5652. return ConstantVector::getSplat(End, Val);
  5653. SmallVector<Constant *, 4> ConstVec;
  5654. UndefValue *UndefVal = UndefValue::get(Val->getType());
  5655. for (unsigned Idx = 0; Idx != End; ++Idx) {
  5656. if (Idx == ExtractIdx)
  5657. ConstVec.push_back(Val);
  5658. else
  5659. ConstVec.push_back(UndefVal);
  5660. }
  5661. return ConstantVector::get(ConstVec);
  5662. }
  5663. /// Check if promoting to a vector type an operand at \p OperandIdx
  5664. /// in \p Use can trigger undefined behavior.
  5665. static bool canCauseUndefinedBehavior(const Instruction *Use,
  5666. unsigned OperandIdx) {
  5667. // This is not safe to introduce undef when the operand is on
  5668. // the right hand side of a division-like instruction.
  5669. if (OperandIdx != 1)
  5670. return false;
  5671. switch (Use->getOpcode()) {
  5672. default:
  5673. return false;
  5674. case Instruction::SDiv:
  5675. case Instruction::UDiv:
  5676. case Instruction::SRem:
  5677. case Instruction::URem:
  5678. return true;
  5679. case Instruction::FDiv:
  5680. case Instruction::FRem:
  5681. return !Use->hasNoNaNs();
  5682. }
  5683. llvm_unreachable(nullptr);
  5684. }
  5685. public:
  5686. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  5687. const TargetTransformInfo &TTI, Instruction *Transition,
  5688. unsigned CombineCost)
  5689. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  5690. StoreExtractCombineCost(CombineCost) {
  5691. assert(Transition && "Do not know how to promote null");
  5692. }
  5693. /// Check if we can promote \p ToBePromoted to \p Type.
  5694. bool canPromote(const Instruction *ToBePromoted) const {
  5695. // We could support CastInst too.
  5696. return isa<BinaryOperator>(ToBePromoted);
  5697. }
  5698. /// Check if it is profitable to promote \p ToBePromoted
  5699. /// by moving downward the transition through.
  5700. bool shouldPromote(const Instruction *ToBePromoted) const {
  5701. // Promote only if all the operands can be statically expanded.
  5702. // Indeed, we do not want to introduce any new kind of transitions.
  5703. for (const Use &U : ToBePromoted->operands()) {
  5704. const Value *Val = U.get();
  5705. if (Val == getEndOfTransition()) {
  5706. // If the use is a division and the transition is on the rhs,
  5707. // we cannot promote the operation, otherwise we may create a
  5708. // division by zero.
  5709. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  5710. return false;
  5711. continue;
  5712. }
  5713. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  5714. !isa<ConstantFP>(Val))
  5715. return false;
  5716. }
  5717. // Check that the resulting operation is legal.
  5718. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  5719. if (!ISDOpcode)
  5720. return false;
  5721. return StressStoreExtract ||
  5722. TLI.isOperationLegalOrCustom(
  5723. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  5724. }
  5725. /// Check whether or not \p Use can be combined
  5726. /// with the transition.
  5727. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  5728. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  5729. /// Record \p ToBePromoted as part of the chain to be promoted.
  5730. void enqueueForPromotion(Instruction *ToBePromoted) {
  5731. InstsToBePromoted.push_back(ToBePromoted);
  5732. }
  5733. /// Set the instruction that will be combined with the transition.
  5734. void recordCombineInstruction(Instruction *ToBeCombined) {
  5735. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  5736. CombineInst = ToBeCombined;
  5737. }
  5738. /// Promote all the instructions enqueued for promotion if it is
  5739. /// is profitable.
  5740. /// \return True if the promotion happened, false otherwise.
  5741. bool promote() {
  5742. // Check if there is something to promote.
  5743. // Right now, if we do not have anything to combine with,
  5744. // we assume the promotion is not profitable.
  5745. if (InstsToBePromoted.empty() || !CombineInst)
  5746. return false;
  5747. // Check cost.
  5748. if (!StressStoreExtract && !isProfitableToPromote())
  5749. return false;
  5750. // Promote.
  5751. for (auto &ToBePromoted : InstsToBePromoted)
  5752. promoteImpl(ToBePromoted);
  5753. InstsToBePromoted.clear();
  5754. return true;
  5755. }
  5756. };
  5757. } // end anonymous namespace
  5758. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  5759. // At this point, we know that all the operands of ToBePromoted but Def
  5760. // can be statically promoted.
  5761. // For Def, we need to use its parameter in ToBePromoted:
  5762. // b = ToBePromoted ty1 a
  5763. // Def = Transition ty1 b to ty2
  5764. // Move the transition down.
  5765. // 1. Replace all uses of the promoted operation by the transition.
  5766. // = ... b => = ... Def.
  5767. assert(ToBePromoted->getType() == Transition->getType() &&
  5768. "The type of the result of the transition does not match "
  5769. "the final type");
  5770. ToBePromoted->replaceAllUsesWith(Transition);
  5771. // 2. Update the type of the uses.
  5772. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  5773. Type *TransitionTy = getTransitionType();
  5774. ToBePromoted->mutateType(TransitionTy);
  5775. // 3. Update all the operands of the promoted operation with promoted
  5776. // operands.
  5777. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  5778. for (Use &U : ToBePromoted->operands()) {
  5779. Value *Val = U.get();
  5780. Value *NewVal = nullptr;
  5781. if (Val == Transition)
  5782. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  5783. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  5784. isa<ConstantFP>(Val)) {
  5785. // Use a splat constant if it is not safe to use undef.
  5786. NewVal = getConstantVector(
  5787. cast<Constant>(Val),
  5788. isa<UndefValue>(Val) ||
  5789. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  5790. } else
  5791. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  5792. "this?");
  5793. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  5794. }
  5795. Transition->moveAfter(ToBePromoted);
  5796. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  5797. }
  5798. /// Some targets can do store(extractelement) with one instruction.
  5799. /// Try to push the extractelement towards the stores when the target
  5800. /// has this feature and this is profitable.
  5801. bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
  5802. unsigned CombineCost = std::numeric_limits<unsigned>::max();
  5803. if (DisableStoreExtract || !TLI ||
  5804. (!StressStoreExtract &&
  5805. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  5806. Inst->getOperand(1), CombineCost)))
  5807. return false;
  5808. // At this point we know that Inst is a vector to scalar transition.
  5809. // Try to move it down the def-use chain, until:
  5810. // - We can combine the transition with its single use
  5811. // => we got rid of the transition.
  5812. // - We escape the current basic block
  5813. // => we would need to check that we are moving it at a cheaper place and
  5814. // we do not do that for now.
  5815. BasicBlock *Parent = Inst->getParent();
  5816. LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  5817. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  5818. // If the transition has more than one use, assume this is not going to be
  5819. // beneficial.
  5820. while (Inst->hasOneUse()) {
  5821. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  5822. LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  5823. if (ToBePromoted->getParent() != Parent) {
  5824. LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
  5825. << ToBePromoted->getParent()->getName()
  5826. << ") than the transition (" << Parent->getName()
  5827. << ").\n");
  5828. return false;
  5829. }
  5830. if (VPH.canCombine(ToBePromoted)) {
  5831. LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
  5832. << "will be combined with: " << *ToBePromoted << '\n');
  5833. VPH.recordCombineInstruction(ToBePromoted);
  5834. bool Changed = VPH.promote();
  5835. NumStoreExtractExposed += Changed;
  5836. return Changed;
  5837. }
  5838. LLVM_DEBUG(dbgs() << "Try promoting.\n");
  5839. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  5840. return false;
  5841. LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  5842. VPH.enqueueForPromotion(ToBePromoted);
  5843. Inst = ToBePromoted;
  5844. }
  5845. return false;
  5846. }
  5847. /// For the instruction sequence of store below, F and I values
  5848. /// are bundled together as an i64 value before being stored into memory.
  5849. /// Sometimes it is more efficient to generate separate stores for F and I,
  5850. /// which can remove the bitwise instructions or sink them to colder places.
  5851. ///
  5852. /// (store (or (zext (bitcast F to i32) to i64),
  5853. /// (shl (zext I to i64), 32)), addr) -->
  5854. /// (store F, addr) and (store I, addr+4)
  5855. ///
  5856. /// Similarly, splitting for other merged store can also be beneficial, like:
  5857. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  5858. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  5859. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  5860. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  5861. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  5862. ///
  5863. /// We allow each target to determine specifically which kind of splitting is
  5864. /// supported.
  5865. ///
  5866. /// The store patterns are commonly seen from the simple code snippet below
  5867. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  5868. /// void goo(const std::pair<int, float> &);
  5869. /// hoo() {
  5870. /// ...
  5871. /// goo(std::make_pair(tmp, ftmp));
  5872. /// ...
  5873. /// }
  5874. ///
  5875. /// Although we already have similar splitting in DAG Combine, we duplicate
  5876. /// it in CodeGenPrepare to catch the case in which pattern is across
  5877. /// multiple BBs. The logic in DAG Combine is kept to catch case generated
  5878. /// during code expansion.
  5879. static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
  5880. const TargetLowering &TLI) {
  5881. // Handle simple but common cases only.
  5882. Type *StoreType = SI.getValueOperand()->getType();
  5883. if (!DL.typeSizeEqualsStoreSize(StoreType) ||
  5884. DL.getTypeSizeInBits(StoreType) == 0)
  5885. return false;
  5886. unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
  5887. Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
  5888. if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
  5889. return false;
  5890. // Don't split the store if it is volatile.
  5891. if (SI.isVolatile())
  5892. return false;
  5893. // Match the following patterns:
  5894. // (store (or (zext LValue to i64),
  5895. // (shl (zext HValue to i64), 32)), HalfValBitSize)
  5896. // or
  5897. // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
  5898. // (zext LValue to i64),
  5899. // Expect both operands of OR and the first operand of SHL have only
  5900. // one use.
  5901. Value *LValue, *HValue;
  5902. if (!match(SI.getValueOperand(),
  5903. m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
  5904. m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
  5905. m_SpecificInt(HalfValBitSize))))))
  5906. return false;
  5907. // Check LValue and HValue are int with size less or equal than 32.
  5908. if (!LValue->getType()->isIntegerTy() ||
  5909. DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
  5910. !HValue->getType()->isIntegerTy() ||
  5911. DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
  5912. return false;
  5913. // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
  5914. // as the input of target query.
  5915. auto *LBC = dyn_cast<BitCastInst>(LValue);
  5916. auto *HBC = dyn_cast<BitCastInst>(HValue);
  5917. EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
  5918. : EVT::getEVT(LValue->getType());
  5919. EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
  5920. : EVT::getEVT(HValue->getType());
  5921. if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  5922. return false;
  5923. // Start to split store.
  5924. IRBuilder<> Builder(SI.getContext());
  5925. Builder.SetInsertPoint(&SI);
  5926. // If LValue/HValue is a bitcast in another BB, create a new one in current
  5927. // BB so it may be merged with the splitted stores by dag combiner.
  5928. if (LBC && LBC->getParent() != SI.getParent())
  5929. LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
  5930. if (HBC && HBC->getParent() != SI.getParent())
  5931. HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
  5932. bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
  5933. auto CreateSplitStore = [&](Value *V, bool Upper) {
  5934. V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
  5935. Value *Addr = Builder.CreateBitCast(
  5936. SI.getOperand(1),
  5937. SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
  5938. if ((IsLE && Upper) || (!IsLE && !Upper))
  5939. Addr = Builder.CreateGEP(
  5940. SplitStoreType, Addr,
  5941. ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
  5942. Builder.CreateAlignedStore(
  5943. V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
  5944. };
  5945. CreateSplitStore(LValue, false);
  5946. CreateSplitStore(HValue, true);
  5947. // Delete the old store.
  5948. SI.eraseFromParent();
  5949. return true;
  5950. }
  5951. // Return true if the GEP has two operands, the first operand is of a sequential
  5952. // type, and the second operand is a constant.
  5953. static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
  5954. gep_type_iterator I = gep_type_begin(*GEP);
  5955. return GEP->getNumOperands() == 2 &&
  5956. I.isSequential() &&
  5957. isa<ConstantInt>(GEP->getOperand(1));
  5958. }
  5959. // Try unmerging GEPs to reduce liveness interference (register pressure) across
  5960. // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
  5961. // reducing liveness interference across those edges benefits global register
  5962. // allocation. Currently handles only certain cases.
  5963. //
  5964. // For example, unmerge %GEPI and %UGEPI as below.
  5965. //
  5966. // ---------- BEFORE ----------
  5967. // SrcBlock:
  5968. // ...
  5969. // %GEPIOp = ...
  5970. // ...
  5971. // %GEPI = gep %GEPIOp, Idx
  5972. // ...
  5973. // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
  5974. // (* %GEPI is alive on the indirectbr edges due to other uses ahead)
  5975. // (* %GEPIOp is alive on the indirectbr edges only because of it's used by
  5976. // %UGEPI)
  5977. //
  5978. // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
  5979. // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
  5980. // ...
  5981. //
  5982. // DstBi:
  5983. // ...
  5984. // %UGEPI = gep %GEPIOp, UIdx
  5985. // ...
  5986. // ---------------------------
  5987. //
  5988. // ---------- AFTER ----------
  5989. // SrcBlock:
  5990. // ... (same as above)
  5991. // (* %GEPI is still alive on the indirectbr edges)
  5992. // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
  5993. // unmerging)
  5994. // ...
  5995. //
  5996. // DstBi:
  5997. // ...
  5998. // %UGEPI = gep %GEPI, (UIdx-Idx)
  5999. // ...
  6000. // ---------------------------
  6001. //
  6002. // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
  6003. // no longer alive on them.
  6004. //
  6005. // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
  6006. // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
  6007. // not to disable further simplications and optimizations as a result of GEP
  6008. // merging.
  6009. //
  6010. // Note this unmerging may increase the length of the data flow critical path
  6011. // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
  6012. // between the register pressure and the length of data-flow critical
  6013. // path. Restricting this to the uncommon IndirectBr case would minimize the
  6014. // impact of potentially longer critical path, if any, and the impact on compile
  6015. // time.
  6016. static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
  6017. const TargetTransformInfo *TTI) {
  6018. BasicBlock *SrcBlock = GEPI->getParent();
  6019. // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
  6020. // (non-IndirectBr) cases exit early here.
  6021. if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
  6022. return false;
  6023. // Check that GEPI is a simple gep with a single constant index.
  6024. if (!GEPSequentialConstIndexed(GEPI))
  6025. return false;
  6026. ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
  6027. // Check that GEPI is a cheap one.
  6028. if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
  6029. > TargetTransformInfo::TCC_Basic)
  6030. return false;
  6031. Value *GEPIOp = GEPI->getOperand(0);
  6032. // Check that GEPIOp is an instruction that's also defined in SrcBlock.
  6033. if (!isa<Instruction>(GEPIOp))
  6034. return false;
  6035. auto *GEPIOpI = cast<Instruction>(GEPIOp);
  6036. if (GEPIOpI->getParent() != SrcBlock)
  6037. return false;
  6038. // Check that GEP is used outside the block, meaning it's alive on the
  6039. // IndirectBr edge(s).
  6040. if (find_if(GEPI->users(), [&](User *Usr) {
  6041. if (auto *I = dyn_cast<Instruction>(Usr)) {
  6042. if (I->getParent() != SrcBlock) {
  6043. return true;
  6044. }
  6045. }
  6046. return false;
  6047. }) == GEPI->users().end())
  6048. return false;
  6049. // The second elements of the GEP chains to be unmerged.
  6050. std::vector<GetElementPtrInst *> UGEPIs;
  6051. // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
  6052. // on IndirectBr edges.
  6053. for (User *Usr : GEPIOp->users()) {
  6054. if (Usr == GEPI) continue;
  6055. // Check if Usr is an Instruction. If not, give up.
  6056. if (!isa<Instruction>(Usr))
  6057. return false;
  6058. auto *UI = cast<Instruction>(Usr);
  6059. // Check if Usr in the same block as GEPIOp, which is fine, skip.
  6060. if (UI->getParent() == SrcBlock)
  6061. continue;
  6062. // Check if Usr is a GEP. If not, give up.
  6063. if (!isa<GetElementPtrInst>(Usr))
  6064. return false;
  6065. auto *UGEPI = cast<GetElementPtrInst>(Usr);
  6066. // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
  6067. // the pointer operand to it. If so, record it in the vector. If not, give
  6068. // up.
  6069. if (!GEPSequentialConstIndexed(UGEPI))
  6070. return false;
  6071. if (UGEPI->getOperand(0) != GEPIOp)
  6072. return false;
  6073. if (GEPIIdx->getType() !=
  6074. cast<ConstantInt>(UGEPI->getOperand(1))->getType())
  6075. return false;
  6076. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6077. if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
  6078. > TargetTransformInfo::TCC_Basic)
  6079. return false;
  6080. UGEPIs.push_back(UGEPI);
  6081. }
  6082. if (UGEPIs.size() == 0)
  6083. return false;
  6084. // Check the materializing cost of (Uidx-Idx).
  6085. for (GetElementPtrInst *UGEPI : UGEPIs) {
  6086. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6087. APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
  6088. unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
  6089. if (ImmCost > TargetTransformInfo::TCC_Basic)
  6090. return false;
  6091. }
  6092. // Now unmerge between GEPI and UGEPIs.
  6093. for (GetElementPtrInst *UGEPI : UGEPIs) {
  6094. UGEPI->setOperand(0, GEPI);
  6095. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  6096. Constant *NewUGEPIIdx =
  6097. ConstantInt::get(GEPIIdx->getType(),
  6098. UGEPIIdx->getValue() - GEPIIdx->getValue());
  6099. UGEPI->setOperand(1, NewUGEPIIdx);
  6100. // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
  6101. // inbounds to avoid UB.
  6102. if (!GEPI->isInBounds()) {
  6103. UGEPI->setIsInBounds(false);
  6104. }
  6105. }
  6106. // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
  6107. // alive on IndirectBr edges).
  6108. assert(find_if(GEPIOp->users(), [&](User *Usr) {
  6109. return cast<Instruction>(Usr)->getParent() != SrcBlock;
  6110. }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
  6111. return true;
  6112. }
  6113. bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
  6114. // Bail out if we inserted the instruction to prevent optimizations from
  6115. // stepping on each other's toes.
  6116. if (InsertedInsts.count(I))
  6117. return false;
  6118. // TODO: Move into the switch on opcode below here.
  6119. if (PHINode *P = dyn_cast<PHINode>(I)) {
  6120. // It is possible for very late stage optimizations (such as SimplifyCFG)
  6121. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  6122. // trivial PHI, go ahead and zap it here.
  6123. if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
  6124. LargeOffsetGEPMap.erase(P);
  6125. P->replaceAllUsesWith(V);
  6126. P->eraseFromParent();
  6127. ++NumPHIsElim;
  6128. return true;
  6129. }
  6130. return false;
  6131. }
  6132. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  6133. // If the source of the cast is a constant, then this should have
  6134. // already been constant folded. The only reason NOT to constant fold
  6135. // it is if something (e.g. LSR) was careful to place the constant
  6136. // evaluation in a block other than then one that uses it (e.g. to hoist
  6137. // the address of globals out of a loop). If this is the case, we don't
  6138. // want to forward-subst the cast.
  6139. if (isa<Constant>(CI->getOperand(0)))
  6140. return false;
  6141. if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
  6142. return true;
  6143. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  6144. /// Sink a zext or sext into its user blocks if the target type doesn't
  6145. /// fit in one register
  6146. if (TLI &&
  6147. TLI->getTypeAction(CI->getContext(),
  6148. TLI->getValueType(*DL, CI->getType())) ==
  6149. TargetLowering::TypeExpandInteger) {
  6150. return SinkCast(CI);
  6151. } else {
  6152. bool MadeChange = optimizeExt(I);
  6153. return MadeChange | optimizeExtUses(I);
  6154. }
  6155. }
  6156. return false;
  6157. }
  6158. if (auto *Cmp = dyn_cast<CmpInst>(I))
  6159. if (TLI && optimizeCmp(Cmp, ModifiedDT))
  6160. return true;
  6161. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  6162. LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  6163. if (TLI) {
  6164. bool Modified = optimizeLoadExt(LI);
  6165. unsigned AS = LI->getPointerAddressSpace();
  6166. Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  6167. return Modified;
  6168. }
  6169. return false;
  6170. }
  6171. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  6172. if (TLI && splitMergedValStore(*SI, *DL, *TLI))
  6173. return true;
  6174. SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  6175. if (TLI) {
  6176. unsigned AS = SI->getPointerAddressSpace();
  6177. return optimizeMemoryInst(I, SI->getOperand(1),
  6178. SI->getOperand(0)->getType(), AS);
  6179. }
  6180. return false;
  6181. }
  6182. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  6183. unsigned AS = RMW->getPointerAddressSpace();
  6184. return optimizeMemoryInst(I, RMW->getPointerOperand(),
  6185. RMW->getType(), AS);
  6186. }
  6187. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
  6188. unsigned AS = CmpX->getPointerAddressSpace();
  6189. return optimizeMemoryInst(I, CmpX->getPointerOperand(),
  6190. CmpX->getCompareOperand()->getType(), AS);
  6191. }
  6192. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  6193. if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
  6194. EnableAndCmpSinking && TLI)
  6195. return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
  6196. // TODO: Move this into the switch on opcode - it handles shifts already.
  6197. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  6198. BinOp->getOpcode() == Instruction::LShr)) {
  6199. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  6200. if (TLI && CI && TLI->hasExtractBitsInsn())
  6201. if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
  6202. return true;
  6203. }
  6204. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  6205. if (GEPI->hasAllZeroIndices()) {
  6206. /// The GEP operand must be a pointer, so must its result -> BitCast
  6207. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  6208. GEPI->getName(), GEPI);
  6209. NC->setDebugLoc(GEPI->getDebugLoc());
  6210. GEPI->replaceAllUsesWith(NC);
  6211. GEPI->eraseFromParent();
  6212. ++NumGEPsElim;
  6213. optimizeInst(NC, ModifiedDT);
  6214. return true;
  6215. }
  6216. if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
  6217. return true;
  6218. }
  6219. return false;
  6220. }
  6221. if (tryToSinkFreeOperands(I))
  6222. return true;
  6223. switch (I->getOpcode()) {
  6224. case Instruction::Shl:
  6225. case Instruction::LShr:
  6226. case Instruction::AShr:
  6227. return optimizeShiftInst(cast<BinaryOperator>(I));
  6228. case Instruction::Call:
  6229. return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
  6230. case Instruction::Select:
  6231. return optimizeSelectInst(cast<SelectInst>(I));
  6232. case Instruction::ShuffleVector:
  6233. return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
  6234. case Instruction::Switch:
  6235. return optimizeSwitchInst(cast<SwitchInst>(I));
  6236. case Instruction::ExtractElement:
  6237. return optimizeExtractElementInst(cast<ExtractElementInst>(I));
  6238. }
  6239. return false;
  6240. }
  6241. /// Given an OR instruction, check to see if this is a bitreverse
  6242. /// idiom. If so, insert the new intrinsic and return true.
  6243. static bool makeBitReverse(Instruction &I, const DataLayout &DL,
  6244. const TargetLowering &TLI) {
  6245. if (!I.getType()->isIntegerTy() ||
  6246. !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
  6247. TLI.getValueType(DL, I.getType(), true)))
  6248. return false;
  6249. SmallVector<Instruction*, 4> Insts;
  6250. if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
  6251. return false;
  6252. Instruction *LastInst = Insts.back();
  6253. I.replaceAllUsesWith(LastInst);
  6254. RecursivelyDeleteTriviallyDeadInstructions(&I);
  6255. return true;
  6256. }
  6257. // In this pass we look for GEP and cast instructions that are used
  6258. // across basic blocks and rewrite them to improve basic-block-at-a-time
  6259. // selection.
  6260. bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
  6261. SunkAddrs.clear();
  6262. bool MadeChange = false;
  6263. CurInstIterator = BB.begin();
  6264. while (CurInstIterator != BB.end()) {
  6265. MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
  6266. if (ModifiedDT)
  6267. return true;
  6268. }
  6269. bool MadeBitReverse = true;
  6270. while (TLI && MadeBitReverse) {
  6271. MadeBitReverse = false;
  6272. for (auto &I : reverse(BB)) {
  6273. if (makeBitReverse(I, *DL, *TLI)) {
  6274. MadeBitReverse = MadeChange = true;
  6275. break;
  6276. }
  6277. }
  6278. }
  6279. MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
  6280. return MadeChange;
  6281. }
  6282. // llvm.dbg.value is far away from the value then iSel may not be able
  6283. // handle it properly. iSel will drop llvm.dbg.value if it can not
  6284. // find a node corresponding to the value.
  6285. bool CodeGenPrepare::placeDbgValues(Function &F) {
  6286. bool MadeChange = false;
  6287. for (BasicBlock &BB : F) {
  6288. Instruction *PrevNonDbgInst = nullptr;
  6289. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  6290. Instruction *Insn = &*BI++;
  6291. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  6292. // Leave dbg.values that refer to an alloca alone. These
  6293. // intrinsics describe the address of a variable (= the alloca)
  6294. // being taken. They should not be moved next to the alloca
  6295. // (and to the beginning of the scope), but rather stay close to
  6296. // where said address is used.
  6297. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  6298. PrevNonDbgInst = Insn;
  6299. continue;
  6300. }
  6301. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  6302. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  6303. // If VI is a phi in a block with an EHPad terminator, we can't insert
  6304. // after it.
  6305. if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
  6306. continue;
  6307. LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
  6308. << *DVI << ' ' << *VI);
  6309. DVI->removeFromParent();
  6310. if (isa<PHINode>(VI))
  6311. DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
  6312. else
  6313. DVI->insertAfter(VI);
  6314. MadeChange = true;
  6315. ++NumDbgValueMoved;
  6316. }
  6317. }
  6318. }
  6319. return MadeChange;
  6320. }
  6321. /// Scale down both weights to fit into uint32_t.
  6322. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  6323. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  6324. uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
  6325. NewTrue = NewTrue / Scale;
  6326. NewFalse = NewFalse / Scale;
  6327. }
  6328. /// Some targets prefer to split a conditional branch like:
  6329. /// \code
  6330. /// %0 = icmp ne i32 %a, 0
  6331. /// %1 = icmp ne i32 %b, 0
  6332. /// %or.cond = or i1 %0, %1
  6333. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  6334. /// \endcode
  6335. /// into multiple branch instructions like:
  6336. /// \code
  6337. /// bb1:
  6338. /// %0 = icmp ne i32 %a, 0
  6339. /// br i1 %0, label %TrueBB, label %bb2
  6340. /// bb2:
  6341. /// %1 = icmp ne i32 %b, 0
  6342. /// br i1 %1, label %TrueBB, label %FalseBB
  6343. /// \endcode
  6344. /// This usually allows instruction selection to do even further optimizations
  6345. /// and combine the compare with the branch instruction. Currently this is
  6346. /// applied for targets which have "cheap" jump instructions.
  6347. ///
  6348. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  6349. ///
  6350. bool CodeGenPrepare::splitBranchCondition(Function &F, bool &ModifiedDT) {
  6351. if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
  6352. return false;
  6353. bool MadeChange = false;
  6354. for (auto &BB : F) {
  6355. // Does this BB end with the following?
  6356. // %cond1 = icmp|fcmp|binary instruction ...
  6357. // %cond2 = icmp|fcmp|binary instruction ...
  6358. // %cond.or = or|and i1 %cond1, cond2
  6359. // br i1 %cond.or label %dest1, label %dest2"
  6360. BinaryOperator *LogicOp;
  6361. BasicBlock *TBB, *FBB;
  6362. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  6363. continue;
  6364. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  6365. if (Br1->getMetadata(LLVMContext::MD_unpredictable))
  6366. continue;
  6367. unsigned Opc;
  6368. Value *Cond1, *Cond2;
  6369. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  6370. m_OneUse(m_Value(Cond2)))))
  6371. Opc = Instruction::And;
  6372. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  6373. m_OneUse(m_Value(Cond2)))))
  6374. Opc = Instruction::Or;
  6375. else
  6376. continue;
  6377. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  6378. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  6379. continue;
  6380. LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  6381. // Create a new BB.
  6382. auto TmpBB =
  6383. BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
  6384. BB.getParent(), BB.getNextNode());
  6385. // Update original basic block by using the first condition directly by the
  6386. // branch instruction and removing the no longer needed and/or instruction.
  6387. Br1->setCondition(Cond1);
  6388. LogicOp->eraseFromParent();
  6389. // Depending on the condition we have to either replace the true or the
  6390. // false successor of the original branch instruction.
  6391. if (Opc == Instruction::And)
  6392. Br1->setSuccessor(0, TmpBB);
  6393. else
  6394. Br1->setSuccessor(1, TmpBB);
  6395. // Fill in the new basic block.
  6396. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  6397. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  6398. I->removeFromParent();
  6399. I->insertBefore(Br2);
  6400. }
  6401. // Update PHI nodes in both successors. The original BB needs to be
  6402. // replaced in one successor's PHI nodes, because the branch comes now from
  6403. // the newly generated BB (NewBB). In the other successor we need to add one
  6404. // incoming edge to the PHI nodes, because both branch instructions target
  6405. // now the same successor. Depending on the original branch condition
  6406. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  6407. // we perform the correct update for the PHI nodes.
  6408. // This doesn't change the successor order of the just created branch
  6409. // instruction (or any other instruction).
  6410. if (Opc == Instruction::Or)
  6411. std::swap(TBB, FBB);
  6412. // Replace the old BB with the new BB.
  6413. TBB->replacePhiUsesWith(&BB, TmpBB);
  6414. // Add another incoming edge form the new BB.
  6415. for (PHINode &PN : FBB->phis()) {
  6416. auto *Val = PN.getIncomingValueForBlock(&BB);
  6417. PN.addIncoming(Val, TmpBB);
  6418. }
  6419. // Update the branch weights (from SelectionDAGBuilder::
  6420. // FindMergedConditions).
  6421. if (Opc == Instruction::Or) {
  6422. // Codegen X | Y as:
  6423. // BB1:
  6424. // jmp_if_X TBB
  6425. // jmp TmpBB
  6426. // TmpBB:
  6427. // jmp_if_Y TBB
  6428. // jmp FBB
  6429. //
  6430. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  6431. // The requirement is that
  6432. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  6433. // = TrueProb for original BB.
  6434. // Assuming the original weights are A and B, one choice is to set BB1's
  6435. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  6436. // assumes that
  6437. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  6438. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  6439. // TmpBB, but the math is more complicated.
  6440. uint64_t TrueWeight, FalseWeight;
  6441. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  6442. uint64_t NewTrueWeight = TrueWeight;
  6443. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  6444. scaleWeights(NewTrueWeight, NewFalseWeight);
  6445. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  6446. .createBranchWeights(TrueWeight, FalseWeight));
  6447. NewTrueWeight = TrueWeight;
  6448. NewFalseWeight = 2 * FalseWeight;
  6449. scaleWeights(NewTrueWeight, NewFalseWeight);
  6450. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  6451. .createBranchWeights(TrueWeight, FalseWeight));
  6452. }
  6453. } else {
  6454. // Codegen X & Y as:
  6455. // BB1:
  6456. // jmp_if_X TmpBB
  6457. // jmp FBB
  6458. // TmpBB:
  6459. // jmp_if_Y TBB
  6460. // jmp FBB
  6461. //
  6462. // This requires creation of TmpBB after CurBB.
  6463. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  6464. // The requirement is that
  6465. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  6466. // = FalseProb for original BB.
  6467. // Assuming the original weights are A and B, one choice is to set BB1's
  6468. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  6469. // assumes that
  6470. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  6471. uint64_t TrueWeight, FalseWeight;
  6472. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  6473. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  6474. uint64_t NewFalseWeight = FalseWeight;
  6475. scaleWeights(NewTrueWeight, NewFalseWeight);
  6476. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  6477. .createBranchWeights(TrueWeight, FalseWeight));
  6478. NewTrueWeight = 2 * TrueWeight;
  6479. NewFalseWeight = FalseWeight;
  6480. scaleWeights(NewTrueWeight, NewFalseWeight);
  6481. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  6482. .createBranchWeights(TrueWeight, FalseWeight));
  6483. }
  6484. }
  6485. ModifiedDT = true;
  6486. MadeChange = true;
  6487. LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  6488. TmpBB->dump());
  6489. }
  6490. return MadeChange;
  6491. }