LoopVectorize.cpp 309 KB

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