LoopVectorize.cpp 304 KB

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