LoopVectorize.cpp 195 KB

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