LoopVectorize.cpp 204 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517
  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. // Other ideas/concepts are from:
  38. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  39. //
  40. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  41. // Vectorizing Compilers.
  42. //
  43. //===----------------------------------------------------------------------===//
  44. #define LV_NAME "loop-vectorize"
  45. #define DEBUG_TYPE LV_NAME
  46. #include "llvm/Transforms/Vectorize.h"
  47. #include "llvm/ADT/DenseMap.h"
  48. #include "llvm/ADT/EquivalenceClasses.h"
  49. #include "llvm/ADT/Hashing.h"
  50. #include "llvm/ADT/MapVector.h"
  51. #include "llvm/ADT/SetVector.h"
  52. #include "llvm/ADT/SmallPtrSet.h"
  53. #include "llvm/ADT/SmallSet.h"
  54. #include "llvm/ADT/SmallVector.h"
  55. #include "llvm/ADT/StringExtras.h"
  56. #include "llvm/Analysis/AliasAnalysis.h"
  57. #include "llvm/Analysis/LoopInfo.h"
  58. #include "llvm/Analysis/LoopIterator.h"
  59. #include "llvm/Analysis/LoopPass.h"
  60. #include "llvm/Analysis/ScalarEvolution.h"
  61. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  62. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  63. #include "llvm/Analysis/TargetTransformInfo.h"
  64. #include "llvm/Analysis/ValueTracking.h"
  65. #include "llvm/IR/Constants.h"
  66. #include "llvm/IR/DataLayout.h"
  67. #include "llvm/IR/DerivedTypes.h"
  68. #include "llvm/IR/Dominators.h"
  69. #include "llvm/IR/Function.h"
  70. #include "llvm/IR/IRBuilder.h"
  71. #include "llvm/IR/Instructions.h"
  72. #include "llvm/IR/IntrinsicInst.h"
  73. #include "llvm/IR/LLVMContext.h"
  74. #include "llvm/IR/Module.h"
  75. #include "llvm/IR/Type.h"
  76. #include "llvm/IR/Value.h"
  77. #include "llvm/IR/Verifier.h"
  78. #include "llvm/Pass.h"
  79. #include "llvm/Support/CommandLine.h"
  80. #include "llvm/Support/Debug.h"
  81. #include "llvm/Support/PatternMatch.h"
  82. #include "llvm/Support/ValueHandle.h"
  83. #include "llvm/Support/raw_ostream.h"
  84. #include "llvm/Target/TargetLibraryInfo.h"
  85. #include "llvm/Transforms/Scalar.h"
  86. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  87. #include "llvm/Transforms/Utils/Local.h"
  88. #include <algorithm>
  89. #include <map>
  90. using namespace llvm;
  91. using namespace llvm::PatternMatch;
  92. static cl::opt<unsigned>
  93. VectorizationFactor("force-vector-width", cl::init(0), cl::Hidden,
  94. cl::desc("Sets the SIMD width. Zero is autoselect."));
  95. static cl::opt<unsigned>
  96. VectorizationUnroll("force-vector-unroll", cl::init(0), cl::Hidden,
  97. cl::desc("Sets the vectorization unroll count. "
  98. "Zero is autoselect."));
  99. static cl::opt<bool>
  100. EnableIfConversion("enable-if-conversion", cl::init(true), cl::Hidden,
  101. cl::desc("Enable if-conversion during vectorization."));
  102. /// We don't vectorize loops with a known constant trip count below this number.
  103. static cl::opt<unsigned>
  104. TinyTripCountVectorThreshold("vectorizer-min-trip-count", cl::init(16),
  105. cl::Hidden,
  106. cl::desc("Don't vectorize loops with a constant "
  107. "trip count that is smaller than this "
  108. "value."));
  109. /// This enables versioning on the strides of symbolically striding memory
  110. /// accesses in code like the following.
  111. /// for (i = 0; i < N; ++i)
  112. /// A[i * Stride1] += B[i * Stride2] ...
  113. ///
  114. /// Will be roughly translated to
  115. /// if (Stride1 == 1 && Stride2 == 1) {
  116. /// for (i = 0; i < N; i+=4)
  117. /// A[i:i+3] += ...
  118. /// } else
  119. /// ...
  120. static cl::opt<bool> EnableMemAccessVersioning(
  121. "enable-mem-access-versioning", cl::init(true), cl::Hidden,
  122. cl::desc("Enable symblic stride memory access versioning"));
  123. /// We don't unroll loops with a known constant trip count below this number.
  124. static const unsigned TinyTripCountUnrollThreshold = 128;
  125. /// When performing memory disambiguation checks at runtime do not make more
  126. /// than this number of comparisons.
  127. static const unsigned RuntimeMemoryCheckThreshold = 8;
  128. /// Maximum simd width.
  129. static const unsigned MaxVectorWidth = 64;
  130. /// Maximum vectorization unroll count.
  131. static const unsigned MaxUnrollFactor = 16;
  132. /// The cost of a loop that is considered 'small' by the unroller.
  133. static const unsigned SmallLoopCost = 20;
  134. namespace {
  135. // Forward declarations.
  136. class LoopVectorizationLegality;
  137. class LoopVectorizationCostModel;
  138. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  139. /// block to a specified vectorization factor (VF).
  140. /// This class performs the widening of scalars into vectors, or multiple
  141. /// scalars. This class also implements the following features:
  142. /// * It inserts an epilogue loop for handling loops that don't have iteration
  143. /// counts that are known to be a multiple of the vectorization factor.
  144. /// * It handles the code generation for reduction variables.
  145. /// * Scalarization (implementation using scalars) of un-vectorizable
  146. /// instructions.
  147. /// InnerLoopVectorizer does not perform any vectorization-legality
  148. /// checks, and relies on the caller to check for the different legality
  149. /// aspects. The InnerLoopVectorizer relies on the
  150. /// LoopVectorizationLegality class to provide information about the induction
  151. /// and reduction variables that were found to a given vectorization factor.
  152. class InnerLoopVectorizer {
  153. public:
  154. InnerLoopVectorizer(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
  155. DominatorTree *DT, DataLayout *DL,
  156. const TargetLibraryInfo *TLI, unsigned VecWidth,
  157. unsigned UnrollFactor)
  158. : OrigLoop(OrigLoop), SE(SE), LI(LI), DT(DT), DL(DL), TLI(TLI),
  159. VF(VecWidth), UF(UnrollFactor), Builder(SE->getContext()), Induction(0),
  160. OldInduction(0), WidenMap(UnrollFactor), Legal(0) {}
  161. // Perform the actual loop widening (vectorization).
  162. void vectorize(LoopVectorizationLegality *L) {
  163. Legal = L;
  164. // Create a new empty loop. Unlink the old loop and connect the new one.
  165. createEmptyLoop();
  166. // Widen each instruction in the old loop to a new one in the new loop.
  167. // Use the Legality module to find the induction and reduction variables.
  168. vectorizeLoop();
  169. // Register the new loop and update the analysis passes.
  170. updateAnalysis();
  171. }
  172. virtual ~InnerLoopVectorizer() {}
  173. protected:
  174. /// A small list of PHINodes.
  175. typedef SmallVector<PHINode*, 4> PhiVector;
  176. /// When we unroll loops we have multiple vector values for each scalar.
  177. /// This data structure holds the unrolled and vectorized values that
  178. /// originated from one scalar instruction.
  179. typedef SmallVector<Value*, 2> VectorParts;
  180. // When we if-convert we need create edge masks. We have to cache values so
  181. // that we don't end up with exponential recursion/IR.
  182. typedef DenseMap<std::pair<BasicBlock*, BasicBlock*>,
  183. VectorParts> EdgeMaskCache;
  184. /// \brief Add code that checks at runtime if the accessed arrays overlap.
  185. ///
  186. /// Returns a pair of instructions where the first element is the first
  187. /// instruction generated in possibly a sequence of instructions and the
  188. /// second value is the final comparator value or NULL if no check is needed.
  189. std::pair<Instruction *, Instruction *> addRuntimeCheck(Instruction *Loc);
  190. /// \brief Add checks for strides that where assumed to be 1.
  191. ///
  192. /// Returns the last check instruction and the first check instruction in the
  193. /// pair as (first, last).
  194. std::pair<Instruction *, Instruction *> addStrideCheck(Instruction *Loc);
  195. /// Create an empty loop, based on the loop ranges of the old loop.
  196. void createEmptyLoop();
  197. /// Copy and widen the instructions from the old loop.
  198. virtual void vectorizeLoop();
  199. /// \brief The Loop exit block may have single value PHI nodes where the
  200. /// incoming value is 'Undef'. While vectorizing we only handled real values
  201. /// that were defined inside the loop. Here we fix the 'undef case'.
  202. /// See PR14725.
  203. void fixLCSSAPHIs();
  204. /// A helper function that computes the predicate of the block BB, assuming
  205. /// that the header block of the loop is set to True. It returns the *entry*
  206. /// mask for the block BB.
  207. VectorParts createBlockInMask(BasicBlock *BB);
  208. /// A helper function that computes the predicate of the edge between SRC
  209. /// and DST.
  210. VectorParts createEdgeMask(BasicBlock *Src, BasicBlock *Dst);
  211. /// A helper function to vectorize a single BB within the innermost loop.
  212. void vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV);
  213. /// Vectorize a single PHINode in a block. This method handles the induction
  214. /// variable canonicalization. It supports both VF = 1 for unrolled loops and
  215. /// arbitrary length vectors.
  216. void widenPHIInstruction(Instruction *PN, VectorParts &Entry,
  217. unsigned UF, unsigned VF, PhiVector *PV);
  218. /// Insert the new loop to the loop hierarchy and pass manager
  219. /// and update the analysis passes.
  220. void updateAnalysis();
  221. /// This instruction is un-vectorizable. Implement it as a sequence
  222. /// of scalars.
  223. virtual void scalarizeInstruction(Instruction *Instr);
  224. /// Vectorize Load and Store instructions,
  225. virtual void vectorizeMemoryInstruction(Instruction *Instr);
  226. /// Create a broadcast instruction. This method generates a broadcast
  227. /// instruction (shuffle) for loop invariant values and for the induction
  228. /// value. If this is the induction variable then we extend it to N, N+1, ...
  229. /// this is needed because each iteration in the loop corresponds to a SIMD
  230. /// element.
  231. virtual Value *getBroadcastInstrs(Value *V);
  232. /// This function adds 0, 1, 2 ... to each vector element, starting at zero.
  233. /// If Negate is set then negative numbers are added e.g. (0, -1, -2, ...).
  234. /// The sequence starts at StartIndex.
  235. virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
  236. /// When we go over instructions in the basic block we rely on previous
  237. /// values within the current basic block or on loop invariant values.
  238. /// When we widen (vectorize) values we place them in the map. If the values
  239. /// are not within the map, they have to be loop invariant, so we simply
  240. /// broadcast them into a vector.
  241. VectorParts &getVectorValue(Value *V);
  242. /// Generate a shuffle sequence that will reverse the vector Vec.
  243. virtual Value *reverseVector(Value *Vec);
  244. /// This is a helper class that holds the vectorizer state. It maps scalar
  245. /// instructions to vector instructions. When the code is 'unrolled' then
  246. /// then a single scalar value is mapped to multiple vector parts. The parts
  247. /// are stored in the VectorPart type.
  248. struct ValueMap {
  249. /// C'tor. UnrollFactor controls the number of vectors ('parts') that
  250. /// are mapped.
  251. ValueMap(unsigned UnrollFactor) : UF(UnrollFactor) {}
  252. /// \return True if 'Key' is saved in the Value Map.
  253. bool has(Value *Key) const { return MapStorage.count(Key); }
  254. /// Initializes a new entry in the map. Sets all of the vector parts to the
  255. /// save value in 'Val'.
  256. /// \return A reference to a vector with splat values.
  257. VectorParts &splat(Value *Key, Value *Val) {
  258. VectorParts &Entry = MapStorage[Key];
  259. Entry.assign(UF, Val);
  260. return Entry;
  261. }
  262. ///\return A reference to the value that is stored at 'Key'.
  263. VectorParts &get(Value *Key) {
  264. VectorParts &Entry = MapStorage[Key];
  265. if (Entry.empty())
  266. Entry.resize(UF);
  267. assert(Entry.size() == UF);
  268. return Entry;
  269. }
  270. private:
  271. /// The unroll factor. Each entry in the map stores this number of vector
  272. /// elements.
  273. unsigned UF;
  274. /// Map storage. We use std::map and not DenseMap because insertions to a
  275. /// dense map invalidates its iterators.
  276. std::map<Value *, VectorParts> MapStorage;
  277. };
  278. /// The original loop.
  279. Loop *OrigLoop;
  280. /// Scev analysis to use.
  281. ScalarEvolution *SE;
  282. /// Loop Info.
  283. LoopInfo *LI;
  284. /// Dominator Tree.
  285. DominatorTree *DT;
  286. /// Data Layout.
  287. DataLayout *DL;
  288. /// Target Library Info.
  289. const TargetLibraryInfo *TLI;
  290. /// The vectorization SIMD factor to use. Each vector will have this many
  291. /// vector elements.
  292. unsigned VF;
  293. protected:
  294. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  295. /// many different vector instructions.
  296. unsigned UF;
  297. /// The builder that we use
  298. IRBuilder<> Builder;
  299. // --- Vectorization state ---
  300. /// The vector-loop preheader.
  301. BasicBlock *LoopVectorPreHeader;
  302. /// The scalar-loop preheader.
  303. BasicBlock *LoopScalarPreHeader;
  304. /// Middle Block between the vector and the scalar.
  305. BasicBlock *LoopMiddleBlock;
  306. ///The ExitBlock of the scalar loop.
  307. BasicBlock *LoopExitBlock;
  308. ///The vector loop body.
  309. BasicBlock *LoopVectorBody;
  310. ///The scalar loop body.
  311. BasicBlock *LoopScalarBody;
  312. /// A list of all bypass blocks. The first block is the entry of the loop.
  313. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  314. /// The new Induction variable which was added to the new block.
  315. PHINode *Induction;
  316. /// The induction variable of the old basic block.
  317. PHINode *OldInduction;
  318. /// Holds the extended (to the widest induction type) start index.
  319. Value *ExtendedIdx;
  320. /// Maps scalars to widened vectors.
  321. ValueMap WidenMap;
  322. EdgeMaskCache MaskCache;
  323. LoopVectorizationLegality *Legal;
  324. };
  325. class InnerLoopUnroller : public InnerLoopVectorizer {
  326. public:
  327. InnerLoopUnroller(Loop *OrigLoop, ScalarEvolution *SE, LoopInfo *LI,
  328. DominatorTree *DT, DataLayout *DL,
  329. const TargetLibraryInfo *TLI, unsigned UnrollFactor) :
  330. InnerLoopVectorizer(OrigLoop, SE, LI, DT, DL, TLI, 1, UnrollFactor) { }
  331. private:
  332. virtual void scalarizeInstruction(Instruction *Instr);
  333. virtual void vectorizeMemoryInstruction(Instruction *Instr);
  334. virtual Value *getBroadcastInstrs(Value *V);
  335. virtual Value *getConsecutiveVector(Value* Val, int StartIdx, bool Negate);
  336. virtual Value *reverseVector(Value *Vec);
  337. };
  338. /// \brief Look for a meaningful debug location on the instruction or it's
  339. /// operands.
  340. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  341. if (!I)
  342. return I;
  343. DebugLoc Empty;
  344. if (I->getDebugLoc() != Empty)
  345. return I;
  346. for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
  347. if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
  348. if (OpInst->getDebugLoc() != Empty)
  349. return OpInst;
  350. }
  351. return I;
  352. }
  353. /// \brief Set the debug location in the builder using the debug location in the
  354. /// instruction.
  355. static void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
  356. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr))
  357. B.SetCurrentDebugLocation(Inst->getDebugLoc());
  358. else
  359. B.SetCurrentDebugLocation(DebugLoc());
  360. }
  361. /// LoopVectorizationLegality checks if it is legal to vectorize a loop, and
  362. /// to what vectorization factor.
  363. /// This class does not look at the profitability of vectorization, only the
  364. /// legality. This class has two main kinds of checks:
  365. /// * Memory checks - The code in canVectorizeMemory checks if vectorization
  366. /// will change the order of memory accesses in a way that will change the
  367. /// correctness of the program.
  368. /// * Scalars checks - The code in canVectorizeInstrs and canVectorizeMemory
  369. /// checks for a number of different conditions, such as the availability of a
  370. /// single induction variable, that all types are supported and vectorize-able,
  371. /// etc. This code reflects the capabilities of InnerLoopVectorizer.
  372. /// This class is also used by InnerLoopVectorizer for identifying
  373. /// induction variable and the different reduction variables.
  374. class LoopVectorizationLegality {
  375. public:
  376. LoopVectorizationLegality(Loop *L, ScalarEvolution *SE, DataLayout *DL,
  377. DominatorTree *DT, TargetLibraryInfo *TLI)
  378. : TheLoop(L), SE(SE), DL(DL), DT(DT), TLI(TLI),
  379. Induction(0), WidestIndTy(0), HasFunNoNaNAttr(false),
  380. MaxSafeDepDistBytes(-1U) {}
  381. /// This enum represents the kinds of reductions that we support.
  382. enum ReductionKind {
  383. RK_NoReduction, ///< Not a reduction.
  384. RK_IntegerAdd, ///< Sum of integers.
  385. RK_IntegerMult, ///< Product of integers.
  386. RK_IntegerOr, ///< Bitwise or logical OR of numbers.
  387. RK_IntegerAnd, ///< Bitwise or logical AND of numbers.
  388. RK_IntegerXor, ///< Bitwise or logical XOR of numbers.
  389. RK_IntegerMinMax, ///< Min/max implemented in terms of select(cmp()).
  390. RK_FloatAdd, ///< Sum of floats.
  391. RK_FloatMult, ///< Product of floats.
  392. RK_FloatMinMax ///< Min/max implemented in terms of select(cmp()).
  393. };
  394. /// This enum represents the kinds of inductions that we support.
  395. enum InductionKind {
  396. IK_NoInduction, ///< Not an induction variable.
  397. IK_IntInduction, ///< Integer induction variable. Step = 1.
  398. IK_ReverseIntInduction, ///< Reverse int induction variable. Step = -1.
  399. IK_PtrInduction, ///< Pointer induction var. Step = sizeof(elem).
  400. IK_ReversePtrInduction ///< Reverse ptr indvar. Step = - sizeof(elem).
  401. };
  402. // This enum represents the kind of minmax reduction.
  403. enum MinMaxReductionKind {
  404. MRK_Invalid,
  405. MRK_UIntMin,
  406. MRK_UIntMax,
  407. MRK_SIntMin,
  408. MRK_SIntMax,
  409. MRK_FloatMin,
  410. MRK_FloatMax
  411. };
  412. /// This struct holds information about reduction variables.
  413. struct ReductionDescriptor {
  414. ReductionDescriptor() : StartValue(0), LoopExitInstr(0),
  415. Kind(RK_NoReduction), MinMaxKind(MRK_Invalid) {}
  416. ReductionDescriptor(Value *Start, Instruction *Exit, ReductionKind K,
  417. MinMaxReductionKind MK)
  418. : StartValue(Start), LoopExitInstr(Exit), Kind(K), MinMaxKind(MK) {}
  419. // The starting value of the reduction.
  420. // It does not have to be zero!
  421. TrackingVH<Value> StartValue;
  422. // The instruction who's value is used outside the loop.
  423. Instruction *LoopExitInstr;
  424. // The kind of the reduction.
  425. ReductionKind Kind;
  426. // If this a min/max reduction the kind of reduction.
  427. MinMaxReductionKind MinMaxKind;
  428. };
  429. /// This POD struct holds information about a potential reduction operation.
  430. struct ReductionInstDesc {
  431. ReductionInstDesc(bool IsRedux, Instruction *I) :
  432. IsReduction(IsRedux), PatternLastInst(I), MinMaxKind(MRK_Invalid) {}
  433. ReductionInstDesc(Instruction *I, MinMaxReductionKind K) :
  434. IsReduction(true), PatternLastInst(I), MinMaxKind(K) {}
  435. // Is this instruction a reduction candidate.
  436. bool IsReduction;
  437. // The last instruction in a min/max pattern (select of the select(icmp())
  438. // pattern), or the current reduction instruction otherwise.
  439. Instruction *PatternLastInst;
  440. // If this is a min/max pattern the comparison predicate.
  441. MinMaxReductionKind MinMaxKind;
  442. };
  443. /// This struct holds information about the memory runtime legality
  444. /// check that a group of pointers do not overlap.
  445. struct RuntimePointerCheck {
  446. RuntimePointerCheck() : Need(false) {}
  447. /// Reset the state of the pointer runtime information.
  448. void reset() {
  449. Need = false;
  450. Pointers.clear();
  451. Starts.clear();
  452. Ends.clear();
  453. IsWritePtr.clear();
  454. DependencySetId.clear();
  455. }
  456. /// Insert a pointer and calculate the start and end SCEVs.
  457. void insert(ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr,
  458. unsigned DepSetId, ValueToValueMap &Strides);
  459. /// This flag indicates if we need to add the runtime check.
  460. bool Need;
  461. /// Holds the pointers that we need to check.
  462. SmallVector<TrackingVH<Value>, 2> Pointers;
  463. /// Holds the pointer value at the beginning of the loop.
  464. SmallVector<const SCEV*, 2> Starts;
  465. /// Holds the pointer value at the end of the loop.
  466. SmallVector<const SCEV*, 2> Ends;
  467. /// Holds the information if this pointer is used for writing to memory.
  468. SmallVector<bool, 2> IsWritePtr;
  469. /// Holds the id of the set of pointers that could be dependent because of a
  470. /// shared underlying object.
  471. SmallVector<unsigned, 2> DependencySetId;
  472. };
  473. /// A struct for saving information about induction variables.
  474. struct InductionInfo {
  475. InductionInfo(Value *Start, InductionKind K) : StartValue(Start), IK(K) {}
  476. InductionInfo() : StartValue(0), IK(IK_NoInduction) {}
  477. /// Start value.
  478. TrackingVH<Value> StartValue;
  479. /// Induction kind.
  480. InductionKind IK;
  481. };
  482. /// ReductionList contains the reduction descriptors for all
  483. /// of the reductions that were found in the loop.
  484. typedef DenseMap<PHINode*, ReductionDescriptor> ReductionList;
  485. /// InductionList saves induction variables and maps them to the
  486. /// induction descriptor.
  487. typedef MapVector<PHINode*, InductionInfo> InductionList;
  488. /// Returns true if it is legal to vectorize this loop.
  489. /// This does not mean that it is profitable to vectorize this
  490. /// loop, only that it is legal to do so.
  491. bool canVectorize();
  492. /// Returns the Induction variable.
  493. PHINode *getInduction() { return Induction; }
  494. /// Returns the reduction variables found in the loop.
  495. ReductionList *getReductionVars() { return &Reductions; }
  496. /// Returns the induction variables found in the loop.
  497. InductionList *getInductionVars() { return &Inductions; }
  498. /// Returns the widest induction type.
  499. Type *getWidestInductionType() { return WidestIndTy; }
  500. /// Returns True if V is an induction variable in this loop.
  501. bool isInductionVariable(const Value *V);
  502. /// Return true if the block BB needs to be predicated in order for the loop
  503. /// to be vectorized.
  504. bool blockNeedsPredication(BasicBlock *BB);
  505. /// Check if this pointer is consecutive when vectorizing. This happens
  506. /// when the last index of the GEP is the induction variable, or that the
  507. /// pointer itself is an induction variable.
  508. /// This check allows us to vectorize A[idx] into a wide load/store.
  509. /// Returns:
  510. /// 0 - Stride is unknown or non-consecutive.
  511. /// 1 - Address is consecutive.
  512. /// -1 - Address is consecutive, and decreasing.
  513. int isConsecutivePtr(Value *Ptr);
  514. /// Returns true if the value V is uniform within the loop.
  515. bool isUniform(Value *V);
  516. /// Returns true if this instruction will remain scalar after vectorization.
  517. bool isUniformAfterVectorization(Instruction* I) { return Uniforms.count(I); }
  518. /// Returns the information that we collected about runtime memory check.
  519. RuntimePointerCheck *getRuntimePointerCheck() { return &PtrRtCheck; }
  520. /// This function returns the identity element (or neutral element) for
  521. /// the operation K.
  522. static Constant *getReductionIdentity(ReductionKind K, Type *Tp);
  523. unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
  524. bool hasStride(Value *V) { return StrideSet.count(V); }
  525. bool mustCheckStrides() { return !StrideSet.empty(); }
  526. SmallPtrSet<Value *, 8>::iterator strides_begin() {
  527. return StrideSet.begin();
  528. }
  529. SmallPtrSet<Value *, 8>::iterator strides_end() { return StrideSet.end(); }
  530. private:
  531. /// Check if a single basic block loop is vectorizable.
  532. /// At this point we know that this is a loop with a constant trip count
  533. /// and we only need to check individual instructions.
  534. bool canVectorizeInstrs();
  535. /// When we vectorize loops we may change the order in which
  536. /// we read and write from memory. This method checks if it is
  537. /// legal to vectorize the code, considering only memory constrains.
  538. /// Returns true if the loop is vectorizable
  539. bool canVectorizeMemory();
  540. /// Return true if we can vectorize this loop using the IF-conversion
  541. /// transformation.
  542. bool canVectorizeWithIfConvert();
  543. /// Collect the variables that need to stay uniform after vectorization.
  544. void collectLoopUniforms();
  545. /// Return true if all of the instructions in the block can be speculatively
  546. /// executed. \p SafePtrs is a list of addresses that are known to be legal
  547. /// and we know that we can read from them without segfault.
  548. bool blockCanBePredicated(BasicBlock *BB, SmallPtrSet<Value *, 8>& SafePtrs);
  549. /// Returns True, if 'Phi' is the kind of reduction variable for type
  550. /// 'Kind'. If this is a reduction variable, it adds it to ReductionList.
  551. bool AddReductionVar(PHINode *Phi, ReductionKind Kind);
  552. /// Returns a struct describing if the instruction 'I' can be a reduction
  553. /// variable of type 'Kind'. If the reduction is a min/max pattern of
  554. /// select(icmp()) this function advances the instruction pointer 'I' from the
  555. /// compare instruction to the select instruction and stores this pointer in
  556. /// 'PatternLastInst' member of the returned struct.
  557. ReductionInstDesc isReductionInstr(Instruction *I, ReductionKind Kind,
  558. ReductionInstDesc &Desc);
  559. /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
  560. /// pattern corresponding to a min(X, Y) or max(X, Y).
  561. static ReductionInstDesc isMinMaxSelectCmpPattern(Instruction *I,
  562. ReductionInstDesc &Prev);
  563. /// Returns the induction kind of Phi. This function may return NoInduction
  564. /// if the PHI is not an induction variable.
  565. InductionKind isInductionVariable(PHINode *Phi);
  566. /// \brief Collect memory access with loop invariant strides.
  567. ///
  568. /// Looks for accesses like "a[i * StrideA]" where "StrideA" is loop
  569. /// invariant.
  570. void collectStridedAcccess(Value *LoadOrStoreInst);
  571. /// The loop that we evaluate.
  572. Loop *TheLoop;
  573. /// Scev analysis.
  574. ScalarEvolution *SE;
  575. /// DataLayout analysis.
  576. DataLayout *DL;
  577. /// Dominators.
  578. DominatorTree *DT;
  579. /// Target Library Info.
  580. TargetLibraryInfo *TLI;
  581. // --- vectorization state --- //
  582. /// Holds the integer induction variable. This is the counter of the
  583. /// loop.
  584. PHINode *Induction;
  585. /// Holds the reduction variables.
  586. ReductionList Reductions;
  587. /// Holds all of the induction variables that we found in the loop.
  588. /// Notice that inductions don't need to start at zero and that induction
  589. /// variables can be pointers.
  590. InductionList Inductions;
  591. /// Holds the widest induction type encountered.
  592. Type *WidestIndTy;
  593. /// Allowed outside users. This holds the reduction
  594. /// vars which can be accessed from outside the loop.
  595. SmallPtrSet<Value*, 4> AllowedExit;
  596. /// This set holds the variables which are known to be uniform after
  597. /// vectorization.
  598. SmallPtrSet<Instruction*, 4> Uniforms;
  599. /// We need to check that all of the pointers in this list are disjoint
  600. /// at runtime.
  601. RuntimePointerCheck PtrRtCheck;
  602. /// Can we assume the absence of NaNs.
  603. bool HasFunNoNaNAttr;
  604. unsigned MaxSafeDepDistBytes;
  605. ValueToValueMap Strides;
  606. SmallPtrSet<Value *, 8> StrideSet;
  607. };
  608. /// LoopVectorizationCostModel - estimates the expected speedups due to
  609. /// vectorization.
  610. /// In many cases vectorization is not profitable. This can happen because of
  611. /// a number of reasons. In this class we mainly attempt to predict the
  612. /// expected speedup/slowdowns due to the supported instruction set. We use the
  613. /// TargetTransformInfo to query the different backends for the cost of
  614. /// different operations.
  615. class LoopVectorizationCostModel {
  616. public:
  617. LoopVectorizationCostModel(Loop *L, ScalarEvolution *SE, LoopInfo *LI,
  618. LoopVectorizationLegality *Legal,
  619. const TargetTransformInfo &TTI,
  620. DataLayout *DL, const TargetLibraryInfo *TLI)
  621. : TheLoop(L), SE(SE), LI(LI), Legal(Legal), TTI(TTI), DL(DL), TLI(TLI) {}
  622. /// Information about vectorization costs
  623. struct VectorizationFactor {
  624. unsigned Width; // Vector width with best cost
  625. unsigned Cost; // Cost of the loop with that width
  626. };
  627. /// \return The most profitable vectorization factor and the cost of that VF.
  628. /// This method checks every power of two up to VF. If UserVF is not ZERO
  629. /// then this vectorization factor will be selected if vectorization is
  630. /// possible.
  631. VectorizationFactor selectVectorizationFactor(bool OptForSize,
  632. unsigned UserVF);
  633. /// \return The size (in bits) of the widest type in the code that
  634. /// needs to be vectorized. We ignore values that remain scalar such as
  635. /// 64 bit loop indices.
  636. unsigned getWidestType();
  637. /// \return The most profitable unroll factor.
  638. /// If UserUF is non-zero then this method finds the best unroll-factor
  639. /// based on register pressure and other parameters.
  640. /// VF and LoopCost are the selected vectorization factor and the cost of the
  641. /// selected VF.
  642. unsigned selectUnrollFactor(bool OptForSize, unsigned UserUF, unsigned VF,
  643. unsigned LoopCost);
  644. /// \brief A struct that represents some properties of the register usage
  645. /// of a loop.
  646. struct RegisterUsage {
  647. /// Holds the number of loop invariant values that are used in the loop.
  648. unsigned LoopInvariantRegs;
  649. /// Holds the maximum number of concurrent live intervals in the loop.
  650. unsigned MaxLocalUsers;
  651. /// Holds the number of instructions in the loop.
  652. unsigned NumInstructions;
  653. };
  654. /// \return information about the register usage of the loop.
  655. RegisterUsage calculateRegisterUsage();
  656. private:
  657. /// Returns the expected execution cost. The unit of the cost does
  658. /// not matter because we use the 'cost' units to compare different
  659. /// vector widths. The cost that is returned is *not* normalized by
  660. /// the factor width.
  661. unsigned expectedCost(unsigned VF);
  662. /// Returns the execution time cost of an instruction for a given vector
  663. /// width. Vector width of one means scalar.
  664. unsigned getInstructionCost(Instruction *I, unsigned VF);
  665. /// A helper function for converting Scalar types to vector types.
  666. /// If the incoming type is void, we return void. If the VF is 1, we return
  667. /// the scalar type.
  668. static Type* ToVectorTy(Type *Scalar, unsigned VF);
  669. /// Returns whether the instruction is a load or store and will be a emitted
  670. /// as a vector operation.
  671. bool isConsecutiveLoadOrStore(Instruction *I);
  672. /// The loop that we evaluate.
  673. Loop *TheLoop;
  674. /// Scev analysis.
  675. ScalarEvolution *SE;
  676. /// Loop Info analysis.
  677. LoopInfo *LI;
  678. /// Vectorization legality.
  679. LoopVectorizationLegality *Legal;
  680. /// Vector target information.
  681. const TargetTransformInfo &TTI;
  682. /// Target data layout information.
  683. DataLayout *DL;
  684. /// Target Library Info.
  685. const TargetLibraryInfo *TLI;
  686. };
  687. /// Utility class for getting and setting loop vectorizer hints in the form
  688. /// of loop metadata.
  689. struct LoopVectorizeHints {
  690. /// Vectorization width.
  691. unsigned Width;
  692. /// Vectorization unroll factor.
  693. unsigned Unroll;
  694. /// Vectorization forced (-1 not selected, 0 force disabled, 1 force enabled)
  695. int Force;
  696. LoopVectorizeHints(const Loop *L, bool DisableUnrolling)
  697. : Width(VectorizationFactor)
  698. , Unroll(DisableUnrolling ? 1 : VectorizationUnroll)
  699. , Force(-1)
  700. , LoopID(L->getLoopID()) {
  701. getHints(L);
  702. // The command line options override any loop metadata except for when
  703. // width == 1 which is used to indicate the loop is already vectorized.
  704. if (VectorizationFactor.getNumOccurrences() > 0 && Width != 1)
  705. Width = VectorizationFactor;
  706. if (VectorizationUnroll.getNumOccurrences() > 0)
  707. Unroll = VectorizationUnroll;
  708. DEBUG(if (DisableUnrolling && Unroll == 1)
  709. dbgs() << "LV: Unrolling disabled by the pass manager\n");
  710. }
  711. /// Return the loop vectorizer metadata prefix.
  712. static StringRef Prefix() { return "llvm.vectorizer."; }
  713. MDNode *createHint(LLVMContext &Context, StringRef Name, unsigned V) {
  714. SmallVector<Value*, 2> Vals;
  715. Vals.push_back(MDString::get(Context, Name));
  716. Vals.push_back(ConstantInt::get(Type::getInt32Ty(Context), V));
  717. return MDNode::get(Context, Vals);
  718. }
  719. /// Mark the loop L as already vectorized by setting the width to 1.
  720. void setAlreadyVectorized(Loop *L) {
  721. LLVMContext &Context = L->getHeader()->getContext();
  722. Width = 1;
  723. // Create a new loop id with one more operand for the already_vectorized
  724. // hint. If the loop already has a loop id then copy the existing operands.
  725. SmallVector<Value*, 4> Vals(1);
  726. if (LoopID)
  727. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i)
  728. Vals.push_back(LoopID->getOperand(i));
  729. Vals.push_back(createHint(Context, Twine(Prefix(), "width").str(), Width));
  730. Vals.push_back(createHint(Context, Twine(Prefix(), "unroll").str(), 1));
  731. MDNode *NewLoopID = MDNode::get(Context, Vals);
  732. // Set operand 0 to refer to the loop id itself.
  733. NewLoopID->replaceOperandWith(0, NewLoopID);
  734. L->setLoopID(NewLoopID);
  735. if (LoopID)
  736. LoopID->replaceAllUsesWith(NewLoopID);
  737. LoopID = NewLoopID;
  738. }
  739. private:
  740. MDNode *LoopID;
  741. /// Find hints specified in the loop metadata.
  742. void getHints(const Loop *L) {
  743. if (!LoopID)
  744. return;
  745. // First operand should refer to the loop id itself.
  746. assert(LoopID->getNumOperands() > 0 && "requires at least one operand");
  747. assert(LoopID->getOperand(0) == LoopID && "invalid loop id");
  748. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  749. const MDString *S = 0;
  750. SmallVector<Value*, 4> Args;
  751. // The expected hint is either a MDString or a MDNode with the first
  752. // operand a MDString.
  753. if (const MDNode *MD = dyn_cast<MDNode>(LoopID->getOperand(i))) {
  754. if (!MD || MD->getNumOperands() == 0)
  755. continue;
  756. S = dyn_cast<MDString>(MD->getOperand(0));
  757. for (unsigned i = 1, ie = MD->getNumOperands(); i < ie; ++i)
  758. Args.push_back(MD->getOperand(i));
  759. } else {
  760. S = dyn_cast<MDString>(LoopID->getOperand(i));
  761. assert(Args.size() == 0 && "too many arguments for MDString");
  762. }
  763. if (!S)
  764. continue;
  765. // Check if the hint starts with the vectorizer prefix.
  766. StringRef Hint = S->getString();
  767. if (!Hint.startswith(Prefix()))
  768. continue;
  769. // Remove the prefix.
  770. Hint = Hint.substr(Prefix().size(), StringRef::npos);
  771. if (Args.size() == 1)
  772. getHint(Hint, Args[0]);
  773. }
  774. }
  775. // Check string hint with one operand.
  776. void getHint(StringRef Hint, Value *Arg) {
  777. const ConstantInt *C = dyn_cast<ConstantInt>(Arg);
  778. if (!C) return;
  779. unsigned Val = C->getZExtValue();
  780. if (Hint == "width") {
  781. if (isPowerOf2_32(Val) && Val <= MaxVectorWidth)
  782. Width = Val;
  783. else
  784. DEBUG(dbgs() << "LV: ignoring invalid width hint metadata\n");
  785. } else if (Hint == "unroll") {
  786. if (isPowerOf2_32(Val) && Val <= MaxUnrollFactor)
  787. Unroll = Val;
  788. else
  789. DEBUG(dbgs() << "LV: ignoring invalid unroll hint metadata\n");
  790. } else if (Hint == "enable") {
  791. if (C->getBitWidth() == 1)
  792. Force = Val;
  793. else
  794. DEBUG(dbgs() << "LV: ignoring invalid enable hint metadata\n");
  795. } else {
  796. DEBUG(dbgs() << "LV: ignoring unknown hint " << Hint << '\n');
  797. }
  798. }
  799. };
  800. /// The LoopVectorize Pass.
  801. struct LoopVectorize : public LoopPass {
  802. /// Pass identification, replacement for typeid
  803. static char ID;
  804. explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
  805. : LoopPass(ID),
  806. DisableUnrolling(NoUnrolling),
  807. AlwaysVectorize(AlwaysVectorize) {
  808. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  809. }
  810. ScalarEvolution *SE;
  811. DataLayout *DL;
  812. LoopInfo *LI;
  813. TargetTransformInfo *TTI;
  814. DominatorTree *DT;
  815. TargetLibraryInfo *TLI;
  816. bool DisableUnrolling;
  817. bool AlwaysVectorize;
  818. virtual bool runOnLoop(Loop *L, LPPassManager &LPM) {
  819. // We only vectorize innermost loops.
  820. if (!L->empty())
  821. return false;
  822. SE = &getAnalysis<ScalarEvolution>();
  823. DL = getAnalysisIfAvailable<DataLayout>();
  824. LI = &getAnalysis<LoopInfo>();
  825. TTI = &getAnalysis<TargetTransformInfo>();
  826. DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  827. TLI = getAnalysisIfAvailable<TargetLibraryInfo>();
  828. // If the target claims to have no vector registers don't attempt
  829. // vectorization.
  830. if (!TTI->getNumberOfRegisters(true))
  831. return false;
  832. if (DL == NULL) {
  833. DEBUG(dbgs() << "LV: Not vectorizing: Missing data layout\n");
  834. return false;
  835. }
  836. DEBUG(dbgs() << "LV: Checking a loop in \"" <<
  837. L->getHeader()->getParent()->getName() << "\"\n");
  838. LoopVectorizeHints Hints(L, DisableUnrolling);
  839. if (Hints.Force == 0) {
  840. DEBUG(dbgs() << "LV: Not vectorizing: #pragma vectorize disable.\n");
  841. return false;
  842. }
  843. if (!AlwaysVectorize && Hints.Force != 1) {
  844. DEBUG(dbgs() << "LV: Not vectorizing: No #pragma vectorize enable.\n");
  845. return false;
  846. }
  847. if (Hints.Width == 1 && Hints.Unroll == 1) {
  848. DEBUG(dbgs() << "LV: Not vectorizing: Disabled/already vectorized.\n");
  849. return false;
  850. }
  851. // Check if it is legal to vectorize the loop.
  852. LoopVectorizationLegality LVL(L, SE, DL, DT, TLI);
  853. if (!LVL.canVectorize()) {
  854. DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  855. return false;
  856. }
  857. // Use the cost model.
  858. LoopVectorizationCostModel CM(L, SE, LI, &LVL, *TTI, DL, TLI);
  859. // Check the function attributes to find out if this function should be
  860. // optimized for size.
  861. Function *F = L->getHeader()->getParent();
  862. Attribute::AttrKind SzAttr = Attribute::OptimizeForSize;
  863. Attribute::AttrKind FlAttr = Attribute::NoImplicitFloat;
  864. unsigned FnIndex = AttributeSet::FunctionIndex;
  865. bool OptForSize = Hints.Force != 1 &&
  866. F->getAttributes().hasAttribute(FnIndex, SzAttr);
  867. bool NoFloat = F->getAttributes().hasAttribute(FnIndex, FlAttr);
  868. if (NoFloat) {
  869. DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
  870. "attribute is used.\n");
  871. return false;
  872. }
  873. // Select the optimal vectorization factor.
  874. LoopVectorizationCostModel::VectorizationFactor VF;
  875. VF = CM.selectVectorizationFactor(OptForSize, Hints.Width);
  876. // Select the unroll factor.
  877. unsigned UF = CM.selectUnrollFactor(OptForSize, Hints.Unroll, VF.Width,
  878. VF.Cost);
  879. DEBUG(dbgs() << "LV: Found a vectorizable loop ("<< VF.Width << ") in "<<
  880. F->getParent()->getModuleIdentifier() << '\n');
  881. DEBUG(dbgs() << "LV: Unroll Factor is " << UF << '\n');
  882. if (VF.Width == 1) {
  883. DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  884. if (UF == 1)
  885. return false;
  886. DEBUG(dbgs() << "LV: Trying to at least unroll the loops.\n");
  887. // We decided not to vectorize, but we may want to unroll.
  888. InnerLoopUnroller Unroller(L, SE, LI, DT, DL, TLI, UF);
  889. Unroller.vectorize(&LVL);
  890. } else {
  891. // If we decided that it is *legal* to vectorize the loop then do it.
  892. InnerLoopVectorizer LB(L, SE, LI, DT, DL, TLI, VF.Width, UF);
  893. LB.vectorize(&LVL);
  894. }
  895. // Mark the loop as already vectorized to avoid vectorizing again.
  896. Hints.setAlreadyVectorized(L);
  897. DEBUG(verifyFunction(*L->getHeader()->getParent()));
  898. return true;
  899. }
  900. virtual void getAnalysisUsage(AnalysisUsage &AU) const {
  901. LoopPass::getAnalysisUsage(AU);
  902. AU.addRequiredID(LoopSimplifyID);
  903. AU.addRequiredID(LCSSAID);
  904. AU.addRequired<DominatorTreeWrapperPass>();
  905. AU.addRequired<LoopInfo>();
  906. AU.addRequired<ScalarEvolution>();
  907. AU.addRequired<TargetTransformInfo>();
  908. AU.addPreserved<LoopInfo>();
  909. AU.addPreserved<DominatorTreeWrapperPass>();
  910. }
  911. };
  912. } // end anonymous namespace
  913. //===----------------------------------------------------------------------===//
  914. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  915. // LoopVectorizationCostModel.
  916. //===----------------------------------------------------------------------===//
  917. static Value *stripIntegerCast(Value *V) {
  918. if (CastInst *CI = dyn_cast<CastInst>(V))
  919. if (CI->getOperand(0)->getType()->isIntegerTy())
  920. return CI->getOperand(0);
  921. return V;
  922. }
  923. ///\brief Replaces the symbolic stride in a pointer SCEV expression by one.
  924. ///
  925. /// If \p OrigPtr is not null, use it to look up the stride value instead of
  926. /// \p Ptr.
  927. static const SCEV *replaceSymbolicStrideSCEV(ScalarEvolution *SE,
  928. ValueToValueMap &PtrToStride,
  929. Value *Ptr, Value *OrigPtr = 0) {
  930. const SCEV *OrigSCEV = SE->getSCEV(Ptr);
  931. // If there is an entry in the map return the SCEV of the pointer with the
  932. // symbolic stride replaced by one.
  933. ValueToValueMap::iterator SI = PtrToStride.find(OrigPtr ? OrigPtr : Ptr);
  934. if (SI != PtrToStride.end()) {
  935. Value *StrideVal = SI->second;
  936. // Strip casts.
  937. StrideVal = stripIntegerCast(StrideVal);
  938. // Replace symbolic stride by one.
  939. Value *One = ConstantInt::get(StrideVal->getType(), 1);
  940. ValueToValueMap RewriteMap;
  941. RewriteMap[StrideVal] = One;
  942. const SCEV *ByOne =
  943. SCEVParameterRewriter::rewrite(OrigSCEV, *SE, RewriteMap, true);
  944. DEBUG(dbgs() << "LV: Replacing SCEV: " << *OrigSCEV << " by: " << *ByOne
  945. << "\n");
  946. return ByOne;
  947. }
  948. // Otherwise, just return the SCEV of the original pointer.
  949. return SE->getSCEV(Ptr);
  950. }
  951. void LoopVectorizationLegality::RuntimePointerCheck::insert(
  952. ScalarEvolution *SE, Loop *Lp, Value *Ptr, bool WritePtr, unsigned DepSetId,
  953. ValueToValueMap &Strides) {
  954. // Get the stride replaced scev.
  955. const SCEV *Sc = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
  956. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Sc);
  957. assert(AR && "Invalid addrec expression");
  958. const SCEV *Ex = SE->getBackedgeTakenCount(Lp);
  959. const SCEV *ScEnd = AR->evaluateAtIteration(Ex, *SE);
  960. Pointers.push_back(Ptr);
  961. Starts.push_back(AR->getStart());
  962. Ends.push_back(ScEnd);
  963. IsWritePtr.push_back(WritePtr);
  964. DependencySetId.push_back(DepSetId);
  965. }
  966. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  967. // We need to place the broadcast of invariant variables outside the loop.
  968. Instruction *Instr = dyn_cast<Instruction>(V);
  969. bool NewInstr = (Instr && Instr->getParent() == LoopVectorBody);
  970. bool Invariant = OrigLoop->isLoopInvariant(V) && !NewInstr;
  971. // Place the code for broadcasting invariant variables in the new preheader.
  972. IRBuilder<>::InsertPointGuard Guard(Builder);
  973. if (Invariant)
  974. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  975. // Broadcast the scalar into all locations in the vector.
  976. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  977. return Shuf;
  978. }
  979. Value *InnerLoopVectorizer::getConsecutiveVector(Value* Val, int StartIdx,
  980. bool Negate) {
  981. assert(Val->getType()->isVectorTy() && "Must be a vector");
  982. assert(Val->getType()->getScalarType()->isIntegerTy() &&
  983. "Elem must be an integer");
  984. // Create the types.
  985. Type *ITy = Val->getType()->getScalarType();
  986. VectorType *Ty = cast<VectorType>(Val->getType());
  987. int VLen = Ty->getNumElements();
  988. SmallVector<Constant*, 8> Indices;
  989. // Create a vector of consecutive numbers from zero to VF.
  990. for (int i = 0; i < VLen; ++i) {
  991. int64_t Idx = Negate ? (-i) : i;
  992. Indices.push_back(ConstantInt::get(ITy, StartIdx + Idx, Negate));
  993. }
  994. // Add the consecutive indices to the vector value.
  995. Constant *Cv = ConstantVector::get(Indices);
  996. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  997. return Builder.CreateAdd(Val, Cv, "induction");
  998. }
  999. /// \brief Find the operand of the GEP that should be checked for consecutive
  1000. /// stores. This ignores trailing indices that have no effect on the final
  1001. /// pointer.
  1002. static unsigned getGEPInductionOperand(DataLayout *DL,
  1003. const GetElementPtrInst *Gep) {
  1004. unsigned LastOperand = Gep->getNumOperands() - 1;
  1005. unsigned GEPAllocSize = DL->getTypeAllocSize(
  1006. cast<PointerType>(Gep->getType()->getScalarType())->getElementType());
  1007. // Walk backwards and try to peel off zeros.
  1008. while (LastOperand > 1 && match(Gep->getOperand(LastOperand), m_Zero())) {
  1009. // Find the type we're currently indexing into.
  1010. gep_type_iterator GEPTI = gep_type_begin(Gep);
  1011. std::advance(GEPTI, LastOperand - 1);
  1012. // If it's a type with the same allocation size as the result of the GEP we
  1013. // can peel off the zero index.
  1014. if (DL->getTypeAllocSize(*GEPTI) != GEPAllocSize)
  1015. break;
  1016. --LastOperand;
  1017. }
  1018. return LastOperand;
  1019. }
  1020. int LoopVectorizationLegality::isConsecutivePtr(Value *Ptr) {
  1021. assert(Ptr->getType()->isPointerTy() && "Unexpected non-ptr");
  1022. // Make sure that the pointer does not point to structs.
  1023. if (Ptr->getType()->getPointerElementType()->isAggregateType())
  1024. return 0;
  1025. // If this value is a pointer induction variable we know it is consecutive.
  1026. PHINode *Phi = dyn_cast_or_null<PHINode>(Ptr);
  1027. if (Phi && Inductions.count(Phi)) {
  1028. InductionInfo II = Inductions[Phi];
  1029. if (IK_PtrInduction == II.IK)
  1030. return 1;
  1031. else if (IK_ReversePtrInduction == II.IK)
  1032. return -1;
  1033. }
  1034. GetElementPtrInst *Gep = dyn_cast_or_null<GetElementPtrInst>(Ptr);
  1035. if (!Gep)
  1036. return 0;
  1037. unsigned NumOperands = Gep->getNumOperands();
  1038. Value *GpPtr = Gep->getPointerOperand();
  1039. // If this GEP value is a consecutive pointer induction variable and all of
  1040. // the indices are constant then we know it is consecutive. We can
  1041. Phi = dyn_cast<PHINode>(GpPtr);
  1042. if (Phi && Inductions.count(Phi)) {
  1043. // Make sure that the pointer does not point to structs.
  1044. PointerType *GepPtrType = cast<PointerType>(GpPtr->getType());
  1045. if (GepPtrType->getElementType()->isAggregateType())
  1046. return 0;
  1047. // Make sure that all of the index operands are loop invariant.
  1048. for (unsigned i = 1; i < NumOperands; ++i)
  1049. if (!SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
  1050. return 0;
  1051. InductionInfo II = Inductions[Phi];
  1052. if (IK_PtrInduction == II.IK)
  1053. return 1;
  1054. else if (IK_ReversePtrInduction == II.IK)
  1055. return -1;
  1056. }
  1057. unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
  1058. // Check that all of the gep indices are uniform except for our induction
  1059. // operand.
  1060. for (unsigned i = 0; i != NumOperands; ++i)
  1061. if (i != InductionOperand &&
  1062. !SE->isLoopInvariant(SE->getSCEV(Gep->getOperand(i)), TheLoop))
  1063. return 0;
  1064. // We can emit wide load/stores only if the last non-zero index is the
  1065. // induction variable.
  1066. const SCEV *Last = 0;
  1067. if (!Strides.count(Gep))
  1068. Last = SE->getSCEV(Gep->getOperand(InductionOperand));
  1069. else {
  1070. // Because of the multiplication by a stride we can have a s/zext cast.
  1071. // We are going to replace this stride by 1 so the cast is safe to ignore.
  1072. //
  1073. // %indvars.iv = phi i64 [ 0, %entry ], [ %indvars.iv.next, %for.body ]
  1074. // %0 = trunc i64 %indvars.iv to i32
  1075. // %mul = mul i32 %0, %Stride1
  1076. // %idxprom = zext i32 %mul to i64 << Safe cast.
  1077. // %arrayidx = getelementptr inbounds i32* %B, i64 %idxprom
  1078. //
  1079. Last = replaceSymbolicStrideSCEV(SE, Strides,
  1080. Gep->getOperand(InductionOperand), Gep);
  1081. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(Last))
  1082. Last =
  1083. (C->getSCEVType() == scSignExtend || C->getSCEVType() == scZeroExtend)
  1084. ? C->getOperand()
  1085. : Last;
  1086. }
  1087. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Last)) {
  1088. const SCEV *Step = AR->getStepRecurrence(*SE);
  1089. // The memory is consecutive because the last index is consecutive
  1090. // and all other indices are loop invariant.
  1091. if (Step->isOne())
  1092. return 1;
  1093. if (Step->isAllOnesValue())
  1094. return -1;
  1095. }
  1096. return 0;
  1097. }
  1098. bool LoopVectorizationLegality::isUniform(Value *V) {
  1099. return (SE->isLoopInvariant(SE->getSCEV(V), TheLoop));
  1100. }
  1101. InnerLoopVectorizer::VectorParts&
  1102. InnerLoopVectorizer::getVectorValue(Value *V) {
  1103. assert(V != Induction && "The new induction variable should not be used.");
  1104. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  1105. // If we have a stride that is replaced by one, do it here.
  1106. if (Legal->hasStride(V))
  1107. V = ConstantInt::get(V->getType(), 1);
  1108. // If we have this scalar in the map, return it.
  1109. if (WidenMap.has(V))
  1110. return WidenMap.get(V);
  1111. // If this scalar is unknown, assume that it is a constant or that it is
  1112. // loop invariant. Broadcast V and save the value for future uses.
  1113. Value *B = getBroadcastInstrs(V);
  1114. return WidenMap.splat(V, B);
  1115. }
  1116. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  1117. assert(Vec->getType()->isVectorTy() && "Invalid type");
  1118. SmallVector<Constant*, 8> ShuffleMask;
  1119. for (unsigned i = 0; i < VF; ++i)
  1120. ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
  1121. return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
  1122. ConstantVector::get(ShuffleMask),
  1123. "reverse");
  1124. }
  1125. void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr) {
  1126. // Attempt to issue a wide load.
  1127. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  1128. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  1129. assert((LI || SI) && "Invalid Load/Store instruction");
  1130. Type *ScalarDataTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  1131. Type *DataTy = VectorType::get(ScalarDataTy, VF);
  1132. Value *Ptr = LI ? LI->getPointerOperand() : SI->getPointerOperand();
  1133. unsigned Alignment = LI ? LI->getAlignment() : SI->getAlignment();
  1134. // An alignment of 0 means target abi alignment. We need to use the scalar's
  1135. // target abi alignment in such a case.
  1136. if (!Alignment)
  1137. Alignment = DL->getABITypeAlignment(ScalarDataTy);
  1138. unsigned AddressSpace = Ptr->getType()->getPointerAddressSpace();
  1139. unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ScalarDataTy);
  1140. unsigned VectorElementSize = DL->getTypeStoreSize(DataTy)/VF;
  1141. if (ScalarAllocatedSize != VectorElementSize)
  1142. return scalarizeInstruction(Instr);
  1143. // If the pointer is loop invariant or if it is non-consecutive,
  1144. // scalarize the load.
  1145. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  1146. bool Reverse = ConsecutiveStride < 0;
  1147. bool UniformLoad = LI && Legal->isUniform(Ptr);
  1148. if (!ConsecutiveStride || UniformLoad)
  1149. return scalarizeInstruction(Instr);
  1150. Constant *Zero = Builder.getInt32(0);
  1151. VectorParts &Entry = WidenMap.get(Instr);
  1152. // Handle consecutive loads/stores.
  1153. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  1154. if (Gep && Legal->isInductionVariable(Gep->getPointerOperand())) {
  1155. setDebugLocFromInst(Builder, Gep);
  1156. Value *PtrOperand = Gep->getPointerOperand();
  1157. Value *FirstBasePtr = getVectorValue(PtrOperand)[0];
  1158. FirstBasePtr = Builder.CreateExtractElement(FirstBasePtr, Zero);
  1159. // Create the new GEP with the new induction variable.
  1160. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  1161. Gep2->setOperand(0, FirstBasePtr);
  1162. Gep2->setName("gep.indvar.base");
  1163. Ptr = Builder.Insert(Gep2);
  1164. } else if (Gep) {
  1165. setDebugLocFromInst(Builder, Gep);
  1166. assert(SE->isLoopInvariant(SE->getSCEV(Gep->getPointerOperand()),
  1167. OrigLoop) && "Base ptr must be invariant");
  1168. // The last index does not have to be the induction. It can be
  1169. // consecutive and be a function of the index. For example A[I+1];
  1170. unsigned NumOperands = Gep->getNumOperands();
  1171. unsigned InductionOperand = getGEPInductionOperand(DL, Gep);
  1172. // Create the new GEP with the new induction variable.
  1173. GetElementPtrInst *Gep2 = cast<GetElementPtrInst>(Gep->clone());
  1174. for (unsigned i = 0; i < NumOperands; ++i) {
  1175. Value *GepOperand = Gep->getOperand(i);
  1176. Instruction *GepOperandInst = dyn_cast<Instruction>(GepOperand);
  1177. // Update last index or loop invariant instruction anchored in loop.
  1178. if (i == InductionOperand ||
  1179. (GepOperandInst && OrigLoop->contains(GepOperandInst))) {
  1180. assert((i == InductionOperand ||
  1181. SE->isLoopInvariant(SE->getSCEV(GepOperandInst), OrigLoop)) &&
  1182. "Must be last index or loop invariant");
  1183. VectorParts &GEPParts = getVectorValue(GepOperand);
  1184. Value *Index = GEPParts[0];
  1185. Index = Builder.CreateExtractElement(Index, Zero);
  1186. Gep2->setOperand(i, Index);
  1187. Gep2->setName("gep.indvar.idx");
  1188. }
  1189. }
  1190. Ptr = Builder.Insert(Gep2);
  1191. } else {
  1192. // Use the induction element ptr.
  1193. assert(isa<PHINode>(Ptr) && "Invalid induction ptr");
  1194. setDebugLocFromInst(Builder, Ptr);
  1195. VectorParts &PtrVal = getVectorValue(Ptr);
  1196. Ptr = Builder.CreateExtractElement(PtrVal[0], Zero);
  1197. }
  1198. // Handle Stores:
  1199. if (SI) {
  1200. assert(!Legal->isUniform(SI->getPointerOperand()) &&
  1201. "We do not allow storing to uniform addresses");
  1202. setDebugLocFromInst(Builder, SI);
  1203. // We don't want to update the value in the map as it might be used in
  1204. // another expression. So don't use a reference type for "StoredVal".
  1205. VectorParts StoredVal = getVectorValue(SI->getValueOperand());
  1206. for (unsigned Part = 0; Part < UF; ++Part) {
  1207. // Calculate the pointer for the specific unroll-part.
  1208. Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
  1209. if (Reverse) {
  1210. // If we store to reverse consecutive memory locations then we need
  1211. // to reverse the order of elements in the stored value.
  1212. StoredVal[Part] = reverseVector(StoredVal[Part]);
  1213. // If the address is consecutive but reversed, then the
  1214. // wide store needs to start at the last vector element.
  1215. PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
  1216. PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
  1217. }
  1218. Value *VecPtr = Builder.CreateBitCast(PartPtr,
  1219. DataTy->getPointerTo(AddressSpace));
  1220. Builder.CreateStore(StoredVal[Part], VecPtr)->setAlignment(Alignment);
  1221. }
  1222. return;
  1223. }
  1224. // Handle loads.
  1225. assert(LI && "Must have a load instruction");
  1226. setDebugLocFromInst(Builder, LI);
  1227. for (unsigned Part = 0; Part < UF; ++Part) {
  1228. // Calculate the pointer for the specific unroll-part.
  1229. Value *PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF));
  1230. if (Reverse) {
  1231. // If the address is consecutive but reversed, then the
  1232. // wide store needs to start at the last vector element.
  1233. PartPtr = Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF));
  1234. PartPtr = Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF));
  1235. }
  1236. Value *VecPtr = Builder.CreateBitCast(PartPtr,
  1237. DataTy->getPointerTo(AddressSpace));
  1238. Value *LI = Builder.CreateLoad(VecPtr, "wide.load");
  1239. cast<LoadInst>(LI)->setAlignment(Alignment);
  1240. Entry[Part] = Reverse ? reverseVector(LI) : LI;
  1241. }
  1242. }
  1243. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr) {
  1244. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  1245. // Holds vector parameters or scalars, in case of uniform vals.
  1246. SmallVector<VectorParts, 4> Params;
  1247. setDebugLocFromInst(Builder, Instr);
  1248. // Find all of the vectorized parameters.
  1249. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  1250. Value *SrcOp = Instr->getOperand(op);
  1251. // If we are accessing the old induction variable, use the new one.
  1252. if (SrcOp == OldInduction) {
  1253. Params.push_back(getVectorValue(SrcOp));
  1254. continue;
  1255. }
  1256. // Try using previously calculated values.
  1257. Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
  1258. // If the src is an instruction that appeared earlier in the basic block
  1259. // then it should already be vectorized.
  1260. if (SrcInst && OrigLoop->contains(SrcInst)) {
  1261. assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
  1262. // The parameter is a vector value from earlier.
  1263. Params.push_back(WidenMap.get(SrcInst));
  1264. } else {
  1265. // The parameter is a scalar from outside the loop. Maybe even a constant.
  1266. VectorParts Scalars;
  1267. Scalars.append(UF, SrcOp);
  1268. Params.push_back(Scalars);
  1269. }
  1270. }
  1271. assert(Params.size() == Instr->getNumOperands() &&
  1272. "Invalid number of operands");
  1273. // Does this instruction return a value ?
  1274. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  1275. Value *UndefVec = IsVoidRetTy ? 0 :
  1276. UndefValue::get(VectorType::get(Instr->getType(), VF));
  1277. // Create a new entry in the WidenMap and initialize it to Undef or Null.
  1278. VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
  1279. // For each vector unroll 'part':
  1280. for (unsigned Part = 0; Part < UF; ++Part) {
  1281. // For each scalar that we create:
  1282. for (unsigned Width = 0; Width < VF; ++Width) {
  1283. Instruction *Cloned = Instr->clone();
  1284. if (!IsVoidRetTy)
  1285. Cloned->setName(Instr->getName() + ".cloned");
  1286. // Replace the operands of the cloned instructions with extracted scalars.
  1287. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  1288. Value *Op = Params[op][Part];
  1289. // Param is a vector. Need to extract the right lane.
  1290. if (Op->getType()->isVectorTy())
  1291. Op = Builder.CreateExtractElement(Op, Builder.getInt32(Width));
  1292. Cloned->setOperand(op, Op);
  1293. }
  1294. // Place the cloned scalar in the new loop.
  1295. Builder.Insert(Cloned);
  1296. // If the original scalar returns a value we need to place it in a vector
  1297. // so that future users will be able to use it.
  1298. if (!IsVoidRetTy)
  1299. VecResults[Part] = Builder.CreateInsertElement(VecResults[Part], Cloned,
  1300. Builder.getInt32(Width));
  1301. }
  1302. }
  1303. }
  1304. static Instruction *getFirstInst(Instruction *FirstInst, Value *V,
  1305. Instruction *Loc) {
  1306. if (FirstInst)
  1307. return FirstInst;
  1308. if (Instruction *I = dyn_cast<Instruction>(V))
  1309. return I->getParent() == Loc->getParent() ? I : 0;
  1310. return 0;
  1311. }
  1312. std::pair<Instruction *, Instruction *>
  1313. InnerLoopVectorizer::addStrideCheck(Instruction *Loc) {
  1314. Instruction *tnullptr = 0;
  1315. if (!Legal->mustCheckStrides())
  1316. return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
  1317. IRBuilder<> ChkBuilder(Loc);
  1318. // Emit checks.
  1319. Value *Check = 0;
  1320. Instruction *FirstInst = 0;
  1321. for (SmallPtrSet<Value *, 8>::iterator SI = Legal->strides_begin(),
  1322. SE = Legal->strides_end();
  1323. SI != SE; ++SI) {
  1324. Value *Ptr = stripIntegerCast(*SI);
  1325. Value *C = ChkBuilder.CreateICmpNE(Ptr, ConstantInt::get(Ptr->getType(), 1),
  1326. "stride.chk");
  1327. // Store the first instruction we create.
  1328. FirstInst = getFirstInst(FirstInst, C, Loc);
  1329. if (Check)
  1330. Check = ChkBuilder.CreateOr(Check, C);
  1331. else
  1332. Check = C;
  1333. }
  1334. // We have to do this trickery because the IRBuilder might fold the check to a
  1335. // constant expression in which case there is no Instruction anchored in a
  1336. // the block.
  1337. LLVMContext &Ctx = Loc->getContext();
  1338. Instruction *TheCheck =
  1339. BinaryOperator::CreateAnd(Check, ConstantInt::getTrue(Ctx));
  1340. ChkBuilder.Insert(TheCheck, "stride.not.one");
  1341. FirstInst = getFirstInst(FirstInst, TheCheck, Loc);
  1342. return std::make_pair(FirstInst, TheCheck);
  1343. }
  1344. std::pair<Instruction *, Instruction *>
  1345. InnerLoopVectorizer::addRuntimeCheck(Instruction *Loc) {
  1346. LoopVectorizationLegality::RuntimePointerCheck *PtrRtCheck =
  1347. Legal->getRuntimePointerCheck();
  1348. Instruction *tnullptr = 0;
  1349. if (!PtrRtCheck->Need)
  1350. return std::pair<Instruction *, Instruction *>(tnullptr, tnullptr);
  1351. unsigned NumPointers = PtrRtCheck->Pointers.size();
  1352. SmallVector<TrackingVH<Value> , 2> Starts;
  1353. SmallVector<TrackingVH<Value> , 2> Ends;
  1354. LLVMContext &Ctx = Loc->getContext();
  1355. SCEVExpander Exp(*SE, "induction");
  1356. Instruction *FirstInst = 0;
  1357. for (unsigned i = 0; i < NumPointers; ++i) {
  1358. Value *Ptr = PtrRtCheck->Pointers[i];
  1359. const SCEV *Sc = SE->getSCEV(Ptr);
  1360. if (SE->isLoopInvariant(Sc, OrigLoop)) {
  1361. DEBUG(dbgs() << "LV: Adding RT check for a loop invariant ptr:" <<
  1362. *Ptr <<"\n");
  1363. Starts.push_back(Ptr);
  1364. Ends.push_back(Ptr);
  1365. } else {
  1366. DEBUG(dbgs() << "LV: Adding RT check for range:" << *Ptr << '\n');
  1367. unsigned AS = Ptr->getType()->getPointerAddressSpace();
  1368. // Use this type for pointer arithmetic.
  1369. Type *PtrArithTy = Type::getInt8PtrTy(Ctx, AS);
  1370. Value *Start = Exp.expandCodeFor(PtrRtCheck->Starts[i], PtrArithTy, Loc);
  1371. Value *End = Exp.expandCodeFor(PtrRtCheck->Ends[i], PtrArithTy, Loc);
  1372. Starts.push_back(Start);
  1373. Ends.push_back(End);
  1374. }
  1375. }
  1376. IRBuilder<> ChkBuilder(Loc);
  1377. // Our instructions might fold to a constant.
  1378. Value *MemoryRuntimeCheck = 0;
  1379. for (unsigned i = 0; i < NumPointers; ++i) {
  1380. for (unsigned j = i+1; j < NumPointers; ++j) {
  1381. // No need to check if two readonly pointers intersect.
  1382. if (!PtrRtCheck->IsWritePtr[i] && !PtrRtCheck->IsWritePtr[j])
  1383. continue;
  1384. // Only need to check pointers between two different dependency sets.
  1385. if (PtrRtCheck->DependencySetId[i] == PtrRtCheck->DependencySetId[j])
  1386. continue;
  1387. unsigned AS0 = Starts[i]->getType()->getPointerAddressSpace();
  1388. unsigned AS1 = Starts[j]->getType()->getPointerAddressSpace();
  1389. assert((AS0 == Ends[j]->getType()->getPointerAddressSpace()) &&
  1390. (AS1 == Ends[i]->getType()->getPointerAddressSpace()) &&
  1391. "Trying to bounds check pointers with different address spaces");
  1392. Type *PtrArithTy0 = Type::getInt8PtrTy(Ctx, AS0);
  1393. Type *PtrArithTy1 = Type::getInt8PtrTy(Ctx, AS1);
  1394. Value *Start0 = ChkBuilder.CreateBitCast(Starts[i], PtrArithTy0, "bc");
  1395. Value *Start1 = ChkBuilder.CreateBitCast(Starts[j], PtrArithTy1, "bc");
  1396. Value *End0 = ChkBuilder.CreateBitCast(Ends[i], PtrArithTy1, "bc");
  1397. Value *End1 = ChkBuilder.CreateBitCast(Ends[j], PtrArithTy0, "bc");
  1398. Value *Cmp0 = ChkBuilder.CreateICmpULE(Start0, End1, "bound0");
  1399. FirstInst = getFirstInst(FirstInst, Cmp0, Loc);
  1400. Value *Cmp1 = ChkBuilder.CreateICmpULE(Start1, End0, "bound1");
  1401. FirstInst = getFirstInst(FirstInst, Cmp1, Loc);
  1402. Value *IsConflict = ChkBuilder.CreateAnd(Cmp0, Cmp1, "found.conflict");
  1403. FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
  1404. if (MemoryRuntimeCheck) {
  1405. IsConflict = ChkBuilder.CreateOr(MemoryRuntimeCheck, IsConflict,
  1406. "conflict.rdx");
  1407. FirstInst = getFirstInst(FirstInst, IsConflict, Loc);
  1408. }
  1409. MemoryRuntimeCheck = IsConflict;
  1410. }
  1411. }
  1412. // We have to do this trickery because the IRBuilder might fold the check to a
  1413. // constant expression in which case there is no Instruction anchored in a
  1414. // the block.
  1415. Instruction *Check = BinaryOperator::CreateAnd(MemoryRuntimeCheck,
  1416. ConstantInt::getTrue(Ctx));
  1417. ChkBuilder.Insert(Check, "memcheck.conflict");
  1418. FirstInst = getFirstInst(FirstInst, Check, Loc);
  1419. return std::make_pair(FirstInst, Check);
  1420. }
  1421. void InnerLoopVectorizer::createEmptyLoop() {
  1422. /*
  1423. In this function we generate a new loop. The new loop will contain
  1424. the vectorized instructions while the old loop will continue to run the
  1425. scalar remainder.
  1426. [ ] <-- vector loop bypass (may consist of multiple blocks).
  1427. / |
  1428. / v
  1429. | [ ] <-- vector pre header.
  1430. | |
  1431. | v
  1432. | [ ] \
  1433. | [ ]_| <-- vector loop.
  1434. | |
  1435. \ v
  1436. >[ ] <--- middle-block.
  1437. / |
  1438. / v
  1439. | [ ] <--- new preheader.
  1440. | |
  1441. | v
  1442. | [ ] \
  1443. | [ ]_| <-- old scalar loop to handle remainder.
  1444. \ |
  1445. \ v
  1446. >[ ] <-- exit block.
  1447. ...
  1448. */
  1449. BasicBlock *OldBasicBlock = OrigLoop->getHeader();
  1450. BasicBlock *BypassBlock = OrigLoop->getLoopPreheader();
  1451. BasicBlock *ExitBlock = OrigLoop->getExitBlock();
  1452. assert(ExitBlock && "Must have an exit block");
  1453. // Some loops have a single integer induction variable, while other loops
  1454. // don't. One example is c++ iterators that often have multiple pointer
  1455. // induction variables. In the code below we also support a case where we
  1456. // don't have a single induction variable.
  1457. OldInduction = Legal->getInduction();
  1458. Type *IdxTy = Legal->getWidestInductionType();
  1459. // Find the loop boundaries.
  1460. const SCEV *ExitCount = SE->getBackedgeTakenCount(OrigLoop);
  1461. assert(ExitCount != SE->getCouldNotCompute() && "Invalid loop count");
  1462. // The exit count might have the type of i64 while the phi is i32. This can
  1463. // happen if we have an induction variable that is sign extended before the
  1464. // compare. The only way that we get a backedge taken count is that the
  1465. // induction variable was signed and as such will not overflow. In such a case
  1466. // truncation is legal.
  1467. if (ExitCount->getType()->getPrimitiveSizeInBits() >
  1468. IdxTy->getPrimitiveSizeInBits())
  1469. ExitCount = SE->getTruncateOrNoop(ExitCount, IdxTy);
  1470. ExitCount = SE->getNoopOrZeroExtend(ExitCount, IdxTy);
  1471. // Get the total trip count from the count by adding 1.
  1472. ExitCount = SE->getAddExpr(ExitCount,
  1473. SE->getConstant(ExitCount->getType(), 1));
  1474. // Expand the trip count and place the new instructions in the preheader.
  1475. // Notice that the pre-header does not change, only the loop body.
  1476. SCEVExpander Exp(*SE, "induction");
  1477. // Count holds the overall loop count (N).
  1478. Value *Count = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  1479. BypassBlock->getTerminator());
  1480. // The loop index does not have to start at Zero. Find the original start
  1481. // value from the induction PHI node. If we don't have an induction variable
  1482. // then we know that it starts at zero.
  1483. Builder.SetInsertPoint(BypassBlock->getTerminator());
  1484. Value *StartIdx = ExtendedIdx = OldInduction ?
  1485. Builder.CreateZExt(OldInduction->getIncomingValueForBlock(BypassBlock),
  1486. IdxTy):
  1487. ConstantInt::get(IdxTy, 0);
  1488. assert(BypassBlock && "Invalid loop structure");
  1489. LoopBypassBlocks.push_back(BypassBlock);
  1490. // Split the single block loop into the two loop structure described above.
  1491. BasicBlock *VectorPH =
  1492. BypassBlock->splitBasicBlock(BypassBlock->getTerminator(), "vector.ph");
  1493. BasicBlock *VecBody =
  1494. VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
  1495. BasicBlock *MiddleBlock =
  1496. VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
  1497. BasicBlock *ScalarPH =
  1498. MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
  1499. // Create and register the new vector loop.
  1500. Loop* Lp = new Loop();
  1501. Loop *ParentLoop = OrigLoop->getParentLoop();
  1502. // Insert the new loop into the loop nest and register the new basic blocks
  1503. // before calling any utilities such as SCEV that require valid LoopInfo.
  1504. if (ParentLoop) {
  1505. ParentLoop->addChildLoop(Lp);
  1506. ParentLoop->addBasicBlockToLoop(ScalarPH, LI->getBase());
  1507. ParentLoop->addBasicBlockToLoop(VectorPH, LI->getBase());
  1508. ParentLoop->addBasicBlockToLoop(MiddleBlock, LI->getBase());
  1509. } else {
  1510. LI->addTopLevelLoop(Lp);
  1511. }
  1512. Lp->addBasicBlockToLoop(VecBody, LI->getBase());
  1513. // Use this IR builder to create the loop instructions (Phi, Br, Cmp)
  1514. // inside the loop.
  1515. Builder.SetInsertPoint(VecBody->getFirstNonPHI());
  1516. // Generate the induction variable.
  1517. setDebugLocFromInst(Builder, getDebugLocFromInstOrOperands(OldInduction));
  1518. Induction = Builder.CreatePHI(IdxTy, 2, "index");
  1519. // The loop step is equal to the vectorization factor (num of SIMD elements)
  1520. // times the unroll factor (num of SIMD instructions).
  1521. Constant *Step = ConstantInt::get(IdxTy, VF * UF);
  1522. // This is the IR builder that we use to add all of the logic for bypassing
  1523. // the new vector loop.
  1524. IRBuilder<> BypassBuilder(BypassBlock->getTerminator());
  1525. setDebugLocFromInst(BypassBuilder,
  1526. getDebugLocFromInstOrOperands(OldInduction));
  1527. // We may need to extend the index in case there is a type mismatch.
  1528. // We know that the count starts at zero and does not overflow.
  1529. if (Count->getType() != IdxTy) {
  1530. // The exit count can be of pointer type. Convert it to the correct
  1531. // integer type.
  1532. if (ExitCount->getType()->isPointerTy())
  1533. Count = BypassBuilder.CreatePointerCast(Count, IdxTy, "ptrcnt.to.int");
  1534. else
  1535. Count = BypassBuilder.CreateZExtOrTrunc(Count, IdxTy, "cnt.cast");
  1536. }
  1537. // Add the start index to the loop count to get the new end index.
  1538. Value *IdxEnd = BypassBuilder.CreateAdd(Count, StartIdx, "end.idx");
  1539. // Now we need to generate the expression for N - (N % VF), which is
  1540. // the part that the vectorized body will execute.
  1541. Value *R = BypassBuilder.CreateURem(Count, Step, "n.mod.vf");
  1542. Value *CountRoundDown = BypassBuilder.CreateSub(Count, R, "n.vec");
  1543. Value *IdxEndRoundDown = BypassBuilder.CreateAdd(CountRoundDown, StartIdx,
  1544. "end.idx.rnd.down");
  1545. // Now, compare the new count to zero. If it is zero skip the vector loop and
  1546. // jump to the scalar loop.
  1547. Value *Cmp = BypassBuilder.CreateICmpEQ(IdxEndRoundDown, StartIdx,
  1548. "cmp.zero");
  1549. BasicBlock *LastBypassBlock = BypassBlock;
  1550. // Generate the code to check that the strides we assumed to be one are really
  1551. // one. We want the new basic block to start at the first instruction in a
  1552. // sequence of instructions that form a check.
  1553. Instruction *StrideCheck;
  1554. Instruction *FirstCheckInst;
  1555. tie(FirstCheckInst, StrideCheck) =
  1556. addStrideCheck(BypassBlock->getTerminator());
  1557. if (StrideCheck) {
  1558. // Create a new block containing the stride check.
  1559. BasicBlock *CheckBlock =
  1560. BypassBlock->splitBasicBlock(FirstCheckInst, "vector.stridecheck");
  1561. if (ParentLoop)
  1562. ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
  1563. LoopBypassBlocks.push_back(CheckBlock);
  1564. // Replace the branch into the memory check block with a conditional branch
  1565. // for the "few elements case".
  1566. Instruction *OldTerm = BypassBlock->getTerminator();
  1567. BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
  1568. OldTerm->eraseFromParent();
  1569. Cmp = StrideCheck;
  1570. LastBypassBlock = CheckBlock;
  1571. }
  1572. // Generate the code that checks in runtime if arrays overlap. We put the
  1573. // checks into a separate block to make the more common case of few elements
  1574. // faster.
  1575. Instruction *MemRuntimeCheck;
  1576. tie(FirstCheckInst, MemRuntimeCheck) =
  1577. addRuntimeCheck(LastBypassBlock->getTerminator());
  1578. if (MemRuntimeCheck) {
  1579. // Create a new block containing the memory check.
  1580. BasicBlock *CheckBlock =
  1581. LastBypassBlock->splitBasicBlock(MemRuntimeCheck, "vector.memcheck");
  1582. if (ParentLoop)
  1583. ParentLoop->addBasicBlockToLoop(CheckBlock, LI->getBase());
  1584. LoopBypassBlocks.push_back(CheckBlock);
  1585. // Replace the branch into the memory check block with a conditional branch
  1586. // for the "few elements case".
  1587. Instruction *OldTerm = LastBypassBlock->getTerminator();
  1588. BranchInst::Create(MiddleBlock, CheckBlock, Cmp, OldTerm);
  1589. OldTerm->eraseFromParent();
  1590. Cmp = MemRuntimeCheck;
  1591. LastBypassBlock = CheckBlock;
  1592. }
  1593. LastBypassBlock->getTerminator()->eraseFromParent();
  1594. BranchInst::Create(MiddleBlock, VectorPH, Cmp,
  1595. LastBypassBlock);
  1596. // We are going to resume the execution of the scalar loop.
  1597. // Go over all of the induction variables that we found and fix the
  1598. // PHIs that are left in the scalar version of the loop.
  1599. // The starting values of PHI nodes depend on the counter of the last
  1600. // iteration in the vectorized loop.
  1601. // If we come from a bypass edge then we need to start from the original
  1602. // start value.
  1603. // This variable saves the new starting index for the scalar loop.
  1604. PHINode *ResumeIndex = 0;
  1605. LoopVectorizationLegality::InductionList::iterator I, E;
  1606. LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
  1607. // Set builder to point to last bypass block.
  1608. BypassBuilder.SetInsertPoint(LoopBypassBlocks.back()->getTerminator());
  1609. for (I = List->begin(), E = List->end(); I != E; ++I) {
  1610. PHINode *OrigPhi = I->first;
  1611. LoopVectorizationLegality::InductionInfo II = I->second;
  1612. Type *ResumeValTy = (OrigPhi == OldInduction) ? IdxTy : OrigPhi->getType();
  1613. PHINode *ResumeVal = PHINode::Create(ResumeValTy, 2, "resume.val",
  1614. MiddleBlock->getTerminator());
  1615. // We might have extended the type of the induction variable but we need a
  1616. // truncated version for the scalar loop.
  1617. PHINode *TruncResumeVal = (OrigPhi == OldInduction) ?
  1618. PHINode::Create(OrigPhi->getType(), 2, "trunc.resume.val",
  1619. MiddleBlock->getTerminator()) : 0;
  1620. Value *EndValue = 0;
  1621. switch (II.IK) {
  1622. case LoopVectorizationLegality::IK_NoInduction:
  1623. llvm_unreachable("Unknown induction");
  1624. case LoopVectorizationLegality::IK_IntInduction: {
  1625. // Handle the integer induction counter.
  1626. assert(OrigPhi->getType()->isIntegerTy() && "Invalid type");
  1627. // We have the canonical induction variable.
  1628. if (OrigPhi == OldInduction) {
  1629. // Create a truncated version of the resume value for the scalar loop,
  1630. // we might have promoted the type to a larger width.
  1631. EndValue =
  1632. BypassBuilder.CreateTrunc(IdxEndRoundDown, OrigPhi->getType());
  1633. // The new PHI merges the original incoming value, in case of a bypass,
  1634. // or the value at the end of the vectorized loop.
  1635. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  1636. TruncResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
  1637. TruncResumeVal->addIncoming(EndValue, VecBody);
  1638. // We know what the end value is.
  1639. EndValue = IdxEndRoundDown;
  1640. // We also know which PHI node holds it.
  1641. ResumeIndex = ResumeVal;
  1642. break;
  1643. }
  1644. // Not the canonical induction variable - add the vector loop count to the
  1645. // start value.
  1646. Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
  1647. II.StartValue->getType(),
  1648. "cast.crd");
  1649. EndValue = BypassBuilder.CreateAdd(CRD, II.StartValue , "ind.end");
  1650. break;
  1651. }
  1652. case LoopVectorizationLegality::IK_ReverseIntInduction: {
  1653. // Convert the CountRoundDown variable to the PHI size.
  1654. Value *CRD = BypassBuilder.CreateSExtOrTrunc(CountRoundDown,
  1655. II.StartValue->getType(),
  1656. "cast.crd");
  1657. // Handle reverse integer induction counter.
  1658. EndValue = BypassBuilder.CreateSub(II.StartValue, CRD, "rev.ind.end");
  1659. break;
  1660. }
  1661. case LoopVectorizationLegality::IK_PtrInduction: {
  1662. // For pointer induction variables, calculate the offset using
  1663. // the end index.
  1664. EndValue = BypassBuilder.CreateGEP(II.StartValue, CountRoundDown,
  1665. "ptr.ind.end");
  1666. break;
  1667. }
  1668. case LoopVectorizationLegality::IK_ReversePtrInduction: {
  1669. // The value at the end of the loop for the reverse pointer is calculated
  1670. // by creating a GEP with a negative index starting from the start value.
  1671. Value *Zero = ConstantInt::get(CountRoundDown->getType(), 0);
  1672. Value *NegIdx = BypassBuilder.CreateSub(Zero, CountRoundDown,
  1673. "rev.ind.end");
  1674. EndValue = BypassBuilder.CreateGEP(II.StartValue, NegIdx,
  1675. "rev.ptr.ind.end");
  1676. break;
  1677. }
  1678. }// end of case
  1679. // The new PHI merges the original incoming value, in case of a bypass,
  1680. // or the value at the end of the vectorized loop.
  1681. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I) {
  1682. if (OrigPhi == OldInduction)
  1683. ResumeVal->addIncoming(StartIdx, LoopBypassBlocks[I]);
  1684. else
  1685. ResumeVal->addIncoming(II.StartValue, LoopBypassBlocks[I]);
  1686. }
  1687. ResumeVal->addIncoming(EndValue, VecBody);
  1688. // Fix the scalar body counter (PHI node).
  1689. unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
  1690. // The old inductions phi node in the scalar body needs the truncated value.
  1691. if (OrigPhi == OldInduction)
  1692. OrigPhi->setIncomingValue(BlockIdx, TruncResumeVal);
  1693. else
  1694. OrigPhi->setIncomingValue(BlockIdx, ResumeVal);
  1695. }
  1696. // If we are generating a new induction variable then we also need to
  1697. // generate the code that calculates the exit value. This value is not
  1698. // simply the end of the counter because we may skip the vectorized body
  1699. // in case of a runtime check.
  1700. if (!OldInduction){
  1701. assert(!ResumeIndex && "Unexpected resume value found");
  1702. ResumeIndex = PHINode::Create(IdxTy, 2, "new.indc.resume.val",
  1703. MiddleBlock->getTerminator());
  1704. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  1705. ResumeIndex->addIncoming(StartIdx, LoopBypassBlocks[I]);
  1706. ResumeIndex->addIncoming(IdxEndRoundDown, VecBody);
  1707. }
  1708. // Make sure that we found the index where scalar loop needs to continue.
  1709. assert(ResumeIndex && ResumeIndex->getType()->isIntegerTy() &&
  1710. "Invalid resume Index");
  1711. // Add a check in the middle block to see if we have completed
  1712. // all of the iterations in the first vector loop.
  1713. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  1714. Value *CmpN = CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, IdxEnd,
  1715. ResumeIndex, "cmp.n",
  1716. MiddleBlock->getTerminator());
  1717. BranchInst::Create(ExitBlock, ScalarPH, CmpN, MiddleBlock->getTerminator());
  1718. // Remove the old terminator.
  1719. MiddleBlock->getTerminator()->eraseFromParent();
  1720. // Create i+1 and fill the PHINode.
  1721. Value *NextIdx = Builder.CreateAdd(Induction, Step, "index.next");
  1722. Induction->addIncoming(StartIdx, VectorPH);
  1723. Induction->addIncoming(NextIdx, VecBody);
  1724. // Create the compare.
  1725. Value *ICmp = Builder.CreateICmpEQ(NextIdx, IdxEndRoundDown);
  1726. Builder.CreateCondBr(ICmp, MiddleBlock, VecBody);
  1727. // Now we have two terminators. Remove the old one from the block.
  1728. VecBody->getTerminator()->eraseFromParent();
  1729. // Get ready to start creating new instructions into the vectorized body.
  1730. Builder.SetInsertPoint(VecBody->getFirstInsertionPt());
  1731. // Save the state.
  1732. LoopVectorPreHeader = VectorPH;
  1733. LoopScalarPreHeader = ScalarPH;
  1734. LoopMiddleBlock = MiddleBlock;
  1735. LoopExitBlock = ExitBlock;
  1736. LoopVectorBody = VecBody;
  1737. LoopScalarBody = OldBasicBlock;
  1738. LoopVectorizeHints Hints(Lp, true);
  1739. Hints.setAlreadyVectorized(Lp);
  1740. }
  1741. /// This function returns the identity element (or neutral element) for
  1742. /// the operation K.
  1743. Constant*
  1744. LoopVectorizationLegality::getReductionIdentity(ReductionKind K, Type *Tp) {
  1745. switch (K) {
  1746. case RK_IntegerXor:
  1747. case RK_IntegerAdd:
  1748. case RK_IntegerOr:
  1749. // Adding, Xoring, Oring zero to a number does not change it.
  1750. return ConstantInt::get(Tp, 0);
  1751. case RK_IntegerMult:
  1752. // Multiplying a number by 1 does not change it.
  1753. return ConstantInt::get(Tp, 1);
  1754. case RK_IntegerAnd:
  1755. // AND-ing a number with an all-1 value does not change it.
  1756. return ConstantInt::get(Tp, -1, true);
  1757. case RK_FloatMult:
  1758. // Multiplying a number by 1 does not change it.
  1759. return ConstantFP::get(Tp, 1.0L);
  1760. case RK_FloatAdd:
  1761. // Adding zero to a number does not change it.
  1762. return ConstantFP::get(Tp, 0.0L);
  1763. default:
  1764. llvm_unreachable("Unknown reduction kind");
  1765. }
  1766. }
  1767. static Intrinsic::ID checkUnaryFloatSignature(const CallInst &I,
  1768. Intrinsic::ID ValidIntrinsicID) {
  1769. if (I.getNumArgOperands() != 1 ||
  1770. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  1771. I.getType() != I.getArgOperand(0)->getType() ||
  1772. !I.onlyReadsMemory())
  1773. return Intrinsic::not_intrinsic;
  1774. return ValidIntrinsicID;
  1775. }
  1776. static Intrinsic::ID checkBinaryFloatSignature(const CallInst &I,
  1777. Intrinsic::ID ValidIntrinsicID) {
  1778. if (I.getNumArgOperands() != 2 ||
  1779. !I.getArgOperand(0)->getType()->isFloatingPointTy() ||
  1780. !I.getArgOperand(1)->getType()->isFloatingPointTy() ||
  1781. I.getType() != I.getArgOperand(0)->getType() ||
  1782. I.getType() != I.getArgOperand(1)->getType() ||
  1783. !I.onlyReadsMemory())
  1784. return Intrinsic::not_intrinsic;
  1785. return ValidIntrinsicID;
  1786. }
  1787. static Intrinsic::ID
  1788. getIntrinsicIDForCall(CallInst *CI, const TargetLibraryInfo *TLI) {
  1789. // If we have an intrinsic call, check if it is trivially vectorizable.
  1790. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI)) {
  1791. switch (II->getIntrinsicID()) {
  1792. case Intrinsic::sqrt:
  1793. case Intrinsic::sin:
  1794. case Intrinsic::cos:
  1795. case Intrinsic::exp:
  1796. case Intrinsic::exp2:
  1797. case Intrinsic::log:
  1798. case Intrinsic::log10:
  1799. case Intrinsic::log2:
  1800. case Intrinsic::fabs:
  1801. case Intrinsic::copysign:
  1802. case Intrinsic::floor:
  1803. case Intrinsic::ceil:
  1804. case Intrinsic::trunc:
  1805. case Intrinsic::rint:
  1806. case Intrinsic::nearbyint:
  1807. case Intrinsic::round:
  1808. case Intrinsic::pow:
  1809. case Intrinsic::fma:
  1810. case Intrinsic::fmuladd:
  1811. case Intrinsic::lifetime_start:
  1812. case Intrinsic::lifetime_end:
  1813. return II->getIntrinsicID();
  1814. default:
  1815. return Intrinsic::not_intrinsic;
  1816. }
  1817. }
  1818. if (!TLI)
  1819. return Intrinsic::not_intrinsic;
  1820. LibFunc::Func Func;
  1821. Function *F = CI->getCalledFunction();
  1822. // We're going to make assumptions on the semantics of the functions, check
  1823. // that the target knows that it's available in this environment and it does
  1824. // not have local linkage.
  1825. if (!F || F->hasLocalLinkage() || !TLI->getLibFunc(F->getName(), Func))
  1826. return Intrinsic::not_intrinsic;
  1827. // Otherwise check if we have a call to a function that can be turned into a
  1828. // vector intrinsic.
  1829. switch (Func) {
  1830. default:
  1831. break;
  1832. case LibFunc::sin:
  1833. case LibFunc::sinf:
  1834. case LibFunc::sinl:
  1835. return checkUnaryFloatSignature(*CI, Intrinsic::sin);
  1836. case LibFunc::cos:
  1837. case LibFunc::cosf:
  1838. case LibFunc::cosl:
  1839. return checkUnaryFloatSignature(*CI, Intrinsic::cos);
  1840. case LibFunc::exp:
  1841. case LibFunc::expf:
  1842. case LibFunc::expl:
  1843. return checkUnaryFloatSignature(*CI, Intrinsic::exp);
  1844. case LibFunc::exp2:
  1845. case LibFunc::exp2f:
  1846. case LibFunc::exp2l:
  1847. return checkUnaryFloatSignature(*CI, Intrinsic::exp2);
  1848. case LibFunc::log:
  1849. case LibFunc::logf:
  1850. case LibFunc::logl:
  1851. return checkUnaryFloatSignature(*CI, Intrinsic::log);
  1852. case LibFunc::log10:
  1853. case LibFunc::log10f:
  1854. case LibFunc::log10l:
  1855. return checkUnaryFloatSignature(*CI, Intrinsic::log10);
  1856. case LibFunc::log2:
  1857. case LibFunc::log2f:
  1858. case LibFunc::log2l:
  1859. return checkUnaryFloatSignature(*CI, Intrinsic::log2);
  1860. case LibFunc::fabs:
  1861. case LibFunc::fabsf:
  1862. case LibFunc::fabsl:
  1863. return checkUnaryFloatSignature(*CI, Intrinsic::fabs);
  1864. case LibFunc::copysign:
  1865. case LibFunc::copysignf:
  1866. case LibFunc::copysignl:
  1867. return checkBinaryFloatSignature(*CI, Intrinsic::copysign);
  1868. case LibFunc::floor:
  1869. case LibFunc::floorf:
  1870. case LibFunc::floorl:
  1871. return checkUnaryFloatSignature(*CI, Intrinsic::floor);
  1872. case LibFunc::ceil:
  1873. case LibFunc::ceilf:
  1874. case LibFunc::ceill:
  1875. return checkUnaryFloatSignature(*CI, Intrinsic::ceil);
  1876. case LibFunc::trunc:
  1877. case LibFunc::truncf:
  1878. case LibFunc::truncl:
  1879. return checkUnaryFloatSignature(*CI, Intrinsic::trunc);
  1880. case LibFunc::rint:
  1881. case LibFunc::rintf:
  1882. case LibFunc::rintl:
  1883. return checkUnaryFloatSignature(*CI, Intrinsic::rint);
  1884. case LibFunc::nearbyint:
  1885. case LibFunc::nearbyintf:
  1886. case LibFunc::nearbyintl:
  1887. return checkUnaryFloatSignature(*CI, Intrinsic::nearbyint);
  1888. case LibFunc::round:
  1889. case LibFunc::roundf:
  1890. case LibFunc::roundl:
  1891. return checkUnaryFloatSignature(*CI, Intrinsic::round);
  1892. case LibFunc::pow:
  1893. case LibFunc::powf:
  1894. case LibFunc::powl:
  1895. return checkBinaryFloatSignature(*CI, Intrinsic::pow);
  1896. }
  1897. return Intrinsic::not_intrinsic;
  1898. }
  1899. /// This function translates the reduction kind to an LLVM binary operator.
  1900. static unsigned
  1901. getReductionBinOp(LoopVectorizationLegality::ReductionKind Kind) {
  1902. switch (Kind) {
  1903. case LoopVectorizationLegality::RK_IntegerAdd:
  1904. return Instruction::Add;
  1905. case LoopVectorizationLegality::RK_IntegerMult:
  1906. return Instruction::Mul;
  1907. case LoopVectorizationLegality::RK_IntegerOr:
  1908. return Instruction::Or;
  1909. case LoopVectorizationLegality::RK_IntegerAnd:
  1910. return Instruction::And;
  1911. case LoopVectorizationLegality::RK_IntegerXor:
  1912. return Instruction::Xor;
  1913. case LoopVectorizationLegality::RK_FloatMult:
  1914. return Instruction::FMul;
  1915. case LoopVectorizationLegality::RK_FloatAdd:
  1916. return Instruction::FAdd;
  1917. case LoopVectorizationLegality::RK_IntegerMinMax:
  1918. return Instruction::ICmp;
  1919. case LoopVectorizationLegality::RK_FloatMinMax:
  1920. return Instruction::FCmp;
  1921. default:
  1922. llvm_unreachable("Unknown reduction operation");
  1923. }
  1924. }
  1925. Value *createMinMaxOp(IRBuilder<> &Builder,
  1926. LoopVectorizationLegality::MinMaxReductionKind RK,
  1927. Value *Left,
  1928. Value *Right) {
  1929. CmpInst::Predicate P = CmpInst::ICMP_NE;
  1930. switch (RK) {
  1931. default:
  1932. llvm_unreachable("Unknown min/max reduction kind");
  1933. case LoopVectorizationLegality::MRK_UIntMin:
  1934. P = CmpInst::ICMP_ULT;
  1935. break;
  1936. case LoopVectorizationLegality::MRK_UIntMax:
  1937. P = CmpInst::ICMP_UGT;
  1938. break;
  1939. case LoopVectorizationLegality::MRK_SIntMin:
  1940. P = CmpInst::ICMP_SLT;
  1941. break;
  1942. case LoopVectorizationLegality::MRK_SIntMax:
  1943. P = CmpInst::ICMP_SGT;
  1944. break;
  1945. case LoopVectorizationLegality::MRK_FloatMin:
  1946. P = CmpInst::FCMP_OLT;
  1947. break;
  1948. case LoopVectorizationLegality::MRK_FloatMax:
  1949. P = CmpInst::FCMP_OGT;
  1950. break;
  1951. }
  1952. Value *Cmp;
  1953. if (RK == LoopVectorizationLegality::MRK_FloatMin ||
  1954. RK == LoopVectorizationLegality::MRK_FloatMax)
  1955. Cmp = Builder.CreateFCmp(P, Left, Right, "rdx.minmax.cmp");
  1956. else
  1957. Cmp = Builder.CreateICmp(P, Left, Right, "rdx.minmax.cmp");
  1958. Value *Select = Builder.CreateSelect(Cmp, Left, Right, "rdx.minmax.select");
  1959. return Select;
  1960. }
  1961. namespace {
  1962. struct CSEDenseMapInfo {
  1963. static bool canHandle(Instruction *I) {
  1964. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  1965. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  1966. }
  1967. static inline Instruction *getEmptyKey() {
  1968. return DenseMapInfo<Instruction *>::getEmptyKey();
  1969. }
  1970. static inline Instruction *getTombstoneKey() {
  1971. return DenseMapInfo<Instruction *>::getTombstoneKey();
  1972. }
  1973. static unsigned getHashValue(Instruction *I) {
  1974. assert(canHandle(I) && "Unknown instruction!");
  1975. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  1976. I->value_op_end()));
  1977. }
  1978. static bool isEqual(Instruction *LHS, Instruction *RHS) {
  1979. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  1980. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  1981. return LHS == RHS;
  1982. return LHS->isIdenticalTo(RHS);
  1983. }
  1984. };
  1985. }
  1986. ///\brief Perform cse of induction variable instructions.
  1987. static void cse(BasicBlock *BB) {
  1988. // Perform simple cse.
  1989. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  1990. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  1991. Instruction *In = I++;
  1992. if (!CSEDenseMapInfo::canHandle(In))
  1993. continue;
  1994. // Check if we can replace this instruction with any of the
  1995. // visited instructions.
  1996. if (Instruction *V = CSEMap.lookup(In)) {
  1997. In->replaceAllUsesWith(V);
  1998. In->eraseFromParent();
  1999. continue;
  2000. }
  2001. CSEMap[In] = In;
  2002. }
  2003. }
  2004. void InnerLoopVectorizer::vectorizeLoop() {
  2005. //===------------------------------------------------===//
  2006. //
  2007. // Notice: any optimization or new instruction that go
  2008. // into the code below should be also be implemented in
  2009. // the cost-model.
  2010. //
  2011. //===------------------------------------------------===//
  2012. Constant *Zero = Builder.getInt32(0);
  2013. // In order to support reduction variables we need to be able to vectorize
  2014. // Phi nodes. Phi nodes have cycles, so we need to vectorize them in two
  2015. // stages. First, we create a new vector PHI node with no incoming edges.
  2016. // We use this value when we vectorize all of the instructions that use the
  2017. // PHI. Next, after all of the instructions in the block are complete we
  2018. // add the new incoming edges to the PHI. At this point all of the
  2019. // instructions in the basic block are vectorized, so we can use them to
  2020. // construct the PHI.
  2021. PhiVector RdxPHIsToFix;
  2022. // Scan the loop in a topological order to ensure that defs are vectorized
  2023. // before users.
  2024. LoopBlocksDFS DFS(OrigLoop);
  2025. DFS.perform(LI);
  2026. // Vectorize all of the blocks in the original loop.
  2027. for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
  2028. be = DFS.endRPO(); bb != be; ++bb)
  2029. vectorizeBlockInLoop(*bb, &RdxPHIsToFix);
  2030. // At this point every instruction in the original loop is widened to
  2031. // a vector form. We are almost done. Now, we need to fix the PHI nodes
  2032. // that we vectorized. The PHI nodes are currently empty because we did
  2033. // not want to introduce cycles. Notice that the remaining PHI nodes
  2034. // that we need to fix are reduction variables.
  2035. // Create the 'reduced' values for each of the induction vars.
  2036. // The reduced values are the vector values that we scalarize and combine
  2037. // after the loop is finished.
  2038. for (PhiVector::iterator it = RdxPHIsToFix.begin(), e = RdxPHIsToFix.end();
  2039. it != e; ++it) {
  2040. PHINode *RdxPhi = *it;
  2041. assert(RdxPhi && "Unable to recover vectorized PHI");
  2042. // Find the reduction variable descriptor.
  2043. assert(Legal->getReductionVars()->count(RdxPhi) &&
  2044. "Unable to find the reduction variable");
  2045. LoopVectorizationLegality::ReductionDescriptor RdxDesc =
  2046. (*Legal->getReductionVars())[RdxPhi];
  2047. setDebugLocFromInst(Builder, RdxDesc.StartValue);
  2048. // We need to generate a reduction vector from the incoming scalar.
  2049. // To do so, we need to generate the 'identity' vector and override
  2050. // one of the elements with the incoming scalar reduction. We need
  2051. // to do it in the vector-loop preheader.
  2052. Builder.SetInsertPoint(LoopBypassBlocks.front()->getTerminator());
  2053. // This is the vector-clone of the value that leaves the loop.
  2054. VectorParts &VectorExit = getVectorValue(RdxDesc.LoopExitInstr);
  2055. Type *VecTy = VectorExit[0]->getType();
  2056. // Find the reduction identity variable. Zero for addition, or, xor,
  2057. // one for multiplication, -1 for And.
  2058. Value *Identity;
  2059. Value *VectorStart;
  2060. if (RdxDesc.Kind == LoopVectorizationLegality::RK_IntegerMinMax ||
  2061. RdxDesc.Kind == LoopVectorizationLegality::RK_FloatMinMax) {
  2062. // MinMax reduction have the start value as their identify.
  2063. if (VF == 1) {
  2064. VectorStart = Identity = RdxDesc.StartValue;
  2065. } else {
  2066. VectorStart = Identity = Builder.CreateVectorSplat(VF,
  2067. RdxDesc.StartValue,
  2068. "minmax.ident");
  2069. }
  2070. } else {
  2071. // Handle other reduction kinds:
  2072. Constant *Iden =
  2073. LoopVectorizationLegality::getReductionIdentity(RdxDesc.Kind,
  2074. VecTy->getScalarType());
  2075. if (VF == 1) {
  2076. Identity = Iden;
  2077. // This vector is the Identity vector where the first element is the
  2078. // incoming scalar reduction.
  2079. VectorStart = RdxDesc.StartValue;
  2080. } else {
  2081. Identity = ConstantVector::getSplat(VF, Iden);
  2082. // This vector is the Identity vector where the first element is the
  2083. // incoming scalar reduction.
  2084. VectorStart = Builder.CreateInsertElement(Identity,
  2085. RdxDesc.StartValue, Zero);
  2086. }
  2087. }
  2088. // Fix the vector-loop phi.
  2089. // We created the induction variable so we know that the
  2090. // preheader is the first entry.
  2091. BasicBlock *VecPreheader = Induction->getIncomingBlock(0);
  2092. // Reductions do not have to start at zero. They can start with
  2093. // any loop invariant values.
  2094. VectorParts &VecRdxPhi = WidenMap.get(RdxPhi);
  2095. BasicBlock *Latch = OrigLoop->getLoopLatch();
  2096. Value *LoopVal = RdxPhi->getIncomingValueForBlock(Latch);
  2097. VectorParts &Val = getVectorValue(LoopVal);
  2098. for (unsigned part = 0; part < UF; ++part) {
  2099. // Make sure to add the reduction stat value only to the
  2100. // first unroll part.
  2101. Value *StartVal = (part == 0) ? VectorStart : Identity;
  2102. cast<PHINode>(VecRdxPhi[part])->addIncoming(StartVal, VecPreheader);
  2103. cast<PHINode>(VecRdxPhi[part])->addIncoming(Val[part], LoopVectorBody);
  2104. }
  2105. // Before each round, move the insertion point right between
  2106. // the PHIs and the values we are going to write.
  2107. // This allows us to write both PHINodes and the extractelement
  2108. // instructions.
  2109. Builder.SetInsertPoint(LoopMiddleBlock->getFirstInsertionPt());
  2110. VectorParts RdxParts;
  2111. setDebugLocFromInst(Builder, RdxDesc.LoopExitInstr);
  2112. for (unsigned part = 0; part < UF; ++part) {
  2113. // This PHINode contains the vectorized reduction variable, or
  2114. // the initial value vector, if we bypass the vector loop.
  2115. VectorParts &RdxExitVal = getVectorValue(RdxDesc.LoopExitInstr);
  2116. PHINode *NewPhi = Builder.CreatePHI(VecTy, 2, "rdx.vec.exit.phi");
  2117. Value *StartVal = (part == 0) ? VectorStart : Identity;
  2118. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  2119. NewPhi->addIncoming(StartVal, LoopBypassBlocks[I]);
  2120. NewPhi->addIncoming(RdxExitVal[part], LoopVectorBody);
  2121. RdxParts.push_back(NewPhi);
  2122. }
  2123. // Reduce all of the unrolled parts into a single vector.
  2124. Value *ReducedPartRdx = RdxParts[0];
  2125. unsigned Op = getReductionBinOp(RdxDesc.Kind);
  2126. setDebugLocFromInst(Builder, ReducedPartRdx);
  2127. for (unsigned part = 1; part < UF; ++part) {
  2128. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  2129. ReducedPartRdx = Builder.CreateBinOp((Instruction::BinaryOps)Op,
  2130. RdxParts[part], ReducedPartRdx,
  2131. "bin.rdx");
  2132. else
  2133. ReducedPartRdx = createMinMaxOp(Builder, RdxDesc.MinMaxKind,
  2134. ReducedPartRdx, RdxParts[part]);
  2135. }
  2136. if (VF > 1) {
  2137. // VF is a power of 2 so we can emit the reduction using log2(VF) shuffles
  2138. // and vector ops, reducing the set of values being computed by half each
  2139. // round.
  2140. assert(isPowerOf2_32(VF) &&
  2141. "Reduction emission only supported for pow2 vectors!");
  2142. Value *TmpVec = ReducedPartRdx;
  2143. SmallVector<Constant*, 32> ShuffleMask(VF, 0);
  2144. for (unsigned i = VF; i != 1; i >>= 1) {
  2145. // Move the upper half of the vector to the lower half.
  2146. for (unsigned j = 0; j != i/2; ++j)
  2147. ShuffleMask[j] = Builder.getInt32(i/2 + j);
  2148. // Fill the rest of the mask with undef.
  2149. std::fill(&ShuffleMask[i/2], ShuffleMask.end(),
  2150. UndefValue::get(Builder.getInt32Ty()));
  2151. Value *Shuf =
  2152. Builder.CreateShuffleVector(TmpVec,
  2153. UndefValue::get(TmpVec->getType()),
  2154. ConstantVector::get(ShuffleMask),
  2155. "rdx.shuf");
  2156. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  2157. TmpVec = Builder.CreateBinOp((Instruction::BinaryOps)Op, TmpVec, Shuf,
  2158. "bin.rdx");
  2159. else
  2160. TmpVec = createMinMaxOp(Builder, RdxDesc.MinMaxKind, TmpVec, Shuf);
  2161. }
  2162. // The result is in the first element of the vector.
  2163. ReducedPartRdx = Builder.CreateExtractElement(TmpVec,
  2164. Builder.getInt32(0));
  2165. }
  2166. // Now, we need to fix the users of the reduction variable
  2167. // inside and outside of the scalar remainder loop.
  2168. // We know that the loop is in LCSSA form. We need to update the
  2169. // PHI nodes in the exit blocks.
  2170. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  2171. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  2172. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  2173. if (!LCSSAPhi) break;
  2174. // All PHINodes need to have a single entry edge, or two if
  2175. // we already fixed them.
  2176. assert(LCSSAPhi->getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
  2177. // We found our reduction value exit-PHI. Update it with the
  2178. // incoming bypass edge.
  2179. if (LCSSAPhi->getIncomingValue(0) == RdxDesc.LoopExitInstr) {
  2180. // Add an edge coming from the bypass.
  2181. LCSSAPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  2182. break;
  2183. }
  2184. }// end of the LCSSA phi scan.
  2185. // Fix the scalar loop reduction variable with the incoming reduction sum
  2186. // from the vector body and from the backedge value.
  2187. int IncomingEdgeBlockIdx =
  2188. (RdxPhi)->getBasicBlockIndex(OrigLoop->getLoopLatch());
  2189. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  2190. // Pick the other block.
  2191. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  2192. (RdxPhi)->setIncomingValue(SelfEdgeBlockIdx, ReducedPartRdx);
  2193. (RdxPhi)->setIncomingValue(IncomingEdgeBlockIdx, RdxDesc.LoopExitInstr);
  2194. }// end of for each redux variable.
  2195. fixLCSSAPHIs();
  2196. // Remove redundant induction instructions.
  2197. cse(LoopVectorBody);
  2198. }
  2199. void InnerLoopVectorizer::fixLCSSAPHIs() {
  2200. for (BasicBlock::iterator LEI = LoopExitBlock->begin(),
  2201. LEE = LoopExitBlock->end(); LEI != LEE; ++LEI) {
  2202. PHINode *LCSSAPhi = dyn_cast<PHINode>(LEI);
  2203. if (!LCSSAPhi) break;
  2204. if (LCSSAPhi->getNumIncomingValues() == 1)
  2205. LCSSAPhi->addIncoming(UndefValue::get(LCSSAPhi->getType()),
  2206. LoopMiddleBlock);
  2207. }
  2208. }
  2209. InnerLoopVectorizer::VectorParts
  2210. InnerLoopVectorizer::createEdgeMask(BasicBlock *Src, BasicBlock *Dst) {
  2211. assert(std::find(pred_begin(Dst), pred_end(Dst), Src) != pred_end(Dst) &&
  2212. "Invalid edge");
  2213. // Look for cached value.
  2214. std::pair<BasicBlock*, BasicBlock*> Edge(Src, Dst);
  2215. EdgeMaskCache::iterator ECEntryIt = MaskCache.find(Edge);
  2216. if (ECEntryIt != MaskCache.end())
  2217. return ECEntryIt->second;
  2218. VectorParts SrcMask = createBlockInMask(Src);
  2219. // The terminator has to be a branch inst!
  2220. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  2221. assert(BI && "Unexpected terminator found");
  2222. if (BI->isConditional()) {
  2223. VectorParts EdgeMask = getVectorValue(BI->getCondition());
  2224. if (BI->getSuccessor(0) != Dst)
  2225. for (unsigned part = 0; part < UF; ++part)
  2226. EdgeMask[part] = Builder.CreateNot(EdgeMask[part]);
  2227. for (unsigned part = 0; part < UF; ++part)
  2228. EdgeMask[part] = Builder.CreateAnd(EdgeMask[part], SrcMask[part]);
  2229. MaskCache[Edge] = EdgeMask;
  2230. return EdgeMask;
  2231. }
  2232. MaskCache[Edge] = SrcMask;
  2233. return SrcMask;
  2234. }
  2235. InnerLoopVectorizer::VectorParts
  2236. InnerLoopVectorizer::createBlockInMask(BasicBlock *BB) {
  2237. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  2238. // Loop incoming mask is all-one.
  2239. if (OrigLoop->getHeader() == BB) {
  2240. Value *C = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 1);
  2241. return getVectorValue(C);
  2242. }
  2243. // This is the block mask. We OR all incoming edges, and with zero.
  2244. Value *Zero = ConstantInt::get(IntegerType::getInt1Ty(BB->getContext()), 0);
  2245. VectorParts BlockMask = getVectorValue(Zero);
  2246. // For each pred:
  2247. for (pred_iterator it = pred_begin(BB), e = pred_end(BB); it != e; ++it) {
  2248. VectorParts EM = createEdgeMask(*it, BB);
  2249. for (unsigned part = 0; part < UF; ++part)
  2250. BlockMask[part] = Builder.CreateOr(BlockMask[part], EM[part]);
  2251. }
  2252. return BlockMask;
  2253. }
  2254. void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN,
  2255. InnerLoopVectorizer::VectorParts &Entry,
  2256. unsigned UF, unsigned VF, PhiVector *PV) {
  2257. PHINode* P = cast<PHINode>(PN);
  2258. // Handle reduction variables:
  2259. if (Legal->getReductionVars()->count(P)) {
  2260. for (unsigned part = 0; part < UF; ++part) {
  2261. // This is phase one of vectorizing PHIs.
  2262. Type *VecTy = (VF == 1) ? PN->getType() :
  2263. VectorType::get(PN->getType(), VF);
  2264. Entry[part] = PHINode::Create(VecTy, 2, "vec.phi",
  2265. LoopVectorBody-> getFirstInsertionPt());
  2266. }
  2267. PV->push_back(P);
  2268. return;
  2269. }
  2270. setDebugLocFromInst(Builder, P);
  2271. // Check for PHI nodes that are lowered to vector selects.
  2272. if (P->getParent() != OrigLoop->getHeader()) {
  2273. // We know that all PHIs in non-header blocks are converted into
  2274. // selects, so we don't have to worry about the insertion order and we
  2275. // can just use the builder.
  2276. // At this point we generate the predication tree. There may be
  2277. // duplications since this is a simple recursive scan, but future
  2278. // optimizations will clean it up.
  2279. unsigned NumIncoming = P->getNumIncomingValues();
  2280. // Generate a sequence of selects of the form:
  2281. // SELECT(Mask3, In3,
  2282. // SELECT(Mask2, In2,
  2283. // ( ...)))
  2284. for (unsigned In = 0; In < NumIncoming; In++) {
  2285. VectorParts Cond = createEdgeMask(P->getIncomingBlock(In),
  2286. P->getParent());
  2287. VectorParts &In0 = getVectorValue(P->getIncomingValue(In));
  2288. for (unsigned part = 0; part < UF; ++part) {
  2289. // We might have single edge PHIs (blocks) - use an identity
  2290. // 'select' for the first PHI operand.
  2291. if (In == 0)
  2292. Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
  2293. In0[part]);
  2294. else
  2295. // Select between the current value and the previous incoming edge
  2296. // based on the incoming mask.
  2297. Entry[part] = Builder.CreateSelect(Cond[part], In0[part],
  2298. Entry[part], "predphi");
  2299. }
  2300. }
  2301. return;
  2302. }
  2303. // This PHINode must be an induction variable.
  2304. // Make sure that we know about it.
  2305. assert(Legal->getInductionVars()->count(P) &&
  2306. "Not an induction variable");
  2307. LoopVectorizationLegality::InductionInfo II =
  2308. Legal->getInductionVars()->lookup(P);
  2309. switch (II.IK) {
  2310. case LoopVectorizationLegality::IK_NoInduction:
  2311. llvm_unreachable("Unknown induction");
  2312. case LoopVectorizationLegality::IK_IntInduction: {
  2313. assert(P->getType() == II.StartValue->getType() && "Types must match");
  2314. Type *PhiTy = P->getType();
  2315. Value *Broadcasted;
  2316. if (P == OldInduction) {
  2317. // Handle the canonical induction variable. We might have had to
  2318. // extend the type.
  2319. Broadcasted = Builder.CreateTrunc(Induction, PhiTy);
  2320. } else {
  2321. // Handle other induction variables that are now based on the
  2322. // canonical one.
  2323. Value *NormalizedIdx = Builder.CreateSub(Induction, ExtendedIdx,
  2324. "normalized.idx");
  2325. NormalizedIdx = Builder.CreateSExtOrTrunc(NormalizedIdx, PhiTy);
  2326. Broadcasted = Builder.CreateAdd(II.StartValue, NormalizedIdx,
  2327. "offset.idx");
  2328. }
  2329. Broadcasted = getBroadcastInstrs(Broadcasted);
  2330. // After broadcasting the induction variable we need to make the vector
  2331. // consecutive by adding 0, 1, 2, etc.
  2332. for (unsigned part = 0; part < UF; ++part)
  2333. Entry[part] = getConsecutiveVector(Broadcasted, VF * part, false);
  2334. return;
  2335. }
  2336. case LoopVectorizationLegality::IK_ReverseIntInduction:
  2337. case LoopVectorizationLegality::IK_PtrInduction:
  2338. case LoopVectorizationLegality::IK_ReversePtrInduction:
  2339. // Handle reverse integer and pointer inductions.
  2340. Value *StartIdx = ExtendedIdx;
  2341. // This is the normalized GEP that starts counting at zero.
  2342. Value *NormalizedIdx = Builder.CreateSub(Induction, StartIdx,
  2343. "normalized.idx");
  2344. // Handle the reverse integer induction variable case.
  2345. if (LoopVectorizationLegality::IK_ReverseIntInduction == II.IK) {
  2346. IntegerType *DstTy = cast<IntegerType>(II.StartValue->getType());
  2347. Value *CNI = Builder.CreateSExtOrTrunc(NormalizedIdx, DstTy,
  2348. "resize.norm.idx");
  2349. Value *ReverseInd = Builder.CreateSub(II.StartValue, CNI,
  2350. "reverse.idx");
  2351. // This is a new value so do not hoist it out.
  2352. Value *Broadcasted = getBroadcastInstrs(ReverseInd);
  2353. // After broadcasting the induction variable we need to make the
  2354. // vector consecutive by adding ... -3, -2, -1, 0.
  2355. for (unsigned part = 0; part < UF; ++part)
  2356. Entry[part] = getConsecutiveVector(Broadcasted, -(int)VF * part,
  2357. true);
  2358. return;
  2359. }
  2360. // Handle the pointer induction variable case.
  2361. assert(P->getType()->isPointerTy() && "Unexpected type.");
  2362. // Is this a reverse induction ptr or a consecutive induction ptr.
  2363. bool Reverse = (LoopVectorizationLegality::IK_ReversePtrInduction ==
  2364. II.IK);
  2365. // This is the vector of results. Notice that we don't generate
  2366. // vector geps because scalar geps result in better code.
  2367. for (unsigned part = 0; part < UF; ++part) {
  2368. if (VF == 1) {
  2369. int EltIndex = (part) * (Reverse ? -1 : 1);
  2370. Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
  2371. Value *GlobalIdx;
  2372. if (Reverse)
  2373. GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
  2374. else
  2375. GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
  2376. Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
  2377. "next.gep");
  2378. Entry[part] = SclrGep;
  2379. continue;
  2380. }
  2381. Value *VecVal = UndefValue::get(VectorType::get(P->getType(), VF));
  2382. for (unsigned int i = 0; i < VF; ++i) {
  2383. int EltIndex = (i + part * VF) * (Reverse ? -1 : 1);
  2384. Constant *Idx = ConstantInt::get(Induction->getType(), EltIndex);
  2385. Value *GlobalIdx;
  2386. if (!Reverse)
  2387. GlobalIdx = Builder.CreateAdd(NormalizedIdx, Idx, "gep.idx");
  2388. else
  2389. GlobalIdx = Builder.CreateSub(Idx, NormalizedIdx, "gep.ridx");
  2390. Value *SclrGep = Builder.CreateGEP(II.StartValue, GlobalIdx,
  2391. "next.gep");
  2392. VecVal = Builder.CreateInsertElement(VecVal, SclrGep,
  2393. Builder.getInt32(i),
  2394. "insert.gep");
  2395. }
  2396. Entry[part] = VecVal;
  2397. }
  2398. return;
  2399. }
  2400. }
  2401. void InnerLoopVectorizer::vectorizeBlockInLoop(BasicBlock *BB, PhiVector *PV) {
  2402. // For each instruction in the old loop.
  2403. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  2404. VectorParts &Entry = WidenMap.get(it);
  2405. switch (it->getOpcode()) {
  2406. case Instruction::Br:
  2407. // Nothing to do for PHIs and BR, since we already took care of the
  2408. // loop control flow instructions.
  2409. continue;
  2410. case Instruction::PHI:{
  2411. // Vectorize PHINodes.
  2412. widenPHIInstruction(it, Entry, UF, VF, PV);
  2413. continue;
  2414. }// End of PHI.
  2415. case Instruction::Add:
  2416. case Instruction::FAdd:
  2417. case Instruction::Sub:
  2418. case Instruction::FSub:
  2419. case Instruction::Mul:
  2420. case Instruction::FMul:
  2421. case Instruction::UDiv:
  2422. case Instruction::SDiv:
  2423. case Instruction::FDiv:
  2424. case Instruction::URem:
  2425. case Instruction::SRem:
  2426. case Instruction::FRem:
  2427. case Instruction::Shl:
  2428. case Instruction::LShr:
  2429. case Instruction::AShr:
  2430. case Instruction::And:
  2431. case Instruction::Or:
  2432. case Instruction::Xor: {
  2433. // Just widen binops.
  2434. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(it);
  2435. setDebugLocFromInst(Builder, BinOp);
  2436. VectorParts &A = getVectorValue(it->getOperand(0));
  2437. VectorParts &B = getVectorValue(it->getOperand(1));
  2438. // Use this vector value for all users of the original instruction.
  2439. for (unsigned Part = 0; Part < UF; ++Part) {
  2440. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A[Part], B[Part]);
  2441. // Update the NSW, NUW and Exact flags. Notice: V can be an Undef.
  2442. BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V);
  2443. if (VecOp && isa<OverflowingBinaryOperator>(BinOp)) {
  2444. VecOp->setHasNoSignedWrap(BinOp->hasNoSignedWrap());
  2445. VecOp->setHasNoUnsignedWrap(BinOp->hasNoUnsignedWrap());
  2446. }
  2447. if (VecOp && isa<PossiblyExactOperator>(VecOp))
  2448. VecOp->setIsExact(BinOp->isExact());
  2449. Entry[Part] = V;
  2450. }
  2451. break;
  2452. }
  2453. case Instruction::Select: {
  2454. // Widen selects.
  2455. // If the selector is loop invariant we can create a select
  2456. // instruction with a scalar condition. Otherwise, use vector-select.
  2457. bool InvariantCond = SE->isLoopInvariant(SE->getSCEV(it->getOperand(0)),
  2458. OrigLoop);
  2459. setDebugLocFromInst(Builder, it);
  2460. // The condition can be loop invariant but still defined inside the
  2461. // loop. This means that we can't just use the original 'cond' value.
  2462. // We have to take the 'vectorized' value and pick the first lane.
  2463. // Instcombine will make this a no-op.
  2464. VectorParts &Cond = getVectorValue(it->getOperand(0));
  2465. VectorParts &Op0 = getVectorValue(it->getOperand(1));
  2466. VectorParts &Op1 = getVectorValue(it->getOperand(2));
  2467. Value *ScalarCond = (VF == 1) ? Cond[0] :
  2468. Builder.CreateExtractElement(Cond[0], Builder.getInt32(0));
  2469. for (unsigned Part = 0; Part < UF; ++Part) {
  2470. Entry[Part] = Builder.CreateSelect(
  2471. InvariantCond ? ScalarCond : Cond[Part],
  2472. Op0[Part],
  2473. Op1[Part]);
  2474. }
  2475. break;
  2476. }
  2477. case Instruction::ICmp:
  2478. case Instruction::FCmp: {
  2479. // Widen compares. Generate vector compares.
  2480. bool FCmp = (it->getOpcode() == Instruction::FCmp);
  2481. CmpInst *Cmp = dyn_cast<CmpInst>(it);
  2482. setDebugLocFromInst(Builder, it);
  2483. VectorParts &A = getVectorValue(it->getOperand(0));
  2484. VectorParts &B = getVectorValue(it->getOperand(1));
  2485. for (unsigned Part = 0; Part < UF; ++Part) {
  2486. Value *C = 0;
  2487. if (FCmp)
  2488. C = Builder.CreateFCmp(Cmp->getPredicate(), A[Part], B[Part]);
  2489. else
  2490. C = Builder.CreateICmp(Cmp->getPredicate(), A[Part], B[Part]);
  2491. Entry[Part] = C;
  2492. }
  2493. break;
  2494. }
  2495. case Instruction::Store:
  2496. case Instruction::Load:
  2497. vectorizeMemoryInstruction(it);
  2498. break;
  2499. case Instruction::ZExt:
  2500. case Instruction::SExt:
  2501. case Instruction::FPToUI:
  2502. case Instruction::FPToSI:
  2503. case Instruction::FPExt:
  2504. case Instruction::PtrToInt:
  2505. case Instruction::IntToPtr:
  2506. case Instruction::SIToFP:
  2507. case Instruction::UIToFP:
  2508. case Instruction::Trunc:
  2509. case Instruction::FPTrunc:
  2510. case Instruction::BitCast: {
  2511. CastInst *CI = dyn_cast<CastInst>(it);
  2512. setDebugLocFromInst(Builder, it);
  2513. /// Optimize the special case where the source is the induction
  2514. /// variable. Notice that we can only optimize the 'trunc' case
  2515. /// because: a. FP conversions lose precision, b. sext/zext may wrap,
  2516. /// c. other casts depend on pointer size.
  2517. if (CI->getOperand(0) == OldInduction &&
  2518. it->getOpcode() == Instruction::Trunc) {
  2519. Value *ScalarCast = Builder.CreateCast(CI->getOpcode(), Induction,
  2520. CI->getType());
  2521. Value *Broadcasted = getBroadcastInstrs(ScalarCast);
  2522. for (unsigned Part = 0; Part < UF; ++Part)
  2523. Entry[Part] = getConsecutiveVector(Broadcasted, VF * Part, false);
  2524. break;
  2525. }
  2526. /// Vectorize casts.
  2527. Type *DestTy = (VF == 1) ? CI->getType() :
  2528. VectorType::get(CI->getType(), VF);
  2529. VectorParts &A = getVectorValue(it->getOperand(0));
  2530. for (unsigned Part = 0; Part < UF; ++Part)
  2531. Entry[Part] = Builder.CreateCast(CI->getOpcode(), A[Part], DestTy);
  2532. break;
  2533. }
  2534. case Instruction::Call: {
  2535. // Ignore dbg intrinsics.
  2536. if (isa<DbgInfoIntrinsic>(it))
  2537. break;
  2538. setDebugLocFromInst(Builder, it);
  2539. Module *M = BB->getParent()->getParent();
  2540. CallInst *CI = cast<CallInst>(it);
  2541. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  2542. assert(ID && "Not an intrinsic call!");
  2543. switch (ID) {
  2544. case Intrinsic::lifetime_end:
  2545. case Intrinsic::lifetime_start:
  2546. scalarizeInstruction(it);
  2547. break;
  2548. default:
  2549. for (unsigned Part = 0; Part < UF; ++Part) {
  2550. SmallVector<Value *, 4> Args;
  2551. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  2552. VectorParts &Arg = getVectorValue(CI->getArgOperand(i));
  2553. Args.push_back(Arg[Part]);
  2554. }
  2555. Type *Tys[] = {CI->getType()};
  2556. if (VF > 1)
  2557. Tys[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  2558. Function *F = Intrinsic::getDeclaration(M, ID, Tys);
  2559. Entry[Part] = Builder.CreateCall(F, Args);
  2560. }
  2561. break;
  2562. }
  2563. break;
  2564. }
  2565. default:
  2566. // All other instructions are unsupported. Scalarize them.
  2567. scalarizeInstruction(it);
  2568. break;
  2569. }// end of switch.
  2570. }// end of for_each instr.
  2571. }
  2572. void InnerLoopVectorizer::updateAnalysis() {
  2573. // Forget the original basic block.
  2574. SE->forgetLoop(OrigLoop);
  2575. // Update the dominator tree information.
  2576. assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
  2577. "Entry does not dominate exit.");
  2578. for (unsigned I = 1, E = LoopBypassBlocks.size(); I != E; ++I)
  2579. DT->addNewBlock(LoopBypassBlocks[I], LoopBypassBlocks[I-1]);
  2580. DT->addNewBlock(LoopVectorPreHeader, LoopBypassBlocks.back());
  2581. DT->addNewBlock(LoopVectorBody, LoopVectorPreHeader);
  2582. DT->addNewBlock(LoopMiddleBlock, LoopBypassBlocks.front());
  2583. DT->addNewBlock(LoopScalarPreHeader, LoopMiddleBlock);
  2584. DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
  2585. DT->changeImmediateDominator(LoopExitBlock, LoopMiddleBlock);
  2586. DEBUG(DT->verifyDomTree());
  2587. }
  2588. /// \brief Check whether it is safe to if-convert this phi node.
  2589. ///
  2590. /// Phi nodes with constant expressions that can trap are not safe to if
  2591. /// convert.
  2592. static bool canIfConvertPHINodes(BasicBlock *BB) {
  2593. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  2594. PHINode *Phi = dyn_cast<PHINode>(I);
  2595. if (!Phi)
  2596. return true;
  2597. for (unsigned p = 0, e = Phi->getNumIncomingValues(); p != e; ++p)
  2598. if (Constant *C = dyn_cast<Constant>(Phi->getIncomingValue(p)))
  2599. if (C->canTrap())
  2600. return false;
  2601. }
  2602. return true;
  2603. }
  2604. bool LoopVectorizationLegality::canVectorizeWithIfConvert() {
  2605. if (!EnableIfConversion)
  2606. return false;
  2607. assert(TheLoop->getNumBlocks() > 1 && "Single block loops are vectorizable");
  2608. // A list of pointers that we can safely read and write to.
  2609. SmallPtrSet<Value *, 8> SafePointes;
  2610. // Collect safe addresses.
  2611. for (Loop::block_iterator BI = TheLoop->block_begin(),
  2612. BE = TheLoop->block_end(); BI != BE; ++BI) {
  2613. BasicBlock *BB = *BI;
  2614. if (blockNeedsPredication(BB))
  2615. continue;
  2616. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ++I) {
  2617. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  2618. SafePointes.insert(LI->getPointerOperand());
  2619. else if (StoreInst *SI = dyn_cast<StoreInst>(I))
  2620. SafePointes.insert(SI->getPointerOperand());
  2621. }
  2622. }
  2623. // Collect the blocks that need predication.
  2624. BasicBlock *Header = TheLoop->getHeader();
  2625. for (Loop::block_iterator BI = TheLoop->block_begin(),
  2626. BE = TheLoop->block_end(); BI != BE; ++BI) {
  2627. BasicBlock *BB = *BI;
  2628. // We don't support switch statements inside loops.
  2629. if (!isa<BranchInst>(BB->getTerminator()))
  2630. return false;
  2631. // We must be able to predicate all blocks that need to be predicated.
  2632. if (blockNeedsPredication(BB)) {
  2633. if (!blockCanBePredicated(BB, SafePointes))
  2634. return false;
  2635. } else if (BB != Header && !canIfConvertPHINodes(BB))
  2636. return false;
  2637. }
  2638. // We can if-convert this loop.
  2639. return true;
  2640. }
  2641. bool LoopVectorizationLegality::canVectorize() {
  2642. // We must have a loop in canonical form. Loops with indirectbr in them cannot
  2643. // be canonicalized.
  2644. if (!TheLoop->getLoopPreheader())
  2645. return false;
  2646. // We can only vectorize innermost loops.
  2647. if (TheLoop->getSubLoopsVector().size())
  2648. return false;
  2649. // We must have a single backedge.
  2650. if (TheLoop->getNumBackEdges() != 1)
  2651. return false;
  2652. // We must have a single exiting block.
  2653. if (!TheLoop->getExitingBlock())
  2654. return false;
  2655. // We need to have a loop header.
  2656. DEBUG(dbgs() << "LV: Found a loop: " <<
  2657. TheLoop->getHeader()->getName() << '\n');
  2658. // Check if we can if-convert non-single-bb loops.
  2659. unsigned NumBlocks = TheLoop->getNumBlocks();
  2660. if (NumBlocks != 1 && !canVectorizeWithIfConvert()) {
  2661. DEBUG(dbgs() << "LV: Can't if-convert the loop.\n");
  2662. return false;
  2663. }
  2664. // ScalarEvolution needs to be able to find the exit count.
  2665. const SCEV *ExitCount = SE->getBackedgeTakenCount(TheLoop);
  2666. if (ExitCount == SE->getCouldNotCompute()) {
  2667. DEBUG(dbgs() << "LV: SCEV could not compute the loop exit count.\n");
  2668. return false;
  2669. }
  2670. // Do not loop-vectorize loops with a tiny trip count.
  2671. BasicBlock *Latch = TheLoop->getLoopLatch();
  2672. unsigned TC = SE->getSmallConstantTripCount(TheLoop, Latch);
  2673. if (TC > 0u && TC < TinyTripCountVectorThreshold) {
  2674. DEBUG(dbgs() << "LV: Found a loop with a very small trip count. " <<
  2675. "This loop is not worth vectorizing.\n");
  2676. return false;
  2677. }
  2678. // Check if we can vectorize the instructions and CFG in this loop.
  2679. if (!canVectorizeInstrs()) {
  2680. DEBUG(dbgs() << "LV: Can't vectorize the instructions or CFG\n");
  2681. return false;
  2682. }
  2683. // Go over each instruction and look at memory deps.
  2684. if (!canVectorizeMemory()) {
  2685. DEBUG(dbgs() << "LV: Can't vectorize due to memory conflicts\n");
  2686. return false;
  2687. }
  2688. // Collect all of the variables that remain uniform after vectorization.
  2689. collectLoopUniforms();
  2690. DEBUG(dbgs() << "LV: We can vectorize this loop" <<
  2691. (PtrRtCheck.Need ? " (with a runtime bound check)" : "")
  2692. <<"!\n");
  2693. // Okay! We can vectorize. At this point we don't have any other mem analysis
  2694. // which may limit our maximum vectorization factor, so just return true with
  2695. // no restrictions.
  2696. return true;
  2697. }
  2698. static Type *convertPointerToIntegerType(DataLayout &DL, Type *Ty) {
  2699. if (Ty->isPointerTy())
  2700. return DL.getIntPtrType(Ty);
  2701. // It is possible that char's or short's overflow when we ask for the loop's
  2702. // trip count, work around this by changing the type size.
  2703. if (Ty->getScalarSizeInBits() < 32)
  2704. return Type::getInt32Ty(Ty->getContext());
  2705. return Ty;
  2706. }
  2707. static Type* getWiderType(DataLayout &DL, Type *Ty0, Type *Ty1) {
  2708. Ty0 = convertPointerToIntegerType(DL, Ty0);
  2709. Ty1 = convertPointerToIntegerType(DL, Ty1);
  2710. if (Ty0->getScalarSizeInBits() > Ty1->getScalarSizeInBits())
  2711. return Ty0;
  2712. return Ty1;
  2713. }
  2714. /// \brief Check that the instruction has outside loop users and is not an
  2715. /// identified reduction variable.
  2716. static bool hasOutsideLoopUser(const Loop *TheLoop, Instruction *Inst,
  2717. SmallPtrSet<Value *, 4> &Reductions) {
  2718. // Reduction instructions are allowed to have exit users. All other
  2719. // instructions must not have external users.
  2720. if (!Reductions.count(Inst))
  2721. //Check that all of the users of the loop are inside the BB.
  2722. for (Value::use_iterator I = Inst->use_begin(), E = Inst->use_end();
  2723. I != E; ++I) {
  2724. Instruction *U = cast<Instruction>(*I);
  2725. // This user may be a reduction exit value.
  2726. if (!TheLoop->contains(U)) {
  2727. DEBUG(dbgs() << "LV: Found an outside user for : " << *U << '\n');
  2728. return true;
  2729. }
  2730. }
  2731. return false;
  2732. }
  2733. bool LoopVectorizationLegality::canVectorizeInstrs() {
  2734. BasicBlock *PreHeader = TheLoop->getLoopPreheader();
  2735. BasicBlock *Header = TheLoop->getHeader();
  2736. // Look for the attribute signaling the absence of NaNs.
  2737. Function &F = *Header->getParent();
  2738. if (F.hasFnAttribute("no-nans-fp-math"))
  2739. HasFunNoNaNAttr = F.getAttributes().getAttribute(
  2740. AttributeSet::FunctionIndex,
  2741. "no-nans-fp-math").getValueAsString() == "true";
  2742. // For each block in the loop.
  2743. for (Loop::block_iterator bb = TheLoop->block_begin(),
  2744. be = TheLoop->block_end(); bb != be; ++bb) {
  2745. // Scan the instructions in the block and look for hazards.
  2746. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  2747. ++it) {
  2748. if (PHINode *Phi = dyn_cast<PHINode>(it)) {
  2749. Type *PhiTy = Phi->getType();
  2750. // Check that this PHI type is allowed.
  2751. if (!PhiTy->isIntegerTy() &&
  2752. !PhiTy->isFloatingPointTy() &&
  2753. !PhiTy->isPointerTy()) {
  2754. DEBUG(dbgs() << "LV: Found an non-int non-pointer PHI.\n");
  2755. return false;
  2756. }
  2757. // If this PHINode is not in the header block, then we know that we
  2758. // can convert it to select during if-conversion. No need to check if
  2759. // the PHIs in this block are induction or reduction variables.
  2760. if (*bb != Header) {
  2761. // Check that this instruction has no outside users or is an
  2762. // identified reduction value with an outside user.
  2763. if(!hasOutsideLoopUser(TheLoop, it, AllowedExit))
  2764. continue;
  2765. return false;
  2766. }
  2767. // We only allow if-converted PHIs with more than two incoming values.
  2768. if (Phi->getNumIncomingValues() != 2) {
  2769. DEBUG(dbgs() << "LV: Found an invalid PHI.\n");
  2770. return false;
  2771. }
  2772. // This is the value coming from the preheader.
  2773. Value *StartValue = Phi->getIncomingValueForBlock(PreHeader);
  2774. // Check if this is an induction variable.
  2775. InductionKind IK = isInductionVariable(Phi);
  2776. if (IK_NoInduction != IK) {
  2777. // Get the widest type.
  2778. if (!WidestIndTy)
  2779. WidestIndTy = convertPointerToIntegerType(*DL, PhiTy);
  2780. else
  2781. WidestIndTy = getWiderType(*DL, PhiTy, WidestIndTy);
  2782. // Int inductions are special because we only allow one IV.
  2783. if (IK == IK_IntInduction) {
  2784. // Use the phi node with the widest type as induction. Use the last
  2785. // one if there are multiple (no good reason for doing this other
  2786. // than it is expedient).
  2787. if (!Induction || PhiTy == WidestIndTy)
  2788. Induction = Phi;
  2789. }
  2790. DEBUG(dbgs() << "LV: Found an induction variable.\n");
  2791. Inductions[Phi] = InductionInfo(StartValue, IK);
  2792. // Until we explicitly handle the case of an induction variable with
  2793. // an outside loop user we have to give up vectorizing this loop.
  2794. if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
  2795. return false;
  2796. continue;
  2797. }
  2798. if (AddReductionVar(Phi, RK_IntegerAdd)) {
  2799. DEBUG(dbgs() << "LV: Found an ADD reduction PHI."<< *Phi <<"\n");
  2800. continue;
  2801. }
  2802. if (AddReductionVar(Phi, RK_IntegerMult)) {
  2803. DEBUG(dbgs() << "LV: Found a MUL reduction PHI."<< *Phi <<"\n");
  2804. continue;
  2805. }
  2806. if (AddReductionVar(Phi, RK_IntegerOr)) {
  2807. DEBUG(dbgs() << "LV: Found an OR reduction PHI."<< *Phi <<"\n");
  2808. continue;
  2809. }
  2810. if (AddReductionVar(Phi, RK_IntegerAnd)) {
  2811. DEBUG(dbgs() << "LV: Found an AND reduction PHI."<< *Phi <<"\n");
  2812. continue;
  2813. }
  2814. if (AddReductionVar(Phi, RK_IntegerXor)) {
  2815. DEBUG(dbgs() << "LV: Found a XOR reduction PHI."<< *Phi <<"\n");
  2816. continue;
  2817. }
  2818. if (AddReductionVar(Phi, RK_IntegerMinMax)) {
  2819. DEBUG(dbgs() << "LV: Found a MINMAX reduction PHI."<< *Phi <<"\n");
  2820. continue;
  2821. }
  2822. if (AddReductionVar(Phi, RK_FloatMult)) {
  2823. DEBUG(dbgs() << "LV: Found an FMult reduction PHI."<< *Phi <<"\n");
  2824. continue;
  2825. }
  2826. if (AddReductionVar(Phi, RK_FloatAdd)) {
  2827. DEBUG(dbgs() << "LV: Found an FAdd reduction PHI."<< *Phi <<"\n");
  2828. continue;
  2829. }
  2830. if (AddReductionVar(Phi, RK_FloatMinMax)) {
  2831. DEBUG(dbgs() << "LV: Found an float MINMAX reduction PHI."<< *Phi <<
  2832. "\n");
  2833. continue;
  2834. }
  2835. DEBUG(dbgs() << "LV: Found an unidentified PHI."<< *Phi <<"\n");
  2836. return false;
  2837. }// end of PHI handling
  2838. // We still don't handle functions. However, we can ignore dbg intrinsic
  2839. // calls and we do handle certain intrinsic and libm functions.
  2840. CallInst *CI = dyn_cast<CallInst>(it);
  2841. if (CI && !getIntrinsicIDForCall(CI, TLI) && !isa<DbgInfoIntrinsic>(CI)) {
  2842. DEBUG(dbgs() << "LV: Found a call site.\n");
  2843. return false;
  2844. }
  2845. // Check that the instruction return type is vectorizable.
  2846. // Also, we can't vectorize extractelement instructions.
  2847. if ((!VectorType::isValidElementType(it->getType()) &&
  2848. !it->getType()->isVoidTy()) || isa<ExtractElementInst>(it)) {
  2849. DEBUG(dbgs() << "LV: Found unvectorizable type.\n");
  2850. return false;
  2851. }
  2852. // Check that the stored type is vectorizable.
  2853. if (StoreInst *ST = dyn_cast<StoreInst>(it)) {
  2854. Type *T = ST->getValueOperand()->getType();
  2855. if (!VectorType::isValidElementType(T))
  2856. return false;
  2857. if (EnableMemAccessVersioning)
  2858. collectStridedAcccess(ST);
  2859. }
  2860. if (EnableMemAccessVersioning)
  2861. if (LoadInst *LI = dyn_cast<LoadInst>(it))
  2862. collectStridedAcccess(LI);
  2863. // Reduction instructions are allowed to have exit users.
  2864. // All other instructions must not have external users.
  2865. if (hasOutsideLoopUser(TheLoop, it, AllowedExit))
  2866. return false;
  2867. } // next instr.
  2868. }
  2869. if (!Induction) {
  2870. DEBUG(dbgs() << "LV: Did not find one integer induction var.\n");
  2871. if (Inductions.empty())
  2872. return false;
  2873. }
  2874. return true;
  2875. }
  2876. ///\brief Remove GEPs whose indices but the last one are loop invariant and
  2877. /// return the induction operand of the gep pointer.
  2878. static Value *stripGetElementPtr(Value *Ptr, ScalarEvolution *SE,
  2879. DataLayout *DL, Loop *Lp) {
  2880. GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr);
  2881. if (!GEP)
  2882. return Ptr;
  2883. unsigned InductionOperand = getGEPInductionOperand(DL, GEP);
  2884. // Check that all of the gep indices are uniform except for our induction
  2885. // operand.
  2886. for (unsigned i = 0, e = GEP->getNumOperands(); i != e; ++i)
  2887. if (i != InductionOperand &&
  2888. !SE->isLoopInvariant(SE->getSCEV(GEP->getOperand(i)), Lp))
  2889. return Ptr;
  2890. return GEP->getOperand(InductionOperand);
  2891. }
  2892. ///\brief Look for a cast use of the passed value.
  2893. static Value *getUniqueCastUse(Value *Ptr, Loop *Lp, Type *Ty) {
  2894. Value *UniqueCast = 0;
  2895. for (Value::use_iterator UI = Ptr->use_begin(), UE = Ptr->use_end(); UI != UE;
  2896. ++UI) {
  2897. CastInst *CI = dyn_cast<CastInst>(*UI);
  2898. if (CI && CI->getType() == Ty) {
  2899. if (!UniqueCast)
  2900. UniqueCast = CI;
  2901. else
  2902. return 0;
  2903. }
  2904. }
  2905. return UniqueCast;
  2906. }
  2907. ///\brief Get the stride of a pointer access in a loop.
  2908. /// Looks for symbolic strides "a[i*stride]". Returns the symbolic stride as a
  2909. /// pointer to the Value, or null otherwise.
  2910. static Value *getStrideFromPointer(Value *Ptr, ScalarEvolution *SE,
  2911. DataLayout *DL, Loop *Lp) {
  2912. const PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  2913. if (!PtrTy || PtrTy->isAggregateType())
  2914. return 0;
  2915. // Try to remove a gep instruction to make the pointer (actually index at this
  2916. // point) easier analyzable. If OrigPtr is equal to Ptr we are analzying the
  2917. // pointer, otherwise, we are analyzing the index.
  2918. Value *OrigPtr = Ptr;
  2919. // The size of the pointer access.
  2920. int64_t PtrAccessSize = 1;
  2921. Ptr = stripGetElementPtr(Ptr, SE, DL, Lp);
  2922. const SCEV *V = SE->getSCEV(Ptr);
  2923. if (Ptr != OrigPtr)
  2924. // Strip off casts.
  2925. while (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V))
  2926. V = C->getOperand();
  2927. const SCEVAddRecExpr *S = dyn_cast<SCEVAddRecExpr>(V);
  2928. if (!S)
  2929. return 0;
  2930. V = S->getStepRecurrence(*SE);
  2931. if (!V)
  2932. return 0;
  2933. // Strip off the size of access multiplication if we are still analyzing the
  2934. // pointer.
  2935. if (OrigPtr == Ptr) {
  2936. DL->getTypeAllocSize(PtrTy->getElementType());
  2937. if (const SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(V)) {
  2938. if (M->getOperand(0)->getSCEVType() != scConstant)
  2939. return 0;
  2940. const APInt &APStepVal =
  2941. cast<SCEVConstant>(M->getOperand(0))->getValue()->getValue();
  2942. // Huge step value - give up.
  2943. if (APStepVal.getBitWidth() > 64)
  2944. return 0;
  2945. int64_t StepVal = APStepVal.getSExtValue();
  2946. if (PtrAccessSize != StepVal)
  2947. return 0;
  2948. V = M->getOperand(1);
  2949. }
  2950. }
  2951. // Strip off casts.
  2952. Type *StripedOffRecurrenceCast = 0;
  2953. if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(V)) {
  2954. StripedOffRecurrenceCast = C->getType();
  2955. V = C->getOperand();
  2956. }
  2957. // Look for the loop invariant symbolic value.
  2958. const SCEVUnknown *U = dyn_cast<SCEVUnknown>(V);
  2959. if (!U)
  2960. return 0;
  2961. Value *Stride = U->getValue();
  2962. if (!Lp->isLoopInvariant(Stride))
  2963. return 0;
  2964. // If we have stripped off the recurrence cast we have to make sure that we
  2965. // return the value that is used in this loop so that we can replace it later.
  2966. if (StripedOffRecurrenceCast)
  2967. Stride = getUniqueCastUse(Stride, Lp, StripedOffRecurrenceCast);
  2968. return Stride;
  2969. }
  2970. void LoopVectorizationLegality::collectStridedAcccess(Value *MemAccess) {
  2971. Value *Ptr = 0;
  2972. if (LoadInst *LI = dyn_cast<LoadInst>(MemAccess))
  2973. Ptr = LI->getPointerOperand();
  2974. else if (StoreInst *SI = dyn_cast<StoreInst>(MemAccess))
  2975. Ptr = SI->getPointerOperand();
  2976. else
  2977. return;
  2978. Value *Stride = getStrideFromPointer(Ptr, SE, DL, TheLoop);
  2979. if (!Stride)
  2980. return;
  2981. DEBUG(dbgs() << "LV: Found a strided access that we can version");
  2982. DEBUG(dbgs() << " Ptr: " << *Ptr << " Stride: " << *Stride << "\n");
  2983. Strides[Ptr] = Stride;
  2984. StrideSet.insert(Stride);
  2985. }
  2986. void LoopVectorizationLegality::collectLoopUniforms() {
  2987. // We now know that the loop is vectorizable!
  2988. // Collect variables that will remain uniform after vectorization.
  2989. std::vector<Value*> Worklist;
  2990. BasicBlock *Latch = TheLoop->getLoopLatch();
  2991. // Start with the conditional branch and walk up the block.
  2992. Worklist.push_back(Latch->getTerminator()->getOperand(0));
  2993. while (Worklist.size()) {
  2994. Instruction *I = dyn_cast<Instruction>(Worklist.back());
  2995. Worklist.pop_back();
  2996. // Look at instructions inside this loop.
  2997. // Stop when reaching PHI nodes.
  2998. // TODO: we need to follow values all over the loop, not only in this block.
  2999. if (!I || !TheLoop->contains(I) || isa<PHINode>(I))
  3000. continue;
  3001. // This is a known uniform.
  3002. Uniforms.insert(I);
  3003. // Insert all operands.
  3004. Worklist.insert(Worklist.end(), I->op_begin(), I->op_end());
  3005. }
  3006. }
  3007. namespace {
  3008. /// \brief Analyses memory accesses in a loop.
  3009. ///
  3010. /// Checks whether run time pointer checks are needed and builds sets for data
  3011. /// dependence checking.
  3012. class AccessAnalysis {
  3013. public:
  3014. /// \brief Read or write access location.
  3015. typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
  3016. typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
  3017. /// \brief Set of potential dependent memory accesses.
  3018. typedef EquivalenceClasses<MemAccessInfo> DepCandidates;
  3019. AccessAnalysis(DataLayout *Dl, DepCandidates &DA) :
  3020. DL(Dl), DepCands(DA), AreAllWritesIdentified(true),
  3021. AreAllReadsIdentified(true), IsRTCheckNeeded(false) {}
  3022. /// \brief Register a load and whether it is only read from.
  3023. void addLoad(Value *Ptr, bool IsReadOnly) {
  3024. Accesses.insert(MemAccessInfo(Ptr, false));
  3025. if (IsReadOnly)
  3026. ReadOnlyPtr.insert(Ptr);
  3027. }
  3028. /// \brief Register a store.
  3029. void addStore(Value *Ptr) {
  3030. Accesses.insert(MemAccessInfo(Ptr, true));
  3031. }
  3032. /// \brief Check whether we can check the pointers at runtime for
  3033. /// non-intersection.
  3034. bool canCheckPtrAtRT(LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
  3035. unsigned &NumComparisons, ScalarEvolution *SE,
  3036. Loop *TheLoop, ValueToValueMap &Strides,
  3037. bool ShouldCheckStride = false);
  3038. /// \brief Goes over all memory accesses, checks whether a RT check is needed
  3039. /// and builds sets of dependent accesses.
  3040. void buildDependenceSets() {
  3041. // Process read-write pointers first.
  3042. processMemAccesses(false);
  3043. // Next, process read pointers.
  3044. processMemAccesses(true);
  3045. }
  3046. bool isRTCheckNeeded() { return IsRTCheckNeeded; }
  3047. bool isDependencyCheckNeeded() { return !CheckDeps.empty(); }
  3048. void resetDepChecks() { CheckDeps.clear(); }
  3049. MemAccessInfoSet &getDependenciesToCheck() { return CheckDeps; }
  3050. private:
  3051. typedef SetVector<MemAccessInfo> PtrAccessSet;
  3052. typedef DenseMap<Value*, MemAccessInfo> UnderlyingObjToAccessMap;
  3053. /// \brief Go over all memory access or only the deferred ones if
  3054. /// \p UseDeferred is true and check whether runtime pointer checks are needed
  3055. /// and build sets of dependency check candidates.
  3056. void processMemAccesses(bool UseDeferred);
  3057. /// Set of all accesses.
  3058. PtrAccessSet Accesses;
  3059. /// Set of access to check after all writes have been processed.
  3060. PtrAccessSet DeferredAccesses;
  3061. /// Map of pointers to last access encountered.
  3062. UnderlyingObjToAccessMap ObjToLastAccess;
  3063. /// Set of accesses that need a further dependence check.
  3064. MemAccessInfoSet CheckDeps;
  3065. /// Set of pointers that are read only.
  3066. SmallPtrSet<Value*, 16> ReadOnlyPtr;
  3067. /// Set of underlying objects already written to.
  3068. SmallPtrSet<Value*, 16> WriteObjects;
  3069. DataLayout *DL;
  3070. /// Sets of potentially dependent accesses - members of one set share an
  3071. /// underlying pointer. The set "CheckDeps" identfies which sets really need a
  3072. /// dependence check.
  3073. DepCandidates &DepCands;
  3074. bool AreAllWritesIdentified;
  3075. bool AreAllReadsIdentified;
  3076. bool IsRTCheckNeeded;
  3077. };
  3078. } // end anonymous namespace
  3079. /// \brief Check whether a pointer can participate in a runtime bounds check.
  3080. static bool hasComputableBounds(ScalarEvolution *SE, ValueToValueMap &Strides,
  3081. Value *Ptr) {
  3082. const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, Strides, Ptr);
  3083. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
  3084. if (!AR)
  3085. return false;
  3086. return AR->isAffine();
  3087. }
  3088. /// \brief Check the stride of the pointer and ensure that it does not wrap in
  3089. /// the address space.
  3090. static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
  3091. const Loop *Lp, ValueToValueMap &StridesMap);
  3092. bool AccessAnalysis::canCheckPtrAtRT(
  3093. LoopVectorizationLegality::RuntimePointerCheck &RtCheck,
  3094. unsigned &NumComparisons, ScalarEvolution *SE, Loop *TheLoop,
  3095. ValueToValueMap &StridesMap, bool ShouldCheckStride) {
  3096. // Find pointers with computable bounds. We are going to use this information
  3097. // to place a runtime bound check.
  3098. unsigned NumReadPtrChecks = 0;
  3099. unsigned NumWritePtrChecks = 0;
  3100. bool CanDoRT = true;
  3101. bool IsDepCheckNeeded = isDependencyCheckNeeded();
  3102. // We assign consecutive id to access from different dependence sets.
  3103. // Accesses within the same set don't need a runtime check.
  3104. unsigned RunningDepId = 1;
  3105. DenseMap<Value *, unsigned> DepSetId;
  3106. for (PtrAccessSet::iterator AI = Accesses.begin(), AE = Accesses.end();
  3107. AI != AE; ++AI) {
  3108. const MemAccessInfo &Access = *AI;
  3109. Value *Ptr = Access.getPointer();
  3110. bool IsWrite = Access.getInt();
  3111. // Just add write checks if we have both.
  3112. if (!IsWrite && Accesses.count(MemAccessInfo(Ptr, true)))
  3113. continue;
  3114. if (IsWrite)
  3115. ++NumWritePtrChecks;
  3116. else
  3117. ++NumReadPtrChecks;
  3118. if (hasComputableBounds(SE, StridesMap, Ptr) &&
  3119. // When we run after a failing dependency check we have to make sure we
  3120. // don't have wrapping pointers.
  3121. (!ShouldCheckStride ||
  3122. isStridedPtr(SE, DL, Ptr, TheLoop, StridesMap) == 1)) {
  3123. // The id of the dependence set.
  3124. unsigned DepId;
  3125. if (IsDepCheckNeeded) {
  3126. Value *Leader = DepCands.getLeaderValue(Access).getPointer();
  3127. unsigned &LeaderId = DepSetId[Leader];
  3128. if (!LeaderId)
  3129. LeaderId = RunningDepId++;
  3130. DepId = LeaderId;
  3131. } else
  3132. // Each access has its own dependence set.
  3133. DepId = RunningDepId++;
  3134. RtCheck.insert(SE, TheLoop, Ptr, IsWrite, DepId, StridesMap);
  3135. DEBUG(dbgs() << "LV: Found a runtime check ptr:" << *Ptr << '\n');
  3136. } else {
  3137. CanDoRT = false;
  3138. }
  3139. }
  3140. if (IsDepCheckNeeded && CanDoRT && RunningDepId == 2)
  3141. NumComparisons = 0; // Only one dependence set.
  3142. else {
  3143. NumComparisons = (NumWritePtrChecks * (NumReadPtrChecks +
  3144. NumWritePtrChecks - 1));
  3145. }
  3146. // If the pointers that we would use for the bounds comparison have different
  3147. // address spaces, assume the values aren't directly comparable, so we can't
  3148. // use them for the runtime check. We also have to assume they could
  3149. // overlap. In the future there should be metadata for whether address spaces
  3150. // are disjoint.
  3151. unsigned NumPointers = RtCheck.Pointers.size();
  3152. for (unsigned i = 0; i < NumPointers; ++i) {
  3153. for (unsigned j = i + 1; j < NumPointers; ++j) {
  3154. // Only need to check pointers between two different dependency sets.
  3155. if (RtCheck.DependencySetId[i] == RtCheck.DependencySetId[j])
  3156. continue;
  3157. Value *PtrI = RtCheck.Pointers[i];
  3158. Value *PtrJ = RtCheck.Pointers[j];
  3159. unsigned ASi = PtrI->getType()->getPointerAddressSpace();
  3160. unsigned ASj = PtrJ->getType()->getPointerAddressSpace();
  3161. if (ASi != ASj) {
  3162. DEBUG(dbgs() << "LV: Runtime check would require comparison between"
  3163. " different address spaces\n");
  3164. return false;
  3165. }
  3166. }
  3167. }
  3168. return CanDoRT;
  3169. }
  3170. static bool isFunctionScopeIdentifiedObject(Value *Ptr) {
  3171. return isNoAliasArgument(Ptr) || isNoAliasCall(Ptr) || isa<AllocaInst>(Ptr);
  3172. }
  3173. void AccessAnalysis::processMemAccesses(bool UseDeferred) {
  3174. // We process the set twice: first we process read-write pointers, last we
  3175. // process read-only pointers. This allows us to skip dependence tests for
  3176. // read-only pointers.
  3177. PtrAccessSet &S = UseDeferred ? DeferredAccesses : Accesses;
  3178. for (PtrAccessSet::iterator AI = S.begin(), AE = S.end(); AI != AE; ++AI) {
  3179. const MemAccessInfo &Access = *AI;
  3180. Value *Ptr = Access.getPointer();
  3181. bool IsWrite = Access.getInt();
  3182. DepCands.insert(Access);
  3183. // Memorize read-only pointers for later processing and skip them in the
  3184. // first round (they need to be checked after we have seen all write
  3185. // pointers). Note: we also mark pointer that are not consecutive as
  3186. // "read-only" pointers (so that we check "a[b[i]] +="). Hence, we need the
  3187. // second check for "!IsWrite".
  3188. bool IsReadOnlyPtr = ReadOnlyPtr.count(Ptr) && !IsWrite;
  3189. if (!UseDeferred && IsReadOnlyPtr) {
  3190. DeferredAccesses.insert(Access);
  3191. continue;
  3192. }
  3193. bool NeedDepCheck = false;
  3194. // Check whether there is the possibility of dependency because of
  3195. // underlying objects being the same.
  3196. typedef SmallVector<Value*, 16> ValueVector;
  3197. ValueVector TempObjects;
  3198. GetUnderlyingObjects(Ptr, TempObjects, DL);
  3199. for (ValueVector::iterator UI = TempObjects.begin(), UE = TempObjects.end();
  3200. UI != UE; ++UI) {
  3201. Value *UnderlyingObj = *UI;
  3202. // If this is a write then it needs to be an identified object. If this a
  3203. // read and all writes (so far) are identified function scope objects we
  3204. // don't need an identified underlying object but only an Argument (the
  3205. // next write is going to invalidate this assumption if it is
  3206. // unidentified).
  3207. // This is a micro-optimization for the case where all writes are
  3208. // identified and we have one argument pointer.
  3209. // Otherwise, we do need a runtime check.
  3210. if ((IsWrite && !isFunctionScopeIdentifiedObject(UnderlyingObj)) ||
  3211. (!IsWrite && (!AreAllWritesIdentified ||
  3212. !isa<Argument>(UnderlyingObj)) &&
  3213. !isIdentifiedObject(UnderlyingObj))) {
  3214. DEBUG(dbgs() << "LV: Found an unidentified " <<
  3215. (IsWrite ? "write" : "read" ) << " ptr: " << *UnderlyingObj <<
  3216. "\n");
  3217. IsRTCheckNeeded = (IsRTCheckNeeded ||
  3218. !isIdentifiedObject(UnderlyingObj) ||
  3219. !AreAllReadsIdentified);
  3220. if (IsWrite)
  3221. AreAllWritesIdentified = false;
  3222. if (!IsWrite)
  3223. AreAllReadsIdentified = false;
  3224. }
  3225. // If this is a write - check other reads and writes for conflicts. If
  3226. // this is a read only check other writes for conflicts (but only if there
  3227. // is no other write to the ptr - this is an optimization to catch "a[i] =
  3228. // a[i] + " without having to do a dependence check).
  3229. if ((IsWrite || IsReadOnlyPtr) && WriteObjects.count(UnderlyingObj))
  3230. NeedDepCheck = true;
  3231. if (IsWrite)
  3232. WriteObjects.insert(UnderlyingObj);
  3233. // Create sets of pointers connected by shared underlying objects.
  3234. UnderlyingObjToAccessMap::iterator Prev =
  3235. ObjToLastAccess.find(UnderlyingObj);
  3236. if (Prev != ObjToLastAccess.end())
  3237. DepCands.unionSets(Access, Prev->second);
  3238. ObjToLastAccess[UnderlyingObj] = Access;
  3239. }
  3240. if (NeedDepCheck)
  3241. CheckDeps.insert(Access);
  3242. }
  3243. }
  3244. namespace {
  3245. /// \brief Checks memory dependences among accesses to the same underlying
  3246. /// object to determine whether there vectorization is legal or not (and at
  3247. /// which vectorization factor).
  3248. ///
  3249. /// This class works under the assumption that we already checked that memory
  3250. /// locations with different underlying pointers are "must-not alias".
  3251. /// We use the ScalarEvolution framework to symbolically evalutate access
  3252. /// functions pairs. Since we currently don't restructure the loop we can rely
  3253. /// on the program order of memory accesses to determine their safety.
  3254. /// At the moment we will only deem accesses as safe for:
  3255. /// * A negative constant distance assuming program order.
  3256. ///
  3257. /// Safe: tmp = a[i + 1]; OR a[i + 1] = x;
  3258. /// a[i] = tmp; y = a[i];
  3259. ///
  3260. /// The latter case is safe because later checks guarantuee that there can't
  3261. /// be a cycle through a phi node (that is, we check that "x" and "y" is not
  3262. /// the same variable: a header phi can only be an induction or a reduction, a
  3263. /// reduction can't have a memory sink, an induction can't have a memory
  3264. /// source). This is important and must not be violated (or we have to
  3265. /// resort to checking for cycles through memory).
  3266. ///
  3267. /// * A positive constant distance assuming program order that is bigger
  3268. /// than the biggest memory access.
  3269. ///
  3270. /// tmp = a[i] OR b[i] = x
  3271. /// a[i+2] = tmp y = b[i+2];
  3272. ///
  3273. /// Safe distance: 2 x sizeof(a[0]), and 2 x sizeof(b[0]), respectively.
  3274. ///
  3275. /// * Zero distances and all accesses have the same size.
  3276. ///
  3277. class MemoryDepChecker {
  3278. public:
  3279. typedef PointerIntPair<Value *, 1, bool> MemAccessInfo;
  3280. typedef SmallPtrSet<MemAccessInfo, 8> MemAccessInfoSet;
  3281. MemoryDepChecker(ScalarEvolution *Se, DataLayout *Dl, const Loop *L)
  3282. : SE(Se), DL(Dl), InnermostLoop(L), AccessIdx(0),
  3283. ShouldRetryWithRuntimeCheck(false) {}
  3284. /// \brief Register the location (instructions are given increasing numbers)
  3285. /// of a write access.
  3286. void addAccess(StoreInst *SI) {
  3287. Value *Ptr = SI->getPointerOperand();
  3288. Accesses[MemAccessInfo(Ptr, true)].push_back(AccessIdx);
  3289. InstMap.push_back(SI);
  3290. ++AccessIdx;
  3291. }
  3292. /// \brief Register the location (instructions are given increasing numbers)
  3293. /// of a write access.
  3294. void addAccess(LoadInst *LI) {
  3295. Value *Ptr = LI->getPointerOperand();
  3296. Accesses[MemAccessInfo(Ptr, false)].push_back(AccessIdx);
  3297. InstMap.push_back(LI);
  3298. ++AccessIdx;
  3299. }
  3300. /// \brief Check whether the dependencies between the accesses are safe.
  3301. ///
  3302. /// Only checks sets with elements in \p CheckDeps.
  3303. bool areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
  3304. MemAccessInfoSet &CheckDeps, ValueToValueMap &Strides);
  3305. /// \brief The maximum number of bytes of a vector register we can vectorize
  3306. /// the accesses safely with.
  3307. unsigned getMaxSafeDepDistBytes() { return MaxSafeDepDistBytes; }
  3308. /// \brief In same cases when the dependency check fails we can still
  3309. /// vectorize the loop with a dynamic array access check.
  3310. bool shouldRetryWithRuntimeCheck() { return ShouldRetryWithRuntimeCheck; }
  3311. private:
  3312. ScalarEvolution *SE;
  3313. DataLayout *DL;
  3314. const Loop *InnermostLoop;
  3315. /// \brief Maps access locations (ptr, read/write) to program order.
  3316. DenseMap<MemAccessInfo, std::vector<unsigned> > Accesses;
  3317. /// \brief Memory access instructions in program order.
  3318. SmallVector<Instruction *, 16> InstMap;
  3319. /// \brief The program order index to be used for the next instruction.
  3320. unsigned AccessIdx;
  3321. // We can access this many bytes in parallel safely.
  3322. unsigned MaxSafeDepDistBytes;
  3323. /// \brief If we see a non-constant dependence distance we can still try to
  3324. /// vectorize this loop with runtime checks.
  3325. bool ShouldRetryWithRuntimeCheck;
  3326. /// \brief Check whether there is a plausible dependence between the two
  3327. /// accesses.
  3328. ///
  3329. /// Access \p A must happen before \p B in program order. The two indices
  3330. /// identify the index into the program order map.
  3331. ///
  3332. /// This function checks whether there is a plausible dependence (or the
  3333. /// absence of such can't be proved) between the two accesses. If there is a
  3334. /// plausible dependence but the dependence distance is bigger than one
  3335. /// element access it records this distance in \p MaxSafeDepDistBytes (if this
  3336. /// distance is smaller than any other distance encountered so far).
  3337. /// Otherwise, this function returns true signaling a possible dependence.
  3338. bool isDependent(const MemAccessInfo &A, unsigned AIdx,
  3339. const MemAccessInfo &B, unsigned BIdx,
  3340. ValueToValueMap &Strides);
  3341. /// \brief Check whether the data dependence could prevent store-load
  3342. /// forwarding.
  3343. bool couldPreventStoreLoadForward(unsigned Distance, unsigned TypeByteSize);
  3344. };
  3345. } // end anonymous namespace
  3346. static bool isInBoundsGep(Value *Ptr) {
  3347. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
  3348. return GEP->isInBounds();
  3349. return false;
  3350. }
  3351. /// \brief Check whether the access through \p Ptr has a constant stride.
  3352. static int isStridedPtr(ScalarEvolution *SE, DataLayout *DL, Value *Ptr,
  3353. const Loop *Lp, ValueToValueMap &StridesMap) {
  3354. const Type *Ty = Ptr->getType();
  3355. assert(Ty->isPointerTy() && "Unexpected non-ptr");
  3356. // Make sure that the pointer does not point to aggregate types.
  3357. const PointerType *PtrTy = cast<PointerType>(Ty);
  3358. if (PtrTy->getElementType()->isAggregateType()) {
  3359. DEBUG(dbgs() << "LV: Bad stride - Not a pointer to a scalar type" << *Ptr <<
  3360. "\n");
  3361. return 0;
  3362. }
  3363. const SCEV *PtrScev = replaceSymbolicStrideSCEV(SE, StridesMap, Ptr);
  3364. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PtrScev);
  3365. if (!AR) {
  3366. DEBUG(dbgs() << "LV: Bad stride - Not an AddRecExpr pointer "
  3367. << *Ptr << " SCEV: " << *PtrScev << "\n");
  3368. return 0;
  3369. }
  3370. // The accesss function must stride over the innermost loop.
  3371. if (Lp != AR->getLoop()) {
  3372. DEBUG(dbgs() << "LV: Bad stride - Not striding over innermost loop " <<
  3373. *Ptr << " SCEV: " << *PtrScev << "\n");
  3374. }
  3375. // The address calculation must not wrap. Otherwise, a dependence could be
  3376. // inverted.
  3377. // An inbounds getelementptr that is a AddRec with a unit stride
  3378. // cannot wrap per definition. The unit stride requirement is checked later.
  3379. // An getelementptr without an inbounds attribute and unit stride would have
  3380. // to access the pointer value "0" which is undefined behavior in address
  3381. // space 0, therefore we can also vectorize this case.
  3382. bool IsInBoundsGEP = isInBoundsGep(Ptr);
  3383. bool IsNoWrapAddRec = AR->getNoWrapFlags(SCEV::NoWrapMask);
  3384. bool IsInAddressSpaceZero = PtrTy->getAddressSpace() == 0;
  3385. if (!IsNoWrapAddRec && !IsInBoundsGEP && !IsInAddressSpaceZero) {
  3386. DEBUG(dbgs() << "LV: Bad stride - Pointer may wrap in the address space "
  3387. << *Ptr << " SCEV: " << *PtrScev << "\n");
  3388. return 0;
  3389. }
  3390. // Check the step is constant.
  3391. const SCEV *Step = AR->getStepRecurrence(*SE);
  3392. // Calculate the pointer stride and check if it is consecutive.
  3393. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  3394. if (!C) {
  3395. DEBUG(dbgs() << "LV: Bad stride - Not a constant strided " << *Ptr <<
  3396. " SCEV: " << *PtrScev << "\n");
  3397. return 0;
  3398. }
  3399. int64_t Size = DL->getTypeAllocSize(PtrTy->getElementType());
  3400. const APInt &APStepVal = C->getValue()->getValue();
  3401. // Huge step value - give up.
  3402. if (APStepVal.getBitWidth() > 64)
  3403. return 0;
  3404. int64_t StepVal = APStepVal.getSExtValue();
  3405. // Strided access.
  3406. int64_t Stride = StepVal / Size;
  3407. int64_t Rem = StepVal % Size;
  3408. if (Rem)
  3409. return 0;
  3410. // If the SCEV could wrap but we have an inbounds gep with a unit stride we
  3411. // know we can't "wrap around the address space". In case of address space
  3412. // zero we know that this won't happen without triggering undefined behavior.
  3413. if (!IsNoWrapAddRec && (IsInBoundsGEP || IsInAddressSpaceZero) &&
  3414. Stride != 1 && Stride != -1)
  3415. return 0;
  3416. return Stride;
  3417. }
  3418. bool MemoryDepChecker::couldPreventStoreLoadForward(unsigned Distance,
  3419. unsigned TypeByteSize) {
  3420. // If loads occur at a distance that is not a multiple of a feasible vector
  3421. // factor store-load forwarding does not take place.
  3422. // Positive dependences might cause troubles because vectorizing them might
  3423. // prevent store-load forwarding making vectorized code run a lot slower.
  3424. // a[i] = a[i-3] ^ a[i-8];
  3425. // The stores to a[i:i+1] don't align with the stores to a[i-3:i-2] and
  3426. // hence on your typical architecture store-load forwarding does not take
  3427. // place. Vectorizing in such cases does not make sense.
  3428. // Store-load forwarding distance.
  3429. const unsigned NumCyclesForStoreLoadThroughMemory = 8*TypeByteSize;
  3430. // Maximum vector factor.
  3431. unsigned MaxVFWithoutSLForwardIssues = MaxVectorWidth*TypeByteSize;
  3432. if(MaxSafeDepDistBytes < MaxVFWithoutSLForwardIssues)
  3433. MaxVFWithoutSLForwardIssues = MaxSafeDepDistBytes;
  3434. for (unsigned vf = 2*TypeByteSize; vf <= MaxVFWithoutSLForwardIssues;
  3435. vf *= 2) {
  3436. if (Distance % vf && Distance / vf < NumCyclesForStoreLoadThroughMemory) {
  3437. MaxVFWithoutSLForwardIssues = (vf >>=1);
  3438. break;
  3439. }
  3440. }
  3441. if (MaxVFWithoutSLForwardIssues< 2*TypeByteSize) {
  3442. DEBUG(dbgs() << "LV: Distance " << Distance <<
  3443. " that could cause a store-load forwarding conflict\n");
  3444. return true;
  3445. }
  3446. if (MaxVFWithoutSLForwardIssues < MaxSafeDepDistBytes &&
  3447. MaxVFWithoutSLForwardIssues != MaxVectorWidth*TypeByteSize)
  3448. MaxSafeDepDistBytes = MaxVFWithoutSLForwardIssues;
  3449. return false;
  3450. }
  3451. bool MemoryDepChecker::isDependent(const MemAccessInfo &A, unsigned AIdx,
  3452. const MemAccessInfo &B, unsigned BIdx,
  3453. ValueToValueMap &Strides) {
  3454. assert (AIdx < BIdx && "Must pass arguments in program order");
  3455. Value *APtr = A.getPointer();
  3456. Value *BPtr = B.getPointer();
  3457. bool AIsWrite = A.getInt();
  3458. bool BIsWrite = B.getInt();
  3459. // Two reads are independent.
  3460. if (!AIsWrite && !BIsWrite)
  3461. return false;
  3462. const SCEV *AScev = replaceSymbolicStrideSCEV(SE, Strides, APtr);
  3463. const SCEV *BScev = replaceSymbolicStrideSCEV(SE, Strides, BPtr);
  3464. int StrideAPtr = isStridedPtr(SE, DL, APtr, InnermostLoop, Strides);
  3465. int StrideBPtr = isStridedPtr(SE, DL, BPtr, InnermostLoop, Strides);
  3466. const SCEV *Src = AScev;
  3467. const SCEV *Sink = BScev;
  3468. // If the induction step is negative we have to invert source and sink of the
  3469. // dependence.
  3470. if (StrideAPtr < 0) {
  3471. //Src = BScev;
  3472. //Sink = AScev;
  3473. std::swap(APtr, BPtr);
  3474. std::swap(Src, Sink);
  3475. std::swap(AIsWrite, BIsWrite);
  3476. std::swap(AIdx, BIdx);
  3477. std::swap(StrideAPtr, StrideBPtr);
  3478. }
  3479. const SCEV *Dist = SE->getMinusSCEV(Sink, Src);
  3480. DEBUG(dbgs() << "LV: Src Scev: " << *Src << "Sink Scev: " << *Sink
  3481. << "(Induction step: " << StrideAPtr << ")\n");
  3482. DEBUG(dbgs() << "LV: Distance for " << *InstMap[AIdx] << " to "
  3483. << *InstMap[BIdx] << ": " << *Dist << "\n");
  3484. // Need consecutive accesses. We don't want to vectorize
  3485. // "A[B[i]] += ..." and similar code or pointer arithmetic that could wrap in
  3486. // the address space.
  3487. if (!StrideAPtr || !StrideBPtr || StrideAPtr != StrideBPtr){
  3488. DEBUG(dbgs() << "Non-consecutive pointer access\n");
  3489. return true;
  3490. }
  3491. const SCEVConstant *C = dyn_cast<SCEVConstant>(Dist);
  3492. if (!C) {
  3493. DEBUG(dbgs() << "LV: Dependence because of non-constant distance\n");
  3494. ShouldRetryWithRuntimeCheck = true;
  3495. return true;
  3496. }
  3497. Type *ATy = APtr->getType()->getPointerElementType();
  3498. Type *BTy = BPtr->getType()->getPointerElementType();
  3499. unsigned TypeByteSize = DL->getTypeAllocSize(ATy);
  3500. // Negative distances are not plausible dependencies.
  3501. const APInt &Val = C->getValue()->getValue();
  3502. if (Val.isNegative()) {
  3503. bool IsTrueDataDependence = (AIsWrite && !BIsWrite);
  3504. if (IsTrueDataDependence &&
  3505. (couldPreventStoreLoadForward(Val.abs().getZExtValue(), TypeByteSize) ||
  3506. ATy != BTy))
  3507. return true;
  3508. DEBUG(dbgs() << "LV: Dependence is negative: NoDep\n");
  3509. return false;
  3510. }
  3511. // Write to the same location with the same size.
  3512. // Could be improved to assert type sizes are the same (i32 == float, etc).
  3513. if (Val == 0) {
  3514. if (ATy == BTy)
  3515. return false;
  3516. DEBUG(dbgs() << "LV: Zero dependence difference but different types\n");
  3517. return true;
  3518. }
  3519. assert(Val.isStrictlyPositive() && "Expect a positive value");
  3520. // Positive distance bigger than max vectorization factor.
  3521. if (ATy != BTy) {
  3522. DEBUG(dbgs() <<
  3523. "LV: ReadWrite-Write positive dependency with different types\n");
  3524. return false;
  3525. }
  3526. unsigned Distance = (unsigned) Val.getZExtValue();
  3527. // Bail out early if passed-in parameters make vectorization not feasible.
  3528. unsigned ForcedFactor = VectorizationFactor ? VectorizationFactor : 1;
  3529. unsigned ForcedUnroll = VectorizationUnroll ? VectorizationUnroll : 1;
  3530. // The distance must be bigger than the size needed for a vectorized version
  3531. // of the operation and the size of the vectorized operation must not be
  3532. // bigger than the currrent maximum size.
  3533. if (Distance < 2*TypeByteSize ||
  3534. 2*TypeByteSize > MaxSafeDepDistBytes ||
  3535. Distance < TypeByteSize * ForcedUnroll * ForcedFactor) {
  3536. DEBUG(dbgs() << "LV: Failure because of Positive distance "
  3537. << Val.getSExtValue() << '\n');
  3538. return true;
  3539. }
  3540. MaxSafeDepDistBytes = Distance < MaxSafeDepDistBytes ?
  3541. Distance : MaxSafeDepDistBytes;
  3542. bool IsTrueDataDependence = (!AIsWrite && BIsWrite);
  3543. if (IsTrueDataDependence &&
  3544. couldPreventStoreLoadForward(Distance, TypeByteSize))
  3545. return true;
  3546. DEBUG(dbgs() << "LV: Positive distance " << Val.getSExtValue() <<
  3547. " with max VF = " << MaxSafeDepDistBytes / TypeByteSize << '\n');
  3548. return false;
  3549. }
  3550. bool MemoryDepChecker::areDepsSafe(AccessAnalysis::DepCandidates &AccessSets,
  3551. MemAccessInfoSet &CheckDeps,
  3552. ValueToValueMap &Strides) {
  3553. MaxSafeDepDistBytes = -1U;
  3554. while (!CheckDeps.empty()) {
  3555. MemAccessInfo CurAccess = *CheckDeps.begin();
  3556. // Get the relevant memory access set.
  3557. EquivalenceClasses<MemAccessInfo>::iterator I =
  3558. AccessSets.findValue(AccessSets.getLeaderValue(CurAccess));
  3559. // Check accesses within this set.
  3560. EquivalenceClasses<MemAccessInfo>::member_iterator AI, AE;
  3561. AI = AccessSets.member_begin(I), AE = AccessSets.member_end();
  3562. // Check every access pair.
  3563. while (AI != AE) {
  3564. CheckDeps.erase(*AI);
  3565. EquivalenceClasses<MemAccessInfo>::member_iterator OI = llvm::next(AI);
  3566. while (OI != AE) {
  3567. // Check every accessing instruction pair in program order.
  3568. for (std::vector<unsigned>::iterator I1 = Accesses[*AI].begin(),
  3569. I1E = Accesses[*AI].end(); I1 != I1E; ++I1)
  3570. for (std::vector<unsigned>::iterator I2 = Accesses[*OI].begin(),
  3571. I2E = Accesses[*OI].end(); I2 != I2E; ++I2) {
  3572. if (*I1 < *I2 && isDependent(*AI, *I1, *OI, *I2, Strides))
  3573. return false;
  3574. if (*I2 < *I1 && isDependent(*OI, *I2, *AI, *I1, Strides))
  3575. return false;
  3576. }
  3577. ++OI;
  3578. }
  3579. AI++;
  3580. }
  3581. }
  3582. return true;
  3583. }
  3584. bool LoopVectorizationLegality::canVectorizeMemory() {
  3585. typedef SmallVector<Value*, 16> ValueVector;
  3586. typedef SmallPtrSet<Value*, 16> ValueSet;
  3587. // Holds the Load and Store *instructions*.
  3588. ValueVector Loads;
  3589. ValueVector Stores;
  3590. // Holds all the different accesses in the loop.
  3591. unsigned NumReads = 0;
  3592. unsigned NumReadWrites = 0;
  3593. PtrRtCheck.Pointers.clear();
  3594. PtrRtCheck.Need = false;
  3595. const bool IsAnnotatedParallel = TheLoop->isAnnotatedParallel();
  3596. MemoryDepChecker DepChecker(SE, DL, TheLoop);
  3597. // For each block.
  3598. for (Loop::block_iterator bb = TheLoop->block_begin(),
  3599. be = TheLoop->block_end(); bb != be; ++bb) {
  3600. // Scan the BB and collect legal loads and stores.
  3601. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  3602. ++it) {
  3603. // If this is a load, save it. If this instruction can read from memory
  3604. // but is not a load, then we quit. Notice that we don't handle function
  3605. // calls that read or write.
  3606. if (it->mayReadFromMemory()) {
  3607. // Many math library functions read the rounding mode. We will only
  3608. // vectorize a loop if it contains known function calls that don't set
  3609. // the flag. Therefore, it is safe to ignore this read from memory.
  3610. CallInst *Call = dyn_cast<CallInst>(it);
  3611. if (Call && getIntrinsicIDForCall(Call, TLI))
  3612. continue;
  3613. LoadInst *Ld = dyn_cast<LoadInst>(it);
  3614. if (!Ld) return false;
  3615. if (!Ld->isSimple() && !IsAnnotatedParallel) {
  3616. DEBUG(dbgs() << "LV: Found a non-simple load.\n");
  3617. return false;
  3618. }
  3619. Loads.push_back(Ld);
  3620. DepChecker.addAccess(Ld);
  3621. continue;
  3622. }
  3623. // Save 'store' instructions. Abort if other instructions write to memory.
  3624. if (it->mayWriteToMemory()) {
  3625. StoreInst *St = dyn_cast<StoreInst>(it);
  3626. if (!St) return false;
  3627. if (!St->isSimple() && !IsAnnotatedParallel) {
  3628. DEBUG(dbgs() << "LV: Found a non-simple store.\n");
  3629. return false;
  3630. }
  3631. Stores.push_back(St);
  3632. DepChecker.addAccess(St);
  3633. }
  3634. } // Next instr.
  3635. } // Next block.
  3636. // Now we have two lists that hold the loads and the stores.
  3637. // Next, we find the pointers that they use.
  3638. // Check if we see any stores. If there are no stores, then we don't
  3639. // care if the pointers are *restrict*.
  3640. if (!Stores.size()) {
  3641. DEBUG(dbgs() << "LV: Found a read-only loop!\n");
  3642. return true;
  3643. }
  3644. AccessAnalysis::DepCandidates DependentAccesses;
  3645. AccessAnalysis Accesses(DL, DependentAccesses);
  3646. // Holds the analyzed pointers. We don't want to call GetUnderlyingObjects
  3647. // multiple times on the same object. If the ptr is accessed twice, once
  3648. // for read and once for write, it will only appear once (on the write
  3649. // list). This is okay, since we are going to check for conflicts between
  3650. // writes and between reads and writes, but not between reads and reads.
  3651. ValueSet Seen;
  3652. ValueVector::iterator I, IE;
  3653. for (I = Stores.begin(), IE = Stores.end(); I != IE; ++I) {
  3654. StoreInst *ST = cast<StoreInst>(*I);
  3655. Value* Ptr = ST->getPointerOperand();
  3656. if (isUniform(Ptr)) {
  3657. DEBUG(dbgs() << "LV: We don't allow storing to uniform addresses\n");
  3658. return false;
  3659. }
  3660. // If we did *not* see this pointer before, insert it to the read-write
  3661. // list. At this phase it is only a 'write' list.
  3662. if (Seen.insert(Ptr)) {
  3663. ++NumReadWrites;
  3664. Accesses.addStore(Ptr);
  3665. }
  3666. }
  3667. if (IsAnnotatedParallel) {
  3668. DEBUG(dbgs()
  3669. << "LV: A loop annotated parallel, ignore memory dependency "
  3670. << "checks.\n");
  3671. return true;
  3672. }
  3673. for (I = Loads.begin(), IE = Loads.end(); I != IE; ++I) {
  3674. LoadInst *LD = cast<LoadInst>(*I);
  3675. Value* Ptr = LD->getPointerOperand();
  3676. // If we did *not* see this pointer before, insert it to the
  3677. // read list. If we *did* see it before, then it is already in
  3678. // the read-write list. This allows us to vectorize expressions
  3679. // such as A[i] += x; Because the address of A[i] is a read-write
  3680. // pointer. This only works if the index of A[i] is consecutive.
  3681. // If the address of i is unknown (for example A[B[i]]) then we may
  3682. // read a few words, modify, and write a few words, and some of the
  3683. // words may be written to the same address.
  3684. bool IsReadOnlyPtr = false;
  3685. if (Seen.insert(Ptr) || !isStridedPtr(SE, DL, Ptr, TheLoop, Strides)) {
  3686. ++NumReads;
  3687. IsReadOnlyPtr = true;
  3688. }
  3689. Accesses.addLoad(Ptr, IsReadOnlyPtr);
  3690. }
  3691. // If we write (or read-write) to a single destination and there are no
  3692. // other reads in this loop then is it safe to vectorize.
  3693. if (NumReadWrites == 1 && NumReads == 0) {
  3694. DEBUG(dbgs() << "LV: Found a write-only loop!\n");
  3695. return true;
  3696. }
  3697. // Build dependence sets and check whether we need a runtime pointer bounds
  3698. // check.
  3699. Accesses.buildDependenceSets();
  3700. bool NeedRTCheck = Accesses.isRTCheckNeeded();
  3701. // Find pointers with computable bounds. We are going to use this information
  3702. // to place a runtime bound check.
  3703. unsigned NumComparisons = 0;
  3704. bool CanDoRT = false;
  3705. if (NeedRTCheck)
  3706. CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE, TheLoop,
  3707. Strides);
  3708. DEBUG(dbgs() << "LV: We need to do " << NumComparisons <<
  3709. " pointer comparisons.\n");
  3710. // If we only have one set of dependences to check pointers among we don't
  3711. // need a runtime check.
  3712. if (NumComparisons == 0 && NeedRTCheck)
  3713. NeedRTCheck = false;
  3714. // Check that we did not collect too many pointers or found an unsizeable
  3715. // pointer.
  3716. if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
  3717. PtrRtCheck.reset();
  3718. CanDoRT = false;
  3719. }
  3720. if (CanDoRT) {
  3721. DEBUG(dbgs() << "LV: We can perform a memory runtime check if needed.\n");
  3722. }
  3723. if (NeedRTCheck && !CanDoRT) {
  3724. DEBUG(dbgs() << "LV: We can't vectorize because we can't find " <<
  3725. "the array bounds.\n");
  3726. PtrRtCheck.reset();
  3727. return false;
  3728. }
  3729. PtrRtCheck.Need = NeedRTCheck;
  3730. bool CanVecMem = true;
  3731. if (Accesses.isDependencyCheckNeeded()) {
  3732. DEBUG(dbgs() << "LV: Checking memory dependencies\n");
  3733. CanVecMem = DepChecker.areDepsSafe(
  3734. DependentAccesses, Accesses.getDependenciesToCheck(), Strides);
  3735. MaxSafeDepDistBytes = DepChecker.getMaxSafeDepDistBytes();
  3736. if (!CanVecMem && DepChecker.shouldRetryWithRuntimeCheck()) {
  3737. DEBUG(dbgs() << "LV: Retrying with memory checks\n");
  3738. NeedRTCheck = true;
  3739. // Clear the dependency checks. We assume they are not needed.
  3740. Accesses.resetDepChecks();
  3741. PtrRtCheck.reset();
  3742. PtrRtCheck.Need = true;
  3743. CanDoRT = Accesses.canCheckPtrAtRT(PtrRtCheck, NumComparisons, SE,
  3744. TheLoop, Strides, true);
  3745. // Check that we did not collect too many pointers or found an unsizeable
  3746. // pointer.
  3747. if (!CanDoRT || NumComparisons > RuntimeMemoryCheckThreshold) {
  3748. DEBUG(dbgs() << "LV: Can't vectorize with memory checks\n");
  3749. PtrRtCheck.reset();
  3750. return false;
  3751. }
  3752. CanVecMem = true;
  3753. }
  3754. }
  3755. DEBUG(dbgs() << "LV: We" << (NeedRTCheck ? "" : " don't") <<
  3756. " need a runtime memory check.\n");
  3757. return CanVecMem;
  3758. }
  3759. static bool hasMultipleUsesOf(Instruction *I,
  3760. SmallPtrSet<Instruction *, 8> &Insts) {
  3761. unsigned NumUses = 0;
  3762. for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use) {
  3763. if (Insts.count(dyn_cast<Instruction>(*Use)))
  3764. ++NumUses;
  3765. if (NumUses > 1)
  3766. return true;
  3767. }
  3768. return false;
  3769. }
  3770. static bool areAllUsesIn(Instruction *I, SmallPtrSet<Instruction *, 8> &Set) {
  3771. for(User::op_iterator Use = I->op_begin(), E = I->op_end(); Use != E; ++Use)
  3772. if (!Set.count(dyn_cast<Instruction>(*Use)))
  3773. return false;
  3774. return true;
  3775. }
  3776. bool LoopVectorizationLegality::AddReductionVar(PHINode *Phi,
  3777. ReductionKind Kind) {
  3778. if (Phi->getNumIncomingValues() != 2)
  3779. return false;
  3780. // Reduction variables are only found in the loop header block.
  3781. if (Phi->getParent() != TheLoop->getHeader())
  3782. return false;
  3783. // Obtain the reduction start value from the value that comes from the loop
  3784. // preheader.
  3785. Value *RdxStart = Phi->getIncomingValueForBlock(TheLoop->getLoopPreheader());
  3786. // ExitInstruction is the single value which is used outside the loop.
  3787. // We only allow for a single reduction value to be used outside the loop.
  3788. // This includes users of the reduction, variables (which form a cycle
  3789. // which ends in the phi node).
  3790. Instruction *ExitInstruction = 0;
  3791. // Indicates that we found a reduction operation in our scan.
  3792. bool FoundReduxOp = false;
  3793. // We start with the PHI node and scan for all of the users of this
  3794. // instruction. All users must be instructions that can be used as reduction
  3795. // variables (such as ADD). We must have a single out-of-block user. The cycle
  3796. // must include the original PHI.
  3797. bool FoundStartPHI = false;
  3798. // To recognize min/max patterns formed by a icmp select sequence, we store
  3799. // the number of instruction we saw from the recognized min/max pattern,
  3800. // to make sure we only see exactly the two instructions.
  3801. unsigned NumCmpSelectPatternInst = 0;
  3802. ReductionInstDesc ReduxDesc(false, 0);
  3803. SmallPtrSet<Instruction *, 8> VisitedInsts;
  3804. SmallVector<Instruction *, 8> Worklist;
  3805. Worklist.push_back(Phi);
  3806. VisitedInsts.insert(Phi);
  3807. // A value in the reduction can be used:
  3808. // - By the reduction:
  3809. // - Reduction operation:
  3810. // - One use of reduction value (safe).
  3811. // - Multiple use of reduction value (not safe).
  3812. // - PHI:
  3813. // - All uses of the PHI must be the reduction (safe).
  3814. // - Otherwise, not safe.
  3815. // - By one instruction outside of the loop (safe).
  3816. // - By further instructions outside of the loop (not safe).
  3817. // - By an instruction that is not part of the reduction (not safe).
  3818. // This is either:
  3819. // * An instruction type other than PHI or the reduction operation.
  3820. // * A PHI in the header other than the initial PHI.
  3821. while (!Worklist.empty()) {
  3822. Instruction *Cur = Worklist.back();
  3823. Worklist.pop_back();
  3824. // No Users.
  3825. // If the instruction has no users then this is a broken chain and can't be
  3826. // a reduction variable.
  3827. if (Cur->use_empty())
  3828. return false;
  3829. bool IsAPhi = isa<PHINode>(Cur);
  3830. // A header PHI use other than the original PHI.
  3831. if (Cur != Phi && IsAPhi && Cur->getParent() == Phi->getParent())
  3832. return false;
  3833. // Reductions of instructions such as Div, and Sub is only possible if the
  3834. // LHS is the reduction variable.
  3835. if (!Cur->isCommutative() && !IsAPhi && !isa<SelectInst>(Cur) &&
  3836. !isa<ICmpInst>(Cur) && !isa<FCmpInst>(Cur) &&
  3837. !VisitedInsts.count(dyn_cast<Instruction>(Cur->getOperand(0))))
  3838. return false;
  3839. // Any reduction instruction must be of one of the allowed kinds.
  3840. ReduxDesc = isReductionInstr(Cur, Kind, ReduxDesc);
  3841. if (!ReduxDesc.IsReduction)
  3842. return false;
  3843. // A reduction operation must only have one use of the reduction value.
  3844. if (!IsAPhi && Kind != RK_IntegerMinMax && Kind != RK_FloatMinMax &&
  3845. hasMultipleUsesOf(Cur, VisitedInsts))
  3846. return false;
  3847. // All inputs to a PHI node must be a reduction value.
  3848. if(IsAPhi && Cur != Phi && !areAllUsesIn(Cur, VisitedInsts))
  3849. return false;
  3850. if (Kind == RK_IntegerMinMax && (isa<ICmpInst>(Cur) ||
  3851. isa<SelectInst>(Cur)))
  3852. ++NumCmpSelectPatternInst;
  3853. if (Kind == RK_FloatMinMax && (isa<FCmpInst>(Cur) ||
  3854. isa<SelectInst>(Cur)))
  3855. ++NumCmpSelectPatternInst;
  3856. // Check whether we found a reduction operator.
  3857. FoundReduxOp |= !IsAPhi;
  3858. // Process users of current instruction. Push non-PHI nodes after PHI nodes
  3859. // onto the stack. This way we are going to have seen all inputs to PHI
  3860. // nodes once we get to them.
  3861. SmallVector<Instruction *, 8> NonPHIs;
  3862. SmallVector<Instruction *, 8> PHIs;
  3863. for (Value::use_iterator UI = Cur->use_begin(), E = Cur->use_end(); UI != E;
  3864. ++UI) {
  3865. Instruction *Usr = cast<Instruction>(*UI);
  3866. // Check if we found the exit user.
  3867. BasicBlock *Parent = Usr->getParent();
  3868. if (!TheLoop->contains(Parent)) {
  3869. // Exit if you find multiple outside users or if the header phi node is
  3870. // being used. In this case the user uses the value of the previous
  3871. // iteration, in which case we would loose "VF-1" iterations of the
  3872. // reduction operation if we vectorize.
  3873. if (ExitInstruction != 0 || Cur == Phi)
  3874. return false;
  3875. // The instruction used by an outside user must be the last instruction
  3876. // before we feed back to the reduction phi. Otherwise, we loose VF-1
  3877. // operations on the value.
  3878. if (std::find(Phi->op_begin(), Phi->op_end(), Cur) == Phi->op_end())
  3879. return false;
  3880. ExitInstruction = Cur;
  3881. continue;
  3882. }
  3883. // Process instructions only once (termination). Each reduction cycle
  3884. // value must only be used once, except by phi nodes and min/max
  3885. // reductions which are represented as a cmp followed by a select.
  3886. ReductionInstDesc IgnoredVal(false, 0);
  3887. if (VisitedInsts.insert(Usr)) {
  3888. if (isa<PHINode>(Usr))
  3889. PHIs.push_back(Usr);
  3890. else
  3891. NonPHIs.push_back(Usr);
  3892. } else if (!isa<PHINode>(Usr) &&
  3893. ((!isa<FCmpInst>(Usr) &&
  3894. !isa<ICmpInst>(Usr) &&
  3895. !isa<SelectInst>(Usr)) ||
  3896. !isMinMaxSelectCmpPattern(Usr, IgnoredVal).IsReduction))
  3897. return false;
  3898. // Remember that we completed the cycle.
  3899. if (Usr == Phi)
  3900. FoundStartPHI = true;
  3901. }
  3902. Worklist.append(PHIs.begin(), PHIs.end());
  3903. Worklist.append(NonPHIs.begin(), NonPHIs.end());
  3904. }
  3905. // This means we have seen one but not the other instruction of the
  3906. // pattern or more than just a select and cmp.
  3907. if ((Kind == RK_IntegerMinMax || Kind == RK_FloatMinMax) &&
  3908. NumCmpSelectPatternInst != 2)
  3909. return false;
  3910. if (!FoundStartPHI || !FoundReduxOp || !ExitInstruction)
  3911. return false;
  3912. // We found a reduction var if we have reached the original phi node and we
  3913. // only have a single instruction with out-of-loop users.
  3914. // This instruction is allowed to have out-of-loop users.
  3915. AllowedExit.insert(ExitInstruction);
  3916. // Save the description of this reduction variable.
  3917. ReductionDescriptor RD(RdxStart, ExitInstruction, Kind,
  3918. ReduxDesc.MinMaxKind);
  3919. Reductions[Phi] = RD;
  3920. // We've ended the cycle. This is a reduction variable if we have an
  3921. // outside user and it has a binary op.
  3922. return true;
  3923. }
  3924. /// Returns true if the instruction is a Select(ICmp(X, Y), X, Y) instruction
  3925. /// pattern corresponding to a min(X, Y) or max(X, Y).
  3926. LoopVectorizationLegality::ReductionInstDesc
  3927. LoopVectorizationLegality::isMinMaxSelectCmpPattern(Instruction *I,
  3928. ReductionInstDesc &Prev) {
  3929. assert((isa<ICmpInst>(I) || isa<FCmpInst>(I) || isa<SelectInst>(I)) &&
  3930. "Expect a select instruction");
  3931. Instruction *Cmp = 0;
  3932. SelectInst *Select = 0;
  3933. // We must handle the select(cmp()) as a single instruction. Advance to the
  3934. // select.
  3935. if ((Cmp = dyn_cast<ICmpInst>(I)) || (Cmp = dyn_cast<FCmpInst>(I))) {
  3936. if (!Cmp->hasOneUse() || !(Select = dyn_cast<SelectInst>(*I->use_begin())))
  3937. return ReductionInstDesc(false, I);
  3938. return ReductionInstDesc(Select, Prev.MinMaxKind);
  3939. }
  3940. // Only handle single use cases for now.
  3941. if (!(Select = dyn_cast<SelectInst>(I)))
  3942. return ReductionInstDesc(false, I);
  3943. if (!(Cmp = dyn_cast<ICmpInst>(I->getOperand(0))) &&
  3944. !(Cmp = dyn_cast<FCmpInst>(I->getOperand(0))))
  3945. return ReductionInstDesc(false, I);
  3946. if (!Cmp->hasOneUse())
  3947. return ReductionInstDesc(false, I);
  3948. Value *CmpLeft;
  3949. Value *CmpRight;
  3950. // Look for a min/max pattern.
  3951. if (m_UMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3952. return ReductionInstDesc(Select, MRK_UIntMin);
  3953. else if (m_UMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3954. return ReductionInstDesc(Select, MRK_UIntMax);
  3955. else if (m_SMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3956. return ReductionInstDesc(Select, MRK_SIntMax);
  3957. else if (m_SMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3958. return ReductionInstDesc(Select, MRK_SIntMin);
  3959. else if (m_OrdFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3960. return ReductionInstDesc(Select, MRK_FloatMin);
  3961. else if (m_OrdFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3962. return ReductionInstDesc(Select, MRK_FloatMax);
  3963. else if (m_UnordFMin(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3964. return ReductionInstDesc(Select, MRK_FloatMin);
  3965. else if (m_UnordFMax(m_Value(CmpLeft), m_Value(CmpRight)).match(Select))
  3966. return ReductionInstDesc(Select, MRK_FloatMax);
  3967. return ReductionInstDesc(false, I);
  3968. }
  3969. LoopVectorizationLegality::ReductionInstDesc
  3970. LoopVectorizationLegality::isReductionInstr(Instruction *I,
  3971. ReductionKind Kind,
  3972. ReductionInstDesc &Prev) {
  3973. bool FP = I->getType()->isFloatingPointTy();
  3974. bool FastMath = (FP && I->isCommutative() && I->isAssociative());
  3975. switch (I->getOpcode()) {
  3976. default:
  3977. return ReductionInstDesc(false, I);
  3978. case Instruction::PHI:
  3979. if (FP && (Kind != RK_FloatMult && Kind != RK_FloatAdd &&
  3980. Kind != RK_FloatMinMax))
  3981. return ReductionInstDesc(false, I);
  3982. return ReductionInstDesc(I, Prev.MinMaxKind);
  3983. case Instruction::Sub:
  3984. case Instruction::Add:
  3985. return ReductionInstDesc(Kind == RK_IntegerAdd, I);
  3986. case Instruction::Mul:
  3987. return ReductionInstDesc(Kind == RK_IntegerMult, I);
  3988. case Instruction::And:
  3989. return ReductionInstDesc(Kind == RK_IntegerAnd, I);
  3990. case Instruction::Or:
  3991. return ReductionInstDesc(Kind == RK_IntegerOr, I);
  3992. case Instruction::Xor:
  3993. return ReductionInstDesc(Kind == RK_IntegerXor, I);
  3994. case Instruction::FMul:
  3995. return ReductionInstDesc(Kind == RK_FloatMult && FastMath, I);
  3996. case Instruction::FAdd:
  3997. return ReductionInstDesc(Kind == RK_FloatAdd && FastMath, I);
  3998. case Instruction::FCmp:
  3999. case Instruction::ICmp:
  4000. case Instruction::Select:
  4001. if (Kind != RK_IntegerMinMax &&
  4002. (!HasFunNoNaNAttr || Kind != RK_FloatMinMax))
  4003. return ReductionInstDesc(false, I);
  4004. return isMinMaxSelectCmpPattern(I, Prev);
  4005. }
  4006. }
  4007. LoopVectorizationLegality::InductionKind
  4008. LoopVectorizationLegality::isInductionVariable(PHINode *Phi) {
  4009. Type *PhiTy = Phi->getType();
  4010. // We only handle integer and pointer inductions variables.
  4011. if (!PhiTy->isIntegerTy() && !PhiTy->isPointerTy())
  4012. return IK_NoInduction;
  4013. // Check that the PHI is consecutive.
  4014. const SCEV *PhiScev = SE->getSCEV(Phi);
  4015. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(PhiScev);
  4016. if (!AR) {
  4017. DEBUG(dbgs() << "LV: PHI is not a poly recurrence.\n");
  4018. return IK_NoInduction;
  4019. }
  4020. const SCEV *Step = AR->getStepRecurrence(*SE);
  4021. // Integer inductions need to have a stride of one.
  4022. if (PhiTy->isIntegerTy()) {
  4023. if (Step->isOne())
  4024. return IK_IntInduction;
  4025. if (Step->isAllOnesValue())
  4026. return IK_ReverseIntInduction;
  4027. return IK_NoInduction;
  4028. }
  4029. // Calculate the pointer stride and check if it is consecutive.
  4030. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  4031. if (!C)
  4032. return IK_NoInduction;
  4033. assert(PhiTy->isPointerTy() && "The PHI must be a pointer");
  4034. uint64_t Size = DL->getTypeAllocSize(PhiTy->getPointerElementType());
  4035. if (C->getValue()->equalsInt(Size))
  4036. return IK_PtrInduction;
  4037. else if (C->getValue()->equalsInt(0 - Size))
  4038. return IK_ReversePtrInduction;
  4039. return IK_NoInduction;
  4040. }
  4041. bool LoopVectorizationLegality::isInductionVariable(const Value *V) {
  4042. Value *In0 = const_cast<Value*>(V);
  4043. PHINode *PN = dyn_cast_or_null<PHINode>(In0);
  4044. if (!PN)
  4045. return false;
  4046. return Inductions.count(PN);
  4047. }
  4048. bool LoopVectorizationLegality::blockNeedsPredication(BasicBlock *BB) {
  4049. assert(TheLoop->contains(BB) && "Unknown block used");
  4050. // Blocks that do not dominate the latch need predication.
  4051. BasicBlock* Latch = TheLoop->getLoopLatch();
  4052. return !DT->dominates(BB, Latch);
  4053. }
  4054. bool LoopVectorizationLegality::blockCanBePredicated(BasicBlock *BB,
  4055. SmallPtrSet<Value *, 8>& SafePtrs) {
  4056. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4057. // We might be able to hoist the load.
  4058. if (it->mayReadFromMemory()) {
  4059. LoadInst *LI = dyn_cast<LoadInst>(it);
  4060. if (!LI || !SafePtrs.count(LI->getPointerOperand()))
  4061. return false;
  4062. }
  4063. // We don't predicate stores at the moment.
  4064. if (it->mayWriteToMemory() || it->mayThrow())
  4065. return false;
  4066. // Check that we don't have a constant expression that can trap as operand.
  4067. for (Instruction::op_iterator OI = it->op_begin(), OE = it->op_end();
  4068. OI != OE; ++OI) {
  4069. if (Constant *C = dyn_cast<Constant>(*OI))
  4070. if (C->canTrap())
  4071. return false;
  4072. }
  4073. // The instructions below can trap.
  4074. switch (it->getOpcode()) {
  4075. default: continue;
  4076. case Instruction::UDiv:
  4077. case Instruction::SDiv:
  4078. case Instruction::URem:
  4079. case Instruction::SRem:
  4080. return false;
  4081. }
  4082. }
  4083. return true;
  4084. }
  4085. LoopVectorizationCostModel::VectorizationFactor
  4086. LoopVectorizationCostModel::selectVectorizationFactor(bool OptForSize,
  4087. unsigned UserVF) {
  4088. // Width 1 means no vectorize
  4089. VectorizationFactor Factor = { 1U, 0U };
  4090. if (OptForSize && Legal->getRuntimePointerCheck()->Need) {
  4091. DEBUG(dbgs() << "LV: Aborting. Runtime ptr check is required in Os.\n");
  4092. return Factor;
  4093. }
  4094. // Find the trip count.
  4095. unsigned TC = SE->getSmallConstantTripCount(TheLoop, TheLoop->getLoopLatch());
  4096. DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4097. unsigned WidestType = getWidestType();
  4098. unsigned WidestRegister = TTI.getRegisterBitWidth(true);
  4099. unsigned MaxSafeDepDist = -1U;
  4100. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4101. MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
  4102. WidestRegister = ((WidestRegister < MaxSafeDepDist) ?
  4103. WidestRegister : MaxSafeDepDist);
  4104. unsigned MaxVectorSize = WidestRegister / WidestType;
  4105. DEBUG(dbgs() << "LV: The Widest type: " << WidestType << " bits.\n");
  4106. DEBUG(dbgs() << "LV: The Widest register is: "
  4107. << WidestRegister << " bits.\n");
  4108. if (MaxVectorSize == 0) {
  4109. DEBUG(dbgs() << "LV: The target has no vector registers.\n");
  4110. MaxVectorSize = 1;
  4111. }
  4112. assert(MaxVectorSize <= 32 && "Did not expect to pack so many elements"
  4113. " into one vector!");
  4114. unsigned VF = MaxVectorSize;
  4115. // If we optimize the program for size, avoid creating the tail loop.
  4116. if (OptForSize) {
  4117. // If we are unable to calculate the trip count then don't try to vectorize.
  4118. if (TC < 2) {
  4119. DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
  4120. return Factor;
  4121. }
  4122. // Find the maximum SIMD width that can fit within the trip count.
  4123. VF = TC % MaxVectorSize;
  4124. if (VF == 0)
  4125. VF = MaxVectorSize;
  4126. // If the trip count that we found modulo the vectorization factor is not
  4127. // zero then we require a tail.
  4128. if (VF < 2) {
  4129. DEBUG(dbgs() << "LV: Aborting. A tail loop is required in Os.\n");
  4130. return Factor;
  4131. }
  4132. }
  4133. if (UserVF != 0) {
  4134. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  4135. DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  4136. Factor.Width = UserVF;
  4137. return Factor;
  4138. }
  4139. float Cost = expectedCost(1);
  4140. unsigned Width = 1;
  4141. DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)Cost << ".\n");
  4142. for (unsigned i=2; i <= VF; i*=2) {
  4143. // Notice that the vector loop needs to be executed less times, so
  4144. // we need to divide the cost of the vector loops by the width of
  4145. // the vector elements.
  4146. float VectorCost = expectedCost(i) / (float)i;
  4147. DEBUG(dbgs() << "LV: Vector loop of width " << i << " costs: " <<
  4148. (int)VectorCost << ".\n");
  4149. if (VectorCost < Cost) {
  4150. Cost = VectorCost;
  4151. Width = i;
  4152. }
  4153. }
  4154. DEBUG(dbgs() << "LV: Selecting VF = : "<< Width << ".\n");
  4155. Factor.Width = Width;
  4156. Factor.Cost = Width * Cost;
  4157. return Factor;
  4158. }
  4159. unsigned LoopVectorizationCostModel::getWidestType() {
  4160. unsigned MaxWidth = 8;
  4161. // For each block.
  4162. for (Loop::block_iterator bb = TheLoop->block_begin(),
  4163. be = TheLoop->block_end(); bb != be; ++bb) {
  4164. BasicBlock *BB = *bb;
  4165. // For each instruction in the loop.
  4166. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4167. Type *T = it->getType();
  4168. // Only examine Loads, Stores and PHINodes.
  4169. if (!isa<LoadInst>(it) && !isa<StoreInst>(it) && !isa<PHINode>(it))
  4170. continue;
  4171. // Examine PHI nodes that are reduction variables.
  4172. if (PHINode *PN = dyn_cast<PHINode>(it))
  4173. if (!Legal->getReductionVars()->count(PN))
  4174. continue;
  4175. // Examine the stored values.
  4176. if (StoreInst *ST = dyn_cast<StoreInst>(it))
  4177. T = ST->getValueOperand()->getType();
  4178. // Ignore loaded pointer types and stored pointer types that are not
  4179. // consecutive. However, we do want to take consecutive stores/loads of
  4180. // pointer vectors into account.
  4181. if (T->isPointerTy() && !isConsecutiveLoadOrStore(it))
  4182. continue;
  4183. MaxWidth = std::max(MaxWidth,
  4184. (unsigned)DL->getTypeSizeInBits(T->getScalarType()));
  4185. }
  4186. }
  4187. return MaxWidth;
  4188. }
  4189. unsigned
  4190. LoopVectorizationCostModel::selectUnrollFactor(bool OptForSize,
  4191. unsigned UserUF,
  4192. unsigned VF,
  4193. unsigned LoopCost) {
  4194. // -- The unroll heuristics --
  4195. // We unroll the loop in order to expose ILP and reduce the loop overhead.
  4196. // There are many micro-architectural considerations that we can't predict
  4197. // at this level. For example frontend pressure (on decode or fetch) due to
  4198. // code size, or the number and capabilities of the execution ports.
  4199. //
  4200. // We use the following heuristics to select the unroll factor:
  4201. // 1. If the code has reductions the we unroll in order to break the cross
  4202. // iteration dependency.
  4203. // 2. If the loop is really small then we unroll in order to reduce the loop
  4204. // overhead.
  4205. // 3. We don't unroll if we think that we will spill registers to memory due
  4206. // to the increased register pressure.
  4207. // Use the user preference, unless 'auto' is selected.
  4208. if (UserUF != 0)
  4209. return UserUF;
  4210. // When we optimize for size we don't unroll.
  4211. if (OptForSize)
  4212. return 1;
  4213. // We used the distance for the unroll factor.
  4214. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4215. return 1;
  4216. // Do not unroll loops with a relatively small trip count.
  4217. unsigned TC = SE->getSmallConstantTripCount(TheLoop,
  4218. TheLoop->getLoopLatch());
  4219. if (TC > 1 && TC < TinyTripCountUnrollThreshold)
  4220. return 1;
  4221. unsigned TargetVectorRegisters = TTI.getNumberOfRegisters(true);
  4222. DEBUG(dbgs() << "LV: The target has " << TargetVectorRegisters <<
  4223. " vector registers\n");
  4224. LoopVectorizationCostModel::RegisterUsage R = calculateRegisterUsage();
  4225. // We divide by these constants so assume that we have at least one
  4226. // instruction that uses at least one register.
  4227. R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
  4228. R.NumInstructions = std::max(R.NumInstructions, 1U);
  4229. // We calculate the unroll factor using the following formula.
  4230. // Subtract the number of loop invariants from the number of available
  4231. // registers. These registers are used by all of the unrolled instances.
  4232. // Next, divide the remaining registers by the number of registers that is
  4233. // required by the loop, in order to estimate how many parallel instances
  4234. // fit without causing spills.
  4235. unsigned UF = (TargetVectorRegisters - R.LoopInvariantRegs) / R.MaxLocalUsers;
  4236. // Clamp the unroll factor ranges to reasonable factors.
  4237. unsigned MaxUnrollSize = TTI.getMaximumUnrollFactor();
  4238. // If we did not calculate the cost for VF (because the user selected the VF)
  4239. // then we calculate the cost of VF here.
  4240. if (LoopCost == 0)
  4241. LoopCost = expectedCost(VF);
  4242. // Clamp the calculated UF to be between the 1 and the max unroll factor
  4243. // that the target allows.
  4244. if (UF > MaxUnrollSize)
  4245. UF = MaxUnrollSize;
  4246. else if (UF < 1)
  4247. UF = 1;
  4248. bool HasReductions = Legal->getReductionVars()->size();
  4249. // Decide if we want to unroll if we decided that it is legal to vectorize
  4250. // but not profitable.
  4251. if (VF == 1) {
  4252. if (TheLoop->getNumBlocks() > 1 || !HasReductions ||
  4253. LoopCost > SmallLoopCost)
  4254. return 1;
  4255. return UF;
  4256. }
  4257. if (HasReductions) {
  4258. DEBUG(dbgs() << "LV: Unrolling because of reductions.\n");
  4259. return UF;
  4260. }
  4261. // We want to unroll tiny loops in order to reduce the loop overhead.
  4262. // We assume that the cost overhead is 1 and we use the cost model
  4263. // to estimate the cost of the loop and unroll until the cost of the
  4264. // loop overhead is about 5% of the cost of the loop.
  4265. DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
  4266. if (LoopCost < SmallLoopCost) {
  4267. DEBUG(dbgs() << "LV: Unrolling to reduce branch cost.\n");
  4268. unsigned NewUF = SmallLoopCost / (LoopCost + 1);
  4269. return std::min(NewUF, UF);
  4270. }
  4271. DEBUG(dbgs() << "LV: Not Unrolling.\n");
  4272. return 1;
  4273. }
  4274. LoopVectorizationCostModel::RegisterUsage
  4275. LoopVectorizationCostModel::calculateRegisterUsage() {
  4276. // This function calculates the register usage by measuring the highest number
  4277. // of values that are alive at a single location. Obviously, this is a very
  4278. // rough estimation. We scan the loop in a topological order in order and
  4279. // assign a number to each instruction. We use RPO to ensure that defs are
  4280. // met before their users. We assume that each instruction that has in-loop
  4281. // users starts an interval. We record every time that an in-loop value is
  4282. // used, so we have a list of the first and last occurrences of each
  4283. // instruction. Next, we transpose this data structure into a multi map that
  4284. // holds the list of intervals that *end* at a specific location. This multi
  4285. // map allows us to perform a linear search. We scan the instructions linearly
  4286. // and record each time that a new interval starts, by placing it in a set.
  4287. // If we find this value in the multi-map then we remove it from the set.
  4288. // The max register usage is the maximum size of the set.
  4289. // We also search for instructions that are defined outside the loop, but are
  4290. // used inside the loop. We need this number separately from the max-interval
  4291. // usage number because when we unroll, loop-invariant values do not take
  4292. // more register.
  4293. LoopBlocksDFS DFS(TheLoop);
  4294. DFS.perform(LI);
  4295. RegisterUsage R;
  4296. R.NumInstructions = 0;
  4297. // Each 'key' in the map opens a new interval. The values
  4298. // of the map are the index of the 'last seen' usage of the
  4299. // instruction that is the key.
  4300. typedef DenseMap<Instruction*, unsigned> IntervalMap;
  4301. // Maps instruction to its index.
  4302. DenseMap<unsigned, Instruction*> IdxToInstr;
  4303. // Marks the end of each interval.
  4304. IntervalMap EndPoint;
  4305. // Saves the list of instruction indices that are used in the loop.
  4306. SmallSet<Instruction*, 8> Ends;
  4307. // Saves the list of values that are used in the loop but are
  4308. // defined outside the loop, such as arguments and constants.
  4309. SmallPtrSet<Value*, 8> LoopInvariants;
  4310. unsigned Index = 0;
  4311. for (LoopBlocksDFS::RPOIterator bb = DFS.beginRPO(),
  4312. be = DFS.endRPO(); bb != be; ++bb) {
  4313. R.NumInstructions += (*bb)->size();
  4314. for (BasicBlock::iterator it = (*bb)->begin(), e = (*bb)->end(); it != e;
  4315. ++it) {
  4316. Instruction *I = it;
  4317. IdxToInstr[Index++] = I;
  4318. // Save the end location of each USE.
  4319. for (unsigned i = 0; i < I->getNumOperands(); ++i) {
  4320. Value *U = I->getOperand(i);
  4321. Instruction *Instr = dyn_cast<Instruction>(U);
  4322. // Ignore non-instruction values such as arguments, constants, etc.
  4323. if (!Instr) continue;
  4324. // If this instruction is outside the loop then record it and continue.
  4325. if (!TheLoop->contains(Instr)) {
  4326. LoopInvariants.insert(Instr);
  4327. continue;
  4328. }
  4329. // Overwrite previous end points.
  4330. EndPoint[Instr] = Index;
  4331. Ends.insert(Instr);
  4332. }
  4333. }
  4334. }
  4335. // Saves the list of intervals that end with the index in 'key'.
  4336. typedef SmallVector<Instruction*, 2> InstrList;
  4337. DenseMap<unsigned, InstrList> TransposeEnds;
  4338. // Transpose the EndPoints to a list of values that end at each index.
  4339. for (IntervalMap::iterator it = EndPoint.begin(), e = EndPoint.end();
  4340. it != e; ++it)
  4341. TransposeEnds[it->second].push_back(it->first);
  4342. SmallSet<Instruction*, 8> OpenIntervals;
  4343. unsigned MaxUsage = 0;
  4344. DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  4345. for (unsigned int i = 0; i < Index; ++i) {
  4346. Instruction *I = IdxToInstr[i];
  4347. // Ignore instructions that are never used within the loop.
  4348. if (!Ends.count(I)) continue;
  4349. // Remove all of the instructions that end at this location.
  4350. InstrList &List = TransposeEnds[i];
  4351. for (unsigned int j=0, e = List.size(); j < e; ++j)
  4352. OpenIntervals.erase(List[j]);
  4353. // Count the number of live interals.
  4354. MaxUsage = std::max(MaxUsage, OpenIntervals.size());
  4355. DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # " <<
  4356. OpenIntervals.size() << '\n');
  4357. // Add the current instruction to the list of open intervals.
  4358. OpenIntervals.insert(I);
  4359. }
  4360. unsigned Invariant = LoopInvariants.size();
  4361. DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsage << '\n');
  4362. DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant << '\n');
  4363. DEBUG(dbgs() << "LV(REG): LoopSize: " << R.NumInstructions << '\n');
  4364. R.LoopInvariantRegs = Invariant;
  4365. R.MaxLocalUsers = MaxUsage;
  4366. return R;
  4367. }
  4368. unsigned LoopVectorizationCostModel::expectedCost(unsigned VF) {
  4369. unsigned Cost = 0;
  4370. // For each block.
  4371. for (Loop::block_iterator bb = TheLoop->block_begin(),
  4372. be = TheLoop->block_end(); bb != be; ++bb) {
  4373. unsigned BlockCost = 0;
  4374. BasicBlock *BB = *bb;
  4375. // For each instruction in the old loop.
  4376. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  4377. // Skip dbg intrinsics.
  4378. if (isa<DbgInfoIntrinsic>(it))
  4379. continue;
  4380. unsigned C = getInstructionCost(it, VF);
  4381. BlockCost += C;
  4382. DEBUG(dbgs() << "LV: Found an estimated cost of " << C << " for VF " <<
  4383. VF << " For instruction: " << *it << '\n');
  4384. }
  4385. // We assume that if-converted blocks have a 50% chance of being executed.
  4386. // When the code is scalar then some of the blocks are avoided due to CF.
  4387. // When the code is vectorized we execute all code paths.
  4388. if (VF == 1 && Legal->blockNeedsPredication(*bb))
  4389. BlockCost /= 2;
  4390. Cost += BlockCost;
  4391. }
  4392. return Cost;
  4393. }
  4394. /// \brief Check whether the address computation for a non-consecutive memory
  4395. /// access looks like an unlikely candidate for being merged into the indexing
  4396. /// mode.
  4397. ///
  4398. /// We look for a GEP which has one index that is an induction variable and all
  4399. /// other indices are loop invariant. If the stride of this access is also
  4400. /// within a small bound we decide that this address computation can likely be
  4401. /// merged into the addressing mode.
  4402. /// In all other cases, we identify the address computation as complex.
  4403. static bool isLikelyComplexAddressComputation(Value *Ptr,
  4404. LoopVectorizationLegality *Legal,
  4405. ScalarEvolution *SE,
  4406. const Loop *TheLoop) {
  4407. GetElementPtrInst *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  4408. if (!Gep)
  4409. return true;
  4410. // We are looking for a gep with all loop invariant indices except for one
  4411. // which should be an induction variable.
  4412. unsigned NumOperands = Gep->getNumOperands();
  4413. for (unsigned i = 1; i < NumOperands; ++i) {
  4414. Value *Opd = Gep->getOperand(i);
  4415. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  4416. !Legal->isInductionVariable(Opd))
  4417. return true;
  4418. }
  4419. // Now we know we have a GEP ptr, %inv, %ind, %inv. Make sure that the step
  4420. // can likely be merged into the address computation.
  4421. unsigned MaxMergeDistance = 64;
  4422. const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Ptr));
  4423. if (!AddRec)
  4424. return true;
  4425. // Check the step is constant.
  4426. const SCEV *Step = AddRec->getStepRecurrence(*SE);
  4427. // Calculate the pointer stride and check if it is consecutive.
  4428. const SCEVConstant *C = dyn_cast<SCEVConstant>(Step);
  4429. if (!C)
  4430. return true;
  4431. const APInt &APStepVal = C->getValue()->getValue();
  4432. // Huge step value - give up.
  4433. if (APStepVal.getBitWidth() > 64)
  4434. return true;
  4435. int64_t StepVal = APStepVal.getSExtValue();
  4436. return StepVal > MaxMergeDistance;
  4437. }
  4438. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  4439. if (Legal->hasStride(I->getOperand(0)) || Legal->hasStride(I->getOperand(1)))
  4440. return true;
  4441. return false;
  4442. }
  4443. unsigned
  4444. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
  4445. // If we know that this instruction will remain uniform, check the cost of
  4446. // the scalar version.
  4447. if (Legal->isUniformAfterVectorization(I))
  4448. VF = 1;
  4449. Type *RetTy = I->getType();
  4450. Type *VectorTy = ToVectorTy(RetTy, VF);
  4451. // TODO: We need to estimate the cost of intrinsic calls.
  4452. switch (I->getOpcode()) {
  4453. case Instruction::GetElementPtr:
  4454. // We mark this instruction as zero-cost because the cost of GEPs in
  4455. // vectorized code depends on whether the corresponding memory instruction
  4456. // is scalarized or not. Therefore, we handle GEPs with the memory
  4457. // instruction cost.
  4458. return 0;
  4459. case Instruction::Br: {
  4460. return TTI.getCFInstrCost(I->getOpcode());
  4461. }
  4462. case Instruction::PHI:
  4463. //TODO: IF-converted IFs become selects.
  4464. return 0;
  4465. case Instruction::Add:
  4466. case Instruction::FAdd:
  4467. case Instruction::Sub:
  4468. case Instruction::FSub:
  4469. case Instruction::Mul:
  4470. case Instruction::FMul:
  4471. case Instruction::UDiv:
  4472. case Instruction::SDiv:
  4473. case Instruction::FDiv:
  4474. case Instruction::URem:
  4475. case Instruction::SRem:
  4476. case Instruction::FRem:
  4477. case Instruction::Shl:
  4478. case Instruction::LShr:
  4479. case Instruction::AShr:
  4480. case Instruction::And:
  4481. case Instruction::Or:
  4482. case Instruction::Xor: {
  4483. // Since we will replace the stride by 1 the multiplication should go away.
  4484. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  4485. return 0;
  4486. // Certain instructions can be cheaper to vectorize if they have a constant
  4487. // second vector operand. One example of this are shifts on x86.
  4488. TargetTransformInfo::OperandValueKind Op1VK =
  4489. TargetTransformInfo::OK_AnyValue;
  4490. TargetTransformInfo::OperandValueKind Op2VK =
  4491. TargetTransformInfo::OK_AnyValue;
  4492. if (isa<ConstantInt>(I->getOperand(1)))
  4493. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  4494. return TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK, Op2VK);
  4495. }
  4496. case Instruction::Select: {
  4497. SelectInst *SI = cast<SelectInst>(I);
  4498. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  4499. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  4500. Type *CondTy = SI->getCondition()->getType();
  4501. if (!ScalarCond)
  4502. CondTy = VectorType::get(CondTy, VF);
  4503. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy);
  4504. }
  4505. case Instruction::ICmp:
  4506. case Instruction::FCmp: {
  4507. Type *ValTy = I->getOperand(0)->getType();
  4508. VectorTy = ToVectorTy(ValTy, VF);
  4509. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy);
  4510. }
  4511. case Instruction::Store:
  4512. case Instruction::Load: {
  4513. StoreInst *SI = dyn_cast<StoreInst>(I);
  4514. LoadInst *LI = dyn_cast<LoadInst>(I);
  4515. Type *ValTy = (SI ? SI->getValueOperand()->getType() :
  4516. LI->getType());
  4517. VectorTy = ToVectorTy(ValTy, VF);
  4518. unsigned Alignment = SI ? SI->getAlignment() : LI->getAlignment();
  4519. unsigned AS = SI ? SI->getPointerAddressSpace() :
  4520. LI->getPointerAddressSpace();
  4521. Value *Ptr = SI ? SI->getPointerOperand() : LI->getPointerOperand();
  4522. // We add the cost of address computation here instead of with the gep
  4523. // instruction because only here we know whether the operation is
  4524. // scalarized.
  4525. if (VF == 1)
  4526. return TTI.getAddressComputationCost(VectorTy) +
  4527. TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  4528. // Scalarized loads/stores.
  4529. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  4530. bool Reverse = ConsecutiveStride < 0;
  4531. unsigned ScalarAllocatedSize = DL->getTypeAllocSize(ValTy);
  4532. unsigned VectorElementSize = DL->getTypeStoreSize(VectorTy)/VF;
  4533. if (!ConsecutiveStride || ScalarAllocatedSize != VectorElementSize) {
  4534. bool IsComplexComputation =
  4535. isLikelyComplexAddressComputation(Ptr, Legal, SE, TheLoop);
  4536. unsigned Cost = 0;
  4537. // The cost of extracting from the value vector and pointer vector.
  4538. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  4539. for (unsigned i = 0; i < VF; ++i) {
  4540. // The cost of extracting the pointer operand.
  4541. Cost += TTI.getVectorInstrCost(Instruction::ExtractElement, PtrTy, i);
  4542. // In case of STORE, the cost of ExtractElement from the vector.
  4543. // In case of LOAD, the cost of InsertElement into the returned
  4544. // vector.
  4545. Cost += TTI.getVectorInstrCost(SI ? Instruction::ExtractElement :
  4546. Instruction::InsertElement,
  4547. VectorTy, i);
  4548. }
  4549. // The cost of the scalar loads/stores.
  4550. Cost += VF * TTI.getAddressComputationCost(PtrTy, IsComplexComputation);
  4551. Cost += VF * TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(),
  4552. Alignment, AS);
  4553. return Cost;
  4554. }
  4555. // Wide load/stores.
  4556. unsigned Cost = TTI.getAddressComputationCost(VectorTy);
  4557. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  4558. if (Reverse)
  4559. Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse,
  4560. VectorTy, 0);
  4561. return Cost;
  4562. }
  4563. case Instruction::ZExt:
  4564. case Instruction::SExt:
  4565. case Instruction::FPToUI:
  4566. case Instruction::FPToSI:
  4567. case Instruction::FPExt:
  4568. case Instruction::PtrToInt:
  4569. case Instruction::IntToPtr:
  4570. case Instruction::SIToFP:
  4571. case Instruction::UIToFP:
  4572. case Instruction::Trunc:
  4573. case Instruction::FPTrunc:
  4574. case Instruction::BitCast: {
  4575. // We optimize the truncation of induction variable.
  4576. // The cost of these is the same as the scalar operation.
  4577. if (I->getOpcode() == Instruction::Trunc &&
  4578. Legal->isInductionVariable(I->getOperand(0)))
  4579. return TTI.getCastInstrCost(I->getOpcode(), I->getType(),
  4580. I->getOperand(0)->getType());
  4581. Type *SrcVecTy = ToVectorTy(I->getOperand(0)->getType(), VF);
  4582. return TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy);
  4583. }
  4584. case Instruction::Call: {
  4585. CallInst *CI = cast<CallInst>(I);
  4586. Intrinsic::ID ID = getIntrinsicIDForCall(CI, TLI);
  4587. assert(ID && "Not an intrinsic call!");
  4588. Type *RetTy = ToVectorTy(CI->getType(), VF);
  4589. SmallVector<Type*, 4> Tys;
  4590. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i)
  4591. Tys.push_back(ToVectorTy(CI->getArgOperand(i)->getType(), VF));
  4592. return TTI.getIntrinsicInstrCost(ID, RetTy, Tys);
  4593. }
  4594. default: {
  4595. // We are scalarizing the instruction. Return the cost of the scalar
  4596. // instruction, plus the cost of insert and extract into vector
  4597. // elements, times the vector width.
  4598. unsigned Cost = 0;
  4599. if (!RetTy->isVoidTy() && VF != 1) {
  4600. unsigned InsCost = TTI.getVectorInstrCost(Instruction::InsertElement,
  4601. VectorTy);
  4602. unsigned ExtCost = TTI.getVectorInstrCost(Instruction::ExtractElement,
  4603. VectorTy);
  4604. // The cost of inserting the results plus extracting each one of the
  4605. // operands.
  4606. Cost += VF * (InsCost + ExtCost * I->getNumOperands());
  4607. }
  4608. // The cost of executing VF copies of the scalar instruction. This opcode
  4609. // is unknown. Assume that it is the same as 'mul'.
  4610. Cost += VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy);
  4611. return Cost;
  4612. }
  4613. }// end of switch.
  4614. }
  4615. Type* LoopVectorizationCostModel::ToVectorTy(Type *Scalar, unsigned VF) {
  4616. if (Scalar->isVoidTy() || VF == 1)
  4617. return Scalar;
  4618. return VectorType::get(Scalar, VF);
  4619. }
  4620. char LoopVectorize::ID = 0;
  4621. static const char lv_name[] = "Loop Vectorization";
  4622. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  4623. INITIALIZE_AG_DEPENDENCY(TargetTransformInfo)
  4624. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  4625. INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
  4626. INITIALIZE_PASS_DEPENDENCY(LCSSA)
  4627. INITIALIZE_PASS_DEPENDENCY(LoopInfo)
  4628. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  4629. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  4630. namespace llvm {
  4631. Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
  4632. return new LoopVectorize(NoUnrolling, AlwaysVectorize);
  4633. }
  4634. }
  4635. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  4636. // Check for a store.
  4637. if (StoreInst *ST = dyn_cast<StoreInst>(Inst))
  4638. return Legal->isConsecutivePtr(ST->getPointerOperand()) != 0;
  4639. // Check for a load.
  4640. if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  4641. return Legal->isConsecutivePtr(LI->getPointerOperand()) != 0;
  4642. return false;
  4643. }
  4644. void InnerLoopUnroller::scalarizeInstruction(Instruction *Instr) {
  4645. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  4646. // Holds vector parameters or scalars, in case of uniform vals.
  4647. SmallVector<VectorParts, 4> Params;
  4648. setDebugLocFromInst(Builder, Instr);
  4649. // Find all of the vectorized parameters.
  4650. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  4651. Value *SrcOp = Instr->getOperand(op);
  4652. // If we are accessing the old induction variable, use the new one.
  4653. if (SrcOp == OldInduction) {
  4654. Params.push_back(getVectorValue(SrcOp));
  4655. continue;
  4656. }
  4657. // Try using previously calculated values.
  4658. Instruction *SrcInst = dyn_cast<Instruction>(SrcOp);
  4659. // If the src is an instruction that appeared earlier in the basic block
  4660. // then it should already be vectorized.
  4661. if (SrcInst && OrigLoop->contains(SrcInst)) {
  4662. assert(WidenMap.has(SrcInst) && "Source operand is unavailable");
  4663. // The parameter is a vector value from earlier.
  4664. Params.push_back(WidenMap.get(SrcInst));
  4665. } else {
  4666. // The parameter is a scalar from outside the loop. Maybe even a constant.
  4667. VectorParts Scalars;
  4668. Scalars.append(UF, SrcOp);
  4669. Params.push_back(Scalars);
  4670. }
  4671. }
  4672. assert(Params.size() == Instr->getNumOperands() &&
  4673. "Invalid number of operands");
  4674. // Does this instruction return a value ?
  4675. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  4676. Value *UndefVec = IsVoidRetTy ? 0 :
  4677. UndefValue::get(Instr->getType());
  4678. // Create a new entry in the WidenMap and initialize it to Undef or Null.
  4679. VectorParts &VecResults = WidenMap.splat(Instr, UndefVec);
  4680. // For each vector unroll 'part':
  4681. for (unsigned Part = 0; Part < UF; ++Part) {
  4682. // For each scalar that we create:
  4683. Instruction *Cloned = Instr->clone();
  4684. if (!IsVoidRetTy)
  4685. Cloned->setName(Instr->getName() + ".cloned");
  4686. // Replace the operands of the cloned instructions with extracted scalars.
  4687. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  4688. Value *Op = Params[op][Part];
  4689. Cloned->setOperand(op, Op);
  4690. }
  4691. // Place the cloned scalar in the new loop.
  4692. Builder.Insert(Cloned);
  4693. // If the original scalar returns a value we need to place it in a vector
  4694. // so that future users will be able to use it.
  4695. if (!IsVoidRetTy)
  4696. VecResults[Part] = Cloned;
  4697. }
  4698. }
  4699. void InnerLoopUnroller::vectorizeMemoryInstruction(Instruction *Instr) {
  4700. return scalarizeInstruction(Instr);
  4701. }
  4702. Value *InnerLoopUnroller::reverseVector(Value *Vec) {
  4703. return Vec;
  4704. }
  4705. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) {
  4706. return V;
  4707. }
  4708. Value *InnerLoopUnroller::getConsecutiveVector(Value* Val, int StartIdx,
  4709. bool Negate) {
  4710. // When unrolling and the VF is 1, we only need to add a simple scalar.
  4711. Type *ITy = Val->getType();
  4712. assert(!ITy->isVectorTy() && "Val must be a scalar");
  4713. Constant *C = ConstantInt::get(ITy, StartIdx, Negate);
  4714. return Builder.CreateAdd(Val, C, "induction");
  4715. }