SimplifyCFG.cpp 182 KB

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