CodeGenPrepare.cpp 209 KB

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