SimplifyCFG.cpp 182 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721
  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/Transforms/Utils/Local.h"
  14. #include "llvm/ADT/DenseMap.h"
  15. #include "llvm/ADT/STLExtras.h"
  16. #include "llvm/ADT/SetVector.h"
  17. #include "llvm/ADT/SmallPtrSet.h"
  18. #include "llvm/ADT/SmallVector.h"
  19. #include "llvm/ADT/Statistic.h"
  20. #include "llvm/Analysis/ConstantFolding.h"
  21. #include "llvm/Analysis/InstructionSimplify.h"
  22. #include "llvm/Analysis/TargetTransformInfo.h"
  23. #include "llvm/Analysis/ValueTracking.h"
  24. #include "llvm/IR/CFG.h"
  25. #include "llvm/IR/ConstantRange.h"
  26. #include "llvm/IR/Constants.h"
  27. #include "llvm/IR/DataLayout.h"
  28. #include "llvm/IR/DerivedTypes.h"
  29. #include "llvm/IR/GlobalVariable.h"
  30. #include "llvm/IR/IRBuilder.h"
  31. #include "llvm/IR/Instructions.h"
  32. #include "llvm/IR/IntrinsicInst.h"
  33. #include "llvm/IR/LLVMContext.h"
  34. #include "llvm/IR/MDBuilder.h"
  35. #include "llvm/IR/Metadata.h"
  36. #include "llvm/IR/Module.h"
  37. #include "llvm/IR/NoFolder.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/IR/PatternMatch.h"
  40. #include "llvm/IR/Type.h"
  41. #include "llvm/Support/CommandLine.h"
  42. #include "llvm/Support/Debug.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  45. #include "llvm/Transforms/Utils/Local.h"
  46. #include "llvm/Transforms/Utils/ValueMapper.h"
  47. #include <algorithm>
  48. #include <map>
  49. #include <set>
  50. using namespace llvm;
  51. using namespace PatternMatch;
  52. #define DEBUG_TYPE "simplifycfg"
  53. // Chosen as 2 so as to be cheap, but still to have enough power to fold
  54. // a select, so the "clamp" idiom (of a min followed by a max) will be caught.
  55. // To catch this, we need to fold a compare and a select, hence '2' being the
  56. // minimum reasonable default.
  57. static cl::opt<unsigned>
  58. PHINodeFoldingThreshold("phi-node-folding-threshold", cl::Hidden, cl::init(2),
  59. cl::desc("Control the amount of phi node folding to perform (default = 2)"));
  60. static cl::opt<bool>
  61. DupRet("simplifycfg-dup-ret", cl::Hidden, cl::init(false),
  62. cl::desc("Duplicate return instructions into unconditional branches"));
  63. static cl::opt<bool>
  64. SinkCommon("simplifycfg-sink-common", cl::Hidden, cl::init(true),
  65. cl::desc("Sink common instructions down to the end block"));
  66. static cl::opt<bool> HoistCondStores(
  67. "simplifycfg-hoist-cond-stores", cl::Hidden, cl::init(true),
  68. cl::desc("Hoist conditional stores if an unconditional store precedes"));
  69. STATISTIC(NumBitMaps, "Number of switch instructions turned into bitmaps");
  70. STATISTIC(NumLinearMaps, "Number of switch instructions turned into linear mapping");
  71. STATISTIC(NumLookupTables, "Number of switch instructions turned into lookup tables");
  72. STATISTIC(NumLookupTablesHoles, "Number of switch instructions turned into lookup tables (holes checked)");
  73. STATISTIC(NumTableCmpReuses, "Number of reused switch table lookup compares");
  74. STATISTIC(NumSinkCommons, "Number of common instructions sunk down to the end block");
  75. STATISTIC(NumSpeculations, "Number of speculative executed instructions");
  76. namespace {
  77. // The first field contains the value that the switch produces when a certain
  78. // case group is selected, and the second field is a vector containing the cases
  79. // composing the case group.
  80. typedef SmallVector<std::pair<Constant *, SmallVector<ConstantInt *, 4>>, 2>
  81. SwitchCaseResultVectorTy;
  82. // The first field contains the phi node that generates a result of the switch
  83. // and the second field contains the value generated for a certain case in the switch
  84. // for that PHI.
  85. typedef SmallVector<std::pair<PHINode *, Constant *>, 4> SwitchCaseResultsTy;
  86. /// ValueEqualityComparisonCase - Represents a case of a switch.
  87. struct ValueEqualityComparisonCase {
  88. ConstantInt *Value;
  89. BasicBlock *Dest;
  90. ValueEqualityComparisonCase(ConstantInt *Value, BasicBlock *Dest)
  91. : Value(Value), Dest(Dest) {}
  92. bool operator<(ValueEqualityComparisonCase RHS) const {
  93. // Comparing pointers is ok as we only rely on the order for uniquing.
  94. return Value < RHS.Value;
  95. }
  96. bool operator==(BasicBlock *RHSDest) const { return Dest == RHSDest; }
  97. };
  98. class SimplifyCFGOpt {
  99. const TargetTransformInfo &TTI;
  100. const DataLayout &DL;
  101. unsigned BonusInstThreshold;
  102. AssumptionCache *AC;
  103. Value *isValueEqualityComparison(TerminatorInst *TI);
  104. BasicBlock *GetValueEqualityComparisonCases(TerminatorInst *TI,
  105. std::vector<ValueEqualityComparisonCase> &Cases);
  106. bool SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  107. BasicBlock *Pred,
  108. IRBuilder<> &Builder);
  109. bool FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  110. IRBuilder<> &Builder);
  111. bool SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder);
  112. bool SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder);
  113. bool SimplifyUnreachable(UnreachableInst *UI);
  114. bool SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder);
  115. bool SimplifyIndirectBr(IndirectBrInst *IBI);
  116. bool SimplifyUncondBranch(BranchInst *BI, IRBuilder <> &Builder);
  117. bool SimplifyCondBranch(BranchInst *BI, IRBuilder <>&Builder);
  118. public:
  119. SimplifyCFGOpt(const TargetTransformInfo &TTI, const DataLayout &DL,
  120. unsigned BonusInstThreshold, AssumptionCache *AC)
  121. : TTI(TTI), DL(DL), BonusInstThreshold(BonusInstThreshold), AC(AC) {}
  122. bool run(BasicBlock *BB);
  123. };
  124. }
  125. /// Return true if it is safe to merge these two
  126. /// terminator instructions together.
  127. static bool SafeToMergeTerminators(TerminatorInst *SI1, TerminatorInst *SI2) {
  128. if (SI1 == SI2) return false; // Can't merge with self!
  129. // It is not safe to merge these two switch instructions if they have a common
  130. // successor, and if that successor has a PHI node, and if *that* PHI node has
  131. // conflicting incoming values from the two switch blocks.
  132. BasicBlock *SI1BB = SI1->getParent();
  133. BasicBlock *SI2BB = SI2->getParent();
  134. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  135. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  136. if (SI1Succs.count(*I))
  137. for (BasicBlock::iterator BBI = (*I)->begin();
  138. isa<PHINode>(BBI); ++BBI) {
  139. PHINode *PN = cast<PHINode>(BBI);
  140. if (PN->getIncomingValueForBlock(SI1BB) !=
  141. PN->getIncomingValueForBlock(SI2BB))
  142. return false;
  143. }
  144. return true;
  145. }
  146. /// Return true if it is safe and profitable to merge these two terminator
  147. /// instructions together, where SI1 is an unconditional branch. PhiNodes will
  148. /// store all PHI nodes in common successors.
  149. static bool isProfitableToFoldUnconditional(BranchInst *SI1,
  150. BranchInst *SI2,
  151. Instruction *Cond,
  152. SmallVectorImpl<PHINode*> &PhiNodes) {
  153. if (SI1 == SI2) return false; // Can't merge with self!
  154. assert(SI1->isUnconditional() && SI2->isConditional());
  155. // We fold the unconditional branch if we can easily update all PHI nodes in
  156. // common successors:
  157. // 1> We have a constant incoming value for the conditional branch;
  158. // 2> We have "Cond" as the incoming value for the unconditional branch;
  159. // 3> SI2->getCondition() and Cond have same operands.
  160. CmpInst *Ci2 = dyn_cast<CmpInst>(SI2->getCondition());
  161. if (!Ci2) return false;
  162. if (!(Cond->getOperand(0) == Ci2->getOperand(0) &&
  163. Cond->getOperand(1) == Ci2->getOperand(1)) &&
  164. !(Cond->getOperand(0) == Ci2->getOperand(1) &&
  165. Cond->getOperand(1) == Ci2->getOperand(0)))
  166. return false;
  167. BasicBlock *SI1BB = SI1->getParent();
  168. BasicBlock *SI2BB = SI2->getParent();
  169. SmallPtrSet<BasicBlock*, 16> SI1Succs(succ_begin(SI1BB), succ_end(SI1BB));
  170. for (succ_iterator I = succ_begin(SI2BB), E = succ_end(SI2BB); I != E; ++I)
  171. if (SI1Succs.count(*I))
  172. for (BasicBlock::iterator BBI = (*I)->begin();
  173. isa<PHINode>(BBI); ++BBI) {
  174. PHINode *PN = cast<PHINode>(BBI);
  175. if (PN->getIncomingValueForBlock(SI1BB) != Cond ||
  176. !isa<ConstantInt>(PN->getIncomingValueForBlock(SI2BB)))
  177. return false;
  178. PhiNodes.push_back(PN);
  179. }
  180. return true;
  181. }
  182. /// Update PHI nodes in Succ to indicate that there will now be entries in it
  183. /// from the 'NewPred' block. The values that will be flowing into the PHI nodes
  184. /// will be the same as those coming in from ExistPred, an existing predecessor
  185. /// of Succ.
  186. static void AddPredecessorToBlock(BasicBlock *Succ, BasicBlock *NewPred,
  187. BasicBlock *ExistPred) {
  188. if (!isa<PHINode>(Succ->begin())) return; // Quick exit if nothing to do
  189. PHINode *PN;
  190. for (BasicBlock::iterator I = Succ->begin();
  191. (PN = dyn_cast<PHINode>(I)); ++I)
  192. PN->addIncoming(PN->getIncomingValueForBlock(ExistPred), NewPred);
  193. }
  194. /// Compute an abstract "cost" of speculating the given instruction,
  195. /// which is assumed to be safe to speculate. TCC_Free means cheap,
  196. /// TCC_Basic means less cheap, and TCC_Expensive means prohibitively
  197. /// expensive.
  198. static unsigned ComputeSpeculationCost(const User *I,
  199. const TargetTransformInfo &TTI) {
  200. assert(isSafeToSpeculativelyExecute(I) &&
  201. "Instruction is not safe to speculatively execute!");
  202. return TTI.getUserCost(I);
  203. }
  204. /// If we have a merge point of an "if condition" as accepted above,
  205. /// return true if the specified value dominates the block. We
  206. /// don't handle the true generality of domination here, just a special case
  207. /// which works well enough for us.
  208. ///
  209. /// If AggressiveInsts is non-null, and if V does not dominate BB, we check to
  210. /// see if V (which must be an instruction) and its recursive operands
  211. /// that do not dominate BB have a combined cost lower than CostRemaining and
  212. /// are non-trapping. If both are true, the instruction is inserted into the
  213. /// set and true is returned.
  214. ///
  215. /// The cost for most non-trapping instructions is defined as 1 except for
  216. /// Select whose cost is 2.
  217. ///
  218. /// After this function returns, CostRemaining is decreased by the cost of
  219. /// V plus its non-dominating operands. If that cost is greater than
  220. /// CostRemaining, false is returned and CostRemaining is undefined.
  221. static bool DominatesMergePoint(Value *V, BasicBlock *BB,
  222. SmallPtrSetImpl<Instruction*> *AggressiveInsts,
  223. unsigned &CostRemaining,
  224. const TargetTransformInfo &TTI) {
  225. Instruction *I = dyn_cast<Instruction>(V);
  226. if (!I) {
  227. // Non-instructions all dominate instructions, but not all constantexprs
  228. // can be executed unconditionally.
  229. if (ConstantExpr *C = dyn_cast<ConstantExpr>(V))
  230. if (C->canTrap())
  231. return false;
  232. return true;
  233. }
  234. BasicBlock *PBB = I->getParent();
  235. // We don't want to allow weird loops that might have the "if condition" in
  236. // the bottom of this block.
  237. if (PBB == BB) return false;
  238. // If this instruction is defined in a block that contains an unconditional
  239. // branch to BB, then it must be in the 'conditional' part of the "if
  240. // statement". If not, it definitely dominates the region.
  241. BranchInst *BI = dyn_cast<BranchInst>(PBB->getTerminator());
  242. if (!BI || BI->isConditional() || BI->getSuccessor(0) != BB)
  243. return true;
  244. // If we aren't allowing aggressive promotion anymore, then don't consider
  245. // instructions in the 'if region'.
  246. if (!AggressiveInsts) return false;
  247. // If we have seen this instruction before, don't count it again.
  248. if (AggressiveInsts->count(I)) return true;
  249. // Okay, it looks like the instruction IS in the "condition". Check to
  250. // see if it's a cheap instruction to unconditionally compute, and if it
  251. // only uses stuff defined outside of the condition. If so, hoist it out.
  252. if (!isSafeToSpeculativelyExecute(I))
  253. return false;
  254. unsigned Cost = ComputeSpeculationCost(I, TTI);
  255. if (Cost > CostRemaining)
  256. return false;
  257. CostRemaining -= Cost;
  258. // Okay, we can only really hoist these out if their operands do
  259. // not take us over the cost threshold.
  260. for (User::op_iterator i = I->op_begin(), e = I->op_end(); i != e; ++i)
  261. if (!DominatesMergePoint(*i, BB, AggressiveInsts, CostRemaining, TTI))
  262. return false;
  263. // Okay, it's safe to do this! Remember this instruction.
  264. AggressiveInsts->insert(I);
  265. return true;
  266. }
  267. /// Extract ConstantInt from value, looking through IntToPtr
  268. /// and PointerNullValue. Return NULL if value is not a constant int.
  269. static ConstantInt *GetConstantInt(Value *V, const DataLayout &DL) {
  270. // Normal constant int.
  271. ConstantInt *CI = dyn_cast<ConstantInt>(V);
  272. if (CI || !isa<Constant>(V) || !V->getType()->isPointerTy())
  273. return CI;
  274. // This is some kind of pointer constant. Turn it into a pointer-sized
  275. // ConstantInt if possible.
  276. IntegerType *PtrTy = cast<IntegerType>(DL.getIntPtrType(V->getType()));
  277. // Null pointer means 0, see SelectionDAGBuilder::getValue(const Value*).
  278. if (isa<ConstantPointerNull>(V))
  279. return ConstantInt::get(PtrTy, 0);
  280. // IntToPtr const int.
  281. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
  282. if (CE->getOpcode() == Instruction::IntToPtr)
  283. if (ConstantInt *CI = dyn_cast<ConstantInt>(CE->getOperand(0))) {
  284. // The constant is very likely to have the right type already.
  285. if (CI->getType() == PtrTy)
  286. return CI;
  287. else
  288. return cast<ConstantInt>
  289. (ConstantExpr::getIntegerCast(CI, PtrTy, /*isSigned=*/false));
  290. }
  291. return nullptr;
  292. }
  293. namespace {
  294. /// Given a chain of or (||) or and (&&) comparison of a value against a
  295. /// constant, this will try to recover the information required for a switch
  296. /// structure.
  297. /// It will depth-first traverse the chain of comparison, seeking for patterns
  298. /// like %a == 12 or %a < 4 and combine them to produce a set of integer
  299. /// representing the different cases for the switch.
  300. /// Note that if the chain is composed of '||' it will build the set of elements
  301. /// that matches the comparisons (i.e. any of this value validate the chain)
  302. /// while for a chain of '&&' it will build the set elements that make the test
  303. /// fail.
  304. struct ConstantComparesGatherer {
  305. const DataLayout &DL;
  306. Value *CompValue; /// Value found for the switch comparison
  307. Value *Extra; /// Extra clause to be checked before the switch
  308. SmallVector<ConstantInt *, 8> Vals; /// Set of integers to match in switch
  309. unsigned UsedICmps; /// Number of comparisons matched in the and/or chain
  310. /// Construct and compute the result for the comparison instruction Cond
  311. ConstantComparesGatherer(Instruction *Cond, const DataLayout &DL)
  312. : DL(DL), CompValue(nullptr), Extra(nullptr), UsedICmps(0) {
  313. gather(Cond);
  314. }
  315. /// Prevent copy
  316. ConstantComparesGatherer(const ConstantComparesGatherer &) = delete;
  317. ConstantComparesGatherer &
  318. operator=(const ConstantComparesGatherer &) = delete;
  319. private:
  320. /// Try to set the current value used for the comparison, it succeeds only if
  321. /// it wasn't set before or if the new value is the same as the old one
  322. bool setValueOnce(Value *NewVal) {
  323. if(CompValue && CompValue != NewVal) return false;
  324. CompValue = NewVal;
  325. return (CompValue != nullptr);
  326. }
  327. /// Try to match Instruction "I" as a comparison against a constant and
  328. /// populates the array Vals with the set of values that match (or do not
  329. /// match depending on isEQ).
  330. /// Return false on failure. On success, the Value the comparison matched
  331. /// against is placed in CompValue.
  332. /// If CompValue is already set, the function is expected to fail if a match
  333. /// is found but the value compared to is different.
  334. bool matchInstruction(Instruction *I, bool isEQ) {
  335. // If this is an icmp against a constant, handle this as one of the cases.
  336. ICmpInst *ICI;
  337. ConstantInt *C;
  338. if (!((ICI = dyn_cast<ICmpInst>(I)) &&
  339. (C = GetConstantInt(I->getOperand(1), DL)))) {
  340. return false;
  341. }
  342. Value *RHSVal;
  343. ConstantInt *RHSC;
  344. // Pattern match a special case
  345. // (x & ~2^x) == y --> x == y || x == y|2^x
  346. // This undoes a transformation done by instcombine to fuse 2 compares.
  347. if (ICI->getPredicate() == (isEQ ? ICmpInst::ICMP_EQ:ICmpInst::ICMP_NE)) {
  348. if (match(ICI->getOperand(0),
  349. m_And(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
  350. APInt Not = ~RHSC->getValue();
  351. if (Not.isPowerOf2()) {
  352. // If we already have a value for the switch, it has to match!
  353. if(!setValueOnce(RHSVal))
  354. return false;
  355. Vals.push_back(C);
  356. Vals.push_back(ConstantInt::get(C->getContext(),
  357. C->getValue() | Not));
  358. UsedICmps++;
  359. return true;
  360. }
  361. }
  362. // If we already have a value for the switch, it has to match!
  363. if(!setValueOnce(ICI->getOperand(0)))
  364. return false;
  365. UsedICmps++;
  366. Vals.push_back(C);
  367. return ICI->getOperand(0);
  368. }
  369. // If we have "x ult 3", for example, then we can add 0,1,2 to the set.
  370. ConstantRange Span = ConstantRange::makeAllowedICmpRegion(
  371. ICI->getPredicate(), C->getValue());
  372. // Shift the range if the compare is fed by an add. This is the range
  373. // compare idiom as emitted by instcombine.
  374. Value *CandidateVal = I->getOperand(0);
  375. if(match(I->getOperand(0), m_Add(m_Value(RHSVal), m_ConstantInt(RHSC)))) {
  376. Span = Span.subtract(RHSC->getValue());
  377. CandidateVal = RHSVal;
  378. }
  379. // If this is an and/!= check, then we are looking to build the set of
  380. // value that *don't* pass the and chain. I.e. to turn "x ugt 2" into
  381. // x != 0 && x != 1.
  382. if (!isEQ)
  383. Span = Span.inverse();
  384. // If there are a ton of values, we don't want to make a ginormous switch.
  385. if (Span.getSetSize().ugt(8) || Span.isEmptySet()) {
  386. return false;
  387. }
  388. // If we already have a value for the switch, it has to match!
  389. if(!setValueOnce(CandidateVal))
  390. return false;
  391. // Add all values from the range to the set
  392. for (APInt Tmp = Span.getLower(); Tmp != Span.getUpper(); ++Tmp)
  393. Vals.push_back(ConstantInt::get(I->getContext(), Tmp));
  394. UsedICmps++;
  395. return true;
  396. }
  397. /// Given a potentially 'or'd or 'and'd together collection of icmp
  398. /// eq/ne/lt/gt instructions that compare a value against a constant, extract
  399. /// the value being compared, and stick the list constants into the Vals
  400. /// vector.
  401. /// One "Extra" case is allowed to differ from the other.
  402. void gather(Value *V) {
  403. Instruction *I = dyn_cast<Instruction>(V);
  404. bool isEQ = (I->getOpcode() == Instruction::Or);
  405. // Keep a stack (SmallVector for efficiency) for depth-first traversal
  406. SmallVector<Value *, 8> DFT;
  407. // Initialize
  408. DFT.push_back(V);
  409. while(!DFT.empty()) {
  410. V = DFT.pop_back_val();
  411. if (Instruction *I = dyn_cast<Instruction>(V)) {
  412. // If it is a || (or && depending on isEQ), process the operands.
  413. if (I->getOpcode() == (isEQ ? Instruction::Or : Instruction::And)) {
  414. DFT.push_back(I->getOperand(1));
  415. DFT.push_back(I->getOperand(0));
  416. continue;
  417. }
  418. // Try to match the current instruction
  419. if (matchInstruction(I, isEQ))
  420. // Match succeed, continue the loop
  421. continue;
  422. }
  423. // One element of the sequence of || (or &&) could not be match as a
  424. // comparison against the same value as the others.
  425. // We allow only one "Extra" case to be checked before the switch
  426. if (!Extra) {
  427. Extra = V;
  428. continue;
  429. }
  430. // Failed to parse a proper sequence, abort now
  431. CompValue = nullptr;
  432. break;
  433. }
  434. }
  435. };
  436. }
  437. static void EraseTerminatorInstAndDCECond(TerminatorInst *TI) {
  438. Instruction *Cond = nullptr;
  439. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  440. Cond = dyn_cast<Instruction>(SI->getCondition());
  441. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  442. if (BI->isConditional())
  443. Cond = dyn_cast<Instruction>(BI->getCondition());
  444. } else if (IndirectBrInst *IBI = dyn_cast<IndirectBrInst>(TI)) {
  445. Cond = dyn_cast<Instruction>(IBI->getAddress());
  446. }
  447. TI->eraseFromParent();
  448. if (Cond) RecursivelyDeleteTriviallyDeadInstructions(Cond);
  449. }
  450. /// Return true if the specified terminator checks
  451. /// to see if a value is equal to constant integer value.
  452. Value *SimplifyCFGOpt::isValueEqualityComparison(TerminatorInst *TI) {
  453. Value *CV = nullptr;
  454. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  455. // Do not permit merging of large switch instructions into their
  456. // predecessors unless there is only one predecessor.
  457. if (SI->getNumSuccessors()*std::distance(pred_begin(SI->getParent()),
  458. pred_end(SI->getParent())) <= 128)
  459. CV = SI->getCondition();
  460. } else if (BranchInst *BI = dyn_cast<BranchInst>(TI))
  461. if (BI->isConditional() && BI->getCondition()->hasOneUse())
  462. if (ICmpInst *ICI = dyn_cast<ICmpInst>(BI->getCondition())) {
  463. if (ICI->isEquality() && GetConstantInt(ICI->getOperand(1), DL))
  464. CV = ICI->getOperand(0);
  465. }
  466. // Unwrap any lossless ptrtoint cast.
  467. if (CV) {
  468. if (PtrToIntInst *PTII = dyn_cast<PtrToIntInst>(CV)) {
  469. Value *Ptr = PTII->getPointerOperand();
  470. if (PTII->getType() == DL.getIntPtrType(Ptr->getType()))
  471. CV = Ptr;
  472. }
  473. }
  474. return CV;
  475. }
  476. /// Given a value comparison instruction,
  477. /// decode all of the 'cases' that it represents and return the 'default' block.
  478. BasicBlock *SimplifyCFGOpt::
  479. GetValueEqualityComparisonCases(TerminatorInst *TI,
  480. std::vector<ValueEqualityComparisonCase>
  481. &Cases) {
  482. if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  483. Cases.reserve(SI->getNumCases());
  484. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end(); i != e; ++i)
  485. Cases.push_back(ValueEqualityComparisonCase(i.getCaseValue(),
  486. i.getCaseSuccessor()));
  487. return SI->getDefaultDest();
  488. }
  489. BranchInst *BI = cast<BranchInst>(TI);
  490. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  491. BasicBlock *Succ = BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_NE);
  492. Cases.push_back(ValueEqualityComparisonCase(GetConstantInt(ICI->getOperand(1),
  493. DL),
  494. Succ));
  495. return BI->getSuccessor(ICI->getPredicate() == ICmpInst::ICMP_EQ);
  496. }
  497. /// Given a vector of bb/value pairs, remove any entries
  498. /// in the list that match the specified block.
  499. static void EliminateBlockCases(BasicBlock *BB,
  500. std::vector<ValueEqualityComparisonCase> &Cases) {
  501. Cases.erase(std::remove(Cases.begin(), Cases.end(), BB), Cases.end());
  502. }
  503. /// Return true if there are any keys in C1 that exist in C2 as well.
  504. static bool
  505. ValuesOverlap(std::vector<ValueEqualityComparisonCase> &C1,
  506. std::vector<ValueEqualityComparisonCase > &C2) {
  507. std::vector<ValueEqualityComparisonCase> *V1 = &C1, *V2 = &C2;
  508. // Make V1 be smaller than V2.
  509. if (V1->size() > V2->size())
  510. std::swap(V1, V2);
  511. if (V1->size() == 0) return false;
  512. if (V1->size() == 1) {
  513. // Just scan V2.
  514. ConstantInt *TheVal = (*V1)[0].Value;
  515. for (unsigned i = 0, e = V2->size(); i != e; ++i)
  516. if (TheVal == (*V2)[i].Value)
  517. return true;
  518. }
  519. // Otherwise, just sort both lists and compare element by element.
  520. array_pod_sort(V1->begin(), V1->end());
  521. array_pod_sort(V2->begin(), V2->end());
  522. unsigned i1 = 0, i2 = 0, e1 = V1->size(), e2 = V2->size();
  523. while (i1 != e1 && i2 != e2) {
  524. if ((*V1)[i1].Value == (*V2)[i2].Value)
  525. return true;
  526. if ((*V1)[i1].Value < (*V2)[i2].Value)
  527. ++i1;
  528. else
  529. ++i2;
  530. }
  531. return false;
  532. }
  533. /// If TI is known to be a terminator instruction and its block is known to
  534. /// only have a single predecessor block, check to see if that predecessor is
  535. /// also a value comparison with the same value, and if that comparison
  536. /// determines the outcome of this comparison. If so, simplify TI. This does a
  537. /// very limited form of jump threading.
  538. bool SimplifyCFGOpt::
  539. SimplifyEqualityComparisonWithOnlyPredecessor(TerminatorInst *TI,
  540. BasicBlock *Pred,
  541. IRBuilder<> &Builder) {
  542. Value *PredVal = isValueEqualityComparison(Pred->getTerminator());
  543. if (!PredVal) return false; // Not a value comparison in predecessor.
  544. Value *ThisVal = isValueEqualityComparison(TI);
  545. assert(ThisVal && "This isn't a value comparison!!");
  546. if (ThisVal != PredVal) return false; // Different predicates.
  547. // TODO: Preserve branch weight metadata, similarly to how
  548. // FoldValueComparisonIntoPredecessors preserves it.
  549. // Find out information about when control will move from Pred to TI's block.
  550. std::vector<ValueEqualityComparisonCase> PredCases;
  551. BasicBlock *PredDef = GetValueEqualityComparisonCases(Pred->getTerminator(),
  552. PredCases);
  553. EliminateBlockCases(PredDef, PredCases); // Remove default from cases.
  554. // Find information about how control leaves this block.
  555. std::vector<ValueEqualityComparisonCase> ThisCases;
  556. BasicBlock *ThisDef = GetValueEqualityComparisonCases(TI, ThisCases);
  557. EliminateBlockCases(ThisDef, ThisCases); // Remove default from cases.
  558. // If TI's block is the default block from Pred's comparison, potentially
  559. // simplify TI based on this knowledge.
  560. if (PredDef == TI->getParent()) {
  561. // If we are here, we know that the value is none of those cases listed in
  562. // PredCases. If there are any cases in ThisCases that are in PredCases, we
  563. // can simplify TI.
  564. if (!ValuesOverlap(PredCases, ThisCases))
  565. return false;
  566. if (isa<BranchInst>(TI)) {
  567. // Okay, one of the successors of this condbr is dead. Convert it to a
  568. // uncond br.
  569. assert(ThisCases.size() == 1 && "Branch can only have one case!");
  570. // Insert the new branch.
  571. Instruction *NI = Builder.CreateBr(ThisDef);
  572. (void) NI;
  573. // Remove PHI node entries for the dead edge.
  574. ThisCases[0].Dest->removePredecessor(TI->getParent());
  575. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  576. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  577. EraseTerminatorInstAndDCECond(TI);
  578. return true;
  579. }
  580. SwitchInst *SI = cast<SwitchInst>(TI);
  581. // Okay, TI has cases that are statically dead, prune them away.
  582. SmallPtrSet<Constant*, 16> DeadCases;
  583. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  584. DeadCases.insert(PredCases[i].Value);
  585. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  586. << "Through successor TI: " << *TI);
  587. // Collect branch weights into a vector.
  588. SmallVector<uint32_t, 8> Weights;
  589. MDNode *MD = SI->getMetadata(LLVMContext::MD_prof);
  590. bool HasWeight = MD && (MD->getNumOperands() == 2 + SI->getNumCases());
  591. if (HasWeight)
  592. for (unsigned MD_i = 1, MD_e = MD->getNumOperands(); MD_i < MD_e;
  593. ++MD_i) {
  594. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(MD_i));
  595. Weights.push_back(CI->getValue().getZExtValue());
  596. }
  597. for (SwitchInst::CaseIt i = SI->case_end(), e = SI->case_begin(); i != e;) {
  598. --i;
  599. if (DeadCases.count(i.getCaseValue())) {
  600. if (HasWeight) {
  601. std::swap(Weights[i.getCaseIndex()+1], Weights.back());
  602. Weights.pop_back();
  603. }
  604. i.getCaseSuccessor()->removePredecessor(TI->getParent());
  605. SI->removeCase(i);
  606. }
  607. }
  608. if (HasWeight && Weights.size() >= 2)
  609. SI->setMetadata(LLVMContext::MD_prof,
  610. MDBuilder(SI->getParent()->getContext()).
  611. createBranchWeights(Weights));
  612. DEBUG(dbgs() << "Leaving: " << *TI << "\n");
  613. return true;
  614. }
  615. // Otherwise, TI's block must correspond to some matched value. Find out
  616. // which value (or set of values) this is.
  617. ConstantInt *TIV = nullptr;
  618. BasicBlock *TIBB = TI->getParent();
  619. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  620. if (PredCases[i].Dest == TIBB) {
  621. if (TIV)
  622. return false; // Cannot handle multiple values coming to this block.
  623. TIV = PredCases[i].Value;
  624. }
  625. assert(TIV && "No edge from pred to succ?");
  626. // Okay, we found the one constant that our value can be if we get into TI's
  627. // BB. Find out which successor will unconditionally be branched to.
  628. BasicBlock *TheRealDest = nullptr;
  629. for (unsigned i = 0, e = ThisCases.size(); i != e; ++i)
  630. if (ThisCases[i].Value == TIV) {
  631. TheRealDest = ThisCases[i].Dest;
  632. break;
  633. }
  634. // If not handled by any explicit cases, it is handled by the default case.
  635. if (!TheRealDest) TheRealDest = ThisDef;
  636. // Remove PHI node entries for dead edges.
  637. BasicBlock *CheckEdge = TheRealDest;
  638. for (succ_iterator SI = succ_begin(TIBB), e = succ_end(TIBB); SI != e; ++SI)
  639. if (*SI != CheckEdge)
  640. (*SI)->removePredecessor(TIBB);
  641. else
  642. CheckEdge = nullptr;
  643. // Insert the new branch.
  644. Instruction *NI = Builder.CreateBr(TheRealDest);
  645. (void) NI;
  646. DEBUG(dbgs() << "Threading pred instr: " << *Pred->getTerminator()
  647. << "Through successor TI: " << *TI << "Leaving: " << *NI << "\n");
  648. EraseTerminatorInstAndDCECond(TI);
  649. return true;
  650. }
  651. namespace {
  652. /// This class implements a stable ordering of constant
  653. /// integers that does not depend on their address. This is important for
  654. /// applications that sort ConstantInt's to ensure uniqueness.
  655. struct ConstantIntOrdering {
  656. bool operator()(const ConstantInt *LHS, const ConstantInt *RHS) const {
  657. return LHS->getValue().ult(RHS->getValue());
  658. }
  659. };
  660. }
  661. // HLSL Change: changed calling convention to __cdecl
  662. static int __cdecl ConstantIntSortPredicate(ConstantInt *const *P1,
  663. ConstantInt *const *P2) {
  664. const ConstantInt *LHS = *P1;
  665. const ConstantInt *RHS = *P2;
  666. if (LHS->getValue().ult(RHS->getValue()))
  667. return 1;
  668. if (LHS->getValue() == RHS->getValue())
  669. return 0;
  670. return -1;
  671. }
  672. static inline bool HasBranchWeights(const Instruction* I) {
  673. MDNode *ProfMD = I->getMetadata(LLVMContext::MD_prof);
  674. if (ProfMD && ProfMD->getOperand(0))
  675. if (MDString* MDS = dyn_cast<MDString>(ProfMD->getOperand(0)))
  676. return MDS->getString().equals("branch_weights");
  677. return false;
  678. }
  679. /// Get Weights of a given TerminatorInst, the default weight is at the front
  680. /// of the vector. If TI is a conditional eq, we need to swap the branch-weight
  681. /// metadata.
  682. static void GetBranchWeights(TerminatorInst *TI,
  683. SmallVectorImpl<uint64_t> &Weights) {
  684. MDNode *MD = TI->getMetadata(LLVMContext::MD_prof);
  685. assert(MD);
  686. for (unsigned i = 1, e = MD->getNumOperands(); i < e; ++i) {
  687. ConstantInt *CI = mdconst::extract<ConstantInt>(MD->getOperand(i));
  688. Weights.push_back(CI->getValue().getZExtValue());
  689. }
  690. // If TI is a conditional eq, the default case is the false case,
  691. // and the corresponding branch-weight data is at index 2. We swap the
  692. // default weight to be the first entry.
  693. if (BranchInst* BI = dyn_cast<BranchInst>(TI)) {
  694. assert(Weights.size() == 2);
  695. ICmpInst *ICI = cast<ICmpInst>(BI->getCondition());
  696. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  697. std::swap(Weights.front(), Weights.back());
  698. }
  699. }
  700. /// Keep halving the weights until all can fit in uint32_t.
  701. static void FitWeights(MutableArrayRef<uint64_t> Weights) {
  702. uint64_t Max = *std::max_element(Weights.begin(), Weights.end());
  703. if (Max > UINT_MAX) {
  704. unsigned Offset = 32 - countLeadingZeros(Max);
  705. for (uint64_t &I : Weights)
  706. I >>= Offset;
  707. }
  708. }
  709. /// The specified terminator is a value equality comparison instruction
  710. /// (either a switch or a branch on "X == c").
  711. /// See if any of the predecessors of the terminator block are value comparisons
  712. /// on the same value. If so, and if safe to do so, fold them together.
  713. bool SimplifyCFGOpt::FoldValueComparisonIntoPredecessors(TerminatorInst *TI,
  714. IRBuilder<> &Builder) {
  715. #if 0 // HLSL Change - fold to switch will not help hlsl.
  716. BasicBlock *BB = TI->getParent();
  717. Value *CV = isValueEqualityComparison(TI); // CondVal
  718. assert(CV && "Not a comparison?");
  719. bool Changed = false;
  720. SmallVector<BasicBlock*, 16> Preds(pred_begin(BB), pred_end(BB));
  721. while (!Preds.empty()) {
  722. BasicBlock *Pred = Preds.pop_back_val();
  723. // See if the predecessor is a comparison with the same value.
  724. TerminatorInst *PTI = Pred->getTerminator();
  725. Value *PCV = isValueEqualityComparison(PTI); // PredCondVal
  726. if (PCV == CV && SafeToMergeTerminators(TI, PTI)) {
  727. // Figure out which 'cases' to copy from SI to PSI.
  728. std::vector<ValueEqualityComparisonCase> BBCases;
  729. BasicBlock *BBDefault = GetValueEqualityComparisonCases(TI, BBCases);
  730. std::vector<ValueEqualityComparisonCase> PredCases;
  731. BasicBlock *PredDefault = GetValueEqualityComparisonCases(PTI, PredCases);
  732. // Based on whether the default edge from PTI goes to BB or not, fill in
  733. // PredCases and PredDefault with the new switch cases we would like to
  734. // build.
  735. SmallVector<BasicBlock*, 8> NewSuccessors;
  736. // Update the branch weight metadata along the way
  737. SmallVector<uint64_t, 8> Weights;
  738. bool PredHasWeights = HasBranchWeights(PTI);
  739. bool SuccHasWeights = HasBranchWeights(TI);
  740. if (PredHasWeights) {
  741. GetBranchWeights(PTI, Weights);
  742. // branch-weight metadata is inconsistent here.
  743. if (Weights.size() != 1 + PredCases.size())
  744. PredHasWeights = SuccHasWeights = false;
  745. } else if (SuccHasWeights)
  746. // If there are no predecessor weights but there are successor weights,
  747. // populate Weights with 1, which will later be scaled to the sum of
  748. // successor's weights
  749. Weights.assign(1 + PredCases.size(), 1);
  750. SmallVector<uint64_t, 8> SuccWeights;
  751. if (SuccHasWeights) {
  752. GetBranchWeights(TI, SuccWeights);
  753. // branch-weight metadata is inconsistent here.
  754. if (SuccWeights.size() != 1 + BBCases.size())
  755. PredHasWeights = SuccHasWeights = false;
  756. } else if (PredHasWeights)
  757. SuccWeights.assign(1 + BBCases.size(), 1);
  758. if (PredDefault == BB) {
  759. // If this is the default destination from PTI, only the edges in TI
  760. // that don't occur in PTI, or that branch to BB will be activated.
  761. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  762. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  763. if (PredCases[i].Dest != BB)
  764. PTIHandled.insert(PredCases[i].Value);
  765. else {
  766. // The default destination is BB, we don't need explicit targets.
  767. std::swap(PredCases[i], PredCases.back());
  768. if (PredHasWeights || SuccHasWeights) {
  769. // Increase weight for the default case.
  770. Weights[0] += Weights[i+1];
  771. std::swap(Weights[i+1], Weights.back());
  772. Weights.pop_back();
  773. }
  774. PredCases.pop_back();
  775. --i; --e;
  776. }
  777. // Reconstruct the new switch statement we will be building.
  778. if (PredDefault != BBDefault) {
  779. PredDefault->removePredecessor(Pred);
  780. PredDefault = BBDefault;
  781. NewSuccessors.push_back(BBDefault);
  782. }
  783. unsigned CasesFromPred = Weights.size();
  784. uint64_t ValidTotalSuccWeight = 0;
  785. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  786. if (!PTIHandled.count(BBCases[i].Value) &&
  787. BBCases[i].Dest != BBDefault) {
  788. PredCases.push_back(BBCases[i]);
  789. NewSuccessors.push_back(BBCases[i].Dest);
  790. if (SuccHasWeights || PredHasWeights) {
  791. // The default weight is at index 0, so weight for the ith case
  792. // should be at index i+1. Scale the cases from successor by
  793. // PredDefaultWeight (Weights[0]).
  794. Weights.push_back(Weights[0] * SuccWeights[i+1]);
  795. ValidTotalSuccWeight += SuccWeights[i+1];
  796. }
  797. }
  798. if (SuccHasWeights || PredHasWeights) {
  799. ValidTotalSuccWeight += SuccWeights[0];
  800. // Scale the cases from predecessor by ValidTotalSuccWeight.
  801. for (unsigned i = 1; i < CasesFromPred; ++i)
  802. Weights[i] *= ValidTotalSuccWeight;
  803. // Scale the default weight by SuccDefaultWeight (SuccWeights[0]).
  804. Weights[0] *= SuccWeights[0];
  805. }
  806. } else {
  807. // If this is not the default destination from PSI, only the edges
  808. // in SI that occur in PSI with a destination of BB will be
  809. // activated.
  810. std::set<ConstantInt*, ConstantIntOrdering> PTIHandled;
  811. std::map<ConstantInt*, uint64_t> WeightsForHandled;
  812. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  813. if (PredCases[i].Dest == BB) {
  814. PTIHandled.insert(PredCases[i].Value);
  815. if (PredHasWeights || SuccHasWeights) {
  816. WeightsForHandled[PredCases[i].Value] = Weights[i+1];
  817. std::swap(Weights[i+1], Weights.back());
  818. Weights.pop_back();
  819. }
  820. std::swap(PredCases[i], PredCases.back());
  821. PredCases.pop_back();
  822. --i; --e;
  823. }
  824. // Okay, now we know which constants were sent to BB from the
  825. // predecessor. Figure out where they will all go now.
  826. for (unsigned i = 0, e = BBCases.size(); i != e; ++i)
  827. if (PTIHandled.count(BBCases[i].Value)) {
  828. // If this is one we are capable of getting...
  829. if (PredHasWeights || SuccHasWeights)
  830. Weights.push_back(WeightsForHandled[BBCases[i].Value]);
  831. PredCases.push_back(BBCases[i]);
  832. NewSuccessors.push_back(BBCases[i].Dest);
  833. PTIHandled.erase(BBCases[i].Value);// This constant is taken care of
  834. }
  835. // If there are any constants vectored to BB that TI doesn't handle,
  836. // they must go to the default destination of TI.
  837. for (std::set<ConstantInt*, ConstantIntOrdering>::iterator I =
  838. PTIHandled.begin(),
  839. E = PTIHandled.end(); I != E; ++I) {
  840. if (PredHasWeights || SuccHasWeights)
  841. Weights.push_back(WeightsForHandled[*I]);
  842. PredCases.push_back(ValueEqualityComparisonCase(*I, BBDefault));
  843. NewSuccessors.push_back(BBDefault);
  844. }
  845. }
  846. // Okay, at this point, we know which new successor Pred will get. Make
  847. // sure we update the number of entries in the PHI nodes for these
  848. // successors.
  849. for (unsigned i = 0, e = NewSuccessors.size(); i != e; ++i)
  850. AddPredecessorToBlock(NewSuccessors[i], Pred, BB);
  851. Builder.SetInsertPoint(PTI);
  852. // Convert pointer to int before we switch.
  853. if (CV->getType()->isPointerTy()) {
  854. CV = Builder.CreatePtrToInt(CV, DL.getIntPtrType(CV->getType()),
  855. "magicptr");
  856. }
  857. // Now that the successors are updated, create the new Switch instruction.
  858. SwitchInst *NewSI = Builder.CreateSwitch(CV, PredDefault,
  859. PredCases.size());
  860. NewSI->setDebugLoc(PTI->getDebugLoc());
  861. for (unsigned i = 0, e = PredCases.size(); i != e; ++i)
  862. NewSI->addCase(PredCases[i].Value, PredCases[i].Dest);
  863. if (PredHasWeights || SuccHasWeights) {
  864. // Halve the weights if any of them cannot fit in an uint32_t
  865. FitWeights(Weights);
  866. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  867. NewSI->setMetadata(LLVMContext::MD_prof,
  868. MDBuilder(BB->getContext()).
  869. createBranchWeights(MDWeights));
  870. }
  871. EraseTerminatorInstAndDCECond(PTI);
  872. // Okay, last check. If BB is still a successor of PSI, then we must
  873. // have an infinite loop case. If so, add an infinitely looping block
  874. // to handle the case to preserve the behavior of the code.
  875. BasicBlock *InfLoopBlock = nullptr;
  876. for (unsigned i = 0, e = NewSI->getNumSuccessors(); i != e; ++i)
  877. if (NewSI->getSuccessor(i) == BB) {
  878. if (!InfLoopBlock) {
  879. // Insert it at the end of the function, because it's either code,
  880. // or it won't matter if it's hot. :)
  881. InfLoopBlock = BasicBlock::Create(BB->getContext(),
  882. "infloop", BB->getParent());
  883. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  884. }
  885. NewSI->setSuccessor(i, InfLoopBlock);
  886. }
  887. Changed = true;
  888. }
  889. }
  890. return Changed;
  891. #else // HLSL Change Begin. // fold to switch will not help hlsl.
  892. return false;
  893. #endif // HLSL Change End.
  894. }
  895. // If we would need to insert a select that uses the value of this invoke
  896. // (comments in HoistThenElseCodeToIf explain why we would need to do this), we
  897. // can't hoist the invoke, as there is nowhere to put the select in this case.
  898. static bool isSafeToHoistInvoke(BasicBlock *BB1, BasicBlock *BB2,
  899. Instruction *I1, Instruction *I2) {
  900. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  901. PHINode *PN;
  902. for (BasicBlock::iterator BBI = SI->begin();
  903. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  904. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  905. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  906. if (BB1V != BB2V && (BB1V==I1 || BB2V==I2)) {
  907. return false;
  908. }
  909. }
  910. }
  911. return true;
  912. }
  913. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I);
  914. /// Given a conditional branch that goes to BB1 and BB2, hoist any common code
  915. /// in the two blocks up into the branch block. The caller of this function
  916. /// guarantees that BI's block dominates BB1 and BB2.
  917. static bool HoistThenElseCodeToIf(BranchInst *BI,
  918. const TargetTransformInfo &TTI) {
  919. // HLSL Change Begins.
  920. // Leave CSE to target backend.
  921. // Also wave operations should not be CSEed.
  922. return false;
  923. // HLSL Change Ends.
  924. // This does very trivial matching, with limited scanning, to find identical
  925. // instructions in the two blocks. In particular, we don't want to get into
  926. // O(M*N) situations here where M and N are the sizes of BB1 and BB2. As
  927. // such, we currently just scan for obviously identical instructions in an
  928. // identical order.
  929. BasicBlock *BB1 = BI->getSuccessor(0); // The true destination.
  930. BasicBlock *BB2 = BI->getSuccessor(1); // The false destination
  931. BasicBlock::iterator BB1_Itr = BB1->begin();
  932. BasicBlock::iterator BB2_Itr = BB2->begin();
  933. Instruction *I1 = BB1_Itr++, *I2 = BB2_Itr++;
  934. // Skip debug info if it is not identical.
  935. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  936. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  937. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  938. while (isa<DbgInfoIntrinsic>(I1))
  939. I1 = BB1_Itr++;
  940. while (isa<DbgInfoIntrinsic>(I2))
  941. I2 = BB2_Itr++;
  942. }
  943. if (isa<PHINode>(I1) || !I1->isIdenticalToWhenDefined(I2) ||
  944. (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2)))
  945. return false;
  946. BasicBlock *BIParent = BI->getParent();
  947. bool Changed = false;
  948. do {
  949. // If we are hoisting the terminator instruction, don't move one (making a
  950. // broken BB), instead clone it, and remove BI.
  951. if (isa<TerminatorInst>(I1))
  952. goto HoistTerminator;
  953. if (!TTI.isProfitableToHoist(I1) || !TTI.isProfitableToHoist(I2))
  954. return Changed;
  955. // For a normal instruction, we just move one to right before the branch,
  956. // then replace all uses of the other with the first. Finally, we remove
  957. // the now redundant second instruction.
  958. BIParent->getInstList().splice(BI, BB1->getInstList(), I1);
  959. if (!I2->use_empty())
  960. I2->replaceAllUsesWith(I1);
  961. I1->intersectOptionalDataWith(I2);
  962. unsigned KnownIDs[] = {
  963. LLVMContext::MD_tbaa,
  964. LLVMContext::MD_range,
  965. LLVMContext::MD_fpmath,
  966. LLVMContext::MD_invariant_load,
  967. LLVMContext::MD_nonnull
  968. };
  969. combineMetadata(I1, I2, KnownIDs);
  970. I2->eraseFromParent();
  971. Changed = true;
  972. I1 = BB1_Itr++;
  973. I2 = BB2_Itr++;
  974. // Skip debug info if it is not identical.
  975. DbgInfoIntrinsic *DBI1 = dyn_cast<DbgInfoIntrinsic>(I1);
  976. DbgInfoIntrinsic *DBI2 = dyn_cast<DbgInfoIntrinsic>(I2);
  977. if (!DBI1 || !DBI2 || !DBI1->isIdenticalToWhenDefined(DBI2)) {
  978. while (isa<DbgInfoIntrinsic>(I1))
  979. I1 = BB1_Itr++;
  980. while (isa<DbgInfoIntrinsic>(I2))
  981. I2 = BB2_Itr++;
  982. }
  983. } while (I1->isIdenticalToWhenDefined(I2));
  984. return true;
  985. HoistTerminator:
  986. // It may not be possible to hoist an invoke.
  987. if (isa<InvokeInst>(I1) && !isSafeToHoistInvoke(BB1, BB2, I1, I2))
  988. return Changed;
  989. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  990. PHINode *PN;
  991. for (BasicBlock::iterator BBI = SI->begin();
  992. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  993. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  994. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  995. if (BB1V == BB2V)
  996. continue;
  997. // Check for passingValueIsAlwaysUndefined here because we would rather
  998. // eliminate undefined control flow then converting it to a select.
  999. if (passingValueIsAlwaysUndefined(BB1V, PN) ||
  1000. passingValueIsAlwaysUndefined(BB2V, PN))
  1001. return Changed;
  1002. if (isa<ConstantExpr>(BB1V) && !isSafeToSpeculativelyExecute(BB1V))
  1003. return Changed;
  1004. if (isa<ConstantExpr>(BB2V) && !isSafeToSpeculativelyExecute(BB2V))
  1005. return Changed;
  1006. }
  1007. }
  1008. // Okay, it is safe to hoist the terminator.
  1009. Instruction *NT = I1->clone();
  1010. BIParent->getInstList().insert(BI, NT);
  1011. if (!NT->getType()->isVoidTy()) {
  1012. I1->replaceAllUsesWith(NT);
  1013. I2->replaceAllUsesWith(NT);
  1014. NT->takeName(I1);
  1015. }
  1016. IRBuilder<true, NoFolder> Builder(NT);
  1017. // Hoisting one of the terminators from our successor is a great thing.
  1018. // Unfortunately, the successors of the if/else blocks may have PHI nodes in
  1019. // them. If they do, all PHI entries for BB1/BB2 must agree for all PHI
  1020. // nodes, so we insert select instruction to compute the final result.
  1021. std::map<std::pair<Value*,Value*>, SelectInst*> InsertedSelects;
  1022. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI) {
  1023. PHINode *PN;
  1024. for (BasicBlock::iterator BBI = SI->begin();
  1025. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  1026. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1027. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1028. if (BB1V == BB2V) continue;
  1029. // These values do not agree. Insert a select instruction before NT
  1030. // that determines the right value.
  1031. SelectInst *&SI = InsertedSelects[std::make_pair(BB1V, BB2V)];
  1032. if (!SI)
  1033. SI = cast<SelectInst>
  1034. (Builder.CreateSelect(BI->getCondition(), BB1V, BB2V,
  1035. BB1V->getName()+"."+BB2V->getName()));
  1036. // Make the PHI node use the select for all incoming values for BB1/BB2
  1037. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  1038. if (PN->getIncomingBlock(i) == BB1 || PN->getIncomingBlock(i) == BB2)
  1039. PN->setIncomingValue(i, SI);
  1040. }
  1041. }
  1042. // Update any PHI nodes in our new successors.
  1043. for (succ_iterator SI = succ_begin(BB1), E = succ_end(BB1); SI != E; ++SI)
  1044. AddPredecessorToBlock(*SI, BIParent, BB1);
  1045. EraseTerminatorInstAndDCECond(BI);
  1046. return true;
  1047. }
  1048. /// Given an unconditional branch that goes to BBEnd,
  1049. /// check whether BBEnd has only two predecessors and the other predecessor
  1050. /// ends with an unconditional branch. If it is true, sink any common code
  1051. /// in the two predecessors to BBEnd.
  1052. static bool SinkThenElseCodeToEnd(BranchInst *BI1) {
  1053. assert(BI1->isUnconditional());
  1054. BasicBlock *BB1 = BI1->getParent();
  1055. BasicBlock *BBEnd = BI1->getSuccessor(0);
  1056. // Check that BBEnd has two predecessors and the other predecessor ends with
  1057. // an unconditional branch.
  1058. pred_iterator PI = pred_begin(BBEnd), PE = pred_end(BBEnd);
  1059. BasicBlock *Pred0 = *PI++;
  1060. if (PI == PE) // Only one predecessor.
  1061. return false;
  1062. BasicBlock *Pred1 = *PI++;
  1063. if (PI != PE) // More than two predecessors.
  1064. return false;
  1065. BasicBlock *BB2 = (Pred0 == BB1) ? Pred1 : Pred0;
  1066. BranchInst *BI2 = dyn_cast<BranchInst>(BB2->getTerminator());
  1067. if (!BI2 || !BI2->isUnconditional())
  1068. return false;
  1069. // Gather the PHI nodes in BBEnd.
  1070. SmallDenseMap<std::pair<Value *, Value *>, PHINode *> JointValueMap;
  1071. Instruction *FirstNonPhiInBBEnd = nullptr;
  1072. for (BasicBlock::iterator I = BBEnd->begin(), E = BBEnd->end(); I != E; ++I) {
  1073. if (PHINode *PN = dyn_cast<PHINode>(I)) {
  1074. Value *BB1V = PN->getIncomingValueForBlock(BB1);
  1075. Value *BB2V = PN->getIncomingValueForBlock(BB2);
  1076. JointValueMap[std::make_pair(BB1V, BB2V)] = PN;
  1077. } else {
  1078. FirstNonPhiInBBEnd = &*I;
  1079. break;
  1080. }
  1081. }
  1082. if (!FirstNonPhiInBBEnd)
  1083. return false;
  1084. // This does very trivial matching, with limited scanning, to find identical
  1085. // instructions in the two blocks. We scan backward for obviously identical
  1086. // instructions in an identical order.
  1087. BasicBlock::InstListType::reverse_iterator RI1 = BB1->getInstList().rbegin(),
  1088. RE1 = BB1->getInstList().rend(),
  1089. RI2 = BB2->getInstList().rbegin(),
  1090. RE2 = BB2->getInstList().rend();
  1091. // Skip debug info.
  1092. while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
  1093. if (RI1 == RE1)
  1094. return false;
  1095. while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
  1096. if (RI2 == RE2)
  1097. return false;
  1098. // Skip the unconditional branches.
  1099. ++RI1;
  1100. ++RI2;
  1101. bool Changed = false;
  1102. while (RI1 != RE1 && RI2 != RE2) {
  1103. // Skip debug info.
  1104. while (RI1 != RE1 && isa<DbgInfoIntrinsic>(&*RI1)) ++RI1;
  1105. if (RI1 == RE1)
  1106. return Changed;
  1107. while (RI2 != RE2 && isa<DbgInfoIntrinsic>(&*RI2)) ++RI2;
  1108. if (RI2 == RE2)
  1109. return Changed;
  1110. Instruction *I1 = &*RI1, *I2 = &*RI2;
  1111. auto InstPair = std::make_pair(I1, I2);
  1112. // I1 and I2 should have a single use in the same PHI node, and they
  1113. // perform the same operation.
  1114. // Cannot move control-flow-involving, volatile loads, vaarg, etc.
  1115. if (isa<PHINode>(I1) || isa<PHINode>(I2) ||
  1116. isa<TerminatorInst>(I1) || isa<TerminatorInst>(I2) ||
  1117. isa<LandingPadInst>(I1) || isa<LandingPadInst>(I2) ||
  1118. isa<AllocaInst>(I1) || isa<AllocaInst>(I2) ||
  1119. I1->mayHaveSideEffects() || I2->mayHaveSideEffects() ||
  1120. I1->mayReadOrWriteMemory() || I2->mayReadOrWriteMemory() ||
  1121. !I1->hasOneUse() || !I2->hasOneUse() ||
  1122. !JointValueMap.count(InstPair))
  1123. return Changed;
  1124. // Check whether we should swap the operands of ICmpInst.
  1125. // TODO: Add support of communativity.
  1126. ICmpInst *ICmp1 = dyn_cast<ICmpInst>(I1), *ICmp2 = dyn_cast<ICmpInst>(I2);
  1127. bool SwapOpnds = false;
  1128. if (ICmp1 && ICmp2 &&
  1129. ICmp1->getOperand(0) != ICmp2->getOperand(0) &&
  1130. ICmp1->getOperand(1) != ICmp2->getOperand(1) &&
  1131. (ICmp1->getOperand(0) == ICmp2->getOperand(1) ||
  1132. ICmp1->getOperand(1) == ICmp2->getOperand(0))) {
  1133. ICmp2->swapOperands();
  1134. SwapOpnds = true;
  1135. }
  1136. if (!I1->isSameOperationAs(I2)) {
  1137. if (SwapOpnds)
  1138. ICmp2->swapOperands();
  1139. return Changed;
  1140. }
  1141. // The operands should be either the same or they need to be generated
  1142. // with a PHI node after sinking. We only handle the case where there is
  1143. // a single pair of different operands.
  1144. Value *DifferentOp1 = nullptr, *DifferentOp2 = nullptr;
  1145. unsigned Op1Idx = ~0U;
  1146. for (unsigned I = 0, E = I1->getNumOperands(); I != E; ++I) {
  1147. if (I1->getOperand(I) == I2->getOperand(I))
  1148. continue;
  1149. // Early exit if we have more-than one pair of different operands or if
  1150. // we need a PHI node to replace a constant.
  1151. if (Op1Idx != ~0U ||
  1152. isa<Constant>(I1->getOperand(I)) ||
  1153. isa<Constant>(I2->getOperand(I))) {
  1154. // If we can't sink the instructions, undo the swapping.
  1155. if (SwapOpnds)
  1156. ICmp2->swapOperands();
  1157. return Changed;
  1158. }
  1159. DifferentOp1 = I1->getOperand(I);
  1160. Op1Idx = I;
  1161. DifferentOp2 = I2->getOperand(I);
  1162. }
  1163. // HLSL Change Begin.
  1164. // Don't sink struct type which will generate struct PhiNode to make sure
  1165. // struct type value only used by Extract/InsertValue.
  1166. if (DifferentOp1 && DifferentOp1->getType()->isStructTy())
  1167. return Changed;
  1168. // HLSL Change End.
  1169. DEBUG(dbgs() << "SINK common instructions " << *I1 << "\n");
  1170. DEBUG(dbgs() << " " << *I2 << "\n");
  1171. // We insert the pair of different operands to JointValueMap and
  1172. // remove (I1, I2) from JointValueMap.
  1173. if (Op1Idx != ~0U) {
  1174. auto &NewPN = JointValueMap[std::make_pair(DifferentOp1, DifferentOp2)];
  1175. if (!NewPN) {
  1176. NewPN =
  1177. PHINode::Create(DifferentOp1->getType(), 2,
  1178. DifferentOp1->getName() + ".sink", BBEnd->begin());
  1179. NewPN->addIncoming(DifferentOp1, BB1);
  1180. NewPN->addIncoming(DifferentOp2, BB2);
  1181. DEBUG(dbgs() << "Create PHI node " << *NewPN << "\n";);
  1182. }
  1183. // I1 should use NewPN instead of DifferentOp1.
  1184. I1->setOperand(Op1Idx, NewPN);
  1185. }
  1186. PHINode *OldPN = JointValueMap[InstPair];
  1187. JointValueMap.erase(InstPair);
  1188. // We need to update RE1 and RE2 if we are going to sink the first
  1189. // instruction in the basic block down.
  1190. bool UpdateRE1 = (I1 == BB1->begin()), UpdateRE2 = (I2 == BB2->begin());
  1191. // Sink the instruction.
  1192. BBEnd->getInstList().splice(FirstNonPhiInBBEnd, BB1->getInstList(), I1);
  1193. if (!OldPN->use_empty())
  1194. OldPN->replaceAllUsesWith(I1);
  1195. OldPN->eraseFromParent();
  1196. if (!I2->use_empty())
  1197. I2->replaceAllUsesWith(I1);
  1198. I1->intersectOptionalDataWith(I2);
  1199. // TODO: Use combineMetadata here to preserve what metadata we can
  1200. // (analogous to the hoisting case above).
  1201. I2->eraseFromParent();
  1202. if (UpdateRE1)
  1203. RE1 = BB1->getInstList().rend();
  1204. if (UpdateRE2)
  1205. RE2 = BB2->getInstList().rend();
  1206. FirstNonPhiInBBEnd = I1;
  1207. NumSinkCommons++;
  1208. Changed = true;
  1209. }
  1210. return Changed;
  1211. }
  1212. /// \brief Determine if we can hoist sink a sole store instruction out of a
  1213. /// conditional block.
  1214. ///
  1215. /// We are looking for code like the following:
  1216. /// BrBB:
  1217. /// store i32 %add, i32* %arrayidx2
  1218. /// ... // No other stores or function calls (we could be calling a memory
  1219. /// ... // function).
  1220. /// %cmp = icmp ult %x, %y
  1221. /// br i1 %cmp, label %EndBB, label %ThenBB
  1222. /// ThenBB:
  1223. /// store i32 %add5, i32* %arrayidx2
  1224. /// br label EndBB
  1225. /// EndBB:
  1226. /// ...
  1227. /// We are going to transform this into:
  1228. /// BrBB:
  1229. /// store i32 %add, i32* %arrayidx2
  1230. /// ... //
  1231. /// %cmp = icmp ult %x, %y
  1232. /// %add.add5 = select i1 %cmp, i32 %add, %add5
  1233. /// store i32 %add.add5, i32* %arrayidx2
  1234. /// ...
  1235. ///
  1236. /// \return The pointer to the value of the previous store if the store can be
  1237. /// hoisted into the predecessor block. 0 otherwise.
  1238. static Value *isSafeToSpeculateStore(Instruction *I, BasicBlock *BrBB,
  1239. BasicBlock *StoreBB, BasicBlock *EndBB) {
  1240. StoreInst *StoreToHoist = dyn_cast<StoreInst>(I);
  1241. if (!StoreToHoist)
  1242. return nullptr;
  1243. // Volatile or atomic.
  1244. if (!StoreToHoist->isSimple())
  1245. return nullptr;
  1246. Value *StorePtr = StoreToHoist->getPointerOperand();
  1247. // Look for a store to the same pointer in BrBB.
  1248. unsigned MaxNumInstToLookAt = 10;
  1249. for (BasicBlock::reverse_iterator RI = BrBB->rbegin(),
  1250. RE = BrBB->rend(); RI != RE && (--MaxNumInstToLookAt); ++RI) {
  1251. Instruction *CurI = &*RI;
  1252. // Could be calling an instruction that effects memory like free().
  1253. if (CurI->mayHaveSideEffects() && !isa<StoreInst>(CurI))
  1254. return nullptr;
  1255. StoreInst *SI = dyn_cast<StoreInst>(CurI);
  1256. // Found the previous store make sure it stores to the same location.
  1257. if (SI && SI->getPointerOperand() == StorePtr)
  1258. // Found the previous store, return its value operand.
  1259. return SI->getValueOperand();
  1260. else if (SI)
  1261. return nullptr; // Unknown store.
  1262. }
  1263. return nullptr;
  1264. }
  1265. /// \brief Speculate a conditional basic block flattening the CFG.
  1266. ///
  1267. /// Note that this is a very risky transform currently. Speculating
  1268. /// instructions like this is most often not desirable. Instead, there is an MI
  1269. /// pass which can do it with full awareness of the resource constraints.
  1270. /// However, some cases are "obvious" and we should do directly. An example of
  1271. /// this is speculating a single, reasonably cheap instruction.
  1272. ///
  1273. /// There is only one distinct advantage to flattening the CFG at the IR level:
  1274. /// it makes very common but simplistic optimizations such as are common in
  1275. /// instcombine and the DAG combiner more powerful by removing CFG edges and
  1276. /// modeling their effects with easier to reason about SSA value graphs.
  1277. ///
  1278. ///
  1279. /// An illustration of this transform is turning this IR:
  1280. /// \code
  1281. /// BB:
  1282. /// %cmp = icmp ult %x, %y
  1283. /// br i1 %cmp, label %EndBB, label %ThenBB
  1284. /// ThenBB:
  1285. /// %sub = sub %x, %y
  1286. /// br label BB2
  1287. /// EndBB:
  1288. /// %phi = phi [ %sub, %ThenBB ], [ 0, %EndBB ]
  1289. /// ...
  1290. /// \endcode
  1291. ///
  1292. /// Into this IR:
  1293. /// \code
  1294. /// BB:
  1295. /// %cmp = icmp ult %x, %y
  1296. /// %sub = sub %x, %y
  1297. /// %cond = select i1 %cmp, 0, %sub
  1298. /// ...
  1299. /// \endcode
  1300. ///
  1301. /// \returns true if the conditional block is removed.
  1302. static bool SpeculativelyExecuteBB(BranchInst *BI, BasicBlock *ThenBB,
  1303. const TargetTransformInfo &TTI) {
  1304. // HLSL Change Begins.
  1305. // Skip block with control flow hint.
  1306. if (BI->hasMetadata()) {
  1307. return false;
  1308. }
  1309. // HLSL Change Ends.
  1310. // Be conservative for now. FP select instruction can often be expensive.
  1311. Value *BrCond = BI->getCondition();
  1312. if (isa<FCmpInst>(BrCond))
  1313. return false;
  1314. BasicBlock *BB = BI->getParent();
  1315. BasicBlock *EndBB = ThenBB->getTerminator()->getSuccessor(0);
  1316. // If ThenBB is actually on the false edge of the conditional branch, remember
  1317. // to swap the select operands later.
  1318. bool Invert = false;
  1319. if (ThenBB != BI->getSuccessor(0)) {
  1320. assert(ThenBB == BI->getSuccessor(1) && "No edge from 'if' block?");
  1321. Invert = true;
  1322. }
  1323. assert(EndBB == BI->getSuccessor(!Invert) && "No edge from to end block");
  1324. // Keep a count of how many times instructions are used within CondBB when
  1325. // they are candidates for sinking into CondBB. Specifically:
  1326. // - They are defined in BB, and
  1327. // - They have no side effects, and
  1328. // - All of their uses are in CondBB.
  1329. SmallDenseMap<Instruction *, unsigned, 4> SinkCandidateUseCounts;
  1330. unsigned SpeculationCost = 0;
  1331. Value *SpeculatedStoreValue = nullptr;
  1332. StoreInst *SpeculatedStore = nullptr;
  1333. for (BasicBlock::iterator BBI = ThenBB->begin(),
  1334. BBE = std::prev(ThenBB->end());
  1335. BBI != BBE; ++BBI) {
  1336. Instruction *I = BBI;
  1337. // Skip debug info.
  1338. if (isa<DbgInfoIntrinsic>(I))
  1339. continue;
  1340. // Only speculatively execute a single instruction (not counting the
  1341. // terminator) for now.
  1342. ++SpeculationCost;
  1343. if (SpeculationCost > 1)
  1344. return false;
  1345. // Don't hoist the instruction if it's unsafe or expensive.
  1346. if (!isSafeToSpeculativelyExecute(I) &&
  1347. !(HoistCondStores && (SpeculatedStoreValue = isSafeToSpeculateStore(
  1348. I, BB, ThenBB, EndBB))))
  1349. return false;
  1350. if (!SpeculatedStoreValue &&
  1351. ComputeSpeculationCost(I, TTI) >
  1352. PHINodeFoldingThreshold * TargetTransformInfo::TCC_Basic)
  1353. return false;
  1354. // Store the store speculation candidate.
  1355. if (SpeculatedStoreValue)
  1356. SpeculatedStore = cast<StoreInst>(I);
  1357. // Do not hoist the instruction if any of its operands are defined but not
  1358. // used in BB. The transformation will prevent the operand from
  1359. // being sunk into the use block.
  1360. for (User::op_iterator i = I->op_begin(), e = I->op_end();
  1361. i != e; ++i) {
  1362. Instruction *OpI = dyn_cast<Instruction>(*i);
  1363. if (!OpI || OpI->getParent() != BB ||
  1364. OpI->mayHaveSideEffects())
  1365. continue; // Not a candidate for sinking.
  1366. ++SinkCandidateUseCounts[OpI];
  1367. }
  1368. }
  1369. // Consider any sink candidates which are only used in CondBB as costs for
  1370. // speculation. Note, while we iterate over a DenseMap here, we are summing
  1371. // and so iteration order isn't significant.
  1372. for (SmallDenseMap<Instruction *, unsigned, 4>::iterator I =
  1373. SinkCandidateUseCounts.begin(), E = SinkCandidateUseCounts.end();
  1374. I != E; ++I)
  1375. if (I->first->getNumUses() == I->second) {
  1376. ++SpeculationCost;
  1377. if (SpeculationCost > 1)
  1378. return false;
  1379. }
  1380. // Check that the PHI nodes can be converted to selects.
  1381. bool HaveRewritablePHIs = false;
  1382. for (BasicBlock::iterator I = EndBB->begin();
  1383. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  1384. Value *OrigV = PN->getIncomingValueForBlock(BB);
  1385. Value *ThenV = PN->getIncomingValueForBlock(ThenBB);
  1386. // FIXME: Try to remove some of the duplication with HoistThenElseCodeToIf.
  1387. // Skip PHIs which are trivial.
  1388. if (ThenV == OrigV)
  1389. continue;
  1390. // Don't convert to selects if we could remove undefined behavior instead.
  1391. if (passingValueIsAlwaysUndefined(OrigV, PN) ||
  1392. passingValueIsAlwaysUndefined(ThenV, PN))
  1393. return false;
  1394. HaveRewritablePHIs = true;
  1395. ConstantExpr *OrigCE = dyn_cast<ConstantExpr>(OrigV);
  1396. ConstantExpr *ThenCE = dyn_cast<ConstantExpr>(ThenV);
  1397. if (!OrigCE && !ThenCE)
  1398. continue; // Known safe and cheap.
  1399. if ((ThenCE && !isSafeToSpeculativelyExecute(ThenCE)) ||
  1400. (OrigCE && !isSafeToSpeculativelyExecute(OrigCE)))
  1401. return false;
  1402. unsigned OrigCost = OrigCE ? ComputeSpeculationCost(OrigCE, TTI) : 0;
  1403. unsigned ThenCost = ThenCE ? ComputeSpeculationCost(ThenCE, TTI) : 0;
  1404. unsigned MaxCost = 2 * PHINodeFoldingThreshold *
  1405. TargetTransformInfo::TCC_Basic;
  1406. if (OrigCost + ThenCost > MaxCost)
  1407. return false;
  1408. // Account for the cost of an unfolded ConstantExpr which could end up
  1409. // getting expanded into Instructions.
  1410. // FIXME: This doesn't account for how many operations are combined in the
  1411. // constant expression.
  1412. ++SpeculationCost;
  1413. if (SpeculationCost > 1)
  1414. return false;
  1415. }
  1416. // If there are no PHIs to process, bail early. This helps ensure idempotence
  1417. // as well.
  1418. if (!HaveRewritablePHIs && !(HoistCondStores && SpeculatedStoreValue))
  1419. return false;
  1420. // If we get here, we can hoist the instruction and if-convert.
  1421. DEBUG(dbgs() << "SPECULATIVELY EXECUTING BB" << *ThenBB << "\n";);
  1422. // Insert a select of the value of the speculated store.
  1423. if (SpeculatedStoreValue) {
  1424. IRBuilder<true, NoFolder> Builder(BI);
  1425. Value *TrueV = SpeculatedStore->getValueOperand();
  1426. Value *FalseV = SpeculatedStoreValue;
  1427. if (Invert)
  1428. std::swap(TrueV, FalseV);
  1429. Value *S = Builder.CreateSelect(BrCond, TrueV, FalseV, TrueV->getName() +
  1430. "." + FalseV->getName());
  1431. SpeculatedStore->setOperand(0, S);
  1432. }
  1433. // Hoist the instructions.
  1434. BB->getInstList().splice(BI, ThenBB->getInstList(), ThenBB->begin(),
  1435. std::prev(ThenBB->end()));
  1436. // Insert selects and rewrite the PHI operands.
  1437. IRBuilder<true, NoFolder> Builder(BI);
  1438. for (BasicBlock::iterator I = EndBB->begin();
  1439. PHINode *PN = dyn_cast<PHINode>(I); ++I) {
  1440. unsigned OrigI = PN->getBasicBlockIndex(BB);
  1441. unsigned ThenI = PN->getBasicBlockIndex(ThenBB);
  1442. Value *OrigV = PN->getIncomingValue(OrigI);
  1443. Value *ThenV = PN->getIncomingValue(ThenI);
  1444. // Skip PHIs which are trivial.
  1445. if (OrigV == ThenV)
  1446. continue;
  1447. // Create a select whose true value is the speculatively executed value and
  1448. // false value is the preexisting value. Swap them if the branch
  1449. // destinations were inverted.
  1450. Value *TrueV = ThenV, *FalseV = OrigV;
  1451. if (Invert)
  1452. std::swap(TrueV, FalseV);
  1453. Value *V = Builder.CreateSelect(BrCond, TrueV, FalseV,
  1454. TrueV->getName() + "." + FalseV->getName());
  1455. PN->setIncomingValue(OrigI, V);
  1456. PN->setIncomingValue(ThenI, V);
  1457. }
  1458. ++NumSpeculations;
  1459. return true;
  1460. }
  1461. /// \returns True if this block contains a CallInst with the NoDuplicate
  1462. /// attribute.
  1463. static bool HasNoDuplicateCall(const BasicBlock *BB) {
  1464. for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  1465. const CallInst *CI = dyn_cast<CallInst>(I);
  1466. if (!CI)
  1467. continue;
  1468. if (CI->cannotDuplicate())
  1469. return true;
  1470. }
  1471. return false;
  1472. }
  1473. /// Return true if we can thread a branch across this block.
  1474. static bool BlockIsSimpleEnoughToThreadThrough(BasicBlock *BB) {
  1475. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  1476. unsigned Size = 0;
  1477. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1478. if (isa<DbgInfoIntrinsic>(BBI))
  1479. continue;
  1480. if (Size > 10) return false; // Don't clone large BB's.
  1481. ++Size;
  1482. // We can only support instructions that do not define values that are
  1483. // live outside of the current basic block.
  1484. for (User *U : BBI->users()) {
  1485. Instruction *UI = cast<Instruction>(U);
  1486. if (UI->getParent() != BB || isa<PHINode>(UI)) return false;
  1487. }
  1488. // Looks ok, continue checking.
  1489. }
  1490. return true;
  1491. }
  1492. /// If we have a conditional branch on a PHI node value that is defined in the
  1493. /// same block as the branch and if any PHI entries are constants, thread edges
  1494. /// corresponding to that entry to be branches to their ultimate destination.
  1495. static bool FoldCondBranchOnPHI(BranchInst *BI, const DataLayout &DL) {
  1496. BasicBlock *BB = BI->getParent();
  1497. PHINode *PN = dyn_cast<PHINode>(BI->getCondition());
  1498. // NOTE: we currently cannot transform this case if the PHI node is used
  1499. // outside of the block.
  1500. if (!PN || PN->getParent() != BB || !PN->hasOneUse())
  1501. return false;
  1502. // Degenerate case of a single entry PHI.
  1503. if (PN->getNumIncomingValues() == 1) {
  1504. FoldSingleEntryPHINodes(PN->getParent());
  1505. return true;
  1506. }
  1507. // Now we know that this block has multiple preds and two succs.
  1508. if (!BlockIsSimpleEnoughToThreadThrough(BB)) return false;
  1509. if (HasNoDuplicateCall(BB)) return false;
  1510. // Okay, this is a simple enough basic block. See if any phi values are
  1511. // constants.
  1512. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  1513. ConstantInt *CB = dyn_cast<ConstantInt>(PN->getIncomingValue(i));
  1514. if (!CB || !CB->getType()->isIntegerTy(1)) continue;
  1515. // Okay, we now know that all edges from PredBB should be revectored to
  1516. // branch to RealDest.
  1517. BasicBlock *PredBB = PN->getIncomingBlock(i);
  1518. BasicBlock *RealDest = BI->getSuccessor(!CB->getZExtValue());
  1519. if (RealDest == BB) continue; // Skip self loops.
  1520. // Skip if the predecessor's terminator is an indirect branch.
  1521. if (isa<IndirectBrInst>(PredBB->getTerminator())) continue;
  1522. // The dest block might have PHI nodes, other predecessors and other
  1523. // difficult cases. Instead of being smart about this, just insert a new
  1524. // block that jumps to the destination block, effectively splitting
  1525. // the edge we are about to create.
  1526. BasicBlock *EdgeBB = BasicBlock::Create(BB->getContext(),
  1527. RealDest->getName()+".critedge",
  1528. RealDest->getParent(), RealDest);
  1529. BranchInst::Create(RealDest, EdgeBB);
  1530. // Update PHI nodes.
  1531. AddPredecessorToBlock(RealDest, EdgeBB, BB);
  1532. // BB may have instructions that are being threaded over. Clone these
  1533. // instructions into EdgeBB. We know that there will be no uses of the
  1534. // cloned instructions outside of EdgeBB.
  1535. BasicBlock::iterator InsertPt = EdgeBB->begin();
  1536. DenseMap<Value*, Value*> TranslateMap; // Track translated values.
  1537. for (BasicBlock::iterator BBI = BB->begin(); &*BBI != BI; ++BBI) {
  1538. if (PHINode *PN = dyn_cast<PHINode>(BBI)) {
  1539. TranslateMap[PN] = PN->getIncomingValueForBlock(PredBB);
  1540. continue;
  1541. }
  1542. // Clone the instruction.
  1543. Instruction *N = BBI->clone();
  1544. if (BBI->hasName()) N->setName(BBI->getName()+".c");
  1545. // Update operands due to translation.
  1546. for (User::op_iterator i = N->op_begin(), e = N->op_end();
  1547. i != e; ++i) {
  1548. DenseMap<Value*, Value*>::iterator PI = TranslateMap.find(*i);
  1549. if (PI != TranslateMap.end())
  1550. *i = PI->second;
  1551. }
  1552. // Check for trivial simplification.
  1553. if (Value *V = SimplifyInstruction(N, DL)) {
  1554. TranslateMap[BBI] = V;
  1555. delete N; // Instruction folded away, don't need actual inst
  1556. } else {
  1557. // Insert the new instruction into its new home.
  1558. EdgeBB->getInstList().insert(InsertPt, N);
  1559. if (!BBI->use_empty())
  1560. TranslateMap[BBI] = N;
  1561. }
  1562. }
  1563. // Loop over all of the edges from PredBB to BB, changing them to branch
  1564. // to EdgeBB instead.
  1565. TerminatorInst *PredBBTI = PredBB->getTerminator();
  1566. for (unsigned i = 0, e = PredBBTI->getNumSuccessors(); i != e; ++i)
  1567. if (PredBBTI->getSuccessor(i) == BB) {
  1568. BB->removePredecessor(PredBB);
  1569. PredBBTI->setSuccessor(i, EdgeBB);
  1570. }
  1571. // Recurse, simplifying any other constants.
  1572. return FoldCondBranchOnPHI(BI, DL) | true;
  1573. }
  1574. return false;
  1575. }
  1576. /// Given a BB that starts with the specified two-entry PHI node,
  1577. /// see if we can eliminate it.
  1578. static bool FoldTwoEntryPHINode(PHINode *PN, const TargetTransformInfo &TTI,
  1579. const DataLayout &DL) {
  1580. // Ok, this is a two entry PHI node. Check to see if this is a simple "if
  1581. // statement", which has a very simple dominance structure. Basically, we
  1582. // are trying to find the condition that is being branched on, which
  1583. // subsequently causes this merge to happen. We really want control
  1584. // dependence information for this check, but simplifycfg can't keep it up
  1585. // to date, and this catches most of the cases we care about anyway.
  1586. BasicBlock *BB = PN->getParent();
  1587. BasicBlock *IfTrue, *IfFalse;
  1588. Value *IfCond = GetIfCondition(BB, IfTrue, IfFalse);
  1589. if (!IfCond ||
  1590. // Don't bother if the branch will be constant folded trivially.
  1591. isa<ConstantInt>(IfCond))
  1592. return false;
  1593. // Okay, we found that we can merge this two-entry phi node into a select.
  1594. // Doing so would require us to fold *all* two entry phi nodes in this block.
  1595. // At some point this becomes non-profitable (particularly if the target
  1596. // doesn't support cmov's). Only do this transformation if there are two or
  1597. // fewer PHI nodes in this block.
  1598. unsigned NumPhis = 0;
  1599. for (BasicBlock::iterator I = BB->begin(); isa<PHINode>(I); ++NumPhis, ++I)
  1600. if (NumPhis > 2)
  1601. return false;
  1602. // Loop over the PHI's seeing if we can promote them all to select
  1603. // instructions. While we are at it, keep track of the instructions
  1604. // that need to be moved to the dominating block.
  1605. SmallPtrSet<Instruction*, 4> AggressiveInsts;
  1606. unsigned MaxCostVal0 = PHINodeFoldingThreshold,
  1607. MaxCostVal1 = PHINodeFoldingThreshold;
  1608. MaxCostVal0 *= TargetTransformInfo::TCC_Basic;
  1609. MaxCostVal1 *= TargetTransformInfo::TCC_Basic;
  1610. for (BasicBlock::iterator II = BB->begin(); isa<PHINode>(II);) {
  1611. PHINode *PN = cast<PHINode>(II++);
  1612. if (Value *V = SimplifyInstruction(PN, DL)) {
  1613. PN->replaceAllUsesWith(V);
  1614. PN->eraseFromParent();
  1615. continue;
  1616. }
  1617. if (!DominatesMergePoint(PN->getIncomingValue(0), BB, &AggressiveInsts,
  1618. MaxCostVal0, TTI) ||
  1619. !DominatesMergePoint(PN->getIncomingValue(1), BB, &AggressiveInsts,
  1620. MaxCostVal1, TTI))
  1621. return false;
  1622. }
  1623. // If we folded the first phi, PN dangles at this point. Refresh it. If
  1624. // we ran out of PHIs then we simplified them all.
  1625. PN = dyn_cast<PHINode>(BB->begin());
  1626. if (!PN) return true;
  1627. // Don't fold i1 branches on PHIs which contain binary operators. These can
  1628. // often be turned into switches and other things.
  1629. if (PN->getType()->isIntegerTy(1) &&
  1630. (isa<BinaryOperator>(PN->getIncomingValue(0)) ||
  1631. isa<BinaryOperator>(PN->getIncomingValue(1)) ||
  1632. isa<BinaryOperator>(IfCond)))
  1633. return false;
  1634. // If we all PHI nodes are promotable, check to make sure that all
  1635. // instructions in the predecessor blocks can be promoted as well. If
  1636. // not, we won't be able to get rid of the control flow, so it's not
  1637. // worth promoting to select instructions.
  1638. BasicBlock *DomBlock = nullptr;
  1639. BasicBlock *IfBlock1 = PN->getIncomingBlock(0);
  1640. BasicBlock *IfBlock2 = PN->getIncomingBlock(1);
  1641. if (cast<BranchInst>(IfBlock1->getTerminator())->isConditional()) {
  1642. IfBlock1 = nullptr;
  1643. } else {
  1644. DomBlock = *pred_begin(IfBlock1);
  1645. for (BasicBlock::iterator I = IfBlock1->begin();!isa<TerminatorInst>(I);++I)
  1646. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1647. // This is not an aggressive instruction that we can promote.
  1648. // Because of this, we won't be able to get rid of the control
  1649. // flow, so the xform is not worth it.
  1650. return false;
  1651. }
  1652. }
  1653. if (cast<BranchInst>(IfBlock2->getTerminator())->isConditional()) {
  1654. IfBlock2 = nullptr;
  1655. } else {
  1656. DomBlock = *pred_begin(IfBlock2);
  1657. for (BasicBlock::iterator I = IfBlock2->begin();!isa<TerminatorInst>(I);++I)
  1658. if (!AggressiveInsts.count(I) && !isa<DbgInfoIntrinsic>(I)) {
  1659. // This is not an aggressive instruction that we can promote.
  1660. // Because of this, we won't be able to get rid of the control
  1661. // flow, so the xform is not worth it.
  1662. return false;
  1663. }
  1664. }
  1665. DEBUG(dbgs() << "FOUND IF CONDITION! " << *IfCond << " T: "
  1666. << IfTrue->getName() << " F: " << IfFalse->getName() << "\n");
  1667. // If we can still promote the PHI nodes after this gauntlet of tests,
  1668. // do all of the PHI's now.
  1669. Instruction *InsertPt = DomBlock->getTerminator();
  1670. // HLSL Change Begins.
  1671. // Skip block with control flow hint.
  1672. if (InsertPt->hasMetadata()) {
  1673. return false;
  1674. }
  1675. // HLSL Change Ends.
  1676. IRBuilder<true, NoFolder> Builder(InsertPt);
  1677. // Move all 'aggressive' instructions, which are defined in the
  1678. // conditional parts of the if's up to the dominating block.
  1679. if (IfBlock1)
  1680. DomBlock->getInstList().splice(InsertPt,
  1681. IfBlock1->getInstList(), IfBlock1->begin(),
  1682. IfBlock1->getTerminator());
  1683. if (IfBlock2)
  1684. DomBlock->getInstList().splice(InsertPt,
  1685. IfBlock2->getInstList(), IfBlock2->begin(),
  1686. IfBlock2->getTerminator());
  1687. while (PHINode *PN = dyn_cast<PHINode>(BB->begin())) {
  1688. // Change the PHI node into a select instruction.
  1689. Value *TrueVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfFalse);
  1690. Value *FalseVal = PN->getIncomingValue(PN->getIncomingBlock(0) == IfTrue);
  1691. SelectInst *NV =
  1692. cast<SelectInst>(Builder.CreateSelect(IfCond, TrueVal, FalseVal, ""));
  1693. PN->replaceAllUsesWith(NV);
  1694. NV->takeName(PN);
  1695. PN->eraseFromParent();
  1696. }
  1697. // At this point, IfBlock1 and IfBlock2 are both empty, so our if statement
  1698. // has been flattened. Change DomBlock to jump directly to our new block to
  1699. // avoid other simplifycfg's kicking in on the diamond.
  1700. TerminatorInst *OldTI = DomBlock->getTerminator();
  1701. Builder.SetInsertPoint(OldTI);
  1702. Builder.CreateBr(BB);
  1703. OldTI->eraseFromParent();
  1704. return true;
  1705. }
  1706. /// If we found a conditional branch that goes to two returning blocks,
  1707. /// try to merge them together into one return,
  1708. /// introducing a select if the return values disagree.
  1709. static bool SimplifyCondBranchToTwoReturns(BranchInst *BI,
  1710. IRBuilder<> &Builder) {
  1711. assert(BI->isConditional() && "Must be a conditional branch");
  1712. BasicBlock *TrueSucc = BI->getSuccessor(0);
  1713. BasicBlock *FalseSucc = BI->getSuccessor(1);
  1714. ReturnInst *TrueRet = cast<ReturnInst>(TrueSucc->getTerminator());
  1715. ReturnInst *FalseRet = cast<ReturnInst>(FalseSucc->getTerminator());
  1716. // Check to ensure both blocks are empty (just a return) or optionally empty
  1717. // with PHI nodes. If there are other instructions, merging would cause extra
  1718. // computation on one path or the other.
  1719. if (!TrueSucc->getFirstNonPHIOrDbg()->isTerminator())
  1720. return false;
  1721. if (!FalseSucc->getFirstNonPHIOrDbg()->isTerminator())
  1722. return false;
  1723. Builder.SetInsertPoint(BI);
  1724. // Okay, we found a branch that is going to two return nodes. If
  1725. // there is no return value for this function, just change the
  1726. // branch into a return.
  1727. if (FalseRet->getNumOperands() == 0) {
  1728. TrueSucc->removePredecessor(BI->getParent());
  1729. FalseSucc->removePredecessor(BI->getParent());
  1730. Builder.CreateRetVoid();
  1731. EraseTerminatorInstAndDCECond(BI);
  1732. return true;
  1733. }
  1734. // Otherwise, figure out what the true and false return values are
  1735. // so we can insert a new select instruction.
  1736. Value *TrueValue = TrueRet->getReturnValue();
  1737. Value *FalseValue = FalseRet->getReturnValue();
  1738. // Unwrap any PHI nodes in the return blocks.
  1739. if (PHINode *TVPN = dyn_cast_or_null<PHINode>(TrueValue))
  1740. if (TVPN->getParent() == TrueSucc)
  1741. TrueValue = TVPN->getIncomingValueForBlock(BI->getParent());
  1742. if (PHINode *FVPN = dyn_cast_or_null<PHINode>(FalseValue))
  1743. if (FVPN->getParent() == FalseSucc)
  1744. FalseValue = FVPN->getIncomingValueForBlock(BI->getParent());
  1745. // In order for this transformation to be safe, we must be able to
  1746. // unconditionally execute both operands to the return. This is
  1747. // normally the case, but we could have a potentially-trapping
  1748. // constant expression that prevents this transformation from being
  1749. // safe.
  1750. if (ConstantExpr *TCV = dyn_cast_or_null<ConstantExpr>(TrueValue))
  1751. if (TCV->canTrap())
  1752. return false;
  1753. if (ConstantExpr *FCV = dyn_cast_or_null<ConstantExpr>(FalseValue))
  1754. if (FCV->canTrap())
  1755. return false;
  1756. // Okay, we collected all the mapped values and checked them for sanity, and
  1757. // defined to really do this transformation. First, update the CFG.
  1758. TrueSucc->removePredecessor(BI->getParent());
  1759. FalseSucc->removePredecessor(BI->getParent());
  1760. // Insert select instructions where needed.
  1761. Value *BrCond = BI->getCondition();
  1762. if (TrueValue) {
  1763. // Insert a select if the results differ.
  1764. if (TrueValue == FalseValue || isa<UndefValue>(FalseValue)) {
  1765. } else if (isa<UndefValue>(TrueValue)) {
  1766. TrueValue = FalseValue;
  1767. } else {
  1768. TrueValue = Builder.CreateSelect(BrCond, TrueValue,
  1769. FalseValue, "retval");
  1770. }
  1771. }
  1772. Value *RI = !TrueValue ?
  1773. Builder.CreateRetVoid() : Builder.CreateRet(TrueValue);
  1774. (void) RI;
  1775. DEBUG(dbgs() << "\nCHANGING BRANCH TO TWO RETURNS INTO SELECT:"
  1776. << "\n " << *BI << "NewRet = " << *RI
  1777. << "TRUEBLOCK: " << *TrueSucc << "FALSEBLOCK: "<< *FalseSucc);
  1778. EraseTerminatorInstAndDCECond(BI);
  1779. return true;
  1780. }
  1781. /// Given a conditional BranchInstruction, retrieve the probabilities of the
  1782. /// branch taking each edge. Fills in the two APInt parameters and returns true,
  1783. /// or returns false if no or invalid metadata was found.
  1784. static bool ExtractBranchMetadata(BranchInst *BI,
  1785. uint64_t &ProbTrue, uint64_t &ProbFalse) {
  1786. assert(BI->isConditional() &&
  1787. "Looking for probabilities on unconditional branch?");
  1788. MDNode *ProfileData = BI->getMetadata(LLVMContext::MD_prof);
  1789. if (!ProfileData || ProfileData->getNumOperands() != 3) return false;
  1790. ConstantInt *CITrue =
  1791. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(1));
  1792. ConstantInt *CIFalse =
  1793. mdconst::dyn_extract<ConstantInt>(ProfileData->getOperand(2));
  1794. if (!CITrue || !CIFalse) return false;
  1795. ProbTrue = CITrue->getValue().getZExtValue();
  1796. ProbFalse = CIFalse->getValue().getZExtValue();
  1797. return true;
  1798. }
  1799. /// Return true if the given instruction is available
  1800. /// in its predecessor block. If yes, the instruction will be removed.
  1801. static bool checkCSEInPredecessor(Instruction *Inst, BasicBlock *PB) {
  1802. if (!isa<BinaryOperator>(Inst) && !isa<CmpInst>(Inst))
  1803. return false;
  1804. for (BasicBlock::iterator I = PB->begin(), E = PB->end(); I != E; I++) {
  1805. Instruction *PBI = &*I;
  1806. // Check whether Inst and PBI generate the same value.
  1807. if (Inst->isIdenticalTo(PBI)) {
  1808. Inst->replaceAllUsesWith(PBI);
  1809. Inst->eraseFromParent();
  1810. return true;
  1811. }
  1812. }
  1813. return false;
  1814. }
  1815. /// If this basic block is simple enough, and if a predecessor branches to us
  1816. /// and one of our successors, fold the block into the predecessor and use
  1817. /// logical operations to pick the right destination.
  1818. bool llvm::FoldBranchToCommonDest(BranchInst *BI, unsigned BonusInstThreshold) {
  1819. BasicBlock *BB = BI->getParent();
  1820. Instruction *Cond = nullptr;
  1821. if (BI->isConditional())
  1822. Cond = dyn_cast<Instruction>(BI->getCondition());
  1823. else {
  1824. // For unconditional branch, check for a simple CFG pattern, where
  1825. // BB has a single predecessor and BB's successor is also its predecessor's
  1826. // successor. If such pattern exisits, check for CSE between BB and its
  1827. // predecessor.
  1828. if (BasicBlock *PB = BB->getSinglePredecessor())
  1829. if (BranchInst *PBI = dyn_cast<BranchInst>(PB->getTerminator()))
  1830. if (PBI->isConditional() &&
  1831. (BI->getSuccessor(0) == PBI->getSuccessor(0) ||
  1832. BI->getSuccessor(0) == PBI->getSuccessor(1))) {
  1833. for (BasicBlock::iterator I = BB->begin(), E = BB->end();
  1834. I != E; ) {
  1835. Instruction *Curr = I++;
  1836. if (isa<CmpInst>(Curr)) {
  1837. Cond = Curr;
  1838. break;
  1839. }
  1840. // Quit if we can't remove this instruction.
  1841. if (!checkCSEInPredecessor(Curr, PB))
  1842. return false;
  1843. }
  1844. }
  1845. if (!Cond)
  1846. return false;
  1847. }
  1848. if (!Cond || (!isa<CmpInst>(Cond) && !isa<BinaryOperator>(Cond)) ||
  1849. Cond->getParent() != BB || !Cond->hasOneUse())
  1850. return false;
  1851. // Make sure the instruction after the condition is the cond branch.
  1852. BasicBlock::iterator CondIt = Cond; ++CondIt;
  1853. // Ignore dbg intrinsics.
  1854. while (isa<DbgInfoIntrinsic>(CondIt)) ++CondIt;
  1855. if (&*CondIt != BI)
  1856. return false;
  1857. // Only allow this transformation if computing the condition doesn't involve
  1858. // too many instructions and these involved instructions can be executed
  1859. // unconditionally. We denote all involved instructions except the condition
  1860. // as "bonus instructions", and only allow this transformation when the
  1861. // number of the bonus instructions does not exceed a certain threshold.
  1862. unsigned NumBonusInsts = 0;
  1863. for (auto I = BB->begin(); Cond != I; ++I) {
  1864. // Ignore dbg intrinsics.
  1865. if (isa<DbgInfoIntrinsic>(I))
  1866. continue;
  1867. if (!I->hasOneUse() || !isSafeToSpeculativelyExecute(I))
  1868. return false;
  1869. // I has only one use and can be executed unconditionally.
  1870. Instruction *User = dyn_cast<Instruction>(I->user_back());
  1871. if (User == nullptr || User->getParent() != BB)
  1872. return false;
  1873. // I is used in the same BB. Since BI uses Cond and doesn't have more slots
  1874. // to use any other instruction, User must be an instruction between next(I)
  1875. // and Cond.
  1876. ++NumBonusInsts;
  1877. // Early exits once we reach the limit.
  1878. if (NumBonusInsts > BonusInstThreshold)
  1879. return false;
  1880. }
  1881. // Cond is known to be a compare or binary operator. Check to make sure that
  1882. // neither operand is a potentially-trapping constant expression.
  1883. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(0)))
  1884. if (CE->canTrap())
  1885. return false;
  1886. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Cond->getOperand(1)))
  1887. if (CE->canTrap())
  1888. return false;
  1889. // Finally, don't infinitely unroll conditional loops.
  1890. BasicBlock *TrueDest = BI->getSuccessor(0);
  1891. BasicBlock *FalseDest = (BI->isConditional()) ? BI->getSuccessor(1) : nullptr;
  1892. if (TrueDest == BB || FalseDest == BB)
  1893. return false;
  1894. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  1895. BasicBlock *PredBlock = *PI;
  1896. BranchInst *PBI = dyn_cast<BranchInst>(PredBlock->getTerminator());
  1897. // Check that we have two conditional branches. If there is a PHI node in
  1898. // the common successor, verify that the same value flows in from both
  1899. // blocks.
  1900. SmallVector<PHINode*, 4> PHIs;
  1901. if (!PBI || PBI->isUnconditional() ||
  1902. (BI->isConditional() &&
  1903. !SafeToMergeTerminators(BI, PBI)) ||
  1904. (!BI->isConditional() &&
  1905. !isProfitableToFoldUnconditional(BI, PBI, Cond, PHIs)))
  1906. continue;
  1907. // Determine if the two branches share a common destination.
  1908. Instruction::BinaryOps Opc = Instruction::BinaryOpsEnd;
  1909. bool InvertPredCond = false;
  1910. if (BI->isConditional()) {
  1911. if (PBI->getSuccessor(0) == TrueDest)
  1912. Opc = Instruction::Or;
  1913. else if (PBI->getSuccessor(1) == FalseDest)
  1914. Opc = Instruction::And;
  1915. else if (PBI->getSuccessor(0) == FalseDest)
  1916. Opc = Instruction::And, InvertPredCond = true;
  1917. else if (PBI->getSuccessor(1) == TrueDest)
  1918. Opc = Instruction::Or, InvertPredCond = true;
  1919. else
  1920. continue;
  1921. } else {
  1922. if (PBI->getSuccessor(0) != TrueDest && PBI->getSuccessor(1) != TrueDest)
  1923. continue;
  1924. }
  1925. DEBUG(dbgs() << "FOLDING BRANCH TO COMMON DEST:\n" << *PBI << *BB);
  1926. IRBuilder<> Builder(PBI);
  1927. // If we need to invert the condition in the pred block to match, do so now.
  1928. if (InvertPredCond) {
  1929. Value *NewCond = PBI->getCondition();
  1930. if (NewCond->hasOneUse() && isa<CmpInst>(NewCond)) {
  1931. CmpInst *CI = cast<CmpInst>(NewCond);
  1932. CI->setPredicate(CI->getInversePredicate());
  1933. } else {
  1934. NewCond = Builder.CreateNot(NewCond,
  1935. PBI->getCondition()->getName()+".not");
  1936. }
  1937. PBI->setCondition(NewCond);
  1938. PBI->swapSuccessors();
  1939. }
  1940. // If we have bonus instructions, clone them into the predecessor block.
  1941. // Note that there may be multiple predecessor blocks, so we cannot move
  1942. // bonus instructions to a predecessor block.
  1943. ValueToValueMapTy VMap; // maps original values to cloned values
  1944. // We already make sure Cond is the last instruction before BI. Therefore,
  1945. // all instructions before Cond other than DbgInfoIntrinsic are bonus
  1946. // instructions.
  1947. for (auto BonusInst = BB->begin(); Cond != BonusInst; ++BonusInst) {
  1948. if (isa<DbgInfoIntrinsic>(BonusInst))
  1949. continue;
  1950. Instruction *NewBonusInst = BonusInst->clone();
  1951. RemapInstruction(NewBonusInst, VMap,
  1952. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  1953. VMap[BonusInst] = NewBonusInst;
  1954. // If we moved a load, we cannot any longer claim any knowledge about
  1955. // its potential value. The previous information might have been valid
  1956. // only given the branch precondition.
  1957. // For an analogous reason, we must also drop all the metadata whose
  1958. // semantics we don't understand.
  1959. NewBonusInst->dropUnknownMetadata(LLVMContext::MD_dbg);
  1960. PredBlock->getInstList().insert(PBI, NewBonusInst);
  1961. NewBonusInst->takeName(BonusInst);
  1962. BonusInst->setName(BonusInst->getName() + ".old");
  1963. }
  1964. // Clone Cond into the predecessor basic block, and or/and the
  1965. // two conditions together.
  1966. Instruction *New = Cond->clone();
  1967. RemapInstruction(New, VMap,
  1968. RF_NoModuleLevelChanges | RF_IgnoreMissingEntries);
  1969. PredBlock->getInstList().insert(PBI, New);
  1970. New->takeName(Cond);
  1971. Cond->setName(New->getName() + ".old");
  1972. if (BI->isConditional()) {
  1973. Instruction *NewCond =
  1974. cast<Instruction>(Builder.CreateBinOp(Opc, PBI->getCondition(),
  1975. New, "or.cond"));
  1976. PBI->setCondition(NewCond);
  1977. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  1978. bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
  1979. PredFalseWeight);
  1980. bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
  1981. SuccFalseWeight);
  1982. SmallVector<uint64_t, 8> NewWeights;
  1983. if (PBI->getSuccessor(0) == BB) {
  1984. if (PredHasWeights && SuccHasWeights) {
  1985. // PBI: br i1 %x, BB, FalseDest
  1986. // BI: br i1 %y, TrueDest, FalseDest
  1987. //TrueWeight is TrueWeight for PBI * TrueWeight for BI.
  1988. NewWeights.push_back(PredTrueWeight * SuccTrueWeight);
  1989. //FalseWeight is FalseWeight for PBI * TotalWeight for BI +
  1990. // TrueWeight for PBI * FalseWeight for BI.
  1991. // We assume that total weights of a BranchInst can fit into 32 bits.
  1992. // Therefore, we will not have overflow using 64-bit arithmetic.
  1993. NewWeights.push_back(PredFalseWeight * (SuccFalseWeight +
  1994. SuccTrueWeight) + PredTrueWeight * SuccFalseWeight);
  1995. }
  1996. AddPredecessorToBlock(TrueDest, PredBlock, BB);
  1997. PBI->setSuccessor(0, TrueDest);
  1998. }
  1999. if (PBI->getSuccessor(1) == BB) {
  2000. if (PredHasWeights && SuccHasWeights) {
  2001. // PBI: br i1 %x, TrueDest, BB
  2002. // BI: br i1 %y, TrueDest, FalseDest
  2003. //TrueWeight is TrueWeight for PBI * TotalWeight for BI +
  2004. // FalseWeight for PBI * TrueWeight for BI.
  2005. NewWeights.push_back(PredTrueWeight * (SuccFalseWeight +
  2006. SuccTrueWeight) + PredFalseWeight * SuccTrueWeight);
  2007. //FalseWeight is FalseWeight for PBI * FalseWeight for BI.
  2008. NewWeights.push_back(PredFalseWeight * SuccFalseWeight);
  2009. }
  2010. AddPredecessorToBlock(FalseDest, PredBlock, BB);
  2011. PBI->setSuccessor(1, FalseDest);
  2012. }
  2013. if (NewWeights.size() == 2) {
  2014. // Halve the weights if any of them cannot fit in an uint32_t
  2015. FitWeights(NewWeights);
  2016. SmallVector<uint32_t, 8> MDWeights(NewWeights.begin(),NewWeights.end());
  2017. PBI->setMetadata(LLVMContext::MD_prof,
  2018. MDBuilder(BI->getContext()).
  2019. createBranchWeights(MDWeights));
  2020. } else
  2021. PBI->setMetadata(LLVMContext::MD_prof, nullptr);
  2022. } else {
  2023. // Update PHI nodes in the common successors.
  2024. for (unsigned i = 0, e = PHIs.size(); i != e; ++i) {
  2025. ConstantInt *PBI_C = cast<ConstantInt>(
  2026. PHIs[i]->getIncomingValueForBlock(PBI->getParent()));
  2027. assert(PBI_C->getType()->isIntegerTy(1));
  2028. Instruction *MergedCond = nullptr;
  2029. if (PBI->getSuccessor(0) == TrueDest) {
  2030. // Create (PBI_Cond and PBI_C) or (!PBI_Cond and BI_Value)
  2031. // PBI_C is true: PBI_Cond or (!PBI_Cond and BI_Value)
  2032. // is false: !PBI_Cond and BI_Value
  2033. Instruction *NotCond =
  2034. cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
  2035. "not.cond"));
  2036. MergedCond =
  2037. cast<Instruction>(Builder.CreateBinOp(Instruction::And,
  2038. NotCond, New,
  2039. "and.cond"));
  2040. if (PBI_C->isOne())
  2041. MergedCond =
  2042. cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
  2043. PBI->getCondition(), MergedCond,
  2044. "or.cond"));
  2045. } else {
  2046. // Create (PBI_Cond and BI_Value) or (!PBI_Cond and PBI_C)
  2047. // PBI_C is true: (PBI_Cond and BI_Value) or (!PBI_Cond)
  2048. // is false: PBI_Cond and BI_Value
  2049. MergedCond =
  2050. cast<Instruction>(Builder.CreateBinOp(Instruction::And,
  2051. PBI->getCondition(), New,
  2052. "and.cond"));
  2053. if (PBI_C->isOne()) {
  2054. Instruction *NotCond =
  2055. cast<Instruction>(Builder.CreateNot(PBI->getCondition(),
  2056. "not.cond"));
  2057. MergedCond =
  2058. cast<Instruction>(Builder.CreateBinOp(Instruction::Or,
  2059. NotCond, MergedCond,
  2060. "or.cond"));
  2061. }
  2062. }
  2063. // Update PHI Node.
  2064. PHIs[i]->setIncomingValue(PHIs[i]->getBasicBlockIndex(PBI->getParent()),
  2065. MergedCond);
  2066. }
  2067. // Change PBI from Conditional to Unconditional.
  2068. BranchInst *New_PBI = BranchInst::Create(TrueDest, PBI);
  2069. EraseTerminatorInstAndDCECond(PBI);
  2070. PBI = New_PBI;
  2071. }
  2072. // TODO: If BB is reachable from all paths through PredBlock, then we
  2073. // could replace PBI's branch probabilities with BI's.
  2074. // Copy any debug value intrinsics into the end of PredBlock.
  2075. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I)
  2076. if (isa<DbgInfoIntrinsic>(*I))
  2077. I->clone()->insertBefore(PBI);
  2078. return true;
  2079. }
  2080. return false;
  2081. }
  2082. /// If we have a conditional branch as a predecessor of another block,
  2083. /// this function tries to simplify it. We know
  2084. /// that PBI and BI are both conditional branches, and BI is in one of the
  2085. /// successor blocks of PBI - PBI branches to BI.
  2086. static bool SimplifyCondBranchToCondBranch(BranchInst *PBI, BranchInst *BI) {
  2087. assert(PBI->isConditional() && BI->isConditional());
  2088. BasicBlock *BB = BI->getParent();
  2089. // If this block ends with a branch instruction, and if there is a
  2090. // predecessor that ends on a branch of the same condition, make
  2091. // this conditional branch redundant.
  2092. if (PBI->getCondition() == BI->getCondition() &&
  2093. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2094. // Okay, the outcome of this conditional branch is statically
  2095. // knowable. If this block had a single pred, handle specially.
  2096. if (BB->getSinglePredecessor()) {
  2097. // Turn this into a branch on constant.
  2098. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2099. BI->setCondition(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  2100. CondIsTrue));
  2101. return true; // Nuke the branch on constant.
  2102. }
  2103. // Otherwise, if there are multiple predecessors, insert a PHI that merges
  2104. // in the constant and simplify the block result. Subsequent passes of
  2105. // simplifycfg will thread the block.
  2106. if (BlockIsSimpleEnoughToThreadThrough(BB)) {
  2107. pred_iterator PB = pred_begin(BB), PE = pred_end(BB);
  2108. PHINode *NewPN = PHINode::Create(Type::getInt1Ty(BB->getContext()),
  2109. std::distance(PB, PE),
  2110. BI->getCondition()->getName() + ".pr",
  2111. BB->begin());
  2112. // Okay, we're going to insert the PHI node. Since PBI is not the only
  2113. // predecessor, compute the PHI'd conditional value for all of the preds.
  2114. // Any predecessor where the condition is not computable we keep symbolic.
  2115. for (pred_iterator PI = PB; PI != PE; ++PI) {
  2116. BasicBlock *P = *PI;
  2117. if ((PBI = dyn_cast<BranchInst>(P->getTerminator())) &&
  2118. PBI != BI && PBI->isConditional() &&
  2119. PBI->getCondition() == BI->getCondition() &&
  2120. PBI->getSuccessor(0) != PBI->getSuccessor(1)) {
  2121. bool CondIsTrue = PBI->getSuccessor(0) == BB;
  2122. NewPN->addIncoming(ConstantInt::get(Type::getInt1Ty(BB->getContext()),
  2123. CondIsTrue), P);
  2124. } else {
  2125. NewPN->addIncoming(BI->getCondition(), P);
  2126. }
  2127. }
  2128. BI->setCondition(NewPN);
  2129. return true;
  2130. }
  2131. }
  2132. // If this is a conditional branch in an empty block, and if any
  2133. // predecessors are a conditional branch to one of our destinations,
  2134. // fold the conditions into logical ops and one cond br.
  2135. BasicBlock::iterator BBI = BB->begin();
  2136. // Ignore dbg intrinsics.
  2137. while (isa<DbgInfoIntrinsic>(BBI))
  2138. ++BBI;
  2139. if (&*BBI != BI)
  2140. return false;
  2141. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BI->getCondition()))
  2142. if (CE->canTrap())
  2143. return false;
  2144. int PBIOp, BIOp;
  2145. if (PBI->getSuccessor(0) == BI->getSuccessor(0))
  2146. PBIOp = BIOp = 0;
  2147. else if (PBI->getSuccessor(0) == BI->getSuccessor(1))
  2148. PBIOp = 0, BIOp = 1;
  2149. else if (PBI->getSuccessor(1) == BI->getSuccessor(0))
  2150. PBIOp = 1, BIOp = 0;
  2151. else if (PBI->getSuccessor(1) == BI->getSuccessor(1))
  2152. PBIOp = BIOp = 1;
  2153. else
  2154. return false;
  2155. // Check to make sure that the other destination of this branch
  2156. // isn't BB itself. If so, this is an infinite loop that will
  2157. // keep getting unwound.
  2158. if (PBI->getSuccessor(PBIOp) == BB)
  2159. return false;
  2160. // Do not perform this transformation if it would require
  2161. // insertion of a large number of select instructions. For targets
  2162. // without predication/cmovs, this is a big pessimization.
  2163. // Also do not perform this transformation if any phi node in the common
  2164. // destination block can trap when reached by BB or PBB (PR17073). In that
  2165. // case, it would be unsafe to hoist the operation into a select instruction.
  2166. BasicBlock *CommonDest = PBI->getSuccessor(PBIOp);
  2167. unsigned NumPhis = 0;
  2168. for (BasicBlock::iterator II = CommonDest->begin();
  2169. isa<PHINode>(II); ++II, ++NumPhis) {
  2170. if (NumPhis > 2) // Disable this xform.
  2171. return false;
  2172. PHINode *PN = cast<PHINode>(II);
  2173. Value *BIV = PN->getIncomingValueForBlock(BB);
  2174. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(BIV))
  2175. if (CE->canTrap())
  2176. return false;
  2177. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2178. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2179. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(PBIV))
  2180. if (CE->canTrap())
  2181. return false;
  2182. }
  2183. // Finally, if everything is ok, fold the branches to logical ops.
  2184. BasicBlock *OtherDest = BI->getSuccessor(BIOp ^ 1);
  2185. DEBUG(dbgs() << "FOLDING BRs:" << *PBI->getParent()
  2186. << "AND: " << *BI->getParent());
  2187. // If OtherDest *is* BB, then BB is a basic block with a single conditional
  2188. // branch in it, where one edge (OtherDest) goes back to itself but the other
  2189. // exits. We don't *know* that the program avoids the infinite loop
  2190. // (even though that seems likely). If we do this xform naively, we'll end up
  2191. // recursively unpeeling the loop. Since we know that (after the xform is
  2192. // done) that the block *is* infinite if reached, we just make it an obviously
  2193. // infinite loop with no cond branch.
  2194. if (OtherDest == BB) {
  2195. // Insert it at the end of the function, because it's either code,
  2196. // or it won't matter if it's hot. :)
  2197. BasicBlock *InfLoopBlock = BasicBlock::Create(BB->getContext(),
  2198. "infloop", BB->getParent());
  2199. BranchInst::Create(InfLoopBlock, InfLoopBlock);
  2200. OtherDest = InfLoopBlock;
  2201. }
  2202. DEBUG(dbgs() << *PBI->getParent()->getParent());
  2203. // BI may have other predecessors. Because of this, we leave
  2204. // it alone, but modify PBI.
  2205. // Make sure we get to CommonDest on True&True directions.
  2206. Value *PBICond = PBI->getCondition();
  2207. IRBuilder<true, NoFolder> Builder(PBI);
  2208. if (PBIOp)
  2209. PBICond = Builder.CreateNot(PBICond, PBICond->getName()+".not");
  2210. Value *BICond = BI->getCondition();
  2211. if (BIOp)
  2212. BICond = Builder.CreateNot(BICond, BICond->getName()+".not");
  2213. // Merge the conditions.
  2214. Value *Cond = Builder.CreateOr(PBICond, BICond, "brmerge");
  2215. // Modify PBI to branch on the new condition to the new dests.
  2216. PBI->setCondition(Cond);
  2217. PBI->setSuccessor(0, CommonDest);
  2218. PBI->setSuccessor(1, OtherDest);
  2219. // Update branch weight for PBI.
  2220. uint64_t PredTrueWeight, PredFalseWeight, SuccTrueWeight, SuccFalseWeight;
  2221. bool PredHasWeights = ExtractBranchMetadata(PBI, PredTrueWeight,
  2222. PredFalseWeight);
  2223. bool SuccHasWeights = ExtractBranchMetadata(BI, SuccTrueWeight,
  2224. SuccFalseWeight);
  2225. if (PredHasWeights && SuccHasWeights) {
  2226. uint64_t PredCommon = PBIOp ? PredFalseWeight : PredTrueWeight;
  2227. uint64_t PredOther = PBIOp ?PredTrueWeight : PredFalseWeight;
  2228. uint64_t SuccCommon = BIOp ? SuccFalseWeight : SuccTrueWeight;
  2229. uint64_t SuccOther = BIOp ? SuccTrueWeight : SuccFalseWeight;
  2230. // The weight to CommonDest should be PredCommon * SuccTotal +
  2231. // PredOther * SuccCommon.
  2232. // The weight to OtherDest should be PredOther * SuccOther.
  2233. uint64_t NewWeights[2] = {PredCommon * (SuccCommon + SuccOther) +
  2234. PredOther * SuccCommon,
  2235. PredOther * SuccOther};
  2236. // Halve the weights if any of them cannot fit in an uint32_t
  2237. FitWeights(NewWeights);
  2238. PBI->setMetadata(LLVMContext::MD_prof,
  2239. MDBuilder(BI->getContext())
  2240. .createBranchWeights(NewWeights[0], NewWeights[1]));
  2241. }
  2242. // OtherDest may have phi nodes. If so, add an entry from PBI's
  2243. // block that are identical to the entries for BI's block.
  2244. AddPredecessorToBlock(OtherDest, PBI->getParent(), BB);
  2245. // We know that the CommonDest already had an edge from PBI to
  2246. // it. If it has PHIs though, the PHIs may have different
  2247. // entries for BB and PBI's BB. If so, insert a select to make
  2248. // them agree.
  2249. PHINode *PN;
  2250. for (BasicBlock::iterator II = CommonDest->begin();
  2251. (PN = dyn_cast<PHINode>(II)); ++II) {
  2252. Value *BIV = PN->getIncomingValueForBlock(BB);
  2253. unsigned PBBIdx = PN->getBasicBlockIndex(PBI->getParent());
  2254. Value *PBIV = PN->getIncomingValue(PBBIdx);
  2255. if (BIV != PBIV) {
  2256. // Insert a select in PBI to pick the right value.
  2257. Value *NV = cast<SelectInst>
  2258. (Builder.CreateSelect(PBICond, PBIV, BIV, PBIV->getName()+".mux"));
  2259. PN->setIncomingValue(PBBIdx, NV);
  2260. }
  2261. }
  2262. DEBUG(dbgs() << "INTO: " << *PBI->getParent());
  2263. DEBUG(dbgs() << *PBI->getParent()->getParent());
  2264. // This basic block is probably dead. We know it has at least
  2265. // one fewer predecessor.
  2266. return true;
  2267. }
  2268. // Simplifies a terminator by replacing it with a branch to TrueBB if Cond is
  2269. // true or to FalseBB if Cond is false.
  2270. // Takes care of updating the successors and removing the old terminator.
  2271. // Also makes sure not to introduce new successors by assuming that edges to
  2272. // non-successor TrueBBs and FalseBBs aren't reachable.
  2273. static bool SimplifyTerminatorOnSelect(TerminatorInst *OldTerm, Value *Cond,
  2274. BasicBlock *TrueBB, BasicBlock *FalseBB,
  2275. uint32_t TrueWeight,
  2276. uint32_t FalseWeight){
  2277. // Remove any superfluous successor edges from the CFG.
  2278. // First, figure out which successors to preserve.
  2279. // If TrueBB and FalseBB are equal, only try to preserve one copy of that
  2280. // successor.
  2281. BasicBlock *KeepEdge1 = TrueBB;
  2282. BasicBlock *KeepEdge2 = TrueBB != FalseBB ? FalseBB : nullptr;
  2283. // Then remove the rest.
  2284. for (unsigned I = 0, E = OldTerm->getNumSuccessors(); I != E; ++I) {
  2285. BasicBlock *Succ = OldTerm->getSuccessor(I);
  2286. // Make sure only to keep exactly one copy of each edge.
  2287. if (Succ == KeepEdge1)
  2288. KeepEdge1 = nullptr;
  2289. else if (Succ == KeepEdge2)
  2290. KeepEdge2 = nullptr;
  2291. else
  2292. Succ->removePredecessor(OldTerm->getParent());
  2293. }
  2294. IRBuilder<> Builder(OldTerm);
  2295. Builder.SetCurrentDebugLocation(OldTerm->getDebugLoc());
  2296. // Insert an appropriate new terminator.
  2297. if (!KeepEdge1 && !KeepEdge2) {
  2298. if (TrueBB == FalseBB)
  2299. // We were only looking for one successor, and it was present.
  2300. // Create an unconditional branch to it.
  2301. Builder.CreateBr(TrueBB);
  2302. else {
  2303. // We found both of the successors we were looking for.
  2304. // Create a conditional branch sharing the condition of the select.
  2305. BranchInst *NewBI = Builder.CreateCondBr(Cond, TrueBB, FalseBB);
  2306. if (TrueWeight != FalseWeight)
  2307. NewBI->setMetadata(LLVMContext::MD_prof,
  2308. MDBuilder(OldTerm->getContext()).
  2309. createBranchWeights(TrueWeight, FalseWeight));
  2310. }
  2311. } else if (KeepEdge1 && (KeepEdge2 || TrueBB == FalseBB)) {
  2312. // Neither of the selected blocks were successors, so this
  2313. // terminator must be unreachable.
  2314. new UnreachableInst(OldTerm->getContext(), OldTerm);
  2315. } else {
  2316. // One of the selected values was a successor, but the other wasn't.
  2317. // Insert an unconditional branch to the one that was found;
  2318. // the edge to the one that wasn't must be unreachable.
  2319. if (!KeepEdge1)
  2320. // Only TrueBB was found.
  2321. Builder.CreateBr(TrueBB);
  2322. else
  2323. // Only FalseBB was found.
  2324. Builder.CreateBr(FalseBB);
  2325. }
  2326. EraseTerminatorInstAndDCECond(OldTerm);
  2327. return true;
  2328. }
  2329. // Replaces
  2330. // (switch (select cond, X, Y)) on constant X, Y
  2331. // with a branch - conditional if X and Y lead to distinct BBs,
  2332. // unconditional otherwise.
  2333. static bool SimplifySwitchOnSelect(SwitchInst *SI, SelectInst *Select) {
  2334. // Check for constant integer values in the select.
  2335. ConstantInt *TrueVal = dyn_cast<ConstantInt>(Select->getTrueValue());
  2336. ConstantInt *FalseVal = dyn_cast<ConstantInt>(Select->getFalseValue());
  2337. if (!TrueVal || !FalseVal)
  2338. return false;
  2339. // Find the relevant condition and destinations.
  2340. Value *Condition = Select->getCondition();
  2341. BasicBlock *TrueBB = SI->findCaseValue(TrueVal).getCaseSuccessor();
  2342. BasicBlock *FalseBB = SI->findCaseValue(FalseVal).getCaseSuccessor();
  2343. // Get weight for TrueBB and FalseBB.
  2344. uint32_t TrueWeight = 0, FalseWeight = 0;
  2345. SmallVector<uint64_t, 8> Weights;
  2346. bool HasWeights = HasBranchWeights(SI);
  2347. if (HasWeights) {
  2348. GetBranchWeights(SI, Weights);
  2349. if (Weights.size() == 1 + SI->getNumCases()) {
  2350. TrueWeight = (uint32_t)Weights[SI->findCaseValue(TrueVal).
  2351. getSuccessorIndex()];
  2352. FalseWeight = (uint32_t)Weights[SI->findCaseValue(FalseVal).
  2353. getSuccessorIndex()];
  2354. }
  2355. }
  2356. // Perform the actual simplification.
  2357. return SimplifyTerminatorOnSelect(SI, Condition, TrueBB, FalseBB,
  2358. TrueWeight, FalseWeight);
  2359. }
  2360. // Replaces
  2361. // (indirectbr (select cond, blockaddress(@fn, BlockA),
  2362. // blockaddress(@fn, BlockB)))
  2363. // with
  2364. // (br cond, BlockA, BlockB).
  2365. static bool SimplifyIndirectBrOnSelect(IndirectBrInst *IBI, SelectInst *SI) {
  2366. // Check that both operands of the select are block addresses.
  2367. BlockAddress *TBA = dyn_cast<BlockAddress>(SI->getTrueValue());
  2368. BlockAddress *FBA = dyn_cast<BlockAddress>(SI->getFalseValue());
  2369. if (!TBA || !FBA)
  2370. return false;
  2371. // Extract the actual blocks.
  2372. BasicBlock *TrueBB = TBA->getBasicBlock();
  2373. BasicBlock *FalseBB = FBA->getBasicBlock();
  2374. // Perform the actual simplification.
  2375. return SimplifyTerminatorOnSelect(IBI, SI->getCondition(), TrueBB, FalseBB,
  2376. 0, 0);
  2377. }
  2378. /// This is called when we find an icmp instruction
  2379. /// (a seteq/setne with a constant) as the only instruction in a
  2380. /// block that ends with an uncond branch. We are looking for a very specific
  2381. /// pattern that occurs when "A == 1 || A == 2 || A == 3" gets simplified. In
  2382. /// this case, we merge the first two "or's of icmp" into a switch, but then the
  2383. /// default value goes to an uncond block with a seteq in it, we get something
  2384. /// like:
  2385. ///
  2386. /// switch i8 %A, label %DEFAULT [ i8 1, label %end i8 2, label %end ]
  2387. /// DEFAULT:
  2388. /// %tmp = icmp eq i8 %A, 92
  2389. /// br label %end
  2390. /// end:
  2391. /// ... = phi i1 [ true, %entry ], [ %tmp, %DEFAULT ], [ true, %entry ]
  2392. ///
  2393. /// We prefer to split the edge to 'end' so that there is a true/false entry to
  2394. /// the PHI, merging the third icmp into the switch.
  2395. static bool TryToSimplifyUncondBranchWithICmpInIt(
  2396. ICmpInst *ICI, IRBuilder<> &Builder, const DataLayout &DL,
  2397. const TargetTransformInfo &TTI, unsigned BonusInstThreshold,
  2398. AssumptionCache *AC) {
  2399. BasicBlock *BB = ICI->getParent();
  2400. // If the block has any PHIs in it or the icmp has multiple uses, it is too
  2401. // complex.
  2402. if (isa<PHINode>(BB->begin()) || !ICI->hasOneUse()) return false;
  2403. Value *V = ICI->getOperand(0);
  2404. ConstantInt *Cst = cast<ConstantInt>(ICI->getOperand(1));
  2405. // The pattern we're looking for is where our only predecessor is a switch on
  2406. // 'V' and this block is the default case for the switch. In this case we can
  2407. // fold the compared value into the switch to simplify things.
  2408. BasicBlock *Pred = BB->getSinglePredecessor();
  2409. if (!Pred || !isa<SwitchInst>(Pred->getTerminator())) return false;
  2410. SwitchInst *SI = cast<SwitchInst>(Pred->getTerminator());
  2411. if (SI->getCondition() != V)
  2412. return false;
  2413. // If BB is reachable on a non-default case, then we simply know the value of
  2414. // V in this block. Substitute it and constant fold the icmp instruction
  2415. // away.
  2416. if (SI->getDefaultDest() != BB) {
  2417. ConstantInt *VVal = SI->findCaseDest(BB);
  2418. assert(VVal && "Should have a unique destination value");
  2419. ICI->setOperand(0, VVal);
  2420. if (Value *V = SimplifyInstruction(ICI, DL)) {
  2421. ICI->replaceAllUsesWith(V);
  2422. ICI->eraseFromParent();
  2423. }
  2424. // BB is now empty, so it is likely to simplify away.
  2425. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  2426. }
  2427. // Ok, the block is reachable from the default dest. If the constant we're
  2428. // comparing exists in one of the other edges, then we can constant fold ICI
  2429. // and zap it.
  2430. if (SI->findCaseValue(Cst) != SI->case_default()) {
  2431. Value *V;
  2432. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  2433. V = ConstantInt::getFalse(BB->getContext());
  2434. else
  2435. V = ConstantInt::getTrue(BB->getContext());
  2436. ICI->replaceAllUsesWith(V);
  2437. ICI->eraseFromParent();
  2438. // BB is now empty, so it is likely to simplify away.
  2439. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  2440. }
  2441. // The use of the icmp has to be in the 'end' block, by the only PHI node in
  2442. // the block.
  2443. BasicBlock *SuccBlock = BB->getTerminator()->getSuccessor(0);
  2444. PHINode *PHIUse = dyn_cast<PHINode>(ICI->user_back());
  2445. if (PHIUse == nullptr || PHIUse != &SuccBlock->front() ||
  2446. isa<PHINode>(++BasicBlock::iterator(PHIUse)))
  2447. return false;
  2448. // If the icmp is a SETEQ, then the default dest gets false, the new edge gets
  2449. // true in the PHI.
  2450. Constant *DefaultCst = ConstantInt::getTrue(BB->getContext());
  2451. Constant *NewCst = ConstantInt::getFalse(BB->getContext());
  2452. if (ICI->getPredicate() == ICmpInst::ICMP_EQ)
  2453. std::swap(DefaultCst, NewCst);
  2454. // Replace ICI (which is used by the PHI for the default value) with true or
  2455. // false depending on if it is EQ or NE.
  2456. ICI->replaceAllUsesWith(DefaultCst);
  2457. ICI->eraseFromParent();
  2458. // Okay, the switch goes to this block on a default value. Add an edge from
  2459. // the switch to the merge point on the compared value.
  2460. BasicBlock *NewBB = BasicBlock::Create(BB->getContext(), "switch.edge",
  2461. BB->getParent(), BB);
  2462. SmallVector<uint64_t, 8> Weights;
  2463. bool HasWeights = HasBranchWeights(SI);
  2464. if (HasWeights) {
  2465. GetBranchWeights(SI, Weights);
  2466. if (Weights.size() == 1 + SI->getNumCases()) {
  2467. // Split weight for default case to case for "Cst".
  2468. Weights[0] = (Weights[0]+1) >> 1;
  2469. Weights.push_back(Weights[0]);
  2470. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  2471. SI->setMetadata(LLVMContext::MD_prof,
  2472. MDBuilder(SI->getContext()).
  2473. createBranchWeights(MDWeights));
  2474. }
  2475. }
  2476. SI->addCase(Cst, NewBB);
  2477. // NewBB branches to the phi block, add the uncond branch and the phi entry.
  2478. Builder.SetInsertPoint(NewBB);
  2479. Builder.SetCurrentDebugLocation(SI->getDebugLoc());
  2480. Builder.CreateBr(SuccBlock);
  2481. PHIUse->addIncoming(NewCst, NewBB);
  2482. return true;
  2483. }
  2484. /// The specified branch is a conditional branch.
  2485. /// Check to see if it is branching on an or/and chain of icmp instructions, and
  2486. /// fold it into a switch instruction if so.
  2487. static bool SimplifyBranchOnICmpChain(BranchInst *BI, IRBuilder<> &Builder,
  2488. const DataLayout &DL) {
  2489. Instruction *Cond = dyn_cast<Instruction>(BI->getCondition());
  2490. if (!Cond) return false;
  2491. // Change br (X == 0 | X == 1), T, F into a switch instruction.
  2492. // If this is a bunch of seteq's or'd together, or if it's a bunch of
  2493. // 'setne's and'ed together, collect them.
  2494. // Try to gather values from a chain of and/or to be turned into a switch
  2495. ConstantComparesGatherer ConstantCompare(Cond, DL);
  2496. // Unpack the result
  2497. SmallVectorImpl<ConstantInt*> &Values = ConstantCompare.Vals;
  2498. Value *CompVal = ConstantCompare.CompValue;
  2499. unsigned UsedICmps = ConstantCompare.UsedICmps;
  2500. Value *ExtraCase = ConstantCompare.Extra;
  2501. // If we didn't have a multiply compared value, fail.
  2502. if (!CompVal) return false;
  2503. // Avoid turning single icmps into a switch.
  2504. if (UsedICmps <= 1)
  2505. return false;
  2506. bool TrueWhenEqual = (Cond->getOpcode() == Instruction::Or);
  2507. // There might be duplicate constants in the list, which the switch
  2508. // instruction can't handle, remove them now.
  2509. array_pod_sort(Values.begin(), Values.end(), ConstantIntSortPredicate);
  2510. Values.erase(std::unique(Values.begin(), Values.end()), Values.end());
  2511. // If Extra was used, we require at least two switch values to do the
  2512. // transformation. A switch with one value is just an cond branch.
  2513. if (ExtraCase && Values.size() < 2) return false;
  2514. // TODO: Preserve branch weight metadata, similarly to how
  2515. // FoldValueComparisonIntoPredecessors preserves it.
  2516. // Figure out which block is which destination.
  2517. BasicBlock *DefaultBB = BI->getSuccessor(1);
  2518. BasicBlock *EdgeBB = BI->getSuccessor(0);
  2519. if (!TrueWhenEqual) std::swap(DefaultBB, EdgeBB);
  2520. BasicBlock *BB = BI->getParent();
  2521. DEBUG(dbgs() << "Converting 'icmp' chain with " << Values.size()
  2522. << " cases into SWITCH. BB is:\n" << *BB);
  2523. // If there are any extra values that couldn't be folded into the switch
  2524. // then we evaluate them with an explicit branch first. Split the block
  2525. // right before the condbr to handle it.
  2526. if (ExtraCase) {
  2527. BasicBlock *NewBB = BB->splitBasicBlock(BI, "switch.early.test");
  2528. // Remove the uncond branch added to the old block.
  2529. TerminatorInst *OldTI = BB->getTerminator();
  2530. Builder.SetInsertPoint(OldTI);
  2531. if (TrueWhenEqual)
  2532. Builder.CreateCondBr(ExtraCase, EdgeBB, NewBB);
  2533. else
  2534. Builder.CreateCondBr(ExtraCase, NewBB, EdgeBB);
  2535. OldTI->eraseFromParent();
  2536. // If there are PHI nodes in EdgeBB, then we need to add a new entry to them
  2537. // for the edge we just added.
  2538. AddPredecessorToBlock(EdgeBB, BB, NewBB);
  2539. DEBUG(dbgs() << " ** 'icmp' chain unhandled condition: " << *ExtraCase
  2540. << "\nEXTRABB = " << *BB);
  2541. BB = NewBB;
  2542. }
  2543. Builder.SetInsertPoint(BI);
  2544. // Convert pointer to int before we switch.
  2545. if (CompVal->getType()->isPointerTy()) {
  2546. CompVal = Builder.CreatePtrToInt(
  2547. CompVal, DL.getIntPtrType(CompVal->getType()), "magicptr");
  2548. }
  2549. // Create the new switch instruction now.
  2550. SwitchInst *New = Builder.CreateSwitch(CompVal, DefaultBB, Values.size());
  2551. // Add all of the 'cases' to the switch instruction.
  2552. for (unsigned i = 0, e = Values.size(); i != e; ++i)
  2553. New->addCase(Values[i], EdgeBB);
  2554. // We added edges from PI to the EdgeBB. As such, if there were any
  2555. // PHI nodes in EdgeBB, they need entries to be added corresponding to
  2556. // the number of edges added.
  2557. for (BasicBlock::iterator BBI = EdgeBB->begin();
  2558. isa<PHINode>(BBI); ++BBI) {
  2559. PHINode *PN = cast<PHINode>(BBI);
  2560. Value *InVal = PN->getIncomingValueForBlock(BB);
  2561. for (unsigned i = 0, e = Values.size()-1; i != e; ++i)
  2562. PN->addIncoming(InVal, BB);
  2563. }
  2564. // Erase the old branch instruction.
  2565. EraseTerminatorInstAndDCECond(BI);
  2566. DEBUG(dbgs() << " ** 'icmp' chain result is:\n" << *BB << '\n');
  2567. return true;
  2568. }
  2569. bool SimplifyCFGOpt::SimplifyResume(ResumeInst *RI, IRBuilder<> &Builder) {
  2570. // If this is a trivial landing pad that just continues unwinding the caught
  2571. // exception then zap the landing pad, turning its invokes into calls.
  2572. BasicBlock *BB = RI->getParent();
  2573. LandingPadInst *LPInst = dyn_cast<LandingPadInst>(BB->getFirstNonPHI());
  2574. if (RI->getValue() != LPInst)
  2575. // Not a landing pad, or the resume is not unwinding the exception that
  2576. // caused control to branch here.
  2577. return false;
  2578. // Check that there are no other instructions except for debug intrinsics.
  2579. BasicBlock::iterator I = LPInst, E = RI;
  2580. while (++I != E)
  2581. if (!isa<DbgInfoIntrinsic>(I))
  2582. return false;
  2583. // Turn all invokes that unwind here into calls and delete the basic block.
  2584. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE;) {
  2585. InvokeInst *II = cast<InvokeInst>((*PI++)->getTerminator());
  2586. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end() - 3);
  2587. // Insert a call instruction before the invoke.
  2588. CallInst *Call = CallInst::Create(II->getCalledValue(), Args, "", II);
  2589. Call->takeName(II);
  2590. Call->setCallingConv(II->getCallingConv());
  2591. Call->setAttributes(II->getAttributes());
  2592. Call->setDebugLoc(II->getDebugLoc());
  2593. // Anything that used the value produced by the invoke instruction now uses
  2594. // the value produced by the call instruction. Note that we do this even
  2595. // for void functions and calls with no uses so that the callgraph edge is
  2596. // updated.
  2597. II->replaceAllUsesWith(Call);
  2598. BB->removePredecessor(II->getParent());
  2599. // Insert a branch to the normal destination right before the invoke.
  2600. BranchInst::Create(II->getNormalDest(), II);
  2601. // Finally, delete the invoke instruction!
  2602. II->eraseFromParent();
  2603. }
  2604. // The landingpad is now unreachable. Zap it.
  2605. BB->eraseFromParent();
  2606. return true;
  2607. }
  2608. bool SimplifyCFGOpt::SimplifyReturn(ReturnInst *RI, IRBuilder<> &Builder) {
  2609. BasicBlock *BB = RI->getParent();
  2610. if (!BB->getFirstNonPHIOrDbg()->isTerminator()) return false;
  2611. // Find predecessors that end with branches.
  2612. SmallVector<BasicBlock*, 8> UncondBranchPreds;
  2613. SmallVector<BranchInst*, 8> CondBranchPreds;
  2614. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI) {
  2615. BasicBlock *P = *PI;
  2616. TerminatorInst *PTI = P->getTerminator();
  2617. if (BranchInst *BI = dyn_cast<BranchInst>(PTI)) {
  2618. if (BI->isUnconditional())
  2619. UncondBranchPreds.push_back(P);
  2620. else
  2621. CondBranchPreds.push_back(BI);
  2622. }
  2623. }
  2624. // If we found some, do the transformation!
  2625. if (!UncondBranchPreds.empty() && DupRet) {
  2626. while (!UncondBranchPreds.empty()) {
  2627. BasicBlock *Pred = UncondBranchPreds.pop_back_val();
  2628. DEBUG(dbgs() << "FOLDING: " << *BB
  2629. << "INTO UNCOND BRANCH PRED: " << *Pred);
  2630. (void)FoldReturnIntoUncondBranch(RI, BB, Pred);
  2631. }
  2632. // If we eliminated all predecessors of the block, delete the block now.
  2633. if (pred_empty(BB))
  2634. // We know there are no successors, so just nuke the block.
  2635. BB->eraseFromParent();
  2636. return true;
  2637. }
  2638. // Check out all of the conditional branches going to this return
  2639. // instruction. If any of them just select between returns, change the
  2640. // branch itself into a select/return pair.
  2641. while (!CondBranchPreds.empty()) {
  2642. BranchInst *BI = CondBranchPreds.pop_back_val();
  2643. // Check to see if the non-BB successor is also a return block.
  2644. if (isa<ReturnInst>(BI->getSuccessor(0)->getTerminator()) &&
  2645. isa<ReturnInst>(BI->getSuccessor(1)->getTerminator()) &&
  2646. SimplifyCondBranchToTwoReturns(BI, Builder))
  2647. return true;
  2648. }
  2649. return false;
  2650. }
  2651. bool SimplifyCFGOpt::SimplifyUnreachable(UnreachableInst *UI) {
  2652. BasicBlock *BB = UI->getParent();
  2653. bool Changed = false;
  2654. // If there are any instructions immediately before the unreachable that can
  2655. // be removed, do so.
  2656. while (UI != BB->begin()) {
  2657. BasicBlock::iterator BBI = UI;
  2658. --BBI;
  2659. // Do not delete instructions that can have side effects which might cause
  2660. // the unreachable to not be reachable; specifically, calls and volatile
  2661. // operations may have this effect.
  2662. if (isa<CallInst>(BBI) && !isa<DbgInfoIntrinsic>(BBI)) break;
  2663. if (BBI->mayHaveSideEffects()) {
  2664. if (StoreInst *SI = dyn_cast<StoreInst>(BBI)) {
  2665. if (SI->isVolatile())
  2666. break;
  2667. } else if (LoadInst *LI = dyn_cast<LoadInst>(BBI)) {
  2668. if (LI->isVolatile())
  2669. break;
  2670. } else if (AtomicRMWInst *RMWI = dyn_cast<AtomicRMWInst>(BBI)) {
  2671. if (RMWI->isVolatile())
  2672. break;
  2673. } else if (AtomicCmpXchgInst *CXI = dyn_cast<AtomicCmpXchgInst>(BBI)) {
  2674. if (CXI->isVolatile())
  2675. break;
  2676. } else if (!isa<FenceInst>(BBI) && !isa<VAArgInst>(BBI) &&
  2677. !isa<LandingPadInst>(BBI)) {
  2678. break;
  2679. }
  2680. // Note that deleting LandingPad's here is in fact okay, although it
  2681. // involves a bit of subtle reasoning. If this inst is a LandingPad,
  2682. // all the predecessors of this block will be the unwind edges of Invokes,
  2683. // and we can therefore guarantee this block will be erased.
  2684. }
  2685. // Delete this instruction (any uses are guaranteed to be dead)
  2686. if (!BBI->use_empty())
  2687. BBI->replaceAllUsesWith(UndefValue::get(BBI->getType()));
  2688. BBI->eraseFromParent();
  2689. Changed = true;
  2690. }
  2691. // If the unreachable instruction is the first in the block, take a gander
  2692. // at all of the predecessors of this instruction, and simplify them.
  2693. if (&BB->front() != UI) return Changed;
  2694. SmallVector<BasicBlock*, 8> Preds(pred_begin(BB), pred_end(BB));
  2695. for (unsigned i = 0, e = Preds.size(); i != e; ++i) {
  2696. TerminatorInst *TI = Preds[i]->getTerminator();
  2697. IRBuilder<> Builder(TI);
  2698. if (BranchInst *BI = dyn_cast<BranchInst>(TI)) {
  2699. if (BI->isUnconditional()) {
  2700. if (BI->getSuccessor(0) == BB) {
  2701. new UnreachableInst(TI->getContext(), TI);
  2702. TI->eraseFromParent();
  2703. Changed = true;
  2704. }
  2705. } else {
  2706. if (BI->getSuccessor(0) == BB) {
  2707. Builder.CreateBr(BI->getSuccessor(1));
  2708. EraseTerminatorInstAndDCECond(BI);
  2709. } else if (BI->getSuccessor(1) == BB) {
  2710. Builder.CreateBr(BI->getSuccessor(0));
  2711. EraseTerminatorInstAndDCECond(BI);
  2712. Changed = true;
  2713. }
  2714. }
  2715. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(TI)) {
  2716. for (SwitchInst::CaseIt i = SI->case_begin(), e = SI->case_end();
  2717. i != e; ++i)
  2718. if (i.getCaseSuccessor() == BB) {
  2719. BB->removePredecessor(SI->getParent());
  2720. SI->removeCase(i);
  2721. --i; --e;
  2722. Changed = true;
  2723. }
  2724. } else if (InvokeInst *II = dyn_cast<InvokeInst>(TI)) {
  2725. if (II->getUnwindDest() == BB) {
  2726. // Convert the invoke to a call instruction. This would be a good
  2727. // place to note that the call does not throw though.
  2728. BranchInst *BI = Builder.CreateBr(II->getNormalDest());
  2729. II->removeFromParent(); // Take out of symbol table
  2730. // Insert the call now...
  2731. SmallVector<Value*, 8> Args(II->op_begin(), II->op_end()-3);
  2732. Builder.SetInsertPoint(BI);
  2733. CallInst *CI = Builder.CreateCall(II->getCalledValue(),
  2734. Args, II->getName());
  2735. CI->setCallingConv(II->getCallingConv());
  2736. CI->setAttributes(II->getAttributes());
  2737. // If the invoke produced a value, the call does now instead.
  2738. II->replaceAllUsesWith(CI);
  2739. delete II;
  2740. Changed = true;
  2741. }
  2742. }
  2743. }
  2744. // If this block is now dead, remove it.
  2745. if (pred_empty(BB) &&
  2746. BB != &BB->getParent()->getEntryBlock()) {
  2747. // We know there are no successors, so just nuke the block.
  2748. BB->eraseFromParent();
  2749. return true;
  2750. }
  2751. return Changed;
  2752. }
  2753. static bool CasesAreContiguous(SmallVectorImpl<ConstantInt *> &Cases) {
  2754. assert(Cases.size() >= 1);
  2755. array_pod_sort(Cases.begin(), Cases.end(), ConstantIntSortPredicate);
  2756. for (size_t I = 1, E = Cases.size(); I != E; ++I) {
  2757. if (Cases[I - 1]->getValue() != Cases[I]->getValue() + 1)
  2758. return false;
  2759. }
  2760. return true;
  2761. }
  2762. /// Turn a switch with two reachable destinations into an integer range
  2763. /// comparison and branch.
  2764. static bool TurnSwitchRangeIntoICmp(SwitchInst *SI, IRBuilder<> &Builder) {
  2765. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  2766. bool HasDefault =
  2767. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  2768. // Partition the cases into two sets with different destinations.
  2769. BasicBlock *DestA = HasDefault ? SI->getDefaultDest() : nullptr;
  2770. BasicBlock *DestB = nullptr;
  2771. SmallVector <ConstantInt *, 16> CasesA;
  2772. SmallVector <ConstantInt *, 16> CasesB;
  2773. for (SwitchInst::CaseIt I : SI->cases()) {
  2774. BasicBlock *Dest = I.getCaseSuccessor();
  2775. if (!DestA) DestA = Dest;
  2776. if (Dest == DestA) {
  2777. CasesA.push_back(I.getCaseValue());
  2778. continue;
  2779. }
  2780. if (!DestB) DestB = Dest;
  2781. if (Dest == DestB) {
  2782. CasesB.push_back(I.getCaseValue());
  2783. continue;
  2784. }
  2785. return false; // More than two destinations.
  2786. }
  2787. assert(DestA && DestB && "Single-destination switch should have been folded.");
  2788. assert(DestA != DestB);
  2789. assert(DestB != SI->getDefaultDest());
  2790. assert(!CasesB.empty() && "There must be non-default cases.");
  2791. assert(!CasesA.empty() || HasDefault);
  2792. // Figure out if one of the sets of cases form a contiguous range.
  2793. SmallVectorImpl<ConstantInt *> *ContiguousCases = nullptr;
  2794. BasicBlock *ContiguousDest = nullptr;
  2795. BasicBlock *OtherDest = nullptr;
  2796. if (!CasesA.empty() && CasesAreContiguous(CasesA)) {
  2797. ContiguousCases = &CasesA;
  2798. ContiguousDest = DestA;
  2799. OtherDest = DestB;
  2800. } else if (CasesAreContiguous(CasesB)) {
  2801. ContiguousCases = &CasesB;
  2802. ContiguousDest = DestB;
  2803. OtherDest = DestA;
  2804. } else
  2805. return false;
  2806. // Start building the compare and branch.
  2807. Constant *Offset = ConstantExpr::getNeg(ContiguousCases->back());
  2808. Constant *NumCases = ConstantInt::get(Offset->getType(), ContiguousCases->size());
  2809. Value *Sub = SI->getCondition();
  2810. if (!Offset->isNullValue())
  2811. Sub = Builder.CreateAdd(Sub, Offset, Sub->getName() + ".off");
  2812. Value *Cmp;
  2813. // If NumCases overflowed, then all possible values jump to the successor.
  2814. if (NumCases->isNullValue() && !ContiguousCases->empty())
  2815. Cmp = ConstantInt::getTrue(SI->getContext());
  2816. else
  2817. Cmp = Builder.CreateICmpULT(Sub, NumCases, "switch");
  2818. BranchInst *NewBI = Builder.CreateCondBr(Cmp, ContiguousDest, OtherDest);
  2819. // Update weight for the newly-created conditional branch.
  2820. if (HasBranchWeights(SI)) {
  2821. SmallVector<uint64_t, 8> Weights;
  2822. GetBranchWeights(SI, Weights);
  2823. if (Weights.size() == 1 + SI->getNumCases()) {
  2824. uint64_t TrueWeight = 0;
  2825. uint64_t FalseWeight = 0;
  2826. for (size_t I = 0, E = Weights.size(); I != E; ++I) {
  2827. if (SI->getSuccessor(I) == ContiguousDest)
  2828. TrueWeight += Weights[I];
  2829. else
  2830. FalseWeight += Weights[I];
  2831. }
  2832. while (TrueWeight > UINT32_MAX || FalseWeight > UINT32_MAX) {
  2833. TrueWeight /= 2;
  2834. FalseWeight /= 2;
  2835. }
  2836. NewBI->setMetadata(LLVMContext::MD_prof,
  2837. MDBuilder(SI->getContext()).createBranchWeights(
  2838. (uint32_t)TrueWeight, (uint32_t)FalseWeight));
  2839. }
  2840. }
  2841. // Prune obsolete incoming values off the successors' PHI nodes.
  2842. for (auto BBI = ContiguousDest->begin(); isa<PHINode>(BBI); ++BBI) {
  2843. unsigned PreviousEdges = ContiguousCases->size();
  2844. if (ContiguousDest == SI->getDefaultDest()) ++PreviousEdges;
  2845. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  2846. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  2847. }
  2848. for (auto BBI = OtherDest->begin(); isa<PHINode>(BBI); ++BBI) {
  2849. unsigned PreviousEdges = SI->getNumCases() - ContiguousCases->size();
  2850. if (OtherDest == SI->getDefaultDest()) ++PreviousEdges;
  2851. for (unsigned I = 0, E = PreviousEdges - 1; I != E; ++I)
  2852. cast<PHINode>(BBI)->removeIncomingValue(SI->getParent());
  2853. }
  2854. // Drop the switch.
  2855. SI->eraseFromParent();
  2856. return true;
  2857. }
  2858. /// Compute masked bits for the condition of a switch
  2859. /// and use it to remove dead cases.
  2860. static bool EliminateDeadSwitchCases(SwitchInst *SI, AssumptionCache *AC,
  2861. const DataLayout &DL) {
  2862. Value *Cond = SI->getCondition();
  2863. unsigned Bits = Cond->getType()->getIntegerBitWidth();
  2864. APInt KnownZero(Bits, 0), KnownOne(Bits, 0);
  2865. computeKnownBits(Cond, KnownZero, KnownOne, DL, 0, AC, SI);
  2866. // Gather dead cases.
  2867. SmallVector<ConstantInt*, 8> DeadCases;
  2868. for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
  2869. if ((I.getCaseValue()->getValue() & KnownZero) != 0 ||
  2870. (I.getCaseValue()->getValue() & KnownOne) != KnownOne) {
  2871. DeadCases.push_back(I.getCaseValue());
  2872. DEBUG(dbgs() << "SimplifyCFG: switch case '"
  2873. << I.getCaseValue() << "' is dead.\n");
  2874. }
  2875. }
  2876. SmallVector<uint64_t, 8> Weights;
  2877. bool HasWeight = HasBranchWeights(SI);
  2878. if (HasWeight) {
  2879. GetBranchWeights(SI, Weights);
  2880. HasWeight = (Weights.size() == 1 + SI->getNumCases());
  2881. }
  2882. // Remove dead cases from the switch.
  2883. for (unsigned I = 0, E = DeadCases.size(); I != E; ++I) {
  2884. SwitchInst::CaseIt Case = SI->findCaseValue(DeadCases[I]);
  2885. assert(Case != SI->case_default() &&
  2886. "Case was not found. Probably mistake in DeadCases forming.");
  2887. if (HasWeight) {
  2888. std::swap(Weights[Case.getCaseIndex()+1], Weights.back());
  2889. Weights.pop_back();
  2890. }
  2891. // Prune unused values from PHI nodes.
  2892. Case.getCaseSuccessor()->removePredecessor(SI->getParent());
  2893. SI->removeCase(Case);
  2894. }
  2895. if (HasWeight && Weights.size() >= 2) {
  2896. SmallVector<uint32_t, 8> MDWeights(Weights.begin(), Weights.end());
  2897. SI->setMetadata(LLVMContext::MD_prof,
  2898. MDBuilder(SI->getParent()->getContext()).
  2899. createBranchWeights(MDWeights));
  2900. }
  2901. return !DeadCases.empty();
  2902. }
  2903. /// If BB would be eligible for simplification by
  2904. /// TryToSimplifyUncondBranchFromEmptyBlock (i.e. it is empty and terminated
  2905. /// by an unconditional branch), look at the phi node for BB in the successor
  2906. /// block and see if the incoming value is equal to CaseValue. If so, return
  2907. /// the phi node, and set PhiIndex to BB's index in the phi node.
  2908. static PHINode *FindPHIForConditionForwarding(ConstantInt *CaseValue,
  2909. BasicBlock *BB,
  2910. int *PhiIndex) {
  2911. if (BB->getFirstNonPHIOrDbg() != BB->getTerminator())
  2912. return nullptr; // BB must be empty to be a candidate for simplification.
  2913. if (!BB->getSinglePredecessor())
  2914. return nullptr; // BB must be dominated by the switch.
  2915. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  2916. if (!Branch || !Branch->isUnconditional())
  2917. return nullptr; // Terminator must be unconditional branch.
  2918. BasicBlock *Succ = Branch->getSuccessor(0);
  2919. BasicBlock::iterator I = Succ->begin();
  2920. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  2921. int Idx = PHI->getBasicBlockIndex(BB);
  2922. assert(Idx >= 0 && "PHI has no entry for predecessor?");
  2923. Value *InValue = PHI->getIncomingValue(Idx);
  2924. if (InValue != CaseValue) continue;
  2925. *PhiIndex = Idx;
  2926. return PHI;
  2927. }
  2928. return nullptr;
  2929. }
  2930. /// Try to forward the condition of a switch instruction to a phi node
  2931. /// dominated by the switch, if that would mean that some of the destination
  2932. /// blocks of the switch can be folded away.
  2933. /// Returns true if a change is made.
  2934. static bool ForwardSwitchConditionToPHI(SwitchInst *SI) {
  2935. typedef DenseMap<PHINode*, SmallVector<int,4> > ForwardingNodesMap;
  2936. ForwardingNodesMap ForwardingNodes;
  2937. for (SwitchInst::CaseIt I = SI->case_begin(), E = SI->case_end(); I != E; ++I) {
  2938. ConstantInt *CaseValue = I.getCaseValue();
  2939. BasicBlock *CaseDest = I.getCaseSuccessor();
  2940. int PhiIndex;
  2941. PHINode *PHI = FindPHIForConditionForwarding(CaseValue, CaseDest,
  2942. &PhiIndex);
  2943. if (!PHI) continue;
  2944. ForwardingNodes[PHI].push_back(PhiIndex);
  2945. }
  2946. bool Changed = false;
  2947. for (ForwardingNodesMap::iterator I = ForwardingNodes.begin(),
  2948. E = ForwardingNodes.end(); I != E; ++I) {
  2949. PHINode *Phi = I->first;
  2950. SmallVectorImpl<int> &Indexes = I->second;
  2951. if (Indexes.size() < 2) continue;
  2952. for (size_t I = 0, E = Indexes.size(); I != E; ++I)
  2953. Phi->setIncomingValue(Indexes[I], SI->getCondition());
  2954. Changed = true;
  2955. }
  2956. return Changed;
  2957. }
  2958. /// Return true if the backend will be able to handle
  2959. /// initializing an array of constants like C.
  2960. static bool ValidLookupTableConstant(Constant *C) {
  2961. if (C->isThreadDependent())
  2962. return false;
  2963. if (C->isDLLImportDependent())
  2964. return false;
  2965. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(C))
  2966. return CE->isGEPWithNoNotionalOverIndexing();
  2967. return isa<ConstantFP>(C) ||
  2968. isa<ConstantInt>(C) ||
  2969. isa<ConstantPointerNull>(C) ||
  2970. isa<GlobalValue>(C) ||
  2971. isa<UndefValue>(C);
  2972. }
  2973. /// If V is a Constant, return it. Otherwise, try to look up
  2974. /// its constant value in ConstantPool, returning 0 if it's not there.
  2975. static Constant *LookupConstant(Value *V,
  2976. const SmallDenseMap<Value*, Constant*>& ConstantPool) {
  2977. if (Constant *C = dyn_cast<Constant>(V))
  2978. return C;
  2979. return ConstantPool.lookup(V);
  2980. }
  2981. /// Try to fold instruction I into a constant. This works for
  2982. /// simple instructions such as binary operations where both operands are
  2983. /// constant or can be replaced by constants from the ConstantPool. Returns the
  2984. /// resulting constant on success, 0 otherwise.
  2985. static Constant *
  2986. ConstantFold(Instruction *I, const DataLayout &DL,
  2987. const SmallDenseMap<Value *, Constant *> &ConstantPool) {
  2988. if (SelectInst *Select = dyn_cast<SelectInst>(I)) {
  2989. Constant *A = LookupConstant(Select->getCondition(), ConstantPool);
  2990. if (!A)
  2991. return nullptr;
  2992. if (A->isAllOnesValue())
  2993. return LookupConstant(Select->getTrueValue(), ConstantPool);
  2994. if (A->isNullValue())
  2995. return LookupConstant(Select->getFalseValue(), ConstantPool);
  2996. return nullptr;
  2997. }
  2998. SmallVector<Constant *, 4> COps;
  2999. for (unsigned N = 0, E = I->getNumOperands(); N != E; ++N) {
  3000. if (Constant *A = LookupConstant(I->getOperand(N), ConstantPool))
  3001. COps.push_back(A);
  3002. else
  3003. return nullptr;
  3004. }
  3005. if (CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
  3006. return ConstantFoldCompareInstOperands(Cmp->getPredicate(), COps[0],
  3007. COps[1], DL);
  3008. }
  3009. return ConstantFoldInstOperands(I->getOpcode(), I->getType(), COps, DL);
  3010. }
  3011. /// Try to determine the resulting constant values in phi nodes
  3012. /// at the common destination basic block, *CommonDest, for one of the case
  3013. /// destionations CaseDest corresponding to value CaseVal (0 for the default
  3014. /// case), of a switch instruction SI.
  3015. static bool
  3016. GetCaseResults(SwitchInst *SI, ConstantInt *CaseVal, BasicBlock *CaseDest,
  3017. BasicBlock **CommonDest,
  3018. SmallVectorImpl<std::pair<PHINode *, Constant *>> &Res,
  3019. const DataLayout &DL) {
  3020. // The block from which we enter the common destination.
  3021. BasicBlock *Pred = SI->getParent();
  3022. // If CaseDest is empty except for some side-effect free instructions through
  3023. // which we can constant-propagate the CaseVal, continue to its successor.
  3024. SmallDenseMap<Value*, Constant*> ConstantPool;
  3025. ConstantPool.insert(std::make_pair(SI->getCondition(), CaseVal));
  3026. for (BasicBlock::iterator I = CaseDest->begin(), E = CaseDest->end(); I != E;
  3027. ++I) {
  3028. if (TerminatorInst *T = dyn_cast<TerminatorInst>(I)) {
  3029. // If the terminator is a simple branch, continue to the next block.
  3030. if (T->getNumSuccessors() != 1)
  3031. return false;
  3032. Pred = CaseDest;
  3033. CaseDest = T->getSuccessor(0);
  3034. } else if (isa<DbgInfoIntrinsic>(I)) {
  3035. // Skip debug intrinsic.
  3036. continue;
  3037. } else if (Constant *C = ConstantFold(I, DL, ConstantPool)) {
  3038. // Instruction is side-effect free and constant.
  3039. // If the instruction has uses outside this block or a phi node slot for
  3040. // the block, it is not safe to bypass the instruction since it would then
  3041. // no longer dominate all its uses.
  3042. for (auto &Use : I->uses()) {
  3043. User *User = Use.getUser();
  3044. if (Instruction *I = dyn_cast<Instruction>(User))
  3045. if (I->getParent() == CaseDest)
  3046. continue;
  3047. if (PHINode *Phi = dyn_cast<PHINode>(User))
  3048. if (Phi->getIncomingBlock(Use) == CaseDest)
  3049. continue;
  3050. return false;
  3051. }
  3052. ConstantPool.insert(std::make_pair(I, C));
  3053. } else {
  3054. break;
  3055. }
  3056. }
  3057. // If we did not have a CommonDest before, use the current one.
  3058. if (!*CommonDest)
  3059. *CommonDest = CaseDest;
  3060. // If the destination isn't the common one, abort.
  3061. if (CaseDest != *CommonDest)
  3062. return false;
  3063. // Get the values for this case from phi nodes in the destination block.
  3064. BasicBlock::iterator I = (*CommonDest)->begin();
  3065. while (PHINode *PHI = dyn_cast<PHINode>(I++)) {
  3066. int Idx = PHI->getBasicBlockIndex(Pred);
  3067. if (Idx == -1)
  3068. continue;
  3069. Constant *ConstVal = LookupConstant(PHI->getIncomingValue(Idx),
  3070. ConstantPool);
  3071. if (!ConstVal)
  3072. return false;
  3073. // Be conservative about which kinds of constants we support.
  3074. if (!ValidLookupTableConstant(ConstVal))
  3075. return false;
  3076. Res.push_back(std::make_pair(PHI, ConstVal));
  3077. }
  3078. return Res.size() > 0;
  3079. }
  3080. // Helper function used to add CaseVal to the list of cases that generate
  3081. // Result.
  3082. static void MapCaseToResult(ConstantInt *CaseVal,
  3083. SwitchCaseResultVectorTy &UniqueResults,
  3084. Constant *Result) {
  3085. for (auto &I : UniqueResults) {
  3086. if (I.first == Result) {
  3087. I.second.push_back(CaseVal);
  3088. return;
  3089. }
  3090. }
  3091. UniqueResults.push_back(std::make_pair(Result,
  3092. SmallVector<ConstantInt*, 4>(1, CaseVal)));
  3093. }
  3094. // Helper function that initializes a map containing
  3095. // results for the PHI node of the common destination block for a switch
  3096. // instruction. Returns false if multiple PHI nodes have been found or if
  3097. // there is not a common destination block for the switch.
  3098. static bool InitializeUniqueCases(SwitchInst *SI, PHINode *&PHI,
  3099. BasicBlock *&CommonDest,
  3100. SwitchCaseResultVectorTy &UniqueResults,
  3101. Constant *&DefaultResult,
  3102. const DataLayout &DL) {
  3103. for (auto &I : SI->cases()) {
  3104. ConstantInt *CaseVal = I.getCaseValue();
  3105. // Resulting value at phi nodes for this case value.
  3106. SwitchCaseResultsTy Results;
  3107. if (!GetCaseResults(SI, CaseVal, I.getCaseSuccessor(), &CommonDest, Results,
  3108. DL))
  3109. return false;
  3110. // Only one value per case is permitted
  3111. if (Results.size() > 1)
  3112. return false;
  3113. MapCaseToResult(CaseVal, UniqueResults, Results.begin()->second);
  3114. // Check the PHI consistency.
  3115. if (!PHI)
  3116. PHI = Results[0].first;
  3117. else if (PHI != Results[0].first)
  3118. return false;
  3119. }
  3120. // Find the default result value.
  3121. SmallVector<std::pair<PHINode *, Constant *>, 1> DefaultResults;
  3122. BasicBlock *DefaultDest = SI->getDefaultDest();
  3123. GetCaseResults(SI, nullptr, SI->getDefaultDest(), &CommonDest, DefaultResults,
  3124. DL);
  3125. // If the default value is not found abort unless the default destination
  3126. // is unreachable.
  3127. DefaultResult =
  3128. DefaultResults.size() == 1 ? DefaultResults.begin()->second : nullptr;
  3129. if ((!DefaultResult &&
  3130. !isa<UnreachableInst>(DefaultDest->getFirstNonPHIOrDbg())))
  3131. return false;
  3132. return true;
  3133. }
  3134. // Helper function that checks if it is possible to transform a switch with only
  3135. // two cases (or two cases + default) that produces a result into a select.
  3136. // Example:
  3137. // switch (a) {
  3138. // case 10: %0 = icmp eq i32 %a, 10
  3139. // return 10; %1 = select i1 %0, i32 10, i32 4
  3140. // case 20: ----> %2 = icmp eq i32 %a, 20
  3141. // return 2; %3 = select i1 %2, i32 2, i32 %1
  3142. // default:
  3143. // return 4;
  3144. // }
  3145. static Value *
  3146. ConvertTwoCaseSwitch(const SwitchCaseResultVectorTy &ResultVector,
  3147. Constant *DefaultResult, Value *Condition,
  3148. IRBuilder<> &Builder) {
  3149. assert(ResultVector.size() == 2 &&
  3150. "We should have exactly two unique results at this point");
  3151. // If we are selecting between only two cases transform into a simple
  3152. // select or a two-way select if default is possible.
  3153. if (ResultVector[0].second.size() == 1 &&
  3154. ResultVector[1].second.size() == 1) {
  3155. ConstantInt *const FirstCase = ResultVector[0].second[0];
  3156. ConstantInt *const SecondCase = ResultVector[1].second[0];
  3157. bool DefaultCanTrigger = DefaultResult;
  3158. Value *SelectValue = ResultVector[1].first;
  3159. if (DefaultCanTrigger) {
  3160. Value *const ValueCompare =
  3161. Builder.CreateICmpEQ(Condition, SecondCase, "switch.selectcmp");
  3162. SelectValue = Builder.CreateSelect(ValueCompare, ResultVector[1].first,
  3163. DefaultResult, "switch.select");
  3164. }
  3165. Value *const ValueCompare =
  3166. Builder.CreateICmpEQ(Condition, FirstCase, "switch.selectcmp");
  3167. return Builder.CreateSelect(ValueCompare, ResultVector[0].first, SelectValue,
  3168. "switch.select");
  3169. }
  3170. return nullptr;
  3171. }
  3172. // Helper function to cleanup a switch instruction that has been converted into
  3173. // a select, fixing up PHI nodes and basic blocks.
  3174. static void RemoveSwitchAfterSelectConversion(SwitchInst *SI, PHINode *PHI,
  3175. Value *SelectValue,
  3176. IRBuilder<> &Builder) {
  3177. BasicBlock *SelectBB = SI->getParent();
  3178. while (PHI->getBasicBlockIndex(SelectBB) >= 0)
  3179. PHI->removeIncomingValue(SelectBB);
  3180. PHI->addIncoming(SelectValue, SelectBB);
  3181. Builder.CreateBr(PHI->getParent());
  3182. // Remove the switch.
  3183. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  3184. BasicBlock *Succ = SI->getSuccessor(i);
  3185. if (Succ == PHI->getParent())
  3186. continue;
  3187. Succ->removePredecessor(SelectBB);
  3188. }
  3189. SI->eraseFromParent();
  3190. }
  3191. /// If the switch is only used to initialize one or more
  3192. /// phi nodes in a common successor block with only two different
  3193. /// constant values, replace the switch with select.
  3194. static bool SwitchToSelect(SwitchInst *SI, IRBuilder<> &Builder,
  3195. AssumptionCache *AC, const DataLayout &DL) {
  3196. Value *const Cond = SI->getCondition();
  3197. PHINode *PHI = nullptr;
  3198. BasicBlock *CommonDest = nullptr;
  3199. Constant *DefaultResult;
  3200. SwitchCaseResultVectorTy UniqueResults;
  3201. // Collect all the cases that will deliver the same value from the switch.
  3202. if (!InitializeUniqueCases(SI, PHI, CommonDest, UniqueResults, DefaultResult,
  3203. DL))
  3204. return false;
  3205. // Selects choose between maximum two values.
  3206. if (UniqueResults.size() != 2)
  3207. return false;
  3208. assert(PHI != nullptr && "PHI for value select not found");
  3209. Builder.SetInsertPoint(SI);
  3210. Value *SelectValue = ConvertTwoCaseSwitch(
  3211. UniqueResults,
  3212. DefaultResult, Cond, Builder);
  3213. if (SelectValue) {
  3214. RemoveSwitchAfterSelectConversion(SI, PHI, SelectValue, Builder);
  3215. return true;
  3216. }
  3217. // The switch couldn't be converted into a select.
  3218. return false;
  3219. }
  3220. namespace {
  3221. /// This class represents a lookup table that can be used to replace a switch.
  3222. class SwitchLookupTable {
  3223. public:
  3224. /// Create a lookup table to use as a switch replacement with the contents
  3225. /// of Values, using DefaultValue to fill any holes in the table.
  3226. SwitchLookupTable(
  3227. Module &M, uint64_t TableSize, ConstantInt *Offset,
  3228. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  3229. Constant *DefaultValue, const DataLayout &DL);
  3230. /// Build instructions with Builder to retrieve the value at
  3231. /// the position given by Index in the lookup table.
  3232. Value *BuildLookup(Value *Index, IRBuilder<> &Builder);
  3233. /// Return true if a table with TableSize elements of
  3234. /// type ElementType would fit in a target-legal register.
  3235. static bool WouldFitInRegister(const DataLayout &DL, uint64_t TableSize,
  3236. const Type *ElementType);
  3237. private:
  3238. // Depending on the contents of the table, it can be represented in
  3239. // different ways.
  3240. enum {
  3241. // For tables where each element contains the same value, we just have to
  3242. // store that single value and return it for each lookup.
  3243. SingleValueKind,
  3244. // For tables where there is a linear relationship between table index
  3245. // and values. We calculate the result with a simple multiplication
  3246. // and addition instead of a table lookup.
  3247. LinearMapKind,
  3248. // For small tables with integer elements, we can pack them into a bitmap
  3249. // that fits into a target-legal register. Values are retrieved by
  3250. // shift and mask operations.
  3251. BitMapKind,
  3252. // The table is stored as an array of values. Values are retrieved by load
  3253. // instructions from the table.
  3254. ArrayKind
  3255. } Kind;
  3256. // For SingleValueKind, this is the single value.
  3257. Constant *SingleValue;
  3258. // For BitMapKind, this is the bitmap.
  3259. ConstantInt *BitMap;
  3260. IntegerType *BitMapElementTy;
  3261. // For LinearMapKind, these are the constants used to derive the value.
  3262. ConstantInt *LinearOffset;
  3263. ConstantInt *LinearMultiplier;
  3264. // For ArrayKind, this is the array.
  3265. GlobalVariable *Array;
  3266. };
  3267. }
  3268. SwitchLookupTable::SwitchLookupTable(
  3269. Module &M, uint64_t TableSize, ConstantInt *Offset,
  3270. const SmallVectorImpl<std::pair<ConstantInt *, Constant *>> &Values,
  3271. Constant *DefaultValue, const DataLayout &DL)
  3272. : SingleValue(nullptr), BitMap(nullptr), BitMapElementTy(nullptr),
  3273. LinearOffset(nullptr), LinearMultiplier(nullptr), Array(nullptr) {
  3274. assert(Values.size() && "Can't build lookup table without values!");
  3275. assert(TableSize >= Values.size() && "Can't fit values in table!");
  3276. // If all values in the table are equal, this is that value.
  3277. SingleValue = Values.begin()->second;
  3278. Type *ValueType = Values.begin()->second->getType();
  3279. // Build up the table contents.
  3280. SmallVector<Constant*, 64> TableContents(TableSize);
  3281. for (size_t I = 0, E = Values.size(); I != E; ++I) {
  3282. ConstantInt *CaseVal = Values[I].first;
  3283. Constant *CaseRes = Values[I].second;
  3284. assert(CaseRes->getType() == ValueType);
  3285. uint64_t Idx = (CaseVal->getValue() - Offset->getValue())
  3286. .getLimitedValue();
  3287. TableContents[Idx] = CaseRes;
  3288. if (CaseRes != SingleValue)
  3289. SingleValue = nullptr;
  3290. }
  3291. // Fill in any holes in the table with the default result.
  3292. if (Values.size() < TableSize) {
  3293. assert(DefaultValue &&
  3294. "Need a default value to fill the lookup table holes.");
  3295. assert(DefaultValue->getType() == ValueType);
  3296. for (uint64_t I = 0; I < TableSize; ++I) {
  3297. if (!TableContents[I])
  3298. TableContents[I] = DefaultValue;
  3299. }
  3300. if (DefaultValue != SingleValue)
  3301. SingleValue = nullptr;
  3302. }
  3303. // If each element in the table contains the same value, we only need to store
  3304. // that single value.
  3305. if (SingleValue) {
  3306. Kind = SingleValueKind;
  3307. return;
  3308. }
  3309. // Check if we can derive the value with a linear transformation from the
  3310. // table index.
  3311. if (isa<IntegerType>(ValueType)) {
  3312. bool LinearMappingPossible = true;
  3313. APInt PrevVal;
  3314. APInt DistToPrev;
  3315. assert(TableSize >= 2 && "Should be a SingleValue table.");
  3316. // Check if there is the same distance between two consecutive values.
  3317. for (uint64_t I = 0; I < TableSize; ++I) {
  3318. ConstantInt *ConstVal = dyn_cast<ConstantInt>(TableContents[I]);
  3319. if (!ConstVal) {
  3320. // This is an undef. We could deal with it, but undefs in lookup tables
  3321. // are very seldom. It's probably not worth the additional complexity.
  3322. LinearMappingPossible = false;
  3323. break;
  3324. }
  3325. APInt Val = ConstVal->getValue();
  3326. if (I != 0) {
  3327. APInt Dist = Val - PrevVal;
  3328. if (I == 1) {
  3329. DistToPrev = Dist;
  3330. } else if (Dist != DistToPrev) {
  3331. LinearMappingPossible = false;
  3332. break;
  3333. }
  3334. }
  3335. PrevVal = Val;
  3336. }
  3337. if (LinearMappingPossible) {
  3338. LinearOffset = cast<ConstantInt>(TableContents[0]);
  3339. LinearMultiplier = ConstantInt::get(M.getContext(), DistToPrev);
  3340. Kind = LinearMapKind;
  3341. ++NumLinearMaps;
  3342. return;
  3343. }
  3344. }
  3345. // If the type is integer and the table fits in a register, build a bitmap.
  3346. if (WouldFitInRegister(DL, TableSize, ValueType)) {
  3347. IntegerType *IT = cast<IntegerType>(ValueType);
  3348. APInt TableInt(TableSize * IT->getBitWidth(), 0);
  3349. for (uint64_t I = TableSize; I > 0; --I) {
  3350. TableInt <<= IT->getBitWidth();
  3351. // Insert values into the bitmap. Undef values are set to zero.
  3352. if (!isa<UndefValue>(TableContents[I - 1])) {
  3353. ConstantInt *Val = cast<ConstantInt>(TableContents[I - 1]);
  3354. TableInt |= Val->getValue().zext(TableInt.getBitWidth());
  3355. }
  3356. }
  3357. BitMap = ConstantInt::get(M.getContext(), TableInt);
  3358. BitMapElementTy = IT;
  3359. Kind = BitMapKind;
  3360. ++NumBitMaps;
  3361. return;
  3362. }
  3363. // Store the table in an array.
  3364. ArrayType *ArrayTy = ArrayType::get(ValueType, TableSize);
  3365. Constant *Initializer = ConstantArray::get(ArrayTy, TableContents);
  3366. Array = new GlobalVariable(M, ArrayTy, /*constant=*/ true,
  3367. GlobalVariable::PrivateLinkage,
  3368. Initializer,
  3369. "switch.table");
  3370. Array->setUnnamedAddr(true);
  3371. Kind = ArrayKind;
  3372. }
  3373. Value *SwitchLookupTable::BuildLookup(Value *Index, IRBuilder<> &Builder) {
  3374. switch (Kind) {
  3375. case SingleValueKind:
  3376. return SingleValue;
  3377. case LinearMapKind: {
  3378. // Derive the result value from the input value.
  3379. Value *Result = Builder.CreateIntCast(Index, LinearMultiplier->getType(),
  3380. false, "switch.idx.cast");
  3381. if (!LinearMultiplier->isOne())
  3382. Result = Builder.CreateMul(Result, LinearMultiplier, "switch.idx.mult");
  3383. if (!LinearOffset->isZero())
  3384. Result = Builder.CreateAdd(Result, LinearOffset, "switch.offset");
  3385. return Result;
  3386. }
  3387. case BitMapKind: {
  3388. // Type of the bitmap (e.g. i59).
  3389. IntegerType *MapTy = BitMap->getType();
  3390. // Cast Index to the same type as the bitmap.
  3391. // Note: The Index is <= the number of elements in the table, so
  3392. // truncating it to the width of the bitmask is safe.
  3393. Value *ShiftAmt = Builder.CreateZExtOrTrunc(Index, MapTy, "switch.cast");
  3394. // Multiply the shift amount by the element width.
  3395. ShiftAmt = Builder.CreateMul(ShiftAmt,
  3396. ConstantInt::get(MapTy, BitMapElementTy->getBitWidth()),
  3397. "switch.shiftamt");
  3398. // Shift down.
  3399. Value *DownShifted = Builder.CreateLShr(BitMap, ShiftAmt,
  3400. "switch.downshift");
  3401. // Mask off.
  3402. return Builder.CreateTrunc(DownShifted, BitMapElementTy,
  3403. "switch.masked");
  3404. }
  3405. case ArrayKind: {
  3406. // Make sure the table index will not overflow when treated as signed.
  3407. IntegerType *IT = cast<IntegerType>(Index->getType());
  3408. uint64_t TableSize = Array->getInitializer()->getType()
  3409. ->getArrayNumElements();
  3410. if (TableSize > (1ULL << (IT->getBitWidth() - 1)))
  3411. Index = Builder.CreateZExt(Index,
  3412. IntegerType::get(IT->getContext(),
  3413. IT->getBitWidth() + 1),
  3414. "switch.tableidx.zext");
  3415. Value *GEPIndices[] = { Builder.getInt32(0), Index };
  3416. Value *GEP = Builder.CreateInBoundsGEP(Array->getValueType(), Array,
  3417. GEPIndices, "switch.gep");
  3418. return Builder.CreateLoad(GEP, "switch.load");
  3419. }
  3420. }
  3421. llvm_unreachable("Unknown lookup table kind!");
  3422. }
  3423. bool SwitchLookupTable::WouldFitInRegister(const DataLayout &DL,
  3424. uint64_t TableSize,
  3425. const Type *ElementType) {
  3426. const IntegerType *IT = dyn_cast<IntegerType>(ElementType);
  3427. if (!IT)
  3428. return false;
  3429. // FIXME: If the type is wider than it needs to be, e.g. i8 but all values
  3430. // are <= 15, we could try to narrow the type.
  3431. // Avoid overflow, fitsInLegalInteger uses unsigned int for the width.
  3432. if (TableSize >= UINT_MAX/IT->getBitWidth())
  3433. return false;
  3434. return DL.fitsInLegalInteger(TableSize * IT->getBitWidth());
  3435. }
  3436. /// Determine whether a lookup table should be built for this switch, based on
  3437. /// the number of cases, size of the table, and the types of the results.
  3438. static bool
  3439. ShouldBuildLookupTable(SwitchInst *SI, uint64_t TableSize,
  3440. const TargetTransformInfo &TTI, const DataLayout &DL,
  3441. const SmallDenseMap<PHINode *, Type *> &ResultTypes) {
  3442. if (SI->getNumCases() > TableSize || TableSize >= UINT64_MAX / 10)
  3443. return false; // TableSize overflowed, or mul below might overflow.
  3444. bool AllTablesFitInRegister = true;
  3445. bool HasIllegalType = false;
  3446. for (const auto &I : ResultTypes) {
  3447. Type *Ty = I.second;
  3448. // Saturate this flag to true.
  3449. HasIllegalType = HasIllegalType || !TTI.isTypeLegal(Ty);
  3450. // Saturate this flag to false.
  3451. AllTablesFitInRegister = AllTablesFitInRegister &&
  3452. SwitchLookupTable::WouldFitInRegister(DL, TableSize, Ty);
  3453. // If both flags saturate, we're done. NOTE: This *only* works with
  3454. // saturating flags, and all flags have to saturate first due to the
  3455. // non-deterministic behavior of iterating over a dense map.
  3456. if (HasIllegalType && !AllTablesFitInRegister)
  3457. break;
  3458. }
  3459. // If each table would fit in a register, we should build it anyway.
  3460. if (AllTablesFitInRegister)
  3461. return true;
  3462. // Don't build a table that doesn't fit in-register if it has illegal types.
  3463. if (HasIllegalType)
  3464. return false;
  3465. // The table density should be at least 40%. This is the same criterion as for
  3466. // jump tables, see SelectionDAGBuilder::handleJTSwitchCase.
  3467. // FIXME: Find the best cut-off.
  3468. return SI->getNumCases() * 10 >= TableSize * 4;
  3469. }
  3470. /// Try to reuse the switch table index compare. Following pattern:
  3471. /// \code
  3472. /// if (idx < tablesize)
  3473. /// r = table[idx]; // table does not contain default_value
  3474. /// else
  3475. /// r = default_value;
  3476. /// if (r != default_value)
  3477. /// ...
  3478. /// \endcode
  3479. /// Is optimized to:
  3480. /// \code
  3481. /// cond = idx < tablesize;
  3482. /// if (cond)
  3483. /// r = table[idx];
  3484. /// else
  3485. /// r = default_value;
  3486. /// if (cond)
  3487. /// ...
  3488. /// \endcode
  3489. /// Jump threading will then eliminate the second if(cond).
  3490. static void reuseTableCompare(User *PhiUser, BasicBlock *PhiBlock,
  3491. BranchInst *RangeCheckBranch, Constant *DefaultValue,
  3492. const SmallVectorImpl<std::pair<ConstantInt*, Constant*> >& Values) {
  3493. ICmpInst *CmpInst = dyn_cast<ICmpInst>(PhiUser);
  3494. if (!CmpInst)
  3495. return;
  3496. // We require that the compare is in the same block as the phi so that jump
  3497. // threading can do its work afterwards.
  3498. if (CmpInst->getParent() != PhiBlock)
  3499. return;
  3500. Constant *CmpOp1 = dyn_cast<Constant>(CmpInst->getOperand(1));
  3501. if (!CmpOp1)
  3502. return;
  3503. Value *RangeCmp = RangeCheckBranch->getCondition();
  3504. Constant *TrueConst = ConstantInt::getTrue(RangeCmp->getType());
  3505. Constant *FalseConst = ConstantInt::getFalse(RangeCmp->getType());
  3506. // Check if the compare with the default value is constant true or false.
  3507. Constant *DefaultConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  3508. DefaultValue, CmpOp1, true);
  3509. if (DefaultConst != TrueConst && DefaultConst != FalseConst)
  3510. return;
  3511. // Check if the compare with the case values is distinct from the default
  3512. // compare result.
  3513. for (auto ValuePair : Values) {
  3514. Constant *CaseConst = ConstantExpr::getICmp(CmpInst->getPredicate(),
  3515. ValuePair.second, CmpOp1, true);
  3516. if (!CaseConst || CaseConst == DefaultConst)
  3517. return;
  3518. assert((CaseConst == TrueConst || CaseConst == FalseConst) &&
  3519. "Expect true or false as compare result.");
  3520. }
  3521. // Check if the branch instruction dominates the phi node. It's a simple
  3522. // dominance check, but sufficient for our needs.
  3523. // Although this check is invariant in the calling loops, it's better to do it
  3524. // at this late stage. Practically we do it at most once for a switch.
  3525. BasicBlock *BranchBlock = RangeCheckBranch->getParent();
  3526. for (auto PI = pred_begin(PhiBlock), E = pred_end(PhiBlock); PI != E; ++PI) {
  3527. BasicBlock *Pred = *PI;
  3528. if (Pred != BranchBlock && Pred->getUniquePredecessor() != BranchBlock)
  3529. return;
  3530. }
  3531. if (DefaultConst == FalseConst) {
  3532. // The compare yields the same result. We can replace it.
  3533. CmpInst->replaceAllUsesWith(RangeCmp);
  3534. ++NumTableCmpReuses;
  3535. } else {
  3536. // The compare yields the same result, just inverted. We can replace it.
  3537. Value *InvertedTableCmp = BinaryOperator::CreateXor(RangeCmp,
  3538. ConstantInt::get(RangeCmp->getType(), 1), "inverted.cmp",
  3539. RangeCheckBranch);
  3540. CmpInst->replaceAllUsesWith(InvertedTableCmp);
  3541. ++NumTableCmpReuses;
  3542. }
  3543. }
  3544. /// If the switch is only used to initialize one or more phi nodes in a common
  3545. /// successor block with different constant values, replace the switch with
  3546. /// lookup tables.
  3547. static bool SwitchToLookupTable(SwitchInst *SI, IRBuilder<> &Builder,
  3548. const DataLayout &DL,
  3549. const TargetTransformInfo &TTI) {
  3550. assert(SI->getNumCases() > 1 && "Degenerate switch?");
  3551. // Only build lookup table when we have a target that supports it.
  3552. if (!TTI.shouldBuildLookupTables())
  3553. return false;
  3554. // FIXME: If the switch is too sparse for a lookup table, perhaps we could
  3555. // split off a dense part and build a lookup table for that.
  3556. // FIXME: This creates arrays of GEPs to constant strings, which means each
  3557. // GEP needs a runtime relocation in PIC code. We should just build one big
  3558. // string and lookup indices into that.
  3559. // Ignore switches with less than three cases. Lookup tables will not make them
  3560. // faster, so we don't analyze them.
  3561. if (SI->getNumCases() < 3)
  3562. return false;
  3563. // Figure out the corresponding result for each case value and phi node in the
  3564. // common destination, as well as the min and max case values.
  3565. assert(SI->case_begin() != SI->case_end());
  3566. SwitchInst::CaseIt CI = SI->case_begin();
  3567. ConstantInt *MinCaseVal = CI.getCaseValue();
  3568. ConstantInt *MaxCaseVal = CI.getCaseValue();
  3569. BasicBlock *CommonDest = nullptr;
  3570. typedef SmallVector<std::pair<ConstantInt*, Constant*>, 4> ResultListTy;
  3571. SmallDenseMap<PHINode*, ResultListTy> ResultLists;
  3572. SmallDenseMap<PHINode*, Constant*> DefaultResults;
  3573. SmallDenseMap<PHINode*, Type*> ResultTypes;
  3574. SmallVector<PHINode*, 4> PHIs;
  3575. for (SwitchInst::CaseIt E = SI->case_end(); CI != E; ++CI) {
  3576. ConstantInt *CaseVal = CI.getCaseValue();
  3577. if (CaseVal->getValue().slt(MinCaseVal->getValue()))
  3578. MinCaseVal = CaseVal;
  3579. if (CaseVal->getValue().sgt(MaxCaseVal->getValue()))
  3580. MaxCaseVal = CaseVal;
  3581. // Resulting value at phi nodes for this case value.
  3582. typedef SmallVector<std::pair<PHINode*, Constant*>, 4> ResultsTy;
  3583. ResultsTy Results;
  3584. if (!GetCaseResults(SI, CaseVal, CI.getCaseSuccessor(), &CommonDest,
  3585. Results, DL))
  3586. return false;
  3587. // Append the result from this case to the list for each phi.
  3588. for (const auto &I : Results) {
  3589. PHINode *PHI = I.first;
  3590. Constant *Value = I.second;
  3591. if (!ResultLists.count(PHI))
  3592. PHIs.push_back(PHI);
  3593. ResultLists[PHI].push_back(std::make_pair(CaseVal, Value));
  3594. }
  3595. }
  3596. // Keep track of the result types.
  3597. for (PHINode *PHI : PHIs) {
  3598. ResultTypes[PHI] = ResultLists[PHI][0].second->getType();
  3599. }
  3600. uint64_t NumResults = ResultLists[PHIs[0]].size();
  3601. APInt RangeSpread = MaxCaseVal->getValue() - MinCaseVal->getValue();
  3602. uint64_t TableSize = RangeSpread.getLimitedValue() + 1;
  3603. bool TableHasHoles = (NumResults < TableSize);
  3604. // If the table has holes, we need a constant result for the default case
  3605. // or a bitmask that fits in a register.
  3606. SmallVector<std::pair<PHINode*, Constant*>, 4> DefaultResultsList;
  3607. bool HasDefaultResults = GetCaseResults(SI, nullptr, SI->getDefaultDest(),
  3608. &CommonDest, DefaultResultsList, DL);
  3609. bool NeedMask = (TableHasHoles && !HasDefaultResults);
  3610. if (NeedMask) {
  3611. // As an extra penalty for the validity test we require more cases.
  3612. if (SI->getNumCases() < 4) // FIXME: Find best threshold value (benchmark).
  3613. return false;
  3614. if (!DL.fitsInLegalInteger(TableSize))
  3615. return false;
  3616. }
  3617. for (const auto &I : DefaultResultsList) {
  3618. PHINode *PHI = I.first;
  3619. Constant *Result = I.second;
  3620. DefaultResults[PHI] = Result;
  3621. }
  3622. if (!ShouldBuildLookupTable(SI, TableSize, TTI, DL, ResultTypes))
  3623. return false;
  3624. // Create the BB that does the lookups.
  3625. Module &Mod = *CommonDest->getParent()->getParent();
  3626. BasicBlock *LookupBB = BasicBlock::Create(Mod.getContext(),
  3627. "switch.lookup",
  3628. CommonDest->getParent(),
  3629. CommonDest);
  3630. // Compute the table index value.
  3631. Builder.SetInsertPoint(SI);
  3632. Value *TableIndex = Builder.CreateSub(SI->getCondition(), MinCaseVal,
  3633. "switch.tableidx");
  3634. // Compute the maximum table size representable by the integer type we are
  3635. // switching upon.
  3636. unsigned CaseSize = MinCaseVal->getType()->getPrimitiveSizeInBits();
  3637. uint64_t MaxTableSize = CaseSize > 63 ? UINT64_MAX : 1ULL << CaseSize;
  3638. assert(MaxTableSize >= TableSize &&
  3639. "It is impossible for a switch to have more entries than the max "
  3640. "representable value of its input integer type's size.");
  3641. // If the default destination is unreachable, or if the lookup table covers
  3642. // all values of the conditional variable, branch directly to the lookup table
  3643. // BB. Otherwise, check that the condition is within the case range.
  3644. const bool DefaultIsReachable =
  3645. !isa<UnreachableInst>(SI->getDefaultDest()->getFirstNonPHIOrDbg());
  3646. const bool GeneratingCoveredLookupTable = (MaxTableSize == TableSize);
  3647. BranchInst *RangeCheckBranch = nullptr;
  3648. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  3649. Builder.CreateBr(LookupBB);
  3650. // Note: We call removeProdecessor later since we need to be able to get the
  3651. // PHI value for the default case in case we're using a bit mask.
  3652. } else {
  3653. Value *Cmp = Builder.CreateICmpULT(TableIndex, ConstantInt::get(
  3654. MinCaseVal->getType(), TableSize));
  3655. RangeCheckBranch = Builder.CreateCondBr(Cmp, LookupBB, SI->getDefaultDest());
  3656. }
  3657. // Populate the BB that does the lookups.
  3658. Builder.SetInsertPoint(LookupBB);
  3659. if (NeedMask) {
  3660. // Before doing the lookup we do the hole check.
  3661. // The LookupBB is therefore re-purposed to do the hole check
  3662. // and we create a new LookupBB.
  3663. BasicBlock *MaskBB = LookupBB;
  3664. MaskBB->setName("switch.hole_check");
  3665. LookupBB = BasicBlock::Create(Mod.getContext(),
  3666. "switch.lookup",
  3667. CommonDest->getParent(),
  3668. CommonDest);
  3669. // Make the mask's bitwidth at least 8bit and a power-of-2 to avoid
  3670. // unnecessary illegal types.
  3671. uint64_t TableSizePowOf2 = NextPowerOf2(std::max(7ULL, TableSize - 1ULL));
  3672. APInt MaskInt(TableSizePowOf2, 0);
  3673. APInt One(TableSizePowOf2, 1);
  3674. // Build bitmask; fill in a 1 bit for every case.
  3675. const ResultListTy &ResultList = ResultLists[PHIs[0]];
  3676. for (size_t I = 0, E = ResultList.size(); I != E; ++I) {
  3677. uint64_t Idx = (ResultList[I].first->getValue() -
  3678. MinCaseVal->getValue()).getLimitedValue();
  3679. MaskInt |= One << Idx;
  3680. }
  3681. ConstantInt *TableMask = ConstantInt::get(Mod.getContext(), MaskInt);
  3682. // Get the TableIndex'th bit of the bitmask.
  3683. // If this bit is 0 (meaning hole) jump to the default destination,
  3684. // else continue with table lookup.
  3685. IntegerType *MapTy = TableMask->getType();
  3686. Value *MaskIndex = Builder.CreateZExtOrTrunc(TableIndex, MapTy,
  3687. "switch.maskindex");
  3688. Value *Shifted = Builder.CreateLShr(TableMask, MaskIndex,
  3689. "switch.shifted");
  3690. Value *LoBit = Builder.CreateTrunc(Shifted,
  3691. Type::getInt1Ty(Mod.getContext()),
  3692. "switch.lobit");
  3693. Builder.CreateCondBr(LoBit, LookupBB, SI->getDefaultDest());
  3694. Builder.SetInsertPoint(LookupBB);
  3695. AddPredecessorToBlock(SI->getDefaultDest(), MaskBB, SI->getParent());
  3696. }
  3697. if (!DefaultIsReachable || GeneratingCoveredLookupTable) {
  3698. // We cached PHINodes in PHIs, to avoid accessing deleted PHINodes later,
  3699. // do not delete PHINodes here.
  3700. SI->getDefaultDest()->removePredecessor(SI->getParent(),
  3701. /*DontDeleteUselessPHIs=*/true);
  3702. }
  3703. bool ReturnedEarly = false;
  3704. for (size_t I = 0, E = PHIs.size(); I != E; ++I) {
  3705. PHINode *PHI = PHIs[I];
  3706. const ResultListTy &ResultList = ResultLists[PHI];
  3707. // If using a bitmask, use any value to fill the lookup table holes.
  3708. Constant *DV = NeedMask ? ResultLists[PHI][0].second : DefaultResults[PHI];
  3709. SwitchLookupTable Table(Mod, TableSize, MinCaseVal, ResultList, DV, DL);
  3710. Value *Result = Table.BuildLookup(TableIndex, Builder);
  3711. // If the result is used to return immediately from the function, we want to
  3712. // do that right here.
  3713. if (PHI->hasOneUse() && isa<ReturnInst>(*PHI->user_begin()) &&
  3714. PHI->user_back() == CommonDest->getFirstNonPHIOrDbg()) {
  3715. Builder.CreateRet(Result);
  3716. ReturnedEarly = true;
  3717. break;
  3718. }
  3719. // Do a small peephole optimization: re-use the switch table compare if
  3720. // possible.
  3721. if (!TableHasHoles && HasDefaultResults && RangeCheckBranch) {
  3722. BasicBlock *PhiBlock = PHI->getParent();
  3723. // Search for compare instructions which use the phi.
  3724. for (auto *User : PHI->users()) {
  3725. reuseTableCompare(User, PhiBlock, RangeCheckBranch, DV, ResultList);
  3726. }
  3727. }
  3728. PHI->addIncoming(Result, LookupBB);
  3729. }
  3730. if (!ReturnedEarly)
  3731. Builder.CreateBr(CommonDest);
  3732. // Remove the switch.
  3733. for (unsigned i = 0, e = SI->getNumSuccessors(); i < e; ++i) {
  3734. BasicBlock *Succ = SI->getSuccessor(i);
  3735. if (Succ == SI->getDefaultDest())
  3736. continue;
  3737. Succ->removePredecessor(SI->getParent());
  3738. }
  3739. SI->eraseFromParent();
  3740. ++NumLookupTables;
  3741. if (NeedMask)
  3742. ++NumLookupTablesHoles;
  3743. return true;
  3744. }
  3745. bool SimplifyCFGOpt::SimplifySwitch(SwitchInst *SI, IRBuilder<> &Builder) {
  3746. BasicBlock *BB = SI->getParent();
  3747. if (isValueEqualityComparison(SI)) {
  3748. // If we only have one predecessor, and if it is a branch on this value,
  3749. // see if that predecessor totally determines the outcome of this switch.
  3750. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  3751. if (SimplifyEqualityComparisonWithOnlyPredecessor(SI, OnlyPred, Builder))
  3752. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3753. Value *Cond = SI->getCondition();
  3754. if (SelectInst *Select = dyn_cast<SelectInst>(Cond))
  3755. if (SimplifySwitchOnSelect(SI, Select))
  3756. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3757. // If the block only contains the switch, see if we can fold the block
  3758. // away into any preds.
  3759. BasicBlock::iterator BBI = BB->begin();
  3760. // Ignore dbg intrinsics.
  3761. while (isa<DbgInfoIntrinsic>(BBI))
  3762. ++BBI;
  3763. if (SI == &*BBI)
  3764. if (FoldValueComparisonIntoPredecessors(SI, Builder))
  3765. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3766. }
  3767. // Try to transform the switch into an icmp and a branch.
  3768. if (TurnSwitchRangeIntoICmp(SI, Builder))
  3769. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3770. // Remove unreachable cases.
  3771. if (EliminateDeadSwitchCases(SI, AC, DL))
  3772. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3773. if (SwitchToSelect(SI, Builder, AC, DL))
  3774. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3775. if (ForwardSwitchConditionToPHI(SI))
  3776. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3777. if (SwitchToLookupTable(SI, Builder, DL, TTI))
  3778. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3779. return false;
  3780. }
  3781. bool SimplifyCFGOpt::SimplifyIndirectBr(IndirectBrInst *IBI) {
  3782. BasicBlock *BB = IBI->getParent();
  3783. bool Changed = false;
  3784. // Eliminate redundant destinations.
  3785. SmallPtrSet<Value *, 8> Succs;
  3786. for (unsigned i = 0, e = IBI->getNumDestinations(); i != e; ++i) {
  3787. BasicBlock *Dest = IBI->getDestination(i);
  3788. if (!Dest->hasAddressTaken() || !Succs.insert(Dest).second) {
  3789. Dest->removePredecessor(BB);
  3790. IBI->removeDestination(i);
  3791. --i; --e;
  3792. Changed = true;
  3793. }
  3794. }
  3795. if (IBI->getNumDestinations() == 0) {
  3796. // If the indirectbr has no successors, change it to unreachable.
  3797. new UnreachableInst(IBI->getContext(), IBI);
  3798. EraseTerminatorInstAndDCECond(IBI);
  3799. return true;
  3800. }
  3801. if (IBI->getNumDestinations() == 1) {
  3802. // If the indirectbr has one successor, change it to a direct branch.
  3803. BranchInst::Create(IBI->getDestination(0), IBI);
  3804. EraseTerminatorInstAndDCECond(IBI);
  3805. return true;
  3806. }
  3807. if (SelectInst *SI = dyn_cast<SelectInst>(IBI->getAddress())) {
  3808. if (SimplifyIndirectBrOnSelect(IBI, SI))
  3809. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3810. }
  3811. return Changed;
  3812. }
  3813. /// Given an block with only a single landing pad and a unconditional branch
  3814. /// try to find another basic block which this one can be merged with. This
  3815. /// handles cases where we have multiple invokes with unique landing pads, but
  3816. /// a shared handler.
  3817. ///
  3818. /// We specifically choose to not worry about merging non-empty blocks
  3819. /// here. That is a PRE/scheduling problem and is best solved elsewhere. In
  3820. /// practice, the optimizer produces empty landing pad blocks quite frequently
  3821. /// when dealing with exception dense code. (see: instcombine, gvn, if-else
  3822. /// sinking in this file)
  3823. ///
  3824. /// This is primarily a code size optimization. We need to avoid performing
  3825. /// any transform which might inhibit optimization (such as our ability to
  3826. /// specialize a particular handler via tail commoning). We do this by not
  3827. /// merging any blocks which require us to introduce a phi. Since the same
  3828. /// values are flowing through both blocks, we don't loose any ability to
  3829. /// specialize. If anything, we make such specialization more likely.
  3830. ///
  3831. /// TODO - This transformation could remove entries from a phi in the target
  3832. /// block when the inputs in the phi are the same for the two blocks being
  3833. /// merged. In some cases, this could result in removal of the PHI entirely.
  3834. static bool TryToMergeLandingPad(LandingPadInst *LPad, BranchInst *BI,
  3835. BasicBlock *BB) {
  3836. auto Succ = BB->getUniqueSuccessor();
  3837. assert(Succ);
  3838. // If there's a phi in the successor block, we'd likely have to introduce
  3839. // a phi into the merged landing pad block.
  3840. if (isa<PHINode>(*Succ->begin()))
  3841. return false;
  3842. for (BasicBlock *OtherPred : predecessors(Succ)) {
  3843. if (BB == OtherPred)
  3844. continue;
  3845. BasicBlock::iterator I = OtherPred->begin();
  3846. LandingPadInst *LPad2 = dyn_cast<LandingPadInst>(I);
  3847. if (!LPad2 || !LPad2->isIdenticalTo(LPad))
  3848. continue;
  3849. for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
  3850. BranchInst *BI2 = dyn_cast<BranchInst>(I);
  3851. if (!BI2 || !BI2->isIdenticalTo(BI))
  3852. continue;
  3853. // We've found an identical block. Update our predeccessors to take that
  3854. // path instead and make ourselves dead.
  3855. SmallSet<BasicBlock *, 16> Preds;
  3856. Preds.insert(pred_begin(BB), pred_end(BB));
  3857. for (BasicBlock *Pred : Preds) {
  3858. InvokeInst *II = cast<InvokeInst>(Pred->getTerminator());
  3859. assert(II->getNormalDest() != BB &&
  3860. II->getUnwindDest() == BB && "unexpected successor");
  3861. II->setUnwindDest(OtherPred);
  3862. }
  3863. // The debug info in OtherPred doesn't cover the merged control flow that
  3864. // used to go through BB. We need to delete it or update it.
  3865. for (auto I = OtherPred->begin(), E = OtherPred->end();
  3866. I != E;) {
  3867. Instruction &Inst = *I; I++;
  3868. if (isa<DbgInfoIntrinsic>(Inst))
  3869. Inst.eraseFromParent();
  3870. }
  3871. SmallSet<BasicBlock *, 16> Succs;
  3872. Succs.insert(succ_begin(BB), succ_end(BB));
  3873. for (BasicBlock *Succ : Succs) {
  3874. Succ->removePredecessor(BB);
  3875. }
  3876. IRBuilder<> Builder(BI);
  3877. Builder.CreateUnreachable();
  3878. BI->eraseFromParent();
  3879. return true;
  3880. }
  3881. return false;
  3882. }
  3883. bool SimplifyCFGOpt::SimplifyUncondBranch(BranchInst *BI, IRBuilder<> &Builder){
  3884. BasicBlock *BB = BI->getParent();
  3885. if (SinkCommon && SinkThenElseCodeToEnd(BI))
  3886. return true;
  3887. // If the Terminator is the only non-phi instruction, simplify the block.
  3888. BasicBlock::iterator I = BB->getFirstNonPHIOrDbg();
  3889. if (I->isTerminator() && BB != &BB->getParent()->getEntryBlock() &&
  3890. TryToSimplifyUncondBranchFromEmptyBlock(BB))
  3891. return true;
  3892. // If the only instruction in the block is a seteq/setne comparison
  3893. // against a constant, try to simplify the block.
  3894. if (ICmpInst *ICI = dyn_cast<ICmpInst>(I))
  3895. if (ICI->isEquality() && isa<ConstantInt>(ICI->getOperand(1))) {
  3896. for (++I; isa<DbgInfoIntrinsic>(I); ++I)
  3897. ;
  3898. if (I->isTerminator() &&
  3899. TryToSimplifyUncondBranchWithICmpInIt(ICI, Builder, DL, TTI,
  3900. BonusInstThreshold, AC))
  3901. return true;
  3902. }
  3903. // See if we can merge an empty landing pad block with another which is
  3904. // equivalent.
  3905. if (LandingPadInst *LPad = dyn_cast<LandingPadInst>(I)) {
  3906. for (++I; isa<DbgInfoIntrinsic>(I); ++I) {}
  3907. if (I->isTerminator() &&
  3908. TryToMergeLandingPad(LPad, BI, BB))
  3909. return true;
  3910. }
  3911. // If this basic block is ONLY a compare and a branch, and if a predecessor
  3912. // branches to us and our successor, fold the comparison into the
  3913. // predecessor and use logical operations to update the incoming value
  3914. // for PHI nodes in common successor.
  3915. if (FoldBranchToCommonDest(BI, BonusInstThreshold))
  3916. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3917. return false;
  3918. }
  3919. bool SimplifyCFGOpt::SimplifyCondBranch(BranchInst *BI, IRBuilder<> &Builder) {
  3920. BasicBlock *BB = BI->getParent();
  3921. // Conditional branch
  3922. if (isValueEqualityComparison(BI)) {
  3923. // If we only have one predecessor, and if it is a branch on this value,
  3924. // see if that predecessor totally determines the outcome of this
  3925. // switch.
  3926. if (BasicBlock *OnlyPred = BB->getSinglePredecessor())
  3927. if (SimplifyEqualityComparisonWithOnlyPredecessor(BI, OnlyPred, Builder))
  3928. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3929. // This block must be empty, except for the setcond inst, if it exists.
  3930. // Ignore dbg intrinsics.
  3931. BasicBlock::iterator I = BB->begin();
  3932. // Ignore dbg intrinsics.
  3933. while (isa<DbgInfoIntrinsic>(I))
  3934. ++I;
  3935. if (&*I == BI) {
  3936. if (FoldValueComparisonIntoPredecessors(BI, Builder))
  3937. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3938. } else if (&*I == cast<Instruction>(BI->getCondition())){
  3939. ++I;
  3940. // Ignore dbg intrinsics.
  3941. while (isa<DbgInfoIntrinsic>(I))
  3942. ++I;
  3943. if (&*I == BI && FoldValueComparisonIntoPredecessors(BI, Builder))
  3944. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3945. }
  3946. }
  3947. #if 0 // HLSL Change Begins. This will not help for hlsl.
  3948. // Try to turn "br (X == 0 | X == 1), T, F" into a switch instruction.
  3949. if (SimplifyBranchOnICmpChain(BI, Builder, DL))
  3950. return true;
  3951. #endif // HLSL Change Ends.
  3952. // If this basic block is ONLY a compare and a branch, and if a predecessor
  3953. // branches to us and one of our successors, fold the comparison into the
  3954. // predecessor and use logical operations to pick the right destination.
  3955. if (FoldBranchToCommonDest(BI, BonusInstThreshold))
  3956. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3957. // We have a conditional branch to two blocks that are only reachable
  3958. // from BI. We know that the condbr dominates the two blocks, so see if
  3959. // there is any identical code in the "then" and "else" blocks. If so, we
  3960. // can hoist it up to the branching block.
  3961. if (BI->getSuccessor(0)->getSinglePredecessor()) {
  3962. if (BI->getSuccessor(1)->getSinglePredecessor()) {
  3963. if (HoistThenElseCodeToIf(BI, TTI))
  3964. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3965. } else {
  3966. // If Successor #1 has multiple preds, we may be able to conditionally
  3967. // execute Successor #0 if it branches to Successor #1.
  3968. TerminatorInst *Succ0TI = BI->getSuccessor(0)->getTerminator();
  3969. if (Succ0TI->getNumSuccessors() == 1 &&
  3970. Succ0TI->getSuccessor(0) == BI->getSuccessor(1))
  3971. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(0), TTI))
  3972. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3973. }
  3974. } else if (BI->getSuccessor(1)->getSinglePredecessor()) {
  3975. // If Successor #0 has multiple preds, we may be able to conditionally
  3976. // execute Successor #1 if it branches to Successor #0.
  3977. TerminatorInst *Succ1TI = BI->getSuccessor(1)->getTerminator();
  3978. if (Succ1TI->getNumSuccessors() == 1 &&
  3979. Succ1TI->getSuccessor(0) == BI->getSuccessor(0))
  3980. if (SpeculativelyExecuteBB(BI, BI->getSuccessor(1), TTI))
  3981. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3982. }
  3983. // If this is a branch on a phi node in the current block, thread control
  3984. // through this block if any PHI node entries are constants.
  3985. if (PHINode *PN = dyn_cast<PHINode>(BI->getCondition()))
  3986. if (PN->getParent() == BI->getParent())
  3987. if (FoldCondBranchOnPHI(BI, DL))
  3988. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3989. // Scan predecessor blocks for conditional branches.
  3990. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  3991. if (BranchInst *PBI = dyn_cast<BranchInst>((*PI)->getTerminator()))
  3992. if (PBI != BI && PBI->isConditional())
  3993. if (SimplifyCondBranchToCondBranch(PBI, BI))
  3994. return SimplifyCFG(BB, TTI, BonusInstThreshold, AC) | true;
  3995. return false;
  3996. }
  3997. /// Check if passing a value to an instruction will cause undefined behavior.
  3998. static bool passingValueIsAlwaysUndefined(Value *V, Instruction *I) {
  3999. Constant *C = dyn_cast<Constant>(V);
  4000. if (!C)
  4001. return false;
  4002. if (I->use_empty())
  4003. return false;
  4004. if (C->isNullValue()) {
  4005. // Only look at the first use, avoid hurting compile time with long uselists
  4006. User *Use = *I->user_begin();
  4007. // Now make sure that there are no instructions in between that can alter
  4008. // control flow (eg. calls)
  4009. for (BasicBlock::iterator i = ++BasicBlock::iterator(I); &*i != Use; ++i)
  4010. if (i == I->getParent()->end() || i->mayHaveSideEffects())
  4011. return false;
  4012. // Look through GEPs. A load from a GEP derived from NULL is still undefined
  4013. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Use))
  4014. if (GEP->getPointerOperand() == I)
  4015. return passingValueIsAlwaysUndefined(V, GEP);
  4016. // Look through bitcasts.
  4017. if (BitCastInst *BC = dyn_cast<BitCastInst>(Use))
  4018. return passingValueIsAlwaysUndefined(V, BC);
  4019. // Load from null is undefined.
  4020. if (LoadInst *LI = dyn_cast<LoadInst>(Use))
  4021. if (!LI->isVolatile())
  4022. return LI->getPointerAddressSpace() == 0;
  4023. // Store to null is undefined.
  4024. if (StoreInst *SI = dyn_cast<StoreInst>(Use))
  4025. if (!SI->isVolatile())
  4026. return SI->getPointerAddressSpace() == 0 && SI->getPointerOperand() == I;
  4027. }
  4028. return false;
  4029. }
  4030. /// If BB has an incoming value that will always trigger undefined behavior
  4031. /// (eg. null pointer dereference), remove the branch leading here.
  4032. static bool removeUndefIntroducingPredecessor(BasicBlock *BB) {
  4033. for (BasicBlock::iterator i = BB->begin();
  4034. PHINode *PHI = dyn_cast<PHINode>(i); ++i)
  4035. for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
  4036. if (passingValueIsAlwaysUndefined(PHI->getIncomingValue(i), PHI)) {
  4037. TerminatorInst *T = PHI->getIncomingBlock(i)->getTerminator();
  4038. IRBuilder<> Builder(T);
  4039. if (BranchInst *BI = dyn_cast<BranchInst>(T)) {
  4040. BB->removePredecessor(PHI->getIncomingBlock(i));
  4041. // Turn uncoditional branches into unreachables and remove the dead
  4042. // destination from conditional branches.
  4043. if (BI->isUnconditional())
  4044. Builder.CreateUnreachable();
  4045. else
  4046. Builder.CreateBr(BI->getSuccessor(0) == BB ? BI->getSuccessor(1) :
  4047. BI->getSuccessor(0));
  4048. BI->eraseFromParent();
  4049. return true;
  4050. }
  4051. // TODO: SwitchInst.
  4052. }
  4053. return false;
  4054. }
  4055. bool SimplifyCFGOpt::run(BasicBlock *BB) {
  4056. bool Changed = false;
  4057. assert(BB && BB->getParent() && "Block not embedded in function!");
  4058. assert(BB->getTerminator() && "Degenerate basic block encountered!");
  4059. // Remove basic blocks that have no predecessors (except the entry block)...
  4060. // or that just have themself as a predecessor. These are unreachable.
  4061. if ((pred_empty(BB) &&
  4062. BB != &BB->getParent()->getEntryBlock()) ||
  4063. BB->getSinglePredecessor() == BB) {
  4064. DEBUG(dbgs() << "Removing BB: \n" << *BB);
  4065. DeleteDeadBlock(BB);
  4066. return true;
  4067. }
  4068. // Check to see if we can constant propagate this terminator instruction
  4069. // away...
  4070. Changed |= ConstantFoldTerminator(BB, true);
  4071. // Check for and eliminate duplicate PHI nodes in this block.
  4072. Changed |= EliminateDuplicatePHINodes(BB);
  4073. // Check for and remove branches that will always cause undefined behavior.
  4074. Changed |= removeUndefIntroducingPredecessor(BB);
  4075. // Merge basic blocks into their predecessor if there is only one distinct
  4076. // pred, and if there is only one distinct successor of the predecessor, and
  4077. // if there are no PHI nodes.
  4078. //
  4079. if (MergeBlockIntoPredecessor(BB))
  4080. return true;
  4081. IRBuilder<> Builder(BB);
  4082. // If there is a trivial two-entry PHI node in this basic block, and we can
  4083. // eliminate it, do so now.
  4084. if (PHINode *PN = dyn_cast<PHINode>(BB->begin()))
  4085. if (PN->getNumIncomingValues() == 2)
  4086. Changed |= FoldTwoEntryPHINode(PN, TTI, DL);
  4087. Builder.SetInsertPoint(BB->getTerminator());
  4088. if (BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator())) {
  4089. if (BI->isUnconditional()) {
  4090. if (SimplifyUncondBranch(BI, Builder)) return true;
  4091. } else {
  4092. if (SimplifyCondBranch(BI, Builder)) return true;
  4093. }
  4094. } else if (ReturnInst *RI = dyn_cast<ReturnInst>(BB->getTerminator())) {
  4095. if (SimplifyReturn(RI, Builder)) return true;
  4096. } else if (ResumeInst *RI = dyn_cast<ResumeInst>(BB->getTerminator())) {
  4097. if (SimplifyResume(RI, Builder)) return true;
  4098. } else if (SwitchInst *SI = dyn_cast<SwitchInst>(BB->getTerminator())) {
  4099. if (SimplifySwitch(SI, Builder)) return true;
  4100. } else if (UnreachableInst *UI =
  4101. dyn_cast<UnreachableInst>(BB->getTerminator())) {
  4102. if (SimplifyUnreachable(UI)) return true;
  4103. } else if (IndirectBrInst *IBI =
  4104. dyn_cast<IndirectBrInst>(BB->getTerminator())) {
  4105. if (SimplifyIndirectBr(IBI)) return true;
  4106. }
  4107. return Changed;
  4108. }
  4109. /// This function is used to do simplification of a CFG.
  4110. /// For example, it adjusts branches to branches to eliminate the extra hop,
  4111. /// eliminates unreachable basic blocks, and does other "peephole" optimization
  4112. /// of the CFG. It returns true if a modification was made.
  4113. ///
  4114. bool llvm::SimplifyCFG(BasicBlock *BB, const TargetTransformInfo &TTI,
  4115. unsigned BonusInstThreshold, AssumptionCache *AC) {
  4116. return SimplifyCFGOpt(TTI, BB->getModule()->getDataLayout(),
  4117. BonusInstThreshold, AC).run(BB);
  4118. }