SimplifyCFG.cpp 232 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114
  1. //===- SimplifyCFG.cpp - Code to perform CFG simplification ---------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // Peephole optimize the CFG.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "llvm/ADT/APInt.h"
  13. #include "llvm/ADT/ArrayRef.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/Optional.h"
  16. #include "llvm/ADT/STLExtras.h"
  17. #include "llvm/ADT/SetOperations.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallPtrSet.h"
  20. #include "llvm/ADT/SmallVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/ADT/StringRef.h"
  23. #include "llvm/Analysis/AssumptionCache.h"
  24. #include "llvm/Analysis/ConstantFolding.h"
  25. #include "llvm/Analysis/EHPersonalities.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/MemorySSA.h"
  28. #include "llvm/Analysis/MemorySSAUpdater.h"
  29. #include "llvm/Analysis/TargetTransformInfo.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/IR/Attributes.h"
  32. #include "llvm/IR/BasicBlock.h"
  33. #include "llvm/IR/CFG.h"
  34. #include "llvm/IR/CallSite.h"
  35. #include "llvm/IR/Constant.h"
  36. #include "llvm/IR/ConstantRange.h"
  37. #include "llvm/IR/Constants.h"
  38. #include "llvm/IR/DataLayout.h"
  39. #include "llvm/IR/DerivedTypes.h"
  40. #include "llvm/IR/Function.h"
  41. #include "llvm/IR/GlobalValue.h"
  42. #include "llvm/IR/GlobalVariable.h"
  43. #include "llvm/IR/IRBuilder.h"
  44. #include "llvm/IR/InstrTypes.h"
  45. #include "llvm/IR/Instruction.h"
  46. #include "llvm/IR/Instructions.h"
  47. #include "llvm/IR/IntrinsicInst.h"
  48. #include "llvm/IR/Intrinsics.h"
  49. #include "llvm/IR/LLVMContext.h"
  50. #include "llvm/IR/MDBuilder.h"
  51. #include "llvm/IR/Metadata.h"
  52. #include "llvm/IR/Module.h"
  53. #include "llvm/IR/NoFolder.h"
  54. #include "llvm/IR/Operator.h"
  55. #include "llvm/IR/PatternMatch.h"
  56. #include "llvm/IR/Type.h"
  57. #include "llvm/IR/Use.h"
  58. #include "llvm/IR/User.h"
  59. #include "llvm/IR/Value.h"
  60. #include "llvm/Support/Casting.h"
  61. #include "llvm/Support/CommandLine.h"
  62. #include "llvm/Support/Debug.h"
  63. #include "llvm/Support/ErrorHandling.h"
  64. #include "llvm/Support/KnownBits.h"
  65. #include "llvm/Support/MathExtras.h"
  66. #include "llvm/Support/raw_ostream.h"
  67. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  68. #include "llvm/Transforms/Utils/Local.h"
  69. #include "llvm/Transforms/Utils/ValueMapper.h"
  70. #include <algorithm>
  71. #include <cassert>
  72. #include <climits>
  73. #include <cstddef>
  74. #include <cstdint>
  75. #include <iterator>
  76. #include <map>
  77. #include <set>
  78. #include <tuple>
  79. #include <utility>
  80. #include <vector>
  81. using namespace llvm;
  82. using namespace PatternMatch;
  83. #define DEBUG_TYPE "simplifycfg"
  84. // Chosen as 2 so as to be cheap, but still to have enough power to fold
  85. // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
  86. // To catch this, we need to fold a compare and a select, hence '2' being the
  87. // minimum reasonable default.
  88. static cl::opt<unsigned> PHINodeFoldingThreshold(
  89. "phi-node-folding-threshold", cl::Hidden, cl::init(2),
  90. cl::desc(
  91. "Control the amount of phi node folding to perform (default = 2)"));
  92. static cl::opt<bool> DupRet(
  93. "simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  94. cl::desc("Duplicate return instructions into unconditional branches"));
  95. static cl::opt<bool>
  96. SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
  97. cl::desc("Sink common instructions down to the end block"));
  98. static cl::opt<bool> HoistCondStores(
  99. "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
  100. cl::desc("Hoist conditional stores if an unconditional store precedes"));
  101. static cl::opt<bool> MergeCondStores(
  102. "simplifycfg-merge-cond-stores", cl::Hidden, cl::init(true),
  103. cl::desc("Hoist conditional stores even if an unconditional store does not "
  104. "precede - hoist multiple conditional stores into a single "
  105. "predicated store"));
  106. static cl::opt<bool> MergeCondStoresAggressively(
  107. "simplifycfg-merge-cond-stores-aggressively", cl::Hidden, cl::init(false),
  108. cl::desc("When merging conditional stores, do so even if the resultant "
  109. "basic blocks are unlikely to be if-converted as a result"));
  110. static cl::opt<bool> SpeculateOneExpensiveInst(
  111. "speculate-one-expensive-inst", cl::Hidden, cl::init(true),
  112. cl::desc("Allow exactly one expensive instruction to be speculatively "
  113. "executed"));
  114. static cl::opt<unsigned> MaxSpeculationDepth(
  115. "max-speculation-depth", cl::Hidden, cl::init(10),
  116. cl::desc("Limit maximum recursion depth when calculating costs of "
  117. "speculatively executed instructions"));
  118. STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
  119. STATISTIC(NumLinearMaps,
  120. "Number of switch instructions turned into linear mapping");
  121. STATISTIC(NumLookupTables,
  122. "Number of switch instructions turned into lookup tables");
  123. STATISTIC(
  124. NumLookupTablesHoles,
  125. "Number of switch instructions turned into lookup tables (holes checked)");
  126. STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
  127. STATISTIC(NumSinkCommons,
  128. "Number of common instructions sunk down to the end block");
  129. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  130. namespace {
  131. // The first field contains the value that the switch produces when a certain
  132. // case group is selected, and the second field is a vector containing the
  133. // cases composing the case group.
  134. using SwitchCaseResultVectorTy =
  135. SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>;
  136. // The first field contains the phi node that generates a result of the switch
  137. // and the second field contains the value generated for a certain case in the
  138. // switch for that PHI.
  139. using SwitchCaseResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
  140. /// ValueEqualityComparisonCase - Represents a case of a switch.
  141. struct ValueEqualityComparisonCase {
  142. ConstantInt *Value;
  143. BasicBlock *Dest;
  144. ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
  145. : Value(Value), Dest(Dest) {}
  146. bool operator<(ValueEqualityComparisonCase RHS) const {
  147. // Comparing pointers is ok as we only rely on the order for uniquing.
  148. return Value < RHS.Value;
  149. }
  150. bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
  151. };
  152. class SimplifyCFGOpt {
  153. const TargetTransformInfo &TTI;
  154. const DataLayout &DL;
  155. SmallPtrSetImpl<BasicBlock *> *LoopHeaders;
  156. const SimplifyCFGOptions &Options;
  157. bool Resimplify;
  158. Value *isValueEqualityComparison(Instruction *TI);
  159. BasicBlock *GetValueEqualityComparisonCases(
  160. Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases);
  161. bool SimplifyEqualityComparisonWithOnlyPredecessor(Instruction *TI,
  162. BasicBlock *Pred,
  163. IRBuilder<> &Builder);
  164. bool FoldValueComparisonIntoPredecessors(Instruction *TI,
  165. IRBuilder<> &Builder);
  166. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  167. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  168. bool SimplifySingleResume(ResumeInst *RI);
  169. bool SimplifyCommonResume(ResumeInst *RI);
  170. bool SimplifyCleanupReturn(CleanupReturnInst *RI);
  171. bool SimplifyUnreachable(UnreachableInst *UI);
  172. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  173. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  174. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder);
  175. bool SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder);
  176. bool tryToSimplifyUncondBranchWithICmpInIt(ICmpInst *ICI,
  177. IRBuilder<> &Builder);
  178. public:
  179. SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
  180. SmallPtrSetImpl<BasicBlock *> *LoopHeaders,
  181. const SimplifyCFGOptions &Opts)
  182. : TTI(TTI), DL(DL), LoopHeaders(LoopHeaders), Options(Opts) {}
  183. bool run(BasicBlock *BB);
  184. bool simplifyOnce(BasicBlock *BB);
  185. // Helper to set Resimplify and return change indication.
  186. bool requestResimplify() {
  187. Resimplify = true;
  188. return true;
  189. }
  190. };
  191. } // end anonymous namespace
  192. /// Return true if it is safe to merge these two
  193. /// terminator instructions together.
  194. static bool
  195. SafeToMergeTerminators(Instruction *SI1, Instruction *SI2,
  196. SmallSetVector<BasicBlock *, 4> *FailBlocks = nullptr) {
  197. if (SI1 == SI2)
  198. return false; // Can't merge with self!
  199. // It is not safe to merge these two switch instructions if they have a common
  200. // successor, and if that successor has a PHI node, and if *that* PHI node has
  201. // conflicting incoming values from the two switch blocks.
  202. BasicBlock *SI1BB = SI1->getParent();
  203. BasicBlock *SI2BB = SI2->getParent();
  204. SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  205. bool Fail = false;
  206. for (BasicBlock *Succ : successors(SI2BB))
  207. if (SI1Succs.count(Succ))
  208. for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
  209. PHINode *PN = cast<PHINode>(BBI);
  210. if (PN->getIncomingValueForBlock(SI1BB) !=
  211. PN->getIncomingValueForBlock(SI2BB)) {
  212. if (FailBlocks)
  213. FailBlocks->insert(Succ);
  214. Fail = true;
  215. }
  216. }
  217. return !Fail;
  218. }
  219. /// Return true if it is safe and profitable to merge these two terminator
  220. /// instructions together, where SI1 is an unconditional branch. PhiNodes will
  221. /// store all PHI nodes in common successors.
  222. static bool
  223. isProfitableToFoldUnconditional(BranchInst *SI1, BranchInst *SI2,
  224. Instruction *Cond,
  225. SmallVectorImpl<PHINode *> &PhiNodes) {
  226. if (SI1 == SI2)
  227. return false; // Can't merge with self!
  228. assert(SI1->isUnconditional() && SI2->isConditional());
  229. // We fold the unconditional branch if we can easily update all PHI nodes in
  230. // common successors:
  231. // 1> We have a constant incoming value for the conditional branch;
  232. // 2> We have "Cond" as the incoming value for the unconditional branch;
  233. // 3> SI2->getCondition() and Cond have same operands.
  234. CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
  235. if (!Ci2)
  236. return false;
  237. if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
  238. Cond->getOperand(1) == Ci2->getOperand(1)) &&
  239. !(Cond->getOperand(0) == Ci2->getOperand(1) &&
  240. Cond->getOperand(1) == Ci2->getOperand(0)))
  241. return false;
  242. BasicBlock *SI1BB = SI1->getParent();
  243. BasicBlock *SI2BB = SI2->getParent();
  244. SmallPtrSet<BasicBlock *, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  245. for (BasicBlock *Succ : successors(SI2BB))
  246. if (SI1Succs.count(Succ))
  247. for (BasicBlock::iterator BBI = Succ->begin(); isa<PHINode>(BBI); ++BBI) {
  248. PHINode *PN = cast<PHINode>(BBI);
  249. if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
  250. !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
  251. return false;
  252. PhiNodes.push_back(PN);
  253. }
  254. return true;
  255. }
  256. /// Update PHI nodes in Succ to indicate that there will now be entries in it
  257. /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
  258. /// will be the same as those coming in from ExistPred, an existing predecessor
  259. /// of Succ.
  260. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  261. BasicBlock *ExistPred,
  262. MemorySSAUpdater *MSSAU = nullptr) {
  263. for (PHINode &PN : Succ->phis())
  264. PN.addIncoming(PN.getIncomingValueForBlock(ExistPred), NewPred);
  265. if (MSSAU)
  266. if (auto *MPhi = MSSAU->getMemorySSA()->getMemoryAccess(Succ))
  267. MPhi->addIncoming(MPhi->getIncomingValueForBlock(ExistPred), NewPred);
  268. }
  269. /// Compute an abstract "cost" of speculating the given instruction,
  270. /// which is assumed to be safe to speculate. TCC_Free means cheap,
  271. /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
  272. /// expensive.
  273. static unsigned ComputeSpeculationCost(const User *I,
  274. const TargetTransformInfo &TTI) {
  275. assert(isSafeToSpeculativelyExecute(I) &&
  276. "Instruction is not safe to speculatively execute!");
  277. return TTI.getUserCost(I);
  278. }
  279. /// If we have a merge point of an "if condition" as accepted above,
  280. /// return true if the specified value dominates the block. We
  281. /// don't handle the true generality of domination here, just a special case
  282. /// which works well enough for us.
  283. ///
  284. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  285. /// see if V (which must be an instruction) and its recursive operands
  286. /// that do not dominate BB have a combined cost lower than CostRemaining and
  287. /// are non-trapping. If both are true, the instruction is inserted into the
  288. /// set and true is returned.
  289. ///
  290. /// The cost for most non-trapping instructions is defined as 1 except for
  291. /// Select whose cost is 2.
  292. ///
  293. /// After this function returns, CostRemaining is decreased by the cost of
  294. /// V plus its non-dominating operands. If that cost is greater than
  295. /// CostRemaining, false is returned and CostRemaining is undefined.
  296. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  297. SmallPtrSetImpl<Instruction *> &AggressiveInsts,
  298. unsigned &CostRemaining,
  299. const TargetTransformInfo &TTI,
  300. unsigned Depth = 0) {
  301. // It is possible to hit a zero-cost cycle (phi/gep instructions for example),
  302. // so limit the recursion depth.
  303. // TODO: While this recursion limit does prevent pathological behavior, it
  304. // would be better to track visited instructions to avoid cycles.
  305. if (Depth == MaxSpeculationDepth)
  306. return false;
  307. Instruction *I = dyn_cast<Instruction>(V);
  308. if (!I) {
  309. // Non-instructions all dominate instructions, but not all constantexprs
  310. // can be executed unconditionally.
  311. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  312. if (C->canTrap())
  313. return false;
  314. return true;
  315. }
  316. BasicBlock *PBB = I->getParent();
  317. // We don't want to allow weird loops that might have the "if condition" in
  318. // the bottom of this block.
  319. if (PBB == BB)
  320. return false;
  321. // If this instruction is defined in a block that contains an unconditional
  322. // branch to BB, then it must be in the 'conditional' part of the "if
  323. // statement". If not, it definitely dominates the region.
  324. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  325. if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
  326. return true;
  327. // If we have seen this instruction before, don't count it again.
  328. if (AggressiveInsts.count(I))
  329. return true;
  330. // Okay, it looks like the instruction IS in the "condition". Check to
  331. // see if it's a cheap instruction to unconditionally compute, and if it
  332. // only uses stuff defined outside of the condition. If so, hoist it out.
  333. if (!isSafeToSpeculativelyExecute(I))
  334. return false;
  335. unsigned Cost = ComputeSpeculationCost(I, TTI);
  336. // Allow exactly one instruction to be speculated regardless of its cost
  337. // (as long as it is safe to do so).
  338. // This is intended to flatten the CFG even if the instruction is a division
  339. // or other expensive operation. The speculation of an expensive instruction
  340. // is expected to be undone in CodeGenPrepare if the speculation has not
  341. // enabled further IR optimizations.
  342. if (Cost > CostRemaining &&
  343. (!SpeculateOneExpensiveInst || !AggressiveInsts.empty() || Depth > 0))
  344. return false;
  345. // Avoid unsigned wrap.
  346. CostRemaining = (Cost > CostRemaining) ? 0 : CostRemaining - Cost;
  347. // Okay, we can only really hoist these out if their operands do
  348. // not take us over the cost threshold.
  349. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  350. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI,
  351. Depth + 1))
  352. return false;
  353. // Okay, it's safe to do this! Remember this instruction.
  354. AggressiveInsts.insert(I);
  355. return true;
  356. }
  357. /// Extract ConstantInt from value, looking through IntToPtr
  358. /// and PointerNullValue. Return NULL if value is not a constant int.
  359. static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
  360. // Normal constant int.
  361. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  362. if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
  363. return CI;
  364. // This is some kind of pointer constant. Turn it into a pointer-sized
  365. // ConstantInt if possible.
  366. IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
  367. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  368. if (isa<ConstantPointerNull>(V))
  369. return ConstantInt::get(PtrTy, 0);
  370. // IntToPtr const int.
  371. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  372. if (CE->getOpcode() == Instruction::IntToPtr)
  373. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  374. // The constant is very likely to have the right type already.
  375. if (CI->getType() == PtrTy)
  376. return CI;
  377. else
  378. return cast<ConstantInt>(
  379. ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  380. }
  381. return nullptr;
  382. }
  383. namespace {
  384. /// Given a chain of or (||) or and (&&) comparison of a value against a
  385. /// constant, this will try to recover the information required for a switch
  386. /// structure.
  387. /// It will depth-first traverse the chain of comparison, seeking for patterns
  388. /// like %a == 12 or %a < 4 and combine them to produce a set of integer
  389. /// representing the different cases for the switch.
  390. /// Note that if the chain is composed of '||' it will build the set of elements
  391. /// that matches the comparisons (i.e. any of this value validate the chain)
  392. /// while for a chain of '&&' it will build the set elements that make the test
  393. /// fail.
  394. struct ConstantComparesGatherer {
  395. const DataLayout &DL;
  396. /// Value found for the switch comparison
  397. Value *CompValue = nullptr;
  398. /// Extra clause to be checked before the switch
  399. Value *Extra = nullptr;
  400. /// Set of integers to match in switch
  401. SmallVector<ConstantInt *, 8> Vals;
  402. /// Number of comparisons matched in the and/or chain
  403. unsigned UsedICmps = 0;
  404. /// Construct and compute the result for the comparison instruction Cond
  405. ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL) : DL(DL) {
  406. gather(Cond);
  407. }
  408. ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
  409. ConstantComparesGatherer &
  410. operator=(const ConstantComparesGatherer &) = delete;
  411. private:
  412. /// Try to set the current value used for the comparison, it succeeds only if
  413. /// it wasn't set before or if the new value is the same as the old one
  414. bool setValueOnce(Value *NewVal) {
  415. if (CompValue && CompValue != NewVal)
  416. return false;
  417. CompValue = NewVal;
  418. return (CompValue != nullptr);
  419. }
  420. /// Try to match Instruction "I" as a comparison against a constant and
  421. /// populates the array Vals with the set of values that match (or do not
  422. /// match depending on isEQ).
  423. /// Return false on failure. On success, the Value the comparison matched
  424. /// against is placed in CompValue.
  425. /// If CompValue is already set, the function is expected to fail if a match
  426. /// is found but the value compared to is different.
  427. bool matchInstruction(Instruction *I, bool isEQ) {
  428. // If this is an icmp against a constant, handle this as one of the cases.
  429. ICmpInst *ICI;
  430. ConstantInt *C;
  431. if (!((ICI = dyn_cast<ICmpInst>(I)) &&
  432. (C = GetConstantInt(I->getOperand(1), DL)))) {
  433. return false;
  434. }
  435. Value *RHSVal;
  436. const APInt *RHSC;
  437. // Pattern match a special case
  438. // (x & ~2^z) == y --> x == y || x == y|2^z
  439. // This undoes a transformation done by instcombine to fuse 2 compares.
  440. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_NE)) {
  441. // It's a little bit hard to see why the following transformations are
  442. // correct. Here is a CVC3 program to verify them for 64-bit values:
  443. /*
  444. ONE : BITVECTOR(64) = BVZEROEXTEND(0bin1, 63);
  445. x : BITVECTOR(64);
  446. y : BITVECTOR(64);
  447. z : BITVECTOR(64);
  448. mask : BITVECTOR(64) = BVSHL(ONE, z);
  449. QUERY( (y & ~mask = y) =>
  450. ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
  451. );
  452. QUERY( (y | mask = y) =>
  453. ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
  454. );
  455. */
  456. // Please note that each pattern must be a dual implication (<--> or
  457. // iff). One directional implication can create spurious matches. If the
  458. // implication is only one-way, an unsatisfiable condition on the left
  459. // side can imply a satisfiable condition on the right side. Dual
  460. // implication ensures that satisfiable conditions are transformed to
  461. // other satisfiable conditions and unsatisfiable conditions are
  462. // transformed to other unsatisfiable conditions.
  463. // Here is a concrete example of a unsatisfiable condition on the left
  464. // implying a satisfiable condition on the right:
  465. //
  466. // mask = (1 << z)
  467. // (x & ~mask) == y --> (x == y || x == (y | mask))
  468. //
  469. // Substituting y = 3, z = 0 yields:
  470. // (x & -2) == 3 --> (x == 3 || x == 2)
  471. // Pattern match a special case:
  472. /*
  473. QUERY( (y & ~mask = y) =>
  474. ((x & ~mask = y) <=> (x = y OR x = (y | mask)))
  475. );
  476. */
  477. if (match(ICI->getOperand(0),
  478. m_And(m_Value(RHSVal), m_APInt(RHSC)))) {
  479. APInt Mask = ~*RHSC;
  480. if (Mask.isPowerOf2() && (C->getValue() & ~Mask) == C->getValue()) {
  481. // If we already have a value for the switch, it has to match!
  482. if (!setValueOnce(RHSVal))
  483. return false;
  484. Vals.push_back(C);
  485. Vals.push_back(
  486. ConstantInt::get(C->getContext(),
  487. C->getValue() | Mask));
  488. UsedICmps++;
  489. return true;
  490. }
  491. }
  492. // Pattern match a special case:
  493. /*
  494. QUERY( (y | mask = y) =>
  495. ((x | mask = y) <=> (x = y OR x = (y & ~mask)))
  496. );
  497. */
  498. if (match(ICI->getOperand(0),
  499. m_Or(m_Value(RHSVal), m_APInt(RHSC)))) {
  500. APInt Mask = *RHSC;
  501. if (Mask.isPowerOf2() && (C->getValue() | Mask) == C->getValue()) {
  502. // If we already have a value for the switch, it has to match!
  503. if (!setValueOnce(RHSVal))
  504. return false;
  505. Vals.push_back(C);
  506. Vals.push_back(ConstantInt::get(C->getContext(),
  507. C->getValue() & ~Mask));
  508. UsedICmps++;
  509. return true;
  510. }
  511. }
  512. // If we already have a value for the switch, it has to match!
  513. if (!setValueOnce(ICI->getOperand(0)))
  514. return false;
  515. UsedICmps++;
  516. Vals.push_back(C);
  517. return ICI->getOperand(0);
  518. }
  519. // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
  520. ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
  521. ICI->getPredicate(), C->getValue());
  522. // Shift the range if the compare is fed by an add. This is the range
  523. // compare idiom as emitted by instcombine.
  524. Value *CandidateVal = I->getOperand(0);
  525. if (match(I->getOperand(0), m_Add(m_Value(RHSVal), m_APInt(RHSC)))) {
  526. Span = Span.subtract(*RHSC);
  527. CandidateVal = RHSVal;
  528. }
  529. // If this is an and/!= check, then we are looking to build the set of
  530. // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
  531. // x != 0 && x != 1.
  532. if (!isEQ)
  533. Span = Span.inverse();
  534. // If there are a ton of values, we don't want to make a ginormous switch.
  535. if (Span.isSizeLargerThan(8) || Span.isEmptySet()) {
  536. return false;
  537. }
  538. // If we already have a value for the switch, it has to match!
  539. if (!setValueOnce(CandidateVal))
  540. return false;
  541. // Add all values from the range to the set
  542. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  543. Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
  544. UsedICmps++;
  545. return true;
  546. }
  547. /// Given a potentially 'or'd or 'and'd together collection of icmp
  548. /// eq/ne/lt/gt instructions that compare a value against a constant, extract
  549. /// the value being compared, and stick the list constants into the Vals
  550. /// vector.
  551. /// One "Extra" case is allowed to differ from the other.
  552. void gather(Value *V) {
  553. Instruction *I = dyn_cast<Instruction>(V);
  554. bool isEQ = (I->getOpcode() == Instruction::Or);
  555. // Keep a stack (SmallVector for efficiency) for depth-first traversal
  556. SmallVector<Value *, 8> DFT;
  557. SmallPtrSet<Value *, 8> Visited;
  558. // Initialize
  559. Visited.insert(V);
  560. DFT.push_back(V);
  561. while (!DFT.empty()) {
  562. V = DFT.pop_back_val();
  563. if (Instruction *I = dyn_cast<Instruction>(V)) {
  564. // If it is a || (or && depending on isEQ), process the operands.
  565. if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
  566. if (Visited.insert(I->getOperand(1)).second)
  567. DFT.push_back(I->getOperand(1));
  568. if (Visited.insert(I->getOperand(0)).second)
  569. DFT.push_back(I->getOperand(0));
  570. continue;
  571. }
  572. // Try to match the current instruction
  573. if (matchInstruction(I, isEQ))
  574. // Match succeed, continue the loop
  575. continue;
  576. }
  577. // One element of the sequence of || (or &&) could not be match as a
  578. // comparison against the same value as the others.
  579. // We allow only one "Extra" case to be checked before the switch
  580. if (!Extra) {
  581. Extra = V;
  582. continue;
  583. }
  584. // Failed to parse a proper sequence, abort now
  585. CompValue = nullptr;
  586. break;
  587. }
  588. }
  589. };
  590. } // end anonymous namespace
  591. static void EraseTerminatorAndDCECond(Instruction *TI,
  592. MemorySSAUpdater *MSSAU = nullptr) {
  593. Instruction *Cond = nullptr;
  594. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  595. Cond = dyn_cast<Instruction>(SI->getCondition());
  596. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  597. if (BI->isConditional())
  598. Cond = dyn_cast<Instruction>(BI->getCondition());
  599. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  600. Cond = dyn_cast<Instruction>(IBI->getAddress());
  601. }
  602. TI->eraseFromParent();
  603. if (Cond)
  604. RecursivelyDeleteTriviallyDeadInstructions(Cond, nullptr, MSSAU);
  605. }
  606. /// Return true if the specified terminator checks
  607. /// to see if a value is equal to constant integer value.
  608. Value *SimplifyCFGOpt::isValueEqualityComparison(Instruction *TI) {
  609. Value *CV = nullptr;
  610. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  611. // Do not permit merging of large switch instructions into their
  612. // predecessors unless there is only one predecessor.
  613. if (!SI->getParent()->hasNPredecessorsOrMore(128 / SI->getNumSuccessors()))
  614. CV = SI->getCondition();
  615. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  616. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  617. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
  618. if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
  619. CV = ICI->getOperand(0);
  620. }
  621. // Unwrap any lossless ptrtoint cast.
  622. if (CV) {
  623. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
  624. Value *Ptr = PTII->getPointerOperand();
  625. if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
  626. CV = Ptr;
  627. }
  628. }
  629. return CV;
  630. }
  631. /// Given a value comparison instruction,
  632. /// decode all of the 'cases' that it represents and return the 'default' block.
  633. BasicBlock *SimplifyCFGOpt::GetValueEqualityComparisonCases(
  634. Instruction *TI, std::vector<ValueEqualityComparisonCase> &Cases) {
  635. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  636. Cases.reserve(SI->getNumCases());
  637. for (auto Case : SI->cases())
  638. Cases.push_back(ValueEqualityComparisonCase(Case.getCaseValue(),
  639. Case.getCaseSuccessor()));
  640. return SI->getDefaultDest();
  641. }
  642. BranchInst *BI = cast<BranchInst>(TI);
  643. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  644. BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
  645. Cases.push_back(ValueEqualityComparisonCase(
  646. GetConstantInt(ICI->getOperand(1), DL), Succ));
  647. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  648. }
  649. /// Given a vector of bb/value pairs, remove any entries
  650. /// in the list that match the specified block.
  651. static void
  652. EliminateBlockCases(BasicBlock *BB,
  653. std::vector<ValueEqualityComparisonCase> &Cases) {
  654. Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
  655. }
  656. /// Return true if there are any keys in C1 that exist in C2 as well.
  657. static bool ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
  658. std::vector<ValueEqualityComparisonCase> &C2) {
  659. std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
  660. // Make V1 be smaller than V2.
  661. if (V1->size() > V2->size())
  662. std::swap(V1, V2);
  663. if (V1->empty())
  664. return false;
  665. if (V1->size() == 1) {
  666. // Just scan V2.
  667. ConstantInt *TheVal = (*V1)[0].Value;
  668. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  669. if (TheVal == (*V2)[i].Value)
  670. return true;
  671. }
  672. // Otherwise, just sort both lists and compare element by element.
  673. array_pod_sort(V1->begin(), V1->end());
  674. array_pod_sort(V2->begin(), V2->end());
  675. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  676. while (i1 != e1 && i2 != e2) {
  677. if ((*V1)[i1].Value == (*V2)[i2].Value)
  678. return true;
  679. if ((*V1)[i1].Value < (*V2)[i2].Value)
  680. ++i1;
  681. else
  682. ++i2;
  683. }
  684. return false;
  685. }
  686. // Set branch weights on SwitchInst. This sets the metadata if there is at
  687. // least one non-zero weight.
  688. static void setBranchWeights(SwitchInst *SI, ArrayRef<uint32_t> Weights) {
  689. // Check that there is at least one non-zero weight. Otherwise, pass
  690. // nullptr to setMetadata which will erase the existing metadata.
  691. MDNode *N = nullptr;
  692. if (llvm::any_of(Weights, [](uint32_t W) { return W != 0; }))
  693. N = MDBuilder(SI->getParent()->getContext()).createBranchWeights(Weights);
  694. SI->setMetadata(LLVMContext::MD_prof, N);
  695. }
  696. // Similar to the above, but for branch and select instructions that take
  697. // exactly 2 weights.
  698. static void setBranchWeights(Instruction *I, uint32_t TrueWeight,
  699. uint32_t FalseWeight) {
  700. assert(isa<BranchInst>(I) || isa<SelectInst>(I));
  701. // Check that there is at least one non-zero weight. Otherwise, pass
  702. // nullptr to setMetadata which will erase the existing metadata.
  703. MDNode *N = nullptr;
  704. if (TrueWeight || FalseWeight)
  705. N = MDBuilder(I->getParent()->getContext())
  706. .createBranchWeights(TrueWeight, FalseWeight);
  707. I->setMetadata(LLVMContext::MD_prof, N);
  708. }
  709. /// If TI is known to be a terminator instruction and its block is known to
  710. /// only have a single predecessor block, check to see if that predecessor is
  711. /// also a value comparison with the same value, and if that comparison
  712. /// determines the outcome of this comparison. If so, simplify TI. This does a
  713. /// very limited form of jump threading.
  714. bool SimplifyCFGOpt::SimplifyEqualityComparisonWithOnlyPredecessor(
  715. Instruction *TI, BasicBlock *Pred, IRBuilder<> &Builder) {
  716. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  717. if (!PredVal)
  718. return false; // Not a value comparison in predecessor.
  719. Value *ThisVal = isValueEqualityComparison(TI);
  720. assert(ThisVal && "This isn't a value comparison!!");
  721. if (ThisVal != PredVal)
  722. return false; // Different predicates.
  723. // TODO: Preserve branch weight metadata, similarly to how
  724. // FoldValueComparisonIntoPredecessors preserves it.
  725. // Find out information about when control will move from Pred to TI's block.
  726. std::vector<ValueEqualityComparisonCase> PredCases;
  727. BasicBlock *PredDef =
  728. GetValueEqualityComparisonCases(Pred->getTerminator(), PredCases);
  729. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  730. // Find information about how control leaves this block.
  731. std::vector<ValueEqualityComparisonCase> ThisCases;
  732. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  733. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  734. // If TI's block is the default block from Pred's comparison, potentially
  735. // simplify TI based on this knowledge.
  736. if (PredDef == TI->getParent()) {
  737. // If we are here, we know that the value is none of those cases listed in
  738. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  739. // can simplify TI.
  740. if (!ValuesOverlap(PredCases, ThisCases))
  741. return false;
  742. if (isa<BranchInst>(TI)) {
  743. // Okay, one of the successors of this condbr is dead. Convert it to a
  744. // uncond br.
  745. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  746. // Insert the new branch.
  747. Instruction *NI = Builder.CreateBr(ThisDef);
  748. (void)NI;
  749. // Remove PHI node entries for the dead edge.
  750. ThisCases[0].Dest->removePredecessor(TI->getParent());
  751. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  752. << "Through successor TI: " << *TI << "Leaving: " << *NI
  753. << "\n");
  754. EraseTerminatorAndDCECond(TI);
  755. return true;
  756. }
  757. SwitchInst *SI = cast<SwitchInst>(TI);
  758. // Okay, TI has cases that are statically dead, prune them away.
  759. SmallPtrSet<Constant *, 16> DeadCases;
  760. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  761. DeadCases.insert(PredCases[i].Value);
  762. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  763. << "Through successor TI: " << *TI);
  764. // Collect branch weights into a vector.
  765. SmallVector<uint32_t, 8> Weights;
  766. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  767. bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
  768. if (HasWeight)
  769. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  770. ++MD_i) {
  771. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  772. Weights.push_back(CI->getValue().getZExtValue());
  773. }
  774. for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
  775. --i;
  776. if (DeadCases.count(i->getCaseValue())) {
  777. if (HasWeight) {
  778. std::swap(Weights[i->getCaseIndex() + 1], Weights.back());
  779. Weights.pop_back();
  780. }
  781. i->getCaseSuccessor()->removePredecessor(TI->getParent());
  782. SI->removeCase(i);
  783. }
  784. }
  785. if (HasWeight && Weights.size() >= 2)
  786. setBranchWeights(SI, Weights);
  787. LLVM_DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  788. return true;
  789. }
  790. // Otherwise, TI's block must correspond to some matched value. Find out
  791. // which value (or set of values) this is.
  792. ConstantInt *TIV = nullptr;
  793. BasicBlock *TIBB = TI->getParent();
  794. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  795. if (PredCases[i].Dest == TIBB) {
  796. if (TIV)
  797. return false; // Cannot handle multiple values coming to this block.
  798. TIV = PredCases[i].Value;
  799. }
  800. assert(TIV && "No edge from pred to succ?");
  801. // Okay, we found the one constant that our value can be if we get into TI's
  802. // BB. Find out which successor will unconditionally be branched to.
  803. BasicBlock *TheRealDest = nullptr;
  804. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  805. if (ThisCases[i].Value == TIV) {
  806. TheRealDest = ThisCases[i].Dest;
  807. break;
  808. }
  809. // If not handled by any explicit cases, it is handled by the default case.
  810. if (!TheRealDest)
  811. TheRealDest = ThisDef;
  812. // Remove PHI node entries for dead edges.
  813. BasicBlock *CheckEdge = TheRealDest;
  814. for (BasicBlock *Succ : successors(TIBB))
  815. if (Succ != CheckEdge)
  816. Succ->removePredecessor(TIBB);
  817. else
  818. CheckEdge = nullptr;
  819. // Insert the new branch.
  820. Instruction *NI = Builder.CreateBr(TheRealDest);
  821. (void)NI;
  822. LLVM_DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  823. << "Through successor TI: " << *TI << "Leaving: " << *NI
  824. << "\n");
  825. EraseTerminatorAndDCECond(TI);
  826. return true;
  827. }
  828. namespace {
  829. /// This class implements a stable ordering of constant
  830. /// integers that does not depend on their address. This is important for
  831. /// applications that sort ConstantInt's to ensure uniqueness.
  832. struct ConstantIntOrdering {
  833. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  834. return LHS->getValue().ult(RHS->getValue());
  835. }
  836. };
  837. } // end anonymous namespace
  838. static int ConstantIntSortPredicate(ConstantInt *const *P1,
  839. ConstantInt *const *P2) {
  840. const ConstantInt *LHS = *P1;
  841. const ConstantInt *RHS = *P2;
  842. if (LHS == RHS)
  843. return 0;
  844. return LHS->getValue().ult(RHS->getValue()) ? 1 : -1;
  845. }
  846. static inline bool HasBranchWeights(const Instruction *I) {
  847. MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
  848. if (ProfMD && ProfMD->getOperand(0))
  849. if (MDString *MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
  850. return MDS->getString().equals("branch_weights");
  851. return false;
  852. }
  853. /// Get Weights of a given terminator, the default weight is at the front
  854. /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
  855. /// metadata.
  856. static void GetBranchWeights(Instruction *TI,
  857. SmallVectorImpl<uint64_t> &Weights) {
  858. MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
  859. assert(MD);
  860. for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
  861. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
  862. Weights.push_back(CI->getValue().getZExtValue());
  863. }
  864. // If TI is a conditional eq, the default case is the false case,
  865. // and the corresponding branch-weight data is at index 2. We swap the
  866. // default weight to be the first entry.
  867. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  868. assert(Weights.size() == 2);
  869. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  870. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  871. std::swap(Weights.front(), Weights.back());
  872. }
  873. }
  874. /// Keep halving the weights until all can fit in uint32_t.
  875. static void FitWeights(MutableArrayRef<uint64_t> Weights) {
  876. uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
  877. if (Max > UINT_MAX) {
  878. unsigned Offset = 32 - countLeadingZeros(Max);
  879. for (uint64_t &I : Weights)
  880. I >>= Offset;
  881. }
  882. }
  883. /// The specified terminator is a value equality comparison instruction
  884. /// (either a switch or a branch on "X == c").
  885. /// See if any of the predecessors of the terminator block are value comparisons
  886. /// on the same value. If so, and if safe to do so, fold them together.
  887. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(Instruction *TI,
  888. IRBuilder<> &Builder) {
  889. BasicBlock *BB = TI->getParent();
  890. Value *CV = isValueEqualityComparison(TI); // CondVal
  891. assert(CV && "Not a comparison?");
  892. bool Changed = false;
  893. SmallVector<BasicBlock *, 16> Preds(pred_begin(BB), pred_end(BB));
  894. while (!Preds.empty()) {
  895. BasicBlock *Pred = Preds.pop_back_val();
  896. // See if the predecessor is a comparison with the same value.
  897. Instruction *PTI = Pred->getTerminator();
  898. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  899. if (PCV == CV && TI != PTI) {
  900. SmallSetVector<BasicBlock*, 4> FailBlocks;
  901. if (!SafeToMergeTerminators(TI, PTI, &FailBlocks)) {
  902. for (auto *Succ : FailBlocks) {
  903. if (!SplitBlockPredecessors(Succ, TI->getParent(), ".fold.split"))
  904. return false;
  905. }
  906. }
  907. // Figure out which 'cases' to copy from SI to PSI.
  908. std::vector<ValueEqualityComparisonCase> BBCases;
  909. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  910. std::vector<ValueEqualityComparisonCase> PredCases;
  911. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  912. // Based on whether the default edge from PTI goes to BB or not, fill in
  913. // PredCases and PredDefault with the new switch cases we would like to
  914. // build.
  915. SmallVector<BasicBlock *, 8> NewSuccessors;
  916. // Update the branch weight metadata along the way
  917. SmallVector<uint64_t, 8> Weights;
  918. bool PredHasWeights = HasBranchWeights(PTI);
  919. bool SuccHasWeights = HasBranchWeights(TI);
  920. if (PredHasWeights) {
  921. GetBranchWeights(PTI, Weights);
  922. // branch-weight metadata is inconsistent here.
  923. if (Weights.size() != 1 + PredCases.size())
  924. PredHasWeights = SuccHasWeights = false;
  925. } else if (SuccHasWeights)
  926. // If there are no predecessor weights but there are successor weights,
  927. // populate Weights with 1, which will later be scaled to the sum of
  928. // successor's weights
  929. Weights.assign(1 + PredCases.size(), 1);
  930. SmallVector<uint64_t, 8> SuccWeights;
  931. if (SuccHasWeights) {
  932. GetBranchWeights(TI, SuccWeights);
  933. // branch-weight metadata is inconsistent here.
  934. if (SuccWeights.size() != 1 + BBCases.size())
  935. PredHasWeights = SuccHasWeights = false;
  936. } else if (PredHasWeights)
  937. SuccWeights.assign(1 + BBCases.size(), 1);
  938. if (PredDefault == BB) {
  939. // If this is the default destination from PTI, only the edges in TI
  940. // that don't occur in PTI, or that branch to BB will be activated.
  941. std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
  942. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  943. if (PredCases[i].Dest != BB)
  944. PTIHandled.insert(PredCases[i].Value);
  945. else {
  946. // The default destination is BB, we don't need explicit targets.
  947. std::swap(PredCases[i], PredCases.back());
  948. if (PredHasWeights || SuccHasWeights) {
  949. // Increase weight for the default case.
  950. Weights[0] += Weights[i + 1];
  951. std::swap(Weights[i + 1], Weights.back());
  952. Weights.pop_back();
  953. }
  954. PredCases.pop_back();
  955. --i;
  956. --e;
  957. }
  958. // Reconstruct the new switch statement we will be building.
  959. if (PredDefault != BBDefault) {
  960. PredDefault->removePredecessor(Pred);
  961. PredDefault = BBDefault;
  962. NewSuccessors.push_back(BBDefault);
  963. }
  964. unsigned CasesFromPred = Weights.size();
  965. uint64_t ValidTotalSuccWeight = 0;
  966. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  967. if (!PTIHandled.count(BBCases[i].Value) &&
  968. BBCases[i].Dest != BBDefault) {
  969. PredCases.push_back(BBCases[i]);
  970. NewSuccessors.push_back(BBCases[i].Dest);
  971. if (SuccHasWeights || PredHasWeights) {
  972. // The default weight is at index 0, so weight for the ith case
  973. // should be at index i+1. Scale the cases from successor by
  974. // PredDefaultWeight (Weights[0]).
  975. Weights.push_back(Weights[0] * SuccWeights[i + 1]);
  976. ValidTotalSuccWeight += SuccWeights[i + 1];
  977. }
  978. }
  979. if (SuccHasWeights || PredHasWeights) {
  980. ValidTotalSuccWeight += SuccWeights[0];
  981. // Scale the cases from predecessor by ValidTotalSuccWeight.
  982. for (unsigned i = 1; i < CasesFromPred; ++i)
  983. Weights[i] *= ValidTotalSuccWeight;
  984. // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
  985. Weights[0] *= SuccWeights[0];
  986. }
  987. } else {
  988. // If this is not the default destination from PSI, only the edges
  989. // in SI that occur in PSI with a destination of BB will be
  990. // activated.
  991. std::set<ConstantInt *, ConstantIntOrdering> PTIHandled;
  992. std::map<ConstantInt *, uint64_t> WeightsForHandled;
  993. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  994. if (PredCases[i].Dest == BB) {
  995. PTIHandled.insert(PredCases[i].Value);
  996. if (PredHasWeights || SuccHasWeights) {
  997. WeightsForHandled[PredCases[i].Value] = Weights[i + 1];
  998. std::swap(Weights[i + 1], Weights.back());
  999. Weights.pop_back();
  1000. }
  1001. std::swap(PredCases[i], PredCases.back());
  1002. PredCases.pop_back();
  1003. --i;
  1004. --e;
  1005. }
  1006. // Okay, now we know which constants were sent to BB from the
  1007. // predecessor. Figure out where they will all go now.
  1008. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  1009. if (PTIHandled.count(BBCases[i].Value)) {
  1010. // If this is one we are capable of getting...
  1011. if (PredHasWeights || SuccHasWeights)
  1012. Weights.push_back(WeightsForHandled[BBCases[i].Value]);
  1013. PredCases.push_back(BBCases[i]);
  1014. NewSuccessors.push_back(BBCases[i].Dest);
  1015. PTIHandled.erase(
  1016. BBCases[i].Value); // This constant is taken care of
  1017. }
  1018. // If there are any constants vectored to BB that TI doesn't handle,
  1019. // they must go to the default destination of TI.
  1020. for (ConstantInt *I : PTIHandled) {
  1021. if (PredHasWeights || SuccHasWeights)
  1022. Weights.push_back(WeightsForHandled[I]);
  1023. PredCases.push_back(ValueEqualityComparisonCase(I, BBDefault));
  1024. NewSuccessors.push_back(BBDefault);
  1025. }
  1026. }
  1027. // Okay, at this point, we know which new successor Pred will get. Make
  1028. // sure we update the number of entries in the PHI nodes for these
  1029. // successors.
  1030. for (BasicBlock *NewSuccessor : NewSuccessors)
  1031. AddPredecessorToBlock(NewSuccessor, Pred, BB);
  1032. Builder.SetInsertPoint(PTI);
  1033. // Convert pointer to int before we switch.
  1034. if (CV->getType()->isPointerTy()) {
  1035. CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
  1036. "magicptr");
  1037. }
  1038. // Now that the successors are updated, create the new Switch instruction.
  1039. SwitchInst *NewSI =
  1040. Builder.CreateSwitch(CV, PredDefault, PredCases.size());
  1041. NewSI->setDebugLoc(PTI->getDebugLoc());
  1042. for (ValueEqualityComparisonCase &V : PredCases)
  1043. NewSI->addCase(V.Value, V.Dest);
  1044. if (PredHasWeights || SuccHasWeights) {
  1045. // Halve the weights if any of them cannot fit in an uint32_t
  1046. FitWeights(Weights);
  1047. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  1048. setBranchWeights(NewSI, MDWeights);
  1049. }
  1050. EraseTerminatorAndDCECond(PTI);
  1051. // Okay, last check. If BB is still a successor of PSI, then we must
  1052. // have an infinite loop case. If so, add an infinitely looping block
  1053. // to handle the case to preserve the behavior of the code.
  1054. BasicBlock *InfLoopBlock = nullptr;
  1055. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  1056. if (NewSI->getSuccessor(i) == BB) {
  1057. if (!InfLoopBlock) {
  1058. // Insert it at the end of the function, because it's either code,
  1059. // or it won't matter if it's hot. :)
  1060. InfLoopBlock = BasicBlock::Create(BB->getContext(), "infloop",
  1061. BB->getParent());
  1062. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  1063. }
  1064. NewSI->setSuccessor(i, InfLoopBlock);
  1065. }
  1066. Changed = true;
  1067. }
  1068. }
  1069. return Changed;
  1070. }
  1071. // If we would need to insert a select that uses the value of this invoke
  1072. // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
  1073. // can't hoist the invoke, as there is nowhere to put the select in this case.
  1074. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  1075. Instruction *I1, Instruction *I2) {
  1076. for (BasicBlock *Succ : successors(BB1)) {
  1077. for (const PHINode &PN : Succ->phis()) {
  1078. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1079. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1080. if (BB1V != BB2V && (BB1V == I1 || BB2V == I2)) {
  1081. return false;
  1082. }
  1083. }
  1084. }
  1085. return true;
  1086. }
  1087. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
  1088. /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
  1089. /// in the two blocks up into the branch block. The caller of this function
  1090. /// guarantees that BI's block dominates BB1 and BB2.
  1091. static bool HoistThenElseCodeToIf(BranchInst *BI,
  1092. const TargetTransformInfo &TTI) {
  1093. // This does very trivial matching, with limited scanning, to find identical
  1094. // instructions in the two blocks. In particular, we don't want to get into
  1095. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  1096. // such, we currently just scan for obviously identical instructions in an
  1097. // identical order.
  1098. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  1099. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  1100. BasicBlock::iterator BB1_Itr = BB1->begin();
  1101. BasicBlock::iterator BB2_Itr = BB2->begin();
  1102. Instruction *I1 = &*BB1_Itr++, *I2 = &*BB2_Itr++;
  1103. // Skip debug info if it is not identical.
  1104. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  1105. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  1106. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  1107. while (isa<DbgInfoIntrinsic>(I1))
  1108. I1 = &*BB1_Itr++;
  1109. while (isa<DbgInfoIntrinsic>(I2))
  1110. I2 = &*BB2_Itr++;
  1111. }
  1112. // FIXME: Can we define a safety predicate for CallBr?
  1113. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  1114. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)) ||
  1115. isa<CallBrInst>(I1))
  1116. return false;
  1117. BasicBlock *BIParent = BI->getParent();
  1118. bool Changed = false;
  1119. do {
  1120. // If we are hoisting the terminator instruction, don't move one (making a
  1121. // broken BB), instead clone it, and remove BI.
  1122. if (I1->isTerminator())
  1123. goto HoistTerminator;
  1124. // If we're going to hoist a call, make sure that the two instructions we're
  1125. // commoning/hoisting are both marked with musttail, or neither of them is
  1126. // marked as such. Otherwise, we might end up in a situation where we hoist
  1127. // from a block where the terminator is a `ret` to a block where the terminator
  1128. // is a `br`, and `musttail` calls expect to be followed by a return.
  1129. auto *C1 = dyn_cast<CallInst>(I1);
  1130. auto *C2 = dyn_cast<CallInst>(I2);
  1131. if (C1 && C2)
  1132. if (C1->isMustTailCall() != C2->isMustTailCall())
  1133. return Changed;
  1134. if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
  1135. return Changed;
  1136. if (isa<DbgInfoIntrinsic>(I1) || isa<DbgInfoIntrinsic>(I2)) {
  1137. assert (isa<DbgInfoIntrinsic>(I1) && isa<DbgInfoIntrinsic>(I2));
  1138. // The debug location is an integral part of a debug info intrinsic
  1139. // and can't be separated from it or replaced. Instead of attempting
  1140. // to merge locations, simply hoist both copies of the intrinsic.
  1141. BIParent->getInstList().splice(BI->getIterator(),
  1142. BB1->getInstList(), I1);
  1143. BIParent->getInstList().splice(BI->getIterator(),
  1144. BB2->getInstList(), I2);
  1145. Changed = true;
  1146. } else {
  1147. // For a normal instruction, we just move one to right before the branch,
  1148. // then replace all uses of the other with the first. Finally, we remove
  1149. // the now redundant second instruction.
  1150. BIParent->getInstList().splice(BI->getIterator(),
  1151. BB1->getInstList(), I1);
  1152. if (!I2->use_empty())
  1153. I2->replaceAllUsesWith(I1);
  1154. I1->andIRFlags(I2);
  1155. unsigned KnownIDs[] = {LLVMContext::MD_tbaa,
  1156. LLVMContext::MD_range,
  1157. LLVMContext::MD_fpmath,
  1158. LLVMContext::MD_invariant_load,
  1159. LLVMContext::MD_nonnull,
  1160. LLVMContext::MD_invariant_group,
  1161. LLVMContext::MD_align,
  1162. LLVMContext::MD_dereferenceable,
  1163. LLVMContext::MD_dereferenceable_or_null,
  1164. LLVMContext::MD_mem_parallel_loop_access,
  1165. LLVMContext::MD_access_group};
  1166. combineMetadata(I1, I2, KnownIDs, true);
  1167. // I1 and I2 are being combined into a single instruction. Its debug
  1168. // location is the merged locations of the original instructions.
  1169. I1->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
  1170. I2->eraseFromParent();
  1171. Changed = true;
  1172. }
  1173. I1 = &*BB1_Itr++;
  1174. I2 = &*BB2_Itr++;
  1175. // Skip debug info if it is not identical.
  1176. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  1177. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  1178. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  1179. while (isa<DbgInfoIntrinsic>(I1))
  1180. I1 = &*BB1_Itr++;
  1181. while (isa<DbgInfoIntrinsic>(I2))
  1182. I2 = &*BB2_Itr++;
  1183. }
  1184. } while (I1->isIdenticalToWhenDefined(I2));
  1185. return true;
  1186. HoistTerminator:
  1187. // It may not be possible to hoist an invoke.
  1188. // FIXME: Can we define a safety predicate for CallBr?
  1189. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  1190. return Changed;
  1191. // TODO: callbr hoisting currently disabled pending further study.
  1192. if (isa<CallBrInst>(I1))
  1193. return Changed;
  1194. for (BasicBlock *Succ : successors(BB1)) {
  1195. for (PHINode &PN : Succ->phis()) {
  1196. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1197. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1198. if (BB1V == BB2V)
  1199. continue;
  1200. // Check for passingValueIsAlwaysUndefined here because we would rather
  1201. // eliminate undefined control flow then converting it to a select.
  1202. if (passingValueIsAlwaysUndefined(BB1V, &PN) ||
  1203. passingValueIsAlwaysUndefined(BB2V, &PN))
  1204. return Changed;
  1205. if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
  1206. return Changed;
  1207. if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
  1208. return Changed;
  1209. }
  1210. }
  1211. // Okay, it is safe to hoist the terminator.
  1212. Instruction *NT = I1->clone();
  1213. BIParent->getInstList().insert(BI->getIterator(), NT);
  1214. if (!NT->getType()->isVoidTy()) {
  1215. I1->replaceAllUsesWith(NT);
  1216. I2->replaceAllUsesWith(NT);
  1217. NT->takeName(I1);
  1218. }
  1219. // Ensure terminator gets a debug location, even an unknown one, in case
  1220. // it involves inlinable calls.
  1221. NT->applyMergedLocation(I1->getDebugLoc(), I2->getDebugLoc());
  1222. // PHIs created below will adopt NT's merged DebugLoc.
  1223. IRBuilder<NoFolder> Builder(NT);
  1224. // Hoisting one of the terminators from our successor is a great thing.
  1225. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  1226. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  1227. // nodes, so we insert select instruction to compute the final result.
  1228. std::map<std::pair<Value *, Value *>, SelectInst *> InsertedSelects;
  1229. for (BasicBlock *Succ : successors(BB1)) {
  1230. for (PHINode &PN : Succ->phis()) {
  1231. Value *BB1V = PN.getIncomingValueForBlock(BB1);
  1232. Value *BB2V = PN.getIncomingValueForBlock(BB2);
  1233. if (BB1V == BB2V)
  1234. continue;
  1235. // These values do not agree. Insert a select instruction before NT
  1236. // that determines the right value.
  1237. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  1238. if (!SI)
  1239. SI = cast<SelectInst>(
  1240. Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  1241. BB1V->getName() + "." + BB2V->getName(), BI));
  1242. // Make the PHI node use the select for all incoming values for BB1/BB2
  1243. for (unsigned i = 0, e = PN.getNumIncomingValues(); i != e; ++i)
  1244. if (PN.getIncomingBlock(i) == BB1 || PN.getIncomingBlock(i) == BB2)
  1245. PN.setIncomingValue(i, SI);
  1246. }
  1247. }
  1248. // Update any PHI nodes in our new successors.
  1249. for (BasicBlock *Succ : successors(BB1))
  1250. AddPredecessorToBlock(Succ, BIParent, BB1);
  1251. EraseTerminatorAndDCECond(BI);
  1252. return true;
  1253. }
  1254. // All instructions in Insts belong to different blocks that all unconditionally
  1255. // branch to a common successor. Analyze each instruction and return true if it
  1256. // would be possible to sink them into their successor, creating one common
  1257. // instruction instead. For every value that would be required to be provided by
  1258. // PHI node (because an operand varies in each input block), add to PHIOperands.
  1259. static bool canSinkInstructions(
  1260. ArrayRef<Instruction *> Insts,
  1261. DenseMap<Instruction *, SmallVector<Value *, 4>> &PHIOperands) {
  1262. // Prune out obviously bad instructions to move. Any non-store instruction
  1263. // must have exactly one use, and we check later that use is by a single,
  1264. // common PHI instruction in the successor.
  1265. for (auto *I : Insts) {
  1266. // These instructions may change or break semantics if moved.
  1267. if (isa<PHINode>(I) || I->isEHPad() || isa<AllocaInst>(I) ||
  1268. I->getType()->isTokenTy())
  1269. return false;
  1270. // Conservatively return false if I is an inline-asm instruction. Sinking
  1271. // and merging inline-asm instructions can potentially create arguments
  1272. // that cannot satisfy the inline-asm constraints.
  1273. if (const auto *C = dyn_cast<CallBase>(I))
  1274. if (C->isInlineAsm())
  1275. return false;
  1276. // Everything must have only one use too, apart from stores which
  1277. // have no uses.
  1278. if (!isa<StoreInst>(I) && !I->hasOneUse())
  1279. return false;
  1280. }
  1281. const Instruction *I0 = Insts.front();
  1282. for (auto *I : Insts)
  1283. if (!I->isSameOperationAs(I0))
  1284. return false;
  1285. // All instructions in Insts are known to be the same opcode. If they aren't
  1286. // stores, check the only user of each is a PHI or in the same block as the
  1287. // instruction, because if a user is in the same block as an instruction
  1288. // we're contemplating sinking, it must already be determined to be sinkable.
  1289. if (!isa<StoreInst>(I0)) {
  1290. auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
  1291. auto *Succ = I0->getParent()->getTerminator()->getSuccessor(0);
  1292. if (!all_of(Insts, [&PNUse,&Succ](const Instruction *I) -> bool {
  1293. auto *U = cast<Instruction>(*I->user_begin());
  1294. return (PNUse &&
  1295. PNUse->getParent() == Succ &&
  1296. PNUse->getIncomingValueForBlock(I->getParent()) == I) ||
  1297. U->getParent() == I->getParent();
  1298. }))
  1299. return false;
  1300. }
  1301. // Because SROA can't handle speculating stores of selects, try not
  1302. // to sink loads or stores of allocas when we'd have to create a PHI for
  1303. // the address operand. Also, because it is likely that loads or stores
  1304. // of allocas will disappear when Mem2Reg/SROA is run, don't sink them.
  1305. // This can cause code churn which can have unintended consequences down
  1306. // the line - see https://llvm.org/bugs/show_bug.cgi?id=30244.
  1307. // FIXME: This is a workaround for a deficiency in SROA - see
  1308. // https://llvm.org/bugs/show_bug.cgi?id=30188
  1309. if (isa<StoreInst>(I0) && any_of(Insts, [](const Instruction *I) {
  1310. return isa<AllocaInst>(I->getOperand(1));
  1311. }))
  1312. return false;
  1313. if (isa<LoadInst>(I0) && any_of(Insts, [](const Instruction *I) {
  1314. return isa<AllocaInst>(I->getOperand(0));
  1315. }))
  1316. return false;
  1317. for (unsigned OI = 0, OE = I0->getNumOperands(); OI != OE; ++OI) {
  1318. if (I0->getOperand(OI)->getType()->isTokenTy())
  1319. // Don't touch any operand of token type.
  1320. return false;
  1321. auto SameAsI0 = [&I0, OI](const Instruction *I) {
  1322. assert(I->getNumOperands() == I0->getNumOperands());
  1323. return I->getOperand(OI) == I0->getOperand(OI);
  1324. };
  1325. if (!all_of(Insts, SameAsI0)) {
  1326. if (!canReplaceOperandWithVariable(I0, OI))
  1327. // We can't create a PHI from this GEP.
  1328. return false;
  1329. // Don't create indirect calls! The called value is the final operand.
  1330. if (isa<CallBase>(I0) && OI == OE - 1) {
  1331. // FIXME: if the call was *already* indirect, we should do this.
  1332. return false;
  1333. }
  1334. for (auto *I : Insts)
  1335. PHIOperands[I].push_back(I->getOperand(OI));
  1336. }
  1337. }
  1338. return true;
  1339. }
  1340. // Assuming canSinkLastInstruction(Blocks) has returned true, sink the last
  1341. // instruction of every block in Blocks to their common successor, commoning
  1342. // into one instruction.
  1343. static bool sinkLastInstruction(ArrayRef<BasicBlock*> Blocks) {
  1344. auto *BBEnd = Blocks[0]->getTerminator()->getSuccessor(0);
  1345. // canSinkLastInstruction returning true guarantees that every block has at
  1346. // least one non-terminator instruction.
  1347. SmallVector<Instruction*,4> Insts;
  1348. for (auto *BB : Blocks) {
  1349. Instruction *I = BB->getTerminator();
  1350. do {
  1351. I = I->getPrevNode();
  1352. } while (isa<DbgInfoIntrinsic>(I) && I != &BB->front());
  1353. if (!isa<DbgInfoIntrinsic>(I))
  1354. Insts.push_back(I);
  1355. }
  1356. // The only checking we need to do now is that all users of all instructions
  1357. // are the same PHI node. canSinkLastInstruction should have checked this but
  1358. // it is slightly over-aggressive - it gets confused by commutative instructions
  1359. // so double-check it here.
  1360. Instruction *I0 = Insts.front();
  1361. if (!isa<StoreInst>(I0)) {
  1362. auto *PNUse = dyn_cast<PHINode>(*I0->user_begin());
  1363. if (!all_of(Insts, [&PNUse](const Instruction *I) -> bool {
  1364. auto *U = cast<Instruction>(*I->user_begin());
  1365. return U == PNUse;
  1366. }))
  1367. return false;
  1368. }
  1369. // We don't need to do any more checking here; canSinkLastInstruction should
  1370. // have done it all for us.
  1371. SmallVector<Value*, 4> NewOperands;
  1372. for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O) {
  1373. // This check is different to that in canSinkLastInstruction. There, we
  1374. // cared about the global view once simplifycfg (and instcombine) have
  1375. // completed - it takes into account PHIs that become trivially
  1376. // simplifiable. However here we need a more local view; if an operand
  1377. // differs we create a PHI and rely on instcombine to clean up the very
  1378. // small mess we may make.
  1379. bool NeedPHI = any_of(Insts, [&I0, O](const Instruction *I) {
  1380. return I->getOperand(O) != I0->getOperand(O);
  1381. });
  1382. if (!NeedPHI) {
  1383. NewOperands.push_back(I0->getOperand(O));
  1384. continue;
  1385. }
  1386. // Create a new PHI in the successor block and populate it.
  1387. auto *Op = I0->getOperand(O);
  1388. assert(!Op->getType()->isTokenTy() && "Can't PHI tokens!");
  1389. auto *PN = PHINode::Create(Op->getType(), Insts.size(),
  1390. Op->getName() + ".sink", &BBEnd->front());
  1391. for (auto *I : Insts)
  1392. PN->addIncoming(I->getOperand(O), I->getParent());
  1393. NewOperands.push_back(PN);
  1394. }
  1395. // Arbitrarily use I0 as the new "common" instruction; remap its operands
  1396. // and move it to the start of the successor block.
  1397. for (unsigned O = 0, E = I0->getNumOperands(); O != E; ++O)
  1398. I0->getOperandUse(O).set(NewOperands[O]);
  1399. I0->moveBefore(&*BBEnd->getFirstInsertionPt());
  1400. // Update metadata and IR flags, and merge debug locations.
  1401. for (auto *I : Insts)
  1402. if (I != I0) {
  1403. // The debug location for the "common" instruction is the merged locations
  1404. // of all the commoned instructions. We start with the original location
  1405. // of the "common" instruction and iteratively merge each location in the
  1406. // loop below.
  1407. // This is an N-way merge, which will be inefficient if I0 is a CallInst.
  1408. // However, as N-way merge for CallInst is rare, so we use simplified API
  1409. // instead of using complex API for N-way merge.
  1410. I0->applyMergedLocation(I0->getDebugLoc(), I->getDebugLoc());
  1411. combineMetadataForCSE(I0, I, true);
  1412. I0->andIRFlags(I);
  1413. }
  1414. if (!isa<StoreInst>(I0)) {
  1415. // canSinkLastInstruction checked that all instructions were used by
  1416. // one and only one PHI node. Find that now, RAUW it to our common
  1417. // instruction and nuke it.
  1418. assert(I0->hasOneUse());
  1419. auto *PN = cast<PHINode>(*I0->user_begin());
  1420. PN->replaceAllUsesWith(I0);
  1421. PN->eraseFromParent();
  1422. }
  1423. // Finally nuke all instructions apart from the common instruction.
  1424. for (auto *I : Insts)
  1425. if (I != I0)
  1426. I->eraseFromParent();
  1427. return true;
  1428. }
  1429. namespace {
  1430. // LockstepReverseIterator - Iterates through instructions
  1431. // in a set of blocks in reverse order from the first non-terminator.
  1432. // For example (assume all blocks have size n):
  1433. // LockstepReverseIterator I([B1, B2, B3]);
  1434. // *I-- = [B1[n], B2[n], B3[n]];
  1435. // *I-- = [B1[n-1], B2[n-1], B3[n-1]];
  1436. // *I-- = [B1[n-2], B2[n-2], B3[n-2]];
  1437. // ...
  1438. class LockstepReverseIterator {
  1439. ArrayRef<BasicBlock*> Blocks;
  1440. SmallVector<Instruction*,4> Insts;
  1441. bool Fail;
  1442. public:
  1443. LockstepReverseIterator(ArrayRef<BasicBlock*> Blocks) : Blocks(Blocks) {
  1444. reset();
  1445. }
  1446. void reset() {
  1447. Fail = false;
  1448. Insts.clear();
  1449. for (auto *BB : Blocks) {
  1450. Instruction *Inst = BB->getTerminator();
  1451. for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
  1452. Inst = Inst->getPrevNode();
  1453. if (!Inst) {
  1454. // Block wasn't big enough.
  1455. Fail = true;
  1456. return;
  1457. }
  1458. Insts.push_back(Inst);
  1459. }
  1460. }
  1461. bool isValid() const {
  1462. return !Fail;
  1463. }
  1464. void operator--() {
  1465. if (Fail)
  1466. return;
  1467. for (auto *&Inst : Insts) {
  1468. for (Inst = Inst->getPrevNode(); Inst && isa<DbgInfoIntrinsic>(Inst);)
  1469. Inst = Inst->getPrevNode();
  1470. // Already at beginning of block.
  1471. if (!Inst) {
  1472. Fail = true;
  1473. return;
  1474. }
  1475. }
  1476. }
  1477. ArrayRef<Instruction*> operator * () const {
  1478. return Insts;
  1479. }
  1480. };
  1481. } // end anonymous namespace
  1482. /// Check whether BB's predecessors end with unconditional branches. If it is
  1483. /// true, sink any common code from the predecessors to BB.
  1484. /// We also allow one predecessor to end with conditional branch (but no more
  1485. /// than one).
  1486. static bool SinkCommonCodeFromPredecessors(BasicBlock *BB) {
  1487. // We support two situations:
  1488. // (1) all incoming arcs are unconditional
  1489. // (2) one incoming arc is conditional
  1490. //
  1491. // (2) is very common in switch defaults and
  1492. // else-if patterns;
  1493. //
  1494. // if (a) f(1);
  1495. // else if (b) f(2);
  1496. //
  1497. // produces:
  1498. //
  1499. // [if]
  1500. // / \
  1501. // [f(1)] [if]
  1502. // | | \
  1503. // | | |
  1504. // | [f(2)]|
  1505. // \ | /
  1506. // [ end ]
  1507. //
  1508. // [end] has two unconditional predecessor arcs and one conditional. The
  1509. // conditional refers to the implicit empty 'else' arc. This conditional
  1510. // arc can also be caused by an empty default block in a switch.
  1511. //
  1512. // In this case, we attempt to sink code from all *unconditional* arcs.
  1513. // If we can sink instructions from these arcs (determined during the scan
  1514. // phase below) we insert a common successor for all unconditional arcs and
  1515. // connect that to [end], to enable sinking:
  1516. //
  1517. // [if]
  1518. // / \
  1519. // [x(1)] [if]
  1520. // | | \
  1521. // | | \
  1522. // | [x(2)] |
  1523. // \ / |
  1524. // [sink.split] |
  1525. // \ /
  1526. // [ end ]
  1527. //
  1528. SmallVector<BasicBlock*,4> UnconditionalPreds;
  1529. Instruction *Cond = nullptr;
  1530. for (auto *B : predecessors(BB)) {
  1531. auto *T = B->getTerminator();
  1532. if (isa<BranchInst>(T) && cast<BranchInst>(T)->isUnconditional())
  1533. UnconditionalPreds.push_back(B);
  1534. else if ((isa<BranchInst>(T) || isa<SwitchInst>(T)) && !Cond)
  1535. Cond = T;
  1536. else
  1537. return false;
  1538. }
  1539. if (UnconditionalPreds.size() < 2)
  1540. return false;
  1541. bool Changed = false;
  1542. // We take a two-step approach to tail sinking. First we scan from the end of
  1543. // each block upwards in lockstep. If the n'th instruction from the end of each
  1544. // block can be sunk, those instructions are added to ValuesToSink and we
  1545. // carry on. If we can sink an instruction but need to PHI-merge some operands
  1546. // (because they're not identical in each instruction) we add these to
  1547. // PHIOperands.
  1548. unsigned ScanIdx = 0;
  1549. SmallPtrSet<Value*,4> InstructionsToSink;
  1550. DenseMap<Instruction*, SmallVector<Value*,4>> PHIOperands;
  1551. LockstepReverseIterator LRI(UnconditionalPreds);
  1552. while (LRI.isValid() &&
  1553. canSinkInstructions(*LRI, PHIOperands)) {
  1554. LLVM_DEBUG(dbgs() << "SINK: instruction can be sunk: " << *(*LRI)[0]
  1555. << "\n");
  1556. InstructionsToSink.insert((*LRI).begin(), (*LRI).end());
  1557. ++ScanIdx;
  1558. --LRI;
  1559. }
  1560. auto ProfitableToSinkInstruction = [&](LockstepReverseIterator &LRI) {
  1561. unsigned NumPHIdValues = 0;
  1562. for (auto *I : *LRI)
  1563. for (auto *V : PHIOperands[I])
  1564. if (InstructionsToSink.count(V) == 0)
  1565. ++NumPHIdValues;
  1566. LLVM_DEBUG(dbgs() << "SINK: #phid values: " << NumPHIdValues << "\n");
  1567. unsigned NumPHIInsts = NumPHIdValues / UnconditionalPreds.size();
  1568. if ((NumPHIdValues % UnconditionalPreds.size()) != 0)
  1569. NumPHIInsts++;
  1570. return NumPHIInsts <= 1;
  1571. };
  1572. if (ScanIdx > 0 && Cond) {
  1573. // Check if we would actually sink anything first! This mutates the CFG and
  1574. // adds an extra block. The goal in doing this is to allow instructions that
  1575. // couldn't be sunk before to be sunk - obviously, speculatable instructions
  1576. // (such as trunc, add) can be sunk and predicated already. So we check that
  1577. // we're going to sink at least one non-speculatable instruction.
  1578. LRI.reset();
  1579. unsigned Idx = 0;
  1580. bool Profitable = false;
  1581. while (ProfitableToSinkInstruction(LRI) && Idx < ScanIdx) {
  1582. if (!isSafeToSpeculativelyExecute((*LRI)[0])) {
  1583. Profitable = true;
  1584. break;
  1585. }
  1586. --LRI;
  1587. ++Idx;
  1588. }
  1589. if (!Profitable)
  1590. return false;
  1591. LLVM_DEBUG(dbgs() << "SINK: Splitting edge\n");
  1592. // We have a conditional edge and we're going to sink some instructions.
  1593. // Insert a new block postdominating all blocks we're going to sink from.
  1594. if (!SplitBlockPredecessors(BB, UnconditionalPreds, ".sink.split"))
  1595. // Edges couldn't be split.
  1596. return false;
  1597. Changed = true;
  1598. }
  1599. // Now that we've analyzed all potential sinking candidates, perform the
  1600. // actual sink. We iteratively sink the last non-terminator of the source
  1601. // blocks into their common successor unless doing so would require too
  1602. // many PHI instructions to be generated (currently only one PHI is allowed
  1603. // per sunk instruction).
  1604. //
  1605. // We can use InstructionsToSink to discount values needing PHI-merging that will
  1606. // actually be sunk in a later iteration. This allows us to be more
  1607. // aggressive in what we sink. This does allow a false positive where we
  1608. // sink presuming a later value will also be sunk, but stop half way through
  1609. // and never actually sink it which means we produce more PHIs than intended.
  1610. // This is unlikely in practice though.
  1611. for (unsigned SinkIdx = 0; SinkIdx != ScanIdx; ++SinkIdx) {
  1612. LLVM_DEBUG(dbgs() << "SINK: Sink: "
  1613. << *UnconditionalPreds[0]->getTerminator()->getPrevNode()
  1614. << "\n");
  1615. // Because we've sunk every instruction in turn, the current instruction to
  1616. // sink is always at index 0.
  1617. LRI.reset();
  1618. if (!ProfitableToSinkInstruction(LRI)) {
  1619. // Too many PHIs would be created.
  1620. LLVM_DEBUG(
  1621. dbgs() << "SINK: stopping here, too many PHIs would be created!\n");
  1622. break;
  1623. }
  1624. if (!sinkLastInstruction(UnconditionalPreds))
  1625. return Changed;
  1626. NumSinkCommons++;
  1627. Changed = true;
  1628. }
  1629. return Changed;
  1630. }
  1631. /// Determine if we can hoist sink a sole store instruction out of a
  1632. /// conditional block.
  1633. ///
  1634. /// We are looking for code like the following:
  1635. /// BrBB:
  1636. /// store i32 %add, i32* %arrayidx2
  1637. /// ... // No other stores or function calls (we could be calling a memory
  1638. /// ... // function).
  1639. /// %cmp = icmp ult %x, %y
  1640. /// br i1 %cmp, label %EndBB, label %ThenBB
  1641. /// ThenBB:
  1642. /// store i32 %add5, i32* %arrayidx2
  1643. /// br label EndBB
  1644. /// EndBB:
  1645. /// ...
  1646. /// We are going to transform this into:
  1647. /// BrBB:
  1648. /// store i32 %add, i32* %arrayidx2
  1649. /// ... //
  1650. /// %cmp = icmp ult %x, %y
  1651. /// %add.add5 = select i1 %cmp, i32 %add, %add5
  1652. /// store i32 %add.add5, i32* %arrayidx2
  1653. /// ...
  1654. ///
  1655. /// \return The pointer to the value of the previous store if the store can be
  1656. /// hoisted into the predecessor block. 0 otherwise.
  1657. static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
  1658. BasicBlock *StoreBB, BasicBlock *EndBB) {
  1659. StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
  1660. if (!StoreToHoist)
  1661. return nullptr;
  1662. // Volatile or atomic.
  1663. if (!StoreToHoist->isSimple())
  1664. return nullptr;
  1665. Value *StorePtr = StoreToHoist->getPointerOperand();
  1666. // Look for a store to the same pointer in BrBB.
  1667. unsigned MaxNumInstToLookAt = 9;
  1668. for (Instruction &CurI : reverse(BrBB->instructionsWithoutDebug())) {
  1669. if (!MaxNumInstToLookAt)
  1670. break;
  1671. --MaxNumInstToLookAt;
  1672. // Could be calling an instruction that affects memory like free().
  1673. if (CurI.mayHaveSideEffects() && !isa<StoreInst>(CurI))
  1674. return nullptr;
  1675. if (auto *SI = dyn_cast<StoreInst>(&CurI)) {
  1676. // Found the previous store make sure it stores to the same location.
  1677. if (SI->getPointerOperand() == StorePtr)
  1678. // Found the previous store, return its value operand.
  1679. return SI->getValueOperand();
  1680. return nullptr; // Unknown store.
  1681. }
  1682. }
  1683. return nullptr;
  1684. }
  1685. /// Speculate a conditional basic block flattening the CFG.
  1686. ///
  1687. /// Note that this is a very risky transform currently. Speculating
  1688. /// instructions like this is most often not desirable. Instead, there is an MI
  1689. /// pass which can do it with full awareness of the resource constraints.
  1690. /// However, some cases are "obvious" and we should do directly. An example of
  1691. /// this is speculating a single, reasonably cheap instruction.
  1692. ///
  1693. /// There is only one distinct advantage to flattening the CFG at the IR level:
  1694. /// it makes very common but simplistic optimizations such as are common in
  1695. /// instcombine and the DAG combiner more powerful by removing CFG edges and
  1696. /// modeling their effects with easier to reason about SSA value graphs.
  1697. ///
  1698. ///
  1699. /// An illustration of this transform is turning this IR:
  1700. /// \code
  1701. /// BB:
  1702. /// %cmp = icmp ult %x, %y
  1703. /// br i1 %cmp, label %EndBB, label %ThenBB
  1704. /// ThenBB:
  1705. /// %sub = sub %x, %y
  1706. /// br label BB2
  1707. /// EndBB:
  1708. /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
  1709. /// ...
  1710. /// \endcode
  1711. ///
  1712. /// Into this IR:
  1713. /// \code
  1714. /// BB:
  1715. /// %cmp = icmp ult %x, %y
  1716. /// %sub = sub %x, %y
  1717. /// %cond = select i1 %cmp, 0, %sub
  1718. /// ...
  1719. /// \endcode
  1720. ///
  1721. /// \returns true if the conditional block is removed.
  1722. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
  1723. const TargetTransformInfo &TTI) {
  1724. // Be conservative for now. FP select instruction can often be expensive.
  1725. Value *BrCond = BI->getCondition();
  1726. if (isa<FCmpInst>(BrCond))
  1727. return false;
  1728. BasicBlock *BB = BI->getParent();
  1729. BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
  1730. // If ThenBB is actually on the false edge of the conditional branch, remember
  1731. // to swap the select operands later.
  1732. bool Invert = false;
  1733. if (ThenBB != BI->getSuccessor(0)) {
  1734. assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
  1735. Invert = true;
  1736. }
  1737. assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
  1738. // Keep a count of how many times instructions are used within ThenBB when
  1739. // they are candidates for sinking into ThenBB. Specifically:
  1740. // - They are defined in BB, and
  1741. // - They have no side effects, and
  1742. // - All of their uses are in ThenBB.
  1743. SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
  1744. SmallVector<Instruction *, 4> SpeculatedDbgIntrinsics;
  1745. unsigned SpeculationCost = 0;
  1746. Value *SpeculatedStoreValue = nullptr;
  1747. StoreInst *SpeculatedStore = nullptr;
  1748. for (BasicBlock::iterator BBI = ThenBB->begin(),
  1749. BBE = std::prev(ThenBB->end());
  1750. BBI != BBE; ++BBI) {
  1751. Instruction *I = &*BBI;
  1752. // Skip debug info.
  1753. if (isa<DbgInfoIntrinsic>(I)) {
  1754. SpeculatedDbgIntrinsics.push_back(I);
  1755. continue;
  1756. }
  1757. // Only speculatively execute a single instruction (not counting the
  1758. // terminator) for now.
  1759. ++SpeculationCost;
  1760. if (SpeculationCost > 1)
  1761. return false;
  1762. // Don't hoist the instruction if it's unsafe or expensive.
  1763. if (!isSafeToSpeculativelyExecute(I) &&
  1764. !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
  1765. I, BB, ThenBB, EndBB))))
  1766. return false;
  1767. if (!SpeculatedStoreValue &&
  1768. ComputeSpeculationCost(I, TTI) >
  1769. PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
  1770. return false;
  1771. // Store the store speculation candidate.
  1772. if (SpeculatedStoreValue)
  1773. SpeculatedStore = cast<StoreInst>(I);
  1774. // Do not hoist the instruction if any of its operands are defined but not
  1775. // used in BB. The transformation will prevent the operand from
  1776. // being sunk into the use block.
  1777. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i) {
  1778. Instruction *OpI = dyn_cast<Instruction>(*i);
  1779. if (!OpI || OpI->getParent() != BB || OpI->mayHaveSideEffects())
  1780. continue; // Not a candidate for sinking.
  1781. ++SinkCandidateUseCounts[OpI];
  1782. }
  1783. }
  1784. // Consider any sink candidates which are only used in ThenBB as costs for
  1785. // speculation. Note, while we iterate over a DenseMap here, we are summing
  1786. // and so iteration order isn't significant.
  1787. for (SmallDenseMap<Instruction *, unsigned, 4>::iterator
  1788. I = SinkCandidateUseCounts.begin(),
  1789. E = SinkCandidateUseCounts.end();
  1790. I != E; ++I)
  1791. if (I->first->hasNUses(I->second)) {
  1792. ++SpeculationCost;
  1793. if (SpeculationCost > 1)
  1794. return false;
  1795. }
  1796. // Check that the PHI nodes can be converted to selects.
  1797. bool HaveRewritablePHIs = false;
  1798. for (PHINode &PN : EndBB->phis()) {
  1799. Value *OrigV = PN.getIncomingValueForBlock(BB);
  1800. Value *ThenV = PN.getIncomingValueForBlock(ThenBB);
  1801. // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
  1802. // Skip PHIs which are trivial.
  1803. if (ThenV == OrigV)
  1804. continue;
  1805. // Don't convert to selects if we could remove undefined behavior instead.
  1806. if (passingValueIsAlwaysUndefined(OrigV, &PN) ||
  1807. passingValueIsAlwaysUndefined(ThenV, &PN))
  1808. return false;
  1809. HaveRewritablePHIs = true;
  1810. ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
  1811. ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
  1812. if (!OrigCE && !ThenCE)
  1813. continue; // Known safe and cheap.
  1814. if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
  1815. (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
  1816. return false;
  1817. unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
  1818. unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
  1819. unsigned MaxCost =
  1820. 2 * PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic;
  1821. if (OrigCost + ThenCost > MaxCost)
  1822. return false;
  1823. // Account for the cost of an unfolded ConstantExpr which could end up
  1824. // getting expanded into Instructions.
  1825. // FIXME: This doesn't account for how many operations are combined in the
  1826. // constant expression.
  1827. ++SpeculationCost;
  1828. if (SpeculationCost > 1)
  1829. return false;
  1830. }
  1831. // If there are no PHIs to process, bail early. This helps ensure idempotence
  1832. // as well.
  1833. if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
  1834. return false;
  1835. // If we get here, we can hoist the instruction and if-convert.
  1836. LLVM_DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
  1837. // Insert a select of the value of the speculated store.
  1838. if (SpeculatedStoreValue) {
  1839. IRBuilder<NoFolder> Builder(BI);
  1840. Value *TrueV = SpeculatedStore->getValueOperand();
  1841. Value *FalseV = SpeculatedStoreValue;
  1842. if (Invert)
  1843. std::swap(TrueV, FalseV);
  1844. Value *S = Builder.CreateSelect(
  1845. BrCond, TrueV, FalseV, "spec.store.select", BI);
  1846. SpeculatedStore->setOperand(0, S);
  1847. SpeculatedStore->applyMergedLocation(BI->getDebugLoc(),
  1848. SpeculatedStore->getDebugLoc());
  1849. }
  1850. // Metadata can be dependent on the condition we are hoisting above.
  1851. // Conservatively strip all metadata on the instruction.
  1852. for (auto &I : *ThenBB)
  1853. I.dropUnknownNonDebugMetadata();
  1854. // Hoist the instructions.
  1855. BB->getInstList().splice(BI->getIterator(), ThenBB->getInstList(),
  1856. ThenBB->begin(), std::prev(ThenBB->end()));
  1857. // Insert selects and rewrite the PHI operands.
  1858. IRBuilder<NoFolder> Builder(BI);
  1859. for (PHINode &PN : EndBB->phis()) {
  1860. unsigned OrigI = PN.getBasicBlockIndex(BB);
  1861. unsigned ThenI = PN.getBasicBlockIndex(ThenBB);
  1862. Value *OrigV = PN.getIncomingValue(OrigI);
  1863. Value *ThenV = PN.getIncomingValue(ThenI);
  1864. // Skip PHIs which are trivial.
  1865. if (OrigV == ThenV)
  1866. continue;
  1867. // Create a select whose true value is the speculatively executed value and
  1868. // false value is the preexisting value. Swap them if the branch
  1869. // destinations were inverted.
  1870. Value *TrueV = ThenV, *FalseV = OrigV;
  1871. if (Invert)
  1872. std::swap(TrueV, FalseV);
  1873. Value *V = Builder.CreateSelect(
  1874. BrCond, TrueV, FalseV, "spec.select", BI);
  1875. PN.setIncomingValue(OrigI, V);
  1876. PN.setIncomingValue(ThenI, V);
  1877. }
  1878. // Remove speculated dbg intrinsics.
  1879. // FIXME: Is it possible to do this in a more elegant way? Moving/merging the
  1880. // dbg value for the different flows and inserting it after the select.
  1881. for (Instruction *I : SpeculatedDbgIntrinsics)
  1882. I->eraseFromParent();
  1883. ++NumSpeculations;
  1884. return true;
  1885. }
  1886. /// Return true if we can thread a branch across this block.
  1887. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  1888. unsigned Size = 0;
  1889. for (Instruction &I : BB->instructionsWithoutDebug()) {
  1890. if (Size > 10)
  1891. return false; // Don't clone large BB's.
  1892. ++Size;
  1893. // We can only support instructions that do not define values that are
  1894. // live outside of the current basic block.
  1895. for (User *U : I.users()) {
  1896. Instruction *UI = cast<Instruction>(U);
  1897. if (UI->getParent() != BB || isa<PHINode>(UI))
  1898. return false;
  1899. }
  1900. // Looks ok, continue checking.
  1901. }
  1902. return true;
  1903. }
  1904. /// If we have a conditional branch on a PHI node value that is defined in the
  1905. /// same block as the branch and if any PHI entries are constants, thread edges
  1906. /// corresponding to that entry to be branches to their ultimate destination.
  1907. static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL,
  1908. AssumptionCache *AC) {
  1909. BasicBlock *BB = BI->getParent();
  1910. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  1911. // NOTE: we currently cannot transform this case if the PHI node is used
  1912. // outside of the block.
  1913. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  1914. return false;
  1915. // Degenerate case of a single entry PHI.
  1916. if (PN->getNumIncomingValues() == 1) {
  1917. FoldSingleEntryPHINodes(PN->getParent());
  1918. return true;
  1919. }
  1920. // Now we know that this block has multiple preds and two succs.
  1921. if (!BlockIsSimpleEnoughToThreadThrough(BB))
  1922. return false;
  1923. // Can't fold blocks that contain noduplicate or convergent calls.
  1924. if (any_of(*BB, [](const Instruction &I) {
  1925. const CallInst *CI = dyn_cast<CallInst>(&I);
  1926. return CI && (CI->cannotDuplicate() || CI->isConvergent());
  1927. }))
  1928. return false;
  1929. // Okay, this is a simple enough basic block. See if any phi values are
  1930. // constants.
  1931. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1932. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1933. if (!CB || !CB->getType()->isIntegerTy(1))
  1934. continue;
  1935. // Okay, we now know that all edges from PredBB should be revectored to
  1936. // branch to RealDest.
  1937. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1938. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1939. if (RealDest == BB)
  1940. continue; // Skip self loops.
  1941. // Skip if the predecessor's terminator is an indirect branch.
  1942. if (isa<IndirectBrInst>(PredBB->getTerminator()))
  1943. continue;
  1944. // The dest block might have PHI nodes, other predecessors and other
  1945. // difficult cases. Instead of being smart about this, just insert a new
  1946. // block that jumps to the destination block, effectively splitting
  1947. // the edge we are about to create.
  1948. BasicBlock *EdgeBB =
  1949. BasicBlock::Create(BB->getContext(), RealDest->getName() + ".critedge",
  1950. RealDest->getParent(), RealDest);
  1951. BranchInst *CritEdgeBranch = BranchInst::Create(RealDest, EdgeBB);
  1952. CritEdgeBranch->setDebugLoc(BI->getDebugLoc());
  1953. // Update PHI nodes.
  1954. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1955. // BB may have instructions that are being threaded over. Clone these
  1956. // instructions into EdgeBB. We know that there will be no uses of the
  1957. // cloned instructions outside of EdgeBB.
  1958. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1959. DenseMap<Value *, Value *> TranslateMap; // Track translated values.
  1960. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1961. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1962. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1963. continue;
  1964. }
  1965. // Clone the instruction.
  1966. Instruction *N = BBI->clone();
  1967. if (BBI->hasName())
  1968. N->setName(BBI->getName() + ".c");
  1969. // Update operands due to translation.
  1970. for (User::op_iterator i = N->op_begin(), e = N->op_end(); i != e; ++i) {
  1971. DenseMap<Value *, Value *>::iterator PI = TranslateMap.find(*i);
  1972. if (PI != TranslateMap.end())
  1973. *i = PI->second;
  1974. }
  1975. // Check for trivial simplification.
  1976. if (Value *V = SimplifyInstruction(N, {DL, nullptr, nullptr, AC})) {
  1977. if (!BBI->use_empty())
  1978. TranslateMap[&*BBI] = V;
  1979. if (!N->mayHaveSideEffects()) {
  1980. N->deleteValue(); // Instruction folded away, don't need actual inst
  1981. N = nullptr;
  1982. }
  1983. } else {
  1984. if (!BBI->use_empty())
  1985. TranslateMap[&*BBI] = N;
  1986. }
  1987. // Insert the new instruction into its new home.
  1988. if (N)
  1989. EdgeBB->getInstList().insert(InsertPt, N);
  1990. // Register the new instruction with the assumption cache if necessary.
  1991. if (auto *II = dyn_cast_or_null<IntrinsicInst>(N))
  1992. if (II->getIntrinsicID() == Intrinsic::assume)
  1993. AC->registerAssumption(II);
  1994. }
  1995. // Loop over all of the edges from PredBB to BB, changing them to branch
  1996. // to EdgeBB instead.
  1997. Instruction *PredBBTI = PredBB->getTerminator();
  1998. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1999. if (PredBBTI->getSuccessor(i) == BB) {
  2000. BB->removePredecessor(PredBB);
  2001. PredBBTI->setSuccessor(i, EdgeBB);
  2002. }
  2003. // Recurse, simplifying any other constants.
  2004. return FoldCondBranchOnPHI(BI, DL, AC) || true;
  2005. }
  2006. return false;
  2007. }
  2008. /// Given a BB that starts with the specified two-entry PHI node,
  2009. /// see if we can eliminate it.
  2010. static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
  2011. const DataLayout &DL) {
  2012. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  2013. // statement", which has a very simple dominance structure. Basically, we
  2014. // are trying to find the condition that is being branched on, which
  2015. // subsequently causes this merge to happen. We really want control
  2016. // dependence information for this check, but simplifycfg can't keep it up
  2017. // to date, and this catches most of the cases we care about anyway.
  2018. BasicBlock *BB = PN->getParent();
  2019. const Function *Fn = BB->getParent();
  2020. if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
  2021. return false;
  2022. BasicBlock *IfTrue, *IfFalse;
  2023. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  2024. if (!IfCond ||
  2025. // Don't bother if the branch will be constant folded trivially.
  2026. isa<ConstantInt>(IfCond))
  2027. return false;
  2028. // Okay, we found that we can merge this two-entry phi node into a select.
  2029. // Doing so would require us to fold *all* two entry phi nodes in this block.
  2030. // At some point this becomes non-profitable (particularly if the target
  2031. // doesn't support cmov's). Only do this transformation if there are two or
  2032. // fewer PHI nodes in this block.
  2033. unsigned NumPhis = 0;
  2034. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  2035. if (NumPhis > 2)
  2036. return false;
  2037. // Loop over the PHI's seeing if we can promote them all to select
  2038. // instructions. While we are at it, keep track of the instructions
  2039. // that need to be moved to the dominating block.
  2040. SmallPtrSet<Instruction *, 4> AggressiveInsts;
  2041. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  2042. MaxCostVal1 = PHINodeFoldingThreshold;
  2043. MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
  2044. MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
  2045. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  2046. PHINode *PN = cast<PHINode>(II++);
  2047. if (Value *V = SimplifyInstruction(PN, {DL, PN})) {
  2048. PN->replaceAllUsesWith(V);
  2049. PN->eraseFromParent();
  2050. continue;
  2051. }
  2052. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, AggressiveInsts,
  2053. MaxCostVal0, TTI) ||
  2054. !DominatesMergePoint(PN->getIncomingValue(1), BB, AggressiveInsts,
  2055. MaxCostVal1, TTI))
  2056. return false;
  2057. }
  2058. // If we folded the first phi, PN dangles at this point. Refresh it. If
  2059. // we ran out of PHIs then we simplified them all.
  2060. PN = dyn_cast<PHINode>(BB->begin());
  2061. if (!PN)
  2062. return true;
  2063. // Don't fold i1 branches on PHIs which contain binary operators. These can
  2064. // often be turned into switches and other things.
  2065. if (PN->getType()->isIntegerTy(1) &&
  2066. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  2067. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  2068. isa<BinaryOperator>(IfCond)))
  2069. return false;
  2070. // If all PHI nodes are promotable, check to make sure that all instructions
  2071. // in the predecessor blocks can be promoted as well. If not, we won't be able
  2072. // to get rid of the control flow, so it's not worth promoting to select
  2073. // instructions.
  2074. BasicBlock *DomBlock = nullptr;
  2075. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  2076. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  2077. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  2078. IfBlock1 = nullptr;
  2079. } else {
  2080. DomBlock = *pred_begin(IfBlock1);
  2081. for (BasicBlock::iterator I = IfBlock1->begin(); !I->isTerminator(); ++I)
  2082. if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
  2083. // This is not an aggressive instruction that we can promote.
  2084. // Because of this, we won't be able to get rid of the control flow, so
  2085. // the xform is not worth it.
  2086. return false;
  2087. }
  2088. }
  2089. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  2090. IfBlock2 = nullptr;
  2091. } else {
  2092. DomBlock = *pred_begin(IfBlock2);
  2093. for (BasicBlock::iterator I = IfBlock2->begin(); !I->isTerminator(); ++I)
  2094. if (!AggressiveInsts.count(&*I) && !isa<DbgInfoIntrinsic>(I)) {
  2095. // This is not an aggressive instruction that we can promote.
  2096. // Because of this, we won't be able to get rid of the control flow, so
  2097. // the xform is not worth it.
  2098. return false;
  2099. }
  2100. }
  2101. LLVM_DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond
  2102. << " T: " << IfTrue->getName()
  2103. << " F: " << IfFalse->getName() << "\n");
  2104. // If we can still promote the PHI nodes after this gauntlet of tests,
  2105. // do all of the PHI's now.
  2106. Instruction *InsertPt = DomBlock->getTerminator();
  2107. IRBuilder<NoFolder> Builder(InsertPt);
  2108. // Move all 'aggressive' instructions, which are defined in the
  2109. // conditional parts of the if's up to the dominating block.
  2110. if (IfBlock1)
  2111. hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock1);
  2112. if (IfBlock2)
  2113. hoistAllInstructionsInto(DomBlock, InsertPt, IfBlock2);
  2114. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  2115. // Change the PHI node into a select instruction.
  2116. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  2117. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  2118. Value *Sel = Builder.CreateSelect(IfCond, TrueVal, FalseVal, "", InsertPt);
  2119. PN->replaceAllUsesWith(Sel);
  2120. Sel->takeName(PN);
  2121. PN->eraseFromParent();
  2122. }
  2123. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  2124. // has been flattened. Change DomBlock to jump directly to our new block to
  2125. // avoid other simplifycfg's kicking in on the diamond.
  2126. Instruction *OldTI = DomBlock->getTerminator();
  2127. Builder.SetInsertPoint(OldTI);
  2128. Builder.CreateBr(BB);
  2129. OldTI->eraseFromParent();
  2130. return true;
  2131. }
  2132. /// If we found a conditional branch that goes to two returning blocks,
  2133. /// try to merge them together into one return,
  2134. /// introducing a select if the return values disagree.
  2135. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  2136. IRBuilder<> &Builder) {
  2137. assert(BI->isConditional() && "Must be a conditional branch");
  2138. BasicBlock *TrueSucc = BI->getSuccessor(0);
  2139. BasicBlock *FalseSucc = BI->getSuccessor(1);
  2140. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  2141. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  2142. // Check to ensure both blocks are empty (just a return) or optionally empty
  2143. // with PHI nodes. If there are other instructions, merging would cause extra
  2144. // computation on one path or the other.
  2145. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  2146. return false;
  2147. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  2148. return false;
  2149. Builder.SetInsertPoint(BI);
  2150. // Okay, we found a branch that is going to two return nodes. If
  2151. // there is no return value for this function, just change the
  2152. // branch into a return.
  2153. if (FalseRet->getNumOperands() == 0) {
  2154. TrueSucc->removePredecessor(BI->getParent());
  2155. FalseSucc->removePredecessor(BI->getParent());
  2156. Builder.CreateRetVoid();
  2157. EraseTerminatorAndDCECond(BI);
  2158. return true;
  2159. }
  2160. // Otherwise, figure out what the true and false return values are
  2161. // so we can insert a new select instruction.
  2162. Value *TrueValue = TrueRet->getReturnValue();
  2163. Value *FalseValue = FalseRet->getReturnValue();
  2164. // Unwrap any PHI nodes in the return blocks.
  2165. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  2166. if (TVPN->getParent() == TrueSucc)
  2167. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  2168. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  2169. if (FVPN->getParent() == FalseSucc)
  2170. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  2171. // In order for this transformation to be safe, we must be able to
  2172. // unconditionally execute both operands to the return. This is
  2173. // normally the case, but we could have a potentially-trapping
  2174. // constant expression that prevents this transformation from being
  2175. // safe.
  2176. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  2177. if (TCV->canTrap())
  2178. return false;
  2179. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  2180. if (FCV->canTrap())
  2181. return false;
  2182. // Okay, we collected all the mapped values and checked them for sanity, and
  2183. // defined to really do this transformation. First, update the CFG.
  2184. TrueSucc->removePredecessor(BI->getParent());
  2185. FalseSucc->removePredecessor(BI->getParent());
  2186. // Insert select instructions where needed.
  2187. Value *BrCond = BI->getCondition();
  2188. if (TrueValue) {
  2189. // Insert a select if the results differ.
  2190. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  2191. } else if (isa<UndefValue>(TrueValue)) {
  2192. TrueValue = FalseValue;
  2193. } else {
  2194. TrueValue =
  2195. Builder.CreateSelect(BrCond, TrueValue, FalseValue, "retval", BI);
  2196. }
  2197. }
  2198. Value *RI =
  2199. !TrueValue ? Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  2200. (void)RI;
  2201. LLVM_DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  2202. << "\n " << *BI << "NewRet = " << *RI << "TRUEBLOCK: "
  2203. << *TrueSucc << "FALSEBLOCK: " << *FalseSucc);
  2204. EraseTerminatorAndDCECond(BI);
  2205. return true;
  2206. }
  2207. /// Return true if the given instruction is available
  2208. /// in its predecessor block. If yes, the instruction will be removed.
  2209. static bool tryCSEWithPredecessor(Instruction *Inst, BasicBlock *PB) {
  2210. if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
  2211. return false;
  2212. for (Instruction &I : *PB) {
  2213. Instruction *PBI = &I;
  2214. // Check whether Inst and PBI generate the same value.
  2215. if (Inst->isIdenticalTo(PBI)) {
  2216. Inst->replaceAllUsesWith(PBI);
  2217. Inst->eraseFromParent();
  2218. return true;
  2219. }
  2220. }
  2221. return false;
  2222. }
  2223. /// Return true if either PBI or BI has branch weight available, and store
  2224. /// the weights in {Pred|Succ}{True|False}Weight. If one of PBI and BI does
  2225. /// not have branch weight, use 1:1 as its weight.
  2226. static bool extractPredSuccWeights(BranchInst *PBI, BranchInst *BI,
  2227. uint64_t &PredTrueWeight,
  2228. uint64_t &PredFalseWeight,
  2229. uint64_t &SuccTrueWeight,
  2230. uint64_t &SuccFalseWeight) {
  2231. bool PredHasWeights =
  2232. PBI->extractProfMetadata(PredTrueWeight, PredFalseWeight);
  2233. bool SuccHasWeights =
  2234. BI->extractProfMetadata(SuccTrueWeight, SuccFalseWeight);
  2235. if (PredHasWeights || SuccHasWeights) {
  2236. if (!PredHasWeights)
  2237. PredTrueWeight = PredFalseWeight = 1;
  2238. if (!SuccHasWeights)
  2239. SuccTrueWeight = SuccFalseWeight = 1;
  2240. return true;
  2241. } else {
  2242. return false;
  2243. }
  2244. }
  2245. /// If this basic block is simple enough, and if a predecessor branches to us
  2246. /// and one of our successors, fold the block into the predecessor and use
  2247. /// logical operations to pick the right destination.
  2248. bool llvm::FoldBranchToCommonDest(BranchInst *BI, MemorySSAUpdater *MSSAU,
  2249. unsigned BonusInstThreshold) {
  2250. BasicBlock *BB = BI->getParent();
  2251. const unsigned PredCount = pred_size(BB);
  2252. Instruction *Cond = nullptr;
  2253. if (BI->isConditional())
  2254. Cond = dyn_cast<Instruction>(BI->getCondition());
  2255. else {
  2256. // For unconditional branch, check for a simple CFG pattern, where
  2257. // BB has a single predecessor and BB's successor is also its predecessor's
  2258. // successor. If such pattern exists, check for CSE between BB and its
  2259. // predecessor.
  2260. if (BasicBlock *PB = BB->getSinglePredecessor())
  2261. if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
  2262. if (PBI->isConditional() &&
  2263. (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
  2264. BI->getSuccessor(0) == PBI->getSuccessor(1))) {
  2265. for (auto I = BB->instructionsWithoutDebug().begin(),
  2266. E = BB->instructionsWithoutDebug().end();
  2267. I != E;) {
  2268. Instruction *Curr = &*I++;
  2269. if (isa<CmpInst>(Curr)) {
  2270. Cond = Curr;
  2271. break;
  2272. }
  2273. // Quit if we can't remove this instruction.
  2274. if (!tryCSEWithPredecessor(Curr, PB))
  2275. return false;
  2276. }
  2277. }
  2278. if (!Cond)
  2279. return false;
  2280. }
  2281. if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  2282. Cond->getParent() != BB || !Cond->hasOneUse())
  2283. return false;
  2284. // Make sure the instruction after the condition is the cond branch.
  2285. BasicBlock::iterator CondIt = ++Cond->getIterator();
  2286. // Ignore dbg intrinsics.
  2287. while (isa<DbgInfoIntrinsic>(CondIt))
  2288. ++CondIt;
  2289. if (&*CondIt != BI)
  2290. return false;
  2291. // Only allow this transformation if computing the condition doesn't involve
  2292. // too many instructions and these involved instructions can be executed
  2293. // unconditionally. We denote all involved instructions except the condition
  2294. // as "bonus instructions", and only allow this transformation when the
  2295. // number of the bonus instructions we'll need to create when cloning into
  2296. // each predecessor does not exceed a certain threshold.
  2297. unsigned NumBonusInsts = 0;
  2298. for (auto I = BB->begin(); Cond != &*I; ++I) {
  2299. // Ignore dbg intrinsics.
  2300. if (isa<DbgInfoIntrinsic>(I))
  2301. continue;
  2302. if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(&*I))
  2303. return false;
  2304. // I has only one use and can be executed unconditionally.
  2305. Instruction *User = dyn_cast<Instruction>(I->user_back());
  2306. if (User == nullptr || User->getParent() != BB)
  2307. return false;
  2308. // I is used in the same BB. Since BI uses Cond and doesn't have more slots
  2309. // to use any other instruction, User must be an instruction between next(I)
  2310. // and Cond.
  2311. // Account for the cost of duplicating this instruction into each
  2312. // predecessor.
  2313. NumBonusInsts += PredCount;
  2314. // Early exits once we reach the limit.
  2315. if (NumBonusInsts > BonusInstThreshold)
  2316. return false;
  2317. }
  2318. // Cond is known to be a compare or binary operator. Check to make sure that
  2319. // neither operand is a potentially-trapping constant expression.
  2320. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  2321. if (CE->canTrap())
  2322. return false;
  2323. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  2324. if (CE->canTrap())
  2325. return false;
  2326. // Finally, don't infinitely unroll conditional loops.
  2327. BasicBlock *TrueDest = BI->getSuccessor(0);
  2328. BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
  2329. if (TrueDest == BB || FalseDest == BB)
  2330. return false;
  2331. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  2332. BasicBlock *PredBlock = *PI;
  2333. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  2334. // Check that we have two conditional branches. If there is a PHI node in
  2335. // the common successor, verify that the same value flows in from both
  2336. // blocks.
  2337. SmallVector<PHINode *, 4> PHIs;
  2338. if (!PBI || PBI->isUnconditional() ||
  2339. (BI->isConditional() && !SafeToMergeTerminators(BI, PBI)) ||
  2340. (!BI->isConditional() &&
  2341. !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
  2342. continue;
  2343. // Determine if the two branches share a common destination.
  2344. Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
  2345. bool InvertPredCond = false;
  2346. if (BI->isConditional()) {
  2347. if (PBI->getSuccessor(0) == TrueDest) {
  2348. Opc = Instruction::Or;
  2349. } else if (PBI->getSuccessor(1) == FalseDest) {
  2350. Opc = Instruction::And;
  2351. } else if (PBI->getSuccessor(0) == FalseDest) {
  2352. Opc = Instruction::And;
  2353. InvertPredCond = true;
  2354. } else if (PBI->getSuccessor(1) == TrueDest) {
  2355. Opc = Instruction::Or;
  2356. InvertPredCond = true;
  2357. } else {
  2358. continue;
  2359. }
  2360. } else {
  2361. if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
  2362. continue;
  2363. }
  2364. LLVM_DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  2365. IRBuilder<> Builder(PBI);
  2366. // If we need to invert the condition in the pred block to match, do so now.
  2367. if (InvertPredCond) {
  2368. Value *NewCond = PBI->getCondition();
  2369. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  2370. CmpInst *CI = cast<CmpInst>(NewCond);
  2371. CI->setPredicate(CI->getInversePredicate());
  2372. } else {
  2373. NewCond =
  2374. Builder.CreateNot(NewCond, PBI->getCondition()->getName() + ".not");
  2375. }
  2376. PBI->setCondition(NewCond);
  2377. PBI->swapSuccessors();
  2378. }
  2379. // If we have bonus instructions, clone them into the predecessor block.
  2380. // Note that there may be multiple predecessor blocks, so we cannot move
  2381. // bonus instructions to a predecessor block.
  2382. ValueToValueMapTy VMap; // maps original values to cloned values
  2383. // We already make sure Cond is the last instruction before BI. Therefore,
  2384. // all instructions before Cond other than DbgInfoIntrinsic are bonus
  2385. // instructions.
  2386. for (auto BonusInst = BB->begin(); Cond != &*BonusInst; ++BonusInst) {
  2387. if (isa<DbgInfoIntrinsic>(BonusInst))
  2388. continue;
  2389. Instruction *NewBonusInst = BonusInst->clone();
  2390. RemapInstruction(NewBonusInst, VMap,
  2391. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  2392. VMap[&*BonusInst] = NewBonusInst;
  2393. // If we moved a load, we cannot any longer claim any knowledge about
  2394. // its potential value. The previous information might have been valid
  2395. // only given the branch precondition.
  2396. // For an analogous reason, we must also drop all the metadata whose
  2397. // semantics we don't understand.
  2398. NewBonusInst->dropUnknownNonDebugMetadata();
  2399. PredBlock->getInstList().insert(PBI->getIterator(), NewBonusInst);
  2400. NewBonusInst->takeName(&*BonusInst);
  2401. BonusInst->setName(BonusInst->getName() + ".old");
  2402. }
  2403. // Clone Cond into the predecessor basic block, and or/and the
  2404. // two conditions together.
  2405. Instruction *CondInPred = Cond->clone();
  2406. RemapInstruction(CondInPred, VMap,
  2407. RF_NoModuleLevelChanges | RF_IgnoreMissingLocals);
  2408. PredBlock->getInstList().insert(PBI->getIterator(), CondInPred);
  2409. CondInPred->takeName(Cond);
  2410. Cond->setName(CondInPred->getName() + ".old");
  2411. if (BI->isConditional()) {
  2412. Instruction *NewCond = cast<Instruction>(
  2413. Builder.CreateBinOp(Opc, PBI->getCondition(), CondInPred, "or.cond"));
  2414. PBI->setCondition(NewCond);
  2415. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2416. bool HasWeights =
  2417. extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
  2418. SuccTrueWeight, SuccFalseWeight);
  2419. SmallVector<uint64_t, 8> NewWeights;
  2420. if (PBI->getSuccessor(0) == BB) {
  2421. if (HasWeights) {
  2422. // PBI: br i1 %x, BB, FalseDest
  2423. // BI: br i1 %y, TrueDest, FalseDest
  2424. // TrueWeight is TrueWeight for PBI * TrueWeight for BI.
  2425. NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
  2426. // FalseWeight is FalseWeight for PBI * TotalWeight for BI +
  2427. // TrueWeight for PBI * FalseWeight for BI.
  2428. // We assume that total weights of a BranchInst can fit into 32 bits.
  2429. // Therefore, we will not have overflow using 64-bit arithmetic.
  2430. NewWeights.push_back(PredFalseWeight *
  2431. (SuccFalseWeight + SuccTrueWeight) +
  2432. PredTrueWeight * SuccFalseWeight);
  2433. }
  2434. AddPredecessorToBlock(TrueDest, PredBlock, BB, MSSAU);
  2435. PBI->setSuccessor(0, TrueDest);
  2436. }
  2437. if (PBI->getSuccessor(1) == BB) {
  2438. if (HasWeights) {
  2439. // PBI: br i1 %x, TrueDest, BB
  2440. // BI: br i1 %y, TrueDest, FalseDest
  2441. // TrueWeight is TrueWeight for PBI * TotalWeight for BI +
  2442. // FalseWeight for PBI * TrueWeight for BI.
  2443. NewWeights.push_back(PredTrueWeight *
  2444. (SuccFalseWeight + SuccTrueWeight) +
  2445. PredFalseWeight * SuccTrueWeight);
  2446. // FalseWeight is FalseWeight for PBI * FalseWeight for BI.
  2447. NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
  2448. }
  2449. AddPredecessorToBlock(FalseDest, PredBlock, BB, MSSAU);
  2450. PBI->setSuccessor(1, FalseDest);
  2451. }
  2452. if (NewWeights.size() == 2) {
  2453. // Halve the weights if any of them cannot fit in an uint32_t
  2454. FitWeights(NewWeights);
  2455. SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),
  2456. NewWeights.end());
  2457. setBranchWeights(PBI, MDWeights[0], MDWeights[1]);
  2458. } else
  2459. PBI->setMetadata(LLVMContext::MD_prof, nullptr);
  2460. } else {
  2461. // Update PHI nodes in the common successors.
  2462. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  2463. ConstantInt *PBI_C = cast<ConstantInt>(
  2464. PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
  2465. assert(PBI_C->getType()->isIntegerTy(1));
  2466. Instruction *MergedCond = nullptr;
  2467. if (PBI->getSuccessor(0) == TrueDest) {
  2468. // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
  2469. // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
  2470. // is false: !PBI_Cond and BI_Value
  2471. Instruction *NotCond = cast<Instruction>(
  2472. Builder.CreateNot(PBI->getCondition(), "not.cond"));
  2473. MergedCond = cast<Instruction>(
  2474. Builder.CreateBinOp(Instruction::And, NotCond, CondInPred,
  2475. "and.cond"));
  2476. if (PBI_C->isOne())
  2477. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2478. Instruction::Or, PBI->getCondition(), MergedCond, "or.cond"));
  2479. } else {
  2480. // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
  2481. // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
  2482. // is false: PBI_Cond and BI_Value
  2483. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2484. Instruction::And, PBI->getCondition(), CondInPred, "and.cond"));
  2485. if (PBI_C->isOne()) {
  2486. Instruction *NotCond = cast<Instruction>(
  2487. Builder.CreateNot(PBI->getCondition(), "not.cond"));
  2488. MergedCond = cast<Instruction>(Builder.CreateBinOp(
  2489. Instruction::Or, NotCond, MergedCond, "or.cond"));
  2490. }
  2491. }
  2492. // Update PHI Node.
  2493. PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
  2494. MergedCond);
  2495. }
  2496. // PBI is changed to branch to TrueDest below. Remove itself from
  2497. // potential phis from all other successors.
  2498. if (MSSAU)
  2499. MSSAU->changeCondBranchToUnconditionalTo(PBI, TrueDest);
  2500. // Change PBI from Conditional to Unconditional.
  2501. BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
  2502. EraseTerminatorAndDCECond(PBI, MSSAU);
  2503. PBI = New_PBI;
  2504. }
  2505. // If BI was a loop latch, it may have had associated loop metadata.
  2506. // We need to copy it to the new latch, that is, PBI.
  2507. if (MDNode *LoopMD = BI->getMetadata(LLVMContext::MD_loop))
  2508. PBI->setMetadata(LLVMContext::MD_loop, LoopMD);
  2509. // TODO: If BB is reachable from all paths through PredBlock, then we
  2510. // could replace PBI's branch probabilities with BI's.
  2511. // Copy any debug value intrinsics into the end of PredBlock.
  2512. for (Instruction &I : *BB)
  2513. if (isa<DbgInfoIntrinsic>(I))
  2514. I.clone()->insertBefore(PBI);
  2515. return true;
  2516. }
  2517. return false;
  2518. }
  2519. // If there is only one store in BB1 and BB2, return it, otherwise return
  2520. // nullptr.
  2521. static StoreInst *findUniqueStoreInBlocks(BasicBlock *BB1, BasicBlock *BB2) {
  2522. StoreInst *S = nullptr;
  2523. for (auto *BB : {BB1, BB2}) {
  2524. if (!BB)
  2525. continue;
  2526. for (auto &I : *BB)
  2527. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  2528. if (S)
  2529. // Multiple stores seen.
  2530. return nullptr;
  2531. else
  2532. S = SI;
  2533. }
  2534. }
  2535. return S;
  2536. }
  2537. static Value *ensureValueAvailableInSuccessor(Value *V, BasicBlock *BB,
  2538. Value *AlternativeV = nullptr) {
  2539. // PHI is going to be a PHI node that allows the value V that is defined in
  2540. // BB to be referenced in BB's only successor.
  2541. //
  2542. // If AlternativeV is nullptr, the only value we care about in PHI is V. It
  2543. // doesn't matter to us what the other operand is (it'll never get used). We
  2544. // could just create a new PHI with an undef incoming value, but that could
  2545. // increase register pressure if EarlyCSE/InstCombine can't fold it with some
  2546. // other PHI. So here we directly look for some PHI in BB's successor with V
  2547. // as an incoming operand. If we find one, we use it, else we create a new
  2548. // one.
  2549. //
  2550. // If AlternativeV is not nullptr, we care about both incoming values in PHI.
  2551. // PHI must be exactly: phi <ty> [ %BB, %V ], [ %OtherBB, %AlternativeV]
  2552. // where OtherBB is the single other predecessor of BB's only successor.
  2553. PHINode *PHI = nullptr;
  2554. BasicBlock *Succ = BB->getSingleSuccessor();
  2555. for (auto I = Succ->begin(); isa<PHINode>(I); ++I)
  2556. if (cast<PHINode>(I)->getIncomingValueForBlock(BB) == V) {
  2557. PHI = cast<PHINode>(I);
  2558. if (!AlternativeV)
  2559. break;
  2560. assert(Succ->hasNPredecessors(2));
  2561. auto PredI = pred_begin(Succ);
  2562. BasicBlock *OtherPredBB = *PredI == BB ? *++PredI : *PredI;
  2563. if (PHI->getIncomingValueForBlock(OtherPredBB) == AlternativeV)
  2564. break;
  2565. PHI = nullptr;
  2566. }
  2567. if (PHI)
  2568. return PHI;
  2569. // If V is not an instruction defined in BB, just return it.
  2570. if (!AlternativeV &&
  2571. (!isa<Instruction>(V) || cast<Instruction>(V)->getParent() != BB))
  2572. return V;
  2573. PHI = PHINode::Create(V->getType(), 2, "simplifycfg.merge", &Succ->front());
  2574. PHI->addIncoming(V, BB);
  2575. for (BasicBlock *PredBB : predecessors(Succ))
  2576. if (PredBB != BB)
  2577. PHI->addIncoming(
  2578. AlternativeV ? AlternativeV : UndefValue::get(V->getType()), PredBB);
  2579. return PHI;
  2580. }
  2581. static bool mergeConditionalStoreToAddress(BasicBlock *PTB, BasicBlock *PFB,
  2582. BasicBlock *QTB, BasicBlock *QFB,
  2583. BasicBlock *PostBB, Value *Address,
  2584. bool InvertPCond, bool InvertQCond,
  2585. const DataLayout &DL) {
  2586. auto IsaBitcastOfPointerType = [](const Instruction &I) {
  2587. return Operator::getOpcode(&I) == Instruction::BitCast &&
  2588. I.getType()->isPointerTy();
  2589. };
  2590. // If we're not in aggressive mode, we only optimize if we have some
  2591. // confidence that by optimizing we'll allow P and/or Q to be if-converted.
  2592. auto IsWorthwhile = [&](BasicBlock *BB) {
  2593. if (!BB)
  2594. return true;
  2595. // Heuristic: if the block can be if-converted/phi-folded and the
  2596. // instructions inside are all cheap (arithmetic/GEPs), it's worthwhile to
  2597. // thread this store.
  2598. unsigned N = 0;
  2599. for (auto &I : BB->instructionsWithoutDebug()) {
  2600. // Cheap instructions viable for folding.
  2601. if (isa<BinaryOperator>(I) || isa<GetElementPtrInst>(I) ||
  2602. isa<StoreInst>(I))
  2603. ++N;
  2604. // Free instructions.
  2605. else if (I.isTerminator() || IsaBitcastOfPointerType(I))
  2606. continue;
  2607. else
  2608. return false;
  2609. }
  2610. // The store we want to merge is counted in N, so add 1 to make sure
  2611. // we're counting the instructions that would be left.
  2612. return N <= (PHINodeFoldingThreshold + 1);
  2613. };
  2614. if (!MergeCondStoresAggressively &&
  2615. (!IsWorthwhile(PTB) || !IsWorthwhile(PFB) || !IsWorthwhile(QTB) ||
  2616. !IsWorthwhile(QFB)))
  2617. return false;
  2618. // For every pointer, there must be exactly two stores, one coming from
  2619. // PTB or PFB, and the other from QTB or QFB. We don't support more than one
  2620. // store (to any address) in PTB,PFB or QTB,QFB.
  2621. // FIXME: We could relax this restriction with a bit more work and performance
  2622. // testing.
  2623. StoreInst *PStore = findUniqueStoreInBlocks(PTB, PFB);
  2624. StoreInst *QStore = findUniqueStoreInBlocks(QTB, QFB);
  2625. if (!PStore || !QStore)
  2626. return false;
  2627. // Now check the stores are compatible.
  2628. if (!QStore->isUnordered() || !PStore->isUnordered())
  2629. return false;
  2630. // Check that sinking the store won't cause program behavior changes. Sinking
  2631. // the store out of the Q blocks won't change any behavior as we're sinking
  2632. // from a block to its unconditional successor. But we're moving a store from
  2633. // the P blocks down through the middle block (QBI) and past both QFB and QTB.
  2634. // So we need to check that there are no aliasing loads or stores in
  2635. // QBI, QTB and QFB. We also need to check there are no conflicting memory
  2636. // operations between PStore and the end of its parent block.
  2637. //
  2638. // The ideal way to do this is to query AliasAnalysis, but we don't
  2639. // preserve AA currently so that is dangerous. Be super safe and just
  2640. // check there are no other memory operations at all.
  2641. for (auto &I : *QFB->getSinglePredecessor())
  2642. if (I.mayReadOrWriteMemory())
  2643. return false;
  2644. for (auto &I : *QFB)
  2645. if (&I != QStore && I.mayReadOrWriteMemory())
  2646. return false;
  2647. if (QTB)
  2648. for (auto &I : *QTB)
  2649. if (&I != QStore && I.mayReadOrWriteMemory())
  2650. return false;
  2651. for (auto I = BasicBlock::iterator(PStore), E = PStore->getParent()->end();
  2652. I != E; ++I)
  2653. if (&*I != PStore && I->mayReadOrWriteMemory())
  2654. return false;
  2655. // If PostBB has more than two predecessors, we need to split it so we can
  2656. // sink the store.
  2657. if (std::next(pred_begin(PostBB), 2) != pred_end(PostBB)) {
  2658. // We know that QFB's only successor is PostBB. And QFB has a single
  2659. // predecessor. If QTB exists, then its only successor is also PostBB.
  2660. // If QTB does not exist, then QFB's only predecessor has a conditional
  2661. // branch to QFB and PostBB.
  2662. BasicBlock *TruePred = QTB ? QTB : QFB->getSinglePredecessor();
  2663. BasicBlock *NewBB = SplitBlockPredecessors(PostBB, { QFB, TruePred},
  2664. "condstore.split");
  2665. if (!NewBB)
  2666. return false;
  2667. PostBB = NewBB;
  2668. }
  2669. // OK, we're going to sink the stores to PostBB. The store has to be
  2670. // conditional though, so first create the predicate.
  2671. Value *PCond = cast<BranchInst>(PFB->getSinglePredecessor()->getTerminator())
  2672. ->getCondition();
  2673. Value *QCond = cast<BranchInst>(QFB->getSinglePredecessor()->getTerminator())
  2674. ->getCondition();
  2675. Value *PPHI = ensureValueAvailableInSuccessor(PStore->getValueOperand(),
  2676. PStore->getParent());
  2677. Value *QPHI = ensureValueAvailableInSuccessor(QStore->getValueOperand(),
  2678. QStore->getParent(), PPHI);
  2679. IRBuilder<> QB(&*PostBB->getFirstInsertionPt());
  2680. Value *PPred = PStore->getParent() == PTB ? PCond : QB.CreateNot(PCond);
  2681. Value *QPred = QStore->getParent() == QTB ? QCond : QB.CreateNot(QCond);
  2682. if (InvertPCond)
  2683. PPred = QB.CreateNot(PPred);
  2684. if (InvertQCond)
  2685. QPred = QB.CreateNot(QPred);
  2686. Value *CombinedPred = QB.CreateOr(PPred, QPred);
  2687. auto *T =
  2688. SplitBlockAndInsertIfThen(CombinedPred, &*QB.GetInsertPoint(), false);
  2689. QB.SetInsertPoint(T);
  2690. StoreInst *SI = cast<StoreInst>(QB.CreateStore(QPHI, Address));
  2691. AAMDNodes AAMD;
  2692. PStore->getAAMetadata(AAMD, /*Merge=*/false);
  2693. PStore->getAAMetadata(AAMD, /*Merge=*/true);
  2694. SI->setAAMetadata(AAMD);
  2695. unsigned PAlignment = PStore->getAlignment();
  2696. unsigned QAlignment = QStore->getAlignment();
  2697. unsigned TypeAlignment =
  2698. DL.getABITypeAlignment(SI->getValueOperand()->getType());
  2699. unsigned MinAlignment;
  2700. unsigned MaxAlignment;
  2701. std::tie(MinAlignment, MaxAlignment) = std::minmax(PAlignment, QAlignment);
  2702. // Choose the minimum alignment. If we could prove both stores execute, we
  2703. // could use biggest one. In this case, though, we only know that one of the
  2704. // stores executes. And we don't know it's safe to take the alignment from a
  2705. // store that doesn't execute.
  2706. if (MinAlignment != 0) {
  2707. // Choose the minimum of all non-zero alignments.
  2708. SI->setAlignment(MinAlignment);
  2709. } else if (MaxAlignment != 0) {
  2710. // Choose the minimal alignment between the non-zero alignment and the ABI
  2711. // default alignment for the type of the stored value.
  2712. SI->setAlignment(std::min(MaxAlignment, TypeAlignment));
  2713. } else {
  2714. // If both alignments are zero, use ABI default alignment for the type of
  2715. // the stored value.
  2716. SI->setAlignment(TypeAlignment);
  2717. }
  2718. QStore->eraseFromParent();
  2719. PStore->eraseFromParent();
  2720. return true;
  2721. }
  2722. static bool mergeConditionalStores(BranchInst *PBI, BranchInst *QBI,
  2723. const DataLayout &DL) {
  2724. // The intention here is to find diamonds or triangles (see below) where each
  2725. // conditional block contains a store to the same address. Both of these
  2726. // stores are conditional, so they can't be unconditionally sunk. But it may
  2727. // be profitable to speculatively sink the stores into one merged store at the
  2728. // end, and predicate the merged store on the union of the two conditions of
  2729. // PBI and QBI.
  2730. //
  2731. // This can reduce the number of stores executed if both of the conditions are
  2732. // true, and can allow the blocks to become small enough to be if-converted.
  2733. // This optimization will also chain, so that ladders of test-and-set
  2734. // sequences can be if-converted away.
  2735. //
  2736. // We only deal with simple diamonds or triangles:
  2737. //
  2738. // PBI or PBI or a combination of the two
  2739. // / \ | \
  2740. // PTB PFB | PFB
  2741. // \ / | /
  2742. // QBI QBI
  2743. // / \ | \
  2744. // QTB QFB | QFB
  2745. // \ / | /
  2746. // PostBB PostBB
  2747. //
  2748. // We model triangles as a type of diamond with a nullptr "true" block.
  2749. // Triangles are canonicalized so that the fallthrough edge is represented by
  2750. // a true condition, as in the diagram above.
  2751. BasicBlock *PTB = PBI->getSuccessor(0);
  2752. BasicBlock *PFB = PBI->getSuccessor(1);
  2753. BasicBlock *QTB = QBI->getSuccessor(0);
  2754. BasicBlock *QFB = QBI->getSuccessor(1);
  2755. BasicBlock *PostBB = QFB->getSingleSuccessor();
  2756. // Make sure we have a good guess for PostBB. If QTB's only successor is
  2757. // QFB, then QFB is a better PostBB.
  2758. if (QTB->getSingleSuccessor() == QFB)
  2759. PostBB = QFB;
  2760. // If we couldn't find a good PostBB, stop.
  2761. if (!PostBB)
  2762. return false;
  2763. bool InvertPCond = false, InvertQCond = false;
  2764. // Canonicalize fallthroughs to the true branches.
  2765. if (PFB == QBI->getParent()) {
  2766. std::swap(PFB, PTB);
  2767. InvertPCond = true;
  2768. }
  2769. if (QFB == PostBB) {
  2770. std::swap(QFB, QTB);
  2771. InvertQCond = true;
  2772. }
  2773. // From this point on we can assume PTB or QTB may be fallthroughs but PFB
  2774. // and QFB may not. Model fallthroughs as a nullptr block.
  2775. if (PTB == QBI->getParent())
  2776. PTB = nullptr;
  2777. if (QTB == PostBB)
  2778. QTB = nullptr;
  2779. // Legality bailouts. We must have at least the non-fallthrough blocks and
  2780. // the post-dominating block, and the non-fallthroughs must only have one
  2781. // predecessor.
  2782. auto HasOnePredAndOneSucc = [](BasicBlock *BB, BasicBlock *P, BasicBlock *S) {
  2783. return BB->getSinglePredecessor() == P && BB->getSingleSuccessor() == S;
  2784. };
  2785. if (!HasOnePredAndOneSucc(PFB, PBI->getParent(), QBI->getParent()) ||
  2786. !HasOnePredAndOneSucc(QFB, QBI->getParent(), PostBB))
  2787. return false;
  2788. if ((PTB && !HasOnePredAndOneSucc(PTB, PBI->getParent(), QBI->getParent())) ||
  2789. (QTB && !HasOnePredAndOneSucc(QTB, QBI->getParent(), PostBB)))
  2790. return false;
  2791. if (!QBI->getParent()->hasNUses(2))
  2792. return false;
  2793. // OK, this is a sequence of two diamonds or triangles.
  2794. // Check if there are stores in PTB or PFB that are repeated in QTB or QFB.
  2795. SmallPtrSet<Value *, 4> PStoreAddresses, QStoreAddresses;
  2796. for (auto *BB : {PTB, PFB}) {
  2797. if (!BB)
  2798. continue;
  2799. for (auto &I : *BB)
  2800. if (StoreInst *SI = dyn_cast<StoreInst>(&I))
  2801. PStoreAddresses.insert(SI->getPointerOperand());
  2802. }
  2803. for (auto *BB : {QTB, QFB}) {
  2804. if (!BB)
  2805. continue;
  2806. for (auto &I : *BB)
  2807. if (StoreInst *SI = dyn_cast<StoreInst>(&I))
  2808. QStoreAddresses.insert(SI->getPointerOperand());
  2809. }
  2810. set_intersect(PStoreAddresses, QStoreAddresses);
  2811. // set_intersect mutates PStoreAddresses in place. Rename it here to make it
  2812. // clear what it contains.
  2813. auto &CommonAddresses = PStoreAddresses;
  2814. bool Changed = false;
  2815. for (auto *Address : CommonAddresses)
  2816. Changed |= mergeConditionalStoreToAddress(
  2817. PTB, PFB, QTB, QFB, PostBB, Address, InvertPCond, InvertQCond, DL);
  2818. return Changed;
  2819. }
  2820. /// If we have a conditional branch as a predecessor of another block,
  2821. /// this function tries to simplify it. We know
  2822. /// that PBI and BI are both conditional branches, and BI is in one of the
  2823. /// successor blocks of PBI - PBI branches to BI.
  2824. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI,
  2825. const DataLayout &DL) {
  2826. assert(PBI->isConditional() && BI->isConditional());
  2827. BasicBlock *BB = BI->getParent();
  2828. // If this block ends with a branch instruction, and if there is a
  2829. // predecessor that ends on a branch of the same condition, make
  2830. // this conditional branch redundant.
  2831. if (PBI->getCondition() == BI->getCondition() &&
  2832. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2833. // Okay, the outcome of this conditional branch is statically
  2834. // knowable. If this block had a single pred, handle specially.
  2835. if (BB->getSinglePredecessor()) {
  2836. // Turn this into a branch on constant.
  2837. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2838. BI->setCondition(
  2839. ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue));
  2840. return true; // Nuke the branch on constant.
  2841. }
  2842. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  2843. // in the constant and simplify the block result. Subsequent passes of
  2844. // simplifycfg will thread the block.
  2845. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  2846. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  2847. PHINode *NewPN = PHINode::Create(
  2848. Type::getInt1Ty(BB->getContext()), std::distance(PB, PE),
  2849. BI->getCondition()->getName() + ".pr", &BB->front());
  2850. // Okay, we're going to insert the PHI node. Since PBI is not the only
  2851. // predecessor, compute the PHI'd conditional value for all of the preds.
  2852. // Any predecessor where the condition is not computable we keep symbolic.
  2853. for (pred_iterator PI = PB; PI != PE; ++PI) {
  2854. BasicBlock *P = *PI;
  2855. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) && PBI != BI &&
  2856. PBI->isConditional() && PBI->getCondition() == BI->getCondition() &&
  2857. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2858. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2859. NewPN->addIncoming(
  2860. ConstantInt::get(Type::getInt1Ty(BB->getContext()), CondIsTrue),
  2861. P);
  2862. } else {
  2863. NewPN->addIncoming(BI->getCondition(), P);
  2864. }
  2865. }
  2866. BI->setCondition(NewPN);
  2867. return true;
  2868. }
  2869. }
  2870. if (auto *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  2871. if (CE->canTrap())
  2872. return false;
  2873. // If both branches are conditional and both contain stores to the same
  2874. // address, remove the stores from the conditionals and create a conditional
  2875. // merged store at the end.
  2876. if (MergeCondStores && mergeConditionalStores(PBI, BI, DL))
  2877. return true;
  2878. // If this is a conditional branch in an empty block, and if any
  2879. // predecessors are a conditional branch to one of our destinations,
  2880. // fold the conditions into logical ops and one cond br.
  2881. // Ignore dbg intrinsics.
  2882. if (&*BB->instructionsWithoutDebug().begin() != BI)
  2883. return false;
  2884. int PBIOp, BIOp;
  2885. if (PBI->getSuccessor(0) == BI->getSuccessor(0)) {
  2886. PBIOp = 0;
  2887. BIOp = 0;
  2888. } else if (PBI->getSuccessor(0) == BI->getSuccessor(1)) {
  2889. PBIOp = 0;
  2890. BIOp = 1;
  2891. } else if (PBI->getSuccessor(1) == BI->getSuccessor(0)) {
  2892. PBIOp = 1;
  2893. BIOp = 0;
  2894. } else if (PBI->getSuccessor(1) == BI->getSuccessor(1)) {
  2895. PBIOp = 1;
  2896. BIOp = 1;
  2897. } else {
  2898. return false;
  2899. }
  2900. // Check to make sure that the other destination of this branch
  2901. // isn't BB itself. If so, this is an infinite loop that will
  2902. // keep getting unwound.
  2903. if (PBI->getSuccessor(PBIOp) == BB)
  2904. return false;
  2905. // Do not perform this transformation if it would require
  2906. // insertion of a large number of select instructions. For targets
  2907. // without predication/cmovs, this is a big pessimization.
  2908. // Also do not perform this transformation if any phi node in the common
  2909. // destination block can trap when reached by BB or PBB (PR17073). In that
  2910. // case, it would be unsafe to hoist the operation into a select instruction.
  2911. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  2912. unsigned NumPhis = 0;
  2913. for (BasicBlock::iterator II = CommonDest->begin(); isa<PHINode>(II);
  2914. ++II, ++NumPhis) {
  2915. if (NumPhis > 2) // Disable this xform.
  2916. return false;
  2917. PHINode *PN = cast<PHINode>(II);
  2918. Value *BIV = PN->getIncomingValueForBlock(BB);
  2919. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
  2920. if (CE->canTrap())
  2921. return false;
  2922. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2923. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2924. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
  2925. if (CE->canTrap())
  2926. return false;
  2927. }
  2928. // Finally, if everything is ok, fold the branches to logical ops.
  2929. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  2930. LLVM_DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  2931. << "AND: " << *BI->getParent());
  2932. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  2933. // branch in it, where one edge (OtherDest) goes back to itself but the other
  2934. // exits. We don't *know* that the program avoids the infinite loop
  2935. // (even though that seems likely). If we do this xform naively, we'll end up
  2936. // recursively unpeeling the loop. Since we know that (after the xform is
  2937. // done) that the block *is* infinite if reached, we just make it an obviously
  2938. // infinite loop with no cond branch.
  2939. if (OtherDest == BB) {
  2940. // Insert it at the end of the function, because it's either code,
  2941. // or it won't matter if it's hot. :)
  2942. BasicBlock *InfLoopBlock =
  2943. BasicBlock::Create(BB->getContext(), "infloop", BB->getParent());
  2944. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  2945. OtherDest = InfLoopBlock;
  2946. }
  2947. LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
  2948. // BI may have other predecessors. Because of this, we leave
  2949. // it alone, but modify PBI.
  2950. // Make sure we get to CommonDest on True&True directions.
  2951. Value *PBICond = PBI->getCondition();
  2952. IRBuilder<NoFolder> Builder(PBI);
  2953. if (PBIOp)
  2954. PBICond = Builder.CreateNot(PBICond, PBICond->getName() + ".not");
  2955. Value *BICond = BI->getCondition();
  2956. if (BIOp)
  2957. BICond = Builder.CreateNot(BICond, BICond->getName() + ".not");
  2958. // Merge the conditions.
  2959. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  2960. // Modify PBI to branch on the new condition to the new dests.
  2961. PBI->setCondition(Cond);
  2962. PBI->setSuccessor(0, CommonDest);
  2963. PBI->setSuccessor(1, OtherDest);
  2964. // Update branch weight for PBI.
  2965. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2966. uint64_t PredCommon, PredOther, SuccCommon, SuccOther;
  2967. bool HasWeights =
  2968. extractPredSuccWeights(PBI, BI, PredTrueWeight, PredFalseWeight,
  2969. SuccTrueWeight, SuccFalseWeight);
  2970. if (HasWeights) {
  2971. PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2972. PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
  2973. SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2974. SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2975. // The weight to CommonDest should be PredCommon * SuccTotal +
  2976. // PredOther * SuccCommon.
  2977. // The weight to OtherDest should be PredOther * SuccOther.
  2978. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
  2979. PredOther * SuccCommon,
  2980. PredOther * SuccOther};
  2981. // Halve the weights if any of them cannot fit in an uint32_t
  2982. FitWeights(NewWeights);
  2983. setBranchWeights(PBI, NewWeights[0], NewWeights[1]);
  2984. }
  2985. // OtherDest may have phi nodes. If so, add an entry from PBI's
  2986. // block that are identical to the entries for BI's block.
  2987. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  2988. // We know that the CommonDest already had an edge from PBI to
  2989. // it. If it has PHIs though, the PHIs may have different
  2990. // entries for BB and PBI's BB. If so, insert a select to make
  2991. // them agree.
  2992. for (PHINode &PN : CommonDest->phis()) {
  2993. Value *BIV = PN.getIncomingValueForBlock(BB);
  2994. unsigned PBBIdx = PN.getBasicBlockIndex(PBI->getParent());
  2995. Value *PBIV = PN.getIncomingValue(PBBIdx);
  2996. if (BIV != PBIV) {
  2997. // Insert a select in PBI to pick the right value.
  2998. SelectInst *NV = cast<SelectInst>(
  2999. Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName() + ".mux"));
  3000. PN.setIncomingValue(PBBIdx, NV);
  3001. // Although the select has the same condition as PBI, the original branch
  3002. // weights for PBI do not apply to the new select because the select's
  3003. // 'logical' edges are incoming edges of the phi that is eliminated, not
  3004. // the outgoing edges of PBI.
  3005. if (HasWeights) {
  3006. uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  3007. uint64_t PredOther = PBIOp ? PredTrueWeight : PredFalseWeight;
  3008. uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  3009. uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  3010. // The weight to PredCommonDest should be PredCommon * SuccTotal.
  3011. // The weight to PredOtherDest should be PredOther * SuccCommon.
  3012. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther),
  3013. PredOther * SuccCommon};
  3014. FitWeights(NewWeights);
  3015. setBranchWeights(NV, NewWeights[0], NewWeights[1]);
  3016. }
  3017. }
  3018. }
  3019. LLVM_DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  3020. LLVM_DEBUG(dbgs() << *PBI->getParent()->getParent());
  3021. // This basic block is probably dead. We know it has at least
  3022. // one fewer predecessor.
  3023. return true;
  3024. }
  3025. // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
  3026. // true or to FalseBB if Cond is false.
  3027. // Takes care of updating the successors and removing the old terminator.
  3028. // Also makes sure not to introduce new successors by assuming that edges to
  3029. // non-successor TrueBBs and FalseBBs aren't reachable.
  3030. static bool SimplifyTerminatorOnSelect(Instruction *OldTerm, Value *Cond,
  3031. BasicBlock *TrueBB, BasicBlock *FalseBB,
  3032. uint32_t TrueWeight,
  3033. uint32_t FalseWeight) {
  3034. // Remove any superfluous successor edges from the CFG.
  3035. // First, figure out which successors to preserve.
  3036. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  3037. // successor.
  3038. BasicBlock *KeepEdge1 = TrueBB;
  3039. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
  3040. // Then remove the rest.
  3041. for (BasicBlock *Succ : successors(OldTerm)) {
  3042. // Make sure only to keep exactly one copy of each edge.
  3043. if (Succ == KeepEdge1)
  3044. KeepEdge1 = nullptr;
  3045. else if (Succ == KeepEdge2)
  3046. KeepEdge2 = nullptr;
  3047. else
  3048. Succ->removePredecessor(OldTerm->getParent(),
  3049. /*KeepOneInputPHIs=*/true);
  3050. }
  3051. IRBuilder<> Builder(OldTerm);
  3052. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  3053. // Insert an appropriate new terminator.
  3054. if (!KeepEdge1 && !KeepEdge2) {
  3055. if (TrueBB == FalseBB)
  3056. // We were only looking for one successor, and it was present.
  3057. // Create an unconditional branch to it.
  3058. Builder.CreateBr(TrueBB);
  3059. else {
  3060. // We found both of the successors we were looking for.
  3061. // Create a conditional branch sharing the condition of the select.
  3062. BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  3063. if (TrueWeight != FalseWeight)
  3064. setBranchWeights(NewBI, TrueWeight, FalseWeight);
  3065. }
  3066. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  3067. // Neither of the selected blocks were successors, so this
  3068. // terminator must be unreachable.
  3069. new UnreachableInst(OldTerm->getContext(), OldTerm);
  3070. } else {
  3071. // One of the selected values was a successor, but the other wasn't.
  3072. // Insert an unconditional branch to the one that was found;
  3073. // the edge to the one that wasn't must be unreachable.
  3074. if (!KeepEdge1)
  3075. // Only TrueBB was found.
  3076. Builder.CreateBr(TrueBB);
  3077. else
  3078. // Only FalseBB was found.
  3079. Builder.CreateBr(FalseBB);
  3080. }
  3081. EraseTerminatorAndDCECond(OldTerm);
  3082. return true;
  3083. }
  3084. // Replaces
  3085. // (switch (select cond, X, Y)) on constant X, Y
  3086. // with a branch - conditional if X and Y lead to distinct BBs,
  3087. // unconditional otherwise.
  3088. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  3089. // Check for constant integer values in the select.
  3090. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  3091. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  3092. if (!TrueVal || !FalseVal)
  3093. return false;
  3094. // Find the relevant condition and destinations.
  3095. Value *Condition = Select->getCondition();
  3096. BasicBlock *TrueBB = SI->findCaseValue(TrueVal)->getCaseSuccessor();
  3097. BasicBlock *FalseBB = SI->findCaseValue(FalseVal)->getCaseSuccessor();
  3098. // Get weight for TrueBB and FalseBB.
  3099. uint32_t TrueWeight = 0, FalseWeight = 0;
  3100. SmallVector<uint64_t, 8> Weights;
  3101. bool HasWeights = HasBranchWeights(SI);
  3102. if (HasWeights) {
  3103. GetBranchWeights(SI, Weights);
  3104. if (Weights.size() == 1 + SI->getNumCases()) {
  3105. TrueWeight =
  3106. (uint32_t)Weights[SI->findCaseValue(TrueVal)->getSuccessorIndex()];
  3107. FalseWeight =
  3108. (uint32_t)Weights[SI->findCaseValue(FalseVal)->getSuccessorIndex()];
  3109. }
  3110. }
  3111. // Perform the actual simplification.
  3112. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB, TrueWeight,
  3113. FalseWeight);
  3114. }
  3115. // Replaces
  3116. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  3117. // blockaddress(@fn, BlockB)))
  3118. // with
  3119. // (br cond, BlockA, BlockB).
  3120. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  3121. // Check that both operands of the select are block addresses.
  3122. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  3123. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  3124. if (!TBA || !FBA)
  3125. return false;
  3126. // Extract the actual blocks.
  3127. BasicBlock *TrueBB = TBA->getBasicBlock();
  3128. BasicBlock *FalseBB = FBA->getBasicBlock();
  3129. // Perform the actual simplification.
  3130. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB, 0,
  3131. 0);
  3132. }
  3133. /// This is called when we find an icmp instruction
  3134. /// (a seteq/setne with a constant) as the only instruction in a
  3135. /// block that ends with an uncond branch. We are looking for a very specific
  3136. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  3137. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  3138. /// default value goes to an uncond block with a seteq in it, we get something
  3139. /// like:
  3140. ///
  3141. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  3142. /// DEFAULT:
  3143. /// %tmp = icmp eq i8 %A, 92
  3144. /// br label %end
  3145. /// end:
  3146. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  3147. ///
  3148. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  3149. /// the PHI, merging the third icmp into the switch.
  3150. bool SimplifyCFGOpt::tryToSimplifyUncondBranchWithICmpInIt(
  3151. ICmpInst *ICI, IRBuilder<> &Builder) {
  3152. BasicBlock *BB = ICI->getParent();
  3153. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  3154. // complex.
  3155. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse())
  3156. return false;
  3157. Value *V = ICI->getOperand(0);
  3158. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  3159. // The pattern we're looking for is where our only predecessor is a switch on
  3160. // 'V' and this block is the default case for the switch. In this case we can
  3161. // fold the compared value into the switch to simplify things.
  3162. BasicBlock *Pred = BB->getSinglePredecessor();
  3163. if (!Pred || !isa<SwitchInst>(Pred->getTerminator()))
  3164. return false;
  3165. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  3166. if (SI->getCondition() != V)
  3167. return false;
  3168. // If BB is reachable on a non-default case, then we simply know the value of
  3169. // V in this block. Substitute it and constant fold the icmp instruction
  3170. // away.
  3171. if (SI->getDefaultDest() != BB) {
  3172. ConstantInt *VVal = SI->findCaseDest(BB);
  3173. assert(VVal && "Should have a unique destination value");
  3174. ICI->setOperand(0, VVal);
  3175. if (Value *V = SimplifyInstruction(ICI, {DL, ICI})) {
  3176. ICI->replaceAllUsesWith(V);
  3177. ICI->eraseFromParent();
  3178. }
  3179. // BB is now empty, so it is likely to simplify away.
  3180. return requestResimplify();
  3181. }
  3182. // Ok, the block is reachable from the default dest. If the constant we're
  3183. // comparing exists in one of the other edges, then we can constant fold ICI
  3184. // and zap it.
  3185. if (SI->findCaseValue(Cst) != SI->case_default()) {
  3186. Value *V;
  3187. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  3188. V = ConstantInt::getFalse(BB->getContext());
  3189. else
  3190. V = ConstantInt::getTrue(BB->getContext());
  3191. ICI->replaceAllUsesWith(V);
  3192. ICI->eraseFromParent();
  3193. // BB is now empty, so it is likely to simplify away.
  3194. return requestResimplify();
  3195. }
  3196. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  3197. // the block.
  3198. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  3199. PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
  3200. if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
  3201. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  3202. return false;
  3203. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  3204. // true in the PHI.
  3205. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  3206. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  3207. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  3208. std::swap(DefaultCst, NewCst);
  3209. // Replace ICI (which is used by the PHI for the default value) with true or
  3210. // false depending on if it is EQ or NE.
  3211. ICI->replaceAllUsesWith(DefaultCst);
  3212. ICI->eraseFromParent();
  3213. // Okay, the switch goes to this block on a default value. Add an edge from
  3214. // the switch to the merge point on the compared value.
  3215. BasicBlock *NewBB =
  3216. BasicBlock::Create(BB->getContext(), "switch.edge", BB->getParent(), BB);
  3217. SmallVector<uint64_t, 8> Weights;
  3218. bool HasWeights = HasBranchWeights(SI);
  3219. if (HasWeights) {
  3220. GetBranchWeights(SI, Weights);
  3221. if (Weights.size() == 1 + SI->getNumCases()) {
  3222. // Split weight for default case to case for "Cst".
  3223. Weights[0] = (Weights[0] + 1) >> 1;
  3224. Weights.push_back(Weights[0]);
  3225. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  3226. setBranchWeights(SI, MDWeights);
  3227. }
  3228. }
  3229. SI->addCase(Cst, NewBB);
  3230. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  3231. Builder.SetInsertPoint(NewBB);
  3232. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  3233. Builder.CreateBr(SuccBlock);
  3234. PHIUse->addIncoming(NewCst, NewBB);
  3235. return true;
  3236. }
  3237. /// The specified branch is a conditional branch.
  3238. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  3239. /// fold it into a switch instruction if so.
  3240. static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
  3241. const DataLayout &DL) {
  3242. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  3243. if (!Cond)
  3244. return false;
  3245. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  3246. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  3247. // 'setne's and'ed together, collect them.
  3248. // Try to gather values from a chain of and/or to be turned into a switch
  3249. ConstantComparesGatherer ConstantCompare(Cond, DL);
  3250. // Unpack the result
  3251. SmallVectorImpl<ConstantInt *> &Values = ConstantCompare.Vals;
  3252. Value *CompVal = ConstantCompare.CompValue;
  3253. unsigned UsedICmps = ConstantCompare.UsedICmps;
  3254. Value *ExtraCase = ConstantCompare.Extra;
  3255. // If we didn't have a multiply compared value, fail.
  3256. if (!CompVal)
  3257. return false;
  3258. // Avoid turning single icmps into a switch.
  3259. if (UsedICmps <= 1)
  3260. return false;
  3261. bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
  3262. // There might be duplicate constants in the list, which the switch
  3263. // instruction can't handle, remove them now.
  3264. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  3265. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  3266. // If Extra was used, we require at least two switch values to do the
  3267. // transformation. A switch with one value is just a conditional branch.
  3268. if (ExtraCase && Values.size() < 2)
  3269. return false;
  3270. // TODO: Preserve branch weight metadata, similarly to how
  3271. // FoldValueComparisonIntoPredecessors preserves it.
  3272. // Figure out which block is which destination.
  3273. BasicBlock *DefaultBB = BI->getSuccessor(1);
  3274. BasicBlock *EdgeBB = BI->getSuccessor(0);
  3275. if (!TrueWhenEqual)
  3276. std::swap(DefaultBB, EdgeBB);
  3277. BasicBlock *BB = BI->getParent();
  3278. LLVM_DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  3279. << " cases into SWITCH. BB is:\n"
  3280. << *BB);
  3281. // If there are any extra values that couldn't be folded into the switch
  3282. // then we evaluate them with an explicit branch first. Split the block
  3283. // right before the condbr to handle it.
  3284. if (ExtraCase) {
  3285. BasicBlock *NewBB =
  3286. BB->splitBasicBlock(BI->getIterator(), "switch.early.test");
  3287. // Remove the uncond branch added to the old block.
  3288. Instruction *OldTI = BB->getTerminator();
  3289. Builder.SetInsertPoint(OldTI);
  3290. if (TrueWhenEqual)
  3291. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  3292. else
  3293. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  3294. OldTI->eraseFromParent();
  3295. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  3296. // for the edge we just added.
  3297. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  3298. LLVM_DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  3299. << "\nEXTRABB = " << *BB);
  3300. BB = NewBB;
  3301. }
  3302. Builder.SetInsertPoint(BI);
  3303. // Convert pointer to int before we switch.
  3304. if (CompVal->getType()->isPointerTy()) {
  3305. CompVal = Builder.CreatePtrToInt(
  3306. CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
  3307. }
  3308. // Create the new switch instruction now.
  3309. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  3310. // Add all of the 'cases' to the switch instruction.
  3311. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  3312. New->addCase(Values[i], EdgeBB);
  3313. // We added edges from PI to the EdgeBB. As such, if there were any
  3314. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  3315. // the number of edges added.
  3316. for (BasicBlock::iterator BBI = EdgeBB->begin(); isa<PHINode>(BBI); ++BBI) {
  3317. PHINode *PN = cast<PHINode>(BBI);
  3318. Value *InVal = PN->getIncomingValueForBlock(BB);
  3319. for (unsigned i = 0, e = Values.size() - 1; i != e; ++i)
  3320. PN->addIncoming(InVal, BB);
  3321. }
  3322. // Erase the old branch instruction.
  3323. EraseTerminatorAndDCECond(BI);
  3324. LLVM_DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  3325. return true;
  3326. }
  3327. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  3328. if (isa<PHINode>(RI->getValue()))
  3329. return SimplifyCommonResume(RI);
  3330. else if (isa<LandingPadInst>(RI->getParent()->getFirstNonPHI()) &&
  3331. RI->getValue() == RI->getParent()->getFirstNonPHI())
  3332. // The resume must unwind the exception that caused control to branch here.
  3333. return SimplifySingleResume(RI);
  3334. return false;
  3335. }
  3336. // Simplify resume that is shared by several landing pads (phi of landing pad).
  3337. bool SimplifyCFGOpt::SimplifyCommonResume(ResumeInst *RI) {
  3338. BasicBlock *BB = RI->getParent();
  3339. // Check that there are no other instructions except for debug intrinsics
  3340. // between the phi of landing pads (RI->getValue()) and resume instruction.
  3341. BasicBlock::iterator I = cast<Instruction>(RI->getValue())->getIterator(),
  3342. E = RI->getIterator();
  3343. while (++I != E)
  3344. if (!isa<DbgInfoIntrinsic>(I))
  3345. return false;
  3346. SmallSetVector<BasicBlock *, 4> TrivialUnwindBlocks;
  3347. auto *PhiLPInst = cast<PHINode>(RI->getValue());
  3348. // Check incoming blocks to see if any of them are trivial.
  3349. for (unsigned Idx = 0, End = PhiLPInst->getNumIncomingValues(); Idx != End;
  3350. Idx++) {
  3351. auto *IncomingBB = PhiLPInst->getIncomingBlock(Idx);
  3352. auto *IncomingValue = PhiLPInst->getIncomingValue(Idx);
  3353. // If the block has other successors, we can not delete it because
  3354. // it has other dependents.
  3355. if (IncomingBB->getUniqueSuccessor() != BB)
  3356. continue;
  3357. auto *LandingPad = dyn_cast<LandingPadInst>(IncomingBB->getFirstNonPHI());
  3358. // Not the landing pad that caused the control to branch here.
  3359. if (IncomingValue != LandingPad)
  3360. continue;
  3361. bool isTrivial = true;
  3362. I = IncomingBB->getFirstNonPHI()->getIterator();
  3363. E = IncomingBB->getTerminator()->getIterator();
  3364. while (++I != E)
  3365. if (!isa<DbgInfoIntrinsic>(I)) {
  3366. isTrivial = false;
  3367. break;
  3368. }
  3369. if (isTrivial)
  3370. TrivialUnwindBlocks.insert(IncomingBB);
  3371. }
  3372. // If no trivial unwind blocks, don't do any simplifications.
  3373. if (TrivialUnwindBlocks.empty())
  3374. return false;
  3375. // Turn all invokes that unwind here into calls.
  3376. for (auto *TrivialBB : TrivialUnwindBlocks) {
  3377. // Blocks that will be simplified should be removed from the phi node.
  3378. // Note there could be multiple edges to the resume block, and we need
  3379. // to remove them all.
  3380. while (PhiLPInst->getBasicBlockIndex(TrivialBB) != -1)
  3381. BB->removePredecessor(TrivialBB, true);
  3382. for (pred_iterator PI = pred_begin(TrivialBB), PE = pred_end(TrivialBB);
  3383. PI != PE;) {
  3384. BasicBlock *Pred = *PI++;
  3385. removeUnwindEdge(Pred);
  3386. }
  3387. // In each SimplifyCFG run, only the current processed block can be erased.
  3388. // Otherwise, it will break the iteration of SimplifyCFG pass. So instead
  3389. // of erasing TrivialBB, we only remove the branch to the common resume
  3390. // block so that we can later erase the resume block since it has no
  3391. // predecessors.
  3392. TrivialBB->getTerminator()->eraseFromParent();
  3393. new UnreachableInst(RI->getContext(), TrivialBB);
  3394. }
  3395. // Delete the resume block if all its predecessors have been removed.
  3396. if (pred_empty(BB))
  3397. BB->eraseFromParent();
  3398. return !TrivialUnwindBlocks.empty();
  3399. }
  3400. // Simplify resume that is only used by a single (non-phi) landing pad.
  3401. bool SimplifyCFGOpt::SimplifySingleResume(ResumeInst *RI) {
  3402. BasicBlock *BB = RI->getParent();
  3403. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  3404. assert(RI->getValue() == LPInst &&
  3405. "Resume must unwind the exception that caused control to here");
  3406. // Check that there are no other instructions except for debug intrinsics.
  3407. BasicBlock::iterator I = LPInst->getIterator(), E = RI->getIterator();
  3408. while (++I != E)
  3409. if (!isa<DbgInfoIntrinsic>(I))
  3410. return false;
  3411. // Turn all invokes that unwind here into calls and delete the basic block.
  3412. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  3413. BasicBlock *Pred = *PI++;
  3414. removeUnwindEdge(Pred);
  3415. }
  3416. // The landingpad is now unreachable. Zap it.
  3417. if (LoopHeaders)
  3418. LoopHeaders->erase(BB);
  3419. BB->eraseFromParent();
  3420. return true;
  3421. }
  3422. static bool removeEmptyCleanup(CleanupReturnInst *RI) {
  3423. // If this is a trivial cleanup pad that executes no instructions, it can be
  3424. // eliminated. If the cleanup pad continues to the caller, any predecessor
  3425. // that is an EH pad will be updated to continue to the caller and any
  3426. // predecessor that terminates with an invoke instruction will have its invoke
  3427. // instruction converted to a call instruction. If the cleanup pad being
  3428. // simplified does not continue to the caller, each predecessor will be
  3429. // updated to continue to the unwind destination of the cleanup pad being
  3430. // simplified.
  3431. BasicBlock *BB = RI->getParent();
  3432. CleanupPadInst *CPInst = RI->getCleanupPad();
  3433. if (CPInst->getParent() != BB)
  3434. // This isn't an empty cleanup.
  3435. return false;
  3436. // We cannot kill the pad if it has multiple uses. This typically arises
  3437. // from unreachable basic blocks.
  3438. if (!CPInst->hasOneUse())
  3439. return false;
  3440. // Check that there are no other instructions except for benign intrinsics.
  3441. BasicBlock::iterator I = CPInst->getIterator(), E = RI->getIterator();
  3442. while (++I != E) {
  3443. auto *II = dyn_cast<IntrinsicInst>(I);
  3444. if (!II)
  3445. return false;
  3446. Intrinsic::ID IntrinsicID = II->getIntrinsicID();
  3447. switch (IntrinsicID) {
  3448. case Intrinsic::dbg_declare:
  3449. case Intrinsic::dbg_value:
  3450. case Intrinsic::dbg_label:
  3451. case Intrinsic::lifetime_end:
  3452. break;
  3453. default:
  3454. return false;
  3455. }
  3456. }
  3457. // If the cleanup return we are simplifying unwinds to the caller, this will
  3458. // set UnwindDest to nullptr.
  3459. BasicBlock *UnwindDest = RI->getUnwindDest();
  3460. Instruction *DestEHPad = UnwindDest ? UnwindDest->getFirstNonPHI() : nullptr;
  3461. // We're about to remove BB from the control flow. Before we do, sink any
  3462. // PHINodes into the unwind destination. Doing this before changing the
  3463. // control flow avoids some potentially slow checks, since we can currently
  3464. // be certain that UnwindDest and BB have no common predecessors (since they
  3465. // are both EH pads).
  3466. if (UnwindDest) {
  3467. // First, go through the PHI nodes in UnwindDest and update any nodes that
  3468. // reference the block we are removing
  3469. for (BasicBlock::iterator I = UnwindDest->begin(),
  3470. IE = DestEHPad->getIterator();
  3471. I != IE; ++I) {
  3472. PHINode *DestPN = cast<PHINode>(I);
  3473. int Idx = DestPN->getBasicBlockIndex(BB);
  3474. // Since BB unwinds to UnwindDest, it has to be in the PHI node.
  3475. assert(Idx != -1);
  3476. // This PHI node has an incoming value that corresponds to a control
  3477. // path through the cleanup pad we are removing. If the incoming
  3478. // value is in the cleanup pad, it must be a PHINode (because we
  3479. // verified above that the block is otherwise empty). Otherwise, the
  3480. // value is either a constant or a value that dominates the cleanup
  3481. // pad being removed.
  3482. //
  3483. // Because BB and UnwindDest are both EH pads, all of their
  3484. // predecessors must unwind to these blocks, and since no instruction
  3485. // can have multiple unwind destinations, there will be no overlap in
  3486. // incoming blocks between SrcPN and DestPN.
  3487. Value *SrcVal = DestPN->getIncomingValue(Idx);
  3488. PHINode *SrcPN = dyn_cast<PHINode>(SrcVal);
  3489. // Remove the entry for the block we are deleting.
  3490. DestPN->removeIncomingValue(Idx, false);
  3491. if (SrcPN && SrcPN->getParent() == BB) {
  3492. // If the incoming value was a PHI node in the cleanup pad we are
  3493. // removing, we need to merge that PHI node's incoming values into
  3494. // DestPN.
  3495. for (unsigned SrcIdx = 0, SrcE = SrcPN->getNumIncomingValues();
  3496. SrcIdx != SrcE; ++SrcIdx) {
  3497. DestPN->addIncoming(SrcPN->getIncomingValue(SrcIdx),
  3498. SrcPN->getIncomingBlock(SrcIdx));
  3499. }
  3500. } else {
  3501. // Otherwise, the incoming value came from above BB and
  3502. // so we can just reuse it. We must associate all of BB's
  3503. // predecessors with this value.
  3504. for (auto *pred : predecessors(BB)) {
  3505. DestPN->addIncoming(SrcVal, pred);
  3506. }
  3507. }
  3508. }
  3509. // Sink any remaining PHI nodes directly into UnwindDest.
  3510. Instruction *InsertPt = DestEHPad;
  3511. for (BasicBlock::iterator I = BB->begin(),
  3512. IE = BB->getFirstNonPHI()->getIterator();
  3513. I != IE;) {
  3514. // The iterator must be incremented here because the instructions are
  3515. // being moved to another block.
  3516. PHINode *PN = cast<PHINode>(I++);
  3517. if (PN->use_empty())
  3518. // If the PHI node has no uses, just leave it. It will be erased
  3519. // when we erase BB below.
  3520. continue;
  3521. // Otherwise, sink this PHI node into UnwindDest.
  3522. // Any predecessors to UnwindDest which are not already represented
  3523. // must be back edges which inherit the value from the path through
  3524. // BB. In this case, the PHI value must reference itself.
  3525. for (auto *pred : predecessors(UnwindDest))
  3526. if (pred != BB)
  3527. PN->addIncoming(PN, pred);
  3528. PN->moveBefore(InsertPt);
  3529. }
  3530. }
  3531. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  3532. // The iterator must be updated here because we are removing this pred.
  3533. BasicBlock *PredBB = *PI++;
  3534. if (UnwindDest == nullptr) {
  3535. removeUnwindEdge(PredBB);
  3536. } else {
  3537. Instruction *TI = PredBB->getTerminator();
  3538. TI->replaceUsesOfWith(BB, UnwindDest);
  3539. }
  3540. }
  3541. // The cleanup pad is now unreachable. Zap it.
  3542. BB->eraseFromParent();
  3543. return true;
  3544. }
  3545. // Try to merge two cleanuppads together.
  3546. static bool mergeCleanupPad(CleanupReturnInst *RI) {
  3547. // Skip any cleanuprets which unwind to caller, there is nothing to merge
  3548. // with.
  3549. BasicBlock *UnwindDest = RI->getUnwindDest();
  3550. if (!UnwindDest)
  3551. return false;
  3552. // This cleanupret isn't the only predecessor of this cleanuppad, it wouldn't
  3553. // be safe to merge without code duplication.
  3554. if (UnwindDest->getSinglePredecessor() != RI->getParent())
  3555. return false;
  3556. // Verify that our cleanuppad's unwind destination is another cleanuppad.
  3557. auto *SuccessorCleanupPad = dyn_cast<CleanupPadInst>(&UnwindDest->front());
  3558. if (!SuccessorCleanupPad)
  3559. return false;
  3560. CleanupPadInst *PredecessorCleanupPad = RI->getCleanupPad();
  3561. // Replace any uses of the successor cleanupad with the predecessor pad
  3562. // The only cleanuppad uses should be this cleanupret, it's cleanupret and
  3563. // funclet bundle operands.
  3564. SuccessorCleanupPad->replaceAllUsesWith(PredecessorCleanupPad);
  3565. // Remove the old cleanuppad.
  3566. SuccessorCleanupPad->eraseFromParent();
  3567. // Now, we simply replace the cleanupret with a branch to the unwind
  3568. // destination.
  3569. BranchInst::Create(UnwindDest, RI->getParent());
  3570. RI->eraseFromParent();
  3571. return true;
  3572. }
  3573. bool SimplifyCFGOpt::SimplifyCleanupReturn(CleanupReturnInst *RI) {
  3574. // It is possible to transiantly have an undef cleanuppad operand because we
  3575. // have deleted some, but not all, dead blocks.
  3576. // Eventually, this block will be deleted.
  3577. if (isa<UndefValue>(RI->getOperand(0)))
  3578. return false;
  3579. if (mergeCleanupPad(RI))
  3580. return true;
  3581. if (removeEmptyCleanup(RI))
  3582. return true;
  3583. return false;
  3584. }
  3585. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  3586. BasicBlock *BB = RI->getParent();
  3587. if (!BB->getFirstNonPHIOrDbg()->isTerminator())
  3588. return false;
  3589. // Find predecessors that end with branches.
  3590. SmallVector<BasicBlock *, 8> UncondBranchPreds;
  3591. SmallVector<BranchInst *, 8> CondBranchPreds;
  3592. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  3593. BasicBlock *P = *PI;
  3594. Instruction *PTI = P->getTerminator();
  3595. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  3596. if (BI->isUnconditional())
  3597. UncondBranchPreds.push_back(P);
  3598. else
  3599. CondBranchPreds.push_back(BI);
  3600. }
  3601. }
  3602. // If we found some, do the transformation!
  3603. if (!UncondBranchPreds.empty() && DupRet) {
  3604. while (!UncondBranchPreds.empty()) {
  3605. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  3606. LLVM_DEBUG(dbgs() << "FOLDING: " << *BB
  3607. << "INTO UNCOND BRANCH PRED: " << *Pred);
  3608. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  3609. }
  3610. // If we eliminated all predecessors of the block, delete the block now.
  3611. if (pred_empty(BB)) {
  3612. // We know there are no successors, so just nuke the block.
  3613. if (LoopHeaders)
  3614. LoopHeaders->erase(BB);
  3615. BB->eraseFromParent();
  3616. }
  3617. return true;
  3618. }
  3619. // Check out all of the conditional branches going to this return
  3620. // instruction. If any of them just select between returns, change the
  3621. // branch itself into a select/return pair.
  3622. while (!CondBranchPreds.empty()) {
  3623. BranchInst *BI = CondBranchPreds.pop_back_val();
  3624. // Check to see if the non-BB successor is also a return block.
  3625. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  3626. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  3627. SimplifyCondBranchToTwoReturns(BI, Builder))
  3628. return true;
  3629. }
  3630. return false;
  3631. }
  3632. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  3633. BasicBlock *BB = UI->getParent();
  3634. bool Changed = false;
  3635. // If there are any instructions immediately before the unreachable that can
  3636. // be removed, do so.
  3637. while (UI->getIterator() != BB->begin()) {
  3638. BasicBlock::iterator BBI = UI->getIterator();
  3639. --BBI;
  3640. // Do not delete instructions that can have side effects which might cause
  3641. // the unreachable to not be reachable; specifically, calls and volatile
  3642. // operations may have this effect.
  3643. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI))
  3644. break;
  3645. if (BBI->mayHaveSideEffects()) {
  3646. if (auto *SI = dyn_cast<StoreInst>(BBI)) {
  3647. if (SI->isVolatile())
  3648. break;
  3649. } else if (auto *LI = dyn_cast<LoadInst>(BBI)) {
  3650. if (LI->isVolatile())
  3651. break;
  3652. } else if (auto *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  3653. if (RMWI->isVolatile())
  3654. break;
  3655. } else if (auto *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  3656. if (CXI->isVolatile())
  3657. break;
  3658. } else if (isa<CatchPadInst>(BBI)) {
  3659. // A catchpad may invoke exception object constructors and such, which
  3660. // in some languages can be arbitrary code, so be conservative by
  3661. // default.
  3662. // For CoreCLR, it just involves a type test, so can be removed.
  3663. if (classifyEHPersonality(BB->getParent()->getPersonalityFn()) !=
  3664. EHPersonality::CoreCLR)
  3665. break;
  3666. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  3667. !isa<LandingPadInst>(BBI)) {
  3668. break;
  3669. }
  3670. // Note that deleting LandingPad's here is in fact okay, although it
  3671. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  3672. // all the predecessors of this block will be the unwind edges of Invokes,
  3673. // and we can therefore guarantee this block will be erased.
  3674. }
  3675. // Delete this instruction (any uses are guaranteed to be dead)
  3676. if (!BBI->use_empty())
  3677. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  3678. BBI->eraseFromParent();
  3679. Changed = true;
  3680. }
  3681. // If the unreachable instruction is the first in the block, take a gander
  3682. // at all of the predecessors of this instruction, and simplify them.
  3683. if (&BB->front() != UI)
  3684. return Changed;
  3685. SmallVector<BasicBlock *, 8> Preds(pred_begin(BB), pred_end(BB));
  3686. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  3687. Instruction *TI = Preds[i]->getTerminator();
  3688. IRBuilder<> Builder(TI);
  3689. if (auto *BI = dyn_cast<BranchInst>(TI)) {
  3690. if (BI->isUnconditional()) {
  3691. if (BI->getSuccessor(0) == BB) {
  3692. new UnreachableInst(TI->getContext(), TI);
  3693. TI->eraseFromParent();
  3694. Changed = true;
  3695. }
  3696. } else {
  3697. if (BI->getSuccessor(0) == BB) {
  3698. Builder.CreateBr(BI->getSuccessor(1));
  3699. EraseTerminatorAndDCECond(BI);
  3700. } else if (BI->getSuccessor(1) == BB) {
  3701. Builder.CreateBr(BI->getSuccessor(0));
  3702. EraseTerminatorAndDCECond(BI);
  3703. Changed = true;
  3704. }
  3705. }
  3706. } else if (auto *SI = dyn_cast<SwitchInst>(TI)) {
  3707. for (auto i = SI->case_begin(), e = SI->case_end(); i != e;) {
  3708. if (i->getCaseSuccessor() != BB) {
  3709. ++i;
  3710. continue;
  3711. }
  3712. BB->removePredecessor(SI->getParent());
  3713. i = SI->removeCase(i);
  3714. e = SI->case_end();
  3715. Changed = true;
  3716. }
  3717. } else if (auto *II = dyn_cast<InvokeInst>(TI)) {
  3718. if (II->getUnwindDest() == BB) {
  3719. removeUnwindEdge(TI->getParent());
  3720. Changed = true;
  3721. }
  3722. } else if (auto *CSI = dyn_cast<CatchSwitchInst>(TI)) {
  3723. if (CSI->getUnwindDest() == BB) {
  3724. removeUnwindEdge(TI->getParent());
  3725. Changed = true;
  3726. continue;
  3727. }
  3728. for (CatchSwitchInst::handler_iterator I = CSI->handler_begin(),
  3729. E = CSI->handler_end();
  3730. I != E; ++I) {
  3731. if (*I == BB) {
  3732. CSI->removeHandler(I);
  3733. --I;
  3734. --E;
  3735. Changed = true;
  3736. }
  3737. }
  3738. if (CSI->getNumHandlers() == 0) {
  3739. BasicBlock *CatchSwitchBB = CSI->getParent();
  3740. if (CSI->hasUnwindDest()) {
  3741. // Redirect preds to the unwind dest
  3742. CatchSwitchBB->replaceAllUsesWith(CSI->getUnwindDest());
  3743. } else {
  3744. // Rewrite all preds to unwind to caller (or from invoke to call).
  3745. SmallVector<BasicBlock *, 8> EHPreds(predecessors(CatchSwitchBB));
  3746. for (BasicBlock *EHPred : EHPreds)
  3747. removeUnwindEdge(EHPred);
  3748. }
  3749. // The catchswitch is no longer reachable.
  3750. new UnreachableInst(CSI->getContext(), CSI);
  3751. CSI->eraseFromParent();
  3752. Changed = true;
  3753. }
  3754. } else if (isa<CleanupReturnInst>(TI)) {
  3755. new UnreachableInst(TI->getContext(), TI);
  3756. TI->eraseFromParent();
  3757. Changed = true;
  3758. }
  3759. }
  3760. // If this block is now dead, remove it.
  3761. if (pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) {
  3762. // We know there are no successors, so just nuke the block.
  3763. if (LoopHeaders)
  3764. LoopHeaders->erase(BB);
  3765. BB->eraseFromParent();
  3766. return true;
  3767. }
  3768. return Changed;
  3769. }
  3770. static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
  3771. assert(Cases.size() >= 1);
  3772. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  3773. for (size_t I = 1, E = Cases.size(); I != E; ++I) {
  3774. if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
  3775. return false;
  3776. }
  3777. return true;
  3778. }
  3779. /// Turn a switch with two reachable destinations into an integer range
  3780. /// comparison and branch.
  3781. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  3782. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  3783. bool HasDefault =
  3784. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3785. // Partition the cases into two sets with different destinations.
  3786. BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
  3787. BasicBlock *DestB = nullptr;
  3788. SmallVector<ConstantInt *, 16> CasesA;
  3789. SmallVector<ConstantInt *, 16> CasesB;
  3790. for (auto Case : SI->cases()) {
  3791. BasicBlock *Dest = Case.getCaseSuccessor();
  3792. if (!DestA)
  3793. DestA = Dest;
  3794. if (Dest == DestA) {
  3795. CasesA.push_back(Case.getCaseValue());
  3796. continue;
  3797. }
  3798. if (!DestB)
  3799. DestB = Dest;
  3800. if (Dest == DestB) {
  3801. CasesB.push_back(Case.getCaseValue());
  3802. continue;
  3803. }
  3804. return false; // More than two destinations.
  3805. }
  3806. assert(DestA && DestB &&
  3807. "Single-destination switch should have been folded.");
  3808. assert(DestA != DestB);
  3809. assert(DestB != SI->getDefaultDest());
  3810. assert(!CasesB.empty() && "There must be non-default cases.");
  3811. assert(!CasesA.empty() || HasDefault);
  3812. // Figure out if one of the sets of cases form a contiguous range.
  3813. SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
  3814. BasicBlock *ContiguousDest = nullptr;
  3815. BasicBlock *OtherDest = nullptr;
  3816. if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
  3817. ContiguousCases = &CasesA;
  3818. ContiguousDest = DestA;
  3819. OtherDest = DestB;
  3820. } else if (CasesAreContiguous(CasesB)) {
  3821. ContiguousCases = &CasesB;
  3822. ContiguousDest = DestB;
  3823. OtherDest = DestA;
  3824. } else
  3825. return false;
  3826. // Start building the compare and branch.
  3827. Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
  3828. Constant *NumCases =
  3829. ConstantInt::get(Offset->getType(), ContiguousCases->size());
  3830. Value *Sub = SI->getCondition();
  3831. if (!Offset->isNullValue())
  3832. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
  3833. Value *Cmp;
  3834. // If NumCases overflowed, then all possible values jump to the successor.
  3835. if (NumCases->isNullValue() && !ContiguousCases->empty())
  3836. Cmp = ConstantInt::getTrue(SI->getContext());
  3837. else
  3838. Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  3839. BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
  3840. // Update weight for the newly-created conditional branch.
  3841. if (HasBranchWeights(SI)) {
  3842. SmallVector<uint64_t, 8> Weights;
  3843. GetBranchWeights(SI, Weights);
  3844. if (Weights.size() == 1 + SI->getNumCases()) {
  3845. uint64_t TrueWeight = 0;
  3846. uint64_t FalseWeight = 0;
  3847. for (size_t I = 0, E = Weights.size(); I != E; ++I) {
  3848. if (SI->getSuccessor(I) == ContiguousDest)
  3849. TrueWeight += Weights[I];
  3850. else
  3851. FalseWeight += Weights[I];
  3852. }
  3853. while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
  3854. TrueWeight /= 2;
  3855. FalseWeight /= 2;
  3856. }
  3857. setBranchWeights(NewBI, TrueWeight, FalseWeight);
  3858. }
  3859. }
  3860. // Prune obsolete incoming values off the successors' PHI nodes.
  3861. for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
  3862. unsigned PreviousEdges = ContiguousCases->size();
  3863. if (ContiguousDest == SI->getDefaultDest())
  3864. ++PreviousEdges;
  3865. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  3866. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  3867. }
  3868. for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
  3869. unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
  3870. if (OtherDest == SI->getDefaultDest())
  3871. ++PreviousEdges;
  3872. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  3873. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  3874. }
  3875. // Drop the switch.
  3876. SI->eraseFromParent();
  3877. return true;
  3878. }
  3879. /// Compute masked bits for the condition of a switch
  3880. /// and use it to remove dead cases.
  3881. static bool eliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
  3882. const DataLayout &DL) {
  3883. Value *Cond = SI->getCondition();
  3884. unsigned Bits = Cond->getType()->getIntegerBitWidth();
  3885. KnownBits Known = computeKnownBits(Cond, DL, 0, AC, SI);
  3886. // We can also eliminate cases by determining that their values are outside of
  3887. // the limited range of the condition based on how many significant (non-sign)
  3888. // bits are in the condition value.
  3889. unsigned ExtraSignBits = ComputeNumSignBits(Cond, DL, 0, AC, SI) - 1;
  3890. unsigned MaxSignificantBitsInCond = Bits - ExtraSignBits;
  3891. // Gather dead cases.
  3892. SmallVector<ConstantInt *, 8> DeadCases;
  3893. for (auto &Case : SI->cases()) {
  3894. const APInt &CaseVal = Case.getCaseValue()->getValue();
  3895. if (Known.Zero.intersects(CaseVal) || !Known.One.isSubsetOf(CaseVal) ||
  3896. (CaseVal.getMinSignedBits() > MaxSignificantBitsInCond)) {
  3897. DeadCases.push_back(Case.getCaseValue());
  3898. LLVM_DEBUG(dbgs() << "SimplifyCFG: switch case " << CaseVal
  3899. << " is dead.\n");
  3900. }
  3901. }
  3902. // If we can prove that the cases must cover all possible values, the
  3903. // default destination becomes dead and we can remove it. If we know some
  3904. // of the bits in the value, we can use that to more precisely compute the
  3905. // number of possible unique case values.
  3906. bool HasDefault =
  3907. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3908. const unsigned NumUnknownBits =
  3909. Bits - (Known.Zero | Known.One).countPopulation();
  3910. assert(NumUnknownBits <= Bits);
  3911. if (HasDefault && DeadCases.empty() &&
  3912. NumUnknownBits < 64 /* avoid overflow */ &&
  3913. SI->getNumCases() == (1ULL << NumUnknownBits)) {
  3914. LLVM_DEBUG(dbgs() << "SimplifyCFG: switch default is dead.\n");
  3915. BasicBlock *NewDefault =
  3916. SplitBlockPredecessors(SI->getDefaultDest(), SI->getParent(), "");
  3917. SI->setDefaultDest(&*NewDefault);
  3918. SplitBlock(&*NewDefault, &NewDefault->front());
  3919. auto *OldTI = NewDefault->getTerminator();
  3920. new UnreachableInst(SI->getContext(), OldTI);
  3921. EraseTerminatorAndDCECond(OldTI);
  3922. return true;
  3923. }
  3924. SmallVector<uint64_t, 8> Weights;
  3925. bool HasWeight = HasBranchWeights(SI);
  3926. if (HasWeight) {
  3927. GetBranchWeights(SI, Weights);
  3928. HasWeight = (Weights.size() == 1 + SI->getNumCases());
  3929. }
  3930. // Remove dead cases from the switch.
  3931. for (ConstantInt *DeadCase : DeadCases) {
  3932. SwitchInst::CaseIt CaseI = SI->findCaseValue(DeadCase);
  3933. assert(CaseI != SI->case_default() &&
  3934. "Case was not found. Probably mistake in DeadCases forming.");
  3935. if (HasWeight) {
  3936. std::swap(Weights[CaseI->getCaseIndex() + 1], Weights.back());
  3937. Weights.pop_back();
  3938. }
  3939. // Prune unused values from PHI nodes.
  3940. CaseI->getCaseSuccessor()->removePredecessor(SI->getParent());
  3941. SI->removeCase(CaseI);
  3942. }
  3943. if (HasWeight && Weights.size() >= 2) {
  3944. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  3945. setBranchWeights(SI, MDWeights);
  3946. }
  3947. return !DeadCases.empty();
  3948. }
  3949. /// If BB would be eligible for simplification by
  3950. /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  3951. /// by an unconditional branch), look at the phi node for BB in the successor
  3952. /// block and see if the incoming value is equal to CaseValue. If so, return
  3953. /// the phi node, and set PhiIndex to BB's index in the phi node.
  3954. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  3955. BasicBlock *BB, int *PhiIndex) {
  3956. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  3957. return nullptr; // BB must be empty to be a candidate for simplification.
  3958. if (!BB->getSinglePredecessor())
  3959. return nullptr; // BB must be dominated by the switch.
  3960. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  3961. if (!Branch || !Branch->isUnconditional())
  3962. return nullptr; // Terminator must be unconditional branch.
  3963. BasicBlock *Succ = Branch->getSuccessor(0);
  3964. for (PHINode &PHI : Succ->phis()) {
  3965. int Idx = PHI.getBasicBlockIndex(BB);
  3966. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  3967. Value *InValue = PHI.getIncomingValue(Idx);
  3968. if (InValue != CaseValue)
  3969. continue;
  3970. *PhiIndex = Idx;
  3971. return &PHI;
  3972. }
  3973. return nullptr;
  3974. }
  3975. /// Try to forward the condition of a switch instruction to a phi node
  3976. /// dominated by the switch, if that would mean that some of the destination
  3977. /// blocks of the switch can be folded away. Return true if a change is made.
  3978. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  3979. using ForwardingNodesMap = DenseMap<PHINode *, SmallVector<int, 4>>;
  3980. ForwardingNodesMap ForwardingNodes;
  3981. BasicBlock *SwitchBlock = SI->getParent();
  3982. bool Changed = false;
  3983. for (auto &Case : SI->cases()) {
  3984. ConstantInt *CaseValue = Case.getCaseValue();
  3985. BasicBlock *CaseDest = Case.getCaseSuccessor();
  3986. // Replace phi operands in successor blocks that are using the constant case
  3987. // value rather than the switch condition variable:
  3988. // switchbb:
  3989. // switch i32 %x, label %default [
  3990. // i32 17, label %succ
  3991. // ...
  3992. // succ:
  3993. // %r = phi i32 ... [ 17, %switchbb ] ...
  3994. // -->
  3995. // %r = phi i32 ... [ %x, %switchbb ] ...
  3996. for (PHINode &Phi : CaseDest->phis()) {
  3997. // This only works if there is exactly 1 incoming edge from the switch to
  3998. // a phi. If there is >1, that means multiple cases of the switch map to 1
  3999. // value in the phi, and that phi value is not the switch condition. Thus,
  4000. // this transform would not make sense (the phi would be invalid because
  4001. // a phi can't have different incoming values from the same block).
  4002. int SwitchBBIdx = Phi.getBasicBlockIndex(SwitchBlock);
  4003. if (Phi.getIncomingValue(SwitchBBIdx) == CaseValue &&
  4004. count(Phi.blocks(), SwitchBlock) == 1) {
  4005. Phi.setIncomingValue(SwitchBBIdx, SI->getCondition());
  4006. Changed = true;
  4007. }
  4008. }
  4009. // Collect phi nodes that are indirectly using this switch's case constants.
  4010. int PhiIdx;
  4011. if (auto *Phi = FindPHIForConditionForwarding(CaseValue, CaseDest, &PhiIdx))
  4012. ForwardingNodes[Phi].push_back(PhiIdx);
  4013. }
  4014. for (auto &ForwardingNode : ForwardingNodes) {
  4015. PHINode *Phi = ForwardingNode.first;
  4016. SmallVectorImpl<int> &Indexes = ForwardingNode.second;
  4017. if (Indexes.size() < 2)
  4018. continue;
  4019. for (int Index : Indexes)
  4020. Phi->setIncomingValue(Index, SI->getCondition());
  4021. Changed = true;
  4022. }
  4023. return Changed;
  4024. }
  4025. /// Return true if the backend will be able to handle
  4026. /// initializing an array of constants like C.
  4027. static bool ValidLookupTableConstant(Constant *C, const TargetTransformInfo &TTI) {
  4028. if (C->isThreadDependent())
  4029. return false;
  4030. if (C->isDLLImportDependent())
  4031. return false;
  4032. if (!isa<ConstantFP>(C) && !isa<ConstantInt>(C) &&
  4033. !isa<ConstantPointerNull>(C) && !isa<GlobalValue>(C) &&
  4034. !isa<UndefValue>(C) && !isa<ConstantExpr>(C))
  4035. return false;
  4036. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C)) {
  4037. if (!CE->isGEPWithNoNotionalOverIndexing())
  4038. return false;
  4039. if (!ValidLookupTableConstant(CE->getOperand(0), TTI))
  4040. return false;
  4041. }
  4042. if (!TTI.shouldBuildLookupTablesForConstant(C))
  4043. return false;
  4044. return true;
  4045. }
  4046. /// If V is a Constant, return it. Otherwise, try to look up
  4047. /// its constant value in ConstantPool, returning 0 if it's not there.
  4048. static Constant *
  4049. LookupConstant(Value *V,
  4050. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  4051. if (Constant *C = dyn_cast<Constant>(V))
  4052. return C;
  4053. return ConstantPool.lookup(V);
  4054. }
  4055. /// Try to fold instruction I into a constant. This works for
  4056. /// simple instructions such as binary operations where both operands are
  4057. /// constant or can be replaced by constants from the ConstantPool. Returns the
  4058. /// resulting constant on success, 0 otherwise.
  4059. static Constant *
  4060. ConstantFold(Instruction *I, const DataLayout &DL,
  4061. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  4062. if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  4063. Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
  4064. if (!A)
  4065. return nullptr;
  4066. if (A->isAllOnesValue())
  4067. return LookupConstant(Select->getTrueValue(), ConstantPool);
  4068. if (A->isNullValue())
  4069. return LookupConstant(Select->getFalseValue(), ConstantPool);
  4070. return nullptr;
  4071. }
  4072. SmallVector<Constant *, 4> COps;
  4073. for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
  4074. if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
  4075. COps.push_back(A);
  4076. else
  4077. return nullptr;
  4078. }
  4079. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  4080. return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
  4081. COps[1], DL);
  4082. }
  4083. return ConstantFoldInstOperands(I, COps, DL);
  4084. }
  4085. /// Try to determine the resulting constant values in phi nodes
  4086. /// at the common destination basic block, *CommonDest, for one of the case
  4087. /// destionations CaseDest corresponding to value CaseVal (0 for the default
  4088. /// case), of a switch instruction SI.
  4089. static bool
  4090. GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
  4091. BasicBlock **CommonDest,
  4092. SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
  4093. const DataLayout &DL, const TargetTransformInfo &TTI) {
  4094. // The block from which we enter the common destination.
  4095. BasicBlock *Pred = SI->getParent();
  4096. // If CaseDest is empty except for some side-effect free instructions through
  4097. // which we can constant-propagate the CaseVal, continue to its successor.
  4098. SmallDenseMap<Value *, Constant *> ConstantPool;
  4099. ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
  4100. for (Instruction &I :CaseDest->instructionsWithoutDebug()) {
  4101. if (I.isTerminator()) {
  4102. // If the terminator is a simple branch, continue to the next block.
  4103. if (I.getNumSuccessors() != 1 || I.isExceptionalTerminator())
  4104. return false;
  4105. Pred = CaseDest;
  4106. CaseDest = I.getSuccessor(0);
  4107. } else if (Constant *C = ConstantFold(&I, DL, ConstantPool)) {
  4108. // Instruction is side-effect free and constant.
  4109. // If the instruction has uses outside this block or a phi node slot for
  4110. // the block, it is not safe to bypass the instruction since it would then
  4111. // no longer dominate all its uses.
  4112. for (auto &Use : I.uses()) {
  4113. User *User = Use.getUser();
  4114. if (Instruction *I = dyn_cast<Instruction>(User))
  4115. if (I->getParent() == CaseDest)
  4116. continue;
  4117. if (PHINode *Phi = dyn_cast<PHINode>(User))
  4118. if (Phi->getIncomingBlock(Use) == CaseDest)
  4119. continue;
  4120. return false;
  4121. }
  4122. ConstantPool.insert(std::make_pair(&I, C));
  4123. } else {
  4124. break;
  4125. }
  4126. }
  4127. // If we did not have a CommonDest before, use the current one.
  4128. if (!*CommonDest)
  4129. *CommonDest = CaseDest;
  4130. // If the destination isn't the common one, abort.
  4131. if (CaseDest != *CommonDest)
  4132. return false;
  4133. // Get the values for this case from phi nodes in the destination block.
  4134. for (PHINode &PHI : (*CommonDest)->phis()) {
  4135. int Idx = PHI.getBasicBlockIndex(Pred);
  4136. if (Idx == -1)
  4137. continue;
  4138. Constant *ConstVal =
  4139. LookupConstant(PHI.getIncomingValue(Idx), ConstantPool);
  4140. if (!ConstVal)
  4141. return false;
  4142. // Be conservative about which kinds of constants we support.
  4143. if (!ValidLookupTableConstant(ConstVal, TTI))
  4144. return false;
  4145. Res.push_back(std::make_pair(&PHI, ConstVal));
  4146. }
  4147. return Res.size() > 0;
  4148. }
  4149. // Helper function used to add CaseVal to the list of cases that generate
  4150. // Result. Returns the updated number of cases that generate this result.
  4151. static uintptr_t MapCaseToResult(ConstantInt *CaseVal,
  4152. SwitchCaseResultVectorTy &UniqueResults,
  4153. Constant *Result) {
  4154. for (auto &I : UniqueResults) {
  4155. if (I.first == Result) {
  4156. I.second.push_back(CaseVal);
  4157. return I.second.size();
  4158. }
  4159. }
  4160. UniqueResults.push_back(
  4161. std::make_pair(Result, SmallVector<ConstantInt *, 4>(1, CaseVal)));
  4162. return 1;
  4163. }
  4164. // Helper function that initializes a map containing
  4165. // results for the PHI node of the common destination block for a switch
  4166. // instruction. Returns false if multiple PHI nodes have been found or if
  4167. // there is not a common destination block for the switch.
  4168. static bool
  4169. InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI, BasicBlock *&CommonDest,
  4170. SwitchCaseResultVectorTy &UniqueResults,
  4171. Constant *&DefaultResult, const DataLayout &DL,
  4172. const TargetTransformInfo &TTI,
  4173. uintptr_t MaxUniqueResults, uintptr_t MaxCasesPerResult) {
  4174. for (auto &I : SI->cases()) {
  4175. ConstantInt *CaseVal = I.getCaseValue();
  4176. // Resulting value at phi nodes for this case value.
  4177. SwitchCaseResultsTy Results;
  4178. if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
  4179. DL, TTI))
  4180. return false;
  4181. // Only one value per case is permitted.
  4182. if (Results.size() > 1)
  4183. return false;
  4184. // Add the case->result mapping to UniqueResults.
  4185. const uintptr_t NumCasesForResult =
  4186. MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
  4187. // Early out if there are too many cases for this result.
  4188. if (NumCasesForResult > MaxCasesPerResult)
  4189. return false;
  4190. // Early out if there are too many unique results.
  4191. if (UniqueResults.size() > MaxUniqueResults)
  4192. return false;
  4193. // Check the PHI consistency.
  4194. if (!PHI)
  4195. PHI = Results[0].first;
  4196. else if (PHI != Results[0].first)
  4197. return false;
  4198. }
  4199. // Find the default result value.
  4200. SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
  4201. BasicBlock *DefaultDest = SI->getDefaultDest();
  4202. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
  4203. DL, TTI);
  4204. // If the default value is not found abort unless the default destination
  4205. // is unreachable.
  4206. DefaultResult =
  4207. DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
  4208. if ((!DefaultResult &&
  4209. !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
  4210. return false;
  4211. return true;
  4212. }
  4213. // Helper function that checks if it is possible to transform a switch with only
  4214. // two cases (or two cases + default) that produces a result into a select.
  4215. // Example:
  4216. // switch (a) {
  4217. // case 10: %0 = icmp eq i32 %a, 10
  4218. // return 10; %1 = select i1 %0, i32 10, i32 4
  4219. // case 20: ----> %2 = icmp eq i32 %a, 20
  4220. // return 2; %3 = select i1 %2, i32 2, i32 %1
  4221. // default:
  4222. // return 4;
  4223. // }
  4224. static Value *ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
  4225. Constant *DefaultResult, Value *Condition,
  4226. IRBuilder<> &Builder) {
  4227. assert(ResultVector.size() == 2 &&
  4228. "We should have exactly two unique results at this point");
  4229. // If we are selecting between only two cases transform into a simple
  4230. // select or a two-way select if default is possible.
  4231. if (ResultVector[0].second.size() == 1 &&
  4232. ResultVector[1].second.size() == 1) {
  4233. ConstantInt *const FirstCase = ResultVector[0].second[0];
  4234. ConstantInt *const SecondCase = ResultVector[1].second[0];
  4235. bool DefaultCanTrigger = DefaultResult;
  4236. Value *SelectValue = ResultVector[1].first;
  4237. if (DefaultCanTrigger) {
  4238. Value *const ValueCompare =
  4239. Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
  4240. SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
  4241. DefaultResult, "switch.select");
  4242. }
  4243. Value *const ValueCompare =
  4244. Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
  4245. return Builder.CreateSelect(ValueCompare, ResultVector[0].first,
  4246. SelectValue, "switch.select");
  4247. }
  4248. return nullptr;
  4249. }
  4250. // Helper function to cleanup a switch instruction that has been converted into
  4251. // a select, fixing up PHI nodes and basic blocks.
  4252. static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
  4253. Value *SelectValue,
  4254. IRBuilder<> &Builder) {
  4255. BasicBlock *SelectBB = SI->getParent();
  4256. while (PHI->getBasicBlockIndex(SelectBB) >= 0)
  4257. PHI->removeIncomingValue(SelectBB);
  4258. PHI->addIncoming(SelectValue, SelectBB);
  4259. Builder.CreateBr(PHI->getParent());
  4260. // Remove the switch.
  4261. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  4262. BasicBlock *Succ = SI->getSuccessor(i);
  4263. if (Succ == PHI->getParent())
  4264. continue;
  4265. Succ->removePredecessor(SelectBB);
  4266. }
  4267. SI->eraseFromParent();
  4268. }
  4269. /// If the switch is only used to initialize one or more
  4270. /// phi nodes in a common successor block with only two different
  4271. /// constant values, replace the switch with select.
  4272. static bool switchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
  4273. const DataLayout &DL,
  4274. const TargetTransformInfo &TTI) {
  4275. Value *const Cond = SI->getCondition();
  4276. PHINode *PHI = nullptr;
  4277. BasicBlock *CommonDest = nullptr;
  4278. Constant *DefaultResult;
  4279. SwitchCaseResultVectorTy UniqueResults;
  4280. // Collect all the cases that will deliver the same value from the switch.
  4281. if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
  4282. DL, TTI, 2, 1))
  4283. return false;
  4284. // Selects choose between maximum two values.
  4285. if (UniqueResults.size() != 2)
  4286. return false;
  4287. assert(PHI != nullptr && "PHI for value select not found");
  4288. Builder.SetInsertPoint(SI);
  4289. Value *SelectValue =
  4290. ConvertTwoCaseSwitch(UniqueResults, DefaultResult, Cond, Builder);
  4291. if (SelectValue) {
  4292. RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
  4293. return true;
  4294. }
  4295. // The switch couldn't be converted into a select.
  4296. return false;
  4297. }
  4298. namespace {
  4299. /// This class represents a lookup table that can be used to replace a switch.
  4300. class SwitchLookupTable {
  4301. public:
  4302. /// Create a lookup table to use as a switch replacement with the contents
  4303. /// of Values, using DefaultValue to fill any holes in the table.
  4304. SwitchLookupTable(
  4305. Module &M, uint64_t TableSize, ConstantInt *Offset,
  4306. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  4307. Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName);
  4308. /// Build instructions with Builder to retrieve the value at
  4309. /// the position given by Index in the lookup table.
  4310. Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
  4311. /// Return true if a table with TableSize elements of
  4312. /// type ElementType would fit in a target-legal register.
  4313. static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
  4314. Type *ElementType);
  4315. private:
  4316. // Depending on the contents of the table, it can be represented in
  4317. // different ways.
  4318. enum {
  4319. // For tables where each element contains the same value, we just have to
  4320. // store that single value and return it for each lookup.
  4321. SingleValueKind,
  4322. // For tables where there is a linear relationship between table index
  4323. // and values. We calculate the result with a simple multiplication
  4324. // and addition instead of a table lookup.
  4325. LinearMapKind,
  4326. // For small tables with integer elements, we can pack them into a bitmap
  4327. // that fits into a target-legal register. Values are retrieved by
  4328. // shift and mask operations.
  4329. BitMapKind,
  4330. // The table is stored as an array of values. Values are retrieved by load
  4331. // instructions from the table.
  4332. ArrayKind
  4333. } Kind;
  4334. // For SingleValueKind, this is the single value.
  4335. Constant *SingleValue = nullptr;
  4336. // For BitMapKind, this is the bitmap.
  4337. ConstantInt *BitMap = nullptr;
  4338. IntegerType *BitMapElementTy = nullptr;
  4339. // For LinearMapKind, these are the constants used to derive the value.
  4340. ConstantInt *LinearOffset = nullptr;
  4341. ConstantInt *LinearMultiplier = nullptr;
  4342. // For ArrayKind, this is the array.
  4343. GlobalVariable *Array = nullptr;
  4344. };
  4345. } // end anonymous namespace
  4346. SwitchLookupTable::SwitchLookupTable(
  4347. Module &M, uint64_t TableSize, ConstantInt *Offset,
  4348. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  4349. Constant *DefaultValue, const DataLayout &DL, const StringRef &FuncName) {
  4350. assert(Values.size() && "Can't build lookup table without values!");
  4351. assert(TableSize >= Values.size() && "Can't fit values in table!");
  4352. // If all values in the table are equal, this is that value.
  4353. SingleValue = Values.begin()->second;
  4354. Type *ValueType = Values.begin()->second->getType();
  4355. // Build up the table contents.
  4356. SmallVector<Constant *, 64> TableContents(TableSize);
  4357. for (size_t I = 0, E = Values.size(); I != E; ++I) {
  4358. ConstantInt *CaseVal = Values[I].first;
  4359. Constant *CaseRes = Values[I].second;
  4360. assert(CaseRes->getType() == ValueType);
  4361. uint64_t Idx = (CaseVal->getValue() - Offset->getValue()).getLimitedValue();
  4362. TableContents[Idx] = CaseRes;
  4363. if (CaseRes != SingleValue)
  4364. SingleValue = nullptr;
  4365. }
  4366. // Fill in any holes in the table with the default result.
  4367. if (Values.size() < TableSize) {
  4368. assert(DefaultValue &&
  4369. "Need a default value to fill the lookup table holes.");
  4370. assert(DefaultValue->getType() == ValueType);
  4371. for (uint64_t I = 0; I < TableSize; ++I) {
  4372. if (!TableContents[I])
  4373. TableContents[I] = DefaultValue;
  4374. }
  4375. if (DefaultValue != SingleValue)
  4376. SingleValue = nullptr;
  4377. }
  4378. // If each element in the table contains the same value, we only need to store
  4379. // that single value.
  4380. if (SingleValue) {
  4381. Kind = SingleValueKind;
  4382. return;
  4383. }
  4384. // Check if we can derive the value with a linear transformation from the
  4385. // table index.
  4386. if (isa<IntegerType>(ValueType)) {
  4387. bool LinearMappingPossible = true;
  4388. APInt PrevVal;
  4389. APInt DistToPrev;
  4390. assert(TableSize >= 2 && "Should be a SingleValue table.");
  4391. // Check if there is the same distance between two consecutive values.
  4392. for (uint64_t I = 0; I < TableSize; ++I) {
  4393. ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
  4394. if (!ConstVal) {
  4395. // This is an undef. We could deal with it, but undefs in lookup tables
  4396. // are very seldom. It's probably not worth the additional complexity.
  4397. LinearMappingPossible = false;
  4398. break;
  4399. }
  4400. const APInt &Val = ConstVal->getValue();
  4401. if (I != 0) {
  4402. APInt Dist = Val - PrevVal;
  4403. if (I == 1) {
  4404. DistToPrev = Dist;
  4405. } else if (Dist != DistToPrev) {
  4406. LinearMappingPossible = false;
  4407. break;
  4408. }
  4409. }
  4410. PrevVal = Val;
  4411. }
  4412. if (LinearMappingPossible) {
  4413. LinearOffset = cast<ConstantInt>(TableContents[0]);
  4414. LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
  4415. Kind = LinearMapKind;
  4416. ++NumLinearMaps;
  4417. return;
  4418. }
  4419. }
  4420. // If the type is integer and the table fits in a register, build a bitmap.
  4421. if (WouldFitInRegister(DL, TableSize, ValueType)) {
  4422. IntegerType *IT = cast<IntegerType>(ValueType);
  4423. APInt TableInt(TableSize * IT->getBitWidth(), 0);
  4424. for (uint64_t I = TableSize; I > 0; --I) {
  4425. TableInt <<= IT->getBitWidth();
  4426. // Insert values into the bitmap. Undef values are set to zero.
  4427. if (!isa<UndefValue>(TableContents[I - 1])) {
  4428. ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
  4429. TableInt |= Val->getValue().zext(TableInt.getBitWidth());
  4430. }
  4431. }
  4432. BitMap = ConstantInt::get(M.getContext(), TableInt);
  4433. BitMapElementTy = IT;
  4434. Kind = BitMapKind;
  4435. ++NumBitMaps;
  4436. return;
  4437. }
  4438. // Store the table in an array.
  4439. ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
  4440. Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
  4441. Array = new GlobalVariable(M, ArrayTy, /*constant=*/true,
  4442. GlobalVariable::PrivateLinkage, Initializer,
  4443. "switch.table." + FuncName);
  4444. Array->setUnnamedAddr(GlobalValue::UnnamedAddr::Global);
  4445. // Set the alignment to that of an array items. We will be only loading one
  4446. // value out of it.
  4447. Array->setAlignment(DL.getPrefTypeAlignment(ValueType));
  4448. Kind = ArrayKind;
  4449. }
  4450. Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
  4451. switch (Kind) {
  4452. case SingleValueKind:
  4453. return SingleValue;
  4454. case LinearMapKind: {
  4455. // Derive the result value from the input value.
  4456. Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
  4457. false, "switch.idx.cast");
  4458. if (!LinearMultiplier->isOne())
  4459. Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
  4460. if (!LinearOffset->isZero())
  4461. Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
  4462. return Result;
  4463. }
  4464. case BitMapKind: {
  4465. // Type of the bitmap (e.g. i59).
  4466. IntegerType *MapTy = BitMap->getType();
  4467. // Cast Index to the same type as the bitmap.
  4468. // Note: The Index is <= the number of elements in the table, so
  4469. // truncating it to the width of the bitmask is safe.
  4470. Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
  4471. // Multiply the shift amount by the element width.
  4472. ShiftAmt = Builder.CreateMul(
  4473. ShiftAmt, ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
  4474. "switch.shiftamt");
  4475. // Shift down.
  4476. Value *DownShifted =
  4477. Builder.CreateLShr(BitMap, ShiftAmt, "switch.downshift");
  4478. // Mask off.
  4479. return Builder.CreateTrunc(DownShifted, BitMapElementTy, "switch.masked");
  4480. }
  4481. case ArrayKind: {
  4482. // Make sure the table index will not overflow when treated as signed.
  4483. IntegerType *IT = cast<IntegerType>(Index->getType());
  4484. uint64_t TableSize =
  4485. Array->getInitializer()->getType()->getArrayNumElements();
  4486. if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
  4487. Index = Builder.CreateZExt(
  4488. Index, IntegerType::get(IT->getContext(), IT->getBitWidth() + 1),
  4489. "switch.tableidx.zext");
  4490. Value *GEPIndices[] = {Builder.getInt32(0), Index};
  4491. Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
  4492. GEPIndices, "switch.gep");
  4493. return Builder.CreateLoad(
  4494. cast<ArrayType>(Array->getValueType())->getElementType(), GEP,
  4495. "switch.load");
  4496. }
  4497. }
  4498. llvm_unreachable("Unknown lookup table kind!");
  4499. }
  4500. bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
  4501. uint64_t TableSize,
  4502. Type *ElementType) {
  4503. auto *IT = dyn_cast<IntegerType>(ElementType);
  4504. if (!IT)
  4505. return false;
  4506. // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
  4507. // are <= 15, we could try to narrow the type.
  4508. // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
  4509. if (TableSize >= UINT_MAX / IT->getBitWidth())
  4510. return false;
  4511. return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
  4512. }
  4513. /// Determine whether a lookup table should be built for this switch, based on
  4514. /// the number of cases, size of the table, and the types of the results.
  4515. static bool
  4516. ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
  4517. const TargetTransformInfo &TTI, const DataLayout &DL,
  4518. const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
  4519. if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
  4520. return false; // TableSize overflowed, or mul below might overflow.
  4521. bool AllTablesFitInRegister = true;
  4522. bool HasIllegalType = false;
  4523. for (const auto &I : ResultTypes) {
  4524. Type *Ty = I.second;
  4525. // Saturate this flag to true.
  4526. HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
  4527. // Saturate this flag to false.
  4528. AllTablesFitInRegister =
  4529. AllTablesFitInRegister &&
  4530. SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
  4531. // If both flags saturate, we're done. NOTE: This *only* works with
  4532. // saturating flags, and all flags have to saturate first due to the
  4533. // non-deterministic behavior of iterating over a dense map.
  4534. if (HasIllegalType && !AllTablesFitInRegister)
  4535. break;
  4536. }
  4537. // If each table would fit in a register, we should build it anyway.
  4538. if (AllTablesFitInRegister)
  4539. return true;
  4540. // Don't build a table that doesn't fit in-register if it has illegal types.
  4541. if (HasIllegalType)
  4542. return false;
  4543. // The table density should be at least 40%. This is the same criterion as for
  4544. // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
  4545. // FIXME: Find the best cut-off.
  4546. return SI->getNumCases() * 10 >= TableSize * 4;
  4547. }
  4548. /// Try to reuse the switch table index compare. Following pattern:
  4549. /// \code
  4550. /// if (idx < tablesize)
  4551. /// r = table[idx]; // table does not contain default_value
  4552. /// else
  4553. /// r = default_value;
  4554. /// if (r != default_value)
  4555. /// ...
  4556. /// \endcode
  4557. /// Is optimized to:
  4558. /// \code
  4559. /// cond = idx < tablesize;
  4560. /// if (cond)
  4561. /// r = table[idx];
  4562. /// else
  4563. /// r = default_value;
  4564. /// if (cond)
  4565. /// ...
  4566. /// \endcode
  4567. /// Jump threading will then eliminate the second if(cond).
  4568. static void reuseTableCompare(
  4569. User *PhiUser, BasicBlock *PhiBlock, BranchInst *RangeCheckBranch,
  4570. Constant *DefaultValue,
  4571. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values) {
  4572. ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
  4573. if (!CmpInst)
  4574. return;
  4575. // We require that the compare is in the same block as the phi so that jump
  4576. // threading can do its work afterwards.
  4577. if (CmpInst->getParent() != PhiBlock)
  4578. return;
  4579. Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
  4580. if (!CmpOp1)
  4581. return;
  4582. Value *RangeCmp = RangeCheckBranch->getCondition();
  4583. Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
  4584. Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
  4585. // Check if the compare with the default value is constant true or false.
  4586. Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  4587. DefaultValue, CmpOp1, true);
  4588. if (DefaultConst != TrueConst && DefaultConst != FalseConst)
  4589. return;
  4590. // Check if the compare with the case values is distinct from the default
  4591. // compare result.
  4592. for (auto ValuePair : Values) {
  4593. Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  4594. ValuePair.second, CmpOp1, true);
  4595. if (!CaseConst || CaseConst == DefaultConst || isa<UndefValue>(CaseConst))
  4596. return;
  4597. assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
  4598. "Expect true or false as compare result.");
  4599. }
  4600. // Check if the branch instruction dominates the phi node. It's a simple
  4601. // dominance check, but sufficient for our needs.
  4602. // Although this check is invariant in the calling loops, it's better to do it
  4603. // at this late stage. Practically we do it at most once for a switch.
  4604. BasicBlock *BranchBlock = RangeCheckBranch->getParent();
  4605. for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
  4606. BasicBlock *Pred = *PI;
  4607. if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
  4608. return;
  4609. }
  4610. if (DefaultConst == FalseConst) {
  4611. // The compare yields the same result. We can replace it.
  4612. CmpInst->replaceAllUsesWith(RangeCmp);
  4613. ++NumTableCmpReuses;
  4614. } else {
  4615. // The compare yields the same result, just inverted. We can replace it.
  4616. Value *InvertedTableCmp = BinaryOperator::CreateXor(
  4617. RangeCmp, ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
  4618. RangeCheckBranch);
  4619. CmpInst->replaceAllUsesWith(InvertedTableCmp);
  4620. ++NumTableCmpReuses;
  4621. }
  4622. }
  4623. /// If the switch is only used to initialize one or more phi nodes in a common
  4624. /// successor block with different constant values, replace the switch with
  4625. /// lookup tables.
  4626. static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
  4627. const DataLayout &DL,
  4628. const TargetTransformInfo &TTI) {
  4629. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  4630. Function *Fn = SI->getParent()->getParent();
  4631. // Only build lookup table when we have a target that supports it or the
  4632. // attribute is not set.
  4633. if (!TTI.shouldBuildLookupTables() ||
  4634. (Fn->getFnAttribute("no-jump-tables").getValueAsString() == "true"))
  4635. return false;
  4636. // FIXME: If the switch is too sparse for a lookup table, perhaps we could
  4637. // split off a dense part and build a lookup table for that.
  4638. // FIXME: This creates arrays of GEPs to constant strings, which means each
  4639. // GEP needs a runtime relocation in PIC code. We should just build one big
  4640. // string and lookup indices into that.
  4641. // Ignore switches with less than three cases. Lookup tables will not make
  4642. // them faster, so we don't analyze them.
  4643. if (SI->getNumCases() < 3)
  4644. return false;
  4645. // Figure out the corresponding result for each case value and phi node in the
  4646. // common destination, as well as the min and max case values.
  4647. assert(!empty(SI->cases()));
  4648. SwitchInst::CaseIt CI = SI->case_begin();
  4649. ConstantInt *MinCaseVal = CI->getCaseValue();
  4650. ConstantInt *MaxCaseVal = CI->getCaseValue();
  4651. BasicBlock *CommonDest = nullptr;
  4652. using ResultListTy = SmallVector<std::pair<ConstantInt *, Constant *>, 4>;
  4653. SmallDenseMap<PHINode *, ResultListTy> ResultLists;
  4654. SmallDenseMap<PHINode *, Constant *> DefaultResults;
  4655. SmallDenseMap<PHINode *, Type *> ResultTypes;
  4656. SmallVector<PHINode *, 4> PHIs;
  4657. for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
  4658. ConstantInt *CaseVal = CI->getCaseValue();
  4659. if (CaseVal->getValue().slt(MinCaseVal->getValue()))
  4660. MinCaseVal = CaseVal;
  4661. if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
  4662. MaxCaseVal = CaseVal;
  4663. // Resulting value at phi nodes for this case value.
  4664. using ResultsTy = SmallVector<std::pair<PHINode *, Constant *>, 4>;
  4665. ResultsTy Results;
  4666. if (!GetCaseResults(SI, CaseVal, CI->getCaseSuccessor(), &CommonDest,
  4667. Results, DL, TTI))
  4668. return false;
  4669. // Append the result from this case to the list for each phi.
  4670. for (const auto &I : Results) {
  4671. PHINode *PHI = I.first;
  4672. Constant *Value = I.second;
  4673. if (!ResultLists.count(PHI))
  4674. PHIs.push_back(PHI);
  4675. ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
  4676. }
  4677. }
  4678. // Keep track of the result types.
  4679. for (PHINode *PHI : PHIs) {
  4680. ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
  4681. }
  4682. uint64_t NumResults = ResultLists[PHIs[0]].size();
  4683. APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
  4684. uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
  4685. bool TableHasHoles = (NumResults < TableSize);
  4686. // If the table has holes, we need a constant result for the default case
  4687. // or a bitmask that fits in a register.
  4688. SmallVector<std::pair<PHINode *, Constant *>, 4> DefaultResultsList;
  4689. bool HasDefaultResults =
  4690. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest,
  4691. DefaultResultsList, DL, TTI);
  4692. bool NeedMask = (TableHasHoles && !HasDefaultResults);
  4693. if (NeedMask) {
  4694. // As an extra penalty for the validity test we require more cases.
  4695. if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
  4696. return false;
  4697. if (!DL.fitsInLegalInteger(TableSize))
  4698. return false;
  4699. }
  4700. for (const auto &I : DefaultResultsList) {
  4701. PHINode *PHI = I.first;
  4702. Constant *Result = I.second;
  4703. DefaultResults[PHI] = Result;
  4704. }
  4705. if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
  4706. return false;
  4707. // Create the BB that does the lookups.
  4708. Module &Mod = *CommonDest->getParent()->getParent();
  4709. BasicBlock *LookupBB = BasicBlock::Create(
  4710. Mod.getContext(), "switch.lookup", CommonDest->getParent(), CommonDest);
  4711. // Compute the table index value.
  4712. Builder.SetInsertPoint(SI);
  4713. Value *TableIndex;
  4714. if (MinCaseVal->isNullValue())
  4715. TableIndex = SI->getCondition();
  4716. else
  4717. TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
  4718. "switch.tableidx");
  4719. // Compute the maximum table size representable by the integer type we are
  4720. // switching upon.
  4721. unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
  4722. uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
  4723. assert(MaxTableSize >= TableSize &&
  4724. "It is impossible for a switch to have more entries than the max "
  4725. "representable value of its input integer type's size.");
  4726. // If the default destination is unreachable, or if the lookup table covers
  4727. // all values of the conditional variable, branch directly to the lookup table
  4728. // BB. Otherwise, check that the condition is within the case range.
  4729. const bool DefaultIsReachable =
  4730. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  4731. const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
  4732. BranchInst *RangeCheckBranch = nullptr;
  4733. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  4734. Builder.CreateBr(LookupBB);
  4735. // Note: We call removeProdecessor later since we need to be able to get the
  4736. // PHI value for the default case in case we're using a bit mask.
  4737. } else {
  4738. Value *Cmp = Builder.CreateICmpULT(
  4739. TableIndex, ConstantInt::get(MinCaseVal->getType(), TableSize));
  4740. RangeCheckBranch =
  4741. Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
  4742. }
  4743. // Populate the BB that does the lookups.
  4744. Builder.SetInsertPoint(LookupBB);
  4745. if (NeedMask) {
  4746. // Before doing the lookup, we do the hole check. The LookupBB is therefore
  4747. // re-purposed to do the hole check, and we create a new LookupBB.
  4748. BasicBlock *MaskBB = LookupBB;
  4749. MaskBB->setName("switch.hole_check");
  4750. LookupBB = BasicBlock::Create(Mod.getContext(), "switch.lookup",
  4751. CommonDest->getParent(), CommonDest);
  4752. // Make the mask's bitwidth at least 8-bit and a power-of-2 to avoid
  4753. // unnecessary illegal types.
  4754. uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
  4755. APInt MaskInt(TableSizePowOf2, 0);
  4756. APInt One(TableSizePowOf2, 1);
  4757. // Build bitmask; fill in a 1 bit for every case.
  4758. const ResultListTy &ResultList = ResultLists[PHIs[0]];
  4759. for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
  4760. uint64_t Idx = (ResultList[I].first->getValue() - MinCaseVal->getValue())
  4761. .getLimitedValue();
  4762. MaskInt |= One << Idx;
  4763. }
  4764. ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
  4765. // Get the TableIndex'th bit of the bitmask.
  4766. // If this bit is 0 (meaning hole) jump to the default destination,
  4767. // else continue with table lookup.
  4768. IntegerType *MapTy = TableMask->getType();
  4769. Value *MaskIndex =
  4770. Builder.CreateZExtOrTrunc(TableIndex, MapTy, "switch.maskindex");
  4771. Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex, "switch.shifted");
  4772. Value *LoBit = Builder.CreateTrunc(
  4773. Shifted, Type::getInt1Ty(Mod.getContext()), "switch.lobit");
  4774. Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
  4775. Builder.SetInsertPoint(LookupBB);
  4776. AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
  4777. }
  4778. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  4779. // We cached PHINodes in PHIs. To avoid accessing deleted PHINodes later,
  4780. // do not delete PHINodes here.
  4781. SI->getDefaultDest()->removePredecessor(SI->getParent(),
  4782. /*KeepOneInputPHIs=*/true);
  4783. }
  4784. bool ReturnedEarly = false;
  4785. for (PHINode *PHI : PHIs) {
  4786. const ResultListTy &ResultList = ResultLists[PHI];
  4787. // If using a bitmask, use any value to fill the lookup table holes.
  4788. Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
  4789. StringRef FuncName = Fn->getName();
  4790. SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL,
  4791. FuncName);
  4792. Value *Result = Table.BuildLookup(TableIndex, Builder);
  4793. // If the result is used to return immediately from the function, we want to
  4794. // do that right here.
  4795. if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
  4796. PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
  4797. Builder.CreateRet(Result);
  4798. ReturnedEarly = true;
  4799. break;
  4800. }
  4801. // Do a small peephole optimization: re-use the switch table compare if
  4802. // possible.
  4803. if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
  4804. BasicBlock *PhiBlock = PHI->getParent();
  4805. // Search for compare instructions which use the phi.
  4806. for (auto *User : PHI->users()) {
  4807. reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
  4808. }
  4809. }
  4810. PHI->addIncoming(Result, LookupBB);
  4811. }
  4812. if (!ReturnedEarly)
  4813. Builder.CreateBr(CommonDest);
  4814. // Remove the switch.
  4815. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  4816. BasicBlock *Succ = SI->getSuccessor(i);
  4817. if (Succ == SI->getDefaultDest())
  4818. continue;
  4819. Succ->removePredecessor(SI->getParent());
  4820. }
  4821. SI->eraseFromParent();
  4822. ++NumLookupTables;
  4823. if (NeedMask)
  4824. ++NumLookupTablesHoles;
  4825. return true;
  4826. }
  4827. static bool isSwitchDense(ArrayRef<int64_t> Values) {
  4828. // See also SelectionDAGBuilder::isDense(), which this function was based on.
  4829. uint64_t Diff = (uint64_t)Values.back() - (uint64_t)Values.front();
  4830. uint64_t Range = Diff + 1;
  4831. uint64_t NumCases = Values.size();
  4832. // 40% is the default density for building a jump table in optsize/minsize mode.
  4833. uint64_t MinDensity = 40;
  4834. return NumCases * 100 >= Range * MinDensity;
  4835. }
  4836. /// Try to transform a switch that has "holes" in it to a contiguous sequence
  4837. /// of cases.
  4838. ///
  4839. /// A switch such as: switch(i) {case 5: case 9: case 13: case 17:} can be
  4840. /// range-reduced to: switch ((i-5) / 4) {case 0: case 1: case 2: case 3:}.
  4841. ///
  4842. /// This converts a sparse switch into a dense switch which allows better
  4843. /// lowering and could also allow transforming into a lookup table.
  4844. static bool ReduceSwitchRange(SwitchInst *SI, IRBuilder<> &Builder,
  4845. const DataLayout &DL,
  4846. const TargetTransformInfo &TTI) {
  4847. auto *CondTy = cast<IntegerType>(SI->getCondition()->getType());
  4848. if (CondTy->getIntegerBitWidth() > 64 ||
  4849. !DL.fitsInLegalInteger(CondTy->getIntegerBitWidth()))
  4850. return false;
  4851. // Only bother with this optimization if there are more than 3 switch cases;
  4852. // SDAG will only bother creating jump tables for 4 or more cases.
  4853. if (SI->getNumCases() < 4)
  4854. return false;
  4855. // This transform is agnostic to the signedness of the input or case values. We
  4856. // can treat the case values as signed or unsigned. We can optimize more common
  4857. // cases such as a sequence crossing zero {-4,0,4,8} if we interpret case values
  4858. // as signed.
  4859. SmallVector<int64_t,4> Values;
  4860. for (auto &C : SI->cases())
  4861. Values.push_back(C.getCaseValue()->getValue().getSExtValue());
  4862. llvm::sort(Values);
  4863. // If the switch is already dense, there's nothing useful to do here.
  4864. if (isSwitchDense(Values))
  4865. return false;
  4866. // First, transform the values such that they start at zero and ascend.
  4867. int64_t Base = Values[0];
  4868. for (auto &V : Values)
  4869. V -= (uint64_t)(Base);
  4870. // Now we have signed numbers that have been shifted so that, given enough
  4871. // precision, there are no negative values. Since the rest of the transform
  4872. // is bitwise only, we switch now to an unsigned representation.
  4873. uint64_t GCD = 0;
  4874. for (auto &V : Values)
  4875. GCD = GreatestCommonDivisor64(GCD, (uint64_t)V);
  4876. // This transform can be done speculatively because it is so cheap - it results
  4877. // in a single rotate operation being inserted. This can only happen if the
  4878. // factor extracted is a power of 2.
  4879. // FIXME: If the GCD is an odd number we can multiply by the multiplicative
  4880. // inverse of GCD and then perform this transform.
  4881. // FIXME: It's possible that optimizing a switch on powers of two might also
  4882. // be beneficial - flag values are often powers of two and we could use a CLZ
  4883. // as the key function.
  4884. if (GCD <= 1 || !isPowerOf2_64(GCD))
  4885. // No common divisor found or too expensive to compute key function.
  4886. return false;
  4887. unsigned Shift = Log2_64(GCD);
  4888. for (auto &V : Values)
  4889. V = (int64_t)((uint64_t)V >> Shift);
  4890. if (!isSwitchDense(Values))
  4891. // Transform didn't create a dense switch.
  4892. return false;
  4893. // The obvious transform is to shift the switch condition right and emit a
  4894. // check that the condition actually cleanly divided by GCD, i.e.
  4895. // C & (1 << Shift - 1) == 0
  4896. // inserting a new CFG edge to handle the case where it didn't divide cleanly.
  4897. //
  4898. // A cheaper way of doing this is a simple ROTR(C, Shift). This performs the
  4899. // shift and puts the shifted-off bits in the uppermost bits. If any of these
  4900. // are nonzero then the switch condition will be very large and will hit the
  4901. // default case.
  4902. auto *Ty = cast<IntegerType>(SI->getCondition()->getType());
  4903. Builder.SetInsertPoint(SI);
  4904. auto *ShiftC = ConstantInt::get(Ty, Shift);
  4905. auto *Sub = Builder.CreateSub(SI->getCondition(), ConstantInt::get(Ty, Base));
  4906. auto *LShr = Builder.CreateLShr(Sub, ShiftC);
  4907. auto *Shl = Builder.CreateShl(Sub, Ty->getBitWidth() - Shift);
  4908. auto *Rot = Builder.CreateOr(LShr, Shl);
  4909. SI->replaceUsesOfWith(SI->getCondition(), Rot);
  4910. for (auto Case : SI->cases()) {
  4911. auto *Orig = Case.getCaseValue();
  4912. auto Sub = Orig->getValue() - APInt(Ty->getBitWidth(), Base);
  4913. Case.setValue(
  4914. cast<ConstantInt>(ConstantInt::get(Ty, Sub.lshr(ShiftC->getValue()))));
  4915. }
  4916. return true;
  4917. }
  4918. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  4919. BasicBlock *BB = SI->getParent();
  4920. if (isValueEqualityComparison(SI)) {
  4921. // If we only have one predecessor, and if it is a branch on this value,
  4922. // see if that predecessor totally determines the outcome of this switch.
  4923. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  4924. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  4925. return requestResimplify();
  4926. Value *Cond = SI->getCondition();
  4927. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  4928. if (SimplifySwitchOnSelect(SI, Select))
  4929. return requestResimplify();
  4930. // If the block only contains the switch, see if we can fold the block
  4931. // away into any preds.
  4932. if (SI == &*BB->instructionsWithoutDebug().begin())
  4933. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  4934. return requestResimplify();
  4935. }
  4936. // Try to transform the switch into an icmp and a branch.
  4937. if (TurnSwitchRangeIntoICmp(SI, Builder))
  4938. return requestResimplify();
  4939. // Remove unreachable cases.
  4940. if (eliminateDeadSwitchCases(SI, Options.AC, DL))
  4941. return requestResimplify();
  4942. if (switchToSelect(SI, Builder, DL, TTI))
  4943. return requestResimplify();
  4944. if (Options.ForwardSwitchCondToPhi && ForwardSwitchConditionToPHI(SI))
  4945. return requestResimplify();
  4946. // The conversion from switch to lookup tables results in difficult-to-analyze
  4947. // code and makes pruning branches much harder. This is a problem if the
  4948. // switch expression itself can still be restricted as a result of inlining or
  4949. // CVP. Therefore, only apply this transformation during late stages of the
  4950. // optimisation pipeline.
  4951. if (Options.ConvertSwitchToLookupTable &&
  4952. SwitchToLookupTable(SI, Builder, DL, TTI))
  4953. return requestResimplify();
  4954. if (ReduceSwitchRange(SI, Builder, DL, TTI))
  4955. return requestResimplify();
  4956. return false;
  4957. }
  4958. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  4959. BasicBlock *BB = IBI->getParent();
  4960. bool Changed = false;
  4961. // Eliminate redundant destinations.
  4962. SmallPtrSet<Value *, 8> Succs;
  4963. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  4964. BasicBlock *Dest = IBI->getDestination(i);
  4965. if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
  4966. Dest->removePredecessor(BB);
  4967. IBI->removeDestination(i);
  4968. --i;
  4969. --e;
  4970. Changed = true;
  4971. }
  4972. }
  4973. if (IBI->getNumDestinations() == 0) {
  4974. // If the indirectbr has no successors, change it to unreachable.
  4975. new UnreachableInst(IBI->getContext(), IBI);
  4976. EraseTerminatorAndDCECond(IBI);
  4977. return true;
  4978. }
  4979. if (IBI->getNumDestinations() == 1) {
  4980. // If the indirectbr has one successor, change it to a direct branch.
  4981. BranchInst::Create(IBI->getDestination(0), IBI);
  4982. EraseTerminatorAndDCECond(IBI);
  4983. return true;
  4984. }
  4985. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  4986. if (SimplifyIndirectBrOnSelect(IBI, SI))
  4987. return requestResimplify();
  4988. }
  4989. return Changed;
  4990. }
  4991. /// Given an block with only a single landing pad and a unconditional branch
  4992. /// try to find another basic block which this one can be merged with. This
  4993. /// handles cases where we have multiple invokes with unique landing pads, but
  4994. /// a shared handler.
  4995. ///
  4996. /// We specifically choose to not worry about merging non-empty blocks
  4997. /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
  4998. /// practice, the optimizer produces empty landing pad blocks quite frequently
  4999. /// when dealing with exception dense code. (see: instcombine, gvn, if-else
  5000. /// sinking in this file)
  5001. ///
  5002. /// This is primarily a code size optimization. We need to avoid performing
  5003. /// any transform which might inhibit optimization (such as our ability to
  5004. /// specialize a particular handler via tail commoning). We do this by not
  5005. /// merging any blocks which require us to introduce a phi. Since the same
  5006. /// values are flowing through both blocks, we don't lose any ability to
  5007. /// specialize. If anything, we make such specialization more likely.
  5008. ///
  5009. /// TODO - This transformation could remove entries from a phi in the target
  5010. /// block when the inputs in the phi are the same for the two blocks being
  5011. /// merged. In some cases, this could result in removal of the PHI entirely.
  5012. static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
  5013. BasicBlock *BB) {
  5014. auto Succ = BB->getUniqueSuccessor();
  5015. assert(Succ);
  5016. // If there's a phi in the successor block, we'd likely have to introduce
  5017. // a phi into the merged landing pad block.
  5018. if (isa<PHINode>(*Succ->begin()))
  5019. return false;
  5020. for (BasicBlock *OtherPred : predecessors(Succ)) {
  5021. if (BB == OtherPred)
  5022. continue;
  5023. BasicBlock::iterator I = OtherPred->begin();
  5024. LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
  5025. if (!LPad2 || !LPad2->isIdenticalTo(LPad))
  5026. continue;
  5027. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5028. ;
  5029. BranchInst *BI2 = dyn_cast<BranchInst>(I);
  5030. if (!BI2 || !BI2->isIdenticalTo(BI))
  5031. continue;
  5032. // We've found an identical block. Update our predecessors to take that
  5033. // path instead and make ourselves dead.
  5034. SmallPtrSet<BasicBlock *, 16> Preds;
  5035. Preds.insert(pred_begin(BB), pred_end(BB));
  5036. for (BasicBlock *Pred : Preds) {
  5037. InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
  5038. assert(II->getNormalDest() != BB && II->getUnwindDest() == BB &&
  5039. "unexpected successor");
  5040. II->setUnwindDest(OtherPred);
  5041. }
  5042. // The debug info in OtherPred doesn't cover the merged control flow that
  5043. // used to go through BB. We need to delete it or update it.
  5044. for (auto I = OtherPred->begin(), E = OtherPred->end(); I != E;) {
  5045. Instruction &Inst = *I;
  5046. I++;
  5047. if (isa<DbgInfoIntrinsic>(Inst))
  5048. Inst.eraseFromParent();
  5049. }
  5050. SmallPtrSet<BasicBlock *, 16> Succs;
  5051. Succs.insert(succ_begin(BB), succ_end(BB));
  5052. for (BasicBlock *Succ : Succs) {
  5053. Succ->removePredecessor(BB);
  5054. }
  5055. IRBuilder<> Builder(BI);
  5056. Builder.CreateUnreachable();
  5057. BI->eraseFromParent();
  5058. return true;
  5059. }
  5060. return false;
  5061. }
  5062. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI,
  5063. IRBuilder<> &Builder) {
  5064. BasicBlock *BB = BI->getParent();
  5065. BasicBlock *Succ = BI->getSuccessor(0);
  5066. // If the Terminator is the only non-phi instruction, simplify the block.
  5067. // If LoopHeader is provided, check if the block or its successor is a loop
  5068. // header. (This is for early invocations before loop simplify and
  5069. // vectorization to keep canonical loop forms for nested loops. These blocks
  5070. // can be eliminated when the pass is invoked later in the back-end.)
  5071. // Note that if BB has only one predecessor then we do not introduce new
  5072. // backedge, so we can eliminate BB.
  5073. bool NeedCanonicalLoop =
  5074. Options.NeedCanonicalLoop &&
  5075. (LoopHeaders && BB->hasNPredecessorsOrMore(2) &&
  5076. (LoopHeaders->count(BB) || LoopHeaders->count(Succ)));
  5077. BasicBlock::iterator I = BB->getFirstNonPHIOrDbg()->getIterator();
  5078. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  5079. !NeedCanonicalLoop && TryToSimplifyUncondBranchFromEmptyBlock(BB))
  5080. return true;
  5081. // If the only instruction in the block is a seteq/setne comparison against a
  5082. // constant, try to simplify the block.
  5083. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  5084. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  5085. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5086. ;
  5087. if (I->isTerminator() &&
  5088. tryToSimplifyUncondBranchWithICmpInIt(ICI, Builder))
  5089. return true;
  5090. }
  5091. // See if we can merge an empty landing pad block with another which is
  5092. // equivalent.
  5093. if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
  5094. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  5095. ;
  5096. if (I->isTerminator() && TryToMergeLandingPad(LPad, BI, BB))
  5097. return true;
  5098. }
  5099. // If this basic block is ONLY a compare and a branch, and if a predecessor
  5100. // branches to us and our successor, fold the comparison into the
  5101. // predecessor and use logical operations to update the incoming value
  5102. // for PHI nodes in common successor.
  5103. if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
  5104. return requestResimplify();
  5105. return false;
  5106. }
  5107. static BasicBlock *allPredecessorsComeFromSameSource(BasicBlock *BB) {
  5108. BasicBlock *PredPred = nullptr;
  5109. for (auto *P : predecessors(BB)) {
  5110. BasicBlock *PPred = P->getSinglePredecessor();
  5111. if (!PPred || (PredPred && PredPred != PPred))
  5112. return nullptr;
  5113. PredPred = PPred;
  5114. }
  5115. return PredPred;
  5116. }
  5117. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  5118. BasicBlock *BB = BI->getParent();
  5119. const Function *Fn = BB->getParent();
  5120. if (Fn && Fn->hasFnAttribute(Attribute::OptForFuzzing))
  5121. return false;
  5122. // Conditional branch
  5123. if (isValueEqualityComparison(BI)) {
  5124. // If we only have one predecessor, and if it is a branch on this value,
  5125. // see if that predecessor totally determines the outcome of this
  5126. // switch.
  5127. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  5128. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  5129. return requestResimplify();
  5130. // This block must be empty, except for the setcond inst, if it exists.
  5131. // Ignore dbg intrinsics.
  5132. auto I = BB->instructionsWithoutDebug().begin();
  5133. if (&*I == BI) {
  5134. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  5135. return requestResimplify();
  5136. } else if (&*I == cast<Instruction>(BI->getCondition())) {
  5137. ++I;
  5138. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  5139. return requestResimplify();
  5140. }
  5141. }
  5142. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  5143. if (SimplifyBranchOnICmpChain(BI, Builder, DL))
  5144. return true;
  5145. // If this basic block has dominating predecessor blocks and the dominating
  5146. // blocks' conditions imply BI's condition, we know the direction of BI.
  5147. Optional<bool> Imp = isImpliedByDomCondition(BI->getCondition(), BI, DL);
  5148. if (Imp) {
  5149. // Turn this into a branch on constant.
  5150. auto *OldCond = BI->getCondition();
  5151. ConstantInt *TorF = *Imp ? ConstantInt::getTrue(BB->getContext())
  5152. : ConstantInt::getFalse(BB->getContext());
  5153. BI->setCondition(TorF);
  5154. RecursivelyDeleteTriviallyDeadInstructions(OldCond);
  5155. return requestResimplify();
  5156. }
  5157. // If this basic block is ONLY a compare and a branch, and if a predecessor
  5158. // branches to us and one of our successors, fold the comparison into the
  5159. // predecessor and use logical operations to pick the right destination.
  5160. if (FoldBranchToCommonDest(BI, nullptr, Options.BonusInstThreshold))
  5161. return requestResimplify();
  5162. // We have a conditional branch to two blocks that are only reachable
  5163. // from BI. We know that the condbr dominates the two blocks, so see if
  5164. // there is any identical code in the "then" and "else" blocks. If so, we
  5165. // can hoist it up to the branching block.
  5166. if (BI->getSuccessor(0)->getSinglePredecessor()) {
  5167. if (BI->getSuccessor(1)->getSinglePredecessor()) {
  5168. if (HoistThenElseCodeToIf(BI, TTI))
  5169. return requestResimplify();
  5170. } else {
  5171. // If Successor #1 has multiple preds, we may be able to conditionally
  5172. // execute Successor #0 if it branches to Successor #1.
  5173. Instruction *Succ0TI = BI->getSuccessor(0)->getTerminator();
  5174. if (Succ0TI->getNumSuccessors() == 1 &&
  5175. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  5176. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
  5177. return requestResimplify();
  5178. }
  5179. } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
  5180. // If Successor #0 has multiple preds, we may be able to conditionally
  5181. // execute Successor #1 if it branches to Successor #0.
  5182. Instruction *Succ1TI = BI->getSuccessor(1)->getTerminator();
  5183. if (Succ1TI->getNumSuccessors() == 1 &&
  5184. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  5185. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
  5186. return requestResimplify();
  5187. }
  5188. // If this is a branch on a phi node in the current block, thread control
  5189. // through this block if any PHI node entries are constants.
  5190. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  5191. if (PN->getParent() == BI->getParent())
  5192. if (FoldCondBranchOnPHI(BI, DL, Options.AC))
  5193. return requestResimplify();
  5194. // Scan predecessor blocks for conditional branches.
  5195. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  5196. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  5197. if (PBI != BI && PBI->isConditional())
  5198. if (SimplifyCondBranchToCondBranch(PBI, BI, DL))
  5199. return requestResimplify();
  5200. // Look for diamond patterns.
  5201. if (MergeCondStores)
  5202. if (BasicBlock *PrevBB = allPredecessorsComeFromSameSource(BB))
  5203. if (BranchInst *PBI = dyn_cast<BranchInst>(PrevBB->getTerminator()))
  5204. if (PBI != BI && PBI->isConditional())
  5205. if (mergeConditionalStores(PBI, BI, DL))
  5206. return requestResimplify();
  5207. return false;
  5208. }
  5209. /// Check if passing a value to an instruction will cause undefined behavior.
  5210. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  5211. Constant *C = dyn_cast<Constant>(V);
  5212. if (!C)
  5213. return false;
  5214. if (I->use_empty())
  5215. return false;
  5216. if (C->isNullValue() || isa<UndefValue>(C)) {
  5217. // Only look at the first use, avoid hurting compile time with long uselists
  5218. User *Use = *I->user_begin();
  5219. // Now make sure that there are no instructions in between that can alter
  5220. // control flow (eg. calls)
  5221. for (BasicBlock::iterator
  5222. i = ++BasicBlock::iterator(I),
  5223. UI = BasicBlock::iterator(dyn_cast<Instruction>(Use));
  5224. i != UI; ++i)
  5225. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  5226. return false;
  5227. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  5228. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  5229. if (GEP->getPointerOperand() == I)
  5230. return passingValueIsAlwaysUndefined(V, GEP);
  5231. // Look through bitcasts.
  5232. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  5233. return passingValueIsAlwaysUndefined(V, BC);
  5234. // Load from null is undefined.
  5235. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  5236. if (!LI->isVolatile())
  5237. return !NullPointerIsDefined(LI->getFunction(),
  5238. LI->getPointerAddressSpace());
  5239. // Store to null is undefined.
  5240. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  5241. if (!SI->isVolatile())
  5242. return (!NullPointerIsDefined(SI->getFunction(),
  5243. SI->getPointerAddressSpace())) &&
  5244. SI->getPointerOperand() == I;
  5245. // A call to null is undefined.
  5246. if (auto CS = CallSite(Use))
  5247. return !NullPointerIsDefined(CS->getFunction()) &&
  5248. CS.getCalledValue() == I;
  5249. }
  5250. return false;
  5251. }
  5252. /// If BB has an incoming value that will always trigger undefined behavior
  5253. /// (eg. null pointer dereference), remove the branch leading here.
  5254. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  5255. for (PHINode &PHI : BB->phis())
  5256. for (unsigned i = 0, e = PHI.getNumIncomingValues(); i != e; ++i)
  5257. if (passingValueIsAlwaysUndefined(PHI.getIncomingValue(i), &PHI)) {
  5258. Instruction *T = PHI.getIncomingBlock(i)->getTerminator();
  5259. IRBuilder<> Builder(T);
  5260. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  5261. BB->removePredecessor(PHI.getIncomingBlock(i));
  5262. // Turn uncoditional branches into unreachables and remove the dead
  5263. // destination from conditional branches.
  5264. if (BI->isUnconditional())
  5265. Builder.CreateUnreachable();
  5266. else
  5267. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1)
  5268. : BI->getSuccessor(0));
  5269. BI->eraseFromParent();
  5270. return true;
  5271. }
  5272. // TODO: SwitchInst.
  5273. }
  5274. return false;
  5275. }
  5276. bool SimplifyCFGOpt::simplifyOnce(BasicBlock *BB) {
  5277. bool Changed = false;
  5278. assert(BB && BB->getParent() && "Block not embedded in function!");
  5279. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  5280. // Remove basic blocks that have no predecessors (except the entry block)...
  5281. // or that just have themself as a predecessor. These are unreachable.
  5282. if ((pred_empty(BB) && BB != &BB->getParent()->getEntryBlock()) ||
  5283. BB->getSinglePredecessor() == BB) {
  5284. LLVM_DEBUG(dbgs() << "Removing BB: \n" << *BB);
  5285. DeleteDeadBlock(BB);
  5286. return true;
  5287. }
  5288. // Check to see if we can constant propagate this terminator instruction
  5289. // away...
  5290. Changed |= ConstantFoldTerminator(BB, true);
  5291. // Check for and eliminate duplicate PHI nodes in this block.
  5292. Changed |= EliminateDuplicatePHINodes(BB);
  5293. // Check for and remove branches that will always cause undefined behavior.
  5294. Changed |= removeUndefIntroducingPredecessor(BB);
  5295. // Merge basic blocks into their predecessor if there is only one distinct
  5296. // pred, and if there is only one distinct successor of the predecessor, and
  5297. // if there are no PHI nodes.
  5298. if (MergeBlockIntoPredecessor(BB))
  5299. return true;
  5300. if (SinkCommon && Options.SinkCommonInsts)
  5301. Changed |= SinkCommonCodeFromPredecessors(BB);
  5302. IRBuilder<> Builder(BB);
  5303. // If there is a trivial two-entry PHI node in this basic block, and we can
  5304. // eliminate it, do so now.
  5305. if (auto *PN = dyn_cast<PHINode>(BB->begin()))
  5306. if (PN->getNumIncomingValues() == 2)
  5307. Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
  5308. Builder.SetInsertPoint(BB->getTerminator());
  5309. if (auto *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  5310. if (BI->isUnconditional()) {
  5311. if (SimplifyUncondBranch(BI, Builder))
  5312. return true;
  5313. } else {
  5314. if (SimplifyCondBranch(BI, Builder))
  5315. return true;
  5316. }
  5317. } else if (auto *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  5318. if (SimplifyReturn(RI, Builder))
  5319. return true;
  5320. } else if (auto *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  5321. if (SimplifyResume(RI, Builder))
  5322. return true;
  5323. } else if (auto *RI = dyn_cast<CleanupReturnInst>(BB->getTerminator())) {
  5324. if (SimplifyCleanupReturn(RI))
  5325. return true;
  5326. } else if (auto *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  5327. if (SimplifySwitch(SI, Builder))
  5328. return true;
  5329. } else if (auto *UI = dyn_cast<UnreachableInst>(BB->getTerminator())) {
  5330. if (SimplifyUnreachable(UI))
  5331. return true;
  5332. } else if (auto *IBI = dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  5333. if (SimplifyIndirectBr(IBI))
  5334. return true;
  5335. }
  5336. return Changed;
  5337. }
  5338. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  5339. bool Changed = false;
  5340. // Repeated simplify BB as long as resimplification is requested.
  5341. do {
  5342. Resimplify = false;
  5343. // Perform one round of simplifcation. Resimplify flag will be set if
  5344. // another iteration is requested.
  5345. Changed |= simplifyOnce(BB);
  5346. } while (Resimplify);
  5347. return Changed;
  5348. }
  5349. bool llvm::simplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
  5350. const SimplifyCFGOptions &Options,
  5351. SmallPtrSetImpl<BasicBlock *> *LoopHeaders) {
  5352. return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(), LoopHeaders,
  5353. Options)
  5354. .run(BB);
  5355. }