SLPVectorizer.cpp 261 KB

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