SimplifyCFG.cpp 228 KB

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