SLPVectorizer.cpp 259 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018
  1. //===- SLPVectorizer.cpp - A bottom up SLP Vectorizer ---------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass implements the Bottom Up SLP vectorizer. It detects consecutive
  10. // stores that can be put together into vector-stores. Next, it attempts to
  11. // construct vectorizable tree using the use-def chains. If a profitable tree
  12. // was found, the SLP vectorizer performs vectorization on the tree.
  13. //
  14. // The pass is inspired by the work described in the paper:
  15. // "Loop-Aware SLP in GCC" by Ira Rosen, Dorit Nuzman, Ayal Zaks.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/DenseSet.h"
  22. #include "llvm/ADT/MapVector.h"
  23. #include "llvm/ADT/None.h"
  24. #include "llvm/ADT/Optional.h"
  25. #include "llvm/ADT/PostOrderIterator.h"
  26. #include "llvm/ADT/STLExtras.h"
  27. #include "llvm/ADT/SetVector.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "llvm/ADT/SmallVector.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/ADT/iterator.h"
  33. #include "llvm/ADT/iterator_range.h"
  34. #include "llvm/Analysis/AliasAnalysis.h"
  35. #include "llvm/Analysis/CodeMetrics.h"
  36. #include "llvm/Analysis/DemandedBits.h"
  37. #include "llvm/Analysis/GlobalsModRef.h"
  38. #include "llvm/Analysis/LoopAccessAnalysis.h"
  39. #include "llvm/Analysis/LoopInfo.h"
  40. #include "llvm/Analysis/MemoryLocation.h"
  41. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  42. #include "llvm/Analysis/ScalarEvolution.h"
  43. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  44. #include "llvm/Analysis/TargetLibraryInfo.h"
  45. #include "llvm/Analysis/TargetTransformInfo.h"
  46. #include "llvm/Analysis/ValueTracking.h"
  47. #include "llvm/Analysis/VectorUtils.h"
  48. #include "llvm/IR/Attributes.h"
  49. #include "llvm/IR/BasicBlock.h"
  50. #include "llvm/IR/Constant.h"
  51. #include "llvm/IR/Constants.h"
  52. #include "llvm/IR/DataLayout.h"
  53. #include "llvm/IR/DebugLoc.h"
  54. #include "llvm/IR/DerivedTypes.h"
  55. #include "llvm/IR/Dominators.h"
  56. #include "llvm/IR/Function.h"
  57. #include "llvm/IR/IRBuilder.h"
  58. #include "llvm/IR/InstrTypes.h"
  59. #include "llvm/IR/Instruction.h"
  60. #include "llvm/IR/Instructions.h"
  61. #include "llvm/IR/IntrinsicInst.h"
  62. #include "llvm/IR/Intrinsics.h"
  63. #include "llvm/IR/Module.h"
  64. #include "llvm/IR/NoFolder.h"
  65. #include "llvm/IR/Operator.h"
  66. #include "llvm/IR/PassManager.h"
  67. #include "llvm/IR/PatternMatch.h"
  68. #include "llvm/IR/Type.h"
  69. #include "llvm/IR/Use.h"
  70. #include "llvm/IR/User.h"
  71. #include "llvm/IR/Value.h"
  72. #include "llvm/IR/ValueHandle.h"
  73. #include "llvm/IR/Verifier.h"
  74. #include "llvm/Pass.h"
  75. #include "llvm/Support/Casting.h"
  76. #include "llvm/Support/CommandLine.h"
  77. #include "llvm/Support/Compiler.h"
  78. #include "llvm/Support/DOTGraphTraits.h"
  79. #include "llvm/Support/Debug.h"
  80. #include "llvm/Support/ErrorHandling.h"
  81. #include "llvm/Support/GraphWriter.h"
  82. #include "llvm/Support/KnownBits.h"
  83. #include "llvm/Support/MathExtras.h"
  84. #include "llvm/Support/raw_ostream.h"
  85. #include "llvm/Transforms/Utils/LoopUtils.h"
  86. #include "llvm/Transforms/Vectorize.h"
  87. #include <algorithm>
  88. #include <cassert>
  89. #include <cstdint>
  90. #include <iterator>
  91. #include <memory>
  92. #include <set>
  93. #include <string>
  94. #include <tuple>
  95. #include <utility>
  96. #include <vector>
  97. using namespace llvm;
  98. using namespace llvm::PatternMatch;
  99. using namespace slpvectorizer;
  100. #define SV_NAME "slp-vectorizer"
  101. #define DEBUG_TYPE "SLP"
  102. STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
  103. cl::opt<bool>
  104. llvm::RunSLPVectorization("vectorize-slp", cl::init(false), cl::Hidden,
  105. cl::desc("Run the SLP vectorization passes"));
  106. static cl::opt<int>
  107. SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
  108. cl::desc("Only vectorize if you gain more than this "
  109. "number "));
  110. static cl::opt<bool>
  111. ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
  112. cl::desc("Attempt to vectorize horizontal reductions"));
  113. static cl::opt<bool> ShouldStartVectorizeHorAtStore(
  114. "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
  115. cl::desc(
  116. "Attempt to vectorize horizontal reductions feeding into a store"));
  117. static cl::opt<int>
  118. MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
  119. cl::desc("Attempt to vectorize for this register size in bits"));
  120. /// Limits the size of scheduling regions in a block.
  121. /// It avoid long compile times for _very_ large blocks where vector
  122. /// instructions are spread over a wide range.
  123. /// This limit is way higher than needed by real-world functions.
  124. static cl::opt<int>
  125. ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
  126. cl::desc("Limit the size of the SLP scheduling region per block"));
  127. static cl::opt<int> MinVectorRegSizeOption(
  128. "slp-min-reg-size", cl::init(128), cl::Hidden,
  129. cl::desc("Attempt to vectorize for this register size in bits"));
  130. static cl::opt<unsigned> RecursionMaxDepth(
  131. "slp-recursion-max-depth", cl::init(12), cl::Hidden,
  132. cl::desc("Limit the recursion depth when building a vectorizable tree"));
  133. static cl::opt<unsigned> MinTreeSize(
  134. "slp-min-tree-size", cl::init(3), cl::Hidden,
  135. cl::desc("Only vectorize small trees if they are fully vectorizable"));
  136. static cl::opt<bool>
  137. ViewSLPTree("view-slp-tree", cl::Hidden,
  138. cl::desc("Display the SLP trees with Graphviz"));
  139. // Limit the number of alias checks. The limit is chosen so that
  140. // it has no negative effect on the llvm benchmarks.
  141. static const unsigned AliasedCheckLimit = 10;
  142. // Another limit for the alias checks: The maximum distance between load/store
  143. // instructions where alias checks are done.
  144. // This limit is useful for very large basic blocks.
  145. static const unsigned MaxMemDepDistance = 160;
  146. /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
  147. /// regions to be handled.
  148. static const int MinScheduleRegionSize = 16;
  149. /// Predicate for the element types that the SLP vectorizer supports.
  150. ///
  151. /// The most important thing to filter here are types which are invalid in LLVM
  152. /// vectors. We also filter target specific types which have absolutely no
  153. /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
  154. /// avoids spending time checking the cost model and realizing that they will
  155. /// be inevitably scalarized.
  156. static bool isValidElementType(Type *Ty) {
  157. return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
  158. !Ty->isPPC_FP128Ty();
  159. }
  160. /// \returns true if all of the instructions in \p VL are in the same block or
  161. /// false otherwise.
  162. static bool allSameBlock(ArrayRef<Value *> VL) {
  163. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  164. if (!I0)
  165. return false;
  166. BasicBlock *BB = I0->getParent();
  167. for (int i = 1, e = VL.size(); i < e; i++) {
  168. Instruction *I = dyn_cast<Instruction>(VL[i]);
  169. if (!I)
  170. return false;
  171. if (BB != I->getParent())
  172. return false;
  173. }
  174. return true;
  175. }
  176. /// \returns True if all of the values in \p VL are constants.
  177. static bool allConstant(ArrayRef<Value *> VL) {
  178. for (Value *i : VL)
  179. if (!isa<Constant>(i))
  180. return false;
  181. return true;
  182. }
  183. /// \returns True if all of the values in \p VL are identical.
  184. static bool isSplat(ArrayRef<Value *> VL) {
  185. for (unsigned i = 1, e = VL.size(); i < e; ++i)
  186. if (VL[i] != VL[0])
  187. return false;
  188. return true;
  189. }
  190. /// \returns True if \p I is commutative, handles CmpInst as well as Instruction.
  191. static bool isCommutative(Instruction *I) {
  192. if (auto *IC = dyn_cast<CmpInst>(I))
  193. return IC->isCommutative();
  194. return I->isCommutative();
  195. }
  196. /// Checks if the vector of instructions can be represented as a shuffle, like:
  197. /// %x0 = extractelement <4 x i8> %x, i32 0
  198. /// %x3 = extractelement <4 x i8> %x, i32 3
  199. /// %y1 = extractelement <4 x i8> %y, i32 1
  200. /// %y2 = extractelement <4 x i8> %y, i32 2
  201. /// %x0x0 = mul i8 %x0, %x0
  202. /// %x3x3 = mul i8 %x3, %x3
  203. /// %y1y1 = mul i8 %y1, %y1
  204. /// %y2y2 = mul i8 %y2, %y2
  205. /// %ins1 = insertelement <4 x i8> undef, i8 %x0x0, i32 0
  206. /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
  207. /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
  208. /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
  209. /// ret <4 x i8> %ins4
  210. /// can be transformed into:
  211. /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
  212. /// i32 6>
  213. /// %2 = mul <4 x i8> %1, %1
  214. /// ret <4 x i8> %2
  215. /// We convert this initially to something like:
  216. /// %x0 = extractelement <4 x i8> %x, i32 0
  217. /// %x3 = extractelement <4 x i8> %x, i32 3
  218. /// %y1 = extractelement <4 x i8> %y, i32 1
  219. /// %y2 = extractelement <4 x i8> %y, i32 2
  220. /// %1 = insertelement <4 x i8> undef, i8 %x0, i32 0
  221. /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
  222. /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
  223. /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
  224. /// %5 = mul <4 x i8> %4, %4
  225. /// %6 = extractelement <4 x i8> %5, i32 0
  226. /// %ins1 = insertelement <4 x i8> undef, i8 %6, i32 0
  227. /// %7 = extractelement <4 x i8> %5, i32 1
  228. /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
  229. /// %8 = extractelement <4 x i8> %5, i32 2
  230. /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
  231. /// %9 = extractelement <4 x i8> %5, i32 3
  232. /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
  233. /// ret <4 x i8> %ins4
  234. /// InstCombiner transforms this into a shuffle and vector mul
  235. /// TODO: Can we split off and reuse the shuffle mask detection from
  236. /// TargetTransformInfo::getInstructionThroughput?
  237. static Optional<TargetTransformInfo::ShuffleKind>
  238. isShuffle(ArrayRef<Value *> VL) {
  239. auto *EI0 = cast<ExtractElementInst>(VL[0]);
  240. unsigned Size = EI0->getVectorOperandType()->getVectorNumElements();
  241. Value *Vec1 = nullptr;
  242. Value *Vec2 = nullptr;
  243. enum ShuffleMode { Unknown, Select, Permute };
  244. ShuffleMode CommonShuffleMode = Unknown;
  245. for (unsigned I = 0, E = VL.size(); I < E; ++I) {
  246. auto *EI = cast<ExtractElementInst>(VL[I]);
  247. auto *Vec = EI->getVectorOperand();
  248. // All vector operands must have the same number of vector elements.
  249. if (Vec->getType()->getVectorNumElements() != Size)
  250. return None;
  251. auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
  252. if (!Idx)
  253. return None;
  254. // Undefined behavior if Idx is negative or >= Size.
  255. if (Idx->getValue().uge(Size))
  256. continue;
  257. unsigned IntIdx = Idx->getValue().getZExtValue();
  258. // We can extractelement from undef vector.
  259. if (isa<UndefValue>(Vec))
  260. continue;
  261. // For correct shuffling we have to have at most 2 different vector operands
  262. // in all extractelement instructions.
  263. if (!Vec1 || Vec1 == Vec)
  264. Vec1 = Vec;
  265. else if (!Vec2 || Vec2 == Vec)
  266. Vec2 = Vec;
  267. else
  268. return None;
  269. if (CommonShuffleMode == Permute)
  270. continue;
  271. // If the extract index is not the same as the operation number, it is a
  272. // permutation.
  273. if (IntIdx != I) {
  274. CommonShuffleMode = Permute;
  275. continue;
  276. }
  277. CommonShuffleMode = Select;
  278. }
  279. // If we're not crossing lanes in different vectors, consider it as blending.
  280. if (CommonShuffleMode == Select && Vec2)
  281. return TargetTransformInfo::SK_Select;
  282. // If Vec2 was never used, we have a permutation of a single vector, otherwise
  283. // we have permutation of 2 vectors.
  284. return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
  285. : TargetTransformInfo::SK_PermuteSingleSrc;
  286. }
  287. namespace {
  288. /// Main data required for vectorization of instructions.
  289. struct InstructionsState {
  290. /// The very first instruction in the list with the main opcode.
  291. Value *OpValue = nullptr;
  292. /// The main/alternate instruction.
  293. Instruction *MainOp = nullptr;
  294. Instruction *AltOp = nullptr;
  295. /// The main/alternate opcodes for the list of instructions.
  296. unsigned getOpcode() const {
  297. return MainOp ? MainOp->getOpcode() : 0;
  298. }
  299. unsigned getAltOpcode() const {
  300. return AltOp ? AltOp->getOpcode() : 0;
  301. }
  302. /// Some of the instructions in the list have alternate opcodes.
  303. bool isAltShuffle() const { return getOpcode() != getAltOpcode(); }
  304. bool isOpcodeOrAlt(Instruction *I) const {
  305. unsigned CheckedOpcode = I->getOpcode();
  306. return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
  307. }
  308. InstructionsState() = delete;
  309. InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
  310. : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
  311. };
  312. } // end anonymous namespace
  313. /// Chooses the correct key for scheduling data. If \p Op has the same (or
  314. /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
  315. /// OpValue.
  316. static Value *isOneOf(const InstructionsState &S, Value *Op) {
  317. auto *I = dyn_cast<Instruction>(Op);
  318. if (I && S.isOpcodeOrAlt(I))
  319. return Op;
  320. return S.OpValue;
  321. }
  322. /// \returns analysis of the Instructions in \p VL described in
  323. /// InstructionsState, the Opcode that we suppose the whole list
  324. /// could be vectorized even if its structure is diverse.
  325. static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
  326. unsigned BaseIndex = 0) {
  327. // Make sure these are all Instructions.
  328. if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
  329. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  330. bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
  331. bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
  332. unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
  333. unsigned AltOpcode = Opcode;
  334. unsigned AltIndex = BaseIndex;
  335. // Check for one alternate opcode from another BinaryOperator.
  336. // TODO - generalize to support all operators (types, calls etc.).
  337. for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
  338. unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
  339. if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
  340. if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  341. continue;
  342. if (Opcode == AltOpcode) {
  343. AltOpcode = InstOpcode;
  344. AltIndex = Cnt;
  345. continue;
  346. }
  347. } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
  348. Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
  349. Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
  350. if (Ty0 == Ty1) {
  351. if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  352. continue;
  353. if (Opcode == AltOpcode) {
  354. AltOpcode = InstOpcode;
  355. AltIndex = Cnt;
  356. continue;
  357. }
  358. }
  359. } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  360. continue;
  361. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  362. }
  363. return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
  364. cast<Instruction>(VL[AltIndex]));
  365. }
  366. /// \returns true if all of the values in \p VL have the same type or false
  367. /// otherwise.
  368. static bool allSameType(ArrayRef<Value *> VL) {
  369. Type *Ty = VL[0]->getType();
  370. for (int i = 1, e = VL.size(); i < e; i++)
  371. if (VL[i]->getType() != Ty)
  372. return false;
  373. return true;
  374. }
  375. /// \returns True if Extract{Value,Element} instruction extracts element Idx.
  376. static Optional<unsigned> getExtractIndex(Instruction *E) {
  377. unsigned Opcode = E->getOpcode();
  378. assert((Opcode == Instruction::ExtractElement ||
  379. Opcode == Instruction::ExtractValue) &&
  380. "Expected extractelement or extractvalue instruction.");
  381. if (Opcode == Instruction::ExtractElement) {
  382. auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
  383. if (!CI)
  384. return None;
  385. return CI->getZExtValue();
  386. }
  387. ExtractValueInst *EI = cast<ExtractValueInst>(E);
  388. if (EI->getNumIndices() != 1)
  389. return None;
  390. return *EI->idx_begin();
  391. }
  392. /// \returns True if in-tree use also needs extract. This refers to
  393. /// possible scalar operand in vectorized instruction.
  394. static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
  395. TargetLibraryInfo *TLI) {
  396. unsigned Opcode = UserInst->getOpcode();
  397. switch (Opcode) {
  398. case Instruction::Load: {
  399. LoadInst *LI = cast<LoadInst>(UserInst);
  400. return (LI->getPointerOperand() == Scalar);
  401. }
  402. case Instruction::Store: {
  403. StoreInst *SI = cast<StoreInst>(UserInst);
  404. return (SI->getPointerOperand() == Scalar);
  405. }
  406. case Instruction::Call: {
  407. CallInst *CI = cast<CallInst>(UserInst);
  408. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  409. for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
  410. if (hasVectorInstrinsicScalarOpd(ID, i))
  411. return (CI->getArgOperand(i) == Scalar);
  412. }
  413. LLVM_FALLTHROUGH;
  414. }
  415. default:
  416. return false;
  417. }
  418. }
  419. /// \returns the AA location that is being access by the instruction.
  420. static MemoryLocation getLocation(Instruction *I, AliasAnalysis *AA) {
  421. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  422. return MemoryLocation::get(SI);
  423. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  424. return MemoryLocation::get(LI);
  425. return MemoryLocation();
  426. }
  427. /// \returns True if the instruction is not a volatile or atomic load/store.
  428. static bool isSimple(Instruction *I) {
  429. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  430. return LI->isSimple();
  431. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  432. return SI->isSimple();
  433. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
  434. return !MI->isVolatile();
  435. return true;
  436. }
  437. namespace llvm {
  438. namespace slpvectorizer {
  439. /// Bottom Up SLP Vectorizer.
  440. class BoUpSLP {
  441. struct TreeEntry;
  442. struct ScheduleData;
  443. public:
  444. using ValueList = SmallVector<Value *, 8>;
  445. using InstrList = SmallVector<Instruction *, 16>;
  446. using ValueSet = SmallPtrSet<Value *, 16>;
  447. using StoreList = SmallVector<StoreInst *, 8>;
  448. using ExtraValueToDebugLocsMap =
  449. MapVector<Value *, SmallVector<Instruction *, 2>>;
  450. BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
  451. TargetLibraryInfo *TLi, AliasAnalysis *Aa, LoopInfo *Li,
  452. DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
  453. const DataLayout *DL, OptimizationRemarkEmitter *ORE)
  454. : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
  455. DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
  456. CodeMetrics::collectEphemeralValues(F, AC, EphValues);
  457. // Use the vector register size specified by the target unless overridden
  458. // by a command-line option.
  459. // TODO: It would be better to limit the vectorization factor based on
  460. // data type rather than just register size. For example, x86 AVX has
  461. // 256-bit registers, but it does not support integer operations
  462. // at that width (that requires AVX2).
  463. if (MaxVectorRegSizeOption.getNumOccurrences())
  464. MaxVecRegSize = MaxVectorRegSizeOption;
  465. else
  466. MaxVecRegSize = TTI->getRegisterBitWidth(true);
  467. if (MinVectorRegSizeOption.getNumOccurrences())
  468. MinVecRegSize = MinVectorRegSizeOption;
  469. else
  470. MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
  471. }
  472. /// Vectorize the tree that starts with the elements in \p VL.
  473. /// Returns the vectorized root.
  474. Value *vectorizeTree();
  475. /// Vectorize the tree but with the list of externally used values \p
  476. /// ExternallyUsedValues. Values in this MapVector can be replaced but the
  477. /// generated extractvalue instructions.
  478. Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
  479. /// \returns the cost incurred by unwanted spills and fills, caused by
  480. /// holding live values over call sites.
  481. int getSpillCost() const;
  482. /// \returns the vectorization cost of the subtree that starts at \p VL.
  483. /// A negative number means that this is profitable.
  484. int getTreeCost();
  485. /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
  486. /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
  487. void buildTree(ArrayRef<Value *> Roots,
  488. ArrayRef<Value *> UserIgnoreLst = None);
  489. /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
  490. /// the purpose of scheduling and extraction in the \p UserIgnoreLst taking
  491. /// into account (anf updating it, if required) list of externally used
  492. /// values stored in \p ExternallyUsedValues.
  493. void buildTree(ArrayRef<Value *> Roots,
  494. ExtraValueToDebugLocsMap &ExternallyUsedValues,
  495. ArrayRef<Value *> UserIgnoreLst = None);
  496. /// Clear the internal data structures that are created by 'buildTree'.
  497. void deleteTree() {
  498. VectorizableTree.clear();
  499. ScalarToTreeEntry.clear();
  500. MustGather.clear();
  501. ExternalUses.clear();
  502. NumOpsWantToKeepOrder.clear();
  503. NumOpsWantToKeepOriginalOrder = 0;
  504. for (auto &Iter : BlocksSchedules) {
  505. BlockScheduling *BS = Iter.second.get();
  506. BS->clear();
  507. }
  508. MinBWs.clear();
  509. }
  510. unsigned getTreeSize() const { return VectorizableTree.size(); }
  511. /// Perform LICM and CSE on the newly generated gather sequences.
  512. void optimizeGatherSequence();
  513. /// \returns The best order of instructions for vectorization.
  514. Optional<ArrayRef<unsigned>> bestOrder() const {
  515. auto I = std::max_element(
  516. NumOpsWantToKeepOrder.begin(), NumOpsWantToKeepOrder.end(),
  517. [](const decltype(NumOpsWantToKeepOrder)::value_type &D1,
  518. const decltype(NumOpsWantToKeepOrder)::value_type &D2) {
  519. return D1.second < D2.second;
  520. });
  521. if (I == NumOpsWantToKeepOrder.end() ||
  522. I->getSecond() <= NumOpsWantToKeepOriginalOrder)
  523. return None;
  524. return makeArrayRef(I->getFirst());
  525. }
  526. /// \return The vector element size in bits to use when vectorizing the
  527. /// expression tree ending at \p V. If V is a store, the size is the width of
  528. /// the stored value. Otherwise, the size is the width of the largest loaded
  529. /// value reaching V. This method is used by the vectorizer to calculate
  530. /// vectorization factors.
  531. unsigned getVectorElementSize(Value *V) const;
  532. /// Compute the minimum type sizes required to represent the entries in a
  533. /// vectorizable tree.
  534. void computeMinimumValueSizes();
  535. // \returns maximum vector register size as set by TTI or overridden by cl::opt.
  536. unsigned getMaxVecRegSize() const {
  537. return MaxVecRegSize;
  538. }
  539. // \returns minimum vector register size as set by cl::opt.
  540. unsigned getMinVecRegSize() const {
  541. return MinVecRegSize;
  542. }
  543. /// Check if ArrayType or StructType is isomorphic to some VectorType.
  544. ///
  545. /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
  546. unsigned canMapToVector(Type *T, const DataLayout &DL) const;
  547. /// \returns True if the VectorizableTree is both tiny and not fully
  548. /// vectorizable. We do not vectorize such trees.
  549. bool isTreeTinyAndNotFullyVectorizable() const;
  550. OptimizationRemarkEmitter *getORE() { return ORE; }
  551. /// This structure holds any data we need about the edges being traversed
  552. /// during buildTree_rec(). We keep track of:
  553. /// (i) the user TreeEntry index, and
  554. /// (ii) the index of the edge.
  555. struct EdgeInfo {
  556. EdgeInfo() = default;
  557. EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
  558. : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
  559. /// The user TreeEntry.
  560. TreeEntry *UserTE = nullptr;
  561. /// The operand index of the use.
  562. unsigned EdgeIdx = UINT_MAX;
  563. #ifndef NDEBUG
  564. friend inline raw_ostream &operator<<(raw_ostream &OS,
  565. const BoUpSLP::EdgeInfo &EI) {
  566. EI.dump(OS);
  567. return OS;
  568. }
  569. /// Debug print.
  570. void dump(raw_ostream &OS) const {
  571. OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
  572. << " EdgeIdx:" << EdgeIdx << "}";
  573. }
  574. LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
  575. #endif
  576. };
  577. /// A helper data structure to hold the operands of a vector of instructions.
  578. /// This supports a fixed vector length for all operand vectors.
  579. class VLOperands {
  580. /// For each operand we need (i) the value, and (ii) the opcode that it
  581. /// would be attached to if the expression was in a left-linearized form.
  582. /// This is required to avoid illegal operand reordering.
  583. /// For example:
  584. /// \verbatim
  585. /// 0 Op1
  586. /// |/
  587. /// Op1 Op2 Linearized + Op2
  588. /// \ / ----------> |/
  589. /// - -
  590. ///
  591. /// Op1 - Op2 (0 + Op1) - Op2
  592. /// \endverbatim
  593. ///
  594. /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
  595. ///
  596. /// Another way to think of this is to track all the operations across the
  597. /// path from the operand all the way to the root of the tree and to
  598. /// calculate the operation that corresponds to this path. For example, the
  599. /// path from Op2 to the root crosses the RHS of the '-', therefore the
  600. /// corresponding operation is a '-' (which matches the one in the
  601. /// linearized tree, as shown above).
  602. ///
  603. /// For lack of a better term, we refer to this operation as Accumulated
  604. /// Path Operation (APO).
  605. struct OperandData {
  606. OperandData() = default;
  607. OperandData(Value *V, bool APO, bool IsUsed)
  608. : V(V), APO(APO), IsUsed(IsUsed) {}
  609. /// The operand value.
  610. Value *V = nullptr;
  611. /// TreeEntries only allow a single opcode, or an alternate sequence of
  612. /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
  613. /// APO. It is set to 'true' if 'V' is attached to an inverse operation
  614. /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
  615. /// (e.g., Add/Mul)
  616. bool APO = false;
  617. /// Helper data for the reordering function.
  618. bool IsUsed = false;
  619. };
  620. /// During operand reordering, we are trying to select the operand at lane
  621. /// that matches best with the operand at the neighboring lane. Our
  622. /// selection is based on the type of value we are looking for. For example,
  623. /// if the neighboring lane has a load, we need to look for a load that is
  624. /// accessing a consecutive address. These strategies are summarized in the
  625. /// 'ReorderingMode' enumerator.
  626. enum class ReorderingMode {
  627. Load, ///< Matching loads to consecutive memory addresses
  628. Opcode, ///< Matching instructions based on opcode (same or alternate)
  629. Constant, ///< Matching constants
  630. Splat, ///< Matching the same instruction multiple times (broadcast)
  631. Failed, ///< We failed to create a vectorizable group
  632. };
  633. using OperandDataVec = SmallVector<OperandData, 2>;
  634. /// A vector of operand vectors.
  635. SmallVector<OperandDataVec, 4> OpsVec;
  636. const DataLayout &DL;
  637. ScalarEvolution &SE;
  638. /// \returns the operand data at \p OpIdx and \p Lane.
  639. OperandData &getData(unsigned OpIdx, unsigned Lane) {
  640. return OpsVec[OpIdx][Lane];
  641. }
  642. /// \returns the operand data at \p OpIdx and \p Lane. Const version.
  643. const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
  644. return OpsVec[OpIdx][Lane];
  645. }
  646. /// Clears the used flag for all entries.
  647. void clearUsed() {
  648. for (unsigned OpIdx = 0, NumOperands = getNumOperands();
  649. OpIdx != NumOperands; ++OpIdx)
  650. for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
  651. ++Lane)
  652. OpsVec[OpIdx][Lane].IsUsed = false;
  653. }
  654. /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
  655. void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
  656. std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
  657. }
  658. // Search all operands in Ops[*][Lane] for the one that matches best
  659. // Ops[OpIdx][LastLane] and return its opreand index.
  660. // If no good match can be found, return None.
  661. Optional<unsigned>
  662. getBestOperand(unsigned OpIdx, int Lane, int LastLane,
  663. ArrayRef<ReorderingMode> ReorderingModes) {
  664. unsigned NumOperands = getNumOperands();
  665. // The operand of the previous lane at OpIdx.
  666. Value *OpLastLane = getData(OpIdx, LastLane).V;
  667. // Our strategy mode for OpIdx.
  668. ReorderingMode RMode = ReorderingModes[OpIdx];
  669. // The linearized opcode of the operand at OpIdx, Lane.
  670. bool OpIdxAPO = getData(OpIdx, Lane).APO;
  671. const unsigned BestScore = 2;
  672. const unsigned GoodScore = 1;
  673. // The best operand index and its score.
  674. // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
  675. // are using the score to differentiate between the two.
  676. struct BestOpData {
  677. Optional<unsigned> Idx = None;
  678. unsigned Score = 0;
  679. } BestOp;
  680. // Iterate through all unused operands and look for the best.
  681. for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
  682. // Get the operand at Idx and Lane.
  683. OperandData &OpData = getData(Idx, Lane);
  684. Value *Op = OpData.V;
  685. bool OpAPO = OpData.APO;
  686. // Skip already selected operands.
  687. if (OpData.IsUsed)
  688. continue;
  689. // Skip if we are trying to move the operand to a position with a
  690. // different opcode in the linearized tree form. This would break the
  691. // semantics.
  692. if (OpAPO != OpIdxAPO)
  693. continue;
  694. // Look for an operand that matches the current mode.
  695. switch (RMode) {
  696. case ReorderingMode::Load:
  697. if (isa<LoadInst>(Op)) {
  698. // Figure out which is left and right, so that we can check for
  699. // consecutive loads
  700. bool LeftToRight = Lane > LastLane;
  701. Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
  702. Value *OpRight = (LeftToRight) ? Op : OpLastLane;
  703. if (isConsecutiveAccess(cast<LoadInst>(OpLeft),
  704. cast<LoadInst>(OpRight), DL, SE))
  705. BestOp.Idx = Idx;
  706. }
  707. break;
  708. case ReorderingMode::Opcode:
  709. // We accept both Instructions and Undefs, but with different scores.
  710. if ((isa<Instruction>(Op) && isa<Instruction>(OpLastLane) &&
  711. cast<Instruction>(Op)->getOpcode() ==
  712. cast<Instruction>(OpLastLane)->getOpcode()) ||
  713. (isa<UndefValue>(OpLastLane) && isa<Instruction>(Op)) ||
  714. isa<UndefValue>(Op)) {
  715. // An instruction has a higher score than an undef.
  716. unsigned Score = (isa<UndefValue>(Op)) ? GoodScore : BestScore;
  717. if (Score > BestOp.Score) {
  718. BestOp.Idx = Idx;
  719. BestOp.Score = Score;
  720. }
  721. }
  722. break;
  723. case ReorderingMode::Constant:
  724. if (isa<Constant>(Op)) {
  725. unsigned Score = (isa<UndefValue>(Op)) ? GoodScore : BestScore;
  726. if (Score > BestOp.Score) {
  727. BestOp.Idx = Idx;
  728. BestOp.Score = Score;
  729. }
  730. }
  731. break;
  732. case ReorderingMode::Splat:
  733. if (Op == OpLastLane)
  734. BestOp.Idx = Idx;
  735. break;
  736. case ReorderingMode::Failed:
  737. return None;
  738. }
  739. }
  740. if (BestOp.Idx) {
  741. getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
  742. return BestOp.Idx;
  743. }
  744. // If we could not find a good match return None.
  745. return None;
  746. }
  747. /// Helper for reorderOperandVecs. \Returns the lane that we should start
  748. /// reordering from. This is the one which has the least number of operands
  749. /// that can freely move about.
  750. unsigned getBestLaneToStartReordering() const {
  751. unsigned BestLane = 0;
  752. unsigned Min = UINT_MAX;
  753. for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
  754. ++Lane) {
  755. unsigned NumFreeOps = getMaxNumOperandsThatCanBeReordered(Lane);
  756. if (NumFreeOps < Min) {
  757. Min = NumFreeOps;
  758. BestLane = Lane;
  759. }
  760. }
  761. return BestLane;
  762. }
  763. /// \Returns the maximum number of operands that are allowed to be reordered
  764. /// for \p Lane. This is used as a heuristic for selecting the first lane to
  765. /// start operand reordering.
  766. unsigned getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
  767. unsigned CntTrue = 0;
  768. unsigned NumOperands = getNumOperands();
  769. // Operands with the same APO can be reordered. We therefore need to count
  770. // how many of them we have for each APO, like this: Cnt[APO] = x.
  771. // Since we only have two APOs, namely true and false, we can avoid using
  772. // a map. Instead we can simply count the number of operands that
  773. // correspond to one of them (in this case the 'true' APO), and calculate
  774. // the other by subtracting it from the total number of operands.
  775. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx)
  776. if (getData(OpIdx, Lane).APO)
  777. ++CntTrue;
  778. unsigned CntFalse = NumOperands - CntTrue;
  779. return std::max(CntTrue, CntFalse);
  780. }
  781. /// Go through the instructions in VL and append their operands.
  782. void appendOperandsOfVL(ArrayRef<Value *> VL) {
  783. assert(!VL.empty() && "Bad VL");
  784. assert((empty() || VL.size() == getNumLanes()) &&
  785. "Expected same number of lanes");
  786. assert(isa<Instruction>(VL[0]) && "Expected instruction");
  787. unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
  788. OpsVec.resize(NumOperands);
  789. unsigned NumLanes = VL.size();
  790. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  791. OpsVec[OpIdx].resize(NumLanes);
  792. for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
  793. assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
  794. // Our tree has just 3 nodes: the root and two operands.
  795. // It is therefore trivial to get the APO. We only need to check the
  796. // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
  797. // RHS operand. The LHS operand of both add and sub is never attached
  798. // to an inversese operation in the linearized form, therefore its APO
  799. // is false. The RHS is true only if VL[Lane] is an inverse operation.
  800. // Since operand reordering is performed on groups of commutative
  801. // operations or alternating sequences (e.g., +, -), we can safely
  802. // tell the inverse operations by checking commutativity.
  803. bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
  804. bool APO = (OpIdx == 0) ? false : IsInverseOperation;
  805. OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
  806. APO, false};
  807. }
  808. }
  809. }
  810. /// \returns the number of operands.
  811. unsigned getNumOperands() const { return OpsVec.size(); }
  812. /// \returns the number of lanes.
  813. unsigned getNumLanes() const { return OpsVec[0].size(); }
  814. /// \returns the operand value at \p OpIdx and \p Lane.
  815. Value *getValue(unsigned OpIdx, unsigned Lane) const {
  816. return getData(OpIdx, Lane).V;
  817. }
  818. /// \returns true if the data structure is empty.
  819. bool empty() const { return OpsVec.empty(); }
  820. /// Clears the data.
  821. void clear() { OpsVec.clear(); }
  822. /// \Returns true if there are enough operands identical to \p Op to fill
  823. /// the whole vector.
  824. /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
  825. bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
  826. bool OpAPO = getData(OpIdx, Lane).APO;
  827. for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
  828. if (Ln == Lane)
  829. continue;
  830. // This is set to true if we found a candidate for broadcast at Lane.
  831. bool FoundCandidate = false;
  832. for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
  833. OperandData &Data = getData(OpI, Ln);
  834. if (Data.APO != OpAPO || Data.IsUsed)
  835. continue;
  836. if (Data.V == Op) {
  837. FoundCandidate = true;
  838. Data.IsUsed = true;
  839. break;
  840. }
  841. }
  842. if (!FoundCandidate)
  843. return false;
  844. }
  845. return true;
  846. }
  847. public:
  848. /// Initialize with all the operands of the instruction vector \p RootVL.
  849. VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
  850. ScalarEvolution &SE)
  851. : DL(DL), SE(SE) {
  852. // Append all the operands of RootVL.
  853. appendOperandsOfVL(RootVL);
  854. }
  855. /// \Returns a value vector with the operands across all lanes for the
  856. /// opearnd at \p OpIdx.
  857. ValueList getVL(unsigned OpIdx) const {
  858. ValueList OpVL(OpsVec[OpIdx].size());
  859. assert(OpsVec[OpIdx].size() == getNumLanes() &&
  860. "Expected same num of lanes across all operands");
  861. for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
  862. OpVL[Lane] = OpsVec[OpIdx][Lane].V;
  863. return OpVL;
  864. }
  865. // Performs operand reordering for 2 or more operands.
  866. // The original operands are in OrigOps[OpIdx][Lane].
  867. // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
  868. void reorder() {
  869. unsigned NumOperands = getNumOperands();
  870. unsigned NumLanes = getNumLanes();
  871. // Each operand has its own mode. We are using this mode to help us select
  872. // the instructions for each lane, so that they match best with the ones
  873. // we have selected so far.
  874. SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
  875. // This is a greedy single-pass algorithm. We are going over each lane
  876. // once and deciding on the best order right away with no back-tracking.
  877. // However, in order to increase its effectiveness, we start with the lane
  878. // that has operands that can move the least. For example, given the
  879. // following lanes:
  880. // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
  881. // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
  882. // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
  883. // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
  884. // we will start at Lane 1, since the operands of the subtraction cannot
  885. // be reordered. Then we will visit the rest of the lanes in a circular
  886. // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
  887. // Find the first lane that we will start our search from.
  888. unsigned FirstLane = getBestLaneToStartReordering();
  889. // Initialize the modes.
  890. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  891. Value *OpLane0 = getValue(OpIdx, FirstLane);
  892. // Keep track if we have instructions with all the same opcode on one
  893. // side.
  894. if (isa<LoadInst>(OpLane0))
  895. ReorderingModes[OpIdx] = ReorderingMode::Load;
  896. else if (isa<Instruction>(OpLane0)) {
  897. // Check if OpLane0 should be broadcast.
  898. if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
  899. ReorderingModes[OpIdx] = ReorderingMode::Splat;
  900. else
  901. ReorderingModes[OpIdx] = ReorderingMode::Opcode;
  902. }
  903. else if (isa<Constant>(OpLane0))
  904. ReorderingModes[OpIdx] = ReorderingMode::Constant;
  905. else if (isa<Argument>(OpLane0))
  906. // Our best hope is a Splat. It may save some cost in some cases.
  907. ReorderingModes[OpIdx] = ReorderingMode::Splat;
  908. else
  909. // NOTE: This should be unreachable.
  910. ReorderingModes[OpIdx] = ReorderingMode::Failed;
  911. }
  912. // If the initial strategy fails for any of the operand indexes, then we
  913. // perform reordering again in a second pass. This helps avoid assigning
  914. // high priority to the failed strategy, and should improve reordering for
  915. // the non-failed operand indexes.
  916. for (int Pass = 0; Pass != 2; ++Pass) {
  917. // Skip the second pass if the first pass did not fail.
  918. bool StrategyFailed = false;
  919. // Mark all operand data as free to use.
  920. clearUsed();
  921. // We keep the original operand order for the FirstLane, so reorder the
  922. // rest of the lanes. We are visiting the nodes in a circular fashion,
  923. // using FirstLane as the center point and increasing the radius
  924. // distance.
  925. for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
  926. // Visit the lane on the right and then the lane on the left.
  927. for (int Direction : {+1, -1}) {
  928. int Lane = FirstLane + Direction * Distance;
  929. if (Lane < 0 || Lane >= (int)NumLanes)
  930. continue;
  931. int LastLane = Lane - Direction;
  932. assert(LastLane >= 0 && LastLane < (int)NumLanes &&
  933. "Out of bounds");
  934. // Look for a good match for each operand.
  935. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  936. // Search for the operand that matches SortedOps[OpIdx][Lane-1].
  937. Optional<unsigned> BestIdx =
  938. getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
  939. // By not selecting a value, we allow the operands that follow to
  940. // select a better matching value. We will get a non-null value in
  941. // the next run of getBestOperand().
  942. if (BestIdx) {
  943. // Swap the current operand with the one returned by
  944. // getBestOperand().
  945. swap(OpIdx, BestIdx.getValue(), Lane);
  946. } else {
  947. // We failed to find a best operand, set mode to 'Failed'.
  948. ReorderingModes[OpIdx] = ReorderingMode::Failed;
  949. // Enable the second pass.
  950. StrategyFailed = true;
  951. }
  952. }
  953. }
  954. }
  955. // Skip second pass if the strategy did not fail.
  956. if (!StrategyFailed)
  957. break;
  958. }
  959. }
  960. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  961. LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
  962. switch (RMode) {
  963. case ReorderingMode::Load:
  964. return "Load";
  965. case ReorderingMode::Opcode:
  966. return "Opcode";
  967. case ReorderingMode::Constant:
  968. return "Constant";
  969. case ReorderingMode::Splat:
  970. return "Splat";
  971. case ReorderingMode::Failed:
  972. return "Failed";
  973. }
  974. llvm_unreachable("Unimplemented Reordering Type");
  975. }
  976. LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
  977. raw_ostream &OS) {
  978. return OS << getModeStr(RMode);
  979. }
  980. /// Debug print.
  981. LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
  982. printMode(RMode, dbgs());
  983. }
  984. friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
  985. return printMode(RMode, OS);
  986. }
  987. LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
  988. const unsigned Indent = 2;
  989. unsigned Cnt = 0;
  990. for (const OperandDataVec &OpDataVec : OpsVec) {
  991. OS << "Operand " << Cnt++ << "\n";
  992. for (const OperandData &OpData : OpDataVec) {
  993. OS.indent(Indent) << "{";
  994. if (Value *V = OpData.V)
  995. OS << *V;
  996. else
  997. OS << "null";
  998. OS << ", APO:" << OpData.APO << "}\n";
  999. }
  1000. OS << "\n";
  1001. }
  1002. return OS;
  1003. }
  1004. /// Debug print.
  1005. LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
  1006. #endif
  1007. };
  1008. private:
  1009. /// Checks if all users of \p I are the part of the vectorization tree.
  1010. bool areAllUsersVectorized(Instruction *I) const;
  1011. /// \returns the cost of the vectorizable entry.
  1012. int getEntryCost(TreeEntry *E);
  1013. /// This is the recursive part of buildTree.
  1014. void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
  1015. const EdgeInfo &EI);
  1016. /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
  1017. /// be vectorized to use the original vector (or aggregate "bitcast" to a
  1018. /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
  1019. /// returns false, setting \p CurrentOrder to either an empty vector or a
  1020. /// non-identity permutation that allows to reuse extract instructions.
  1021. bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
  1022. SmallVectorImpl<unsigned> &CurrentOrder) const;
  1023. /// Vectorize a single entry in the tree.
  1024. Value *vectorizeTree(TreeEntry *E);
  1025. /// Vectorize a single entry in the tree, starting in \p VL.
  1026. Value *vectorizeTree(ArrayRef<Value *> VL);
  1027. /// \returns the scalarization cost for this type. Scalarization in this
  1028. /// context means the creation of vectors from a group of scalars.
  1029. int getGatherCost(Type *Ty, const DenseSet<unsigned> &ShuffledIndices) const;
  1030. /// \returns the scalarization cost for this list of values. Assuming that
  1031. /// this subtree gets vectorized, we may need to extract the values from the
  1032. /// roots. This method calculates the cost of extracting the values.
  1033. int getGatherCost(ArrayRef<Value *> VL) const;
  1034. /// Set the Builder insert point to one after the last instruction in
  1035. /// the bundle
  1036. void setInsertPointAfterBundle(ArrayRef<Value *> VL,
  1037. const InstructionsState &S);
  1038. /// \returns a vector from a collection of scalars in \p VL.
  1039. Value *Gather(ArrayRef<Value *> VL, VectorType *Ty);
  1040. /// \returns whether the VectorizableTree is fully vectorizable and will
  1041. /// be beneficial even the tree height is tiny.
  1042. bool isFullyVectorizableTinyTree() const;
  1043. /// Reorder commutative or alt operands to get better probability of
  1044. /// generating vectorized code.
  1045. static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
  1046. SmallVectorImpl<Value *> &Left,
  1047. SmallVectorImpl<Value *> &Right,
  1048. const DataLayout &DL,
  1049. ScalarEvolution &SE);
  1050. struct TreeEntry {
  1051. using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
  1052. TreeEntry(VecTreeTy &Container) : Container(Container) {}
  1053. /// \returns true if the scalars in VL are equal to this entry.
  1054. bool isSame(ArrayRef<Value *> VL) const {
  1055. if (VL.size() == Scalars.size())
  1056. return std::equal(VL.begin(), VL.end(), Scalars.begin());
  1057. return VL.size() == ReuseShuffleIndices.size() &&
  1058. std::equal(
  1059. VL.begin(), VL.end(), ReuseShuffleIndices.begin(),
  1060. [this](Value *V, unsigned Idx) { return V == Scalars[Idx]; });
  1061. }
  1062. /// A vector of scalars.
  1063. ValueList Scalars;
  1064. /// The Scalars are vectorized into this value. It is initialized to Null.
  1065. Value *VectorizedValue = nullptr;
  1066. /// Do we need to gather this sequence ?
  1067. bool NeedToGather = false;
  1068. /// Does this sequence require some shuffling?
  1069. SmallVector<unsigned, 4> ReuseShuffleIndices;
  1070. /// Does this entry require reordering?
  1071. ArrayRef<unsigned> ReorderIndices;
  1072. /// Points back to the VectorizableTree.
  1073. ///
  1074. /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
  1075. /// to be a pointer and needs to be able to initialize the child iterator.
  1076. /// Thus we need a reference back to the container to translate the indices
  1077. /// to entries.
  1078. VecTreeTy &Container;
  1079. /// The TreeEntry index containing the user of this entry. We can actually
  1080. /// have multiple users so the data structure is not truly a tree.
  1081. SmallVector<EdgeInfo, 1> UserTreeIndices;
  1082. /// The index of this treeEntry in VectorizableTree.
  1083. int Idx = -1;
  1084. private:
  1085. /// The operands of each instruction in each lane Operands[op_index][lane].
  1086. /// Note: This helps avoid the replication of the code that performs the
  1087. /// reordering of operands during buildTree_rec() and vectorizeTree().
  1088. SmallVector<ValueList, 2> Operands;
  1089. public:
  1090. /// Set this bundle's \p OpIdx'th operand to \p OpVL.
  1091. void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
  1092. if (Operands.size() < OpIdx + 1)
  1093. Operands.resize(OpIdx + 1);
  1094. assert(Operands[OpIdx].size() == 0 && "Already resized?");
  1095. Operands[OpIdx].resize(Scalars.size());
  1096. for (unsigned Lane = 0, E = Scalars.size(); Lane != E; ++Lane)
  1097. Operands[OpIdx][Lane] = OpVL[Lane];
  1098. }
  1099. /// Set the operands of this bundle in their original order.
  1100. void setOperandsInOrder() {
  1101. assert(Operands.empty() && "Already initialized?");
  1102. auto *I0 = cast<Instruction>(Scalars[0]);
  1103. Operands.resize(I0->getNumOperands());
  1104. unsigned NumLanes = Scalars.size();
  1105. for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
  1106. OpIdx != NumOperands; ++OpIdx) {
  1107. Operands[OpIdx].resize(NumLanes);
  1108. for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
  1109. auto *I = cast<Instruction>(Scalars[Lane]);
  1110. assert(I->getNumOperands() == NumOperands &&
  1111. "Expected same number of operands");
  1112. Operands[OpIdx][Lane] = I->getOperand(OpIdx);
  1113. }
  1114. }
  1115. }
  1116. /// \returns the \p OpIdx operand of this TreeEntry.
  1117. ValueList &getOperand(unsigned OpIdx) {
  1118. assert(OpIdx < Operands.size() && "Off bounds");
  1119. return Operands[OpIdx];
  1120. }
  1121. /// \returns the number of operands.
  1122. unsigned getNumOperands() const { return Operands.size(); }
  1123. /// \return the single \p OpIdx operand.
  1124. Value *getSingleOperand(unsigned OpIdx) const {
  1125. assert(OpIdx < Operands.size() && "Off bounds");
  1126. assert(!Operands[OpIdx].empty() && "No operand available");
  1127. return Operands[OpIdx][0];
  1128. }
  1129. #ifndef NDEBUG
  1130. /// Debug printer.
  1131. LLVM_DUMP_METHOD void dump() const {
  1132. dbgs() << Idx << ".\n";
  1133. for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
  1134. dbgs() << "Operand " << OpI << ":\n";
  1135. for (const Value *V : Operands[OpI])
  1136. dbgs().indent(2) << *V << "\n";
  1137. }
  1138. dbgs() << "Scalars: \n";
  1139. for (Value *V : Scalars)
  1140. dbgs().indent(2) << *V << "\n";
  1141. dbgs() << "NeedToGather: " << NeedToGather << "\n";
  1142. dbgs() << "VectorizedValue: ";
  1143. if (VectorizedValue)
  1144. dbgs() << *VectorizedValue;
  1145. else
  1146. dbgs() << "NULL";
  1147. dbgs() << "\n";
  1148. dbgs() << "ReuseShuffleIndices: ";
  1149. if (ReuseShuffleIndices.empty())
  1150. dbgs() << "Emtpy";
  1151. else
  1152. for (unsigned Idx : ReuseShuffleIndices)
  1153. dbgs() << Idx << ", ";
  1154. dbgs() << "\n";
  1155. dbgs() << "ReorderIndices: ";
  1156. for (unsigned Idx : ReorderIndices)
  1157. dbgs() << Idx << ", ";
  1158. dbgs() << "\n";
  1159. dbgs() << "UserTreeIndices: ";
  1160. for (const auto &EInfo : UserTreeIndices)
  1161. dbgs() << EInfo << ", ";
  1162. dbgs() << "\n";
  1163. }
  1164. #endif
  1165. };
  1166. /// Create a new VectorizableTree entry.
  1167. TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
  1168. Optional<ScheduleData *> Bundle,
  1169. const EdgeInfo &UserTreeIdx,
  1170. ArrayRef<unsigned> ReuseShuffleIndices = None,
  1171. ArrayRef<unsigned> ReorderIndices = None) {
  1172. bool Vectorized = (bool)Bundle;
  1173. VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
  1174. TreeEntry *Last = VectorizableTree.back().get();
  1175. Last->Idx = VectorizableTree.size() - 1;
  1176. Last->Scalars.insert(Last->Scalars.begin(), VL.begin(), VL.end());
  1177. Last->NeedToGather = !Vectorized;
  1178. Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
  1179. ReuseShuffleIndices.end());
  1180. Last->ReorderIndices = ReorderIndices;
  1181. if (Vectorized) {
  1182. for (int i = 0, e = VL.size(); i != e; ++i) {
  1183. assert(!getTreeEntry(VL[i]) && "Scalar already in tree!");
  1184. ScalarToTreeEntry[VL[i]] = Last;
  1185. }
  1186. // Update the scheduler bundle to point to this TreeEntry.
  1187. unsigned Lane = 0;
  1188. for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
  1189. BundleMember = BundleMember->NextInBundle) {
  1190. BundleMember->TE = Last;
  1191. BundleMember->Lane = Lane;
  1192. ++Lane;
  1193. }
  1194. assert((!Bundle.getValue() || Lane == VL.size()) &&
  1195. "Bundle and VL out of sync");
  1196. } else {
  1197. MustGather.insert(VL.begin(), VL.end());
  1198. }
  1199. if (UserTreeIdx.UserTE)
  1200. Last->UserTreeIndices.push_back(UserTreeIdx);
  1201. return Last;
  1202. }
  1203. /// -- Vectorization State --
  1204. /// Holds all of the tree entries.
  1205. TreeEntry::VecTreeTy VectorizableTree;
  1206. #ifndef NDEBUG
  1207. /// Debug printer.
  1208. LLVM_DUMP_METHOD void dumpVectorizableTree() const {
  1209. for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
  1210. VectorizableTree[Id]->dump();
  1211. dbgs() << "\n";
  1212. }
  1213. }
  1214. #endif
  1215. TreeEntry *getTreeEntry(Value *V) {
  1216. auto I = ScalarToTreeEntry.find(V);
  1217. if (I != ScalarToTreeEntry.end())
  1218. return I->second;
  1219. return nullptr;
  1220. }
  1221. const TreeEntry *getTreeEntry(Value *V) const {
  1222. auto I = ScalarToTreeEntry.find(V);
  1223. if (I != ScalarToTreeEntry.end())
  1224. return I->second;
  1225. return nullptr;
  1226. }
  1227. /// Maps a specific scalar to its tree entry.
  1228. SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
  1229. /// A list of scalars that we found that we need to keep as scalars.
  1230. ValueSet MustGather;
  1231. /// This POD struct describes one external user in the vectorized tree.
  1232. struct ExternalUser {
  1233. ExternalUser(Value *S, llvm::User *U, int L)
  1234. : Scalar(S), User(U), Lane(L) {}
  1235. // Which scalar in our function.
  1236. Value *Scalar;
  1237. // Which user that uses the scalar.
  1238. llvm::User *User;
  1239. // Which lane does the scalar belong to.
  1240. int Lane;
  1241. };
  1242. using UserList = SmallVector<ExternalUser, 16>;
  1243. /// Checks if two instructions may access the same memory.
  1244. ///
  1245. /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
  1246. /// is invariant in the calling loop.
  1247. bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
  1248. Instruction *Inst2) {
  1249. // First check if the result is already in the cache.
  1250. AliasCacheKey key = std::make_pair(Inst1, Inst2);
  1251. Optional<bool> &result = AliasCache[key];
  1252. if (result.hasValue()) {
  1253. return result.getValue();
  1254. }
  1255. MemoryLocation Loc2 = getLocation(Inst2, AA);
  1256. bool aliased = true;
  1257. if (Loc1.Ptr && Loc2.Ptr && isSimple(Inst1) && isSimple(Inst2)) {
  1258. // Do the alias check.
  1259. aliased = AA->alias(Loc1, Loc2);
  1260. }
  1261. // Store the result in the cache.
  1262. result = aliased;
  1263. return aliased;
  1264. }
  1265. using AliasCacheKey = std::pair<Instruction *, Instruction *>;
  1266. /// Cache for alias results.
  1267. /// TODO: consider moving this to the AliasAnalysis itself.
  1268. DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
  1269. /// Removes an instruction from its block and eventually deletes it.
  1270. /// It's like Instruction::eraseFromParent() except that the actual deletion
  1271. /// is delayed until BoUpSLP is destructed.
  1272. /// This is required to ensure that there are no incorrect collisions in the
  1273. /// AliasCache, which can happen if a new instruction is allocated at the
  1274. /// same address as a previously deleted instruction.
  1275. void eraseInstruction(Instruction *I) {
  1276. I->removeFromParent();
  1277. I->dropAllReferences();
  1278. DeletedInstructions.emplace_back(I);
  1279. }
  1280. /// Temporary store for deleted instructions. Instructions will be deleted
  1281. /// eventually when the BoUpSLP is destructed.
  1282. SmallVector<unique_value, 8> DeletedInstructions;
  1283. /// A list of values that need to extracted out of the tree.
  1284. /// This list holds pairs of (Internal Scalar : External User). External User
  1285. /// can be nullptr, it means that this Internal Scalar will be used later,
  1286. /// after vectorization.
  1287. UserList ExternalUses;
  1288. /// Values used only by @llvm.assume calls.
  1289. SmallPtrSet<const Value *, 32> EphValues;
  1290. /// Holds all of the instructions that we gathered.
  1291. SetVector<Instruction *> GatherSeq;
  1292. /// A list of blocks that we are going to CSE.
  1293. SetVector<BasicBlock *> CSEBlocks;
  1294. /// Contains all scheduling relevant data for an instruction.
  1295. /// A ScheduleData either represents a single instruction or a member of an
  1296. /// instruction bundle (= a group of instructions which is combined into a
  1297. /// vector instruction).
  1298. struct ScheduleData {
  1299. // The initial value for the dependency counters. It means that the
  1300. // dependencies are not calculated yet.
  1301. enum { InvalidDeps = -1 };
  1302. ScheduleData() = default;
  1303. void init(int BlockSchedulingRegionID, Value *OpVal) {
  1304. FirstInBundle = this;
  1305. NextInBundle = nullptr;
  1306. NextLoadStore = nullptr;
  1307. IsScheduled = false;
  1308. SchedulingRegionID = BlockSchedulingRegionID;
  1309. UnscheduledDepsInBundle = UnscheduledDeps;
  1310. clearDependencies();
  1311. OpValue = OpVal;
  1312. TE = nullptr;
  1313. Lane = -1;
  1314. }
  1315. /// Returns true if the dependency information has been calculated.
  1316. bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
  1317. /// Returns true for single instructions and for bundle representatives
  1318. /// (= the head of a bundle).
  1319. bool isSchedulingEntity() const { return FirstInBundle == this; }
  1320. /// Returns true if it represents an instruction bundle and not only a
  1321. /// single instruction.
  1322. bool isPartOfBundle() const {
  1323. return NextInBundle != nullptr || FirstInBundle != this;
  1324. }
  1325. /// Returns true if it is ready for scheduling, i.e. it has no more
  1326. /// unscheduled depending instructions/bundles.
  1327. bool isReady() const {
  1328. assert(isSchedulingEntity() &&
  1329. "can't consider non-scheduling entity for ready list");
  1330. return UnscheduledDepsInBundle == 0 && !IsScheduled;
  1331. }
  1332. /// Modifies the number of unscheduled dependencies, also updating it for
  1333. /// the whole bundle.
  1334. int incrementUnscheduledDeps(int Incr) {
  1335. UnscheduledDeps += Incr;
  1336. return FirstInBundle->UnscheduledDepsInBundle += Incr;
  1337. }
  1338. /// Sets the number of unscheduled dependencies to the number of
  1339. /// dependencies.
  1340. void resetUnscheduledDeps() {
  1341. incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
  1342. }
  1343. /// Clears all dependency information.
  1344. void clearDependencies() {
  1345. Dependencies = InvalidDeps;
  1346. resetUnscheduledDeps();
  1347. MemoryDependencies.clear();
  1348. }
  1349. void dump(raw_ostream &os) const {
  1350. if (!isSchedulingEntity()) {
  1351. os << "/ " << *Inst;
  1352. } else if (NextInBundle) {
  1353. os << '[' << *Inst;
  1354. ScheduleData *SD = NextInBundle;
  1355. while (SD) {
  1356. os << ';' << *SD->Inst;
  1357. SD = SD->NextInBundle;
  1358. }
  1359. os << ']';
  1360. } else {
  1361. os << *Inst;
  1362. }
  1363. }
  1364. Instruction *Inst = nullptr;
  1365. /// Points to the head in an instruction bundle (and always to this for
  1366. /// single instructions).
  1367. ScheduleData *FirstInBundle = nullptr;
  1368. /// Single linked list of all instructions in a bundle. Null if it is a
  1369. /// single instruction.
  1370. ScheduleData *NextInBundle = nullptr;
  1371. /// Single linked list of all memory instructions (e.g. load, store, call)
  1372. /// in the block - until the end of the scheduling region.
  1373. ScheduleData *NextLoadStore = nullptr;
  1374. /// The dependent memory instructions.
  1375. /// This list is derived on demand in calculateDependencies().
  1376. SmallVector<ScheduleData *, 4> MemoryDependencies;
  1377. /// This ScheduleData is in the current scheduling region if this matches
  1378. /// the current SchedulingRegionID of BlockScheduling.
  1379. int SchedulingRegionID = 0;
  1380. /// Used for getting a "good" final ordering of instructions.
  1381. int SchedulingPriority = 0;
  1382. /// The number of dependencies. Constitutes of the number of users of the
  1383. /// instruction plus the number of dependent memory instructions (if any).
  1384. /// This value is calculated on demand.
  1385. /// If InvalidDeps, the number of dependencies is not calculated yet.
  1386. int Dependencies = InvalidDeps;
  1387. /// The number of dependencies minus the number of dependencies of scheduled
  1388. /// instructions. As soon as this is zero, the instruction/bundle gets ready
  1389. /// for scheduling.
  1390. /// Note that this is negative as long as Dependencies is not calculated.
  1391. int UnscheduledDeps = InvalidDeps;
  1392. /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
  1393. /// single instructions.
  1394. int UnscheduledDepsInBundle = InvalidDeps;
  1395. /// True if this instruction is scheduled (or considered as scheduled in the
  1396. /// dry-run).
  1397. bool IsScheduled = false;
  1398. /// Opcode of the current instruction in the schedule data.
  1399. Value *OpValue = nullptr;
  1400. /// The TreeEntry that this instruction corresponds to.
  1401. TreeEntry *TE = nullptr;
  1402. /// The lane of this node in the TreeEntry.
  1403. int Lane = -1;
  1404. };
  1405. #ifndef NDEBUG
  1406. friend inline raw_ostream &operator<<(raw_ostream &os,
  1407. const BoUpSLP::ScheduleData &SD) {
  1408. SD.dump(os);
  1409. return os;
  1410. }
  1411. #endif
  1412. friend struct GraphTraits<BoUpSLP *>;
  1413. friend struct DOTGraphTraits<BoUpSLP *>;
  1414. /// Contains all scheduling data for a basic block.
  1415. struct BlockScheduling {
  1416. BlockScheduling(BasicBlock *BB)
  1417. : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
  1418. void clear() {
  1419. ReadyInsts.clear();
  1420. ScheduleStart = nullptr;
  1421. ScheduleEnd = nullptr;
  1422. FirstLoadStoreInRegion = nullptr;
  1423. LastLoadStoreInRegion = nullptr;
  1424. // Reduce the maximum schedule region size by the size of the
  1425. // previous scheduling run.
  1426. ScheduleRegionSizeLimit -= ScheduleRegionSize;
  1427. if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
  1428. ScheduleRegionSizeLimit = MinScheduleRegionSize;
  1429. ScheduleRegionSize = 0;
  1430. // Make a new scheduling region, i.e. all existing ScheduleData is not
  1431. // in the new region yet.
  1432. ++SchedulingRegionID;
  1433. }
  1434. ScheduleData *getScheduleData(Value *V) {
  1435. ScheduleData *SD = ScheduleDataMap[V];
  1436. if (SD && SD->SchedulingRegionID == SchedulingRegionID)
  1437. return SD;
  1438. return nullptr;
  1439. }
  1440. ScheduleData *getScheduleData(Value *V, Value *Key) {
  1441. if (V == Key)
  1442. return getScheduleData(V);
  1443. auto I = ExtraScheduleDataMap.find(V);
  1444. if (I != ExtraScheduleDataMap.end()) {
  1445. ScheduleData *SD = I->second[Key];
  1446. if (SD && SD->SchedulingRegionID == SchedulingRegionID)
  1447. return SD;
  1448. }
  1449. return nullptr;
  1450. }
  1451. bool isInSchedulingRegion(ScheduleData *SD) {
  1452. return SD->SchedulingRegionID == SchedulingRegionID;
  1453. }
  1454. /// Marks an instruction as scheduled and puts all dependent ready
  1455. /// instructions into the ready-list.
  1456. template <typename ReadyListType>
  1457. void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
  1458. SD->IsScheduled = true;
  1459. LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
  1460. ScheduleData *BundleMember = SD;
  1461. while (BundleMember) {
  1462. if (BundleMember->Inst != BundleMember->OpValue) {
  1463. BundleMember = BundleMember->NextInBundle;
  1464. continue;
  1465. }
  1466. // Handle the def-use chain dependencies.
  1467. // Decrement the unscheduled counter and insert to ready list if ready.
  1468. auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
  1469. doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
  1470. if (OpDef && OpDef->hasValidDependencies() &&
  1471. OpDef->incrementUnscheduledDeps(-1) == 0) {
  1472. // There are no more unscheduled dependencies after
  1473. // decrementing, so we can put the dependent instruction
  1474. // into the ready list.
  1475. ScheduleData *DepBundle = OpDef->FirstInBundle;
  1476. assert(!DepBundle->IsScheduled &&
  1477. "already scheduled bundle gets ready");
  1478. ReadyList.insert(DepBundle);
  1479. LLVM_DEBUG(dbgs()
  1480. << "SLP: gets ready (def): " << *DepBundle << "\n");
  1481. }
  1482. });
  1483. };
  1484. // If BundleMember is a vector bundle, its operands may have been
  1485. // reordered duiring buildTree(). We therefore need to get its operands
  1486. // through the TreeEntry.
  1487. if (TreeEntry *TE = BundleMember->TE) {
  1488. int Lane = BundleMember->Lane;
  1489. assert(Lane >= 0 && "Lane not set");
  1490. for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
  1491. OpIdx != NumOperands; ++OpIdx)
  1492. if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
  1493. DecrUnsched(I);
  1494. } else {
  1495. // If BundleMember is a stand-alone instruction, no operand reordering
  1496. // has taken place, so we directly access its operands.
  1497. for (Use &U : BundleMember->Inst->operands())
  1498. if (auto *I = dyn_cast<Instruction>(U.get()))
  1499. DecrUnsched(I);
  1500. }
  1501. // Handle the memory dependencies.
  1502. for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
  1503. if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
  1504. // There are no more unscheduled dependencies after decrementing,
  1505. // so we can put the dependent instruction into the ready list.
  1506. ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
  1507. assert(!DepBundle->IsScheduled &&
  1508. "already scheduled bundle gets ready");
  1509. ReadyList.insert(DepBundle);
  1510. LLVM_DEBUG(dbgs()
  1511. << "SLP: gets ready (mem): " << *DepBundle << "\n");
  1512. }
  1513. }
  1514. BundleMember = BundleMember->NextInBundle;
  1515. }
  1516. }
  1517. void doForAllOpcodes(Value *V,
  1518. function_ref<void(ScheduleData *SD)> Action) {
  1519. if (ScheduleData *SD = getScheduleData(V))
  1520. Action(SD);
  1521. auto I = ExtraScheduleDataMap.find(V);
  1522. if (I != ExtraScheduleDataMap.end())
  1523. for (auto &P : I->second)
  1524. if (P.second->SchedulingRegionID == SchedulingRegionID)
  1525. Action(P.second);
  1526. }
  1527. /// Put all instructions into the ReadyList which are ready for scheduling.
  1528. template <typename ReadyListType>
  1529. void initialFillReadyList(ReadyListType &ReadyList) {
  1530. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  1531. doForAllOpcodes(I, [&](ScheduleData *SD) {
  1532. if (SD->isSchedulingEntity() && SD->isReady()) {
  1533. ReadyList.insert(SD);
  1534. LLVM_DEBUG(dbgs()
  1535. << "SLP: initially in ready list: " << *I << "\n");
  1536. }
  1537. });
  1538. }
  1539. }
  1540. /// Checks if a bundle of instructions can be scheduled, i.e. has no
  1541. /// cyclic dependencies. This is only a dry-run, no instructions are
  1542. /// actually moved at this stage.
  1543. /// \returns the scheduling bundle. The returned Optional value is non-None
  1544. /// if \p VL is allowed to be scheduled.
  1545. Optional<ScheduleData *>
  1546. tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
  1547. const InstructionsState &S);
  1548. /// Un-bundles a group of instructions.
  1549. void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
  1550. /// Allocates schedule data chunk.
  1551. ScheduleData *allocateScheduleDataChunks();
  1552. /// Extends the scheduling region so that V is inside the region.
  1553. /// \returns true if the region size is within the limit.
  1554. bool extendSchedulingRegion(Value *V, const InstructionsState &S);
  1555. /// Initialize the ScheduleData structures for new instructions in the
  1556. /// scheduling region.
  1557. void initScheduleData(Instruction *FromI, Instruction *ToI,
  1558. ScheduleData *PrevLoadStore,
  1559. ScheduleData *NextLoadStore);
  1560. /// Updates the dependency information of a bundle and of all instructions/
  1561. /// bundles which depend on the original bundle.
  1562. void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
  1563. BoUpSLP *SLP);
  1564. /// Sets all instruction in the scheduling region to un-scheduled.
  1565. void resetSchedule();
  1566. BasicBlock *BB;
  1567. /// Simple memory allocation for ScheduleData.
  1568. std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
  1569. /// The size of a ScheduleData array in ScheduleDataChunks.
  1570. int ChunkSize;
  1571. /// The allocator position in the current chunk, which is the last entry
  1572. /// of ScheduleDataChunks.
  1573. int ChunkPos;
  1574. /// Attaches ScheduleData to Instruction.
  1575. /// Note that the mapping survives during all vectorization iterations, i.e.
  1576. /// ScheduleData structures are recycled.
  1577. DenseMap<Value *, ScheduleData *> ScheduleDataMap;
  1578. /// Attaches ScheduleData to Instruction with the leading key.
  1579. DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
  1580. ExtraScheduleDataMap;
  1581. struct ReadyList : SmallVector<ScheduleData *, 8> {
  1582. void insert(ScheduleData *SD) { push_back(SD); }
  1583. };
  1584. /// The ready-list for scheduling (only used for the dry-run).
  1585. ReadyList ReadyInsts;
  1586. /// The first instruction of the scheduling region.
  1587. Instruction *ScheduleStart = nullptr;
  1588. /// The first instruction _after_ the scheduling region.
  1589. Instruction *ScheduleEnd = nullptr;
  1590. /// The first memory accessing instruction in the scheduling region
  1591. /// (can be null).
  1592. ScheduleData *FirstLoadStoreInRegion = nullptr;
  1593. /// The last memory accessing instruction in the scheduling region
  1594. /// (can be null).
  1595. ScheduleData *LastLoadStoreInRegion = nullptr;
  1596. /// The current size of the scheduling region.
  1597. int ScheduleRegionSize = 0;
  1598. /// The maximum size allowed for the scheduling region.
  1599. int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
  1600. /// The ID of the scheduling region. For a new vectorization iteration this
  1601. /// is incremented which "removes" all ScheduleData from the region.
  1602. // Make sure that the initial SchedulingRegionID is greater than the
  1603. // initial SchedulingRegionID in ScheduleData (which is 0).
  1604. int SchedulingRegionID = 1;
  1605. };
  1606. /// Attaches the BlockScheduling structures to basic blocks.
  1607. MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
  1608. /// Performs the "real" scheduling. Done before vectorization is actually
  1609. /// performed in a basic block.
  1610. void scheduleBlock(BlockScheduling *BS);
  1611. /// List of users to ignore during scheduling and that don't need extracting.
  1612. ArrayRef<Value *> UserIgnoreList;
  1613. using OrdersType = SmallVector<unsigned, 4>;
  1614. /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
  1615. /// sorted SmallVectors of unsigned.
  1616. struct OrdersTypeDenseMapInfo {
  1617. static OrdersType getEmptyKey() {
  1618. OrdersType V;
  1619. V.push_back(~1U);
  1620. return V;
  1621. }
  1622. static OrdersType getTombstoneKey() {
  1623. OrdersType V;
  1624. V.push_back(~2U);
  1625. return V;
  1626. }
  1627. static unsigned getHashValue(const OrdersType &V) {
  1628. return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
  1629. }
  1630. static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
  1631. return LHS == RHS;
  1632. }
  1633. };
  1634. /// Contains orders of operations along with the number of bundles that have
  1635. /// operations in this order. It stores only those orders that require
  1636. /// reordering, if reordering is not required it is counted using \a
  1637. /// NumOpsWantToKeepOriginalOrder.
  1638. DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo> NumOpsWantToKeepOrder;
  1639. /// Number of bundles that do not require reordering.
  1640. unsigned NumOpsWantToKeepOriginalOrder = 0;
  1641. // Analysis and block reference.
  1642. Function *F;
  1643. ScalarEvolution *SE;
  1644. TargetTransformInfo *TTI;
  1645. TargetLibraryInfo *TLI;
  1646. AliasAnalysis *AA;
  1647. LoopInfo *LI;
  1648. DominatorTree *DT;
  1649. AssumptionCache *AC;
  1650. DemandedBits *DB;
  1651. const DataLayout *DL;
  1652. OptimizationRemarkEmitter *ORE;
  1653. unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
  1654. unsigned MinVecRegSize; // Set by cl::opt (default: 128).
  1655. /// Instruction builder to construct the vectorized tree.
  1656. IRBuilder<> Builder;
  1657. /// A map of scalar integer values to the smallest bit width with which they
  1658. /// can legally be represented. The values map to (width, signed) pairs,
  1659. /// where "width" indicates the minimum bit width and "signed" is True if the
  1660. /// value must be signed-extended, rather than zero-extended, back to its
  1661. /// original width.
  1662. MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
  1663. };
  1664. } // end namespace slpvectorizer
  1665. template <> struct GraphTraits<BoUpSLP *> {
  1666. using TreeEntry = BoUpSLP::TreeEntry;
  1667. /// NodeRef has to be a pointer per the GraphWriter.
  1668. using NodeRef = TreeEntry *;
  1669. using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
  1670. /// Add the VectorizableTree to the index iterator to be able to return
  1671. /// TreeEntry pointers.
  1672. struct ChildIteratorType
  1673. : public iterator_adaptor_base<
  1674. ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
  1675. ContainerTy &VectorizableTree;
  1676. ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
  1677. ContainerTy &VT)
  1678. : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
  1679. NodeRef operator*() { return I->UserTE; }
  1680. };
  1681. static NodeRef getEntryNode(BoUpSLP &R) {
  1682. return R.VectorizableTree[0].get();
  1683. }
  1684. static ChildIteratorType child_begin(NodeRef N) {
  1685. return {N->UserTreeIndices.begin(), N->Container};
  1686. }
  1687. static ChildIteratorType child_end(NodeRef N) {
  1688. return {N->UserTreeIndices.end(), N->Container};
  1689. }
  1690. /// For the node iterator we just need to turn the TreeEntry iterator into a
  1691. /// TreeEntry* iterator so that it dereferences to NodeRef.
  1692. class nodes_iterator {
  1693. using ItTy = ContainerTy::iterator;
  1694. ItTy It;
  1695. public:
  1696. nodes_iterator(const ItTy &It2) : It(It2) {}
  1697. NodeRef operator*() { return It->get(); }
  1698. nodes_iterator operator++() {
  1699. ++It;
  1700. return *this;
  1701. }
  1702. bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
  1703. };
  1704. static nodes_iterator nodes_begin(BoUpSLP *R) {
  1705. return nodes_iterator(R->VectorizableTree.begin());
  1706. }
  1707. static nodes_iterator nodes_end(BoUpSLP *R) {
  1708. return nodes_iterator(R->VectorizableTree.end());
  1709. }
  1710. static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
  1711. };
  1712. template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
  1713. using TreeEntry = BoUpSLP::TreeEntry;
  1714. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  1715. std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
  1716. std::string Str;
  1717. raw_string_ostream OS(Str);
  1718. if (isSplat(Entry->Scalars)) {
  1719. OS << "<splat> " << *Entry->Scalars[0];
  1720. return Str;
  1721. }
  1722. for (auto V : Entry->Scalars) {
  1723. OS << *V;
  1724. if (std::any_of(
  1725. R->ExternalUses.begin(), R->ExternalUses.end(),
  1726. [&](const BoUpSLP::ExternalUser &EU) { return EU.Scalar == V; }))
  1727. OS << " <extract>";
  1728. OS << "\n";
  1729. }
  1730. return Str;
  1731. }
  1732. static std::string getNodeAttributes(const TreeEntry *Entry,
  1733. const BoUpSLP *) {
  1734. if (Entry->NeedToGather)
  1735. return "color=red";
  1736. return "";
  1737. }
  1738. };
  1739. } // end namespace llvm
  1740. void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
  1741. ArrayRef<Value *> UserIgnoreLst) {
  1742. ExtraValueToDebugLocsMap ExternallyUsedValues;
  1743. buildTree(Roots, ExternallyUsedValues, UserIgnoreLst);
  1744. }
  1745. void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
  1746. ExtraValueToDebugLocsMap &ExternallyUsedValues,
  1747. ArrayRef<Value *> UserIgnoreLst) {
  1748. deleteTree();
  1749. UserIgnoreList = UserIgnoreLst;
  1750. if (!allSameType(Roots))
  1751. return;
  1752. buildTree_rec(Roots, 0, EdgeInfo());
  1753. // Collect the values that we need to extract from the tree.
  1754. for (auto &TEPtr : VectorizableTree) {
  1755. TreeEntry *Entry = TEPtr.get();
  1756. // No need to handle users of gathered values.
  1757. if (Entry->NeedToGather)
  1758. continue;
  1759. // For each lane:
  1760. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  1761. Value *Scalar = Entry->Scalars[Lane];
  1762. int FoundLane = Lane;
  1763. if (!Entry->ReuseShuffleIndices.empty()) {
  1764. FoundLane =
  1765. std::distance(Entry->ReuseShuffleIndices.begin(),
  1766. llvm::find(Entry->ReuseShuffleIndices, FoundLane));
  1767. }
  1768. // Check if the scalar is externally used as an extra arg.
  1769. auto ExtI = ExternallyUsedValues.find(Scalar);
  1770. if (ExtI != ExternallyUsedValues.end()) {
  1771. LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
  1772. << Lane << " from " << *Scalar << ".\n");
  1773. ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
  1774. }
  1775. for (User *U : Scalar->users()) {
  1776. LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
  1777. Instruction *UserInst = dyn_cast<Instruction>(U);
  1778. if (!UserInst)
  1779. continue;
  1780. // Skip in-tree scalars that become vectors
  1781. if (TreeEntry *UseEntry = getTreeEntry(U)) {
  1782. Value *UseScalar = UseEntry->Scalars[0];
  1783. // Some in-tree scalars will remain as scalar in vectorized
  1784. // instructions. If that is the case, the one in Lane 0 will
  1785. // be used.
  1786. if (UseScalar != U ||
  1787. !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
  1788. LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
  1789. << ".\n");
  1790. assert(!UseEntry->NeedToGather && "Bad state");
  1791. continue;
  1792. }
  1793. }
  1794. // Ignore users in the user ignore list.
  1795. if (is_contained(UserIgnoreList, UserInst))
  1796. continue;
  1797. LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
  1798. << Lane << " from " << *Scalar << ".\n");
  1799. ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
  1800. }
  1801. }
  1802. }
  1803. }
  1804. void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
  1805. const EdgeInfo &UserTreeIdx) {
  1806. assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
  1807. InstructionsState S = getSameOpcode(VL);
  1808. if (Depth == RecursionMaxDepth) {
  1809. LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
  1810. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1811. return;
  1812. }
  1813. // Don't handle vectors.
  1814. if (S.OpValue->getType()->isVectorTy()) {
  1815. LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
  1816. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1817. return;
  1818. }
  1819. if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
  1820. if (SI->getValueOperand()->getType()->isVectorTy()) {
  1821. LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
  1822. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1823. return;
  1824. }
  1825. // If all of the operands are identical or constant we have a simple solution.
  1826. if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode()) {
  1827. LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
  1828. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1829. return;
  1830. }
  1831. // We now know that this is a vector of instructions of the same type from
  1832. // the same block.
  1833. // Don't vectorize ephemeral values.
  1834. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  1835. if (EphValues.count(VL[i])) {
  1836. LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *VL[i]
  1837. << ") is ephemeral.\n");
  1838. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1839. return;
  1840. }
  1841. }
  1842. // Check if this is a duplicate of another entry.
  1843. if (TreeEntry *E = getTreeEntry(S.OpValue)) {
  1844. LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
  1845. if (!E->isSame(VL)) {
  1846. LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
  1847. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1848. return;
  1849. }
  1850. // Record the reuse of the tree node. FIXME, currently this is only used to
  1851. // properly draw the graph rather than for the actual vectorization.
  1852. E->UserTreeIndices.push_back(UserTreeIdx);
  1853. LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
  1854. << ".\n");
  1855. return;
  1856. }
  1857. // Check that none of the instructions in the bundle are already in the tree.
  1858. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  1859. auto *I = dyn_cast<Instruction>(VL[i]);
  1860. if (!I)
  1861. continue;
  1862. if (getTreeEntry(I)) {
  1863. LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *VL[i]
  1864. << ") is already in tree.\n");
  1865. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1866. return;
  1867. }
  1868. }
  1869. // If any of the scalars is marked as a value that needs to stay scalar, then
  1870. // we need to gather the scalars.
  1871. // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
  1872. for (unsigned i = 0, e = VL.size(); i != e; ++i) {
  1873. if (MustGather.count(VL[i]) || is_contained(UserIgnoreList, VL[i])) {
  1874. LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
  1875. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1876. return;
  1877. }
  1878. }
  1879. // Check that all of the users of the scalars that we want to vectorize are
  1880. // schedulable.
  1881. auto *VL0 = cast<Instruction>(S.OpValue);
  1882. BasicBlock *BB = VL0->getParent();
  1883. if (!DT->isReachableFromEntry(BB)) {
  1884. // Don't go into unreachable blocks. They may contain instructions with
  1885. // dependency cycles which confuse the final scheduling.
  1886. LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
  1887. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1888. return;
  1889. }
  1890. // Check that every instruction appears once in this bundle.
  1891. SmallVector<unsigned, 4> ReuseShuffleIndicies;
  1892. SmallVector<Value *, 4> UniqueValues;
  1893. DenseMap<Value *, unsigned> UniquePositions;
  1894. for (Value *V : VL) {
  1895. auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
  1896. ReuseShuffleIndicies.emplace_back(Res.first->second);
  1897. if (Res.second)
  1898. UniqueValues.emplace_back(V);
  1899. }
  1900. size_t NumUniqueScalarValues = UniqueValues.size();
  1901. if (NumUniqueScalarValues == VL.size()) {
  1902. ReuseShuffleIndicies.clear();
  1903. } else {
  1904. LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
  1905. if (NumUniqueScalarValues <= 1 ||
  1906. !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
  1907. LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
  1908. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx);
  1909. return;
  1910. }
  1911. VL = UniqueValues;
  1912. }
  1913. auto &BSRef = BlocksSchedules[BB];
  1914. if (!BSRef)
  1915. BSRef = std::make_unique<BlockScheduling>(BB);
  1916. BlockScheduling &BS = *BSRef.get();
  1917. Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
  1918. if (!Bundle) {
  1919. LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
  1920. assert((!BS.getScheduleData(VL0) ||
  1921. !BS.getScheduleData(VL0)->isPartOfBundle()) &&
  1922. "tryScheduleBundle should cancelScheduling on failure");
  1923. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  1924. ReuseShuffleIndicies);
  1925. return;
  1926. }
  1927. LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
  1928. unsigned ShuffleOrOp = S.isAltShuffle() ?
  1929. (unsigned) Instruction::ShuffleVector : S.getOpcode();
  1930. switch (ShuffleOrOp) {
  1931. case Instruction::PHI: {
  1932. PHINode *PH = dyn_cast<PHINode>(VL0);
  1933. // Check for terminator values (e.g. invoke).
  1934. for (unsigned j = 0; j < VL.size(); ++j)
  1935. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  1936. Instruction *Term = dyn_cast<Instruction>(
  1937. cast<PHINode>(VL[j])->getIncomingValueForBlock(
  1938. PH->getIncomingBlock(i)));
  1939. if (Term && Term->isTerminator()) {
  1940. LLVM_DEBUG(dbgs()
  1941. << "SLP: Need to swizzle PHINodes (terminator use).\n");
  1942. BS.cancelScheduling(VL, VL0);
  1943. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  1944. ReuseShuffleIndicies);
  1945. return;
  1946. }
  1947. }
  1948. TreeEntry *TE =
  1949. newTreeEntry(VL, Bundle, UserTreeIdx, ReuseShuffleIndicies);
  1950. LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
  1951. // Keeps the reordered operands to avoid code duplication.
  1952. SmallVector<ValueList, 2> OperandsVec;
  1953. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  1954. ValueList Operands;
  1955. // Prepare the operand vector.
  1956. for (Value *j : VL)
  1957. Operands.push_back(cast<PHINode>(j)->getIncomingValueForBlock(
  1958. PH->getIncomingBlock(i)));
  1959. TE->setOperand(i, Operands);
  1960. OperandsVec.push_back(Operands);
  1961. }
  1962. for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
  1963. buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
  1964. return;
  1965. }
  1966. case Instruction::ExtractValue:
  1967. case Instruction::ExtractElement: {
  1968. OrdersType CurrentOrder;
  1969. bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
  1970. if (Reuse) {
  1971. LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
  1972. ++NumOpsWantToKeepOriginalOrder;
  1973. newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  1974. ReuseShuffleIndicies);
  1975. // This is a special case, as it does not gather, but at the same time
  1976. // we are not extending buildTree_rec() towards the operands.
  1977. ValueList Op0;
  1978. Op0.assign(VL.size(), VL0->getOperand(0));
  1979. VectorizableTree.back()->setOperand(0, Op0);
  1980. return;
  1981. }
  1982. if (!CurrentOrder.empty()) {
  1983. LLVM_DEBUG({
  1984. dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
  1985. "with order";
  1986. for (unsigned Idx : CurrentOrder)
  1987. dbgs() << " " << Idx;
  1988. dbgs() << "\n";
  1989. });
  1990. // Insert new order with initial value 0, if it does not exist,
  1991. // otherwise return the iterator to the existing one.
  1992. auto StoredCurrentOrderAndNum =
  1993. NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
  1994. ++StoredCurrentOrderAndNum->getSecond();
  1995. newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  1996. ReuseShuffleIndicies,
  1997. StoredCurrentOrderAndNum->getFirst());
  1998. // This is a special case, as it does not gather, but at the same time
  1999. // we are not extending buildTree_rec() towards the operands.
  2000. ValueList Op0;
  2001. Op0.assign(VL.size(), VL0->getOperand(0));
  2002. VectorizableTree.back()->setOperand(0, Op0);
  2003. return;
  2004. }
  2005. LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
  2006. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2007. ReuseShuffleIndicies);
  2008. BS.cancelScheduling(VL, VL0);
  2009. return;
  2010. }
  2011. case Instruction::Load: {
  2012. // Check that a vectorized load would load the same memory as a scalar
  2013. // load. For example, we don't want to vectorize loads that are smaller
  2014. // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
  2015. // treats loading/storing it as an i8 struct. If we vectorize loads/stores
  2016. // from such a struct, we read/write packed bits disagreeing with the
  2017. // unvectorized version.
  2018. Type *ScalarTy = VL0->getType();
  2019. if (DL->getTypeSizeInBits(ScalarTy) !=
  2020. DL->getTypeAllocSizeInBits(ScalarTy)) {
  2021. BS.cancelScheduling(VL, VL0);
  2022. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2023. ReuseShuffleIndicies);
  2024. LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
  2025. return;
  2026. }
  2027. // Make sure all loads in the bundle are simple - we can't vectorize
  2028. // atomic or volatile loads.
  2029. SmallVector<Value *, 4> PointerOps(VL.size());
  2030. auto POIter = PointerOps.begin();
  2031. for (Value *V : VL) {
  2032. auto *L = cast<LoadInst>(V);
  2033. if (!L->isSimple()) {
  2034. BS.cancelScheduling(VL, VL0);
  2035. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2036. ReuseShuffleIndicies);
  2037. LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
  2038. return;
  2039. }
  2040. *POIter = L->getPointerOperand();
  2041. ++POIter;
  2042. }
  2043. OrdersType CurrentOrder;
  2044. // Check the order of pointer operands.
  2045. if (llvm::sortPtrAccesses(PointerOps, *DL, *SE, CurrentOrder)) {
  2046. Value *Ptr0;
  2047. Value *PtrN;
  2048. if (CurrentOrder.empty()) {
  2049. Ptr0 = PointerOps.front();
  2050. PtrN = PointerOps.back();
  2051. } else {
  2052. Ptr0 = PointerOps[CurrentOrder.front()];
  2053. PtrN = PointerOps[CurrentOrder.back()];
  2054. }
  2055. const SCEV *Scev0 = SE->getSCEV(Ptr0);
  2056. const SCEV *ScevN = SE->getSCEV(PtrN);
  2057. const auto *Diff =
  2058. dyn_cast<SCEVConstant>(SE->getMinusSCEV(ScevN, Scev0));
  2059. uint64_t Size = DL->getTypeAllocSize(ScalarTy);
  2060. // Check that the sorted loads are consecutive.
  2061. if (Diff && Diff->getAPInt().getZExtValue() == (VL.size() - 1) * Size) {
  2062. if (CurrentOrder.empty()) {
  2063. // Original loads are consecutive and does not require reordering.
  2064. ++NumOpsWantToKeepOriginalOrder;
  2065. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2066. ReuseShuffleIndicies);
  2067. TE->setOperandsInOrder();
  2068. LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
  2069. } else {
  2070. // Need to reorder.
  2071. auto I = NumOpsWantToKeepOrder.try_emplace(CurrentOrder).first;
  2072. ++I->getSecond();
  2073. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2074. ReuseShuffleIndicies, I->getFirst());
  2075. TE->setOperandsInOrder();
  2076. LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
  2077. }
  2078. return;
  2079. }
  2080. }
  2081. LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
  2082. BS.cancelScheduling(VL, VL0);
  2083. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2084. ReuseShuffleIndicies);
  2085. return;
  2086. }
  2087. case Instruction::ZExt:
  2088. case Instruction::SExt:
  2089. case Instruction::FPToUI:
  2090. case Instruction::FPToSI:
  2091. case Instruction::FPExt:
  2092. case Instruction::PtrToInt:
  2093. case Instruction::IntToPtr:
  2094. case Instruction::SIToFP:
  2095. case Instruction::UIToFP:
  2096. case Instruction::Trunc:
  2097. case Instruction::FPTrunc:
  2098. case Instruction::BitCast: {
  2099. Type *SrcTy = VL0->getOperand(0)->getType();
  2100. for (unsigned i = 0; i < VL.size(); ++i) {
  2101. Type *Ty = cast<Instruction>(VL[i])->getOperand(0)->getType();
  2102. if (Ty != SrcTy || !isValidElementType(Ty)) {
  2103. BS.cancelScheduling(VL, VL0);
  2104. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2105. ReuseShuffleIndicies);
  2106. LLVM_DEBUG(dbgs()
  2107. << "SLP: Gathering casts with different src types.\n");
  2108. return;
  2109. }
  2110. }
  2111. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2112. ReuseShuffleIndicies);
  2113. LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
  2114. TE->setOperandsInOrder();
  2115. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  2116. ValueList Operands;
  2117. // Prepare the operand vector.
  2118. for (Value *j : VL)
  2119. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  2120. buildTree_rec(Operands, Depth + 1, {TE, i});
  2121. }
  2122. return;
  2123. }
  2124. case Instruction::ICmp:
  2125. case Instruction::FCmp: {
  2126. // Check that all of the compares have the same predicate.
  2127. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  2128. CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
  2129. Type *ComparedTy = VL0->getOperand(0)->getType();
  2130. for (unsigned i = 1, e = VL.size(); i < e; ++i) {
  2131. CmpInst *Cmp = cast<CmpInst>(VL[i]);
  2132. if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
  2133. Cmp->getOperand(0)->getType() != ComparedTy) {
  2134. BS.cancelScheduling(VL, VL0);
  2135. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2136. ReuseShuffleIndicies);
  2137. LLVM_DEBUG(dbgs()
  2138. << "SLP: Gathering cmp with different predicate.\n");
  2139. return;
  2140. }
  2141. }
  2142. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2143. ReuseShuffleIndicies);
  2144. LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
  2145. ValueList Left, Right;
  2146. if (cast<CmpInst>(VL0)->isCommutative()) {
  2147. // Commutative predicate - collect + sort operands of the instructions
  2148. // so that each side is more likely to have the same opcode.
  2149. assert(P0 == SwapP0 && "Commutative Predicate mismatch");
  2150. reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE);
  2151. } else {
  2152. // Collect operands - commute if it uses the swapped predicate.
  2153. for (Value *V : VL) {
  2154. auto *Cmp = cast<CmpInst>(V);
  2155. Value *LHS = Cmp->getOperand(0);
  2156. Value *RHS = Cmp->getOperand(1);
  2157. if (Cmp->getPredicate() != P0)
  2158. std::swap(LHS, RHS);
  2159. Left.push_back(LHS);
  2160. Right.push_back(RHS);
  2161. }
  2162. }
  2163. TE->setOperand(0, Left);
  2164. TE->setOperand(1, Right);
  2165. buildTree_rec(Left, Depth + 1, {TE, 0});
  2166. buildTree_rec(Right, Depth + 1, {TE, 1});
  2167. return;
  2168. }
  2169. case Instruction::Select:
  2170. case Instruction::FNeg:
  2171. case Instruction::Add:
  2172. case Instruction::FAdd:
  2173. case Instruction::Sub:
  2174. case Instruction::FSub:
  2175. case Instruction::Mul:
  2176. case Instruction::FMul:
  2177. case Instruction::UDiv:
  2178. case Instruction::SDiv:
  2179. case Instruction::FDiv:
  2180. case Instruction::URem:
  2181. case Instruction::SRem:
  2182. case Instruction::FRem:
  2183. case Instruction::Shl:
  2184. case Instruction::LShr:
  2185. case Instruction::AShr:
  2186. case Instruction::And:
  2187. case Instruction::Or:
  2188. case Instruction::Xor: {
  2189. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2190. ReuseShuffleIndicies);
  2191. LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
  2192. // Sort operands of the instructions so that each side is more likely to
  2193. // have the same opcode.
  2194. if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
  2195. ValueList Left, Right;
  2196. reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE);
  2197. TE->setOperand(0, Left);
  2198. TE->setOperand(1, Right);
  2199. buildTree_rec(Left, Depth + 1, {TE, 0});
  2200. buildTree_rec(Right, Depth + 1, {TE, 1});
  2201. return;
  2202. }
  2203. TE->setOperandsInOrder();
  2204. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  2205. ValueList Operands;
  2206. // Prepare the operand vector.
  2207. for (Value *j : VL)
  2208. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  2209. buildTree_rec(Operands, Depth + 1, {TE, i});
  2210. }
  2211. return;
  2212. }
  2213. case Instruction::GetElementPtr: {
  2214. // We don't combine GEPs with complicated (nested) indexing.
  2215. for (unsigned j = 0; j < VL.size(); ++j) {
  2216. if (cast<Instruction>(VL[j])->getNumOperands() != 2) {
  2217. LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
  2218. BS.cancelScheduling(VL, VL0);
  2219. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2220. ReuseShuffleIndicies);
  2221. return;
  2222. }
  2223. }
  2224. // We can't combine several GEPs into one vector if they operate on
  2225. // different types.
  2226. Type *Ty0 = VL0->getOperand(0)->getType();
  2227. for (unsigned j = 0; j < VL.size(); ++j) {
  2228. Type *CurTy = cast<Instruction>(VL[j])->getOperand(0)->getType();
  2229. if (Ty0 != CurTy) {
  2230. LLVM_DEBUG(dbgs()
  2231. << "SLP: not-vectorizable GEP (different types).\n");
  2232. BS.cancelScheduling(VL, VL0);
  2233. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2234. ReuseShuffleIndicies);
  2235. return;
  2236. }
  2237. }
  2238. // We don't combine GEPs with non-constant indexes.
  2239. for (unsigned j = 0; j < VL.size(); ++j) {
  2240. auto Op = cast<Instruction>(VL[j])->getOperand(1);
  2241. if (!isa<ConstantInt>(Op)) {
  2242. LLVM_DEBUG(dbgs()
  2243. << "SLP: not-vectorizable GEP (non-constant indexes).\n");
  2244. BS.cancelScheduling(VL, VL0);
  2245. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2246. ReuseShuffleIndicies);
  2247. return;
  2248. }
  2249. }
  2250. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2251. ReuseShuffleIndicies);
  2252. LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
  2253. TE->setOperandsInOrder();
  2254. for (unsigned i = 0, e = 2; i < e; ++i) {
  2255. ValueList Operands;
  2256. // Prepare the operand vector.
  2257. for (Value *j : VL)
  2258. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  2259. buildTree_rec(Operands, Depth + 1, {TE, i});
  2260. }
  2261. return;
  2262. }
  2263. case Instruction::Store: {
  2264. // Check if the stores are consecutive or of we need to swizzle them.
  2265. for (unsigned i = 0, e = VL.size() - 1; i < e; ++i)
  2266. if (!isConsecutiveAccess(VL[i], VL[i + 1], *DL, *SE)) {
  2267. BS.cancelScheduling(VL, VL0);
  2268. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2269. ReuseShuffleIndicies);
  2270. LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
  2271. return;
  2272. }
  2273. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2274. ReuseShuffleIndicies);
  2275. LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
  2276. ValueList Operands;
  2277. for (Value *j : VL)
  2278. Operands.push_back(cast<Instruction>(j)->getOperand(0));
  2279. TE->setOperandsInOrder();
  2280. buildTree_rec(Operands, Depth + 1, {TE, 0});
  2281. return;
  2282. }
  2283. case Instruction::Call: {
  2284. // Check if the calls are all to the same vectorizable intrinsic.
  2285. CallInst *CI = cast<CallInst>(VL0);
  2286. // Check if this is an Intrinsic call or something that can be
  2287. // represented by an intrinsic call
  2288. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  2289. if (!isTriviallyVectorizable(ID)) {
  2290. BS.cancelScheduling(VL, VL0);
  2291. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2292. ReuseShuffleIndicies);
  2293. LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
  2294. return;
  2295. }
  2296. Function *Int = CI->getCalledFunction();
  2297. unsigned NumArgs = CI->getNumArgOperands();
  2298. SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
  2299. for (unsigned j = 0; j != NumArgs; ++j)
  2300. if (hasVectorInstrinsicScalarOpd(ID, j))
  2301. ScalarArgs[j] = CI->getArgOperand(j);
  2302. for (unsigned i = 1, e = VL.size(); i != e; ++i) {
  2303. CallInst *CI2 = dyn_cast<CallInst>(VL[i]);
  2304. if (!CI2 || CI2->getCalledFunction() != Int ||
  2305. getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
  2306. !CI->hasIdenticalOperandBundleSchema(*CI2)) {
  2307. BS.cancelScheduling(VL, VL0);
  2308. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2309. ReuseShuffleIndicies);
  2310. LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *VL[i]
  2311. << "\n");
  2312. return;
  2313. }
  2314. // Some intrinsics have scalar arguments and should be same in order for
  2315. // them to be vectorized.
  2316. for (unsigned j = 0; j != NumArgs; ++j) {
  2317. if (hasVectorInstrinsicScalarOpd(ID, j)) {
  2318. Value *A1J = CI2->getArgOperand(j);
  2319. if (ScalarArgs[j] != A1J) {
  2320. BS.cancelScheduling(VL, VL0);
  2321. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2322. ReuseShuffleIndicies);
  2323. LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
  2324. << " argument " << ScalarArgs[j] << "!=" << A1J
  2325. << "\n");
  2326. return;
  2327. }
  2328. }
  2329. }
  2330. // Verify that the bundle operands are identical between the two calls.
  2331. if (CI->hasOperandBundles() &&
  2332. !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
  2333. CI->op_begin() + CI->getBundleOperandsEndIndex(),
  2334. CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
  2335. BS.cancelScheduling(VL, VL0);
  2336. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2337. ReuseShuffleIndicies);
  2338. LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
  2339. << *CI << "!=" << *VL[i] << '\n');
  2340. return;
  2341. }
  2342. }
  2343. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2344. ReuseShuffleIndicies);
  2345. TE->setOperandsInOrder();
  2346. for (unsigned i = 0, e = CI->getNumArgOperands(); i != e; ++i) {
  2347. ValueList Operands;
  2348. // Prepare the operand vector.
  2349. for (Value *j : VL) {
  2350. CallInst *CI2 = dyn_cast<CallInst>(j);
  2351. Operands.push_back(CI2->getArgOperand(i));
  2352. }
  2353. buildTree_rec(Operands, Depth + 1, {TE, i});
  2354. }
  2355. return;
  2356. }
  2357. case Instruction::ShuffleVector: {
  2358. // If this is not an alternate sequence of opcode like add-sub
  2359. // then do not vectorize this instruction.
  2360. if (!S.isAltShuffle()) {
  2361. BS.cancelScheduling(VL, VL0);
  2362. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2363. ReuseShuffleIndicies);
  2364. LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
  2365. return;
  2366. }
  2367. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, UserTreeIdx,
  2368. ReuseShuffleIndicies);
  2369. LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
  2370. // Reorder operands if reordering would enable vectorization.
  2371. if (isa<BinaryOperator>(VL0)) {
  2372. ValueList Left, Right;
  2373. reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE);
  2374. TE->setOperand(0, Left);
  2375. TE->setOperand(1, Right);
  2376. buildTree_rec(Left, Depth + 1, {TE, 0});
  2377. buildTree_rec(Right, Depth + 1, {TE, 1});
  2378. return;
  2379. }
  2380. TE->setOperandsInOrder();
  2381. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  2382. ValueList Operands;
  2383. // Prepare the operand vector.
  2384. for (Value *j : VL)
  2385. Operands.push_back(cast<Instruction>(j)->getOperand(i));
  2386. buildTree_rec(Operands, Depth + 1, {TE, i});
  2387. }
  2388. return;
  2389. }
  2390. default:
  2391. BS.cancelScheduling(VL, VL0);
  2392. newTreeEntry(VL, None /*not vectorized*/, UserTreeIdx,
  2393. ReuseShuffleIndicies);
  2394. LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
  2395. return;
  2396. }
  2397. }
  2398. unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
  2399. unsigned N;
  2400. Type *EltTy;
  2401. auto *ST = dyn_cast<StructType>(T);
  2402. if (ST) {
  2403. N = ST->getNumElements();
  2404. EltTy = *ST->element_begin();
  2405. } else {
  2406. N = cast<ArrayType>(T)->getNumElements();
  2407. EltTy = cast<ArrayType>(T)->getElementType();
  2408. }
  2409. if (!isValidElementType(EltTy))
  2410. return 0;
  2411. uint64_t VTSize = DL.getTypeStoreSizeInBits(VectorType::get(EltTy, N));
  2412. if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
  2413. return 0;
  2414. if (ST) {
  2415. // Check that struct is homogeneous.
  2416. for (const auto *Ty : ST->elements())
  2417. if (Ty != EltTy)
  2418. return 0;
  2419. }
  2420. return N;
  2421. }
  2422. bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
  2423. SmallVectorImpl<unsigned> &CurrentOrder) const {
  2424. Instruction *E0 = cast<Instruction>(OpValue);
  2425. assert(E0->getOpcode() == Instruction::ExtractElement ||
  2426. E0->getOpcode() == Instruction::ExtractValue);
  2427. assert(E0->getOpcode() == getSameOpcode(VL).getOpcode() && "Invalid opcode");
  2428. // Check if all of the extracts come from the same vector and from the
  2429. // correct offset.
  2430. Value *Vec = E0->getOperand(0);
  2431. CurrentOrder.clear();
  2432. // We have to extract from a vector/aggregate with the same number of elements.
  2433. unsigned NElts;
  2434. if (E0->getOpcode() == Instruction::ExtractValue) {
  2435. const DataLayout &DL = E0->getModule()->getDataLayout();
  2436. NElts = canMapToVector(Vec->getType(), DL);
  2437. if (!NElts)
  2438. return false;
  2439. // Check if load can be rewritten as load of vector.
  2440. LoadInst *LI = dyn_cast<LoadInst>(Vec);
  2441. if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
  2442. return false;
  2443. } else {
  2444. NElts = Vec->getType()->getVectorNumElements();
  2445. }
  2446. if (NElts != VL.size())
  2447. return false;
  2448. // Check that all of the indices extract from the correct offset.
  2449. bool ShouldKeepOrder = true;
  2450. unsigned E = VL.size();
  2451. // Assign to all items the initial value E + 1 so we can check if the extract
  2452. // instruction index was used already.
  2453. // Also, later we can check that all the indices are used and we have a
  2454. // consecutive access in the extract instructions, by checking that no
  2455. // element of CurrentOrder still has value E + 1.
  2456. CurrentOrder.assign(E, E + 1);
  2457. unsigned I = 0;
  2458. for (; I < E; ++I) {
  2459. auto *Inst = cast<Instruction>(VL[I]);
  2460. if (Inst->getOperand(0) != Vec)
  2461. break;
  2462. Optional<unsigned> Idx = getExtractIndex(Inst);
  2463. if (!Idx)
  2464. break;
  2465. const unsigned ExtIdx = *Idx;
  2466. if (ExtIdx != I) {
  2467. if (ExtIdx >= E || CurrentOrder[ExtIdx] != E + 1)
  2468. break;
  2469. ShouldKeepOrder = false;
  2470. CurrentOrder[ExtIdx] = I;
  2471. } else {
  2472. if (CurrentOrder[I] != E + 1)
  2473. break;
  2474. CurrentOrder[I] = I;
  2475. }
  2476. }
  2477. if (I < E) {
  2478. CurrentOrder.clear();
  2479. return false;
  2480. }
  2481. return ShouldKeepOrder;
  2482. }
  2483. bool BoUpSLP::areAllUsersVectorized(Instruction *I) const {
  2484. return I->hasOneUse() ||
  2485. std::all_of(I->user_begin(), I->user_end(), [this](User *U) {
  2486. return ScalarToTreeEntry.count(U) > 0;
  2487. });
  2488. }
  2489. int BoUpSLP::getEntryCost(TreeEntry *E) {
  2490. ArrayRef<Value*> VL = E->Scalars;
  2491. Type *ScalarTy = VL[0]->getType();
  2492. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  2493. ScalarTy = SI->getValueOperand()->getType();
  2494. else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
  2495. ScalarTy = CI->getOperand(0)->getType();
  2496. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  2497. // If we have computed a smaller type for the expression, update VecTy so
  2498. // that the costs will be accurate.
  2499. if (MinBWs.count(VL[0]))
  2500. VecTy = VectorType::get(
  2501. IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
  2502. unsigned ReuseShuffleNumbers = E->ReuseShuffleIndices.size();
  2503. bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
  2504. int ReuseShuffleCost = 0;
  2505. if (NeedToShuffleReuses) {
  2506. ReuseShuffleCost =
  2507. TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
  2508. }
  2509. if (E->NeedToGather) {
  2510. if (allConstant(VL))
  2511. return 0;
  2512. if (isSplat(VL)) {
  2513. return ReuseShuffleCost +
  2514. TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy, 0);
  2515. }
  2516. if (getSameOpcode(VL).getOpcode() == Instruction::ExtractElement &&
  2517. allSameType(VL) && allSameBlock(VL)) {
  2518. Optional<TargetTransformInfo::ShuffleKind> ShuffleKind = isShuffle(VL);
  2519. if (ShuffleKind.hasValue()) {
  2520. int Cost = TTI->getShuffleCost(ShuffleKind.getValue(), VecTy);
  2521. for (auto *V : VL) {
  2522. // If all users of instruction are going to be vectorized and this
  2523. // instruction itself is not going to be vectorized, consider this
  2524. // instruction as dead and remove its cost from the final cost of the
  2525. // vectorized tree.
  2526. if (areAllUsersVectorized(cast<Instruction>(V)) &&
  2527. !ScalarToTreeEntry.count(V)) {
  2528. auto *IO = cast<ConstantInt>(
  2529. cast<ExtractElementInst>(V)->getIndexOperand());
  2530. Cost -= TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
  2531. IO->getZExtValue());
  2532. }
  2533. }
  2534. return ReuseShuffleCost + Cost;
  2535. }
  2536. }
  2537. return ReuseShuffleCost + getGatherCost(VL);
  2538. }
  2539. InstructionsState S = getSameOpcode(VL);
  2540. assert(S.getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
  2541. Instruction *VL0 = cast<Instruction>(S.OpValue);
  2542. unsigned ShuffleOrOp = S.isAltShuffle() ?
  2543. (unsigned) Instruction::ShuffleVector : S.getOpcode();
  2544. switch (ShuffleOrOp) {
  2545. case Instruction::PHI:
  2546. return 0;
  2547. case Instruction::ExtractValue:
  2548. case Instruction::ExtractElement:
  2549. if (NeedToShuffleReuses) {
  2550. unsigned Idx = 0;
  2551. for (unsigned I : E->ReuseShuffleIndices) {
  2552. if (ShuffleOrOp == Instruction::ExtractElement) {
  2553. auto *IO = cast<ConstantInt>(
  2554. cast<ExtractElementInst>(VL[I])->getIndexOperand());
  2555. Idx = IO->getZExtValue();
  2556. ReuseShuffleCost -= TTI->getVectorInstrCost(
  2557. Instruction::ExtractElement, VecTy, Idx);
  2558. } else {
  2559. ReuseShuffleCost -= TTI->getVectorInstrCost(
  2560. Instruction::ExtractElement, VecTy, Idx);
  2561. ++Idx;
  2562. }
  2563. }
  2564. Idx = ReuseShuffleNumbers;
  2565. for (Value *V : VL) {
  2566. if (ShuffleOrOp == Instruction::ExtractElement) {
  2567. auto *IO = cast<ConstantInt>(
  2568. cast<ExtractElementInst>(V)->getIndexOperand());
  2569. Idx = IO->getZExtValue();
  2570. } else {
  2571. --Idx;
  2572. }
  2573. ReuseShuffleCost +=
  2574. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, Idx);
  2575. }
  2576. }
  2577. if (!E->NeedToGather) {
  2578. int DeadCost = ReuseShuffleCost;
  2579. if (!E->ReorderIndices.empty()) {
  2580. // TODO: Merge this shuffle with the ReuseShuffleCost.
  2581. DeadCost += TTI->getShuffleCost(
  2582. TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
  2583. }
  2584. for (unsigned i = 0, e = VL.size(); i < e; ++i) {
  2585. Instruction *E = cast<Instruction>(VL[i]);
  2586. // If all users are going to be vectorized, instruction can be
  2587. // considered as dead.
  2588. // The same, if have only one user, it will be vectorized for sure.
  2589. if (areAllUsersVectorized(E)) {
  2590. // Take credit for instruction that will become dead.
  2591. if (E->hasOneUse()) {
  2592. Instruction *Ext = E->user_back();
  2593. if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  2594. all_of(Ext->users(),
  2595. [](User *U) { return isa<GetElementPtrInst>(U); })) {
  2596. // Use getExtractWithExtendCost() to calculate the cost of
  2597. // extractelement/ext pair.
  2598. DeadCost -= TTI->getExtractWithExtendCost(
  2599. Ext->getOpcode(), Ext->getType(), VecTy, i);
  2600. // Add back the cost of s|zext which is subtracted separately.
  2601. DeadCost += TTI->getCastInstrCost(
  2602. Ext->getOpcode(), Ext->getType(), E->getType(), Ext);
  2603. continue;
  2604. }
  2605. }
  2606. DeadCost -=
  2607. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, i);
  2608. }
  2609. }
  2610. return DeadCost;
  2611. }
  2612. return ReuseShuffleCost + getGatherCost(VL);
  2613. case Instruction::ZExt:
  2614. case Instruction::SExt:
  2615. case Instruction::FPToUI:
  2616. case Instruction::FPToSI:
  2617. case Instruction::FPExt:
  2618. case Instruction::PtrToInt:
  2619. case Instruction::IntToPtr:
  2620. case Instruction::SIToFP:
  2621. case Instruction::UIToFP:
  2622. case Instruction::Trunc:
  2623. case Instruction::FPTrunc:
  2624. case Instruction::BitCast: {
  2625. Type *SrcTy = VL0->getOperand(0)->getType();
  2626. int ScalarEltCost =
  2627. TTI->getCastInstrCost(S.getOpcode(), ScalarTy, SrcTy, VL0);
  2628. if (NeedToShuffleReuses) {
  2629. ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
  2630. }
  2631. // Calculate the cost of this instruction.
  2632. int ScalarCost = VL.size() * ScalarEltCost;
  2633. VectorType *SrcVecTy = VectorType::get(SrcTy, VL.size());
  2634. int VecCost = 0;
  2635. // Check if the values are candidates to demote.
  2636. if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
  2637. VecCost = ReuseShuffleCost +
  2638. TTI->getCastInstrCost(S.getOpcode(), VecTy, SrcVecTy, VL0);
  2639. }
  2640. return VecCost - ScalarCost;
  2641. }
  2642. case Instruction::FCmp:
  2643. case Instruction::ICmp:
  2644. case Instruction::Select: {
  2645. // Calculate the cost of this instruction.
  2646. int ScalarEltCost = TTI->getCmpSelInstrCost(S.getOpcode(), ScalarTy,
  2647. Builder.getInt1Ty(), VL0);
  2648. if (NeedToShuffleReuses) {
  2649. ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
  2650. }
  2651. VectorType *MaskTy = VectorType::get(Builder.getInt1Ty(), VL.size());
  2652. int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
  2653. int VecCost = TTI->getCmpSelInstrCost(S.getOpcode(), VecTy, MaskTy, VL0);
  2654. return ReuseShuffleCost + VecCost - ScalarCost;
  2655. }
  2656. case Instruction::FNeg:
  2657. case Instruction::Add:
  2658. case Instruction::FAdd:
  2659. case Instruction::Sub:
  2660. case Instruction::FSub:
  2661. case Instruction::Mul:
  2662. case Instruction::FMul:
  2663. case Instruction::UDiv:
  2664. case Instruction::SDiv:
  2665. case Instruction::FDiv:
  2666. case Instruction::URem:
  2667. case Instruction::SRem:
  2668. case Instruction::FRem:
  2669. case Instruction::Shl:
  2670. case Instruction::LShr:
  2671. case Instruction::AShr:
  2672. case Instruction::And:
  2673. case Instruction::Or:
  2674. case Instruction::Xor: {
  2675. // Certain instructions can be cheaper to vectorize if they have a
  2676. // constant second vector operand.
  2677. TargetTransformInfo::OperandValueKind Op1VK =
  2678. TargetTransformInfo::OK_AnyValue;
  2679. TargetTransformInfo::OperandValueKind Op2VK =
  2680. TargetTransformInfo::OK_UniformConstantValue;
  2681. TargetTransformInfo::OperandValueProperties Op1VP =
  2682. TargetTransformInfo::OP_None;
  2683. TargetTransformInfo::OperandValueProperties Op2VP =
  2684. TargetTransformInfo::OP_PowerOf2;
  2685. // If all operands are exactly the same ConstantInt then set the
  2686. // operand kind to OK_UniformConstantValue.
  2687. // If instead not all operands are constants, then set the operand kind
  2688. // to OK_AnyValue. If all operands are constants but not the same,
  2689. // then set the operand kind to OK_NonUniformConstantValue.
  2690. ConstantInt *CInt0 = nullptr;
  2691. for (unsigned i = 0, e = VL.size(); i < e; ++i) {
  2692. const Instruction *I = cast<Instruction>(VL[i]);
  2693. unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
  2694. ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
  2695. if (!CInt) {
  2696. Op2VK = TargetTransformInfo::OK_AnyValue;
  2697. Op2VP = TargetTransformInfo::OP_None;
  2698. break;
  2699. }
  2700. if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
  2701. !CInt->getValue().isPowerOf2())
  2702. Op2VP = TargetTransformInfo::OP_None;
  2703. if (i == 0) {
  2704. CInt0 = CInt;
  2705. continue;
  2706. }
  2707. if (CInt0 != CInt)
  2708. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  2709. }
  2710. SmallVector<const Value *, 4> Operands(VL0->operand_values());
  2711. int ScalarEltCost = TTI->getArithmeticInstrCost(
  2712. S.getOpcode(), ScalarTy, Op1VK, Op2VK, Op1VP, Op2VP, Operands);
  2713. if (NeedToShuffleReuses) {
  2714. ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
  2715. }
  2716. int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
  2717. int VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy, Op1VK,
  2718. Op2VK, Op1VP, Op2VP, Operands);
  2719. return ReuseShuffleCost + VecCost - ScalarCost;
  2720. }
  2721. case Instruction::GetElementPtr: {
  2722. TargetTransformInfo::OperandValueKind Op1VK =
  2723. TargetTransformInfo::OK_AnyValue;
  2724. TargetTransformInfo::OperandValueKind Op2VK =
  2725. TargetTransformInfo::OK_UniformConstantValue;
  2726. int ScalarEltCost =
  2727. TTI->getArithmeticInstrCost(Instruction::Add, ScalarTy, Op1VK, Op2VK);
  2728. if (NeedToShuffleReuses) {
  2729. ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
  2730. }
  2731. int ScalarCost = VecTy->getNumElements() * ScalarEltCost;
  2732. int VecCost =
  2733. TTI->getArithmeticInstrCost(Instruction::Add, VecTy, Op1VK, Op2VK);
  2734. return ReuseShuffleCost + VecCost - ScalarCost;
  2735. }
  2736. case Instruction::Load: {
  2737. // Cost of wide load - cost of scalar loads.
  2738. unsigned alignment = cast<LoadInst>(VL0)->getAlignment();
  2739. int ScalarEltCost =
  2740. TTI->getMemoryOpCost(Instruction::Load, ScalarTy, alignment, 0, VL0);
  2741. if (NeedToShuffleReuses) {
  2742. ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
  2743. }
  2744. int ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
  2745. int VecLdCost =
  2746. TTI->getMemoryOpCost(Instruction::Load, VecTy, alignment, 0, VL0);
  2747. if (!E->ReorderIndices.empty()) {
  2748. // TODO: Merge this shuffle with the ReuseShuffleCost.
  2749. VecLdCost += TTI->getShuffleCost(
  2750. TargetTransformInfo::SK_PermuteSingleSrc, VecTy);
  2751. }
  2752. return ReuseShuffleCost + VecLdCost - ScalarLdCost;
  2753. }
  2754. case Instruction::Store: {
  2755. // We know that we can merge the stores. Calculate the cost.
  2756. unsigned alignment = cast<StoreInst>(VL0)->getAlignment();
  2757. int ScalarEltCost =
  2758. TTI->getMemoryOpCost(Instruction::Store, ScalarTy, alignment, 0, VL0);
  2759. if (NeedToShuffleReuses) {
  2760. ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
  2761. }
  2762. int ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
  2763. int VecStCost =
  2764. TTI->getMemoryOpCost(Instruction::Store, VecTy, alignment, 0, VL0);
  2765. return ReuseShuffleCost + VecStCost - ScalarStCost;
  2766. }
  2767. case Instruction::Call: {
  2768. CallInst *CI = cast<CallInst>(VL0);
  2769. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  2770. // Calculate the cost of the scalar and vector calls.
  2771. SmallVector<Type *, 4> ScalarTys;
  2772. for (unsigned op = 0, opc = CI->getNumArgOperands(); op != opc; ++op)
  2773. ScalarTys.push_back(CI->getArgOperand(op)->getType());
  2774. FastMathFlags FMF;
  2775. if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
  2776. FMF = FPMO->getFastMathFlags();
  2777. int ScalarEltCost =
  2778. TTI->getIntrinsicInstrCost(ID, ScalarTy, ScalarTys, FMF);
  2779. if (NeedToShuffleReuses) {
  2780. ReuseShuffleCost -= (ReuseShuffleNumbers - VL.size()) * ScalarEltCost;
  2781. }
  2782. int ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
  2783. SmallVector<Value *, 4> Args(CI->arg_operands());
  2784. int VecCallCost = TTI->getIntrinsicInstrCost(ID, CI->getType(), Args, FMF,
  2785. VecTy->getNumElements());
  2786. LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
  2787. << " (" << VecCallCost << "-" << ScalarCallCost << ")"
  2788. << " for " << *CI << "\n");
  2789. return ReuseShuffleCost + VecCallCost - ScalarCallCost;
  2790. }
  2791. case Instruction::ShuffleVector: {
  2792. assert(S.isAltShuffle() &&
  2793. ((Instruction::isBinaryOp(S.getOpcode()) &&
  2794. Instruction::isBinaryOp(S.getAltOpcode())) ||
  2795. (Instruction::isCast(S.getOpcode()) &&
  2796. Instruction::isCast(S.getAltOpcode()))) &&
  2797. "Invalid Shuffle Vector Operand");
  2798. int ScalarCost = 0;
  2799. if (NeedToShuffleReuses) {
  2800. for (unsigned Idx : E->ReuseShuffleIndices) {
  2801. Instruction *I = cast<Instruction>(VL[Idx]);
  2802. ReuseShuffleCost -= TTI->getInstructionCost(
  2803. I, TargetTransformInfo::TCK_RecipThroughput);
  2804. }
  2805. for (Value *V : VL) {
  2806. Instruction *I = cast<Instruction>(V);
  2807. ReuseShuffleCost += TTI->getInstructionCost(
  2808. I, TargetTransformInfo::TCK_RecipThroughput);
  2809. }
  2810. }
  2811. for (Value *i : VL) {
  2812. Instruction *I = cast<Instruction>(i);
  2813. assert(S.isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
  2814. ScalarCost += TTI->getInstructionCost(
  2815. I, TargetTransformInfo::TCK_RecipThroughput);
  2816. }
  2817. // VecCost is equal to sum of the cost of creating 2 vectors
  2818. // and the cost of creating shuffle.
  2819. int VecCost = 0;
  2820. if (Instruction::isBinaryOp(S.getOpcode())) {
  2821. VecCost = TTI->getArithmeticInstrCost(S.getOpcode(), VecTy);
  2822. VecCost += TTI->getArithmeticInstrCost(S.getAltOpcode(), VecTy);
  2823. } else {
  2824. Type *Src0SclTy = S.MainOp->getOperand(0)->getType();
  2825. Type *Src1SclTy = S.AltOp->getOperand(0)->getType();
  2826. VectorType *Src0Ty = VectorType::get(Src0SclTy, VL.size());
  2827. VectorType *Src1Ty = VectorType::get(Src1SclTy, VL.size());
  2828. VecCost = TTI->getCastInstrCost(S.getOpcode(), VecTy, Src0Ty);
  2829. VecCost += TTI->getCastInstrCost(S.getAltOpcode(), VecTy, Src1Ty);
  2830. }
  2831. VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_Select, VecTy, 0);
  2832. return ReuseShuffleCost + VecCost - ScalarCost;
  2833. }
  2834. default:
  2835. llvm_unreachable("Unknown instruction");
  2836. }
  2837. }
  2838. bool BoUpSLP::isFullyVectorizableTinyTree() const {
  2839. LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
  2840. << VectorizableTree.size() << " is fully vectorizable .\n");
  2841. // We only handle trees of heights 1 and 2.
  2842. if (VectorizableTree.size() == 1 && !VectorizableTree[0]->NeedToGather)
  2843. return true;
  2844. if (VectorizableTree.size() != 2)
  2845. return false;
  2846. // Handle splat and all-constants stores.
  2847. if (!VectorizableTree[0]->NeedToGather &&
  2848. (allConstant(VectorizableTree[1]->Scalars) ||
  2849. isSplat(VectorizableTree[1]->Scalars)))
  2850. return true;
  2851. // Gathering cost would be too much for tiny trees.
  2852. if (VectorizableTree[0]->NeedToGather || VectorizableTree[1]->NeedToGather)
  2853. return false;
  2854. return true;
  2855. }
  2856. bool BoUpSLP::isTreeTinyAndNotFullyVectorizable() const {
  2857. // We can vectorize the tree if its size is greater than or equal to the
  2858. // minimum size specified by the MinTreeSize command line option.
  2859. if (VectorizableTree.size() >= MinTreeSize)
  2860. return false;
  2861. // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
  2862. // can vectorize it if we can prove it fully vectorizable.
  2863. if (isFullyVectorizableTinyTree())
  2864. return false;
  2865. assert(VectorizableTree.empty()
  2866. ? ExternalUses.empty()
  2867. : true && "We shouldn't have any external users");
  2868. // Otherwise, we can't vectorize the tree. It is both tiny and not fully
  2869. // vectorizable.
  2870. return true;
  2871. }
  2872. int BoUpSLP::getSpillCost() const {
  2873. // Walk from the bottom of the tree to the top, tracking which values are
  2874. // live. When we see a call instruction that is not part of our tree,
  2875. // query TTI to see if there is a cost to keeping values live over it
  2876. // (for example, if spills and fills are required).
  2877. unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
  2878. int Cost = 0;
  2879. SmallPtrSet<Instruction*, 4> LiveValues;
  2880. Instruction *PrevInst = nullptr;
  2881. for (const auto &TEPtr : VectorizableTree) {
  2882. Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
  2883. if (!Inst)
  2884. continue;
  2885. if (!PrevInst) {
  2886. PrevInst = Inst;
  2887. continue;
  2888. }
  2889. // Update LiveValues.
  2890. LiveValues.erase(PrevInst);
  2891. for (auto &J : PrevInst->operands()) {
  2892. if (isa<Instruction>(&*J) && getTreeEntry(&*J))
  2893. LiveValues.insert(cast<Instruction>(&*J));
  2894. }
  2895. LLVM_DEBUG({
  2896. dbgs() << "SLP: #LV: " << LiveValues.size();
  2897. for (auto *X : LiveValues)
  2898. dbgs() << " " << X->getName();
  2899. dbgs() << ", Looking at ";
  2900. Inst->dump();
  2901. });
  2902. // Now find the sequence of instructions between PrevInst and Inst.
  2903. unsigned NumCalls = 0;
  2904. BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
  2905. PrevInstIt =
  2906. PrevInst->getIterator().getReverse();
  2907. while (InstIt != PrevInstIt) {
  2908. if (PrevInstIt == PrevInst->getParent()->rend()) {
  2909. PrevInstIt = Inst->getParent()->rbegin();
  2910. continue;
  2911. }
  2912. // Debug informations don't impact spill cost.
  2913. if ((isa<CallInst>(&*PrevInstIt) &&
  2914. !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
  2915. &*PrevInstIt != PrevInst)
  2916. NumCalls++;
  2917. ++PrevInstIt;
  2918. }
  2919. if (NumCalls) {
  2920. SmallVector<Type*, 4> V;
  2921. for (auto *II : LiveValues)
  2922. V.push_back(VectorType::get(II->getType(), BundleWidth));
  2923. Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
  2924. }
  2925. PrevInst = Inst;
  2926. }
  2927. return Cost;
  2928. }
  2929. int BoUpSLP::getTreeCost() {
  2930. int Cost = 0;
  2931. LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
  2932. << VectorizableTree.size() << ".\n");
  2933. unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
  2934. for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
  2935. TreeEntry &TE = *VectorizableTree[I].get();
  2936. // We create duplicate tree entries for gather sequences that have multiple
  2937. // uses. However, we should not compute the cost of duplicate sequences.
  2938. // For example, if we have a build vector (i.e., insertelement sequence)
  2939. // that is used by more than one vector instruction, we only need to
  2940. // compute the cost of the insertelement instructions once. The redundant
  2941. // instructions will be eliminated by CSE.
  2942. //
  2943. // We should consider not creating duplicate tree entries for gather
  2944. // sequences, and instead add additional edges to the tree representing
  2945. // their uses. Since such an approach results in fewer total entries,
  2946. // existing heuristics based on tree size may yield different results.
  2947. //
  2948. if (TE.NeedToGather &&
  2949. std::any_of(
  2950. std::next(VectorizableTree.begin(), I + 1), VectorizableTree.end(),
  2951. [TE](const std::unique_ptr<TreeEntry> &EntryPtr) {
  2952. return EntryPtr->NeedToGather && EntryPtr->isSame(TE.Scalars);
  2953. }))
  2954. continue;
  2955. int C = getEntryCost(&TE);
  2956. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  2957. << " for bundle that starts with " << *TE.Scalars[0]
  2958. << ".\n");
  2959. Cost += C;
  2960. }
  2961. SmallPtrSet<Value *, 16> ExtractCostCalculated;
  2962. int ExtractCost = 0;
  2963. for (ExternalUser &EU : ExternalUses) {
  2964. // We only add extract cost once for the same scalar.
  2965. if (!ExtractCostCalculated.insert(EU.Scalar).second)
  2966. continue;
  2967. // Uses by ephemeral values are free (because the ephemeral value will be
  2968. // removed prior to code generation, and so the extraction will be
  2969. // removed as well).
  2970. if (EphValues.count(EU.User))
  2971. continue;
  2972. // If we plan to rewrite the tree in a smaller type, we will need to sign
  2973. // extend the extracted value back to the original type. Here, we account
  2974. // for the extract and the added cost of the sign extend if needed.
  2975. auto *VecTy = VectorType::get(EU.Scalar->getType(), BundleWidth);
  2976. auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
  2977. if (MinBWs.count(ScalarRoot)) {
  2978. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  2979. auto Extend =
  2980. MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
  2981. VecTy = VectorType::get(MinTy, BundleWidth);
  2982. ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
  2983. VecTy, EU.Lane);
  2984. } else {
  2985. ExtractCost +=
  2986. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
  2987. }
  2988. }
  2989. int SpillCost = getSpillCost();
  2990. Cost += SpillCost + ExtractCost;
  2991. std::string Str;
  2992. {
  2993. raw_string_ostream OS(Str);
  2994. OS << "SLP: Spill Cost = " << SpillCost << ".\n"
  2995. << "SLP: Extract Cost = " << ExtractCost << ".\n"
  2996. << "SLP: Total Cost = " << Cost << ".\n";
  2997. }
  2998. LLVM_DEBUG(dbgs() << Str);
  2999. if (ViewSLPTree)
  3000. ViewGraph(this, "SLP" + F->getName(), false, Str);
  3001. return Cost;
  3002. }
  3003. int BoUpSLP::getGatherCost(Type *Ty,
  3004. const DenseSet<unsigned> &ShuffledIndices) const {
  3005. int Cost = 0;
  3006. for (unsigned i = 0, e = cast<VectorType>(Ty)->getNumElements(); i < e; ++i)
  3007. if (!ShuffledIndices.count(i))
  3008. Cost += TTI->getVectorInstrCost(Instruction::InsertElement, Ty, i);
  3009. if (!ShuffledIndices.empty())
  3010. Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
  3011. return Cost;
  3012. }
  3013. int BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
  3014. // Find the type of the operands in VL.
  3015. Type *ScalarTy = VL[0]->getType();
  3016. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  3017. ScalarTy = SI->getValueOperand()->getType();
  3018. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  3019. // Find the cost of inserting/extracting values from the vector.
  3020. // Check if the same elements are inserted several times and count them as
  3021. // shuffle candidates.
  3022. DenseSet<unsigned> ShuffledElements;
  3023. DenseSet<Value *> UniqueElements;
  3024. // Iterate in reverse order to consider insert elements with the high cost.
  3025. for (unsigned I = VL.size(); I > 0; --I) {
  3026. unsigned Idx = I - 1;
  3027. if (!UniqueElements.insert(VL[Idx]).second)
  3028. ShuffledElements.insert(Idx);
  3029. }
  3030. return getGatherCost(VecTy, ShuffledElements);
  3031. }
  3032. // Perform operand reordering on the instructions in VL and return the reordered
  3033. // operands in Left and Right.
  3034. void BoUpSLP::reorderInputsAccordingToOpcode(
  3035. ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left,
  3036. SmallVectorImpl<Value *> &Right, const DataLayout &DL,
  3037. ScalarEvolution &SE) {
  3038. if (VL.empty())
  3039. return;
  3040. VLOperands Ops(VL, DL, SE);
  3041. // Reorder the operands in place.
  3042. Ops.reorder();
  3043. Left = Ops.getVL(0);
  3044. Right = Ops.getVL(1);
  3045. }
  3046. void BoUpSLP::setInsertPointAfterBundle(ArrayRef<Value *> VL,
  3047. const InstructionsState &S) {
  3048. // Get the basic block this bundle is in. All instructions in the bundle
  3049. // should be in this block.
  3050. auto *Front = cast<Instruction>(S.OpValue);
  3051. auto *BB = Front->getParent();
  3052. assert(llvm::all_of(make_range(VL.begin(), VL.end()), [=](Value *V) -> bool {
  3053. auto *I = cast<Instruction>(V);
  3054. return !S.isOpcodeOrAlt(I) || I->getParent() == BB;
  3055. }));
  3056. // The last instruction in the bundle in program order.
  3057. Instruction *LastInst = nullptr;
  3058. // Find the last instruction. The common case should be that BB has been
  3059. // scheduled, and the last instruction is VL.back(). So we start with
  3060. // VL.back() and iterate over schedule data until we reach the end of the
  3061. // bundle. The end of the bundle is marked by null ScheduleData.
  3062. if (BlocksSchedules.count(BB)) {
  3063. auto *Bundle =
  3064. BlocksSchedules[BB]->getScheduleData(isOneOf(S, VL.back()));
  3065. if (Bundle && Bundle->isPartOfBundle())
  3066. for (; Bundle; Bundle = Bundle->NextInBundle)
  3067. if (Bundle->OpValue == Bundle->Inst)
  3068. LastInst = Bundle->Inst;
  3069. }
  3070. // LastInst can still be null at this point if there's either not an entry
  3071. // for BB in BlocksSchedules or there's no ScheduleData available for
  3072. // VL.back(). This can be the case if buildTree_rec aborts for various
  3073. // reasons (e.g., the maximum recursion depth is reached, the maximum region
  3074. // size is reached, etc.). ScheduleData is initialized in the scheduling
  3075. // "dry-run".
  3076. //
  3077. // If this happens, we can still find the last instruction by brute force. We
  3078. // iterate forwards from Front (inclusive) until we either see all
  3079. // instructions in the bundle or reach the end of the block. If Front is the
  3080. // last instruction in program order, LastInst will be set to Front, and we
  3081. // will visit all the remaining instructions in the block.
  3082. //
  3083. // One of the reasons we exit early from buildTree_rec is to place an upper
  3084. // bound on compile-time. Thus, taking an additional compile-time hit here is
  3085. // not ideal. However, this should be exceedingly rare since it requires that
  3086. // we both exit early from buildTree_rec and that the bundle be out-of-order
  3087. // (causing us to iterate all the way to the end of the block).
  3088. if (!LastInst) {
  3089. SmallPtrSet<Value *, 16> Bundle(VL.begin(), VL.end());
  3090. for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
  3091. if (Bundle.erase(&I) && S.isOpcodeOrAlt(&I))
  3092. LastInst = &I;
  3093. if (Bundle.empty())
  3094. break;
  3095. }
  3096. }
  3097. // Set the insertion point after the last instruction in the bundle. Set the
  3098. // debug location to Front.
  3099. Builder.SetInsertPoint(BB, ++LastInst->getIterator());
  3100. Builder.SetCurrentDebugLocation(Front->getDebugLoc());
  3101. }
  3102. Value *BoUpSLP::Gather(ArrayRef<Value *> VL, VectorType *Ty) {
  3103. Value *Vec = UndefValue::get(Ty);
  3104. // Generate the 'InsertElement' instruction.
  3105. for (unsigned i = 0; i < Ty->getNumElements(); ++i) {
  3106. Vec = Builder.CreateInsertElement(Vec, VL[i], Builder.getInt32(i));
  3107. if (Instruction *Insrt = dyn_cast<Instruction>(Vec)) {
  3108. GatherSeq.insert(Insrt);
  3109. CSEBlocks.insert(Insrt->getParent());
  3110. // Add to our 'need-to-extract' list.
  3111. if (TreeEntry *E = getTreeEntry(VL[i])) {
  3112. // Find which lane we need to extract.
  3113. int FoundLane = -1;
  3114. for (unsigned Lane = 0, LE = E->Scalars.size(); Lane != LE; ++Lane) {
  3115. // Is this the lane of the scalar that we are looking for ?
  3116. if (E->Scalars[Lane] == VL[i]) {
  3117. FoundLane = Lane;
  3118. break;
  3119. }
  3120. }
  3121. assert(FoundLane >= 0 && "Could not find the correct lane");
  3122. if (!E->ReuseShuffleIndices.empty()) {
  3123. FoundLane =
  3124. std::distance(E->ReuseShuffleIndices.begin(),
  3125. llvm::find(E->ReuseShuffleIndices, FoundLane));
  3126. }
  3127. ExternalUses.push_back(ExternalUser(VL[i], Insrt, FoundLane));
  3128. }
  3129. }
  3130. }
  3131. return Vec;
  3132. }
  3133. Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
  3134. InstructionsState S = getSameOpcode(VL);
  3135. if (S.getOpcode()) {
  3136. if (TreeEntry *E = getTreeEntry(S.OpValue)) {
  3137. if (E->isSame(VL)) {
  3138. Value *V = vectorizeTree(E);
  3139. if (VL.size() == E->Scalars.size() && !E->ReuseShuffleIndices.empty()) {
  3140. // We need to get the vectorized value but without shuffle.
  3141. if (auto *SV = dyn_cast<ShuffleVectorInst>(V)) {
  3142. V = SV->getOperand(0);
  3143. } else {
  3144. // Reshuffle to get only unique values.
  3145. SmallVector<unsigned, 4> UniqueIdxs;
  3146. SmallSet<unsigned, 4> UsedIdxs;
  3147. for(unsigned Idx : E->ReuseShuffleIndices)
  3148. if (UsedIdxs.insert(Idx).second)
  3149. UniqueIdxs.emplace_back(Idx);
  3150. V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
  3151. UniqueIdxs);
  3152. }
  3153. }
  3154. return V;
  3155. }
  3156. }
  3157. }
  3158. Type *ScalarTy = S.OpValue->getType();
  3159. if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
  3160. ScalarTy = SI->getValueOperand()->getType();
  3161. // Check that every instruction appears once in this bundle.
  3162. SmallVector<unsigned, 4> ReuseShuffleIndicies;
  3163. SmallVector<Value *, 4> UniqueValues;
  3164. if (VL.size() > 2) {
  3165. DenseMap<Value *, unsigned> UniquePositions;
  3166. for (Value *V : VL) {
  3167. auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
  3168. ReuseShuffleIndicies.emplace_back(Res.first->second);
  3169. if (Res.second || isa<Constant>(V))
  3170. UniqueValues.emplace_back(V);
  3171. }
  3172. // Do not shuffle single element or if number of unique values is not power
  3173. // of 2.
  3174. if (UniqueValues.size() == VL.size() || UniqueValues.size() <= 1 ||
  3175. !llvm::isPowerOf2_32(UniqueValues.size()))
  3176. ReuseShuffleIndicies.clear();
  3177. else
  3178. VL = UniqueValues;
  3179. }
  3180. VectorType *VecTy = VectorType::get(ScalarTy, VL.size());
  3181. Value *V = Gather(VL, VecTy);
  3182. if (!ReuseShuffleIndicies.empty()) {
  3183. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3184. ReuseShuffleIndicies, "shuffle");
  3185. if (auto *I = dyn_cast<Instruction>(V)) {
  3186. GatherSeq.insert(I);
  3187. CSEBlocks.insert(I->getParent());
  3188. }
  3189. }
  3190. return V;
  3191. }
  3192. static void inversePermutation(ArrayRef<unsigned> Indices,
  3193. SmallVectorImpl<unsigned> &Mask) {
  3194. Mask.clear();
  3195. const unsigned E = Indices.size();
  3196. Mask.resize(E);
  3197. for (unsigned I = 0; I < E; ++I)
  3198. Mask[Indices[I]] = I;
  3199. }
  3200. Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
  3201. IRBuilder<>::InsertPointGuard Guard(Builder);
  3202. if (E->VectorizedValue) {
  3203. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
  3204. return E->VectorizedValue;
  3205. }
  3206. InstructionsState S = getSameOpcode(E->Scalars);
  3207. Instruction *VL0 = cast<Instruction>(S.OpValue);
  3208. Type *ScalarTy = VL0->getType();
  3209. if (StoreInst *SI = dyn_cast<StoreInst>(VL0))
  3210. ScalarTy = SI->getValueOperand()->getType();
  3211. VectorType *VecTy = VectorType::get(ScalarTy, E->Scalars.size());
  3212. bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
  3213. if (E->NeedToGather) {
  3214. setInsertPointAfterBundle(E->Scalars, S);
  3215. auto *V = Gather(E->Scalars, VecTy);
  3216. if (NeedToShuffleReuses) {
  3217. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3218. E->ReuseShuffleIndices, "shuffle");
  3219. if (auto *I = dyn_cast<Instruction>(V)) {
  3220. GatherSeq.insert(I);
  3221. CSEBlocks.insert(I->getParent());
  3222. }
  3223. }
  3224. E->VectorizedValue = V;
  3225. return V;
  3226. }
  3227. unsigned ShuffleOrOp = S.isAltShuffle() ?
  3228. (unsigned) Instruction::ShuffleVector : S.getOpcode();
  3229. switch (ShuffleOrOp) {
  3230. case Instruction::PHI: {
  3231. PHINode *PH = dyn_cast<PHINode>(VL0);
  3232. Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
  3233. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  3234. PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
  3235. Value *V = NewPhi;
  3236. if (NeedToShuffleReuses) {
  3237. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3238. E->ReuseShuffleIndices, "shuffle");
  3239. }
  3240. E->VectorizedValue = V;
  3241. // PHINodes may have multiple entries from the same block. We want to
  3242. // visit every block once.
  3243. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  3244. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  3245. ValueList Operands;
  3246. BasicBlock *IBB = PH->getIncomingBlock(i);
  3247. if (!VisitedBBs.insert(IBB).second) {
  3248. NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
  3249. continue;
  3250. }
  3251. Builder.SetInsertPoint(IBB->getTerminator());
  3252. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  3253. Value *Vec = vectorizeTree(E->getOperand(i));
  3254. NewPhi->addIncoming(Vec, IBB);
  3255. }
  3256. assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
  3257. "Invalid number of incoming values");
  3258. return V;
  3259. }
  3260. case Instruction::ExtractElement: {
  3261. if (!E->NeedToGather) {
  3262. Value *V = E->getSingleOperand(0);
  3263. if (!E->ReorderIndices.empty()) {
  3264. OrdersType Mask;
  3265. inversePermutation(E->ReorderIndices, Mask);
  3266. Builder.SetInsertPoint(VL0);
  3267. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy), Mask,
  3268. "reorder_shuffle");
  3269. }
  3270. if (NeedToShuffleReuses) {
  3271. // TODO: Merge this shuffle with the ReorderShuffleMask.
  3272. if (E->ReorderIndices.empty())
  3273. Builder.SetInsertPoint(VL0);
  3274. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3275. E->ReuseShuffleIndices, "shuffle");
  3276. }
  3277. E->VectorizedValue = V;
  3278. return V;
  3279. }
  3280. setInsertPointAfterBundle(E->Scalars, S);
  3281. auto *V = Gather(E->Scalars, VecTy);
  3282. if (NeedToShuffleReuses) {
  3283. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3284. E->ReuseShuffleIndices, "shuffle");
  3285. if (auto *I = dyn_cast<Instruction>(V)) {
  3286. GatherSeq.insert(I);
  3287. CSEBlocks.insert(I->getParent());
  3288. }
  3289. }
  3290. E->VectorizedValue = V;
  3291. return V;
  3292. }
  3293. case Instruction::ExtractValue: {
  3294. if (!E->NeedToGather) {
  3295. LoadInst *LI = cast<LoadInst>(E->getSingleOperand(0));
  3296. Builder.SetInsertPoint(LI);
  3297. PointerType *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
  3298. Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
  3299. LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlignment());
  3300. Value *NewV = propagateMetadata(V, E->Scalars);
  3301. if (!E->ReorderIndices.empty()) {
  3302. OrdersType Mask;
  3303. inversePermutation(E->ReorderIndices, Mask);
  3304. NewV = Builder.CreateShuffleVector(NewV, UndefValue::get(VecTy), Mask,
  3305. "reorder_shuffle");
  3306. }
  3307. if (NeedToShuffleReuses) {
  3308. // TODO: Merge this shuffle with the ReorderShuffleMask.
  3309. NewV = Builder.CreateShuffleVector(
  3310. NewV, UndefValue::get(VecTy), E->ReuseShuffleIndices, "shuffle");
  3311. }
  3312. E->VectorizedValue = NewV;
  3313. return NewV;
  3314. }
  3315. setInsertPointAfterBundle(E->Scalars, S);
  3316. auto *V = Gather(E->Scalars, VecTy);
  3317. if (NeedToShuffleReuses) {
  3318. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3319. E->ReuseShuffleIndices, "shuffle");
  3320. if (auto *I = dyn_cast<Instruction>(V)) {
  3321. GatherSeq.insert(I);
  3322. CSEBlocks.insert(I->getParent());
  3323. }
  3324. }
  3325. E->VectorizedValue = V;
  3326. return V;
  3327. }
  3328. case Instruction::ZExt:
  3329. case Instruction::SExt:
  3330. case Instruction::FPToUI:
  3331. case Instruction::FPToSI:
  3332. case Instruction::FPExt:
  3333. case Instruction::PtrToInt:
  3334. case Instruction::IntToPtr:
  3335. case Instruction::SIToFP:
  3336. case Instruction::UIToFP:
  3337. case Instruction::Trunc:
  3338. case Instruction::FPTrunc:
  3339. case Instruction::BitCast: {
  3340. setInsertPointAfterBundle(E->Scalars, S);
  3341. Value *InVec = vectorizeTree(E->getOperand(0));
  3342. if (E->VectorizedValue) {
  3343. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  3344. return E->VectorizedValue;
  3345. }
  3346. CastInst *CI = dyn_cast<CastInst>(VL0);
  3347. Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
  3348. if (NeedToShuffleReuses) {
  3349. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3350. E->ReuseShuffleIndices, "shuffle");
  3351. }
  3352. E->VectorizedValue = V;
  3353. ++NumVectorInstructions;
  3354. return V;
  3355. }
  3356. case Instruction::FCmp:
  3357. case Instruction::ICmp: {
  3358. setInsertPointAfterBundle(E->Scalars, S);
  3359. Value *L = vectorizeTree(E->getOperand(0));
  3360. Value *R = vectorizeTree(E->getOperand(1));
  3361. if (E->VectorizedValue) {
  3362. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  3363. return E->VectorizedValue;
  3364. }
  3365. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  3366. Value *V;
  3367. if (S.getOpcode() == Instruction::FCmp)
  3368. V = Builder.CreateFCmp(P0, L, R);
  3369. else
  3370. V = Builder.CreateICmp(P0, L, R);
  3371. propagateIRFlags(V, E->Scalars, VL0);
  3372. if (NeedToShuffleReuses) {
  3373. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3374. E->ReuseShuffleIndices, "shuffle");
  3375. }
  3376. E->VectorizedValue = V;
  3377. ++NumVectorInstructions;
  3378. return V;
  3379. }
  3380. case Instruction::Select: {
  3381. setInsertPointAfterBundle(E->Scalars, S);
  3382. Value *Cond = vectorizeTree(E->getOperand(0));
  3383. Value *True = vectorizeTree(E->getOperand(1));
  3384. Value *False = vectorizeTree(E->getOperand(2));
  3385. if (E->VectorizedValue) {
  3386. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  3387. return E->VectorizedValue;
  3388. }
  3389. Value *V = Builder.CreateSelect(Cond, True, False);
  3390. if (NeedToShuffleReuses) {
  3391. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3392. E->ReuseShuffleIndices, "shuffle");
  3393. }
  3394. E->VectorizedValue = V;
  3395. ++NumVectorInstructions;
  3396. return V;
  3397. }
  3398. case Instruction::FNeg: {
  3399. setInsertPointAfterBundle(E->Scalars, S);
  3400. Value *Op = vectorizeTree(E->getOperand(0));
  3401. if (E->VectorizedValue) {
  3402. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  3403. return E->VectorizedValue;
  3404. }
  3405. Value *V = Builder.CreateUnOp(
  3406. static_cast<Instruction::UnaryOps>(S.getOpcode()), Op);
  3407. propagateIRFlags(V, E->Scalars, VL0);
  3408. if (auto *I = dyn_cast<Instruction>(V))
  3409. V = propagateMetadata(I, E->Scalars);
  3410. if (NeedToShuffleReuses) {
  3411. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3412. E->ReuseShuffleIndices, "shuffle");
  3413. }
  3414. E->VectorizedValue = V;
  3415. ++NumVectorInstructions;
  3416. return V;
  3417. }
  3418. case Instruction::Add:
  3419. case Instruction::FAdd:
  3420. case Instruction::Sub:
  3421. case Instruction::FSub:
  3422. case Instruction::Mul:
  3423. case Instruction::FMul:
  3424. case Instruction::UDiv:
  3425. case Instruction::SDiv:
  3426. case Instruction::FDiv:
  3427. case Instruction::URem:
  3428. case Instruction::SRem:
  3429. case Instruction::FRem:
  3430. case Instruction::Shl:
  3431. case Instruction::LShr:
  3432. case Instruction::AShr:
  3433. case Instruction::And:
  3434. case Instruction::Or:
  3435. case Instruction::Xor: {
  3436. setInsertPointAfterBundle(E->Scalars, S);
  3437. Value *LHS = vectorizeTree(E->getOperand(0));
  3438. Value *RHS = vectorizeTree(E->getOperand(1));
  3439. if (E->VectorizedValue) {
  3440. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  3441. return E->VectorizedValue;
  3442. }
  3443. Value *V = Builder.CreateBinOp(
  3444. static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
  3445. propagateIRFlags(V, E->Scalars, VL0);
  3446. if (auto *I = dyn_cast<Instruction>(V))
  3447. V = propagateMetadata(I, E->Scalars);
  3448. if (NeedToShuffleReuses) {
  3449. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3450. E->ReuseShuffleIndices, "shuffle");
  3451. }
  3452. E->VectorizedValue = V;
  3453. ++NumVectorInstructions;
  3454. return V;
  3455. }
  3456. case Instruction::Load: {
  3457. // Loads are inserted at the head of the tree because we don't want to
  3458. // sink them all the way down past store instructions.
  3459. bool IsReorder = !E->ReorderIndices.empty();
  3460. if (IsReorder) {
  3461. S = getSameOpcode(E->Scalars, E->ReorderIndices.front());
  3462. VL0 = cast<Instruction>(S.OpValue);
  3463. }
  3464. setInsertPointAfterBundle(E->Scalars, S);
  3465. LoadInst *LI = cast<LoadInst>(VL0);
  3466. Type *ScalarLoadTy = LI->getType();
  3467. unsigned AS = LI->getPointerAddressSpace();
  3468. Value *VecPtr = Builder.CreateBitCast(LI->getPointerOperand(),
  3469. VecTy->getPointerTo(AS));
  3470. // The pointer operand uses an in-tree scalar so we add the new BitCast to
  3471. // ExternalUses list to make sure that an extract will be generated in the
  3472. // future.
  3473. Value *PO = LI->getPointerOperand();
  3474. if (getTreeEntry(PO))
  3475. ExternalUses.push_back(ExternalUser(PO, cast<User>(VecPtr), 0));
  3476. unsigned Alignment = LI->getAlignment();
  3477. LI = Builder.CreateLoad(VecTy, VecPtr);
  3478. if (!Alignment) {
  3479. Alignment = DL->getABITypeAlignment(ScalarLoadTy);
  3480. }
  3481. LI->setAlignment(Alignment);
  3482. Value *V = propagateMetadata(LI, E->Scalars);
  3483. if (IsReorder) {
  3484. OrdersType Mask;
  3485. inversePermutation(E->ReorderIndices, Mask);
  3486. V = Builder.CreateShuffleVector(V, UndefValue::get(V->getType()),
  3487. Mask, "reorder_shuffle");
  3488. }
  3489. if (NeedToShuffleReuses) {
  3490. // TODO: Merge this shuffle with the ReorderShuffleMask.
  3491. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3492. E->ReuseShuffleIndices, "shuffle");
  3493. }
  3494. E->VectorizedValue = V;
  3495. ++NumVectorInstructions;
  3496. return V;
  3497. }
  3498. case Instruction::Store: {
  3499. StoreInst *SI = cast<StoreInst>(VL0);
  3500. unsigned Alignment = SI->getAlignment();
  3501. unsigned AS = SI->getPointerAddressSpace();
  3502. setInsertPointAfterBundle(E->Scalars, S);
  3503. Value *VecValue = vectorizeTree(E->getOperand(0));
  3504. Value *ScalarPtr = SI->getPointerOperand();
  3505. Value *VecPtr = Builder.CreateBitCast(ScalarPtr, VecTy->getPointerTo(AS));
  3506. StoreInst *ST = Builder.CreateStore(VecValue, VecPtr);
  3507. // The pointer operand uses an in-tree scalar, so add the new BitCast to
  3508. // ExternalUses to make sure that an extract will be generated in the
  3509. // future.
  3510. if (getTreeEntry(ScalarPtr))
  3511. ExternalUses.push_back(ExternalUser(ScalarPtr, cast<User>(VecPtr), 0));
  3512. if (!Alignment)
  3513. Alignment = DL->getABITypeAlignment(SI->getValueOperand()->getType());
  3514. ST->setAlignment(Alignment);
  3515. Value *V = propagateMetadata(ST, E->Scalars);
  3516. if (NeedToShuffleReuses) {
  3517. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3518. E->ReuseShuffleIndices, "shuffle");
  3519. }
  3520. E->VectorizedValue = V;
  3521. ++NumVectorInstructions;
  3522. return V;
  3523. }
  3524. case Instruction::GetElementPtr: {
  3525. setInsertPointAfterBundle(E->Scalars, S);
  3526. Value *Op0 = vectorizeTree(E->getOperand(0));
  3527. std::vector<Value *> OpVecs;
  3528. for (int j = 1, e = cast<GetElementPtrInst>(VL0)->getNumOperands(); j < e;
  3529. ++j) {
  3530. Value *OpVec = vectorizeTree(E->getOperand(j));
  3531. OpVecs.push_back(OpVec);
  3532. }
  3533. Value *V = Builder.CreateGEP(
  3534. cast<GetElementPtrInst>(VL0)->getSourceElementType(), Op0, OpVecs);
  3535. if (Instruction *I = dyn_cast<Instruction>(V))
  3536. V = propagateMetadata(I, E->Scalars);
  3537. if (NeedToShuffleReuses) {
  3538. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3539. E->ReuseShuffleIndices, "shuffle");
  3540. }
  3541. E->VectorizedValue = V;
  3542. ++NumVectorInstructions;
  3543. return V;
  3544. }
  3545. case Instruction::Call: {
  3546. CallInst *CI = cast<CallInst>(VL0);
  3547. setInsertPointAfterBundle(E->Scalars, S);
  3548. Intrinsic::ID IID = Intrinsic::not_intrinsic;
  3549. if (Function *FI = CI->getCalledFunction())
  3550. IID = FI->getIntrinsicID();
  3551. Value *ScalarArg = nullptr;
  3552. std::vector<Value *> OpVecs;
  3553. for (int j = 0, e = CI->getNumArgOperands(); j < e; ++j) {
  3554. ValueList OpVL;
  3555. // Some intrinsics have scalar arguments. This argument should not be
  3556. // vectorized.
  3557. if (hasVectorInstrinsicScalarOpd(IID, j)) {
  3558. CallInst *CEI = cast<CallInst>(VL0);
  3559. ScalarArg = CEI->getArgOperand(j);
  3560. OpVecs.push_back(CEI->getArgOperand(j));
  3561. continue;
  3562. }
  3563. Value *OpVec = vectorizeTree(E->getOperand(j));
  3564. LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
  3565. OpVecs.push_back(OpVec);
  3566. }
  3567. Module *M = F->getParent();
  3568. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3569. Type *Tys[] = { VectorType::get(CI->getType(), E->Scalars.size()) };
  3570. Function *CF = Intrinsic::getDeclaration(M, ID, Tys);
  3571. SmallVector<OperandBundleDef, 1> OpBundles;
  3572. CI->getOperandBundlesAsDefs(OpBundles);
  3573. Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
  3574. // The scalar argument uses an in-tree scalar so we add the new vectorized
  3575. // call to ExternalUses list to make sure that an extract will be
  3576. // generated in the future.
  3577. if (ScalarArg && getTreeEntry(ScalarArg))
  3578. ExternalUses.push_back(ExternalUser(ScalarArg, cast<User>(V), 0));
  3579. propagateIRFlags(V, E->Scalars, VL0);
  3580. if (NeedToShuffleReuses) {
  3581. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3582. E->ReuseShuffleIndices, "shuffle");
  3583. }
  3584. E->VectorizedValue = V;
  3585. ++NumVectorInstructions;
  3586. return V;
  3587. }
  3588. case Instruction::ShuffleVector: {
  3589. assert(S.isAltShuffle() &&
  3590. ((Instruction::isBinaryOp(S.getOpcode()) &&
  3591. Instruction::isBinaryOp(S.getAltOpcode())) ||
  3592. (Instruction::isCast(S.getOpcode()) &&
  3593. Instruction::isCast(S.getAltOpcode()))) &&
  3594. "Invalid Shuffle Vector Operand");
  3595. Value *LHS = nullptr, *RHS = nullptr;
  3596. if (Instruction::isBinaryOp(S.getOpcode())) {
  3597. setInsertPointAfterBundle(E->Scalars, S);
  3598. LHS = vectorizeTree(E->getOperand(0));
  3599. RHS = vectorizeTree(E->getOperand(1));
  3600. } else {
  3601. setInsertPointAfterBundle(E->Scalars, S);
  3602. LHS = vectorizeTree(E->getOperand(0));
  3603. }
  3604. if (E->VectorizedValue) {
  3605. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  3606. return E->VectorizedValue;
  3607. }
  3608. Value *V0, *V1;
  3609. if (Instruction::isBinaryOp(S.getOpcode())) {
  3610. V0 = Builder.CreateBinOp(
  3611. static_cast<Instruction::BinaryOps>(S.getOpcode()), LHS, RHS);
  3612. V1 = Builder.CreateBinOp(
  3613. static_cast<Instruction::BinaryOps>(S.getAltOpcode()), LHS, RHS);
  3614. } else {
  3615. V0 = Builder.CreateCast(
  3616. static_cast<Instruction::CastOps>(S.getOpcode()), LHS, VecTy);
  3617. V1 = Builder.CreateCast(
  3618. static_cast<Instruction::CastOps>(S.getAltOpcode()), LHS, VecTy);
  3619. }
  3620. // Create shuffle to take alternate operations from the vector.
  3621. // Also, gather up main and alt scalar ops to propagate IR flags to
  3622. // each vector operation.
  3623. ValueList OpScalars, AltScalars;
  3624. unsigned e = E->Scalars.size();
  3625. SmallVector<Constant *, 8> Mask(e);
  3626. for (unsigned i = 0; i < e; ++i) {
  3627. auto *OpInst = cast<Instruction>(E->Scalars[i]);
  3628. assert(S.isOpcodeOrAlt(OpInst) && "Unexpected main/alternate opcode");
  3629. if (OpInst->getOpcode() == S.getAltOpcode()) {
  3630. Mask[i] = Builder.getInt32(e + i);
  3631. AltScalars.push_back(E->Scalars[i]);
  3632. } else {
  3633. Mask[i] = Builder.getInt32(i);
  3634. OpScalars.push_back(E->Scalars[i]);
  3635. }
  3636. }
  3637. Value *ShuffleMask = ConstantVector::get(Mask);
  3638. propagateIRFlags(V0, OpScalars);
  3639. propagateIRFlags(V1, AltScalars);
  3640. Value *V = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
  3641. if (Instruction *I = dyn_cast<Instruction>(V))
  3642. V = propagateMetadata(I, E->Scalars);
  3643. if (NeedToShuffleReuses) {
  3644. V = Builder.CreateShuffleVector(V, UndefValue::get(VecTy),
  3645. E->ReuseShuffleIndices, "shuffle");
  3646. }
  3647. E->VectorizedValue = V;
  3648. ++NumVectorInstructions;
  3649. return V;
  3650. }
  3651. default:
  3652. llvm_unreachable("unknown inst");
  3653. }
  3654. return nullptr;
  3655. }
  3656. Value *BoUpSLP::vectorizeTree() {
  3657. ExtraValueToDebugLocsMap ExternallyUsedValues;
  3658. return vectorizeTree(ExternallyUsedValues);
  3659. }
  3660. Value *
  3661. BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
  3662. // All blocks must be scheduled before any instructions are inserted.
  3663. for (auto &BSIter : BlocksSchedules) {
  3664. scheduleBlock(BSIter.second.get());
  3665. }
  3666. Builder.SetInsertPoint(&F->getEntryBlock().front());
  3667. auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
  3668. // If the vectorized tree can be rewritten in a smaller type, we truncate the
  3669. // vectorized root. InstCombine will then rewrite the entire expression. We
  3670. // sign extend the extracted values below.
  3671. auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
  3672. if (MinBWs.count(ScalarRoot)) {
  3673. if (auto *I = dyn_cast<Instruction>(VectorRoot))
  3674. Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
  3675. auto BundleWidth = VectorizableTree[0]->Scalars.size();
  3676. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  3677. auto *VecTy = VectorType::get(MinTy, BundleWidth);
  3678. auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
  3679. VectorizableTree[0]->VectorizedValue = Trunc;
  3680. }
  3681. LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
  3682. << " values .\n");
  3683. // If necessary, sign-extend or zero-extend ScalarRoot to the larger type
  3684. // specified by ScalarType.
  3685. auto extend = [&](Value *ScalarRoot, Value *Ex, Type *ScalarType) {
  3686. if (!MinBWs.count(ScalarRoot))
  3687. return Ex;
  3688. if (MinBWs[ScalarRoot].second)
  3689. return Builder.CreateSExt(Ex, ScalarType);
  3690. return Builder.CreateZExt(Ex, ScalarType);
  3691. };
  3692. // Extract all of the elements with the external uses.
  3693. for (const auto &ExternalUse : ExternalUses) {
  3694. Value *Scalar = ExternalUse.Scalar;
  3695. llvm::User *User = ExternalUse.User;
  3696. // Skip users that we already RAUW. This happens when one instruction
  3697. // has multiple uses of the same value.
  3698. if (User && !is_contained(Scalar->users(), User))
  3699. continue;
  3700. TreeEntry *E = getTreeEntry(Scalar);
  3701. assert(E && "Invalid scalar");
  3702. assert(!E->NeedToGather && "Extracting from a gather list");
  3703. Value *Vec = E->VectorizedValue;
  3704. assert(Vec && "Can't find vectorizable value");
  3705. Value *Lane = Builder.getInt32(ExternalUse.Lane);
  3706. // If User == nullptr, the Scalar is used as extra arg. Generate
  3707. // ExtractElement instruction and update the record for this scalar in
  3708. // ExternallyUsedValues.
  3709. if (!User) {
  3710. assert(ExternallyUsedValues.count(Scalar) &&
  3711. "Scalar with nullptr as an external user must be registered in "
  3712. "ExternallyUsedValues map");
  3713. if (auto *VecI = dyn_cast<Instruction>(Vec)) {
  3714. Builder.SetInsertPoint(VecI->getParent(),
  3715. std::next(VecI->getIterator()));
  3716. } else {
  3717. Builder.SetInsertPoint(&F->getEntryBlock().front());
  3718. }
  3719. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  3720. Ex = extend(ScalarRoot, Ex, Scalar->getType());
  3721. CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
  3722. auto &Locs = ExternallyUsedValues[Scalar];
  3723. ExternallyUsedValues.insert({Ex, Locs});
  3724. ExternallyUsedValues.erase(Scalar);
  3725. // Required to update internally referenced instructions.
  3726. Scalar->replaceAllUsesWith(Ex);
  3727. continue;
  3728. }
  3729. // Generate extracts for out-of-tree users.
  3730. // Find the insertion point for the extractelement lane.
  3731. if (auto *VecI = dyn_cast<Instruction>(Vec)) {
  3732. if (PHINode *PH = dyn_cast<PHINode>(User)) {
  3733. for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
  3734. if (PH->getIncomingValue(i) == Scalar) {
  3735. Instruction *IncomingTerminator =
  3736. PH->getIncomingBlock(i)->getTerminator();
  3737. if (isa<CatchSwitchInst>(IncomingTerminator)) {
  3738. Builder.SetInsertPoint(VecI->getParent(),
  3739. std::next(VecI->getIterator()));
  3740. } else {
  3741. Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
  3742. }
  3743. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  3744. Ex = extend(ScalarRoot, Ex, Scalar->getType());
  3745. CSEBlocks.insert(PH->getIncomingBlock(i));
  3746. PH->setOperand(i, Ex);
  3747. }
  3748. }
  3749. } else {
  3750. Builder.SetInsertPoint(cast<Instruction>(User));
  3751. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  3752. Ex = extend(ScalarRoot, Ex, Scalar->getType());
  3753. CSEBlocks.insert(cast<Instruction>(User)->getParent());
  3754. User->replaceUsesOfWith(Scalar, Ex);
  3755. }
  3756. } else {
  3757. Builder.SetInsertPoint(&F->getEntryBlock().front());
  3758. Value *Ex = Builder.CreateExtractElement(Vec, Lane);
  3759. Ex = extend(ScalarRoot, Ex, Scalar->getType());
  3760. CSEBlocks.insert(&F->getEntryBlock());
  3761. User->replaceUsesOfWith(Scalar, Ex);
  3762. }
  3763. LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
  3764. }
  3765. // For each vectorized value:
  3766. for (auto &TEPtr : VectorizableTree) {
  3767. TreeEntry *Entry = TEPtr.get();
  3768. // No need to handle users of gathered values.
  3769. if (Entry->NeedToGather)
  3770. continue;
  3771. assert(Entry->VectorizedValue && "Can't find vectorizable value");
  3772. // For each lane:
  3773. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  3774. Value *Scalar = Entry->Scalars[Lane];
  3775. Type *Ty = Scalar->getType();
  3776. if (!Ty->isVoidTy()) {
  3777. #ifndef NDEBUG
  3778. for (User *U : Scalar->users()) {
  3779. LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
  3780. // It is legal to replace users in the ignorelist by undef.
  3781. assert((getTreeEntry(U) || is_contained(UserIgnoreList, U)) &&
  3782. "Replacing out-of-tree value with undef");
  3783. }
  3784. #endif
  3785. Value *Undef = UndefValue::get(Ty);
  3786. Scalar->replaceAllUsesWith(Undef);
  3787. }
  3788. LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
  3789. eraseInstruction(cast<Instruction>(Scalar));
  3790. }
  3791. }
  3792. Builder.ClearInsertionPoint();
  3793. return VectorizableTree[0]->VectorizedValue;
  3794. }
  3795. void BoUpSLP::optimizeGatherSequence() {
  3796. LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherSeq.size()
  3797. << " gather sequences instructions.\n");
  3798. // LICM InsertElementInst sequences.
  3799. for (Instruction *I : GatherSeq) {
  3800. if (!isa<InsertElementInst>(I) && !isa<ShuffleVectorInst>(I))
  3801. continue;
  3802. // Check if this block is inside a loop.
  3803. Loop *L = LI->getLoopFor(I->getParent());
  3804. if (!L)
  3805. continue;
  3806. // Check if it has a preheader.
  3807. BasicBlock *PreHeader = L->getLoopPreheader();
  3808. if (!PreHeader)
  3809. continue;
  3810. // If the vector or the element that we insert into it are
  3811. // instructions that are defined in this basic block then we can't
  3812. // hoist this instruction.
  3813. auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
  3814. auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
  3815. if (Op0 && L->contains(Op0))
  3816. continue;
  3817. if (Op1 && L->contains(Op1))
  3818. continue;
  3819. // We can hoist this instruction. Move it to the pre-header.
  3820. I->moveBefore(PreHeader->getTerminator());
  3821. }
  3822. // Make a list of all reachable blocks in our CSE queue.
  3823. SmallVector<const DomTreeNode *, 8> CSEWorkList;
  3824. CSEWorkList.reserve(CSEBlocks.size());
  3825. for (BasicBlock *BB : CSEBlocks)
  3826. if (DomTreeNode *N = DT->getNode(BB)) {
  3827. assert(DT->isReachableFromEntry(N));
  3828. CSEWorkList.push_back(N);
  3829. }
  3830. // Sort blocks by domination. This ensures we visit a block after all blocks
  3831. // dominating it are visited.
  3832. llvm::stable_sort(CSEWorkList,
  3833. [this](const DomTreeNode *A, const DomTreeNode *B) {
  3834. return DT->properlyDominates(A, B);
  3835. });
  3836. // Perform O(N^2) search over the gather sequences and merge identical
  3837. // instructions. TODO: We can further optimize this scan if we split the
  3838. // instructions into different buckets based on the insert lane.
  3839. SmallVector<Instruction *, 16> Visited;
  3840. for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
  3841. assert((I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
  3842. "Worklist not sorted properly!");
  3843. BasicBlock *BB = (*I)->getBlock();
  3844. // For all instructions in blocks containing gather sequences:
  3845. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e;) {
  3846. Instruction *In = &*it++;
  3847. if (!isa<InsertElementInst>(In) && !isa<ExtractElementInst>(In))
  3848. continue;
  3849. // Check if we can replace this instruction with any of the
  3850. // visited instructions.
  3851. for (Instruction *v : Visited) {
  3852. if (In->isIdenticalTo(v) &&
  3853. DT->dominates(v->getParent(), In->getParent())) {
  3854. In->replaceAllUsesWith(v);
  3855. eraseInstruction(In);
  3856. In = nullptr;
  3857. break;
  3858. }
  3859. }
  3860. if (In) {
  3861. assert(!is_contained(Visited, In));
  3862. Visited.push_back(In);
  3863. }
  3864. }
  3865. }
  3866. CSEBlocks.clear();
  3867. GatherSeq.clear();
  3868. }
  3869. // Groups the instructions to a bundle (which is then a single scheduling entity)
  3870. // and schedules instructions until the bundle gets ready.
  3871. Optional<BoUpSLP::ScheduleData *>
  3872. BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
  3873. const InstructionsState &S) {
  3874. if (isa<PHINode>(S.OpValue))
  3875. return nullptr;
  3876. // Initialize the instruction bundle.
  3877. Instruction *OldScheduleEnd = ScheduleEnd;
  3878. ScheduleData *PrevInBundle = nullptr;
  3879. ScheduleData *Bundle = nullptr;
  3880. bool ReSchedule = false;
  3881. LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n");
  3882. // Make sure that the scheduling region contains all
  3883. // instructions of the bundle.
  3884. for (Value *V : VL) {
  3885. if (!extendSchedulingRegion(V, S))
  3886. return None;
  3887. }
  3888. for (Value *V : VL) {
  3889. ScheduleData *BundleMember = getScheduleData(V);
  3890. assert(BundleMember &&
  3891. "no ScheduleData for bundle member (maybe not in same basic block)");
  3892. if (BundleMember->IsScheduled) {
  3893. // A bundle member was scheduled as single instruction before and now
  3894. // needs to be scheduled as part of the bundle. We just get rid of the
  3895. // existing schedule.
  3896. LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
  3897. << " was already scheduled\n");
  3898. ReSchedule = true;
  3899. }
  3900. assert(BundleMember->isSchedulingEntity() &&
  3901. "bundle member already part of other bundle");
  3902. if (PrevInBundle) {
  3903. PrevInBundle->NextInBundle = BundleMember;
  3904. } else {
  3905. Bundle = BundleMember;
  3906. }
  3907. BundleMember->UnscheduledDepsInBundle = 0;
  3908. Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
  3909. // Group the instructions to a bundle.
  3910. BundleMember->FirstInBundle = Bundle;
  3911. PrevInBundle = BundleMember;
  3912. }
  3913. if (ScheduleEnd != OldScheduleEnd) {
  3914. // The scheduling region got new instructions at the lower end (or it is a
  3915. // new region for the first bundle). This makes it necessary to
  3916. // recalculate all dependencies.
  3917. // It is seldom that this needs to be done a second time after adding the
  3918. // initial bundle to the region.
  3919. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  3920. doForAllOpcodes(I, [](ScheduleData *SD) {
  3921. SD->clearDependencies();
  3922. });
  3923. }
  3924. ReSchedule = true;
  3925. }
  3926. if (ReSchedule) {
  3927. resetSchedule();
  3928. initialFillReadyList(ReadyInsts);
  3929. }
  3930. assert(Bundle && "Failed to find schedule bundle");
  3931. LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle << " in block "
  3932. << BB->getName() << "\n");
  3933. calculateDependencies(Bundle, true, SLP);
  3934. // Now try to schedule the new bundle. As soon as the bundle is "ready" it
  3935. // means that there are no cyclic dependencies and we can schedule it.
  3936. // Note that's important that we don't "schedule" the bundle yet (see
  3937. // cancelScheduling).
  3938. while (!Bundle->isReady() && !ReadyInsts.empty()) {
  3939. ScheduleData *pickedSD = ReadyInsts.back();
  3940. ReadyInsts.pop_back();
  3941. if (pickedSD->isSchedulingEntity() && pickedSD->isReady()) {
  3942. schedule(pickedSD, ReadyInsts);
  3943. }
  3944. }
  3945. if (!Bundle->isReady()) {
  3946. cancelScheduling(VL, S.OpValue);
  3947. return None;
  3948. }
  3949. return Bundle;
  3950. }
  3951. void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
  3952. Value *OpValue) {
  3953. if (isa<PHINode>(OpValue))
  3954. return;
  3955. ScheduleData *Bundle = getScheduleData(OpValue);
  3956. LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
  3957. assert(!Bundle->IsScheduled &&
  3958. "Can't cancel bundle which is already scheduled");
  3959. assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
  3960. "tried to unbundle something which is not a bundle");
  3961. // Un-bundle: make single instructions out of the bundle.
  3962. ScheduleData *BundleMember = Bundle;
  3963. while (BundleMember) {
  3964. assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
  3965. BundleMember->FirstInBundle = BundleMember;
  3966. ScheduleData *Next = BundleMember->NextInBundle;
  3967. BundleMember->NextInBundle = nullptr;
  3968. BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
  3969. if (BundleMember->UnscheduledDepsInBundle == 0) {
  3970. ReadyInsts.insert(BundleMember);
  3971. }
  3972. BundleMember = Next;
  3973. }
  3974. }
  3975. BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
  3976. // Allocate a new ScheduleData for the instruction.
  3977. if (ChunkPos >= ChunkSize) {
  3978. ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
  3979. ChunkPos = 0;
  3980. }
  3981. return &(ScheduleDataChunks.back()[ChunkPos++]);
  3982. }
  3983. bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
  3984. const InstructionsState &S) {
  3985. if (getScheduleData(V, isOneOf(S, V)))
  3986. return true;
  3987. Instruction *I = dyn_cast<Instruction>(V);
  3988. assert(I && "bundle member must be an instruction");
  3989. assert(!isa<PHINode>(I) && "phi nodes don't need to be scheduled");
  3990. auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
  3991. ScheduleData *ISD = getScheduleData(I);
  3992. if (!ISD)
  3993. return false;
  3994. assert(isInSchedulingRegion(ISD) &&
  3995. "ScheduleData not in scheduling region");
  3996. ScheduleData *SD = allocateScheduleDataChunks();
  3997. SD->Inst = I;
  3998. SD->init(SchedulingRegionID, S.OpValue);
  3999. ExtraScheduleDataMap[I][S.OpValue] = SD;
  4000. return true;
  4001. };
  4002. if (CheckSheduleForI(I))
  4003. return true;
  4004. if (!ScheduleStart) {
  4005. // It's the first instruction in the new region.
  4006. initScheduleData(I, I->getNextNode(), nullptr, nullptr);
  4007. ScheduleStart = I;
  4008. ScheduleEnd = I->getNextNode();
  4009. if (isOneOf(S, I) != I)
  4010. CheckSheduleForI(I);
  4011. assert(ScheduleEnd && "tried to vectorize a terminator?");
  4012. LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
  4013. return true;
  4014. }
  4015. // Search up and down at the same time, because we don't know if the new
  4016. // instruction is above or below the existing scheduling region.
  4017. BasicBlock::reverse_iterator UpIter =
  4018. ++ScheduleStart->getIterator().getReverse();
  4019. BasicBlock::reverse_iterator UpperEnd = BB->rend();
  4020. BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
  4021. BasicBlock::iterator LowerEnd = BB->end();
  4022. while (true) {
  4023. if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
  4024. LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
  4025. return false;
  4026. }
  4027. if (UpIter != UpperEnd) {
  4028. if (&*UpIter == I) {
  4029. initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
  4030. ScheduleStart = I;
  4031. if (isOneOf(S, I) != I)
  4032. CheckSheduleForI(I);
  4033. LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I
  4034. << "\n");
  4035. return true;
  4036. }
  4037. ++UpIter;
  4038. }
  4039. if (DownIter != LowerEnd) {
  4040. if (&*DownIter == I) {
  4041. initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
  4042. nullptr);
  4043. ScheduleEnd = I->getNextNode();
  4044. if (isOneOf(S, I) != I)
  4045. CheckSheduleForI(I);
  4046. assert(ScheduleEnd && "tried to vectorize a terminator?");
  4047. LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I
  4048. << "\n");
  4049. return true;
  4050. }
  4051. ++DownIter;
  4052. }
  4053. assert((UpIter != UpperEnd || DownIter != LowerEnd) &&
  4054. "instruction not found in block");
  4055. }
  4056. return true;
  4057. }
  4058. void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
  4059. Instruction *ToI,
  4060. ScheduleData *PrevLoadStore,
  4061. ScheduleData *NextLoadStore) {
  4062. ScheduleData *CurrentLoadStore = PrevLoadStore;
  4063. for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
  4064. ScheduleData *SD = ScheduleDataMap[I];
  4065. if (!SD) {
  4066. SD = allocateScheduleDataChunks();
  4067. ScheduleDataMap[I] = SD;
  4068. SD->Inst = I;
  4069. }
  4070. assert(!isInSchedulingRegion(SD) &&
  4071. "new ScheduleData already in scheduling region");
  4072. SD->init(SchedulingRegionID, I);
  4073. if (I->mayReadOrWriteMemory() &&
  4074. (!isa<IntrinsicInst>(I) ||
  4075. cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect)) {
  4076. // Update the linked list of memory accessing instructions.
  4077. if (CurrentLoadStore) {
  4078. CurrentLoadStore->NextLoadStore = SD;
  4079. } else {
  4080. FirstLoadStoreInRegion = SD;
  4081. }
  4082. CurrentLoadStore = SD;
  4083. }
  4084. }
  4085. if (NextLoadStore) {
  4086. if (CurrentLoadStore)
  4087. CurrentLoadStore->NextLoadStore = NextLoadStore;
  4088. } else {
  4089. LastLoadStoreInRegion = CurrentLoadStore;
  4090. }
  4091. }
  4092. void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
  4093. bool InsertInReadyList,
  4094. BoUpSLP *SLP) {
  4095. assert(SD->isSchedulingEntity());
  4096. SmallVector<ScheduleData *, 10> WorkList;
  4097. WorkList.push_back(SD);
  4098. while (!WorkList.empty()) {
  4099. ScheduleData *SD = WorkList.back();
  4100. WorkList.pop_back();
  4101. ScheduleData *BundleMember = SD;
  4102. while (BundleMember) {
  4103. assert(isInSchedulingRegion(BundleMember));
  4104. if (!BundleMember->hasValidDependencies()) {
  4105. LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember
  4106. << "\n");
  4107. BundleMember->Dependencies = 0;
  4108. BundleMember->resetUnscheduledDeps();
  4109. // Handle def-use chain dependencies.
  4110. if (BundleMember->OpValue != BundleMember->Inst) {
  4111. ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
  4112. if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
  4113. BundleMember->Dependencies++;
  4114. ScheduleData *DestBundle = UseSD->FirstInBundle;
  4115. if (!DestBundle->IsScheduled)
  4116. BundleMember->incrementUnscheduledDeps(1);
  4117. if (!DestBundle->hasValidDependencies())
  4118. WorkList.push_back(DestBundle);
  4119. }
  4120. } else {
  4121. for (User *U : BundleMember->Inst->users()) {
  4122. if (isa<Instruction>(U)) {
  4123. ScheduleData *UseSD = getScheduleData(U);
  4124. if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
  4125. BundleMember->Dependencies++;
  4126. ScheduleData *DestBundle = UseSD->FirstInBundle;
  4127. if (!DestBundle->IsScheduled)
  4128. BundleMember->incrementUnscheduledDeps(1);
  4129. if (!DestBundle->hasValidDependencies())
  4130. WorkList.push_back(DestBundle);
  4131. }
  4132. } else {
  4133. // I'm not sure if this can ever happen. But we need to be safe.
  4134. // This lets the instruction/bundle never be scheduled and
  4135. // eventually disable vectorization.
  4136. BundleMember->Dependencies++;
  4137. BundleMember->incrementUnscheduledDeps(1);
  4138. }
  4139. }
  4140. }
  4141. // Handle the memory dependencies.
  4142. ScheduleData *DepDest = BundleMember->NextLoadStore;
  4143. if (DepDest) {
  4144. Instruction *SrcInst = BundleMember->Inst;
  4145. MemoryLocation SrcLoc = getLocation(SrcInst, SLP->AA);
  4146. bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
  4147. unsigned numAliased = 0;
  4148. unsigned DistToSrc = 1;
  4149. while (DepDest) {
  4150. assert(isInSchedulingRegion(DepDest));
  4151. // We have two limits to reduce the complexity:
  4152. // 1) AliasedCheckLimit: It's a small limit to reduce calls to
  4153. // SLP->isAliased (which is the expensive part in this loop).
  4154. // 2) MaxMemDepDistance: It's for very large blocks and it aborts
  4155. // the whole loop (even if the loop is fast, it's quadratic).
  4156. // It's important for the loop break condition (see below) to
  4157. // check this limit even between two read-only instructions.
  4158. if (DistToSrc >= MaxMemDepDistance ||
  4159. ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
  4160. (numAliased >= AliasedCheckLimit ||
  4161. SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
  4162. // We increment the counter only if the locations are aliased
  4163. // (instead of counting all alias checks). This gives a better
  4164. // balance between reduced runtime and accurate dependencies.
  4165. numAliased++;
  4166. DepDest->MemoryDependencies.push_back(BundleMember);
  4167. BundleMember->Dependencies++;
  4168. ScheduleData *DestBundle = DepDest->FirstInBundle;
  4169. if (!DestBundle->IsScheduled) {
  4170. BundleMember->incrementUnscheduledDeps(1);
  4171. }
  4172. if (!DestBundle->hasValidDependencies()) {
  4173. WorkList.push_back(DestBundle);
  4174. }
  4175. }
  4176. DepDest = DepDest->NextLoadStore;
  4177. // Example, explaining the loop break condition: Let's assume our
  4178. // starting instruction is i0 and MaxMemDepDistance = 3.
  4179. //
  4180. // +--------v--v--v
  4181. // i0,i1,i2,i3,i4,i5,i6,i7,i8
  4182. // +--------^--^--^
  4183. //
  4184. // MaxMemDepDistance let us stop alias-checking at i3 and we add
  4185. // dependencies from i0 to i3,i4,.. (even if they are not aliased).
  4186. // Previously we already added dependencies from i3 to i6,i7,i8
  4187. // (because of MaxMemDepDistance). As we added a dependency from
  4188. // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
  4189. // and we can abort this loop at i6.
  4190. if (DistToSrc >= 2 * MaxMemDepDistance)
  4191. break;
  4192. DistToSrc++;
  4193. }
  4194. }
  4195. }
  4196. BundleMember = BundleMember->NextInBundle;
  4197. }
  4198. if (InsertInReadyList && SD->isReady()) {
  4199. ReadyInsts.push_back(SD);
  4200. LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst
  4201. << "\n");
  4202. }
  4203. }
  4204. }
  4205. void BoUpSLP::BlockScheduling::resetSchedule() {
  4206. assert(ScheduleStart &&
  4207. "tried to reset schedule on block which has not been scheduled");
  4208. for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  4209. doForAllOpcodes(I, [&](ScheduleData *SD) {
  4210. assert(isInSchedulingRegion(SD) &&
  4211. "ScheduleData not in scheduling region");
  4212. SD->IsScheduled = false;
  4213. SD->resetUnscheduledDeps();
  4214. });
  4215. }
  4216. ReadyInsts.clear();
  4217. }
  4218. void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
  4219. if (!BS->ScheduleStart)
  4220. return;
  4221. LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
  4222. BS->resetSchedule();
  4223. // For the real scheduling we use a more sophisticated ready-list: it is
  4224. // sorted by the original instruction location. This lets the final schedule
  4225. // be as close as possible to the original instruction order.
  4226. struct ScheduleDataCompare {
  4227. bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
  4228. return SD2->SchedulingPriority < SD1->SchedulingPriority;
  4229. }
  4230. };
  4231. std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
  4232. // Ensure that all dependency data is updated and fill the ready-list with
  4233. // initial instructions.
  4234. int Idx = 0;
  4235. int NumToSchedule = 0;
  4236. for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
  4237. I = I->getNextNode()) {
  4238. BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
  4239. assert(SD->isPartOfBundle() ==
  4240. (getTreeEntry(SD->Inst) != nullptr) &&
  4241. "scheduler and vectorizer bundle mismatch");
  4242. SD->FirstInBundle->SchedulingPriority = Idx++;
  4243. if (SD->isSchedulingEntity()) {
  4244. BS->calculateDependencies(SD, false, this);
  4245. NumToSchedule++;
  4246. }
  4247. });
  4248. }
  4249. BS->initialFillReadyList(ReadyInsts);
  4250. Instruction *LastScheduledInst = BS->ScheduleEnd;
  4251. // Do the "real" scheduling.
  4252. while (!ReadyInsts.empty()) {
  4253. ScheduleData *picked = *ReadyInsts.begin();
  4254. ReadyInsts.erase(ReadyInsts.begin());
  4255. // Move the scheduled instruction(s) to their dedicated places, if not
  4256. // there yet.
  4257. ScheduleData *BundleMember = picked;
  4258. while (BundleMember) {
  4259. Instruction *pickedInst = BundleMember->Inst;
  4260. if (LastScheduledInst->getNextNode() != pickedInst) {
  4261. BS->BB->getInstList().remove(pickedInst);
  4262. BS->BB->getInstList().insert(LastScheduledInst->getIterator(),
  4263. pickedInst);
  4264. }
  4265. LastScheduledInst = pickedInst;
  4266. BundleMember = BundleMember->NextInBundle;
  4267. }
  4268. BS->schedule(picked, ReadyInsts);
  4269. NumToSchedule--;
  4270. }
  4271. assert(NumToSchedule == 0 && "could not schedule all instructions");
  4272. // Avoid duplicate scheduling of the block.
  4273. BS->ScheduleStart = nullptr;
  4274. }
  4275. unsigned BoUpSLP::getVectorElementSize(Value *V) const {
  4276. // If V is a store, just return the width of the stored value without
  4277. // traversing the expression tree. This is the common case.
  4278. if (auto *Store = dyn_cast<StoreInst>(V))
  4279. return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
  4280. // If V is not a store, we can traverse the expression tree to find loads
  4281. // that feed it. The type of the loaded value may indicate a more suitable
  4282. // width than V's type. We want to base the vector element size on the width
  4283. // of memory operations where possible.
  4284. SmallVector<Instruction *, 16> Worklist;
  4285. SmallPtrSet<Instruction *, 16> Visited;
  4286. if (auto *I = dyn_cast<Instruction>(V))
  4287. Worklist.push_back(I);
  4288. // Traverse the expression tree in bottom-up order looking for loads. If we
  4289. // encounter an instruction we don't yet handle, we give up.
  4290. auto MaxWidth = 0u;
  4291. auto FoundUnknownInst = false;
  4292. while (!Worklist.empty() && !FoundUnknownInst) {
  4293. auto *I = Worklist.pop_back_val();
  4294. Visited.insert(I);
  4295. // We should only be looking at scalar instructions here. If the current
  4296. // instruction has a vector type, give up.
  4297. auto *Ty = I->getType();
  4298. if (isa<VectorType>(Ty))
  4299. FoundUnknownInst = true;
  4300. // If the current instruction is a load, update MaxWidth to reflect the
  4301. // width of the loaded value.
  4302. else if (isa<LoadInst>(I))
  4303. MaxWidth = std::max<unsigned>(MaxWidth, DL->getTypeSizeInBits(Ty));
  4304. // Otherwise, we need to visit the operands of the instruction. We only
  4305. // handle the interesting cases from buildTree here. If an operand is an
  4306. // instruction we haven't yet visited, we add it to the worklist.
  4307. else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
  4308. isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I)) {
  4309. for (Use &U : I->operands())
  4310. if (auto *J = dyn_cast<Instruction>(U.get()))
  4311. if (!Visited.count(J))
  4312. Worklist.push_back(J);
  4313. }
  4314. // If we don't yet handle the instruction, give up.
  4315. else
  4316. FoundUnknownInst = true;
  4317. }
  4318. // If we didn't encounter a memory access in the expression tree, or if we
  4319. // gave up for some reason, just return the width of V.
  4320. if (!MaxWidth || FoundUnknownInst)
  4321. return DL->getTypeSizeInBits(V->getType());
  4322. // Otherwise, return the maximum width we found.
  4323. return MaxWidth;
  4324. }
  4325. // Determine if a value V in a vectorizable expression Expr can be demoted to a
  4326. // smaller type with a truncation. We collect the values that will be demoted
  4327. // in ToDemote and additional roots that require investigating in Roots.
  4328. static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
  4329. SmallVectorImpl<Value *> &ToDemote,
  4330. SmallVectorImpl<Value *> &Roots) {
  4331. // We can always demote constants.
  4332. if (isa<Constant>(V)) {
  4333. ToDemote.push_back(V);
  4334. return true;
  4335. }
  4336. // If the value is not an instruction in the expression with only one use, it
  4337. // cannot be demoted.
  4338. auto *I = dyn_cast<Instruction>(V);
  4339. if (!I || !I->hasOneUse() || !Expr.count(I))
  4340. return false;
  4341. switch (I->getOpcode()) {
  4342. // We can always demote truncations and extensions. Since truncations can
  4343. // seed additional demotion, we save the truncated value.
  4344. case Instruction::Trunc:
  4345. Roots.push_back(I->getOperand(0));
  4346. break;
  4347. case Instruction::ZExt:
  4348. case Instruction::SExt:
  4349. break;
  4350. // We can demote certain binary operations if we can demote both of their
  4351. // operands.
  4352. case Instruction::Add:
  4353. case Instruction::Sub:
  4354. case Instruction::Mul:
  4355. case Instruction::And:
  4356. case Instruction::Or:
  4357. case Instruction::Xor:
  4358. if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
  4359. !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
  4360. return false;
  4361. break;
  4362. // We can demote selects if we can demote their true and false values.
  4363. case Instruction::Select: {
  4364. SelectInst *SI = cast<SelectInst>(I);
  4365. if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
  4366. !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
  4367. return false;
  4368. break;
  4369. }
  4370. // We can demote phis if we can demote all their incoming operands. Note that
  4371. // we don't need to worry about cycles since we ensure single use above.
  4372. case Instruction::PHI: {
  4373. PHINode *PN = cast<PHINode>(I);
  4374. for (Value *IncValue : PN->incoming_values())
  4375. if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
  4376. return false;
  4377. break;
  4378. }
  4379. // Otherwise, conservatively give up.
  4380. default:
  4381. return false;
  4382. }
  4383. // Record the value that we can demote.
  4384. ToDemote.push_back(V);
  4385. return true;
  4386. }
  4387. void BoUpSLP::computeMinimumValueSizes() {
  4388. // If there are no external uses, the expression tree must be rooted by a
  4389. // store. We can't demote in-memory values, so there is nothing to do here.
  4390. if (ExternalUses.empty())
  4391. return;
  4392. // We only attempt to truncate integer expressions.
  4393. auto &TreeRoot = VectorizableTree[0]->Scalars;
  4394. auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
  4395. if (!TreeRootIT)
  4396. return;
  4397. // If the expression is not rooted by a store, these roots should have
  4398. // external uses. We will rely on InstCombine to rewrite the expression in
  4399. // the narrower type. However, InstCombine only rewrites single-use values.
  4400. // This means that if a tree entry other than a root is used externally, it
  4401. // must have multiple uses and InstCombine will not rewrite it. The code
  4402. // below ensures that only the roots are used externally.
  4403. SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
  4404. for (auto &EU : ExternalUses)
  4405. if (!Expr.erase(EU.Scalar))
  4406. return;
  4407. if (!Expr.empty())
  4408. return;
  4409. // Collect the scalar values of the vectorizable expression. We will use this
  4410. // context to determine which values can be demoted. If we see a truncation,
  4411. // we mark it as seeding another demotion.
  4412. for (auto &EntryPtr : VectorizableTree)
  4413. Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
  4414. // Ensure the roots of the vectorizable tree don't form a cycle. They must
  4415. // have a single external user that is not in the vectorizable tree.
  4416. for (auto *Root : TreeRoot)
  4417. if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
  4418. return;
  4419. // Conservatively determine if we can actually truncate the roots of the
  4420. // expression. Collect the values that can be demoted in ToDemote and
  4421. // additional roots that require investigating in Roots.
  4422. SmallVector<Value *, 32> ToDemote;
  4423. SmallVector<Value *, 4> Roots;
  4424. for (auto *Root : TreeRoot)
  4425. if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
  4426. return;
  4427. // The maximum bit width required to represent all the values that can be
  4428. // demoted without loss of precision. It would be safe to truncate the roots
  4429. // of the expression to this width.
  4430. auto MaxBitWidth = 8u;
  4431. // We first check if all the bits of the roots are demanded. If they're not,
  4432. // we can truncate the roots to this narrower type.
  4433. for (auto *Root : TreeRoot) {
  4434. auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
  4435. MaxBitWidth = std::max<unsigned>(
  4436. Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
  4437. }
  4438. // True if the roots can be zero-extended back to their original type, rather
  4439. // than sign-extended. We know that if the leading bits are not demanded, we
  4440. // can safely zero-extend. So we initialize IsKnownPositive to True.
  4441. bool IsKnownPositive = true;
  4442. // If all the bits of the roots are demanded, we can try a little harder to
  4443. // compute a narrower type. This can happen, for example, if the roots are
  4444. // getelementptr indices. InstCombine promotes these indices to the pointer
  4445. // width. Thus, all their bits are technically demanded even though the
  4446. // address computation might be vectorized in a smaller type.
  4447. //
  4448. // We start by looking at each entry that can be demoted. We compute the
  4449. // maximum bit width required to store the scalar by using ValueTracking to
  4450. // compute the number of high-order bits we can truncate.
  4451. if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
  4452. llvm::all_of(TreeRoot, [](Value *R) {
  4453. assert(R->hasOneUse() && "Root should have only one use!");
  4454. return isa<GetElementPtrInst>(R->user_back());
  4455. })) {
  4456. MaxBitWidth = 8u;
  4457. // Determine if the sign bit of all the roots is known to be zero. If not,
  4458. // IsKnownPositive is set to False.
  4459. IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
  4460. KnownBits Known = computeKnownBits(R, *DL);
  4461. return Known.isNonNegative();
  4462. });
  4463. // Determine the maximum number of bits required to store the scalar
  4464. // values.
  4465. for (auto *Scalar : ToDemote) {
  4466. auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
  4467. auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
  4468. MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
  4469. }
  4470. // If we can't prove that the sign bit is zero, we must add one to the
  4471. // maximum bit width to account for the unknown sign bit. This preserves
  4472. // the existing sign bit so we can safely sign-extend the root back to the
  4473. // original type. Otherwise, if we know the sign bit is zero, we will
  4474. // zero-extend the root instead.
  4475. //
  4476. // FIXME: This is somewhat suboptimal, as there will be cases where adding
  4477. // one to the maximum bit width will yield a larger-than-necessary
  4478. // type. In general, we need to add an extra bit only if we can't
  4479. // prove that the upper bit of the original type is equal to the
  4480. // upper bit of the proposed smaller type. If these two bits are the
  4481. // same (either zero or one) we know that sign-extending from the
  4482. // smaller type will result in the same value. Here, since we can't
  4483. // yet prove this, we are just making the proposed smaller type
  4484. // larger to ensure correctness.
  4485. if (!IsKnownPositive)
  4486. ++MaxBitWidth;
  4487. }
  4488. // Round MaxBitWidth up to the next power-of-two.
  4489. if (!isPowerOf2_64(MaxBitWidth))
  4490. MaxBitWidth = NextPowerOf2(MaxBitWidth);
  4491. // If the maximum bit width we compute is less than the with of the roots'
  4492. // type, we can proceed with the narrowing. Otherwise, do nothing.
  4493. if (MaxBitWidth >= TreeRootIT->getBitWidth())
  4494. return;
  4495. // If we can truncate the root, we must collect additional values that might
  4496. // be demoted as a result. That is, those seeded by truncations we will
  4497. // modify.
  4498. while (!Roots.empty())
  4499. collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
  4500. // Finally, map the values we can demote to the maximum bit with we computed.
  4501. for (auto *Scalar : ToDemote)
  4502. MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
  4503. }
  4504. namespace {
  4505. /// The SLPVectorizer Pass.
  4506. struct SLPVectorizer : public FunctionPass {
  4507. SLPVectorizerPass Impl;
  4508. /// Pass identification, replacement for typeid
  4509. static char ID;
  4510. explicit SLPVectorizer() : FunctionPass(ID) {
  4511. initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
  4512. }
  4513. bool doInitialization(Module &M) override {
  4514. return false;
  4515. }
  4516. bool runOnFunction(Function &F) override {
  4517. if (skipFunction(F))
  4518. return false;
  4519. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  4520. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  4521. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  4522. auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
  4523. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  4524. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  4525. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  4526. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  4527. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  4528. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  4529. return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
  4530. }
  4531. void getAnalysisUsage(AnalysisUsage &AU) const override {
  4532. FunctionPass::getAnalysisUsage(AU);
  4533. AU.addRequired<AssumptionCacheTracker>();
  4534. AU.addRequired<ScalarEvolutionWrapperPass>();
  4535. AU.addRequired<AAResultsWrapperPass>();
  4536. AU.addRequired<TargetTransformInfoWrapperPass>();
  4537. AU.addRequired<LoopInfoWrapperPass>();
  4538. AU.addRequired<DominatorTreeWrapperPass>();
  4539. AU.addRequired<DemandedBitsWrapperPass>();
  4540. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  4541. AU.addPreserved<LoopInfoWrapperPass>();
  4542. AU.addPreserved<DominatorTreeWrapperPass>();
  4543. AU.addPreserved<AAResultsWrapperPass>();
  4544. AU.addPreserved<GlobalsAAWrapperPass>();
  4545. AU.setPreservesCFG();
  4546. }
  4547. };
  4548. } // end anonymous namespace
  4549. PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
  4550. auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
  4551. auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
  4552. auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
  4553. auto *AA = &AM.getResult<AAManager>(F);
  4554. auto *LI = &AM.getResult<LoopAnalysis>(F);
  4555. auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
  4556. auto *AC = &AM.getResult<AssumptionAnalysis>(F);
  4557. auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
  4558. auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  4559. bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
  4560. if (!Changed)
  4561. return PreservedAnalyses::all();
  4562. PreservedAnalyses PA;
  4563. PA.preserveSet<CFGAnalyses>();
  4564. PA.preserve<AAManager>();
  4565. PA.preserve<GlobalsAA>();
  4566. return PA;
  4567. }
  4568. bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
  4569. TargetTransformInfo *TTI_,
  4570. TargetLibraryInfo *TLI_, AliasAnalysis *AA_,
  4571. LoopInfo *LI_, DominatorTree *DT_,
  4572. AssumptionCache *AC_, DemandedBits *DB_,
  4573. OptimizationRemarkEmitter *ORE_) {
  4574. SE = SE_;
  4575. TTI = TTI_;
  4576. TLI = TLI_;
  4577. AA = AA_;
  4578. LI = LI_;
  4579. DT = DT_;
  4580. AC = AC_;
  4581. DB = DB_;
  4582. DL = &F.getParent()->getDataLayout();
  4583. Stores.clear();
  4584. GEPs.clear();
  4585. bool Changed = false;
  4586. // If the target claims to have no vector registers don't attempt
  4587. // vectorization.
  4588. if (!TTI->getNumberOfRegisters(true))
  4589. return false;
  4590. // Don't vectorize when the attribute NoImplicitFloat is used.
  4591. if (F.hasFnAttribute(Attribute::NoImplicitFloat))
  4592. return false;
  4593. LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
  4594. // Use the bottom up slp vectorizer to construct chains that start with
  4595. // store instructions.
  4596. BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
  4597. // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
  4598. // delete instructions.
  4599. // Scan the blocks in the function in post order.
  4600. for (auto BB : post_order(&F.getEntryBlock())) {
  4601. collectSeedInstructions(BB);
  4602. // Vectorize trees that end at stores.
  4603. if (!Stores.empty()) {
  4604. LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
  4605. << " underlying objects.\n");
  4606. Changed |= vectorizeStoreChains(R);
  4607. }
  4608. // Vectorize trees that end at reductions.
  4609. Changed |= vectorizeChainsInBlock(BB, R);
  4610. // Vectorize the index computations of getelementptr instructions. This
  4611. // is primarily intended to catch gather-like idioms ending at
  4612. // non-consecutive loads.
  4613. if (!GEPs.empty()) {
  4614. LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
  4615. << " underlying objects.\n");
  4616. Changed |= vectorizeGEPIndices(BB, R);
  4617. }
  4618. }
  4619. if (Changed) {
  4620. R.optimizeGatherSequence();
  4621. LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
  4622. LLVM_DEBUG(verifyFunction(F));
  4623. }
  4624. return Changed;
  4625. }
  4626. /// Check that the Values in the slice in VL array are still existent in
  4627. /// the WeakTrackingVH array.
  4628. /// Vectorization of part of the VL array may cause later values in the VL array
  4629. /// to become invalid. We track when this has happened in the WeakTrackingVH
  4630. /// array.
  4631. static bool hasValueBeenRAUWed(ArrayRef<Value *> VL,
  4632. ArrayRef<WeakTrackingVH> VH, unsigned SliceBegin,
  4633. unsigned SliceSize) {
  4634. VL = VL.slice(SliceBegin, SliceSize);
  4635. VH = VH.slice(SliceBegin, SliceSize);
  4636. return !std::equal(VL.begin(), VL.end(), VH.begin());
  4637. }
  4638. bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
  4639. unsigned VecRegSize) {
  4640. const unsigned ChainLen = Chain.size();
  4641. LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << ChainLen
  4642. << "\n");
  4643. const unsigned Sz = R.getVectorElementSize(Chain[0]);
  4644. const unsigned VF = VecRegSize / Sz;
  4645. if (!isPowerOf2_32(Sz) || VF < 2)
  4646. return false;
  4647. // Keep track of values that were deleted by vectorizing in the loop below.
  4648. const SmallVector<WeakTrackingVH, 8> TrackValues(Chain.begin(), Chain.end());
  4649. bool Changed = false;
  4650. // Look for profitable vectorizable trees at all offsets, starting at zero.
  4651. for (unsigned i = 0, e = ChainLen; i + VF <= e; ++i) {
  4652. // Check that a previous iteration of this loop did not delete the Value.
  4653. if (hasValueBeenRAUWed(Chain, TrackValues, i, VF))
  4654. continue;
  4655. LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << i
  4656. << "\n");
  4657. ArrayRef<Value *> Operands = Chain.slice(i, VF);
  4658. R.buildTree(Operands);
  4659. if (R.isTreeTinyAndNotFullyVectorizable())
  4660. continue;
  4661. R.computeMinimumValueSizes();
  4662. int Cost = R.getTreeCost();
  4663. LLVM_DEBUG(dbgs() << "SLP: Found cost=" << Cost << " for VF=" << VF
  4664. << "\n");
  4665. if (Cost < -SLPCostThreshold) {
  4666. LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost=" << Cost << "\n");
  4667. using namespace ore;
  4668. R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
  4669. cast<StoreInst>(Chain[i]))
  4670. << "Stores SLP vectorized with cost " << NV("Cost", Cost)
  4671. << " and with tree size "
  4672. << NV("TreeSize", R.getTreeSize()));
  4673. R.vectorizeTree();
  4674. // Move to the next bundle.
  4675. i += VF - 1;
  4676. Changed = true;
  4677. }
  4678. }
  4679. return Changed;
  4680. }
  4681. bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
  4682. BoUpSLP &R) {
  4683. SetVector<StoreInst *> Heads;
  4684. SmallDenseSet<StoreInst *> Tails;
  4685. SmallDenseMap<StoreInst *, StoreInst *> ConsecutiveChain;
  4686. // We may run into multiple chains that merge into a single chain. We mark the
  4687. // stores that we vectorized so that we don't visit the same store twice.
  4688. BoUpSLP::ValueSet VectorizedStores;
  4689. bool Changed = false;
  4690. auto &&FindConsecutiveAccess =
  4691. [this, &Stores, &Heads, &Tails, &ConsecutiveChain] (int K, int Idx) {
  4692. if (!isConsecutiveAccess(Stores[K], Stores[Idx], *DL, *SE))
  4693. return false;
  4694. Tails.insert(Stores[Idx]);
  4695. Heads.insert(Stores[K]);
  4696. ConsecutiveChain[Stores[K]] = Stores[Idx];
  4697. return true;
  4698. };
  4699. // Do a quadratic search on all of the given stores in reverse order and find
  4700. // all of the pairs of stores that follow each other.
  4701. int E = Stores.size();
  4702. for (int Idx = E - 1; Idx >= 0; --Idx) {
  4703. // If a store has multiple consecutive store candidates, search according
  4704. // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
  4705. // This is because usually pairing with immediate succeeding or preceding
  4706. // candidate create the best chance to find slp vectorization opportunity.
  4707. for (int Offset = 1, F = std::max(E - Idx, Idx + 1); Offset < F; ++Offset)
  4708. if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
  4709. (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
  4710. break;
  4711. }
  4712. // For stores that start but don't end a link in the chain:
  4713. for (auto *SI : llvm::reverse(Heads)) {
  4714. if (Tails.count(SI))
  4715. continue;
  4716. // We found a store instr that starts a chain. Now follow the chain and try
  4717. // to vectorize it.
  4718. BoUpSLP::ValueList Operands;
  4719. StoreInst *I = SI;
  4720. // Collect the chain into a list.
  4721. while ((Tails.count(I) || Heads.count(I)) && !VectorizedStores.count(I)) {
  4722. Operands.push_back(I);
  4723. // Move to the next value in the chain.
  4724. I = ConsecutiveChain[I];
  4725. }
  4726. // FIXME: Is division-by-2 the correct step? Should we assert that the
  4727. // register size is a power-of-2?
  4728. for (unsigned Size = R.getMaxVecRegSize(); Size >= R.getMinVecRegSize();
  4729. Size /= 2) {
  4730. if (vectorizeStoreChain(Operands, R, Size)) {
  4731. // Mark the vectorized stores so that we don't vectorize them again.
  4732. VectorizedStores.insert(Operands.begin(), Operands.end());
  4733. Changed = true;
  4734. break;
  4735. }
  4736. }
  4737. }
  4738. return Changed;
  4739. }
  4740. void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
  4741. // Initialize the collections. We will make a single pass over the block.
  4742. Stores.clear();
  4743. GEPs.clear();
  4744. // Visit the store and getelementptr instructions in BB and organize them in
  4745. // Stores and GEPs according to the underlying objects of their pointer
  4746. // operands.
  4747. for (Instruction &I : *BB) {
  4748. // Ignore store instructions that are volatile or have a pointer operand
  4749. // that doesn't point to a scalar type.
  4750. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  4751. if (!SI->isSimple())
  4752. continue;
  4753. if (!isValidElementType(SI->getValueOperand()->getType()))
  4754. continue;
  4755. Stores[GetUnderlyingObject(SI->getPointerOperand(), *DL)].push_back(SI);
  4756. }
  4757. // Ignore getelementptr instructions that have more than one index, a
  4758. // constant index, or a pointer operand that doesn't point to a scalar
  4759. // type.
  4760. else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  4761. auto Idx = GEP->idx_begin()->get();
  4762. if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
  4763. continue;
  4764. if (!isValidElementType(Idx->getType()))
  4765. continue;
  4766. if (GEP->getType()->isVectorTy())
  4767. continue;
  4768. GEPs[GEP->getPointerOperand()].push_back(GEP);
  4769. }
  4770. }
  4771. }
  4772. bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
  4773. if (!A || !B)
  4774. return false;
  4775. Value *VL[] = { A, B };
  4776. return tryToVectorizeList(VL, R, /*UserCost=*/0, true);
  4777. }
  4778. bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
  4779. int UserCost, bool AllowReorder) {
  4780. if (VL.size() < 2)
  4781. return false;
  4782. LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
  4783. << VL.size() << ".\n");
  4784. // Check that all of the parts are scalar instructions of the same type,
  4785. // we permit an alternate opcode via InstructionsState.
  4786. InstructionsState S = getSameOpcode(VL);
  4787. if (!S.getOpcode())
  4788. return false;
  4789. Instruction *I0 = cast<Instruction>(S.OpValue);
  4790. unsigned Sz = R.getVectorElementSize(I0);
  4791. unsigned MinVF = std::max(2U, R.getMinVecRegSize() / Sz);
  4792. unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
  4793. if (MaxVF < 2) {
  4794. R.getORE()->emit([&]() {
  4795. return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
  4796. << "Cannot SLP vectorize list: vectorization factor "
  4797. << "less than 2 is not supported";
  4798. });
  4799. return false;
  4800. }
  4801. for (Value *V : VL) {
  4802. Type *Ty = V->getType();
  4803. if (!isValidElementType(Ty)) {
  4804. // NOTE: the following will give user internal llvm type name, which may
  4805. // not be useful.
  4806. R.getORE()->emit([&]() {
  4807. std::string type_str;
  4808. llvm::raw_string_ostream rso(type_str);
  4809. Ty->print(rso);
  4810. return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
  4811. << "Cannot SLP vectorize list: type "
  4812. << rso.str() + " is unsupported by vectorizer";
  4813. });
  4814. return false;
  4815. }
  4816. }
  4817. bool Changed = false;
  4818. bool CandidateFound = false;
  4819. int MinCost = SLPCostThreshold;
  4820. // Keep track of values that were deleted by vectorizing in the loop below.
  4821. SmallVector<WeakTrackingVH, 8> TrackValues(VL.begin(), VL.end());
  4822. unsigned NextInst = 0, MaxInst = VL.size();
  4823. for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF;
  4824. VF /= 2) {
  4825. // No actual vectorization should happen, if number of parts is the same as
  4826. // provided vectorization factor (i.e. the scalar type is used for vector
  4827. // code during codegen).
  4828. auto *VecTy = VectorType::get(VL[0]->getType(), VF);
  4829. if (TTI->getNumberOfParts(VecTy) == VF)
  4830. continue;
  4831. for (unsigned I = NextInst; I < MaxInst; ++I) {
  4832. unsigned OpsWidth = 0;
  4833. if (I + VF > MaxInst)
  4834. OpsWidth = MaxInst - I;
  4835. else
  4836. OpsWidth = VF;
  4837. if (!isPowerOf2_32(OpsWidth) || OpsWidth < 2)
  4838. break;
  4839. // Check that a previous iteration of this loop did not delete the Value.
  4840. if (hasValueBeenRAUWed(VL, TrackValues, I, OpsWidth))
  4841. continue;
  4842. LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
  4843. << "\n");
  4844. ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
  4845. R.buildTree(Ops);
  4846. Optional<ArrayRef<unsigned>> Order = R.bestOrder();
  4847. // TODO: check if we can allow reordering for more cases.
  4848. if (AllowReorder && Order) {
  4849. // TODO: reorder tree nodes without tree rebuilding.
  4850. // Conceptually, there is nothing actually preventing us from trying to
  4851. // reorder a larger list. In fact, we do exactly this when vectorizing
  4852. // reductions. However, at this point, we only expect to get here when
  4853. // there are exactly two operations.
  4854. assert(Ops.size() == 2);
  4855. Value *ReorderedOps[] = {Ops[1], Ops[0]};
  4856. R.buildTree(ReorderedOps, None);
  4857. }
  4858. if (R.isTreeTinyAndNotFullyVectorizable())
  4859. continue;
  4860. R.computeMinimumValueSizes();
  4861. int Cost = R.getTreeCost() - UserCost;
  4862. CandidateFound = true;
  4863. MinCost = std::min(MinCost, Cost);
  4864. if (Cost < -SLPCostThreshold) {
  4865. LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
  4866. R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
  4867. cast<Instruction>(Ops[0]))
  4868. << "SLP vectorized with cost " << ore::NV("Cost", Cost)
  4869. << " and with tree size "
  4870. << ore::NV("TreeSize", R.getTreeSize()));
  4871. R.vectorizeTree();
  4872. // Move to the next bundle.
  4873. I += VF - 1;
  4874. NextInst = I + 1;
  4875. Changed = true;
  4876. }
  4877. }
  4878. }
  4879. if (!Changed && CandidateFound) {
  4880. R.getORE()->emit([&]() {
  4881. return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
  4882. << "List vectorization was possible but not beneficial with cost "
  4883. << ore::NV("Cost", MinCost) << " >= "
  4884. << ore::NV("Treshold", -SLPCostThreshold);
  4885. });
  4886. } else if (!Changed) {
  4887. R.getORE()->emit([&]() {
  4888. return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
  4889. << "Cannot SLP vectorize list: vectorization was impossible"
  4890. << " with available vectorization factors";
  4891. });
  4892. }
  4893. return Changed;
  4894. }
  4895. bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
  4896. if (!I)
  4897. return false;
  4898. if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
  4899. return false;
  4900. Value *P = I->getParent();
  4901. // Vectorize in current basic block only.
  4902. auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
  4903. auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
  4904. if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
  4905. return false;
  4906. // Try to vectorize V.
  4907. if (tryToVectorizePair(Op0, Op1, R))
  4908. return true;
  4909. auto *A = dyn_cast<BinaryOperator>(Op0);
  4910. auto *B = dyn_cast<BinaryOperator>(Op1);
  4911. // Try to skip B.
  4912. if (B && B->hasOneUse()) {
  4913. auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
  4914. auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
  4915. if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
  4916. return true;
  4917. if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
  4918. return true;
  4919. }
  4920. // Try to skip A.
  4921. if (A && A->hasOneUse()) {
  4922. auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
  4923. auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
  4924. if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
  4925. return true;
  4926. if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
  4927. return true;
  4928. }
  4929. return false;
  4930. }
  4931. /// Generate a shuffle mask to be used in a reduction tree.
  4932. ///
  4933. /// \param VecLen The length of the vector to be reduced.
  4934. /// \param NumEltsToRdx The number of elements that should be reduced in the
  4935. /// vector.
  4936. /// \param IsPairwise Whether the reduction is a pairwise or splitting
  4937. /// reduction. A pairwise reduction will generate a mask of
  4938. /// <0,2,...> or <1,3,..> while a splitting reduction will generate
  4939. /// <2,3, undef,undef> for a vector of 4 and NumElts = 2.
  4940. /// \param IsLeft True will generate a mask of even elements, odd otherwise.
  4941. static Value *createRdxShuffleMask(unsigned VecLen, unsigned NumEltsToRdx,
  4942. bool IsPairwise, bool IsLeft,
  4943. IRBuilder<> &Builder) {
  4944. assert((IsPairwise || !IsLeft) && "Don't support a <0,1,undef,...> mask");
  4945. SmallVector<Constant *, 32> ShuffleMask(
  4946. VecLen, UndefValue::get(Builder.getInt32Ty()));
  4947. if (IsPairwise)
  4948. // Build a mask of 0, 2, ... (left) or 1, 3, ... (right).
  4949. for (unsigned i = 0; i != NumEltsToRdx; ++i)
  4950. ShuffleMask[i] = Builder.getInt32(2 * i + !IsLeft);
  4951. else
  4952. // Move the upper half of the vector to the lower half.
  4953. for (unsigned i = 0; i != NumEltsToRdx; ++i)
  4954. ShuffleMask[i] = Builder.getInt32(NumEltsToRdx + i);
  4955. return ConstantVector::get(ShuffleMask);
  4956. }
  4957. namespace {
  4958. /// Model horizontal reductions.
  4959. ///
  4960. /// A horizontal reduction is a tree of reduction operations (currently add and
  4961. /// fadd) that has operations that can be put into a vector as its leaf.
  4962. /// For example, this tree:
  4963. ///
  4964. /// mul mul mul mul
  4965. /// \ / \ /
  4966. /// + +
  4967. /// \ /
  4968. /// +
  4969. /// This tree has "mul" as its reduced values and "+" as its reduction
  4970. /// operations. A reduction might be feeding into a store or a binary operation
  4971. /// feeding a phi.
  4972. /// ...
  4973. /// \ /
  4974. /// +
  4975. /// |
  4976. /// phi +=
  4977. ///
  4978. /// Or:
  4979. /// ...
  4980. /// \ /
  4981. /// +
  4982. /// |
  4983. /// *p =
  4984. ///
  4985. class HorizontalReduction {
  4986. using ReductionOpsType = SmallVector<Value *, 16>;
  4987. using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
  4988. ReductionOpsListType ReductionOps;
  4989. SmallVector<Value *, 32> ReducedVals;
  4990. // Use map vector to make stable output.
  4991. MapVector<Instruction *, Value *> ExtraArgs;
  4992. /// Kind of the reduction data.
  4993. enum ReductionKind {
  4994. RK_None, /// Not a reduction.
  4995. RK_Arithmetic, /// Binary reduction data.
  4996. RK_Min, /// Minimum reduction data.
  4997. RK_UMin, /// Unsigned minimum reduction data.
  4998. RK_Max, /// Maximum reduction data.
  4999. RK_UMax, /// Unsigned maximum reduction data.
  5000. };
  5001. /// Contains info about operation, like its opcode, left and right operands.
  5002. class OperationData {
  5003. /// Opcode of the instruction.
  5004. unsigned Opcode = 0;
  5005. /// Left operand of the reduction operation.
  5006. Value *LHS = nullptr;
  5007. /// Right operand of the reduction operation.
  5008. Value *RHS = nullptr;
  5009. /// Kind of the reduction operation.
  5010. ReductionKind Kind = RK_None;
  5011. /// True if float point min/max reduction has no NaNs.
  5012. bool NoNaN = false;
  5013. /// Checks if the reduction operation can be vectorized.
  5014. bool isVectorizable() const {
  5015. return LHS && RHS &&
  5016. // We currently only support add/mul/logical && min/max reductions.
  5017. ((Kind == RK_Arithmetic &&
  5018. (Opcode == Instruction::Add || Opcode == Instruction::FAdd ||
  5019. Opcode == Instruction::Mul || Opcode == Instruction::FMul ||
  5020. Opcode == Instruction::And || Opcode == Instruction::Or ||
  5021. Opcode == Instruction::Xor)) ||
  5022. ((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
  5023. (Kind == RK_Min || Kind == RK_Max)) ||
  5024. (Opcode == Instruction::ICmp &&
  5025. (Kind == RK_UMin || Kind == RK_UMax)));
  5026. }
  5027. /// Creates reduction operation with the current opcode.
  5028. Value *createOp(IRBuilder<> &Builder, const Twine &Name) const {
  5029. assert(isVectorizable() &&
  5030. "Expected add|fadd or min/max reduction operation.");
  5031. Value *Cmp = nullptr;
  5032. switch (Kind) {
  5033. case RK_Arithmetic:
  5034. return Builder.CreateBinOp((Instruction::BinaryOps)Opcode, LHS, RHS,
  5035. Name);
  5036. case RK_Min:
  5037. Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSLT(LHS, RHS)
  5038. : Builder.CreateFCmpOLT(LHS, RHS);
  5039. break;
  5040. case RK_Max:
  5041. Cmp = Opcode == Instruction::ICmp ? Builder.CreateICmpSGT(LHS, RHS)
  5042. : Builder.CreateFCmpOGT(LHS, RHS);
  5043. break;
  5044. case RK_UMin:
  5045. assert(Opcode == Instruction::ICmp && "Expected integer types.");
  5046. Cmp = Builder.CreateICmpULT(LHS, RHS);
  5047. break;
  5048. case RK_UMax:
  5049. assert(Opcode == Instruction::ICmp && "Expected integer types.");
  5050. Cmp = Builder.CreateICmpUGT(LHS, RHS);
  5051. break;
  5052. case RK_None:
  5053. llvm_unreachable("Unknown reduction operation.");
  5054. }
  5055. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  5056. }
  5057. public:
  5058. explicit OperationData() = default;
  5059. /// Construction for reduced values. They are identified by opcode only and
  5060. /// don't have associated LHS/RHS values.
  5061. explicit OperationData(Value *V) {
  5062. if (auto *I = dyn_cast<Instruction>(V))
  5063. Opcode = I->getOpcode();
  5064. }
  5065. /// Constructor for reduction operations with opcode and its left and
  5066. /// right operands.
  5067. OperationData(unsigned Opcode, Value *LHS, Value *RHS, ReductionKind Kind,
  5068. bool NoNaN = false)
  5069. : Opcode(Opcode), LHS(LHS), RHS(RHS), Kind(Kind), NoNaN(NoNaN) {
  5070. assert(Kind != RK_None && "One of the reduction operations is expected.");
  5071. }
  5072. explicit operator bool() const { return Opcode; }
  5073. /// Get the index of the first operand.
  5074. unsigned getFirstOperandIndex() const {
  5075. assert(!!*this && "The opcode is not set.");
  5076. switch (Kind) {
  5077. case RK_Min:
  5078. case RK_UMin:
  5079. case RK_Max:
  5080. case RK_UMax:
  5081. return 1;
  5082. case RK_Arithmetic:
  5083. case RK_None:
  5084. break;
  5085. }
  5086. return 0;
  5087. }
  5088. /// Total number of operands in the reduction operation.
  5089. unsigned getNumberOfOperands() const {
  5090. assert(Kind != RK_None && !!*this && LHS && RHS &&
  5091. "Expected reduction operation.");
  5092. switch (Kind) {
  5093. case RK_Arithmetic:
  5094. return 2;
  5095. case RK_Min:
  5096. case RK_UMin:
  5097. case RK_Max:
  5098. case RK_UMax:
  5099. return 3;
  5100. case RK_None:
  5101. break;
  5102. }
  5103. llvm_unreachable("Reduction kind is not set");
  5104. }
  5105. /// Checks if the operation has the same parent as \p P.
  5106. bool hasSameParent(Instruction *I, Value *P, bool IsRedOp) const {
  5107. assert(Kind != RK_None && !!*this && LHS && RHS &&
  5108. "Expected reduction operation.");
  5109. if (!IsRedOp)
  5110. return I->getParent() == P;
  5111. switch (Kind) {
  5112. case RK_Arithmetic:
  5113. // Arithmetic reduction operation must be used once only.
  5114. return I->getParent() == P;
  5115. case RK_Min:
  5116. case RK_UMin:
  5117. case RK_Max:
  5118. case RK_UMax: {
  5119. // SelectInst must be used twice while the condition op must have single
  5120. // use only.
  5121. auto *Cmp = cast<Instruction>(cast<SelectInst>(I)->getCondition());
  5122. return I->getParent() == P && Cmp && Cmp->getParent() == P;
  5123. }
  5124. case RK_None:
  5125. break;
  5126. }
  5127. llvm_unreachable("Reduction kind is not set");
  5128. }
  5129. /// Expected number of uses for reduction operations/reduced values.
  5130. bool hasRequiredNumberOfUses(Instruction *I, bool IsReductionOp) const {
  5131. assert(Kind != RK_None && !!*this && LHS && RHS &&
  5132. "Expected reduction operation.");
  5133. switch (Kind) {
  5134. case RK_Arithmetic:
  5135. return I->hasOneUse();
  5136. case RK_Min:
  5137. case RK_UMin:
  5138. case RK_Max:
  5139. case RK_UMax:
  5140. return I->hasNUses(2) &&
  5141. (!IsReductionOp ||
  5142. cast<SelectInst>(I)->getCondition()->hasOneUse());
  5143. case RK_None:
  5144. break;
  5145. }
  5146. llvm_unreachable("Reduction kind is not set");
  5147. }
  5148. /// Initializes the list of reduction operations.
  5149. void initReductionOps(ReductionOpsListType &ReductionOps) {
  5150. assert(Kind != RK_None && !!*this && LHS && RHS &&
  5151. "Expected reduction operation.");
  5152. switch (Kind) {
  5153. case RK_Arithmetic:
  5154. ReductionOps.assign(1, ReductionOpsType());
  5155. break;
  5156. case RK_Min:
  5157. case RK_UMin:
  5158. case RK_Max:
  5159. case RK_UMax:
  5160. ReductionOps.assign(2, ReductionOpsType());
  5161. break;
  5162. case RK_None:
  5163. llvm_unreachable("Reduction kind is not set");
  5164. }
  5165. }
  5166. /// Add all reduction operations for the reduction instruction \p I.
  5167. void addReductionOps(Instruction *I, ReductionOpsListType &ReductionOps) {
  5168. assert(Kind != RK_None && !!*this && LHS && RHS &&
  5169. "Expected reduction operation.");
  5170. switch (Kind) {
  5171. case RK_Arithmetic:
  5172. ReductionOps[0].emplace_back(I);
  5173. break;
  5174. case RK_Min:
  5175. case RK_UMin:
  5176. case RK_Max:
  5177. case RK_UMax:
  5178. ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
  5179. ReductionOps[1].emplace_back(I);
  5180. break;
  5181. case RK_None:
  5182. llvm_unreachable("Reduction kind is not set");
  5183. }
  5184. }
  5185. /// Checks if instruction is associative and can be vectorized.
  5186. bool isAssociative(Instruction *I) const {
  5187. assert(Kind != RK_None && *this && LHS && RHS &&
  5188. "Expected reduction operation.");
  5189. switch (Kind) {
  5190. case RK_Arithmetic:
  5191. return I->isAssociative();
  5192. case RK_Min:
  5193. case RK_Max:
  5194. return Opcode == Instruction::ICmp ||
  5195. cast<Instruction>(I->getOperand(0))->isFast();
  5196. case RK_UMin:
  5197. case RK_UMax:
  5198. assert(Opcode == Instruction::ICmp &&
  5199. "Only integer compare operation is expected.");
  5200. return true;
  5201. case RK_None:
  5202. break;
  5203. }
  5204. llvm_unreachable("Reduction kind is not set");
  5205. }
  5206. /// Checks if the reduction operation can be vectorized.
  5207. bool isVectorizable(Instruction *I) const {
  5208. return isVectorizable() && isAssociative(I);
  5209. }
  5210. /// Checks if two operation data are both a reduction op or both a reduced
  5211. /// value.
  5212. bool operator==(const OperationData &OD) {
  5213. assert(((Kind != OD.Kind) || ((!LHS == !OD.LHS) && (!RHS == !OD.RHS))) &&
  5214. "One of the comparing operations is incorrect.");
  5215. return this == &OD || (Kind == OD.Kind && Opcode == OD.Opcode);
  5216. }
  5217. bool operator!=(const OperationData &OD) { return !(*this == OD); }
  5218. void clear() {
  5219. Opcode = 0;
  5220. LHS = nullptr;
  5221. RHS = nullptr;
  5222. Kind = RK_None;
  5223. NoNaN = false;
  5224. }
  5225. /// Get the opcode of the reduction operation.
  5226. unsigned getOpcode() const {
  5227. assert(isVectorizable() && "Expected vectorizable operation.");
  5228. return Opcode;
  5229. }
  5230. /// Get kind of reduction data.
  5231. ReductionKind getKind() const { return Kind; }
  5232. Value *getLHS() const { return LHS; }
  5233. Value *getRHS() const { return RHS; }
  5234. Type *getConditionType() const {
  5235. switch (Kind) {
  5236. case RK_Arithmetic:
  5237. return nullptr;
  5238. case RK_Min:
  5239. case RK_Max:
  5240. case RK_UMin:
  5241. case RK_UMax:
  5242. return CmpInst::makeCmpResultType(LHS->getType());
  5243. case RK_None:
  5244. break;
  5245. }
  5246. llvm_unreachable("Reduction kind is not set");
  5247. }
  5248. /// Creates reduction operation with the current opcode with the IR flags
  5249. /// from \p ReductionOps.
  5250. Value *createOp(IRBuilder<> &Builder, const Twine &Name,
  5251. const ReductionOpsListType &ReductionOps) const {
  5252. assert(isVectorizable() &&
  5253. "Expected add|fadd or min/max reduction operation.");
  5254. auto *Op = createOp(Builder, Name);
  5255. switch (Kind) {
  5256. case RK_Arithmetic:
  5257. propagateIRFlags(Op, ReductionOps[0]);
  5258. return Op;
  5259. case RK_Min:
  5260. case RK_Max:
  5261. case RK_UMin:
  5262. case RK_UMax:
  5263. if (auto *SI = dyn_cast<SelectInst>(Op))
  5264. propagateIRFlags(SI->getCondition(), ReductionOps[0]);
  5265. propagateIRFlags(Op, ReductionOps[1]);
  5266. return Op;
  5267. case RK_None:
  5268. break;
  5269. }
  5270. llvm_unreachable("Unknown reduction operation.");
  5271. }
  5272. /// Creates reduction operation with the current opcode with the IR flags
  5273. /// from \p I.
  5274. Value *createOp(IRBuilder<> &Builder, const Twine &Name,
  5275. Instruction *I) const {
  5276. assert(isVectorizable() &&
  5277. "Expected add|fadd or min/max reduction operation.");
  5278. auto *Op = createOp(Builder, Name);
  5279. switch (Kind) {
  5280. case RK_Arithmetic:
  5281. propagateIRFlags(Op, I);
  5282. return Op;
  5283. case RK_Min:
  5284. case RK_Max:
  5285. case RK_UMin:
  5286. case RK_UMax:
  5287. if (auto *SI = dyn_cast<SelectInst>(Op)) {
  5288. propagateIRFlags(SI->getCondition(),
  5289. cast<SelectInst>(I)->getCondition());
  5290. }
  5291. propagateIRFlags(Op, I);
  5292. return Op;
  5293. case RK_None:
  5294. break;
  5295. }
  5296. llvm_unreachable("Unknown reduction operation.");
  5297. }
  5298. TargetTransformInfo::ReductionFlags getFlags() const {
  5299. TargetTransformInfo::ReductionFlags Flags;
  5300. Flags.NoNaN = NoNaN;
  5301. switch (Kind) {
  5302. case RK_Arithmetic:
  5303. break;
  5304. case RK_Min:
  5305. Flags.IsSigned = Opcode == Instruction::ICmp;
  5306. Flags.IsMaxOp = false;
  5307. break;
  5308. case RK_Max:
  5309. Flags.IsSigned = Opcode == Instruction::ICmp;
  5310. Flags.IsMaxOp = true;
  5311. break;
  5312. case RK_UMin:
  5313. Flags.IsSigned = false;
  5314. Flags.IsMaxOp = false;
  5315. break;
  5316. case RK_UMax:
  5317. Flags.IsSigned = false;
  5318. Flags.IsMaxOp = true;
  5319. break;
  5320. case RK_None:
  5321. llvm_unreachable("Reduction kind is not set");
  5322. }
  5323. return Flags;
  5324. }
  5325. };
  5326. WeakTrackingVH ReductionRoot;
  5327. /// The operation data of the reduction operation.
  5328. OperationData ReductionData;
  5329. /// The operation data of the values we perform a reduction on.
  5330. OperationData ReducedValueData;
  5331. /// Should we model this reduction as a pairwise reduction tree or a tree that
  5332. /// splits the vector in halves and adds those halves.
  5333. bool IsPairwiseReduction = false;
  5334. /// Checks if the ParentStackElem.first should be marked as a reduction
  5335. /// operation with an extra argument or as extra argument itself.
  5336. void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
  5337. Value *ExtraArg) {
  5338. if (ExtraArgs.count(ParentStackElem.first)) {
  5339. ExtraArgs[ParentStackElem.first] = nullptr;
  5340. // We ran into something like:
  5341. // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
  5342. // The whole ParentStackElem.first should be considered as an extra value
  5343. // in this case.
  5344. // Do not perform analysis of remaining operands of ParentStackElem.first
  5345. // instruction, this whole instruction is an extra argument.
  5346. ParentStackElem.second = ParentStackElem.first->getNumOperands();
  5347. } else {
  5348. // We ran into something like:
  5349. // ParentStackElem.first += ... + ExtraArg + ...
  5350. ExtraArgs[ParentStackElem.first] = ExtraArg;
  5351. }
  5352. }
  5353. static OperationData getOperationData(Value *V) {
  5354. if (!V)
  5355. return OperationData();
  5356. Value *LHS;
  5357. Value *RHS;
  5358. if (m_BinOp(m_Value(LHS), m_Value(RHS)).match(V)) {
  5359. return OperationData(cast<BinaryOperator>(V)->getOpcode(), LHS, RHS,
  5360. RK_Arithmetic);
  5361. }
  5362. if (auto *Select = dyn_cast<SelectInst>(V)) {
  5363. // Look for a min/max pattern.
  5364. if (m_UMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
  5365. return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
  5366. } else if (m_SMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
  5367. return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
  5368. } else if (m_OrdFMin(m_Value(LHS), m_Value(RHS)).match(Select) ||
  5369. m_UnordFMin(m_Value(LHS), m_Value(RHS)).match(Select)) {
  5370. return OperationData(
  5371. Instruction::FCmp, LHS, RHS, RK_Min,
  5372. cast<Instruction>(Select->getCondition())->hasNoNaNs());
  5373. } else if (m_UMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
  5374. return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
  5375. } else if (m_SMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
  5376. return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
  5377. } else if (m_OrdFMax(m_Value(LHS), m_Value(RHS)).match(Select) ||
  5378. m_UnordFMax(m_Value(LHS), m_Value(RHS)).match(Select)) {
  5379. return OperationData(
  5380. Instruction::FCmp, LHS, RHS, RK_Max,
  5381. cast<Instruction>(Select->getCondition())->hasNoNaNs());
  5382. } else {
  5383. // Try harder: look for min/max pattern based on instructions producing
  5384. // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
  5385. // During the intermediate stages of SLP, it's very common to have
  5386. // pattern like this (since optimizeGatherSequence is run only once
  5387. // at the end):
  5388. // %1 = extractelement <2 x i32> %a, i32 0
  5389. // %2 = extractelement <2 x i32> %a, i32 1
  5390. // %cond = icmp sgt i32 %1, %2
  5391. // %3 = extractelement <2 x i32> %a, i32 0
  5392. // %4 = extractelement <2 x i32> %a, i32 1
  5393. // %select = select i1 %cond, i32 %3, i32 %4
  5394. CmpInst::Predicate Pred;
  5395. Instruction *L1;
  5396. Instruction *L2;
  5397. LHS = Select->getTrueValue();
  5398. RHS = Select->getFalseValue();
  5399. Value *Cond = Select->getCondition();
  5400. // TODO: Support inverse predicates.
  5401. if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
  5402. if (!isa<ExtractElementInst>(RHS) ||
  5403. !L2->isIdenticalTo(cast<Instruction>(RHS)))
  5404. return OperationData(V);
  5405. } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
  5406. if (!isa<ExtractElementInst>(LHS) ||
  5407. !L1->isIdenticalTo(cast<Instruction>(LHS)))
  5408. return OperationData(V);
  5409. } else {
  5410. if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
  5411. return OperationData(V);
  5412. if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
  5413. !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
  5414. !L2->isIdenticalTo(cast<Instruction>(RHS)))
  5415. return OperationData(V);
  5416. }
  5417. switch (Pred) {
  5418. default:
  5419. return OperationData(V);
  5420. case CmpInst::ICMP_ULT:
  5421. case CmpInst::ICMP_ULE:
  5422. return OperationData(Instruction::ICmp, LHS, RHS, RK_UMin);
  5423. case CmpInst::ICMP_SLT:
  5424. case CmpInst::ICMP_SLE:
  5425. return OperationData(Instruction::ICmp, LHS, RHS, RK_Min);
  5426. case CmpInst::FCMP_OLT:
  5427. case CmpInst::FCMP_OLE:
  5428. case CmpInst::FCMP_ULT:
  5429. case CmpInst::FCMP_ULE:
  5430. return OperationData(Instruction::FCmp, LHS, RHS, RK_Min,
  5431. cast<Instruction>(Cond)->hasNoNaNs());
  5432. case CmpInst::ICMP_UGT:
  5433. case CmpInst::ICMP_UGE:
  5434. return OperationData(Instruction::ICmp, LHS, RHS, RK_UMax);
  5435. case CmpInst::ICMP_SGT:
  5436. case CmpInst::ICMP_SGE:
  5437. return OperationData(Instruction::ICmp, LHS, RHS, RK_Max);
  5438. case CmpInst::FCMP_OGT:
  5439. case CmpInst::FCMP_OGE:
  5440. case CmpInst::FCMP_UGT:
  5441. case CmpInst::FCMP_UGE:
  5442. return OperationData(Instruction::FCmp, LHS, RHS, RK_Max,
  5443. cast<Instruction>(Cond)->hasNoNaNs());
  5444. }
  5445. }
  5446. }
  5447. return OperationData(V);
  5448. }
  5449. public:
  5450. HorizontalReduction() = default;
  5451. /// Try to find a reduction tree.
  5452. bool matchAssociativeReduction(PHINode *Phi, Instruction *B) {
  5453. assert((!Phi || is_contained(Phi->operands(), B)) &&
  5454. "Thi phi needs to use the binary operator");
  5455. ReductionData = getOperationData(B);
  5456. // We could have a initial reductions that is not an add.
  5457. // r *= v1 + v2 + v3 + v4
  5458. // In such a case start looking for a tree rooted in the first '+'.
  5459. if (Phi) {
  5460. if (ReductionData.getLHS() == Phi) {
  5461. Phi = nullptr;
  5462. B = dyn_cast<Instruction>(ReductionData.getRHS());
  5463. ReductionData = getOperationData(B);
  5464. } else if (ReductionData.getRHS() == Phi) {
  5465. Phi = nullptr;
  5466. B = dyn_cast<Instruction>(ReductionData.getLHS());
  5467. ReductionData = getOperationData(B);
  5468. }
  5469. }
  5470. if (!ReductionData.isVectorizable(B))
  5471. return false;
  5472. Type *Ty = B->getType();
  5473. if (!isValidElementType(Ty))
  5474. return false;
  5475. if (!Ty->isIntOrIntVectorTy() && !Ty->isFPOrFPVectorTy())
  5476. return false;
  5477. ReducedValueData.clear();
  5478. ReductionRoot = B;
  5479. // Post order traverse the reduction tree starting at B. We only handle true
  5480. // trees containing only binary operators.
  5481. SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
  5482. Stack.push_back(std::make_pair(B, ReductionData.getFirstOperandIndex()));
  5483. ReductionData.initReductionOps(ReductionOps);
  5484. while (!Stack.empty()) {
  5485. Instruction *TreeN = Stack.back().first;
  5486. unsigned EdgeToVist = Stack.back().second++;
  5487. OperationData OpData = getOperationData(TreeN);
  5488. bool IsReducedValue = OpData != ReductionData;
  5489. // Postorder vist.
  5490. if (IsReducedValue || EdgeToVist == OpData.getNumberOfOperands()) {
  5491. if (IsReducedValue)
  5492. ReducedVals.push_back(TreeN);
  5493. else {
  5494. auto I = ExtraArgs.find(TreeN);
  5495. if (I != ExtraArgs.end() && !I->second) {
  5496. // Check if TreeN is an extra argument of its parent operation.
  5497. if (Stack.size() <= 1) {
  5498. // TreeN can't be an extra argument as it is a root reduction
  5499. // operation.
  5500. return false;
  5501. }
  5502. // Yes, TreeN is an extra argument, do not add it to a list of
  5503. // reduction operations.
  5504. // Stack[Stack.size() - 2] always points to the parent operation.
  5505. markExtraArg(Stack[Stack.size() - 2], TreeN);
  5506. ExtraArgs.erase(TreeN);
  5507. } else
  5508. ReductionData.addReductionOps(TreeN, ReductionOps);
  5509. }
  5510. // Retract.
  5511. Stack.pop_back();
  5512. continue;
  5513. }
  5514. // Visit left or right.
  5515. Value *NextV = TreeN->getOperand(EdgeToVist);
  5516. if (NextV != Phi) {
  5517. auto *I = dyn_cast<Instruction>(NextV);
  5518. OpData = getOperationData(I);
  5519. // Continue analysis if the next operand is a reduction operation or
  5520. // (possibly) a reduced value. If the reduced value opcode is not set,
  5521. // the first met operation != reduction operation is considered as the
  5522. // reduced value class.
  5523. if (I && (!ReducedValueData || OpData == ReducedValueData ||
  5524. OpData == ReductionData)) {
  5525. const bool IsReductionOperation = OpData == ReductionData;
  5526. // Only handle trees in the current basic block.
  5527. if (!ReductionData.hasSameParent(I, B->getParent(),
  5528. IsReductionOperation)) {
  5529. // I is an extra argument for TreeN (its parent operation).
  5530. markExtraArg(Stack.back(), I);
  5531. continue;
  5532. }
  5533. // Each tree node needs to have minimal number of users except for the
  5534. // ultimate reduction.
  5535. if (!ReductionData.hasRequiredNumberOfUses(I,
  5536. OpData == ReductionData) &&
  5537. I != B) {
  5538. // I is an extra argument for TreeN (its parent operation).
  5539. markExtraArg(Stack.back(), I);
  5540. continue;
  5541. }
  5542. if (IsReductionOperation) {
  5543. // We need to be able to reassociate the reduction operations.
  5544. if (!OpData.isAssociative(I)) {
  5545. // I is an extra argument for TreeN (its parent operation).
  5546. markExtraArg(Stack.back(), I);
  5547. continue;
  5548. }
  5549. } else if (ReducedValueData &&
  5550. ReducedValueData != OpData) {
  5551. // Make sure that the opcodes of the operations that we are going to
  5552. // reduce match.
  5553. // I is an extra argument for TreeN (its parent operation).
  5554. markExtraArg(Stack.back(), I);
  5555. continue;
  5556. } else if (!ReducedValueData)
  5557. ReducedValueData = OpData;
  5558. Stack.push_back(std::make_pair(I, OpData.getFirstOperandIndex()));
  5559. continue;
  5560. }
  5561. }
  5562. // NextV is an extra argument for TreeN (its parent operation).
  5563. markExtraArg(Stack.back(), NextV);
  5564. }
  5565. return true;
  5566. }
  5567. /// Attempt to vectorize the tree found by
  5568. /// matchAssociativeReduction.
  5569. bool tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
  5570. if (ReducedVals.empty())
  5571. return false;
  5572. // If there is a sufficient number of reduction values, reduce
  5573. // to a nearby power-of-2. Can safely generate oversized
  5574. // vectors and rely on the backend to split them to legal sizes.
  5575. unsigned NumReducedVals = ReducedVals.size();
  5576. if (NumReducedVals < 4)
  5577. return false;
  5578. unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
  5579. Value *VectorizedTree = nullptr;
  5580. // FIXME: Fast-math-flags should be set based on the instructions in the
  5581. // reduction (not all of 'fast' are required).
  5582. IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
  5583. FastMathFlags Unsafe;
  5584. Unsafe.setFast();
  5585. Builder.setFastMathFlags(Unsafe);
  5586. unsigned i = 0;
  5587. BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
  5588. // The same extra argument may be used several time, so log each attempt
  5589. // to use it.
  5590. for (auto &Pair : ExtraArgs) {
  5591. assert(Pair.first && "DebugLoc must be set.");
  5592. ExternallyUsedValues[Pair.second].push_back(Pair.first);
  5593. }
  5594. // The reduction root is used as the insertion point for new instructions,
  5595. // so set it as externally used to prevent it from being deleted.
  5596. ExternallyUsedValues[ReductionRoot];
  5597. SmallVector<Value *, 16> IgnoreList;
  5598. for (auto &V : ReductionOps)
  5599. IgnoreList.append(V.begin(), V.end());
  5600. while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
  5601. auto VL = makeArrayRef(&ReducedVals[i], ReduxWidth);
  5602. V.buildTree(VL, ExternallyUsedValues, IgnoreList);
  5603. Optional<ArrayRef<unsigned>> Order = V.bestOrder();
  5604. // TODO: Handle orders of size less than number of elements in the vector.
  5605. if (Order && Order->size() == VL.size()) {
  5606. // TODO: reorder tree nodes without tree rebuilding.
  5607. SmallVector<Value *, 4> ReorderedOps(VL.size());
  5608. llvm::transform(*Order, ReorderedOps.begin(),
  5609. [VL](const unsigned Idx) { return VL[Idx]; });
  5610. V.buildTree(ReorderedOps, ExternallyUsedValues, IgnoreList);
  5611. }
  5612. if (V.isTreeTinyAndNotFullyVectorizable())
  5613. break;
  5614. V.computeMinimumValueSizes();
  5615. // Estimate cost.
  5616. int TreeCost = V.getTreeCost();
  5617. int ReductionCost = getReductionCost(TTI, ReducedVals[i], ReduxWidth);
  5618. int Cost = TreeCost + ReductionCost;
  5619. if (Cost >= -SLPCostThreshold) {
  5620. V.getORE()->emit([&]() {
  5621. return OptimizationRemarkMissed(
  5622. SV_NAME, "HorSLPNotBeneficial", cast<Instruction>(VL[0]))
  5623. << "Vectorizing horizontal reduction is possible"
  5624. << "but not beneficial with cost "
  5625. << ore::NV("Cost", Cost) << " and threshold "
  5626. << ore::NV("Threshold", -SLPCostThreshold);
  5627. });
  5628. break;
  5629. }
  5630. LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
  5631. << Cost << ". (HorRdx)\n");
  5632. V.getORE()->emit([&]() {
  5633. return OptimizationRemark(
  5634. SV_NAME, "VectorizedHorizontalReduction", cast<Instruction>(VL[0]))
  5635. << "Vectorized horizontal reduction with cost "
  5636. << ore::NV("Cost", Cost) << " and with tree size "
  5637. << ore::NV("TreeSize", V.getTreeSize());
  5638. });
  5639. // Vectorize a tree.
  5640. DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
  5641. Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
  5642. // Emit a reduction.
  5643. Builder.SetInsertPoint(cast<Instruction>(ReductionRoot));
  5644. Value *ReducedSubTree =
  5645. emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
  5646. if (VectorizedTree) {
  5647. Builder.SetCurrentDebugLocation(Loc);
  5648. OperationData VectReductionData(ReductionData.getOpcode(),
  5649. VectorizedTree, ReducedSubTree,
  5650. ReductionData.getKind());
  5651. VectorizedTree =
  5652. VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
  5653. } else
  5654. VectorizedTree = ReducedSubTree;
  5655. i += ReduxWidth;
  5656. ReduxWidth = PowerOf2Floor(NumReducedVals - i);
  5657. }
  5658. if (VectorizedTree) {
  5659. // Finish the reduction.
  5660. for (; i < NumReducedVals; ++i) {
  5661. auto *I = cast<Instruction>(ReducedVals[i]);
  5662. Builder.SetCurrentDebugLocation(I->getDebugLoc());
  5663. OperationData VectReductionData(ReductionData.getOpcode(),
  5664. VectorizedTree, I,
  5665. ReductionData.getKind());
  5666. VectorizedTree = VectReductionData.createOp(Builder, "", ReductionOps);
  5667. }
  5668. for (auto &Pair : ExternallyUsedValues) {
  5669. // Add each externally used value to the final reduction.
  5670. for (auto *I : Pair.second) {
  5671. Builder.SetCurrentDebugLocation(I->getDebugLoc());
  5672. OperationData VectReductionData(ReductionData.getOpcode(),
  5673. VectorizedTree, Pair.first,
  5674. ReductionData.getKind());
  5675. VectorizedTree = VectReductionData.createOp(Builder, "op.extra", I);
  5676. }
  5677. }
  5678. // Update users.
  5679. ReductionRoot->replaceAllUsesWith(VectorizedTree);
  5680. }
  5681. return VectorizedTree != nullptr;
  5682. }
  5683. unsigned numReductionValues() const {
  5684. return ReducedVals.size();
  5685. }
  5686. private:
  5687. /// Calculate the cost of a reduction.
  5688. int getReductionCost(TargetTransformInfo *TTI, Value *FirstReducedVal,
  5689. unsigned ReduxWidth) {
  5690. Type *ScalarTy = FirstReducedVal->getType();
  5691. Type *VecTy = VectorType::get(ScalarTy, ReduxWidth);
  5692. int PairwiseRdxCost;
  5693. int SplittingRdxCost;
  5694. switch (ReductionData.getKind()) {
  5695. case RK_Arithmetic:
  5696. PairwiseRdxCost =
  5697. TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
  5698. /*IsPairwiseForm=*/true);
  5699. SplittingRdxCost =
  5700. TTI->getArithmeticReductionCost(ReductionData.getOpcode(), VecTy,
  5701. /*IsPairwiseForm=*/false);
  5702. break;
  5703. case RK_Min:
  5704. case RK_Max:
  5705. case RK_UMin:
  5706. case RK_UMax: {
  5707. Type *VecCondTy = CmpInst::makeCmpResultType(VecTy);
  5708. bool IsUnsigned = ReductionData.getKind() == RK_UMin ||
  5709. ReductionData.getKind() == RK_UMax;
  5710. PairwiseRdxCost =
  5711. TTI->getMinMaxReductionCost(VecTy, VecCondTy,
  5712. /*IsPairwiseForm=*/true, IsUnsigned);
  5713. SplittingRdxCost =
  5714. TTI->getMinMaxReductionCost(VecTy, VecCondTy,
  5715. /*IsPairwiseForm=*/false, IsUnsigned);
  5716. break;
  5717. }
  5718. case RK_None:
  5719. llvm_unreachable("Expected arithmetic or min/max reduction operation");
  5720. }
  5721. IsPairwiseReduction = PairwiseRdxCost < SplittingRdxCost;
  5722. int VecReduxCost = IsPairwiseReduction ? PairwiseRdxCost : SplittingRdxCost;
  5723. int ScalarReduxCost = 0;
  5724. switch (ReductionData.getKind()) {
  5725. case RK_Arithmetic:
  5726. ScalarReduxCost =
  5727. TTI->getArithmeticInstrCost(ReductionData.getOpcode(), ScalarTy);
  5728. break;
  5729. case RK_Min:
  5730. case RK_Max:
  5731. case RK_UMin:
  5732. case RK_UMax:
  5733. ScalarReduxCost =
  5734. TTI->getCmpSelInstrCost(ReductionData.getOpcode(), ScalarTy) +
  5735. TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
  5736. CmpInst::makeCmpResultType(ScalarTy));
  5737. break;
  5738. case RK_None:
  5739. llvm_unreachable("Expected arithmetic or min/max reduction operation");
  5740. }
  5741. ScalarReduxCost *= (ReduxWidth - 1);
  5742. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VecReduxCost - ScalarReduxCost
  5743. << " for reduction that starts with " << *FirstReducedVal
  5744. << " (It is a "
  5745. << (IsPairwiseReduction ? "pairwise" : "splitting")
  5746. << " reduction)\n");
  5747. return VecReduxCost - ScalarReduxCost;
  5748. }
  5749. /// Emit a horizontal reduction of the vectorized value.
  5750. Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
  5751. unsigned ReduxWidth, const TargetTransformInfo *TTI) {
  5752. assert(VectorizedValue && "Need to have a vectorized tree node");
  5753. assert(isPowerOf2_32(ReduxWidth) &&
  5754. "We only handle power-of-two reductions for now");
  5755. if (!IsPairwiseReduction) {
  5756. // FIXME: The builder should use an FMF guard. It should not be hard-coded
  5757. // to 'fast'.
  5758. assert(Builder.getFastMathFlags().isFast() && "Expected 'fast' FMF");
  5759. return createSimpleTargetReduction(
  5760. Builder, TTI, ReductionData.getOpcode(), VectorizedValue,
  5761. ReductionData.getFlags(), ReductionOps.back());
  5762. }
  5763. Value *TmpVec = VectorizedValue;
  5764. for (unsigned i = ReduxWidth / 2; i != 0; i >>= 1) {
  5765. Value *LeftMask =
  5766. createRdxShuffleMask(ReduxWidth, i, true, true, Builder);
  5767. Value *RightMask =
  5768. createRdxShuffleMask(ReduxWidth, i, true, false, Builder);
  5769. Value *LeftShuf = Builder.CreateShuffleVector(
  5770. TmpVec, UndefValue::get(TmpVec->getType()), LeftMask, "rdx.shuf.l");
  5771. Value *RightShuf = Builder.CreateShuffleVector(
  5772. TmpVec, UndefValue::get(TmpVec->getType()), (RightMask),
  5773. "rdx.shuf.r");
  5774. OperationData VectReductionData(ReductionData.getOpcode(), LeftShuf,
  5775. RightShuf, ReductionData.getKind());
  5776. TmpVec = VectReductionData.createOp(Builder, "op.rdx", ReductionOps);
  5777. }
  5778. // The result is in the first element of the vector.
  5779. return Builder.CreateExtractElement(TmpVec, Builder.getInt32(0));
  5780. }
  5781. };
  5782. } // end anonymous namespace
  5783. /// Recognize construction of vectors like
  5784. /// %ra = insertelement <4 x float> undef, float %s0, i32 0
  5785. /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
  5786. /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
  5787. /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
  5788. /// starting from the last insertelement instruction.
  5789. ///
  5790. /// Returns true if it matches
  5791. static bool findBuildVector(InsertElementInst *LastInsertElem,
  5792. TargetTransformInfo *TTI,
  5793. SmallVectorImpl<Value *> &BuildVectorOpds,
  5794. int &UserCost) {
  5795. UserCost = 0;
  5796. Value *V = nullptr;
  5797. do {
  5798. if (auto *CI = dyn_cast<ConstantInt>(LastInsertElem->getOperand(2))) {
  5799. UserCost += TTI->getVectorInstrCost(Instruction::InsertElement,
  5800. LastInsertElem->getType(),
  5801. CI->getZExtValue());
  5802. }
  5803. BuildVectorOpds.push_back(LastInsertElem->getOperand(1));
  5804. V = LastInsertElem->getOperand(0);
  5805. if (isa<UndefValue>(V))
  5806. break;
  5807. LastInsertElem = dyn_cast<InsertElementInst>(V);
  5808. if (!LastInsertElem || !LastInsertElem->hasOneUse())
  5809. return false;
  5810. } while (true);
  5811. std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
  5812. return true;
  5813. }
  5814. /// Like findBuildVector, but looks for construction of aggregate.
  5815. ///
  5816. /// \return true if it matches.
  5817. static bool findBuildAggregate(InsertValueInst *IV,
  5818. SmallVectorImpl<Value *> &BuildVectorOpds) {
  5819. Value *V;
  5820. do {
  5821. BuildVectorOpds.push_back(IV->getInsertedValueOperand());
  5822. V = IV->getAggregateOperand();
  5823. if (isa<UndefValue>(V))
  5824. break;
  5825. IV = dyn_cast<InsertValueInst>(V);
  5826. if (!IV || !IV->hasOneUse())
  5827. return false;
  5828. } while (true);
  5829. std::reverse(BuildVectorOpds.begin(), BuildVectorOpds.end());
  5830. return true;
  5831. }
  5832. static bool PhiTypeSorterFunc(Value *V, Value *V2) {
  5833. return V->getType() < V2->getType();
  5834. }
  5835. /// Try and get a reduction value from a phi node.
  5836. ///
  5837. /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
  5838. /// if they come from either \p ParentBB or a containing loop latch.
  5839. ///
  5840. /// \returns A candidate reduction value if possible, or \code nullptr \endcode
  5841. /// if not possible.
  5842. static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
  5843. BasicBlock *ParentBB, LoopInfo *LI) {
  5844. // There are situations where the reduction value is not dominated by the
  5845. // reduction phi. Vectorizing such cases has been reported to cause
  5846. // miscompiles. See PR25787.
  5847. auto DominatedReduxValue = [&](Value *R) {
  5848. return isa<Instruction>(R) &&
  5849. DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
  5850. };
  5851. Value *Rdx = nullptr;
  5852. // Return the incoming value if it comes from the same BB as the phi node.
  5853. if (P->getIncomingBlock(0) == ParentBB) {
  5854. Rdx = P->getIncomingValue(0);
  5855. } else if (P->getIncomingBlock(1) == ParentBB) {
  5856. Rdx = P->getIncomingValue(1);
  5857. }
  5858. if (Rdx && DominatedReduxValue(Rdx))
  5859. return Rdx;
  5860. // Otherwise, check whether we have a loop latch to look at.
  5861. Loop *BBL = LI->getLoopFor(ParentBB);
  5862. if (!BBL)
  5863. return nullptr;
  5864. BasicBlock *BBLatch = BBL->getLoopLatch();
  5865. if (!BBLatch)
  5866. return nullptr;
  5867. // There is a loop latch, return the incoming value if it comes from
  5868. // that. This reduction pattern occasionally turns up.
  5869. if (P->getIncomingBlock(0) == BBLatch) {
  5870. Rdx = P->getIncomingValue(0);
  5871. } else if (P->getIncomingBlock(1) == BBLatch) {
  5872. Rdx = P->getIncomingValue(1);
  5873. }
  5874. if (Rdx && DominatedReduxValue(Rdx))
  5875. return Rdx;
  5876. return nullptr;
  5877. }
  5878. /// Attempt to reduce a horizontal reduction.
  5879. /// If it is legal to match a horizontal reduction feeding the phi node \a P
  5880. /// with reduction operators \a Root (or one of its operands) in a basic block
  5881. /// \a BB, then check if it can be done. If horizontal reduction is not found
  5882. /// and root instruction is a binary operation, vectorization of the operands is
  5883. /// attempted.
  5884. /// \returns true if a horizontal reduction was matched and reduced or operands
  5885. /// of one of the binary instruction were vectorized.
  5886. /// \returns false if a horizontal reduction was not matched (or not possible)
  5887. /// or no vectorization of any binary operation feeding \a Root instruction was
  5888. /// performed.
  5889. static bool tryToVectorizeHorReductionOrInstOperands(
  5890. PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
  5891. TargetTransformInfo *TTI,
  5892. const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
  5893. if (!ShouldVectorizeHor)
  5894. return false;
  5895. if (!Root)
  5896. return false;
  5897. if (Root->getParent() != BB || isa<PHINode>(Root))
  5898. return false;
  5899. // Start analysis starting from Root instruction. If horizontal reduction is
  5900. // found, try to vectorize it. If it is not a horizontal reduction or
  5901. // vectorization is not possible or not effective, and currently analyzed
  5902. // instruction is a binary operation, try to vectorize the operands, using
  5903. // pre-order DFS traversal order. If the operands were not vectorized, repeat
  5904. // the same procedure considering each operand as a possible root of the
  5905. // horizontal reduction.
  5906. // Interrupt the process if the Root instruction itself was vectorized or all
  5907. // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
  5908. SmallVector<std::pair<WeakTrackingVH, unsigned>, 8> Stack(1, {Root, 0});
  5909. SmallPtrSet<Value *, 8> VisitedInstrs;
  5910. bool Res = false;
  5911. while (!Stack.empty()) {
  5912. Value *V;
  5913. unsigned Level;
  5914. std::tie(V, Level) = Stack.pop_back_val();
  5915. if (!V)
  5916. continue;
  5917. auto *Inst = dyn_cast<Instruction>(V);
  5918. if (!Inst)
  5919. continue;
  5920. auto *BI = dyn_cast<BinaryOperator>(Inst);
  5921. auto *SI = dyn_cast<SelectInst>(Inst);
  5922. if (BI || SI) {
  5923. HorizontalReduction HorRdx;
  5924. if (HorRdx.matchAssociativeReduction(P, Inst)) {
  5925. if (HorRdx.tryToReduce(R, TTI)) {
  5926. Res = true;
  5927. // Set P to nullptr to avoid re-analysis of phi node in
  5928. // matchAssociativeReduction function unless this is the root node.
  5929. P = nullptr;
  5930. continue;
  5931. }
  5932. }
  5933. if (P && BI) {
  5934. Inst = dyn_cast<Instruction>(BI->getOperand(0));
  5935. if (Inst == P)
  5936. Inst = dyn_cast<Instruction>(BI->getOperand(1));
  5937. if (!Inst) {
  5938. // Set P to nullptr to avoid re-analysis of phi node in
  5939. // matchAssociativeReduction function unless this is the root node.
  5940. P = nullptr;
  5941. continue;
  5942. }
  5943. }
  5944. }
  5945. // Set P to nullptr to avoid re-analysis of phi node in
  5946. // matchAssociativeReduction function unless this is the root node.
  5947. P = nullptr;
  5948. if (Vectorize(Inst, R)) {
  5949. Res = true;
  5950. continue;
  5951. }
  5952. // Try to vectorize operands.
  5953. // Continue analysis for the instruction from the same basic block only to
  5954. // save compile time.
  5955. if (++Level < RecursionMaxDepth)
  5956. for (auto *Op : Inst->operand_values())
  5957. if (VisitedInstrs.insert(Op).second)
  5958. if (auto *I = dyn_cast<Instruction>(Op))
  5959. if (!isa<PHINode>(I) && I->getParent() == BB)
  5960. Stack.emplace_back(Op, Level);
  5961. }
  5962. return Res;
  5963. }
  5964. bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
  5965. BasicBlock *BB, BoUpSLP &R,
  5966. TargetTransformInfo *TTI) {
  5967. if (!V)
  5968. return false;
  5969. auto *I = dyn_cast<Instruction>(V);
  5970. if (!I)
  5971. return false;
  5972. if (!isa<BinaryOperator>(I))
  5973. P = nullptr;
  5974. // Try to match and vectorize a horizontal reduction.
  5975. auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
  5976. return tryToVectorize(I, R);
  5977. };
  5978. return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
  5979. ExtraVectorization);
  5980. }
  5981. bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
  5982. BasicBlock *BB, BoUpSLP &R) {
  5983. const DataLayout &DL = BB->getModule()->getDataLayout();
  5984. if (!R.canMapToVector(IVI->getType(), DL))
  5985. return false;
  5986. SmallVector<Value *, 16> BuildVectorOpds;
  5987. if (!findBuildAggregate(IVI, BuildVectorOpds))
  5988. return false;
  5989. LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
  5990. // Aggregate value is unlikely to be processed in vector register, we need to
  5991. // extract scalars into scalar registers, so NeedExtraction is set true.
  5992. return tryToVectorizeList(BuildVectorOpds, R);
  5993. }
  5994. bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
  5995. BasicBlock *BB, BoUpSLP &R) {
  5996. int UserCost;
  5997. SmallVector<Value *, 16> BuildVectorOpds;
  5998. if (!findBuildVector(IEI, TTI, BuildVectorOpds, UserCost) ||
  5999. (llvm::all_of(BuildVectorOpds,
  6000. [](Value *V) { return isa<ExtractElementInst>(V); }) &&
  6001. isShuffle(BuildVectorOpds)))
  6002. return false;
  6003. // Vectorize starting with the build vector operands ignoring the BuildVector
  6004. // instructions for the purpose of scheduling and user extraction.
  6005. return tryToVectorizeList(BuildVectorOpds, R, UserCost);
  6006. }
  6007. bool SLPVectorizerPass::vectorizeCmpInst(CmpInst *CI, BasicBlock *BB,
  6008. BoUpSLP &R) {
  6009. if (tryToVectorizePair(CI->getOperand(0), CI->getOperand(1), R))
  6010. return true;
  6011. bool OpsChanged = false;
  6012. for (int Idx = 0; Idx < 2; ++Idx) {
  6013. OpsChanged |=
  6014. vectorizeRootInstruction(nullptr, CI->getOperand(Idx), BB, R, TTI);
  6015. }
  6016. return OpsChanged;
  6017. }
  6018. bool SLPVectorizerPass::vectorizeSimpleInstructions(
  6019. SmallVectorImpl<WeakVH> &Instructions, BasicBlock *BB, BoUpSLP &R) {
  6020. bool OpsChanged = false;
  6021. for (auto &VH : reverse(Instructions)) {
  6022. auto *I = dyn_cast_or_null<Instruction>(VH);
  6023. if (!I)
  6024. continue;
  6025. if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
  6026. OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
  6027. else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
  6028. OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
  6029. else if (auto *CI = dyn_cast<CmpInst>(I))
  6030. OpsChanged |= vectorizeCmpInst(CI, BB, R);
  6031. }
  6032. Instructions.clear();
  6033. return OpsChanged;
  6034. }
  6035. bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
  6036. bool Changed = false;
  6037. SmallVector<Value *, 4> Incoming;
  6038. SmallPtrSet<Value *, 16> VisitedInstrs;
  6039. bool HaveVectorizedPhiNodes = true;
  6040. while (HaveVectorizedPhiNodes) {
  6041. HaveVectorizedPhiNodes = false;
  6042. // Collect the incoming values from the PHIs.
  6043. Incoming.clear();
  6044. for (Instruction &I : *BB) {
  6045. PHINode *P = dyn_cast<PHINode>(&I);
  6046. if (!P)
  6047. break;
  6048. if (!VisitedInstrs.count(P))
  6049. Incoming.push_back(P);
  6050. }
  6051. // Sort by type.
  6052. llvm::stable_sort(Incoming, PhiTypeSorterFunc);
  6053. // Try to vectorize elements base on their type.
  6054. for (SmallVector<Value *, 4>::iterator IncIt = Incoming.begin(),
  6055. E = Incoming.end();
  6056. IncIt != E;) {
  6057. // Look for the next elements with the same type.
  6058. SmallVector<Value *, 4>::iterator SameTypeIt = IncIt;
  6059. while (SameTypeIt != E &&
  6060. (*SameTypeIt)->getType() == (*IncIt)->getType()) {
  6061. VisitedInstrs.insert(*SameTypeIt);
  6062. ++SameTypeIt;
  6063. }
  6064. // Try to vectorize them.
  6065. unsigned NumElts = (SameTypeIt - IncIt);
  6066. LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at PHIs ("
  6067. << NumElts << ")\n");
  6068. // The order in which the phi nodes appear in the program does not matter.
  6069. // So allow tryToVectorizeList to reorder them if it is beneficial. This
  6070. // is done when there are exactly two elements since tryToVectorizeList
  6071. // asserts that there are only two values when AllowReorder is true.
  6072. bool AllowReorder = NumElts == 2;
  6073. if (NumElts > 1 && tryToVectorizeList(makeArrayRef(IncIt, NumElts), R,
  6074. /*UserCost=*/0, AllowReorder)) {
  6075. // Success start over because instructions might have been changed.
  6076. HaveVectorizedPhiNodes = true;
  6077. Changed = true;
  6078. break;
  6079. }
  6080. // Start over at the next instruction of a different type (or the end).
  6081. IncIt = SameTypeIt;
  6082. }
  6083. }
  6084. VisitedInstrs.clear();
  6085. SmallVector<WeakVH, 8> PostProcessInstructions;
  6086. SmallDenseSet<Instruction *, 4> KeyNodes;
  6087. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  6088. // We may go through BB multiple times so skip the one we have checked.
  6089. if (!VisitedInstrs.insert(&*it).second) {
  6090. if (it->use_empty() && KeyNodes.count(&*it) > 0 &&
  6091. vectorizeSimpleInstructions(PostProcessInstructions, BB, R)) {
  6092. // We would like to start over since some instructions are deleted
  6093. // and the iterator may become invalid value.
  6094. Changed = true;
  6095. it = BB->begin();
  6096. e = BB->end();
  6097. }
  6098. continue;
  6099. }
  6100. if (isa<DbgInfoIntrinsic>(it))
  6101. continue;
  6102. // Try to vectorize reductions that use PHINodes.
  6103. if (PHINode *P = dyn_cast<PHINode>(it)) {
  6104. // Check that the PHI is a reduction PHI.
  6105. if (P->getNumIncomingValues() != 2)
  6106. return Changed;
  6107. // Try to match and vectorize a horizontal reduction.
  6108. if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
  6109. TTI)) {
  6110. Changed = true;
  6111. it = BB->begin();
  6112. e = BB->end();
  6113. continue;
  6114. }
  6115. continue;
  6116. }
  6117. // Ran into an instruction without users, like terminator, or function call
  6118. // with ignored return value, store. Ignore unused instructions (basing on
  6119. // instruction type, except for CallInst and InvokeInst).
  6120. if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
  6121. isa<InvokeInst>(it))) {
  6122. KeyNodes.insert(&*it);
  6123. bool OpsChanged = false;
  6124. if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
  6125. for (auto *V : it->operand_values()) {
  6126. // Try to match and vectorize a horizontal reduction.
  6127. OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
  6128. }
  6129. }
  6130. // Start vectorization of post-process list of instructions from the
  6131. // top-tree instructions to try to vectorize as many instructions as
  6132. // possible.
  6133. OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R);
  6134. if (OpsChanged) {
  6135. // We would like to start over since some instructions are deleted
  6136. // and the iterator may become invalid value.
  6137. Changed = true;
  6138. it = BB->begin();
  6139. e = BB->end();
  6140. continue;
  6141. }
  6142. }
  6143. if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
  6144. isa<InsertValueInst>(it))
  6145. PostProcessInstructions.push_back(&*it);
  6146. }
  6147. return Changed;
  6148. }
  6149. bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
  6150. auto Changed = false;
  6151. for (auto &Entry : GEPs) {
  6152. // If the getelementptr list has fewer than two elements, there's nothing
  6153. // to do.
  6154. if (Entry.second.size() < 2)
  6155. continue;
  6156. LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
  6157. << Entry.second.size() << ".\n");
  6158. // We process the getelementptr list in chunks of 16 (like we do for
  6159. // stores) to minimize compile-time.
  6160. for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += 16) {
  6161. auto Len = std::min<unsigned>(BE - BI, 16);
  6162. auto GEPList = makeArrayRef(&Entry.second[BI], Len);
  6163. // Initialize a set a candidate getelementptrs. Note that we use a
  6164. // SetVector here to preserve program order. If the index computations
  6165. // are vectorizable and begin with loads, we want to minimize the chance
  6166. // of having to reorder them later.
  6167. SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
  6168. // Some of the candidates may have already been vectorized after we
  6169. // initially collected them. If so, the WeakTrackingVHs will have
  6170. // nullified the
  6171. // values, so remove them from the set of candidates.
  6172. Candidates.remove(nullptr);
  6173. // Remove from the set of candidates all pairs of getelementptrs with
  6174. // constant differences. Such getelementptrs are likely not good
  6175. // candidates for vectorization in a bottom-up phase since one can be
  6176. // computed from the other. We also ensure all candidate getelementptr
  6177. // indices are unique.
  6178. for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
  6179. auto *GEPI = cast<GetElementPtrInst>(GEPList[I]);
  6180. if (!Candidates.count(GEPI))
  6181. continue;
  6182. auto *SCEVI = SE->getSCEV(GEPList[I]);
  6183. for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
  6184. auto *GEPJ = cast<GetElementPtrInst>(GEPList[J]);
  6185. auto *SCEVJ = SE->getSCEV(GEPList[J]);
  6186. if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
  6187. Candidates.remove(GEPList[I]);
  6188. Candidates.remove(GEPList[J]);
  6189. } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
  6190. Candidates.remove(GEPList[J]);
  6191. }
  6192. }
  6193. }
  6194. // We break out of the above computation as soon as we know there are
  6195. // fewer than two candidates remaining.
  6196. if (Candidates.size() < 2)
  6197. continue;
  6198. // Add the single, non-constant index of each candidate to the bundle. We
  6199. // ensured the indices met these constraints when we originally collected
  6200. // the getelementptrs.
  6201. SmallVector<Value *, 16> Bundle(Candidates.size());
  6202. auto BundleIndex = 0u;
  6203. for (auto *V : Candidates) {
  6204. auto *GEP = cast<GetElementPtrInst>(V);
  6205. auto *GEPIdx = GEP->idx_begin()->get();
  6206. assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
  6207. Bundle[BundleIndex++] = GEPIdx;
  6208. }
  6209. // Try and vectorize the indices. We are currently only interested in
  6210. // gather-like cases of the form:
  6211. //
  6212. // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
  6213. //
  6214. // where the loads of "a", the loads of "b", and the subtractions can be
  6215. // performed in parallel. It's likely that detecting this pattern in a
  6216. // bottom-up phase will be simpler and less costly than building a
  6217. // full-blown top-down phase beginning at the consecutive loads.
  6218. Changed |= tryToVectorizeList(Bundle, R);
  6219. }
  6220. }
  6221. return Changed;
  6222. }
  6223. bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
  6224. bool Changed = false;
  6225. // Attempt to sort and vectorize each of the store-groups.
  6226. for (StoreListMap::iterator it = Stores.begin(), e = Stores.end(); it != e;
  6227. ++it) {
  6228. if (it->second.size() < 2)
  6229. continue;
  6230. LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
  6231. << it->second.size() << ".\n");
  6232. // Process the stores in chunks of 16.
  6233. // TODO: The limit of 16 inhibits greater vectorization factors.
  6234. // For example, AVX2 supports v32i8. Increasing this limit, however,
  6235. // may cause a significant compile-time increase.
  6236. for (unsigned CI = 0, CE = it->second.size(); CI < CE; CI += 16) {
  6237. unsigned Len = std::min<unsigned>(CE - CI, 16);
  6238. Changed |= vectorizeStores(makeArrayRef(&it->second[CI], Len), R);
  6239. }
  6240. }
  6241. return Changed;
  6242. }
  6243. char SLPVectorizer::ID = 0;
  6244. static const char lv_name[] = "SLP Vectorizer";
  6245. INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
  6246. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  6247. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  6248. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  6249. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  6250. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  6251. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  6252. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  6253. INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
  6254. Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }