CodeGenPrepare.cpp 217 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  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. // This pass munges the code in the input function to better prepare it for
  11. // SelectionDAG-based code generation. This works around limitations in it's
  12. // basic-block-at-a-time approach. It should eventually be removed.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/CodeGen/Passes.h"
  16. #include "llvm/CodeGen/TargetPassConfig.h"
  17. #include "llvm/ADT/DenseMap.h"
  18. #include "llvm/ADT/SetVector.h"
  19. #include "llvm/ADT/SmallSet.h"
  20. #include "llvm/ADT/Statistic.h"
  21. #include "llvm/Analysis/BlockFrequencyInfo.h"
  22. #include "llvm/Analysis/BranchProbabilityInfo.h"
  23. #include "llvm/Analysis/CFG.h"
  24. #include "llvm/Analysis/InstructionSimplify.h"
  25. #include "llvm/Analysis/LoopInfo.h"
  26. #include "llvm/Analysis/ProfileSummaryInfo.h"
  27. #include "llvm/Analysis/TargetLibraryInfo.h"
  28. #include "llvm/Analysis/TargetTransformInfo.h"
  29. #include "llvm/Analysis/ValueTracking.h"
  30. #include "llvm/Analysis/MemoryBuiltins.h"
  31. #include "llvm/CodeGen/Analysis.h"
  32. #include "llvm/IR/CallSite.h"
  33. #include "llvm/IR/Constants.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/DerivedTypes.h"
  36. #include "llvm/IR/Dominators.h"
  37. #include "llvm/IR/Function.h"
  38. #include "llvm/IR/GetElementPtrTypeIterator.h"
  39. #include "llvm/IR/IRBuilder.h"
  40. #include "llvm/IR/InlineAsm.h"
  41. #include "llvm/IR/Instructions.h"
  42. #include "llvm/IR/IntrinsicInst.h"
  43. #include "llvm/IR/MDBuilder.h"
  44. #include "llvm/IR/PatternMatch.h"
  45. #include "llvm/IR/Statepoint.h"
  46. #include "llvm/IR/ValueHandle.h"
  47. #include "llvm/IR/ValueMap.h"
  48. #include "llvm/Pass.h"
  49. #include "llvm/Support/BranchProbability.h"
  50. #include "llvm/Support/CommandLine.h"
  51. #include "llvm/Support/Debug.h"
  52. #include "llvm/Support/raw_ostream.h"
  53. #include "llvm/Target/TargetLowering.h"
  54. #include "llvm/Target/TargetSubtargetInfo.h"
  55. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  56. #include "llvm/Transforms/Utils/BuildLibCalls.h"
  57. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  58. #include "llvm/Transforms/Utils/Cloning.h"
  59. #include "llvm/Transforms/Utils/Local.h"
  60. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  61. #include "llvm/Transforms/Utils/ValueMapper.h"
  62. using namespace llvm;
  63. using namespace llvm::PatternMatch;
  64. #define DEBUG_TYPE "codegenprepare"
  65. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  66. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  67. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  68. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  69. "sunken Cmps");
  70. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  71. "of sunken Casts");
  72. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  73. "computations were sunk");
  74. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  75. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  76. STATISTIC(NumAndsAdded,
  77. "Number of and mask instructions added to form ext loads");
  78. STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
  79. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  80. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  81. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  82. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  83. static cl::opt<bool> DisableBranchOpts(
  84. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  85. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  86. static cl::opt<bool>
  87. DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
  88. cl::desc("Disable GC optimizations in CodeGenPrepare"));
  89. static cl::opt<bool> DisableSelectToBranch(
  90. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  91. cl::desc("Disable select to branch conversion."));
  92. static cl::opt<bool> AddrSinkUsingGEPs(
  93. "addr-sink-using-gep", cl::Hidden, cl::init(true),
  94. cl::desc("Address sinking in CGP using GEPs."));
  95. static cl::opt<bool> EnableAndCmpSinking(
  96. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  97. cl::desc("Enable sinkinig and/cmp into branches."));
  98. static cl::opt<bool> DisableStoreExtract(
  99. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  100. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  101. static cl::opt<bool> StressStoreExtract(
  102. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  103. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  104. static cl::opt<bool> DisableExtLdPromotion(
  105. "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  106. cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
  107. "CodeGenPrepare"));
  108. static cl::opt<bool> StressExtLdPromotion(
  109. "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  110. cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
  111. "optimization in CodeGenPrepare"));
  112. static cl::opt<bool> DisablePreheaderProtect(
  113. "disable-preheader-prot", cl::Hidden, cl::init(false),
  114. cl::desc("Disable protection against removing loop preheaders"));
  115. static cl::opt<bool> ProfileGuidedSectionPrefix(
  116. "profile-guided-section-prefix", cl::Hidden, cl::init(true),
  117. cl::desc("Use profile info to add section prefix for hot/cold functions"));
  118. static cl::opt<unsigned> FreqRatioToSkipMerge(
  119. "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
  120. cl::desc("Skip merging empty blocks if (frequency of empty block) / "
  121. "(frequency of destination block) is greater than this ratio"));
  122. static cl::opt<bool> ForceSplitStore(
  123. "force-split-store", cl::Hidden, cl::init(false),
  124. cl::desc("Force store splitting no matter what the target query says."));
  125. static cl::opt<bool>
  126. EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
  127. cl::desc("Enable merging of redundant sexts when one is dominating"
  128. " the other."), cl::init(true));
  129. namespace {
  130. typedef SmallPtrSet<Instruction *, 16> SetOfInstrs;
  131. typedef PointerIntPair<Type *, 1, bool> TypeIsSExt;
  132. typedef DenseMap<Instruction *, TypeIsSExt> InstrToOrigTy;
  133. typedef SmallVector<Instruction *, 16> SExts;
  134. typedef DenseMap<Value *, SExts> ValueToSExts;
  135. class TypePromotionTransaction;
  136. class CodeGenPrepare : public FunctionPass {
  137. const TargetMachine *TM;
  138. const TargetSubtargetInfo *SubtargetInfo;
  139. const TargetLowering *TLI;
  140. const TargetRegisterInfo *TRI;
  141. const TargetTransformInfo *TTI;
  142. const TargetLibraryInfo *TLInfo;
  143. const LoopInfo *LI;
  144. std::unique_ptr<BlockFrequencyInfo> BFI;
  145. std::unique_ptr<BranchProbabilityInfo> BPI;
  146. /// As we scan instructions optimizing them, this is the next instruction
  147. /// to optimize. Transforms that can invalidate this should update it.
  148. BasicBlock::iterator CurInstIterator;
  149. /// Keeps track of non-local addresses that have been sunk into a block.
  150. /// This allows us to avoid inserting duplicate code for blocks with
  151. /// multiple load/stores of the same address.
  152. ValueMap<Value*, Value*> SunkAddrs;
  153. /// Keeps track of all instructions inserted for the current function.
  154. SetOfInstrs InsertedInsts;
  155. /// Keeps track of the type of the related instruction before their
  156. /// promotion for the current function.
  157. InstrToOrigTy PromotedInsts;
  158. /// Keep track of instructions removed during promotion.
  159. SetOfInstrs RemovedInsts;
  160. /// Keep track of sext chains based on their initial value.
  161. DenseMap<Value *, Instruction *> SeenChainsForSExt;
  162. /// Keep track of SExt promoted.
  163. ValueToSExts ValToSExtendedUses;
  164. /// True if CFG is modified in any way.
  165. bool ModifiedDT;
  166. /// True if optimizing for size.
  167. bool OptSize;
  168. /// DataLayout for the Function being processed.
  169. const DataLayout *DL;
  170. public:
  171. static char ID; // Pass identification, replacement for typeid
  172. CodeGenPrepare()
  173. : FunctionPass(ID), TM(nullptr), TLI(nullptr), TTI(nullptr),
  174. DL(nullptr) {
  175. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  176. }
  177. bool runOnFunction(Function &F) override;
  178. StringRef getPassName() const override { return "CodeGen Prepare"; }
  179. void getAnalysisUsage(AnalysisUsage &AU) const override {
  180. // FIXME: When we can selectively preserve passes, preserve the domtree.
  181. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  182. AU.addRequired<TargetLibraryInfoWrapperPass>();
  183. AU.addRequired<TargetTransformInfoWrapperPass>();
  184. AU.addRequired<LoopInfoWrapperPass>();
  185. }
  186. private:
  187. bool eliminateFallThrough(Function &F);
  188. bool eliminateMostlyEmptyBlocks(Function &F);
  189. BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
  190. bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  191. void eliminateMostlyEmptyBlock(BasicBlock *BB);
  192. bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
  193. bool isPreheader);
  194. bool optimizeBlock(BasicBlock &BB, bool& ModifiedDT);
  195. bool optimizeInst(Instruction *I, bool& ModifiedDT);
  196. bool optimizeMemoryInst(Instruction *I, Value *Addr,
  197. Type *AccessTy, unsigned AS);
  198. bool optimizeInlineAsmInst(CallInst *CS);
  199. bool optimizeCallInst(CallInst *CI, bool& ModifiedDT);
  200. bool optimizeExt(Instruction *&I);
  201. bool optimizeExtUses(Instruction *I);
  202. bool optimizeLoadExt(LoadInst *I);
  203. bool optimizeSelectInst(SelectInst *SI);
  204. bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
  205. bool optimizeSwitchInst(SwitchInst *CI);
  206. bool optimizeExtractElementInst(Instruction *Inst);
  207. bool dupRetToEnableTailCallOpts(BasicBlock *BB);
  208. bool placeDbgValues(Function &F);
  209. bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
  210. LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
  211. bool tryToPromoteExts(TypePromotionTransaction &TPT,
  212. const SmallVectorImpl<Instruction *> &Exts,
  213. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  214. unsigned CreatedInstsCost = 0);
  215. bool mergeSExts(Function &F);
  216. bool performAddressTypePromotion(
  217. Instruction *&Inst,
  218. bool AllowPromotionWithoutCommonHeader,
  219. bool HasPromoted, TypePromotionTransaction &TPT,
  220. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
  221. bool splitBranchCondition(Function &F);
  222. bool simplifyOffsetableRelocate(Instruction &I);
  223. bool splitIndirectCriticalEdges(Function &F);
  224. };
  225. }
  226. char CodeGenPrepare::ID = 0;
  227. INITIALIZE_PASS_BEGIN(CodeGenPrepare, "codegenprepare",
  228. "Optimize for code generation", false, false)
  229. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  230. INITIALIZE_PASS_END(CodeGenPrepare, "codegenprepare",
  231. "Optimize for code generation", false, false)
  232. FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
  233. bool CodeGenPrepare::runOnFunction(Function &F) {
  234. if (skipFunction(F))
  235. return false;
  236. DL = &F.getParent()->getDataLayout();
  237. bool EverMadeChange = false;
  238. // Clear per function information.
  239. InsertedInsts.clear();
  240. PromotedInsts.clear();
  241. BFI.reset();
  242. BPI.reset();
  243. ModifiedDT = false;
  244. if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
  245. TM = &TPC->getTM<TargetMachine>();
  246. SubtargetInfo = TM->getSubtargetImpl(F);
  247. TLI = SubtargetInfo->getTargetLowering();
  248. TRI = SubtargetInfo->getRegisterInfo();
  249. }
  250. TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  251. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  252. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  253. OptSize = F.optForSize();
  254. if (ProfileGuidedSectionPrefix) {
  255. ProfileSummaryInfo *PSI =
  256. getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  257. if (PSI->isFunctionHotInCallGraph(&F))
  258. F.setSectionPrefix(".hot");
  259. else if (PSI->isFunctionColdInCallGraph(&F))
  260. F.setSectionPrefix(".unlikely");
  261. }
  262. /// This optimization identifies DIV instructions that can be
  263. /// profitably bypassed and carried out with a shorter, faster divide.
  264. if (!OptSize && TLI && TLI->isSlowDivBypassed()) {
  265. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  266. TLI->getBypassSlowDivWidths();
  267. BasicBlock* BB = &*F.begin();
  268. while (BB != nullptr) {
  269. // bypassSlowDivision may create new BBs, but we don't want to reapply the
  270. // optimization to those blocks.
  271. BasicBlock* Next = BB->getNextNode();
  272. EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
  273. BB = Next;
  274. }
  275. }
  276. // Eliminate blocks that contain only PHI nodes and an
  277. // unconditional branch.
  278. EverMadeChange |= eliminateMostlyEmptyBlocks(F);
  279. // llvm.dbg.value is far away from the value then iSel may not be able
  280. // handle it properly. iSel will drop llvm.dbg.value if it can not
  281. // find a node corresponding to the value.
  282. EverMadeChange |= placeDbgValues(F);
  283. if (!DisableBranchOpts)
  284. EverMadeChange |= splitBranchCondition(F);
  285. // Split some critical edges where one of the sources is an indirect branch,
  286. // to help generate sane code for PHIs involving such edges.
  287. EverMadeChange |= splitIndirectCriticalEdges(F);
  288. bool MadeChange = true;
  289. while (MadeChange) {
  290. MadeChange = false;
  291. SeenChainsForSExt.clear();
  292. ValToSExtendedUses.clear();
  293. RemovedInsts.clear();
  294. for (Function::iterator I = F.begin(); I != F.end(); ) {
  295. BasicBlock *BB = &*I++;
  296. bool ModifiedDTOnIteration = false;
  297. MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
  298. // Restart BB iteration if the dominator tree of the Function was changed
  299. if (ModifiedDTOnIteration)
  300. break;
  301. }
  302. if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
  303. MadeChange |= mergeSExts(F);
  304. // Really free removed instructions during promotion.
  305. for (Instruction *I : RemovedInsts)
  306. delete I;
  307. EverMadeChange |= MadeChange;
  308. }
  309. SunkAddrs.clear();
  310. if (!DisableBranchOpts) {
  311. MadeChange = false;
  312. SmallPtrSet<BasicBlock*, 8> WorkList;
  313. for (BasicBlock &BB : F) {
  314. SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
  315. MadeChange |= ConstantFoldTerminator(&BB, true);
  316. if (!MadeChange) continue;
  317. for (SmallVectorImpl<BasicBlock*>::iterator
  318. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  319. if (pred_begin(*II) == pred_end(*II))
  320. WorkList.insert(*II);
  321. }
  322. // Delete the dead blocks and any of their dead successors.
  323. MadeChange |= !WorkList.empty();
  324. while (!WorkList.empty()) {
  325. BasicBlock *BB = *WorkList.begin();
  326. WorkList.erase(BB);
  327. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  328. DeleteDeadBlock(BB);
  329. for (SmallVectorImpl<BasicBlock*>::iterator
  330. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  331. if (pred_begin(*II) == pred_end(*II))
  332. WorkList.insert(*II);
  333. }
  334. // Merge pairs of basic blocks with unconditional branches, connected by
  335. // a single edge.
  336. if (EverMadeChange || MadeChange)
  337. MadeChange |= eliminateFallThrough(F);
  338. EverMadeChange |= MadeChange;
  339. }
  340. if (!DisableGCOpts) {
  341. SmallVector<Instruction *, 2> Statepoints;
  342. for (BasicBlock &BB : F)
  343. for (Instruction &I : BB)
  344. if (isStatepoint(I))
  345. Statepoints.push_back(&I);
  346. for (auto &I : Statepoints)
  347. EverMadeChange |= simplifyOffsetableRelocate(*I);
  348. }
  349. return EverMadeChange;
  350. }
  351. /// Merge basic blocks which are connected by a single edge, where one of the
  352. /// basic blocks has a single successor pointing to the other basic block,
  353. /// which has a single predecessor.
  354. bool CodeGenPrepare::eliminateFallThrough(Function &F) {
  355. bool Changed = false;
  356. // Scan all of the blocks in the function, except for the entry block.
  357. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  358. BasicBlock *BB = &*I++;
  359. // If the destination block has a single pred, then this is a trivial
  360. // edge, just collapse it.
  361. BasicBlock *SinglePred = BB->getSinglePredecessor();
  362. // Don't merge if BB's address is taken.
  363. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  364. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  365. if (Term && !Term->isConditional()) {
  366. Changed = true;
  367. DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
  368. // Remember if SinglePred was the entry block of the function.
  369. // If so, we will need to move BB back to the entry position.
  370. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  371. MergeBasicBlockIntoOnlyPred(BB, nullptr);
  372. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  373. BB->moveBefore(&BB->getParent()->getEntryBlock());
  374. // We have erased a block. Update the iterator.
  375. I = BB->getIterator();
  376. }
  377. }
  378. return Changed;
  379. }
  380. /// Find a destination block from BB if BB is mergeable empty block.
  381. BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
  382. // If this block doesn't end with an uncond branch, ignore it.
  383. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  384. if (!BI || !BI->isUnconditional())
  385. return nullptr;
  386. // If the instruction before the branch (skipping debug info) isn't a phi
  387. // node, then other stuff is happening here.
  388. BasicBlock::iterator BBI = BI->getIterator();
  389. if (BBI != BB->begin()) {
  390. --BBI;
  391. while (isa<DbgInfoIntrinsic>(BBI)) {
  392. if (BBI == BB->begin())
  393. break;
  394. --BBI;
  395. }
  396. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  397. return nullptr;
  398. }
  399. // Do not break infinite loops.
  400. BasicBlock *DestBB = BI->getSuccessor(0);
  401. if (DestBB == BB)
  402. return nullptr;
  403. if (!canMergeBlocks(BB, DestBB))
  404. DestBB = nullptr;
  405. return DestBB;
  406. }
  407. // Return the unique indirectbr predecessor of a block. This may return null
  408. // even if such a predecessor exists, if it's not useful for splitting.
  409. // If a predecessor is found, OtherPreds will contain all other (non-indirectbr)
  410. // predecessors of BB.
  411. static BasicBlock *
  412. findIBRPredecessor(BasicBlock *BB, SmallVectorImpl<BasicBlock *> &OtherPreds) {
  413. // If the block doesn't have any PHIs, we don't care about it, since there's
  414. // no point in splitting it.
  415. PHINode *PN = dyn_cast<PHINode>(BB->begin());
  416. if (!PN)
  417. return nullptr;
  418. // Verify we have exactly one IBR predecessor.
  419. // Conservatively bail out if one of the other predecessors is not a "regular"
  420. // terminator (that is, not a switch or a br).
  421. BasicBlock *IBB = nullptr;
  422. for (unsigned Pred = 0, E = PN->getNumIncomingValues(); Pred != E; ++Pred) {
  423. BasicBlock *PredBB = PN->getIncomingBlock(Pred);
  424. TerminatorInst *PredTerm = PredBB->getTerminator();
  425. switch (PredTerm->getOpcode()) {
  426. case Instruction::IndirectBr:
  427. if (IBB)
  428. return nullptr;
  429. IBB = PredBB;
  430. break;
  431. case Instruction::Br:
  432. case Instruction::Switch:
  433. OtherPreds.push_back(PredBB);
  434. continue;
  435. default:
  436. return nullptr;
  437. }
  438. }
  439. return IBB;
  440. }
  441. // Split critical edges where the source of the edge is an indirectbr
  442. // instruction. This isn't always possible, but we can handle some easy cases.
  443. // This is useful because MI is unable to split such critical edges,
  444. // which means it will not be able to sink instructions along those edges.
  445. // This is especially painful for indirect branches with many successors, where
  446. // we end up having to prepare all outgoing values in the origin block.
  447. //
  448. // Our normal algorithm for splitting critical edges requires us to update
  449. // the outgoing edges of the edge origin block, but for an indirectbr this
  450. // is hard, since it would require finding and updating the block addresses
  451. // the indirect branch uses. But if a block only has a single indirectbr
  452. // predecessor, with the others being regular branches, we can do it in a
  453. // different way.
  454. // Say we have A -> D, B -> D, I -> D where only I -> D is an indirectbr.
  455. // We can split D into D0 and D1, where D0 contains only the PHIs from D,
  456. // and D1 is the D block body. We can then duplicate D0 as D0A and D0B, and
  457. // create the following structure:
  458. // A -> D0A, B -> D0A, I -> D0B, D0A -> D1, D0B -> D1
  459. bool CodeGenPrepare::splitIndirectCriticalEdges(Function &F) {
  460. // Check whether the function has any indirectbrs, and collect which blocks
  461. // they may jump to. Since most functions don't have indirect branches,
  462. // this lowers the common case's overhead to O(Blocks) instead of O(Edges).
  463. SmallSetVector<BasicBlock *, 16> Targets;
  464. for (auto &BB : F) {
  465. auto *IBI = dyn_cast<IndirectBrInst>(BB.getTerminator());
  466. if (!IBI)
  467. continue;
  468. for (unsigned Succ = 0, E = IBI->getNumSuccessors(); Succ != E; ++Succ)
  469. Targets.insert(IBI->getSuccessor(Succ));
  470. }
  471. if (Targets.empty())
  472. return false;
  473. bool Changed = false;
  474. for (BasicBlock *Target : Targets) {
  475. SmallVector<BasicBlock *, 16> OtherPreds;
  476. BasicBlock *IBRPred = findIBRPredecessor(Target, OtherPreds);
  477. // If we did not found an indirectbr, or the indirectbr is the only
  478. // incoming edge, this isn't the kind of edge we're looking for.
  479. if (!IBRPred || OtherPreds.empty())
  480. continue;
  481. // Don't even think about ehpads/landingpads.
  482. Instruction *FirstNonPHI = Target->getFirstNonPHI();
  483. if (FirstNonPHI->isEHPad() || Target->isLandingPad())
  484. continue;
  485. BasicBlock *BodyBlock = Target->splitBasicBlock(FirstNonPHI, ".split");
  486. // It's possible Target was its own successor through an indirectbr.
  487. // In this case, the indirectbr now comes from BodyBlock.
  488. if (IBRPred == Target)
  489. IBRPred = BodyBlock;
  490. // At this point Target only has PHIs, and BodyBlock has the rest of the
  491. // block's body. Create a copy of Target that will be used by the "direct"
  492. // preds.
  493. ValueToValueMapTy VMap;
  494. BasicBlock *DirectSucc = CloneBasicBlock(Target, VMap, ".clone", &F);
  495. for (BasicBlock *Pred : OtherPreds) {
  496. // If the target is a loop to itself, then the terminator of the split
  497. // block needs to be updated.
  498. if (Pred == Target)
  499. BodyBlock->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
  500. else
  501. Pred->getTerminator()->replaceUsesOfWith(Target, DirectSucc);
  502. }
  503. // Ok, now fix up the PHIs. We know the two blocks only have PHIs, and that
  504. // they are clones, so the number of PHIs are the same.
  505. // (a) Remove the edge coming from IBRPred from the "Direct" PHI
  506. // (b) Leave that as the only edge in the "Indirect" PHI.
  507. // (c) Merge the two in the body block.
  508. BasicBlock::iterator Indirect = Target->begin(),
  509. End = Target->getFirstNonPHI()->getIterator();
  510. BasicBlock::iterator Direct = DirectSucc->begin();
  511. BasicBlock::iterator MergeInsert = BodyBlock->getFirstInsertionPt();
  512. assert(&*End == Target->getTerminator() &&
  513. "Block was expected to only contain PHIs");
  514. while (Indirect != End) {
  515. PHINode *DirPHI = cast<PHINode>(Direct);
  516. PHINode *IndPHI = cast<PHINode>(Indirect);
  517. // Now, clean up - the direct block shouldn't get the indirect value,
  518. // and vice versa.
  519. DirPHI->removeIncomingValue(IBRPred);
  520. Direct++;
  521. // Advance the pointer here, to avoid invalidation issues when the old
  522. // PHI is erased.
  523. Indirect++;
  524. PHINode *NewIndPHI = PHINode::Create(IndPHI->getType(), 1, "ind", IndPHI);
  525. NewIndPHI->addIncoming(IndPHI->getIncomingValueForBlock(IBRPred),
  526. IBRPred);
  527. // Create a PHI in the body block, to merge the direct and indirect
  528. // predecessors.
  529. PHINode *MergePHI =
  530. PHINode::Create(IndPHI->getType(), 2, "merge", &*MergeInsert);
  531. MergePHI->addIncoming(NewIndPHI, Target);
  532. MergePHI->addIncoming(DirPHI, DirectSucc);
  533. IndPHI->replaceAllUsesWith(MergePHI);
  534. IndPHI->eraseFromParent();
  535. }
  536. Changed = true;
  537. }
  538. return Changed;
  539. }
  540. /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
  541. /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
  542. /// edges in ways that are non-optimal for isel. Start by eliminating these
  543. /// blocks so we can split them the way we want them.
  544. bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
  545. SmallPtrSet<BasicBlock *, 16> Preheaders;
  546. SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
  547. while (!LoopList.empty()) {
  548. Loop *L = LoopList.pop_back_val();
  549. LoopList.insert(LoopList.end(), L->begin(), L->end());
  550. if (BasicBlock *Preheader = L->getLoopPreheader())
  551. Preheaders.insert(Preheader);
  552. }
  553. bool MadeChange = false;
  554. // Note that this intentionally skips the entry block.
  555. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  556. BasicBlock *BB = &*I++;
  557. BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
  558. if (!DestBB ||
  559. !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
  560. continue;
  561. eliminateMostlyEmptyBlock(BB);
  562. MadeChange = true;
  563. }
  564. return MadeChange;
  565. }
  566. bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
  567. BasicBlock *DestBB,
  568. bool isPreheader) {
  569. // Do not delete loop preheaders if doing so would create a critical edge.
  570. // Loop preheaders can be good locations to spill registers. If the
  571. // preheader is deleted and we create a critical edge, registers may be
  572. // spilled in the loop body instead.
  573. if (!DisablePreheaderProtect && isPreheader &&
  574. !(BB->getSinglePredecessor() &&
  575. BB->getSinglePredecessor()->getSingleSuccessor()))
  576. return false;
  577. // Try to skip merging if the unique predecessor of BB is terminated by a
  578. // switch or indirect branch instruction, and BB is used as an incoming block
  579. // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
  580. // add COPY instructions in the predecessor of BB instead of BB (if it is not
  581. // merged). Note that the critical edge created by merging such blocks wont be
  582. // split in MachineSink because the jump table is not analyzable. By keeping
  583. // such empty block (BB), ISel will place COPY instructions in BB, not in the
  584. // predecessor of BB.
  585. BasicBlock *Pred = BB->getUniquePredecessor();
  586. if (!Pred ||
  587. !(isa<SwitchInst>(Pred->getTerminator()) ||
  588. isa<IndirectBrInst>(Pred->getTerminator())))
  589. return true;
  590. if (BB->getTerminator() != BB->getFirstNonPHI())
  591. return true;
  592. // We use a simple cost heuristic which determine skipping merging is
  593. // profitable if the cost of skipping merging is less than the cost of
  594. // merging : Cost(skipping merging) < Cost(merging BB), where the
  595. // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
  596. // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
  597. // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
  598. // Freq(Pred) / Freq(BB) > 2.
  599. // Note that if there are multiple empty blocks sharing the same incoming
  600. // value for the PHIs in the DestBB, we consider them together. In such
  601. // case, Cost(merging BB) will be the sum of their frequencies.
  602. if (!isa<PHINode>(DestBB->begin()))
  603. return true;
  604. SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
  605. // Find all other incoming blocks from which incoming values of all PHIs in
  606. // DestBB are the same as the ones from BB.
  607. for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
  608. ++PI) {
  609. BasicBlock *DestBBPred = *PI;
  610. if (DestBBPred == BB)
  611. continue;
  612. bool HasAllSameValue = true;
  613. BasicBlock::const_iterator DestBBI = DestBB->begin();
  614. while (const PHINode *DestPN = dyn_cast<PHINode>(DestBBI++)) {
  615. if (DestPN->getIncomingValueForBlock(BB) !=
  616. DestPN->getIncomingValueForBlock(DestBBPred)) {
  617. HasAllSameValue = false;
  618. break;
  619. }
  620. }
  621. if (HasAllSameValue)
  622. SameIncomingValueBBs.insert(DestBBPred);
  623. }
  624. // See if all BB's incoming values are same as the value from Pred. In this
  625. // case, no reason to skip merging because COPYs are expected to be place in
  626. // Pred already.
  627. if (SameIncomingValueBBs.count(Pred))
  628. return true;
  629. if (!BFI) {
  630. Function &F = *BB->getParent();
  631. LoopInfo LI{DominatorTree(F)};
  632. BPI.reset(new BranchProbabilityInfo(F, LI));
  633. BFI.reset(new BlockFrequencyInfo(F, *BPI, LI));
  634. }
  635. BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
  636. BlockFrequency BBFreq = BFI->getBlockFreq(BB);
  637. for (auto SameValueBB : SameIncomingValueBBs)
  638. if (SameValueBB->getUniquePredecessor() == Pred &&
  639. DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
  640. BBFreq += BFI->getBlockFreq(SameValueBB);
  641. return PredFreq.getFrequency() <=
  642. BBFreq.getFrequency() * FreqRatioToSkipMerge;
  643. }
  644. /// Return true if we can merge BB into DestBB if there is a single
  645. /// unconditional branch between them, and BB contains no other non-phi
  646. /// instructions.
  647. bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
  648. const BasicBlock *DestBB) const {
  649. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  650. // the successor. If there are more complex condition (e.g. preheaders),
  651. // don't mess around with them.
  652. BasicBlock::const_iterator BBI = BB->begin();
  653. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  654. for (const User *U : PN->users()) {
  655. const Instruction *UI = cast<Instruction>(U);
  656. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  657. return false;
  658. // If User is inside DestBB block and it is a PHINode then check
  659. // incoming value. If incoming value is not from BB then this is
  660. // a complex condition (e.g. preheaders) we want to avoid here.
  661. if (UI->getParent() == DestBB) {
  662. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  663. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  664. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  665. if (Insn && Insn->getParent() == BB &&
  666. Insn->getParent() != UPN->getIncomingBlock(I))
  667. return false;
  668. }
  669. }
  670. }
  671. }
  672. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  673. // and DestBB may have conflicting incoming values for the block. If so, we
  674. // can't merge the block.
  675. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  676. if (!DestBBPN) return true; // no conflict.
  677. // Collect the preds of BB.
  678. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  679. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  680. // It is faster to get preds from a PHI than with pred_iterator.
  681. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  682. BBPreds.insert(BBPN->getIncomingBlock(i));
  683. } else {
  684. BBPreds.insert(pred_begin(BB), pred_end(BB));
  685. }
  686. // Walk the preds of DestBB.
  687. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  688. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  689. if (BBPreds.count(Pred)) { // Common predecessor?
  690. BBI = DestBB->begin();
  691. while (const PHINode *PN = dyn_cast<PHINode>(BBI++)) {
  692. const Value *V1 = PN->getIncomingValueForBlock(Pred);
  693. const Value *V2 = PN->getIncomingValueForBlock(BB);
  694. // If V2 is a phi node in BB, look up what the mapped value will be.
  695. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  696. if (V2PN->getParent() == BB)
  697. V2 = V2PN->getIncomingValueForBlock(Pred);
  698. // If there is a conflict, bail out.
  699. if (V1 != V2) return false;
  700. }
  701. }
  702. }
  703. return true;
  704. }
  705. /// Eliminate a basic block that has only phi's and an unconditional branch in
  706. /// it.
  707. void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
  708. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  709. BasicBlock *DestBB = BI->getSuccessor(0);
  710. DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
  711. // If the destination block has a single pred, then this is a trivial edge,
  712. // just collapse it.
  713. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  714. if (SinglePred != DestBB) {
  715. // Remember if SinglePred was the entry block of the function. If so, we
  716. // will need to move BB back to the entry position.
  717. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  718. MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
  719. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  720. BB->moveBefore(&BB->getParent()->getEntryBlock());
  721. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  722. return;
  723. }
  724. }
  725. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  726. // to handle the new incoming edges it is about to have.
  727. PHINode *PN;
  728. for (BasicBlock::iterator BBI = DestBB->begin();
  729. (PN = dyn_cast<PHINode>(BBI)); ++BBI) {
  730. // Remove the incoming value for BB, and remember it.
  731. Value *InVal = PN->removeIncomingValue(BB, false);
  732. // Two options: either the InVal is a phi node defined in BB or it is some
  733. // value that dominates BB.
  734. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  735. if (InValPhi && InValPhi->getParent() == BB) {
  736. // Add all of the input values of the input PHI as inputs of this phi.
  737. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  738. PN->addIncoming(InValPhi->getIncomingValue(i),
  739. InValPhi->getIncomingBlock(i));
  740. } else {
  741. // Otherwise, add one instance of the dominating value for each edge that
  742. // we will be adding.
  743. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  744. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  745. PN->addIncoming(InVal, BBPN->getIncomingBlock(i));
  746. } else {
  747. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  748. PN->addIncoming(InVal, *PI);
  749. }
  750. }
  751. }
  752. // The PHIs are now updated, change everything that refers to BB to use
  753. // DestBB and remove BB.
  754. BB->replaceAllUsesWith(DestBB);
  755. BB->eraseFromParent();
  756. ++NumBlocksElim;
  757. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  758. }
  759. // Computes a map of base pointer relocation instructions to corresponding
  760. // derived pointer relocation instructions given a vector of all relocate calls
  761. static void computeBaseDerivedRelocateMap(
  762. const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
  763. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
  764. &RelocateInstMap) {
  765. // Collect information in two maps: one primarily for locating the base object
  766. // while filling the second map; the second map is the final structure holding
  767. // a mapping between Base and corresponding Derived relocate calls
  768. DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
  769. for (auto *ThisRelocate : AllRelocateCalls) {
  770. auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
  771. ThisRelocate->getDerivedPtrIndex());
  772. RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
  773. }
  774. for (auto &Item : RelocateIdxMap) {
  775. std::pair<unsigned, unsigned> Key = Item.first;
  776. if (Key.first == Key.second)
  777. // Base relocation: nothing to insert
  778. continue;
  779. GCRelocateInst *I = Item.second;
  780. auto BaseKey = std::make_pair(Key.first, Key.first);
  781. // We're iterating over RelocateIdxMap so we cannot modify it.
  782. auto MaybeBase = RelocateIdxMap.find(BaseKey);
  783. if (MaybeBase == RelocateIdxMap.end())
  784. // TODO: We might want to insert a new base object relocate and gep off
  785. // that, if there are enough derived object relocates.
  786. continue;
  787. RelocateInstMap[MaybeBase->second].push_back(I);
  788. }
  789. }
  790. // Accepts a GEP and extracts the operands into a vector provided they're all
  791. // small integer constants
  792. static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
  793. SmallVectorImpl<Value *> &OffsetV) {
  794. for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
  795. // Only accept small constant integer operands
  796. auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
  797. if (!Op || Op->getZExtValue() > 20)
  798. return false;
  799. }
  800. for (unsigned i = 1; i < GEP->getNumOperands(); i++)
  801. OffsetV.push_back(GEP->getOperand(i));
  802. return true;
  803. }
  804. // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
  805. // replace, computes a replacement, and affects it.
  806. static bool
  807. simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
  808. const SmallVectorImpl<GCRelocateInst *> &Targets) {
  809. bool MadeChange = false;
  810. for (GCRelocateInst *ToReplace : Targets) {
  811. assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
  812. "Not relocating a derived object of the original base object");
  813. if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
  814. // A duplicate relocate call. TODO: coalesce duplicates.
  815. continue;
  816. }
  817. if (RelocatedBase->getParent() != ToReplace->getParent()) {
  818. // Base and derived relocates are in different basic blocks.
  819. // In this case transform is only valid when base dominates derived
  820. // relocate. However it would be too expensive to check dominance
  821. // for each such relocate, so we skip the whole transformation.
  822. continue;
  823. }
  824. Value *Base = ToReplace->getBasePtr();
  825. auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
  826. if (!Derived || Derived->getPointerOperand() != Base)
  827. continue;
  828. SmallVector<Value *, 2> OffsetV;
  829. if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
  830. continue;
  831. // Create a Builder and replace the target callsite with a gep
  832. assert(RelocatedBase->getNextNode() &&
  833. "Should always have one since it's not a terminator");
  834. // Insert after RelocatedBase
  835. IRBuilder<> Builder(RelocatedBase->getNextNode());
  836. Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
  837. // If gc_relocate does not match the actual type, cast it to the right type.
  838. // In theory, there must be a bitcast after gc_relocate if the type does not
  839. // match, and we should reuse it to get the derived pointer. But it could be
  840. // cases like this:
  841. // bb1:
  842. // ...
  843. // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  844. // br label %merge
  845. //
  846. // bb2:
  847. // ...
  848. // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  849. // br label %merge
  850. //
  851. // merge:
  852. // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
  853. // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
  854. //
  855. // In this case, we can not find the bitcast any more. So we insert a new bitcast
  856. // no matter there is already one or not. In this way, we can handle all cases, and
  857. // the extra bitcast should be optimized away in later passes.
  858. Value *ActualRelocatedBase = RelocatedBase;
  859. if (RelocatedBase->getType() != Base->getType()) {
  860. ActualRelocatedBase =
  861. Builder.CreateBitCast(RelocatedBase, Base->getType());
  862. }
  863. Value *Replacement = Builder.CreateGEP(
  864. Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
  865. Replacement->takeName(ToReplace);
  866. // If the newly generated derived pointer's type does not match the original derived
  867. // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
  868. Value *ActualReplacement = Replacement;
  869. if (Replacement->getType() != ToReplace->getType()) {
  870. ActualReplacement =
  871. Builder.CreateBitCast(Replacement, ToReplace->getType());
  872. }
  873. ToReplace->replaceAllUsesWith(ActualReplacement);
  874. ToReplace->eraseFromParent();
  875. MadeChange = true;
  876. }
  877. return MadeChange;
  878. }
  879. // Turns this:
  880. //
  881. // %base = ...
  882. // %ptr = gep %base + 15
  883. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  884. // %base' = relocate(%tok, i32 4, i32 4)
  885. // %ptr' = relocate(%tok, i32 4, i32 5)
  886. // %val = load %ptr'
  887. //
  888. // into this:
  889. //
  890. // %base = ...
  891. // %ptr = gep %base + 15
  892. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  893. // %base' = gc.relocate(%tok, i32 4, i32 4)
  894. // %ptr' = gep %base' + 15
  895. // %val = load %ptr'
  896. bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
  897. bool MadeChange = false;
  898. SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
  899. for (auto *U : I.users())
  900. if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
  901. // Collect all the relocate calls associated with a statepoint
  902. AllRelocateCalls.push_back(Relocate);
  903. // We need atleast one base pointer relocation + one derived pointer
  904. // relocation to mangle
  905. if (AllRelocateCalls.size() < 2)
  906. return false;
  907. // RelocateInstMap is a mapping from the base relocate instruction to the
  908. // corresponding derived relocate instructions
  909. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
  910. computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
  911. if (RelocateInstMap.empty())
  912. return false;
  913. for (auto &Item : RelocateInstMap)
  914. // Item.first is the RelocatedBase to offset against
  915. // Item.second is the vector of Targets to replace
  916. MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
  917. return MadeChange;
  918. }
  919. /// SinkCast - Sink the specified cast instruction into its user blocks
  920. static bool SinkCast(CastInst *CI) {
  921. BasicBlock *DefBB = CI->getParent();
  922. /// InsertedCasts - Only insert a cast in each block once.
  923. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  924. bool MadeChange = false;
  925. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  926. UI != E; ) {
  927. Use &TheUse = UI.getUse();
  928. Instruction *User = cast<Instruction>(*UI);
  929. // Figure out which BB this cast is used in. For PHI's this is the
  930. // appropriate predecessor block.
  931. BasicBlock *UserBB = User->getParent();
  932. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  933. UserBB = PN->getIncomingBlock(TheUse);
  934. }
  935. // Preincrement use iterator so we don't invalidate it.
  936. ++UI;
  937. // The first insertion point of a block containing an EH pad is after the
  938. // pad. If the pad is the user, we cannot sink the cast past the pad.
  939. if (User->isEHPad())
  940. continue;
  941. // If the block selected to receive the cast is an EH pad that does not
  942. // allow non-PHI instructions before the terminator, we can't sink the
  943. // cast.
  944. if (UserBB->getTerminator()->isEHPad())
  945. continue;
  946. // If this user is in the same block as the cast, don't change the cast.
  947. if (UserBB == DefBB) continue;
  948. // If we have already inserted a cast into this block, use it.
  949. CastInst *&InsertedCast = InsertedCasts[UserBB];
  950. if (!InsertedCast) {
  951. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  952. assert(InsertPt != UserBB->end());
  953. InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
  954. CI->getType(), "", &*InsertPt);
  955. }
  956. // Replace a use of the cast with a use of the new cast.
  957. TheUse = InsertedCast;
  958. MadeChange = true;
  959. ++NumCastUses;
  960. }
  961. // If we removed all uses, nuke the cast.
  962. if (CI->use_empty()) {
  963. CI->eraseFromParent();
  964. MadeChange = true;
  965. }
  966. return MadeChange;
  967. }
  968. /// If the specified cast instruction is a noop copy (e.g. it's casting from
  969. /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
  970. /// reduce the number of virtual registers that must be created and coalesced.
  971. ///
  972. /// Return true if any changes are made.
  973. ///
  974. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
  975. const DataLayout &DL) {
  976. // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
  977. // than sinking only nop casts, but is helpful on some platforms.
  978. if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
  979. if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
  980. ASC->getDestAddressSpace()))
  981. return false;
  982. }
  983. // If this is a noop copy,
  984. EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  985. EVT DstVT = TLI.getValueType(DL, CI->getType());
  986. // This is an fp<->int conversion?
  987. if (SrcVT.isInteger() != DstVT.isInteger())
  988. return false;
  989. // If this is an extension, it will be a zero or sign extension, which
  990. // isn't a noop.
  991. if (SrcVT.bitsLT(DstVT)) return false;
  992. // If these values will be promoted, find out what they will be promoted
  993. // to. This helps us consider truncates on PPC as noop copies when they
  994. // are.
  995. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  996. TargetLowering::TypePromoteInteger)
  997. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  998. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  999. TargetLowering::TypePromoteInteger)
  1000. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  1001. // If, after promotion, these are the same types, this is a noop copy.
  1002. if (SrcVT != DstVT)
  1003. return false;
  1004. return SinkCast(CI);
  1005. }
  1006. /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
  1007. /// possible.
  1008. ///
  1009. /// Return true if any changes were made.
  1010. static bool CombineUAddWithOverflow(CmpInst *CI) {
  1011. Value *A, *B;
  1012. Instruction *AddI;
  1013. if (!match(CI,
  1014. m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
  1015. return false;
  1016. Type *Ty = AddI->getType();
  1017. if (!isa<IntegerType>(Ty))
  1018. return false;
  1019. // We don't want to move around uses of condition values this late, so we we
  1020. // check if it is legal to create the call to the intrinsic in the basic
  1021. // block containing the icmp:
  1022. if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
  1023. return false;
  1024. #ifndef NDEBUG
  1025. // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
  1026. // for now:
  1027. if (AddI->hasOneUse())
  1028. assert(*AddI->user_begin() == CI && "expected!");
  1029. #endif
  1030. Module *M = CI->getModule();
  1031. Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
  1032. auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
  1033. auto *UAddWithOverflow =
  1034. CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
  1035. auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
  1036. auto *Overflow =
  1037. ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
  1038. CI->replaceAllUsesWith(Overflow);
  1039. AddI->replaceAllUsesWith(UAdd);
  1040. CI->eraseFromParent();
  1041. AddI->eraseFromParent();
  1042. return true;
  1043. }
  1044. /// Sink the given CmpInst into user blocks to reduce the number of virtual
  1045. /// registers that must be created and coalesced. This is a clear win except on
  1046. /// targets with multiple condition code registers (PowerPC), where it might
  1047. /// lose; some adjustment may be wanted there.
  1048. ///
  1049. /// Return true if any changes are made.
  1050. static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
  1051. BasicBlock *DefBB = CI->getParent();
  1052. // Avoid sinking soft-FP comparisons, since this can move them into a loop.
  1053. if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
  1054. return false;
  1055. // Only insert a cmp in each block once.
  1056. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  1057. bool MadeChange = false;
  1058. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  1059. UI != E; ) {
  1060. Use &TheUse = UI.getUse();
  1061. Instruction *User = cast<Instruction>(*UI);
  1062. // Preincrement use iterator so we don't invalidate it.
  1063. ++UI;
  1064. // Don't bother for PHI nodes.
  1065. if (isa<PHINode>(User))
  1066. continue;
  1067. // Figure out which BB this cmp is used in.
  1068. BasicBlock *UserBB = User->getParent();
  1069. // If this user is in the same block as the cmp, don't change the cmp.
  1070. if (UserBB == DefBB) continue;
  1071. // If we have already inserted a cmp into this block, use it.
  1072. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  1073. if (!InsertedCmp) {
  1074. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1075. assert(InsertPt != UserBB->end());
  1076. InsertedCmp =
  1077. CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
  1078. CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
  1079. // Propagate the debug info.
  1080. InsertedCmp->setDebugLoc(CI->getDebugLoc());
  1081. }
  1082. // Replace a use of the cmp with a use of the new cmp.
  1083. TheUse = InsertedCmp;
  1084. MadeChange = true;
  1085. ++NumCmpUses;
  1086. }
  1087. // If we removed all uses, nuke the cmp.
  1088. if (CI->use_empty()) {
  1089. CI->eraseFromParent();
  1090. MadeChange = true;
  1091. }
  1092. return MadeChange;
  1093. }
  1094. static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
  1095. if (SinkCmpExpression(CI, TLI))
  1096. return true;
  1097. if (CombineUAddWithOverflow(CI))
  1098. return true;
  1099. return false;
  1100. }
  1101. /// Duplicate and sink the given 'and' instruction into user blocks where it is
  1102. /// used in a compare to allow isel to generate better code for targets where
  1103. /// this operation can be combined.
  1104. ///
  1105. /// Return true if any changes are made.
  1106. static bool sinkAndCmp0Expression(Instruction *AndI,
  1107. const TargetLowering &TLI,
  1108. SetOfInstrs &InsertedInsts) {
  1109. // Double-check that we're not trying to optimize an instruction that was
  1110. // already optimized by some other part of this pass.
  1111. assert(!InsertedInsts.count(AndI) &&
  1112. "Attempting to optimize already optimized and instruction");
  1113. (void) InsertedInsts;
  1114. // Nothing to do for single use in same basic block.
  1115. if (AndI->hasOneUse() &&
  1116. AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
  1117. return false;
  1118. // Try to avoid cases where sinking/duplicating is likely to increase register
  1119. // pressure.
  1120. if (!isa<ConstantInt>(AndI->getOperand(0)) &&
  1121. !isa<ConstantInt>(AndI->getOperand(1)) &&
  1122. AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
  1123. return false;
  1124. for (auto *U : AndI->users()) {
  1125. Instruction *User = cast<Instruction>(U);
  1126. // Only sink for and mask feeding icmp with 0.
  1127. if (!isa<ICmpInst>(User))
  1128. return false;
  1129. auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
  1130. if (!CmpC || !CmpC->isZero())
  1131. return false;
  1132. }
  1133. if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
  1134. return false;
  1135. DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
  1136. DEBUG(AndI->getParent()->dump());
  1137. // Push the 'and' into the same block as the icmp 0. There should only be
  1138. // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
  1139. // others, so we don't need to keep track of which BBs we insert into.
  1140. for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
  1141. UI != E; ) {
  1142. Use &TheUse = UI.getUse();
  1143. Instruction *User = cast<Instruction>(*UI);
  1144. // Preincrement use iterator so we don't invalidate it.
  1145. ++UI;
  1146. DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
  1147. // Keep the 'and' in the same place if the use is already in the same block.
  1148. Instruction *InsertPt =
  1149. User->getParent() == AndI->getParent() ? AndI : User;
  1150. Instruction *InsertedAnd =
  1151. BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
  1152. AndI->getOperand(1), "", InsertPt);
  1153. // Propagate the debug info.
  1154. InsertedAnd->setDebugLoc(AndI->getDebugLoc());
  1155. // Replace a use of the 'and' with a use of the new 'and'.
  1156. TheUse = InsertedAnd;
  1157. ++NumAndUses;
  1158. DEBUG(User->getParent()->dump());
  1159. }
  1160. // We removed all uses, nuke the and.
  1161. AndI->eraseFromParent();
  1162. return true;
  1163. }
  1164. /// Check if the candidates could be combined with a shift instruction, which
  1165. /// includes:
  1166. /// 1. Truncate instruction
  1167. /// 2. And instruction and the imm is a mask of the low bits:
  1168. /// imm & (imm+1) == 0
  1169. static bool isExtractBitsCandidateUse(Instruction *User) {
  1170. if (!isa<TruncInst>(User)) {
  1171. if (User->getOpcode() != Instruction::And ||
  1172. !isa<ConstantInt>(User->getOperand(1)))
  1173. return false;
  1174. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  1175. if ((Cimm & (Cimm + 1)).getBoolValue())
  1176. return false;
  1177. }
  1178. return true;
  1179. }
  1180. /// Sink both shift and truncate instruction to the use of truncate's BB.
  1181. static bool
  1182. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  1183. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  1184. const TargetLowering &TLI, const DataLayout &DL) {
  1185. BasicBlock *UserBB = User->getParent();
  1186. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  1187. TruncInst *TruncI = dyn_cast<TruncInst>(User);
  1188. bool MadeChange = false;
  1189. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  1190. TruncE = TruncI->user_end();
  1191. TruncUI != TruncE;) {
  1192. Use &TruncTheUse = TruncUI.getUse();
  1193. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  1194. // Preincrement use iterator so we don't invalidate it.
  1195. ++TruncUI;
  1196. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  1197. if (!ISDOpcode)
  1198. continue;
  1199. // If the use is actually a legal node, there will not be an
  1200. // implicit truncate.
  1201. // FIXME: always querying the result type is just an
  1202. // approximation; some nodes' legality is determined by the
  1203. // operand or other means. There's no good way to find out though.
  1204. if (TLI.isOperationLegalOrCustom(
  1205. ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
  1206. continue;
  1207. // Don't bother for PHI nodes.
  1208. if (isa<PHINode>(TruncUser))
  1209. continue;
  1210. BasicBlock *TruncUserBB = TruncUser->getParent();
  1211. if (UserBB == TruncUserBB)
  1212. continue;
  1213. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  1214. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  1215. if (!InsertedShift && !InsertedTrunc) {
  1216. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  1217. assert(InsertPt != TruncUserBB->end());
  1218. // Sink the shift
  1219. if (ShiftI->getOpcode() == Instruction::AShr)
  1220. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1221. "", &*InsertPt);
  1222. else
  1223. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1224. "", &*InsertPt);
  1225. // Sink the trunc
  1226. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  1227. TruncInsertPt++;
  1228. assert(TruncInsertPt != TruncUserBB->end());
  1229. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  1230. TruncI->getType(), "", &*TruncInsertPt);
  1231. MadeChange = true;
  1232. TruncTheUse = InsertedTrunc;
  1233. }
  1234. }
  1235. return MadeChange;
  1236. }
  1237. /// Sink the shift *right* instruction into user blocks if the uses could
  1238. /// potentially be combined with this shift instruction and generate BitExtract
  1239. /// instruction. It will only be applied if the architecture supports BitExtract
  1240. /// instruction. Here is an example:
  1241. /// BB1:
  1242. /// %x.extract.shift = lshr i64 %arg1, 32
  1243. /// BB2:
  1244. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  1245. /// ==>
  1246. ///
  1247. /// BB2:
  1248. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  1249. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  1250. ///
  1251. /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
  1252. /// instruction.
  1253. /// Return true if any changes are made.
  1254. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  1255. const TargetLowering &TLI,
  1256. const DataLayout &DL) {
  1257. BasicBlock *DefBB = ShiftI->getParent();
  1258. /// Only insert instructions in each block once.
  1259. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  1260. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
  1261. bool MadeChange = false;
  1262. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  1263. UI != E;) {
  1264. Use &TheUse = UI.getUse();
  1265. Instruction *User = cast<Instruction>(*UI);
  1266. // Preincrement use iterator so we don't invalidate it.
  1267. ++UI;
  1268. // Don't bother for PHI nodes.
  1269. if (isa<PHINode>(User))
  1270. continue;
  1271. if (!isExtractBitsCandidateUse(User))
  1272. continue;
  1273. BasicBlock *UserBB = User->getParent();
  1274. if (UserBB == DefBB) {
  1275. // If the shift and truncate instruction are in the same BB. The use of
  1276. // the truncate(TruncUse) may still introduce another truncate if not
  1277. // legal. In this case, we would like to sink both shift and truncate
  1278. // instruction to the BB of TruncUse.
  1279. // for example:
  1280. // BB1:
  1281. // i64 shift.result = lshr i64 opnd, imm
  1282. // trunc.result = trunc shift.result to i16
  1283. //
  1284. // BB2:
  1285. // ----> We will have an implicit truncate here if the architecture does
  1286. // not have i16 compare.
  1287. // cmp i16 trunc.result, opnd2
  1288. //
  1289. if (isa<TruncInst>(User) && shiftIsLegal
  1290. // If the type of the truncate is legal, no trucate will be
  1291. // introduced in other basic blocks.
  1292. &&
  1293. (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
  1294. MadeChange =
  1295. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
  1296. continue;
  1297. }
  1298. // If we have already inserted a shift into this block, use it.
  1299. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  1300. if (!InsertedShift) {
  1301. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1302. assert(InsertPt != UserBB->end());
  1303. if (ShiftI->getOpcode() == Instruction::AShr)
  1304. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1305. "", &*InsertPt);
  1306. else
  1307. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1308. "", &*InsertPt);
  1309. MadeChange = true;
  1310. }
  1311. // Replace a use of the shift with a use of the new shift.
  1312. TheUse = InsertedShift;
  1313. }
  1314. // If we removed all uses, nuke the shift.
  1315. if (ShiftI->use_empty())
  1316. ShiftI->eraseFromParent();
  1317. return MadeChange;
  1318. }
  1319. /// If counting leading or trailing zeros is an expensive operation and a zero
  1320. /// input is defined, add a check for zero to avoid calling the intrinsic.
  1321. ///
  1322. /// We want to transform:
  1323. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
  1324. ///
  1325. /// into:
  1326. /// entry:
  1327. /// %cmpz = icmp eq i64 %A, 0
  1328. /// br i1 %cmpz, label %cond.end, label %cond.false
  1329. /// cond.false:
  1330. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
  1331. /// br label %cond.end
  1332. /// cond.end:
  1333. /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
  1334. ///
  1335. /// If the transform is performed, return true and set ModifiedDT to true.
  1336. static bool despeculateCountZeros(IntrinsicInst *CountZeros,
  1337. const TargetLowering *TLI,
  1338. const DataLayout *DL,
  1339. bool &ModifiedDT) {
  1340. if (!TLI || !DL)
  1341. return false;
  1342. // If a zero input is undefined, it doesn't make sense to despeculate that.
  1343. if (match(CountZeros->getOperand(1), m_One()))
  1344. return false;
  1345. // If it's cheap to speculate, there's nothing to do.
  1346. auto IntrinsicID = CountZeros->getIntrinsicID();
  1347. if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
  1348. (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
  1349. return false;
  1350. // Only handle legal scalar cases. Anything else requires too much work.
  1351. Type *Ty = CountZeros->getType();
  1352. unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
  1353. if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
  1354. return false;
  1355. // The intrinsic will be sunk behind a compare against zero and branch.
  1356. BasicBlock *StartBlock = CountZeros->getParent();
  1357. BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
  1358. // Create another block after the count zero intrinsic. A PHI will be added
  1359. // in this block to select the result of the intrinsic or the bit-width
  1360. // constant if the input to the intrinsic is zero.
  1361. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
  1362. BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
  1363. // Set up a builder to create a compare, conditional branch, and PHI.
  1364. IRBuilder<> Builder(CountZeros->getContext());
  1365. Builder.SetInsertPoint(StartBlock->getTerminator());
  1366. Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
  1367. // Replace the unconditional branch that was created by the first split with
  1368. // a compare against zero and a conditional branch.
  1369. Value *Zero = Constant::getNullValue(Ty);
  1370. Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
  1371. Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
  1372. StartBlock->getTerminator()->eraseFromParent();
  1373. // Create a PHI in the end block to select either the output of the intrinsic
  1374. // or the bit width of the operand.
  1375. Builder.SetInsertPoint(&EndBlock->front());
  1376. PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
  1377. CountZeros->replaceAllUsesWith(PN);
  1378. Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
  1379. PN->addIncoming(BitWidth, StartBlock);
  1380. PN->addIncoming(CountZeros, CallBlock);
  1381. // We are explicitly handling the zero case, so we can set the intrinsic's
  1382. // undefined zero argument to 'true'. This will also prevent reprocessing the
  1383. // intrinsic; we only despeculate when a zero input is defined.
  1384. CountZeros->setArgOperand(1, Builder.getTrue());
  1385. ModifiedDT = true;
  1386. return true;
  1387. }
  1388. bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool& ModifiedDT) {
  1389. BasicBlock *BB = CI->getParent();
  1390. // Lower inline assembly if we can.
  1391. // If we found an inline asm expession, and if the target knows how to
  1392. // lower it to normal LLVM code, do so now.
  1393. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  1394. if (TLI->ExpandInlineAsm(CI)) {
  1395. // Avoid invalidating the iterator.
  1396. CurInstIterator = BB->begin();
  1397. // Avoid processing instructions out of order, which could cause
  1398. // reuse before a value is defined.
  1399. SunkAddrs.clear();
  1400. return true;
  1401. }
  1402. // Sink address computing for memory operands into the block.
  1403. if (optimizeInlineAsmInst(CI))
  1404. return true;
  1405. }
  1406. // Align the pointer arguments to this call if the target thinks it's a good
  1407. // idea
  1408. unsigned MinSize, PrefAlign;
  1409. if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
  1410. for (auto &Arg : CI->arg_operands()) {
  1411. // We want to align both objects whose address is used directly and
  1412. // objects whose address is used in casts and GEPs, though it only makes
  1413. // sense for GEPs if the offset is a multiple of the desired alignment and
  1414. // if size - offset meets the size threshold.
  1415. if (!Arg->getType()->isPointerTy())
  1416. continue;
  1417. APInt Offset(DL->getPointerSizeInBits(
  1418. cast<PointerType>(Arg->getType())->getAddressSpace()),
  1419. 0);
  1420. Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
  1421. uint64_t Offset2 = Offset.getLimitedValue();
  1422. if ((Offset2 & (PrefAlign-1)) != 0)
  1423. continue;
  1424. AllocaInst *AI;
  1425. if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
  1426. DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
  1427. AI->setAlignment(PrefAlign);
  1428. // Global variables can only be aligned if they are defined in this
  1429. // object (i.e. they are uniquely initialized in this object), and
  1430. // over-aligning global variables that have an explicit section is
  1431. // forbidden.
  1432. GlobalVariable *GV;
  1433. if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
  1434. GV->getPointerAlignment(*DL) < PrefAlign &&
  1435. DL->getTypeAllocSize(GV->getValueType()) >=
  1436. MinSize + Offset2)
  1437. GV->setAlignment(PrefAlign);
  1438. }
  1439. // If this is a memcpy (or similar) then we may be able to improve the
  1440. // alignment
  1441. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
  1442. unsigned Align = getKnownAlignment(MI->getDest(), *DL);
  1443. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI))
  1444. Align = std::min(Align, getKnownAlignment(MTI->getSource(), *DL));
  1445. if (Align > MI->getAlignment())
  1446. MI->setAlignment(ConstantInt::get(MI->getAlignmentType(), Align));
  1447. }
  1448. }
  1449. // If we have a cold call site, try to sink addressing computation into the
  1450. // cold block. This interacts with our handling for loads and stores to
  1451. // ensure that we can fold all uses of a potential addressing computation
  1452. // into their uses. TODO: generalize this to work over profiling data
  1453. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  1454. for (auto &Arg : CI->arg_operands()) {
  1455. if (!Arg->getType()->isPointerTy())
  1456. continue;
  1457. unsigned AS = Arg->getType()->getPointerAddressSpace();
  1458. return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
  1459. }
  1460. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  1461. if (II) {
  1462. switch (II->getIntrinsicID()) {
  1463. default: break;
  1464. case Intrinsic::objectsize: {
  1465. // Lower all uses of llvm.objectsize.*
  1466. ConstantInt *RetVal =
  1467. lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
  1468. // Substituting this can cause recursive simplifications, which can
  1469. // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
  1470. // this
  1471. // happens.
  1472. Value *CurValue = &*CurInstIterator;
  1473. WeakTrackingVH IterHandle(CurValue);
  1474. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1475. // If the iterator instruction was recursively deleted, start over at the
  1476. // start of the block.
  1477. if (IterHandle != CurValue) {
  1478. CurInstIterator = BB->begin();
  1479. SunkAddrs.clear();
  1480. }
  1481. return true;
  1482. }
  1483. case Intrinsic::aarch64_stlxr:
  1484. case Intrinsic::aarch64_stxr: {
  1485. ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
  1486. if (!ExtVal || !ExtVal->hasOneUse() ||
  1487. ExtVal->getParent() == CI->getParent())
  1488. return false;
  1489. // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
  1490. ExtVal->moveBefore(CI);
  1491. // Mark this instruction as "inserted by CGP", so that other
  1492. // optimizations don't touch it.
  1493. InsertedInsts.insert(ExtVal);
  1494. return true;
  1495. }
  1496. case Intrinsic::invariant_group_barrier:
  1497. II->replaceAllUsesWith(II->getArgOperand(0));
  1498. II->eraseFromParent();
  1499. return true;
  1500. case Intrinsic::cttz:
  1501. case Intrinsic::ctlz:
  1502. // If counting zeros is expensive, try to avoid it.
  1503. return despeculateCountZeros(II, TLI, DL, ModifiedDT);
  1504. }
  1505. if (TLI) {
  1506. SmallVector<Value*, 2> PtrOps;
  1507. Type *AccessTy;
  1508. if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
  1509. while (!PtrOps.empty()) {
  1510. Value *PtrVal = PtrOps.pop_back_val();
  1511. unsigned AS = PtrVal->getType()->getPointerAddressSpace();
  1512. if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
  1513. return true;
  1514. }
  1515. }
  1516. }
  1517. // From here on out we're working with named functions.
  1518. if (!CI->getCalledFunction()) return false;
  1519. // Lower all default uses of _chk calls. This is very similar
  1520. // to what InstCombineCalls does, but here we are only lowering calls
  1521. // to fortified library functions (e.g. __memcpy_chk) that have the default
  1522. // "don't know" as the objectsize. Anything else should be left alone.
  1523. FortifiedLibCallSimplifier Simplifier(TLInfo, true);
  1524. if (Value *V = Simplifier.optimizeCall(CI)) {
  1525. CI->replaceAllUsesWith(V);
  1526. CI->eraseFromParent();
  1527. return true;
  1528. }
  1529. return false;
  1530. }
  1531. /// Look for opportunities to duplicate return instructions to the predecessor
  1532. /// to enable tail call optimizations. The case it is currently looking for is:
  1533. /// @code
  1534. /// bb0:
  1535. /// %tmp0 = tail call i32 @f0()
  1536. /// br label %return
  1537. /// bb1:
  1538. /// %tmp1 = tail call i32 @f1()
  1539. /// br label %return
  1540. /// bb2:
  1541. /// %tmp2 = tail call i32 @f2()
  1542. /// br label %return
  1543. /// return:
  1544. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  1545. /// ret i32 %retval
  1546. /// @endcode
  1547. ///
  1548. /// =>
  1549. ///
  1550. /// @code
  1551. /// bb0:
  1552. /// %tmp0 = tail call i32 @f0()
  1553. /// ret i32 %tmp0
  1554. /// bb1:
  1555. /// %tmp1 = tail call i32 @f1()
  1556. /// ret i32 %tmp1
  1557. /// bb2:
  1558. /// %tmp2 = tail call i32 @f2()
  1559. /// ret i32 %tmp2
  1560. /// @endcode
  1561. bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
  1562. if (!TLI)
  1563. return false;
  1564. ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
  1565. if (!RetI)
  1566. return false;
  1567. PHINode *PN = nullptr;
  1568. BitCastInst *BCI = nullptr;
  1569. Value *V = RetI->getReturnValue();
  1570. if (V) {
  1571. BCI = dyn_cast<BitCastInst>(V);
  1572. if (BCI)
  1573. V = BCI->getOperand(0);
  1574. PN = dyn_cast<PHINode>(V);
  1575. if (!PN)
  1576. return false;
  1577. }
  1578. if (PN && PN->getParent() != BB)
  1579. return false;
  1580. // Make sure there are no instructions between the PHI and return, or that the
  1581. // return is the first instruction in the block.
  1582. if (PN) {
  1583. BasicBlock::iterator BI = BB->begin();
  1584. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
  1585. if (&*BI == BCI)
  1586. // Also skip over the bitcast.
  1587. ++BI;
  1588. if (&*BI != RetI)
  1589. return false;
  1590. } else {
  1591. BasicBlock::iterator BI = BB->begin();
  1592. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  1593. if (&*BI != RetI)
  1594. return false;
  1595. }
  1596. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  1597. /// call.
  1598. const Function *F = BB->getParent();
  1599. SmallVector<CallInst*, 4> TailCalls;
  1600. if (PN) {
  1601. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  1602. CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
  1603. // Make sure the phi value is indeed produced by the tail call.
  1604. if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
  1605. TLI->mayBeEmittedAsTailCall(CI) &&
  1606. attributesPermitTailCall(F, CI, RetI, *TLI))
  1607. TailCalls.push_back(CI);
  1608. }
  1609. } else {
  1610. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  1611. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  1612. if (!VisitedBBs.insert(*PI).second)
  1613. continue;
  1614. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  1615. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  1616. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  1617. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  1618. if (RI == RE)
  1619. continue;
  1620. CallInst *CI = dyn_cast<CallInst>(&*RI);
  1621. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
  1622. attributesPermitTailCall(F, CI, RetI, *TLI))
  1623. TailCalls.push_back(CI);
  1624. }
  1625. }
  1626. bool Changed = false;
  1627. for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
  1628. CallInst *CI = TailCalls[i];
  1629. CallSite CS(CI);
  1630. // Conservatively require the attributes of the call to match those of the
  1631. // return. Ignore noalias because it doesn't affect the call sequence.
  1632. AttributeList CalleeAttrs = CS.getAttributes();
  1633. if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
  1634. .removeAttribute(Attribute::NoAlias) !=
  1635. AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
  1636. .removeAttribute(Attribute::NoAlias))
  1637. continue;
  1638. // Make sure the call instruction is followed by an unconditional branch to
  1639. // the return block.
  1640. BasicBlock *CallBB = CI->getParent();
  1641. BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
  1642. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  1643. continue;
  1644. // Duplicate the return into CallBB.
  1645. (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
  1646. ModifiedDT = Changed = true;
  1647. ++NumRetsDup;
  1648. }
  1649. // If we eliminated all predecessors of the block, delete the block now.
  1650. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  1651. BB->eraseFromParent();
  1652. return Changed;
  1653. }
  1654. //===----------------------------------------------------------------------===//
  1655. // Memory Optimization
  1656. //===----------------------------------------------------------------------===//
  1657. namespace {
  1658. /// This is an extended version of TargetLowering::AddrMode
  1659. /// which holds actual Value*'s for register values.
  1660. struct ExtAddrMode : public TargetLowering::AddrMode {
  1661. Value *BaseReg;
  1662. Value *ScaledReg;
  1663. ExtAddrMode() : BaseReg(nullptr), ScaledReg(nullptr) {}
  1664. void print(raw_ostream &OS) const;
  1665. void dump() const;
  1666. bool operator==(const ExtAddrMode& O) const {
  1667. return (BaseReg == O.BaseReg) && (ScaledReg == O.ScaledReg) &&
  1668. (BaseGV == O.BaseGV) && (BaseOffs == O.BaseOffs) &&
  1669. (HasBaseReg == O.HasBaseReg) && (Scale == O.Scale);
  1670. }
  1671. };
  1672. #ifndef NDEBUG
  1673. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  1674. AM.print(OS);
  1675. return OS;
  1676. }
  1677. #endif
  1678. void ExtAddrMode::print(raw_ostream &OS) const {
  1679. bool NeedPlus = false;
  1680. OS << "[";
  1681. if (BaseGV) {
  1682. OS << (NeedPlus ? " + " : "")
  1683. << "GV:";
  1684. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  1685. NeedPlus = true;
  1686. }
  1687. if (BaseOffs) {
  1688. OS << (NeedPlus ? " + " : "")
  1689. << BaseOffs;
  1690. NeedPlus = true;
  1691. }
  1692. if (BaseReg) {
  1693. OS << (NeedPlus ? " + " : "")
  1694. << "Base:";
  1695. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  1696. NeedPlus = true;
  1697. }
  1698. if (Scale) {
  1699. OS << (NeedPlus ? " + " : "")
  1700. << Scale << "*";
  1701. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  1702. }
  1703. OS << ']';
  1704. }
  1705. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1706. LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
  1707. print(dbgs());
  1708. dbgs() << '\n';
  1709. }
  1710. #endif
  1711. /// \brief This class provides transaction based operation on the IR.
  1712. /// Every change made through this class is recorded in the internal state and
  1713. /// can be undone (rollback) until commit is called.
  1714. class TypePromotionTransaction {
  1715. /// \brief This represents the common interface of the individual transaction.
  1716. /// Each class implements the logic for doing one specific modification on
  1717. /// the IR via the TypePromotionTransaction.
  1718. class TypePromotionAction {
  1719. protected:
  1720. /// The Instruction modified.
  1721. Instruction *Inst;
  1722. public:
  1723. /// \brief Constructor of the action.
  1724. /// The constructor performs the related action on the IR.
  1725. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  1726. virtual ~TypePromotionAction() {}
  1727. /// \brief Undo the modification done by this action.
  1728. /// When this method is called, the IR must be in the same state as it was
  1729. /// before this action was applied.
  1730. /// \pre Undoing the action works if and only if the IR is in the exact same
  1731. /// state as it was directly after this action was applied.
  1732. virtual void undo() = 0;
  1733. /// \brief Advocate every change made by this action.
  1734. /// When the results on the IR of the action are to be kept, it is important
  1735. /// to call this function, otherwise hidden information may be kept forever.
  1736. virtual void commit() {
  1737. // Nothing to be done, this action is not doing anything.
  1738. }
  1739. };
  1740. /// \brief Utility to remember the position of an instruction.
  1741. class InsertionHandler {
  1742. /// Position of an instruction.
  1743. /// Either an instruction:
  1744. /// - Is the first in a basic block: BB is used.
  1745. /// - Has a previous instructon: PrevInst is used.
  1746. union {
  1747. Instruction *PrevInst;
  1748. BasicBlock *BB;
  1749. } Point;
  1750. /// Remember whether or not the instruction had a previous instruction.
  1751. bool HasPrevInstruction;
  1752. public:
  1753. /// \brief Record the position of \p Inst.
  1754. InsertionHandler(Instruction *Inst) {
  1755. BasicBlock::iterator It = Inst->getIterator();
  1756. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  1757. if (HasPrevInstruction)
  1758. Point.PrevInst = &*--It;
  1759. else
  1760. Point.BB = Inst->getParent();
  1761. }
  1762. /// \brief Insert \p Inst at the recorded position.
  1763. void insert(Instruction *Inst) {
  1764. if (HasPrevInstruction) {
  1765. if (Inst->getParent())
  1766. Inst->removeFromParent();
  1767. Inst->insertAfter(Point.PrevInst);
  1768. } else {
  1769. Instruction *Position = &*Point.BB->getFirstInsertionPt();
  1770. if (Inst->getParent())
  1771. Inst->moveBefore(Position);
  1772. else
  1773. Inst->insertBefore(Position);
  1774. }
  1775. }
  1776. };
  1777. /// \brief Move an instruction before another.
  1778. class InstructionMoveBefore : public TypePromotionAction {
  1779. /// Original position of the instruction.
  1780. InsertionHandler Position;
  1781. public:
  1782. /// \brief Move \p Inst before \p Before.
  1783. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  1784. : TypePromotionAction(Inst), Position(Inst) {
  1785. DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
  1786. Inst->moveBefore(Before);
  1787. }
  1788. /// \brief Move the instruction back to its original position.
  1789. void undo() override {
  1790. DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  1791. Position.insert(Inst);
  1792. }
  1793. };
  1794. /// \brief Set the operand of an instruction with a new value.
  1795. class OperandSetter : public TypePromotionAction {
  1796. /// Original operand of the instruction.
  1797. Value *Origin;
  1798. /// Index of the modified instruction.
  1799. unsigned Idx;
  1800. public:
  1801. /// \brief Set \p Idx operand of \p Inst with \p NewVal.
  1802. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  1803. : TypePromotionAction(Inst), Idx(Idx) {
  1804. DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  1805. << "for:" << *Inst << "\n"
  1806. << "with:" << *NewVal << "\n");
  1807. Origin = Inst->getOperand(Idx);
  1808. Inst->setOperand(Idx, NewVal);
  1809. }
  1810. /// \brief Restore the original value of the instruction.
  1811. void undo() override {
  1812. DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  1813. << "for: " << *Inst << "\n"
  1814. << "with: " << *Origin << "\n");
  1815. Inst->setOperand(Idx, Origin);
  1816. }
  1817. };
  1818. /// \brief Hide the operands of an instruction.
  1819. /// Do as if this instruction was not using any of its operands.
  1820. class OperandsHider : public TypePromotionAction {
  1821. /// The list of original operands.
  1822. SmallVector<Value *, 4> OriginalValues;
  1823. public:
  1824. /// \brief Remove \p Inst from the uses of the operands of \p Inst.
  1825. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  1826. DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  1827. unsigned NumOpnds = Inst->getNumOperands();
  1828. OriginalValues.reserve(NumOpnds);
  1829. for (unsigned It = 0; It < NumOpnds; ++It) {
  1830. // Save the current operand.
  1831. Value *Val = Inst->getOperand(It);
  1832. OriginalValues.push_back(Val);
  1833. // Set a dummy one.
  1834. // We could use OperandSetter here, but that would imply an overhead
  1835. // that we are not willing to pay.
  1836. Inst->setOperand(It, UndefValue::get(Val->getType()));
  1837. }
  1838. }
  1839. /// \brief Restore the original list of uses.
  1840. void undo() override {
  1841. DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  1842. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  1843. Inst->setOperand(It, OriginalValues[It]);
  1844. }
  1845. };
  1846. /// \brief Build a truncate instruction.
  1847. class TruncBuilder : public TypePromotionAction {
  1848. Value *Val;
  1849. public:
  1850. /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
  1851. /// result.
  1852. /// trunc Opnd to Ty.
  1853. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  1854. IRBuilder<> Builder(Opnd);
  1855. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  1856. DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  1857. }
  1858. /// \brief Get the built value.
  1859. Value *getBuiltValue() { return Val; }
  1860. /// \brief Remove the built instruction.
  1861. void undo() override {
  1862. DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  1863. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1864. IVal->eraseFromParent();
  1865. }
  1866. };
  1867. /// \brief Build a sign extension instruction.
  1868. class SExtBuilder : public TypePromotionAction {
  1869. Value *Val;
  1870. public:
  1871. /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
  1872. /// result.
  1873. /// sext Opnd to Ty.
  1874. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1875. : TypePromotionAction(InsertPt) {
  1876. IRBuilder<> Builder(InsertPt);
  1877. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  1878. DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  1879. }
  1880. /// \brief Get the built value.
  1881. Value *getBuiltValue() { return Val; }
  1882. /// \brief Remove the built instruction.
  1883. void undo() override {
  1884. DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  1885. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1886. IVal->eraseFromParent();
  1887. }
  1888. };
  1889. /// \brief Build a zero extension instruction.
  1890. class ZExtBuilder : public TypePromotionAction {
  1891. Value *Val;
  1892. public:
  1893. /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
  1894. /// result.
  1895. /// zext Opnd to Ty.
  1896. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1897. : TypePromotionAction(InsertPt) {
  1898. IRBuilder<> Builder(InsertPt);
  1899. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  1900. DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  1901. }
  1902. /// \brief Get the built value.
  1903. Value *getBuiltValue() { return Val; }
  1904. /// \brief Remove the built instruction.
  1905. void undo() override {
  1906. DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  1907. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1908. IVal->eraseFromParent();
  1909. }
  1910. };
  1911. /// \brief Mutate an instruction to another type.
  1912. class TypeMutator : public TypePromotionAction {
  1913. /// Record the original type.
  1914. Type *OrigTy;
  1915. public:
  1916. /// \brief Mutate the type of \p Inst into \p NewTy.
  1917. TypeMutator(Instruction *Inst, Type *NewTy)
  1918. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  1919. DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  1920. << "\n");
  1921. Inst->mutateType(NewTy);
  1922. }
  1923. /// \brief Mutate the instruction back to its original type.
  1924. void undo() override {
  1925. DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  1926. << "\n");
  1927. Inst->mutateType(OrigTy);
  1928. }
  1929. };
  1930. /// \brief Replace the uses of an instruction by another instruction.
  1931. class UsesReplacer : public TypePromotionAction {
  1932. /// Helper structure to keep track of the replaced uses.
  1933. struct InstructionAndIdx {
  1934. /// The instruction using the instruction.
  1935. Instruction *Inst;
  1936. /// The index where this instruction is used for Inst.
  1937. unsigned Idx;
  1938. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  1939. : Inst(Inst), Idx(Idx) {}
  1940. };
  1941. /// Keep track of the original uses (pair Instruction, Index).
  1942. SmallVector<InstructionAndIdx, 4> OriginalUses;
  1943. typedef SmallVectorImpl<InstructionAndIdx>::iterator use_iterator;
  1944. public:
  1945. /// \brief Replace all the use of \p Inst by \p New.
  1946. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  1947. DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  1948. << "\n");
  1949. // Record the original uses.
  1950. for (Use &U : Inst->uses()) {
  1951. Instruction *UserI = cast<Instruction>(U.getUser());
  1952. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  1953. }
  1954. // Now, we can replace the uses.
  1955. Inst->replaceAllUsesWith(New);
  1956. }
  1957. /// \brief Reassign the original uses of Inst to Inst.
  1958. void undo() override {
  1959. DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  1960. for (use_iterator UseIt = OriginalUses.begin(),
  1961. EndIt = OriginalUses.end();
  1962. UseIt != EndIt; ++UseIt) {
  1963. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  1964. }
  1965. }
  1966. };
  1967. /// \brief Remove an instruction from the IR.
  1968. class InstructionRemover : public TypePromotionAction {
  1969. /// Original position of the instruction.
  1970. InsertionHandler Inserter;
  1971. /// Helper structure to hide all the link to the instruction. In other
  1972. /// words, this helps to do as if the instruction was removed.
  1973. OperandsHider Hider;
  1974. /// Keep track of the uses replaced, if any.
  1975. UsesReplacer *Replacer;
  1976. /// Keep track of instructions removed.
  1977. SetOfInstrs &RemovedInsts;
  1978. public:
  1979. /// \brief Remove all reference of \p Inst and optinally replace all its
  1980. /// uses with New.
  1981. /// \p RemovedInsts Keep track of the instructions removed by this Action.
  1982. /// \pre If !Inst->use_empty(), then New != nullptr
  1983. InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
  1984. Value *New = nullptr)
  1985. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  1986. Replacer(nullptr), RemovedInsts(RemovedInsts) {
  1987. if (New)
  1988. Replacer = new UsesReplacer(Inst, New);
  1989. DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  1990. RemovedInsts.insert(Inst);
  1991. /// The instructions removed here will be freed after completing
  1992. /// optimizeBlock() for all blocks as we need to keep track of the
  1993. /// removed instructions during promotion.
  1994. Inst->removeFromParent();
  1995. }
  1996. ~InstructionRemover() override { delete Replacer; }
  1997. /// \brief Resurrect the instruction and reassign it to the proper uses if
  1998. /// new value was provided when build this action.
  1999. void undo() override {
  2000. DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  2001. Inserter.insert(Inst);
  2002. if (Replacer)
  2003. Replacer->undo();
  2004. Hider.undo();
  2005. RemovedInsts.erase(Inst);
  2006. }
  2007. };
  2008. public:
  2009. /// Restoration point.
  2010. /// The restoration point is a pointer to an action instead of an iterator
  2011. /// because the iterator may be invalidated but not the pointer.
  2012. typedef const TypePromotionAction *ConstRestorationPt;
  2013. TypePromotionTransaction(SetOfInstrs &RemovedInsts)
  2014. : RemovedInsts(RemovedInsts) {}
  2015. /// Advocate every changes made in that transaction.
  2016. void commit();
  2017. /// Undo all the changes made after the given point.
  2018. void rollback(ConstRestorationPt Point);
  2019. /// Get the current restoration point.
  2020. ConstRestorationPt getRestorationPoint() const;
  2021. /// \name API for IR modification with state keeping to support rollback.
  2022. /// @{
  2023. /// Same as Instruction::setOperand.
  2024. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  2025. /// Same as Instruction::eraseFromParent.
  2026. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  2027. /// Same as Value::replaceAllUsesWith.
  2028. void replaceAllUsesWith(Instruction *Inst, Value *New);
  2029. /// Same as Value::mutateType.
  2030. void mutateType(Instruction *Inst, Type *NewTy);
  2031. /// Same as IRBuilder::createTrunc.
  2032. Value *createTrunc(Instruction *Opnd, Type *Ty);
  2033. /// Same as IRBuilder::createSExt.
  2034. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2035. /// Same as IRBuilder::createZExt.
  2036. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2037. /// Same as Instruction::moveBefore.
  2038. void moveBefore(Instruction *Inst, Instruction *Before);
  2039. /// @}
  2040. private:
  2041. /// The ordered list of actions made so far.
  2042. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  2043. typedef SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator CommitPt;
  2044. SetOfInstrs &RemovedInsts;
  2045. };
  2046. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  2047. Value *NewVal) {
  2048. Actions.push_back(
  2049. make_unique<TypePromotionTransaction::OperandSetter>(Inst, Idx, NewVal));
  2050. }
  2051. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  2052. Value *NewVal) {
  2053. Actions.push_back(
  2054. make_unique<TypePromotionTransaction::InstructionRemover>(Inst,
  2055. RemovedInsts, NewVal));
  2056. }
  2057. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  2058. Value *New) {
  2059. Actions.push_back(make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  2060. }
  2061. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  2062. Actions.push_back(make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  2063. }
  2064. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  2065. Type *Ty) {
  2066. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  2067. Value *Val = Ptr->getBuiltValue();
  2068. Actions.push_back(std::move(Ptr));
  2069. return Val;
  2070. }
  2071. Value *TypePromotionTransaction::createSExt(Instruction *Inst,
  2072. Value *Opnd, Type *Ty) {
  2073. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  2074. Value *Val = Ptr->getBuiltValue();
  2075. Actions.push_back(std::move(Ptr));
  2076. return Val;
  2077. }
  2078. Value *TypePromotionTransaction::createZExt(Instruction *Inst,
  2079. Value *Opnd, Type *Ty) {
  2080. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  2081. Value *Val = Ptr->getBuiltValue();
  2082. Actions.push_back(std::move(Ptr));
  2083. return Val;
  2084. }
  2085. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  2086. Instruction *Before) {
  2087. Actions.push_back(
  2088. make_unique<TypePromotionTransaction::InstructionMoveBefore>(Inst, Before));
  2089. }
  2090. TypePromotionTransaction::ConstRestorationPt
  2091. TypePromotionTransaction::getRestorationPoint() const {
  2092. return !Actions.empty() ? Actions.back().get() : nullptr;
  2093. }
  2094. void TypePromotionTransaction::commit() {
  2095. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  2096. ++It)
  2097. (*It)->commit();
  2098. Actions.clear();
  2099. }
  2100. void TypePromotionTransaction::rollback(
  2101. TypePromotionTransaction::ConstRestorationPt Point) {
  2102. while (!Actions.empty() && Point != Actions.back().get()) {
  2103. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  2104. Curr->undo();
  2105. }
  2106. }
  2107. /// \brief A helper class for matching addressing modes.
  2108. ///
  2109. /// This encapsulates the logic for matching the target-legal addressing modes.
  2110. class AddressingModeMatcher {
  2111. SmallVectorImpl<Instruction*> &AddrModeInsts;
  2112. const TargetLowering &TLI;
  2113. const TargetRegisterInfo &TRI;
  2114. const DataLayout &DL;
  2115. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  2116. /// the memory instruction that we're computing this address for.
  2117. Type *AccessTy;
  2118. unsigned AddrSpace;
  2119. Instruction *MemoryInst;
  2120. /// This is the addressing mode that we're building up. This is
  2121. /// part of the return value of this addressing mode matching stuff.
  2122. ExtAddrMode &AddrMode;
  2123. /// The instructions inserted by other CodeGenPrepare optimizations.
  2124. const SetOfInstrs &InsertedInsts;
  2125. /// A map from the instructions to their type before promotion.
  2126. InstrToOrigTy &PromotedInsts;
  2127. /// The ongoing transaction where every action should be registered.
  2128. TypePromotionTransaction &TPT;
  2129. /// This is set to true when we should not do profitability checks.
  2130. /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
  2131. bool IgnoreProfitability;
  2132. AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
  2133. const TargetLowering &TLI,
  2134. const TargetRegisterInfo &TRI,
  2135. Type *AT, unsigned AS,
  2136. Instruction *MI, ExtAddrMode &AM,
  2137. const SetOfInstrs &InsertedInsts,
  2138. InstrToOrigTy &PromotedInsts,
  2139. TypePromotionTransaction &TPT)
  2140. : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
  2141. DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
  2142. MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
  2143. PromotedInsts(PromotedInsts), TPT(TPT) {
  2144. IgnoreProfitability = false;
  2145. }
  2146. public:
  2147. /// Find the maximal addressing mode that a load/store of V can fold,
  2148. /// give an access type of AccessTy. This returns a list of involved
  2149. /// instructions in AddrModeInsts.
  2150. /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
  2151. /// optimizations.
  2152. /// \p PromotedInsts maps the instructions to their type before promotion.
  2153. /// \p The ongoing transaction where every action should be registered.
  2154. static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
  2155. Instruction *MemoryInst,
  2156. SmallVectorImpl<Instruction*> &AddrModeInsts,
  2157. const TargetLowering &TLI,
  2158. const TargetRegisterInfo &TRI,
  2159. const SetOfInstrs &InsertedInsts,
  2160. InstrToOrigTy &PromotedInsts,
  2161. TypePromotionTransaction &TPT) {
  2162. ExtAddrMode Result;
  2163. bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
  2164. AccessTy, AS,
  2165. MemoryInst, Result, InsertedInsts,
  2166. PromotedInsts, TPT).matchAddr(V, 0);
  2167. (void)Success; assert(Success && "Couldn't select *anything*?");
  2168. return Result;
  2169. }
  2170. private:
  2171. bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  2172. bool matchAddr(Value *V, unsigned Depth);
  2173. bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
  2174. bool *MovedAway = nullptr);
  2175. bool isProfitableToFoldIntoAddressingMode(Instruction *I,
  2176. ExtAddrMode &AMBefore,
  2177. ExtAddrMode &AMAfter);
  2178. bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  2179. bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
  2180. Value *PromotedOperand) const;
  2181. };
  2182. /// Try adding ScaleReg*Scale to the current addressing mode.
  2183. /// Return true and update AddrMode if this addr mode is legal for the target,
  2184. /// false if not.
  2185. bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
  2186. unsigned Depth) {
  2187. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  2188. // mode. Just process that directly.
  2189. if (Scale == 1)
  2190. return matchAddr(ScaleReg, Depth);
  2191. // If the scale is 0, it takes nothing to add this.
  2192. if (Scale == 0)
  2193. return true;
  2194. // If we already have a scale of this value, we can add to it, otherwise, we
  2195. // need an available scale field.
  2196. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  2197. return false;
  2198. ExtAddrMode TestAddrMode = AddrMode;
  2199. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  2200. // [A+B + A*7] -> [B+A*8].
  2201. TestAddrMode.Scale += Scale;
  2202. TestAddrMode.ScaledReg = ScaleReg;
  2203. // If the new address isn't legal, bail out.
  2204. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  2205. return false;
  2206. // It was legal, so commit it.
  2207. AddrMode = TestAddrMode;
  2208. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  2209. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  2210. // X*Scale + C*Scale to addr mode.
  2211. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  2212. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  2213. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  2214. TestAddrMode.ScaledReg = AddLHS;
  2215. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  2216. // If this addressing mode is legal, commit it and remember that we folded
  2217. // this instruction.
  2218. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  2219. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  2220. AddrMode = TestAddrMode;
  2221. return true;
  2222. }
  2223. }
  2224. // Otherwise, not (x+c)*scale, just return what we have.
  2225. return true;
  2226. }
  2227. /// This is a little filter, which returns true if an addressing computation
  2228. /// involving I might be folded into a load/store accessing it.
  2229. /// This doesn't need to be perfect, but needs to accept at least
  2230. /// the set of instructions that MatchOperationAddr can.
  2231. static bool MightBeFoldableInst(Instruction *I) {
  2232. switch (I->getOpcode()) {
  2233. case Instruction::BitCast:
  2234. case Instruction::AddrSpaceCast:
  2235. // Don't touch identity bitcasts.
  2236. if (I->getType() == I->getOperand(0)->getType())
  2237. return false;
  2238. return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
  2239. case Instruction::PtrToInt:
  2240. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  2241. return true;
  2242. case Instruction::IntToPtr:
  2243. // We know the input is intptr_t, so this is foldable.
  2244. return true;
  2245. case Instruction::Add:
  2246. return true;
  2247. case Instruction::Mul:
  2248. case Instruction::Shl:
  2249. // Can only handle X*C and X << C.
  2250. return isa<ConstantInt>(I->getOperand(1));
  2251. case Instruction::GetElementPtr:
  2252. return true;
  2253. default:
  2254. return false;
  2255. }
  2256. }
  2257. /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
  2258. /// \note \p Val is assumed to be the product of some type promotion.
  2259. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  2260. /// to be legal, as the non-promoted value would have had the same state.
  2261. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  2262. const DataLayout &DL, Value *Val) {
  2263. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  2264. if (!PromotedInst)
  2265. return false;
  2266. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  2267. // If the ISDOpcode is undefined, it was undefined before the promotion.
  2268. if (!ISDOpcode)
  2269. return true;
  2270. // Otherwise, check if the promoted instruction is legal or not.
  2271. return TLI.isOperationLegalOrCustom(
  2272. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  2273. }
  2274. /// \brief Hepler class to perform type promotion.
  2275. class TypePromotionHelper {
  2276. /// \brief Utility function to check whether or not a sign or zero extension
  2277. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  2278. /// either using the operands of \p Inst or promoting \p Inst.
  2279. /// The type of the extension is defined by \p IsSExt.
  2280. /// In other words, check if:
  2281. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  2282. /// #1 Promotion applies:
  2283. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  2284. /// #2 Operand reuses:
  2285. /// ext opnd1 to ConsideredExtType.
  2286. /// \p PromotedInsts maps the instructions to their type before promotion.
  2287. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  2288. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  2289. /// \brief Utility function to determine if \p OpIdx should be promoted when
  2290. /// promoting \p Inst.
  2291. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  2292. return !(isa<SelectInst>(Inst) && OpIdx == 0);
  2293. }
  2294. /// \brief Utility function to promote the operand of \p Ext when this
  2295. /// operand is a promotable trunc or sext or zext.
  2296. /// \p PromotedInsts maps the instructions to their type before promotion.
  2297. /// \p CreatedInstsCost[out] contains the cost of all instructions
  2298. /// created to promote the operand of Ext.
  2299. /// Newly added extensions are inserted in \p Exts.
  2300. /// Newly added truncates are inserted in \p Truncs.
  2301. /// Should never be called directly.
  2302. /// \return The promoted value which is used instead of Ext.
  2303. static Value *promoteOperandForTruncAndAnyExt(
  2304. Instruction *Ext, TypePromotionTransaction &TPT,
  2305. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2306. SmallVectorImpl<Instruction *> *Exts,
  2307. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  2308. /// \brief Utility function to promote the operand of \p Ext when this
  2309. /// operand is promotable and is not a supported trunc or sext.
  2310. /// \p PromotedInsts maps the instructions to their type before promotion.
  2311. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  2312. /// created to promote the operand of Ext.
  2313. /// Newly added extensions are inserted in \p Exts.
  2314. /// Newly added truncates are inserted in \p Truncs.
  2315. /// Should never be called directly.
  2316. /// \return The promoted value which is used instead of Ext.
  2317. static Value *promoteOperandForOther(Instruction *Ext,
  2318. TypePromotionTransaction &TPT,
  2319. InstrToOrigTy &PromotedInsts,
  2320. unsigned &CreatedInstsCost,
  2321. SmallVectorImpl<Instruction *> *Exts,
  2322. SmallVectorImpl<Instruction *> *Truncs,
  2323. const TargetLowering &TLI, bool IsSExt);
  2324. /// \see promoteOperandForOther.
  2325. static Value *signExtendOperandForOther(
  2326. Instruction *Ext, TypePromotionTransaction &TPT,
  2327. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2328. SmallVectorImpl<Instruction *> *Exts,
  2329. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2330. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2331. Exts, Truncs, TLI, true);
  2332. }
  2333. /// \see promoteOperandForOther.
  2334. static Value *zeroExtendOperandForOther(
  2335. Instruction *Ext, TypePromotionTransaction &TPT,
  2336. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2337. SmallVectorImpl<Instruction *> *Exts,
  2338. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2339. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2340. Exts, Truncs, TLI, false);
  2341. }
  2342. public:
  2343. /// Type for the utility function that promotes the operand of Ext.
  2344. typedef Value *(*Action)(Instruction *Ext, TypePromotionTransaction &TPT,
  2345. InstrToOrigTy &PromotedInsts,
  2346. unsigned &CreatedInstsCost,
  2347. SmallVectorImpl<Instruction *> *Exts,
  2348. SmallVectorImpl<Instruction *> *Truncs,
  2349. const TargetLowering &TLI);
  2350. /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
  2351. /// action to promote the operand of \p Ext instead of using Ext.
  2352. /// \return NULL if no promotable action is possible with the current
  2353. /// sign extension.
  2354. /// \p InsertedInsts keeps track of all the instructions inserted by the
  2355. /// other CodeGenPrepare optimizations. This information is important
  2356. /// because we do not want to promote these instructions as CodeGenPrepare
  2357. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  2358. /// \p PromotedInsts maps the instructions to their type before promotion.
  2359. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2360. const TargetLowering &TLI,
  2361. const InstrToOrigTy &PromotedInsts);
  2362. };
  2363. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  2364. Type *ConsideredExtType,
  2365. const InstrToOrigTy &PromotedInsts,
  2366. bool IsSExt) {
  2367. // The promotion helper does not know how to deal with vector types yet.
  2368. // To be able to fix that, we would need to fix the places where we
  2369. // statically extend, e.g., constants and such.
  2370. if (Inst->getType()->isVectorTy())
  2371. return false;
  2372. // We can always get through zext.
  2373. if (isa<ZExtInst>(Inst))
  2374. return true;
  2375. // sext(sext) is ok too.
  2376. if (IsSExt && isa<SExtInst>(Inst))
  2377. return true;
  2378. // We can get through binary operator, if it is legal. In other words, the
  2379. // binary operator must have a nuw or nsw flag.
  2380. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  2381. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  2382. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  2383. (IsSExt && BinOp->hasNoSignedWrap())))
  2384. return true;
  2385. // Check if we can do the following simplification.
  2386. // ext(trunc(opnd)) --> ext(opnd)
  2387. if (!isa<TruncInst>(Inst))
  2388. return false;
  2389. Value *OpndVal = Inst->getOperand(0);
  2390. // Check if we can use this operand in the extension.
  2391. // If the type is larger than the result type of the extension, we cannot.
  2392. if (!OpndVal->getType()->isIntegerTy() ||
  2393. OpndVal->getType()->getIntegerBitWidth() >
  2394. ConsideredExtType->getIntegerBitWidth())
  2395. return false;
  2396. // If the operand of the truncate is not an instruction, we will not have
  2397. // any information on the dropped bits.
  2398. // (Actually we could for constant but it is not worth the extra logic).
  2399. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  2400. if (!Opnd)
  2401. return false;
  2402. // Check if the source of the type is narrow enough.
  2403. // I.e., check that trunc just drops extended bits of the same kind of
  2404. // the extension.
  2405. // #1 get the type of the operand and check the kind of the extended bits.
  2406. const Type *OpndType;
  2407. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  2408. if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
  2409. OpndType = It->second.getPointer();
  2410. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  2411. OpndType = Opnd->getOperand(0)->getType();
  2412. else
  2413. return false;
  2414. // #2 check that the truncate just drops extended bits.
  2415. return Inst->getType()->getIntegerBitWidth() >=
  2416. OpndType->getIntegerBitWidth();
  2417. }
  2418. TypePromotionHelper::Action TypePromotionHelper::getAction(
  2419. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2420. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  2421. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  2422. "Unexpected instruction type");
  2423. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  2424. Type *ExtTy = Ext->getType();
  2425. bool IsSExt = isa<SExtInst>(Ext);
  2426. // If the operand of the extension is not an instruction, we cannot
  2427. // get through.
  2428. // If it, check we can get through.
  2429. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  2430. return nullptr;
  2431. // Do not promote if the operand has been added by codegenprepare.
  2432. // Otherwise, it means we are undoing an optimization that is likely to be
  2433. // redone, thus causing potential infinite loop.
  2434. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  2435. return nullptr;
  2436. // SExt or Trunc instructions.
  2437. // Return the related handler.
  2438. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  2439. isa<ZExtInst>(ExtOpnd))
  2440. return promoteOperandForTruncAndAnyExt;
  2441. // Regular instruction.
  2442. // Abort early if we will have to insert non-free instructions.
  2443. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  2444. return nullptr;
  2445. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  2446. }
  2447. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  2448. llvm::Instruction *SExt, TypePromotionTransaction &TPT,
  2449. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2450. SmallVectorImpl<Instruction *> *Exts,
  2451. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2452. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  2453. // get through it and this method should not be called.
  2454. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  2455. Value *ExtVal = SExt;
  2456. bool HasMergedNonFreeExt = false;
  2457. if (isa<ZExtInst>(SExtOpnd)) {
  2458. // Replace s|zext(zext(opnd))
  2459. // => zext(opnd).
  2460. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  2461. Value *ZExt =
  2462. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  2463. TPT.replaceAllUsesWith(SExt, ZExt);
  2464. TPT.eraseInstruction(SExt);
  2465. ExtVal = ZExt;
  2466. } else {
  2467. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  2468. // => z|sext(opnd).
  2469. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  2470. }
  2471. CreatedInstsCost = 0;
  2472. // Remove dead code.
  2473. if (SExtOpnd->use_empty())
  2474. TPT.eraseInstruction(SExtOpnd);
  2475. // Check if the extension is still needed.
  2476. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  2477. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  2478. if (ExtInst) {
  2479. if (Exts)
  2480. Exts->push_back(ExtInst);
  2481. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  2482. }
  2483. return ExtVal;
  2484. }
  2485. // At this point we have: ext ty opnd to ty.
  2486. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  2487. Value *NextVal = ExtInst->getOperand(0);
  2488. TPT.eraseInstruction(ExtInst, NextVal);
  2489. return NextVal;
  2490. }
  2491. Value *TypePromotionHelper::promoteOperandForOther(
  2492. Instruction *Ext, TypePromotionTransaction &TPT,
  2493. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2494. SmallVectorImpl<Instruction *> *Exts,
  2495. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  2496. bool IsSExt) {
  2497. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  2498. // get through it and this method should not be called.
  2499. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  2500. CreatedInstsCost = 0;
  2501. if (!ExtOpnd->hasOneUse()) {
  2502. // ExtOpnd will be promoted.
  2503. // All its uses, but Ext, will need to use a truncated value of the
  2504. // promoted version.
  2505. // Create the truncate now.
  2506. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  2507. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  2508. ITrunc->removeFromParent();
  2509. // Insert it just after the definition.
  2510. ITrunc->insertAfter(ExtOpnd);
  2511. if (Truncs)
  2512. Truncs->push_back(ITrunc);
  2513. }
  2514. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  2515. // Restore the operand of Ext (which has been replaced by the previous call
  2516. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  2517. TPT.setOperand(Ext, 0, ExtOpnd);
  2518. }
  2519. // Get through the Instruction:
  2520. // 1. Update its type.
  2521. // 2. Replace the uses of Ext by Inst.
  2522. // 3. Extend each operand that needs to be extended.
  2523. // Remember the original type of the instruction before promotion.
  2524. // This is useful to know that the high bits are sign extended bits.
  2525. PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
  2526. ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
  2527. // Step #1.
  2528. TPT.mutateType(ExtOpnd, Ext->getType());
  2529. // Step #2.
  2530. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  2531. // Step #3.
  2532. Instruction *ExtForOpnd = Ext;
  2533. DEBUG(dbgs() << "Propagate Ext to operands\n");
  2534. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  2535. ++OpIdx) {
  2536. DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  2537. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  2538. !shouldExtOperand(ExtOpnd, OpIdx)) {
  2539. DEBUG(dbgs() << "No need to propagate\n");
  2540. continue;
  2541. }
  2542. // Check if we can statically extend the operand.
  2543. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  2544. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  2545. DEBUG(dbgs() << "Statically extend\n");
  2546. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  2547. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  2548. : Cst->getValue().zext(BitWidth);
  2549. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  2550. continue;
  2551. }
  2552. // UndefValue are typed, so we have to statically sign extend them.
  2553. if (isa<UndefValue>(Opnd)) {
  2554. DEBUG(dbgs() << "Statically extend\n");
  2555. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  2556. continue;
  2557. }
  2558. // Otherwise we have to explicity sign extend the operand.
  2559. // Check if Ext was reused to extend an operand.
  2560. if (!ExtForOpnd) {
  2561. // If yes, create a new one.
  2562. DEBUG(dbgs() << "More operands to ext\n");
  2563. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  2564. : TPT.createZExt(Ext, Opnd, Ext->getType());
  2565. if (!isa<Instruction>(ValForExtOpnd)) {
  2566. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  2567. continue;
  2568. }
  2569. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  2570. }
  2571. if (Exts)
  2572. Exts->push_back(ExtForOpnd);
  2573. TPT.setOperand(ExtForOpnd, 0, Opnd);
  2574. // Move the sign extension before the insertion point.
  2575. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  2576. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  2577. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  2578. // If more sext are required, new instructions will have to be created.
  2579. ExtForOpnd = nullptr;
  2580. }
  2581. if (ExtForOpnd == Ext) {
  2582. DEBUG(dbgs() << "Extension is useless now\n");
  2583. TPT.eraseInstruction(Ext);
  2584. }
  2585. return ExtOpnd;
  2586. }
  2587. /// Check whether or not promoting an instruction to a wider type is profitable.
  2588. /// \p NewCost gives the cost of extension instructions created by the
  2589. /// promotion.
  2590. /// \p OldCost gives the cost of extension instructions before the promotion
  2591. /// plus the number of instructions that have been
  2592. /// matched in the addressing mode the promotion.
  2593. /// \p PromotedOperand is the value that has been promoted.
  2594. /// \return True if the promotion is profitable, false otherwise.
  2595. bool AddressingModeMatcher::isPromotionProfitable(
  2596. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  2597. DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
  2598. // The cost of the new extensions is greater than the cost of the
  2599. // old extension plus what we folded.
  2600. // This is not profitable.
  2601. if (NewCost > OldCost)
  2602. return false;
  2603. if (NewCost < OldCost)
  2604. return true;
  2605. // The promotion is neutral but it may help folding the sign extension in
  2606. // loads for instance.
  2607. // Check that we did not create an illegal instruction.
  2608. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  2609. }
  2610. /// Given an instruction or constant expr, see if we can fold the operation
  2611. /// into the addressing mode. If so, update the addressing mode and return
  2612. /// true, otherwise return false without modifying AddrMode.
  2613. /// If \p MovedAway is not NULL, it contains the information of whether or
  2614. /// not AddrInst has to be folded into the addressing mode on success.
  2615. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  2616. /// because it has been moved away.
  2617. /// Thus AddrInst must not be added in the matched instructions.
  2618. /// This state can happen when AddrInst is a sext, since it may be moved away.
  2619. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  2620. /// not be referenced anymore.
  2621. bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
  2622. unsigned Depth,
  2623. bool *MovedAway) {
  2624. // Avoid exponential behavior on extremely deep expression trees.
  2625. if (Depth >= 5) return false;
  2626. // By default, all matched instructions stay in place.
  2627. if (MovedAway)
  2628. *MovedAway = false;
  2629. switch (Opcode) {
  2630. case Instruction::PtrToInt:
  2631. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  2632. return matchAddr(AddrInst->getOperand(0), Depth);
  2633. case Instruction::IntToPtr: {
  2634. auto AS = AddrInst->getType()->getPointerAddressSpace();
  2635. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  2636. // This inttoptr is a no-op if the integer type is pointer sized.
  2637. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  2638. return matchAddr(AddrInst->getOperand(0), Depth);
  2639. return false;
  2640. }
  2641. case Instruction::BitCast:
  2642. // BitCast is always a noop, and we can handle it as long as it is
  2643. // int->int or pointer->pointer (we don't want int<->fp or something).
  2644. if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
  2645. AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
  2646. // Don't touch identity bitcasts. These were probably put here by LSR,
  2647. // and we don't want to mess around with them. Assume it knows what it
  2648. // is doing.
  2649. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  2650. return matchAddr(AddrInst->getOperand(0), Depth);
  2651. return false;
  2652. case Instruction::AddrSpaceCast: {
  2653. unsigned SrcAS
  2654. = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  2655. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  2656. if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  2657. return matchAddr(AddrInst->getOperand(0), Depth);
  2658. return false;
  2659. }
  2660. case Instruction::Add: {
  2661. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  2662. ExtAddrMode BackupAddrMode = AddrMode;
  2663. unsigned OldSize = AddrModeInsts.size();
  2664. // Start a transaction at this point.
  2665. // The LHS may match but not the RHS.
  2666. // Therefore, we need a higher level restoration point to undo partially
  2667. // matched operation.
  2668. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2669. TPT.getRestorationPoint();
  2670. if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
  2671. matchAddr(AddrInst->getOperand(0), Depth+1))
  2672. return true;
  2673. // Restore the old addr mode info.
  2674. AddrMode = BackupAddrMode;
  2675. AddrModeInsts.resize(OldSize);
  2676. TPT.rollback(LastKnownGood);
  2677. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  2678. if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
  2679. matchAddr(AddrInst->getOperand(1), Depth+1))
  2680. return true;
  2681. // Otherwise we definitely can't merge the ADD in.
  2682. AddrMode = BackupAddrMode;
  2683. AddrModeInsts.resize(OldSize);
  2684. TPT.rollback(LastKnownGood);
  2685. break;
  2686. }
  2687. //case Instruction::Or:
  2688. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  2689. //break;
  2690. case Instruction::Mul:
  2691. case Instruction::Shl: {
  2692. // Can only handle X*C and X << C.
  2693. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  2694. if (!RHS)
  2695. return false;
  2696. int64_t Scale = RHS->getSExtValue();
  2697. if (Opcode == Instruction::Shl)
  2698. Scale = 1LL << Scale;
  2699. return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  2700. }
  2701. case Instruction::GetElementPtr: {
  2702. // Scan the GEP. We check it if it contains constant offsets and at most
  2703. // one variable offset.
  2704. int VariableOperand = -1;
  2705. unsigned VariableScale = 0;
  2706. int64_t ConstantOffset = 0;
  2707. gep_type_iterator GTI = gep_type_begin(AddrInst);
  2708. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  2709. if (StructType *STy = GTI.getStructTypeOrNull()) {
  2710. const StructLayout *SL = DL.getStructLayout(STy);
  2711. unsigned Idx =
  2712. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  2713. ConstantOffset += SL->getElementOffset(Idx);
  2714. } else {
  2715. uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
  2716. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  2717. ConstantOffset += CI->getSExtValue()*TypeSize;
  2718. } else if (TypeSize) { // Scales of zero don't do anything.
  2719. // We only allow one variable index at the moment.
  2720. if (VariableOperand != -1)
  2721. return false;
  2722. // Remember the variable index.
  2723. VariableOperand = i;
  2724. VariableScale = TypeSize;
  2725. }
  2726. }
  2727. }
  2728. // A common case is for the GEP to only do a constant offset. In this case,
  2729. // just add it to the disp field and check validity.
  2730. if (VariableOperand == -1) {
  2731. AddrMode.BaseOffs += ConstantOffset;
  2732. if (ConstantOffset == 0 ||
  2733. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  2734. // Check to see if we can fold the base pointer in too.
  2735. if (matchAddr(AddrInst->getOperand(0), Depth+1))
  2736. return true;
  2737. }
  2738. AddrMode.BaseOffs -= ConstantOffset;
  2739. return false;
  2740. }
  2741. // Save the valid addressing mode in case we can't match.
  2742. ExtAddrMode BackupAddrMode = AddrMode;
  2743. unsigned OldSize = AddrModeInsts.size();
  2744. // See if the scale and offset amount is valid for this target.
  2745. AddrMode.BaseOffs += ConstantOffset;
  2746. // Match the base operand of the GEP.
  2747. if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
  2748. // If it couldn't be matched, just stuff the value in a register.
  2749. if (AddrMode.HasBaseReg) {
  2750. AddrMode = BackupAddrMode;
  2751. AddrModeInsts.resize(OldSize);
  2752. return false;
  2753. }
  2754. AddrMode.HasBaseReg = true;
  2755. AddrMode.BaseReg = AddrInst->getOperand(0);
  2756. }
  2757. // Match the remaining variable portion of the GEP.
  2758. if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  2759. Depth)) {
  2760. // If it couldn't be matched, try stuffing the base into a register
  2761. // instead of matching it, and retrying the match of the scale.
  2762. AddrMode = BackupAddrMode;
  2763. AddrModeInsts.resize(OldSize);
  2764. if (AddrMode.HasBaseReg)
  2765. return false;
  2766. AddrMode.HasBaseReg = true;
  2767. AddrMode.BaseReg = AddrInst->getOperand(0);
  2768. AddrMode.BaseOffs += ConstantOffset;
  2769. if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
  2770. VariableScale, Depth)) {
  2771. // If even that didn't work, bail.
  2772. AddrMode = BackupAddrMode;
  2773. AddrModeInsts.resize(OldSize);
  2774. return false;
  2775. }
  2776. }
  2777. return true;
  2778. }
  2779. case Instruction::SExt:
  2780. case Instruction::ZExt: {
  2781. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  2782. if (!Ext)
  2783. return false;
  2784. // Try to move this ext out of the way of the addressing mode.
  2785. // Ask for a method for doing so.
  2786. TypePromotionHelper::Action TPH =
  2787. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  2788. if (!TPH)
  2789. return false;
  2790. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2791. TPT.getRestorationPoint();
  2792. unsigned CreatedInstsCost = 0;
  2793. unsigned ExtCost = !TLI.isExtFree(Ext);
  2794. Value *PromotedOperand =
  2795. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  2796. // SExt has been moved away.
  2797. // Thus either it will be rematched later in the recursive calls or it is
  2798. // gone. Anyway, we must not fold it into the addressing mode at this point.
  2799. // E.g.,
  2800. // op = add opnd, 1
  2801. // idx = ext op
  2802. // addr = gep base, idx
  2803. // is now:
  2804. // promotedOpnd = ext opnd <- no match here
  2805. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  2806. // addr = gep base, op <- match
  2807. if (MovedAway)
  2808. *MovedAway = true;
  2809. assert(PromotedOperand &&
  2810. "TypePromotionHelper should have filtered out those cases");
  2811. ExtAddrMode BackupAddrMode = AddrMode;
  2812. unsigned OldSize = AddrModeInsts.size();
  2813. if (!matchAddr(PromotedOperand, Depth) ||
  2814. // The total of the new cost is equal to the cost of the created
  2815. // instructions.
  2816. // The total of the old cost is equal to the cost of the extension plus
  2817. // what we have saved in the addressing mode.
  2818. !isPromotionProfitable(CreatedInstsCost,
  2819. ExtCost + (AddrModeInsts.size() - OldSize),
  2820. PromotedOperand)) {
  2821. AddrMode = BackupAddrMode;
  2822. AddrModeInsts.resize(OldSize);
  2823. DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  2824. TPT.rollback(LastKnownGood);
  2825. return false;
  2826. }
  2827. return true;
  2828. }
  2829. }
  2830. return false;
  2831. }
  2832. /// If we can, try to add the value of 'Addr' into the current addressing mode.
  2833. /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
  2834. /// unmodified. This assumes that Addr is either a pointer type or intptr_t
  2835. /// for the target.
  2836. ///
  2837. bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
  2838. // Start a transaction at this point that we will rollback if the matching
  2839. // fails.
  2840. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  2841. TPT.getRestorationPoint();
  2842. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  2843. // Fold in immediates if legal for the target.
  2844. AddrMode.BaseOffs += CI->getSExtValue();
  2845. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2846. return true;
  2847. AddrMode.BaseOffs -= CI->getSExtValue();
  2848. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  2849. // If this is a global variable, try to fold it into the addressing mode.
  2850. if (!AddrMode.BaseGV) {
  2851. AddrMode.BaseGV = GV;
  2852. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2853. return true;
  2854. AddrMode.BaseGV = nullptr;
  2855. }
  2856. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  2857. ExtAddrMode BackupAddrMode = AddrMode;
  2858. unsigned OldSize = AddrModeInsts.size();
  2859. // Check to see if it is possible to fold this operation.
  2860. bool MovedAway = false;
  2861. if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  2862. // This instruction may have been moved away. If so, there is nothing
  2863. // to check here.
  2864. if (MovedAway)
  2865. return true;
  2866. // Okay, it's possible to fold this. Check to see if it is actually
  2867. // *profitable* to do so. We use a simple cost model to avoid increasing
  2868. // register pressure too much.
  2869. if (I->hasOneUse() ||
  2870. isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  2871. AddrModeInsts.push_back(I);
  2872. return true;
  2873. }
  2874. // It isn't profitable to do this, roll back.
  2875. //cerr << "NOT FOLDING: " << *I;
  2876. AddrMode = BackupAddrMode;
  2877. AddrModeInsts.resize(OldSize);
  2878. TPT.rollback(LastKnownGood);
  2879. }
  2880. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  2881. if (matchOperationAddr(CE, CE->getOpcode(), Depth))
  2882. return true;
  2883. TPT.rollback(LastKnownGood);
  2884. } else if (isa<ConstantPointerNull>(Addr)) {
  2885. // Null pointer gets folded without affecting the addressing mode.
  2886. return true;
  2887. }
  2888. // Worse case, the target should support [reg] addressing modes. :)
  2889. if (!AddrMode.HasBaseReg) {
  2890. AddrMode.HasBaseReg = true;
  2891. AddrMode.BaseReg = Addr;
  2892. // Still check for legality in case the target supports [imm] but not [i+r].
  2893. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2894. return true;
  2895. AddrMode.HasBaseReg = false;
  2896. AddrMode.BaseReg = nullptr;
  2897. }
  2898. // If the base register is already taken, see if we can do [r+r].
  2899. if (AddrMode.Scale == 0) {
  2900. AddrMode.Scale = 1;
  2901. AddrMode.ScaledReg = Addr;
  2902. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  2903. return true;
  2904. AddrMode.Scale = 0;
  2905. AddrMode.ScaledReg = nullptr;
  2906. }
  2907. // Couldn't match.
  2908. TPT.rollback(LastKnownGood);
  2909. return false;
  2910. }
  2911. /// Check to see if all uses of OpVal by the specified inline asm call are due
  2912. /// to memory operands. If so, return true, otherwise return false.
  2913. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  2914. const TargetLowering &TLI,
  2915. const TargetRegisterInfo &TRI) {
  2916. const Function *F = CI->getParent()->getParent();
  2917. TargetLowering::AsmOperandInfoVector TargetConstraints =
  2918. TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
  2919. ImmutableCallSite(CI));
  2920. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  2921. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  2922. // Compute the constraint code and ConstraintType to use.
  2923. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  2924. // If this asm operand is our Value*, and if it isn't an indirect memory
  2925. // operand, we can't fold it!
  2926. if (OpInfo.CallOperandVal == OpVal &&
  2927. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  2928. !OpInfo.isIndirect))
  2929. return false;
  2930. }
  2931. return true;
  2932. }
  2933. /// Recursively walk all the uses of I until we find a memory use.
  2934. /// If we find an obviously non-foldable instruction, return true.
  2935. /// Add the ultimately found memory instructions to MemoryUses.
  2936. static bool FindAllMemoryUses(
  2937. Instruction *I,
  2938. SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
  2939. SmallPtrSetImpl<Instruction *> &ConsideredInsts,
  2940. const TargetLowering &TLI, const TargetRegisterInfo &TRI) {
  2941. // If we already considered this instruction, we're done.
  2942. if (!ConsideredInsts.insert(I).second)
  2943. return false;
  2944. // If this is an obviously unfoldable instruction, bail out.
  2945. if (!MightBeFoldableInst(I))
  2946. return true;
  2947. const bool OptSize = I->getFunction()->optForSize();
  2948. // Loop over all the uses, recursively processing them.
  2949. for (Use &U : I->uses()) {
  2950. Instruction *UserI = cast<Instruction>(U.getUser());
  2951. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  2952. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  2953. continue;
  2954. }
  2955. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  2956. unsigned opNo = U.getOperandNo();
  2957. if (opNo != StoreInst::getPointerOperandIndex())
  2958. return true; // Storing addr, not into addr.
  2959. MemoryUses.push_back(std::make_pair(SI, opNo));
  2960. continue;
  2961. }
  2962. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
  2963. unsigned opNo = U.getOperandNo();
  2964. if (opNo != AtomicRMWInst::getPointerOperandIndex())
  2965. return true; // Storing addr, not into addr.
  2966. MemoryUses.push_back(std::make_pair(RMW, opNo));
  2967. continue;
  2968. }
  2969. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
  2970. unsigned opNo = U.getOperandNo();
  2971. if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
  2972. return true; // Storing addr, not into addr.
  2973. MemoryUses.push_back(std::make_pair(CmpX, opNo));
  2974. continue;
  2975. }
  2976. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  2977. // If this is a cold call, we can sink the addressing calculation into
  2978. // the cold path. See optimizeCallInst
  2979. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  2980. continue;
  2981. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  2982. if (!IA) return true;
  2983. // If this is a memory operand, we're cool, otherwise bail out.
  2984. if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
  2985. return true;
  2986. continue;
  2987. }
  2988. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI))
  2989. return true;
  2990. }
  2991. return false;
  2992. }
  2993. /// Return true if Val is already known to be live at the use site that we're
  2994. /// folding it into. If so, there is no cost to include it in the addressing
  2995. /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
  2996. /// instruction already.
  2997. bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  2998. Value *KnownLive2) {
  2999. // If Val is either of the known-live values, we know it is live!
  3000. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  3001. return true;
  3002. // All values other than instructions and arguments (e.g. constants) are live.
  3003. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  3004. // If Val is a constant sized alloca in the entry block, it is live, this is
  3005. // true because it is just a reference to the stack/frame pointer, which is
  3006. // live for the whole function.
  3007. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  3008. if (AI->isStaticAlloca())
  3009. return true;
  3010. // Check to see if this value is already used in the memory instruction's
  3011. // block. If so, it's already live into the block at the very least, so we
  3012. // can reasonably fold it.
  3013. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  3014. }
  3015. /// It is possible for the addressing mode of the machine to fold the specified
  3016. /// instruction into a load or store that ultimately uses it.
  3017. /// However, the specified instruction has multiple uses.
  3018. /// Given this, it may actually increase register pressure to fold it
  3019. /// into the load. For example, consider this code:
  3020. ///
  3021. /// X = ...
  3022. /// Y = X+1
  3023. /// use(Y) -> nonload/store
  3024. /// Z = Y+1
  3025. /// load Z
  3026. ///
  3027. /// In this case, Y has multiple uses, and can be folded into the load of Z
  3028. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  3029. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  3030. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  3031. /// number of computations either.
  3032. ///
  3033. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  3034. /// X was live across 'load Z' for other reasons, we actually *would* want to
  3035. /// fold the addressing mode in the Z case. This would make Y die earlier.
  3036. bool AddressingModeMatcher::
  3037. isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  3038. ExtAddrMode &AMAfter) {
  3039. if (IgnoreProfitability) return true;
  3040. // AMBefore is the addressing mode before this instruction was folded into it,
  3041. // and AMAfter is the addressing mode after the instruction was folded. Get
  3042. // the set of registers referenced by AMAfter and subtract out those
  3043. // referenced by AMBefore: this is the set of values which folding in this
  3044. // address extends the lifetime of.
  3045. //
  3046. // Note that there are only two potential values being referenced here,
  3047. // BaseReg and ScaleReg (global addresses are always available, as are any
  3048. // folded immediates).
  3049. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  3050. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  3051. // lifetime wasn't extended by adding this instruction.
  3052. if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3053. BaseReg = nullptr;
  3054. if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3055. ScaledReg = nullptr;
  3056. // If folding this instruction (and it's subexprs) didn't extend any live
  3057. // ranges, we're ok with it.
  3058. if (!BaseReg && !ScaledReg)
  3059. return true;
  3060. // If all uses of this instruction can have the address mode sunk into them,
  3061. // we can remove the addressing mode and effectively trade one live register
  3062. // for another (at worst.) In this context, folding an addressing mode into
  3063. // the use is just a particularly nice way of sinking it.
  3064. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  3065. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  3066. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
  3067. return false; // Has a non-memory, non-foldable use!
  3068. // Now that we know that all uses of this instruction are part of a chain of
  3069. // computation involving only operations that could theoretically be folded
  3070. // into a memory use, loop over each of these memory operation uses and see
  3071. // if they could *actually* fold the instruction. The assumption is that
  3072. // addressing modes are cheap and that duplicating the computation involved
  3073. // many times is worthwhile, even on a fastpath. For sinking candidates
  3074. // (i.e. cold call sites), this serves as a way to prevent excessive code
  3075. // growth since most architectures have some reasonable small and fast way to
  3076. // compute an effective address. (i.e LEA on x86)
  3077. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  3078. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  3079. Instruction *User = MemoryUses[i].first;
  3080. unsigned OpNo = MemoryUses[i].second;
  3081. // Get the access type of this use. If the use isn't a pointer, we don't
  3082. // know what it accesses.
  3083. Value *Address = User->getOperand(OpNo);
  3084. PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
  3085. if (!AddrTy)
  3086. return false;
  3087. Type *AddressAccessTy = AddrTy->getElementType();
  3088. unsigned AS = AddrTy->getAddressSpace();
  3089. // Do a match against the root of this address, ignoring profitability. This
  3090. // will tell us if the addressing mode for the memory operation will
  3091. // *actually* cover the shared instruction.
  3092. ExtAddrMode Result;
  3093. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3094. TPT.getRestorationPoint();
  3095. AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
  3096. AddressAccessTy, AS,
  3097. MemoryInst, Result, InsertedInsts,
  3098. PromotedInsts, TPT);
  3099. Matcher.IgnoreProfitability = true;
  3100. bool Success = Matcher.matchAddr(Address, 0);
  3101. (void)Success; assert(Success && "Couldn't select *anything*?");
  3102. // The match was to check the profitability, the changes made are not
  3103. // part of the original matcher. Therefore, they should be dropped
  3104. // otherwise the original matcher will not present the right state.
  3105. TPT.rollback(LastKnownGood);
  3106. // If the match didn't cover I, then it won't be shared by it.
  3107. if (!is_contained(MatchedAddrModeInsts, I))
  3108. return false;
  3109. MatchedAddrModeInsts.clear();
  3110. }
  3111. return true;
  3112. }
  3113. } // end anonymous namespace
  3114. /// Return true if the specified values are defined in a
  3115. /// different basic block than BB.
  3116. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  3117. if (Instruction *I = dyn_cast<Instruction>(V))
  3118. return I->getParent() != BB;
  3119. return false;
  3120. }
  3121. /// Sink addressing mode computation immediate before MemoryInst if doing so
  3122. /// can be done without increasing register pressure. The need for the
  3123. /// register pressure constraint means this can end up being an all or nothing
  3124. /// decision for all uses of the same addressing computation.
  3125. ///
  3126. /// Load and Store Instructions often have addressing modes that can do
  3127. /// significant amounts of computation. As such, instruction selection will try
  3128. /// to get the load or store to do as much computation as possible for the
  3129. /// program. The problem is that isel can only see within a single block. As
  3130. /// such, we sink as much legal addressing mode work into the block as possible.
  3131. ///
  3132. /// This method is used to optimize both load/store and inline asms with memory
  3133. /// operands. It's also used to sink addressing computations feeding into cold
  3134. /// call sites into their (cold) basic block.
  3135. ///
  3136. /// The motivation for handling sinking into cold blocks is that doing so can
  3137. /// both enable other address mode sinking (by satisfying the register pressure
  3138. /// constraint above), and reduce register pressure globally (by removing the
  3139. /// addressing mode computation from the fast path entirely.).
  3140. bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  3141. Type *AccessTy, unsigned AddrSpace) {
  3142. Value *Repl = Addr;
  3143. // Try to collapse single-value PHI nodes. This is necessary to undo
  3144. // unprofitable PRE transformations.
  3145. SmallVector<Value*, 8> worklist;
  3146. SmallPtrSet<Value*, 16> Visited;
  3147. worklist.push_back(Addr);
  3148. // Use a worklist to iteratively look through PHI nodes, and ensure that
  3149. // the addressing mode obtained from the non-PHI roots of the graph
  3150. // are equivalent.
  3151. Value *Consensus = nullptr;
  3152. unsigned NumUsesConsensus = 0;
  3153. bool IsNumUsesConsensusValid = false;
  3154. SmallVector<Instruction*, 16> AddrModeInsts;
  3155. ExtAddrMode AddrMode;
  3156. TypePromotionTransaction TPT(RemovedInsts);
  3157. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3158. TPT.getRestorationPoint();
  3159. while (!worklist.empty()) {
  3160. Value *V = worklist.back();
  3161. worklist.pop_back();
  3162. // Break use-def graph loops.
  3163. if (!Visited.insert(V).second) {
  3164. Consensus = nullptr;
  3165. break;
  3166. }
  3167. // For a PHI node, push all of its incoming values.
  3168. if (PHINode *P = dyn_cast<PHINode>(V)) {
  3169. for (Value *IncValue : P->incoming_values())
  3170. worklist.push_back(IncValue);
  3171. continue;
  3172. }
  3173. // For non-PHIs, determine the addressing mode being computed. Note that
  3174. // the result may differ depending on what other uses our candidate
  3175. // addressing instructions might have.
  3176. SmallVector<Instruction*, 16> NewAddrModeInsts;
  3177. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  3178. V, AccessTy, AddrSpace, MemoryInst, NewAddrModeInsts, *TLI, *TRI,
  3179. InsertedInsts, PromotedInsts, TPT);
  3180. // This check is broken into two cases with very similar code to avoid using
  3181. // getNumUses() as much as possible. Some values have a lot of uses, so
  3182. // calling getNumUses() unconditionally caused a significant compile-time
  3183. // regression.
  3184. if (!Consensus) {
  3185. Consensus = V;
  3186. AddrMode = NewAddrMode;
  3187. AddrModeInsts = NewAddrModeInsts;
  3188. continue;
  3189. } else if (NewAddrMode == AddrMode) {
  3190. if (!IsNumUsesConsensusValid) {
  3191. NumUsesConsensus = Consensus->getNumUses();
  3192. IsNumUsesConsensusValid = true;
  3193. }
  3194. // Ensure that the obtained addressing mode is equivalent to that obtained
  3195. // for all other roots of the PHI traversal. Also, when choosing one
  3196. // such root as representative, select the one with the most uses in order
  3197. // to keep the cost modeling heuristics in AddressingModeMatcher
  3198. // applicable.
  3199. unsigned NumUses = V->getNumUses();
  3200. if (NumUses > NumUsesConsensus) {
  3201. Consensus = V;
  3202. NumUsesConsensus = NumUses;
  3203. AddrModeInsts = NewAddrModeInsts;
  3204. }
  3205. continue;
  3206. }
  3207. Consensus = nullptr;
  3208. break;
  3209. }
  3210. // If the addressing mode couldn't be determined, or if multiple different
  3211. // ones were determined, bail out now.
  3212. if (!Consensus) {
  3213. TPT.rollback(LastKnownGood);
  3214. return false;
  3215. }
  3216. TPT.commit();
  3217. // If all the instructions matched are already in this BB, don't do anything.
  3218. if (none_of(AddrModeInsts, [&](Value *V) {
  3219. return IsNonLocalValue(V, MemoryInst->getParent());
  3220. })) {
  3221. DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
  3222. return false;
  3223. }
  3224. // Insert this computation right after this user. Since our caller is
  3225. // scanning from the top of the BB to the bottom, reuse of the expr are
  3226. // guaranteed to happen later.
  3227. IRBuilder<> Builder(MemoryInst);
  3228. // Now that we determined the addressing expression we want to use and know
  3229. // that we have to sink it into this block. Check to see if we have already
  3230. // done this for some other load/store instr in this block. If so, reuse the
  3231. // computation.
  3232. Value *&SunkAddr = SunkAddrs[Addr];
  3233. if (SunkAddr) {
  3234. DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
  3235. << *MemoryInst << "\n");
  3236. if (SunkAddr->getType() != Addr->getType())
  3237. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  3238. } else if (AddrSinkUsingGEPs ||
  3239. (!AddrSinkUsingGEPs.getNumOccurrences() && TM &&
  3240. SubtargetInfo->useAA())) {
  3241. // By default, we use the GEP-based method when AA is used later. This
  3242. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  3243. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  3244. << *MemoryInst << "\n");
  3245. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  3246. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  3247. // First, find the pointer.
  3248. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  3249. ResultPtr = AddrMode.BaseReg;
  3250. AddrMode.BaseReg = nullptr;
  3251. }
  3252. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  3253. // We can't add more than one pointer together, nor can we scale a
  3254. // pointer (both of which seem meaningless).
  3255. if (ResultPtr || AddrMode.Scale != 1)
  3256. return false;
  3257. ResultPtr = AddrMode.ScaledReg;
  3258. AddrMode.Scale = 0;
  3259. }
  3260. if (AddrMode.BaseGV) {
  3261. if (ResultPtr)
  3262. return false;
  3263. ResultPtr = AddrMode.BaseGV;
  3264. }
  3265. // If the real base value actually came from an inttoptr, then the matcher
  3266. // will look through it and provide only the integer value. In that case,
  3267. // use it here.
  3268. if (!ResultPtr && AddrMode.BaseReg) {
  3269. ResultPtr =
  3270. Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(), "sunkaddr");
  3271. AddrMode.BaseReg = nullptr;
  3272. } else if (!ResultPtr && AddrMode.Scale == 1) {
  3273. ResultPtr =
  3274. Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(), "sunkaddr");
  3275. AddrMode.Scale = 0;
  3276. }
  3277. if (!ResultPtr &&
  3278. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  3279. SunkAddr = Constant::getNullValue(Addr->getType());
  3280. } else if (!ResultPtr) {
  3281. return false;
  3282. } else {
  3283. Type *I8PtrTy =
  3284. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  3285. Type *I8Ty = Builder.getInt8Ty();
  3286. // Start with the base register. Do this first so that subsequent address
  3287. // matching finds it last, which will prevent it from trying to match it
  3288. // as the scaled value in case it happens to be a mul. That would be
  3289. // problematic if we've sunk a different mul for the scale, because then
  3290. // we'd end up sinking both muls.
  3291. if (AddrMode.BaseReg) {
  3292. Value *V = AddrMode.BaseReg;
  3293. if (V->getType() != IntPtrTy)
  3294. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  3295. ResultIndex = V;
  3296. }
  3297. // Add the scale value.
  3298. if (AddrMode.Scale) {
  3299. Value *V = AddrMode.ScaledReg;
  3300. if (V->getType() == IntPtrTy) {
  3301. // done.
  3302. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  3303. cast<IntegerType>(V->getType())->getBitWidth()) {
  3304. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  3305. } else {
  3306. // It is only safe to sign extend the BaseReg if we know that the math
  3307. // required to create it did not overflow before we extend it. Since
  3308. // the original IR value was tossed in favor of a constant back when
  3309. // the AddrMode was created we need to bail out gracefully if widths
  3310. // do not match instead of extending it.
  3311. Instruction *I = dyn_cast_or_null<Instruction>(ResultIndex);
  3312. if (I && (ResultIndex != AddrMode.BaseReg))
  3313. I->eraseFromParent();
  3314. return false;
  3315. }
  3316. if (AddrMode.Scale != 1)
  3317. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3318. "sunkaddr");
  3319. if (ResultIndex)
  3320. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  3321. else
  3322. ResultIndex = V;
  3323. }
  3324. // Add in the Base Offset if present.
  3325. if (AddrMode.BaseOffs) {
  3326. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3327. if (ResultIndex) {
  3328. // We need to add this separately from the scale above to help with
  3329. // SDAG consecutive load/store merging.
  3330. if (ResultPtr->getType() != I8PtrTy)
  3331. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  3332. ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3333. }
  3334. ResultIndex = V;
  3335. }
  3336. if (!ResultIndex) {
  3337. SunkAddr = ResultPtr;
  3338. } else {
  3339. if (ResultPtr->getType() != I8PtrTy)
  3340. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  3341. SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3342. }
  3343. if (SunkAddr->getType() != Addr->getType())
  3344. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  3345. }
  3346. } else {
  3347. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  3348. << *MemoryInst << "\n");
  3349. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  3350. Value *Result = nullptr;
  3351. // Start with the base register. Do this first so that subsequent address
  3352. // matching finds it last, which will prevent it from trying to match it
  3353. // as the scaled value in case it happens to be a mul. That would be
  3354. // problematic if we've sunk a different mul for the scale, because then
  3355. // we'd end up sinking both muls.
  3356. if (AddrMode.BaseReg) {
  3357. Value *V = AddrMode.BaseReg;
  3358. if (V->getType()->isPointerTy())
  3359. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3360. if (V->getType() != IntPtrTy)
  3361. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  3362. Result = V;
  3363. }
  3364. // Add the scale value.
  3365. if (AddrMode.Scale) {
  3366. Value *V = AddrMode.ScaledReg;
  3367. if (V->getType() == IntPtrTy) {
  3368. // done.
  3369. } else if (V->getType()->isPointerTy()) {
  3370. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3371. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  3372. cast<IntegerType>(V->getType())->getBitWidth()) {
  3373. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  3374. } else {
  3375. // It is only safe to sign extend the BaseReg if we know that the math
  3376. // required to create it did not overflow before we extend it. Since
  3377. // the original IR value was tossed in favor of a constant back when
  3378. // the AddrMode was created we need to bail out gracefully if widths
  3379. // do not match instead of extending it.
  3380. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  3381. if (I && (Result != AddrMode.BaseReg))
  3382. I->eraseFromParent();
  3383. return false;
  3384. }
  3385. if (AddrMode.Scale != 1)
  3386. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3387. "sunkaddr");
  3388. if (Result)
  3389. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3390. else
  3391. Result = V;
  3392. }
  3393. // Add in the BaseGV if present.
  3394. if (AddrMode.BaseGV) {
  3395. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  3396. if (Result)
  3397. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3398. else
  3399. Result = V;
  3400. }
  3401. // Add in the Base Offset if present.
  3402. if (AddrMode.BaseOffs) {
  3403. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3404. if (Result)
  3405. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3406. else
  3407. Result = V;
  3408. }
  3409. if (!Result)
  3410. SunkAddr = Constant::getNullValue(Addr->getType());
  3411. else
  3412. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  3413. }
  3414. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  3415. // If we have no uses, recursively delete the value and all dead instructions
  3416. // using it.
  3417. if (Repl->use_empty()) {
  3418. // This can cause recursive deletion, which can invalidate our iterator.
  3419. // Use a WeakTrackingVH to hold onto it in case this happens.
  3420. Value *CurValue = &*CurInstIterator;
  3421. WeakTrackingVH IterHandle(CurValue);
  3422. BasicBlock *BB = CurInstIterator->getParent();
  3423. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  3424. if (IterHandle != CurValue) {
  3425. // If the iterator instruction was recursively deleted, start over at the
  3426. // start of the block.
  3427. CurInstIterator = BB->begin();
  3428. SunkAddrs.clear();
  3429. }
  3430. }
  3431. ++NumMemoryInsts;
  3432. return true;
  3433. }
  3434. /// If there are any memory operands, use OptimizeMemoryInst to sink their
  3435. /// address computing into the block when possible / profitable.
  3436. bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
  3437. bool MadeChange = false;
  3438. const TargetRegisterInfo *TRI =
  3439. TM->getSubtargetImpl(*CS->getParent()->getParent())->getRegisterInfo();
  3440. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3441. TLI->ParseConstraints(*DL, TRI, CS);
  3442. unsigned ArgNo = 0;
  3443. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3444. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3445. // Compute the constraint code and ConstraintType to use.
  3446. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  3447. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  3448. OpInfo.isIndirect) {
  3449. Value *OpVal = CS->getArgOperand(ArgNo++);
  3450. MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  3451. } else if (OpInfo.Type == InlineAsm::isInput)
  3452. ArgNo++;
  3453. }
  3454. return MadeChange;
  3455. }
  3456. /// \brief Check if all the uses of \p Val are equivalent (or free) zero or
  3457. /// sign extensions.
  3458. static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
  3459. assert(!Val->use_empty() && "Input must have at least one use");
  3460. const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
  3461. bool IsSExt = isa<SExtInst>(FirstUser);
  3462. Type *ExtTy = FirstUser->getType();
  3463. for (const User *U : Val->users()) {
  3464. const Instruction *UI = cast<Instruction>(U);
  3465. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  3466. return false;
  3467. Type *CurTy = UI->getType();
  3468. // Same input and output types: Same instruction after CSE.
  3469. if (CurTy == ExtTy)
  3470. continue;
  3471. // If IsSExt is true, we are in this situation:
  3472. // a = Val
  3473. // b = sext ty1 a to ty2
  3474. // c = sext ty1 a to ty3
  3475. // Assuming ty2 is shorter than ty3, this could be turned into:
  3476. // a = Val
  3477. // b = sext ty1 a to ty2
  3478. // c = sext ty2 b to ty3
  3479. // However, the last sext is not free.
  3480. if (IsSExt)
  3481. return false;
  3482. // This is a ZExt, maybe this is free to extend from one type to another.
  3483. // In that case, we would not account for a different use.
  3484. Type *NarrowTy;
  3485. Type *LargeTy;
  3486. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  3487. CurTy->getScalarType()->getIntegerBitWidth()) {
  3488. NarrowTy = CurTy;
  3489. LargeTy = ExtTy;
  3490. } else {
  3491. NarrowTy = ExtTy;
  3492. LargeTy = CurTy;
  3493. }
  3494. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  3495. return false;
  3496. }
  3497. // All uses are the same or can be derived from one another for free.
  3498. return true;
  3499. }
  3500. /// \brief Try to speculatively promote extensions in \p Exts and continue
  3501. /// promoting through newly promoted operands recursively as far as doing so is
  3502. /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
  3503. /// When some promotion happened, \p TPT contains the proper state to revert
  3504. /// them.
  3505. ///
  3506. /// \return true if some promotion happened, false otherwise.
  3507. bool CodeGenPrepare::tryToPromoteExts(
  3508. TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
  3509. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  3510. unsigned CreatedInstsCost) {
  3511. bool Promoted = false;
  3512. // Iterate over all the extensions to try to promote them.
  3513. for (auto I : Exts) {
  3514. // Early check if we directly have ext(load).
  3515. if (isa<LoadInst>(I->getOperand(0))) {
  3516. ProfitablyMovedExts.push_back(I);
  3517. continue;
  3518. }
  3519. // Check whether or not we want to do any promotion. The reason we have
  3520. // this check inside the for loop is to catch the case where an extension
  3521. // is directly fed by a load because in such case the extension can be moved
  3522. // up without any promotion on its operands.
  3523. if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  3524. return false;
  3525. // Get the action to perform the promotion.
  3526. TypePromotionHelper::Action TPH =
  3527. TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
  3528. // Check if we can promote.
  3529. if (!TPH) {
  3530. // Save the current extension as we cannot move up through its operand.
  3531. ProfitablyMovedExts.push_back(I);
  3532. continue;
  3533. }
  3534. // Save the current state.
  3535. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3536. TPT.getRestorationPoint();
  3537. SmallVector<Instruction *, 4> NewExts;
  3538. unsigned NewCreatedInstsCost = 0;
  3539. unsigned ExtCost = !TLI->isExtFree(I);
  3540. // Promote.
  3541. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  3542. &NewExts, nullptr, *TLI);
  3543. assert(PromotedVal &&
  3544. "TypePromotionHelper should have filtered out those cases");
  3545. // We would be able to merge only one extension in a load.
  3546. // Therefore, if we have more than 1 new extension we heuristically
  3547. // cut this search path, because it means we degrade the code quality.
  3548. // With exactly 2, the transformation is neutral, because we will merge
  3549. // one extension but leave one. However, we optimistically keep going,
  3550. // because the new extension may be removed too.
  3551. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  3552. // FIXME: It would be possible to propagate a negative value instead of
  3553. // conservatively ceiling it to 0.
  3554. TotalCreatedInstsCost =
  3555. std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
  3556. if (!StressExtLdPromotion &&
  3557. (TotalCreatedInstsCost > 1 ||
  3558. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  3559. // This promotion is not profitable, rollback to the previous state, and
  3560. // save the current extension in ProfitablyMovedExts as the latest
  3561. // speculative promotion turned out to be unprofitable.
  3562. TPT.rollback(LastKnownGood);
  3563. ProfitablyMovedExts.push_back(I);
  3564. continue;
  3565. }
  3566. // Continue promoting NewExts as far as doing so is profitable.
  3567. SmallVector<Instruction *, 2> NewlyMovedExts;
  3568. (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
  3569. bool NewPromoted = false;
  3570. for (auto ExtInst : NewlyMovedExts) {
  3571. Instruction *MovedExt = cast<Instruction>(ExtInst);
  3572. Value *ExtOperand = MovedExt->getOperand(0);
  3573. // If we have reached to a load, we need this extra profitability check
  3574. // as it could potentially be merged into an ext(load).
  3575. if (isa<LoadInst>(ExtOperand) &&
  3576. !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  3577. (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
  3578. continue;
  3579. ProfitablyMovedExts.push_back(MovedExt);
  3580. NewPromoted = true;
  3581. }
  3582. // If none of speculative promotions for NewExts is profitable, rollback
  3583. // and save the current extension (I) as the last profitable extension.
  3584. if (!NewPromoted) {
  3585. TPT.rollback(LastKnownGood);
  3586. ProfitablyMovedExts.push_back(I);
  3587. continue;
  3588. }
  3589. // The promotion is profitable.
  3590. Promoted = true;
  3591. }
  3592. return Promoted;
  3593. }
  3594. /// Merging redundant sexts when one is dominating the other.
  3595. bool CodeGenPrepare::mergeSExts(Function &F) {
  3596. DominatorTree DT(F);
  3597. bool Changed = false;
  3598. for (auto &Entry : ValToSExtendedUses) {
  3599. SExts &Insts = Entry.second;
  3600. SExts CurPts;
  3601. for (Instruction *Inst : Insts) {
  3602. if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
  3603. Inst->getOperand(0) != Entry.first)
  3604. continue;
  3605. bool inserted = false;
  3606. for (auto &Pt : CurPts) {
  3607. if (DT.dominates(Inst, Pt)) {
  3608. Pt->replaceAllUsesWith(Inst);
  3609. RemovedInsts.insert(Pt);
  3610. Pt->removeFromParent();
  3611. Pt = Inst;
  3612. inserted = true;
  3613. Changed = true;
  3614. break;
  3615. }
  3616. if (!DT.dominates(Pt, Inst))
  3617. // Give up if we need to merge in a common dominator as the
  3618. // expermients show it is not profitable.
  3619. continue;
  3620. Inst->replaceAllUsesWith(Pt);
  3621. RemovedInsts.insert(Inst);
  3622. Inst->removeFromParent();
  3623. inserted = true;
  3624. Changed = true;
  3625. break;
  3626. }
  3627. if (!inserted)
  3628. CurPts.push_back(Inst);
  3629. }
  3630. }
  3631. return Changed;
  3632. }
  3633. /// Return true, if an ext(load) can be formed from an extension in
  3634. /// \p MovedExts.
  3635. bool CodeGenPrepare::canFormExtLd(
  3636. const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
  3637. Instruction *&Inst, bool HasPromoted) {
  3638. for (auto *MovedExtInst : MovedExts) {
  3639. if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
  3640. LI = cast<LoadInst>(MovedExtInst->getOperand(0));
  3641. Inst = MovedExtInst;
  3642. break;
  3643. }
  3644. }
  3645. if (!LI)
  3646. return false;
  3647. // If they're already in the same block, there's nothing to do.
  3648. // Make the cheap checks first if we did not promote.
  3649. // If we promoted, we need to check if it is indeed profitable.
  3650. if (!HasPromoted && LI->getParent() == Inst->getParent())
  3651. return false;
  3652. EVT VT = TLI->getValueType(*DL, Inst->getType());
  3653. EVT LoadVT = TLI->getValueType(*DL, LI->getType());
  3654. // If the load has other users and the truncate is not free, this probably
  3655. // isn't worthwhile.
  3656. if (!LI->hasOneUse() && (TLI->isTypeLegal(LoadVT) || !TLI->isTypeLegal(VT)) &&
  3657. !TLI->isTruncateFree(Inst->getType(), LI->getType()))
  3658. return false;
  3659. // Check whether the target supports casts folded into loads.
  3660. unsigned LType;
  3661. if (isa<ZExtInst>(Inst))
  3662. LType = ISD::ZEXTLOAD;
  3663. else {
  3664. assert(isa<SExtInst>(Inst) && "Unexpected ext type!");
  3665. LType = ISD::SEXTLOAD;
  3666. }
  3667. return TLI->isLoadExtLegal(LType, VT, LoadVT);
  3668. }
  3669. /// Move a zext or sext fed by a load into the same basic block as the load,
  3670. /// unless conditions are unfavorable. This allows SelectionDAG to fold the
  3671. /// extend into the load.
  3672. ///
  3673. /// E.g.,
  3674. /// \code
  3675. /// %ld = load i32* %addr
  3676. /// %add = add nuw i32 %ld, 4
  3677. /// %zext = zext i32 %add to i64
  3678. // \endcode
  3679. /// =>
  3680. /// \code
  3681. /// %ld = load i32* %addr
  3682. /// %zext = zext i32 %ld to i64
  3683. /// %add = add nuw i64 %zext, 4
  3684. /// \encode
  3685. /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
  3686. /// allow us to match zext(load i32*) to i64.
  3687. ///
  3688. /// Also, try to promote the computations used to obtain a sign extended
  3689. /// value used into memory accesses.
  3690. /// E.g.,
  3691. /// \code
  3692. /// a = add nsw i32 b, 3
  3693. /// d = sext i32 a to i64
  3694. /// e = getelementptr ..., i64 d
  3695. /// \endcode
  3696. /// =>
  3697. /// \code
  3698. /// f = sext i32 b to i64
  3699. /// a = add nsw i64 f, 3
  3700. /// e = getelementptr ..., i64 a
  3701. /// \endcode
  3702. ///
  3703. /// \p Inst[in/out] the extension may be modified during the process if some
  3704. /// promotions apply.
  3705. bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
  3706. // ExtLoad formation and address type promotion infrastructure requires TLI to
  3707. // be effective.
  3708. if (!TLI)
  3709. return false;
  3710. bool AllowPromotionWithoutCommonHeader = false;
  3711. /// See if it is an interesting sext operations for the address type
  3712. /// promotion before trying to promote it, e.g., the ones with the right
  3713. /// type and used in memory accesses.
  3714. bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
  3715. *Inst, AllowPromotionWithoutCommonHeader);
  3716. TypePromotionTransaction TPT(RemovedInsts);
  3717. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3718. TPT.getRestorationPoint();
  3719. SmallVector<Instruction *, 1> Exts;
  3720. SmallVector<Instruction *, 2> SpeculativelyMovedExts;
  3721. Exts.push_back(Inst);
  3722. bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
  3723. // Look for a load being extended.
  3724. LoadInst *LI = nullptr;
  3725. Instruction *ExtFedByLoad;
  3726. // Try to promote a chain of computation if it allows to form an extended
  3727. // load.
  3728. if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
  3729. assert(LI && ExtFedByLoad && "Expect a valid load and extension");
  3730. TPT.commit();
  3731. // Move the extend into the same block as the load
  3732. ExtFedByLoad->removeFromParent();
  3733. ExtFedByLoad->insertAfter(LI);
  3734. // CGP does not check if the zext would be speculatively executed when moved
  3735. // to the same basic block as the load. Preserving its original location
  3736. // would pessimize the debugging experience, as well as negatively impact
  3737. // the quality of sample pgo. We don't want to use "line 0" as that has a
  3738. // size cost in the line-table section and logically the zext can be seen as
  3739. // part of the load. Therefore we conservatively reuse the same debug
  3740. // location for the load and the zext.
  3741. ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
  3742. ++NumExtsMoved;
  3743. Inst = ExtFedByLoad;
  3744. return true;
  3745. }
  3746. // Continue promoting SExts if known as considerable depending on targets.
  3747. if (ATPConsiderable &&
  3748. performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
  3749. HasPromoted, TPT, SpeculativelyMovedExts))
  3750. return true;
  3751. TPT.rollback(LastKnownGood);
  3752. return false;
  3753. }
  3754. // Perform address type promotion if doing so is profitable.
  3755. // If AllowPromotionWithoutCommonHeader == false, we should find other sext
  3756. // instructions that sign extended the same initial value. However, if
  3757. // AllowPromotionWithoutCommonHeader == true, we expect promoting the
  3758. // extension is just profitable.
  3759. bool CodeGenPrepare::performAddressTypePromotion(
  3760. Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
  3761. bool HasPromoted, TypePromotionTransaction &TPT,
  3762. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
  3763. bool Promoted = false;
  3764. SmallPtrSet<Instruction *, 1> UnhandledExts;
  3765. bool AllSeenFirst = true;
  3766. for (auto I : SpeculativelyMovedExts) {
  3767. Value *HeadOfChain = I->getOperand(0);
  3768. DenseMap<Value *, Instruction *>::iterator AlreadySeen =
  3769. SeenChainsForSExt.find(HeadOfChain);
  3770. // If there is an unhandled SExt which has the same header, try to promote
  3771. // it as well.
  3772. if (AlreadySeen != SeenChainsForSExt.end()) {
  3773. if (AlreadySeen->second != nullptr)
  3774. UnhandledExts.insert(AlreadySeen->second);
  3775. AllSeenFirst = false;
  3776. }
  3777. }
  3778. if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
  3779. SpeculativelyMovedExts.size() == 1)) {
  3780. TPT.commit();
  3781. if (HasPromoted)
  3782. Promoted = true;
  3783. for (auto I : SpeculativelyMovedExts) {
  3784. Value *HeadOfChain = I->getOperand(0);
  3785. SeenChainsForSExt[HeadOfChain] = nullptr;
  3786. ValToSExtendedUses[HeadOfChain].push_back(I);
  3787. }
  3788. // Update Inst as promotion happen.
  3789. Inst = SpeculativelyMovedExts.pop_back_val();
  3790. } else {
  3791. // This is the first chain visited from the header, keep the current chain
  3792. // as unhandled. Defer to promote this until we encounter another SExt
  3793. // chain derived from the same header.
  3794. for (auto I : SpeculativelyMovedExts) {
  3795. Value *HeadOfChain = I->getOperand(0);
  3796. SeenChainsForSExt[HeadOfChain] = Inst;
  3797. }
  3798. return false;
  3799. }
  3800. if (!AllSeenFirst && !UnhandledExts.empty())
  3801. for (auto VisitedSExt : UnhandledExts) {
  3802. if (RemovedInsts.count(VisitedSExt))
  3803. continue;
  3804. TypePromotionTransaction TPT(RemovedInsts);
  3805. SmallVector<Instruction *, 1> Exts;
  3806. SmallVector<Instruction *, 2> Chains;
  3807. Exts.push_back(VisitedSExt);
  3808. bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
  3809. TPT.commit();
  3810. if (HasPromoted)
  3811. Promoted = true;
  3812. for (auto I : Chains) {
  3813. Value *HeadOfChain = I->getOperand(0);
  3814. // Mark this as handled.
  3815. SeenChainsForSExt[HeadOfChain] = nullptr;
  3816. ValToSExtendedUses[HeadOfChain].push_back(I);
  3817. }
  3818. }
  3819. return Promoted;
  3820. }
  3821. bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
  3822. BasicBlock *DefBB = I->getParent();
  3823. // If the result of a {s|z}ext and its source are both live out, rewrite all
  3824. // other uses of the source with result of extension.
  3825. Value *Src = I->getOperand(0);
  3826. if (Src->hasOneUse())
  3827. return false;
  3828. // Only do this xform if truncating is free.
  3829. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  3830. return false;
  3831. // Only safe to perform the optimization if the source is also defined in
  3832. // this block.
  3833. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  3834. return false;
  3835. bool DefIsLiveOut = false;
  3836. for (User *U : I->users()) {
  3837. Instruction *UI = cast<Instruction>(U);
  3838. // Figure out which BB this ext is used in.
  3839. BasicBlock *UserBB = UI->getParent();
  3840. if (UserBB == DefBB) continue;
  3841. DefIsLiveOut = true;
  3842. break;
  3843. }
  3844. if (!DefIsLiveOut)
  3845. return false;
  3846. // Make sure none of the uses are PHI nodes.
  3847. for (User *U : Src->users()) {
  3848. Instruction *UI = cast<Instruction>(U);
  3849. BasicBlock *UserBB = UI->getParent();
  3850. if (UserBB == DefBB) continue;
  3851. // Be conservative. We don't want this xform to end up introducing
  3852. // reloads just before load / store instructions.
  3853. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  3854. return false;
  3855. }
  3856. // InsertedTruncs - Only insert one trunc in each block once.
  3857. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  3858. bool MadeChange = false;
  3859. for (Use &U : Src->uses()) {
  3860. Instruction *User = cast<Instruction>(U.getUser());
  3861. // Figure out which BB this ext is used in.
  3862. BasicBlock *UserBB = User->getParent();
  3863. if (UserBB == DefBB) continue;
  3864. // Both src and def are live in this block. Rewrite the use.
  3865. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  3866. if (!InsertedTrunc) {
  3867. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  3868. assert(InsertPt != UserBB->end());
  3869. InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
  3870. InsertedInsts.insert(InsertedTrunc);
  3871. }
  3872. // Replace a use of the {s|z}ext source with a use of the result.
  3873. U = InsertedTrunc;
  3874. ++NumExtUses;
  3875. MadeChange = true;
  3876. }
  3877. return MadeChange;
  3878. }
  3879. // Find loads whose uses only use some of the loaded value's bits. Add an "and"
  3880. // just after the load if the target can fold this into one extload instruction,
  3881. // with the hope of eliminating some of the other later "and" instructions using
  3882. // the loaded value. "and"s that are made trivially redundant by the insertion
  3883. // of the new "and" are removed by this function, while others (e.g. those whose
  3884. // path from the load goes through a phi) are left for isel to potentially
  3885. // remove.
  3886. //
  3887. // For example:
  3888. //
  3889. // b0:
  3890. // x = load i32
  3891. // ...
  3892. // b1:
  3893. // y = and x, 0xff
  3894. // z = use y
  3895. //
  3896. // becomes:
  3897. //
  3898. // b0:
  3899. // x = load i32
  3900. // x' = and x, 0xff
  3901. // ...
  3902. // b1:
  3903. // z = use x'
  3904. //
  3905. // whereas:
  3906. //
  3907. // b0:
  3908. // x1 = load i32
  3909. // ...
  3910. // b1:
  3911. // x2 = load i32
  3912. // ...
  3913. // b2:
  3914. // x = phi x1, x2
  3915. // y = and x, 0xff
  3916. //
  3917. // becomes (after a call to optimizeLoadExt for each load):
  3918. //
  3919. // b0:
  3920. // x1 = load i32
  3921. // x1' = and x1, 0xff
  3922. // ...
  3923. // b1:
  3924. // x2 = load i32
  3925. // x2' = and x2, 0xff
  3926. // ...
  3927. // b2:
  3928. // x = phi x1', x2'
  3929. // y = and x, 0xff
  3930. //
  3931. bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
  3932. if (!Load->isSimple() ||
  3933. !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
  3934. return false;
  3935. // Skip loads we've already transformed.
  3936. if (Load->hasOneUse() &&
  3937. InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
  3938. return false;
  3939. // Look at all uses of Load, looking through phis, to determine how many bits
  3940. // of the loaded value are needed.
  3941. SmallVector<Instruction *, 8> WorkList;
  3942. SmallPtrSet<Instruction *, 16> Visited;
  3943. SmallVector<Instruction *, 8> AndsToMaybeRemove;
  3944. for (auto *U : Load->users())
  3945. WorkList.push_back(cast<Instruction>(U));
  3946. EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
  3947. unsigned BitWidth = LoadResultVT.getSizeInBits();
  3948. APInt DemandBits(BitWidth, 0);
  3949. APInt WidestAndBits(BitWidth, 0);
  3950. while (!WorkList.empty()) {
  3951. Instruction *I = WorkList.back();
  3952. WorkList.pop_back();
  3953. // Break use-def graph loops.
  3954. if (!Visited.insert(I).second)
  3955. continue;
  3956. // For a PHI node, push all of its users.
  3957. if (auto *Phi = dyn_cast<PHINode>(I)) {
  3958. for (auto *U : Phi->users())
  3959. WorkList.push_back(cast<Instruction>(U));
  3960. continue;
  3961. }
  3962. switch (I->getOpcode()) {
  3963. case llvm::Instruction::And: {
  3964. auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
  3965. if (!AndC)
  3966. return false;
  3967. APInt AndBits = AndC->getValue();
  3968. DemandBits |= AndBits;
  3969. // Keep track of the widest and mask we see.
  3970. if (AndBits.ugt(WidestAndBits))
  3971. WidestAndBits = AndBits;
  3972. if (AndBits == WidestAndBits && I->getOperand(0) == Load)
  3973. AndsToMaybeRemove.push_back(I);
  3974. break;
  3975. }
  3976. case llvm::Instruction::Shl: {
  3977. auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
  3978. if (!ShlC)
  3979. return false;
  3980. uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
  3981. DemandBits.setLowBits(BitWidth - ShiftAmt);
  3982. break;
  3983. }
  3984. case llvm::Instruction::Trunc: {
  3985. EVT TruncVT = TLI->getValueType(*DL, I->getType());
  3986. unsigned TruncBitWidth = TruncVT.getSizeInBits();
  3987. DemandBits.setLowBits(TruncBitWidth);
  3988. break;
  3989. }
  3990. default:
  3991. return false;
  3992. }
  3993. }
  3994. uint32_t ActiveBits = DemandBits.getActiveBits();
  3995. // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
  3996. // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
  3997. // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
  3998. // (and (load x) 1) is not matched as a single instruction, rather as a LDR
  3999. // followed by an AND.
  4000. // TODO: Look into removing this restriction by fixing backends to either
  4001. // return false for isLoadExtLegal for i1 or have them select this pattern to
  4002. // a single instruction.
  4003. //
  4004. // Also avoid hoisting if we didn't see any ands with the exact DemandBits
  4005. // mask, since these are the only ands that will be removed by isel.
  4006. if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
  4007. WidestAndBits != DemandBits)
  4008. return false;
  4009. LLVMContext &Ctx = Load->getType()->getContext();
  4010. Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
  4011. EVT TruncVT = TLI->getValueType(*DL, TruncTy);
  4012. // Reject cases that won't be matched as extloads.
  4013. if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
  4014. !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
  4015. return false;
  4016. IRBuilder<> Builder(Load->getNextNode());
  4017. auto *NewAnd = dyn_cast<Instruction>(
  4018. Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
  4019. // Mark this instruction as "inserted by CGP", so that other
  4020. // optimizations don't touch it.
  4021. InsertedInsts.insert(NewAnd);
  4022. // Replace all uses of load with new and (except for the use of load in the
  4023. // new and itself).
  4024. Load->replaceAllUsesWith(NewAnd);
  4025. NewAnd->setOperand(0, Load);
  4026. // Remove any and instructions that are now redundant.
  4027. for (auto *And : AndsToMaybeRemove)
  4028. // Check that the and mask is the same as the one we decided to put on the
  4029. // new and.
  4030. if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
  4031. And->replaceAllUsesWith(NewAnd);
  4032. if (&*CurInstIterator == And)
  4033. CurInstIterator = std::next(And->getIterator());
  4034. And->eraseFromParent();
  4035. ++NumAndUses;
  4036. }
  4037. ++NumAndsAdded;
  4038. return true;
  4039. }
  4040. /// Check if V (an operand of a select instruction) is an expensive instruction
  4041. /// that is only used once.
  4042. static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
  4043. auto *I = dyn_cast<Instruction>(V);
  4044. // If it's safe to speculatively execute, then it should not have side
  4045. // effects; therefore, it's safe to sink and possibly *not* execute.
  4046. return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
  4047. TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
  4048. }
  4049. /// Returns true if a SelectInst should be turned into an explicit branch.
  4050. static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
  4051. const TargetLowering *TLI,
  4052. SelectInst *SI) {
  4053. // If even a predictable select is cheap, then a branch can't be cheaper.
  4054. if (!TLI->isPredictableSelectExpensive())
  4055. return false;
  4056. // FIXME: This should use the same heuristics as IfConversion to determine
  4057. // whether a select is better represented as a branch.
  4058. // If metadata tells us that the select condition is obviously predictable,
  4059. // then we want to replace the select with a branch.
  4060. uint64_t TrueWeight, FalseWeight;
  4061. if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
  4062. uint64_t Max = std::max(TrueWeight, FalseWeight);
  4063. uint64_t Sum = TrueWeight + FalseWeight;
  4064. if (Sum != 0) {
  4065. auto Probability = BranchProbability::getBranchProbability(Max, Sum);
  4066. if (Probability > TLI->getPredictableBranchThreshold())
  4067. return true;
  4068. }
  4069. }
  4070. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  4071. // If a branch is predictable, an out-of-order CPU can avoid blocking on its
  4072. // comparison condition. If the compare has more than one use, there's
  4073. // probably another cmov or setcc around, so it's not worth emitting a branch.
  4074. if (!Cmp || !Cmp->hasOneUse())
  4075. return false;
  4076. // If either operand of the select is expensive and only needed on one side
  4077. // of the select, we should form a branch.
  4078. if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
  4079. sinkSelectOperand(TTI, SI->getFalseValue()))
  4080. return true;
  4081. return false;
  4082. }
  4083. /// If \p isTrue is true, return the true value of \p SI, otherwise return
  4084. /// false value of \p SI. If the true/false value of \p SI is defined by any
  4085. /// select instructions in \p Selects, look through the defining select
  4086. /// instruction until the true/false value is not defined in \p Selects.
  4087. static Value *getTrueOrFalseValue(
  4088. SelectInst *SI, bool isTrue,
  4089. const SmallPtrSet<const Instruction *, 2> &Selects) {
  4090. Value *V;
  4091. for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
  4092. DefSI = dyn_cast<SelectInst>(V)) {
  4093. assert(DefSI->getCondition() == SI->getCondition() &&
  4094. "The condition of DefSI does not match with SI");
  4095. V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
  4096. }
  4097. return V;
  4098. }
  4099. /// If we have a SelectInst that will likely profit from branch prediction,
  4100. /// turn it into a branch.
  4101. bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
  4102. // Find all consecutive select instructions that share the same condition.
  4103. SmallVector<SelectInst *, 2> ASI;
  4104. ASI.push_back(SI);
  4105. for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
  4106. It != SI->getParent()->end(); ++It) {
  4107. SelectInst *I = dyn_cast<SelectInst>(&*It);
  4108. if (I && SI->getCondition() == I->getCondition()) {
  4109. ASI.push_back(I);
  4110. } else {
  4111. break;
  4112. }
  4113. }
  4114. SelectInst *LastSI = ASI.back();
  4115. // Increment the current iterator to skip all the rest of select instructions
  4116. // because they will be either "not lowered" or "all lowered" to branch.
  4117. CurInstIterator = std::next(LastSI->getIterator());
  4118. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  4119. // Can we convert the 'select' to CF ?
  4120. if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
  4121. SI->getMetadata(LLVMContext::MD_unpredictable))
  4122. return false;
  4123. TargetLowering::SelectSupportKind SelectKind;
  4124. if (VectorCond)
  4125. SelectKind = TargetLowering::VectorMaskSelect;
  4126. else if (SI->getType()->isVectorTy())
  4127. SelectKind = TargetLowering::ScalarCondVectorVal;
  4128. else
  4129. SelectKind = TargetLowering::ScalarValSelect;
  4130. if (TLI->isSelectSupported(SelectKind) &&
  4131. !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
  4132. return false;
  4133. ModifiedDT = true;
  4134. // Transform a sequence like this:
  4135. // start:
  4136. // %cmp = cmp uge i32 %a, %b
  4137. // %sel = select i1 %cmp, i32 %c, i32 %d
  4138. //
  4139. // Into:
  4140. // start:
  4141. // %cmp = cmp uge i32 %a, %b
  4142. // br i1 %cmp, label %select.true, label %select.false
  4143. // select.true:
  4144. // br label %select.end
  4145. // select.false:
  4146. // br label %select.end
  4147. // select.end:
  4148. // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
  4149. //
  4150. // In addition, we may sink instructions that produce %c or %d from
  4151. // the entry block into the destination(s) of the new branch.
  4152. // If the true or false blocks do not contain a sunken instruction, that
  4153. // block and its branch may be optimized away. In that case, one side of the
  4154. // first branch will point directly to select.end, and the corresponding PHI
  4155. // predecessor block will be the start block.
  4156. // First, we split the block containing the select into 2 blocks.
  4157. BasicBlock *StartBlock = SI->getParent();
  4158. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
  4159. BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  4160. // Delete the unconditional branch that was just created by the split.
  4161. StartBlock->getTerminator()->eraseFromParent();
  4162. // These are the new basic blocks for the conditional branch.
  4163. // At least one will become an actual new basic block.
  4164. BasicBlock *TrueBlock = nullptr;
  4165. BasicBlock *FalseBlock = nullptr;
  4166. BranchInst *TrueBranch = nullptr;
  4167. BranchInst *FalseBranch = nullptr;
  4168. // Sink expensive instructions into the conditional blocks to avoid executing
  4169. // them speculatively.
  4170. for (SelectInst *SI : ASI) {
  4171. if (sinkSelectOperand(TTI, SI->getTrueValue())) {
  4172. if (TrueBlock == nullptr) {
  4173. TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
  4174. EndBlock->getParent(), EndBlock);
  4175. TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
  4176. }
  4177. auto *TrueInst = cast<Instruction>(SI->getTrueValue());
  4178. TrueInst->moveBefore(TrueBranch);
  4179. }
  4180. if (sinkSelectOperand(TTI, SI->getFalseValue())) {
  4181. if (FalseBlock == nullptr) {
  4182. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
  4183. EndBlock->getParent(), EndBlock);
  4184. FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  4185. }
  4186. auto *FalseInst = cast<Instruction>(SI->getFalseValue());
  4187. FalseInst->moveBefore(FalseBranch);
  4188. }
  4189. }
  4190. // If there was nothing to sink, then arbitrarily choose the 'false' side
  4191. // for a new input value to the PHI.
  4192. if (TrueBlock == FalseBlock) {
  4193. assert(TrueBlock == nullptr &&
  4194. "Unexpected basic block transform while optimizing select");
  4195. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
  4196. EndBlock->getParent(), EndBlock);
  4197. BranchInst::Create(EndBlock, FalseBlock);
  4198. }
  4199. // Insert the real conditional branch based on the original condition.
  4200. // If we did not create a new block for one of the 'true' or 'false' paths
  4201. // of the condition, it means that side of the branch goes to the end block
  4202. // directly and the path originates from the start block from the point of
  4203. // view of the new PHI.
  4204. BasicBlock *TT, *FT;
  4205. if (TrueBlock == nullptr) {
  4206. TT = EndBlock;
  4207. FT = FalseBlock;
  4208. TrueBlock = StartBlock;
  4209. } else if (FalseBlock == nullptr) {
  4210. TT = TrueBlock;
  4211. FT = EndBlock;
  4212. FalseBlock = StartBlock;
  4213. } else {
  4214. TT = TrueBlock;
  4215. FT = FalseBlock;
  4216. }
  4217. IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
  4218. SmallPtrSet<const Instruction *, 2> INS;
  4219. INS.insert(ASI.begin(), ASI.end());
  4220. // Use reverse iterator because later select may use the value of the
  4221. // earlier select, and we need to propagate value through earlier select
  4222. // to get the PHI operand.
  4223. for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
  4224. SelectInst *SI = *It;
  4225. // The select itself is replaced with a PHI Node.
  4226. PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
  4227. PN->takeName(SI);
  4228. PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
  4229. PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
  4230. SI->replaceAllUsesWith(PN);
  4231. SI->eraseFromParent();
  4232. INS.erase(SI);
  4233. ++NumSelectsExpanded;
  4234. }
  4235. // Instruct OptimizeBlock to skip to the next block.
  4236. CurInstIterator = StartBlock->end();
  4237. return true;
  4238. }
  4239. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  4240. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  4241. int SplatElem = -1;
  4242. for (unsigned i = 0; i < Mask.size(); ++i) {
  4243. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  4244. return false;
  4245. SplatElem = Mask[i];
  4246. }
  4247. return true;
  4248. }
  4249. /// Some targets have expensive vector shifts if the lanes aren't all the same
  4250. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  4251. /// it's often worth sinking a shufflevector splat down to its use so that
  4252. /// codegen can spot all lanes are identical.
  4253. bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  4254. BasicBlock *DefBB = SVI->getParent();
  4255. // Only do this xform if variable vector shifts are particularly expensive.
  4256. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  4257. return false;
  4258. // We only expect better codegen by sinking a shuffle if we can recognise a
  4259. // constant splat.
  4260. if (!isBroadcastShuffle(SVI))
  4261. return false;
  4262. // InsertedShuffles - Only insert a shuffle in each block once.
  4263. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  4264. bool MadeChange = false;
  4265. for (User *U : SVI->users()) {
  4266. Instruction *UI = cast<Instruction>(U);
  4267. // Figure out which BB this ext is used in.
  4268. BasicBlock *UserBB = UI->getParent();
  4269. if (UserBB == DefBB) continue;
  4270. // For now only apply this when the splat is used by a shift instruction.
  4271. if (!UI->isShift()) continue;
  4272. // Everything checks out, sink the shuffle if the user's block doesn't
  4273. // already have a copy.
  4274. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  4275. if (!InsertedShuffle) {
  4276. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  4277. assert(InsertPt != UserBB->end());
  4278. InsertedShuffle =
  4279. new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
  4280. SVI->getOperand(2), "", &*InsertPt);
  4281. }
  4282. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  4283. MadeChange = true;
  4284. }
  4285. // If we removed all uses, nuke the shuffle.
  4286. if (SVI->use_empty()) {
  4287. SVI->eraseFromParent();
  4288. MadeChange = true;
  4289. }
  4290. return MadeChange;
  4291. }
  4292. bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
  4293. if (!TLI || !DL)
  4294. return false;
  4295. Value *Cond = SI->getCondition();
  4296. Type *OldType = Cond->getType();
  4297. LLVMContext &Context = Cond->getContext();
  4298. MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
  4299. unsigned RegWidth = RegType.getSizeInBits();
  4300. if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
  4301. return false;
  4302. // If the register width is greater than the type width, expand the condition
  4303. // of the switch instruction and each case constant to the width of the
  4304. // register. By widening the type of the switch condition, subsequent
  4305. // comparisons (for case comparisons) will not need to be extended to the
  4306. // preferred register width, so we will potentially eliminate N-1 extends,
  4307. // where N is the number of cases in the switch.
  4308. auto *NewType = Type::getIntNTy(Context, RegWidth);
  4309. // Zero-extend the switch condition and case constants unless the switch
  4310. // condition is a function argument that is already being sign-extended.
  4311. // In that case, we can avoid an unnecessary mask/extension by sign-extending
  4312. // everything instead.
  4313. Instruction::CastOps ExtType = Instruction::ZExt;
  4314. if (auto *Arg = dyn_cast<Argument>(Cond))
  4315. if (Arg->hasSExtAttr())
  4316. ExtType = Instruction::SExt;
  4317. auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
  4318. ExtInst->insertBefore(SI);
  4319. SI->setCondition(ExtInst);
  4320. for (auto Case : SI->cases()) {
  4321. APInt NarrowConst = Case.getCaseValue()->getValue();
  4322. APInt WideConst = (ExtType == Instruction::ZExt) ?
  4323. NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
  4324. Case.setValue(ConstantInt::get(Context, WideConst));
  4325. }
  4326. return true;
  4327. }
  4328. namespace {
  4329. /// \brief Helper class to promote a scalar operation to a vector one.
  4330. /// This class is used to move downward extractelement transition.
  4331. /// E.g.,
  4332. /// a = vector_op <2 x i32>
  4333. /// b = extractelement <2 x i32> a, i32 0
  4334. /// c = scalar_op b
  4335. /// store c
  4336. ///
  4337. /// =>
  4338. /// a = vector_op <2 x i32>
  4339. /// c = vector_op a (equivalent to scalar_op on the related lane)
  4340. /// * d = extractelement <2 x i32> c, i32 0
  4341. /// * store d
  4342. /// Assuming both extractelement and store can be combine, we get rid of the
  4343. /// transition.
  4344. class VectorPromoteHelper {
  4345. /// DataLayout associated with the current module.
  4346. const DataLayout &DL;
  4347. /// Used to perform some checks on the legality of vector operations.
  4348. const TargetLowering &TLI;
  4349. /// Used to estimated the cost of the promoted chain.
  4350. const TargetTransformInfo &TTI;
  4351. /// The transition being moved downwards.
  4352. Instruction *Transition;
  4353. /// The sequence of instructions to be promoted.
  4354. SmallVector<Instruction *, 4> InstsToBePromoted;
  4355. /// Cost of combining a store and an extract.
  4356. unsigned StoreExtractCombineCost;
  4357. /// Instruction that will be combined with the transition.
  4358. Instruction *CombineInst;
  4359. /// \brief The instruction that represents the current end of the transition.
  4360. /// Since we are faking the promotion until we reach the end of the chain
  4361. /// of computation, we need a way to get the current end of the transition.
  4362. Instruction *getEndOfTransition() const {
  4363. if (InstsToBePromoted.empty())
  4364. return Transition;
  4365. return InstsToBePromoted.back();
  4366. }
  4367. /// \brief Return the index of the original value in the transition.
  4368. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  4369. /// c, is at index 0.
  4370. unsigned getTransitionOriginalValueIdx() const {
  4371. assert(isa<ExtractElementInst>(Transition) &&
  4372. "Other kind of transitions are not supported yet");
  4373. return 0;
  4374. }
  4375. /// \brief Return the index of the index in the transition.
  4376. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  4377. /// is at index 1.
  4378. unsigned getTransitionIdx() const {
  4379. assert(isa<ExtractElementInst>(Transition) &&
  4380. "Other kind of transitions are not supported yet");
  4381. return 1;
  4382. }
  4383. /// \brief Get the type of the transition.
  4384. /// This is the type of the original value.
  4385. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  4386. /// transition is <2 x i32>.
  4387. Type *getTransitionType() const {
  4388. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  4389. }
  4390. /// \brief Promote \p ToBePromoted by moving \p Def downward through.
  4391. /// I.e., we have the following sequence:
  4392. /// Def = Transition <ty1> a to <ty2>
  4393. /// b = ToBePromoted <ty2> Def, ...
  4394. /// =>
  4395. /// b = ToBePromoted <ty1> a, ...
  4396. /// Def = Transition <ty1> ToBePromoted to <ty2>
  4397. void promoteImpl(Instruction *ToBePromoted);
  4398. /// \brief Check whether or not it is profitable to promote all the
  4399. /// instructions enqueued to be promoted.
  4400. bool isProfitableToPromote() {
  4401. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  4402. unsigned Index = isa<ConstantInt>(ValIdx)
  4403. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  4404. : -1;
  4405. Type *PromotedType = getTransitionType();
  4406. StoreInst *ST = cast<StoreInst>(CombineInst);
  4407. unsigned AS = ST->getPointerAddressSpace();
  4408. unsigned Align = ST->getAlignment();
  4409. // Check if this store is supported.
  4410. if (!TLI.allowsMisalignedMemoryAccesses(
  4411. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  4412. Align)) {
  4413. // If this is not supported, there is no way we can combine
  4414. // the extract with the store.
  4415. return false;
  4416. }
  4417. // The scalar chain of computation has to pay for the transition
  4418. // scalar to vector.
  4419. // The vector chain has to account for the combining cost.
  4420. uint64_t ScalarCost =
  4421. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  4422. uint64_t VectorCost = StoreExtractCombineCost;
  4423. for (const auto &Inst : InstsToBePromoted) {
  4424. // Compute the cost.
  4425. // By construction, all instructions being promoted are arithmetic ones.
  4426. // Moreover, one argument is a constant that can be viewed as a splat
  4427. // constant.
  4428. Value *Arg0 = Inst->getOperand(0);
  4429. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  4430. isa<ConstantFP>(Arg0);
  4431. TargetTransformInfo::OperandValueKind Arg0OVK =
  4432. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  4433. : TargetTransformInfo::OK_AnyValue;
  4434. TargetTransformInfo::OperandValueKind Arg1OVK =
  4435. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  4436. : TargetTransformInfo::OK_AnyValue;
  4437. ScalarCost += TTI.getArithmeticInstrCost(
  4438. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  4439. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  4440. Arg0OVK, Arg1OVK);
  4441. }
  4442. DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  4443. << ScalarCost << "\nVector: " << VectorCost << '\n');
  4444. return ScalarCost > VectorCost;
  4445. }
  4446. /// \brief Generate a constant vector with \p Val with the same
  4447. /// number of elements as the transition.
  4448. /// \p UseSplat defines whether or not \p Val should be replicated
  4449. /// across the whole vector.
  4450. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  4451. /// otherwise we generate a vector with as many undef as possible:
  4452. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  4453. /// used at the index of the extract.
  4454. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  4455. unsigned ExtractIdx = UINT_MAX;
  4456. if (!UseSplat) {
  4457. // If we cannot determine where the constant must be, we have to
  4458. // use a splat constant.
  4459. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  4460. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  4461. ExtractIdx = CstVal->getSExtValue();
  4462. else
  4463. UseSplat = true;
  4464. }
  4465. unsigned End = getTransitionType()->getVectorNumElements();
  4466. if (UseSplat)
  4467. return ConstantVector::getSplat(End, Val);
  4468. SmallVector<Constant *, 4> ConstVec;
  4469. UndefValue *UndefVal = UndefValue::get(Val->getType());
  4470. for (unsigned Idx = 0; Idx != End; ++Idx) {
  4471. if (Idx == ExtractIdx)
  4472. ConstVec.push_back(Val);
  4473. else
  4474. ConstVec.push_back(UndefVal);
  4475. }
  4476. return ConstantVector::get(ConstVec);
  4477. }
  4478. /// \brief Check if promoting to a vector type an operand at \p OperandIdx
  4479. /// in \p Use can trigger undefined behavior.
  4480. static bool canCauseUndefinedBehavior(const Instruction *Use,
  4481. unsigned OperandIdx) {
  4482. // This is not safe to introduce undef when the operand is on
  4483. // the right hand side of a division-like instruction.
  4484. if (OperandIdx != 1)
  4485. return false;
  4486. switch (Use->getOpcode()) {
  4487. default:
  4488. return false;
  4489. case Instruction::SDiv:
  4490. case Instruction::UDiv:
  4491. case Instruction::SRem:
  4492. case Instruction::URem:
  4493. return true;
  4494. case Instruction::FDiv:
  4495. case Instruction::FRem:
  4496. return !Use->hasNoNaNs();
  4497. }
  4498. llvm_unreachable(nullptr);
  4499. }
  4500. public:
  4501. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  4502. const TargetTransformInfo &TTI, Instruction *Transition,
  4503. unsigned CombineCost)
  4504. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  4505. StoreExtractCombineCost(CombineCost), CombineInst(nullptr) {
  4506. assert(Transition && "Do not know how to promote null");
  4507. }
  4508. /// \brief Check if we can promote \p ToBePromoted to \p Type.
  4509. bool canPromote(const Instruction *ToBePromoted) const {
  4510. // We could support CastInst too.
  4511. return isa<BinaryOperator>(ToBePromoted);
  4512. }
  4513. /// \brief Check if it is profitable to promote \p ToBePromoted
  4514. /// by moving downward the transition through.
  4515. bool shouldPromote(const Instruction *ToBePromoted) const {
  4516. // Promote only if all the operands can be statically expanded.
  4517. // Indeed, we do not want to introduce any new kind of transitions.
  4518. for (const Use &U : ToBePromoted->operands()) {
  4519. const Value *Val = U.get();
  4520. if (Val == getEndOfTransition()) {
  4521. // If the use is a division and the transition is on the rhs,
  4522. // we cannot promote the operation, otherwise we may create a
  4523. // division by zero.
  4524. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  4525. return false;
  4526. continue;
  4527. }
  4528. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  4529. !isa<ConstantFP>(Val))
  4530. return false;
  4531. }
  4532. // Check that the resulting operation is legal.
  4533. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  4534. if (!ISDOpcode)
  4535. return false;
  4536. return StressStoreExtract ||
  4537. TLI.isOperationLegalOrCustom(
  4538. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  4539. }
  4540. /// \brief Check whether or not \p Use can be combined
  4541. /// with the transition.
  4542. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  4543. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  4544. /// \brief Record \p ToBePromoted as part of the chain to be promoted.
  4545. void enqueueForPromotion(Instruction *ToBePromoted) {
  4546. InstsToBePromoted.push_back(ToBePromoted);
  4547. }
  4548. /// \brief Set the instruction that will be combined with the transition.
  4549. void recordCombineInstruction(Instruction *ToBeCombined) {
  4550. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  4551. CombineInst = ToBeCombined;
  4552. }
  4553. /// \brief Promote all the instructions enqueued for promotion if it is
  4554. /// is profitable.
  4555. /// \return True if the promotion happened, false otherwise.
  4556. bool promote() {
  4557. // Check if there is something to promote.
  4558. // Right now, if we do not have anything to combine with,
  4559. // we assume the promotion is not profitable.
  4560. if (InstsToBePromoted.empty() || !CombineInst)
  4561. return false;
  4562. // Check cost.
  4563. if (!StressStoreExtract && !isProfitableToPromote())
  4564. return false;
  4565. // Promote.
  4566. for (auto &ToBePromoted : InstsToBePromoted)
  4567. promoteImpl(ToBePromoted);
  4568. InstsToBePromoted.clear();
  4569. return true;
  4570. }
  4571. };
  4572. } // End of anonymous namespace.
  4573. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  4574. // At this point, we know that all the operands of ToBePromoted but Def
  4575. // can be statically promoted.
  4576. // For Def, we need to use its parameter in ToBePromoted:
  4577. // b = ToBePromoted ty1 a
  4578. // Def = Transition ty1 b to ty2
  4579. // Move the transition down.
  4580. // 1. Replace all uses of the promoted operation by the transition.
  4581. // = ... b => = ... Def.
  4582. assert(ToBePromoted->getType() == Transition->getType() &&
  4583. "The type of the result of the transition does not match "
  4584. "the final type");
  4585. ToBePromoted->replaceAllUsesWith(Transition);
  4586. // 2. Update the type of the uses.
  4587. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  4588. Type *TransitionTy = getTransitionType();
  4589. ToBePromoted->mutateType(TransitionTy);
  4590. // 3. Update all the operands of the promoted operation with promoted
  4591. // operands.
  4592. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  4593. for (Use &U : ToBePromoted->operands()) {
  4594. Value *Val = U.get();
  4595. Value *NewVal = nullptr;
  4596. if (Val == Transition)
  4597. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  4598. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  4599. isa<ConstantFP>(Val)) {
  4600. // Use a splat constant if it is not safe to use undef.
  4601. NewVal = getConstantVector(
  4602. cast<Constant>(Val),
  4603. isa<UndefValue>(Val) ||
  4604. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  4605. } else
  4606. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  4607. "this?");
  4608. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  4609. }
  4610. Transition->removeFromParent();
  4611. Transition->insertAfter(ToBePromoted);
  4612. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  4613. }
  4614. /// Some targets can do store(extractelement) with one instruction.
  4615. /// Try to push the extractelement towards the stores when the target
  4616. /// has this feature and this is profitable.
  4617. bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
  4618. unsigned CombineCost = UINT_MAX;
  4619. if (DisableStoreExtract || !TLI ||
  4620. (!StressStoreExtract &&
  4621. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  4622. Inst->getOperand(1), CombineCost)))
  4623. return false;
  4624. // At this point we know that Inst is a vector to scalar transition.
  4625. // Try to move it down the def-use chain, until:
  4626. // - We can combine the transition with its single use
  4627. // => we got rid of the transition.
  4628. // - We escape the current basic block
  4629. // => we would need to check that we are moving it at a cheaper place and
  4630. // we do not do that for now.
  4631. BasicBlock *Parent = Inst->getParent();
  4632. DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  4633. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  4634. // If the transition has more than one use, assume this is not going to be
  4635. // beneficial.
  4636. while (Inst->hasOneUse()) {
  4637. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  4638. DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  4639. if (ToBePromoted->getParent() != Parent) {
  4640. DEBUG(dbgs() << "Instruction to promote is in a different block ("
  4641. << ToBePromoted->getParent()->getName()
  4642. << ") than the transition (" << Parent->getName() << ").\n");
  4643. return false;
  4644. }
  4645. if (VPH.canCombine(ToBePromoted)) {
  4646. DEBUG(dbgs() << "Assume " << *Inst << '\n'
  4647. << "will be combined with: " << *ToBePromoted << '\n');
  4648. VPH.recordCombineInstruction(ToBePromoted);
  4649. bool Changed = VPH.promote();
  4650. NumStoreExtractExposed += Changed;
  4651. return Changed;
  4652. }
  4653. DEBUG(dbgs() << "Try promoting.\n");
  4654. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  4655. return false;
  4656. DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  4657. VPH.enqueueForPromotion(ToBePromoted);
  4658. Inst = ToBePromoted;
  4659. }
  4660. return false;
  4661. }
  4662. /// For the instruction sequence of store below, F and I values
  4663. /// are bundled together as an i64 value before being stored into memory.
  4664. /// Sometimes it is more efficent to generate separate stores for F and I,
  4665. /// which can remove the bitwise instructions or sink them to colder places.
  4666. ///
  4667. /// (store (or (zext (bitcast F to i32) to i64),
  4668. /// (shl (zext I to i64), 32)), addr) -->
  4669. /// (store F, addr) and (store I, addr+4)
  4670. ///
  4671. /// Similarly, splitting for other merged store can also be beneficial, like:
  4672. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  4673. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  4674. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  4675. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  4676. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  4677. ///
  4678. /// We allow each target to determine specifically which kind of splitting is
  4679. /// supported.
  4680. ///
  4681. /// The store patterns are commonly seen from the simple code snippet below
  4682. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  4683. /// void goo(const std::pair<int, float> &);
  4684. /// hoo() {
  4685. /// ...
  4686. /// goo(std::make_pair(tmp, ftmp));
  4687. /// ...
  4688. /// }
  4689. ///
  4690. /// Although we already have similar splitting in DAG Combine, we duplicate
  4691. /// it in CodeGenPrepare to catch the case in which pattern is across
  4692. /// multiple BBs. The logic in DAG Combine is kept to catch case generated
  4693. /// during code expansion.
  4694. static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
  4695. const TargetLowering &TLI) {
  4696. // Handle simple but common cases only.
  4697. Type *StoreType = SI.getValueOperand()->getType();
  4698. if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
  4699. DL.getTypeSizeInBits(StoreType) == 0)
  4700. return false;
  4701. unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
  4702. Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
  4703. if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
  4704. DL.getTypeSizeInBits(SplitStoreType))
  4705. return false;
  4706. // Match the following patterns:
  4707. // (store (or (zext LValue to i64),
  4708. // (shl (zext HValue to i64), 32)), HalfValBitSize)
  4709. // or
  4710. // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
  4711. // (zext LValue to i64),
  4712. // Expect both operands of OR and the first operand of SHL have only
  4713. // one use.
  4714. Value *LValue, *HValue;
  4715. if (!match(SI.getValueOperand(),
  4716. m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
  4717. m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
  4718. m_SpecificInt(HalfValBitSize))))))
  4719. return false;
  4720. // Check LValue and HValue are int with size less or equal than 32.
  4721. if (!LValue->getType()->isIntegerTy() ||
  4722. DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
  4723. !HValue->getType()->isIntegerTy() ||
  4724. DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
  4725. return false;
  4726. // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
  4727. // as the input of target query.
  4728. auto *LBC = dyn_cast<BitCastInst>(LValue);
  4729. auto *HBC = dyn_cast<BitCastInst>(HValue);
  4730. EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
  4731. : EVT::getEVT(LValue->getType());
  4732. EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
  4733. : EVT::getEVT(HValue->getType());
  4734. if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  4735. return false;
  4736. // Start to split store.
  4737. IRBuilder<> Builder(SI.getContext());
  4738. Builder.SetInsertPoint(&SI);
  4739. // If LValue/HValue is a bitcast in another BB, create a new one in current
  4740. // BB so it may be merged with the splitted stores by dag combiner.
  4741. if (LBC && LBC->getParent() != SI.getParent())
  4742. LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
  4743. if (HBC && HBC->getParent() != SI.getParent())
  4744. HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
  4745. auto CreateSplitStore = [&](Value *V, bool Upper) {
  4746. V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
  4747. Value *Addr = Builder.CreateBitCast(
  4748. SI.getOperand(1),
  4749. SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
  4750. if (Upper)
  4751. Addr = Builder.CreateGEP(
  4752. SplitStoreType, Addr,
  4753. ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
  4754. Builder.CreateAlignedStore(
  4755. V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
  4756. };
  4757. CreateSplitStore(LValue, false);
  4758. CreateSplitStore(HValue, true);
  4759. // Delete the old store.
  4760. SI.eraseFromParent();
  4761. return true;
  4762. }
  4763. bool CodeGenPrepare::optimizeInst(Instruction *I, bool& ModifiedDT) {
  4764. // Bail out if we inserted the instruction to prevent optimizations from
  4765. // stepping on each other's toes.
  4766. if (InsertedInsts.count(I))
  4767. return false;
  4768. if (PHINode *P = dyn_cast<PHINode>(I)) {
  4769. // It is possible for very late stage optimizations (such as SimplifyCFG)
  4770. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  4771. // trivial PHI, go ahead and zap it here.
  4772. if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
  4773. P->replaceAllUsesWith(V);
  4774. P->eraseFromParent();
  4775. ++NumPHIsElim;
  4776. return true;
  4777. }
  4778. return false;
  4779. }
  4780. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  4781. // If the source of the cast is a constant, then this should have
  4782. // already been constant folded. The only reason NOT to constant fold
  4783. // it is if something (e.g. LSR) was careful to place the constant
  4784. // evaluation in a block other than then one that uses it (e.g. to hoist
  4785. // the address of globals out of a loop). If this is the case, we don't
  4786. // want to forward-subst the cast.
  4787. if (isa<Constant>(CI->getOperand(0)))
  4788. return false;
  4789. if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
  4790. return true;
  4791. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  4792. /// Sink a zext or sext into its user blocks if the target type doesn't
  4793. /// fit in one register
  4794. if (TLI &&
  4795. TLI->getTypeAction(CI->getContext(),
  4796. TLI->getValueType(*DL, CI->getType())) ==
  4797. TargetLowering::TypeExpandInteger) {
  4798. return SinkCast(CI);
  4799. } else {
  4800. bool MadeChange = optimizeExt(I);
  4801. return MadeChange | optimizeExtUses(I);
  4802. }
  4803. }
  4804. return false;
  4805. }
  4806. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  4807. if (!TLI || !TLI->hasMultipleConditionRegisters())
  4808. return OptimizeCmpExpression(CI, TLI);
  4809. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  4810. LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  4811. if (TLI) {
  4812. bool Modified = optimizeLoadExt(LI);
  4813. unsigned AS = LI->getPointerAddressSpace();
  4814. Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  4815. return Modified;
  4816. }
  4817. return false;
  4818. }
  4819. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  4820. if (TLI && splitMergedValStore(*SI, *DL, *TLI))
  4821. return true;
  4822. SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  4823. if (TLI) {
  4824. unsigned AS = SI->getPointerAddressSpace();
  4825. return optimizeMemoryInst(I, SI->getOperand(1),
  4826. SI->getOperand(0)->getType(), AS);
  4827. }
  4828. return false;
  4829. }
  4830. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  4831. unsigned AS = RMW->getPointerAddressSpace();
  4832. return optimizeMemoryInst(I, RMW->getPointerOperand(),
  4833. RMW->getType(), AS);
  4834. }
  4835. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
  4836. unsigned AS = CmpX->getPointerAddressSpace();
  4837. return optimizeMemoryInst(I, CmpX->getPointerOperand(),
  4838. CmpX->getCompareOperand()->getType(), AS);
  4839. }
  4840. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  4841. if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
  4842. EnableAndCmpSinking && TLI)
  4843. return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
  4844. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  4845. BinOp->getOpcode() == Instruction::LShr)) {
  4846. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  4847. if (TLI && CI && TLI->hasExtractBitsInsn())
  4848. return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
  4849. return false;
  4850. }
  4851. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  4852. if (GEPI->hasAllZeroIndices()) {
  4853. /// The GEP operand must be a pointer, so must its result -> BitCast
  4854. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  4855. GEPI->getName(), GEPI);
  4856. GEPI->replaceAllUsesWith(NC);
  4857. GEPI->eraseFromParent();
  4858. ++NumGEPsElim;
  4859. optimizeInst(NC, ModifiedDT);
  4860. return true;
  4861. }
  4862. return false;
  4863. }
  4864. if (CallInst *CI = dyn_cast<CallInst>(I))
  4865. return optimizeCallInst(CI, ModifiedDT);
  4866. if (SelectInst *SI = dyn_cast<SelectInst>(I))
  4867. return optimizeSelectInst(SI);
  4868. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
  4869. return optimizeShuffleVectorInst(SVI);
  4870. if (auto *Switch = dyn_cast<SwitchInst>(I))
  4871. return optimizeSwitchInst(Switch);
  4872. if (isa<ExtractElementInst>(I))
  4873. return optimizeExtractElementInst(I);
  4874. return false;
  4875. }
  4876. /// Given an OR instruction, check to see if this is a bitreverse
  4877. /// idiom. If so, insert the new intrinsic and return true.
  4878. static bool makeBitReverse(Instruction &I, const DataLayout &DL,
  4879. const TargetLowering &TLI) {
  4880. if (!I.getType()->isIntegerTy() ||
  4881. !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
  4882. TLI.getValueType(DL, I.getType(), true)))
  4883. return false;
  4884. SmallVector<Instruction*, 4> Insts;
  4885. if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
  4886. return false;
  4887. Instruction *LastInst = Insts.back();
  4888. I.replaceAllUsesWith(LastInst);
  4889. RecursivelyDeleteTriviallyDeadInstructions(&I);
  4890. return true;
  4891. }
  4892. // In this pass we look for GEP and cast instructions that are used
  4893. // across basic blocks and rewrite them to improve basic-block-at-a-time
  4894. // selection.
  4895. bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool& ModifiedDT) {
  4896. SunkAddrs.clear();
  4897. bool MadeChange = false;
  4898. CurInstIterator = BB.begin();
  4899. while (CurInstIterator != BB.end()) {
  4900. MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
  4901. if (ModifiedDT)
  4902. return true;
  4903. }
  4904. bool MadeBitReverse = true;
  4905. while (TLI && MadeBitReverse) {
  4906. MadeBitReverse = false;
  4907. for (auto &I : reverse(BB)) {
  4908. if (makeBitReverse(I, *DL, *TLI)) {
  4909. MadeBitReverse = MadeChange = true;
  4910. ModifiedDT = true;
  4911. break;
  4912. }
  4913. }
  4914. }
  4915. MadeChange |= dupRetToEnableTailCallOpts(&BB);
  4916. return MadeChange;
  4917. }
  4918. // llvm.dbg.value is far away from the value then iSel may not be able
  4919. // handle it properly. iSel will drop llvm.dbg.value if it can not
  4920. // find a node corresponding to the value.
  4921. bool CodeGenPrepare::placeDbgValues(Function &F) {
  4922. bool MadeChange = false;
  4923. for (BasicBlock &BB : F) {
  4924. Instruction *PrevNonDbgInst = nullptr;
  4925. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  4926. Instruction *Insn = &*BI++;
  4927. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  4928. // Leave dbg.values that refer to an alloca alone. These
  4929. // instrinsics describe the address of a variable (= the alloca)
  4930. // being taken. They should not be moved next to the alloca
  4931. // (and to the beginning of the scope), but rather stay close to
  4932. // where said address is used.
  4933. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  4934. PrevNonDbgInst = Insn;
  4935. continue;
  4936. }
  4937. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  4938. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  4939. // If VI is a phi in a block with an EHPad terminator, we can't insert
  4940. // after it.
  4941. if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
  4942. continue;
  4943. DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
  4944. DVI->removeFromParent();
  4945. if (isa<PHINode>(VI))
  4946. DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
  4947. else
  4948. DVI->insertAfter(VI);
  4949. MadeChange = true;
  4950. ++NumDbgValueMoved;
  4951. }
  4952. }
  4953. }
  4954. return MadeChange;
  4955. }
  4956. /// \brief Scale down both weights to fit into uint32_t.
  4957. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  4958. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  4959. uint32_t Scale = (NewMax / UINT32_MAX) + 1;
  4960. NewTrue = NewTrue / Scale;
  4961. NewFalse = NewFalse / Scale;
  4962. }
  4963. /// \brief Some targets prefer to split a conditional branch like:
  4964. /// \code
  4965. /// %0 = icmp ne i32 %a, 0
  4966. /// %1 = icmp ne i32 %b, 0
  4967. /// %or.cond = or i1 %0, %1
  4968. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  4969. /// \endcode
  4970. /// into multiple branch instructions like:
  4971. /// \code
  4972. /// bb1:
  4973. /// %0 = icmp ne i32 %a, 0
  4974. /// br i1 %0, label %TrueBB, label %bb2
  4975. /// bb2:
  4976. /// %1 = icmp ne i32 %b, 0
  4977. /// br i1 %1, label %TrueBB, label %FalseBB
  4978. /// \endcode
  4979. /// This usually allows instruction selection to do even further optimizations
  4980. /// and combine the compare with the branch instruction. Currently this is
  4981. /// applied for targets which have "cheap" jump instructions.
  4982. ///
  4983. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  4984. ///
  4985. bool CodeGenPrepare::splitBranchCondition(Function &F) {
  4986. if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
  4987. return false;
  4988. bool MadeChange = false;
  4989. for (auto &BB : F) {
  4990. // Does this BB end with the following?
  4991. // %cond1 = icmp|fcmp|binary instruction ...
  4992. // %cond2 = icmp|fcmp|binary instruction ...
  4993. // %cond.or = or|and i1 %cond1, cond2
  4994. // br i1 %cond.or label %dest1, label %dest2"
  4995. BinaryOperator *LogicOp;
  4996. BasicBlock *TBB, *FBB;
  4997. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  4998. continue;
  4999. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  5000. if (Br1->getMetadata(LLVMContext::MD_unpredictable))
  5001. continue;
  5002. unsigned Opc;
  5003. Value *Cond1, *Cond2;
  5004. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  5005. m_OneUse(m_Value(Cond2)))))
  5006. Opc = Instruction::And;
  5007. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  5008. m_OneUse(m_Value(Cond2)))))
  5009. Opc = Instruction::Or;
  5010. else
  5011. continue;
  5012. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  5013. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  5014. continue;
  5015. DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  5016. // Create a new BB.
  5017. auto TmpBB =
  5018. BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
  5019. BB.getParent(), BB.getNextNode());
  5020. // Update original basic block by using the first condition directly by the
  5021. // branch instruction and removing the no longer needed and/or instruction.
  5022. Br1->setCondition(Cond1);
  5023. LogicOp->eraseFromParent();
  5024. // Depending on the conditon we have to either replace the true or the false
  5025. // successor of the original branch instruction.
  5026. if (Opc == Instruction::And)
  5027. Br1->setSuccessor(0, TmpBB);
  5028. else
  5029. Br1->setSuccessor(1, TmpBB);
  5030. // Fill in the new basic block.
  5031. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  5032. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  5033. I->removeFromParent();
  5034. I->insertBefore(Br2);
  5035. }
  5036. // Update PHI nodes in both successors. The original BB needs to be
  5037. // replaced in one succesor's PHI nodes, because the branch comes now from
  5038. // the newly generated BB (NewBB). In the other successor we need to add one
  5039. // incoming edge to the PHI nodes, because both branch instructions target
  5040. // now the same successor. Depending on the original branch condition
  5041. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  5042. // we perform the correct update for the PHI nodes.
  5043. // This doesn't change the successor order of the just created branch
  5044. // instruction (or any other instruction).
  5045. if (Opc == Instruction::Or)
  5046. std::swap(TBB, FBB);
  5047. // Replace the old BB with the new BB.
  5048. for (auto &I : *TBB) {
  5049. PHINode *PN = dyn_cast<PHINode>(&I);
  5050. if (!PN)
  5051. break;
  5052. int i;
  5053. while ((i = PN->getBasicBlockIndex(&BB)) >= 0)
  5054. PN->setIncomingBlock(i, TmpBB);
  5055. }
  5056. // Add another incoming edge form the new BB.
  5057. for (auto &I : *FBB) {
  5058. PHINode *PN = dyn_cast<PHINode>(&I);
  5059. if (!PN)
  5060. break;
  5061. auto *Val = PN->getIncomingValueForBlock(&BB);
  5062. PN->addIncoming(Val, TmpBB);
  5063. }
  5064. // Update the branch weights (from SelectionDAGBuilder::
  5065. // FindMergedConditions).
  5066. if (Opc == Instruction::Or) {
  5067. // Codegen X | Y as:
  5068. // BB1:
  5069. // jmp_if_X TBB
  5070. // jmp TmpBB
  5071. // TmpBB:
  5072. // jmp_if_Y TBB
  5073. // jmp FBB
  5074. //
  5075. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  5076. // The requirement is that
  5077. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  5078. // = TrueProb for orignal BB.
  5079. // Assuming the orignal weights are A and B, one choice is to set BB1's
  5080. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  5081. // assumes that
  5082. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  5083. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  5084. // TmpBB, but the math is more complicated.
  5085. uint64_t TrueWeight, FalseWeight;
  5086. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  5087. uint64_t NewTrueWeight = TrueWeight;
  5088. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  5089. scaleWeights(NewTrueWeight, NewFalseWeight);
  5090. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  5091. .createBranchWeights(TrueWeight, FalseWeight));
  5092. NewTrueWeight = TrueWeight;
  5093. NewFalseWeight = 2 * FalseWeight;
  5094. scaleWeights(NewTrueWeight, NewFalseWeight);
  5095. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  5096. .createBranchWeights(TrueWeight, FalseWeight));
  5097. }
  5098. } else {
  5099. // Codegen X & Y as:
  5100. // BB1:
  5101. // jmp_if_X TmpBB
  5102. // jmp FBB
  5103. // TmpBB:
  5104. // jmp_if_Y TBB
  5105. // jmp FBB
  5106. //
  5107. // This requires creation of TmpBB after CurBB.
  5108. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  5109. // The requirement is that
  5110. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  5111. // = FalseProb for orignal BB.
  5112. // Assuming the orignal weights are A and B, one choice is to set BB1's
  5113. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  5114. // assumes that
  5115. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  5116. uint64_t TrueWeight, FalseWeight;
  5117. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  5118. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  5119. uint64_t NewFalseWeight = FalseWeight;
  5120. scaleWeights(NewTrueWeight, NewFalseWeight);
  5121. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  5122. .createBranchWeights(TrueWeight, FalseWeight));
  5123. NewTrueWeight = 2 * TrueWeight;
  5124. NewFalseWeight = FalseWeight;
  5125. scaleWeights(NewTrueWeight, NewFalseWeight);
  5126. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  5127. .createBranchWeights(TrueWeight, FalseWeight));
  5128. }
  5129. }
  5130. // Note: No point in getting fancy here, since the DT info is never
  5131. // available to CodeGenPrepare.
  5132. ModifiedDT = true;
  5133. MadeChange = true;
  5134. DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  5135. TmpBB->dump());
  5136. }
  5137. return MadeChange;
  5138. }