LoopVectorize.cpp 311 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654
  1. //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
  10. // and generates target-independent LLVM-IR.
  11. // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
  12. // of instructions in order to estimate the profitability of vectorization.
  13. //
  14. // The loop vectorizer combines consecutive loop iterations into a single
  15. // 'wide' iteration. After this transformation the index is incremented
  16. // by the SIMD vector width, and not by one.
  17. //
  18. // This pass has three parts:
  19. // 1. The main loop pass that drives the different parts.
  20. // 2. LoopVectorizationLegality - A unit that checks for the legality
  21. // of the vectorization.
  22. // 3. InnerLoopVectorizer - A unit that performs the actual
  23. // widening of instructions.
  24. // 4. LoopVectorizationCostModel - A unit that checks for the profitability
  25. // of vectorization. It decides on the optimal vector width, which
  26. // can be one, if vectorization is not profitable.
  27. //
  28. // There is a development effort going on to migrate loop vectorizer to the
  29. // VPlan infrastructure and to introduce outer loop vectorization support (see
  30. // docs/Proposal/VectorizationPlan.rst and
  31. // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
  32. // purpose, we temporarily introduced the VPlan-native vectorization path: an
  33. // alternative vectorization path that is natively implemented on top of the
  34. // VPlan infrastructure. See EnableVPlanNativePath for enabling.
  35. //
  36. //===----------------------------------------------------------------------===//
  37. //
  38. // The reduction-variable vectorization is based on the paper:
  39. // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
  40. //
  41. // Variable uniformity checks are inspired by:
  42. // Karrenberg, R. and Hack, S. Whole Function Vectorization.
  43. //
  44. // The interleaved access vectorization is based on the paper:
  45. // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
  46. // Data for SIMD
  47. //
  48. // Other ideas/concepts are from:
  49. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  50. //
  51. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  52. // Vectorizing Compilers.
  53. //
  54. //===----------------------------------------------------------------------===//
  55. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  56. #include "LoopVectorizationPlanner.h"
  57. #include "VPRecipeBuilder.h"
  58. #include "VPlanHCFGBuilder.h"
  59. #include "VPlanHCFGTransforms.h"
  60. #include "VPlanPredicator.h"
  61. #include "llvm/ADT/APInt.h"
  62. #include "llvm/ADT/ArrayRef.h"
  63. #include "llvm/ADT/DenseMap.h"
  64. #include "llvm/ADT/DenseMapInfo.h"
  65. #include "llvm/ADT/Hashing.h"
  66. #include "llvm/ADT/MapVector.h"
  67. #include "llvm/ADT/None.h"
  68. #include "llvm/ADT/Optional.h"
  69. #include "llvm/ADT/STLExtras.h"
  70. #include "llvm/ADT/SetVector.h"
  71. #include "llvm/ADT/SmallPtrSet.h"
  72. #include "llvm/ADT/SmallVector.h"
  73. #include "llvm/ADT/Statistic.h"
  74. #include "llvm/ADT/StringRef.h"
  75. #include "llvm/ADT/Twine.h"
  76. #include "llvm/ADT/iterator_range.h"
  77. #include "llvm/Analysis/AssumptionCache.h"
  78. #include "llvm/Analysis/BasicAliasAnalysis.h"
  79. #include "llvm/Analysis/BlockFrequencyInfo.h"
  80. #include "llvm/Analysis/CFG.h"
  81. #include "llvm/Analysis/CodeMetrics.h"
  82. #include "llvm/Analysis/DemandedBits.h"
  83. #include "llvm/Analysis/GlobalsModRef.h"
  84. #include "llvm/Analysis/LoopAccessAnalysis.h"
  85. #include "llvm/Analysis/LoopAnalysisManager.h"
  86. #include "llvm/Analysis/LoopInfo.h"
  87. #include "llvm/Analysis/LoopIterator.h"
  88. #include "llvm/Analysis/MemorySSA.h"
  89. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  90. #include "llvm/Analysis/ProfileSummaryInfo.h"
  91. #include "llvm/Analysis/ScalarEvolution.h"
  92. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  93. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  94. #include "llvm/Analysis/TargetLibraryInfo.h"
  95. #include "llvm/Analysis/TargetTransformInfo.h"
  96. #include "llvm/Analysis/VectorUtils.h"
  97. #include "llvm/IR/Attributes.h"
  98. #include "llvm/IR/BasicBlock.h"
  99. #include "llvm/IR/CFG.h"
  100. #include "llvm/IR/Constant.h"
  101. #include "llvm/IR/Constants.h"
  102. #include "llvm/IR/DataLayout.h"
  103. #include "llvm/IR/DebugInfoMetadata.h"
  104. #include "llvm/IR/DebugLoc.h"
  105. #include "llvm/IR/DerivedTypes.h"
  106. #include "llvm/IR/DiagnosticInfo.h"
  107. #include "llvm/IR/Dominators.h"
  108. #include "llvm/IR/Function.h"
  109. #include "llvm/IR/IRBuilder.h"
  110. #include "llvm/IR/InstrTypes.h"
  111. #include "llvm/IR/Instruction.h"
  112. #include "llvm/IR/Instructions.h"
  113. #include "llvm/IR/IntrinsicInst.h"
  114. #include "llvm/IR/Intrinsics.h"
  115. #include "llvm/IR/LLVMContext.h"
  116. #include "llvm/IR/Metadata.h"
  117. #include "llvm/IR/Module.h"
  118. #include "llvm/IR/Operator.h"
  119. #include "llvm/IR/Type.h"
  120. #include "llvm/IR/Use.h"
  121. #include "llvm/IR/User.h"
  122. #include "llvm/IR/Value.h"
  123. #include "llvm/IR/ValueHandle.h"
  124. #include "llvm/IR/Verifier.h"
  125. #include "llvm/Pass.h"
  126. #include "llvm/Support/Casting.h"
  127. #include "llvm/Support/CommandLine.h"
  128. #include "llvm/Support/Compiler.h"
  129. #include "llvm/Support/Debug.h"
  130. #include "llvm/Support/ErrorHandling.h"
  131. #include "llvm/Support/MathExtras.h"
  132. #include "llvm/Support/raw_ostream.h"
  133. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  134. #include "llvm/Transforms/Utils/LoopSimplify.h"
  135. #include "llvm/Transforms/Utils/LoopUtils.h"
  136. #include "llvm/Transforms/Utils/LoopVersioning.h"
  137. #include "llvm/Transforms/Utils/SizeOpts.h"
  138. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  139. #include <algorithm>
  140. #include <cassert>
  141. #include <cstdint>
  142. #include <cstdlib>
  143. #include <functional>
  144. #include <iterator>
  145. #include <limits>
  146. #include <memory>
  147. #include <string>
  148. #include <tuple>
  149. #include <utility>
  150. #include <vector>
  151. using namespace llvm;
  152. #define LV_NAME "loop-vectorize"
  153. #define DEBUG_TYPE LV_NAME
  154. /// @{
  155. /// Metadata attribute names
  156. static const char *const LLVMLoopVectorizeFollowupAll =
  157. "llvm.loop.vectorize.followup_all";
  158. static const char *const LLVMLoopVectorizeFollowupVectorized =
  159. "llvm.loop.vectorize.followup_vectorized";
  160. static const char *const LLVMLoopVectorizeFollowupEpilogue =
  161. "llvm.loop.vectorize.followup_epilogue";
  162. /// @}
  163. STATISTIC(LoopsVectorized, "Number of loops vectorized");
  164. STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
  165. /// Loops with a known constant trip count below this number are vectorized only
  166. /// if no scalar iteration overheads are incurred.
  167. static cl::opt<unsigned> TinyTripCountVectorThreshold(
  168. "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
  169. cl::desc("Loops with a constant trip count that is smaller than this "
  170. "value are vectorized only if no scalar iteration overheads "
  171. "are incurred."));
  172. static cl::opt<bool> MaximizeBandwidth(
  173. "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
  174. cl::desc("Maximize bandwidth when selecting vectorization factor which "
  175. "will be determined by the smallest type in loop."));
  176. static cl::opt<bool> EnableInterleavedMemAccesses(
  177. "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  178. cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
  179. /// An interleave-group may need masking if it resides in a block that needs
  180. /// predication, or in order to mask away gaps.
  181. static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
  182. "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  183. cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
  184. /// We don't interleave loops with a known constant trip count below this
  185. /// number.
  186. static const unsigned TinyTripCountInterleaveThreshold = 128;
  187. static cl::opt<unsigned> ForceTargetNumScalarRegs(
  188. "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
  189. cl::desc("A flag that overrides the target's number of scalar registers."));
  190. static cl::opt<unsigned> ForceTargetNumVectorRegs(
  191. "force-target-num-vector-regs", cl::init(0), cl::Hidden,
  192. cl::desc("A flag that overrides the target's number of vector registers."));
  193. static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
  194. "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
  195. cl::desc("A flag that overrides the target's max interleave factor for "
  196. "scalar loops."));
  197. static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
  198. "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
  199. cl::desc("A flag that overrides the target's max interleave factor for "
  200. "vectorized loops."));
  201. static cl::opt<unsigned> ForceTargetInstructionCost(
  202. "force-target-instruction-cost", cl::init(0), cl::Hidden,
  203. cl::desc("A flag that overrides the target's expected cost for "
  204. "an instruction to a single constant value. Mostly "
  205. "useful for getting consistent testing."));
  206. static cl::opt<unsigned> SmallLoopCost(
  207. "small-loop-cost", cl::init(20), cl::Hidden,
  208. cl::desc(
  209. "The cost of a loop that is considered 'small' by the interleaver."));
  210. static cl::opt<bool> LoopVectorizeWithBlockFrequency(
  211. "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
  212. cl::desc("Enable the use of the block frequency analysis to access PGO "
  213. "heuristics minimizing code growth in cold regions and being more "
  214. "aggressive in hot regions."));
  215. // Runtime interleave loops for load/store throughput.
  216. static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
  217. "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
  218. cl::desc(
  219. "Enable runtime interleaving until load/store ports are saturated"));
  220. /// The number of stores in a loop that are allowed to need predication.
  221. static cl::opt<unsigned> NumberOfStoresToPredicate(
  222. "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
  223. cl::desc("Max number of stores to be predicated behind an if."));
  224. static cl::opt<bool> EnableIndVarRegisterHeur(
  225. "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
  226. cl::desc("Count the induction variable only once when interleaving"));
  227. static cl::opt<bool> EnableCondStoresVectorization(
  228. "enable-cond-stores-vec", cl::init(true), cl::Hidden,
  229. cl::desc("Enable if predication of stores during vectorization."));
  230. static cl::opt<unsigned> MaxNestedScalarReductionIC(
  231. "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
  232. cl::desc("The maximum interleave count to use when interleaving a scalar "
  233. "reduction in a nested loop."));
  234. cl::opt<bool> EnableVPlanNativePath(
  235. "enable-vplan-native-path", cl::init(false), cl::Hidden,
  236. cl::desc("Enable VPlan-native vectorization path with "
  237. "support for outer loop vectorization."));
  238. // FIXME: Remove this switch once we have divergence analysis. Currently we
  239. // assume divergent non-backedge branches when this switch is true.
  240. cl::opt<bool> EnableVPlanPredication(
  241. "enable-vplan-predication", cl::init(false), cl::Hidden,
  242. cl::desc("Enable VPlan-native vectorization path predicator with "
  243. "support for outer loop vectorization."));
  244. // This flag enables the stress testing of the VPlan H-CFG construction in the
  245. // VPlan-native vectorization path. It must be used in conjuction with
  246. // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
  247. // verification of the H-CFGs built.
  248. static cl::opt<bool> VPlanBuildStressTest(
  249. "vplan-build-stress-test", cl::init(false), cl::Hidden,
  250. cl::desc(
  251. "Build VPlan for every supported loop nest in the function and bail "
  252. "out right after the build (stress test the VPlan H-CFG construction "
  253. "in the VPlan-native vectorization path)."));
  254. cl::opt<bool> llvm::EnableLoopInterleaving(
  255. "interleave-loops", cl::init(true), cl::Hidden,
  256. cl::desc("Enable loop interleaving in Loop vectorization passes"));
  257. cl::opt<bool> llvm::EnableLoopVectorization(
  258. "vectorize-loops", cl::init(true), cl::Hidden,
  259. cl::desc("Run the Loop vectorization passes"));
  260. /// A helper function for converting Scalar types to vector types.
  261. /// If the incoming type is void, we return void. If the VF is 1, we return
  262. /// the scalar type.
  263. static Type *ToVectorTy(Type *Scalar, unsigned VF) {
  264. if (Scalar->isVoidTy() || VF == 1)
  265. return Scalar;
  266. return VectorType::get(Scalar, VF);
  267. }
  268. /// A helper function that returns the type of loaded or stored value.
  269. static Type *getMemInstValueType(Value *I) {
  270. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  271. "Expected Load or Store instruction");
  272. if (auto *LI = dyn_cast<LoadInst>(I))
  273. return LI->getType();
  274. return cast<StoreInst>(I)->getValueOperand()->getType();
  275. }
  276. /// A helper function that returns true if the given type is irregular. The
  277. /// type is irregular if its allocated size doesn't equal the store size of an
  278. /// element of the corresponding vector type at the given vectorization factor.
  279. static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
  280. // Determine if an array of VF elements of type Ty is "bitcast compatible"
  281. // with a <VF x Ty> vector.
  282. if (VF > 1) {
  283. auto *VectorTy = VectorType::get(Ty, VF);
  284. return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
  285. }
  286. // If the vectorization factor is one, we just check if an array of type Ty
  287. // requires padding between elements.
  288. return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
  289. }
  290. /// A helper function that returns the reciprocal of the block probability of
  291. /// predicated blocks. If we return X, we are assuming the predicated block
  292. /// will execute once for every X iterations of the loop header.
  293. ///
  294. /// TODO: We should use actual block probability here, if available. Currently,
  295. /// we always assume predicated blocks have a 50% chance of executing.
  296. static unsigned getReciprocalPredBlockProb() { return 2; }
  297. /// A helper function that adds a 'fast' flag to floating-point operations.
  298. static Value *addFastMathFlag(Value *V) {
  299. if (isa<FPMathOperator>(V))
  300. cast<Instruction>(V)->setFastMathFlags(FastMathFlags::getFast());
  301. return V;
  302. }
  303. static Value *addFastMathFlag(Value *V, FastMathFlags FMF) {
  304. if (isa<FPMathOperator>(V))
  305. cast<Instruction>(V)->setFastMathFlags(FMF);
  306. return V;
  307. }
  308. /// A helper function that returns an integer or floating-point constant with
  309. /// value C.
  310. static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
  311. return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
  312. : ConstantFP::get(Ty, C);
  313. }
  314. namespace llvm {
  315. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  316. /// block to a specified vectorization factor (VF).
  317. /// This class performs the widening of scalars into vectors, or multiple
  318. /// scalars. This class also implements the following features:
  319. /// * It inserts an epilogue loop for handling loops that don't have iteration
  320. /// counts that are known to be a multiple of the vectorization factor.
  321. /// * It handles the code generation for reduction variables.
  322. /// * Scalarization (implementation using scalars) of un-vectorizable
  323. /// instructions.
  324. /// InnerLoopVectorizer does not perform any vectorization-legality
  325. /// checks, and relies on the caller to check for the different legality
  326. /// aspects. The InnerLoopVectorizer relies on the
  327. /// LoopVectorizationLegality class to provide information about the induction
  328. /// and reduction variables that were found to a given vectorization factor.
  329. class InnerLoopVectorizer {
  330. public:
  331. InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  332. LoopInfo *LI, DominatorTree *DT,
  333. const TargetLibraryInfo *TLI,
  334. const TargetTransformInfo *TTI, AssumptionCache *AC,
  335. OptimizationRemarkEmitter *ORE, unsigned VecWidth,
  336. unsigned UnrollFactor, LoopVectorizationLegality *LVL,
  337. LoopVectorizationCostModel *CM)
  338. : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
  339. AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
  340. Builder(PSE.getSE()->getContext()),
  341. VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
  342. virtual ~InnerLoopVectorizer() = default;
  343. /// Create a new empty loop. Unlink the old loop and connect the new one.
  344. /// Return the pre-header block of the new loop.
  345. BasicBlock *createVectorizedLoopSkeleton();
  346. /// Widen a single instruction within the innermost loop.
  347. void widenInstruction(Instruction &I);
  348. /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
  349. void fixVectorizedLoop();
  350. // Return true if any runtime check is added.
  351. bool areSafetyChecksAdded() { return AddedSafetyChecks; }
  352. /// A type for vectorized values in the new loop. Each value from the
  353. /// original loop, when vectorized, is represented by UF vector values in the
  354. /// new unrolled loop, where UF is the unroll factor.
  355. using VectorParts = SmallVector<Value *, 2>;
  356. /// Vectorize a single PHINode in a block. This method handles the induction
  357. /// variable canonicalization. It supports both VF = 1 for unrolled loops and
  358. /// arbitrary length vectors.
  359. void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
  360. /// A helper function to scalarize a single Instruction in the innermost loop.
  361. /// Generates a sequence of scalar instances for each lane between \p MinLane
  362. /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
  363. /// inclusive..
  364. void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
  365. bool IfPredicateInstr);
  366. /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
  367. /// is provided, the integer induction variable will first be truncated to
  368. /// the corresponding type.
  369. void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
  370. /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
  371. /// vector or scalar value on-demand if one is not yet available. When
  372. /// vectorizing a loop, we visit the definition of an instruction before its
  373. /// uses. When visiting the definition, we either vectorize or scalarize the
  374. /// instruction, creating an entry for it in the corresponding map. (In some
  375. /// cases, such as induction variables, we will create both vector and scalar
  376. /// entries.) Then, as we encounter uses of the definition, we derive values
  377. /// for each scalar or vector use unless such a value is already available.
  378. /// For example, if we scalarize a definition and one of its uses is vector,
  379. /// we build the required vector on-demand with an insertelement sequence
  380. /// when visiting the use. Otherwise, if the use is scalar, we can use the
  381. /// existing scalar definition.
  382. ///
  383. /// Return a value in the new loop corresponding to \p V from the original
  384. /// loop at unroll index \p Part. If the value has already been vectorized,
  385. /// the corresponding vector entry in VectorLoopValueMap is returned. If,
  386. /// however, the value has a scalar entry in VectorLoopValueMap, we construct
  387. /// a new vector value on-demand by inserting the scalar values into a vector
  388. /// with an insertelement sequence. If the value has been neither vectorized
  389. /// nor scalarized, it must be loop invariant, so we simply broadcast the
  390. /// value into a vector.
  391. Value *getOrCreateVectorValue(Value *V, unsigned Part);
  392. /// Return a value in the new loop corresponding to \p V from the original
  393. /// loop at unroll and vector indices \p Instance. If the value has been
  394. /// vectorized but not scalarized, the necessary extractelement instruction
  395. /// will be generated.
  396. Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
  397. /// Construct the vector value of a scalarized value \p V one lane at a time.
  398. void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
  399. /// Try to vectorize the interleaved access group that \p Instr belongs to,
  400. /// optionally masking the vector operations if \p BlockInMask is non-null.
  401. void vectorizeInterleaveGroup(Instruction *Instr,
  402. VectorParts *BlockInMask = nullptr);
  403. /// Vectorize Load and Store instructions, optionally masking the vector
  404. /// operations if \p BlockInMask is non-null.
  405. void vectorizeMemoryInstruction(Instruction *Instr,
  406. VectorParts *BlockInMask = nullptr);
  407. /// Set the debug location in the builder using the debug location in
  408. /// the instruction.
  409. void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
  410. /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
  411. void fixNonInductionPHIs(void);
  412. protected:
  413. friend class LoopVectorizationPlanner;
  414. /// A small list of PHINodes.
  415. using PhiVector = SmallVector<PHINode *, 4>;
  416. /// A type for scalarized values in the new loop. Each value from the
  417. /// original loop, when scalarized, is represented by UF x VF scalar values
  418. /// in the new unrolled loop, where UF is the unroll factor and VF is the
  419. /// vectorization factor.
  420. using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
  421. /// Set up the values of the IVs correctly when exiting the vector loop.
  422. void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
  423. Value *CountRoundDown, Value *EndValue,
  424. BasicBlock *MiddleBlock);
  425. /// Create a new induction variable inside L.
  426. PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
  427. Value *Step, Instruction *DL);
  428. /// Handle all cross-iteration phis in the header.
  429. void fixCrossIterationPHIs();
  430. /// Fix a first-order recurrence. This is the second phase of vectorizing
  431. /// this phi node.
  432. void fixFirstOrderRecurrence(PHINode *Phi);
  433. /// Fix a reduction cross-iteration phi. This is the second phase of
  434. /// vectorizing this phi node.
  435. void fixReduction(PHINode *Phi);
  436. /// The Loop exit block may have single value PHI nodes with some
  437. /// incoming value. While vectorizing we only handled real values
  438. /// that were defined inside the loop and we should have one value for
  439. /// each predecessor of its parent basic block. See PR14725.
  440. void fixLCSSAPHIs();
  441. /// Iteratively sink the scalarized operands of a predicated instruction into
  442. /// the block that was created for it.
  443. void sinkScalarOperands(Instruction *PredInst);
  444. /// Shrinks vector element sizes to the smallest bitwidth they can be legally
  445. /// represented as.
  446. void truncateToMinimalBitwidths();
  447. /// Insert the new loop to the loop hierarchy and pass manager
  448. /// and update the analysis passes.
  449. void updateAnalysis();
  450. /// Create a broadcast instruction. This method generates a broadcast
  451. /// instruction (shuffle) for loop invariant values and for the induction
  452. /// value. If this is the induction variable then we extend it to N, N+1, ...
  453. /// this is needed because each iteration in the loop corresponds to a SIMD
  454. /// element.
  455. virtual Value *getBroadcastInstrs(Value *V);
  456. /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
  457. /// to each vector element of Val. The sequence starts at StartIndex.
  458. /// \p Opcode is relevant for FP induction variable.
  459. virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  460. Instruction::BinaryOps Opcode =
  461. Instruction::BinaryOpsEnd);
  462. /// Compute scalar induction steps. \p ScalarIV is the scalar induction
  463. /// variable on which to base the steps, \p Step is the size of the step, and
  464. /// \p EntryVal is the value from the original loop that maps to the steps.
  465. /// Note that \p EntryVal doesn't have to be an induction variable - it
  466. /// can also be a truncate instruction.
  467. void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
  468. const InductionDescriptor &ID);
  469. /// Create a vector induction phi node based on an existing scalar one. \p
  470. /// EntryVal is the value from the original loop that maps to the vector phi
  471. /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
  472. /// truncate instruction, instead of widening the original IV, we widen a
  473. /// version of the IV truncated to \p EntryVal's type.
  474. void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
  475. Value *Step, Instruction *EntryVal);
  476. /// Returns true if an instruction \p I should be scalarized instead of
  477. /// vectorized for the chosen vectorization factor.
  478. bool shouldScalarizeInstruction(Instruction *I) const;
  479. /// Returns true if we should generate a scalar version of \p IV.
  480. bool needsScalarInduction(Instruction *IV) const;
  481. /// If there is a cast involved in the induction variable \p ID, which should
  482. /// be ignored in the vectorized loop body, this function records the
  483. /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
  484. /// cast. We had already proved that the casted Phi is equal to the uncasted
  485. /// Phi in the vectorized loop (under a runtime guard), and therefore
  486. /// there is no need to vectorize the cast - the same value can be used in the
  487. /// vector loop for both the Phi and the cast.
  488. /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
  489. /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
  490. ///
  491. /// \p EntryVal is the value from the original loop that maps to the vector
  492. /// phi node and is used to distinguish what is the IV currently being
  493. /// processed - original one (if \p EntryVal is a phi corresponding to the
  494. /// original IV) or the "newly-created" one based on the proof mentioned above
  495. /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
  496. /// latter case \p EntryVal is a TruncInst and we must not record anything for
  497. /// that IV, but it's error-prone to expect callers of this routine to care
  498. /// about that, hence this explicit parameter.
  499. void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID,
  500. const Instruction *EntryVal,
  501. Value *VectorLoopValue,
  502. unsigned Part,
  503. unsigned Lane = UINT_MAX);
  504. /// Generate a shuffle sequence that will reverse the vector Vec.
  505. virtual Value *reverseVector(Value *Vec);
  506. /// Returns (and creates if needed) the original loop trip count.
  507. Value *getOrCreateTripCount(Loop *NewLoop);
  508. /// Returns (and creates if needed) the trip count of the widened loop.
  509. Value *getOrCreateVectorTripCount(Loop *NewLoop);
  510. /// Returns a bitcasted value to the requested vector type.
  511. /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
  512. Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
  513. const DataLayout &DL);
  514. /// Emit a bypass check to see if the vector trip count is zero, including if
  515. /// it overflows.
  516. void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
  517. /// Emit a bypass check to see if all of the SCEV assumptions we've
  518. /// had to make are correct.
  519. void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
  520. /// Emit bypass checks to check any memory assumptions we may have made.
  521. void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
  522. /// Compute the transformed value of Index at offset StartValue using step
  523. /// StepValue.
  524. /// For integer induction, returns StartValue + Index * StepValue.
  525. /// For pointer induction, returns StartValue[Index * StepValue].
  526. /// FIXME: The newly created binary instructions should contain nsw/nuw
  527. /// flags, which can be found from the original scalar operations.
  528. Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
  529. const DataLayout &DL,
  530. const InductionDescriptor &ID) const;
  531. /// Add additional metadata to \p To that was not present on \p Orig.
  532. ///
  533. /// Currently this is used to add the noalias annotations based on the
  534. /// inserted memchecks. Use this for instructions that are *cloned* into the
  535. /// vector loop.
  536. void addNewMetadata(Instruction *To, const Instruction *Orig);
  537. /// Add metadata from one instruction to another.
  538. ///
  539. /// This includes both the original MDs from \p From and additional ones (\see
  540. /// addNewMetadata). Use this for *newly created* instructions in the vector
  541. /// loop.
  542. void addMetadata(Instruction *To, Instruction *From);
  543. /// Similar to the previous function but it adds the metadata to a
  544. /// vector of instructions.
  545. void addMetadata(ArrayRef<Value *> To, Instruction *From);
  546. /// The original loop.
  547. Loop *OrigLoop;
  548. /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
  549. /// dynamic knowledge to simplify SCEV expressions and converts them to a
  550. /// more usable form.
  551. PredicatedScalarEvolution &PSE;
  552. /// Loop Info.
  553. LoopInfo *LI;
  554. /// Dominator Tree.
  555. DominatorTree *DT;
  556. /// Alias Analysis.
  557. AliasAnalysis *AA;
  558. /// Target Library Info.
  559. const TargetLibraryInfo *TLI;
  560. /// Target Transform Info.
  561. const TargetTransformInfo *TTI;
  562. /// Assumption Cache.
  563. AssumptionCache *AC;
  564. /// Interface to emit optimization remarks.
  565. OptimizationRemarkEmitter *ORE;
  566. /// LoopVersioning. It's only set up (non-null) if memchecks were
  567. /// used.
  568. ///
  569. /// This is currently only used to add no-alias metadata based on the
  570. /// memchecks. The actually versioning is performed manually.
  571. std::unique_ptr<LoopVersioning> LVer;
  572. /// The vectorization SIMD factor to use. Each vector will have this many
  573. /// vector elements.
  574. unsigned VF;
  575. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  576. /// many different vector instructions.
  577. unsigned UF;
  578. /// The builder that we use
  579. IRBuilder<> Builder;
  580. // --- Vectorization state ---
  581. /// The vector-loop preheader.
  582. BasicBlock *LoopVectorPreHeader;
  583. /// The scalar-loop preheader.
  584. BasicBlock *LoopScalarPreHeader;
  585. /// Middle Block between the vector and the scalar.
  586. BasicBlock *LoopMiddleBlock;
  587. /// The ExitBlock of the scalar loop.
  588. BasicBlock *LoopExitBlock;
  589. /// The vector loop body.
  590. BasicBlock *LoopVectorBody;
  591. /// The scalar loop body.
  592. BasicBlock *LoopScalarBody;
  593. /// A list of all bypass blocks. The first block is the entry of the loop.
  594. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  595. /// The new Induction variable which was added to the new block.
  596. PHINode *Induction = nullptr;
  597. /// The induction variable of the old basic block.
  598. PHINode *OldInduction = nullptr;
  599. /// Maps values from the original loop to their corresponding values in the
  600. /// vectorized loop. A key value can map to either vector values, scalar
  601. /// values or both kinds of values, depending on whether the key was
  602. /// vectorized and scalarized.
  603. VectorizerValueMap VectorLoopValueMap;
  604. /// Store instructions that were predicated.
  605. SmallVector<Instruction *, 4> PredicatedInstructions;
  606. /// Trip count of the original loop.
  607. Value *TripCount = nullptr;
  608. /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
  609. Value *VectorTripCount = nullptr;
  610. /// The legality analysis.
  611. LoopVectorizationLegality *Legal;
  612. /// The profitablity analysis.
  613. LoopVectorizationCostModel *Cost;
  614. // Record whether runtime checks are added.
  615. bool AddedSafetyChecks = false;
  616. // Holds the end values for each induction variable. We save the end values
  617. // so we can later fix-up the external users of the induction variables.
  618. DenseMap<PHINode *, Value *> IVEndValues;
  619. // Vector of original scalar PHIs whose corresponding widened PHIs need to be
  620. // fixed up at the end of vector code generation.
  621. SmallVector<PHINode *, 8> OrigPHIsToFix;
  622. };
  623. class InnerLoopUnroller : public InnerLoopVectorizer {
  624. public:
  625. InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  626. LoopInfo *LI, DominatorTree *DT,
  627. const TargetLibraryInfo *TLI,
  628. const TargetTransformInfo *TTI, AssumptionCache *AC,
  629. OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
  630. LoopVectorizationLegality *LVL,
  631. LoopVectorizationCostModel *CM)
  632. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
  633. UnrollFactor, LVL, CM) {}
  634. private:
  635. Value *getBroadcastInstrs(Value *V) override;
  636. Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  637. Instruction::BinaryOps Opcode =
  638. Instruction::BinaryOpsEnd) override;
  639. Value *reverseVector(Value *Vec) override;
  640. };
  641. } // end namespace llvm
  642. /// Look for a meaningful debug location on the instruction or it's
  643. /// operands.
  644. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  645. if (!I)
  646. return I;
  647. DebugLoc Empty;
  648. if (I->getDebugLoc() != Empty)
  649. return I;
  650. for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
  651. if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
  652. if (OpInst->getDebugLoc() != Empty)
  653. return OpInst;
  654. }
  655. return I;
  656. }
  657. void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
  658. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
  659. const DILocation *DIL = Inst->getDebugLoc();
  660. if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
  661. !isa<DbgInfoIntrinsic>(Inst)) {
  662. auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(UF * VF);
  663. if (NewDIL)
  664. B.SetCurrentDebugLocation(NewDIL.getValue());
  665. else
  666. LLVM_DEBUG(dbgs()
  667. << "Failed to create new discriminator: "
  668. << DIL->getFilename() << " Line: " << DIL->getLine());
  669. }
  670. else
  671. B.SetCurrentDebugLocation(DIL);
  672. } else
  673. B.SetCurrentDebugLocation(DebugLoc());
  674. }
  675. #ifndef NDEBUG
  676. /// \return string containing a file name and a line # for the given loop.
  677. static std::string getDebugLocString(const Loop *L) {
  678. std::string Result;
  679. if (L) {
  680. raw_string_ostream OS(Result);
  681. if (const DebugLoc LoopDbgLoc = L->getStartLoc())
  682. LoopDbgLoc.print(OS);
  683. else
  684. // Just print the module name.
  685. OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
  686. OS.flush();
  687. }
  688. return Result;
  689. }
  690. #endif
  691. void InnerLoopVectorizer::addNewMetadata(Instruction *To,
  692. const Instruction *Orig) {
  693. // If the loop was versioned with memchecks, add the corresponding no-alias
  694. // metadata.
  695. if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
  696. LVer->annotateInstWithNoAlias(To, Orig);
  697. }
  698. void InnerLoopVectorizer::addMetadata(Instruction *To,
  699. Instruction *From) {
  700. propagateMetadata(To, From);
  701. addNewMetadata(To, From);
  702. }
  703. void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
  704. Instruction *From) {
  705. for (Value *V : To) {
  706. if (Instruction *I = dyn_cast<Instruction>(V))
  707. addMetadata(I, From);
  708. }
  709. }
  710. namespace llvm {
  711. /// LoopVectorizationCostModel - estimates the expected speedups due to
  712. /// vectorization.
  713. /// In many cases vectorization is not profitable. This can happen because of
  714. /// a number of reasons. In this class we mainly attempt to predict the
  715. /// expected speedup/slowdowns due to the supported instruction set. We use the
  716. /// TargetTransformInfo to query the different backends for the cost of
  717. /// different operations.
  718. class LoopVectorizationCostModel {
  719. public:
  720. LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
  721. LoopInfo *LI, LoopVectorizationLegality *Legal,
  722. const TargetTransformInfo &TTI,
  723. const TargetLibraryInfo *TLI, DemandedBits *DB,
  724. AssumptionCache *AC,
  725. OptimizationRemarkEmitter *ORE, const Function *F,
  726. const LoopVectorizeHints *Hints,
  727. InterleavedAccessInfo &IAI)
  728. : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
  729. AC(AC), ORE(ORE), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {}
  730. /// \return An upper bound for the vectorization factor, or None if
  731. /// vectorization and interleaving should be avoided up front.
  732. Optional<unsigned> computeMaxVF(bool OptForSize);
  733. /// \return The most profitable vectorization factor and the cost of that VF.
  734. /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
  735. /// then this vectorization factor will be selected if vectorization is
  736. /// possible.
  737. VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
  738. /// Setup cost-based decisions for user vectorization factor.
  739. void selectUserVectorizationFactor(unsigned UserVF) {
  740. collectUniformsAndScalars(UserVF);
  741. collectInstsToScalarize(UserVF);
  742. }
  743. /// \return The size (in bits) of the smallest and widest types in the code
  744. /// that needs to be vectorized. We ignore values that remain scalar such as
  745. /// 64 bit loop indices.
  746. std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
  747. /// \return The desired interleave count.
  748. /// If interleave count has been specified by metadata it will be returned.
  749. /// Otherwise, the interleave count is computed and returned. VF and LoopCost
  750. /// are the selected vectorization factor and the cost of the selected VF.
  751. unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
  752. unsigned LoopCost);
  753. /// Memory access instruction may be vectorized in more than one way.
  754. /// Form of instruction after vectorization depends on cost.
  755. /// This function takes cost-based decisions for Load/Store instructions
  756. /// and collects them in a map. This decisions map is used for building
  757. /// the lists of loop-uniform and loop-scalar instructions.
  758. /// The calculated cost is saved with widening decision in order to
  759. /// avoid redundant calculations.
  760. void setCostBasedWideningDecision(unsigned VF);
  761. /// A struct that represents some properties of the register usage
  762. /// of a loop.
  763. struct RegisterUsage {
  764. /// Holds the number of loop invariant values that are used in the loop.
  765. unsigned LoopInvariantRegs;
  766. /// Holds the maximum number of concurrent live intervals in the loop.
  767. unsigned MaxLocalUsers;
  768. };
  769. /// \return Returns information about the register usages of the loop for the
  770. /// given vectorization factors.
  771. SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
  772. /// Collect values we want to ignore in the cost model.
  773. void collectValuesToIgnore();
  774. /// \returns The smallest bitwidth each instruction can be represented with.
  775. /// The vector equivalents of these instructions should be truncated to this
  776. /// type.
  777. const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
  778. return MinBWs;
  779. }
  780. /// \returns True if it is more profitable to scalarize instruction \p I for
  781. /// vectorization factor \p VF.
  782. bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
  783. assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.");
  784. // Cost model is not run in the VPlan-native path - return conservative
  785. // result until this changes.
  786. if (EnableVPlanNativePath)
  787. return false;
  788. auto Scalars = InstsToScalarize.find(VF);
  789. assert(Scalars != InstsToScalarize.end() &&
  790. "VF not yet analyzed for scalarization profitability");
  791. return Scalars->second.find(I) != Scalars->second.end();
  792. }
  793. /// Returns true if \p I is known to be uniform after vectorization.
  794. bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
  795. if (VF == 1)
  796. return true;
  797. // Cost model is not run in the VPlan-native path - return conservative
  798. // result until this changes.
  799. if (EnableVPlanNativePath)
  800. return false;
  801. auto UniformsPerVF = Uniforms.find(VF);
  802. assert(UniformsPerVF != Uniforms.end() &&
  803. "VF not yet analyzed for uniformity");
  804. return UniformsPerVF->second.find(I) != UniformsPerVF->second.end();
  805. }
  806. /// Returns true if \p I is known to be scalar after vectorization.
  807. bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
  808. if (VF == 1)
  809. return true;
  810. // Cost model is not run in the VPlan-native path - return conservative
  811. // result until this changes.
  812. if (EnableVPlanNativePath)
  813. return false;
  814. auto ScalarsPerVF = Scalars.find(VF);
  815. assert(ScalarsPerVF != Scalars.end() &&
  816. "Scalar values are not calculated for VF");
  817. return ScalarsPerVF->second.find(I) != ScalarsPerVF->second.end();
  818. }
  819. /// \returns True if instruction \p I can be truncated to a smaller bitwidth
  820. /// for vectorization factor \p VF.
  821. bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
  822. return VF > 1 && MinBWs.find(I) != MinBWs.end() &&
  823. !isProfitableToScalarize(I, VF) &&
  824. !isScalarAfterVectorization(I, VF);
  825. }
  826. /// Decision that was taken during cost calculation for memory instruction.
  827. enum InstWidening {
  828. CM_Unknown,
  829. CM_Widen, // For consecutive accesses with stride +1.
  830. CM_Widen_Reverse, // For consecutive accesses with stride -1.
  831. CM_Interleave,
  832. CM_GatherScatter,
  833. CM_Scalarize
  834. };
  835. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  836. /// instruction \p I and vector width \p VF.
  837. void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
  838. unsigned Cost) {
  839. assert(VF >= 2 && "Expected VF >=2");
  840. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  841. }
  842. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  843. /// interleaving group \p Grp and vector width \p VF.
  844. void setWideningDecision(const InterleaveGroup<Instruction> *Grp, unsigned VF,
  845. InstWidening W, unsigned Cost) {
  846. assert(VF >= 2 && "Expected VF >=2");
  847. /// Broadcast this decicion to all instructions inside the group.
  848. /// But the cost will be assigned to one instruction only.
  849. for (unsigned i = 0; i < Grp->getFactor(); ++i) {
  850. if (auto *I = Grp->getMember(i)) {
  851. if (Grp->getInsertPos() == I)
  852. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  853. else
  854. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
  855. }
  856. }
  857. }
  858. /// Return the cost model decision for the given instruction \p I and vector
  859. /// width \p VF. Return CM_Unknown if this instruction did not pass
  860. /// through the cost modeling.
  861. InstWidening getWideningDecision(Instruction *I, unsigned VF) {
  862. assert(VF >= 2 && "Expected VF >=2");
  863. // Cost model is not run in the VPlan-native path - return conservative
  864. // result until this changes.
  865. if (EnableVPlanNativePath)
  866. return CM_GatherScatter;
  867. std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
  868. auto Itr = WideningDecisions.find(InstOnVF);
  869. if (Itr == WideningDecisions.end())
  870. return CM_Unknown;
  871. return Itr->second.first;
  872. }
  873. /// Return the vectorization cost for the given instruction \p I and vector
  874. /// width \p VF.
  875. unsigned getWideningCost(Instruction *I, unsigned VF) {
  876. assert(VF >= 2 && "Expected VF >=2");
  877. std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
  878. assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
  879. "The cost is not calculated");
  880. return WideningDecisions[InstOnVF].second;
  881. }
  882. /// Return True if instruction \p I is an optimizable truncate whose operand
  883. /// is an induction variable. Such a truncate will be removed by adding a new
  884. /// induction variable with the destination type.
  885. bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
  886. // If the instruction is not a truncate, return false.
  887. auto *Trunc = dyn_cast<TruncInst>(I);
  888. if (!Trunc)
  889. return false;
  890. // Get the source and destination types of the truncate.
  891. Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
  892. Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
  893. // If the truncate is free for the given types, return false. Replacing a
  894. // free truncate with an induction variable would add an induction variable
  895. // update instruction to each iteration of the loop. We exclude from this
  896. // check the primary induction variable since it will need an update
  897. // instruction regardless.
  898. Value *Op = Trunc->getOperand(0);
  899. if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
  900. return false;
  901. // If the truncated value is not an induction variable, return false.
  902. return Legal->isInductionPhi(Op);
  903. }
  904. /// Collects the instructions to scalarize for each predicated instruction in
  905. /// the loop.
  906. void collectInstsToScalarize(unsigned VF);
  907. /// Collect Uniform and Scalar values for the given \p VF.
  908. /// The sets depend on CM decision for Load/Store instructions
  909. /// that may be vectorized as interleave, gather-scatter or scalarized.
  910. void collectUniformsAndScalars(unsigned VF) {
  911. // Do the analysis once.
  912. if (VF == 1 || Uniforms.find(VF) != Uniforms.end())
  913. return;
  914. setCostBasedWideningDecision(VF);
  915. collectLoopUniforms(VF);
  916. collectLoopScalars(VF);
  917. }
  918. /// Returns true if the target machine supports masked store operation
  919. /// for the given \p DataType and kind of access to \p Ptr.
  920. bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
  921. return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType);
  922. }
  923. /// Returns true if the target machine supports masked load operation
  924. /// for the given \p DataType and kind of access to \p Ptr.
  925. bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
  926. return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType);
  927. }
  928. /// Returns true if the target machine supports masked scatter operation
  929. /// for the given \p DataType.
  930. bool isLegalMaskedScatter(Type *DataType) {
  931. return TTI.isLegalMaskedScatter(DataType);
  932. }
  933. /// Returns true if the target machine supports masked gather operation
  934. /// for the given \p DataType.
  935. bool isLegalMaskedGather(Type *DataType) {
  936. return TTI.isLegalMaskedGather(DataType);
  937. }
  938. /// Returns true if the target machine can represent \p V as a masked gather
  939. /// or scatter operation.
  940. bool isLegalGatherOrScatter(Value *V) {
  941. bool LI = isa<LoadInst>(V);
  942. bool SI = isa<StoreInst>(V);
  943. if (!LI && !SI)
  944. return false;
  945. auto *Ty = getMemInstValueType(V);
  946. return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
  947. }
  948. /// Returns true if \p I is an instruction that will be scalarized with
  949. /// predication. Such instructions include conditional stores and
  950. /// instructions that may divide by zero.
  951. /// If a non-zero VF has been calculated, we check if I will be scalarized
  952. /// predication for that VF.
  953. bool isScalarWithPredication(Instruction *I, unsigned VF = 1);
  954. // Returns true if \p I is an instruction that will be predicated either
  955. // through scalar predication or masked load/store or masked gather/scatter.
  956. // Superset of instructions that return true for isScalarWithPredication.
  957. bool isPredicatedInst(Instruction *I) {
  958. if (!blockNeedsPredication(I->getParent()))
  959. return false;
  960. // Loads and stores that need some form of masked operation are predicated
  961. // instructions.
  962. if (isa<LoadInst>(I) || isa<StoreInst>(I))
  963. return Legal->isMaskRequired(I);
  964. return isScalarWithPredication(I);
  965. }
  966. /// Returns true if \p I is a memory instruction with consecutive memory
  967. /// access that can be widened.
  968. bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
  969. /// Returns true if \p I is a memory instruction in an interleaved-group
  970. /// of memory accesses that can be vectorized with wide vector loads/stores
  971. /// and shuffles.
  972. bool interleavedAccessCanBeWidened(Instruction *I, unsigned VF = 1);
  973. /// Check if \p Instr belongs to any interleaved access group.
  974. bool isAccessInterleaved(Instruction *Instr) {
  975. return InterleaveInfo.isInterleaved(Instr);
  976. }
  977. /// Get the interleaved access group that \p Instr belongs to.
  978. const InterleaveGroup<Instruction> *
  979. getInterleavedAccessGroup(Instruction *Instr) {
  980. return InterleaveInfo.getInterleaveGroup(Instr);
  981. }
  982. /// Returns true if an interleaved group requires a scalar iteration
  983. /// to handle accesses with gaps, and there is nothing preventing us from
  984. /// creating a scalar epilogue.
  985. bool requiresScalarEpilogue() const {
  986. return IsScalarEpilogueAllowed && InterleaveInfo.requiresScalarEpilogue();
  987. }
  988. /// Returns true if a scalar epilogue is not allowed due to optsize.
  989. bool isScalarEpilogueAllowed() const { return IsScalarEpilogueAllowed; }
  990. /// Returns true if all loop blocks should be masked to fold tail loop.
  991. bool foldTailByMasking() const { return FoldTailByMasking; }
  992. bool blockNeedsPredication(BasicBlock *BB) {
  993. return foldTailByMasking() || Legal->blockNeedsPredication(BB);
  994. }
  995. /// Estimate cost of an intrinsic call instruction CI if it were vectorized
  996. /// with factor VF. Return the cost of the instruction, including
  997. /// scalarization overhead if it's needed.
  998. unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF);
  999. /// Estimate cost of a call instruction CI if it were vectorized with factor
  1000. /// VF. Return the cost of the instruction, including scalarization overhead
  1001. /// if it's needed. The flag NeedToScalarize shows if the call needs to be
  1002. /// scalarized -
  1003. // i.e. either vector version isn't available, or is too expensive.
  1004. unsigned getVectorCallCost(CallInst *CI, unsigned VF, bool &NeedToScalarize);
  1005. private:
  1006. unsigned NumPredStores = 0;
  1007. /// \return An upper bound for the vectorization factor, larger than zero.
  1008. /// One is returned if vectorization should best be avoided due to cost.
  1009. unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
  1010. /// The vectorization cost is a combination of the cost itself and a boolean
  1011. /// indicating whether any of the contributing operations will actually
  1012. /// operate on
  1013. /// vector values after type legalization in the backend. If this latter value
  1014. /// is
  1015. /// false, then all operations will be scalarized (i.e. no vectorization has
  1016. /// actually taken place).
  1017. using VectorizationCostTy = std::pair<unsigned, bool>;
  1018. /// Returns the expected execution cost. The unit of the cost does
  1019. /// not matter because we use the 'cost' units to compare different
  1020. /// vector widths. The cost that is returned is *not* normalized by
  1021. /// the factor width.
  1022. VectorizationCostTy expectedCost(unsigned VF);
  1023. /// Returns the execution time cost of an instruction for a given vector
  1024. /// width. Vector width of one means scalar.
  1025. VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
  1026. /// The cost-computation logic from getInstructionCost which provides
  1027. /// the vector type as an output parameter.
  1028. unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
  1029. /// Calculate vectorization cost of memory instruction \p I.
  1030. unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
  1031. /// The cost computation for scalarized memory instruction.
  1032. unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
  1033. /// The cost computation for interleaving group of memory instructions.
  1034. unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
  1035. /// The cost computation for Gather/Scatter instruction.
  1036. unsigned getGatherScatterCost(Instruction *I, unsigned VF);
  1037. /// The cost computation for widening instruction \p I with consecutive
  1038. /// memory access.
  1039. unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
  1040. /// The cost calculation for Load/Store instruction \p I with uniform pointer -
  1041. /// Load: scalar load + broadcast.
  1042. /// Store: scalar store + (loop invariant value stored? 0 : extract of last
  1043. /// element)
  1044. unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
  1045. /// Estimate the overhead of scalarizing an instruction. This is a
  1046. /// convenience wrapper for the type-based getScalarizationOverhead API.
  1047. unsigned getScalarizationOverhead(Instruction *I, unsigned VF);
  1048. /// Returns whether the instruction is a load or store and will be a emitted
  1049. /// as a vector operation.
  1050. bool isConsecutiveLoadOrStore(Instruction *I);
  1051. /// Returns true if an artificially high cost for emulated masked memrefs
  1052. /// should be used.
  1053. bool useEmulatedMaskMemRefHack(Instruction *I);
  1054. /// Create an analysis remark that explains why vectorization failed
  1055. ///
  1056. /// \p RemarkName is the identifier for the remark. \return the remark object
  1057. /// that can be streamed to.
  1058. OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
  1059. return createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(),
  1060. RemarkName, TheLoop);
  1061. }
  1062. /// Map of scalar integer values to the smallest bitwidth they can be legally
  1063. /// represented as. The vector equivalents of these values should be truncated
  1064. /// to this type.
  1065. MapVector<Instruction *, uint64_t> MinBWs;
  1066. /// A type representing the costs for instructions if they were to be
  1067. /// scalarized rather than vectorized. The entries are Instruction-Cost
  1068. /// pairs.
  1069. using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
  1070. /// A set containing all BasicBlocks that are known to present after
  1071. /// vectorization as a predicated block.
  1072. SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
  1073. /// Records whether it is allowed to have the original scalar loop execute at
  1074. /// least once. This may be needed as a fallback loop in case runtime
  1075. /// aliasing/dependence checks fail, or to handle the tail/remainder
  1076. /// iterations when the trip count is unknown or doesn't divide by the VF,
  1077. /// or as a peel-loop to handle gaps in interleave-groups.
  1078. /// Under optsize and when the trip count is very small we don't allow any
  1079. /// iterations to execute in the scalar loop.
  1080. bool IsScalarEpilogueAllowed = true;
  1081. /// All blocks of loop are to be masked to fold tail of scalar iterations.
  1082. bool FoldTailByMasking = false;
  1083. /// A map holding scalar costs for different vectorization factors. The
  1084. /// presence of a cost for an instruction in the mapping indicates that the
  1085. /// instruction will be scalarized when vectorizing with the associated
  1086. /// vectorization factor. The entries are VF-ScalarCostTy pairs.
  1087. DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
  1088. /// Holds the instructions known to be uniform after vectorization.
  1089. /// The data is collected per VF.
  1090. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
  1091. /// Holds the instructions known to be scalar after vectorization.
  1092. /// The data is collected per VF.
  1093. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
  1094. /// Holds the instructions (address computations) that are forced to be
  1095. /// scalarized.
  1096. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
  1097. /// Returns the expected difference in cost from scalarizing the expression
  1098. /// feeding a predicated instruction \p PredInst. The instructions to
  1099. /// scalarize and their scalar costs are collected in \p ScalarCosts. A
  1100. /// non-negative return value implies the expression will be scalarized.
  1101. /// Currently, only single-use chains are considered for scalarization.
  1102. int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
  1103. unsigned VF);
  1104. /// Collect the instructions that are uniform after vectorization. An
  1105. /// instruction is uniform if we represent it with a single scalar value in
  1106. /// the vectorized loop corresponding to each vector iteration. Examples of
  1107. /// uniform instructions include pointer operands of consecutive or
  1108. /// interleaved memory accesses. Note that although uniformity implies an
  1109. /// instruction will be scalar, the reverse is not true. In general, a
  1110. /// scalarized instruction will be represented by VF scalar values in the
  1111. /// vectorized loop, each corresponding to an iteration of the original
  1112. /// scalar loop.
  1113. void collectLoopUniforms(unsigned VF);
  1114. /// Collect the instructions that are scalar after vectorization. An
  1115. /// instruction is scalar if it is known to be uniform or will be scalarized
  1116. /// during vectorization. Non-uniform scalarized instructions will be
  1117. /// represented by VF values in the vectorized loop, each corresponding to an
  1118. /// iteration of the original scalar loop.
  1119. void collectLoopScalars(unsigned VF);
  1120. /// Keeps cost model vectorization decision and cost for instructions.
  1121. /// Right now it is used for memory instructions only.
  1122. using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
  1123. std::pair<InstWidening, unsigned>>;
  1124. DecisionList WideningDecisions;
  1125. public:
  1126. /// The loop that we evaluate.
  1127. Loop *TheLoop;
  1128. /// Predicated scalar evolution analysis.
  1129. PredicatedScalarEvolution &PSE;
  1130. /// Loop Info analysis.
  1131. LoopInfo *LI;
  1132. /// Vectorization legality.
  1133. LoopVectorizationLegality *Legal;
  1134. /// Vector target information.
  1135. const TargetTransformInfo &TTI;
  1136. /// Target Library Info.
  1137. const TargetLibraryInfo *TLI;
  1138. /// Demanded bits analysis.
  1139. DemandedBits *DB;
  1140. /// Assumption cache.
  1141. AssumptionCache *AC;
  1142. /// Interface to emit optimization remarks.
  1143. OptimizationRemarkEmitter *ORE;
  1144. const Function *TheFunction;
  1145. /// Loop Vectorize Hint.
  1146. const LoopVectorizeHints *Hints;
  1147. /// The interleave access information contains groups of interleaved accesses
  1148. /// with the same stride and close to each other.
  1149. InterleavedAccessInfo &InterleaveInfo;
  1150. /// Values to ignore in the cost model.
  1151. SmallPtrSet<const Value *, 16> ValuesToIgnore;
  1152. /// Values to ignore in the cost model when VF > 1.
  1153. SmallPtrSet<const Value *, 16> VecValuesToIgnore;
  1154. };
  1155. } // end namespace llvm
  1156. // Return true if \p OuterLp is an outer loop annotated with hints for explicit
  1157. // vectorization. The loop needs to be annotated with #pragma omp simd
  1158. // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
  1159. // vector length information is not provided, vectorization is not considered
  1160. // explicit. Interleave hints are not allowed either. These limitations will be
  1161. // relaxed in the future.
  1162. // Please, note that we are currently forced to abuse the pragma 'clang
  1163. // vectorize' semantics. This pragma provides *auto-vectorization hints*
  1164. // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
  1165. // provides *explicit vectorization hints* (LV can bypass legal checks and
  1166. // assume that vectorization is legal). However, both hints are implemented
  1167. // using the same metadata (llvm.loop.vectorize, processed by
  1168. // LoopVectorizeHints). This will be fixed in the future when the native IR
  1169. // representation for pragma 'omp simd' is introduced.
  1170. static bool isExplicitVecOuterLoop(Loop *OuterLp,
  1171. OptimizationRemarkEmitter *ORE) {
  1172. assert(!OuterLp->empty() && "This is not an outer loop");
  1173. LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
  1174. // Only outer loops with an explicit vectorization hint are supported.
  1175. // Unannotated outer loops are ignored.
  1176. if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
  1177. return false;
  1178. Function *Fn = OuterLp->getHeader()->getParent();
  1179. if (!Hints.allowVectorization(Fn, OuterLp,
  1180. true /*VectorizeOnlyWhenForced*/)) {
  1181. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
  1182. return false;
  1183. }
  1184. if (Hints.getInterleave() > 1) {
  1185. // TODO: Interleave support is future work.
  1186. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
  1187. "outer loops.\n");
  1188. Hints.emitRemarkWithHints();
  1189. return false;
  1190. }
  1191. return true;
  1192. }
  1193. static void collectSupportedLoops(Loop &L, LoopInfo *LI,
  1194. OptimizationRemarkEmitter *ORE,
  1195. SmallVectorImpl<Loop *> &V) {
  1196. // Collect inner loops and outer loops without irreducible control flow. For
  1197. // now, only collect outer loops that have explicit vectorization hints. If we
  1198. // are stress testing the VPlan H-CFG construction, we collect the outermost
  1199. // loop of every loop nest.
  1200. if (L.empty() || VPlanBuildStressTest ||
  1201. (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
  1202. LoopBlocksRPO RPOT(&L);
  1203. RPOT.perform(LI);
  1204. if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
  1205. V.push_back(&L);
  1206. // TODO: Collect inner loops inside marked outer loops in case
  1207. // vectorization fails for the outer loop. Do not invoke
  1208. // 'containsIrreducibleCFG' again for inner loops when the outer loop is
  1209. // already known to be reducible. We can use an inherited attribute for
  1210. // that.
  1211. return;
  1212. }
  1213. }
  1214. for (Loop *InnerL : L)
  1215. collectSupportedLoops(*InnerL, LI, ORE, V);
  1216. }
  1217. namespace {
  1218. /// The LoopVectorize Pass.
  1219. struct LoopVectorize : public FunctionPass {
  1220. /// Pass identification, replacement for typeid
  1221. static char ID;
  1222. LoopVectorizePass Impl;
  1223. explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
  1224. bool VectorizeOnlyWhenForced = false)
  1225. : FunctionPass(ID) {
  1226. Impl.InterleaveOnlyWhenForced = InterleaveOnlyWhenForced;
  1227. Impl.VectorizeOnlyWhenForced = VectorizeOnlyWhenForced;
  1228. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  1229. }
  1230. bool runOnFunction(Function &F) override {
  1231. if (skipFunction(F))
  1232. return false;
  1233. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1234. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1235. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1236. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1237. auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
  1238. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1239. auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
  1240. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1241. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1242. auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
  1243. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  1244. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  1245. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  1246. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  1247. [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
  1248. return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
  1249. GetLAA, *ORE, PSI);
  1250. }
  1251. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1252. AU.addRequired<AssumptionCacheTracker>();
  1253. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  1254. AU.addRequired<DominatorTreeWrapperPass>();
  1255. AU.addRequired<LoopInfoWrapperPass>();
  1256. AU.addRequired<ScalarEvolutionWrapperPass>();
  1257. AU.addRequired<TargetTransformInfoWrapperPass>();
  1258. AU.addRequired<AAResultsWrapperPass>();
  1259. AU.addRequired<LoopAccessLegacyAnalysis>();
  1260. AU.addRequired<DemandedBitsWrapperPass>();
  1261. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  1262. // We currently do not preserve loopinfo/dominator analyses with outer loop
  1263. // vectorization. Until this is addressed, mark these analyses as preserved
  1264. // only for non-VPlan-native path.
  1265. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  1266. if (!EnableVPlanNativePath) {
  1267. AU.addPreserved<LoopInfoWrapperPass>();
  1268. AU.addPreserved<DominatorTreeWrapperPass>();
  1269. }
  1270. AU.addPreserved<BasicAAWrapperPass>();
  1271. AU.addPreserved<GlobalsAAWrapperPass>();
  1272. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  1273. }
  1274. };
  1275. } // end anonymous namespace
  1276. //===----------------------------------------------------------------------===//
  1277. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  1278. // LoopVectorizationCostModel and LoopVectorizationPlanner.
  1279. //===----------------------------------------------------------------------===//
  1280. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  1281. // We need to place the broadcast of invariant variables outside the loop,
  1282. // but only if it's proven safe to do so. Else, broadcast will be inside
  1283. // vector loop body.
  1284. Instruction *Instr = dyn_cast<Instruction>(V);
  1285. bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
  1286. (!Instr ||
  1287. DT->dominates(Instr->getParent(), LoopVectorPreHeader));
  1288. // Place the code for broadcasting invariant variables in the new preheader.
  1289. IRBuilder<>::InsertPointGuard Guard(Builder);
  1290. if (SafeToHoist)
  1291. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1292. // Broadcast the scalar into all locations in the vector.
  1293. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  1294. return Shuf;
  1295. }
  1296. void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
  1297. const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
  1298. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1299. "Expected either an induction phi-node or a truncate of it!");
  1300. Value *Start = II.getStartValue();
  1301. // Construct the initial value of the vector IV in the vector loop preheader
  1302. auto CurrIP = Builder.saveIP();
  1303. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1304. if (isa<TruncInst>(EntryVal)) {
  1305. assert(Start->getType()->isIntegerTy() &&
  1306. "Truncation requires an integer type");
  1307. auto *TruncType = cast<IntegerType>(EntryVal->getType());
  1308. Step = Builder.CreateTrunc(Step, TruncType);
  1309. Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
  1310. }
  1311. Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
  1312. Value *SteppedStart =
  1313. getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
  1314. // We create vector phi nodes for both integer and floating-point induction
  1315. // variables. Here, we determine the kind of arithmetic we will perform.
  1316. Instruction::BinaryOps AddOp;
  1317. Instruction::BinaryOps MulOp;
  1318. if (Step->getType()->isIntegerTy()) {
  1319. AddOp = Instruction::Add;
  1320. MulOp = Instruction::Mul;
  1321. } else {
  1322. AddOp = II.getInductionOpcode();
  1323. MulOp = Instruction::FMul;
  1324. }
  1325. // Multiply the vectorization factor by the step using integer or
  1326. // floating-point arithmetic as appropriate.
  1327. Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
  1328. Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
  1329. // Create a vector splat to use in the induction update.
  1330. //
  1331. // FIXME: If the step is non-constant, we create the vector splat with
  1332. // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
  1333. // handle a constant vector splat.
  1334. Value *SplatVF = isa<Constant>(Mul)
  1335. ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
  1336. : Builder.CreateVectorSplat(VF, Mul);
  1337. Builder.restoreIP(CurrIP);
  1338. // We may need to add the step a number of times, depending on the unroll
  1339. // factor. The last of those goes into the PHI.
  1340. PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
  1341. &*LoopVectorBody->getFirstInsertionPt());
  1342. VecInd->setDebugLoc(EntryVal->getDebugLoc());
  1343. Instruction *LastInduction = VecInd;
  1344. for (unsigned Part = 0; Part < UF; ++Part) {
  1345. VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
  1346. if (isa<TruncInst>(EntryVal))
  1347. addMetadata(LastInduction, EntryVal);
  1348. recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
  1349. LastInduction = cast<Instruction>(addFastMathFlag(
  1350. Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
  1351. LastInduction->setDebugLoc(EntryVal->getDebugLoc());
  1352. }
  1353. // Move the last step to the end of the latch block. This ensures consistent
  1354. // placement of all induction updates.
  1355. auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
  1356. auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
  1357. auto *ICmp = cast<Instruction>(Br->getCondition());
  1358. LastInduction->moveBefore(ICmp);
  1359. LastInduction->setName("vec.ind.next");
  1360. VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
  1361. VecInd->addIncoming(LastInduction, LoopVectorLatch);
  1362. }
  1363. bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
  1364. return Cost->isScalarAfterVectorization(I, VF) ||
  1365. Cost->isProfitableToScalarize(I, VF);
  1366. }
  1367. bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
  1368. if (shouldScalarizeInstruction(IV))
  1369. return true;
  1370. auto isScalarInst = [&](User *U) -> bool {
  1371. auto *I = cast<Instruction>(U);
  1372. return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
  1373. };
  1374. return llvm::any_of(IV->users(), isScalarInst);
  1375. }
  1376. void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
  1377. const InductionDescriptor &ID, const Instruction *EntryVal,
  1378. Value *VectorLoopVal, unsigned Part, unsigned Lane) {
  1379. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1380. "Expected either an induction phi-node or a truncate of it!");
  1381. // This induction variable is not the phi from the original loop but the
  1382. // newly-created IV based on the proof that casted Phi is equal to the
  1383. // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
  1384. // re-uses the same InductionDescriptor that original IV uses but we don't
  1385. // have to do any recording in this case - that is done when original IV is
  1386. // processed.
  1387. if (isa<TruncInst>(EntryVal))
  1388. return;
  1389. const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
  1390. if (Casts.empty())
  1391. return;
  1392. // Only the first Cast instruction in the Casts vector is of interest.
  1393. // The rest of the Casts (if exist) have no uses outside the
  1394. // induction update chain itself.
  1395. Instruction *CastInst = *Casts.begin();
  1396. if (Lane < UINT_MAX)
  1397. VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
  1398. else
  1399. VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
  1400. }
  1401. void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
  1402. assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
  1403. "Primary induction variable must have an integer type");
  1404. auto II = Legal->getInductionVars()->find(IV);
  1405. assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
  1406. auto ID = II->second;
  1407. assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
  1408. // The scalar value to broadcast. This will be derived from the canonical
  1409. // induction variable.
  1410. Value *ScalarIV = nullptr;
  1411. // The value from the original loop to which we are mapping the new induction
  1412. // variable.
  1413. Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
  1414. // True if we have vectorized the induction variable.
  1415. auto VectorizedIV = false;
  1416. // Determine if we want a scalar version of the induction variable. This is
  1417. // true if the induction variable itself is not widened, or if it has at
  1418. // least one user in the loop that is not widened.
  1419. auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
  1420. // Generate code for the induction step. Note that induction steps are
  1421. // required to be loop-invariant
  1422. assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
  1423. "Induction step should be loop invariant");
  1424. auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  1425. Value *Step = nullptr;
  1426. if (PSE.getSE()->isSCEVable(IV->getType())) {
  1427. SCEVExpander Exp(*PSE.getSE(), DL, "induction");
  1428. Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
  1429. LoopVectorPreHeader->getTerminator());
  1430. } else {
  1431. Step = cast<SCEVUnknown>(ID.getStep())->getValue();
  1432. }
  1433. // Try to create a new independent vector induction variable. If we can't
  1434. // create the phi node, we will splat the scalar induction variable in each
  1435. // loop iteration.
  1436. if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
  1437. createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
  1438. VectorizedIV = true;
  1439. }
  1440. // If we haven't yet vectorized the induction variable, or if we will create
  1441. // a scalar one, we need to define the scalar induction variable and step
  1442. // values. If we were given a truncation type, truncate the canonical
  1443. // induction variable and step. Otherwise, derive these values from the
  1444. // induction descriptor.
  1445. if (!VectorizedIV || NeedsScalarIV) {
  1446. ScalarIV = Induction;
  1447. if (IV != OldInduction) {
  1448. ScalarIV = IV->getType()->isIntegerTy()
  1449. ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
  1450. : Builder.CreateCast(Instruction::SIToFP, Induction,
  1451. IV->getType());
  1452. ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
  1453. ScalarIV->setName("offset.idx");
  1454. }
  1455. if (Trunc) {
  1456. auto *TruncType = cast<IntegerType>(Trunc->getType());
  1457. assert(Step->getType()->isIntegerTy() &&
  1458. "Truncation requires an integer step");
  1459. ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
  1460. Step = Builder.CreateTrunc(Step, TruncType);
  1461. }
  1462. }
  1463. // If we haven't yet vectorized the induction variable, splat the scalar
  1464. // induction variable, and build the necessary step vectors.
  1465. // TODO: Don't do it unless the vectorized IV is really required.
  1466. if (!VectorizedIV) {
  1467. Value *Broadcasted = getBroadcastInstrs(ScalarIV);
  1468. for (unsigned Part = 0; Part < UF; ++Part) {
  1469. Value *EntryPart =
  1470. getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
  1471. VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
  1472. if (Trunc)
  1473. addMetadata(EntryPart, Trunc);
  1474. recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
  1475. }
  1476. }
  1477. // If an induction variable is only used for counting loop iterations or
  1478. // calculating addresses, it doesn't need to be widened. Create scalar steps
  1479. // that can be used by instructions we will later scalarize. Note that the
  1480. // addition of the scalar steps will not increase the number of instructions
  1481. // in the loop in the common case prior to InstCombine. We will be trading
  1482. // one vector extract for each scalar step.
  1483. if (NeedsScalarIV)
  1484. buildScalarSteps(ScalarIV, Step, EntryVal, ID);
  1485. }
  1486. Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
  1487. Instruction::BinaryOps BinOp) {
  1488. // Create and check the types.
  1489. assert(Val->getType()->isVectorTy() && "Must be a vector");
  1490. int VLen = Val->getType()->getVectorNumElements();
  1491. Type *STy = Val->getType()->getScalarType();
  1492. assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
  1493. "Induction Step must be an integer or FP");
  1494. assert(Step->getType() == STy && "Step has wrong type");
  1495. SmallVector<Constant *, 8> Indices;
  1496. if (STy->isIntegerTy()) {
  1497. // Create a vector of consecutive numbers from zero to VF.
  1498. for (int i = 0; i < VLen; ++i)
  1499. Indices.push_back(ConstantInt::get(STy, StartIdx + i));
  1500. // Add the consecutive indices to the vector value.
  1501. Constant *Cv = ConstantVector::get(Indices);
  1502. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  1503. Step = Builder.CreateVectorSplat(VLen, Step);
  1504. assert(Step->getType() == Val->getType() && "Invalid step vec");
  1505. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  1506. // which can be found from the original scalar operations.
  1507. Step = Builder.CreateMul(Cv, Step);
  1508. return Builder.CreateAdd(Val, Step, "induction");
  1509. }
  1510. // Floating point induction.
  1511. assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
  1512. "Binary Opcode should be specified for FP induction");
  1513. // Create a vector of consecutive numbers from zero to VF.
  1514. for (int i = 0; i < VLen; ++i)
  1515. Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
  1516. // Add the consecutive indices to the vector value.
  1517. Constant *Cv = ConstantVector::get(Indices);
  1518. Step = Builder.CreateVectorSplat(VLen, Step);
  1519. // Floating point operations had to be 'fast' to enable the induction.
  1520. FastMathFlags Flags;
  1521. Flags.setFast();
  1522. Value *MulOp = Builder.CreateFMul(Cv, Step);
  1523. if (isa<Instruction>(MulOp))
  1524. // Have to check, MulOp may be a constant
  1525. cast<Instruction>(MulOp)->setFastMathFlags(Flags);
  1526. Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
  1527. if (isa<Instruction>(BOp))
  1528. cast<Instruction>(BOp)->setFastMathFlags(Flags);
  1529. return BOp;
  1530. }
  1531. void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
  1532. Instruction *EntryVal,
  1533. const InductionDescriptor &ID) {
  1534. // We shouldn't have to build scalar steps if we aren't vectorizing.
  1535. assert(VF > 1 && "VF should be greater than one");
  1536. // Get the value type and ensure it and the step have the same integer type.
  1537. Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
  1538. assert(ScalarIVTy == Step->getType() &&
  1539. "Val and Step should have the same type");
  1540. // We build scalar steps for both integer and floating-point induction
  1541. // variables. Here, we determine the kind of arithmetic we will perform.
  1542. Instruction::BinaryOps AddOp;
  1543. Instruction::BinaryOps MulOp;
  1544. if (ScalarIVTy->isIntegerTy()) {
  1545. AddOp = Instruction::Add;
  1546. MulOp = Instruction::Mul;
  1547. } else {
  1548. AddOp = ID.getInductionOpcode();
  1549. MulOp = Instruction::FMul;
  1550. }
  1551. // Determine the number of scalars we need to generate for each unroll
  1552. // iteration. If EntryVal is uniform, we only need to generate the first
  1553. // lane. Otherwise, we generate all VF values.
  1554. unsigned Lanes =
  1555. Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
  1556. : VF;
  1557. // Compute the scalar steps and save the results in VectorLoopValueMap.
  1558. for (unsigned Part = 0; Part < UF; ++Part) {
  1559. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  1560. auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
  1561. auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
  1562. auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
  1563. VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
  1564. recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
  1565. }
  1566. }
  1567. }
  1568. Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
  1569. assert(V != Induction && "The new induction variable should not be used.");
  1570. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  1571. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  1572. // If we have a stride that is replaced by one, do it here. Defer this for
  1573. // the VPlan-native path until we start running Legal checks in that path.
  1574. if (!EnableVPlanNativePath && Legal->hasStride(V))
  1575. V = ConstantInt::get(V->getType(), 1);
  1576. // If we have a vector mapped to this value, return it.
  1577. if (VectorLoopValueMap.hasVectorValue(V, Part))
  1578. return VectorLoopValueMap.getVectorValue(V, Part);
  1579. // If the value has not been vectorized, check if it has been scalarized
  1580. // instead. If it has been scalarized, and we actually need the value in
  1581. // vector form, we will construct the vector values on demand.
  1582. if (VectorLoopValueMap.hasAnyScalarValue(V)) {
  1583. Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
  1584. // If we've scalarized a value, that value should be an instruction.
  1585. auto *I = cast<Instruction>(V);
  1586. // If we aren't vectorizing, we can just copy the scalar map values over to
  1587. // the vector map.
  1588. if (VF == 1) {
  1589. VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
  1590. return ScalarValue;
  1591. }
  1592. // Get the last scalar instruction we generated for V and Part. If the value
  1593. // is known to be uniform after vectorization, this corresponds to lane zero
  1594. // of the Part unroll iteration. Otherwise, the last instruction is the one
  1595. // we created for the last vector lane of the Part unroll iteration.
  1596. unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
  1597. auto *LastInst = cast<Instruction>(
  1598. VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
  1599. // Set the insert point after the last scalarized instruction. This ensures
  1600. // the insertelement sequence will directly follow the scalar definitions.
  1601. auto OldIP = Builder.saveIP();
  1602. auto NewIP = std::next(BasicBlock::iterator(LastInst));
  1603. Builder.SetInsertPoint(&*NewIP);
  1604. // However, if we are vectorizing, we need to construct the vector values.
  1605. // If the value is known to be uniform after vectorization, we can just
  1606. // broadcast the scalar value corresponding to lane zero for each unroll
  1607. // iteration. Otherwise, we construct the vector values using insertelement
  1608. // instructions. Since the resulting vectors are stored in
  1609. // VectorLoopValueMap, we will only generate the insertelements once.
  1610. Value *VectorValue = nullptr;
  1611. if (Cost->isUniformAfterVectorization(I, VF)) {
  1612. VectorValue = getBroadcastInstrs(ScalarValue);
  1613. VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
  1614. } else {
  1615. // Initialize packing with insertelements to start from undef.
  1616. Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
  1617. VectorLoopValueMap.setVectorValue(V, Part, Undef);
  1618. for (unsigned Lane = 0; Lane < VF; ++Lane)
  1619. packScalarIntoVectorValue(V, {Part, Lane});
  1620. VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
  1621. }
  1622. Builder.restoreIP(OldIP);
  1623. return VectorValue;
  1624. }
  1625. // If this scalar is unknown, assume that it is a constant or that it is
  1626. // loop invariant. Broadcast V and save the value for future uses.
  1627. Value *B = getBroadcastInstrs(V);
  1628. VectorLoopValueMap.setVectorValue(V, Part, B);
  1629. return B;
  1630. }
  1631. Value *
  1632. InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
  1633. const VPIteration &Instance) {
  1634. // If the value is not an instruction contained in the loop, it should
  1635. // already be scalar.
  1636. if (OrigLoop->isLoopInvariant(V))
  1637. return V;
  1638. assert(Instance.Lane > 0
  1639. ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
  1640. : true && "Uniform values only have lane zero");
  1641. // If the value from the original loop has not been vectorized, it is
  1642. // represented by UF x VF scalar values in the new loop. Return the requested
  1643. // scalar value.
  1644. if (VectorLoopValueMap.hasScalarValue(V, Instance))
  1645. return VectorLoopValueMap.getScalarValue(V, Instance);
  1646. // If the value has not been scalarized, get its entry in VectorLoopValueMap
  1647. // for the given unroll part. If this entry is not a vector type (i.e., the
  1648. // vectorization factor is one), there is no need to generate an
  1649. // extractelement instruction.
  1650. auto *U = getOrCreateVectorValue(V, Instance.Part);
  1651. if (!U->getType()->isVectorTy()) {
  1652. assert(VF == 1 && "Value not scalarized has non-vector type");
  1653. return U;
  1654. }
  1655. // Otherwise, the value from the original loop has been vectorized and is
  1656. // represented by UF vector values. Extract and return the requested scalar
  1657. // value from the appropriate vector lane.
  1658. return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
  1659. }
  1660. void InnerLoopVectorizer::packScalarIntoVectorValue(
  1661. Value *V, const VPIteration &Instance) {
  1662. assert(V != Induction && "The new induction variable should not be used.");
  1663. assert(!V->getType()->isVectorTy() && "Can't pack a vector");
  1664. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  1665. Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
  1666. Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
  1667. VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
  1668. Builder.getInt32(Instance.Lane));
  1669. VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
  1670. }
  1671. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  1672. assert(Vec->getType()->isVectorTy() && "Invalid type");
  1673. SmallVector<Constant *, 8> ShuffleMask;
  1674. for (unsigned i = 0; i < VF; ++i)
  1675. ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
  1676. return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
  1677. ConstantVector::get(ShuffleMask),
  1678. "reverse");
  1679. }
  1680. // Return whether we allow using masked interleave-groups (for dealing with
  1681. // strided loads/stores that reside in predicated blocks, or for dealing
  1682. // with gaps).
  1683. static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
  1684. // If an override option has been passed in for interleaved accesses, use it.
  1685. if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
  1686. return EnableMaskedInterleavedMemAccesses;
  1687. return TTI.enableMaskedInterleavedAccessVectorization();
  1688. }
  1689. // Try to vectorize the interleave group that \p Instr belongs to.
  1690. //
  1691. // E.g. Translate following interleaved load group (factor = 3):
  1692. // for (i = 0; i < N; i+=3) {
  1693. // R = Pic[i]; // Member of index 0
  1694. // G = Pic[i+1]; // Member of index 1
  1695. // B = Pic[i+2]; // Member of index 2
  1696. // ... // do something to R, G, B
  1697. // }
  1698. // To:
  1699. // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
  1700. // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
  1701. // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
  1702. // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
  1703. //
  1704. // Or translate following interleaved store group (factor = 3):
  1705. // for (i = 0; i < N; i+=3) {
  1706. // ... do something to R, G, B
  1707. // Pic[i] = R; // Member of index 0
  1708. // Pic[i+1] = G; // Member of index 1
  1709. // Pic[i+2] = B; // Member of index 2
  1710. // }
  1711. // To:
  1712. // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
  1713. // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
  1714. // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
  1715. // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
  1716. // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
  1717. void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr,
  1718. VectorParts *BlockInMask) {
  1719. const InterleaveGroup<Instruction> *Group =
  1720. Cost->getInterleavedAccessGroup(Instr);
  1721. assert(Group && "Fail to get an interleaved access group.");
  1722. // Skip if current instruction is not the insert position.
  1723. if (Instr != Group->getInsertPos())
  1724. return;
  1725. const DataLayout &DL = Instr->getModule()->getDataLayout();
  1726. Value *Ptr = getLoadStorePointerOperand(Instr);
  1727. // Prepare for the vector type of the interleaved load/store.
  1728. Type *ScalarTy = getMemInstValueType(Instr);
  1729. unsigned InterleaveFactor = Group->getFactor();
  1730. Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
  1731. Type *PtrTy = VecTy->getPointerTo(getLoadStoreAddressSpace(Instr));
  1732. // Prepare for the new pointers.
  1733. setDebugLocFromInst(Builder, Ptr);
  1734. SmallVector<Value *, 2> NewPtrs;
  1735. unsigned Index = Group->getIndex(Instr);
  1736. VectorParts Mask;
  1737. bool IsMaskForCondRequired = BlockInMask;
  1738. if (IsMaskForCondRequired) {
  1739. Mask = *BlockInMask;
  1740. // TODO: extend the masked interleaved-group support to reversed access.
  1741. assert(!Group->isReverse() && "Reversed masked interleave-group "
  1742. "not supported.");
  1743. }
  1744. // If the group is reverse, adjust the index to refer to the last vector lane
  1745. // instead of the first. We adjust the index from the first vector lane,
  1746. // rather than directly getting the pointer for lane VF - 1, because the
  1747. // pointer operand of the interleaved access is supposed to be uniform. For
  1748. // uniform instructions, we're only required to generate a value for the
  1749. // first vector lane in each unroll iteration.
  1750. if (Group->isReverse())
  1751. Index += (VF - 1) * Group->getFactor();
  1752. bool InBounds = false;
  1753. if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
  1754. InBounds = gep->isInBounds();
  1755. for (unsigned Part = 0; Part < UF; Part++) {
  1756. Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
  1757. // Notice current instruction could be any index. Need to adjust the address
  1758. // to the member of index 0.
  1759. //
  1760. // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
  1761. // b = A[i]; // Member of index 0
  1762. // Current pointer is pointed to A[i+1], adjust it to A[i].
  1763. //
  1764. // E.g. A[i+1] = a; // Member of index 1
  1765. // A[i] = b; // Member of index 0
  1766. // A[i+2] = c; // Member of index 2 (Current instruction)
  1767. // Current pointer is pointed to A[i+2], adjust it to A[i].
  1768. NewPtr = Builder.CreateGEP(ScalarTy, NewPtr, Builder.getInt32(-Index));
  1769. if (InBounds)
  1770. cast<GetElementPtrInst>(NewPtr)->setIsInBounds(true);
  1771. // Cast to the vector pointer type.
  1772. NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
  1773. }
  1774. setDebugLocFromInst(Builder, Instr);
  1775. Value *UndefVec = UndefValue::get(VecTy);
  1776. Value *MaskForGaps = nullptr;
  1777. if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
  1778. MaskForGaps = createBitMaskForGaps(Builder, VF, *Group);
  1779. assert(MaskForGaps && "Mask for Gaps is required but it is null");
  1780. }
  1781. // Vectorize the interleaved load group.
  1782. if (isa<LoadInst>(Instr)) {
  1783. // For each unroll part, create a wide load for the group.
  1784. SmallVector<Value *, 2> NewLoads;
  1785. for (unsigned Part = 0; Part < UF; Part++) {
  1786. Instruction *NewLoad;
  1787. if (IsMaskForCondRequired || MaskForGaps) {
  1788. assert(useMaskedInterleavedAccesses(*TTI) &&
  1789. "masked interleaved groups are not allowed.");
  1790. Value *GroupMask = MaskForGaps;
  1791. if (IsMaskForCondRequired) {
  1792. auto *Undefs = UndefValue::get(Mask[Part]->getType());
  1793. auto *RepMask = createReplicatedMask(Builder, InterleaveFactor, VF);
  1794. Value *ShuffledMask = Builder.CreateShuffleVector(
  1795. Mask[Part], Undefs, RepMask, "interleaved.mask");
  1796. GroupMask = MaskForGaps
  1797. ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
  1798. MaskForGaps)
  1799. : ShuffledMask;
  1800. }
  1801. NewLoad =
  1802. Builder.CreateMaskedLoad(NewPtrs[Part], Group->getAlignment(),
  1803. GroupMask, UndefVec, "wide.masked.vec");
  1804. }
  1805. else
  1806. NewLoad = Builder.CreateAlignedLoad(VecTy, NewPtrs[Part],
  1807. Group->getAlignment(), "wide.vec");
  1808. Group->addMetadata(NewLoad);
  1809. NewLoads.push_back(NewLoad);
  1810. }
  1811. // For each member in the group, shuffle out the appropriate data from the
  1812. // wide loads.
  1813. for (unsigned I = 0; I < InterleaveFactor; ++I) {
  1814. Instruction *Member = Group->getMember(I);
  1815. // Skip the gaps in the group.
  1816. if (!Member)
  1817. continue;
  1818. Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
  1819. for (unsigned Part = 0; Part < UF; Part++) {
  1820. Value *StridedVec = Builder.CreateShuffleVector(
  1821. NewLoads[Part], UndefVec, StrideMask, "strided.vec");
  1822. // If this member has different type, cast the result type.
  1823. if (Member->getType() != ScalarTy) {
  1824. VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
  1825. StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
  1826. }
  1827. if (Group->isReverse())
  1828. StridedVec = reverseVector(StridedVec);
  1829. VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
  1830. }
  1831. }
  1832. return;
  1833. }
  1834. // The sub vector type for current instruction.
  1835. VectorType *SubVT = VectorType::get(ScalarTy, VF);
  1836. // Vectorize the interleaved store group.
  1837. for (unsigned Part = 0; Part < UF; Part++) {
  1838. // Collect the stored vector from each member.
  1839. SmallVector<Value *, 4> StoredVecs;
  1840. for (unsigned i = 0; i < InterleaveFactor; i++) {
  1841. // Interleaved store group doesn't allow a gap, so each index has a member
  1842. Instruction *Member = Group->getMember(i);
  1843. assert(Member && "Fail to get a member from an interleaved store group");
  1844. Value *StoredVec = getOrCreateVectorValue(
  1845. cast<StoreInst>(Member)->getValueOperand(), Part);
  1846. if (Group->isReverse())
  1847. StoredVec = reverseVector(StoredVec);
  1848. // If this member has different type, cast it to a unified type.
  1849. if (StoredVec->getType() != SubVT)
  1850. StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
  1851. StoredVecs.push_back(StoredVec);
  1852. }
  1853. // Concatenate all vectors into a wide vector.
  1854. Value *WideVec = concatenateVectors(Builder, StoredVecs);
  1855. // Interleave the elements in the wide vector.
  1856. Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
  1857. Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
  1858. "interleaved.vec");
  1859. Instruction *NewStoreInstr;
  1860. if (IsMaskForCondRequired) {
  1861. auto *Undefs = UndefValue::get(Mask[Part]->getType());
  1862. auto *RepMask = createReplicatedMask(Builder, InterleaveFactor, VF);
  1863. Value *ShuffledMask = Builder.CreateShuffleVector(
  1864. Mask[Part], Undefs, RepMask, "interleaved.mask");
  1865. NewStoreInstr = Builder.CreateMaskedStore(
  1866. IVec, NewPtrs[Part], Group->getAlignment(), ShuffledMask);
  1867. }
  1868. else
  1869. NewStoreInstr = Builder.CreateAlignedStore(IVec, NewPtrs[Part],
  1870. Group->getAlignment());
  1871. Group->addMetadata(NewStoreInstr);
  1872. }
  1873. }
  1874. void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
  1875. VectorParts *BlockInMask) {
  1876. // Attempt to issue a wide load.
  1877. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  1878. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  1879. assert((LI || SI) && "Invalid Load/Store instruction");
  1880. LoopVectorizationCostModel::InstWidening Decision =
  1881. Cost->getWideningDecision(Instr, VF);
  1882. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  1883. "CM decision should be taken at this point");
  1884. if (Decision == LoopVectorizationCostModel::CM_Interleave)
  1885. return vectorizeInterleaveGroup(Instr);
  1886. Type *ScalarDataTy = getMemInstValueType(Instr);
  1887. Type *DataTy = VectorType::get(ScalarDataTy, VF);
  1888. Value *Ptr = getLoadStorePointerOperand(Instr);
  1889. unsigned Alignment = getLoadStoreAlignment(Instr);
  1890. // An alignment of 0 means target abi alignment. We need to use the scalar's
  1891. // target abi alignment in such a case.
  1892. const DataLayout &DL = Instr->getModule()->getDataLayout();
  1893. if (!Alignment)
  1894. Alignment = DL.getABITypeAlignment(ScalarDataTy);
  1895. unsigned AddressSpace = getLoadStoreAddressSpace(Instr);
  1896. // Determine if the pointer operand of the access is either consecutive or
  1897. // reverse consecutive.
  1898. bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
  1899. bool ConsecutiveStride =
  1900. Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
  1901. bool CreateGatherScatter =
  1902. (Decision == LoopVectorizationCostModel::CM_GatherScatter);
  1903. // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
  1904. // gather/scatter. Otherwise Decision should have been to Scalarize.
  1905. assert((ConsecutiveStride || CreateGatherScatter) &&
  1906. "The instruction should be scalarized");
  1907. // Handle consecutive loads/stores.
  1908. if (ConsecutiveStride)
  1909. Ptr = getOrCreateScalarValue(Ptr, {0, 0});
  1910. VectorParts Mask;
  1911. bool isMaskRequired = BlockInMask;
  1912. if (isMaskRequired)
  1913. Mask = *BlockInMask;
  1914. bool InBounds = false;
  1915. if (auto *gep = dyn_cast<GetElementPtrInst>(
  1916. getLoadStorePointerOperand(Instr)->stripPointerCasts()))
  1917. InBounds = gep->isInBounds();
  1918. const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
  1919. // Calculate the pointer for the specific unroll-part.
  1920. GetElementPtrInst *PartPtr = nullptr;
  1921. if (Reverse) {
  1922. // If the address is consecutive but reversed, then the
  1923. // wide store needs to start at the last vector element.
  1924. PartPtr = cast<GetElementPtrInst>(
  1925. Builder.CreateGEP(ScalarDataTy, Ptr, Builder.getInt32(-Part * VF)));
  1926. PartPtr->setIsInBounds(InBounds);
  1927. PartPtr = cast<GetElementPtrInst>(
  1928. Builder.CreateGEP(ScalarDataTy, PartPtr, Builder.getInt32(1 - VF)));
  1929. PartPtr->setIsInBounds(InBounds);
  1930. if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
  1931. Mask[Part] = reverseVector(Mask[Part]);
  1932. } else {
  1933. PartPtr = cast<GetElementPtrInst>(
  1934. Builder.CreateGEP(ScalarDataTy, Ptr, Builder.getInt32(Part * VF)));
  1935. PartPtr->setIsInBounds(InBounds);
  1936. }
  1937. return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
  1938. };
  1939. // Handle Stores:
  1940. if (SI) {
  1941. setDebugLocFromInst(Builder, SI);
  1942. for (unsigned Part = 0; Part < UF; ++Part) {
  1943. Instruction *NewSI = nullptr;
  1944. Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
  1945. if (CreateGatherScatter) {
  1946. Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
  1947. Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
  1948. NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
  1949. MaskPart);
  1950. } else {
  1951. if (Reverse) {
  1952. // If we store to reverse consecutive memory locations, then we need
  1953. // to reverse the order of elements in the stored value.
  1954. StoredVal = reverseVector(StoredVal);
  1955. // We don't want to update the value in the map as it might be used in
  1956. // another expression. So don't call resetVectorValue(StoredVal).
  1957. }
  1958. auto *VecPtr = CreateVecPtr(Part, Ptr);
  1959. if (isMaskRequired)
  1960. NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
  1961. Mask[Part]);
  1962. else
  1963. NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
  1964. }
  1965. addMetadata(NewSI, SI);
  1966. }
  1967. return;
  1968. }
  1969. // Handle loads.
  1970. assert(LI && "Must have a load instruction");
  1971. setDebugLocFromInst(Builder, LI);
  1972. for (unsigned Part = 0; Part < UF; ++Part) {
  1973. Value *NewLI;
  1974. if (CreateGatherScatter) {
  1975. Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
  1976. Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
  1977. NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
  1978. nullptr, "wide.masked.gather");
  1979. addMetadata(NewLI, LI);
  1980. } else {
  1981. auto *VecPtr = CreateVecPtr(Part, Ptr);
  1982. if (isMaskRequired)
  1983. NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
  1984. UndefValue::get(DataTy),
  1985. "wide.masked.load");
  1986. else
  1987. NewLI =
  1988. Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
  1989. // Add metadata to the load, but setVectorValue to the reverse shuffle.
  1990. addMetadata(NewLI, LI);
  1991. if (Reverse)
  1992. NewLI = reverseVector(NewLI);
  1993. }
  1994. VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
  1995. }
  1996. }
  1997. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
  1998. const VPIteration &Instance,
  1999. bool IfPredicateInstr) {
  2000. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  2001. setDebugLocFromInst(Builder, Instr);
  2002. // Does this instruction return a value ?
  2003. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  2004. Instruction *Cloned = Instr->clone();
  2005. if (!IsVoidRetTy)
  2006. Cloned->setName(Instr->getName() + ".cloned");
  2007. // Replace the operands of the cloned instructions with their scalar
  2008. // equivalents in the new loop.
  2009. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  2010. auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
  2011. Cloned->setOperand(op, NewOp);
  2012. }
  2013. addNewMetadata(Cloned, Instr);
  2014. // Place the cloned scalar in the new loop.
  2015. Builder.Insert(Cloned);
  2016. // Add the cloned scalar to the scalar map entry.
  2017. VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
  2018. // If we just cloned a new assumption, add it the assumption cache.
  2019. if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
  2020. if (II->getIntrinsicID() == Intrinsic::assume)
  2021. AC->registerAssumption(II);
  2022. // End if-block.
  2023. if (IfPredicateInstr)
  2024. PredicatedInstructions.push_back(Cloned);
  2025. }
  2026. PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
  2027. Value *End, Value *Step,
  2028. Instruction *DL) {
  2029. BasicBlock *Header = L->getHeader();
  2030. BasicBlock *Latch = L->getLoopLatch();
  2031. // As we're just creating this loop, it's possible no latch exists
  2032. // yet. If so, use the header as this will be a single block loop.
  2033. if (!Latch)
  2034. Latch = Header;
  2035. IRBuilder<> Builder(&*Header->getFirstInsertionPt());
  2036. Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
  2037. setDebugLocFromInst(Builder, OldInst);
  2038. auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
  2039. Builder.SetInsertPoint(Latch->getTerminator());
  2040. setDebugLocFromInst(Builder, OldInst);
  2041. // Create i+1 and fill the PHINode.
  2042. Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
  2043. Induction->addIncoming(Start, L->getLoopPreheader());
  2044. Induction->addIncoming(Next, Latch);
  2045. // Create the compare.
  2046. Value *ICmp = Builder.CreateICmpEQ(Next, End);
  2047. Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
  2048. // Now we have two terminators. Remove the old one from the block.
  2049. Latch->getTerminator()->eraseFromParent();
  2050. return Induction;
  2051. }
  2052. Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
  2053. if (TripCount)
  2054. return TripCount;
  2055. assert(L && "Create Trip Count for null loop.");
  2056. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2057. // Find the loop boundaries.
  2058. ScalarEvolution *SE = PSE.getSE();
  2059. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  2060. assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
  2061. "Invalid loop count");
  2062. Type *IdxTy = Legal->getWidestInductionType();
  2063. assert(IdxTy && "No type for induction");
  2064. // The exit count might have the type of i64 while the phi is i32. This can
  2065. // happen if we have an induction variable that is sign extended before the
  2066. // compare. The only way that we get a backedge taken count is that the
  2067. // induction variable was signed and as such will not overflow. In such a case
  2068. // truncation is legal.
  2069. if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
  2070. IdxTy->getPrimitiveSizeInBits())
  2071. BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
  2072. BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
  2073. // Get the total trip count from the count by adding 1.
  2074. const SCEV *ExitCount = SE->getAddExpr(
  2075. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  2076. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  2077. // Expand the trip count and place the new instructions in the preheader.
  2078. // Notice that the pre-header does not change, only the loop body.
  2079. SCEVExpander Exp(*SE, DL, "induction");
  2080. // Count holds the overall loop count (N).
  2081. TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  2082. L->getLoopPreheader()->getTerminator());
  2083. if (TripCount->getType()->isPointerTy())
  2084. TripCount =
  2085. CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
  2086. L->getLoopPreheader()->getTerminator());
  2087. return TripCount;
  2088. }
  2089. Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
  2090. if (VectorTripCount)
  2091. return VectorTripCount;
  2092. Value *TC = getOrCreateTripCount(L);
  2093. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2094. Type *Ty = TC->getType();
  2095. Constant *Step = ConstantInt::get(Ty, VF * UF);
  2096. // If the tail is to be folded by masking, round the number of iterations N
  2097. // up to a multiple of Step instead of rounding down. This is done by first
  2098. // adding Step-1 and then rounding down. Note that it's ok if this addition
  2099. // overflows: the vector induction variable will eventually wrap to zero given
  2100. // that it starts at zero and its Step is a power of two; the loop will then
  2101. // exit, with the last early-exit vector comparison also producing all-true.
  2102. if (Cost->foldTailByMasking()) {
  2103. assert(isPowerOf2_32(VF * UF) &&
  2104. "VF*UF must be a power of 2 when folding tail by masking");
  2105. TC = Builder.CreateAdd(TC, ConstantInt::get(Ty, VF * UF - 1), "n.rnd.up");
  2106. }
  2107. // Now we need to generate the expression for the part of the loop that the
  2108. // vectorized body will execute. This is equal to N - (N % Step) if scalar
  2109. // iterations are not required for correctness, or N - Step, otherwise. Step
  2110. // is equal to the vectorization factor (number of SIMD elements) times the
  2111. // unroll factor (number of SIMD instructions).
  2112. Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
  2113. // If there is a non-reversed interleaved group that may speculatively access
  2114. // memory out-of-bounds, we need to ensure that there will be at least one
  2115. // iteration of the scalar epilogue loop. Thus, if the step evenly divides
  2116. // the trip count, we set the remainder to be equal to the step. If the step
  2117. // does not evenly divide the trip count, no adjustment is necessary since
  2118. // there will already be scalar iterations. Note that the minimum iterations
  2119. // check ensures that N >= Step.
  2120. if (VF > 1 && Cost->requiresScalarEpilogue()) {
  2121. auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
  2122. R = Builder.CreateSelect(IsZero, Step, R);
  2123. }
  2124. VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
  2125. return VectorTripCount;
  2126. }
  2127. Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
  2128. const DataLayout &DL) {
  2129. // Verify that V is a vector type with same number of elements as DstVTy.
  2130. unsigned VF = DstVTy->getNumElements();
  2131. VectorType *SrcVecTy = cast<VectorType>(V->getType());
  2132. assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
  2133. Type *SrcElemTy = SrcVecTy->getElementType();
  2134. Type *DstElemTy = DstVTy->getElementType();
  2135. assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
  2136. "Vector elements must have same size");
  2137. // Do a direct cast if element types are castable.
  2138. if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
  2139. return Builder.CreateBitOrPointerCast(V, DstVTy);
  2140. }
  2141. // V cannot be directly casted to desired vector type.
  2142. // May happen when V is a floating point vector but DstVTy is a vector of
  2143. // pointers or vice-versa. Handle this using a two-step bitcast using an
  2144. // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
  2145. assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
  2146. "Only one type should be a pointer type");
  2147. assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
  2148. "Only one type should be a floating point type");
  2149. Type *IntTy =
  2150. IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
  2151. VectorType *VecIntTy = VectorType::get(IntTy, VF);
  2152. Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
  2153. return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
  2154. }
  2155. void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
  2156. BasicBlock *Bypass) {
  2157. Value *Count = getOrCreateTripCount(L);
  2158. BasicBlock *BB = L->getLoopPreheader();
  2159. IRBuilder<> Builder(BB->getTerminator());
  2160. // Generate code to check if the loop's trip count is less than VF * UF, or
  2161. // equal to it in case a scalar epilogue is required; this implies that the
  2162. // vector trip count is zero. This check also covers the case where adding one
  2163. // to the backedge-taken count overflowed leading to an incorrect trip count
  2164. // of zero. In this case we will also jump to the scalar loop.
  2165. auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
  2166. : ICmpInst::ICMP_ULT;
  2167. // If tail is to be folded, vector loop takes care of all iterations.
  2168. Value *CheckMinIters = Builder.getFalse();
  2169. if (!Cost->foldTailByMasking())
  2170. CheckMinIters = Builder.CreateICmp(
  2171. P, Count, ConstantInt::get(Count->getType(), VF * UF),
  2172. "min.iters.check");
  2173. BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2174. // Update dominator tree immediately if the generated block is a
  2175. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2176. // checks may query it before the current function is finished.
  2177. DT->addNewBlock(NewBB, BB);
  2178. if (L->getParentLoop())
  2179. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2180. ReplaceInstWithInst(BB->getTerminator(),
  2181. BranchInst::Create(Bypass, NewBB, CheckMinIters));
  2182. LoopBypassBlocks.push_back(BB);
  2183. }
  2184. void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
  2185. BasicBlock *BB = L->getLoopPreheader();
  2186. // Generate the code to check that the SCEV assumptions that we made.
  2187. // We want the new basic block to start at the first instruction in a
  2188. // sequence of instructions that form a check.
  2189. SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
  2190. "scev.check");
  2191. Value *SCEVCheck =
  2192. Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
  2193. if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
  2194. if (C->isZero())
  2195. return;
  2196. assert(!Cost->foldTailByMasking() &&
  2197. "Cannot SCEV check stride or overflow when folding tail");
  2198. // Create a new block containing the stride check.
  2199. BB->setName("vector.scevcheck");
  2200. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2201. // Update dominator tree immediately if the generated block is a
  2202. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2203. // checks may query it before the current function is finished.
  2204. DT->addNewBlock(NewBB, BB);
  2205. if (L->getParentLoop())
  2206. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2207. ReplaceInstWithInst(BB->getTerminator(),
  2208. BranchInst::Create(Bypass, NewBB, SCEVCheck));
  2209. LoopBypassBlocks.push_back(BB);
  2210. AddedSafetyChecks = true;
  2211. }
  2212. void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
  2213. // VPlan-native path does not do any analysis for runtime checks currently.
  2214. if (EnableVPlanNativePath)
  2215. return;
  2216. BasicBlock *BB = L->getLoopPreheader();
  2217. // Generate the code that checks in runtime if arrays overlap. We put the
  2218. // checks into a separate block to make the more common case of few elements
  2219. // faster.
  2220. Instruction *FirstCheckInst;
  2221. Instruction *MemRuntimeCheck;
  2222. std::tie(FirstCheckInst, MemRuntimeCheck) =
  2223. Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
  2224. if (!MemRuntimeCheck)
  2225. return;
  2226. assert(!Cost->foldTailByMasking() && "Cannot check memory when folding tail");
  2227. // Create a new block containing the memory check.
  2228. BB->setName("vector.memcheck");
  2229. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2230. // Update dominator tree immediately if the generated block is a
  2231. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2232. // checks may query it before the current function is finished.
  2233. DT->addNewBlock(NewBB, BB);
  2234. if (L->getParentLoop())
  2235. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2236. ReplaceInstWithInst(BB->getTerminator(),
  2237. BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
  2238. LoopBypassBlocks.push_back(BB);
  2239. AddedSafetyChecks = true;
  2240. // We currently don't use LoopVersioning for the actual loop cloning but we
  2241. // still use it to add the noalias metadata.
  2242. LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
  2243. PSE.getSE());
  2244. LVer->prepareNoAliasMetadata();
  2245. }
  2246. Value *InnerLoopVectorizer::emitTransformedIndex(
  2247. IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
  2248. const InductionDescriptor &ID) const {
  2249. SCEVExpander Exp(*SE, DL, "induction");
  2250. auto Step = ID.getStep();
  2251. auto StartValue = ID.getStartValue();
  2252. assert(Index->getType() == Step->getType() &&
  2253. "Index type does not match StepValue type");
  2254. // Note: the IR at this point is broken. We cannot use SE to create any new
  2255. // SCEV and then expand it, hoping that SCEV's simplification will give us
  2256. // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
  2257. // lead to various SCEV crashes. So all we can do is to use builder and rely
  2258. // on InstCombine for future simplifications. Here we handle some trivial
  2259. // cases only.
  2260. auto CreateAdd = [&B](Value *X, Value *Y) {
  2261. assert(X->getType() == Y->getType() && "Types don't match!");
  2262. if (auto *CX = dyn_cast<ConstantInt>(X))
  2263. if (CX->isZero())
  2264. return Y;
  2265. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2266. if (CY->isZero())
  2267. return X;
  2268. return B.CreateAdd(X, Y);
  2269. };
  2270. auto CreateMul = [&B](Value *X, Value *Y) {
  2271. assert(X->getType() == Y->getType() && "Types don't match!");
  2272. if (auto *CX = dyn_cast<ConstantInt>(X))
  2273. if (CX->isOne())
  2274. return Y;
  2275. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2276. if (CY->isOne())
  2277. return X;
  2278. return B.CreateMul(X, Y);
  2279. };
  2280. switch (ID.getKind()) {
  2281. case InductionDescriptor::IK_IntInduction: {
  2282. assert(Index->getType() == StartValue->getType() &&
  2283. "Index type does not match StartValue type");
  2284. if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
  2285. return B.CreateSub(StartValue, Index);
  2286. auto *Offset = CreateMul(
  2287. Index, Exp.expandCodeFor(Step, Index->getType(), &*B.GetInsertPoint()));
  2288. return CreateAdd(StartValue, Offset);
  2289. }
  2290. case InductionDescriptor::IK_PtrInduction: {
  2291. assert(isa<SCEVConstant>(Step) &&
  2292. "Expected constant step for pointer induction");
  2293. return B.CreateGEP(
  2294. StartValue->getType()->getPointerElementType(), StartValue,
  2295. CreateMul(Index, Exp.expandCodeFor(Step, Index->getType(),
  2296. &*B.GetInsertPoint())));
  2297. }
  2298. case InductionDescriptor::IK_FpInduction: {
  2299. assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
  2300. auto InductionBinOp = ID.getInductionBinOp();
  2301. assert(InductionBinOp &&
  2302. (InductionBinOp->getOpcode() == Instruction::FAdd ||
  2303. InductionBinOp->getOpcode() == Instruction::FSub) &&
  2304. "Original bin op should be defined for FP induction");
  2305. Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
  2306. // Floating point operations had to be 'fast' to enable the induction.
  2307. FastMathFlags Flags;
  2308. Flags.setFast();
  2309. Value *MulExp = B.CreateFMul(StepValue, Index);
  2310. if (isa<Instruction>(MulExp))
  2311. // We have to check, the MulExp may be a constant.
  2312. cast<Instruction>(MulExp)->setFastMathFlags(Flags);
  2313. Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
  2314. "induction");
  2315. if (isa<Instruction>(BOp))
  2316. cast<Instruction>(BOp)->setFastMathFlags(Flags);
  2317. return BOp;
  2318. }
  2319. case InductionDescriptor::IK_NoInduction:
  2320. return nullptr;
  2321. }
  2322. llvm_unreachable("invalid enum");
  2323. }
  2324. BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
  2325. /*
  2326. In this function we generate a new loop. The new loop will contain
  2327. the vectorized instructions while the old loop will continue to run the
  2328. scalar remainder.
  2329. [ ] <-- loop iteration number check.
  2330. / |
  2331. / v
  2332. | [ ] <-- vector loop bypass (may consist of multiple blocks).
  2333. | / |
  2334. | / v
  2335. || [ ] <-- vector pre header.
  2336. |/ |
  2337. | v
  2338. | [ ] \
  2339. | [ ]_| <-- vector loop.
  2340. | |
  2341. | v
  2342. | -[ ] <--- middle-block.
  2343. | / |
  2344. | / v
  2345. -|- >[ ] <--- new preheader.
  2346. | |
  2347. | v
  2348. | [ ] \
  2349. | [ ]_| <-- old scalar loop to handle remainder.
  2350. \ |
  2351. \ v
  2352. >[ ] <-- exit block.
  2353. ...
  2354. */
  2355. BasicBlock *OldBasicBlock = OrigLoop->getHeader();
  2356. BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
  2357. BasicBlock *ExitBlock = OrigLoop->getExitBlock();
  2358. MDNode *OrigLoopID = OrigLoop->getLoopID();
  2359. assert(VectorPH && "Invalid loop structure");
  2360. assert(ExitBlock && "Must have an exit block");
  2361. // Some loops have a single integer induction variable, while other loops
  2362. // don't. One example is c++ iterators that often have multiple pointer
  2363. // induction variables. In the code below we also support a case where we
  2364. // don't have a single induction variable.
  2365. //
  2366. // We try to obtain an induction variable from the original loop as hard
  2367. // as possible. However if we don't find one that:
  2368. // - is an integer
  2369. // - counts from zero, stepping by one
  2370. // - is the size of the widest induction variable type
  2371. // then we create a new one.
  2372. OldInduction = Legal->getPrimaryInduction();
  2373. Type *IdxTy = Legal->getWidestInductionType();
  2374. // Split the single block loop into the two loop structure described above.
  2375. BasicBlock *VecBody =
  2376. VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
  2377. BasicBlock *MiddleBlock =
  2378. VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
  2379. BasicBlock *ScalarPH =
  2380. MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
  2381. // Create and register the new vector loop.
  2382. Loop *Lp = LI->AllocateLoop();
  2383. Loop *ParentLoop = OrigLoop->getParentLoop();
  2384. // Insert the new loop into the loop nest and register the new basic blocks
  2385. // before calling any utilities such as SCEV that require valid LoopInfo.
  2386. if (ParentLoop) {
  2387. ParentLoop->addChildLoop(Lp);
  2388. ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
  2389. ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
  2390. } else {
  2391. LI->addTopLevelLoop(Lp);
  2392. }
  2393. Lp->addBasicBlockToLoop(VecBody, *LI);
  2394. // Find the loop boundaries.
  2395. Value *Count = getOrCreateTripCount(Lp);
  2396. Value *StartIdx = ConstantInt::get(IdxTy, 0);
  2397. // Now, compare the new count to zero. If it is zero skip the vector loop and
  2398. // jump to the scalar loop. This check also covers the case where the
  2399. // backedge-taken count is uint##_max: adding one to it will overflow leading
  2400. // to an incorrect trip count of zero. In this (rare) case we will also jump
  2401. // to the scalar loop.
  2402. emitMinimumIterationCountCheck(Lp, ScalarPH);
  2403. // Generate the code to check any assumptions that we've made for SCEV
  2404. // expressions.
  2405. emitSCEVChecks(Lp, ScalarPH);
  2406. // Generate the code that checks in runtime if arrays overlap. We put the
  2407. // checks into a separate block to make the more common case of few elements
  2408. // faster.
  2409. emitMemRuntimeChecks(Lp, ScalarPH);
  2410. // Generate the induction variable.
  2411. // The loop step is equal to the vectorization factor (num of SIMD elements)
  2412. // times the unroll factor (num of SIMD instructions).
  2413. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  2414. Constant *Step = ConstantInt::get(IdxTy, VF * UF);
  2415. Induction =
  2416. createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
  2417. getDebugLocFromInstOrOperands(OldInduction));
  2418. // We are going to resume the execution of the scalar loop.
  2419. // Go over all of the induction variables that we found and fix the
  2420. // PHIs that are left in the scalar version of the loop.
  2421. // The starting values of PHI nodes depend on the counter of the last
  2422. // iteration in the vectorized loop.
  2423. // If we come from a bypass edge then we need to start from the original
  2424. // start value.
  2425. // This variable saves the new starting index for the scalar loop. It is used
  2426. // to test if there are any tail iterations left once the vector loop has
  2427. // completed.
  2428. LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
  2429. for (auto &InductionEntry : *List) {
  2430. PHINode *OrigPhi = InductionEntry.first;
  2431. InductionDescriptor II = InductionEntry.second;
  2432. // Create phi nodes to merge from the backedge-taken check block.
  2433. PHINode *BCResumeVal = PHINode::Create(
  2434. OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
  2435. // Copy original phi DL over to the new one.
  2436. BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
  2437. Value *&EndValue = IVEndValues[OrigPhi];
  2438. if (OrigPhi == OldInduction) {
  2439. // We know what the end value is.
  2440. EndValue = CountRoundDown;
  2441. } else {
  2442. IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
  2443. Type *StepType = II.getStep()->getType();
  2444. Instruction::CastOps CastOp =
  2445. CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
  2446. Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
  2447. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  2448. EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
  2449. EndValue->setName("ind.end");
  2450. }
  2451. // The new PHI merges the original incoming value, in case of a bypass,
  2452. // or the value at the end of the vectorized loop.
  2453. BCResumeVal->addIncoming(EndValue, MiddleBlock);
  2454. // Fix the scalar body counter (PHI node).
  2455. unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
  2456. // The old induction's phi node in the scalar body needs the truncated
  2457. // value.
  2458. for (BasicBlock *BB : LoopBypassBlocks)
  2459. BCResumeVal->addIncoming(II.getStartValue(), BB);
  2460. OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
  2461. }
  2462. // We need the OrigLoop (scalar loop part) latch terminator to help
  2463. // produce correct debug info for the middle block BB instructions.
  2464. // The legality check stage guarantees that the loop will have a single
  2465. // latch.
  2466. assert(isa<BranchInst>(OrigLoop->getLoopLatch()->getTerminator()) &&
  2467. "Scalar loop latch terminator isn't a branch");
  2468. BranchInst *ScalarLatchBr =
  2469. cast<BranchInst>(OrigLoop->getLoopLatch()->getTerminator());
  2470. // Add a check in the middle block to see if we have completed
  2471. // all of the iterations in the first vector loop.
  2472. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  2473. // If tail is to be folded, we know we don't need to run the remainder.
  2474. Value *CmpN = Builder.getTrue();
  2475. if (!Cost->foldTailByMasking()) {
  2476. CmpN =
  2477. CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
  2478. CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
  2479. // Provide correct stepping behaviour by using the same DebugLoc as the
  2480. // scalar loop latch branch cmp if it exists.
  2481. if (CmpInst *ScalarLatchCmp =
  2482. dyn_cast_or_null<CmpInst>(ScalarLatchBr->getCondition()))
  2483. cast<Instruction>(CmpN)->setDebugLoc(ScalarLatchCmp->getDebugLoc());
  2484. }
  2485. BranchInst *BrInst = BranchInst::Create(ExitBlock, ScalarPH, CmpN);
  2486. BrInst->setDebugLoc(ScalarLatchBr->getDebugLoc());
  2487. ReplaceInstWithInst(MiddleBlock->getTerminator(), BrInst);
  2488. // Get ready to start creating new instructions into the vectorized body.
  2489. Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
  2490. // Save the state.
  2491. LoopVectorPreHeader = Lp->getLoopPreheader();
  2492. LoopScalarPreHeader = ScalarPH;
  2493. LoopMiddleBlock = MiddleBlock;
  2494. LoopExitBlock = ExitBlock;
  2495. LoopVectorBody = VecBody;
  2496. LoopScalarBody = OldBasicBlock;
  2497. Optional<MDNode *> VectorizedLoopID =
  2498. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  2499. LLVMLoopVectorizeFollowupVectorized});
  2500. if (VectorizedLoopID.hasValue()) {
  2501. Lp->setLoopID(VectorizedLoopID.getValue());
  2502. // Do not setAlreadyVectorized if loop attributes have been defined
  2503. // explicitly.
  2504. return LoopVectorPreHeader;
  2505. }
  2506. // Keep all loop hints from the original loop on the vector loop (we'll
  2507. // replace the vectorizer-specific hints below).
  2508. if (MDNode *LID = OrigLoop->getLoopID())
  2509. Lp->setLoopID(LID);
  2510. LoopVectorizeHints Hints(Lp, true, *ORE);
  2511. Hints.setAlreadyVectorized();
  2512. return LoopVectorPreHeader;
  2513. }
  2514. // Fix up external users of the induction variable. At this point, we are
  2515. // in LCSSA form, with all external PHIs that use the IV having one input value,
  2516. // coming from the remainder loop. We need those PHIs to also have a correct
  2517. // value for the IV when arriving directly from the middle block.
  2518. void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
  2519. const InductionDescriptor &II,
  2520. Value *CountRoundDown, Value *EndValue,
  2521. BasicBlock *MiddleBlock) {
  2522. // There are two kinds of external IV usages - those that use the value
  2523. // computed in the last iteration (the PHI) and those that use the penultimate
  2524. // value (the value that feeds into the phi from the loop latch).
  2525. // We allow both, but they, obviously, have different values.
  2526. assert(OrigLoop->getExitBlock() && "Expected a single exit block");
  2527. DenseMap<Value *, Value *> MissingVals;
  2528. // An external user of the last iteration's value should see the value that
  2529. // the remainder loop uses to initialize its own IV.
  2530. Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
  2531. for (User *U : PostInc->users()) {
  2532. Instruction *UI = cast<Instruction>(U);
  2533. if (!OrigLoop->contains(UI)) {
  2534. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  2535. MissingVals[UI] = EndValue;
  2536. }
  2537. }
  2538. // An external user of the penultimate value need to see EndValue - Step.
  2539. // The simplest way to get this is to recompute it from the constituent SCEVs,
  2540. // that is Start + (Step * (CRD - 1)).
  2541. for (User *U : OrigPhi->users()) {
  2542. auto *UI = cast<Instruction>(U);
  2543. if (!OrigLoop->contains(UI)) {
  2544. const DataLayout &DL =
  2545. OrigLoop->getHeader()->getModule()->getDataLayout();
  2546. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  2547. IRBuilder<> B(MiddleBlock->getTerminator());
  2548. Value *CountMinusOne = B.CreateSub(
  2549. CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
  2550. Value *CMO =
  2551. !II.getStep()->getType()->isIntegerTy()
  2552. ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
  2553. II.getStep()->getType())
  2554. : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
  2555. CMO->setName("cast.cmo");
  2556. Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
  2557. Escape->setName("ind.escape");
  2558. MissingVals[UI] = Escape;
  2559. }
  2560. }
  2561. for (auto &I : MissingVals) {
  2562. PHINode *PHI = cast<PHINode>(I.first);
  2563. // One corner case we have to handle is two IVs "chasing" each-other,
  2564. // that is %IV2 = phi [...], [ %IV1, %latch ]
  2565. // In this case, if IV1 has an external use, we need to avoid adding both
  2566. // "last value of IV1" and "penultimate value of IV2". So, verify that we
  2567. // don't already have an incoming value for the middle block.
  2568. if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
  2569. PHI->addIncoming(I.second, MiddleBlock);
  2570. }
  2571. }
  2572. namespace {
  2573. struct CSEDenseMapInfo {
  2574. static bool canHandle(const Instruction *I) {
  2575. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  2576. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  2577. }
  2578. static inline Instruction *getEmptyKey() {
  2579. return DenseMapInfo<Instruction *>::getEmptyKey();
  2580. }
  2581. static inline Instruction *getTombstoneKey() {
  2582. return DenseMapInfo<Instruction *>::getTombstoneKey();
  2583. }
  2584. static unsigned getHashValue(const Instruction *I) {
  2585. assert(canHandle(I) && "Unknown instruction!");
  2586. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  2587. I->value_op_end()));
  2588. }
  2589. static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
  2590. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  2591. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  2592. return LHS == RHS;
  2593. return LHS->isIdenticalTo(RHS);
  2594. }
  2595. };
  2596. } // end anonymous namespace
  2597. ///Perform cse of induction variable instructions.
  2598. static void cse(BasicBlock *BB) {
  2599. // Perform simple cse.
  2600. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  2601. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  2602. Instruction *In = &*I++;
  2603. if (!CSEDenseMapInfo::canHandle(In))
  2604. continue;
  2605. // Check if we can replace this instruction with any of the
  2606. // visited instructions.
  2607. if (Instruction *V = CSEMap.lookup(In)) {
  2608. In->replaceAllUsesWith(V);
  2609. In->eraseFromParent();
  2610. continue;
  2611. }
  2612. CSEMap[In] = In;
  2613. }
  2614. }
  2615. unsigned LoopVectorizationCostModel::getVectorCallCost(CallInst *CI,
  2616. unsigned VF,
  2617. bool &NeedToScalarize) {
  2618. Function *F = CI->getCalledFunction();
  2619. StringRef FnName = CI->getCalledFunction()->getName();
  2620. Type *ScalarRetTy = CI->getType();
  2621. SmallVector<Type *, 4> Tys, ScalarTys;
  2622. for (auto &ArgOp : CI->arg_operands())
  2623. ScalarTys.push_back(ArgOp->getType());
  2624. // Estimate cost of scalarized vector call. The source operands are assumed
  2625. // to be vectors, so we need to extract individual elements from there,
  2626. // execute VF scalar calls, and then gather the result into the vector return
  2627. // value.
  2628. unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
  2629. if (VF == 1)
  2630. return ScalarCallCost;
  2631. // Compute corresponding vector type for return value and arguments.
  2632. Type *RetTy = ToVectorTy(ScalarRetTy, VF);
  2633. for (Type *ScalarTy : ScalarTys)
  2634. Tys.push_back(ToVectorTy(ScalarTy, VF));
  2635. // Compute costs of unpacking argument values for the scalar calls and
  2636. // packing the return values to a vector.
  2637. unsigned ScalarizationCost = getScalarizationOverhead(CI, VF);
  2638. unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
  2639. // If we can't emit a vector call for this function, then the currently found
  2640. // cost is the cost we need to return.
  2641. NeedToScalarize = true;
  2642. if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
  2643. return Cost;
  2644. // If the corresponding vector cost is cheaper, return its cost.
  2645. unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
  2646. if (VectorCallCost < Cost) {
  2647. NeedToScalarize = false;
  2648. return VectorCallCost;
  2649. }
  2650. return Cost;
  2651. }
  2652. unsigned LoopVectorizationCostModel::getVectorIntrinsicCost(CallInst *CI,
  2653. unsigned VF) {
  2654. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  2655. assert(ID && "Expected intrinsic call!");
  2656. FastMathFlags FMF;
  2657. if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
  2658. FMF = FPMO->getFastMathFlags();
  2659. SmallVector<Value *, 4> Operands(CI->arg_operands());
  2660. return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
  2661. }
  2662. static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
  2663. auto *I1 = cast<IntegerType>(T1->getVectorElementType());
  2664. auto *I2 = cast<IntegerType>(T2->getVectorElementType());
  2665. return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
  2666. }
  2667. static Type *largestIntegerVectorType(Type *T1, Type *T2) {
  2668. auto *I1 = cast<IntegerType>(T1->getVectorElementType());
  2669. auto *I2 = cast<IntegerType>(T2->getVectorElementType());
  2670. return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
  2671. }
  2672. void InnerLoopVectorizer::truncateToMinimalBitwidths() {
  2673. // For every instruction `I` in MinBWs, truncate the operands, create a
  2674. // truncated version of `I` and reextend its result. InstCombine runs
  2675. // later and will remove any ext/trunc pairs.
  2676. SmallPtrSet<Value *, 4> Erased;
  2677. for (const auto &KV : Cost->getMinimalBitwidths()) {
  2678. // If the value wasn't vectorized, we must maintain the original scalar
  2679. // type. The absence of the value from VectorLoopValueMap indicates that it
  2680. // wasn't vectorized.
  2681. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  2682. continue;
  2683. for (unsigned Part = 0; Part < UF; ++Part) {
  2684. Value *I = getOrCreateVectorValue(KV.first, Part);
  2685. if (Erased.find(I) != Erased.end() || I->use_empty() ||
  2686. !isa<Instruction>(I))
  2687. continue;
  2688. Type *OriginalTy = I->getType();
  2689. Type *ScalarTruncatedTy =
  2690. IntegerType::get(OriginalTy->getContext(), KV.second);
  2691. Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
  2692. OriginalTy->getVectorNumElements());
  2693. if (TruncatedTy == OriginalTy)
  2694. continue;
  2695. IRBuilder<> B(cast<Instruction>(I));
  2696. auto ShrinkOperand = [&](Value *V) -> Value * {
  2697. if (auto *ZI = dyn_cast<ZExtInst>(V))
  2698. if (ZI->getSrcTy() == TruncatedTy)
  2699. return ZI->getOperand(0);
  2700. return B.CreateZExtOrTrunc(V, TruncatedTy);
  2701. };
  2702. // The actual instruction modification depends on the instruction type,
  2703. // unfortunately.
  2704. Value *NewI = nullptr;
  2705. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  2706. NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
  2707. ShrinkOperand(BO->getOperand(1)));
  2708. // Any wrapping introduced by shrinking this operation shouldn't be
  2709. // considered undefined behavior. So, we can't unconditionally copy
  2710. // arithmetic wrapping flags to NewI.
  2711. cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
  2712. } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
  2713. NewI =
  2714. B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
  2715. ShrinkOperand(CI->getOperand(1)));
  2716. } else if (auto *SI = dyn_cast<SelectInst>(I)) {
  2717. NewI = B.CreateSelect(SI->getCondition(),
  2718. ShrinkOperand(SI->getTrueValue()),
  2719. ShrinkOperand(SI->getFalseValue()));
  2720. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  2721. switch (CI->getOpcode()) {
  2722. default:
  2723. llvm_unreachable("Unhandled cast!");
  2724. case Instruction::Trunc:
  2725. NewI = ShrinkOperand(CI->getOperand(0));
  2726. break;
  2727. case Instruction::SExt:
  2728. NewI = B.CreateSExtOrTrunc(
  2729. CI->getOperand(0),
  2730. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  2731. break;
  2732. case Instruction::ZExt:
  2733. NewI = B.CreateZExtOrTrunc(
  2734. CI->getOperand(0),
  2735. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  2736. break;
  2737. }
  2738. } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
  2739. auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
  2740. auto *O0 = B.CreateZExtOrTrunc(
  2741. SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
  2742. auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
  2743. auto *O1 = B.CreateZExtOrTrunc(
  2744. SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
  2745. NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
  2746. } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
  2747. // Don't do anything with the operands, just extend the result.
  2748. continue;
  2749. } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  2750. auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
  2751. auto *O0 = B.CreateZExtOrTrunc(
  2752. IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2753. auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
  2754. NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
  2755. } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
  2756. auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
  2757. auto *O0 = B.CreateZExtOrTrunc(
  2758. EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2759. NewI = B.CreateExtractElement(O0, EE->getOperand(2));
  2760. } else {
  2761. // If we don't know what to do, be conservative and don't do anything.
  2762. continue;
  2763. }
  2764. // Lastly, extend the result.
  2765. NewI->takeName(cast<Instruction>(I));
  2766. Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
  2767. I->replaceAllUsesWith(Res);
  2768. cast<Instruction>(I)->eraseFromParent();
  2769. Erased.insert(I);
  2770. VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
  2771. }
  2772. }
  2773. // We'll have created a bunch of ZExts that are now parentless. Clean up.
  2774. for (const auto &KV : Cost->getMinimalBitwidths()) {
  2775. // If the value wasn't vectorized, we must maintain the original scalar
  2776. // type. The absence of the value from VectorLoopValueMap indicates that it
  2777. // wasn't vectorized.
  2778. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  2779. continue;
  2780. for (unsigned Part = 0; Part < UF; ++Part) {
  2781. Value *I = getOrCreateVectorValue(KV.first, Part);
  2782. ZExtInst *Inst = dyn_cast<ZExtInst>(I);
  2783. if (Inst && Inst->use_empty()) {
  2784. Value *NewI = Inst->getOperand(0);
  2785. Inst->eraseFromParent();
  2786. VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
  2787. }
  2788. }
  2789. }
  2790. }
  2791. void InnerLoopVectorizer::fixVectorizedLoop() {
  2792. // Insert truncates and extends for any truncated instructions as hints to
  2793. // InstCombine.
  2794. if (VF > 1)
  2795. truncateToMinimalBitwidths();
  2796. // Fix widened non-induction PHIs by setting up the PHI operands.
  2797. if (OrigPHIsToFix.size()) {
  2798. assert(EnableVPlanNativePath &&
  2799. "Unexpected non-induction PHIs for fixup in non VPlan-native path");
  2800. fixNonInductionPHIs();
  2801. }
  2802. // At this point every instruction in the original loop is widened to a
  2803. // vector form. Now we need to fix the recurrences in the loop. These PHI
  2804. // nodes are currently empty because we did not want to introduce cycles.
  2805. // This is the second stage of vectorizing recurrences.
  2806. fixCrossIterationPHIs();
  2807. // Update the dominator tree.
  2808. //
  2809. // FIXME: After creating the structure of the new loop, the dominator tree is
  2810. // no longer up-to-date, and it remains that way until we update it
  2811. // here. An out-of-date dominator tree is problematic for SCEV,
  2812. // because SCEVExpander uses it to guide code generation. The
  2813. // vectorizer use SCEVExpanders in several places. Instead, we should
  2814. // keep the dominator tree up-to-date as we go.
  2815. updateAnalysis();
  2816. // Fix-up external users of the induction variables.
  2817. for (auto &Entry : *Legal->getInductionVars())
  2818. fixupIVUsers(Entry.first, Entry.second,
  2819. getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
  2820. IVEndValues[Entry.first], LoopMiddleBlock);
  2821. fixLCSSAPHIs();
  2822. for (Instruction *PI : PredicatedInstructions)
  2823. sinkScalarOperands(&*PI);
  2824. // Remove redundant induction instructions.
  2825. cse(LoopVectorBody);
  2826. }
  2827. void InnerLoopVectorizer::fixCrossIterationPHIs() {
  2828. // In order to support recurrences we need to be able to vectorize Phi nodes.
  2829. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  2830. // stage #2: We now need to fix the recurrences by adding incoming edges to
  2831. // the currently empty PHI nodes. At this point every instruction in the
  2832. // original loop is widened to a vector form so we can use them to construct
  2833. // the incoming edges.
  2834. for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
  2835. // Handle first-order recurrences and reductions that need to be fixed.
  2836. if (Legal->isFirstOrderRecurrence(&Phi))
  2837. fixFirstOrderRecurrence(&Phi);
  2838. else if (Legal->isReductionVariable(&Phi))
  2839. fixReduction(&Phi);
  2840. }
  2841. }
  2842. void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
  2843. // This is the second phase of vectorizing first-order recurrences. An
  2844. // overview of the transformation is described below. Suppose we have the
  2845. // following loop.
  2846. //
  2847. // for (int i = 0; i < n; ++i)
  2848. // b[i] = a[i] - a[i - 1];
  2849. //
  2850. // There is a first-order recurrence on "a". For this loop, the shorthand
  2851. // scalar IR looks like:
  2852. //
  2853. // scalar.ph:
  2854. // s_init = a[-1]
  2855. // br scalar.body
  2856. //
  2857. // scalar.body:
  2858. // i = phi [0, scalar.ph], [i+1, scalar.body]
  2859. // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
  2860. // s2 = a[i]
  2861. // b[i] = s2 - s1
  2862. // br cond, scalar.body, ...
  2863. //
  2864. // In this example, s1 is a recurrence because it's value depends on the
  2865. // previous iteration. In the first phase of vectorization, we created a
  2866. // temporary value for s1. We now complete the vectorization and produce the
  2867. // shorthand vector IR shown below (for VF = 4, UF = 1).
  2868. //
  2869. // vector.ph:
  2870. // v_init = vector(..., ..., ..., a[-1])
  2871. // br vector.body
  2872. //
  2873. // vector.body
  2874. // i = phi [0, vector.ph], [i+4, vector.body]
  2875. // v1 = phi [v_init, vector.ph], [v2, vector.body]
  2876. // v2 = a[i, i+1, i+2, i+3];
  2877. // v3 = vector(v1(3), v2(0, 1, 2))
  2878. // b[i, i+1, i+2, i+3] = v2 - v3
  2879. // br cond, vector.body, middle.block
  2880. //
  2881. // middle.block:
  2882. // x = v2(3)
  2883. // br scalar.ph
  2884. //
  2885. // scalar.ph:
  2886. // s_init = phi [x, middle.block], [a[-1], otherwise]
  2887. // br scalar.body
  2888. //
  2889. // After execution completes the vector loop, we extract the next value of
  2890. // the recurrence (x) to use as the initial value in the scalar loop.
  2891. // Get the original loop preheader and single loop latch.
  2892. auto *Preheader = OrigLoop->getLoopPreheader();
  2893. auto *Latch = OrigLoop->getLoopLatch();
  2894. // Get the initial and previous values of the scalar recurrence.
  2895. auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
  2896. auto *Previous = Phi->getIncomingValueForBlock(Latch);
  2897. // Create a vector from the initial value.
  2898. auto *VectorInit = ScalarInit;
  2899. if (VF > 1) {
  2900. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  2901. VectorInit = Builder.CreateInsertElement(
  2902. UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
  2903. Builder.getInt32(VF - 1), "vector.recur.init");
  2904. }
  2905. // We constructed a temporary phi node in the first phase of vectorization.
  2906. // This phi node will eventually be deleted.
  2907. Builder.SetInsertPoint(
  2908. cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
  2909. // Create a phi node for the new recurrence. The current value will either be
  2910. // the initial value inserted into a vector or loop-varying vector value.
  2911. auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
  2912. VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
  2913. // Get the vectorized previous value of the last part UF - 1. It appears last
  2914. // among all unrolled iterations, due to the order of their construction.
  2915. Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
  2916. // Set the insertion point after the previous value if it is an instruction.
  2917. // Note that the previous value may have been constant-folded so it is not
  2918. // guaranteed to be an instruction in the vector loop. Also, if the previous
  2919. // value is a phi node, we should insert after all the phi nodes to avoid
  2920. // breaking basic block verification.
  2921. if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
  2922. isa<PHINode>(PreviousLastPart))
  2923. Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
  2924. else
  2925. Builder.SetInsertPoint(
  2926. &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
  2927. // We will construct a vector for the recurrence by combining the values for
  2928. // the current and previous iterations. This is the required shuffle mask.
  2929. SmallVector<Constant *, 8> ShuffleMask(VF);
  2930. ShuffleMask[0] = Builder.getInt32(VF - 1);
  2931. for (unsigned I = 1; I < VF; ++I)
  2932. ShuffleMask[I] = Builder.getInt32(I + VF - 1);
  2933. // The vector from which to take the initial value for the current iteration
  2934. // (actual or unrolled). Initially, this is the vector phi node.
  2935. Value *Incoming = VecPhi;
  2936. // Shuffle the current and previous vector and update the vector parts.
  2937. for (unsigned Part = 0; Part < UF; ++Part) {
  2938. Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
  2939. Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
  2940. auto *Shuffle =
  2941. VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
  2942. ConstantVector::get(ShuffleMask))
  2943. : Incoming;
  2944. PhiPart->replaceAllUsesWith(Shuffle);
  2945. cast<Instruction>(PhiPart)->eraseFromParent();
  2946. VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
  2947. Incoming = PreviousPart;
  2948. }
  2949. // Fix the latch value of the new recurrence in the vector loop.
  2950. VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  2951. // Extract the last vector element in the middle block. This will be the
  2952. // initial value for the recurrence when jumping to the scalar loop.
  2953. auto *ExtractForScalar = Incoming;
  2954. if (VF > 1) {
  2955. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  2956. ExtractForScalar = Builder.CreateExtractElement(
  2957. ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
  2958. }
  2959. // Extract the second last element in the middle block if the
  2960. // Phi is used outside the loop. We need to extract the phi itself
  2961. // and not the last element (the phi update in the current iteration). This
  2962. // will be the value when jumping to the exit block from the LoopMiddleBlock,
  2963. // when the scalar loop is not run at all.
  2964. Value *ExtractForPhiUsedOutsideLoop = nullptr;
  2965. if (VF > 1)
  2966. ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
  2967. Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
  2968. // When loop is unrolled without vectorizing, initialize
  2969. // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
  2970. // `Incoming`. This is analogous to the vectorized case above: extracting the
  2971. // second last element when VF > 1.
  2972. else if (UF > 1)
  2973. ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
  2974. // Fix the initial value of the original recurrence in the scalar loop.
  2975. Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
  2976. auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
  2977. for (auto *BB : predecessors(LoopScalarPreHeader)) {
  2978. auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
  2979. Start->addIncoming(Incoming, BB);
  2980. }
  2981. Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
  2982. Phi->setName("scalar.recur");
  2983. // Finally, fix users of the recurrence outside the loop. The users will need
  2984. // either the last value of the scalar recurrence or the last value of the
  2985. // vector recurrence we extracted in the middle block. Since the loop is in
  2986. // LCSSA form, we just need to find all the phi nodes for the original scalar
  2987. // recurrence in the exit block, and then add an edge for the middle block.
  2988. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  2989. if (LCSSAPhi.getIncomingValue(0) == Phi) {
  2990. LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
  2991. }
  2992. }
  2993. }
  2994. void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
  2995. Constant *Zero = Builder.getInt32(0);
  2996. // Get it's reduction variable descriptor.
  2997. assert(Legal->isReductionVariable(Phi) &&
  2998. "Unable to find the reduction variable");
  2999. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
  3000. RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
  3001. TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
  3002. Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
  3003. RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
  3004. RdxDesc.getMinMaxRecurrenceKind();
  3005. setDebugLocFromInst(Builder, ReductionStartValue);
  3006. // We need to generate a reduction vector from the incoming scalar.
  3007. // To do so, we need to generate the 'identity' vector and override
  3008. // one of the elements with the incoming scalar reduction. We need
  3009. // to do it in the vector-loop preheader.
  3010. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  3011. // This is the vector-clone of the value that leaves the loop.
  3012. Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
  3013. // Find the reduction identity variable. Zero for addition, or, xor,
  3014. // one for multiplication, -1 for And.
  3015. Value *Identity;
  3016. Value *VectorStart;
  3017. if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
  3018. RK == RecurrenceDescriptor::RK_FloatMinMax) {
  3019. // MinMax reduction have the start value as their identify.
  3020. if (VF == 1) {
  3021. VectorStart = Identity = ReductionStartValue;
  3022. } else {
  3023. VectorStart = Identity =
  3024. Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
  3025. }
  3026. } else {
  3027. // Handle other reduction kinds:
  3028. Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
  3029. RK, VecTy->getScalarType());
  3030. if (VF == 1) {
  3031. Identity = Iden;
  3032. // This vector is the Identity vector where the first element is the
  3033. // incoming scalar reduction.
  3034. VectorStart = ReductionStartValue;
  3035. } else {
  3036. Identity = ConstantVector::getSplat(VF, Iden);
  3037. // This vector is the Identity vector where the first element is the
  3038. // incoming scalar reduction.
  3039. VectorStart =
  3040. Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
  3041. }
  3042. }
  3043. // Fix the vector-loop phi.
  3044. // Reductions do not have to start at zero. They can start with
  3045. // any loop invariant values.
  3046. BasicBlock *Latch = OrigLoop->getLoopLatch();
  3047. Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
  3048. for (unsigned Part = 0; Part < UF; ++Part) {
  3049. Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
  3050. Value *Val = getOrCreateVectorValue(LoopVal, Part);
  3051. // Make sure to add the reduction stat value only to the
  3052. // first unroll part.
  3053. Value *StartVal = (Part == 0) ? VectorStart : Identity;
  3054. cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
  3055. cast<PHINode>(VecRdxPhi)
  3056. ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3057. }
  3058. // Before each round, move the insertion point right between
  3059. // the PHIs and the values we are going to write.
  3060. // This allows us to write both PHINodes and the extractelement
  3061. // instructions.
  3062. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3063. setDebugLocFromInst(Builder, LoopExitInst);
  3064. // If the vector reduction can be performed in a smaller type, we truncate
  3065. // then extend the loop exit value to enable InstCombine to evaluate the
  3066. // entire expression in the smaller type.
  3067. if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
  3068. Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
  3069. Builder.SetInsertPoint(
  3070. LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
  3071. VectorParts RdxParts(UF);
  3072. for (unsigned Part = 0; Part < UF; ++Part) {
  3073. RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3074. Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3075. Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
  3076. : Builder.CreateZExt(Trunc, VecTy);
  3077. for (Value::user_iterator UI = RdxParts[Part]->user_begin();
  3078. UI != RdxParts[Part]->user_end();)
  3079. if (*UI != Trunc) {
  3080. (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
  3081. RdxParts[Part] = Extnd;
  3082. } else {
  3083. ++UI;
  3084. }
  3085. }
  3086. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3087. for (unsigned Part = 0; Part < UF; ++Part) {
  3088. RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3089. VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
  3090. }
  3091. }
  3092. // Reduce all of the unrolled parts into a single vector.
  3093. Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
  3094. unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
  3095. setDebugLocFromInst(Builder, ReducedPartRdx);
  3096. for (unsigned Part = 1; Part < UF; ++Part) {
  3097. Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3098. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  3099. // Floating point operations had to be 'fast' to enable the reduction.
  3100. ReducedPartRdx = addFastMathFlag(
  3101. Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
  3102. ReducedPartRdx, "bin.rdx"),
  3103. RdxDesc.getFastMathFlags());
  3104. else
  3105. ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
  3106. RdxPart);
  3107. }
  3108. if (VF > 1) {
  3109. bool NoNaN = Legal->hasFunNoNaNAttr();
  3110. ReducedPartRdx =
  3111. createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
  3112. // If the reduction can be performed in a smaller type, we need to extend
  3113. // the reduction to the wider type before we branch to the original loop.
  3114. if (Phi->getType() != RdxDesc.getRecurrenceType())
  3115. ReducedPartRdx =
  3116. RdxDesc.isSigned()
  3117. ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
  3118. : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
  3119. }
  3120. // Create a phi node that merges control-flow from the backedge-taken check
  3121. // block and the middle block.
  3122. PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
  3123. LoopScalarPreHeader->getTerminator());
  3124. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  3125. BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
  3126. BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3127. // Now, we need to fix the users of the reduction variable
  3128. // inside and outside of the scalar remainder loop.
  3129. // We know that the loop is in LCSSA form. We need to update the
  3130. // PHI nodes in the exit blocks.
  3131. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3132. // All PHINodes need to have a single entry edge, or two if
  3133. // we already fixed them.
  3134. assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
  3135. // We found a reduction value exit-PHI. Update it with the
  3136. // incoming bypass edge.
  3137. if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
  3138. LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3139. } // end of the LCSSA phi scan.
  3140. // Fix the scalar loop reduction variable with the incoming reduction sum
  3141. // from the vector body and from the backedge value.
  3142. int IncomingEdgeBlockIdx =
  3143. Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
  3144. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  3145. // Pick the other block.
  3146. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  3147. Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
  3148. Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
  3149. }
  3150. void InnerLoopVectorizer::fixLCSSAPHIs() {
  3151. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3152. if (LCSSAPhi.getNumIncomingValues() == 1) {
  3153. auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
  3154. // Non-instruction incoming values will have only one value.
  3155. unsigned LastLane = 0;
  3156. if (isa<Instruction>(IncomingValue))
  3157. LastLane = Cost->isUniformAfterVectorization(
  3158. cast<Instruction>(IncomingValue), VF)
  3159. ? 0
  3160. : VF - 1;
  3161. // Can be a loop invariant incoming value or the last scalar value to be
  3162. // extracted from the vectorized loop.
  3163. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3164. Value *lastIncomingValue =
  3165. getOrCreateScalarValue(IncomingValue, { UF - 1, LastLane });
  3166. LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
  3167. }
  3168. }
  3169. }
  3170. void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
  3171. // The basic block and loop containing the predicated instruction.
  3172. auto *PredBB = PredInst->getParent();
  3173. auto *VectorLoop = LI->getLoopFor(PredBB);
  3174. // Initialize a worklist with the operands of the predicated instruction.
  3175. SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
  3176. // Holds instructions that we need to analyze again. An instruction may be
  3177. // reanalyzed if we don't yet know if we can sink it or not.
  3178. SmallVector<Instruction *, 8> InstsToReanalyze;
  3179. // Returns true if a given use occurs in the predicated block. Phi nodes use
  3180. // their operands in their corresponding predecessor blocks.
  3181. auto isBlockOfUsePredicated = [&](Use &U) -> bool {
  3182. auto *I = cast<Instruction>(U.getUser());
  3183. BasicBlock *BB = I->getParent();
  3184. if (auto *Phi = dyn_cast<PHINode>(I))
  3185. BB = Phi->getIncomingBlock(
  3186. PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
  3187. return BB == PredBB;
  3188. };
  3189. // Iteratively sink the scalarized operands of the predicated instruction
  3190. // into the block we created for it. When an instruction is sunk, it's
  3191. // operands are then added to the worklist. The algorithm ends after one pass
  3192. // through the worklist doesn't sink a single instruction.
  3193. bool Changed;
  3194. do {
  3195. // Add the instructions that need to be reanalyzed to the worklist, and
  3196. // reset the changed indicator.
  3197. Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
  3198. InstsToReanalyze.clear();
  3199. Changed = false;
  3200. while (!Worklist.empty()) {
  3201. auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
  3202. // We can't sink an instruction if it is a phi node, is already in the
  3203. // predicated block, is not in the loop, or may have side effects.
  3204. if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
  3205. !VectorLoop->contains(I) || I->mayHaveSideEffects())
  3206. continue;
  3207. // It's legal to sink the instruction if all its uses occur in the
  3208. // predicated block. Otherwise, there's nothing to do yet, and we may
  3209. // need to reanalyze the instruction.
  3210. if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
  3211. InstsToReanalyze.push_back(I);
  3212. continue;
  3213. }
  3214. // Move the instruction to the beginning of the predicated block, and add
  3215. // it's operands to the worklist.
  3216. I->moveBefore(&*PredBB->getFirstInsertionPt());
  3217. Worklist.insert(I->op_begin(), I->op_end());
  3218. // The sinking may have enabled other instructions to be sunk, so we will
  3219. // need to iterate.
  3220. Changed = true;
  3221. }
  3222. } while (Changed);
  3223. }
  3224. void InnerLoopVectorizer::fixNonInductionPHIs() {
  3225. for (PHINode *OrigPhi : OrigPHIsToFix) {
  3226. PHINode *NewPhi =
  3227. cast<PHINode>(VectorLoopValueMap.getVectorValue(OrigPhi, 0));
  3228. unsigned NumIncomingValues = OrigPhi->getNumIncomingValues();
  3229. SmallVector<BasicBlock *, 2> ScalarBBPredecessors(
  3230. predecessors(OrigPhi->getParent()));
  3231. SmallVector<BasicBlock *, 2> VectorBBPredecessors(
  3232. predecessors(NewPhi->getParent()));
  3233. assert(ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&
  3234. "Scalar and Vector BB should have the same number of predecessors");
  3235. // The insertion point in Builder may be invalidated by the time we get
  3236. // here. Force the Builder insertion point to something valid so that we do
  3237. // not run into issues during insertion point restore in
  3238. // getOrCreateVectorValue calls below.
  3239. Builder.SetInsertPoint(NewPhi);
  3240. // The predecessor order is preserved and we can rely on mapping between
  3241. // scalar and vector block predecessors.
  3242. for (unsigned i = 0; i < NumIncomingValues; ++i) {
  3243. BasicBlock *NewPredBB = VectorBBPredecessors[i];
  3244. // When looking up the new scalar/vector values to fix up, use incoming
  3245. // values from original phi.
  3246. Value *ScIncV =
  3247. OrigPhi->getIncomingValueForBlock(ScalarBBPredecessors[i]);
  3248. // Scalar incoming value may need a broadcast
  3249. Value *NewIncV = getOrCreateVectorValue(ScIncV, 0);
  3250. NewPhi->addIncoming(NewIncV, NewPredBB);
  3251. }
  3252. }
  3253. }
  3254. void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
  3255. unsigned VF) {
  3256. PHINode *P = cast<PHINode>(PN);
  3257. if (EnableVPlanNativePath) {
  3258. // Currently we enter here in the VPlan-native path for non-induction
  3259. // PHIs where all control flow is uniform. We simply widen these PHIs.
  3260. // Create a vector phi with no operands - the vector phi operands will be
  3261. // set at the end of vector code generation.
  3262. Type *VecTy =
  3263. (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
  3264. Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
  3265. VectorLoopValueMap.setVectorValue(P, 0, VecPhi);
  3266. OrigPHIsToFix.push_back(P);
  3267. return;
  3268. }
  3269. assert(PN->getParent() == OrigLoop->getHeader() &&
  3270. "Non-header phis should have been handled elsewhere");
  3271. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3272. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  3273. // stage #1: We create a new vector PHI node with no incoming edges. We'll use
  3274. // this value when we vectorize all of the instructions that use the PHI.
  3275. if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
  3276. for (unsigned Part = 0; Part < UF; ++Part) {
  3277. // This is phase one of vectorizing PHIs.
  3278. Type *VecTy =
  3279. (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
  3280. Value *EntryPart = PHINode::Create(
  3281. VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
  3282. VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
  3283. }
  3284. return;
  3285. }
  3286. setDebugLocFromInst(Builder, P);
  3287. // This PHINode must be an induction variable.
  3288. // Make sure that we know about it.
  3289. assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
  3290. InductionDescriptor II = Legal->getInductionVars()->lookup(P);
  3291. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  3292. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  3293. // which can be found from the original scalar operations.
  3294. switch (II.getKind()) {
  3295. case InductionDescriptor::IK_NoInduction:
  3296. llvm_unreachable("Unknown induction");
  3297. case InductionDescriptor::IK_IntInduction:
  3298. case InductionDescriptor::IK_FpInduction:
  3299. llvm_unreachable("Integer/fp induction is handled elsewhere.");
  3300. case InductionDescriptor::IK_PtrInduction: {
  3301. // Handle the pointer induction variable case.
  3302. assert(P->getType()->isPointerTy() && "Unexpected type.");
  3303. // This is the normalized GEP that starts counting at zero.
  3304. Value *PtrInd = Induction;
  3305. PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
  3306. // Determine the number of scalars we need to generate for each unroll
  3307. // iteration. If the instruction is uniform, we only need to generate the
  3308. // first lane. Otherwise, we generate all VF values.
  3309. unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
  3310. // These are the scalar results. Notice that we don't generate vector GEPs
  3311. // because scalar GEPs result in better code.
  3312. for (unsigned Part = 0; Part < UF; ++Part) {
  3313. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  3314. Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
  3315. Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
  3316. Value *SclrGep =
  3317. emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
  3318. SclrGep->setName("next.gep");
  3319. VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
  3320. }
  3321. }
  3322. return;
  3323. }
  3324. }
  3325. }
  3326. /// A helper function for checking whether an integer division-related
  3327. /// instruction may divide by zero (in which case it must be predicated if
  3328. /// executed conditionally in the scalar code).
  3329. /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
  3330. /// Non-zero divisors that are non compile-time constants will not be
  3331. /// converted into multiplication, so we will still end up scalarizing
  3332. /// the division, but can do so w/o predication.
  3333. static bool mayDivideByZero(Instruction &I) {
  3334. assert((I.getOpcode() == Instruction::UDiv ||
  3335. I.getOpcode() == Instruction::SDiv ||
  3336. I.getOpcode() == Instruction::URem ||
  3337. I.getOpcode() == Instruction::SRem) &&
  3338. "Unexpected instruction");
  3339. Value *Divisor = I.getOperand(1);
  3340. auto *CInt = dyn_cast<ConstantInt>(Divisor);
  3341. return !CInt || CInt->isZero();
  3342. }
  3343. void InnerLoopVectorizer::widenInstruction(Instruction &I) {
  3344. switch (I.getOpcode()) {
  3345. case Instruction::Br:
  3346. case Instruction::PHI:
  3347. llvm_unreachable("This instruction is handled by a different recipe.");
  3348. case Instruction::GetElementPtr: {
  3349. // Construct a vector GEP by widening the operands of the scalar GEP as
  3350. // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
  3351. // results in a vector of pointers when at least one operand of the GEP
  3352. // is vector-typed. Thus, to keep the representation compact, we only use
  3353. // vector-typed operands for loop-varying values.
  3354. auto *GEP = cast<GetElementPtrInst>(&I);
  3355. if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
  3356. // If we are vectorizing, but the GEP has only loop-invariant operands,
  3357. // the GEP we build (by only using vector-typed operands for
  3358. // loop-varying values) would be a scalar pointer. Thus, to ensure we
  3359. // produce a vector of pointers, we need to either arbitrarily pick an
  3360. // operand to broadcast, or broadcast a clone of the original GEP.
  3361. // Here, we broadcast a clone of the original.
  3362. //
  3363. // TODO: If at some point we decide to scalarize instructions having
  3364. // loop-invariant operands, this special case will no longer be
  3365. // required. We would add the scalarization decision to
  3366. // collectLoopScalars() and teach getVectorValue() to broadcast
  3367. // the lane-zero scalar value.
  3368. auto *Clone = Builder.Insert(GEP->clone());
  3369. for (unsigned Part = 0; Part < UF; ++Part) {
  3370. Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
  3371. VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
  3372. addMetadata(EntryPart, GEP);
  3373. }
  3374. } else {
  3375. // If the GEP has at least one loop-varying operand, we are sure to
  3376. // produce a vector of pointers. But if we are only unrolling, we want
  3377. // to produce a scalar GEP for each unroll part. Thus, the GEP we
  3378. // produce with the code below will be scalar (if VF == 1) or vector
  3379. // (otherwise). Note that for the unroll-only case, we still maintain
  3380. // values in the vector mapping with initVector, as we do for other
  3381. // instructions.
  3382. for (unsigned Part = 0; Part < UF; ++Part) {
  3383. // The pointer operand of the new GEP. If it's loop-invariant, we
  3384. // won't broadcast it.
  3385. auto *Ptr =
  3386. OrigLoop->isLoopInvariant(GEP->getPointerOperand())
  3387. ? GEP->getPointerOperand()
  3388. : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
  3389. // Collect all the indices for the new GEP. If any index is
  3390. // loop-invariant, we won't broadcast it.
  3391. SmallVector<Value *, 4> Indices;
  3392. for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
  3393. if (OrigLoop->isLoopInvariant(U.get()))
  3394. Indices.push_back(U.get());
  3395. else
  3396. Indices.push_back(getOrCreateVectorValue(U.get(), Part));
  3397. }
  3398. // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
  3399. // but it should be a vector, otherwise.
  3400. auto *NewGEP =
  3401. GEP->isInBounds()
  3402. ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
  3403. Indices)
  3404. : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
  3405. assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
  3406. "NewGEP is not a pointer vector");
  3407. VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
  3408. addMetadata(NewGEP, GEP);
  3409. }
  3410. }
  3411. break;
  3412. }
  3413. case Instruction::UDiv:
  3414. case Instruction::SDiv:
  3415. case Instruction::SRem:
  3416. case Instruction::URem:
  3417. case Instruction::Add:
  3418. case Instruction::FAdd:
  3419. case Instruction::Sub:
  3420. case Instruction::FSub:
  3421. case Instruction::Mul:
  3422. case Instruction::FMul:
  3423. case Instruction::FDiv:
  3424. case Instruction::FRem:
  3425. case Instruction::Shl:
  3426. case Instruction::LShr:
  3427. case Instruction::AShr:
  3428. case Instruction::And:
  3429. case Instruction::Or:
  3430. case Instruction::Xor: {
  3431. // Just widen binops.
  3432. auto *BinOp = cast<BinaryOperator>(&I);
  3433. setDebugLocFromInst(Builder, BinOp);
  3434. for (unsigned Part = 0; Part < UF; ++Part) {
  3435. Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
  3436. Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
  3437. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
  3438. if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
  3439. VecOp->copyIRFlags(BinOp);
  3440. // Use this vector value for all users of the original instruction.
  3441. VectorLoopValueMap.setVectorValue(&I, Part, V);
  3442. addMetadata(V, BinOp);
  3443. }
  3444. break;
  3445. }
  3446. case Instruction::Select: {
  3447. // Widen selects.
  3448. // If the selector is loop invariant we can create a select
  3449. // instruction with a scalar condition. Otherwise, use vector-select.
  3450. auto *SE = PSE.getSE();
  3451. bool InvariantCond =
  3452. SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
  3453. setDebugLocFromInst(Builder, &I);
  3454. // The condition can be loop invariant but still defined inside the
  3455. // loop. This means that we can't just use the original 'cond' value.
  3456. // We have to take the 'vectorized' value and pick the first lane.
  3457. // Instcombine will make this a no-op.
  3458. auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
  3459. for (unsigned Part = 0; Part < UF; ++Part) {
  3460. Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
  3461. Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
  3462. Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
  3463. Value *Sel =
  3464. Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
  3465. VectorLoopValueMap.setVectorValue(&I, Part, Sel);
  3466. addMetadata(Sel, &I);
  3467. }
  3468. break;
  3469. }
  3470. case Instruction::ICmp:
  3471. case Instruction::FCmp: {
  3472. // Widen compares. Generate vector compares.
  3473. bool FCmp = (I.getOpcode() == Instruction::FCmp);
  3474. auto *Cmp = dyn_cast<CmpInst>(&I);
  3475. setDebugLocFromInst(Builder, Cmp);
  3476. for (unsigned Part = 0; Part < UF; ++Part) {
  3477. Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
  3478. Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
  3479. Value *C = nullptr;
  3480. if (FCmp) {
  3481. // Propagate fast math flags.
  3482. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  3483. Builder.setFastMathFlags(Cmp->getFastMathFlags());
  3484. C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
  3485. } else {
  3486. C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
  3487. }
  3488. VectorLoopValueMap.setVectorValue(&I, Part, C);
  3489. addMetadata(C, &I);
  3490. }
  3491. break;
  3492. }
  3493. case Instruction::ZExt:
  3494. case Instruction::SExt:
  3495. case Instruction::FPToUI:
  3496. case Instruction::FPToSI:
  3497. case Instruction::FPExt:
  3498. case Instruction::PtrToInt:
  3499. case Instruction::IntToPtr:
  3500. case Instruction::SIToFP:
  3501. case Instruction::UIToFP:
  3502. case Instruction::Trunc:
  3503. case Instruction::FPTrunc:
  3504. case Instruction::BitCast: {
  3505. auto *CI = dyn_cast<CastInst>(&I);
  3506. setDebugLocFromInst(Builder, CI);
  3507. /// Vectorize casts.
  3508. Type *DestTy =
  3509. (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
  3510. for (unsigned Part = 0; Part < UF; ++Part) {
  3511. Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
  3512. Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
  3513. VectorLoopValueMap.setVectorValue(&I, Part, Cast);
  3514. addMetadata(Cast, &I);
  3515. }
  3516. break;
  3517. }
  3518. case Instruction::Call: {
  3519. // Ignore dbg intrinsics.
  3520. if (isa<DbgInfoIntrinsic>(I))
  3521. break;
  3522. setDebugLocFromInst(Builder, &I);
  3523. Module *M = I.getParent()->getParent()->getParent();
  3524. auto *CI = cast<CallInst>(&I);
  3525. StringRef FnName = CI->getCalledFunction()->getName();
  3526. Function *F = CI->getCalledFunction();
  3527. Type *RetTy = ToVectorTy(CI->getType(), VF);
  3528. SmallVector<Type *, 4> Tys;
  3529. for (Value *ArgOperand : CI->arg_operands())
  3530. Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
  3531. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3532. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  3533. // version of the instruction.
  3534. // Is it beneficial to perform intrinsic call compared to lib call?
  3535. bool NeedToScalarize;
  3536. unsigned CallCost = Cost->getVectorCallCost(CI, VF, NeedToScalarize);
  3537. bool UseVectorIntrinsic =
  3538. ID && Cost->getVectorIntrinsicCost(CI, VF) <= CallCost;
  3539. assert((UseVectorIntrinsic || !NeedToScalarize) &&
  3540. "Instruction should be scalarized elsewhere.");
  3541. for (unsigned Part = 0; Part < UF; ++Part) {
  3542. SmallVector<Value *, 4> Args;
  3543. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  3544. Value *Arg = CI->getArgOperand(i);
  3545. // Some intrinsics have a scalar argument - don't replace it with a
  3546. // vector.
  3547. if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
  3548. Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
  3549. Args.push_back(Arg);
  3550. }
  3551. Function *VectorF;
  3552. if (UseVectorIntrinsic) {
  3553. // Use vector version of the intrinsic.
  3554. Type *TysForDecl[] = {CI->getType()};
  3555. if (VF > 1)
  3556. TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  3557. VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
  3558. } else {
  3559. // Use vector version of the library call.
  3560. StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
  3561. assert(!VFnName.empty() && "Vector function name is empty.");
  3562. VectorF = M->getFunction(VFnName);
  3563. if (!VectorF) {
  3564. // Generate a declaration
  3565. FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
  3566. VectorF =
  3567. Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
  3568. VectorF->copyAttributesFrom(F);
  3569. }
  3570. }
  3571. assert(VectorF && "Can't create vector function.");
  3572. SmallVector<OperandBundleDef, 1> OpBundles;
  3573. CI->getOperandBundlesAsDefs(OpBundles);
  3574. CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
  3575. if (isa<FPMathOperator>(V))
  3576. V->copyFastMathFlags(CI);
  3577. VectorLoopValueMap.setVectorValue(&I, Part, V);
  3578. addMetadata(V, &I);
  3579. }
  3580. break;
  3581. }
  3582. default:
  3583. // This instruction is not vectorized by simple widening.
  3584. LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
  3585. llvm_unreachable("Unhandled instruction!");
  3586. } // end of switch.
  3587. }
  3588. void InnerLoopVectorizer::updateAnalysis() {
  3589. // Forget the original basic block.
  3590. PSE.getSE()->forgetLoop(OrigLoop);
  3591. // DT is not kept up-to-date for outer loop vectorization
  3592. if (EnableVPlanNativePath)
  3593. return;
  3594. // Update the dominator tree information.
  3595. assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
  3596. "Entry does not dominate exit.");
  3597. DT->addNewBlock(LoopMiddleBlock,
  3598. LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3599. DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
  3600. DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
  3601. DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
  3602. assert(DT->verify(DominatorTree::VerificationLevel::Fast));
  3603. }
  3604. void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
  3605. // We should not collect Scalars more than once per VF. Right now, this
  3606. // function is called from collectUniformsAndScalars(), which already does
  3607. // this check. Collecting Scalars for VF=1 does not make any sense.
  3608. assert(VF >= 2 && Scalars.find(VF) == Scalars.end() &&
  3609. "This function should not be visited twice for the same VF");
  3610. SmallSetVector<Instruction *, 8> Worklist;
  3611. // These sets are used to seed the analysis with pointers used by memory
  3612. // accesses that will remain scalar.
  3613. SmallSetVector<Instruction *, 8> ScalarPtrs;
  3614. SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
  3615. // A helper that returns true if the use of Ptr by MemAccess will be scalar.
  3616. // The pointer operands of loads and stores will be scalar as long as the
  3617. // memory access is not a gather or scatter operation. The value operand of a
  3618. // store will remain scalar if the store is scalarized.
  3619. auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
  3620. InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
  3621. assert(WideningDecision != CM_Unknown &&
  3622. "Widening decision should be ready at this moment");
  3623. if (auto *Store = dyn_cast<StoreInst>(MemAccess))
  3624. if (Ptr == Store->getValueOperand())
  3625. return WideningDecision == CM_Scalarize;
  3626. assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
  3627. "Ptr is neither a value or pointer operand");
  3628. return WideningDecision != CM_GatherScatter;
  3629. };
  3630. // A helper that returns true if the given value is a bitcast or
  3631. // getelementptr instruction contained in the loop.
  3632. auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
  3633. return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
  3634. isa<GetElementPtrInst>(V)) &&
  3635. !TheLoop->isLoopInvariant(V);
  3636. };
  3637. // A helper that evaluates a memory access's use of a pointer. If the use
  3638. // will be a scalar use, and the pointer is only used by memory accesses, we
  3639. // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
  3640. // PossibleNonScalarPtrs.
  3641. auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
  3642. // We only care about bitcast and getelementptr instructions contained in
  3643. // the loop.
  3644. if (!isLoopVaryingBitCastOrGEP(Ptr))
  3645. return;
  3646. // If the pointer has already been identified as scalar (e.g., if it was
  3647. // also identified as uniform), there's nothing to do.
  3648. auto *I = cast<Instruction>(Ptr);
  3649. if (Worklist.count(I))
  3650. return;
  3651. // If the use of the pointer will be a scalar use, and all users of the
  3652. // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
  3653. // place the pointer in PossibleNonScalarPtrs.
  3654. if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
  3655. return isa<LoadInst>(U) || isa<StoreInst>(U);
  3656. }))
  3657. ScalarPtrs.insert(I);
  3658. else
  3659. PossibleNonScalarPtrs.insert(I);
  3660. };
  3661. // We seed the scalars analysis with three classes of instructions: (1)
  3662. // instructions marked uniform-after-vectorization, (2) bitcast and
  3663. // getelementptr instructions used by memory accesses requiring a scalar use,
  3664. // and (3) pointer induction variables and their update instructions (we
  3665. // currently only scalarize these).
  3666. //
  3667. // (1) Add to the worklist all instructions that have been identified as
  3668. // uniform-after-vectorization.
  3669. Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
  3670. // (2) Add to the worklist all bitcast and getelementptr instructions used by
  3671. // memory accesses requiring a scalar use. The pointer operands of loads and
  3672. // stores will be scalar as long as the memory accesses is not a gather or
  3673. // scatter operation. The value operand of a store will remain scalar if the
  3674. // store is scalarized.
  3675. for (auto *BB : TheLoop->blocks())
  3676. for (auto &I : *BB) {
  3677. if (auto *Load = dyn_cast<LoadInst>(&I)) {
  3678. evaluatePtrUse(Load, Load->getPointerOperand());
  3679. } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
  3680. evaluatePtrUse(Store, Store->getPointerOperand());
  3681. evaluatePtrUse(Store, Store->getValueOperand());
  3682. }
  3683. }
  3684. for (auto *I : ScalarPtrs)
  3685. if (PossibleNonScalarPtrs.find(I) == PossibleNonScalarPtrs.end()) {
  3686. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
  3687. Worklist.insert(I);
  3688. }
  3689. // (3) Add to the worklist all pointer induction variables and their update
  3690. // instructions.
  3691. //
  3692. // TODO: Once we are able to vectorize pointer induction variables we should
  3693. // no longer insert them into the worklist here.
  3694. auto *Latch = TheLoop->getLoopLatch();
  3695. for (auto &Induction : *Legal->getInductionVars()) {
  3696. auto *Ind = Induction.first;
  3697. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3698. if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
  3699. continue;
  3700. Worklist.insert(Ind);
  3701. Worklist.insert(IndUpdate);
  3702. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  3703. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  3704. << "\n");
  3705. }
  3706. // Insert the forced scalars.
  3707. // FIXME: Currently widenPHIInstruction() often creates a dead vector
  3708. // induction variable when the PHI user is scalarized.
  3709. auto ForcedScalar = ForcedScalars.find(VF);
  3710. if (ForcedScalar != ForcedScalars.end())
  3711. for (auto *I : ForcedScalar->second)
  3712. Worklist.insert(I);
  3713. // Expand the worklist by looking through any bitcasts and getelementptr
  3714. // instructions we've already identified as scalar. This is similar to the
  3715. // expansion step in collectLoopUniforms(); however, here we're only
  3716. // expanding to include additional bitcasts and getelementptr instructions.
  3717. unsigned Idx = 0;
  3718. while (Idx != Worklist.size()) {
  3719. Instruction *Dst = Worklist[Idx++];
  3720. if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
  3721. continue;
  3722. auto *Src = cast<Instruction>(Dst->getOperand(0));
  3723. if (llvm::all_of(Src->users(), [&](User *U) -> bool {
  3724. auto *J = cast<Instruction>(U);
  3725. return !TheLoop->contains(J) || Worklist.count(J) ||
  3726. ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
  3727. isScalarUse(J, Src));
  3728. })) {
  3729. Worklist.insert(Src);
  3730. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
  3731. }
  3732. }
  3733. // An induction variable will remain scalar if all users of the induction
  3734. // variable and induction variable update remain scalar.
  3735. for (auto &Induction : *Legal->getInductionVars()) {
  3736. auto *Ind = Induction.first;
  3737. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3738. // We already considered pointer induction variables, so there's no reason
  3739. // to look at their users again.
  3740. //
  3741. // TODO: Once we are able to vectorize pointer induction variables we
  3742. // should no longer skip over them here.
  3743. if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
  3744. continue;
  3745. // Determine if all users of the induction variable are scalar after
  3746. // vectorization.
  3747. auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  3748. auto *I = cast<Instruction>(U);
  3749. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
  3750. });
  3751. if (!ScalarInd)
  3752. continue;
  3753. // Determine if all users of the induction variable update instruction are
  3754. // scalar after vectorization.
  3755. auto ScalarIndUpdate =
  3756. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  3757. auto *I = cast<Instruction>(U);
  3758. return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
  3759. });
  3760. if (!ScalarIndUpdate)
  3761. continue;
  3762. // The induction variable and its update instruction will remain scalar.
  3763. Worklist.insert(Ind);
  3764. Worklist.insert(IndUpdate);
  3765. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  3766. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  3767. << "\n");
  3768. }
  3769. Scalars[VF].insert(Worklist.begin(), Worklist.end());
  3770. }
  3771. bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I, unsigned VF) {
  3772. if (!blockNeedsPredication(I->getParent()))
  3773. return false;
  3774. switch(I->getOpcode()) {
  3775. default:
  3776. break;
  3777. case Instruction::Load:
  3778. case Instruction::Store: {
  3779. if (!Legal->isMaskRequired(I))
  3780. return false;
  3781. auto *Ptr = getLoadStorePointerOperand(I);
  3782. auto *Ty = getMemInstValueType(I);
  3783. // We have already decided how to vectorize this instruction, get that
  3784. // result.
  3785. if (VF > 1) {
  3786. InstWidening WideningDecision = getWideningDecision(I, VF);
  3787. assert(WideningDecision != CM_Unknown &&
  3788. "Widening decision should be ready at this moment");
  3789. return WideningDecision == CM_Scalarize;
  3790. }
  3791. return isa<LoadInst>(I) ?
  3792. !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty))
  3793. : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
  3794. }
  3795. case Instruction::UDiv:
  3796. case Instruction::SDiv:
  3797. case Instruction::SRem:
  3798. case Instruction::URem:
  3799. return mayDivideByZero(*I);
  3800. }
  3801. return false;
  3802. }
  3803. bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(Instruction *I,
  3804. unsigned VF) {
  3805. assert(isAccessInterleaved(I) && "Expecting interleaved access.");
  3806. assert(getWideningDecision(I, VF) == CM_Unknown &&
  3807. "Decision should not be set yet.");
  3808. auto *Group = getInterleavedAccessGroup(I);
  3809. assert(Group && "Must have a group.");
  3810. // Check if masking is required.
  3811. // A Group may need masking for one of two reasons: it resides in a block that
  3812. // needs predication, or it was decided to use masking to deal with gaps.
  3813. bool PredicatedAccessRequiresMasking =
  3814. Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
  3815. bool AccessWithGapsRequiresMasking =
  3816. Group->requiresScalarEpilogue() && !IsScalarEpilogueAllowed;
  3817. if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
  3818. return true;
  3819. // If masked interleaving is required, we expect that the user/target had
  3820. // enabled it, because otherwise it either wouldn't have been created or
  3821. // it should have been invalidated by the CostModel.
  3822. assert(useMaskedInterleavedAccesses(TTI) &&
  3823. "Masked interleave-groups for predicated accesses are not enabled.");
  3824. auto *Ty = getMemInstValueType(I);
  3825. return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty)
  3826. : TTI.isLegalMaskedStore(Ty);
  3827. }
  3828. bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I,
  3829. unsigned VF) {
  3830. // Get and ensure we have a valid memory instruction.
  3831. LoadInst *LI = dyn_cast<LoadInst>(I);
  3832. StoreInst *SI = dyn_cast<StoreInst>(I);
  3833. assert((LI || SI) && "Invalid memory instruction");
  3834. auto *Ptr = getLoadStorePointerOperand(I);
  3835. // In order to be widened, the pointer should be consecutive, first of all.
  3836. if (!Legal->isConsecutivePtr(Ptr))
  3837. return false;
  3838. // If the instruction is a store located in a predicated block, it will be
  3839. // scalarized.
  3840. if (isScalarWithPredication(I))
  3841. return false;
  3842. // If the instruction's allocated size doesn't equal it's type size, it
  3843. // requires padding and will be scalarized.
  3844. auto &DL = I->getModule()->getDataLayout();
  3845. auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  3846. if (hasIrregularType(ScalarTy, DL, VF))
  3847. return false;
  3848. return true;
  3849. }
  3850. void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
  3851. // We should not collect Uniforms more than once per VF. Right now,
  3852. // this function is called from collectUniformsAndScalars(), which
  3853. // already does this check. Collecting Uniforms for VF=1 does not make any
  3854. // sense.
  3855. assert(VF >= 2 && Uniforms.find(VF) == Uniforms.end() &&
  3856. "This function should not be visited twice for the same VF");
  3857. // Visit the list of Uniforms. If we'll not find any uniform value, we'll
  3858. // not analyze again. Uniforms.count(VF) will return 1.
  3859. Uniforms[VF].clear();
  3860. // We now know that the loop is vectorizable!
  3861. // Collect instructions inside the loop that will remain uniform after
  3862. // vectorization.
  3863. // Global values, params and instructions outside of current loop are out of
  3864. // scope.
  3865. auto isOutOfScope = [&](Value *V) -> bool {
  3866. Instruction *I = dyn_cast<Instruction>(V);
  3867. return (!I || !TheLoop->contains(I));
  3868. };
  3869. SetVector<Instruction *> Worklist;
  3870. BasicBlock *Latch = TheLoop->getLoopLatch();
  3871. // Start with the conditional branch. If the branch condition is an
  3872. // instruction contained in the loop that is only used by the branch, it is
  3873. // uniform.
  3874. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  3875. if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
  3876. Worklist.insert(Cmp);
  3877. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
  3878. }
  3879. // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
  3880. // are pointers that are treated like consecutive pointers during
  3881. // vectorization. The pointer operands of interleaved accesses are an
  3882. // example.
  3883. SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
  3884. // Holds pointer operands of instructions that are possibly non-uniform.
  3885. SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
  3886. auto isUniformDecision = [&](Instruction *I, unsigned VF) {
  3887. InstWidening WideningDecision = getWideningDecision(I, VF);
  3888. assert(WideningDecision != CM_Unknown &&
  3889. "Widening decision should be ready at this moment");
  3890. return (WideningDecision == CM_Widen ||
  3891. WideningDecision == CM_Widen_Reverse ||
  3892. WideningDecision == CM_Interleave);
  3893. };
  3894. // Iterate over the instructions in the loop, and collect all
  3895. // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
  3896. // that a consecutive-like pointer operand will be scalarized, we collect it
  3897. // in PossibleNonUniformPtrs instead. We use two sets here because a single
  3898. // getelementptr instruction can be used by both vectorized and scalarized
  3899. // memory instructions. For example, if a loop loads and stores from the same
  3900. // location, but the store is conditional, the store will be scalarized, and
  3901. // the getelementptr won't remain uniform.
  3902. for (auto *BB : TheLoop->blocks())
  3903. for (auto &I : *BB) {
  3904. // If there's no pointer operand, there's nothing to do.
  3905. auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  3906. if (!Ptr)
  3907. continue;
  3908. // True if all users of Ptr are memory accesses that have Ptr as their
  3909. // pointer operand.
  3910. auto UsersAreMemAccesses =
  3911. llvm::all_of(Ptr->users(), [&](User *U) -> bool {
  3912. return getLoadStorePointerOperand(U) == Ptr;
  3913. });
  3914. // Ensure the memory instruction will not be scalarized or used by
  3915. // gather/scatter, making its pointer operand non-uniform. If the pointer
  3916. // operand is used by any instruction other than a memory access, we
  3917. // conservatively assume the pointer operand may be non-uniform.
  3918. if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
  3919. PossibleNonUniformPtrs.insert(Ptr);
  3920. // If the memory instruction will be vectorized and its pointer operand
  3921. // is consecutive-like, or interleaving - the pointer operand should
  3922. // remain uniform.
  3923. else
  3924. ConsecutiveLikePtrs.insert(Ptr);
  3925. }
  3926. // Add to the Worklist all consecutive and consecutive-like pointers that
  3927. // aren't also identified as possibly non-uniform.
  3928. for (auto *V : ConsecutiveLikePtrs)
  3929. if (PossibleNonUniformPtrs.find(V) == PossibleNonUniformPtrs.end()) {
  3930. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
  3931. Worklist.insert(V);
  3932. }
  3933. // Expand Worklist in topological order: whenever a new instruction
  3934. // is added , its users should be already inside Worklist. It ensures
  3935. // a uniform instruction will only be used by uniform instructions.
  3936. unsigned idx = 0;
  3937. while (idx != Worklist.size()) {
  3938. Instruction *I = Worklist[idx++];
  3939. for (auto OV : I->operand_values()) {
  3940. // isOutOfScope operands cannot be uniform instructions.
  3941. if (isOutOfScope(OV))
  3942. continue;
  3943. // First order recurrence Phi's should typically be considered
  3944. // non-uniform.
  3945. auto *OP = dyn_cast<PHINode>(OV);
  3946. if (OP && Legal->isFirstOrderRecurrence(OP))
  3947. continue;
  3948. // If all the users of the operand are uniform, then add the
  3949. // operand into the uniform worklist.
  3950. auto *OI = cast<Instruction>(OV);
  3951. if (llvm::all_of(OI->users(), [&](User *U) -> bool {
  3952. auto *J = cast<Instruction>(U);
  3953. return Worklist.count(J) ||
  3954. (OI == getLoadStorePointerOperand(J) &&
  3955. isUniformDecision(J, VF));
  3956. })) {
  3957. Worklist.insert(OI);
  3958. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
  3959. }
  3960. }
  3961. }
  3962. // Returns true if Ptr is the pointer operand of a memory access instruction
  3963. // I, and I is known to not require scalarization.
  3964. auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
  3965. return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
  3966. };
  3967. // For an instruction to be added into Worklist above, all its users inside
  3968. // the loop should also be in Worklist. However, this condition cannot be
  3969. // true for phi nodes that form a cyclic dependence. We must process phi
  3970. // nodes separately. An induction variable will remain uniform if all users
  3971. // of the induction variable and induction variable update remain uniform.
  3972. // The code below handles both pointer and non-pointer induction variables.
  3973. for (auto &Induction : *Legal->getInductionVars()) {
  3974. auto *Ind = Induction.first;
  3975. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3976. // Determine if all users of the induction variable are uniform after
  3977. // vectorization.
  3978. auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  3979. auto *I = cast<Instruction>(U);
  3980. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
  3981. isVectorizedMemAccessUse(I, Ind);
  3982. });
  3983. if (!UniformInd)
  3984. continue;
  3985. // Determine if all users of the induction variable update instruction are
  3986. // uniform after vectorization.
  3987. auto UniformIndUpdate =
  3988. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  3989. auto *I = cast<Instruction>(U);
  3990. return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
  3991. isVectorizedMemAccessUse(I, IndUpdate);
  3992. });
  3993. if (!UniformIndUpdate)
  3994. continue;
  3995. // The induction variable and its update instruction will remain uniform.
  3996. Worklist.insert(Ind);
  3997. Worklist.insert(IndUpdate);
  3998. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
  3999. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate
  4000. << "\n");
  4001. }
  4002. Uniforms[VF].insert(Worklist.begin(), Worklist.end());
  4003. }
  4004. Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
  4005. if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
  4006. // TODO: It may by useful to do since it's still likely to be dynamically
  4007. // uniform if the target can skip.
  4008. LLVM_DEBUG(
  4009. dbgs() << "LV: Not inserting runtime ptr check for divergent target");
  4010. ORE->emit(
  4011. createMissedAnalysis("CantVersionLoopWithDivergentTarget")
  4012. << "runtime pointer checks needed. Not enabled for divergent target");
  4013. return None;
  4014. }
  4015. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4016. if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
  4017. return computeFeasibleMaxVF(OptForSize, TC);
  4018. if (Legal->getRuntimePointerChecking()->Need) {
  4019. ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
  4020. << "runtime pointer checks needed. Enable vectorization of this "
  4021. "loop with '#pragma clang loop vectorize(enable)' when "
  4022. "compiling with -Os/-Oz");
  4023. LLVM_DEBUG(
  4024. dbgs()
  4025. << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
  4026. return None;
  4027. }
  4028. if (!PSE.getUnionPredicate().getPredicates().empty()) {
  4029. ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
  4030. << "runtime SCEV checks needed. Enable vectorization of this "
  4031. "loop with '#pragma clang loop vectorize(enable)' when "
  4032. "compiling with -Os/-Oz");
  4033. LLVM_DEBUG(
  4034. dbgs()
  4035. << "LV: Aborting. Runtime SCEV check is required with -Os/-Oz.\n");
  4036. return None;
  4037. }
  4038. // FIXME: Avoid specializing for stride==1 instead of bailing out.
  4039. if (!Legal->getLAI()->getSymbolicStrides().empty()) {
  4040. ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
  4041. << "runtime stride == 1 checks needed. Enable vectorization of "
  4042. "this loop with '#pragma clang loop vectorize(enable)' when "
  4043. "compiling with -Os/-Oz");
  4044. LLVM_DEBUG(
  4045. dbgs()
  4046. << "LV: Aborting. Runtime stride check is required with -Os/-Oz.\n");
  4047. return None;
  4048. }
  4049. // If we optimize the program for size, avoid creating the tail loop.
  4050. LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4051. if (TC == 1) {
  4052. ORE->emit(createMissedAnalysis("SingleIterationLoop")
  4053. << "loop trip count is one, irrelevant for vectorization");
  4054. LLVM_DEBUG(dbgs() << "LV: Aborting, single iteration (non) loop.\n");
  4055. return None;
  4056. }
  4057. // Record that scalar epilogue is not allowed.
  4058. LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
  4059. IsScalarEpilogueAllowed = !OptForSize;
  4060. // We don't create an epilogue when optimizing for size.
  4061. // Invalidate interleave groups that require an epilogue if we can't mask
  4062. // the interleave-group.
  4063. if (!useMaskedInterleavedAccesses(TTI))
  4064. InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
  4065. unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
  4066. if (TC > 0 && TC % MaxVF == 0) {
  4067. LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
  4068. return MaxVF;
  4069. }
  4070. // If we don't know the precise trip count, or if the trip count that we
  4071. // found modulo the vectorization factor is not zero, try to fold the tail
  4072. // by masking.
  4073. // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
  4074. if (Legal->canFoldTailByMasking()) {
  4075. FoldTailByMasking = true;
  4076. return MaxVF;
  4077. }
  4078. if (TC == 0) {
  4079. ORE->emit(
  4080. createMissedAnalysis("UnknownLoopCountComplexCFG")
  4081. << "unable to calculate the loop count due to complex control flow");
  4082. return None;
  4083. }
  4084. ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
  4085. << "cannot optimize for size and vectorize at the same time. "
  4086. "Enable vectorization of this loop with '#pragma clang loop "
  4087. "vectorize(enable)' when compiling with -Os/-Oz");
  4088. return None;
  4089. }
  4090. unsigned
  4091. LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
  4092. unsigned ConstTripCount) {
  4093. MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
  4094. unsigned SmallestType, WidestType;
  4095. std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
  4096. unsigned WidestRegister = TTI.getRegisterBitWidth(true);
  4097. // Get the maximum safe dependence distance in bits computed by LAA.
  4098. // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
  4099. // the memory accesses that is most restrictive (involved in the smallest
  4100. // dependence distance).
  4101. unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
  4102. WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
  4103. unsigned MaxVectorSize = WidestRegister / WidestType;
  4104. LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
  4105. << " / " << WidestType << " bits.\n");
  4106. LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
  4107. << WidestRegister << " bits.\n");
  4108. assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"
  4109. " into one vector!");
  4110. if (MaxVectorSize == 0) {
  4111. LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
  4112. MaxVectorSize = 1;
  4113. return MaxVectorSize;
  4114. } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
  4115. isPowerOf2_32(ConstTripCount)) {
  4116. // We need to clamp the VF to be the ConstTripCount. There is no point in
  4117. // choosing a higher viable VF as done in the loop below.
  4118. LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
  4119. << ConstTripCount << "\n");
  4120. MaxVectorSize = ConstTripCount;
  4121. return MaxVectorSize;
  4122. }
  4123. unsigned MaxVF = MaxVectorSize;
  4124. if (TTI.shouldMaximizeVectorBandwidth(OptForSize) ||
  4125. (MaximizeBandwidth && !OptForSize)) {
  4126. // Collect all viable vectorization factors larger than the default MaxVF
  4127. // (i.e. MaxVectorSize).
  4128. SmallVector<unsigned, 8> VFs;
  4129. unsigned NewMaxVectorSize = WidestRegister / SmallestType;
  4130. for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
  4131. VFs.push_back(VS);
  4132. // For each VF calculate its register usage.
  4133. auto RUs = calculateRegisterUsage(VFs);
  4134. // Select the largest VF which doesn't require more registers than existing
  4135. // ones.
  4136. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
  4137. for (int i = RUs.size() - 1; i >= 0; --i) {
  4138. if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
  4139. MaxVF = VFs[i];
  4140. break;
  4141. }
  4142. }
  4143. if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
  4144. if (MaxVF < MinVF) {
  4145. LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
  4146. << ") with target's minimum: " << MinVF << '\n');
  4147. MaxVF = MinVF;
  4148. }
  4149. }
  4150. }
  4151. return MaxVF;
  4152. }
  4153. VectorizationFactor
  4154. LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
  4155. float Cost = expectedCost(1).first;
  4156. const float ScalarCost = Cost;
  4157. unsigned Width = 1;
  4158. LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
  4159. bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
  4160. if (ForceVectorization && MaxVF > 1) {
  4161. // Ignore scalar width, because the user explicitly wants vectorization.
  4162. // Initialize cost to max so that VF = 2 is, at least, chosen during cost
  4163. // evaluation.
  4164. Cost = std::numeric_limits<float>::max();
  4165. }
  4166. for (unsigned i = 2; i <= MaxVF; i *= 2) {
  4167. // Notice that the vector loop needs to be executed less times, so
  4168. // we need to divide the cost of the vector loops by the width of
  4169. // the vector elements.
  4170. VectorizationCostTy C = expectedCost(i);
  4171. float VectorCost = C.first / (float)i;
  4172. LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
  4173. << " costs: " << (int)VectorCost << ".\n");
  4174. if (!C.second && !ForceVectorization) {
  4175. LLVM_DEBUG(
  4176. dbgs() << "LV: Not considering vector loop of width " << i
  4177. << " because it will not generate any vector instructions.\n");
  4178. continue;
  4179. }
  4180. if (VectorCost < Cost) {
  4181. Cost = VectorCost;
  4182. Width = i;
  4183. }
  4184. }
  4185. if (!EnableCondStoresVectorization && NumPredStores) {
  4186. ORE->emit(createMissedAnalysis("ConditionalStore")
  4187. << "store that is conditionally executed prevents vectorization");
  4188. LLVM_DEBUG(
  4189. dbgs() << "LV: No vectorization. There are conditional stores.\n");
  4190. Width = 1;
  4191. Cost = ScalarCost;
  4192. }
  4193. LLVM_DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
  4194. << "LV: Vectorization seems to be not beneficial, "
  4195. << "but was forced by a user.\n");
  4196. LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
  4197. VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
  4198. return Factor;
  4199. }
  4200. std::pair<unsigned, unsigned>
  4201. LoopVectorizationCostModel::getSmallestAndWidestTypes() {
  4202. unsigned MinWidth = -1U;
  4203. unsigned MaxWidth = 8;
  4204. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4205. // For each block.
  4206. for (BasicBlock *BB : TheLoop->blocks()) {
  4207. // For each instruction in the loop.
  4208. for (Instruction &I : BB->instructionsWithoutDebug()) {
  4209. Type *T = I.getType();
  4210. // Skip ignored values.
  4211. if (ValuesToIgnore.find(&I) != ValuesToIgnore.end())
  4212. continue;
  4213. // Only examine Loads, Stores and PHINodes.
  4214. if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
  4215. continue;
  4216. // Examine PHI nodes that are reduction variables. Update the type to
  4217. // account for the recurrence type.
  4218. if (auto *PN = dyn_cast<PHINode>(&I)) {
  4219. if (!Legal->isReductionVariable(PN))
  4220. continue;
  4221. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
  4222. T = RdxDesc.getRecurrenceType();
  4223. }
  4224. // Examine the stored values.
  4225. if (auto *ST = dyn_cast<StoreInst>(&I))
  4226. T = ST->getValueOperand()->getType();
  4227. // Ignore loaded pointer types and stored pointer types that are not
  4228. // vectorizable.
  4229. //
  4230. // FIXME: The check here attempts to predict whether a load or store will
  4231. // be vectorized. We only know this for certain after a VF has
  4232. // been selected. Here, we assume that if an access can be
  4233. // vectorized, it will be. We should also look at extending this
  4234. // optimization to non-pointer types.
  4235. //
  4236. if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
  4237. !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
  4238. continue;
  4239. MinWidth = std::min(MinWidth,
  4240. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4241. MaxWidth = std::max(MaxWidth,
  4242. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4243. }
  4244. }
  4245. return {MinWidth, MaxWidth};
  4246. }
  4247. unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
  4248. unsigned VF,
  4249. unsigned LoopCost) {
  4250. // -- The interleave heuristics --
  4251. // We interleave the loop in order to expose ILP and reduce the loop overhead.
  4252. // There are many micro-architectural considerations that we can't predict
  4253. // at this level. For example, frontend pressure (on decode or fetch) due to
  4254. // code size, or the number and capabilities of the execution ports.
  4255. //
  4256. // We use the following heuristics to select the interleave count:
  4257. // 1. If the code has reductions, then we interleave to break the cross
  4258. // iteration dependency.
  4259. // 2. If the loop is really small, then we interleave to reduce the loop
  4260. // overhead.
  4261. // 3. We don't interleave if we think that we will spill registers to memory
  4262. // due to the increased register pressure.
  4263. // When we optimize for size, we don't interleave.
  4264. if (OptForSize)
  4265. return 1;
  4266. // We used the distance for the interleave count.
  4267. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4268. return 1;
  4269. // Do not interleave loops with a relatively small trip count.
  4270. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4271. if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
  4272. return 1;
  4273. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
  4274. LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
  4275. << " registers\n");
  4276. if (VF == 1) {
  4277. if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
  4278. TargetNumRegisters = ForceTargetNumScalarRegs;
  4279. } else {
  4280. if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
  4281. TargetNumRegisters = ForceTargetNumVectorRegs;
  4282. }
  4283. RegisterUsage R = calculateRegisterUsage({VF})[0];
  4284. // We divide by these constants so assume that we have at least one
  4285. // instruction that uses at least one register.
  4286. R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
  4287. // We calculate the interleave count using the following formula.
  4288. // Subtract the number of loop invariants from the number of available
  4289. // registers. These registers are used by all of the interleaved instances.
  4290. // Next, divide the remaining registers by the number of registers that is
  4291. // required by the loop, in order to estimate how many parallel instances
  4292. // fit without causing spills. All of this is rounded down if necessary to be
  4293. // a power of two. We want power of two interleave count to simplify any
  4294. // addressing operations or alignment considerations.
  4295. // We also want power of two interleave counts to ensure that the induction
  4296. // variable of the vector loop wraps to zero, when tail is folded by masking;
  4297. // this currently happens when OptForSize, in which case IC is set to 1 above.
  4298. unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
  4299. R.MaxLocalUsers);
  4300. // Don't count the induction variable as interleaved.
  4301. if (EnableIndVarRegisterHeur)
  4302. IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
  4303. std::max(1U, (R.MaxLocalUsers - 1)));
  4304. // Clamp the interleave ranges to reasonable counts.
  4305. unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
  4306. // Check if the user has overridden the max.
  4307. if (VF == 1) {
  4308. if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
  4309. MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
  4310. } else {
  4311. if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
  4312. MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
  4313. }
  4314. // If we did not calculate the cost for VF (because the user selected the VF)
  4315. // then we calculate the cost of VF here.
  4316. if (LoopCost == 0)
  4317. LoopCost = expectedCost(VF).first;
  4318. assert(LoopCost && "Non-zero loop cost expected");
  4319. // Clamp the calculated IC to be between the 1 and the max interleave count
  4320. // that the target allows.
  4321. if (IC > MaxInterleaveCount)
  4322. IC = MaxInterleaveCount;
  4323. else if (IC < 1)
  4324. IC = 1;
  4325. // Interleave if we vectorized this loop and there is a reduction that could
  4326. // benefit from interleaving.
  4327. if (VF > 1 && !Legal->getReductionVars()->empty()) {
  4328. LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
  4329. return IC;
  4330. }
  4331. // Note that if we've already vectorized the loop we will have done the
  4332. // runtime check and so interleaving won't require further checks.
  4333. bool InterleavingRequiresRuntimePointerCheck =
  4334. (VF == 1 && Legal->getRuntimePointerChecking()->Need);
  4335. // We want to interleave small loops in order to reduce the loop overhead and
  4336. // potentially expose ILP opportunities.
  4337. LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
  4338. if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
  4339. // We assume that the cost overhead is 1 and we use the cost model
  4340. // to estimate the cost of the loop and interleave until the cost of the
  4341. // loop overhead is about 5% of the cost of the loop.
  4342. unsigned SmallIC =
  4343. std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
  4344. // Interleave until store/load ports (estimated by max interleave count) are
  4345. // saturated.
  4346. unsigned NumStores = Legal->getNumStores();
  4347. unsigned NumLoads = Legal->getNumLoads();
  4348. unsigned StoresIC = IC / (NumStores ? NumStores : 1);
  4349. unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
  4350. // If we have a scalar reduction (vector reductions are already dealt with
  4351. // by this point), we can increase the critical path length if the loop
  4352. // we're interleaving is inside another loop. Limit, by default to 2, so the
  4353. // critical path only gets increased by one reduction operation.
  4354. if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) {
  4355. unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
  4356. SmallIC = std::min(SmallIC, F);
  4357. StoresIC = std::min(StoresIC, F);
  4358. LoadsIC = std::min(LoadsIC, F);
  4359. }
  4360. if (EnableLoadStoreRuntimeInterleave &&
  4361. std::max(StoresIC, LoadsIC) > SmallIC) {
  4362. LLVM_DEBUG(
  4363. dbgs() << "LV: Interleaving to saturate store or load ports.\n");
  4364. return std::max(StoresIC, LoadsIC);
  4365. }
  4366. LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
  4367. return SmallIC;
  4368. }
  4369. // Interleave if this is a large loop (small loops are already dealt with by
  4370. // this point) that could benefit from interleaving.
  4371. bool HasReductions = !Legal->getReductionVars()->empty();
  4372. if (TTI.enableAggressiveInterleaving(HasReductions)) {
  4373. LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  4374. return IC;
  4375. }
  4376. LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
  4377. return 1;
  4378. }
  4379. SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
  4380. LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
  4381. // This function calculates the register usage by measuring the highest number
  4382. // of values that are alive at a single location. Obviously, this is a very
  4383. // rough estimation. We scan the loop in a topological order in order and
  4384. // assign a number to each instruction. We use RPO to ensure that defs are
  4385. // met before their users. We assume that each instruction that has in-loop
  4386. // users starts an interval. We record every time that an in-loop value is
  4387. // used, so we have a list of the first and last occurrences of each
  4388. // instruction. Next, we transpose this data structure into a multi map that
  4389. // holds the list of intervals that *end* at a specific location. This multi
  4390. // map allows us to perform a linear search. We scan the instructions linearly
  4391. // and record each time that a new interval starts, by placing it in a set.
  4392. // If we find this value in the multi-map then we remove it from the set.
  4393. // The max register usage is the maximum size of the set.
  4394. // We also search for instructions that are defined outside the loop, but are
  4395. // used inside the loop. We need this number separately from the max-interval
  4396. // usage number because when we unroll, loop-invariant values do not take
  4397. // more register.
  4398. LoopBlocksDFS DFS(TheLoop);
  4399. DFS.perform(LI);
  4400. RegisterUsage RU;
  4401. // Each 'key' in the map opens a new interval. The values
  4402. // of the map are the index of the 'last seen' usage of the
  4403. // instruction that is the key.
  4404. using IntervalMap = DenseMap<Instruction *, unsigned>;
  4405. // Maps instruction to its index.
  4406. SmallVector<Instruction *, 64> IdxToInstr;
  4407. // Marks the end of each interval.
  4408. IntervalMap EndPoint;
  4409. // Saves the list of instruction indices that are used in the loop.
  4410. SmallPtrSet<Instruction *, 8> Ends;
  4411. // Saves the list of values that are used in the loop but are
  4412. // defined outside the loop, such as arguments and constants.
  4413. SmallPtrSet<Value *, 8> LoopInvariants;
  4414. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  4415. for (Instruction &I : BB->instructionsWithoutDebug()) {
  4416. IdxToInstr.push_back(&I);
  4417. // Save the end location of each USE.
  4418. for (Value *U : I.operands()) {
  4419. auto *Instr = dyn_cast<Instruction>(U);
  4420. // Ignore non-instruction values such as arguments, constants, etc.
  4421. if (!Instr)
  4422. continue;
  4423. // If this instruction is outside the loop then record it and continue.
  4424. if (!TheLoop->contains(Instr)) {
  4425. LoopInvariants.insert(Instr);
  4426. continue;
  4427. }
  4428. // Overwrite previous end points.
  4429. EndPoint[Instr] = IdxToInstr.size();
  4430. Ends.insert(Instr);
  4431. }
  4432. }
  4433. }
  4434. // Saves the list of intervals that end with the index in 'key'.
  4435. using InstrList = SmallVector<Instruction *, 2>;
  4436. DenseMap<unsigned, InstrList> TransposeEnds;
  4437. // Transpose the EndPoints to a list of values that end at each index.
  4438. for (auto &Interval : EndPoint)
  4439. TransposeEnds[Interval.second].push_back(Interval.first);
  4440. SmallPtrSet<Instruction *, 8> OpenIntervals;
  4441. // Get the size of the widest register.
  4442. unsigned MaxSafeDepDist = -1U;
  4443. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4444. MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
  4445. unsigned WidestRegister =
  4446. std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
  4447. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4448. SmallVector<RegisterUsage, 8> RUs(VFs.size());
  4449. SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
  4450. LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  4451. // A lambda that gets the register usage for the given type and VF.
  4452. auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
  4453. if (Ty->isTokenTy())
  4454. return 0U;
  4455. unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
  4456. return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
  4457. };
  4458. for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
  4459. Instruction *I = IdxToInstr[i];
  4460. // Remove all of the instructions that end at this location.
  4461. InstrList &List = TransposeEnds[i];
  4462. for (Instruction *ToRemove : List)
  4463. OpenIntervals.erase(ToRemove);
  4464. // Ignore instructions that are never used within the loop.
  4465. if (Ends.find(I) == Ends.end())
  4466. continue;
  4467. // Skip ignored values.
  4468. if (ValuesToIgnore.find(I) != ValuesToIgnore.end())
  4469. continue;
  4470. // For each VF find the maximum usage of registers.
  4471. for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
  4472. if (VFs[j] == 1) {
  4473. MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
  4474. continue;
  4475. }
  4476. collectUniformsAndScalars(VFs[j]);
  4477. // Count the number of live intervals.
  4478. unsigned RegUsage = 0;
  4479. for (auto Inst : OpenIntervals) {
  4480. // Skip ignored values for VF > 1.
  4481. if (VecValuesToIgnore.find(Inst) != VecValuesToIgnore.end() ||
  4482. isScalarAfterVectorization(Inst, VFs[j]))
  4483. continue;
  4484. RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
  4485. }
  4486. MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
  4487. }
  4488. LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
  4489. << OpenIntervals.size() << '\n');
  4490. // Add the current instruction to the list of open intervals.
  4491. OpenIntervals.insert(I);
  4492. }
  4493. for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
  4494. unsigned Invariant = 0;
  4495. if (VFs[i] == 1)
  4496. Invariant = LoopInvariants.size();
  4497. else {
  4498. for (auto Inst : LoopInvariants)
  4499. Invariant += GetRegUsage(Inst->getType(), VFs[i]);
  4500. }
  4501. LLVM_DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
  4502. LLVM_DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
  4503. LLVM_DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant
  4504. << '\n');
  4505. RU.LoopInvariantRegs = Invariant;
  4506. RU.MaxLocalUsers = MaxUsages[i];
  4507. RUs[i] = RU;
  4508. }
  4509. return RUs;
  4510. }
  4511. bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
  4512. // TODO: Cost model for emulated masked load/store is completely
  4513. // broken. This hack guides the cost model to use an artificially
  4514. // high enough value to practically disable vectorization with such
  4515. // operations, except where previously deployed legality hack allowed
  4516. // using very low cost values. This is to avoid regressions coming simply
  4517. // from moving "masked load/store" check from legality to cost model.
  4518. // Masked Load/Gather emulation was previously never allowed.
  4519. // Limited number of Masked Store/Scatter emulation was allowed.
  4520. assert(isPredicatedInst(I) && "Expecting a scalar emulated instruction");
  4521. return isa<LoadInst>(I) ||
  4522. (isa<StoreInst>(I) &&
  4523. NumPredStores > NumberOfStoresToPredicate);
  4524. }
  4525. void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
  4526. // If we aren't vectorizing the loop, or if we've already collected the
  4527. // instructions to scalarize, there's nothing to do. Collection may already
  4528. // have occurred if we have a user-selected VF and are now computing the
  4529. // expected cost for interleaving.
  4530. if (VF < 2 || InstsToScalarize.find(VF) != InstsToScalarize.end())
  4531. return;
  4532. // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
  4533. // not profitable to scalarize any instructions, the presence of VF in the
  4534. // map will indicate that we've analyzed it already.
  4535. ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
  4536. // Find all the instructions that are scalar with predication in the loop and
  4537. // determine if it would be better to not if-convert the blocks they are in.
  4538. // If so, we also record the instructions to scalarize.
  4539. for (BasicBlock *BB : TheLoop->blocks()) {
  4540. if (!blockNeedsPredication(BB))
  4541. continue;
  4542. for (Instruction &I : *BB)
  4543. if (isScalarWithPredication(&I)) {
  4544. ScalarCostsTy ScalarCosts;
  4545. // Do not apply discount logic if hacked cost is needed
  4546. // for emulated masked memrefs.
  4547. if (!useEmulatedMaskMemRefHack(&I) &&
  4548. computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
  4549. ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
  4550. // Remember that BB will remain after vectorization.
  4551. PredicatedBBsAfterVectorization.insert(BB);
  4552. }
  4553. }
  4554. }
  4555. int LoopVectorizationCostModel::computePredInstDiscount(
  4556. Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
  4557. unsigned VF) {
  4558. assert(!isUniformAfterVectorization(PredInst, VF) &&
  4559. "Instruction marked uniform-after-vectorization will be predicated");
  4560. // Initialize the discount to zero, meaning that the scalar version and the
  4561. // vector version cost the same.
  4562. int Discount = 0;
  4563. // Holds instructions to analyze. The instructions we visit are mapped in
  4564. // ScalarCosts. Those instructions are the ones that would be scalarized if
  4565. // we find that the scalar version costs less.
  4566. SmallVector<Instruction *, 8> Worklist;
  4567. // Returns true if the given instruction can be scalarized.
  4568. auto canBeScalarized = [&](Instruction *I) -> bool {
  4569. // We only attempt to scalarize instructions forming a single-use chain
  4570. // from the original predicated block that would otherwise be vectorized.
  4571. // Although not strictly necessary, we give up on instructions we know will
  4572. // already be scalar to avoid traversing chains that are unlikely to be
  4573. // beneficial.
  4574. if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
  4575. isScalarAfterVectorization(I, VF))
  4576. return false;
  4577. // If the instruction is scalar with predication, it will be analyzed
  4578. // separately. We ignore it within the context of PredInst.
  4579. if (isScalarWithPredication(I))
  4580. return false;
  4581. // If any of the instruction's operands are uniform after vectorization,
  4582. // the instruction cannot be scalarized. This prevents, for example, a
  4583. // masked load from being scalarized.
  4584. //
  4585. // We assume we will only emit a value for lane zero of an instruction
  4586. // marked uniform after vectorization, rather than VF identical values.
  4587. // Thus, if we scalarize an instruction that uses a uniform, we would
  4588. // create uses of values corresponding to the lanes we aren't emitting code
  4589. // for. This behavior can be changed by allowing getScalarValue to clone
  4590. // the lane zero values for uniforms rather than asserting.
  4591. for (Use &U : I->operands())
  4592. if (auto *J = dyn_cast<Instruction>(U.get()))
  4593. if (isUniformAfterVectorization(J, VF))
  4594. return false;
  4595. // Otherwise, we can scalarize the instruction.
  4596. return true;
  4597. };
  4598. // Returns true if an operand that cannot be scalarized must be extracted
  4599. // from a vector. We will account for this scalarization overhead below. Note
  4600. // that the non-void predicated instructions are placed in their own blocks,
  4601. // and their return values are inserted into vectors. Thus, an extract would
  4602. // still be required.
  4603. auto needsExtract = [&](Instruction *I) -> bool {
  4604. return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
  4605. };
  4606. // Compute the expected cost discount from scalarizing the entire expression
  4607. // feeding the predicated instruction. We currently only consider expressions
  4608. // that are single-use instruction chains.
  4609. Worklist.push_back(PredInst);
  4610. while (!Worklist.empty()) {
  4611. Instruction *I = Worklist.pop_back_val();
  4612. // If we've already analyzed the instruction, there's nothing to do.
  4613. if (ScalarCosts.find(I) != ScalarCosts.end())
  4614. continue;
  4615. // Compute the cost of the vector instruction. Note that this cost already
  4616. // includes the scalarization overhead of the predicated instruction.
  4617. unsigned VectorCost = getInstructionCost(I, VF).first;
  4618. // Compute the cost of the scalarized instruction. This cost is the cost of
  4619. // the instruction as if it wasn't if-converted and instead remained in the
  4620. // predicated block. We will scale this cost by block probability after
  4621. // computing the scalarization overhead.
  4622. unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
  4623. // Compute the scalarization overhead of needed insertelement instructions
  4624. // and phi nodes.
  4625. if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
  4626. ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
  4627. true, false);
  4628. ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
  4629. }
  4630. // Compute the scalarization overhead of needed extractelement
  4631. // instructions. For each of the instruction's operands, if the operand can
  4632. // be scalarized, add it to the worklist; otherwise, account for the
  4633. // overhead.
  4634. for (Use &U : I->operands())
  4635. if (auto *J = dyn_cast<Instruction>(U.get())) {
  4636. assert(VectorType::isValidElementType(J->getType()) &&
  4637. "Instruction has non-scalar type");
  4638. if (canBeScalarized(J))
  4639. Worklist.push_back(J);
  4640. else if (needsExtract(J))
  4641. ScalarCost += TTI.getScalarizationOverhead(
  4642. ToVectorTy(J->getType(),VF), false, true);
  4643. }
  4644. // Scale the total scalar cost by block probability.
  4645. ScalarCost /= getReciprocalPredBlockProb();
  4646. // Compute the discount. A non-negative discount means the vector version
  4647. // of the instruction costs more, and scalarizing would be beneficial.
  4648. Discount += VectorCost - ScalarCost;
  4649. ScalarCosts[I] = ScalarCost;
  4650. }
  4651. return Discount;
  4652. }
  4653. LoopVectorizationCostModel::VectorizationCostTy
  4654. LoopVectorizationCostModel::expectedCost(unsigned VF) {
  4655. VectorizationCostTy Cost;
  4656. // For each block.
  4657. for (BasicBlock *BB : TheLoop->blocks()) {
  4658. VectorizationCostTy BlockCost;
  4659. // For each instruction in the old loop.
  4660. for (Instruction &I : BB->instructionsWithoutDebug()) {
  4661. // Skip ignored values.
  4662. if (ValuesToIgnore.find(&I) != ValuesToIgnore.end() ||
  4663. (VF > 1 && VecValuesToIgnore.find(&I) != VecValuesToIgnore.end()))
  4664. continue;
  4665. VectorizationCostTy C = getInstructionCost(&I, VF);
  4666. // Check if we should override the cost.
  4667. if (ForceTargetInstructionCost.getNumOccurrences() > 0)
  4668. C.first = ForceTargetInstructionCost;
  4669. BlockCost.first += C.first;
  4670. BlockCost.second |= C.second;
  4671. LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
  4672. << " for VF " << VF << " For instruction: " << I
  4673. << '\n');
  4674. }
  4675. // If we are vectorizing a predicated block, it will have been
  4676. // if-converted. This means that the block's instructions (aside from
  4677. // stores and instructions that may divide by zero) will now be
  4678. // unconditionally executed. For the scalar case, we may not always execute
  4679. // the predicated block. Thus, scale the block's cost by the probability of
  4680. // executing it.
  4681. if (VF == 1 && blockNeedsPredication(BB))
  4682. BlockCost.first /= getReciprocalPredBlockProb();
  4683. Cost.first += BlockCost.first;
  4684. Cost.second |= BlockCost.second;
  4685. }
  4686. return Cost;
  4687. }
  4688. /// Gets Address Access SCEV after verifying that the access pattern
  4689. /// is loop invariant except the induction variable dependence.
  4690. ///
  4691. /// This SCEV can be sent to the Target in order to estimate the address
  4692. /// calculation cost.
  4693. static const SCEV *getAddressAccessSCEV(
  4694. Value *Ptr,
  4695. LoopVectorizationLegality *Legal,
  4696. PredicatedScalarEvolution &PSE,
  4697. const Loop *TheLoop) {
  4698. auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  4699. if (!Gep)
  4700. return nullptr;
  4701. // We are looking for a gep with all loop invariant indices except for one
  4702. // which should be an induction variable.
  4703. auto SE = PSE.getSE();
  4704. unsigned NumOperands = Gep->getNumOperands();
  4705. for (unsigned i = 1; i < NumOperands; ++i) {
  4706. Value *Opd = Gep->getOperand(i);
  4707. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  4708. !Legal->isInductionVariable(Opd))
  4709. return nullptr;
  4710. }
  4711. // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
  4712. return PSE.getSCEV(Ptr);
  4713. }
  4714. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  4715. return Legal->hasStride(I->getOperand(0)) ||
  4716. Legal->hasStride(I->getOperand(1));
  4717. }
  4718. unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
  4719. unsigned VF) {
  4720. assert(VF > 1 && "Scalarization cost of instruction implies vectorization.");
  4721. Type *ValTy = getMemInstValueType(I);
  4722. auto SE = PSE.getSE();
  4723. unsigned Alignment = getLoadStoreAlignment(I);
  4724. unsigned AS = getLoadStoreAddressSpace(I);
  4725. Value *Ptr = getLoadStorePointerOperand(I);
  4726. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  4727. // Figure out whether the access is strided and get the stride value
  4728. // if it's known in compile time
  4729. const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
  4730. // Get the cost of the scalar memory instruction and address computation.
  4731. unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
  4732. // Don't pass *I here, since it is scalar but will actually be part of a
  4733. // vectorized loop where the user of it is a vectorized instruction.
  4734. Cost += VF *
  4735. TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
  4736. AS);
  4737. // Get the overhead of the extractelement and insertelement instructions
  4738. // we might create due to scalarization.
  4739. Cost += getScalarizationOverhead(I, VF);
  4740. // If we have a predicated store, it may not be executed for each vector
  4741. // lane. Scale the cost by the probability of executing the predicated
  4742. // block.
  4743. if (isPredicatedInst(I)) {
  4744. Cost /= getReciprocalPredBlockProb();
  4745. if (useEmulatedMaskMemRefHack(I))
  4746. // Artificially setting to a high enough value to practically disable
  4747. // vectorization with such operations.
  4748. Cost = 3000000;
  4749. }
  4750. return Cost;
  4751. }
  4752. unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
  4753. unsigned VF) {
  4754. Type *ValTy = getMemInstValueType(I);
  4755. Type *VectorTy = ToVectorTy(ValTy, VF);
  4756. unsigned Alignment = getLoadStoreAlignment(I);
  4757. Value *Ptr = getLoadStorePointerOperand(I);
  4758. unsigned AS = getLoadStoreAddressSpace(I);
  4759. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  4760. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  4761. "Stride should be 1 or -1 for consecutive memory access");
  4762. unsigned Cost = 0;
  4763. if (Legal->isMaskRequired(I))
  4764. Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  4765. else
  4766. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
  4767. bool Reverse = ConsecutiveStride < 0;
  4768. if (Reverse)
  4769. Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  4770. return Cost;
  4771. }
  4772. unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
  4773. unsigned VF) {
  4774. Type *ValTy = getMemInstValueType(I);
  4775. Type *VectorTy = ToVectorTy(ValTy, VF);
  4776. unsigned Alignment = getLoadStoreAlignment(I);
  4777. unsigned AS = getLoadStoreAddressSpace(I);
  4778. if (isa<LoadInst>(I)) {
  4779. return TTI.getAddressComputationCost(ValTy) +
  4780. TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
  4781. TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
  4782. }
  4783. StoreInst *SI = cast<StoreInst>(I);
  4784. bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
  4785. return TTI.getAddressComputationCost(ValTy) +
  4786. TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS) +
  4787. (isLoopInvariantStoreValue ? 0 : TTI.getVectorInstrCost(
  4788. Instruction::ExtractElement,
  4789. VectorTy, VF - 1));
  4790. }
  4791. unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
  4792. unsigned VF) {
  4793. Type *ValTy = getMemInstValueType(I);
  4794. Type *VectorTy = ToVectorTy(ValTy, VF);
  4795. unsigned Alignment = getLoadStoreAlignment(I);
  4796. Value *Ptr = getLoadStorePointerOperand(I);
  4797. return TTI.getAddressComputationCost(VectorTy) +
  4798. TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
  4799. Legal->isMaskRequired(I), Alignment);
  4800. }
  4801. unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
  4802. unsigned VF) {
  4803. Type *ValTy = getMemInstValueType(I);
  4804. Type *VectorTy = ToVectorTy(ValTy, VF);
  4805. unsigned AS = getLoadStoreAddressSpace(I);
  4806. auto Group = getInterleavedAccessGroup(I);
  4807. assert(Group && "Fail to get an interleaved access group.");
  4808. unsigned InterleaveFactor = Group->getFactor();
  4809. Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
  4810. // Holds the indices of existing members in an interleaved load group.
  4811. // An interleaved store group doesn't need this as it doesn't allow gaps.
  4812. SmallVector<unsigned, 4> Indices;
  4813. if (isa<LoadInst>(I)) {
  4814. for (unsigned i = 0; i < InterleaveFactor; i++)
  4815. if (Group->getMember(i))
  4816. Indices.push_back(i);
  4817. }
  4818. // Calculate the cost of the whole interleaved group.
  4819. bool UseMaskForGaps =
  4820. Group->requiresScalarEpilogue() && !IsScalarEpilogueAllowed;
  4821. unsigned Cost = TTI.getInterleavedMemoryOpCost(
  4822. I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
  4823. Group->getAlignment(), AS, Legal->isMaskRequired(I), UseMaskForGaps);
  4824. if (Group->isReverse()) {
  4825. // TODO: Add support for reversed masked interleaved access.
  4826. assert(!Legal->isMaskRequired(I) &&
  4827. "Reverse masked interleaved access not supported.");
  4828. Cost += Group->getNumMembers() *
  4829. TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  4830. }
  4831. return Cost;
  4832. }
  4833. unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
  4834. unsigned VF) {
  4835. // Calculate scalar cost only. Vectorization cost should be ready at this
  4836. // moment.
  4837. if (VF == 1) {
  4838. Type *ValTy = getMemInstValueType(I);
  4839. unsigned Alignment = getLoadStoreAlignment(I);
  4840. unsigned AS = getLoadStoreAddressSpace(I);
  4841. return TTI.getAddressComputationCost(ValTy) +
  4842. TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
  4843. }
  4844. return getWideningCost(I, VF);
  4845. }
  4846. LoopVectorizationCostModel::VectorizationCostTy
  4847. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
  4848. // If we know that this instruction will remain uniform, check the cost of
  4849. // the scalar version.
  4850. if (isUniformAfterVectorization(I, VF))
  4851. VF = 1;
  4852. if (VF > 1 && isProfitableToScalarize(I, VF))
  4853. return VectorizationCostTy(InstsToScalarize[VF][I], false);
  4854. // Forced scalars do not have any scalarization overhead.
  4855. auto ForcedScalar = ForcedScalars.find(VF);
  4856. if (VF > 1 && ForcedScalar != ForcedScalars.end()) {
  4857. auto InstSet = ForcedScalar->second;
  4858. if (InstSet.find(I) != InstSet.end())
  4859. return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false);
  4860. }
  4861. Type *VectorTy;
  4862. unsigned C = getInstructionCost(I, VF, VectorTy);
  4863. bool TypeNotScalarized =
  4864. VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF;
  4865. return VectorizationCostTy(C, TypeNotScalarized);
  4866. }
  4867. unsigned LoopVectorizationCostModel::getScalarizationOverhead(Instruction *I,
  4868. unsigned VF) {
  4869. if (VF == 1)
  4870. return 0;
  4871. unsigned Cost = 0;
  4872. Type *RetTy = ToVectorTy(I->getType(), VF);
  4873. if (!RetTy->isVoidTy() &&
  4874. (!isa<LoadInst>(I) || !TTI.supportsEfficientVectorElementLoadStore()))
  4875. Cost += TTI.getScalarizationOverhead(RetTy, true, false);
  4876. // Some targets keep addresses scalar.
  4877. if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
  4878. return Cost;
  4879. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  4880. SmallVector<const Value *, 4> Operands(CI->arg_operands());
  4881. Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
  4882. } else if (!isa<StoreInst>(I) ||
  4883. !TTI.supportsEfficientVectorElementLoadStore()) {
  4884. SmallVector<const Value *, 4> Operands(I->operand_values());
  4885. Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
  4886. }
  4887. return Cost;
  4888. }
  4889. void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
  4890. if (VF == 1)
  4891. return;
  4892. NumPredStores = 0;
  4893. for (BasicBlock *BB : TheLoop->blocks()) {
  4894. // For each instruction in the old loop.
  4895. for (Instruction &I : *BB) {
  4896. Value *Ptr = getLoadStorePointerOperand(&I);
  4897. if (!Ptr)
  4898. continue;
  4899. // TODO: We should generate better code and update the cost model for
  4900. // predicated uniform stores. Today they are treated as any other
  4901. // predicated store (see added test cases in
  4902. // invariant-store-vectorization.ll).
  4903. if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
  4904. NumPredStores++;
  4905. if (Legal->isUniform(Ptr) &&
  4906. // Conditional loads and stores should be scalarized and predicated.
  4907. // isScalarWithPredication cannot be used here since masked
  4908. // gather/scatters are not considered scalar with predication.
  4909. !Legal->blockNeedsPredication(I.getParent())) {
  4910. // TODO: Avoid replicating loads and stores instead of
  4911. // relying on instcombine to remove them.
  4912. // Load: Scalar load + broadcast
  4913. // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
  4914. unsigned Cost = getUniformMemOpCost(&I, VF);
  4915. setWideningDecision(&I, VF, CM_Scalarize, Cost);
  4916. continue;
  4917. }
  4918. // We assume that widening is the best solution when possible.
  4919. if (memoryInstructionCanBeWidened(&I, VF)) {
  4920. unsigned Cost = getConsecutiveMemOpCost(&I, VF);
  4921. int ConsecutiveStride =
  4922. Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
  4923. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  4924. "Expected consecutive stride.");
  4925. InstWidening Decision =
  4926. ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
  4927. setWideningDecision(&I, VF, Decision, Cost);
  4928. continue;
  4929. }
  4930. // Choose between Interleaving, Gather/Scatter or Scalarization.
  4931. unsigned InterleaveCost = std::numeric_limits<unsigned>::max();
  4932. unsigned NumAccesses = 1;
  4933. if (isAccessInterleaved(&I)) {
  4934. auto Group = getInterleavedAccessGroup(&I);
  4935. assert(Group && "Fail to get an interleaved access group.");
  4936. // Make one decision for the whole group.
  4937. if (getWideningDecision(&I, VF) != CM_Unknown)
  4938. continue;
  4939. NumAccesses = Group->getNumMembers();
  4940. if (interleavedAccessCanBeWidened(&I, VF))
  4941. InterleaveCost = getInterleaveGroupCost(&I, VF);
  4942. }
  4943. unsigned GatherScatterCost =
  4944. isLegalGatherOrScatter(&I)
  4945. ? getGatherScatterCost(&I, VF) * NumAccesses
  4946. : std::numeric_limits<unsigned>::max();
  4947. unsigned ScalarizationCost =
  4948. getMemInstScalarizationCost(&I, VF) * NumAccesses;
  4949. // Choose better solution for the current VF,
  4950. // write down this decision and use it during vectorization.
  4951. unsigned Cost;
  4952. InstWidening Decision;
  4953. if (InterleaveCost <= GatherScatterCost &&
  4954. InterleaveCost < ScalarizationCost) {
  4955. Decision = CM_Interleave;
  4956. Cost = InterleaveCost;
  4957. } else if (GatherScatterCost < ScalarizationCost) {
  4958. Decision = CM_GatherScatter;
  4959. Cost = GatherScatterCost;
  4960. } else {
  4961. Decision = CM_Scalarize;
  4962. Cost = ScalarizationCost;
  4963. }
  4964. // If the instructions belongs to an interleave group, the whole group
  4965. // receives the same decision. The whole group receives the cost, but
  4966. // the cost will actually be assigned to one instruction.
  4967. if (auto Group = getInterleavedAccessGroup(&I))
  4968. setWideningDecision(Group, VF, Decision, Cost);
  4969. else
  4970. setWideningDecision(&I, VF, Decision, Cost);
  4971. }
  4972. }
  4973. // Make sure that any load of address and any other address computation
  4974. // remains scalar unless there is gather/scatter support. This avoids
  4975. // inevitable extracts into address registers, and also has the benefit of
  4976. // activating LSR more, since that pass can't optimize vectorized
  4977. // addresses.
  4978. if (TTI.prefersVectorizedAddressing())
  4979. return;
  4980. // Start with all scalar pointer uses.
  4981. SmallPtrSet<Instruction *, 8> AddrDefs;
  4982. for (BasicBlock *BB : TheLoop->blocks())
  4983. for (Instruction &I : *BB) {
  4984. Instruction *PtrDef =
  4985. dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  4986. if (PtrDef && TheLoop->contains(PtrDef) &&
  4987. getWideningDecision(&I, VF) != CM_GatherScatter)
  4988. AddrDefs.insert(PtrDef);
  4989. }
  4990. // Add all instructions used to generate the addresses.
  4991. SmallVector<Instruction *, 4> Worklist;
  4992. for (auto *I : AddrDefs)
  4993. Worklist.push_back(I);
  4994. while (!Worklist.empty()) {
  4995. Instruction *I = Worklist.pop_back_val();
  4996. for (auto &Op : I->operands())
  4997. if (auto *InstOp = dyn_cast<Instruction>(Op))
  4998. if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
  4999. AddrDefs.insert(InstOp).second)
  5000. Worklist.push_back(InstOp);
  5001. }
  5002. for (auto *I : AddrDefs) {
  5003. if (isa<LoadInst>(I)) {
  5004. // Setting the desired widening decision should ideally be handled in
  5005. // by cost functions, but since this involves the task of finding out
  5006. // if the loaded register is involved in an address computation, it is
  5007. // instead changed here when we know this is the case.
  5008. InstWidening Decision = getWideningDecision(I, VF);
  5009. if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
  5010. // Scalarize a widened load of address.
  5011. setWideningDecision(I, VF, CM_Scalarize,
  5012. (VF * getMemoryInstructionCost(I, 1)));
  5013. else if (auto Group = getInterleavedAccessGroup(I)) {
  5014. // Scalarize an interleave group of address loads.
  5015. for (unsigned I = 0; I < Group->getFactor(); ++I) {
  5016. if (Instruction *Member = Group->getMember(I))
  5017. setWideningDecision(Member, VF, CM_Scalarize,
  5018. (VF * getMemoryInstructionCost(Member, 1)));
  5019. }
  5020. }
  5021. } else
  5022. // Make sure I gets scalarized and a cost estimate without
  5023. // scalarization overhead.
  5024. ForcedScalars[VF].insert(I);
  5025. }
  5026. }
  5027. unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
  5028. unsigned VF,
  5029. Type *&VectorTy) {
  5030. Type *RetTy = I->getType();
  5031. if (canTruncateToMinimalBitwidth(I, VF))
  5032. RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
  5033. VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
  5034. auto SE = PSE.getSE();
  5035. // TODO: We need to estimate the cost of intrinsic calls.
  5036. switch (I->getOpcode()) {
  5037. case Instruction::GetElementPtr:
  5038. // We mark this instruction as zero-cost because the cost of GEPs in
  5039. // vectorized code depends on whether the corresponding memory instruction
  5040. // is scalarized or not. Therefore, we handle GEPs with the memory
  5041. // instruction cost.
  5042. return 0;
  5043. case Instruction::Br: {
  5044. // In cases of scalarized and predicated instructions, there will be VF
  5045. // predicated blocks in the vectorized loop. Each branch around these
  5046. // blocks requires also an extract of its vector compare i1 element.
  5047. bool ScalarPredicatedBB = false;
  5048. BranchInst *BI = cast<BranchInst>(I);
  5049. if (VF > 1 && BI->isConditional() &&
  5050. (PredicatedBBsAfterVectorization.find(BI->getSuccessor(0)) !=
  5051. PredicatedBBsAfterVectorization.end() ||
  5052. PredicatedBBsAfterVectorization.find(BI->getSuccessor(1)) !=
  5053. PredicatedBBsAfterVectorization.end()))
  5054. ScalarPredicatedBB = true;
  5055. if (ScalarPredicatedBB) {
  5056. // Return cost for branches around scalarized and predicated blocks.
  5057. Type *Vec_i1Ty =
  5058. VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
  5059. return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
  5060. (TTI.getCFInstrCost(Instruction::Br) * VF));
  5061. } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
  5062. // The back-edge branch will remain, as will all scalar branches.
  5063. return TTI.getCFInstrCost(Instruction::Br);
  5064. else
  5065. // This branch will be eliminated by if-conversion.
  5066. return 0;
  5067. // Note: We currently assume zero cost for an unconditional branch inside
  5068. // a predicated block since it will become a fall-through, although we
  5069. // may decide in the future to call TTI for all branches.
  5070. }
  5071. case Instruction::PHI: {
  5072. auto *Phi = cast<PHINode>(I);
  5073. // First-order recurrences are replaced by vector shuffles inside the loop.
  5074. // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
  5075. if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
  5076. return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  5077. VectorTy, VF - 1, VectorType::get(RetTy, 1));
  5078. // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
  5079. // converted into select instructions. We require N - 1 selects per phi
  5080. // node, where N is the number of incoming values.
  5081. if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
  5082. return (Phi->getNumIncomingValues() - 1) *
  5083. TTI.getCmpSelInstrCost(
  5084. Instruction::Select, ToVectorTy(Phi->getType(), VF),
  5085. ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF));
  5086. return TTI.getCFInstrCost(Instruction::PHI);
  5087. }
  5088. case Instruction::UDiv:
  5089. case Instruction::SDiv:
  5090. case Instruction::URem:
  5091. case Instruction::SRem:
  5092. // If we have a predicated instruction, it may not be executed for each
  5093. // vector lane. Get the scalarization cost and scale this amount by the
  5094. // probability of executing the predicated block. If the instruction is not
  5095. // predicated, we fall through to the next case.
  5096. if (VF > 1 && isScalarWithPredication(I)) {
  5097. unsigned Cost = 0;
  5098. // These instructions have a non-void type, so account for the phi nodes
  5099. // that we will create. This cost is likely to be zero. The phi node
  5100. // cost, if any, should be scaled by the block probability because it
  5101. // models a copy at the end of each predicated block.
  5102. Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
  5103. // The cost of the non-predicated instruction.
  5104. Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
  5105. // The cost of insertelement and extractelement instructions needed for
  5106. // scalarization.
  5107. Cost += getScalarizationOverhead(I, VF);
  5108. // Scale the cost by the probability of executing the predicated blocks.
  5109. // This assumes the predicated block for each vector lane is equally
  5110. // likely.
  5111. return Cost / getReciprocalPredBlockProb();
  5112. }
  5113. LLVM_FALLTHROUGH;
  5114. case Instruction::Add:
  5115. case Instruction::FAdd:
  5116. case Instruction::Sub:
  5117. case Instruction::FSub:
  5118. case Instruction::Mul:
  5119. case Instruction::FMul:
  5120. case Instruction::FDiv:
  5121. case Instruction::FRem:
  5122. case Instruction::Shl:
  5123. case Instruction::LShr:
  5124. case Instruction::AShr:
  5125. case Instruction::And:
  5126. case Instruction::Or:
  5127. case Instruction::Xor: {
  5128. // Since we will replace the stride by 1 the multiplication should go away.
  5129. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  5130. return 0;
  5131. // Certain instructions can be cheaper to vectorize if they have a constant
  5132. // second vector operand. One example of this are shifts on x86.
  5133. Value *Op2 = I->getOperand(1);
  5134. TargetTransformInfo::OperandValueProperties Op2VP;
  5135. TargetTransformInfo::OperandValueKind Op2VK =
  5136. TTI.getOperandInfo(Op2, Op2VP);
  5137. if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
  5138. Op2VK = TargetTransformInfo::OK_UniformValue;
  5139. SmallVector<const Value *, 4> Operands(I->operand_values());
  5140. unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
  5141. return N * TTI.getArithmeticInstrCost(
  5142. I->getOpcode(), VectorTy, TargetTransformInfo::OK_AnyValue,
  5143. Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands);
  5144. }
  5145. case Instruction::Select: {
  5146. SelectInst *SI = cast<SelectInst>(I);
  5147. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  5148. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  5149. Type *CondTy = SI->getCondition()->getType();
  5150. if (!ScalarCond)
  5151. CondTy = VectorType::get(CondTy, VF);
  5152. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
  5153. }
  5154. case Instruction::ICmp:
  5155. case Instruction::FCmp: {
  5156. Type *ValTy = I->getOperand(0)->getType();
  5157. Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
  5158. if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
  5159. ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
  5160. VectorTy = ToVectorTy(ValTy, VF);
  5161. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
  5162. }
  5163. case Instruction::Store:
  5164. case Instruction::Load: {
  5165. unsigned Width = VF;
  5166. if (Width > 1) {
  5167. InstWidening Decision = getWideningDecision(I, Width);
  5168. assert(Decision != CM_Unknown &&
  5169. "CM decision should be taken at this point");
  5170. if (Decision == CM_Scalarize)
  5171. Width = 1;
  5172. }
  5173. VectorTy = ToVectorTy(getMemInstValueType(I), Width);
  5174. return getMemoryInstructionCost(I, VF);
  5175. }
  5176. case Instruction::ZExt:
  5177. case Instruction::SExt:
  5178. case Instruction::FPToUI:
  5179. case Instruction::FPToSI:
  5180. case Instruction::FPExt:
  5181. case Instruction::PtrToInt:
  5182. case Instruction::IntToPtr:
  5183. case Instruction::SIToFP:
  5184. case Instruction::UIToFP:
  5185. case Instruction::Trunc:
  5186. case Instruction::FPTrunc:
  5187. case Instruction::BitCast: {
  5188. // We optimize the truncation of induction variables having constant
  5189. // integer steps. The cost of these truncations is the same as the scalar
  5190. // operation.
  5191. if (isOptimizableIVTruncate(I, VF)) {
  5192. auto *Trunc = cast<TruncInst>(I);
  5193. return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
  5194. Trunc->getSrcTy(), Trunc);
  5195. }
  5196. Type *SrcScalarTy = I->getOperand(0)->getType();
  5197. Type *SrcVecTy =
  5198. VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
  5199. if (canTruncateToMinimalBitwidth(I, VF)) {
  5200. // This cast is going to be shrunk. This may remove the cast or it might
  5201. // turn it into slightly different cast. For example, if MinBW == 16,
  5202. // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
  5203. //
  5204. // Calculate the modified src and dest types.
  5205. Type *MinVecTy = VectorTy;
  5206. if (I->getOpcode() == Instruction::Trunc) {
  5207. SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
  5208. VectorTy =
  5209. largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  5210. } else if (I->getOpcode() == Instruction::ZExt ||
  5211. I->getOpcode() == Instruction::SExt) {
  5212. SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
  5213. VectorTy =
  5214. smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  5215. }
  5216. }
  5217. unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
  5218. return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
  5219. }
  5220. case Instruction::Call: {
  5221. bool NeedToScalarize;
  5222. CallInst *CI = cast<CallInst>(I);
  5223. unsigned CallCost = getVectorCallCost(CI, VF, NeedToScalarize);
  5224. if (getVectorIntrinsicIDForCall(CI, TLI))
  5225. return std::min(CallCost, getVectorIntrinsicCost(CI, VF));
  5226. return CallCost;
  5227. }
  5228. default:
  5229. // The cost of executing VF copies of the scalar instruction. This opcode
  5230. // is unknown. Assume that it is the same as 'mul'.
  5231. return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
  5232. getScalarizationOverhead(I, VF);
  5233. } // end of switch.
  5234. }
  5235. char LoopVectorize::ID = 0;
  5236. static const char lv_name[] = "Loop Vectorization";
  5237. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  5238. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  5239. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  5240. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  5241. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  5242. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  5243. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  5244. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  5245. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  5246. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  5247. INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
  5248. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  5249. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  5250. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  5251. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  5252. namespace llvm {
  5253. Pass *createLoopVectorizePass() { return new LoopVectorize(); }
  5254. Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
  5255. bool VectorizeOnlyWhenForced) {
  5256. return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
  5257. }
  5258. } // end namespace llvm
  5259. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  5260. // Check if the pointer operand of a load or store instruction is
  5261. // consecutive.
  5262. if (auto *Ptr = getLoadStorePointerOperand(Inst))
  5263. return Legal->isConsecutivePtr(Ptr);
  5264. return false;
  5265. }
  5266. void LoopVectorizationCostModel::collectValuesToIgnore() {
  5267. // Ignore ephemeral values.
  5268. CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
  5269. // Ignore type-promoting instructions we identified during reduction
  5270. // detection.
  5271. for (auto &Reduction : *Legal->getReductionVars()) {
  5272. RecurrenceDescriptor &RedDes = Reduction.second;
  5273. SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
  5274. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  5275. }
  5276. // Ignore type-casting instructions we identified during induction
  5277. // detection.
  5278. for (auto &Induction : *Legal->getInductionVars()) {
  5279. InductionDescriptor &IndDes = Induction.second;
  5280. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  5281. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  5282. }
  5283. }
  5284. // TODO: we could return a pair of values that specify the max VF and
  5285. // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
  5286. // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
  5287. // doesn't have a cost model that can choose which plan to execute if
  5288. // more than one is generated.
  5289. static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
  5290. LoopVectorizationCostModel &CM) {
  5291. unsigned WidestType;
  5292. std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
  5293. return WidestVectorRegBits / WidestType;
  5294. }
  5295. VectorizationFactor
  5296. LoopVectorizationPlanner::planInVPlanNativePath(bool OptForSize,
  5297. unsigned UserVF) {
  5298. unsigned VF = UserVF;
  5299. // Outer loop handling: They may require CFG and instruction level
  5300. // transformations before even evaluating whether vectorization is profitable.
  5301. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  5302. // the vectorization pipeline.
  5303. if (!OrigLoop->empty()) {
  5304. // If the user doesn't provide a vectorization factor, determine a
  5305. // reasonable one.
  5306. if (!UserVF) {
  5307. VF = determineVPlanVF(TTI->getRegisterBitWidth(true /* Vector*/), CM);
  5308. LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
  5309. // Make sure we have a VF > 1 for stress testing.
  5310. if (VPlanBuildStressTest && VF < 2) {
  5311. LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
  5312. << "overriding computed VF.\n");
  5313. VF = 4;
  5314. }
  5315. }
  5316. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  5317. assert(isPowerOf2_32(VF) && "VF needs to be a power of two");
  5318. LLVM_DEBUG(dbgs() << "LV: Using " << (UserVF ? "user " : "") << "VF " << VF
  5319. << " to build VPlans.\n");
  5320. buildVPlans(VF, VF);
  5321. // For VPlan build stress testing, we bail out after VPlan construction.
  5322. if (VPlanBuildStressTest)
  5323. return VectorizationFactor::Disabled();
  5324. return {VF, 0};
  5325. }
  5326. LLVM_DEBUG(
  5327. dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
  5328. "VPlan-native path.\n");
  5329. return VectorizationFactor::Disabled();
  5330. }
  5331. Optional<VectorizationFactor> LoopVectorizationPlanner::plan(bool OptForSize,
  5332. unsigned UserVF) {
  5333. assert(OrigLoop->empty() && "Inner loop expected.");
  5334. Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
  5335. if (!MaybeMaxVF) // Cases that should not to be vectorized nor interleaved.
  5336. return None;
  5337. // Invalidate interleave groups if all blocks of loop will be predicated.
  5338. if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
  5339. !useMaskedInterleavedAccesses(*TTI)) {
  5340. LLVM_DEBUG(
  5341. dbgs()
  5342. << "LV: Invalidate all interleaved groups due to fold-tail by masking "
  5343. "which requires masked-interleaved support.\n");
  5344. CM.InterleaveInfo.reset();
  5345. }
  5346. if (UserVF) {
  5347. LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  5348. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  5349. // Collect the instructions (and their associated costs) that will be more
  5350. // profitable to scalarize.
  5351. CM.selectUserVectorizationFactor(UserVF);
  5352. buildVPlansWithVPRecipes(UserVF, UserVF);
  5353. LLVM_DEBUG(printPlans(dbgs()));
  5354. return {{UserVF, 0}};
  5355. }
  5356. unsigned MaxVF = MaybeMaxVF.getValue();
  5357. assert(MaxVF != 0 && "MaxVF is zero.");
  5358. for (unsigned VF = 1; VF <= MaxVF; VF *= 2) {
  5359. // Collect Uniform and Scalar instructions after vectorization with VF.
  5360. CM.collectUniformsAndScalars(VF);
  5361. // Collect the instructions (and their associated costs) that will be more
  5362. // profitable to scalarize.
  5363. if (VF > 1)
  5364. CM.collectInstsToScalarize(VF);
  5365. }
  5366. buildVPlansWithVPRecipes(1, MaxVF);
  5367. LLVM_DEBUG(printPlans(dbgs()));
  5368. if (MaxVF == 1)
  5369. return VectorizationFactor::Disabled();
  5370. // Select the optimal vectorization factor.
  5371. return CM.selectVectorizationFactor(MaxVF);
  5372. }
  5373. void LoopVectorizationPlanner::setBestPlan(unsigned VF, unsigned UF) {
  5374. LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
  5375. << '\n');
  5376. BestVF = VF;
  5377. BestUF = UF;
  5378. erase_if(VPlans, [VF](const VPlanPtr &Plan) {
  5379. return !Plan->hasVF(VF);
  5380. });
  5381. assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
  5382. }
  5383. void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
  5384. DominatorTree *DT) {
  5385. // Perform the actual loop transformation.
  5386. // 1. Create a new empty loop. Unlink the old loop and connect the new one.
  5387. VPCallbackILV CallbackILV(ILV);
  5388. VPTransformState State{BestVF, BestUF, LI,
  5389. DT, ILV.Builder, ILV.VectorLoopValueMap,
  5390. &ILV, CallbackILV};
  5391. State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
  5392. State.TripCount = ILV.getOrCreateTripCount(nullptr);
  5393. //===------------------------------------------------===//
  5394. //
  5395. // Notice: any optimization or new instruction that go
  5396. // into the code below should also be implemented in
  5397. // the cost-model.
  5398. //
  5399. //===------------------------------------------------===//
  5400. // 2. Copy and widen instructions from the old loop into the new loop.
  5401. assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
  5402. VPlans.front()->execute(&State);
  5403. // 3. Fix the vectorized code: take care of header phi's, live-outs,
  5404. // predication, updating analyses.
  5405. ILV.fixVectorizedLoop();
  5406. }
  5407. void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
  5408. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  5409. BasicBlock *Latch = OrigLoop->getLoopLatch();
  5410. // We create new control-flow for the vectorized loop, so the original
  5411. // condition will be dead after vectorization if it's only used by the
  5412. // branch.
  5413. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  5414. if (Cmp && Cmp->hasOneUse())
  5415. DeadInstructions.insert(Cmp);
  5416. // We create new "steps" for induction variable updates to which the original
  5417. // induction variables map. An original update instruction will be dead if
  5418. // all its users except the induction variable are dead.
  5419. for (auto &Induction : *Legal->getInductionVars()) {
  5420. PHINode *Ind = Induction.first;
  5421. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  5422. if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  5423. return U == Ind || DeadInstructions.find(cast<Instruction>(U)) !=
  5424. DeadInstructions.end();
  5425. }))
  5426. DeadInstructions.insert(IndUpdate);
  5427. // We record as "Dead" also the type-casting instructions we had identified
  5428. // during induction analysis. We don't need any handling for them in the
  5429. // vectorized loop because we have proven that, under a proper runtime
  5430. // test guarding the vectorized loop, the value of the phi, and the casted
  5431. // value of the phi, are the same. The last instruction in this casting chain
  5432. // will get its scalar/vector/widened def from the scalar/vector/widened def
  5433. // of the respective phi node. Any other casts in the induction def-use chain
  5434. // have no other uses outside the phi update chain, and will be ignored.
  5435. InductionDescriptor &IndDes = Induction.second;
  5436. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  5437. DeadInstructions.insert(Casts.begin(), Casts.end());
  5438. }
  5439. }
  5440. Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
  5441. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
  5442. Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
  5443. Instruction::BinaryOps BinOp) {
  5444. // When unrolling and the VF is 1, we only need to add a simple scalar.
  5445. Type *Ty = Val->getType();
  5446. assert(!Ty->isVectorTy() && "Val must be a scalar");
  5447. if (Ty->isFloatingPointTy()) {
  5448. Constant *C = ConstantFP::get(Ty, (double)StartIdx);
  5449. // Floating point operations had to be 'fast' to enable the unrolling.
  5450. Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
  5451. return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
  5452. }
  5453. Constant *C = ConstantInt::get(Ty, StartIdx);
  5454. return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
  5455. }
  5456. static void AddRuntimeUnrollDisableMetaData(Loop *L) {
  5457. SmallVector<Metadata *, 4> MDs;
  5458. // Reserve first location for self reference to the LoopID metadata node.
  5459. MDs.push_back(nullptr);
  5460. bool IsUnrollMetadata = false;
  5461. MDNode *LoopID = L->getLoopID();
  5462. if (LoopID) {
  5463. // First find existing loop unrolling disable metadata.
  5464. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  5465. auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  5466. if (MD) {
  5467. const auto *S = dyn_cast<MDString>(MD->getOperand(0));
  5468. IsUnrollMetadata =
  5469. S && S->getString().startswith("llvm.loop.unroll.disable");
  5470. }
  5471. MDs.push_back(LoopID->getOperand(i));
  5472. }
  5473. }
  5474. if (!IsUnrollMetadata) {
  5475. // Add runtime unroll disable metadata.
  5476. LLVMContext &Context = L->getHeader()->getContext();
  5477. SmallVector<Metadata *, 1> DisableOperands;
  5478. DisableOperands.push_back(
  5479. MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
  5480. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  5481. MDs.push_back(DisableNode);
  5482. MDNode *NewLoopID = MDNode::get(Context, MDs);
  5483. // Set operand 0 to refer to the loop id itself.
  5484. NewLoopID->replaceOperandWith(0, NewLoopID);
  5485. L->setLoopID(NewLoopID);
  5486. }
  5487. }
  5488. bool LoopVectorizationPlanner::getDecisionAndClampRange(
  5489. const std::function<bool(unsigned)> &Predicate, VFRange &Range) {
  5490. assert(Range.End > Range.Start && "Trying to test an empty VF range.");
  5491. bool PredicateAtRangeStart = Predicate(Range.Start);
  5492. for (unsigned TmpVF = Range.Start * 2; TmpVF < Range.End; TmpVF *= 2)
  5493. if (Predicate(TmpVF) != PredicateAtRangeStart) {
  5494. Range.End = TmpVF;
  5495. break;
  5496. }
  5497. return PredicateAtRangeStart;
  5498. }
  5499. /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
  5500. /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
  5501. /// of VF's starting at a given VF and extending it as much as possible. Each
  5502. /// vectorization decision can potentially shorten this sub-range during
  5503. /// buildVPlan().
  5504. void LoopVectorizationPlanner::buildVPlans(unsigned MinVF, unsigned MaxVF) {
  5505. for (unsigned VF = MinVF; VF < MaxVF + 1;) {
  5506. VFRange SubRange = {VF, MaxVF + 1};
  5507. VPlans.push_back(buildVPlan(SubRange));
  5508. VF = SubRange.End;
  5509. }
  5510. }
  5511. VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
  5512. VPlanPtr &Plan) {
  5513. assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
  5514. // Look for cached value.
  5515. std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
  5516. EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
  5517. if (ECEntryIt != EdgeMaskCache.end())
  5518. return ECEntryIt->second;
  5519. VPValue *SrcMask = createBlockInMask(Src, Plan);
  5520. // The terminator has to be a branch inst!
  5521. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  5522. assert(BI && "Unexpected terminator found");
  5523. if (!BI->isConditional())
  5524. return EdgeMaskCache[Edge] = SrcMask;
  5525. VPValue *EdgeMask = Plan->getVPValue(BI->getCondition());
  5526. assert(EdgeMask && "No Edge Mask found for condition");
  5527. if (BI->getSuccessor(0) != Dst)
  5528. EdgeMask = Builder.createNot(EdgeMask);
  5529. if (SrcMask) // Otherwise block in-mask is all-one, no need to AND.
  5530. EdgeMask = Builder.createAnd(EdgeMask, SrcMask);
  5531. return EdgeMaskCache[Edge] = EdgeMask;
  5532. }
  5533. VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
  5534. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  5535. // Look for cached value.
  5536. BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
  5537. if (BCEntryIt != BlockMaskCache.end())
  5538. return BCEntryIt->second;
  5539. // All-one mask is modelled as no-mask following the convention for masked
  5540. // load/store/gather/scatter. Initialize BlockMask to no-mask.
  5541. VPValue *BlockMask = nullptr;
  5542. if (OrigLoop->getHeader() == BB) {
  5543. if (!CM.blockNeedsPredication(BB))
  5544. return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
  5545. // Introduce the early-exit compare IV <= BTC to form header block mask.
  5546. // This is used instead of IV < TC because TC may wrap, unlike BTC.
  5547. VPValue *IV = Plan->getVPValue(Legal->getPrimaryInduction());
  5548. VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
  5549. BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
  5550. return BlockMaskCache[BB] = BlockMask;
  5551. }
  5552. // This is the block mask. We OR all incoming edges.
  5553. for (auto *Predecessor : predecessors(BB)) {
  5554. VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
  5555. if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
  5556. return BlockMaskCache[BB] = EdgeMask;
  5557. if (!BlockMask) { // BlockMask has its initialized nullptr value.
  5558. BlockMask = EdgeMask;
  5559. continue;
  5560. }
  5561. BlockMask = Builder.createOr(BlockMask, EdgeMask);
  5562. }
  5563. return BlockMaskCache[BB] = BlockMask;
  5564. }
  5565. VPInterleaveRecipe *VPRecipeBuilder::tryToInterleaveMemory(Instruction *I,
  5566. VFRange &Range,
  5567. VPlanPtr &Plan) {
  5568. const InterleaveGroup<Instruction> *IG = CM.getInterleavedAccessGroup(I);
  5569. if (!IG)
  5570. return nullptr;
  5571. // Now check if IG is relevant for VF's in the given range.
  5572. auto isIGMember = [&](Instruction *I) -> std::function<bool(unsigned)> {
  5573. return [=](unsigned VF) -> bool {
  5574. return (VF >= 2 && // Query is illegal for VF == 1
  5575. CM.getWideningDecision(I, VF) ==
  5576. LoopVectorizationCostModel::CM_Interleave);
  5577. };
  5578. };
  5579. if (!LoopVectorizationPlanner::getDecisionAndClampRange(isIGMember(I), Range))
  5580. return nullptr;
  5581. // I is a member of an InterleaveGroup for VF's in the (possibly trimmed)
  5582. // range. If it's the primary member of the IG construct a VPInterleaveRecipe.
  5583. // Otherwise, it's an adjunct member of the IG, do not construct any Recipe.
  5584. assert(I == IG->getInsertPos() &&
  5585. "Generating a recipe for an adjunct member of an interleave group");
  5586. VPValue *Mask = nullptr;
  5587. if (Legal->isMaskRequired(I))
  5588. Mask = createBlockInMask(I->getParent(), Plan);
  5589. return new VPInterleaveRecipe(IG, Mask);
  5590. }
  5591. VPWidenMemoryInstructionRecipe *
  5592. VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range,
  5593. VPlanPtr &Plan) {
  5594. if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
  5595. return nullptr;
  5596. auto willWiden = [&](unsigned VF) -> bool {
  5597. if (VF == 1)
  5598. return false;
  5599. if (CM.isScalarAfterVectorization(I, VF) ||
  5600. CM.isProfitableToScalarize(I, VF))
  5601. return false;
  5602. LoopVectorizationCostModel::InstWidening Decision =
  5603. CM.getWideningDecision(I, VF);
  5604. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  5605. "CM decision should be taken at this point.");
  5606. assert(Decision != LoopVectorizationCostModel::CM_Interleave &&
  5607. "Interleave memory opportunity should be caught earlier.");
  5608. return Decision != LoopVectorizationCostModel::CM_Scalarize;
  5609. };
  5610. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  5611. return nullptr;
  5612. VPValue *Mask = nullptr;
  5613. if (Legal->isMaskRequired(I))
  5614. Mask = createBlockInMask(I->getParent(), Plan);
  5615. return new VPWidenMemoryInstructionRecipe(*I, Mask);
  5616. }
  5617. VPWidenIntOrFpInductionRecipe *
  5618. VPRecipeBuilder::tryToOptimizeInduction(Instruction *I, VFRange &Range) {
  5619. if (PHINode *Phi = dyn_cast<PHINode>(I)) {
  5620. // Check if this is an integer or fp induction. If so, build the recipe that
  5621. // produces its scalar and vector values.
  5622. InductionDescriptor II = Legal->getInductionVars()->lookup(Phi);
  5623. if (II.getKind() == InductionDescriptor::IK_IntInduction ||
  5624. II.getKind() == InductionDescriptor::IK_FpInduction)
  5625. return new VPWidenIntOrFpInductionRecipe(Phi);
  5626. return nullptr;
  5627. }
  5628. // Optimize the special case where the source is a constant integer
  5629. // induction variable. Notice that we can only optimize the 'trunc' case
  5630. // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
  5631. // (c) other casts depend on pointer size.
  5632. // Determine whether \p K is a truncation based on an induction variable that
  5633. // can be optimized.
  5634. auto isOptimizableIVTruncate =
  5635. [&](Instruction *K) -> std::function<bool(unsigned)> {
  5636. return
  5637. [=](unsigned VF) -> bool { return CM.isOptimizableIVTruncate(K, VF); };
  5638. };
  5639. if (isa<TruncInst>(I) && LoopVectorizationPlanner::getDecisionAndClampRange(
  5640. isOptimizableIVTruncate(I), Range))
  5641. return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
  5642. cast<TruncInst>(I));
  5643. return nullptr;
  5644. }
  5645. VPBlendRecipe *VPRecipeBuilder::tryToBlend(Instruction *I, VPlanPtr &Plan) {
  5646. PHINode *Phi = dyn_cast<PHINode>(I);
  5647. if (!Phi || Phi->getParent() == OrigLoop->getHeader())
  5648. return nullptr;
  5649. // We know that all PHIs in non-header blocks are converted into selects, so
  5650. // we don't have to worry about the insertion order and we can just use the
  5651. // builder. At this point we generate the predication tree. There may be
  5652. // duplications since this is a simple recursive scan, but future
  5653. // optimizations will clean it up.
  5654. SmallVector<VPValue *, 2> Masks;
  5655. unsigned NumIncoming = Phi->getNumIncomingValues();
  5656. for (unsigned In = 0; In < NumIncoming; In++) {
  5657. VPValue *EdgeMask =
  5658. createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
  5659. assert((EdgeMask || NumIncoming == 1) &&
  5660. "Multiple predecessors with one having a full mask");
  5661. if (EdgeMask)
  5662. Masks.push_back(EdgeMask);
  5663. }
  5664. return new VPBlendRecipe(Phi, Masks);
  5665. }
  5666. bool VPRecipeBuilder::tryToWiden(Instruction *I, VPBasicBlock *VPBB,
  5667. VFRange &Range) {
  5668. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  5669. [&](unsigned VF) { return CM.isScalarWithPredication(I, VF); }, Range);
  5670. if (IsPredicated)
  5671. return false;
  5672. auto IsVectorizableOpcode = [](unsigned Opcode) {
  5673. switch (Opcode) {
  5674. case Instruction::Add:
  5675. case Instruction::And:
  5676. case Instruction::AShr:
  5677. case Instruction::BitCast:
  5678. case Instruction::Br:
  5679. case Instruction::Call:
  5680. case Instruction::FAdd:
  5681. case Instruction::FCmp:
  5682. case Instruction::FDiv:
  5683. case Instruction::FMul:
  5684. case Instruction::FPExt:
  5685. case Instruction::FPToSI:
  5686. case Instruction::FPToUI:
  5687. case Instruction::FPTrunc:
  5688. case Instruction::FRem:
  5689. case Instruction::FSub:
  5690. case Instruction::GetElementPtr:
  5691. case Instruction::ICmp:
  5692. case Instruction::IntToPtr:
  5693. case Instruction::Load:
  5694. case Instruction::LShr:
  5695. case Instruction::Mul:
  5696. case Instruction::Or:
  5697. case Instruction::PHI:
  5698. case Instruction::PtrToInt:
  5699. case Instruction::SDiv:
  5700. case Instruction::Select:
  5701. case Instruction::SExt:
  5702. case Instruction::Shl:
  5703. case Instruction::SIToFP:
  5704. case Instruction::SRem:
  5705. case Instruction::Store:
  5706. case Instruction::Sub:
  5707. case Instruction::Trunc:
  5708. case Instruction::UDiv:
  5709. case Instruction::UIToFP:
  5710. case Instruction::URem:
  5711. case Instruction::Xor:
  5712. case Instruction::ZExt:
  5713. return true;
  5714. }
  5715. return false;
  5716. };
  5717. if (!IsVectorizableOpcode(I->getOpcode()))
  5718. return false;
  5719. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  5720. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5721. if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
  5722. ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
  5723. return false;
  5724. }
  5725. auto willWiden = [&](unsigned VF) -> bool {
  5726. if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
  5727. CM.isProfitableToScalarize(I, VF)))
  5728. return false;
  5729. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  5730. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5731. // The following case may be scalarized depending on the VF.
  5732. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  5733. // version of the instruction.
  5734. // Is it beneficial to perform intrinsic call compared to lib call?
  5735. bool NeedToScalarize;
  5736. unsigned CallCost = CM.getVectorCallCost(CI, VF, NeedToScalarize);
  5737. bool UseVectorIntrinsic =
  5738. ID && CM.getVectorIntrinsicCost(CI, VF) <= CallCost;
  5739. return UseVectorIntrinsic || !NeedToScalarize;
  5740. }
  5741. if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
  5742. assert(CM.getWideningDecision(I, VF) ==
  5743. LoopVectorizationCostModel::CM_Scalarize &&
  5744. "Memory widening decisions should have been taken care by now");
  5745. return false;
  5746. }
  5747. return true;
  5748. };
  5749. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  5750. return false;
  5751. // Success: widen this instruction. We optimize the common case where
  5752. // consecutive instructions can be represented by a single recipe.
  5753. if (!VPBB->empty()) {
  5754. VPWidenRecipe *LastWidenRecipe = dyn_cast<VPWidenRecipe>(&VPBB->back());
  5755. if (LastWidenRecipe && LastWidenRecipe->appendInstruction(I))
  5756. return true;
  5757. }
  5758. VPBB->appendRecipe(new VPWidenRecipe(I));
  5759. return true;
  5760. }
  5761. VPBasicBlock *VPRecipeBuilder::handleReplication(
  5762. Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
  5763. DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
  5764. VPlanPtr &Plan) {
  5765. bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
  5766. [&](unsigned VF) { return CM.isUniformAfterVectorization(I, VF); },
  5767. Range);
  5768. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  5769. [&](unsigned VF) { return CM.isScalarWithPredication(I, VF); }, Range);
  5770. auto *Recipe = new VPReplicateRecipe(I, IsUniform, IsPredicated);
  5771. // Find if I uses a predicated instruction. If so, it will use its scalar
  5772. // value. Avoid hoisting the insert-element which packs the scalar value into
  5773. // a vector value, as that happens iff all users use the vector value.
  5774. for (auto &Op : I->operands())
  5775. if (auto *PredInst = dyn_cast<Instruction>(Op))
  5776. if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
  5777. PredInst2Recipe[PredInst]->setAlsoPack(false);
  5778. // Finalize the recipe for Instr, first if it is not predicated.
  5779. if (!IsPredicated) {
  5780. LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
  5781. VPBB->appendRecipe(Recipe);
  5782. return VPBB;
  5783. }
  5784. LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
  5785. assert(VPBB->getSuccessors().empty() &&
  5786. "VPBB has successors when handling predicated replication.");
  5787. // Record predicated instructions for above packing optimizations.
  5788. PredInst2Recipe[I] = Recipe;
  5789. VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
  5790. VPBlockUtils::insertBlockAfter(Region, VPBB);
  5791. auto *RegSucc = new VPBasicBlock();
  5792. VPBlockUtils::insertBlockAfter(RegSucc, Region);
  5793. return RegSucc;
  5794. }
  5795. VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
  5796. VPRecipeBase *PredRecipe,
  5797. VPlanPtr &Plan) {
  5798. // Instructions marked for predication are replicated and placed under an
  5799. // if-then construct to prevent side-effects.
  5800. // Generate recipes to compute the block mask for this region.
  5801. VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
  5802. // Build the triangular if-then region.
  5803. std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
  5804. assert(Instr->getParent() && "Predicated instruction not in any basic block");
  5805. auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
  5806. auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
  5807. auto *PHIRecipe =
  5808. Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr);
  5809. auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
  5810. auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
  5811. VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
  5812. // Note: first set Entry as region entry and then connect successors starting
  5813. // from it in order, to propagate the "parent" of each VPBasicBlock.
  5814. VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
  5815. VPBlockUtils::connectBlocks(Pred, Exit);
  5816. return Region;
  5817. }
  5818. bool VPRecipeBuilder::tryToCreateRecipe(Instruction *Instr, VFRange &Range,
  5819. VPlanPtr &Plan, VPBasicBlock *VPBB) {
  5820. VPRecipeBase *Recipe = nullptr;
  5821. // Check if Instr should belong to an interleave memory recipe, or already
  5822. // does. In the latter case Instr is irrelevant.
  5823. if ((Recipe = tryToInterleaveMemory(Instr, Range, Plan))) {
  5824. VPBB->appendRecipe(Recipe);
  5825. return true;
  5826. }
  5827. // Check if Instr is a memory operation that should be widened.
  5828. if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) {
  5829. VPBB->appendRecipe(Recipe);
  5830. return true;
  5831. }
  5832. // Check if Instr should form some PHI recipe.
  5833. if ((Recipe = tryToOptimizeInduction(Instr, Range))) {
  5834. VPBB->appendRecipe(Recipe);
  5835. return true;
  5836. }
  5837. if ((Recipe = tryToBlend(Instr, Plan))) {
  5838. VPBB->appendRecipe(Recipe);
  5839. return true;
  5840. }
  5841. if (PHINode *Phi = dyn_cast<PHINode>(Instr)) {
  5842. VPBB->appendRecipe(new VPWidenPHIRecipe(Phi));
  5843. return true;
  5844. }
  5845. // Check if Instr is to be widened by a general VPWidenRecipe, after
  5846. // having first checked for specific widening recipes that deal with
  5847. // Interleave Groups, Inductions and Phi nodes.
  5848. if (tryToWiden(Instr, VPBB, Range))
  5849. return true;
  5850. return false;
  5851. }
  5852. void LoopVectorizationPlanner::buildVPlansWithVPRecipes(unsigned MinVF,
  5853. unsigned MaxVF) {
  5854. assert(OrigLoop->empty() && "Inner loop expected.");
  5855. // Collect conditions feeding internal conditional branches; they need to be
  5856. // represented in VPlan for it to model masking.
  5857. SmallPtrSet<Value *, 1> NeedDef;
  5858. auto *Latch = OrigLoop->getLoopLatch();
  5859. for (BasicBlock *BB : OrigLoop->blocks()) {
  5860. if (BB == Latch)
  5861. continue;
  5862. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  5863. if (Branch && Branch->isConditional())
  5864. NeedDef.insert(Branch->getCondition());
  5865. }
  5866. // If the tail is to be folded by masking, the primary induction variable
  5867. // needs to be represented in VPlan for it to model early-exit masking.
  5868. if (CM.foldTailByMasking())
  5869. NeedDef.insert(Legal->getPrimaryInduction());
  5870. // Collect instructions from the original loop that will become trivially dead
  5871. // in the vectorized loop. We don't need to vectorize these instructions. For
  5872. // example, original induction update instructions can become dead because we
  5873. // separately emit induction "steps" when generating code for the new loop.
  5874. // Similarly, we create a new latch condition when setting up the structure
  5875. // of the new loop, so the old one can become dead.
  5876. SmallPtrSet<Instruction *, 4> DeadInstructions;
  5877. collectTriviallyDeadInstructions(DeadInstructions);
  5878. for (unsigned VF = MinVF; VF < MaxVF + 1;) {
  5879. VFRange SubRange = {VF, MaxVF + 1};
  5880. VPlans.push_back(
  5881. buildVPlanWithVPRecipes(SubRange, NeedDef, DeadInstructions));
  5882. VF = SubRange.End;
  5883. }
  5884. }
  5885. LoopVectorizationPlanner::VPlanPtr
  5886. LoopVectorizationPlanner::buildVPlanWithVPRecipes(
  5887. VFRange &Range, SmallPtrSetImpl<Value *> &NeedDef,
  5888. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  5889. // Hold a mapping from predicated instructions to their recipes, in order to
  5890. // fix their AlsoPack behavior if a user is determined to replicate and use a
  5891. // scalar instead of vector value.
  5892. DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
  5893. DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
  5894. DenseMap<Instruction *, Instruction *> SinkAfterInverse;
  5895. // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
  5896. VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
  5897. auto Plan = llvm::make_unique<VPlan>(VPBB);
  5898. VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, Legal, CM, Builder);
  5899. // Represent values that will have defs inside VPlan.
  5900. for (Value *V : NeedDef)
  5901. Plan->addVPValue(V);
  5902. // Scan the body of the loop in a topological order to visit each basic block
  5903. // after having visited its predecessor basic blocks.
  5904. LoopBlocksDFS DFS(OrigLoop);
  5905. DFS.perform(LI);
  5906. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  5907. // Relevant instructions from basic block BB will be grouped into VPRecipe
  5908. // ingredients and fill a new VPBasicBlock.
  5909. unsigned VPBBsForBB = 0;
  5910. auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
  5911. VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
  5912. VPBB = FirstVPBBForBB;
  5913. Builder.setInsertPoint(VPBB);
  5914. std::vector<Instruction *> Ingredients;
  5915. // Organize the ingredients to vectorize from current basic block in the
  5916. // right order.
  5917. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5918. Instruction *Instr = &I;
  5919. // First filter out irrelevant instructions, to ensure no recipes are
  5920. // built for them.
  5921. if (isa<BranchInst>(Instr) ||
  5922. DeadInstructions.find(Instr) != DeadInstructions.end())
  5923. continue;
  5924. // I is a member of an InterleaveGroup for Range.Start. If it's an adjunct
  5925. // member of the IG, do not construct any Recipe for it.
  5926. const InterleaveGroup<Instruction> *IG =
  5927. CM.getInterleavedAccessGroup(Instr);
  5928. if (IG && Instr != IG->getInsertPos() &&
  5929. Range.Start >= 2 && // Query is illegal for VF == 1
  5930. CM.getWideningDecision(Instr, Range.Start) ==
  5931. LoopVectorizationCostModel::CM_Interleave) {
  5932. auto SinkCandidate = SinkAfterInverse.find(Instr);
  5933. if (SinkCandidate != SinkAfterInverse.end())
  5934. Ingredients.push_back(SinkCandidate->second);
  5935. continue;
  5936. }
  5937. // Move instructions to handle first-order recurrences, step 1: avoid
  5938. // handling this instruction until after we've handled the instruction it
  5939. // should follow.
  5940. auto SAIt = SinkAfter.find(Instr);
  5941. if (SAIt != SinkAfter.end()) {
  5942. LLVM_DEBUG(dbgs() << "Sinking" << *SAIt->first << " after"
  5943. << *SAIt->second
  5944. << " to vectorize a 1st order recurrence.\n");
  5945. SinkAfterInverse[SAIt->second] = Instr;
  5946. continue;
  5947. }
  5948. Ingredients.push_back(Instr);
  5949. // Move instructions to handle first-order recurrences, step 2: push the
  5950. // instruction to be sunk at its insertion point.
  5951. auto SAInvIt = SinkAfterInverse.find(Instr);
  5952. if (SAInvIt != SinkAfterInverse.end())
  5953. Ingredients.push_back(SAInvIt->second);
  5954. }
  5955. // Introduce each ingredient into VPlan.
  5956. for (Instruction *Instr : Ingredients) {
  5957. if (RecipeBuilder.tryToCreateRecipe(Instr, Range, Plan, VPBB))
  5958. continue;
  5959. // Otherwise, if all widening options failed, Instruction is to be
  5960. // replicated. This may create a successor for VPBB.
  5961. VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
  5962. Instr, Range, VPBB, PredInst2Recipe, Plan);
  5963. if (NextVPBB != VPBB) {
  5964. VPBB = NextVPBB;
  5965. VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
  5966. : "");
  5967. }
  5968. }
  5969. }
  5970. // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
  5971. // may also be empty, such as the last one VPBB, reflecting original
  5972. // basic-blocks with no recipes.
  5973. VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
  5974. assert(PreEntry->empty() && "Expecting empty pre-entry block.");
  5975. VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
  5976. VPBlockUtils::disconnectBlocks(PreEntry, Entry);
  5977. delete PreEntry;
  5978. std::string PlanName;
  5979. raw_string_ostream RSO(PlanName);
  5980. unsigned VF = Range.Start;
  5981. Plan->addVF(VF);
  5982. RSO << "Initial VPlan for VF={" << VF;
  5983. for (VF *= 2; VF < Range.End; VF *= 2) {
  5984. Plan->addVF(VF);
  5985. RSO << "," << VF;
  5986. }
  5987. RSO << "},UF>=1";
  5988. RSO.flush();
  5989. Plan->setName(PlanName);
  5990. return Plan;
  5991. }
  5992. LoopVectorizationPlanner::VPlanPtr
  5993. LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
  5994. // Outer loop handling: They may require CFG and instruction level
  5995. // transformations before even evaluating whether vectorization is profitable.
  5996. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  5997. // the vectorization pipeline.
  5998. assert(!OrigLoop->empty());
  5999. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  6000. // Create new empty VPlan
  6001. auto Plan = llvm::make_unique<VPlan>();
  6002. // Build hierarchical CFG
  6003. VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
  6004. HCFGBuilder.buildHierarchicalCFG();
  6005. for (unsigned VF = Range.Start; VF < Range.End; VF *= 2)
  6006. Plan->addVF(VF);
  6007. if (EnableVPlanPredication) {
  6008. VPlanPredicator VPP(*Plan);
  6009. VPP.predicate();
  6010. // Avoid running transformation to recipes until masked code generation in
  6011. // VPlan-native path is in place.
  6012. return Plan;
  6013. }
  6014. SmallPtrSet<Instruction *, 1> DeadInstructions;
  6015. VPlanHCFGTransforms::VPInstructionsToVPRecipes(
  6016. Plan, Legal->getInductionVars(), DeadInstructions);
  6017. return Plan;
  6018. }
  6019. Value* LoopVectorizationPlanner::VPCallbackILV::
  6020. getOrCreateVectorValues(Value *V, unsigned Part) {
  6021. return ILV.getOrCreateVectorValue(V, Part);
  6022. }
  6023. void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent) const {
  6024. O << " +\n"
  6025. << Indent << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
  6026. IG->getInsertPos()->printAsOperand(O, false);
  6027. if (User) {
  6028. O << ", ";
  6029. User->getOperand(0)->printAsOperand(O);
  6030. }
  6031. O << "\\l\"";
  6032. for (unsigned i = 0; i < IG->getFactor(); ++i)
  6033. if (Instruction *I = IG->getMember(i))
  6034. O << " +\n"
  6035. << Indent << "\" " << VPlanIngredient(I) << " " << i << "\\l\"";
  6036. }
  6037. void VPWidenRecipe::execute(VPTransformState &State) {
  6038. for (auto &Instr : make_range(Begin, End))
  6039. State.ILV->widenInstruction(Instr);
  6040. }
  6041. void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
  6042. assert(!State.Instance && "Int or FP induction being replicated.");
  6043. State.ILV->widenIntOrFpInduction(IV, Trunc);
  6044. }
  6045. void VPWidenPHIRecipe::execute(VPTransformState &State) {
  6046. State.ILV->widenPHIInstruction(Phi, State.UF, State.VF);
  6047. }
  6048. void VPBlendRecipe::execute(VPTransformState &State) {
  6049. State.ILV->setDebugLocFromInst(State.Builder, Phi);
  6050. // We know that all PHIs in non-header blocks are converted into
  6051. // selects, so we don't have to worry about the insertion order and we
  6052. // can just use the builder.
  6053. // At this point we generate the predication tree. There may be
  6054. // duplications since this is a simple recursive scan, but future
  6055. // optimizations will clean it up.
  6056. unsigned NumIncoming = Phi->getNumIncomingValues();
  6057. assert((User || NumIncoming == 1) &&
  6058. "Multiple predecessors with predecessors having a full mask");
  6059. // Generate a sequence of selects of the form:
  6060. // SELECT(Mask3, In3,
  6061. // SELECT(Mask2, In2,
  6062. // ( ...)))
  6063. InnerLoopVectorizer::VectorParts Entry(State.UF);
  6064. for (unsigned In = 0; In < NumIncoming; ++In) {
  6065. for (unsigned Part = 0; Part < State.UF; ++Part) {
  6066. // We might have single edge PHIs (blocks) - use an identity
  6067. // 'select' for the first PHI operand.
  6068. Value *In0 =
  6069. State.ILV->getOrCreateVectorValue(Phi->getIncomingValue(In), Part);
  6070. if (In == 0)
  6071. Entry[Part] = In0; // Initialize with the first incoming value.
  6072. else {
  6073. // Select between the current value and the previous incoming edge
  6074. // based on the incoming mask.
  6075. Value *Cond = State.get(User->getOperand(In), Part);
  6076. Entry[Part] =
  6077. State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
  6078. }
  6079. }
  6080. }
  6081. for (unsigned Part = 0; Part < State.UF; ++Part)
  6082. State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
  6083. }
  6084. void VPInterleaveRecipe::execute(VPTransformState &State) {
  6085. assert(!State.Instance && "Interleave group being replicated.");
  6086. if (!User)
  6087. return State.ILV->vectorizeInterleaveGroup(IG->getInsertPos());
  6088. // Last (and currently only) operand is a mask.
  6089. InnerLoopVectorizer::VectorParts MaskValues(State.UF);
  6090. VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
  6091. for (unsigned Part = 0; Part < State.UF; ++Part)
  6092. MaskValues[Part] = State.get(Mask, Part);
  6093. State.ILV->vectorizeInterleaveGroup(IG->getInsertPos(), &MaskValues);
  6094. }
  6095. void VPReplicateRecipe::execute(VPTransformState &State) {
  6096. if (State.Instance) { // Generate a single instance.
  6097. State.ILV->scalarizeInstruction(Ingredient, *State.Instance, IsPredicated);
  6098. // Insert scalar instance packing it into a vector.
  6099. if (AlsoPack && State.VF > 1) {
  6100. // If we're constructing lane 0, initialize to start from undef.
  6101. if (State.Instance->Lane == 0) {
  6102. Value *Undef =
  6103. UndefValue::get(VectorType::get(Ingredient->getType(), State.VF));
  6104. State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef);
  6105. }
  6106. State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance);
  6107. }
  6108. return;
  6109. }
  6110. // Generate scalar instances for all VF lanes of all UF parts, unless the
  6111. // instruction is uniform inwhich case generate only the first lane for each
  6112. // of the UF parts.
  6113. unsigned EndLane = IsUniform ? 1 : State.VF;
  6114. for (unsigned Part = 0; Part < State.UF; ++Part)
  6115. for (unsigned Lane = 0; Lane < EndLane; ++Lane)
  6116. State.ILV->scalarizeInstruction(Ingredient, {Part, Lane}, IsPredicated);
  6117. }
  6118. void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
  6119. assert(State.Instance && "Branch on Mask works only on single instance.");
  6120. unsigned Part = State.Instance->Part;
  6121. unsigned Lane = State.Instance->Lane;
  6122. Value *ConditionBit = nullptr;
  6123. if (!User) // Block in mask is all-one.
  6124. ConditionBit = State.Builder.getTrue();
  6125. else {
  6126. VPValue *BlockInMask = User->getOperand(0);
  6127. ConditionBit = State.get(BlockInMask, Part);
  6128. if (ConditionBit->getType()->isVectorTy())
  6129. ConditionBit = State.Builder.CreateExtractElement(
  6130. ConditionBit, State.Builder.getInt32(Lane));
  6131. }
  6132. // Replace the temporary unreachable terminator with a new conditional branch,
  6133. // whose two destinations will be set later when they are created.
  6134. auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
  6135. assert(isa<UnreachableInst>(CurrentTerminator) &&
  6136. "Expected to replace unreachable terminator with conditional branch.");
  6137. auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
  6138. CondBr->setSuccessor(0, nullptr);
  6139. ReplaceInstWithInst(CurrentTerminator, CondBr);
  6140. }
  6141. void VPPredInstPHIRecipe::execute(VPTransformState &State) {
  6142. assert(State.Instance && "Predicated instruction PHI works per instance.");
  6143. Instruction *ScalarPredInst = cast<Instruction>(
  6144. State.ValueMap.getScalarValue(PredInst, *State.Instance));
  6145. BasicBlock *PredicatedBB = ScalarPredInst->getParent();
  6146. BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
  6147. assert(PredicatingBB && "Predicated block has no single predecessor.");
  6148. // By current pack/unpack logic we need to generate only a single phi node: if
  6149. // a vector value for the predicated instruction exists at this point it means
  6150. // the instruction has vector users only, and a phi for the vector value is
  6151. // needed. In this case the recipe of the predicated instruction is marked to
  6152. // also do that packing, thereby "hoisting" the insert-element sequence.
  6153. // Otherwise, a phi node for the scalar value is needed.
  6154. unsigned Part = State.Instance->Part;
  6155. if (State.ValueMap.hasVectorValue(PredInst, Part)) {
  6156. Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
  6157. InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
  6158. PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
  6159. VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
  6160. VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
  6161. State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
  6162. } else {
  6163. Type *PredInstType = PredInst->getType();
  6164. PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
  6165. Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB);
  6166. Phi->addIncoming(ScalarPredInst, PredicatedBB);
  6167. State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
  6168. }
  6169. }
  6170. void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
  6171. if (!User)
  6172. return State.ILV->vectorizeMemoryInstruction(&Instr);
  6173. // Last (and currently only) operand is a mask.
  6174. InnerLoopVectorizer::VectorParts MaskValues(State.UF);
  6175. VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
  6176. for (unsigned Part = 0; Part < State.UF; ++Part)
  6177. MaskValues[Part] = State.get(Mask, Part);
  6178. State.ILV->vectorizeMemoryInstruction(&Instr, &MaskValues);
  6179. }
  6180. // Process the loop in the VPlan-native vectorization path. This path builds
  6181. // VPlan upfront in the vectorization pipeline, which allows to apply
  6182. // VPlan-to-VPlan transformations from the very beginning without modifying the
  6183. // input LLVM IR.
  6184. static bool processLoopInVPlanNativePath(
  6185. Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
  6186. LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
  6187. TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
  6188. OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
  6189. ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints) {
  6190. assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
  6191. Function *F = L->getHeader()->getParent();
  6192. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
  6193. LoopVectorizationCostModel CM(L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
  6194. &Hints, IAI);
  6195. // Use the planner for outer loop vectorization.
  6196. // TODO: CM is not used at this point inside the planner. Turn CM into an
  6197. // optional argument if we don't need it in the future.
  6198. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM);
  6199. // Get user vectorization factor.
  6200. const unsigned UserVF = Hints.getWidth();
  6201. // Check the function attributes and profiles to find out if this function
  6202. // should be optimized for size.
  6203. bool OptForSize =
  6204. Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  6205. (F->hasOptSize() ||
  6206. llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI));
  6207. // Plan how to best vectorize, return the best VF and its cost.
  6208. const VectorizationFactor VF = LVP.planInVPlanNativePath(OptForSize, UserVF);
  6209. // If we are stress testing VPlan builds, do not attempt to generate vector
  6210. // code. Masked vector code generation support will follow soon.
  6211. // Also, do not attempt to vectorize if no vector code will be produced.
  6212. if (VPlanBuildStressTest || EnableVPlanPredication ||
  6213. VectorizationFactor::Disabled() == VF)
  6214. return false;
  6215. LVP.setBestPlan(VF.Width, 1);
  6216. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
  6217. &CM);
  6218. LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
  6219. << L->getHeader()->getParent()->getName() << "\"\n");
  6220. LVP.executePlan(LB, DT);
  6221. // Mark the loop as already vectorized to avoid vectorizing again.
  6222. Hints.setAlreadyVectorized();
  6223. LLVM_DEBUG(verifyFunction(*L->getHeader()->getParent()));
  6224. return true;
  6225. }
  6226. bool LoopVectorizePass::processLoop(Loop *L) {
  6227. assert((EnableVPlanNativePath || L->empty()) &&
  6228. "VPlan-native path is not enabled. Only process inner loops.");
  6229. #ifndef NDEBUG
  6230. const std::string DebugLocStr = getDebugLocString(L);
  6231. #endif /* NDEBUG */
  6232. LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
  6233. << L->getHeader()->getParent()->getName() << "\" from "
  6234. << DebugLocStr << "\n");
  6235. LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
  6236. LLVM_DEBUG(
  6237. dbgs() << "LV: Loop hints:"
  6238. << " force="
  6239. << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
  6240. ? "disabled"
  6241. : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
  6242. ? "enabled"
  6243. : "?"))
  6244. << " width=" << Hints.getWidth()
  6245. << " unroll=" << Hints.getInterleave() << "\n");
  6246. // Function containing loop
  6247. Function *F = L->getHeader()->getParent();
  6248. // Looking at the diagnostic output is the only way to determine if a loop
  6249. // was vectorized (other than looking at the IR or machine code), so it
  6250. // is important to generate an optimization remark for each loop. Most of
  6251. // these messages are generated as OptimizationRemarkAnalysis. Remarks
  6252. // generated as OptimizationRemark and OptimizationRemarkMissed are
  6253. // less verbose reporting vectorized loops and unvectorized loops that may
  6254. // benefit from vectorization, respectively.
  6255. if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
  6256. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
  6257. return false;
  6258. }
  6259. PredicatedScalarEvolution PSE(*SE, *L);
  6260. // Check if it is legal to vectorize the loop.
  6261. LoopVectorizationRequirements Requirements(*ORE);
  6262. LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, GetLAA, LI, ORE,
  6263. &Requirements, &Hints, DB, AC);
  6264. if (!LVL.canVectorize(EnableVPlanNativePath)) {
  6265. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  6266. Hints.emitRemarkWithHints();
  6267. return false;
  6268. }
  6269. // Check the function attributes and profiles to find out if this function
  6270. // should be optimized for size.
  6271. bool OptForSize =
  6272. Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  6273. (F->hasOptSize() ||
  6274. llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI));
  6275. // Entrance to the VPlan-native vectorization path. Outer loops are processed
  6276. // here. They may require CFG and instruction level transformations before
  6277. // even evaluating whether vectorization is profitable. Since we cannot modify
  6278. // the incoming IR, we need to build VPlan upfront in the vectorization
  6279. // pipeline.
  6280. if (!L->empty())
  6281. return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
  6282. ORE, BFI, PSI, Hints);
  6283. assert(L->empty() && "Inner loop expected.");
  6284. // Check the loop for a trip count threshold: vectorize loops with a tiny trip
  6285. // count by optimizing for size, to minimize overheads.
  6286. // Prefer constant trip counts over profile data, over upper bound estimate.
  6287. unsigned ExpectedTC = 0;
  6288. bool HasExpectedTC = false;
  6289. if (const SCEVConstant *ConstExits =
  6290. dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) {
  6291. const APInt &ExitsCount = ConstExits->getAPInt();
  6292. // We are interested in small values for ExpectedTC. Skip over those that
  6293. // can't fit an unsigned.
  6294. if (ExitsCount.ult(std::numeric_limits<unsigned>::max())) {
  6295. ExpectedTC = static_cast<unsigned>(ExitsCount.getZExtValue()) + 1;
  6296. HasExpectedTC = true;
  6297. }
  6298. }
  6299. // ExpectedTC may be large because it's bound by a variable. Check
  6300. // profiling information to validate we should vectorize.
  6301. if (!HasExpectedTC && LoopVectorizeWithBlockFrequency) {
  6302. auto EstimatedTC = getLoopEstimatedTripCount(L);
  6303. if (EstimatedTC) {
  6304. ExpectedTC = *EstimatedTC;
  6305. HasExpectedTC = true;
  6306. }
  6307. }
  6308. if (!HasExpectedTC) {
  6309. ExpectedTC = SE->getSmallConstantMaxTripCount(L);
  6310. HasExpectedTC = (ExpectedTC > 0);
  6311. }
  6312. if (HasExpectedTC && ExpectedTC < TinyTripCountVectorThreshold) {
  6313. LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
  6314. << "This loop is worth vectorizing only if no scalar "
  6315. << "iteration overheads are incurred.");
  6316. if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
  6317. LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
  6318. else {
  6319. LLVM_DEBUG(dbgs() << "\n");
  6320. // Loops with a very small trip count are considered for vectorization
  6321. // under OptForSize, thereby making sure the cost of their loop body is
  6322. // dominant, free of runtime guards and scalar iteration overheads.
  6323. OptForSize = true;
  6324. }
  6325. }
  6326. // Check the function attributes to see if implicit floats are allowed.
  6327. // FIXME: This check doesn't seem possibly correct -- what if the loop is
  6328. // an integer loop and the vector instructions selected are purely integer
  6329. // vector instructions?
  6330. if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
  6331. LLVM_DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
  6332. "attribute is used.\n");
  6333. ORE->emit(createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(),
  6334. "NoImplicitFloat", L)
  6335. << "loop not vectorized due to NoImplicitFloat attribute");
  6336. Hints.emitRemarkWithHints();
  6337. return false;
  6338. }
  6339. // Check if the target supports potentially unsafe FP vectorization.
  6340. // FIXME: Add a check for the type of safety issue (denormal, signaling)
  6341. // for the target we're vectorizing for, to make sure none of the
  6342. // additional fp-math flags can help.
  6343. if (Hints.isPotentiallyUnsafe() &&
  6344. TTI->isFPVectorizationPotentiallyUnsafe()) {
  6345. LLVM_DEBUG(
  6346. dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
  6347. ORE->emit(
  6348. createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
  6349. << "loop not vectorized due to unsafe FP support.");
  6350. Hints.emitRemarkWithHints();
  6351. return false;
  6352. }
  6353. bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
  6354. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
  6355. // If an override option has been passed in for interleaved accesses, use it.
  6356. if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
  6357. UseInterleaved = EnableInterleavedMemAccesses;
  6358. // Analyze interleaved memory accesses.
  6359. if (UseInterleaved) {
  6360. IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
  6361. }
  6362. // Use the cost model.
  6363. LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
  6364. &Hints, IAI);
  6365. CM.collectValuesToIgnore();
  6366. // Use the planner for vectorization.
  6367. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM);
  6368. // Get user vectorization factor.
  6369. unsigned UserVF = Hints.getWidth();
  6370. // Plan how to best vectorize, return the best VF and its cost.
  6371. Optional<VectorizationFactor> MaybeVF = LVP.plan(OptForSize, UserVF);
  6372. VectorizationFactor VF = VectorizationFactor::Disabled();
  6373. unsigned IC = 1;
  6374. unsigned UserIC = Hints.getInterleave();
  6375. if (MaybeVF) {
  6376. VF = *MaybeVF;
  6377. // Select the interleave count.
  6378. IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
  6379. }
  6380. // Identify the diagnostic messages that should be produced.
  6381. std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
  6382. bool VectorizeLoop = true, InterleaveLoop = true;
  6383. if (Requirements.doesNotMeet(F, L, Hints)) {
  6384. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
  6385. "requirements.\n");
  6386. Hints.emitRemarkWithHints();
  6387. return false;
  6388. }
  6389. if (VF.Width == 1) {
  6390. LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  6391. VecDiagMsg = std::make_pair(
  6392. "VectorizationNotBeneficial",
  6393. "the cost-model indicates that vectorization is not beneficial");
  6394. VectorizeLoop = false;
  6395. }
  6396. if (!MaybeVF && UserIC > 1) {
  6397. // Tell the user interleaving was avoided up-front, despite being explicitly
  6398. // requested.
  6399. LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
  6400. "interleaving should be avoided up front\n");
  6401. IntDiagMsg = std::make_pair(
  6402. "InterleavingAvoided",
  6403. "Ignoring UserIC, because interleaving was avoided up front");
  6404. InterleaveLoop = false;
  6405. } else if (IC == 1 && UserIC <= 1) {
  6406. // Tell the user interleaving is not beneficial.
  6407. LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
  6408. IntDiagMsg = std::make_pair(
  6409. "InterleavingNotBeneficial",
  6410. "the cost-model indicates that interleaving is not beneficial");
  6411. InterleaveLoop = false;
  6412. if (UserIC == 1) {
  6413. IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
  6414. IntDiagMsg.second +=
  6415. " and is explicitly disabled or interleave count is set to 1";
  6416. }
  6417. } else if (IC > 1 && UserIC == 1) {
  6418. // Tell the user interleaving is beneficial, but it explicitly disabled.
  6419. LLVM_DEBUG(
  6420. dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
  6421. IntDiagMsg = std::make_pair(
  6422. "InterleavingBeneficialButDisabled",
  6423. "the cost-model indicates that interleaving is beneficial "
  6424. "but is explicitly disabled or interleave count is set to 1");
  6425. InterleaveLoop = false;
  6426. }
  6427. // Override IC if user provided an interleave count.
  6428. IC = UserIC > 0 ? UserIC : IC;
  6429. // Emit diagnostic messages, if any.
  6430. const char *VAPassName = Hints.vectorizeAnalysisPassName();
  6431. if (!VectorizeLoop && !InterleaveLoop) {
  6432. // Do not vectorize or interleaving the loop.
  6433. ORE->emit([&]() {
  6434. return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
  6435. L->getStartLoc(), L->getHeader())
  6436. << VecDiagMsg.second;
  6437. });
  6438. ORE->emit([&]() {
  6439. return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
  6440. L->getStartLoc(), L->getHeader())
  6441. << IntDiagMsg.second;
  6442. });
  6443. return false;
  6444. } else if (!VectorizeLoop && InterleaveLoop) {
  6445. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  6446. ORE->emit([&]() {
  6447. return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
  6448. L->getStartLoc(), L->getHeader())
  6449. << VecDiagMsg.second;
  6450. });
  6451. } else if (VectorizeLoop && !InterleaveLoop) {
  6452. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  6453. << ") in " << DebugLocStr << '\n');
  6454. ORE->emit([&]() {
  6455. return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
  6456. L->getStartLoc(), L->getHeader())
  6457. << IntDiagMsg.second;
  6458. });
  6459. } else if (VectorizeLoop && InterleaveLoop) {
  6460. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  6461. << ") in " << DebugLocStr << '\n');
  6462. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  6463. }
  6464. LVP.setBestPlan(VF.Width, IC);
  6465. using namespace ore;
  6466. bool DisableRuntimeUnroll = false;
  6467. MDNode *OrigLoopID = L->getLoopID();
  6468. if (!VectorizeLoop) {
  6469. assert(IC > 1 && "interleave count should not be 1 or 0");
  6470. // If we decided that it is not legal to vectorize the loop, then
  6471. // interleave it.
  6472. InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
  6473. &CM);
  6474. LVP.executePlan(Unroller, DT);
  6475. ORE->emit([&]() {
  6476. return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
  6477. L->getHeader())
  6478. << "interleaved loop (interleaved count: "
  6479. << NV("InterleaveCount", IC) << ")";
  6480. });
  6481. } else {
  6482. // If we decided that it is *legal* to vectorize the loop, then do it.
  6483. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
  6484. &LVL, &CM);
  6485. LVP.executePlan(LB, DT);
  6486. ++LoopsVectorized;
  6487. // Add metadata to disable runtime unrolling a scalar loop when there are
  6488. // no runtime checks about strides and memory. A scalar loop that is
  6489. // rarely used is not worth unrolling.
  6490. if (!LB.areSafetyChecksAdded())
  6491. DisableRuntimeUnroll = true;
  6492. // Report the vectorization decision.
  6493. ORE->emit([&]() {
  6494. return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
  6495. L->getHeader())
  6496. << "vectorized loop (vectorization width: "
  6497. << NV("VectorizationFactor", VF.Width)
  6498. << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
  6499. });
  6500. }
  6501. Optional<MDNode *> RemainderLoopID =
  6502. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  6503. LLVMLoopVectorizeFollowupEpilogue});
  6504. if (RemainderLoopID.hasValue()) {
  6505. L->setLoopID(RemainderLoopID.getValue());
  6506. } else {
  6507. if (DisableRuntimeUnroll)
  6508. AddRuntimeUnrollDisableMetaData(L);
  6509. // Mark the loop as already vectorized to avoid vectorizing again.
  6510. Hints.setAlreadyVectorized();
  6511. }
  6512. LLVM_DEBUG(verifyFunction(*L->getHeader()->getParent()));
  6513. return true;
  6514. }
  6515. bool LoopVectorizePass::runImpl(
  6516. Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
  6517. DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
  6518. DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
  6519. std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
  6520. OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
  6521. SE = &SE_;
  6522. LI = &LI_;
  6523. TTI = &TTI_;
  6524. DT = &DT_;
  6525. BFI = &BFI_;
  6526. TLI = TLI_;
  6527. AA = &AA_;
  6528. AC = &AC_;
  6529. GetLAA = &GetLAA_;
  6530. DB = &DB_;
  6531. ORE = &ORE_;
  6532. PSI = PSI_;
  6533. // Don't attempt if
  6534. // 1. the target claims to have no vector registers, and
  6535. // 2. interleaving won't help ILP.
  6536. //
  6537. // The second condition is necessary because, even if the target has no
  6538. // vector registers, loop vectorization may still enable scalar
  6539. // interleaving.
  6540. if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
  6541. return false;
  6542. bool Changed = false;
  6543. // The vectorizer requires loops to be in simplified form.
  6544. // Since simplification may add new inner loops, it has to run before the
  6545. // legality and profitability checks. This means running the loop vectorizer
  6546. // will simplify all loops, regardless of whether anything end up being
  6547. // vectorized.
  6548. for (auto &L : *LI)
  6549. Changed |=
  6550. simplifyLoop(L, DT, LI, SE, AC, nullptr, false /* PreserveLCSSA */);
  6551. // Build up a worklist of inner-loops to vectorize. This is necessary as
  6552. // the act of vectorizing or partially unrolling a loop creates new loops
  6553. // and can invalidate iterators across the loops.
  6554. SmallVector<Loop *, 8> Worklist;
  6555. for (Loop *L : *LI)
  6556. collectSupportedLoops(*L, LI, ORE, Worklist);
  6557. LoopsAnalyzed += Worklist.size();
  6558. // Now walk the identified inner loops.
  6559. while (!Worklist.empty()) {
  6560. Loop *L = Worklist.pop_back_val();
  6561. // For the inner loops we actually process, form LCSSA to simplify the
  6562. // transform.
  6563. Changed |= formLCSSARecursively(*L, *DT, LI, SE);
  6564. Changed |= processLoop(L);
  6565. }
  6566. // Process each loop nest in the function.
  6567. return Changed;
  6568. }
  6569. PreservedAnalyses LoopVectorizePass::run(Function &F,
  6570. FunctionAnalysisManager &AM) {
  6571. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  6572. auto &LI = AM.getResult<LoopAnalysis>(F);
  6573. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  6574. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  6575. auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
  6576. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  6577. auto &AA = AM.getResult<AAManager>(F);
  6578. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  6579. auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
  6580. auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  6581. MemorySSA *MSSA = EnableMSSALoopDependency
  6582. ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
  6583. : nullptr;
  6584. auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
  6585. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  6586. [&](Loop &L) -> const LoopAccessInfo & {
  6587. LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, MSSA};
  6588. return LAM.getResult<LoopAccessAnalysis>(L, AR);
  6589. };
  6590. const ModuleAnalysisManager &MAM =
  6591. AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
  6592. ProfileSummaryInfo *PSI =
  6593. MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
  6594. bool Changed =
  6595. runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
  6596. if (!Changed)
  6597. return PreservedAnalyses::all();
  6598. PreservedAnalyses PA;
  6599. // We currently do not preserve loopinfo/dominator analyses with outer loop
  6600. // vectorization. Until this is addressed, mark these analyses as preserved
  6601. // only for non-VPlan-native path.
  6602. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  6603. if (!EnableVPlanNativePath) {
  6604. PA.preserve<LoopAnalysis>();
  6605. PA.preserve<DominatorTreeAnalysis>();
  6606. }
  6607. PA.preserve<BasicAA>();
  6608. PA.preserve<GlobalsAA>();
  6609. return PA;
  6610. }