CodeGenPrepare.cpp 256 KB

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