LoopVectorize.cpp 350 KB

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