LoopVectorize.cpp 239 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210
  1. //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
  11. // and generates target-independent LLVM-IR.
  12. // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
  13. // of instructions in order to estimate the profitability of vectorization.
  14. //
  15. // The loop vectorizer combines consecutive loop iterations into a single
  16. // 'wide' iteration. After this transformation the index is incremented
  17. // by the SIMD vector width, and not by one.
  18. //
  19. // This pass has three parts:
  20. // 1. The main loop pass that drives the different parts.
  21. // 2. LoopVectorizationLegality - A unit that checks for the legality
  22. // of the vectorization.
  23. // 3. InnerLoopVectorizer - A unit that performs the actual
  24. // widening of instructions.
  25. // 4. LoopVectorizationCostModel - A unit that checks for the profitability
  26. // of vectorization. It decides on the optimal vector width, which
  27. // can be one, if vectorization is not profitable.
  28. //
  29. //===----------------------------------------------------------------------===//
  30. //
  31. // The reduction-variable vectorization is based on the paper:
  32. // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
  33. //
  34. // Variable uniformity checks are inspired by:
  35. // Karrenberg, R. and Hack, S. Whole Function Vectorization.
  36. //
  37. // The interleaved access vectorization is based on the paper:
  38. // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
  39. // Data for SIMD
  40. //
  41. // Other ideas/concepts are from:
  42. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  43. //
  44. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  45. // Vectorizing Compilers.
  46. //
  47. //===----------------------------------------------------------------------===//
  48. #include "llvm/Transforms/Vectorize.h"
  49. #include "llvm/ADT/DenseMap.h"
  50. #include "llvm/ADT/Hashing.h"
  51. #include "llvm/ADT/MapVector.h"
  52. #include "llvm/ADT/SetVector.h"
  53. #include "llvm/ADT/SmallPtrSet.h"
  54. #include "llvm/ADT/SmallSet.h"
  55. #include "llvm/ADT/SmallVector.h"
  56. #include "llvm/ADT/Statistic.h"
  57. #include "llvm/ADT/StringExtras.h"
  58. #include "llvm/Analysis/AliasAnalysis.h"
  59. #include "llvm/Analysis/BasicAliasAnalysis.h"
  60. #include "llvm/Analysis/AliasSetTracker.h"
  61. #include "llvm/Analysis/AssumptionCache.h"
  62. #include "llvm/Analysis/BlockFrequencyInfo.h"
  63. #include "llvm/Analysis/CodeMetrics.h"
  64. #include "llvm/Analysis/DemandedBits.h"
  65. #include "llvm/Analysis/GlobalsModRef.h"
  66. #include "llvm/Analysis/LoopAccessAnalysis.h"
  67. #include "llvm/Analysis/LoopInfo.h"
  68. #include "llvm/Analysis/LoopIterator.h"
  69. #include "llvm/Analysis/LoopPass.h"
  70. #include "llvm/Analysis/ScalarEvolution.h"
  71. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  72. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  73. #include "llvm/Analysis/TargetTransformInfo.h"
  74. #include "llvm/Analysis/ValueTracking.h"
  75. #include "llvm/IR/Constants.h"
  76. #include "llvm/IR/DataLayout.h"
  77. #include "llvm/IR/DebugInfo.h"
  78. #include "llvm/IR/DerivedTypes.h"
  79. #include "llvm/IR/DiagnosticInfo.h"
  80. #include "llvm/IR/Dominators.h"
  81. #include "llvm/IR/Function.h"
  82. #include "llvm/IR/IRBuilder.h"
  83. #include "llvm/IR/Instructions.h"
  84. #include "llvm/IR/IntrinsicInst.h"
  85. #include "llvm/IR/LLVMContext.h"
  86. #include "llvm/IR/Module.h"
  87. #include "llvm/IR/PatternMatch.h"
  88. #include "llvm/IR/Type.h"
  89. #include "llvm/IR/Value.h"
  90. #include "llvm/IR/ValueHandle.h"
  91. #include "llvm/IR/Verifier.h"
  92. #include "llvm/Pass.h"
  93. #include "llvm/Support/BranchProbability.h"
  94. #include "llvm/Support/CommandLine.h"
  95. #include "llvm/Support/Debug.h"
  96. #include "llvm/Support/raw_ostream.h"
  97. #include "llvm/Transforms/Scalar.h"
  98. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  99. #include "llvm/Transforms/Utils/Local.h"
  100. #include "llvm/Transforms/Utils/LoopVersioning.h"
  101. #include "llvm/Analysis/VectorUtils.h"
  102. #include "llvm/Transforms/Utils/LoopUtils.h"
  103. #include <algorithm>
  104. #include <functional>
  105. #include <map>
  106. #include <tuple>
  107. using namespace llvm;
  108. using namespace llvm::PatternMatch;
  109. #define LV_NAME "loop-vectorize"
  110. #define DEBUG_TYPE LV_NAME
  111. STATISTIC(LoopsVectorized, "Number of loops vectorized");
  112. STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
  113. static cl::opt<bool>
  114. EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
  115. cl::desc("Enable if-conversion during vectorization."));
  116. /// We don't vectorize loops with a known constant trip count below this number.
  117. static cl::opt<unsigned>
  118. TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
  119. cl::Hidden,
  120. cl::desc("Don't vectorize loops with a constant "
  121. "trip count that is smaller than this "
  122. "value."));
  123. static cl::opt<bool> MaximizeBandwidth(
  124. "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
  125. cl::desc("Maximize bandwidth when selecting vectorization factor which "
  126. "will be determined by the smallest type in loop."));
  127. /// This enables versioning on the strides of symbolically striding memory
  128. /// accesses in code like the following.
  129. /// for (i = 0; i < N; ++i)
  130. /// A[i * Stride1] += B[i * Stride2] ...
  131. ///
  132. /// Will be roughly translated to
  133. /// if (Stride1 == 1 && Stride2 == 1) {
  134. /// for (i = 0; i < N; i+=4)
  135. /// A[i:i+3] += ...
  136. /// } else
  137. /// ...
  138. static cl::opt<bool> EnableMemAccessVersioning(
  139. "enable-mem-access-versioning", cl::init(true), cl::Hidden,
  140. cl::desc("Enable symbolic stride memory access versioning"));
  141. static cl::opt<bool> EnableInterleavedMemAccesses(
  142. "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  143. cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
  144. /// Maximum factor for an interleaved memory access.
  145. static cl::opt<unsigned> MaxInterleaveGroupFactor(
  146. "max-interleave-group-factor", cl::Hidden,
  147. cl::desc("Maximum factor for an interleaved access group (default = 8)"),
  148. cl::init(8));
  149. /// We don't interleave loops with a known constant trip count below this
  150. /// number.
  151. static const unsigned TinyTripCountInterleaveThreshold = 128;
  152. static cl::opt<unsigned> ForceTargetNumScalarRegs(
  153. "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
  154. cl::desc("A flag that overrides the target's number of scalar registers."));
  155. static cl::opt<unsigned> ForceTargetNumVectorRegs(
  156. "force-target-num-vector-regs", cl::init(0), cl::Hidden,
  157. cl::desc("A flag that overrides the target's number of vector registers."));
  158. /// Maximum vectorization interleave count.
  159. static const unsigned MaxInterleaveFactor = 16;
  160. static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
  161. "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
  162. cl::desc("A flag that overrides the target's max interleave factor for "
  163. "scalar loops."));
  164. static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
  165. "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
  166. cl::desc("A flag that overrides the target's max interleave factor for "
  167. "vectorized loops."));
  168. static cl::opt<unsigned> ForceTargetInstructionCost(
  169. "force-target-instruction-cost", cl::init(0), cl::Hidden,
  170. cl::desc("A flag that overrides the target's expected cost for "
  171. "an instruction to a single constant value. Mostly "
  172. "useful for getting consistent testing."));
  173. static cl::opt<unsigned> SmallLoopCost(
  174. "small-loop-cost", cl::init(20), cl::Hidden,
  175. cl::desc(
  176. "The cost of a loop that is considered 'small' by the interleaver."));
  177. static cl::opt<bool> LoopVectorizeWithBlockFrequency(
  178. "loop-vectorize-with-block-frequency", cl::init(false), cl::Hidden,
  179. cl::desc("Enable the use of the block frequency analysis to access PGO "
  180. "heuristics minimizing code growth in cold regions and being more "
  181. "aggressive in hot regions."));
  182. // Runtime interleave loops for load/store throughput.
  183. static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
  184. "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
  185. cl::desc(
  186. "Enable runtime interleaving until load/store ports are saturated"));
  187. /// The number of stores in a loop that are allowed to need predication.
  188. static cl::opt<unsigned> NumberOfStoresToPredicate(
  189. "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
  190. cl::desc("Max number of stores to be predicated behind an if."));
  191. static cl::opt<bool> EnableIndVarRegisterHeur(
  192. "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
  193. cl::desc("Count the induction variable only once when interleaving"));
  194. static cl::opt<bool> EnableCondStoresVectorization(
  195. "enable-cond-stores-vec", cl::init(false), cl::Hidden,
  196. cl::desc("Enable if predication of stores during vectorization."));
  197. static cl::opt<unsigned> MaxNestedScalarReductionIC(
  198. "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
  199. cl::desc("The maximum interleave count to use when interleaving a scalar "
  200. "reduction in a nested loop."));
  201. static cl::opt<unsigned> PragmaVectorizeMemoryCheckThreshold(
  202. "pragma-vectorize-memory-check-threshold", cl::init(128), cl::Hidden,
  203. cl::desc("The maximum allowed number of runtime memory checks with a "
  204. "vectorize(enable) pragma."));
  205. static cl::opt<unsigned> VectorizeSCEVCheckThreshold(
  206. "vectorize-scev-check-threshold", cl::init(16), cl::Hidden,
  207. cl::desc("The maximum number of SCEV checks allowed."));
  208. static cl::opt<unsigned> PragmaVectorizeSCEVCheckThreshold(
  209. "pragma-vectorize-scev-check-threshold", cl::init(128), cl::Hidden,
  210. cl::desc("The maximum number of SCEV checks allowed with a "
  211. "vectorize(enable) pragma"));
  212. namespace {
  213. // Forward declarations.
  214. class LoopVectorizeHints;
  215. class LoopVectorizationLegality;
  216. class LoopVectorizationCostModel;
  217. class LoopVectorizationRequirements;
  218. /// \brief This modifies LoopAccessReport to initialize message with
  219. /// loop-vectorizer-specific part.
  220. class VectorizationReport : public LoopAccessReport {
  221. public:
  222. VectorizationReport(Instruction *I = nullptr)
  223. : LoopAccessReport("loop not vectorized: ", I) {}
  224. /// \brief This allows promotion of the loop-access analysis report into the
  225. /// loop-vectorizer report. It modifies the message to add the
  226. /// loop-vectorizer-specific part of the message.
  227. explicit VectorizationReport(const LoopAccessReport &R)
  228. : LoopAccessReport(Twine("loop not vectorized: ") + R.str(),
  229. R.getInstr()) {}
  230. };
  231. /// A helper function for converting Scalar types to vector types.
  232. /// If the incoming type is void, we return void. If the VF is 1, we return
  233. /// the scalar type.
  234. static Type* ToVectorTy(Type *Scalar, unsigned VF) {
  235. if (Scalar->isVoidTy() || VF == 1)
  236. return Scalar;
  237. return VectorType::get(Scalar, VF);
  238. }
  239. /// A helper function that returns GEP instruction and knows to skip a
  240. /// 'bitcast'. The 'bitcast' may be skipped if the source and the destination
  241. /// pointee types of the 'bitcast' have the same size.
  242. /// For example:
  243. /// bitcast double** %var to i64* - can be skipped
  244. /// bitcast double** %var to i8* - can not
  245. static GetElementPtrInst *getGEPInstruction(Value *Ptr) {
  246. if (isa<GetElementPtrInst>(Ptr))
  247. return cast<GetElementPtrInst>(Ptr);
  248. if (isa<BitCastInst>(Ptr) &&
  249. isa<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0))) {
  250. Type *BitcastTy = Ptr->getType();
  251. Type *GEPTy = cast<BitCastInst>(Ptr)->getSrcTy();
  252. if (!isa<PointerType>(BitcastTy) || !isa<PointerType>(GEPTy))
  253. return nullptr;
  254. Type *Pointee1Ty = cast<PointerType>(BitcastTy)->getPointerElementType();
  255. Type *Pointee2Ty = cast<PointerType>(GEPTy)->getPointerElementType();
  256. const DataLayout &DL = cast<BitCastInst>(Ptr)->getModule()->getDataLayout();
  257. if (DL.getTypeSizeInBits(Pointee1Ty) == DL.getTypeSizeInBits(Pointee2Ty))
  258. return cast<GetElementPtrInst>(cast<BitCastInst>(Ptr)->getOperand(0));
  259. }
  260. return nullptr;
  261. }
  262. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  263. /// block to a specified vectorization factor (VF).
  264. /// This class performs the widening of scalars into vectors, or multiple
  265. /// scalars. This class also implements the following features:
  266. /// * It inserts an epilogue loop for handling loops that don't have iteration
  267. /// counts that are known to be a multiple of the vectorization factor.
  268. /// * It handles the code generation for reduction variables.
  269. /// * Scalarization (implementation using scalars) of un-vectorizable
  270. /// instructions.
  271. /// InnerLoopVectorizer does not perform any vectorization-legality
  272. /// checks, and relies on the caller to check for the different legality
  273. /// aspects. The InnerLoopVectorizer relies on the
  274. /// LoopVectorizationLegality class to provide information about the induction
  275. /// and reduction variables that were found to a given vectorization factor.
  276. class InnerLoopVectorizer {
  277. public:
  278. InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  279. LoopInfo *LI, DominatorTree *DT,
  280. const TargetLibraryInfo *TLI,
  281. const TargetTransformInfo *TTI, AssumptionCache *AC,
  282. unsigned VecWidth, unsigned UnrollFactor)
  283. : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
  284. AC(AC), VF(VecWidth), UF(UnrollFactor),
  285. Builder(PSE.getSE()->getContext()), Induction(nullptr),
  286. OldInduction(nullptr), WidenMap(UnrollFactor), TripCount(nullptr),
  287. VectorTripCount(nullptr), Legal(nullptr), AddedSafetyChecks(false) {}
  288. // Perform the actual loop widening (vectorization).
  289. // MinimumBitWidths maps scalar integer values to the smallest bitwidth they
  290. // can be validly truncated to. The cost model has assumed this truncation
  291. // will happen when vectorizing.
  292. void vectorize(LoopVectorizationLegality *L,
  293. MapVector<Instruction*,uint64_t> MinimumBitWidths) {
  294. MinBWs = MinimumBitWidths;
  295. Legal = L;
  296. // Create a new empty loop. Unlink the old loop and connect the new one.
  297. createEmptyLoop();
  298. // Widen each instruction in the old loop to a new one in the new loop.
  299. // Use the Legality module to find the induction and reduction variables.
  300. vectorizeLoop();
  301. }
  302. // Return true if any runtime check is added.
  303. bool IsSafetyChecksAdded() {
  304. return AddedSafetyChecks;
  305. }
  306. virtual ~InnerLoopVectorizer() {}
  307. protected:
  308. /// A small list of PHINodes.
  309. typedef SmallVector<PHINode*, 4> PhiVector;
  310. /// When we unroll loops we have multiple vector values for each scalar.
  311. /// This data structure holds the unrolled and vectorized values that
  312. /// originated from one scalar instruction.
  313. typedef SmallVector<Value*, 2> VectorParts;
  314. // When we if-convert we need to create edge masks. We have to cache values
  315. // so that we don't end up with exponential recursion/IR.
  316. typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
  317. VectorParts> EdgeMaskCache;
  318. /// Create an empty loop, based on the loop ranges of the old loop.
  319. void createEmptyLoop();
  320. /// Create a new induction variable inside L.
  321. PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
  322. Value *Step, Instruction *DL);
  323. /// Copy and widen the instructions from the old loop.
  324. virtual void vectorizeLoop();
  325. /// Fix a first-order recurrence. This is the second phase of vectorizing
  326. /// this phi node.
  327. void fixFirstOrderRecurrence(PHINode *Phi);
  328. /// \brief The Loop exit block may have single value PHI nodes where the
  329. /// incoming value is 'Undef'. While vectorizing we only handled real values
  330. /// that were defined inside the loop. Here we fix the 'undef case'.
  331. /// See PR14725.
  332. void fixLCSSAPHIs();
  333. /// Shrinks vector element sizes based on information in "MinBWs".
  334. void truncateToMinimalBitwidths();
  335. /// A helper function that computes the predicate of the block BB, assuming
  336. /// that the header block of the loop is set to True. It returns the *entry*
  337. /// mask for the block BB.
  338. VectorParts createBlockInMask(BasicBlock *BB);
  339. /// A helper function that computes the predicate of the edge between SRC
  340. /// and DST.
  341. VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
  342. /// A helper function to vectorize a single BB within the innermost loop.
  343. void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
  344. /// Vectorize a single PHINode in a block. This method handles the induction
  345. /// variable canonicalization. It supports both VF = 1 for unrolled loops and
  346. /// arbitrary length vectors.
  347. void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
  348. unsigned UF, unsigned VF, PhiVector *PV);
  349. /// Insert the new loop to the loop hierarchy and pass manager
  350. /// and update the analysis passes.
  351. void updateAnalysis();
  352. /// This instruction is un-vectorizable. Implement it as a sequence
  353. /// of scalars. If \p IfPredicateStore is true we need to 'hide' each
  354. /// scalarized instruction behind an if block predicated on the control
  355. /// dependence of the instruction.
  356. virtual void scalarizeInstruction(Instruction *Instr,
  357. bool IfPredicateStore=false);
  358. /// Vectorize Load and Store instructions,
  359. virtual void vectorizeMemoryInstruction(Instruction *Instr);
  360. /// Create a broadcast instruction. This method generates a broadcast
  361. /// instruction (shuffle) for loop invariant values and for the induction
  362. /// value. If this is the induction variable then we extend it to N, N+1, ...
  363. /// this is needed because each iteration in the loop corresponds to a SIMD
  364. /// element.
  365. virtual Value *getBroadcastInstrs(Value *V);
  366. /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
  367. /// to each vector element of Val. The sequence starts at StartIndex.
  368. virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step);
  369. /// When we go over instructions in the basic block we rely on previous
  370. /// values within the current basic block or on loop invariant values.
  371. /// When we widen (vectorize) values we place them in the map. If the values
  372. /// are not within the map, they have to be loop invariant, so we simply
  373. /// broadcast them into a vector.
  374. VectorParts &getVectorValue(Value *V);
  375. /// Try to vectorize the interleaved access group that \p Instr belongs to.
  376. void vectorizeInterleaveGroup(Instruction *Instr);
  377. /// Generate a shuffle sequence that will reverse the vector Vec.
  378. virtual Value *reverseVector(Value *Vec);
  379. /// Returns (and creates if needed) the original loop trip count.
  380. Value *getOrCreateTripCount(Loop *NewLoop);
  381. /// Returns (and creates if needed) the trip count of the widened loop.
  382. Value *getOrCreateVectorTripCount(Loop *NewLoop);
  383. /// Emit a bypass check to see if the trip count would overflow, or we
  384. /// wouldn't have enough iterations to execute one vector loop.
  385. void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
  386. /// Emit a bypass check to see if the vector trip count is nonzero.
  387. void emitVectorLoopEnteredCheck(Loop *L, BasicBlock *Bypass);
  388. /// Emit a bypass check to see if all of the SCEV assumptions we've
  389. /// had to make are correct.
  390. void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
  391. /// Emit bypass checks to check any memory assumptions we may have made.
  392. void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
  393. /// Add additional metadata to \p To that was not present on \p Orig.
  394. ///
  395. /// Currently this is used to add the noalias annotations based on the
  396. /// inserted memchecks. Use this for instructions that are *cloned* into the
  397. /// vector loop.
  398. void addNewMetadata(Instruction *To, const Instruction *Orig);
  399. /// Add metadata from one instruction to another.
  400. ///
  401. /// This includes both the original MDs from \p From and additional ones (\see
  402. /// addNewMetadata). Use this for *newly created* instructions in the vector
  403. /// loop.
  404. void addMetadata(Instruction *To, const Instruction *From);
  405. /// \brief Similar to the previous function but it adds the metadata to a
  406. /// vector of instructions.
  407. void addMetadata(SmallVectorImpl<Value *> &To, const Instruction *From);
  408. /// This is a helper class that holds the vectorizer state. It maps scalar
  409. /// instructions to vector instructions. When the code is 'unrolled' then
  410. /// then a single scalar value is mapped to multiple vector parts. The parts
  411. /// are stored in the VectorPart type.
  412. struct ValueMap {
  413. /// C'tor. UnrollFactor controls the number of vectors ('parts') that
  414. /// are mapped.
  415. ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
  416. /// \return True if 'Key' is saved in the Value Map.
  417. bool has(Value *Key) const { return MapStorage.count(Key); }
  418. /// Initializes a new entry in the map. Sets all of the vector parts to the
  419. /// save value in 'Val'.
  420. /// \return A reference to a vector with splat values.
  421. VectorParts &splat(Value *Key, Value *Val) {
  422. VectorParts &Entry = MapStorage[Key];
  423. Entry.assign(UF, Val);
  424. return Entry;
  425. }
  426. ///\return A reference to the value that is stored at 'Key'.
  427. VectorParts &get(Value *Key) {
  428. VectorParts &Entry = MapStorage[Key];
  429. if (Entry.empty())
  430. Entry.resize(UF);
  431. assert(Entry.size() == UF);
  432. return Entry;
  433. }
  434. private:
  435. /// The unroll factor. Each entry in the map stores this number of vector
  436. /// elements.
  437. unsigned UF;
  438. /// Map storage. We use std::map and not DenseMap because insertions to a
  439. /// dense map invalidates its iterators.
  440. std::map<Value *, VectorParts> MapStorage;
  441. };
  442. /// The original loop.
  443. Loop *OrigLoop;
  444. /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
  445. /// dynamic knowledge to simplify SCEV expressions and converts them to a
  446. /// more usable form.
  447. PredicatedScalarEvolution &PSE;
  448. /// Loop Info.
  449. LoopInfo *LI;
  450. /// Dominator Tree.
  451. DominatorTree *DT;
  452. /// Alias Analysis.
  453. AliasAnalysis *AA;
  454. /// Target Library Info.
  455. const TargetLibraryInfo *TLI;
  456. /// Target Transform Info.
  457. const TargetTransformInfo *TTI;
  458. /// Assumption Cache.
  459. AssumptionCache *AC;
  460. /// \brief LoopVersioning. It's only set up (non-null) if memchecks were
  461. /// used.
  462. ///
  463. /// This is currently only used to add no-alias metadata based on the
  464. /// memchecks. The actually versioning is performed manually.
  465. std::unique_ptr<LoopVersioning> LVer;
  466. /// The vectorization SIMD factor to use. Each vector will have this many
  467. /// vector elements.
  468. unsigned VF;
  469. protected:
  470. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  471. /// many different vector instructions.
  472. unsigned UF;
  473. /// The builder that we use
  474. IRBuilder<> Builder;
  475. // --- Vectorization state ---
  476. /// The vector-loop preheader.
  477. BasicBlock *LoopVectorPreHeader;
  478. /// The scalar-loop preheader.
  479. BasicBlock *LoopScalarPreHeader;
  480. /// Middle Block between the vector and the scalar.
  481. BasicBlock *LoopMiddleBlock;
  482. ///The ExitBlock of the scalar loop.
  483. BasicBlock *LoopExitBlock;
  484. ///The vector loop body.
  485. SmallVector<BasicBlock *, 4> LoopVectorBody;
  486. ///The scalar loop body.
  487. BasicBlock *LoopScalarBody;
  488. /// A list of all bypass blocks. The first block is the entry of the loop.
  489. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  490. /// The new Induction variable which was added to the new block.
  491. PHINode *Induction;
  492. /// The induction variable of the old basic block.
  493. PHINode *OldInduction;
  494. /// Maps scalars to widened vectors.
  495. ValueMap WidenMap;
  496. /// Store instructions that should be predicated, as a pair
  497. /// <StoreInst, Predicate>
  498. SmallVector<std::pair<StoreInst*,Value*>, 4> PredicatedStores;
  499. EdgeMaskCache MaskCache;
  500. /// Trip count of the original loop.
  501. Value *TripCount;
  502. /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
  503. Value *VectorTripCount;
  504. /// Map of scalar integer values to the smallest bitwidth they can be legally
  505. /// represented as. The vector equivalents of these values should be truncated
  506. /// to this type.
  507. MapVector<Instruction*,uint64_t> MinBWs;
  508. LoopVectorizationLegality *Legal;
  509. // Record whether runtime check is added.
  510. bool AddedSafetyChecks;
  511. };
  512. class InnerLoopUnroller : public InnerLoopVectorizer {
  513. public:
  514. InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  515. LoopInfo *LI, DominatorTree *DT,
  516. const TargetLibraryInfo *TLI,
  517. const TargetTransformInfo *TTI, AssumptionCache *AC,
  518. unsigned UnrollFactor)
  519. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, 1,
  520. UnrollFactor) {}
  521. private:
  522. void scalarizeInstruction(Instruction *Instr,
  523. bool IfPredicateStore = false) override;
  524. void vectorizeMemoryInstruction(Instruction *Instr) override;
  525. Value *getBroadcastInstrs(Value *V) override;
  526. Value *getStepVector(Value *Val, int StartIdx, Value *Step) override;
  527. Value *reverseVector(Value *Vec) override;
  528. };
  529. /// \brief Look for a meaningful debug location on the instruction or it's
  530. /// operands.
  531. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  532. if (!I)
  533. return I;
  534. DebugLoc Empty;
  535. if (I->getDebugLoc() != Empty)
  536. return I;
  537. for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
  538. if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
  539. if (OpInst->getDebugLoc() != Empty)
  540. return OpInst;
  541. }
  542. return I;
  543. }
  544. /// \brief Set the debug location in the builder using the debug location in the
  545. /// instruction.
  546. static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
  547. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
  548. B.SetCurrentDebugLocation(Inst->getDebugLoc());
  549. else
  550. B.SetCurrentDebugLocation(DebugLoc());
  551. }
  552. #ifndef NDEBUG
  553. /// \return string containing a file name and a line # for the given loop.
  554. static std::string getDebugLocString(const Loop *L) {
  555. std::string Result;
  556. if (L) {
  557. raw_string_ostream OS(Result);
  558. if (const DebugLoc LoopDbgLoc = L->getStartLoc())
  559. LoopDbgLoc.print(OS);
  560. else
  561. // Just print the module name.
  562. OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
  563. OS.flush();
  564. }
  565. return Result;
  566. }
  567. #endif
  568. /// \brief Propagate known metadata from one instruction to another.
  569. static void propagateMetadata(Instruction *To, const Instruction *From) {
  570. SmallVector<std::pair<unsigned, MDNode *>, 4> Metadata;
  571. From->getAllMetadataOtherThanDebugLoc(Metadata);
  572. for (auto M : Metadata) {
  573. unsigned Kind = M.first;
  574. // These are safe to transfer (this is safe for TBAA, even when we
  575. // if-convert, because should that metadata have had a control dependency
  576. // on the condition, and thus actually aliased with some other
  577. // non-speculated memory access when the condition was false, this would be
  578. // caught by the runtime overlap checks).
  579. if (Kind != LLVMContext::MD_tbaa &&
  580. Kind != LLVMContext::MD_alias_scope &&
  581. Kind != LLVMContext::MD_noalias &&
  582. Kind != LLVMContext::MD_fpmath &&
  583. Kind != LLVMContext::MD_nontemporal)
  584. continue;
  585. To->setMetadata(Kind, M.second);
  586. }
  587. }
  588. void InnerLoopVectorizer::addNewMetadata(Instruction *To,
  589. const Instruction *Orig) {
  590. // If the loop was versioned with memchecks, add the corresponding no-alias
  591. // metadata.
  592. if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
  593. LVer->annotateInstWithNoAlias(To, Orig);
  594. }
  595. void InnerLoopVectorizer::addMetadata(Instruction *To,
  596. const Instruction *From) {
  597. propagateMetadata(To, From);
  598. addNewMetadata(To, From);
  599. }
  600. void InnerLoopVectorizer::addMetadata(SmallVectorImpl<Value *> &To,
  601. const Instruction *From) {
  602. for (Value *V : To)
  603. if (Instruction *I = dyn_cast<Instruction>(V))
  604. addMetadata(I, From);
  605. }
  606. /// \brief The group of interleaved loads/stores sharing the same stride and
  607. /// close to each other.
  608. ///
  609. /// Each member in this group has an index starting from 0, and the largest
  610. /// index should be less than interleaved factor, which is equal to the absolute
  611. /// value of the access's stride.
  612. ///
  613. /// E.g. An interleaved load group of factor 4:
  614. /// for (unsigned i = 0; i < 1024; i+=4) {
  615. /// a = A[i]; // Member of index 0
  616. /// b = A[i+1]; // Member of index 1
  617. /// d = A[i+3]; // Member of index 3
  618. /// ...
  619. /// }
  620. ///
  621. /// An interleaved store group of factor 4:
  622. /// for (unsigned i = 0; i < 1024; i+=4) {
  623. /// ...
  624. /// A[i] = a; // Member of index 0
  625. /// A[i+1] = b; // Member of index 1
  626. /// A[i+2] = c; // Member of index 2
  627. /// A[i+3] = d; // Member of index 3
  628. /// }
  629. ///
  630. /// Note: the interleaved load group could have gaps (missing members), but
  631. /// the interleaved store group doesn't allow gaps.
  632. class InterleaveGroup {
  633. public:
  634. InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
  635. : Align(Align), SmallestKey(0), LargestKey(0), InsertPos(Instr) {
  636. assert(Align && "The alignment should be non-zero");
  637. Factor = std::abs(Stride);
  638. assert(Factor > 1 && "Invalid interleave factor");
  639. Reverse = Stride < 0;
  640. Members[0] = Instr;
  641. }
  642. bool isReverse() const { return Reverse; }
  643. unsigned getFactor() const { return Factor; }
  644. unsigned getAlignment() const { return Align; }
  645. unsigned getNumMembers() const { return Members.size(); }
  646. /// \brief Try to insert a new member \p Instr with index \p Index and
  647. /// alignment \p NewAlign. The index is related to the leader and it could be
  648. /// negative if it is the new leader.
  649. ///
  650. /// \returns false if the instruction doesn't belong to the group.
  651. bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
  652. assert(NewAlign && "The new member's alignment should be non-zero");
  653. int Key = Index + SmallestKey;
  654. // Skip if there is already a member with the same index.
  655. if (Members.count(Key))
  656. return false;
  657. if (Key > LargestKey) {
  658. // The largest index is always less than the interleave factor.
  659. if (Index >= static_cast<int>(Factor))
  660. return false;
  661. LargestKey = Key;
  662. } else if (Key < SmallestKey) {
  663. // The largest index is always less than the interleave factor.
  664. if (LargestKey - Key >= static_cast<int>(Factor))
  665. return false;
  666. SmallestKey = Key;
  667. }
  668. // It's always safe to select the minimum alignment.
  669. Align = std::min(Align, NewAlign);
  670. Members[Key] = Instr;
  671. return true;
  672. }
  673. /// \brief Get the member with the given index \p Index
  674. ///
  675. /// \returns nullptr if contains no such member.
  676. Instruction *getMember(unsigned Index) const {
  677. int Key = SmallestKey + Index;
  678. if (!Members.count(Key))
  679. return nullptr;
  680. return Members.find(Key)->second;
  681. }
  682. /// \brief Get the index for the given member. Unlike the key in the member
  683. /// map, the index starts from 0.
  684. unsigned getIndex(Instruction *Instr) const {
  685. for (auto I : Members)
  686. if (I.second == Instr)
  687. return I.first - SmallestKey;
  688. llvm_unreachable("InterleaveGroup contains no such member");
  689. }
  690. Instruction *getInsertPos() const { return InsertPos; }
  691. void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
  692. private:
  693. unsigned Factor; // Interleave Factor.
  694. bool Reverse;
  695. unsigned Align;
  696. DenseMap<int, Instruction *> Members;
  697. int SmallestKey;
  698. int LargestKey;
  699. // To avoid breaking dependences, vectorized instructions of an interleave
  700. // group should be inserted at either the first load or the last store in
  701. // program order.
  702. //
  703. // E.g. %even = load i32 // Insert Position
  704. // %add = add i32 %even // Use of %even
  705. // %odd = load i32
  706. //
  707. // store i32 %even
  708. // %odd = add i32 // Def of %odd
  709. // store i32 %odd // Insert Position
  710. Instruction *InsertPos;
  711. };
  712. /// \brief Drive the analysis of interleaved memory accesses in the loop.
  713. ///
  714. /// Use this class to analyze interleaved accesses only when we can vectorize
  715. /// a loop. Otherwise it's meaningless to do analysis as the vectorization
  716. /// on interleaved accesses is unsafe.
  717. ///
  718. /// The analysis collects interleave groups and records the relationships
  719. /// between the member and the group in a map.
  720. class InterleavedAccessInfo {
  721. public:
  722. InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
  723. DominatorTree *DT)
  724. : PSE(PSE), TheLoop(L), DT(DT) {}
  725. ~InterleavedAccessInfo() {
  726. SmallSet<InterleaveGroup *, 4> DelSet;
  727. // Avoid releasing a pointer twice.
  728. for (auto &I : InterleaveGroupMap)
  729. DelSet.insert(I.second);
  730. for (auto *Ptr : DelSet)
  731. delete Ptr;
  732. }
  733. /// \brief Analyze the interleaved accesses and collect them in interleave
  734. /// groups. Substitute symbolic strides using \p Strides.
  735. void analyzeInterleaving(const ValueToValueMap &Strides);
  736. /// \brief Check if \p Instr belongs to any interleave group.
  737. bool isInterleaved(Instruction *Instr) const {
  738. return InterleaveGroupMap.count(Instr);
  739. }
  740. /// \brief Get the interleave group that \p Instr belongs to.
  741. ///
  742. /// \returns nullptr if doesn't have such group.
  743. InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
  744. if (InterleaveGroupMap.count(Instr))
  745. return InterleaveGroupMap.find(Instr)->second;
  746. return nullptr;
  747. }
  748. private:
  749. /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
  750. /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
  751. /// The interleaved access analysis can also add new predicates (for example
  752. /// by versioning strides of pointers).
  753. PredicatedScalarEvolution &PSE;
  754. Loop *TheLoop;
  755. DominatorTree *DT;
  756. /// Holds the relationships between the members and the interleave group.
  757. DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
  758. /// \brief The descriptor for a strided memory access.
  759. struct StrideDescriptor {
  760. StrideDescriptor(int Stride, const SCEV *Scev, unsigned Size,
  761. unsigned Align)
  762. : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
  763. StrideDescriptor() : Stride(0), Scev(nullptr), Size(0), Align(0) {}
  764. int Stride; // The access's stride. It is negative for a reverse access.
  765. const SCEV *Scev; // The scalar expression of this access
  766. unsigned Size; // The size of the memory object.
  767. unsigned Align; // The alignment of this access.
  768. };
  769. /// \brief Create a new interleave group with the given instruction \p Instr,
  770. /// stride \p Stride and alignment \p Align.
  771. ///
  772. /// \returns the newly created interleave group.
  773. InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
  774. unsigned Align) {
  775. assert(!InterleaveGroupMap.count(Instr) &&
  776. "Already in an interleaved access group");
  777. InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
  778. return InterleaveGroupMap[Instr];
  779. }
  780. /// \brief Release the group and remove all the relationships.
  781. void releaseGroup(InterleaveGroup *Group) {
  782. for (unsigned i = 0; i < Group->getFactor(); i++)
  783. if (Instruction *Member = Group->getMember(i))
  784. InterleaveGroupMap.erase(Member);
  785. delete Group;
  786. }
  787. /// \brief Collect all the accesses with a constant stride in program order.
  788. void collectConstStridedAccesses(
  789. MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
  790. const ValueToValueMap &Strides);
  791. };
  792. /// Utility class for getting and setting loop vectorizer hints in the form
  793. /// of loop metadata.
  794. /// This class keeps a number of loop annotations locally (as member variables)
  795. /// and can, upon request, write them back as metadata on the loop. It will
  796. /// initially scan the loop for existing metadata, and will update the local
  797. /// values based on information in the loop.
  798. /// We cannot write all values to metadata, as the mere presence of some info,
  799. /// for example 'force', means a decision has been made. So, we need to be
  800. /// careful NOT to add them if the user hasn't specifically asked so.
  801. class LoopVectorizeHints {
  802. enum HintKind {
  803. HK_WIDTH,
  804. HK_UNROLL,
  805. HK_FORCE
  806. };
  807. /// Hint - associates name and validation with the hint value.
  808. struct Hint {
  809. const char * Name;
  810. unsigned Value; // This may have to change for non-numeric values.
  811. HintKind Kind;
  812. Hint(const char * Name, unsigned Value, HintKind Kind)
  813. : Name(Name), Value(Value), Kind(Kind) { }
  814. bool validate(unsigned Val) {
  815. switch (Kind) {
  816. case HK_WIDTH:
  817. return isPowerOf2_32(Val) && Val <= VectorizerParams::MaxVectorWidth;
  818. case HK_UNROLL:
  819. return isPowerOf2_32(Val) && Val <= MaxInterleaveFactor;
  820. case HK_FORCE:
  821. return (Val <= 1);
  822. }
  823. return false;
  824. }
  825. };
  826. /// Vectorization width.
  827. Hint Width;
  828. /// Vectorization interleave factor.
  829. Hint Interleave;
  830. /// Vectorization forced
  831. Hint Force;
  832. /// Return the loop metadata prefix.
  833. static StringRef Prefix() { return "llvm.loop."; }
  834. /// True if there is any unsafe math in the loop.
  835. bool PotentiallyUnsafe;
  836. public:
  837. enum ForceKind {
  838. FK_Undefined = -1, ///< Not selected.
  839. FK_Disabled = 0, ///< Forcing disabled.
  840. FK_Enabled = 1, ///< Forcing enabled.
  841. };
  842. LoopVectorizeHints(const Loop *L, bool DisableInterleaving)
  843. : Width("vectorize.width", VectorizerParams::VectorizationFactor,
  844. HK_WIDTH),
  845. Interleave("interleave.count", DisableInterleaving, HK_UNROLL),
  846. Force("vectorize.enable", FK_Undefined, HK_FORCE),
  847. PotentiallyUnsafe(false), TheLoop(L) {
  848. // Populate values with existing loop metadata.
  849. getHintsFromMetadata();
  850. // force-vector-interleave overrides DisableInterleaving.
  851. if (VectorizerParams::isInterleaveForced())
  852. Interleave.Value = VectorizerParams::VectorizationInterleave;
  853. DEBUG(if (DisableInterleaving && Interleave.Value == 1) dbgs()
  854. << "LV: Interleaving disabled by the pass manager\n");
  855. }
  856. /// Mark the loop L as already vectorized by setting the width to 1.
  857. void setAlreadyVectorized() {
  858. Width.Value = Interleave.Value = 1;
  859. Hint Hints[] = {Width, Interleave};
  860. writeHintsToMetadata(Hints);
  861. }
  862. bool allowVectorization(Function *F, Loop *L, bool AlwaysVectorize) const {
  863. if (getForce() == LoopVectorizeHints::FK_Disabled) {
  864. DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
  865. emitOptimizationRemarkAnalysis(F->getContext(),
  866. vectorizeAnalysisPassName(), *F,
  867. L->getStartLoc(), emitRemark());
  868. return false;
  869. }
  870. if (!AlwaysVectorize && getForce() != LoopVectorizeHints::FK_Enabled) {
  871. DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
  872. emitOptimizationRemarkAnalysis(F->getContext(),
  873. vectorizeAnalysisPassName(), *F,
  874. L->getStartLoc(), emitRemark());
  875. return false;
  876. }
  877. if (getWidth() == 1 && getInterleave() == 1) {
  878. // FIXME: Add a separate metadata to indicate when the loop has already
  879. // been vectorized instead of setting width and count to 1.
  880. DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
  881. // FIXME: Add interleave.disable metadata. This will allow
  882. // vectorize.disable to be used without disabling the pass and errors
  883. // to differentiate between disabled vectorization and a width of 1.
  884. emitOptimizationRemarkAnalysis(
  885. F->getContext(), vectorizeAnalysisPassName(), *F, L->getStartLoc(),
  886. "loop not vectorized: vectorization and interleaving are explicitly "
  887. "disabled, or vectorize width and interleave count are both set to "
  888. "1");
  889. return false;
  890. }
  891. return true;
  892. }
  893. /// Dumps all the hint information.
  894. std::string emitRemark() const {
  895. VectorizationReport R;
  896. if (Force.Value == LoopVectorizeHints::FK_Disabled)
  897. R << "vectorization is explicitly disabled";
  898. else {
  899. R << "use -Rpass-analysis=loop-vectorize for more info";
  900. if (Force.Value == LoopVectorizeHints::FK_Enabled) {
  901. R << " (Force=true";
  902. if (Width.Value != 0)
  903. R << ", Vector Width=" << Width.Value;
  904. if (Interleave.Value != 0)
  905. R << ", Interleave Count=" << Interleave.Value;
  906. R << ")";
  907. }
  908. }
  909. return R.str();
  910. }
  911. unsigned getWidth() const { return Width.Value; }
  912. unsigned getInterleave() const { return Interleave.Value; }
  913. enum ForceKind getForce() const { return (ForceKind)Force.Value; }
  914. const char *vectorizeAnalysisPassName() const {
  915. // If hints are provided that don't disable vectorization use the
  916. // AlwaysPrint pass name to force the frontend to print the diagnostic.
  917. if (getWidth() == 1)
  918. return LV_NAME;
  919. if (getForce() == LoopVectorizeHints::FK_Disabled)
  920. return LV_NAME;
  921. if (getForce() == LoopVectorizeHints::FK_Undefined && getWidth() == 0)
  922. return LV_NAME;
  923. return DiagnosticInfo::AlwaysPrint;
  924. }
  925. bool allowReordering() const {
  926. // When enabling loop hints are provided we allow the vectorizer to change
  927. // the order of operations that is given by the scalar loop. This is not
  928. // enabled by default because can be unsafe or inefficient. For example,
  929. // reordering floating-point operations will change the way round-off
  930. // error accumulates in the loop.
  931. return getForce() == LoopVectorizeHints::FK_Enabled || getWidth() > 1;
  932. }
  933. bool isPotentiallyUnsafe() const {
  934. // Avoid FP vectorization if the target is unsure about proper support.
  935. // This may be related to the SIMD unit in the target not handling
  936. // IEEE 754 FP ops properly, or bad single-to-double promotions.
  937. // Otherwise, a sequence of vectorized loops, even without reduction,
  938. // could lead to different end results on the destination vectors.
  939. return getForce() != LoopVectorizeHints::FK_Enabled && PotentiallyUnsafe;
  940. }
  941. void setPotentiallyUnsafe() {
  942. PotentiallyUnsafe = true;
  943. }
  944. private:
  945. /// Find hints specified in the loop metadata and update local values.
  946. void getHintsFromMetadata() {
  947. MDNode *LoopID = TheLoop->getLoopID();
  948. if (!LoopID)
  949. return;
  950. // First operand should refer to the loop id itself.
  951. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  952. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  953. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  954. const MDString *S = nullptr;
  955. SmallVector<Metadata *, 4> Args;
  956. // The expected hint is either a MDString or a MDNode with the first
  957. // operand a MDString.
  958. if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
  959. if (!MD || MD->getNumOperands() == 0)
  960. continue;
  961. S = dyn_cast<MDString>(MD->getOperand(0));
  962. for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
  963. Args.push_back(MD->getOperand(i));
  964. } else {
  965. S = dyn_cast<MDString>(LoopID->getOperand(i));
  966. assert(Args.size() == 0 && "too many arguments for MDString");
  967. }
  968. if (!S)
  969. continue;
  970. // Check if the hint starts with the loop metadata prefix.
  971. StringRef Name = S->getString();
  972. if (Args.size() == 1)
  973. setHint(Name, Args[0]);
  974. }
  975. }
  976. /// Checks string hint with one operand and set value if valid.
  977. void setHint(StringRef Name, Metadata *Arg) {
  978. if (!Name.startswith(Prefix()))
  979. return;
  980. Name = Name.substr(Prefix().size(), StringRef::npos);
  981. const ConstantInt *C = mdconst::dyn_extract<ConstantInt>(Arg);
  982. if (!C) return;
  983. unsigned Val = C->getZExtValue();
  984. Hint *Hints[] = {&Width, &Interleave, &Force};
  985. for (auto H : Hints) {
  986. if (Name == H->Name) {
  987. if (H->validate(Val))
  988. H->Value = Val;
  989. else
  990. DEBUG(dbgs() << "LV: ignoring invalid hint '" << Name << "'\n");
  991. break;
  992. }
  993. }
  994. }
  995. /// Create a new hint from name / value pair.
  996. MDNode *createHintMetadata(StringRef Name, unsigned V) const {
  997. LLVMContext &Context = TheLoop->getHeader()->getContext();
  998. Metadata *MDs[] = {MDString::get(Context, Name),
  999. ConstantAsMetadata::get(
  1000. ConstantInt::get(Type::getInt32Ty(Context), V))};
  1001. return MDNode::get(Context, MDs);
  1002. }
  1003. /// Matches metadata with hint name.
  1004. bool matchesHintMetadataName(MDNode *Node, ArrayRef<Hint> HintTypes) {
  1005. MDString* Name = dyn_cast<MDString>(Node->getOperand(0));
  1006. if (!Name)
  1007. return false;
  1008. for (auto H : HintTypes)
  1009. if (Name->getString().endswith(H.Name))
  1010. return true;
  1011. return false;
  1012. }
  1013. /// Sets current hints into loop metadata, keeping other values intact.
  1014. void writeHintsToMetadata(ArrayRef<Hint> HintTypes) {
  1015. if (HintTypes.size() == 0)
  1016. return;
  1017. // Reserve the first element to LoopID (see below).
  1018. SmallVector<Metadata *, 4> MDs(1);
  1019. // If the loop already has metadata, then ignore the existing operands.
  1020. MDNode *LoopID = TheLoop->getLoopID();
  1021. if (LoopID) {
  1022. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  1023. MDNode *Node = cast<MDNode>(LoopID->getOperand(i));
  1024. // If node in update list, ignore old value.
  1025. if (!matchesHintMetadataName(Node, HintTypes))
  1026. MDs.push_back(Node);
  1027. }
  1028. }
  1029. // Now, add the missing hints.
  1030. for (auto H : HintTypes)
  1031. MDs.push_back(createHintMetadata(Twine(Prefix(), H.Name).str(), H.Value));
  1032. // Replace current metadata node with new one.
  1033. LLVMContext &Context = TheLoop->getHeader()->getContext();
  1034. MDNode *NewLoopID = MDNode::get(Context, MDs);
  1035. // Set operand 0 to refer to the loop id itself.
  1036. NewLoopID->replaceOperandWith(0, NewLoopID);
  1037. TheLoop->setLoopID(NewLoopID);
  1038. }
  1039. /// The loop these hints belong to.
  1040. const Loop *TheLoop;
  1041. };
  1042. static void emitAnalysisDiag(const Function *TheFunction, const Loop *TheLoop,
  1043. const LoopVectorizeHints &Hints,
  1044. const LoopAccessReport &Message) {
  1045. const char *Name = Hints.vectorizeAnalysisPassName();
  1046. LoopAccessReport::emitAnalysis(Message, TheFunction, TheLoop, Name);
  1047. }
  1048. static void emitMissedWarning(Function *F, Loop *L,
  1049. const LoopVectorizeHints &LH) {
  1050. emitOptimizationRemarkMissed(F->getContext(), LV_NAME, *F, L->getStartLoc(),
  1051. LH.emitRemark());
  1052. if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
  1053. if (LH.getWidth() != 1)
  1054. emitLoopVectorizeWarning(
  1055. F->getContext(), *F, L->getStartLoc(),
  1056. "failed explicitly specified loop vectorization");
  1057. else if (LH.getInterleave() != 1)
  1058. emitLoopInterleaveWarning(
  1059. F->getContext(), *F, L->getStartLoc(),
  1060. "failed explicitly specified loop interleaving");
  1061. }
  1062. }
  1063. /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
  1064. /// to what vectorization factor.
  1065. /// This class does not look at the profitability of vectorization, only the
  1066. /// legality. This class has two main kinds of checks:
  1067. /// * Memory checks - The code in canVectorizeMemory checks if vectorization
  1068. /// will change the order of memory accesses in a way that will change the
  1069. /// correctness of the program.
  1070. /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
  1071. /// checks for a number of different conditions, such as the availability of a
  1072. /// single induction variable, that all types are supported and vectorize-able,
  1073. /// etc. This code reflects the capabilities of InnerLoopVectorizer.
  1074. /// This class is also used by InnerLoopVectorizer for identifying
  1075. /// induction variable and the different reduction variables.
  1076. class LoopVectorizationLegality {
  1077. public:
  1078. LoopVectorizationLegality(Loop *L, PredicatedScalarEvolution &PSE,
  1079. DominatorTree *DT, TargetLibraryInfo *TLI,
  1080. AliasAnalysis *AA, Function *F,
  1081. const TargetTransformInfo *TTI,
  1082. LoopAccessAnalysis *LAA,
  1083. LoopVectorizationRequirements *R,
  1084. LoopVectorizeHints *H)
  1085. : NumPredStores(0), TheLoop(L), PSE(PSE), TLI(TLI), TheFunction(F),
  1086. TTI(TTI), DT(DT), LAA(LAA), LAI(nullptr), InterleaveInfo(PSE, L, DT),
  1087. Induction(nullptr), WidestIndTy(nullptr), HasFunNoNaNAttr(false),
  1088. Requirements(R), Hints(H) {}
  1089. /// ReductionList contains the reduction descriptors for all
  1090. /// of the reductions that were found in the loop.
  1091. typedef DenseMap<PHINode *, RecurrenceDescriptor> ReductionList;
  1092. /// InductionList saves induction variables and maps them to the
  1093. /// induction descriptor.
  1094. typedef MapVector<PHINode*, InductionDescriptor> InductionList;
  1095. /// RecurrenceSet contains the phi nodes that are recurrences other than
  1096. /// inductions and reductions.
  1097. typedef SmallPtrSet<const PHINode *, 8> RecurrenceSet;
  1098. /// Returns true if it is legal to vectorize this loop.
  1099. /// This does not mean that it is profitable to vectorize this
  1100. /// loop, only that it is legal to do so.
  1101. bool canVectorize();
  1102. /// Returns the Induction variable.
  1103. PHINode *getInduction() { return Induction; }
  1104. /// Returns the reduction variables found in the loop.
  1105. ReductionList *getReductionVars() { return &Reductions; }
  1106. /// Returns the induction variables found in the loop.
  1107. InductionList *getInductionVars() { return &Inductions; }
  1108. /// Return the first-order recurrences found in the loop.
  1109. RecurrenceSet *getFirstOrderRecurrences() { return &FirstOrderRecurrences; }
  1110. /// Returns the widest induction type.
  1111. Type *getWidestInductionType() { return WidestIndTy; }
  1112. /// Returns True if V is an induction variable in this loop.
  1113. bool isInductionVariable(const Value *V);
  1114. /// Returns True if PN is a reduction variable in this loop.
  1115. bool isReductionVariable(PHINode *PN) { return Reductions.count(PN); }
  1116. /// Returns True if Phi is a first-order recurrence in this loop.
  1117. bool isFirstOrderRecurrence(const PHINode *Phi);
  1118. /// Return true if the block BB needs to be predicated in order for the loop
  1119. /// to be vectorized.
  1120. bool blockNeedsPredication(BasicBlock *BB);
  1121. /// Check if this pointer is consecutive when vectorizing. This happens
  1122. /// when the last index of the GEP is the induction variable, or that the
  1123. /// pointer itself is an induction variable.
  1124. /// This check allows us to vectorize A[idx] into a wide load/store.
  1125. /// Returns:
  1126. /// 0 - Stride is unknown or non-consecutive.
  1127. /// 1 - Address is consecutive.
  1128. /// -1 - Address is consecutive, and decreasing.
  1129. int isConsecutivePtr(Value *Ptr);
  1130. /// Returns true if the value V is uniform within the loop.
  1131. bool isUniform(Value *V);
  1132. /// Returns true if this instruction will remain scalar after vectorization.
  1133. bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
  1134. /// Returns the information that we collected about runtime memory check.
  1135. const RuntimePointerChecking *getRuntimePointerChecking() const {
  1136. return LAI->getRuntimePointerChecking();
  1137. }
  1138. const LoopAccessInfo *getLAI() const {
  1139. return LAI;
  1140. }
  1141. /// \brief Check if \p Instr belongs to any interleaved access group.
  1142. bool isAccessInterleaved(Instruction *Instr) {
  1143. return InterleaveInfo.isInterleaved(Instr);
  1144. }
  1145. /// \brief Get the interleaved access group that \p Instr belongs to.
  1146. const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
  1147. return InterleaveInfo.getInterleaveGroup(Instr);
  1148. }
  1149. unsigned getMaxSafeDepDistBytes() { return LAI->getMaxSafeDepDistBytes(); }
  1150. bool hasStride(Value *V) { return StrideSet.count(V); }
  1151. bool mustCheckStrides() { return !StrideSet.empty(); }
  1152. SmallPtrSet<Value *, 8>::iterator strides_begin() {
  1153. return StrideSet.begin();
  1154. }
  1155. SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
  1156. /// Returns true if the target machine supports masked store operation
  1157. /// for the given \p DataType and kind of access to \p Ptr.
  1158. bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
  1159. return isConsecutivePtr(Ptr) && TTI->isLegalMaskedStore(DataType);
  1160. }
  1161. /// Returns true if the target machine supports masked load operation
  1162. /// for the given \p DataType and kind of access to \p Ptr.
  1163. bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
  1164. return isConsecutivePtr(Ptr) && TTI->isLegalMaskedLoad(DataType);
  1165. }
  1166. /// Returns true if the target machine supports masked scatter operation
  1167. /// for the given \p DataType.
  1168. bool isLegalMaskedScatter(Type *DataType) {
  1169. return TTI->isLegalMaskedScatter(DataType);
  1170. }
  1171. /// Returns true if the target machine supports masked gather operation
  1172. /// for the given \p DataType.
  1173. bool isLegalMaskedGather(Type *DataType) {
  1174. return TTI->isLegalMaskedGather(DataType);
  1175. }
  1176. /// Returns true if vector representation of the instruction \p I
  1177. /// requires mask.
  1178. bool isMaskRequired(const Instruction* I) {
  1179. return (MaskedOp.count(I) != 0);
  1180. }
  1181. unsigned getNumStores() const {
  1182. return LAI->getNumStores();
  1183. }
  1184. unsigned getNumLoads() const {
  1185. return LAI->getNumLoads();
  1186. }
  1187. unsigned getNumPredStores() const {
  1188. return NumPredStores;
  1189. }
  1190. private:
  1191. /// Check if a single basic block loop is vectorizable.
  1192. /// At this point we know that this is a loop with a constant trip count
  1193. /// and we only need to check individual instructions.
  1194. bool canVectorizeInstrs();
  1195. /// When we vectorize loops we may change the order in which
  1196. /// we read and write from memory. This method checks if it is
  1197. /// legal to vectorize the code, considering only memory constrains.
  1198. /// Returns true if the loop is vectorizable
  1199. bool canVectorizeMemory();
  1200. /// Return true if we can vectorize this loop using the IF-conversion
  1201. /// transformation.
  1202. bool canVectorizeWithIfConvert();
  1203. /// Collect the variables that need to stay uniform after vectorization.
  1204. void collectLoopUniforms();
  1205. /// Return true if all of the instructions in the block can be speculatively
  1206. /// executed. \p SafePtrs is a list of addresses that are known to be legal
  1207. /// and we know that we can read from them without segfault.
  1208. bool blockCanBePredicated(BasicBlock *BB, SmallPtrSetImpl<Value *> &SafePtrs);
  1209. /// \brief Collect memory access with loop invariant strides.
  1210. ///
  1211. /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
  1212. /// invariant.
  1213. void collectStridedAccess(Value *LoadOrStoreInst);
  1214. /// Report an analysis message to assist the user in diagnosing loops that are
  1215. /// not vectorized. These are handled as LoopAccessReport rather than
  1216. /// VectorizationReport because the << operator of VectorizationReport returns
  1217. /// LoopAccessReport.
  1218. void emitAnalysis(const LoopAccessReport &Message) const {
  1219. emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
  1220. }
  1221. unsigned NumPredStores;
  1222. /// The loop that we evaluate.
  1223. Loop *TheLoop;
  1224. /// A wrapper around ScalarEvolution used to add runtime SCEV checks.
  1225. /// Applies dynamic knowledge to simplify SCEV expressions in the context
  1226. /// of existing SCEV assumptions. The analysis will also add a minimal set
  1227. /// of new predicates if this is required to enable vectorization and
  1228. /// unrolling.
  1229. PredicatedScalarEvolution &PSE;
  1230. /// Target Library Info.
  1231. TargetLibraryInfo *TLI;
  1232. /// Parent function
  1233. Function *TheFunction;
  1234. /// Target Transform Info
  1235. const TargetTransformInfo *TTI;
  1236. /// Dominator Tree.
  1237. DominatorTree *DT;
  1238. // LoopAccess analysis.
  1239. LoopAccessAnalysis *LAA;
  1240. // And the loop-accesses info corresponding to this loop. This pointer is
  1241. // null until canVectorizeMemory sets it up.
  1242. const LoopAccessInfo *LAI;
  1243. /// The interleave access information contains groups of interleaved accesses
  1244. /// with the same stride and close to each other.
  1245. InterleavedAccessInfo InterleaveInfo;
  1246. // --- vectorization state --- //
  1247. /// Holds the integer induction variable. This is the counter of the
  1248. /// loop.
  1249. PHINode *Induction;
  1250. /// Holds the reduction variables.
  1251. ReductionList Reductions;
  1252. /// Holds all of the induction variables that we found in the loop.
  1253. /// Notice that inductions don't need to start at zero and that induction
  1254. /// variables can be pointers.
  1255. InductionList Inductions;
  1256. /// Holds the phi nodes that are first-order recurrences.
  1257. RecurrenceSet FirstOrderRecurrences;
  1258. /// Holds the widest induction type encountered.
  1259. Type *WidestIndTy;
  1260. /// Allowed outside users. This holds the reduction
  1261. /// vars which can be accessed from outside the loop.
  1262. SmallPtrSet<Value*, 4> AllowedExit;
  1263. /// This set holds the variables which are known to be uniform after
  1264. /// vectorization.
  1265. SmallPtrSet<Instruction*, 4> Uniforms;
  1266. /// Can we assume the absence of NaNs.
  1267. bool HasFunNoNaNAttr;
  1268. /// Vectorization requirements that will go through late-evaluation.
  1269. LoopVectorizationRequirements *Requirements;
  1270. /// Used to emit an analysis of any legality issues.
  1271. LoopVectorizeHints *Hints;
  1272. ValueToValueMap Strides;
  1273. SmallPtrSet<Value *, 8> StrideSet;
  1274. /// While vectorizing these instructions we have to generate a
  1275. /// call to the appropriate masked intrinsic
  1276. SmallPtrSet<const Instruction *, 8> MaskedOp;
  1277. };
  1278. /// LoopVectorizationCostModel - estimates the expected speedups due to
  1279. /// vectorization.
  1280. /// In many cases vectorization is not profitable. This can happen because of
  1281. /// a number of reasons. In this class we mainly attempt to predict the
  1282. /// expected speedup/slowdowns due to the supported instruction set. We use the
  1283. /// TargetTransformInfo to query the different backends for the cost of
  1284. /// different operations.
  1285. class LoopVectorizationCostModel {
  1286. public:
  1287. LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
  1288. LoopVectorizationLegality *Legal,
  1289. const TargetTransformInfo &TTI,
  1290. const TargetLibraryInfo *TLI,
  1291. DemandedBits *DB, AssumptionCache *AC,
  1292. const Function *F, const LoopVectorizeHints *Hints,
  1293. SmallPtrSetImpl<const Value *> &ValuesToIgnore)
  1294. : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
  1295. TheFunction(F), Hints(Hints), ValuesToIgnore(ValuesToIgnore) {}
  1296. /// Information about vectorization costs
  1297. struct VectorizationFactor {
  1298. unsigned Width; // Vector width with best cost
  1299. unsigned Cost; // Cost of the loop with that width
  1300. };
  1301. /// \return The most profitable vectorization factor and the cost of that VF.
  1302. /// This method checks every power of two up to VF. If UserVF is not ZERO
  1303. /// then this vectorization factor will be selected if vectorization is
  1304. /// possible.
  1305. VectorizationFactor selectVectorizationFactor(bool OptForSize);
  1306. /// \return The size (in bits) of the smallest and widest types in the code
  1307. /// that needs to be vectorized. We ignore values that remain scalar such as
  1308. /// 64 bit loop indices.
  1309. std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
  1310. /// \return The desired interleave count.
  1311. /// If interleave count has been specified by metadata it will be returned.
  1312. /// Otherwise, the interleave count is computed and returned. VF and LoopCost
  1313. /// are the selected vectorization factor and the cost of the selected VF.
  1314. unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
  1315. unsigned LoopCost);
  1316. /// \return The most profitable unroll factor.
  1317. /// This method finds the best unroll-factor based on register pressure and
  1318. /// other parameters. VF and LoopCost are the selected vectorization factor
  1319. /// and the cost of the selected VF.
  1320. unsigned computeInterleaveCount(bool OptForSize, unsigned VF,
  1321. unsigned LoopCost);
  1322. /// \brief A struct that represents some properties of the register usage
  1323. /// of a loop.
  1324. struct RegisterUsage {
  1325. /// Holds the number of loop invariant values that are used in the loop.
  1326. unsigned LoopInvariantRegs;
  1327. /// Holds the maximum number of concurrent live intervals in the loop.
  1328. unsigned MaxLocalUsers;
  1329. /// Holds the number of instructions in the loop.
  1330. unsigned NumInstructions;
  1331. };
  1332. /// \return Returns information about the register usages of the loop for the
  1333. /// given vectorization factors.
  1334. SmallVector<RegisterUsage, 8>
  1335. calculateRegisterUsage(const SmallVector<unsigned, 8> &VFs);
  1336. private:
  1337. /// The vectorization cost is a combination of the cost itself and a boolean
  1338. /// indicating whether any of the contributing operations will actually operate on
  1339. /// vector values after type legalization in the backend. If this latter value is
  1340. /// false, then all operations will be scalarized (i.e. no vectorization has
  1341. /// actually taken place).
  1342. typedef std::pair<unsigned, bool> VectorizationCostTy;
  1343. /// Returns the expected execution cost. The unit of the cost does
  1344. /// not matter because we use the 'cost' units to compare different
  1345. /// vector widths. The cost that is returned is *not* normalized by
  1346. /// the factor width.
  1347. VectorizationCostTy expectedCost(unsigned VF);
  1348. /// Returns the execution time cost of an instruction for a given vector
  1349. /// width. Vector width of one means scalar.
  1350. VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
  1351. /// The cost-computation logic from getInstructionCost which provides
  1352. /// the vector type as an output parameter.
  1353. unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
  1354. /// Returns whether the instruction is a load or store and will be a emitted
  1355. /// as a vector operation.
  1356. bool isConsecutiveLoadOrStore(Instruction *I);
  1357. /// Report an analysis message to assist the user in diagnosing loops that are
  1358. /// not vectorized. These are handled as LoopAccessReport rather than
  1359. /// VectorizationReport because the << operator of VectorizationReport returns
  1360. /// LoopAccessReport.
  1361. void emitAnalysis(const LoopAccessReport &Message) const {
  1362. emitAnalysisDiag(TheFunction, TheLoop, *Hints, Message);
  1363. }
  1364. public:
  1365. /// Map of scalar integer values to the smallest bitwidth they can be legally
  1366. /// represented as. The vector equivalents of these values should be truncated
  1367. /// to this type.
  1368. MapVector<Instruction*,uint64_t> MinBWs;
  1369. /// The loop that we evaluate.
  1370. Loop *TheLoop;
  1371. /// Scev analysis.
  1372. ScalarEvolution *SE;
  1373. /// Loop Info analysis.
  1374. LoopInfo *LI;
  1375. /// Vectorization legality.
  1376. LoopVectorizationLegality *Legal;
  1377. /// Vector target information.
  1378. const TargetTransformInfo &TTI;
  1379. /// Target Library Info.
  1380. const TargetLibraryInfo *TLI;
  1381. /// Demanded bits analysis
  1382. DemandedBits *DB;
  1383. const Function *TheFunction;
  1384. // Loop Vectorize Hint.
  1385. const LoopVectorizeHints *Hints;
  1386. // Values to ignore in the cost model.
  1387. const SmallPtrSetImpl<const Value *> &ValuesToIgnore;
  1388. };
  1389. /// \brief This holds vectorization requirements that must be verified late in
  1390. /// the process. The requirements are set by legalize and costmodel. Once
  1391. /// vectorization has been determined to be possible and profitable the
  1392. /// requirements can be verified by looking for metadata or compiler options.
  1393. /// For example, some loops require FP commutativity which is only allowed if
  1394. /// vectorization is explicitly specified or if the fast-math compiler option
  1395. /// has been provided.
  1396. /// Late evaluation of these requirements allows helpful diagnostics to be
  1397. /// composed that tells the user what need to be done to vectorize the loop. For
  1398. /// example, by specifying #pragma clang loop vectorize or -ffast-math. Late
  1399. /// evaluation should be used only when diagnostics can generated that can be
  1400. /// followed by a non-expert user.
  1401. class LoopVectorizationRequirements {
  1402. public:
  1403. LoopVectorizationRequirements()
  1404. : NumRuntimePointerChecks(0), UnsafeAlgebraInst(nullptr) {}
  1405. void addUnsafeAlgebraInst(Instruction *I) {
  1406. // First unsafe algebra instruction.
  1407. if (!UnsafeAlgebraInst)
  1408. UnsafeAlgebraInst = I;
  1409. }
  1410. void addRuntimePointerChecks(unsigned Num) { NumRuntimePointerChecks = Num; }
  1411. bool doesNotMeet(Function *F, Loop *L, const LoopVectorizeHints &Hints) {
  1412. const char *Name = Hints.vectorizeAnalysisPassName();
  1413. bool Failed = false;
  1414. if (UnsafeAlgebraInst && !Hints.allowReordering()) {
  1415. emitOptimizationRemarkAnalysisFPCommute(
  1416. F->getContext(), Name, *F, UnsafeAlgebraInst->getDebugLoc(),
  1417. VectorizationReport() << "cannot prove it is safe to reorder "
  1418. "floating-point operations");
  1419. Failed = true;
  1420. }
  1421. // Test if runtime memcheck thresholds are exceeded.
  1422. bool PragmaThresholdReached =
  1423. NumRuntimePointerChecks > PragmaVectorizeMemoryCheckThreshold;
  1424. bool ThresholdReached =
  1425. NumRuntimePointerChecks > VectorizerParams::RuntimeMemoryCheckThreshold;
  1426. if ((ThresholdReached && !Hints.allowReordering()) ||
  1427. PragmaThresholdReached) {
  1428. emitOptimizationRemarkAnalysisAliasing(
  1429. F->getContext(), Name, *F, L->getStartLoc(),
  1430. VectorizationReport()
  1431. << "cannot prove it is safe to reorder memory operations");
  1432. DEBUG(dbgs() << "LV: Too many memory checks needed.\n");
  1433. Failed = true;
  1434. }
  1435. return Failed;
  1436. }
  1437. private:
  1438. unsigned NumRuntimePointerChecks;
  1439. Instruction *UnsafeAlgebraInst;
  1440. };
  1441. static void addInnerLoop(Loop &L, SmallVectorImpl<Loop *> &V) {
  1442. if (L.empty())
  1443. return V.push_back(&L);
  1444. for (Loop *InnerL : L)
  1445. addInnerLoop(*InnerL, V);
  1446. }
  1447. /// The LoopVectorize Pass.
  1448. struct LoopVectorize : public FunctionPass {
  1449. /// Pass identification, replacement for typeid
  1450. static char ID;
  1451. explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
  1452. : FunctionPass(ID),
  1453. DisableUnrolling(NoUnrolling),
  1454. AlwaysVectorize(AlwaysVectorize) {
  1455. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  1456. }
  1457. ScalarEvolution *SE;
  1458. LoopInfo *LI;
  1459. TargetTransformInfo *TTI;
  1460. DominatorTree *DT;
  1461. BlockFrequencyInfo *BFI;
  1462. TargetLibraryInfo *TLI;
  1463. DemandedBits *DB;
  1464. AliasAnalysis *AA;
  1465. AssumptionCache *AC;
  1466. LoopAccessAnalysis *LAA;
  1467. bool DisableUnrolling;
  1468. bool AlwaysVectorize;
  1469. BlockFrequency ColdEntryFreq;
  1470. bool runOnFunction(Function &F) override {
  1471. if (skipFunction(F))
  1472. return false;
  1473. SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1474. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1475. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1476. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1477. BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
  1478. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1479. TLI = TLIP ? &TLIP->getTLI() : nullptr;
  1480. AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1481. AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1482. LAA = &getAnalysis<LoopAccessAnalysis>();
  1483. DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  1484. // Compute some weights outside of the loop over the loops. Compute this
  1485. // using a BranchProbability to re-use its scaling math.
  1486. const BranchProbability ColdProb(1, 5); // 20%
  1487. ColdEntryFreq = BlockFrequency(BFI->getEntryFreq()) * ColdProb;
  1488. // Don't attempt if
  1489. // 1. the target claims to have no vector registers, and
  1490. // 2. interleaving won't help ILP.
  1491. //
  1492. // The second condition is necessary because, even if the target has no
  1493. // vector registers, loop vectorization may still enable scalar
  1494. // interleaving.
  1495. if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
  1496. return false;
  1497. // Build up a worklist of inner-loops to vectorize. This is necessary as
  1498. // the act of vectorizing or partially unrolling a loop creates new loops
  1499. // and can invalidate iterators across the loops.
  1500. SmallVector<Loop *, 8> Worklist;
  1501. for (Loop *L : *LI)
  1502. addInnerLoop(*L, Worklist);
  1503. LoopsAnalyzed += Worklist.size();
  1504. // Now walk the identified inner loops.
  1505. bool Changed = false;
  1506. while (!Worklist.empty())
  1507. Changed |= processLoop(Worklist.pop_back_val());
  1508. // Process each loop nest in the function.
  1509. return Changed;
  1510. }
  1511. static void AddRuntimeUnrollDisableMetaData(Loop *L) {
  1512. SmallVector<Metadata *, 4> MDs;
  1513. // Reserve first location for self reference to the LoopID metadata node.
  1514. MDs.push_back(nullptr);
  1515. bool IsUnrollMetadata = false;
  1516. MDNode *LoopID = L->getLoopID();
  1517. if (LoopID) {
  1518. // First find existing loop unrolling disable metadata.
  1519. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  1520. MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  1521. if (MD) {
  1522. const MDString *S = dyn_cast<MDString>(MD->getOperand(0));
  1523. IsUnrollMetadata =
  1524. S && S->getString().startswith("llvm.loop.unroll.disable");
  1525. }
  1526. MDs.push_back(LoopID->getOperand(i));
  1527. }
  1528. }
  1529. if (!IsUnrollMetadata) {
  1530. // Add runtime unroll disable metadata.
  1531. LLVMContext &Context = L->getHeader()->getContext();
  1532. SmallVector<Metadata *, 1> DisableOperands;
  1533. DisableOperands.push_back(
  1534. MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
  1535. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  1536. MDs.push_back(DisableNode);
  1537. MDNode *NewLoopID = MDNode::get(Context, MDs);
  1538. // Set operand 0 to refer to the loop id itself.
  1539. NewLoopID->replaceOperandWith(0, NewLoopID);
  1540. L->setLoopID(NewLoopID);
  1541. }
  1542. }
  1543. bool processLoop(Loop *L) {
  1544. assert(L->empty() && "Only process inner loops.");
  1545. #ifndef NDEBUG
  1546. const std::string DebugLocStr = getDebugLocString(L);
  1547. #endif /* NDEBUG */
  1548. DEBUG(dbgs() << "\nLV: Checking a loop in \""
  1549. << L->getHeader()->getParent()->getName() << "\" from "
  1550. << DebugLocStr << "\n");
  1551. LoopVectorizeHints Hints(L, DisableUnrolling);
  1552. DEBUG(dbgs() << "LV: Loop hints:"
  1553. << " force="
  1554. << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
  1555. ? "disabled"
  1556. : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
  1557. ? "enabled"
  1558. : "?")) << " width=" << Hints.getWidth()
  1559. << " unroll=" << Hints.getInterleave() << "\n");
  1560. // Function containing loop
  1561. Function *F = L->getHeader()->getParent();
  1562. // Looking at the diagnostic output is the only way to determine if a loop
  1563. // was vectorized (other than looking at the IR or machine code), so it
  1564. // is important to generate an optimization remark for each loop. Most of
  1565. // these messages are generated by emitOptimizationRemarkAnalysis. Remarks
  1566. // generated by emitOptimizationRemark and emitOptimizationRemarkMissed are
  1567. // less verbose reporting vectorized loops and unvectorized loops that may
  1568. // benefit from vectorization, respectively.
  1569. if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
  1570. DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
  1571. return false;
  1572. }
  1573. // Check the loop for a trip count threshold:
  1574. // do not vectorize loops with a tiny trip count.
  1575. const unsigned TC = SE->getSmallConstantTripCount(L);
  1576. if (TC > 0u && TC < TinyTripCountVectorThreshold) {
  1577. DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
  1578. << "This loop is not worth vectorizing.");
  1579. if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
  1580. DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
  1581. else {
  1582. DEBUG(dbgs() << "\n");
  1583. emitAnalysisDiag(F, L, Hints, VectorizationReport()
  1584. << "vectorization is not beneficial "
  1585. "and is not explicitly forced");
  1586. return false;
  1587. }
  1588. }
  1589. PredicatedScalarEvolution PSE(*SE, *L);
  1590. // Check if it is legal to vectorize the loop.
  1591. LoopVectorizationRequirements Requirements;
  1592. LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, TTI, LAA,
  1593. &Requirements, &Hints);
  1594. if (!LVL.canVectorize()) {
  1595. DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  1596. emitMissedWarning(F, L, Hints);
  1597. return false;
  1598. }
  1599. // Collect values we want to ignore in the cost model. This includes
  1600. // type-promoting instructions we identified during reduction detection.
  1601. SmallPtrSet<const Value *, 32> ValuesToIgnore;
  1602. CodeMetrics::collectEphemeralValues(L, AC, ValuesToIgnore);
  1603. for (auto &Reduction : *LVL.getReductionVars()) {
  1604. RecurrenceDescriptor &RedDes = Reduction.second;
  1605. SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
  1606. ValuesToIgnore.insert(Casts.begin(), Casts.end());
  1607. }
  1608. // Use the cost model.
  1609. LoopVectorizationCostModel CM(L, PSE.getSE(), LI, &LVL, *TTI, TLI, DB, AC,
  1610. F, &Hints, ValuesToIgnore);
  1611. // Check the function attributes to find out if this function should be
  1612. // optimized for size.
  1613. bool OptForSize = Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  1614. F->optForSize();
  1615. // Compute the weighted frequency of this loop being executed and see if it
  1616. // is less than 20% of the function entry baseline frequency. Note that we
  1617. // always have a canonical loop here because we think we *can* vectorize.
  1618. // FIXME: This is hidden behind a flag due to pervasive problems with
  1619. // exactly what block frequency models.
  1620. if (LoopVectorizeWithBlockFrequency) {
  1621. BlockFrequency LoopEntryFreq = BFI->getBlockFreq(L->getLoopPreheader());
  1622. if (Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  1623. LoopEntryFreq < ColdEntryFreq)
  1624. OptForSize = true;
  1625. }
  1626. // Check the function attributes to see if implicit floats are allowed.
  1627. // FIXME: This check doesn't seem possibly correct -- what if the loop is
  1628. // an integer loop and the vector instructions selected are purely integer
  1629. // vector instructions?
  1630. if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
  1631. DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
  1632. "attribute is used.\n");
  1633. emitAnalysisDiag(
  1634. F, L, Hints,
  1635. VectorizationReport()
  1636. << "loop not vectorized due to NoImplicitFloat attribute");
  1637. emitMissedWarning(F, L, Hints);
  1638. return false;
  1639. }
  1640. // Check if the target supports potentially unsafe FP vectorization.
  1641. // FIXME: Add a check for the type of safety issue (denormal, signaling)
  1642. // for the target we're vectorizing for, to make sure none of the
  1643. // additional fp-math flags can help.
  1644. if (Hints.isPotentiallyUnsafe() &&
  1645. TTI->isFPVectorizationPotentiallyUnsafe()) {
  1646. DEBUG(dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
  1647. emitAnalysisDiag(
  1648. F, L, Hints,
  1649. VectorizationReport()
  1650. << "loop not vectorized due to unsafe FP support.");
  1651. emitMissedWarning(F, L, Hints);
  1652. return false;
  1653. }
  1654. // Select the optimal vectorization factor.
  1655. const LoopVectorizationCostModel::VectorizationFactor VF =
  1656. CM.selectVectorizationFactor(OptForSize);
  1657. // Select the interleave count.
  1658. unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
  1659. // Get user interleave count.
  1660. unsigned UserIC = Hints.getInterleave();
  1661. // Identify the diagnostic messages that should be produced.
  1662. std::string VecDiagMsg, IntDiagMsg;
  1663. bool VectorizeLoop = true, InterleaveLoop = true;
  1664. if (Requirements.doesNotMeet(F, L, Hints)) {
  1665. DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
  1666. "requirements.\n");
  1667. emitMissedWarning(F, L, Hints);
  1668. return false;
  1669. }
  1670. if (VF.Width == 1) {
  1671. DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  1672. VecDiagMsg =
  1673. "the cost-model indicates that vectorization is not beneficial";
  1674. VectorizeLoop = false;
  1675. }
  1676. if (IC == 1 && UserIC <= 1) {
  1677. // Tell the user interleaving is not beneficial.
  1678. DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
  1679. IntDiagMsg =
  1680. "the cost-model indicates that interleaving is not beneficial";
  1681. InterleaveLoop = false;
  1682. if (UserIC == 1)
  1683. IntDiagMsg +=
  1684. " and is explicitly disabled or interleave count is set to 1";
  1685. } else if (IC > 1 && UserIC == 1) {
  1686. // Tell the user interleaving is beneficial, but it explicitly disabled.
  1687. DEBUG(dbgs()
  1688. << "LV: Interleaving is beneficial but is explicitly disabled.");
  1689. IntDiagMsg = "the cost-model indicates that interleaving is beneficial "
  1690. "but is explicitly disabled or interleave count is set to 1";
  1691. InterleaveLoop = false;
  1692. }
  1693. // Override IC if user provided an interleave count.
  1694. IC = UserIC > 0 ? UserIC : IC;
  1695. // Emit diagnostic messages, if any.
  1696. const char *VAPassName = Hints.vectorizeAnalysisPassName();
  1697. if (!VectorizeLoop && !InterleaveLoop) {
  1698. // Do not vectorize or interleaving the loop.
  1699. emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
  1700. L->getStartLoc(), VecDiagMsg);
  1701. emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
  1702. L->getStartLoc(), IntDiagMsg);
  1703. return false;
  1704. } else if (!VectorizeLoop && InterleaveLoop) {
  1705. DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  1706. emitOptimizationRemarkAnalysis(F->getContext(), VAPassName, *F,
  1707. L->getStartLoc(), VecDiagMsg);
  1708. } else if (VectorizeLoop && !InterleaveLoop) {
  1709. DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
  1710. << DebugLocStr << '\n');
  1711. emitOptimizationRemarkAnalysis(F->getContext(), LV_NAME, *F,
  1712. L->getStartLoc(), IntDiagMsg);
  1713. } else if (VectorizeLoop && InterleaveLoop) {
  1714. DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width << ") in "
  1715. << DebugLocStr << '\n');
  1716. DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  1717. }
  1718. if (!VectorizeLoop) {
  1719. assert(IC > 1 && "interleave count should not be 1 or 0");
  1720. // If we decided that it is not legal to vectorize the loop then
  1721. // interleave it.
  1722. InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, IC);
  1723. Unroller.vectorize(&LVL, CM.MinBWs);
  1724. emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
  1725. Twine("interleaved loop (interleaved count: ") +
  1726. Twine(IC) + ")");
  1727. } else {
  1728. // If we decided that it is *legal* to vectorize the loop then do it.
  1729. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, VF.Width, IC);
  1730. LB.vectorize(&LVL, CM.MinBWs);
  1731. ++LoopsVectorized;
  1732. // Add metadata to disable runtime unrolling scalar loop when there's no
  1733. // runtime check about strides and memory. Because at this situation,
  1734. // scalar loop is rarely used not worthy to be unrolled.
  1735. if (!LB.IsSafetyChecksAdded())
  1736. AddRuntimeUnrollDisableMetaData(L);
  1737. // Report the vectorization decision.
  1738. emitOptimizationRemark(F->getContext(), LV_NAME, *F, L->getStartLoc(),
  1739. Twine("vectorized loop (vectorization width: ") +
  1740. Twine(VF.Width) + ", interleaved count: " +
  1741. Twine(IC) + ")");
  1742. }
  1743. // Mark the loop as already vectorized to avoid vectorizing again.
  1744. Hints.setAlreadyVectorized();
  1745. DEBUG(verifyFunction(*L->getHeader()->getParent()));
  1746. return true;
  1747. }
  1748. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1749. AU.addRequired<AssumptionCacheTracker>();
  1750. AU.addRequiredID(LoopSimplifyID);
  1751. AU.addRequiredID(LCSSAID);
  1752. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  1753. AU.addRequired<DominatorTreeWrapperPass>();
  1754. AU.addRequired<LoopInfoWrapperPass>();
  1755. AU.addRequired<ScalarEvolutionWrapperPass>();
  1756. AU.addRequired<TargetTransformInfoWrapperPass>();
  1757. AU.addRequired<AAResultsWrapperPass>();
  1758. AU.addRequired<LoopAccessAnalysis>();
  1759. AU.addRequired<DemandedBitsWrapperPass>();
  1760. AU.addPreserved<LoopInfoWrapperPass>();
  1761. AU.addPreserved<DominatorTreeWrapperPass>();
  1762. AU.addPreserved<BasicAAWrapperPass>();
  1763. AU.addPreserved<AAResultsWrapperPass>();
  1764. AU.addPreserved<GlobalsAAWrapperPass>();
  1765. }
  1766. };
  1767. } // end anonymous namespace
  1768. //===----------------------------------------------------------------------===//
  1769. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  1770. // LoopVectorizationCostModel.
  1771. //===----------------------------------------------------------------------===//
  1772. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  1773. // We need to place the broadcast of invariant variables outside the loop.
  1774. Instruction *Instr = dyn_cast<Instruction>(V);
  1775. bool NewInstr =
  1776. (Instr && std::find(LoopVectorBody.begin(), LoopVectorBody.end(),
  1777. Instr->getParent()) != LoopVectorBody.end());
  1778. bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
  1779. // Place the code for broadcasting invariant variables in the new preheader.
  1780. IRBuilder<>::InsertPointGuard Guard(Builder);
  1781. if (Invariant)
  1782. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1783. // Broadcast the scalar into all locations in the vector.
  1784. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  1785. return Shuf;
  1786. }
  1787. Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx,
  1788. Value *Step) {
  1789. assert(Val->getType()->isVectorTy() && "Must be a vector");
  1790. assert(Val->getType()->getScalarType()->isIntegerTy() &&
  1791. "Elem must be an integer");
  1792. assert(Step->getType() == Val->getType()->getScalarType() &&
  1793. "Step has wrong type");
  1794. // Create the types.
  1795. Type *ITy = Val->getType()->getScalarType();
  1796. VectorType *Ty = cast<VectorType>(Val->getType());
  1797. int VLen = Ty->getNumElements();
  1798. SmallVector<Constant*, 8> Indices;
  1799. // Create a vector of consecutive numbers from zero to VF.
  1800. for (int i = 0; i < VLen; ++i)
  1801. Indices.push_back(ConstantInt::get(ITy, StartIdx + i));
  1802. // Add the consecutive indices to the vector value.
  1803. Constant *Cv = ConstantVector::get(Indices);
  1804. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  1805. Step = Builder.CreateVectorSplat(VLen, Step);
  1806. assert(Step->getType() == Val->getType() && "Invalid step vec");
  1807. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  1808. // which can be found from the original scalar operations.
  1809. Step = Builder.CreateMul(Cv, Step);
  1810. return Builder.CreateAdd(Val, Step, "induction");
  1811. }
  1812. int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
  1813. assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
  1814. auto *SE = PSE.getSE();
  1815. // Make sure that the pointer does not point to structs.
  1816. if (Ptr->getType()->getPointerElementType()->isAggregateType())
  1817. return 0;
  1818. // If this value is a pointer induction variable we know it is consecutive.
  1819. PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
  1820. if (Phi && Inductions.count(Phi)) {
  1821. InductionDescriptor II = Inductions[Phi];
  1822. return II.getConsecutiveDirection();
  1823. }
  1824. GetElementPtrInst *Gep = getGEPInstruction(Ptr);
  1825. if (!Gep)
  1826. return 0;
  1827. unsigned NumOperands = Gep->getNumOperands();
  1828. Value *GpPtr = Gep->getPointerOperand();
  1829. // If this GEP value is a consecutive pointer induction variable and all of
  1830. // the indices are constant then we know it is consecutive. We can
  1831. Phi = dyn_cast<PHINode>(GpPtr);
  1832. if (Phi && Inductions.count(Phi)) {
  1833. // Make sure that the pointer does not point to structs.
  1834. PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
  1835. if (GepPtrType->getElementType()->isAggregateType())
  1836. return 0;
  1837. // Make sure that all of the index operands are loop invariant.
  1838. for (unsigned i = 1; i < NumOperands; ++i)
  1839. if (!SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop))
  1840. return 0;
  1841. InductionDescriptor II = Inductions[Phi];
  1842. return II.getConsecutiveDirection();
  1843. }
  1844. unsigned InductionOperand = getGEPInductionOperand(Gep);
  1845. // Check that all of the gep indices are uniform except for our induction
  1846. // operand.
  1847. for (unsigned i = 0; i != NumOperands; ++i)
  1848. if (i != InductionOperand &&
  1849. !SE->isLoopInvariant(PSE.getSCEV(Gep->getOperand(i)), TheLoop))
  1850. return 0;
  1851. // We can emit wide load/stores only if the last non-zero index is the
  1852. // induction variable.
  1853. const SCEV *Last = nullptr;
  1854. if (!Strides.count(Gep))
  1855. Last = PSE.getSCEV(Gep->getOperand(InductionOperand));
  1856. else {
  1857. // Because of the multiplication by a stride we can have a s/zext cast.
  1858. // We are going to replace this stride by 1 so the cast is safe to ignore.
  1859. //
  1860. // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
  1861. // %0 = trunc i64 %indvars.iv to i32
  1862. // %mul = mul i32 %0, %Stride1
  1863. // %idxprom = zext i32 %mul to i64 << Safe cast.
  1864. // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
  1865. //
  1866. Last = replaceSymbolicStrideSCEV(PSE, Strides,
  1867. Gep->getOperand(InductionOperand), Gep);
  1868. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
  1869. Last =
  1870. (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
  1871. ? C->getOperand()
  1872. : Last;
  1873. }
  1874. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
  1875. const SCEV *Step = AR->getStepRecurrence(*SE);
  1876. // The memory is consecutive because the last index is consecutive
  1877. // and all other indices are loop invariant.
  1878. if (Step->isOne())
  1879. return 1;
  1880. if (Step->isAllOnesValue())
  1881. return -1;
  1882. }
  1883. return 0;
  1884. }
  1885. bool LoopVectorizationLegality::isUniform(Value *V) {
  1886. return LAI->isUniform(V);
  1887. }
  1888. InnerLoopVectorizer::VectorParts&
  1889. InnerLoopVectorizer::getVectorValue(Value *V) {
  1890. assert(V != Induction && "The new induction variable should not be used.");
  1891. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  1892. // If we have a stride that is replaced by one, do it here.
  1893. if (Legal->hasStride(V))
  1894. V = ConstantInt::get(V->getType(), 1);
  1895. // If we have this scalar in the map, return it.
  1896. if (WidenMap.has(V))
  1897. return WidenMap.get(V);
  1898. // If this scalar is unknown, assume that it is a constant or that it is
  1899. // loop invariant. Broadcast V and save the value for future uses.
  1900. Value *B = getBroadcastInstrs(V);
  1901. return WidenMap.splat(V, B);
  1902. }
  1903. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  1904. assert(Vec->getType()->isVectorTy() && "Invalid type");
  1905. SmallVector<Constant*, 8> ShuffleMask;
  1906. for (unsigned i = 0; i < VF; ++i)
  1907. ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
  1908. return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
  1909. ConstantVector::get(ShuffleMask),
  1910. "reverse");
  1911. }
  1912. // Get a mask to interleave \p NumVec vectors into a wide vector.
  1913. // I.e. <0, VF, VF*2, ..., VF*(NumVec-1), 1, VF+1, VF*2+1, ...>
  1914. // E.g. For 2 interleaved vectors, if VF is 4, the mask is:
  1915. // <0, 4, 1, 5, 2, 6, 3, 7>
  1916. static Constant *getInterleavedMask(IRBuilder<> &Builder, unsigned VF,
  1917. unsigned NumVec) {
  1918. SmallVector<Constant *, 16> Mask;
  1919. for (unsigned i = 0; i < VF; i++)
  1920. for (unsigned j = 0; j < NumVec; j++)
  1921. Mask.push_back(Builder.getInt32(j * VF + i));
  1922. return ConstantVector::get(Mask);
  1923. }
  1924. // Get the strided mask starting from index \p Start.
  1925. // I.e. <Start, Start + Stride, ..., Start + Stride*(VF-1)>
  1926. static Constant *getStridedMask(IRBuilder<> &Builder, unsigned Start,
  1927. unsigned Stride, unsigned VF) {
  1928. SmallVector<Constant *, 16> Mask;
  1929. for (unsigned i = 0; i < VF; i++)
  1930. Mask.push_back(Builder.getInt32(Start + i * Stride));
  1931. return ConstantVector::get(Mask);
  1932. }
  1933. // Get a mask of two parts: The first part consists of sequential integers
  1934. // starting from 0, The second part consists of UNDEFs.
  1935. // I.e. <0, 1, 2, ..., NumInt - 1, undef, ..., undef>
  1936. static Constant *getSequentialMask(IRBuilder<> &Builder, unsigned NumInt,
  1937. unsigned NumUndef) {
  1938. SmallVector<Constant *, 16> Mask;
  1939. for (unsigned i = 0; i < NumInt; i++)
  1940. Mask.push_back(Builder.getInt32(i));
  1941. Constant *Undef = UndefValue::get(Builder.getInt32Ty());
  1942. for (unsigned i = 0; i < NumUndef; i++)
  1943. Mask.push_back(Undef);
  1944. return ConstantVector::get(Mask);
  1945. }
  1946. // Concatenate two vectors with the same element type. The 2nd vector should
  1947. // not have more elements than the 1st vector. If the 2nd vector has less
  1948. // elements, extend it with UNDEFs.
  1949. static Value *ConcatenateTwoVectors(IRBuilder<> &Builder, Value *V1,
  1950. Value *V2) {
  1951. VectorType *VecTy1 = dyn_cast<VectorType>(V1->getType());
  1952. VectorType *VecTy2 = dyn_cast<VectorType>(V2->getType());
  1953. assert(VecTy1 && VecTy2 &&
  1954. VecTy1->getScalarType() == VecTy2->getScalarType() &&
  1955. "Expect two vectors with the same element type");
  1956. unsigned NumElts1 = VecTy1->getNumElements();
  1957. unsigned NumElts2 = VecTy2->getNumElements();
  1958. assert(NumElts1 >= NumElts2 && "Unexpect the first vector has less elements");
  1959. if (NumElts1 > NumElts2) {
  1960. // Extend with UNDEFs.
  1961. Constant *ExtMask =
  1962. getSequentialMask(Builder, NumElts2, NumElts1 - NumElts2);
  1963. V2 = Builder.CreateShuffleVector(V2, UndefValue::get(VecTy2), ExtMask);
  1964. }
  1965. Constant *Mask = getSequentialMask(Builder, NumElts1 + NumElts2, 0);
  1966. return Builder.CreateShuffleVector(V1, V2, Mask);
  1967. }
  1968. // Concatenate vectors in the given list. All vectors have the same type.
  1969. static Value *ConcatenateVectors(IRBuilder<> &Builder,
  1970. ArrayRef<Value *> InputList) {
  1971. unsigned NumVec = InputList.size();
  1972. assert(NumVec > 1 && "Should be at least two vectors");
  1973. SmallVector<Value *, 8> ResList;
  1974. ResList.append(InputList.begin(), InputList.end());
  1975. do {
  1976. SmallVector<Value *, 8> TmpList;
  1977. for (unsigned i = 0; i < NumVec - 1; i += 2) {
  1978. Value *V0 = ResList[i], *V1 = ResList[i + 1];
  1979. assert((V0->getType() == V1->getType() || i == NumVec - 2) &&
  1980. "Only the last vector may have a different type");
  1981. TmpList.push_back(ConcatenateTwoVectors(Builder, V0, V1));
  1982. }
  1983. // Push the last vector if the total number of vectors is odd.
  1984. if (NumVec % 2 != 0)
  1985. TmpList.push_back(ResList[NumVec - 1]);
  1986. ResList = TmpList;
  1987. NumVec = ResList.size();
  1988. } while (NumVec > 1);
  1989. return ResList[0];
  1990. }
  1991. // Try to vectorize the interleave group that \p Instr belongs to.
  1992. //
  1993. // E.g. Translate following interleaved load group (factor = 3):
  1994. // for (i = 0; i < N; i+=3) {
  1995. // R = Pic[i]; // Member of index 0
  1996. // G = Pic[i+1]; // Member of index 1
  1997. // B = Pic[i+2]; // Member of index 2
  1998. // ... // do something to R, G, B
  1999. // }
  2000. // To:
  2001. // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
  2002. // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
  2003. // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
  2004. // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
  2005. //
  2006. // Or translate following interleaved store group (factor = 3):
  2007. // for (i = 0; i < N; i+=3) {
  2008. // ... do something to R, G, B
  2009. // Pic[i] = R; // Member of index 0
  2010. // Pic[i+1] = G; // Member of index 1
  2011. // Pic[i+2] = B; // Member of index 2
  2012. // }
  2013. // To:
  2014. // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
  2015. // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
  2016. // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
  2017. // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
  2018. // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
  2019. void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
  2020. const InterleaveGroup *Group = Legal->getInterleavedAccessGroup(Instr);
  2021. assert(Group && "Fail to get an interleaved access group.");
  2022. // Skip if current instruction is not the insert position.
  2023. if (Instr != Group->getInsertPos())
  2024. return;
  2025. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  2026. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  2027. Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
  2028. // Prepare for the vector type of the interleaved load/store.
  2029. Type *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  2030. unsigned InterleaveFactor = Group->getFactor();
  2031. Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
  2032. Type *PtrTy = VecTy->getPointerTo(Ptr->getType()->getPointerAddressSpace());
  2033. // Prepare for the new pointers.
  2034. setDebugLocFromInst(Builder, Ptr);
  2035. VectorParts &PtrParts = getVectorValue(Ptr);
  2036. SmallVector<Value *, 2> NewPtrs;
  2037. unsigned Index = Group->getIndex(Instr);
  2038. for (unsigned Part = 0; Part < UF; Part++) {
  2039. // Extract the pointer for current instruction from the pointer vector. A
  2040. // reverse access uses the pointer in the last lane.
  2041. Value *NewPtr = Builder.CreateExtractElement(
  2042. PtrParts[Part],
  2043. Group->isReverse() ? Builder.getInt32(VF - 1) : Builder.getInt32(0));
  2044. // Notice current instruction could be any index. Need to adjust the address
  2045. // to the member of index 0.
  2046. //
  2047. // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
  2048. // b = A[i]; // Member of index 0
  2049. // Current pointer is pointed to A[i+1], adjust it to A[i].
  2050. //
  2051. // E.g. A[i+1] = a; // Member of index 1
  2052. // A[i] = b; // Member of index 0
  2053. // A[i+2] = c; // Member of index 2 (Current instruction)
  2054. // Current pointer is pointed to A[i+2], adjust it to A[i].
  2055. NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
  2056. // Cast to the vector pointer type.
  2057. NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
  2058. }
  2059. setDebugLocFromInst(Builder, Instr);
  2060. Value *UndefVec = UndefValue::get(VecTy);
  2061. // Vectorize the interleaved load group.
  2062. if (LI) {
  2063. for (unsigned Part = 0; Part < UF; Part++) {
  2064. Instruction *NewLoadInstr = Builder.CreateAlignedLoad(
  2065. NewPtrs[Part], Group->getAlignment(), "wide.vec");
  2066. for (unsigned i = 0; i < InterleaveFactor; i++) {
  2067. Instruction *Member = Group->getMember(i);
  2068. // Skip the gaps in the group.
  2069. if (!Member)
  2070. continue;
  2071. Constant *StrideMask = getStridedMask(Builder, i, InterleaveFactor, VF);
  2072. Value *StridedVec = Builder.CreateShuffleVector(
  2073. NewLoadInstr, UndefVec, StrideMask, "strided.vec");
  2074. // If this member has different type, cast the result type.
  2075. if (Member->getType() != ScalarTy) {
  2076. VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
  2077. StridedVec = Builder.CreateBitOrPointerCast(StridedVec, OtherVTy);
  2078. }
  2079. VectorParts &Entry = WidenMap.get(Member);
  2080. Entry[Part] =
  2081. Group->isReverse() ? reverseVector(StridedVec) : StridedVec;
  2082. }
  2083. addMetadata(NewLoadInstr, Instr);
  2084. }
  2085. return;
  2086. }
  2087. // The sub vector type for current instruction.
  2088. VectorType *SubVT = VectorType::get(ScalarTy, VF);
  2089. // Vectorize the interleaved store group.
  2090. for (unsigned Part = 0; Part < UF; Part++) {
  2091. // Collect the stored vector from each member.
  2092. SmallVector<Value *, 4> StoredVecs;
  2093. for (unsigned i = 0; i < InterleaveFactor; i++) {
  2094. // Interleaved store group doesn't allow a gap, so each index has a member
  2095. Instruction *Member = Group->getMember(i);
  2096. assert(Member && "Fail to get a member from an interleaved store group");
  2097. Value *StoredVec =
  2098. getVectorValue(dyn_cast<StoreInst>(Member)->getValueOperand())[Part];
  2099. if (Group->isReverse())
  2100. StoredVec = reverseVector(StoredVec);
  2101. // If this member has different type, cast it to an unified type.
  2102. if (StoredVec->getType() != SubVT)
  2103. StoredVec = Builder.CreateBitOrPointerCast(StoredVec, SubVT);
  2104. StoredVecs.push_back(StoredVec);
  2105. }
  2106. // Concatenate all vectors into a wide vector.
  2107. Value *WideVec = ConcatenateVectors(Builder, StoredVecs);
  2108. // Interleave the elements in the wide vector.
  2109. Constant *IMask = getInterleavedMask(Builder, VF, InterleaveFactor);
  2110. Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
  2111. "interleaved.vec");
  2112. Instruction *NewStoreInstr =
  2113. Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
  2114. addMetadata(NewStoreInstr, Instr);
  2115. }
  2116. }
  2117. void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
  2118. // Attempt to issue a wide load.
  2119. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  2120. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  2121. assert((LI || SI) && "Invalid Load/Store instruction");
  2122. // Try to vectorize the interleave group if this access is interleaved.
  2123. if (Legal->isAccessInterleaved(Instr))
  2124. return vectorizeInterleaveGroup(Instr);
  2125. Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  2126. Type *DataTy = VectorType::get(ScalarDataTy, VF);
  2127. Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
  2128. unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
  2129. // An alignment of 0 means target abi alignment. We need to use the scalar's
  2130. // target abi alignment in such a case.
  2131. const DataLayout &DL = Instr->getModule()->getDataLayout();
  2132. if (!Alignment)
  2133. Alignment = DL.getABITypeAlignment(ScalarDataTy);
  2134. unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
  2135. unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ScalarDataTy);
  2136. unsigned VectorElementSize = DL.getTypeStoreSize(DataTy) / VF;
  2137. if (SI && Legal->blockNeedsPredication(SI->getParent()) &&
  2138. !Legal->isMaskRequired(SI))
  2139. return scalarizeInstruction(Instr, true);
  2140. if (ScalarAllocatedSize != VectorElementSize)
  2141. return scalarizeInstruction(Instr);
  2142. // If the pointer is loop invariant scalarize the load.
  2143. if (LI && Legal->isUniform(Ptr))
  2144. return scalarizeInstruction(Instr);
  2145. // If the pointer is non-consecutive and gather/scatter is not supported
  2146. // scalarize the instruction.
  2147. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  2148. bool Reverse = ConsecutiveStride < 0;
  2149. bool CreateGatherScatter = !ConsecutiveStride &&
  2150. ((LI && Legal->isLegalMaskedGather(ScalarDataTy)) ||
  2151. (SI && Legal->isLegalMaskedScatter(ScalarDataTy)));
  2152. if (!ConsecutiveStride && !CreateGatherScatter)
  2153. return scalarizeInstruction(Instr);
  2154. Constant *Zero = Builder.getInt32(0);
  2155. VectorParts &Entry = WidenMap.get(Instr);
  2156. VectorParts VectorGep;
  2157. // Handle consecutive loads/stores.
  2158. GetElementPtrInst *Gep = getGEPInstruction(Ptr);
  2159. if (ConsecutiveStride) {
  2160. if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
  2161. setDebugLocFromInst(Builder, Gep);
  2162. Value *PtrOperand = Gep->getPointerOperand();
  2163. Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
  2164. FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
  2165. // Create the new GEP with the new induction variable.
  2166. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  2167. Gep2->setOperand(0, FirstBasePtr);
  2168. Gep2->setName("gep.indvar.base");
  2169. Ptr = Builder.Insert(Gep2);
  2170. } else if (Gep) {
  2171. setDebugLocFromInst(Builder, Gep);
  2172. assert(PSE.getSE()->isLoopInvariant(PSE.getSCEV(Gep->getPointerOperand()),
  2173. OrigLoop) &&
  2174. "Base ptr must be invariant");
  2175. // The last index does not have to be the induction. It can be
  2176. // consecutive and be a function of the index. For example A[I+1];
  2177. unsigned NumOperands = Gep->getNumOperands();
  2178. unsigned InductionOperand = getGEPInductionOperand(Gep);
  2179. // Create the new GEP with the new induction variable.
  2180. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  2181. for (unsigned i = 0; i < NumOperands; ++i) {
  2182. Value *GepOperand = Gep->getOperand(i);
  2183. Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
  2184. // Update last index or loop invariant instruction anchored in loop.
  2185. if (i == InductionOperand ||
  2186. (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
  2187. assert((i == InductionOperand ||
  2188. PSE.getSE()->isLoopInvariant(PSE.getSCEV(GepOperandInst),
  2189. OrigLoop)) &&
  2190. "Must be last index or loop invariant");
  2191. VectorParts &GEPParts = getVectorValue(GepOperand);
  2192. Value *Index = GEPParts[0];
  2193. Index = Builder.CreateExtractElement(Index, Zero);
  2194. Gep2->setOperand(i, Index);
  2195. Gep2->setName("gep.indvar.idx");
  2196. }
  2197. }
  2198. Ptr = Builder.Insert(Gep2);
  2199. } else { // No GEP
  2200. // Use the induction element ptr.
  2201. assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
  2202. setDebugLocFromInst(Builder, Ptr);
  2203. VectorParts &PtrVal = getVectorValue(Ptr);
  2204. Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
  2205. }
  2206. } else {
  2207. // At this point we should vector version of GEP for Gather or Scatter
  2208. assert(CreateGatherScatter && "The instruction should be scalarized");
  2209. if (Gep) {
  2210. SmallVector<VectorParts, 4> OpsV;
  2211. // Vectorizing GEP, across UF parts, we want to keep each loop-invariant
  2212. // base or index of GEP scalar
  2213. for (Value *Op : Gep->operands()) {
  2214. if (PSE.getSE()->isLoopInvariant(PSE.getSCEV(Op), OrigLoop))
  2215. OpsV.push_back(VectorParts(UF, Op));
  2216. else
  2217. OpsV.push_back(getVectorValue(Op));
  2218. }
  2219. for (unsigned Part = 0; Part < UF; ++Part) {
  2220. SmallVector<Value*, 4> Ops;
  2221. Value *GEPBasePtr = OpsV[0][Part];
  2222. for (unsigned i = 1; i < Gep->getNumOperands(); i++)
  2223. Ops.push_back(OpsV[i][Part]);
  2224. Value *NewGep = Builder.CreateGEP(nullptr, GEPBasePtr, Ops,
  2225. "VectorGep");
  2226. assert(NewGep->getType()->isVectorTy() && "Expected vector GEP");
  2227. NewGep = Builder.CreateBitCast(NewGep,
  2228. VectorType::get(Ptr->getType(), VF));
  2229. VectorGep.push_back(NewGep);
  2230. }
  2231. } else
  2232. VectorGep = getVectorValue(Ptr);
  2233. }
  2234. VectorParts Mask = createBlockInMask(Instr->getParent());
  2235. // Handle Stores:
  2236. if (SI) {
  2237. assert(!Legal->isUniform(SI->getPointerOperand()) &&
  2238. "We do not allow storing to uniform addresses");
  2239. setDebugLocFromInst(Builder, SI);
  2240. // We don't want to update the value in the map as it might be used in
  2241. // another expression. So don't use a reference type for "StoredVal".
  2242. VectorParts StoredVal = getVectorValue(SI->getValueOperand());
  2243. for (unsigned Part = 0; Part < UF; ++Part) {
  2244. Instruction *NewSI = nullptr;
  2245. if (CreateGatherScatter) {
  2246. Value *MaskPart = Legal->isMaskRequired(SI) ? Mask[Part] : nullptr;
  2247. NewSI = Builder.CreateMaskedScatter(StoredVal[Part], VectorGep[Part],
  2248. Alignment, MaskPart);
  2249. } else {
  2250. // Calculate the pointer for the specific unroll-part.
  2251. Value *PartPtr =
  2252. Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
  2253. if (Reverse) {
  2254. // If we store to reverse consecutive memory locations, then we need
  2255. // to reverse the order of elements in the stored value.
  2256. StoredVal[Part] = reverseVector(StoredVal[Part]);
  2257. // If the address is consecutive but reversed, then the
  2258. // wide store needs to start at the last vector element.
  2259. PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
  2260. PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
  2261. Mask[Part] = reverseVector(Mask[Part]);
  2262. }
  2263. Value *VecPtr = Builder.CreateBitCast(PartPtr,
  2264. DataTy->getPointerTo(AddressSpace));
  2265. if (Legal->isMaskRequired(SI))
  2266. NewSI = Builder.CreateMaskedStore(StoredVal[Part], VecPtr, Alignment,
  2267. Mask[Part]);
  2268. else
  2269. NewSI = Builder.CreateAlignedStore(StoredVal[Part], VecPtr,
  2270. Alignment);
  2271. }
  2272. addMetadata(NewSI, SI);
  2273. }
  2274. return;
  2275. }
  2276. // Handle loads.
  2277. assert(LI && "Must have a load instruction");
  2278. setDebugLocFromInst(Builder, LI);
  2279. for (unsigned Part = 0; Part < UF; ++Part) {
  2280. Instruction* NewLI;
  2281. if (CreateGatherScatter) {
  2282. Value *MaskPart = Legal->isMaskRequired(LI) ? Mask[Part] : nullptr;
  2283. NewLI = Builder.CreateMaskedGather(VectorGep[Part], Alignment,
  2284. MaskPart, 0, "wide.masked.gather");
  2285. Entry[Part] = NewLI;
  2286. } else {
  2287. // Calculate the pointer for the specific unroll-part.
  2288. Value *PartPtr =
  2289. Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(Part * VF));
  2290. if (Reverse) {
  2291. // If the address is consecutive but reversed, then the
  2292. // wide load needs to start at the last vector element.
  2293. PartPtr = Builder.CreateGEP(nullptr, Ptr, Builder.getInt32(-Part * VF));
  2294. PartPtr = Builder.CreateGEP(nullptr, PartPtr, Builder.getInt32(1 - VF));
  2295. Mask[Part] = reverseVector(Mask[Part]);
  2296. }
  2297. Value *VecPtr = Builder.CreateBitCast(PartPtr,
  2298. DataTy->getPointerTo(AddressSpace));
  2299. if (Legal->isMaskRequired(LI))
  2300. NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
  2301. UndefValue::get(DataTy),
  2302. "wide.masked.load");
  2303. else
  2304. NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
  2305. Entry[Part] = Reverse ? reverseVector(NewLI) : NewLI;
  2306. }
  2307. addMetadata(NewLI, LI);
  2308. }
  2309. }
  2310. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
  2311. bool IfPredicateStore) {
  2312. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  2313. // Holds vector parameters or scalars, in case of uniform vals.
  2314. SmallVector<VectorParts, 4> Params;
  2315. setDebugLocFromInst(Builder, Instr);
  2316. // Find all of the vectorized parameters.
  2317. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  2318. Value *SrcOp = Instr->getOperand(op);
  2319. // If we are accessing the old induction variable, use the new one.
  2320. if (SrcOp == OldInduction) {
  2321. Params.push_back(getVectorValue(SrcOp));
  2322. continue;
  2323. }
  2324. // Try using previously calculated values.
  2325. Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
  2326. // If the src is an instruction that appeared earlier in the basic block,
  2327. // then it should already be vectorized.
  2328. if (SrcInst && OrigLoop->contains(SrcInst)) {
  2329. assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
  2330. // The parameter is a vector value from earlier.
  2331. Params.push_back(WidenMap.get(SrcInst));
  2332. } else {
  2333. // The parameter is a scalar from outside the loop. Maybe even a constant.
  2334. VectorParts Scalars;
  2335. Scalars.append(UF, SrcOp);
  2336. Params.push_back(Scalars);
  2337. }
  2338. }
  2339. assert(Params.size() == Instr->getNumOperands() &&
  2340. "Invalid number of operands");
  2341. // Does this instruction return a value ?
  2342. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  2343. Value *UndefVec = IsVoidRetTy ? nullptr :
  2344. UndefValue::get(VectorType::get(Instr->getType(), VF));
  2345. // Create a new entry in the WidenMap and initialize it to Undef or Null.
  2346. VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
  2347. VectorParts Cond;
  2348. if (IfPredicateStore) {
  2349. assert(Instr->getParent()->getSinglePredecessor() &&
  2350. "Only support single predecessor blocks");
  2351. Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
  2352. Instr->getParent());
  2353. }
  2354. // For each vector unroll 'part':
  2355. for (unsigned Part = 0; Part < UF; ++Part) {
  2356. // For each scalar that we create:
  2357. for (unsigned Width = 0; Width < VF; ++Width) {
  2358. // Start if-block.
  2359. Value *Cmp = nullptr;
  2360. if (IfPredicateStore) {
  2361. Cmp = Builder.CreateExtractElement(Cond[Part], Builder.getInt32(Width));
  2362. Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cmp,
  2363. ConstantInt::get(Cmp->getType(), 1));
  2364. }
  2365. Instruction *Cloned = Instr->clone();
  2366. if (!IsVoidRetTy)
  2367. Cloned->setName(Instr->getName() + ".cloned");
  2368. // Replace the operands of the cloned instructions with extracted scalars.
  2369. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  2370. Value *Op = Params[op][Part];
  2371. // Param is a vector. Need to extract the right lane.
  2372. if (Op->getType()->isVectorTy())
  2373. Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
  2374. Cloned->setOperand(op, Op);
  2375. }
  2376. addNewMetadata(Cloned, Instr);
  2377. // Place the cloned scalar in the new loop.
  2378. Builder.Insert(Cloned);
  2379. // If we just cloned a new assumption, add it the assumption cache.
  2380. if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
  2381. if (II->getIntrinsicID() == Intrinsic::assume)
  2382. AC->registerAssumption(II);
  2383. // If the original scalar returns a value we need to place it in a vector
  2384. // so that future users will be able to use it.
  2385. if (!IsVoidRetTy)
  2386. VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
  2387. Builder.getInt32(Width));
  2388. // End if-block.
  2389. if (IfPredicateStore)
  2390. PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
  2391. Cmp));
  2392. }
  2393. }
  2394. }
  2395. PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
  2396. Value *End, Value *Step,
  2397. Instruction *DL) {
  2398. BasicBlock *Header = L->getHeader();
  2399. BasicBlock *Latch = L->getLoopLatch();
  2400. // As we're just creating this loop, it's possible no latch exists
  2401. // yet. If so, use the header as this will be a single block loop.
  2402. if (!Latch)
  2403. Latch = Header;
  2404. IRBuilder<> Builder(&*Header->getFirstInsertionPt());
  2405. setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
  2406. auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
  2407. Builder.SetInsertPoint(Latch->getTerminator());
  2408. // Create i+1 and fill the PHINode.
  2409. Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
  2410. Induction->addIncoming(Start, L->getLoopPreheader());
  2411. Induction->addIncoming(Next, Latch);
  2412. // Create the compare.
  2413. Value *ICmp = Builder.CreateICmpEQ(Next, End);
  2414. Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
  2415. // Now we have two terminators. Remove the old one from the block.
  2416. Latch->getTerminator()->eraseFromParent();
  2417. return Induction;
  2418. }
  2419. Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
  2420. if (TripCount)
  2421. return TripCount;
  2422. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2423. // Find the loop boundaries.
  2424. ScalarEvolution *SE = PSE.getSE();
  2425. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  2426. assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
  2427. "Invalid loop count");
  2428. Type *IdxTy = Legal->getWidestInductionType();
  2429. // The exit count might have the type of i64 while the phi is i32. This can
  2430. // happen if we have an induction variable that is sign extended before the
  2431. // compare. The only way that we get a backedge taken count is that the
  2432. // induction variable was signed and as such will not overflow. In such a case
  2433. // truncation is legal.
  2434. if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
  2435. IdxTy->getPrimitiveSizeInBits())
  2436. BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
  2437. BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
  2438. // Get the total trip count from the count by adding 1.
  2439. const SCEV *ExitCount = SE->getAddExpr(
  2440. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  2441. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  2442. // Expand the trip count and place the new instructions in the preheader.
  2443. // Notice that the pre-header does not change, only the loop body.
  2444. SCEVExpander Exp(*SE, DL, "induction");
  2445. // Count holds the overall loop count (N).
  2446. TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  2447. L->getLoopPreheader()->getTerminator());
  2448. if (TripCount->getType()->isPointerTy())
  2449. TripCount =
  2450. CastInst::CreatePointerCast(TripCount, IdxTy,
  2451. "exitcount.ptrcnt.to.int",
  2452. L->getLoopPreheader()->getTerminator());
  2453. return TripCount;
  2454. }
  2455. Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
  2456. if (VectorTripCount)
  2457. return VectorTripCount;
  2458. Value *TC = getOrCreateTripCount(L);
  2459. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2460. // Now we need to generate the expression for N - (N % VF), which is
  2461. // the part that the vectorized body will execute.
  2462. // The loop step is equal to the vectorization factor (num of SIMD elements)
  2463. // times the unroll factor (num of SIMD instructions).
  2464. Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
  2465. Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
  2466. VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
  2467. return VectorTripCount;
  2468. }
  2469. void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
  2470. BasicBlock *Bypass) {
  2471. Value *Count = getOrCreateTripCount(L);
  2472. BasicBlock *BB = L->getLoopPreheader();
  2473. IRBuilder<> Builder(BB->getTerminator());
  2474. // Generate code to check that the loop's trip count that we computed by
  2475. // adding one to the backedge-taken count will not overflow.
  2476. Value *CheckMinIters =
  2477. Builder.CreateICmpULT(Count,
  2478. ConstantInt::get(Count->getType(), VF * UF),
  2479. "min.iters.check");
  2480. BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
  2481. "min.iters.checked");
  2482. // Update dominator tree immediately if the generated block is a
  2483. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2484. // checks may query it before the current function is finished.
  2485. DT->addNewBlock(NewBB, BB);
  2486. if (L->getParentLoop())
  2487. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2488. ReplaceInstWithInst(BB->getTerminator(),
  2489. BranchInst::Create(Bypass, NewBB, CheckMinIters));
  2490. LoopBypassBlocks.push_back(BB);
  2491. }
  2492. void InnerLoopVectorizer::emitVectorLoopEnteredCheck(Loop *L,
  2493. BasicBlock *Bypass) {
  2494. Value *TC = getOrCreateVectorTripCount(L);
  2495. BasicBlock *BB = L->getLoopPreheader();
  2496. IRBuilder<> Builder(BB->getTerminator());
  2497. // Now, compare the new count to zero. If it is zero skip the vector loop and
  2498. // jump to the scalar loop.
  2499. Value *Cmp = Builder.CreateICmpEQ(TC, Constant::getNullValue(TC->getType()),
  2500. "cmp.zero");
  2501. // Generate code to check that the loop's trip count that we computed by
  2502. // adding one to the backedge-taken count will not overflow.
  2503. BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(),
  2504. "vector.ph");
  2505. // Update dominator tree immediately if the generated block is a
  2506. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2507. // checks may query it before the current function is finished.
  2508. DT->addNewBlock(NewBB, BB);
  2509. if (L->getParentLoop())
  2510. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2511. ReplaceInstWithInst(BB->getTerminator(),
  2512. BranchInst::Create(Bypass, NewBB, Cmp));
  2513. LoopBypassBlocks.push_back(BB);
  2514. }
  2515. void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
  2516. BasicBlock *BB = L->getLoopPreheader();
  2517. // Generate the code to check that the SCEV assumptions that we made.
  2518. // We want the new basic block to start at the first instruction in a
  2519. // sequence of instructions that form a check.
  2520. SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
  2521. "scev.check");
  2522. Value *SCEVCheck =
  2523. Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
  2524. if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
  2525. if (C->isZero())
  2526. return;
  2527. // Create a new block containing the stride check.
  2528. BB->setName("vector.scevcheck");
  2529. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2530. // Update dominator tree immediately if the generated block is a
  2531. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2532. // checks may query it before the current function is finished.
  2533. DT->addNewBlock(NewBB, BB);
  2534. if (L->getParentLoop())
  2535. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2536. ReplaceInstWithInst(BB->getTerminator(),
  2537. BranchInst::Create(Bypass, NewBB, SCEVCheck));
  2538. LoopBypassBlocks.push_back(BB);
  2539. AddedSafetyChecks = true;
  2540. }
  2541. void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L,
  2542. BasicBlock *Bypass) {
  2543. BasicBlock *BB = L->getLoopPreheader();
  2544. // Generate the code that checks in runtime if arrays overlap. We put the
  2545. // checks into a separate block to make the more common case of few elements
  2546. // faster.
  2547. Instruction *FirstCheckInst;
  2548. Instruction *MemRuntimeCheck;
  2549. std::tie(FirstCheckInst, MemRuntimeCheck) =
  2550. Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
  2551. if (!MemRuntimeCheck)
  2552. return;
  2553. // Create a new block containing the memory check.
  2554. BB->setName("vector.memcheck");
  2555. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2556. // Update dominator tree immediately if the generated block is a
  2557. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2558. // checks may query it before the current function is finished.
  2559. DT->addNewBlock(NewBB, BB);
  2560. if (L->getParentLoop())
  2561. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2562. ReplaceInstWithInst(BB->getTerminator(),
  2563. BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
  2564. LoopBypassBlocks.push_back(BB);
  2565. AddedSafetyChecks = true;
  2566. // We currently don't use LoopVersioning for the actual loop cloning but we
  2567. // still use it to add the noalias metadata.
  2568. LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
  2569. PSE.getSE());
  2570. LVer->prepareNoAliasMetadata();
  2571. }
  2572. void InnerLoopVectorizer::createEmptyLoop() {
  2573. /*
  2574. In this function we generate a new loop. The new loop will contain
  2575. the vectorized instructions while the old loop will continue to run the
  2576. scalar remainder.
  2577. [ ] <-- loop iteration number check.
  2578. / |
  2579. / v
  2580. | [ ] <-- vector loop bypass (may consist of multiple blocks).
  2581. | / |
  2582. | / v
  2583. || [ ] <-- vector pre header.
  2584. |/ |
  2585. | v
  2586. | [ ] \
  2587. | [ ]_| <-- vector loop.
  2588. | |
  2589. | v
  2590. | -[ ] <--- middle-block.
  2591. | / |
  2592. | / v
  2593. -|- >[ ] <--- new preheader.
  2594. | |
  2595. | v
  2596. | [ ] \
  2597. | [ ]_| <-- old scalar loop to handle remainder.
  2598. \ |
  2599. \ v
  2600. >[ ] <-- exit block.
  2601. ...
  2602. */
  2603. BasicBlock *OldBasicBlock = OrigLoop->getHeader();
  2604. BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
  2605. BasicBlock *ExitBlock = OrigLoop->getExitBlock();
  2606. assert(VectorPH && "Invalid loop structure");
  2607. assert(ExitBlock && "Must have an exit block");
  2608. // Some loops have a single integer induction variable, while other loops
  2609. // don't. One example is c++ iterators that often have multiple pointer
  2610. // induction variables. In the code below we also support a case where we
  2611. // don't have a single induction variable.
  2612. //
  2613. // We try to obtain an induction variable from the original loop as hard
  2614. // as possible. However if we don't find one that:
  2615. // - is an integer
  2616. // - counts from zero, stepping by one
  2617. // - is the size of the widest induction variable type
  2618. // then we create a new one.
  2619. OldInduction = Legal->getInduction();
  2620. Type *IdxTy = Legal->getWidestInductionType();
  2621. // Split the single block loop into the two loop structure described above.
  2622. BasicBlock *VecBody =
  2623. VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
  2624. BasicBlock *MiddleBlock =
  2625. VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
  2626. BasicBlock *ScalarPH =
  2627. MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
  2628. // Create and register the new vector loop.
  2629. Loop* Lp = new Loop();
  2630. Loop *ParentLoop = OrigLoop->getParentLoop();
  2631. // Insert the new loop into the loop nest and register the new basic blocks
  2632. // before calling any utilities such as SCEV that require valid LoopInfo.
  2633. if (ParentLoop) {
  2634. ParentLoop->addChildLoop(Lp);
  2635. ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
  2636. ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
  2637. } else {
  2638. LI->addTopLevelLoop(Lp);
  2639. }
  2640. Lp->addBasicBlockToLoop(VecBody, *LI);
  2641. // Find the loop boundaries.
  2642. Value *Count = getOrCreateTripCount(Lp);
  2643. Value *StartIdx = ConstantInt::get(IdxTy, 0);
  2644. // We need to test whether the backedge-taken count is uint##_max. Adding one
  2645. // to it will cause overflow and an incorrect loop trip count in the vector
  2646. // body. In case of overflow we want to directly jump to the scalar remainder
  2647. // loop.
  2648. emitMinimumIterationCountCheck(Lp, ScalarPH);
  2649. // Now, compare the new count to zero. If it is zero skip the vector loop and
  2650. // jump to the scalar loop.
  2651. emitVectorLoopEnteredCheck(Lp, ScalarPH);
  2652. // Generate the code to check any assumptions that we've made for SCEV
  2653. // expressions.
  2654. emitSCEVChecks(Lp, ScalarPH);
  2655. // Generate the code that checks in runtime if arrays overlap. We put the
  2656. // checks into a separate block to make the more common case of few elements
  2657. // faster.
  2658. emitMemRuntimeChecks(Lp, ScalarPH);
  2659. // Generate the induction variable.
  2660. // The loop step is equal to the vectorization factor (num of SIMD elements)
  2661. // times the unroll factor (num of SIMD instructions).
  2662. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  2663. Constant *Step = ConstantInt::get(IdxTy, VF * UF);
  2664. Induction =
  2665. createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
  2666. getDebugLocFromInstOrOperands(OldInduction));
  2667. // We are going to resume the execution of the scalar loop.
  2668. // Go over all of the induction variables that we found and fix the
  2669. // PHIs that are left in the scalar version of the loop.
  2670. // The starting values of PHI nodes depend on the counter of the last
  2671. // iteration in the vectorized loop.
  2672. // If we come from a bypass edge then we need to start from the original
  2673. // start value.
  2674. // This variable saves the new starting index for the scalar loop. It is used
  2675. // to test if there are any tail iterations left once the vector loop has
  2676. // completed.
  2677. LoopVectorizationLegality::InductionList::iterator I, E;
  2678. LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
  2679. for (I = List->begin(), E = List->end(); I != E; ++I) {
  2680. PHINode *OrigPhi = I->first;
  2681. InductionDescriptor II = I->second;
  2682. // Create phi nodes to merge from the backedge-taken check block.
  2683. PHINode *BCResumeVal = PHINode::Create(OrigPhi->getType(), 3,
  2684. "bc.resume.val",
  2685. ScalarPH->getTerminator());
  2686. Value *EndValue;
  2687. if (OrigPhi == OldInduction) {
  2688. // We know what the end value is.
  2689. EndValue = CountRoundDown;
  2690. } else {
  2691. IRBuilder<> B(LoopBypassBlocks.back()->getTerminator());
  2692. Value *CRD = B.CreateSExtOrTrunc(CountRoundDown,
  2693. II.getStepValue()->getType(),
  2694. "cast.crd");
  2695. EndValue = II.transform(B, CRD);
  2696. EndValue->setName("ind.end");
  2697. }
  2698. // The new PHI merges the original incoming value, in case of a bypass,
  2699. // or the value at the end of the vectorized loop.
  2700. BCResumeVal->addIncoming(EndValue, MiddleBlock);
  2701. // Fix the scalar body counter (PHI node).
  2702. unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
  2703. // The old induction's phi node in the scalar body needs the truncated
  2704. // value.
  2705. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  2706. BCResumeVal->addIncoming(II.getStartValue(), LoopBypassBlocks[I]);
  2707. OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
  2708. }
  2709. // Add a check in the middle block to see if we have completed
  2710. // all of the iterations in the first vector loop.
  2711. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  2712. Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
  2713. CountRoundDown, "cmp.n",
  2714. MiddleBlock->getTerminator());
  2715. ReplaceInstWithInst(MiddleBlock->getTerminator(),
  2716. BranchInst::Create(ExitBlock, ScalarPH, CmpN));
  2717. // Get ready to start creating new instructions into the vectorized body.
  2718. Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
  2719. // Save the state.
  2720. LoopVectorPreHeader = Lp->getLoopPreheader();
  2721. LoopScalarPreHeader = ScalarPH;
  2722. LoopMiddleBlock = MiddleBlock;
  2723. LoopExitBlock = ExitBlock;
  2724. LoopVectorBody.push_back(VecBody);
  2725. LoopScalarBody = OldBasicBlock;
  2726. LoopVectorizeHints Hints(Lp, true);
  2727. Hints.setAlreadyVectorized();
  2728. }
  2729. namespace {
  2730. struct CSEDenseMapInfo {
  2731. static bool canHandle(Instruction *I) {
  2732. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  2733. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  2734. }
  2735. static inline Instruction *getEmptyKey() {
  2736. return DenseMapInfo<Instruction *>::getEmptyKey();
  2737. }
  2738. static inline Instruction *getTombstoneKey() {
  2739. return DenseMapInfo<Instruction *>::getTombstoneKey();
  2740. }
  2741. static unsigned getHashValue(Instruction *I) {
  2742. assert(canHandle(I) && "Unknown instruction!");
  2743. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  2744. I->value_op_end()));
  2745. }
  2746. static bool isEqual(Instruction *LHS, Instruction *RHS) {
  2747. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  2748. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  2749. return LHS == RHS;
  2750. return LHS->isIdenticalTo(RHS);
  2751. }
  2752. };
  2753. }
  2754. /// \brief Check whether this block is a predicated block.
  2755. /// Due to if predication of stores we might create a sequence of "if(pred) a[i]
  2756. /// = ...; " blocks. We start with one vectorized basic block. For every
  2757. /// conditional block we split this vectorized block. Therefore, every second
  2758. /// block will be a predicated one.
  2759. static bool isPredicatedBlock(unsigned BlockNum) {
  2760. return BlockNum % 2;
  2761. }
  2762. ///\brief Perform cse of induction variable instructions.
  2763. static void cse(SmallVector<BasicBlock *, 4> &BBs) {
  2764. // Perform simple cse.
  2765. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  2766. for (unsigned i = 0, e = BBs.size(); i != e; ++i) {
  2767. BasicBlock *BB = BBs[i];
  2768. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  2769. Instruction *In = &*I++;
  2770. if (!CSEDenseMapInfo::canHandle(In))
  2771. continue;
  2772. // Check if we can replace this instruction with any of the
  2773. // visited instructions.
  2774. if (Instruction *V = CSEMap.lookup(In)) {
  2775. In->replaceAllUsesWith(V);
  2776. In->eraseFromParent();
  2777. continue;
  2778. }
  2779. // Ignore instructions in conditional blocks. We create "if (pred) a[i] =
  2780. // ...;" blocks for predicated stores. Every second block is a predicated
  2781. // block.
  2782. if (isPredicatedBlock(i))
  2783. continue;
  2784. CSEMap[In] = In;
  2785. }
  2786. }
  2787. }
  2788. /// \brief Adds a 'fast' flag to floating point operations.
  2789. static Value *addFastMathFlag(Value *V) {
  2790. if (isa<FPMathOperator>(V)){
  2791. FastMathFlags Flags;
  2792. Flags.setUnsafeAlgebra();
  2793. cast<Instruction>(V)->setFastMathFlags(Flags);
  2794. }
  2795. return V;
  2796. }
  2797. /// Estimate the overhead of scalarizing a value. Insert and Extract are set if
  2798. /// the result needs to be inserted and/or extracted from vectors.
  2799. static unsigned getScalarizationOverhead(Type *Ty, bool Insert, bool Extract,
  2800. const TargetTransformInfo &TTI) {
  2801. if (Ty->isVoidTy())
  2802. return 0;
  2803. assert(Ty->isVectorTy() && "Can only scalarize vectors");
  2804. unsigned Cost = 0;
  2805. for (int i = 0, e = Ty->getVectorNumElements(); i < e; ++i) {
  2806. if (Insert)
  2807. Cost += TTI.getVectorInstrCost(Instruction::InsertElement, Ty, i);
  2808. if (Extract)
  2809. Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, Ty, i);
  2810. }
  2811. return Cost;
  2812. }
  2813. // Estimate cost of a call instruction CI if it were vectorized with factor VF.
  2814. // Return the cost of the instruction, including scalarization overhead if it's
  2815. // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
  2816. // i.e. either vector version isn't available, or is too expensive.
  2817. static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
  2818. const TargetTransformInfo &TTI,
  2819. const TargetLibraryInfo *TLI,
  2820. bool &NeedToScalarize) {
  2821. Function *F = CI->getCalledFunction();
  2822. StringRef FnName = CI->getCalledFunction()->getName();
  2823. Type *ScalarRetTy = CI->getType();
  2824. SmallVector<Type *, 4> Tys, ScalarTys;
  2825. for (auto &ArgOp : CI->arg_operands())
  2826. ScalarTys.push_back(ArgOp->getType());
  2827. // Estimate cost of scalarized vector call. The source operands are assumed
  2828. // to be vectors, so we need to extract individual elements from there,
  2829. // execute VF scalar calls, and then gather the result into the vector return
  2830. // value.
  2831. unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
  2832. if (VF == 1)
  2833. return ScalarCallCost;
  2834. // Compute corresponding vector type for return value and arguments.
  2835. Type *RetTy = ToVectorTy(ScalarRetTy, VF);
  2836. for (unsigned i = 0, ie = ScalarTys.size(); i != ie; ++i)
  2837. Tys.push_back(ToVectorTy(ScalarTys[i], VF));
  2838. // Compute costs of unpacking argument values for the scalar calls and
  2839. // packing the return values to a vector.
  2840. unsigned ScalarizationCost =
  2841. getScalarizationOverhead(RetTy, true, false, TTI);
  2842. for (unsigned i = 0, ie = Tys.size(); i != ie; ++i)
  2843. ScalarizationCost += getScalarizationOverhead(Tys[i], false, true, TTI);
  2844. unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
  2845. // If we can't emit a vector call for this function, then the currently found
  2846. // cost is the cost we need to return.
  2847. NeedToScalarize = true;
  2848. if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
  2849. return Cost;
  2850. // If the corresponding vector cost is cheaper, return its cost.
  2851. unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
  2852. if (VectorCallCost < Cost) {
  2853. NeedToScalarize = false;
  2854. return VectorCallCost;
  2855. }
  2856. return Cost;
  2857. }
  2858. // Estimate cost of an intrinsic call instruction CI if it were vectorized with
  2859. // factor VF. Return the cost of the instruction, including scalarization
  2860. // overhead if it's needed.
  2861. static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
  2862. const TargetTransformInfo &TTI,
  2863. const TargetLibraryInfo *TLI) {
  2864. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  2865. assert(ID && "Expected intrinsic call!");
  2866. Type *RetTy = ToVectorTy(CI->getType(), VF);
  2867. SmallVector<Type *, 4> Tys;
  2868. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
  2869. Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
  2870. FastMathFlags FMF;
  2871. if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
  2872. FMF = FPMO->getFastMathFlags();
  2873. return TTI.getIntrinsicInstrCost(ID, RetTy, Tys, FMF);
  2874. }
  2875. static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
  2876. IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
  2877. IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
  2878. return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
  2879. }
  2880. static Type *largestIntegerVectorType(Type *T1, Type *T2) {
  2881. IntegerType *I1 = cast<IntegerType>(T1->getVectorElementType());
  2882. IntegerType *I2 = cast<IntegerType>(T2->getVectorElementType());
  2883. return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
  2884. }
  2885. void InnerLoopVectorizer::truncateToMinimalBitwidths() {
  2886. // For every instruction `I` in MinBWs, truncate the operands, create a
  2887. // truncated version of `I` and reextend its result. InstCombine runs
  2888. // later and will remove any ext/trunc pairs.
  2889. //
  2890. for (auto &KV : MinBWs) {
  2891. VectorParts &Parts = WidenMap.get(KV.first);
  2892. for (Value *&I : Parts) {
  2893. if (I->use_empty())
  2894. continue;
  2895. Type *OriginalTy = I->getType();
  2896. Type *ScalarTruncatedTy = IntegerType::get(OriginalTy->getContext(),
  2897. KV.second);
  2898. Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
  2899. OriginalTy->getVectorNumElements());
  2900. if (TruncatedTy == OriginalTy)
  2901. continue;
  2902. if (!isa<Instruction>(I))
  2903. continue;
  2904. IRBuilder<> B(cast<Instruction>(I));
  2905. auto ShrinkOperand = [&](Value *V) -> Value* {
  2906. if (auto *ZI = dyn_cast<ZExtInst>(V))
  2907. if (ZI->getSrcTy() == TruncatedTy)
  2908. return ZI->getOperand(0);
  2909. return B.CreateZExtOrTrunc(V, TruncatedTy);
  2910. };
  2911. // The actual instruction modification depends on the instruction type,
  2912. // unfortunately.
  2913. Value *NewI = nullptr;
  2914. if (BinaryOperator *BO = dyn_cast<BinaryOperator>(I)) {
  2915. NewI = B.CreateBinOp(BO->getOpcode(),
  2916. ShrinkOperand(BO->getOperand(0)),
  2917. ShrinkOperand(BO->getOperand(1)));
  2918. cast<BinaryOperator>(NewI)->copyIRFlags(I);
  2919. } else if (ICmpInst *CI = dyn_cast<ICmpInst>(I)) {
  2920. NewI = B.CreateICmp(CI->getPredicate(),
  2921. ShrinkOperand(CI->getOperand(0)),
  2922. ShrinkOperand(CI->getOperand(1)));
  2923. } else if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  2924. NewI = B.CreateSelect(SI->getCondition(),
  2925. ShrinkOperand(SI->getTrueValue()),
  2926. ShrinkOperand(SI->getFalseValue()));
  2927. } else if (CastInst *CI = dyn_cast<CastInst>(I)) {
  2928. switch (CI->getOpcode()) {
  2929. default: llvm_unreachable("Unhandled cast!");
  2930. case Instruction::Trunc:
  2931. NewI = ShrinkOperand(CI->getOperand(0));
  2932. break;
  2933. case Instruction::SExt:
  2934. NewI = B.CreateSExtOrTrunc(CI->getOperand(0),
  2935. smallestIntegerVectorType(OriginalTy,
  2936. TruncatedTy));
  2937. break;
  2938. case Instruction::ZExt:
  2939. NewI = B.CreateZExtOrTrunc(CI->getOperand(0),
  2940. smallestIntegerVectorType(OriginalTy,
  2941. TruncatedTy));
  2942. break;
  2943. }
  2944. } else if (ShuffleVectorInst *SI = dyn_cast<ShuffleVectorInst>(I)) {
  2945. auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
  2946. auto *O0 =
  2947. B.CreateZExtOrTrunc(SI->getOperand(0),
  2948. VectorType::get(ScalarTruncatedTy, Elements0));
  2949. auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
  2950. auto *O1 =
  2951. B.CreateZExtOrTrunc(SI->getOperand(1),
  2952. VectorType::get(ScalarTruncatedTy, Elements1));
  2953. NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
  2954. } else if (isa<LoadInst>(I)) {
  2955. // Don't do anything with the operands, just extend the result.
  2956. continue;
  2957. } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  2958. auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
  2959. auto *O0 = B.CreateZExtOrTrunc(
  2960. IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2961. auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
  2962. NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
  2963. } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
  2964. auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
  2965. auto *O0 = B.CreateZExtOrTrunc(
  2966. EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2967. NewI = B.CreateExtractElement(O0, EE->getOperand(2));
  2968. } else {
  2969. llvm_unreachable("Unhandled instruction type!");
  2970. }
  2971. // Lastly, extend the result.
  2972. NewI->takeName(cast<Instruction>(I));
  2973. Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
  2974. I->replaceAllUsesWith(Res);
  2975. cast<Instruction>(I)->eraseFromParent();
  2976. I = Res;
  2977. }
  2978. }
  2979. // We'll have created a bunch of ZExts that are now parentless. Clean up.
  2980. for (auto &KV : MinBWs) {
  2981. VectorParts &Parts = WidenMap.get(KV.first);
  2982. for (Value *&I : Parts) {
  2983. ZExtInst *Inst = dyn_cast<ZExtInst>(I);
  2984. if (Inst && Inst->use_empty()) {
  2985. Value *NewI = Inst->getOperand(0);
  2986. Inst->eraseFromParent();
  2987. I = NewI;
  2988. }
  2989. }
  2990. }
  2991. }
  2992. void InnerLoopVectorizer::vectorizeLoop() {
  2993. //===------------------------------------------------===//
  2994. //
  2995. // Notice: any optimization or new instruction that go
  2996. // into the code below should be also be implemented in
  2997. // the cost-model.
  2998. //
  2999. //===------------------------------------------------===//
  3000. Constant *Zero = Builder.getInt32(0);
  3001. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3002. // Phi nodes have cycles, so we need to vectorize them in two stages. First,
  3003. // we create a new vector PHI node with no incoming edges. We use this value
  3004. // when we vectorize all of the instructions that use the PHI. Next, after
  3005. // all of the instructions in the block are complete we add the new incoming
  3006. // edges to the PHI. At this point all of the instructions in the basic block
  3007. // are vectorized, so we can use them to construct the PHI.
  3008. PhiVector PHIsToFix;
  3009. // Scan the loop in a topological order to ensure that defs are vectorized
  3010. // before users.
  3011. LoopBlocksDFS DFS(OrigLoop);
  3012. DFS.perform(LI);
  3013. // Vectorize all of the blocks in the original loop.
  3014. for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
  3015. be = DFS.endRPO(); bb != be; ++bb)
  3016. vectorizeBlockInLoop(*bb, &PHIsToFix);
  3017. // Insert truncates and extends for any truncated instructions as hints to
  3018. // InstCombine.
  3019. if (VF > 1)
  3020. truncateToMinimalBitwidths();
  3021. // At this point every instruction in the original loop is widened to a
  3022. // vector form. Now we need to fix the recurrences in PHIsToFix. These PHI
  3023. // nodes are currently empty because we did not want to introduce cycles.
  3024. // This is the second stage of vectorizing recurrences.
  3025. for (PHINode *Phi : PHIsToFix) {
  3026. assert(Phi && "Unable to recover vectorized PHI");
  3027. // Handle first-order recurrences that need to be fixed.
  3028. if (Legal->isFirstOrderRecurrence(Phi)) {
  3029. fixFirstOrderRecurrence(Phi);
  3030. continue;
  3031. }
  3032. // If the phi node is not a first-order recurrence, it must be a reduction.
  3033. // Get it's reduction variable descriptor.
  3034. assert(Legal->isReductionVariable(Phi) &&
  3035. "Unable to find the reduction variable");
  3036. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
  3037. RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
  3038. TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
  3039. Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
  3040. RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
  3041. RdxDesc.getMinMaxRecurrenceKind();
  3042. setDebugLocFromInst(Builder, ReductionStartValue);
  3043. // We need to generate a reduction vector from the incoming scalar.
  3044. // To do so, we need to generate the 'identity' vector and override
  3045. // one of the elements with the incoming scalar reduction. We need
  3046. // to do it in the vector-loop preheader.
  3047. Builder.SetInsertPoint(LoopBypassBlocks[1]->getTerminator());
  3048. // This is the vector-clone of the value that leaves the loop.
  3049. VectorParts &VectorExit = getVectorValue(LoopExitInst);
  3050. Type *VecTy = VectorExit[0]->getType();
  3051. // Find the reduction identity variable. Zero for addition, or, xor,
  3052. // one for multiplication, -1 for And.
  3053. Value *Identity;
  3054. Value *VectorStart;
  3055. if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
  3056. RK == RecurrenceDescriptor::RK_FloatMinMax) {
  3057. // MinMax reduction have the start value as their identify.
  3058. if (VF == 1) {
  3059. VectorStart = Identity = ReductionStartValue;
  3060. } else {
  3061. VectorStart = Identity =
  3062. Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
  3063. }
  3064. } else {
  3065. // Handle other reduction kinds:
  3066. Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
  3067. RK, VecTy->getScalarType());
  3068. if (VF == 1) {
  3069. Identity = Iden;
  3070. // This vector is the Identity vector where the first element is the
  3071. // incoming scalar reduction.
  3072. VectorStart = ReductionStartValue;
  3073. } else {
  3074. Identity = ConstantVector::getSplat(VF, Iden);
  3075. // This vector is the Identity vector where the first element is the
  3076. // incoming scalar reduction.
  3077. VectorStart =
  3078. Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
  3079. }
  3080. }
  3081. // Fix the vector-loop phi.
  3082. // Reductions do not have to start at zero. They can start with
  3083. // any loop invariant values.
  3084. VectorParts &VecRdxPhi = WidenMap.get(Phi);
  3085. BasicBlock *Latch = OrigLoop->getLoopLatch();
  3086. Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
  3087. VectorParts &Val = getVectorValue(LoopVal);
  3088. for (unsigned part = 0; part < UF; ++part) {
  3089. // Make sure to add the reduction stat value only to the
  3090. // first unroll part.
  3091. Value *StartVal = (part == 0) ? VectorStart : Identity;
  3092. cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal,
  3093. LoopVectorPreHeader);
  3094. cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part],
  3095. LoopVectorBody.back());
  3096. }
  3097. // Before each round, move the insertion point right between
  3098. // the PHIs and the values we are going to write.
  3099. // This allows us to write both PHINodes and the extractelement
  3100. // instructions.
  3101. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3102. VectorParts RdxParts = getVectorValue(LoopExitInst);
  3103. setDebugLocFromInst(Builder, LoopExitInst);
  3104. // If the vector reduction can be performed in a smaller type, we truncate
  3105. // then extend the loop exit value to enable InstCombine to evaluate the
  3106. // entire expression in the smaller type.
  3107. if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
  3108. Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
  3109. Builder.SetInsertPoint(LoopVectorBody.back()->getTerminator());
  3110. for (unsigned part = 0; part < UF; ++part) {
  3111. Value *Trunc = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
  3112. Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
  3113. : Builder.CreateZExt(Trunc, VecTy);
  3114. for (Value::user_iterator UI = RdxParts[part]->user_begin();
  3115. UI != RdxParts[part]->user_end();)
  3116. if (*UI != Trunc) {
  3117. (*UI++)->replaceUsesOfWith(RdxParts[part], Extnd);
  3118. RdxParts[part] = Extnd;
  3119. } else {
  3120. ++UI;
  3121. }
  3122. }
  3123. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3124. for (unsigned part = 0; part < UF; ++part)
  3125. RdxParts[part] = Builder.CreateTrunc(RdxParts[part], RdxVecTy);
  3126. }
  3127. // Reduce all of the unrolled parts into a single vector.
  3128. Value *ReducedPartRdx = RdxParts[0];
  3129. unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
  3130. setDebugLocFromInst(Builder, ReducedPartRdx);
  3131. for (unsigned part = 1; part < UF; ++part) {
  3132. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  3133. // Floating point operations had to be 'fast' to enable the reduction.
  3134. ReducedPartRdx = addFastMathFlag(
  3135. Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxParts[part],
  3136. ReducedPartRdx, "bin.rdx"));
  3137. else
  3138. ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
  3139. Builder, MinMaxKind, ReducedPartRdx, RdxParts[part]);
  3140. }
  3141. if (VF > 1) {
  3142. // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
  3143. // and vector ops, reducing the set of values being computed by half each
  3144. // round.
  3145. assert(isPowerOf2_32(VF) &&
  3146. "Reduction emission only supported for pow2 vectors!");
  3147. Value *TmpVec = ReducedPartRdx;
  3148. SmallVector<Constant*, 32> ShuffleMask(VF, nullptr);
  3149. for (unsigned i = VF; i != 1; i >>= 1) {
  3150. // Move the upper half of the vector to the lower half.
  3151. for (unsigned j = 0; j != i/2; ++j)
  3152. ShuffleMask[j] = Builder.getInt32(i/2 + j);
  3153. // Fill the rest of the mask with undef.
  3154. std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
  3155. UndefValue::get(Builder.getInt32Ty()));
  3156. Value *Shuf =
  3157. Builder.CreateShuffleVector(TmpVec,
  3158. UndefValue::get(TmpVec->getType()),
  3159. ConstantVector::get(ShuffleMask),
  3160. "rdx.shuf");
  3161. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  3162. // Floating point operations had to be 'fast' to enable the reduction.
  3163. TmpVec = addFastMathFlag(Builder.CreateBinOp(
  3164. (Instruction::BinaryOps)Op, TmpVec, Shuf, "bin.rdx"));
  3165. else
  3166. TmpVec = RecurrenceDescriptor::createMinMaxOp(Builder, MinMaxKind,
  3167. TmpVec, Shuf);
  3168. }
  3169. // The result is in the first element of the vector.
  3170. ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
  3171. Builder.getInt32(0));
  3172. // If the reduction can be performed in a smaller type, we need to extend
  3173. // the reduction to the wider type before we branch to the original loop.
  3174. if (Phi->getType() != RdxDesc.getRecurrenceType())
  3175. ReducedPartRdx =
  3176. RdxDesc.isSigned()
  3177. ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
  3178. : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
  3179. }
  3180. // Create a phi node that merges control-flow from the backedge-taken check
  3181. // block and the middle block.
  3182. PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
  3183. LoopScalarPreHeader->getTerminator());
  3184. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  3185. BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
  3186. BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3187. // Now, we need to fix the users of the reduction variable
  3188. // inside and outside of the scalar remainder loop.
  3189. // We know that the loop is in LCSSA form. We need to update the
  3190. // PHI nodes in the exit blocks.
  3191. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  3192. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  3193. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  3194. if (!LCSSAPhi) break;
  3195. // All PHINodes need to have a single entry edge, or two if
  3196. // we already fixed them.
  3197. assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
  3198. // We found our reduction value exit-PHI. Update it with the
  3199. // incoming bypass edge.
  3200. if (LCSSAPhi->getIncomingValue(0) == LoopExitInst) {
  3201. // Add an edge coming from the bypass.
  3202. LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3203. break;
  3204. }
  3205. }// end of the LCSSA phi scan.
  3206. // Fix the scalar loop reduction variable with the incoming reduction sum
  3207. // from the vector body and from the backedge value.
  3208. int IncomingEdgeBlockIdx =
  3209. Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
  3210. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  3211. // Pick the other block.
  3212. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  3213. Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
  3214. Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
  3215. } // end of for each Phi in PHIsToFix.
  3216. fixLCSSAPHIs();
  3217. // Make sure DomTree is updated.
  3218. updateAnalysis();
  3219. // Predicate any stores.
  3220. for (auto KV : PredicatedStores) {
  3221. BasicBlock::iterator I(KV.first);
  3222. auto *BB = SplitBlock(I->getParent(), &*std::next(I), DT, LI);
  3223. auto *T = SplitBlockAndInsertIfThen(KV.second, &*I, /*Unreachable=*/false,
  3224. /*BranchWeights=*/nullptr, DT, LI);
  3225. I->moveBefore(T);
  3226. I->getParent()->setName("pred.store.if");
  3227. BB->setName("pred.store.continue");
  3228. }
  3229. DEBUG(DT->verifyDomTree());
  3230. // Remove redundant induction instructions.
  3231. cse(LoopVectorBody);
  3232. }
  3233. void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
  3234. // This is the second phase of vectorizing first-order rececurrences. An
  3235. // overview of the transformation is described below. Suppose we have the
  3236. // following loop.
  3237. //
  3238. // for (int i = 0; i < n; ++i)
  3239. // b[i] = a[i] - a[i - 1];
  3240. //
  3241. // There is a first-order recurrence on "a". For this loop, the shorthand
  3242. // scalar IR looks like:
  3243. //
  3244. // scalar.ph:
  3245. // s_init = a[-1]
  3246. // br scalar.body
  3247. //
  3248. // scalar.body:
  3249. // i = phi [0, scalar.ph], [i+1, scalar.body]
  3250. // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
  3251. // s2 = a[i]
  3252. // b[i] = s2 - s1
  3253. // br cond, scalar.body, ...
  3254. //
  3255. // In this example, s1 is a recurrence because it's value depends on the
  3256. // previous iteration. In the first phase of vectorization, we created a
  3257. // temporary value for s1. We now complete the vectorization and produce the
  3258. // shorthand vector IR shown below (for VF = 4, UF = 1).
  3259. //
  3260. // vector.ph:
  3261. // v_init = vector(..., ..., ..., a[-1])
  3262. // br vector.body
  3263. //
  3264. // vector.body
  3265. // i = phi [0, vector.ph], [i+4, vector.body]
  3266. // v1 = phi [v_init, vector.ph], [v2, vector.body]
  3267. // v2 = a[i, i+1, i+2, i+3];
  3268. // v3 = vector(v1(3), v2(0, 1, 2))
  3269. // b[i, i+1, i+2, i+3] = v2 - v3
  3270. // br cond, vector.body, middle.block
  3271. //
  3272. // middle.block:
  3273. // x = v2(3)
  3274. // br scalar.ph
  3275. //
  3276. // scalar.ph:
  3277. // s_init = phi [x, middle.block], [a[-1], otherwise]
  3278. // br scalar.body
  3279. //
  3280. // After execution completes the vector loop, we extract the next value of
  3281. // the recurrence (x) to use as the initial value in the scalar loop.
  3282. // Get the original loop preheader and single loop latch.
  3283. auto *Preheader = OrigLoop->getLoopPreheader();
  3284. auto *Latch = OrigLoop->getLoopLatch();
  3285. // Get the initial and previous values of the scalar recurrence.
  3286. auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
  3287. auto *Previous = Phi->getIncomingValueForBlock(Latch);
  3288. // Create a vector from the initial value.
  3289. auto *VectorInit = ScalarInit;
  3290. if (VF > 1) {
  3291. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  3292. VectorInit = Builder.CreateInsertElement(
  3293. UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
  3294. Builder.getInt32(VF - 1), "vector.recur.init");
  3295. }
  3296. // We constructed a temporary phi node in the first phase of vectorization.
  3297. // This phi node will eventually be deleted.
  3298. auto &PhiParts = getVectorValue(Phi);
  3299. Builder.SetInsertPoint(cast<Instruction>(PhiParts[0]));
  3300. // Create a phi node for the new recurrence. The current value will either be
  3301. // the initial value inserted into a vector or loop-varying vector value.
  3302. auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
  3303. VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
  3304. // Get the vectorized previous value. We ensured the previous values was an
  3305. // instruction when detecting the recurrence.
  3306. auto &PreviousParts = getVectorValue(Previous);
  3307. // Set the insertion point to be after this instruction. We ensured the
  3308. // previous value dominated all uses of the phi when detecting the
  3309. // recurrence.
  3310. Builder.SetInsertPoint(
  3311. &*++BasicBlock::iterator(cast<Instruction>(PreviousParts[UF - 1])));
  3312. // We will construct a vector for the recurrence by combining the values for
  3313. // the current and previous iterations. This is the required shuffle mask.
  3314. SmallVector<Constant *, 8> ShuffleMask(VF);
  3315. ShuffleMask[0] = Builder.getInt32(VF - 1);
  3316. for (unsigned I = 1; I < VF; ++I)
  3317. ShuffleMask[I] = Builder.getInt32(I + VF - 1);
  3318. // The vector from which to take the initial value for the current iteration
  3319. // (actual or unrolled). Initially, this is the vector phi node.
  3320. Value *Incoming = VecPhi;
  3321. // Shuffle the current and previous vector and update the vector parts.
  3322. for (unsigned Part = 0; Part < UF; ++Part) {
  3323. auto *Shuffle =
  3324. VF > 1
  3325. ? Builder.CreateShuffleVector(Incoming, PreviousParts[Part],
  3326. ConstantVector::get(ShuffleMask))
  3327. : Incoming;
  3328. PhiParts[Part]->replaceAllUsesWith(Shuffle);
  3329. cast<Instruction>(PhiParts[Part])->eraseFromParent();
  3330. PhiParts[Part] = Shuffle;
  3331. Incoming = PreviousParts[Part];
  3332. }
  3333. // Fix the latch value of the new recurrence in the vector loop.
  3334. VecPhi->addIncoming(Incoming,
  3335. LI->getLoopFor(LoopVectorBody[0])->getLoopLatch());
  3336. // Extract the last vector element in the middle block. This will be the
  3337. // initial value for the recurrence when jumping to the scalar loop.
  3338. auto *Extract = Incoming;
  3339. if (VF > 1) {
  3340. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3341. Extract = Builder.CreateExtractElement(Extract, Builder.getInt32(VF - 1),
  3342. "vector.recur.extract");
  3343. }
  3344. // Fix the initial value of the original recurrence in the scalar loop.
  3345. Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
  3346. auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
  3347. for (auto *BB : predecessors(LoopScalarPreHeader)) {
  3348. auto *Incoming = BB == LoopMiddleBlock ? Extract : ScalarInit;
  3349. Start->addIncoming(Incoming, BB);
  3350. }
  3351. Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
  3352. Phi->setName("scalar.recur");
  3353. // Finally, fix users of the recurrence outside the loop. The users will need
  3354. // either the last value of the scalar recurrence or the last value of the
  3355. // vector recurrence we extracted in the middle block. Since the loop is in
  3356. // LCSSA form, we just need to find the phi node for the original scalar
  3357. // recurrence in the exit block, and then add an edge for the middle block.
  3358. for (auto &I : *LoopExitBlock) {
  3359. auto *LCSSAPhi = dyn_cast<PHINode>(&I);
  3360. if (!LCSSAPhi)
  3361. break;
  3362. if (LCSSAPhi->getIncomingValue(0) == Phi) {
  3363. LCSSAPhi->addIncoming(Extract, LoopMiddleBlock);
  3364. break;
  3365. }
  3366. }
  3367. }
  3368. void InnerLoopVectorizer::fixLCSSAPHIs() {
  3369. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  3370. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  3371. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  3372. if (!LCSSAPhi) break;
  3373. if (LCSSAPhi->getNumIncomingValues() == 1)
  3374. LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
  3375. LoopMiddleBlock);
  3376. }
  3377. }
  3378. InnerLoopVectorizer::VectorParts
  3379. InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
  3380. assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
  3381. "Invalid edge");
  3382. // Look for cached value.
  3383. std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
  3384. EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
  3385. if (ECEntryIt != MaskCache.end())
  3386. return ECEntryIt->second;
  3387. VectorParts SrcMask = createBlockInMask(Src);
  3388. // The terminator has to be a branch inst!
  3389. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  3390. assert(BI && "Unexpected terminator found");
  3391. if (BI->isConditional()) {
  3392. VectorParts EdgeMask = getVectorValue(BI->getCondition());
  3393. if (BI->getSuccessor(0) != Dst)
  3394. for (unsigned part = 0; part < UF; ++part)
  3395. EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
  3396. for (unsigned part = 0; part < UF; ++part)
  3397. EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
  3398. MaskCache[Edge] = EdgeMask;
  3399. return EdgeMask;
  3400. }
  3401. MaskCache[Edge] = SrcMask;
  3402. return SrcMask;
  3403. }
  3404. InnerLoopVectorizer::VectorParts
  3405. InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
  3406. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  3407. // Loop incoming mask is all-one.
  3408. if (OrigLoop->getHeader() == BB) {
  3409. Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
  3410. return getVectorValue(C);
  3411. }
  3412. // This is the block mask. We OR all incoming edges, and with zero.
  3413. Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
  3414. VectorParts BlockMask = getVectorValue(Zero);
  3415. // For each pred:
  3416. for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
  3417. VectorParts EM = createEdgeMask(*it, BB);
  3418. for (unsigned part = 0; part < UF; ++part)
  3419. BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
  3420. }
  3421. return BlockMask;
  3422. }
  3423. void InnerLoopVectorizer::widenPHIInstruction(
  3424. Instruction *PN, InnerLoopVectorizer::VectorParts &Entry, unsigned UF,
  3425. unsigned VF, PhiVector *PV) {
  3426. PHINode* P = cast<PHINode>(PN);
  3427. // Handle recurrences.
  3428. if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
  3429. for (unsigned part = 0; part < UF; ++part) {
  3430. // This is phase one of vectorizing PHIs.
  3431. Type *VecTy = (VF == 1) ? PN->getType() :
  3432. VectorType::get(PN->getType(), VF);
  3433. Entry[part] = PHINode::Create(
  3434. VecTy, 2, "vec.phi", &*LoopVectorBody.back()->getFirstInsertionPt());
  3435. }
  3436. PV->push_back(P);
  3437. return;
  3438. }
  3439. setDebugLocFromInst(Builder, P);
  3440. // Check for PHI nodes that are lowered to vector selects.
  3441. if (P->getParent() != OrigLoop->getHeader()) {
  3442. // We know that all PHIs in non-header blocks are converted into
  3443. // selects, so we don't have to worry about the insertion order and we
  3444. // can just use the builder.
  3445. // At this point we generate the predication tree. There may be
  3446. // duplications since this is a simple recursive scan, but future
  3447. // optimizations will clean it up.
  3448. unsigned NumIncoming = P->getNumIncomingValues();
  3449. // Generate a sequence of selects of the form:
  3450. // SELECT(Mask3, In3,
  3451. // SELECT(Mask2, In2,
  3452. // ( ...)))
  3453. for (unsigned In = 0; In < NumIncoming; In++) {
  3454. VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
  3455. P->getParent());
  3456. VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
  3457. for (unsigned part = 0; part < UF; ++part) {
  3458. // We might have single edge PHIs (blocks) - use an identity
  3459. // 'select' for the first PHI operand.
  3460. if (In == 0)
  3461. Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
  3462. In0[part]);
  3463. else
  3464. // Select between the current value and the previous incoming edge
  3465. // based on the incoming mask.
  3466. Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
  3467. Entry[part], "predphi");
  3468. }
  3469. }
  3470. return;
  3471. }
  3472. // This PHINode must be an induction variable.
  3473. // Make sure that we know about it.
  3474. assert(Legal->getInductionVars()->count(P) &&
  3475. "Not an induction variable");
  3476. InductionDescriptor II = Legal->getInductionVars()->lookup(P);
  3477. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  3478. // which can be found from the original scalar operations.
  3479. switch (II.getKind()) {
  3480. case InductionDescriptor::IK_NoInduction:
  3481. llvm_unreachable("Unknown induction");
  3482. case InductionDescriptor::IK_IntInduction: {
  3483. assert(P->getType() == II.getStartValue()->getType() &&
  3484. "Types must match");
  3485. // Handle other induction variables that are now based on the
  3486. // canonical one.
  3487. Value *V = Induction;
  3488. if (P != OldInduction) {
  3489. V = Builder.CreateSExtOrTrunc(Induction, P->getType());
  3490. V = II.transform(Builder, V);
  3491. V->setName("offset.idx");
  3492. }
  3493. Value *Broadcasted = getBroadcastInstrs(V);
  3494. // After broadcasting the induction variable we need to make the vector
  3495. // consecutive by adding 0, 1, 2, etc.
  3496. for (unsigned part = 0; part < UF; ++part)
  3497. Entry[part] = getStepVector(Broadcasted, VF * part, II.getStepValue());
  3498. return;
  3499. }
  3500. case InductionDescriptor::IK_PtrInduction:
  3501. // Handle the pointer induction variable case.
  3502. assert(P->getType()->isPointerTy() && "Unexpected type.");
  3503. // This is the normalized GEP that starts counting at zero.
  3504. Value *PtrInd = Induction;
  3505. PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStepValue()->getType());
  3506. // This is the vector of results. Notice that we don't generate
  3507. // vector geps because scalar geps result in better code.
  3508. for (unsigned part = 0; part < UF; ++part) {
  3509. if (VF == 1) {
  3510. int EltIndex = part;
  3511. Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
  3512. Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
  3513. Value *SclrGep = II.transform(Builder, GlobalIdx);
  3514. SclrGep->setName("next.gep");
  3515. Entry[part] = SclrGep;
  3516. continue;
  3517. }
  3518. Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
  3519. for (unsigned int i = 0; i < VF; ++i) {
  3520. int EltIndex = i + part * VF;
  3521. Constant *Idx = ConstantInt::get(PtrInd->getType(), EltIndex);
  3522. Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
  3523. Value *SclrGep = II.transform(Builder, GlobalIdx);
  3524. SclrGep->setName("next.gep");
  3525. VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
  3526. Builder.getInt32(i),
  3527. "insert.gep");
  3528. }
  3529. Entry[part] = VecVal;
  3530. }
  3531. return;
  3532. }
  3533. }
  3534. void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
  3535. // For each instruction in the old loop.
  3536. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  3537. VectorParts &Entry = WidenMap.get(&*it);
  3538. switch (it->getOpcode()) {
  3539. case Instruction::Br:
  3540. // Nothing to do for PHIs and BR, since we already took care of the
  3541. // loop control flow instructions.
  3542. continue;
  3543. case Instruction::PHI: {
  3544. // Vectorize PHINodes.
  3545. widenPHIInstruction(&*it, Entry, UF, VF, PV);
  3546. continue;
  3547. }// End of PHI.
  3548. case Instruction::Add:
  3549. case Instruction::FAdd:
  3550. case Instruction::Sub:
  3551. case Instruction::FSub:
  3552. case Instruction::Mul:
  3553. case Instruction::FMul:
  3554. case Instruction::UDiv:
  3555. case Instruction::SDiv:
  3556. case Instruction::FDiv:
  3557. case Instruction::URem:
  3558. case Instruction::SRem:
  3559. case Instruction::FRem:
  3560. case Instruction::Shl:
  3561. case Instruction::LShr:
  3562. case Instruction::AShr:
  3563. case Instruction::And:
  3564. case Instruction::Or:
  3565. case Instruction::Xor: {
  3566. // Just widen binops.
  3567. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
  3568. setDebugLocFromInst(Builder, BinOp);
  3569. VectorParts &A = getVectorValue(it->getOperand(0));
  3570. VectorParts &B = getVectorValue(it->getOperand(1));
  3571. // Use this vector value for all users of the original instruction.
  3572. for (unsigned Part = 0; Part < UF; ++Part) {
  3573. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
  3574. if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
  3575. VecOp->copyIRFlags(BinOp);
  3576. Entry[Part] = V;
  3577. }
  3578. addMetadata(Entry, &*it);
  3579. break;
  3580. }
  3581. case Instruction::Select: {
  3582. // Widen selects.
  3583. // If the selector is loop invariant we can create a select
  3584. // instruction with a scalar condition. Otherwise, use vector-select.
  3585. auto *SE = PSE.getSE();
  3586. bool InvariantCond =
  3587. SE->isLoopInvariant(PSE.getSCEV(it->getOperand(0)), OrigLoop);
  3588. setDebugLocFromInst(Builder, &*it);
  3589. // The condition can be loop invariant but still defined inside the
  3590. // loop. This means that we can't just use the original 'cond' value.
  3591. // We have to take the 'vectorized' value and pick the first lane.
  3592. // Instcombine will make this a no-op.
  3593. VectorParts &Cond = getVectorValue(it->getOperand(0));
  3594. VectorParts &Op0 = getVectorValue(it->getOperand(1));
  3595. VectorParts &Op1 = getVectorValue(it->getOperand(2));
  3596. Value *ScalarCond = (VF == 1) ? Cond[0] :
  3597. Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
  3598. for (unsigned Part = 0; Part < UF; ++Part) {
  3599. Entry[Part] = Builder.CreateSelect(
  3600. InvariantCond ? ScalarCond : Cond[Part],
  3601. Op0[Part],
  3602. Op1[Part]);
  3603. }
  3604. addMetadata(Entry, &*it);
  3605. break;
  3606. }
  3607. case Instruction::ICmp:
  3608. case Instruction::FCmp: {
  3609. // Widen compares. Generate vector compares.
  3610. bool FCmp = (it->getOpcode() == Instruction::FCmp);
  3611. CmpInst *Cmp = dyn_cast<CmpInst>(it);
  3612. setDebugLocFromInst(Builder, &*it);
  3613. VectorParts &A = getVectorValue(it->getOperand(0));
  3614. VectorParts &B = getVectorValue(it->getOperand(1));
  3615. for (unsigned Part = 0; Part < UF; ++Part) {
  3616. Value *C = nullptr;
  3617. if (FCmp) {
  3618. C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
  3619. cast<FCmpInst>(C)->copyFastMathFlags(&*it);
  3620. } else {
  3621. C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
  3622. }
  3623. Entry[Part] = C;
  3624. }
  3625. addMetadata(Entry, &*it);
  3626. break;
  3627. }
  3628. case Instruction::Store:
  3629. case Instruction::Load:
  3630. vectorizeMemoryInstruction(&*it);
  3631. break;
  3632. case Instruction::ZExt:
  3633. case Instruction::SExt:
  3634. case Instruction::FPToUI:
  3635. case Instruction::FPToSI:
  3636. case Instruction::FPExt:
  3637. case Instruction::PtrToInt:
  3638. case Instruction::IntToPtr:
  3639. case Instruction::SIToFP:
  3640. case Instruction::UIToFP:
  3641. case Instruction::Trunc:
  3642. case Instruction::FPTrunc:
  3643. case Instruction::BitCast: {
  3644. CastInst *CI = dyn_cast<CastInst>(it);
  3645. setDebugLocFromInst(Builder, &*it);
  3646. /// Optimize the special case where the source is the induction
  3647. /// variable. Notice that we can only optimize the 'trunc' case
  3648. /// because: a. FP conversions lose precision, b. sext/zext may wrap,
  3649. /// c. other casts depend on pointer size.
  3650. if (CI->getOperand(0) == OldInduction &&
  3651. it->getOpcode() == Instruction::Trunc) {
  3652. Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
  3653. CI->getType());
  3654. Value *Broadcasted = getBroadcastInstrs(ScalarCast);
  3655. InductionDescriptor II =
  3656. Legal->getInductionVars()->lookup(OldInduction);
  3657. Constant *Step = ConstantInt::getSigned(
  3658. CI->getType(), II.getStepValue()->getSExtValue());
  3659. for (unsigned Part = 0; Part < UF; ++Part)
  3660. Entry[Part] = getStepVector(Broadcasted, VF * Part, Step);
  3661. addMetadata(Entry, &*it);
  3662. break;
  3663. }
  3664. /// Vectorize casts.
  3665. Type *DestTy = (VF == 1) ? CI->getType() :
  3666. VectorType::get(CI->getType(), VF);
  3667. VectorParts &A = getVectorValue(it->getOperand(0));
  3668. for (unsigned Part = 0; Part < UF; ++Part)
  3669. Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
  3670. addMetadata(Entry, &*it);
  3671. break;
  3672. }
  3673. case Instruction::Call: {
  3674. // Ignore dbg intrinsics.
  3675. if (isa<DbgInfoIntrinsic>(it))
  3676. break;
  3677. setDebugLocFromInst(Builder, &*it);
  3678. Module *M = BB->getParent()->getParent();
  3679. CallInst *CI = cast<CallInst>(it);
  3680. StringRef FnName = CI->getCalledFunction()->getName();
  3681. Function *F = CI->getCalledFunction();
  3682. Type *RetTy = ToVectorTy(CI->getType(), VF);
  3683. SmallVector<Type *, 4> Tys;
  3684. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
  3685. Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
  3686. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3687. if (ID &&
  3688. (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
  3689. ID == Intrinsic::lifetime_start)) {
  3690. scalarizeInstruction(&*it);
  3691. break;
  3692. }
  3693. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  3694. // version of the instruction.
  3695. // Is it beneficial to perform intrinsic call compared to lib call?
  3696. bool NeedToScalarize;
  3697. unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
  3698. bool UseVectorIntrinsic =
  3699. ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
  3700. if (!UseVectorIntrinsic && NeedToScalarize) {
  3701. scalarizeInstruction(&*it);
  3702. break;
  3703. }
  3704. for (unsigned Part = 0; Part < UF; ++Part) {
  3705. SmallVector<Value *, 4> Args;
  3706. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  3707. Value *Arg = CI->getArgOperand(i);
  3708. // Some intrinsics have a scalar argument - don't replace it with a
  3709. // vector.
  3710. if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i)) {
  3711. VectorParts &VectorArg = getVectorValue(CI->getArgOperand(i));
  3712. Arg = VectorArg[Part];
  3713. }
  3714. Args.push_back(Arg);
  3715. }
  3716. Function *VectorF;
  3717. if (UseVectorIntrinsic) {
  3718. // Use vector version of the intrinsic.
  3719. Type *TysForDecl[] = {CI->getType()};
  3720. if (VF > 1)
  3721. TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  3722. VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
  3723. } else {
  3724. // Use vector version of the library call.
  3725. StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
  3726. assert(!VFnName.empty() && "Vector function name is empty.");
  3727. VectorF = M->getFunction(VFnName);
  3728. if (!VectorF) {
  3729. // Generate a declaration
  3730. FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
  3731. VectorF =
  3732. Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
  3733. VectorF->copyAttributesFrom(F);
  3734. }
  3735. }
  3736. assert(VectorF && "Can't create vector function.");
  3737. CallInst *V = Builder.CreateCall(VectorF, Args);
  3738. if (isa<FPMathOperator>(V))
  3739. V->copyFastMathFlags(CI);
  3740. Entry[Part] = V;
  3741. }
  3742. addMetadata(Entry, &*it);
  3743. break;
  3744. }
  3745. default:
  3746. // All other instructions are unsupported. Scalarize them.
  3747. scalarizeInstruction(&*it);
  3748. break;
  3749. }// end of switch.
  3750. }// end of for_each instr.
  3751. }
  3752. void InnerLoopVectorizer::updateAnalysis() {
  3753. // Forget the original basic block.
  3754. PSE.getSE()->forgetLoop(OrigLoop);
  3755. // Update the dominator tree information.
  3756. assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
  3757. "Entry does not dominate exit.");
  3758. // We don't predicate stores by this point, so the vector body should be a
  3759. // single loop.
  3760. assert(LoopVectorBody.size() == 1 && "Expected single block loop!");
  3761. DT->addNewBlock(LoopVectorBody[0], LoopVectorPreHeader);
  3762. DT->addNewBlock(LoopMiddleBlock, LoopVectorBody.back());
  3763. DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
  3764. DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
  3765. DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
  3766. DEBUG(DT->verifyDomTree());
  3767. }
  3768. /// \brief Check whether it is safe to if-convert this phi node.
  3769. ///
  3770. /// Phi nodes with constant expressions that can trap are not safe to if
  3771. /// convert.
  3772. static bool canIfConvertPHINodes(BasicBlock *BB) {
  3773. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  3774. PHINode *Phi = dyn_cast<PHINode>(I);
  3775. if (!Phi)
  3776. return true;
  3777. for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
  3778. if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
  3779. if (C->canTrap())
  3780. return false;
  3781. }
  3782. return true;
  3783. }
  3784. bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
  3785. if (!EnableIfConversion) {
  3786. emitAnalysis(VectorizationReport() << "if-conversion is disabled");
  3787. return false;
  3788. }
  3789. assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
  3790. // A list of pointers that we can safely read and write to.
  3791. SmallPtrSet<Value *, 8> SafePointes;
  3792. // Collect safe addresses.
  3793. for (Loop::block_iterator BI = TheLoop->block_begin(),
  3794. BE = TheLoop->block_end(); BI != BE; ++BI) {
  3795. BasicBlock *BB = *BI;
  3796. if (blockNeedsPredication(BB))
  3797. continue;
  3798. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  3799. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  3800. SafePointes.insert(LI->getPointerOperand());
  3801. else if (StoreInst *SI = dyn_cast<StoreInst>(I))
  3802. SafePointes.insert(SI->getPointerOperand());
  3803. }
  3804. }
  3805. // Collect the blocks that need predication.
  3806. BasicBlock *Header = TheLoop->getHeader();
  3807. for (Loop::block_iterator BI = TheLoop->block_begin(),
  3808. BE = TheLoop->block_end(); BI != BE; ++BI) {
  3809. BasicBlock *BB = *BI;
  3810. // We don't support switch statements inside loops.
  3811. if (!isa<BranchInst>(BB->getTerminator())) {
  3812. emitAnalysis(VectorizationReport(BB->getTerminator())
  3813. << "loop contains a switch statement");
  3814. return false;
  3815. }
  3816. // We must be able to predicate all blocks that need to be predicated.
  3817. if (blockNeedsPredication(BB)) {
  3818. if (!blockCanBePredicated(BB, SafePointes)) {
  3819. emitAnalysis(VectorizationReport(BB->getTerminator())
  3820. << "control flow cannot be substituted for a select");
  3821. return false;
  3822. }
  3823. } else if (BB != Header && !canIfConvertPHINodes(BB)) {
  3824. emitAnalysis(VectorizationReport(BB->getTerminator())
  3825. << "control flow cannot be substituted for a select");
  3826. return false;
  3827. }
  3828. }
  3829. // We can if-convert this loop.
  3830. return true;
  3831. }
  3832. bool LoopVectorizationLegality::canVectorize() {
  3833. // We must have a loop in canonical form. Loops with indirectbr in them cannot
  3834. // be canonicalized.
  3835. if (!TheLoop->getLoopPreheader()) {
  3836. emitAnalysis(
  3837. VectorizationReport() <<
  3838. "loop control flow is not understood by vectorizer");
  3839. return false;
  3840. }
  3841. // We can only vectorize innermost loops.
  3842. if (!TheLoop->empty()) {
  3843. emitAnalysis(VectorizationReport() << "loop is not the innermost loop");
  3844. return false;
  3845. }
  3846. // We must have a single backedge.
  3847. if (TheLoop->getNumBackEdges() != 1) {
  3848. emitAnalysis(
  3849. VectorizationReport() <<
  3850. "loop control flow is not understood by vectorizer");
  3851. return false;
  3852. }
  3853. // We must have a single exiting block.
  3854. if (!TheLoop->getExitingBlock()) {
  3855. emitAnalysis(
  3856. VectorizationReport() <<
  3857. "loop control flow is not understood by vectorizer");
  3858. return false;
  3859. }
  3860. // We only handle bottom-tested loops, i.e. loop in which the condition is
  3861. // checked at the end of each iteration. With that we can assume that all
  3862. // instructions in the loop are executed the same number of times.
  3863. if (TheLoop->getExitingBlock() != TheLoop->getLoopLatch()) {
  3864. emitAnalysis(
  3865. VectorizationReport() <<
  3866. "loop control flow is not understood by vectorizer");
  3867. return false;
  3868. }
  3869. // We need to have a loop header.
  3870. DEBUG(dbgs() << "LV: Found a loop: " <<
  3871. TheLoop->getHeader()->getName() << '\n');
  3872. // Check if we can if-convert non-single-bb loops.
  3873. unsigned NumBlocks = TheLoop->getNumBlocks();
  3874. if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
  3875. DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
  3876. return false;
  3877. }
  3878. // ScalarEvolution needs to be able to find the exit count.
  3879. const SCEV *ExitCount = PSE.getBackedgeTakenCount();
  3880. if (ExitCount == PSE.getSE()->getCouldNotCompute()) {
  3881. emitAnalysis(VectorizationReport()
  3882. << "could not determine number of loop iterations");
  3883. DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
  3884. return false;
  3885. }
  3886. // Check if we can vectorize the instructions and CFG in this loop.
  3887. if (!canVectorizeInstrs()) {
  3888. DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
  3889. return false;
  3890. }
  3891. // Go over each instruction and look at memory deps.
  3892. if (!canVectorizeMemory()) {
  3893. DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
  3894. return false;
  3895. }
  3896. // Collect all of the variables that remain uniform after vectorization.
  3897. collectLoopUniforms();
  3898. DEBUG(dbgs() << "LV: We can vectorize this loop"
  3899. << (LAI->getRuntimePointerChecking()->Need
  3900. ? " (with a runtime bound check)"
  3901. : "")
  3902. << "!\n");
  3903. bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
  3904. // If an override option has been passed in for interleaved accesses, use it.
  3905. if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
  3906. UseInterleaved = EnableInterleavedMemAccesses;
  3907. // Analyze interleaved memory accesses.
  3908. if (UseInterleaved)
  3909. InterleaveInfo.analyzeInterleaving(Strides);
  3910. unsigned SCEVThreshold = VectorizeSCEVCheckThreshold;
  3911. if (Hints->getForce() == LoopVectorizeHints::FK_Enabled)
  3912. SCEVThreshold = PragmaVectorizeSCEVCheckThreshold;
  3913. if (PSE.getUnionPredicate().getComplexity() > SCEVThreshold) {
  3914. emitAnalysis(VectorizationReport()
  3915. << "Too many SCEV assumptions need to be made and checked "
  3916. << "at runtime");
  3917. DEBUG(dbgs() << "LV: Too many SCEV checks needed.\n");
  3918. return false;
  3919. }
  3920. // Okay! We can vectorize. At this point we don't have any other mem analysis
  3921. // which may limit our maximum vectorization factor, so just return true with
  3922. // no restrictions.
  3923. return true;
  3924. }
  3925. static Type *convertPointerToIntegerType(const DataLayout &DL, Type *Ty) {
  3926. if (Ty->isPointerTy())
  3927. return DL.getIntPtrType(Ty);
  3928. // It is possible that char's or short's overflow when we ask for the loop's
  3929. // trip count, work around this by changing the type size.
  3930. if (Ty->getScalarSizeInBits() < 32)
  3931. return Type::getInt32Ty(Ty->getContext());
  3932. return Ty;
  3933. }
  3934. static Type* getWiderType(const DataLayout &DL, Type *Ty0, Type *Ty1) {
  3935. Ty0 = convertPointerToIntegerType(DL, Ty0);
  3936. Ty1 = convertPointerToIntegerType(DL, Ty1);
  3937. if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
  3938. return Ty0;
  3939. return Ty1;
  3940. }
  3941. /// \brief Check that the instruction has outside loop users and is not an
  3942. /// identified reduction variable.
  3943. static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
  3944. SmallPtrSetImpl<Value *> &Reductions) {
  3945. // Reduction instructions are allowed to have exit users. All other
  3946. // instructions must not have external users.
  3947. if (!Reductions.count(Inst))
  3948. //Check that all of the users of the loop are inside the BB.
  3949. for (User *U : Inst->users()) {
  3950. Instruction *UI = cast<Instruction>(U);
  3951. // This user may be a reduction exit value.
  3952. if (!TheLoop->contains(UI)) {
  3953. DEBUG(dbgs() << "LV: Found an outside user for : " << *UI << '\n');
  3954. return true;
  3955. }
  3956. }
  3957. return false;
  3958. }
  3959. bool LoopVectorizationLegality::canVectorizeInstrs() {
  3960. BasicBlock *Header = TheLoop->getHeader();
  3961. // Look for the attribute signaling the absence of NaNs.
  3962. Function &F = *Header->getParent();
  3963. const DataLayout &DL = F.getParent()->getDataLayout();
  3964. HasFunNoNaNAttr =
  3965. F.getFnAttribute("no-nans-fp-math").getValueAsString() == "true";
  3966. // For each block in the loop.
  3967. for (Loop::block_iterator bb = TheLoop->block_begin(),
  3968. be = TheLoop->block_end(); bb != be; ++bb) {
  3969. // Scan the instructions in the block and look for hazards.
  3970. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  3971. ++it) {
  3972. if (PHINode *Phi = dyn_cast<PHINode>(it)) {
  3973. Type *PhiTy = Phi->getType();
  3974. // Check that this PHI type is allowed.
  3975. if (!PhiTy->isIntegerTy() &&
  3976. !PhiTy->isFloatingPointTy() &&
  3977. !PhiTy->isPointerTy()) {
  3978. emitAnalysis(VectorizationReport(&*it)
  3979. << "loop control flow is not understood by vectorizer");
  3980. DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
  3981. return false;
  3982. }
  3983. // If this PHINode is not in the header block, then we know that we
  3984. // can convert it to select during if-conversion. No need to check if
  3985. // the PHIs in this block are induction or reduction variables.
  3986. if (*bb != Header) {
  3987. // Check that this instruction has no outside users or is an
  3988. // identified reduction value with an outside user.
  3989. if (!hasOutsideLoopUser(TheLoop, &*it, AllowedExit))
  3990. continue;
  3991. emitAnalysis(VectorizationReport(&*it) <<
  3992. "value could not be identified as "
  3993. "an induction or reduction variable");
  3994. return false;
  3995. }
  3996. // We only allow if-converted PHIs with exactly two incoming values.
  3997. if (Phi->getNumIncomingValues() != 2) {
  3998. emitAnalysis(VectorizationReport(&*it)
  3999. << "control flow not understood by vectorizer");
  4000. DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
  4001. return false;
  4002. }
  4003. InductionDescriptor ID;
  4004. if (InductionDescriptor::isInductionPHI(Phi, PSE.getSE(), ID)) {
  4005. Inductions[Phi] = ID;
  4006. // Get the widest type.
  4007. if (!WidestIndTy)
  4008. WidestIndTy = convertPointerToIntegerType(DL, PhiTy);
  4009. else
  4010. WidestIndTy = getWiderType(DL, PhiTy, WidestIndTy);
  4011. // Int inductions are special because we only allow one IV.
  4012. if (ID.getKind() == InductionDescriptor::IK_IntInduction &&
  4013. ID.getStepValue()->isOne() &&
  4014. isa<Constant>(ID.getStartValue()) &&
  4015. cast<Constant>(ID.getStartValue())->isNullValue()) {
  4016. // Use the phi node with the widest type as induction. Use the last
  4017. // one if there are multiple (no good reason for doing this other
  4018. // than it is expedient). We've checked that it begins at zero and
  4019. // steps by one, so this is a canonical induction variable.
  4020. if (!Induction || PhiTy == WidestIndTy)
  4021. Induction = Phi;
  4022. }
  4023. DEBUG(dbgs() << "LV: Found an induction variable.\n");
  4024. // Until we explicitly handle the case of an induction variable with
  4025. // an outside loop user we have to give up vectorizing this loop.
  4026. if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
  4027. emitAnalysis(VectorizationReport(&*it) <<
  4028. "use of induction value outside of the "
  4029. "loop is not handled by vectorizer");
  4030. return false;
  4031. }
  4032. continue;
  4033. }
  4034. RecurrenceDescriptor RedDes;
  4035. if (RecurrenceDescriptor::isReductionPHI(Phi, TheLoop, RedDes)) {
  4036. if (RedDes.hasUnsafeAlgebra())
  4037. Requirements->addUnsafeAlgebraInst(RedDes.getUnsafeAlgebraInst());
  4038. AllowedExit.insert(RedDes.getLoopExitInstr());
  4039. Reductions[Phi] = RedDes;
  4040. continue;
  4041. }
  4042. if (RecurrenceDescriptor::isFirstOrderRecurrence(Phi, TheLoop, DT)) {
  4043. FirstOrderRecurrences.insert(Phi);
  4044. continue;
  4045. }
  4046. emitAnalysis(VectorizationReport(&*it) <<
  4047. "value that could not be identified as "
  4048. "reduction is used outside the loop");
  4049. DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
  4050. return false;
  4051. }// end of PHI handling
  4052. // We handle calls that:
  4053. // * Are debug info intrinsics.
  4054. // * Have a mapping to an IR intrinsic.
  4055. // * Have a vector version available.
  4056. CallInst *CI = dyn_cast<CallInst>(it);
  4057. if (CI && !getVectorIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI) &&
  4058. !(CI->getCalledFunction() && TLI &&
  4059. TLI->isFunctionVectorizable(CI->getCalledFunction()->getName()))) {
  4060. emitAnalysis(VectorizationReport(&*it)
  4061. << "call instruction cannot be vectorized");
  4062. DEBUG(dbgs() << "LV: Found a non-intrinsic, non-libfunc callsite.\n");
  4063. return false;
  4064. }
  4065. // Intrinsics such as powi,cttz and ctlz are legal to vectorize if the
  4066. // second argument is the same (i.e. loop invariant)
  4067. if (CI &&
  4068. hasVectorInstrinsicScalarOpd(getVectorIntrinsicIDForCall(CI, TLI), 1)) {
  4069. auto *SE = PSE.getSE();
  4070. if (!SE->isLoopInvariant(PSE.getSCEV(CI->getOperand(1)), TheLoop)) {
  4071. emitAnalysis(VectorizationReport(&*it)
  4072. << "intrinsic instruction cannot be vectorized");
  4073. DEBUG(dbgs() << "LV: Found unvectorizable intrinsic " << *CI << "\n");
  4074. return false;
  4075. }
  4076. }
  4077. // Check that the instruction return type is vectorizable.
  4078. // Also, we can't vectorize extractelement instructions.
  4079. if ((!VectorType::isValidElementType(it->getType()) &&
  4080. !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
  4081. emitAnalysis(VectorizationReport(&*it)
  4082. << "instruction return type cannot be vectorized");
  4083. DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
  4084. return false;
  4085. }
  4086. // Check that the stored type is vectorizable.
  4087. if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
  4088. Type *T = ST->getValueOperand()->getType();
  4089. if (!VectorType::isValidElementType(T)) {
  4090. emitAnalysis(VectorizationReport(ST) <<
  4091. "store instruction cannot be vectorized");
  4092. return false;
  4093. }
  4094. if (EnableMemAccessVersioning)
  4095. collectStridedAccess(ST);
  4096. } else if (LoadInst *LI = dyn_cast<LoadInst>(it)) {
  4097. if (EnableMemAccessVersioning)
  4098. collectStridedAccess(LI);
  4099. // FP instructions can allow unsafe algebra, thus vectorizable by
  4100. // non-IEEE-754 compliant SIMD units.
  4101. // This applies to floating-point math operations and calls, not memory
  4102. // operations, shuffles, or casts, as they don't change precision or
  4103. // semantics.
  4104. } else if (it->getType()->isFloatingPointTy() &&
  4105. (CI || it->isBinaryOp()) &&
  4106. !it->hasUnsafeAlgebra()) {
  4107. DEBUG(dbgs() << "LV: Found FP op with unsafe algebra.\n");
  4108. Hints->setPotentiallyUnsafe();
  4109. }
  4110. // Reduction instructions are allowed to have exit users.
  4111. // All other instructions must not have external users.
  4112. if (hasOutsideLoopUser(TheLoop, &*it, AllowedExit)) {
  4113. emitAnalysis(VectorizationReport(&*it) <<
  4114. "value cannot be used outside the loop");
  4115. return false;
  4116. }
  4117. } // next instr.
  4118. }
  4119. if (!Induction) {
  4120. DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
  4121. if (Inductions.empty()) {
  4122. emitAnalysis(VectorizationReport()
  4123. << "loop induction variable could not be identified");
  4124. return false;
  4125. }
  4126. }
  4127. // Now we know the widest induction type, check if our found induction
  4128. // is the same size. If it's not, unset it here and InnerLoopVectorizer
  4129. // will create another.
  4130. if (Induction && WidestIndTy != Induction->getType())
  4131. Induction = nullptr;
  4132. return true;
  4133. }
  4134. void LoopVectorizationLegality::collectStridedAccess(Value *MemAccess) {
  4135. Value *Ptr = nullptr;
  4136. if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
  4137. Ptr = LI->getPointerOperand();
  4138. else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
  4139. Ptr = SI->getPointerOperand();
  4140. else
  4141. return;
  4142. Value *Stride = getStrideFromPointer(Ptr, PSE.getSE(), TheLoop);
  4143. if (!Stride)
  4144. return;
  4145. DEBUG(dbgs() << "LV: Found a strided access that we can version");
  4146. DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
  4147. Strides[Ptr] = Stride;
  4148. StrideSet.insert(Stride);
  4149. }
  4150. void LoopVectorizationLegality::collectLoopUniforms() {
  4151. // We now know that the loop is vectorizable!
  4152. // Collect variables that will remain uniform after vectorization.
  4153. std::vector<Value*> Worklist;
  4154. BasicBlock *Latch = TheLoop->getLoopLatch();
  4155. // Start with the conditional branch and walk up the block.
  4156. Worklist.push_back(Latch->getTerminator()->getOperand(0));
  4157. // Also add all consecutive pointer values; these values will be uniform
  4158. // after vectorization (and subsequent cleanup) and, until revectorization is
  4159. // supported, all dependencies must also be uniform.
  4160. for (Loop::block_iterator B = TheLoop->block_begin(),
  4161. BE = TheLoop->block_end(); B != BE; ++B)
  4162. for (BasicBlock::iterator I = (*B)->begin(), IE = (*B)->end();
  4163. I != IE; ++I)
  4164. if (I->getType()->isPointerTy() && isConsecutivePtr(&*I))
  4165. Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
  4166. while (!Worklist.empty()) {
  4167. Instruction *I = dyn_cast<Instruction>(Worklist.back());
  4168. Worklist.pop_back();
  4169. // Look at instructions inside this loop.
  4170. // Stop when reaching PHI nodes.
  4171. // TODO: we need to follow values all over the loop, not only in this block.
  4172. if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
  4173. continue;
  4174. // This is a known uniform.
  4175. Uniforms.insert(I);
  4176. // Insert all operands.
  4177. Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
  4178. }
  4179. }
  4180. bool LoopVectorizationLegality::canVectorizeMemory() {
  4181. LAI = &LAA->getInfo(TheLoop, Strides);
  4182. auto &OptionalReport = LAI->getReport();
  4183. if (OptionalReport)
  4184. emitAnalysis(VectorizationReport(*OptionalReport));
  4185. if (!LAI->canVectorizeMemory())
  4186. return false;
  4187. if (LAI->hasStoreToLoopInvariantAddress()) {
  4188. emitAnalysis(
  4189. VectorizationReport()
  4190. << "write to a loop invariant address could not be vectorized");
  4191. DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
  4192. return false;
  4193. }
  4194. Requirements->addRuntimePointerChecks(LAI->getNumRuntimePointerChecks());
  4195. PSE.addPredicate(LAI->PSE.getUnionPredicate());
  4196. return true;
  4197. }
  4198. bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
  4199. Value *In0 = const_cast<Value*>(V);
  4200. PHINode *PN = dyn_cast_or_null<PHINode>(In0);
  4201. if (!PN)
  4202. return false;
  4203. return Inductions.count(PN);
  4204. }
  4205. bool LoopVectorizationLegality::isFirstOrderRecurrence(const PHINode *Phi) {
  4206. return FirstOrderRecurrences.count(Phi);
  4207. }
  4208. bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
  4209. return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
  4210. }
  4211. bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
  4212. SmallPtrSetImpl<Value *> &SafePtrs) {
  4213. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4214. // Check that we don't have a constant expression that can trap as operand.
  4215. for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
  4216. OI != OE; ++OI) {
  4217. if (Constant *C = dyn_cast<Constant>(*OI))
  4218. if (C->canTrap())
  4219. return false;
  4220. }
  4221. // We might be able to hoist the load.
  4222. if (it->mayReadFromMemory()) {
  4223. LoadInst *LI = dyn_cast<LoadInst>(it);
  4224. if (!LI)
  4225. return false;
  4226. if (!SafePtrs.count(LI->getPointerOperand())) {
  4227. if (isLegalMaskedLoad(LI->getType(), LI->getPointerOperand()) ||
  4228. isLegalMaskedGather(LI->getType())) {
  4229. MaskedOp.insert(LI);
  4230. continue;
  4231. }
  4232. return false;
  4233. }
  4234. }
  4235. // We don't predicate stores at the moment.
  4236. if (it->mayWriteToMemory()) {
  4237. StoreInst *SI = dyn_cast<StoreInst>(it);
  4238. // We only support predication of stores in basic blocks with one
  4239. // predecessor.
  4240. if (!SI)
  4241. return false;
  4242. bool isSafePtr = (SafePtrs.count(SI->getPointerOperand()) != 0);
  4243. bool isSinglePredecessor = SI->getParent()->getSinglePredecessor();
  4244. if (++NumPredStores > NumberOfStoresToPredicate || !isSafePtr ||
  4245. !isSinglePredecessor) {
  4246. // Build a masked store if it is legal for the target, otherwise
  4247. // scalarize the block.
  4248. bool isLegalMaskedOp =
  4249. isLegalMaskedStore(SI->getValueOperand()->getType(),
  4250. SI->getPointerOperand()) ||
  4251. isLegalMaskedScatter(SI->getValueOperand()->getType());
  4252. if (isLegalMaskedOp) {
  4253. --NumPredStores;
  4254. MaskedOp.insert(SI);
  4255. continue;
  4256. }
  4257. return false;
  4258. }
  4259. }
  4260. if (it->mayThrow())
  4261. return false;
  4262. // The instructions below can trap.
  4263. switch (it->getOpcode()) {
  4264. default: continue;
  4265. case Instruction::UDiv:
  4266. case Instruction::SDiv:
  4267. case Instruction::URem:
  4268. case Instruction::SRem:
  4269. return false;
  4270. }
  4271. }
  4272. return true;
  4273. }
  4274. void InterleavedAccessInfo::collectConstStridedAccesses(
  4275. MapVector<Instruction *, StrideDescriptor> &StrideAccesses,
  4276. const ValueToValueMap &Strides) {
  4277. // Holds load/store instructions in program order.
  4278. SmallVector<Instruction *, 16> AccessList;
  4279. for (auto *BB : TheLoop->getBlocks()) {
  4280. bool IsPred = LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
  4281. for (auto &I : *BB) {
  4282. if (!isa<LoadInst>(&I) && !isa<StoreInst>(&I))
  4283. continue;
  4284. // FIXME: Currently we can't handle mixed accesses and predicated accesses
  4285. if (IsPred)
  4286. return;
  4287. AccessList.push_back(&I);
  4288. }
  4289. }
  4290. if (AccessList.empty())
  4291. return;
  4292. auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
  4293. for (auto I : AccessList) {
  4294. LoadInst *LI = dyn_cast<LoadInst>(I);
  4295. StoreInst *SI = dyn_cast<StoreInst>(I);
  4296. Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
  4297. int Stride = isStridedPtr(PSE, Ptr, TheLoop, Strides);
  4298. // The factor of the corresponding interleave group.
  4299. unsigned Factor = std::abs(Stride);
  4300. // Ignore the access if the factor is too small or too large.
  4301. if (Factor < 2 || Factor > MaxInterleaveGroupFactor)
  4302. continue;
  4303. const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
  4304. PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  4305. unsigned Size = DL.getTypeAllocSize(PtrTy->getElementType());
  4306. // An alignment of 0 means target ABI alignment.
  4307. unsigned Align = LI ? LI->getAlignment() : SI->getAlignment();
  4308. if (!Align)
  4309. Align = DL.getABITypeAlignment(PtrTy->getElementType());
  4310. StrideAccesses[I] = StrideDescriptor(Stride, Scev, Size, Align);
  4311. }
  4312. }
  4313. // Analyze interleaved accesses and collect them into interleave groups.
  4314. //
  4315. // Notice that the vectorization on interleaved groups will change instruction
  4316. // orders and may break dependences. But the memory dependence check guarantees
  4317. // that there is no overlap between two pointers of different strides, element
  4318. // sizes or underlying bases.
  4319. //
  4320. // For pointers sharing the same stride, element size and underlying base, no
  4321. // need to worry about Read-After-Write dependences and Write-After-Read
  4322. // dependences.
  4323. //
  4324. // E.g. The RAW dependence: A[i] = a;
  4325. // b = A[i];
  4326. // This won't exist as it is a store-load forwarding conflict, which has
  4327. // already been checked and forbidden in the dependence check.
  4328. //
  4329. // E.g. The WAR dependence: a = A[i]; // (1)
  4330. // A[i] = b; // (2)
  4331. // The store group of (2) is always inserted at or below (2), and the load group
  4332. // of (1) is always inserted at or above (1). The dependence is safe.
  4333. void InterleavedAccessInfo::analyzeInterleaving(
  4334. const ValueToValueMap &Strides) {
  4335. DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
  4336. // Holds all the stride accesses.
  4337. MapVector<Instruction *, StrideDescriptor> StrideAccesses;
  4338. collectConstStridedAccesses(StrideAccesses, Strides);
  4339. if (StrideAccesses.empty())
  4340. return;
  4341. // Holds all interleaved store groups temporarily.
  4342. SmallSetVector<InterleaveGroup *, 4> StoreGroups;
  4343. // Holds all interleaved load groups temporarily.
  4344. SmallSetVector<InterleaveGroup *, 4> LoadGroups;
  4345. // Search the load-load/write-write pair B-A in bottom-up order and try to
  4346. // insert B into the interleave group of A according to 3 rules:
  4347. // 1. A and B have the same stride.
  4348. // 2. A and B have the same memory object size.
  4349. // 3. B belongs to the group according to the distance.
  4350. //
  4351. // The bottom-up order can avoid breaking the Write-After-Write dependences
  4352. // between two pointers of the same base.
  4353. // E.g. A[i] = a; (1)
  4354. // A[i] = b; (2)
  4355. // A[i+1] = c (3)
  4356. // We form the group (2)+(3) in front, so (1) has to form groups with accesses
  4357. // above (1), which guarantees that (1) is always above (2).
  4358. for (auto I = StrideAccesses.rbegin(), E = StrideAccesses.rend(); I != E;
  4359. ++I) {
  4360. Instruction *A = I->first;
  4361. StrideDescriptor DesA = I->second;
  4362. InterleaveGroup *Group = getInterleaveGroup(A);
  4363. if (!Group) {
  4364. DEBUG(dbgs() << "LV: Creating an interleave group with:" << *A << '\n');
  4365. Group = createInterleaveGroup(A, DesA.Stride, DesA.Align);
  4366. }
  4367. if (A->mayWriteToMemory())
  4368. StoreGroups.insert(Group);
  4369. else
  4370. LoadGroups.insert(Group);
  4371. for (auto II = std::next(I); II != E; ++II) {
  4372. Instruction *B = II->first;
  4373. StrideDescriptor DesB = II->second;
  4374. // Ignore if B is already in a group or B is a different memory operation.
  4375. if (isInterleaved(B) || A->mayReadFromMemory() != B->mayReadFromMemory())
  4376. continue;
  4377. // Check the rule 1 and 2.
  4378. if (DesB.Stride != DesA.Stride || DesB.Size != DesA.Size)
  4379. continue;
  4380. // Calculate the distance and prepare for the rule 3.
  4381. const SCEVConstant *DistToA = dyn_cast<SCEVConstant>(
  4382. PSE.getSE()->getMinusSCEV(DesB.Scev, DesA.Scev));
  4383. if (!DistToA)
  4384. continue;
  4385. int DistanceToA = DistToA->getAPInt().getSExtValue();
  4386. // Skip if the distance is not multiple of size as they are not in the
  4387. // same group.
  4388. if (DistanceToA % static_cast<int>(DesA.Size))
  4389. continue;
  4390. // The index of B is the index of A plus the related index to A.
  4391. int IndexB =
  4392. Group->getIndex(A) + DistanceToA / static_cast<int>(DesA.Size);
  4393. // Try to insert B into the group.
  4394. if (Group->insertMember(B, IndexB, DesB.Align)) {
  4395. DEBUG(dbgs() << "LV: Inserted:" << *B << '\n'
  4396. << " into the interleave group with" << *A << '\n');
  4397. InterleaveGroupMap[B] = Group;
  4398. // Set the first load in program order as the insert position.
  4399. if (B->mayReadFromMemory())
  4400. Group->setInsertPos(B);
  4401. }
  4402. } // Iteration on instruction B
  4403. } // Iteration on instruction A
  4404. // Remove interleaved store groups with gaps.
  4405. for (InterleaveGroup *Group : StoreGroups)
  4406. if (Group->getNumMembers() != Group->getFactor())
  4407. releaseGroup(Group);
  4408. // Remove interleaved load groups that don't have the first and last member.
  4409. // This guarantees that we won't do speculative out of bounds loads.
  4410. for (InterleaveGroup *Group : LoadGroups)
  4411. if (!Group->getMember(0) || !Group->getMember(Group->getFactor() - 1))
  4412. releaseGroup(Group);
  4413. }
  4414. LoopVectorizationCostModel::VectorizationFactor
  4415. LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize) {
  4416. // Width 1 means no vectorize
  4417. VectorizationFactor Factor = { 1U, 0U };
  4418. if (OptForSize && Legal->getRuntimePointerChecking()->Need) {
  4419. emitAnalysis(VectorizationReport() <<
  4420. "runtime pointer checks needed. Enable vectorization of this "
  4421. "loop with '#pragma clang loop vectorize(enable)' when "
  4422. "compiling with -Os/-Oz");
  4423. DEBUG(dbgs() <<
  4424. "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
  4425. return Factor;
  4426. }
  4427. if (!EnableCondStoresVectorization && Legal->getNumPredStores()) {
  4428. emitAnalysis(VectorizationReport() <<
  4429. "store that is conditionally executed prevents vectorization");
  4430. DEBUG(dbgs() << "LV: No vectorization. There are conditional stores.\n");
  4431. return Factor;
  4432. }
  4433. // Find the trip count.
  4434. unsigned TC = SE->getSmallConstantTripCount(TheLoop);
  4435. DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4436. MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
  4437. unsigned SmallestType, WidestType;
  4438. std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
  4439. unsigned WidestRegister = TTI.getRegisterBitWidth(true);
  4440. unsigned MaxSafeDepDist = -1U;
  4441. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4442. MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
  4443. WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
  4444. WidestRegister : MaxSafeDepDist);
  4445. unsigned MaxVectorSize = WidestRegister / WidestType;
  4446. DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType << " / "
  4447. << WidestType << " bits.\n");
  4448. DEBUG(dbgs() << "LV: The Widest register is: "
  4449. << WidestRegister << " bits.\n");
  4450. if (MaxVectorSize == 0) {
  4451. DEBUG(dbgs() << "LV: The target has no vector registers.\n");
  4452. MaxVectorSize = 1;
  4453. }
  4454. assert(MaxVectorSize <= 64 && "Did not expect to pack so many elements"
  4455. " into one vector!");
  4456. unsigned VF = MaxVectorSize;
  4457. if (MaximizeBandwidth && !OptForSize) {
  4458. // Collect all viable vectorization factors.
  4459. SmallVector<unsigned, 8> VFs;
  4460. unsigned NewMaxVectorSize = WidestRegister / SmallestType;
  4461. for (unsigned VS = MaxVectorSize; VS <= NewMaxVectorSize; VS *= 2)
  4462. VFs.push_back(VS);
  4463. // For each VF calculate its register usage.
  4464. auto RUs = calculateRegisterUsage(VFs);
  4465. // Select the largest VF which doesn't require more registers than existing
  4466. // ones.
  4467. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
  4468. for (int i = RUs.size() - 1; i >= 0; --i) {
  4469. if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
  4470. VF = VFs[i];
  4471. break;
  4472. }
  4473. }
  4474. }
  4475. // If we optimize the program for size, avoid creating the tail loop.
  4476. if (OptForSize) {
  4477. // If we are unable to calculate the trip count then don't try to vectorize.
  4478. if (TC < 2) {
  4479. emitAnalysis
  4480. (VectorizationReport() <<
  4481. "unable to calculate the loop count due to complex control flow");
  4482. DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
  4483. return Factor;
  4484. }
  4485. // Find the maximum SIMD width that can fit within the trip count.
  4486. VF = TC % MaxVectorSize;
  4487. if (VF == 0)
  4488. VF = MaxVectorSize;
  4489. else {
  4490. // If the trip count that we found modulo the vectorization factor is not
  4491. // zero then we require a tail.
  4492. emitAnalysis(VectorizationReport() <<
  4493. "cannot optimize for size and vectorize at the "
  4494. "same time. Enable vectorization of this loop "
  4495. "with '#pragma clang loop vectorize(enable)' "
  4496. "when compiling with -Os/-Oz");
  4497. DEBUG(dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
  4498. return Factor;
  4499. }
  4500. }
  4501. int UserVF = Hints->getWidth();
  4502. if (UserVF != 0) {
  4503. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  4504. DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  4505. Factor.Width = UserVF;
  4506. return Factor;
  4507. }
  4508. float Cost = expectedCost(1).first;
  4509. #ifndef NDEBUG
  4510. const float ScalarCost = Cost;
  4511. #endif /* NDEBUG */
  4512. unsigned Width = 1;
  4513. DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
  4514. bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
  4515. // Ignore scalar width, because the user explicitly wants vectorization.
  4516. if (ForceVectorization && VF > 1) {
  4517. Width = 2;
  4518. Cost = expectedCost(Width).first / (float)Width;
  4519. }
  4520. for (unsigned i=2; i <= VF; i*=2) {
  4521. // Notice that the vector loop needs to be executed less times, so
  4522. // we need to divide the cost of the vector loops by the width of
  4523. // the vector elements.
  4524. VectorizationCostTy C = expectedCost(i);
  4525. float VectorCost = C.first / (float)i;
  4526. DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
  4527. (int)VectorCost << ".\n");
  4528. if (!C.second && !ForceVectorization) {
  4529. DEBUG(dbgs() << "LV: Not considering vector loop of width " << i <<
  4530. " because it will not generate any vector instructions.\n");
  4531. continue;
  4532. }
  4533. if (VectorCost < Cost) {
  4534. Cost = VectorCost;
  4535. Width = i;
  4536. }
  4537. }
  4538. DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
  4539. << "LV: Vectorization seems to be not beneficial, "
  4540. << "but was forced by a user.\n");
  4541. DEBUG(dbgs() << "LV: Selecting VF: "<< Width << ".\n");
  4542. Factor.Width = Width;
  4543. Factor.Cost = Width * Cost;
  4544. return Factor;
  4545. }
  4546. std::pair<unsigned, unsigned>
  4547. LoopVectorizationCostModel::getSmallestAndWidestTypes() {
  4548. unsigned MinWidth = -1U;
  4549. unsigned MaxWidth = 8;
  4550. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4551. // For each block.
  4552. for (Loop::block_iterator bb = TheLoop->block_begin(),
  4553. be = TheLoop->block_end(); bb != be; ++bb) {
  4554. BasicBlock *BB = *bb;
  4555. // For each instruction in the loop.
  4556. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4557. Type *T = it->getType();
  4558. // Skip ignored values.
  4559. if (ValuesToIgnore.count(&*it))
  4560. continue;
  4561. // Only examine Loads, Stores and PHINodes.
  4562. if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
  4563. continue;
  4564. // Examine PHI nodes that are reduction variables. Update the type to
  4565. // account for the recurrence type.
  4566. if (PHINode *PN = dyn_cast<PHINode>(it)) {
  4567. if (!Legal->isReductionVariable(PN))
  4568. continue;
  4569. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
  4570. T = RdxDesc.getRecurrenceType();
  4571. }
  4572. // Examine the stored values.
  4573. if (StoreInst *ST = dyn_cast<StoreInst>(it))
  4574. T = ST->getValueOperand()->getType();
  4575. // Ignore loaded pointer types and stored pointer types that are not
  4576. // consecutive. However, we do want to take consecutive stores/loads of
  4577. // pointer vectors into account.
  4578. if (T->isPointerTy() && !isConsecutiveLoadOrStore(&*it))
  4579. continue;
  4580. MinWidth = std::min(MinWidth,
  4581. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4582. MaxWidth = std::max(MaxWidth,
  4583. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4584. }
  4585. }
  4586. return {MinWidth, MaxWidth};
  4587. }
  4588. unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
  4589. unsigned VF,
  4590. unsigned LoopCost) {
  4591. // -- The interleave heuristics --
  4592. // We interleave the loop in order to expose ILP and reduce the loop overhead.
  4593. // There are many micro-architectural considerations that we can't predict
  4594. // at this level. For example, frontend pressure (on decode or fetch) due to
  4595. // code size, or the number and capabilities of the execution ports.
  4596. //
  4597. // We use the following heuristics to select the interleave count:
  4598. // 1. If the code has reductions, then we interleave to break the cross
  4599. // iteration dependency.
  4600. // 2. If the loop is really small, then we interleave to reduce the loop
  4601. // overhead.
  4602. // 3. We don't interleave if we think that we will spill registers to memory
  4603. // due to the increased register pressure.
  4604. // When we optimize for size, we don't interleave.
  4605. if (OptForSize)
  4606. return 1;
  4607. // We used the distance for the interleave count.
  4608. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4609. return 1;
  4610. // Do not interleave loops with a relatively small trip count.
  4611. unsigned TC = SE->getSmallConstantTripCount(TheLoop);
  4612. if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
  4613. return 1;
  4614. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
  4615. DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters <<
  4616. " registers\n");
  4617. if (VF == 1) {
  4618. if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
  4619. TargetNumRegisters = ForceTargetNumScalarRegs;
  4620. } else {
  4621. if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
  4622. TargetNumRegisters = ForceTargetNumVectorRegs;
  4623. }
  4624. RegisterUsage R = calculateRegisterUsage({VF})[0];
  4625. // We divide by these constants so assume that we have at least one
  4626. // instruction that uses at least one register.
  4627. R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
  4628. R.NumInstructions = std::max(R.NumInstructions, 1U);
  4629. // We calculate the interleave count using the following formula.
  4630. // Subtract the number of loop invariants from the number of available
  4631. // registers. These registers are used by all of the interleaved instances.
  4632. // Next, divide the remaining registers by the number of registers that is
  4633. // required by the loop, in order to estimate how many parallel instances
  4634. // fit without causing spills. All of this is rounded down if necessary to be
  4635. // a power of two. We want power of two interleave count to simplify any
  4636. // addressing operations or alignment considerations.
  4637. unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
  4638. R.MaxLocalUsers);
  4639. // Don't count the induction variable as interleaved.
  4640. if (EnableIndVarRegisterHeur)
  4641. IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
  4642. std::max(1U, (R.MaxLocalUsers - 1)));
  4643. // Clamp the interleave ranges to reasonable counts.
  4644. unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
  4645. // Check if the user has overridden the max.
  4646. if (VF == 1) {
  4647. if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
  4648. MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
  4649. } else {
  4650. if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
  4651. MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
  4652. }
  4653. // If we did not calculate the cost for VF (because the user selected the VF)
  4654. // then we calculate the cost of VF here.
  4655. if (LoopCost == 0)
  4656. LoopCost = expectedCost(VF).first;
  4657. // Clamp the calculated IC to be between the 1 and the max interleave count
  4658. // that the target allows.
  4659. if (IC > MaxInterleaveCount)
  4660. IC = MaxInterleaveCount;
  4661. else if (IC < 1)
  4662. IC = 1;
  4663. // Interleave if we vectorized this loop and there is a reduction that could
  4664. // benefit from interleaving.
  4665. if (VF > 1 && Legal->getReductionVars()->size()) {
  4666. DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
  4667. return IC;
  4668. }
  4669. // Note that if we've already vectorized the loop we will have done the
  4670. // runtime check and so interleaving won't require further checks.
  4671. bool InterleavingRequiresRuntimePointerCheck =
  4672. (VF == 1 && Legal->getRuntimePointerChecking()->Need);
  4673. // We want to interleave small loops in order to reduce the loop overhead and
  4674. // potentially expose ILP opportunities.
  4675. DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
  4676. if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
  4677. // We assume that the cost overhead is 1 and we use the cost model
  4678. // to estimate the cost of the loop and interleave until the cost of the
  4679. // loop overhead is about 5% of the cost of the loop.
  4680. unsigned SmallIC =
  4681. std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
  4682. // Interleave until store/load ports (estimated by max interleave count) are
  4683. // saturated.
  4684. unsigned NumStores = Legal->getNumStores();
  4685. unsigned NumLoads = Legal->getNumLoads();
  4686. unsigned StoresIC = IC / (NumStores ? NumStores : 1);
  4687. unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
  4688. // If we have a scalar reduction (vector reductions are already dealt with
  4689. // by this point), we can increase the critical path length if the loop
  4690. // we're interleaving is inside another loop. Limit, by default to 2, so the
  4691. // critical path only gets increased by one reduction operation.
  4692. if (Legal->getReductionVars()->size() &&
  4693. TheLoop->getLoopDepth() > 1) {
  4694. unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
  4695. SmallIC = std::min(SmallIC, F);
  4696. StoresIC = std::min(StoresIC, F);
  4697. LoadsIC = std::min(LoadsIC, F);
  4698. }
  4699. if (EnableLoadStoreRuntimeInterleave &&
  4700. std::max(StoresIC, LoadsIC) > SmallIC) {
  4701. DEBUG(dbgs() << "LV: Interleaving to saturate store or load ports.\n");
  4702. return std::max(StoresIC, LoadsIC);
  4703. }
  4704. DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
  4705. return SmallIC;
  4706. }
  4707. // Interleave if this is a large loop (small loops are already dealt with by
  4708. // this point) that could benefit from interleaving.
  4709. bool HasReductions = (Legal->getReductionVars()->size() > 0);
  4710. if (TTI.enableAggressiveInterleaving(HasReductions)) {
  4711. DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  4712. return IC;
  4713. }
  4714. DEBUG(dbgs() << "LV: Not Interleaving.\n");
  4715. return 1;
  4716. }
  4717. SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
  4718. LoopVectorizationCostModel::calculateRegisterUsage(
  4719. const SmallVector<unsigned, 8> &VFs) {
  4720. // This function calculates the register usage by measuring the highest number
  4721. // of values that are alive at a single location. Obviously, this is a very
  4722. // rough estimation. We scan the loop in a topological order in order and
  4723. // assign a number to each instruction. We use RPO to ensure that defs are
  4724. // met before their users. We assume that each instruction that has in-loop
  4725. // users starts an interval. We record every time that an in-loop value is
  4726. // used, so we have a list of the first and last occurrences of each
  4727. // instruction. Next, we transpose this data structure into a multi map that
  4728. // holds the list of intervals that *end* at a specific location. This multi
  4729. // map allows us to perform a linear search. We scan the instructions linearly
  4730. // and record each time that a new interval starts, by placing it in a set.
  4731. // If we find this value in the multi-map then we remove it from the set.
  4732. // The max register usage is the maximum size of the set.
  4733. // We also search for instructions that are defined outside the loop, but are
  4734. // used inside the loop. We need this number separately from the max-interval
  4735. // usage number because when we unroll, loop-invariant values do not take
  4736. // more register.
  4737. LoopBlocksDFS DFS(TheLoop);
  4738. DFS.perform(LI);
  4739. RegisterUsage RU;
  4740. RU.NumInstructions = 0;
  4741. // Each 'key' in the map opens a new interval. The values
  4742. // of the map are the index of the 'last seen' usage of the
  4743. // instruction that is the key.
  4744. typedef DenseMap<Instruction*, unsigned> IntervalMap;
  4745. // Maps instruction to its index.
  4746. DenseMap<unsigned, Instruction*> IdxToInstr;
  4747. // Marks the end of each interval.
  4748. IntervalMap EndPoint;
  4749. // Saves the list of instruction indices that are used in the loop.
  4750. SmallSet<Instruction*, 8> Ends;
  4751. // Saves the list of values that are used in the loop but are
  4752. // defined outside the loop, such as arguments and constants.
  4753. SmallPtrSet<Value*, 8> LoopInvariants;
  4754. unsigned Index = 0;
  4755. for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
  4756. be = DFS.endRPO(); bb != be; ++bb) {
  4757. RU.NumInstructions += (*bb)->size();
  4758. for (Instruction &I : **bb) {
  4759. IdxToInstr[Index++] = &I;
  4760. // Save the end location of each USE.
  4761. for (unsigned i = 0; i < I.getNumOperands(); ++i) {
  4762. Value *U = I.getOperand(i);
  4763. Instruction *Instr = dyn_cast<Instruction>(U);
  4764. // Ignore non-instruction values such as arguments, constants, etc.
  4765. if (!Instr) continue;
  4766. // If this instruction is outside the loop then record it and continue.
  4767. if (!TheLoop->contains(Instr)) {
  4768. LoopInvariants.insert(Instr);
  4769. continue;
  4770. }
  4771. // Overwrite previous end points.
  4772. EndPoint[Instr] = Index;
  4773. Ends.insert(Instr);
  4774. }
  4775. }
  4776. }
  4777. // Saves the list of intervals that end with the index in 'key'.
  4778. typedef SmallVector<Instruction*, 2> InstrList;
  4779. DenseMap<unsigned, InstrList> TransposeEnds;
  4780. // Transpose the EndPoints to a list of values that end at each index.
  4781. for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
  4782. it != e; ++it)
  4783. TransposeEnds[it->second].push_back(it->first);
  4784. SmallSet<Instruction*, 8> OpenIntervals;
  4785. // Get the size of the widest register.
  4786. unsigned MaxSafeDepDist = -1U;
  4787. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4788. MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
  4789. unsigned WidestRegister =
  4790. std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
  4791. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4792. SmallVector<RegisterUsage, 8> RUs(VFs.size());
  4793. SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
  4794. DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  4795. // A lambda that gets the register usage for the given type and VF.
  4796. auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
  4797. unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
  4798. return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
  4799. };
  4800. for (unsigned int i = 0; i < Index; ++i) {
  4801. Instruction *I = IdxToInstr[i];
  4802. // Ignore instructions that are never used within the loop.
  4803. if (!Ends.count(I)) continue;
  4804. // Skip ignored values.
  4805. if (ValuesToIgnore.count(I))
  4806. continue;
  4807. // Remove all of the instructions that end at this location.
  4808. InstrList &List = TransposeEnds[i];
  4809. for (unsigned int j = 0, e = List.size(); j < e; ++j)
  4810. OpenIntervals.erase(List[j]);
  4811. // For each VF find the maximum usage of registers.
  4812. for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
  4813. if (VFs[j] == 1) {
  4814. MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
  4815. continue;
  4816. }
  4817. // Count the number of live intervals.
  4818. unsigned RegUsage = 0;
  4819. for (auto Inst : OpenIntervals)
  4820. RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
  4821. MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
  4822. }
  4823. DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
  4824. << OpenIntervals.size() << '\n');
  4825. // Add the current instruction to the list of open intervals.
  4826. OpenIntervals.insert(I);
  4827. }
  4828. for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
  4829. unsigned Invariant = 0;
  4830. if (VFs[i] == 1)
  4831. Invariant = LoopInvariants.size();
  4832. else {
  4833. for (auto Inst : LoopInvariants)
  4834. Invariant += GetRegUsage(Inst->getType(), VFs[i]);
  4835. }
  4836. DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
  4837. DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
  4838. DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
  4839. DEBUG(dbgs() << "LV(REG): LoopSize: " << RU.NumInstructions << '\n');
  4840. RU.LoopInvariantRegs = Invariant;
  4841. RU.MaxLocalUsers = MaxUsages[i];
  4842. RUs[i] = RU;
  4843. }
  4844. return RUs;
  4845. }
  4846. LoopVectorizationCostModel::VectorizationCostTy
  4847. LoopVectorizationCostModel::expectedCost(unsigned VF) {
  4848. VectorizationCostTy Cost;
  4849. // For each block.
  4850. for (Loop::block_iterator bb = TheLoop->block_begin(),
  4851. be = TheLoop->block_end(); bb != be; ++bb) {
  4852. VectorizationCostTy BlockCost;
  4853. BasicBlock *BB = *bb;
  4854. // For each instruction in the old loop.
  4855. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4856. // Skip dbg intrinsics.
  4857. if (isa<DbgInfoIntrinsic>(it))
  4858. continue;
  4859. // Skip ignored values.
  4860. if (ValuesToIgnore.count(&*it))
  4861. continue;
  4862. VectorizationCostTy C = getInstructionCost(&*it, VF);
  4863. // Check if we should override the cost.
  4864. if (ForceTargetInstructionCost.getNumOccurrences() > 0)
  4865. C.first = ForceTargetInstructionCost;
  4866. BlockCost.first += C.first;
  4867. BlockCost.second |= C.second;
  4868. DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first <<
  4869. " for VF " << VF << " For instruction: " << *it << '\n');
  4870. }
  4871. // We assume that if-converted blocks have a 50% chance of being executed.
  4872. // When the code is scalar then some of the blocks are avoided due to CF.
  4873. // When the code is vectorized we execute all code paths.
  4874. if (VF == 1 && Legal->blockNeedsPredication(*bb))
  4875. BlockCost.first /= 2;
  4876. Cost.first += BlockCost.first;
  4877. Cost.second |= BlockCost.second;
  4878. }
  4879. return Cost;
  4880. }
  4881. /// \brief Check if the load/store instruction \p I may be translated into
  4882. /// gather/scatter during vectorization.
  4883. ///
  4884. /// Pointer \p Ptr specifies address in memory for the given scalar memory
  4885. /// instruction. We need it to retrieve data type.
  4886. /// Using gather/scatter is possible when it is supported by target.
  4887. static bool isGatherOrScatterLegal(Instruction *I, Value *Ptr,
  4888. LoopVectorizationLegality *Legal) {
  4889. Type *DataTy = cast<PointerType>(Ptr->getType())->getElementType();
  4890. return (isa<LoadInst>(I) && Legal->isLegalMaskedGather(DataTy)) ||
  4891. (isa<StoreInst>(I) && Legal->isLegalMaskedScatter(DataTy));
  4892. }
  4893. /// \brief Check whether the address computation for a non-consecutive memory
  4894. /// access looks like an unlikely candidate for being merged into the indexing
  4895. /// mode.
  4896. ///
  4897. /// We look for a GEP which has one index that is an induction variable and all
  4898. /// other indices are loop invariant. If the stride of this access is also
  4899. /// within a small bound we decide that this address computation can likely be
  4900. /// merged into the addressing mode.
  4901. /// In all other cases, we identify the address computation as complex.
  4902. static bool isLikelyComplexAddressComputation(Value *Ptr,
  4903. LoopVectorizationLegality *Legal,
  4904. ScalarEvolution *SE,
  4905. const Loop *TheLoop) {
  4906. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  4907. if (!Gep)
  4908. return true;
  4909. // We are looking for a gep with all loop invariant indices except for one
  4910. // which should be an induction variable.
  4911. unsigned NumOperands = Gep->getNumOperands();
  4912. for (unsigned i = 1; i < NumOperands; ++i) {
  4913. Value *Opd = Gep->getOperand(i);
  4914. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  4915. !Legal->isInductionVariable(Opd))
  4916. return true;
  4917. }
  4918. // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
  4919. // can likely be merged into the address computation.
  4920. unsigned MaxMergeDistance = 64;
  4921. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
  4922. if (!AddRec)
  4923. return true;
  4924. // Check the step is constant.
  4925. const SCEV *Step = AddRec->getStepRecurrence(*SE);
  4926. // Calculate the pointer stride and check if it is consecutive.
  4927. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  4928. if (!C)
  4929. return true;
  4930. const APInt &APStepVal = C->getAPInt();
  4931. // Huge step value - give up.
  4932. if (APStepVal.getBitWidth() > 64)
  4933. return true;
  4934. int64_t StepVal = APStepVal.getSExtValue();
  4935. return StepVal > MaxMergeDistance;
  4936. }
  4937. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  4938. return Legal->hasStride(I->getOperand(0)) ||
  4939. Legal->hasStride(I->getOperand(1));
  4940. }
  4941. LoopVectorizationCostModel::VectorizationCostTy
  4942. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
  4943. // If we know that this instruction will remain uniform, check the cost of
  4944. // the scalar version.
  4945. if (Legal->isUniformAfterVectorization(I))
  4946. VF = 1;
  4947. Type *VectorTy;
  4948. unsigned C = getInstructionCost(I, VF, VectorTy);
  4949. bool TypeNotScalarized = VF > 1 && !VectorTy->isVoidTy() &&
  4950. TTI.getNumberOfParts(VectorTy) < VF;
  4951. return VectorizationCostTy(C, TypeNotScalarized);
  4952. }
  4953. unsigned
  4954. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF,
  4955. Type *&VectorTy) {
  4956. Type *RetTy = I->getType();
  4957. if (VF > 1 && MinBWs.count(I))
  4958. RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
  4959. VectorTy = ToVectorTy(RetTy, VF);
  4960. // TODO: We need to estimate the cost of intrinsic calls.
  4961. switch (I->getOpcode()) {
  4962. case Instruction::GetElementPtr:
  4963. // We mark this instruction as zero-cost because the cost of GEPs in
  4964. // vectorized code depends on whether the corresponding memory instruction
  4965. // is scalarized or not. Therefore, we handle GEPs with the memory
  4966. // instruction cost.
  4967. return 0;
  4968. case Instruction::Br: {
  4969. return TTI.getCFInstrCost(I->getOpcode());
  4970. }
  4971. case Instruction::PHI: {
  4972. auto *Phi = cast<PHINode>(I);
  4973. // First-order recurrences are replaced by vector shuffles inside the loop.
  4974. if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
  4975. return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  4976. VectorTy, VF - 1, VectorTy);
  4977. // TODO: IF-converted IFs become selects.
  4978. return 0;
  4979. }
  4980. case Instruction::Add:
  4981. case Instruction::FAdd:
  4982. case Instruction::Sub:
  4983. case Instruction::FSub:
  4984. case Instruction::Mul:
  4985. case Instruction::FMul:
  4986. case Instruction::UDiv:
  4987. case Instruction::SDiv:
  4988. case Instruction::FDiv:
  4989. case Instruction::URem:
  4990. case Instruction::SRem:
  4991. case Instruction::FRem:
  4992. case Instruction::Shl:
  4993. case Instruction::LShr:
  4994. case Instruction::AShr:
  4995. case Instruction::And:
  4996. case Instruction::Or:
  4997. case Instruction::Xor: {
  4998. // Since we will replace the stride by 1 the multiplication should go away.
  4999. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  5000. return 0;
  5001. // Certain instructions can be cheaper to vectorize if they have a constant
  5002. // second vector operand. One example of this are shifts on x86.
  5003. TargetTransformInfo::OperandValueKind Op1VK =
  5004. TargetTransformInfo::OK_AnyValue;
  5005. TargetTransformInfo::OperandValueKind Op2VK =
  5006. TargetTransformInfo::OK_AnyValue;
  5007. TargetTransformInfo::OperandValueProperties Op1VP =
  5008. TargetTransformInfo::OP_None;
  5009. TargetTransformInfo::OperandValueProperties Op2VP =
  5010. TargetTransformInfo::OP_None;
  5011. Value *Op2 = I->getOperand(1);
  5012. // Check for a splat of a constant or for a non uniform vector of constants.
  5013. if (isa<ConstantInt>(Op2)) {
  5014. ConstantInt *CInt = cast<ConstantInt>(Op2);
  5015. if (CInt && CInt->getValue().isPowerOf2())
  5016. Op2VP = TargetTransformInfo::OP_PowerOf2;
  5017. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  5018. } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
  5019. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  5020. Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
  5021. if (SplatValue) {
  5022. ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
  5023. if (CInt && CInt->getValue().isPowerOf2())
  5024. Op2VP = TargetTransformInfo::OP_PowerOf2;
  5025. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  5026. }
  5027. }
  5028. return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK,
  5029. Op1VP, Op2VP);
  5030. }
  5031. case Instruction::Select: {
  5032. SelectInst *SI = cast<SelectInst>(I);
  5033. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  5034. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  5035. Type *CondTy = SI->getCondition()->getType();
  5036. if (!ScalarCond)
  5037. CondTy = VectorType::get(CondTy, VF);
  5038. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
  5039. }
  5040. case Instruction::ICmp:
  5041. case Instruction::FCmp: {
  5042. Type *ValTy = I->getOperand(0)->getType();
  5043. Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
  5044. auto It = MinBWs.find(Op0AsInstruction);
  5045. if (VF > 1 && It != MinBWs.end())
  5046. ValTy = IntegerType::get(ValTy->getContext(), It->second);
  5047. VectorTy = ToVectorTy(ValTy, VF);
  5048. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
  5049. }
  5050. case Instruction::Store:
  5051. case Instruction::Load: {
  5052. StoreInst *SI = dyn_cast<StoreInst>(I);
  5053. LoadInst *LI = dyn_cast<LoadInst>(I);
  5054. Type *ValTy = (SI ? SI->getValueOperand()->getType() :
  5055. LI->getType());
  5056. VectorTy = ToVectorTy(ValTy, VF);
  5057. unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
  5058. unsigned AS = SI ? SI->getPointerAddressSpace() :
  5059. LI->getPointerAddressSpace();
  5060. Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
  5061. // We add the cost of address computation here instead of with the gep
  5062. // instruction because only here we know whether the operation is
  5063. // scalarized.
  5064. if (VF == 1)
  5065. return TTI.getAddressComputationCost(VectorTy) +
  5066. TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  5067. if (LI && Legal->isUniform(Ptr)) {
  5068. // Scalar load + broadcast
  5069. unsigned Cost = TTI.getAddressComputationCost(ValTy->getScalarType());
  5070. Cost += TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
  5071. Alignment, AS);
  5072. return Cost + TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast,
  5073. ValTy);
  5074. }
  5075. // For an interleaved access, calculate the total cost of the whole
  5076. // interleave group.
  5077. if (Legal->isAccessInterleaved(I)) {
  5078. auto Group = Legal->getInterleavedAccessGroup(I);
  5079. assert(Group && "Fail to get an interleaved access group.");
  5080. // Only calculate the cost once at the insert position.
  5081. if (Group->getInsertPos() != I)
  5082. return 0;
  5083. unsigned InterleaveFactor = Group->getFactor();
  5084. Type *WideVecTy =
  5085. VectorType::get(VectorTy->getVectorElementType(),
  5086. VectorTy->getVectorNumElements() * InterleaveFactor);
  5087. // Holds the indices of existing members in an interleaved load group.
  5088. // An interleaved store group doesn't need this as it dones't allow gaps.
  5089. SmallVector<unsigned, 4> Indices;
  5090. if (LI) {
  5091. for (unsigned i = 0; i < InterleaveFactor; i++)
  5092. if (Group->getMember(i))
  5093. Indices.push_back(i);
  5094. }
  5095. // Calculate the cost of the whole interleaved group.
  5096. unsigned Cost = TTI.getInterleavedMemoryOpCost(
  5097. I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
  5098. Group->getAlignment(), AS);
  5099. if (Group->isReverse())
  5100. Cost +=
  5101. Group->getNumMembers() *
  5102. TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  5103. // FIXME: The interleaved load group with a huge gap could be even more
  5104. // expensive than scalar operations. Then we could ignore such group and
  5105. // use scalar operations instead.
  5106. return Cost;
  5107. }
  5108. // Scalarized loads/stores.
  5109. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  5110. bool UseGatherOrScatter = (ConsecutiveStride == 0) &&
  5111. isGatherOrScatterLegal(I, Ptr, Legal);
  5112. bool Reverse = ConsecutiveStride < 0;
  5113. const DataLayout &DL = I->getModule()->getDataLayout();
  5114. unsigned ScalarAllocatedSize = DL.getTypeAllocSize(ValTy);
  5115. unsigned VectorElementSize = DL.getTypeStoreSize(VectorTy) / VF;
  5116. if ((!ConsecutiveStride && !UseGatherOrScatter) ||
  5117. ScalarAllocatedSize != VectorElementSize) {
  5118. bool IsComplexComputation =
  5119. isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
  5120. unsigned Cost = 0;
  5121. // The cost of extracting from the value vector and pointer vector.
  5122. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  5123. for (unsigned i = 0; i < VF; ++i) {
  5124. // The cost of extracting the pointer operand.
  5125. Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
  5126. // In case of STORE, the cost of ExtractElement from the vector.
  5127. // In case of LOAD, the cost of InsertElement into the returned
  5128. // vector.
  5129. Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
  5130. Instruction::InsertElement,
  5131. VectorTy, i);
  5132. }
  5133. // The cost of the scalar loads/stores.
  5134. Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
  5135. Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
  5136. Alignment, AS);
  5137. return Cost;
  5138. }
  5139. unsigned Cost = TTI.getAddressComputationCost(VectorTy);
  5140. if (UseGatherOrScatter) {
  5141. assert(ConsecutiveStride == 0 &&
  5142. "Gather/Scatter are not used for consecutive stride");
  5143. return Cost +
  5144. TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
  5145. Legal->isMaskRequired(I), Alignment);
  5146. }
  5147. // Wide load/stores.
  5148. if (Legal->isMaskRequired(I))
  5149. Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment,
  5150. AS);
  5151. else
  5152. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  5153. if (Reverse)
  5154. Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
  5155. VectorTy, 0);
  5156. return Cost;
  5157. }
  5158. case Instruction::ZExt:
  5159. case Instruction::SExt:
  5160. case Instruction::FPToUI:
  5161. case Instruction::FPToSI:
  5162. case Instruction::FPExt:
  5163. case Instruction::PtrToInt:
  5164. case Instruction::IntToPtr:
  5165. case Instruction::SIToFP:
  5166. case Instruction::UIToFP:
  5167. case Instruction::Trunc:
  5168. case Instruction::FPTrunc:
  5169. case Instruction::BitCast: {
  5170. // We optimize the truncation of induction variable.
  5171. // The cost of these is the same as the scalar operation.
  5172. if (I->getOpcode() == Instruction::Trunc &&
  5173. Legal->isInductionVariable(I->getOperand(0)))
  5174. return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
  5175. I->getOperand(0)->getType());
  5176. Type *SrcScalarTy = I->getOperand(0)->getType();
  5177. Type *SrcVecTy = ToVectorTy(SrcScalarTy, VF);
  5178. if (VF > 1 && MinBWs.count(I)) {
  5179. // This cast is going to be shrunk. This may remove the cast or it might
  5180. // turn it into slightly different cast. For example, if MinBW == 16,
  5181. // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
  5182. //
  5183. // Calculate the modified src and dest types.
  5184. Type *MinVecTy = VectorTy;
  5185. if (I->getOpcode() == Instruction::Trunc) {
  5186. SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
  5187. VectorTy = largestIntegerVectorType(ToVectorTy(I->getType(), VF),
  5188. MinVecTy);
  5189. } else if (I->getOpcode() == Instruction::ZExt ||
  5190. I->getOpcode() == Instruction::SExt) {
  5191. SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
  5192. VectorTy = smallestIntegerVectorType(ToVectorTy(I->getType(), VF),
  5193. MinVecTy);
  5194. }
  5195. }
  5196. return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
  5197. }
  5198. case Instruction::Call: {
  5199. bool NeedToScalarize;
  5200. CallInst *CI = cast<CallInst>(I);
  5201. unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
  5202. if (getVectorIntrinsicIDForCall(CI, TLI))
  5203. return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
  5204. return CallCost;
  5205. }
  5206. default: {
  5207. // We are scalarizing the instruction. Return the cost of the scalar
  5208. // instruction, plus the cost of insert and extract into vector
  5209. // elements, times the vector width.
  5210. unsigned Cost = 0;
  5211. if (!RetTy->isVoidTy() && VF != 1) {
  5212. unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
  5213. VectorTy);
  5214. unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
  5215. VectorTy);
  5216. // The cost of inserting the results plus extracting each one of the
  5217. // operands.
  5218. Cost += VF * (InsCost + ExtCost * I->getNumOperands());
  5219. }
  5220. // The cost of executing VF copies of the scalar instruction. This opcode
  5221. // is unknown. Assume that it is the same as 'mul'.
  5222. Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
  5223. return Cost;
  5224. }
  5225. }// end of switch.
  5226. }
  5227. char LoopVectorize::ID = 0;
  5228. static const char lv_name[] = "Loop Vectorization";
  5229. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  5230. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  5231. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  5232. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  5233. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  5234. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  5235. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  5236. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  5237. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  5238. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  5239. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  5240. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  5241. INITIALIZE_PASS_DEPENDENCY(LoopAccessAnalysis)
  5242. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  5243. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  5244. namespace llvm {
  5245. Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
  5246. return new LoopVectorize(NoUnrolling, AlwaysVectorize);
  5247. }
  5248. }
  5249. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  5250. // Check for a store.
  5251. if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
  5252. return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
  5253. // Check for a load.
  5254. if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  5255. return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
  5256. return false;
  5257. }
  5258. void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr,
  5259. bool IfPredicateStore) {
  5260. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  5261. // Holds vector parameters or scalars, in case of uniform vals.
  5262. SmallVector<VectorParts, 4> Params;
  5263. setDebugLocFromInst(Builder, Instr);
  5264. // Find all of the vectorized parameters.
  5265. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  5266. Value *SrcOp = Instr->getOperand(op);
  5267. // If we are accessing the old induction variable, use the new one.
  5268. if (SrcOp == OldInduction) {
  5269. Params.push_back(getVectorValue(SrcOp));
  5270. continue;
  5271. }
  5272. // Try using previously calculated values.
  5273. Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
  5274. // If the src is an instruction that appeared earlier in the basic block
  5275. // then it should already be vectorized.
  5276. if (SrcInst && OrigLoop->contains(SrcInst)) {
  5277. assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
  5278. // The parameter is a vector value from earlier.
  5279. Params.push_back(WidenMap.get(SrcInst));
  5280. } else {
  5281. // The parameter is a scalar from outside the loop. Maybe even a constant.
  5282. VectorParts Scalars;
  5283. Scalars.append(UF, SrcOp);
  5284. Params.push_back(Scalars);
  5285. }
  5286. }
  5287. assert(Params.size() == Instr->getNumOperands() &&
  5288. "Invalid number of operands");
  5289. // Does this instruction return a value ?
  5290. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  5291. Value *UndefVec = IsVoidRetTy ? nullptr :
  5292. UndefValue::get(Instr->getType());
  5293. // Create a new entry in the WidenMap and initialize it to Undef or Null.
  5294. VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
  5295. VectorParts Cond;
  5296. if (IfPredicateStore) {
  5297. assert(Instr->getParent()->getSinglePredecessor() &&
  5298. "Only support single predecessor blocks");
  5299. Cond = createEdgeMask(Instr->getParent()->getSinglePredecessor(),
  5300. Instr->getParent());
  5301. }
  5302. // For each vector unroll 'part':
  5303. for (unsigned Part = 0; Part < UF; ++Part) {
  5304. // For each scalar that we create:
  5305. // Start an "if (pred) a[i] = ..." block.
  5306. Value *Cmp = nullptr;
  5307. if (IfPredicateStore) {
  5308. if (Cond[Part]->getType()->isVectorTy())
  5309. Cond[Part] =
  5310. Builder.CreateExtractElement(Cond[Part], Builder.getInt32(0));
  5311. Cmp = Builder.CreateICmp(ICmpInst::ICMP_EQ, Cond[Part],
  5312. ConstantInt::get(Cond[Part]->getType(), 1));
  5313. }
  5314. Instruction *Cloned = Instr->clone();
  5315. if (!IsVoidRetTy)
  5316. Cloned->setName(Instr->getName() + ".cloned");
  5317. // Replace the operands of the cloned instructions with extracted scalars.
  5318. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  5319. Value *Op = Params[op][Part];
  5320. Cloned->setOperand(op, Op);
  5321. }
  5322. // Place the cloned scalar in the new loop.
  5323. Builder.Insert(Cloned);
  5324. // If we just cloned a new assumption, add it the assumption cache.
  5325. if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
  5326. if (II->getIntrinsicID() == Intrinsic::assume)
  5327. AC->registerAssumption(II);
  5328. // If the original scalar returns a value we need to place it in a vector
  5329. // so that future users will be able to use it.
  5330. if (!IsVoidRetTy)
  5331. VecResults[Part] = Cloned;
  5332. // End if-block.
  5333. if (IfPredicateStore)
  5334. PredicatedStores.push_back(std::make_pair(cast<StoreInst>(Cloned),
  5335. Cmp));
  5336. }
  5337. }
  5338. void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
  5339. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  5340. bool IfPredicateStore = (SI && Legal->blockNeedsPredication(SI->getParent()));
  5341. return scalarizeInstruction(Instr, IfPredicateStore);
  5342. }
  5343. Value *InnerLoopUnroller::reverseVector(Value *Vec) {
  5344. return Vec;
  5345. }
  5346. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
  5347. return V;
  5348. }
  5349. Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step) {
  5350. // When unrolling and the VF is 1, we only need to add a simple scalar.
  5351. Type *ITy = Val->getType();
  5352. assert(!ITy->isVectorTy() && "Val must be a scalar");
  5353. Constant *C = ConstantInt::get(ITy, StartIdx);
  5354. return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
  5355. }