SimplifyCFG.cpp 228 KB

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