CodeGenPrepare.cpp 245 KB

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