LoopVectorize.cpp 205 KB

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