SimplifyCFG.cpp 230 KB

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