SLPVectorizer.cpp 558 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972
  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/DenseMap.h"
  20. #include "llvm/ADT/DenseSet.h"
  21. #include "llvm/ADT/PostOrderIterator.h"
  22. #include "llvm/ADT/PriorityQueue.h"
  23. #include "llvm/ADT/STLExtras.h"
  24. #include "llvm/ADT/SetOperations.h"
  25. #include "llvm/ADT/SetVector.h"
  26. #include "llvm/ADT/SmallBitVector.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/ADT/SmallSet.h"
  29. #include "llvm/ADT/SmallString.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/ADT/iterator.h"
  32. #include "llvm/ADT/iterator_range.h"
  33. #include "llvm/Analysis/AliasAnalysis.h"
  34. #include "llvm/Analysis/AssumptionCache.h"
  35. #include "llvm/Analysis/CodeMetrics.h"
  36. #include "llvm/Analysis/DemandedBits.h"
  37. #include "llvm/Analysis/GlobalsModRef.h"
  38. #include "llvm/Analysis/IVDescriptors.h"
  39. #include "llvm/Analysis/LoopAccessAnalysis.h"
  40. #include "llvm/Analysis/LoopInfo.h"
  41. #include "llvm/Analysis/MemoryLocation.h"
  42. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  43. #include "llvm/Analysis/ScalarEvolution.h"
  44. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  45. #include "llvm/Analysis/TargetLibraryInfo.h"
  46. #include "llvm/Analysis/TargetTransformInfo.h"
  47. #include "llvm/Analysis/ValueTracking.h"
  48. #include "llvm/Analysis/VectorUtils.h"
  49. #include "llvm/IR/Attributes.h"
  50. #include "llvm/IR/BasicBlock.h"
  51. #include "llvm/IR/Constant.h"
  52. #include "llvm/IR/Constants.h"
  53. #include "llvm/IR/DataLayout.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/Operator.h"
  65. #include "llvm/IR/PatternMatch.h"
  66. #include "llvm/IR/Type.h"
  67. #include "llvm/IR/Use.h"
  68. #include "llvm/IR/User.h"
  69. #include "llvm/IR/Value.h"
  70. #include "llvm/IR/ValueHandle.h"
  71. #ifdef EXPENSIVE_CHECKS
  72. #include "llvm/IR/Verifier.h"
  73. #endif
  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/InstructionCost.h"
  83. #include "llvm/Support/KnownBits.h"
  84. #include "llvm/Support/MathExtras.h"
  85. #include "llvm/Support/raw_ostream.h"
  86. #include "llvm/Transforms/Utils/InjectTLIMappings.h"
  87. #include "llvm/Transforms/Utils/Local.h"
  88. #include "llvm/Transforms/Utils/LoopUtils.h"
  89. #include "llvm/Transforms/Vectorize.h"
  90. #include <algorithm>
  91. #include <cassert>
  92. #include <cstdint>
  93. #include <iterator>
  94. #include <memory>
  95. #include <optional>
  96. #include <set>
  97. #include <string>
  98. #include <tuple>
  99. #include <utility>
  100. #include <vector>
  101. using namespace llvm;
  102. using namespace llvm::PatternMatch;
  103. using namespace slpvectorizer;
  104. #define SV_NAME "slp-vectorizer"
  105. #define DEBUG_TYPE "SLP"
  106. STATISTIC(NumVectorInstructions, "Number of vector instructions generated");
  107. cl::opt<bool> RunSLPVectorization("vectorize-slp", cl::init(true), cl::Hidden,
  108. cl::desc("Run the SLP vectorization passes"));
  109. static cl::opt<int>
  110. SLPCostThreshold("slp-threshold", cl::init(0), cl::Hidden,
  111. cl::desc("Only vectorize if you gain more than this "
  112. "number "));
  113. static cl::opt<bool>
  114. ShouldVectorizeHor("slp-vectorize-hor", cl::init(true), cl::Hidden,
  115. cl::desc("Attempt to vectorize horizontal reductions"));
  116. static cl::opt<bool> ShouldStartVectorizeHorAtStore(
  117. "slp-vectorize-hor-store", cl::init(false), cl::Hidden,
  118. cl::desc(
  119. "Attempt to vectorize horizontal reductions feeding into a store"));
  120. static cl::opt<int>
  121. MaxVectorRegSizeOption("slp-max-reg-size", cl::init(128), cl::Hidden,
  122. cl::desc("Attempt to vectorize for this register size in bits"));
  123. static cl::opt<unsigned>
  124. MaxVFOption("slp-max-vf", cl::init(0), cl::Hidden,
  125. cl::desc("Maximum SLP vectorization factor (0=unlimited)"));
  126. static cl::opt<int>
  127. MaxStoreLookup("slp-max-store-lookup", cl::init(32), cl::Hidden,
  128. cl::desc("Maximum depth of the lookup for consecutive stores."));
  129. /// Limits the size of scheduling regions in a block.
  130. /// It avoid long compile times for _very_ large blocks where vector
  131. /// instructions are spread over a wide range.
  132. /// This limit is way higher than needed by real-world functions.
  133. static cl::opt<int>
  134. ScheduleRegionSizeBudget("slp-schedule-budget", cl::init(100000), cl::Hidden,
  135. cl::desc("Limit the size of the SLP scheduling region per block"));
  136. static cl::opt<int> MinVectorRegSizeOption(
  137. "slp-min-reg-size", cl::init(128), cl::Hidden,
  138. cl::desc("Attempt to vectorize for this register size in bits"));
  139. static cl::opt<unsigned> RecursionMaxDepth(
  140. "slp-recursion-max-depth", cl::init(12), cl::Hidden,
  141. cl::desc("Limit the recursion depth when building a vectorizable tree"));
  142. static cl::opt<unsigned> MinTreeSize(
  143. "slp-min-tree-size", cl::init(3), cl::Hidden,
  144. cl::desc("Only vectorize small trees if they are fully vectorizable"));
  145. // The maximum depth that the look-ahead score heuristic will explore.
  146. // The higher this value, the higher the compilation time overhead.
  147. static cl::opt<int> LookAheadMaxDepth(
  148. "slp-max-look-ahead-depth", cl::init(2), cl::Hidden,
  149. cl::desc("The maximum look-ahead depth for operand reordering scores"));
  150. // The maximum depth that the look-ahead score heuristic will explore
  151. // when it probing among candidates for vectorization tree roots.
  152. // The higher this value, the higher the compilation time overhead but unlike
  153. // similar limit for operands ordering this is less frequently used, hence
  154. // impact of higher value is less noticeable.
  155. static cl::opt<int> RootLookAheadMaxDepth(
  156. "slp-max-root-look-ahead-depth", cl::init(2), cl::Hidden,
  157. cl::desc("The maximum look-ahead depth for searching best rooting option"));
  158. static cl::opt<bool>
  159. ViewSLPTree("view-slp-tree", cl::Hidden,
  160. cl::desc("Display the SLP trees with Graphviz"));
  161. // Limit the number of alias checks. The limit is chosen so that
  162. // it has no negative effect on the llvm benchmarks.
  163. static const unsigned AliasedCheckLimit = 10;
  164. // Another limit for the alias checks: The maximum distance between load/store
  165. // instructions where alias checks are done.
  166. // This limit is useful for very large basic blocks.
  167. static const unsigned MaxMemDepDistance = 160;
  168. /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
  169. /// regions to be handled.
  170. static const int MinScheduleRegionSize = 16;
  171. /// Predicate for the element types that the SLP vectorizer supports.
  172. ///
  173. /// The most important thing to filter here are types which are invalid in LLVM
  174. /// vectors. We also filter target specific types which have absolutely no
  175. /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
  176. /// avoids spending time checking the cost model and realizing that they will
  177. /// be inevitably scalarized.
  178. static bool isValidElementType(Type *Ty) {
  179. return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
  180. !Ty->isPPC_FP128Ty();
  181. }
  182. /// \returns True if the value is a constant (but not globals/constant
  183. /// expressions).
  184. static bool isConstant(Value *V) {
  185. return isa<Constant>(V) && !isa<ConstantExpr, GlobalValue>(V);
  186. }
  187. /// Checks if \p V is one of vector-like instructions, i.e. undef,
  188. /// insertelement/extractelement with constant indices for fixed vector type or
  189. /// extractvalue instruction.
  190. static bool isVectorLikeInstWithConstOps(Value *V) {
  191. if (!isa<InsertElementInst, ExtractElementInst>(V) &&
  192. !isa<ExtractValueInst, UndefValue>(V))
  193. return false;
  194. auto *I = dyn_cast<Instruction>(V);
  195. if (!I || isa<ExtractValueInst>(I))
  196. return true;
  197. if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
  198. return false;
  199. if (isa<ExtractElementInst>(I))
  200. return isConstant(I->getOperand(1));
  201. assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
  202. return isConstant(I->getOperand(2));
  203. }
  204. /// \returns true if all of the instructions in \p VL are in the same block or
  205. /// false otherwise.
  206. static bool allSameBlock(ArrayRef<Value *> VL) {
  207. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  208. if (!I0)
  209. return false;
  210. if (all_of(VL, isVectorLikeInstWithConstOps))
  211. return true;
  212. BasicBlock *BB = I0->getParent();
  213. for (int I = 1, E = VL.size(); I < E; I++) {
  214. auto *II = dyn_cast<Instruction>(VL[I]);
  215. if (!II)
  216. return false;
  217. if (BB != II->getParent())
  218. return false;
  219. }
  220. return true;
  221. }
  222. /// \returns True if all of the values in \p VL are constants (but not
  223. /// globals/constant expressions).
  224. static bool allConstant(ArrayRef<Value *> VL) {
  225. // Constant expressions and globals can't be vectorized like normal integer/FP
  226. // constants.
  227. return all_of(VL, isConstant);
  228. }
  229. /// \returns True if all of the values in \p VL are identical or some of them
  230. /// are UndefValue.
  231. static bool isSplat(ArrayRef<Value *> VL) {
  232. Value *FirstNonUndef = nullptr;
  233. for (Value *V : VL) {
  234. if (isa<UndefValue>(V))
  235. continue;
  236. if (!FirstNonUndef) {
  237. FirstNonUndef = V;
  238. continue;
  239. }
  240. if (V != FirstNonUndef)
  241. return false;
  242. }
  243. return FirstNonUndef != nullptr;
  244. }
  245. /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
  246. static bool isCommutative(Instruction *I) {
  247. if (auto *Cmp = dyn_cast<CmpInst>(I))
  248. return Cmp->isCommutative();
  249. if (auto *BO = dyn_cast<BinaryOperator>(I))
  250. return BO->isCommutative();
  251. // TODO: This should check for generic Instruction::isCommutative(), but
  252. // we need to confirm that the caller code correctly handles Intrinsics
  253. // for example (does not have 2 operands).
  254. return false;
  255. }
  256. /// \returns inserting index of InsertElement or InsertValue instruction,
  257. /// using Offset as base offset for index.
  258. static std::optional<unsigned> getInsertIndex(const Value *InsertInst,
  259. unsigned Offset = 0) {
  260. int Index = Offset;
  261. if (const auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
  262. const auto *VT = dyn_cast<FixedVectorType>(IE->getType());
  263. if (!VT)
  264. return std::nullopt;
  265. const auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2));
  266. if (!CI)
  267. return std::nullopt;
  268. if (CI->getValue().uge(VT->getNumElements()))
  269. return std::nullopt;
  270. Index *= VT->getNumElements();
  271. Index += CI->getZExtValue();
  272. return Index;
  273. }
  274. const auto *IV = cast<InsertValueInst>(InsertInst);
  275. Type *CurrentType = IV->getType();
  276. for (unsigned I : IV->indices()) {
  277. if (const auto *ST = dyn_cast<StructType>(CurrentType)) {
  278. Index *= ST->getNumElements();
  279. CurrentType = ST->getElementType(I);
  280. } else if (const auto *AT = dyn_cast<ArrayType>(CurrentType)) {
  281. Index *= AT->getNumElements();
  282. CurrentType = AT->getElementType();
  283. } else {
  284. return std::nullopt;
  285. }
  286. Index += I;
  287. }
  288. return Index;
  289. }
  290. namespace {
  291. /// Specifies the way the mask should be analyzed for undefs/poisonous elements
  292. /// in the shuffle mask.
  293. enum class UseMask {
  294. FirstArg, ///< The mask is expected to be for permutation of 1-2 vectors,
  295. ///< check for the mask elements for the first argument (mask
  296. ///< indices are in range [0:VF)).
  297. SecondArg, ///< The mask is expected to be for permutation of 2 vectors, check
  298. ///< for the mask elements for the second argument (mask indices
  299. ///< are in range [VF:2*VF))
  300. UndefsAsMask ///< Consider undef mask elements (-1) as placeholders for
  301. ///< future shuffle elements and mark them as ones as being used
  302. ///< in future. Non-undef elements are considered as unused since
  303. ///< they're already marked as used in the mask.
  304. };
  305. } // namespace
  306. /// Prepares a use bitset for the given mask either for the first argument or
  307. /// for the second.
  308. static SmallBitVector buildUseMask(int VF, ArrayRef<int> Mask,
  309. UseMask MaskArg) {
  310. SmallBitVector UseMask(VF, true);
  311. for (auto P : enumerate(Mask)) {
  312. if (P.value() == UndefMaskElem) {
  313. if (MaskArg == UseMask::UndefsAsMask)
  314. UseMask.reset(P.index());
  315. continue;
  316. }
  317. if (MaskArg == UseMask::FirstArg && P.value() < VF)
  318. UseMask.reset(P.value());
  319. else if (MaskArg == UseMask::SecondArg && P.value() >= VF)
  320. UseMask.reset(P.value() - VF);
  321. }
  322. return UseMask;
  323. }
  324. /// Checks if the given value is actually an undefined constant vector.
  325. /// Also, if the \p UseMask is not empty, tries to check if the non-masked
  326. /// elements actually mask the insertelement buildvector, if any.
  327. template <bool IsPoisonOnly = false>
  328. static SmallBitVector isUndefVector(const Value *V,
  329. const SmallBitVector &UseMask = {}) {
  330. SmallBitVector Res(UseMask.empty() ? 1 : UseMask.size(), true);
  331. using T = std::conditional_t<IsPoisonOnly, PoisonValue, UndefValue>;
  332. if (isa<T>(V))
  333. return Res;
  334. auto *VecTy = dyn_cast<FixedVectorType>(V->getType());
  335. if (!VecTy)
  336. return Res.reset();
  337. auto *C = dyn_cast<Constant>(V);
  338. if (!C) {
  339. if (!UseMask.empty()) {
  340. const Value *Base = V;
  341. while (auto *II = dyn_cast<InsertElementInst>(Base)) {
  342. if (isa<T>(II->getOperand(1)))
  343. continue;
  344. Base = II->getOperand(0);
  345. std::optional<unsigned> Idx = getInsertIndex(II);
  346. if (!Idx)
  347. continue;
  348. if (*Idx < UseMask.size() && !UseMask.test(*Idx))
  349. Res.reset(*Idx);
  350. }
  351. // TODO: Add analysis for shuffles here too.
  352. if (V == Base) {
  353. Res.reset();
  354. } else {
  355. SmallBitVector SubMask(UseMask.size(), false);
  356. Res &= isUndefVector<IsPoisonOnly>(Base, SubMask);
  357. }
  358. } else {
  359. Res.reset();
  360. }
  361. return Res;
  362. }
  363. for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
  364. if (Constant *Elem = C->getAggregateElement(I))
  365. if (!isa<T>(Elem) &&
  366. (UseMask.empty() || (I < UseMask.size() && !UseMask.test(I))))
  367. Res.reset(I);
  368. }
  369. return Res;
  370. }
  371. /// Checks if the vector of instructions can be represented as a shuffle, like:
  372. /// %x0 = extractelement <4 x i8> %x, i32 0
  373. /// %x3 = extractelement <4 x i8> %x, i32 3
  374. /// %y1 = extractelement <4 x i8> %y, i32 1
  375. /// %y2 = extractelement <4 x i8> %y, i32 2
  376. /// %x0x0 = mul i8 %x0, %x0
  377. /// %x3x3 = mul i8 %x3, %x3
  378. /// %y1y1 = mul i8 %y1, %y1
  379. /// %y2y2 = mul i8 %y2, %y2
  380. /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
  381. /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
  382. /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
  383. /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
  384. /// ret <4 x i8> %ins4
  385. /// can be transformed into:
  386. /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
  387. /// i32 6>
  388. /// %2 = mul <4 x i8> %1, %1
  389. /// ret <4 x i8> %2
  390. /// We convert this initially to something like:
  391. /// %x0 = extractelement <4 x i8> %x, i32 0
  392. /// %x3 = extractelement <4 x i8> %x, i32 3
  393. /// %y1 = extractelement <4 x i8> %y, i32 1
  394. /// %y2 = extractelement <4 x i8> %y, i32 2
  395. /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
  396. /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
  397. /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
  398. /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
  399. /// %5 = mul <4 x i8> %4, %4
  400. /// %6 = extractelement <4 x i8> %5, i32 0
  401. /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
  402. /// %7 = extractelement <4 x i8> %5, i32 1
  403. /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
  404. /// %8 = extractelement <4 x i8> %5, i32 2
  405. /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
  406. /// %9 = extractelement <4 x i8> %5, i32 3
  407. /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
  408. /// ret <4 x i8> %ins4
  409. /// InstCombiner transforms this into a shuffle and vector mul
  410. /// Mask will return the Shuffle Mask equivalent to the extracted elements.
  411. /// TODO: Can we split off and reuse the shuffle mask detection from
  412. /// ShuffleVectorInst/getShuffleCost?
  413. static std::optional<TargetTransformInfo::ShuffleKind>
  414. isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
  415. const auto *It =
  416. find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
  417. if (It == VL.end())
  418. return std::nullopt;
  419. auto *EI0 = cast<ExtractElementInst>(*It);
  420. if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
  421. return std::nullopt;
  422. unsigned Size =
  423. cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
  424. Value *Vec1 = nullptr;
  425. Value *Vec2 = nullptr;
  426. enum ShuffleMode { Unknown, Select, Permute };
  427. ShuffleMode CommonShuffleMode = Unknown;
  428. Mask.assign(VL.size(), UndefMaskElem);
  429. for (unsigned I = 0, E = VL.size(); I < E; ++I) {
  430. // Undef can be represented as an undef element in a vector.
  431. if (isa<UndefValue>(VL[I]))
  432. continue;
  433. auto *EI = cast<ExtractElementInst>(VL[I]);
  434. if (isa<ScalableVectorType>(EI->getVectorOperandType()))
  435. return std::nullopt;
  436. auto *Vec = EI->getVectorOperand();
  437. // We can extractelement from undef or poison vector.
  438. if (isUndefVector(Vec).all())
  439. continue;
  440. // All vector operands must have the same number of vector elements.
  441. if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
  442. return std::nullopt;
  443. if (isa<UndefValue>(EI->getIndexOperand()))
  444. continue;
  445. auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
  446. if (!Idx)
  447. return std::nullopt;
  448. // Undefined behavior if Idx is negative or >= Size.
  449. if (Idx->getValue().uge(Size))
  450. continue;
  451. unsigned IntIdx = Idx->getValue().getZExtValue();
  452. Mask[I] = IntIdx;
  453. // For correct shuffling we have to have at most 2 different vector operands
  454. // in all extractelement instructions.
  455. if (!Vec1 || Vec1 == Vec) {
  456. Vec1 = Vec;
  457. } else if (!Vec2 || Vec2 == Vec) {
  458. Vec2 = Vec;
  459. Mask[I] += Size;
  460. } else {
  461. return std::nullopt;
  462. }
  463. if (CommonShuffleMode == Permute)
  464. continue;
  465. // If the extract index is not the same as the operation number, it is a
  466. // permutation.
  467. if (IntIdx != I) {
  468. CommonShuffleMode = Permute;
  469. continue;
  470. }
  471. CommonShuffleMode = Select;
  472. }
  473. // If we're not crossing lanes in different vectors, consider it as blending.
  474. if (CommonShuffleMode == Select && Vec2)
  475. return TargetTransformInfo::SK_Select;
  476. // If Vec2 was never used, we have a permutation of a single vector, otherwise
  477. // we have permutation of 2 vectors.
  478. return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
  479. : TargetTransformInfo::SK_PermuteSingleSrc;
  480. }
  481. /// \returns True if Extract{Value,Element} instruction extracts element Idx.
  482. static std::optional<unsigned> getExtractIndex(Instruction *E) {
  483. unsigned Opcode = E->getOpcode();
  484. assert((Opcode == Instruction::ExtractElement ||
  485. Opcode == Instruction::ExtractValue) &&
  486. "Expected extractelement or extractvalue instruction.");
  487. if (Opcode == Instruction::ExtractElement) {
  488. auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
  489. if (!CI)
  490. return std::nullopt;
  491. return CI->getZExtValue();
  492. }
  493. auto *EI = cast<ExtractValueInst>(E);
  494. if (EI->getNumIndices() != 1)
  495. return std::nullopt;
  496. return *EI->idx_begin();
  497. }
  498. namespace {
  499. /// Main data required for vectorization of instructions.
  500. struct InstructionsState {
  501. /// The very first instruction in the list with the main opcode.
  502. Value *OpValue = nullptr;
  503. /// The main/alternate instruction.
  504. Instruction *MainOp = nullptr;
  505. Instruction *AltOp = nullptr;
  506. /// The main/alternate opcodes for the list of instructions.
  507. unsigned getOpcode() const {
  508. return MainOp ? MainOp->getOpcode() : 0;
  509. }
  510. unsigned getAltOpcode() const {
  511. return AltOp ? AltOp->getOpcode() : 0;
  512. }
  513. /// Some of the instructions in the list have alternate opcodes.
  514. bool isAltShuffle() const { return AltOp != MainOp; }
  515. bool isOpcodeOrAlt(Instruction *I) const {
  516. unsigned CheckedOpcode = I->getOpcode();
  517. return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
  518. }
  519. InstructionsState() = delete;
  520. InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
  521. : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
  522. };
  523. } // end anonymous namespace
  524. /// Chooses the correct key for scheduling data. If \p Op has the same (or
  525. /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
  526. /// OpValue.
  527. static Value *isOneOf(const InstructionsState &S, Value *Op) {
  528. auto *I = dyn_cast<Instruction>(Op);
  529. if (I && S.isOpcodeOrAlt(I))
  530. return Op;
  531. return S.OpValue;
  532. }
  533. /// \returns true if \p Opcode is allowed as part of of the main/alternate
  534. /// instruction for SLP vectorization.
  535. ///
  536. /// Example of unsupported opcode is SDIV that can potentially cause UB if the
  537. /// "shuffled out" lane would result in division by zero.
  538. static bool isValidForAlternation(unsigned Opcode) {
  539. if (Instruction::isIntDivRem(Opcode))
  540. return false;
  541. return true;
  542. }
  543. static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
  544. const TargetLibraryInfo &TLI,
  545. unsigned BaseIndex = 0);
  546. /// Checks if the provided operands of 2 cmp instructions are compatible, i.e.
  547. /// compatible instructions or constants, or just some other regular values.
  548. static bool areCompatibleCmpOps(Value *BaseOp0, Value *BaseOp1, Value *Op0,
  549. Value *Op1, const TargetLibraryInfo &TLI) {
  550. return (isConstant(BaseOp0) && isConstant(Op0)) ||
  551. (isConstant(BaseOp1) && isConstant(Op1)) ||
  552. (!isa<Instruction>(BaseOp0) && !isa<Instruction>(Op0) &&
  553. !isa<Instruction>(BaseOp1) && !isa<Instruction>(Op1)) ||
  554. BaseOp0 == Op0 || BaseOp1 == Op1 ||
  555. getSameOpcode({BaseOp0, Op0}, TLI).getOpcode() ||
  556. getSameOpcode({BaseOp1, Op1}, TLI).getOpcode();
  557. }
  558. /// \returns true if a compare instruction \p CI has similar "look" and
  559. /// same predicate as \p BaseCI, "as is" or with its operands and predicate
  560. /// swapped, false otherwise.
  561. static bool isCmpSameOrSwapped(const CmpInst *BaseCI, const CmpInst *CI,
  562. const TargetLibraryInfo &TLI) {
  563. assert(BaseCI->getOperand(0)->getType() == CI->getOperand(0)->getType() &&
  564. "Assessing comparisons of different types?");
  565. CmpInst::Predicate BasePred = BaseCI->getPredicate();
  566. CmpInst::Predicate Pred = CI->getPredicate();
  567. CmpInst::Predicate SwappedPred = CmpInst::getSwappedPredicate(Pred);
  568. Value *BaseOp0 = BaseCI->getOperand(0);
  569. Value *BaseOp1 = BaseCI->getOperand(1);
  570. Value *Op0 = CI->getOperand(0);
  571. Value *Op1 = CI->getOperand(1);
  572. return (BasePred == Pred &&
  573. areCompatibleCmpOps(BaseOp0, BaseOp1, Op0, Op1, TLI)) ||
  574. (BasePred == SwappedPred &&
  575. areCompatibleCmpOps(BaseOp0, BaseOp1, Op1, Op0, TLI));
  576. }
  577. /// \returns analysis of the Instructions in \p VL described in
  578. /// InstructionsState, the Opcode that we suppose the whole list
  579. /// could be vectorized even if its structure is diverse.
  580. static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
  581. const TargetLibraryInfo &TLI,
  582. unsigned BaseIndex) {
  583. // Make sure these are all Instructions.
  584. if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
  585. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  586. bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
  587. bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
  588. bool IsCmpOp = isa<CmpInst>(VL[BaseIndex]);
  589. CmpInst::Predicate BasePred =
  590. IsCmpOp ? cast<CmpInst>(VL[BaseIndex])->getPredicate()
  591. : CmpInst::BAD_ICMP_PREDICATE;
  592. unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
  593. unsigned AltOpcode = Opcode;
  594. unsigned AltIndex = BaseIndex;
  595. // Check for one alternate opcode from another BinaryOperator.
  596. // TODO - generalize to support all operators (types, calls etc.).
  597. auto *IBase = cast<Instruction>(VL[BaseIndex]);
  598. Intrinsic::ID BaseID = 0;
  599. SmallVector<VFInfo> BaseMappings;
  600. if (auto *CallBase = dyn_cast<CallInst>(IBase)) {
  601. BaseID = getVectorIntrinsicIDForCall(CallBase, &TLI);
  602. BaseMappings = VFDatabase(*CallBase).getMappings(*CallBase);
  603. if (!isTriviallyVectorizable(BaseID) && BaseMappings.empty())
  604. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  605. }
  606. for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
  607. auto *I = cast<Instruction>(VL[Cnt]);
  608. unsigned InstOpcode = I->getOpcode();
  609. if (IsBinOp && isa<BinaryOperator>(I)) {
  610. if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  611. continue;
  612. if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
  613. isValidForAlternation(Opcode)) {
  614. AltOpcode = InstOpcode;
  615. AltIndex = Cnt;
  616. continue;
  617. }
  618. } else if (IsCastOp && isa<CastInst>(I)) {
  619. Value *Op0 = IBase->getOperand(0);
  620. Type *Ty0 = Op0->getType();
  621. Value *Op1 = I->getOperand(0);
  622. Type *Ty1 = Op1->getType();
  623. if (Ty0 == Ty1) {
  624. if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  625. continue;
  626. if (Opcode == AltOpcode) {
  627. assert(isValidForAlternation(Opcode) &&
  628. isValidForAlternation(InstOpcode) &&
  629. "Cast isn't safe for alternation, logic needs to be updated!");
  630. AltOpcode = InstOpcode;
  631. AltIndex = Cnt;
  632. continue;
  633. }
  634. }
  635. } else if (auto *Inst = dyn_cast<CmpInst>(VL[Cnt]); Inst && IsCmpOp) {
  636. auto *BaseInst = cast<CmpInst>(VL[BaseIndex]);
  637. Type *Ty0 = BaseInst->getOperand(0)->getType();
  638. Type *Ty1 = Inst->getOperand(0)->getType();
  639. if (Ty0 == Ty1) {
  640. assert(InstOpcode == Opcode && "Expected same CmpInst opcode.");
  641. // Check for compatible operands. If the corresponding operands are not
  642. // compatible - need to perform alternate vectorization.
  643. CmpInst::Predicate CurrentPred = Inst->getPredicate();
  644. CmpInst::Predicate SwappedCurrentPred =
  645. CmpInst::getSwappedPredicate(CurrentPred);
  646. if (E == 2 &&
  647. (BasePred == CurrentPred || BasePred == SwappedCurrentPred))
  648. continue;
  649. if (isCmpSameOrSwapped(BaseInst, Inst, TLI))
  650. continue;
  651. auto *AltInst = cast<CmpInst>(VL[AltIndex]);
  652. if (AltIndex != BaseIndex) {
  653. if (isCmpSameOrSwapped(AltInst, Inst, TLI))
  654. continue;
  655. } else if (BasePred != CurrentPred) {
  656. assert(
  657. isValidForAlternation(InstOpcode) &&
  658. "CmpInst isn't safe for alternation, logic needs to be updated!");
  659. AltIndex = Cnt;
  660. continue;
  661. }
  662. CmpInst::Predicate AltPred = AltInst->getPredicate();
  663. if (BasePred == CurrentPred || BasePred == SwappedCurrentPred ||
  664. AltPred == CurrentPred || AltPred == SwappedCurrentPred)
  665. continue;
  666. }
  667. } else if (InstOpcode == Opcode || InstOpcode == AltOpcode) {
  668. if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
  669. if (Gep->getNumOperands() != 2 ||
  670. Gep->getOperand(0)->getType() != IBase->getOperand(0)->getType())
  671. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  672. } else if (auto *EI = dyn_cast<ExtractElementInst>(I)) {
  673. if (!isVectorLikeInstWithConstOps(EI))
  674. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  675. } else if (auto *LI = dyn_cast<LoadInst>(I)) {
  676. auto *BaseLI = cast<LoadInst>(IBase);
  677. if (!LI->isSimple() || !BaseLI->isSimple())
  678. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  679. } else if (auto *Call = dyn_cast<CallInst>(I)) {
  680. auto *CallBase = cast<CallInst>(IBase);
  681. if (Call->getCalledFunction() != CallBase->getCalledFunction())
  682. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  683. if (Call->hasOperandBundles() &&
  684. !std::equal(Call->op_begin() + Call->getBundleOperandsStartIndex(),
  685. Call->op_begin() + Call->getBundleOperandsEndIndex(),
  686. CallBase->op_begin() +
  687. CallBase->getBundleOperandsStartIndex()))
  688. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  689. Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, &TLI);
  690. if (ID != BaseID)
  691. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  692. if (!ID) {
  693. SmallVector<VFInfo> Mappings = VFDatabase(*Call).getMappings(*Call);
  694. if (Mappings.size() != BaseMappings.size() ||
  695. Mappings.front().ISA != BaseMappings.front().ISA ||
  696. Mappings.front().ScalarName != BaseMappings.front().ScalarName ||
  697. Mappings.front().VectorName != BaseMappings.front().VectorName ||
  698. Mappings.front().Shape.VF != BaseMappings.front().Shape.VF ||
  699. Mappings.front().Shape.Parameters !=
  700. BaseMappings.front().Shape.Parameters)
  701. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  702. }
  703. }
  704. continue;
  705. }
  706. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  707. }
  708. return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
  709. cast<Instruction>(VL[AltIndex]));
  710. }
  711. /// \returns true if all of the values in \p VL have the same type or false
  712. /// otherwise.
  713. static bool allSameType(ArrayRef<Value *> VL) {
  714. Type *Ty = VL[0]->getType();
  715. for (int i = 1, e = VL.size(); i < e; i++)
  716. if (VL[i]->getType() != Ty)
  717. return false;
  718. return true;
  719. }
  720. /// \returns True if in-tree use also needs extract. This refers to
  721. /// possible scalar operand in vectorized instruction.
  722. static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
  723. TargetLibraryInfo *TLI) {
  724. unsigned Opcode = UserInst->getOpcode();
  725. switch (Opcode) {
  726. case Instruction::Load: {
  727. LoadInst *LI = cast<LoadInst>(UserInst);
  728. return (LI->getPointerOperand() == Scalar);
  729. }
  730. case Instruction::Store: {
  731. StoreInst *SI = cast<StoreInst>(UserInst);
  732. return (SI->getPointerOperand() == Scalar);
  733. }
  734. case Instruction::Call: {
  735. CallInst *CI = cast<CallInst>(UserInst);
  736. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  737. for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
  738. if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
  739. return (CI->getArgOperand(i) == Scalar);
  740. }
  741. [[fallthrough]];
  742. }
  743. default:
  744. return false;
  745. }
  746. }
  747. /// \returns the AA location that is being access by the instruction.
  748. static MemoryLocation getLocation(Instruction *I) {
  749. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  750. return MemoryLocation::get(SI);
  751. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  752. return MemoryLocation::get(LI);
  753. return MemoryLocation();
  754. }
  755. /// \returns True if the instruction is not a volatile or atomic load/store.
  756. static bool isSimple(Instruction *I) {
  757. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  758. return LI->isSimple();
  759. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  760. return SI->isSimple();
  761. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
  762. return !MI->isVolatile();
  763. return true;
  764. }
  765. /// Shuffles \p Mask in accordance with the given \p SubMask.
  766. static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
  767. if (SubMask.empty())
  768. return;
  769. if (Mask.empty()) {
  770. Mask.append(SubMask.begin(), SubMask.end());
  771. return;
  772. }
  773. SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
  774. int TermValue = std::min(Mask.size(), SubMask.size());
  775. for (int I = 0, E = SubMask.size(); I < E; ++I) {
  776. if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
  777. Mask[SubMask[I]] >= TermValue)
  778. continue;
  779. NewMask[I] = Mask[SubMask[I]];
  780. }
  781. Mask.swap(NewMask);
  782. }
  783. /// Order may have elements assigned special value (size) which is out of
  784. /// bounds. Such indices only appear on places which correspond to undef values
  785. /// (see canReuseExtract for details) and used in order to avoid undef values
  786. /// have effect on operands ordering.
  787. /// The first loop below simply finds all unused indices and then the next loop
  788. /// nest assigns these indices for undef values positions.
  789. /// As an example below Order has two undef positions and they have assigned
  790. /// values 3 and 7 respectively:
  791. /// before: 6 9 5 4 9 2 1 0
  792. /// after: 6 3 5 4 7 2 1 0
  793. static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
  794. const unsigned Sz = Order.size();
  795. SmallBitVector UnusedIndices(Sz, /*t=*/true);
  796. SmallBitVector MaskedIndices(Sz);
  797. for (unsigned I = 0; I < Sz; ++I) {
  798. if (Order[I] < Sz)
  799. UnusedIndices.reset(Order[I]);
  800. else
  801. MaskedIndices.set(I);
  802. }
  803. if (MaskedIndices.none())
  804. return;
  805. assert(UnusedIndices.count() == MaskedIndices.count() &&
  806. "Non-synced masked/available indices.");
  807. int Idx = UnusedIndices.find_first();
  808. int MIdx = MaskedIndices.find_first();
  809. while (MIdx >= 0) {
  810. assert(Idx >= 0 && "Indices must be synced.");
  811. Order[MIdx] = Idx;
  812. Idx = UnusedIndices.find_next(Idx);
  813. MIdx = MaskedIndices.find_next(MIdx);
  814. }
  815. }
  816. namespace llvm {
  817. static void inversePermutation(ArrayRef<unsigned> Indices,
  818. SmallVectorImpl<int> &Mask) {
  819. Mask.clear();
  820. const unsigned E = Indices.size();
  821. Mask.resize(E, UndefMaskElem);
  822. for (unsigned I = 0; I < E; ++I)
  823. Mask[Indices[I]] = I;
  824. }
  825. /// Reorders the list of scalars in accordance with the given \p Mask.
  826. static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
  827. ArrayRef<int> Mask) {
  828. assert(!Mask.empty() && "Expected non-empty mask.");
  829. SmallVector<Value *> Prev(Scalars.size(),
  830. UndefValue::get(Scalars.front()->getType()));
  831. Prev.swap(Scalars);
  832. for (unsigned I = 0, E = Prev.size(); I < E; ++I)
  833. if (Mask[I] != UndefMaskElem)
  834. Scalars[Mask[I]] = Prev[I];
  835. }
  836. /// Checks if the provided value does not require scheduling. It does not
  837. /// require scheduling if this is not an instruction or it is an instruction
  838. /// that does not read/write memory and all operands are either not instructions
  839. /// or phi nodes or instructions from different blocks.
  840. static bool areAllOperandsNonInsts(Value *V) {
  841. auto *I = dyn_cast<Instruction>(V);
  842. if (!I)
  843. return true;
  844. return !mayHaveNonDefUseDependency(*I) &&
  845. all_of(I->operands(), [I](Value *V) {
  846. auto *IO = dyn_cast<Instruction>(V);
  847. if (!IO)
  848. return true;
  849. return isa<PHINode>(IO) || IO->getParent() != I->getParent();
  850. });
  851. }
  852. /// Checks if the provided value does not require scheduling. It does not
  853. /// require scheduling if this is not an instruction or it is an instruction
  854. /// that does not read/write memory and all users are phi nodes or instructions
  855. /// from the different blocks.
  856. static bool isUsedOutsideBlock(Value *V) {
  857. auto *I = dyn_cast<Instruction>(V);
  858. if (!I)
  859. return true;
  860. // Limits the number of uses to save compile time.
  861. constexpr int UsesLimit = 8;
  862. return !I->mayReadOrWriteMemory() && !I->hasNUsesOrMore(UsesLimit) &&
  863. all_of(I->users(), [I](User *U) {
  864. auto *IU = dyn_cast<Instruction>(U);
  865. if (!IU)
  866. return true;
  867. return IU->getParent() != I->getParent() || isa<PHINode>(IU);
  868. });
  869. }
  870. /// Checks if the specified value does not require scheduling. It does not
  871. /// require scheduling if all operands and all users do not need to be scheduled
  872. /// in the current basic block.
  873. static bool doesNotNeedToBeScheduled(Value *V) {
  874. return areAllOperandsNonInsts(V) && isUsedOutsideBlock(V);
  875. }
  876. /// Checks if the specified array of instructions does not require scheduling.
  877. /// It is so if all either instructions have operands that do not require
  878. /// scheduling or their users do not require scheduling since they are phis or
  879. /// in other basic blocks.
  880. static bool doesNotNeedToSchedule(ArrayRef<Value *> VL) {
  881. return !VL.empty() &&
  882. (all_of(VL, isUsedOutsideBlock) || all_of(VL, areAllOperandsNonInsts));
  883. }
  884. namespace slpvectorizer {
  885. /// Bottom Up SLP Vectorizer.
  886. class BoUpSLP {
  887. struct TreeEntry;
  888. struct ScheduleData;
  889. class ShuffleInstructionBuilder;
  890. public:
  891. using ValueList = SmallVector<Value *, 8>;
  892. using InstrList = SmallVector<Instruction *, 16>;
  893. using ValueSet = SmallPtrSet<Value *, 16>;
  894. using StoreList = SmallVector<StoreInst *, 8>;
  895. using ExtraValueToDebugLocsMap =
  896. MapVector<Value *, SmallVector<Instruction *, 2>>;
  897. using OrdersType = SmallVector<unsigned, 4>;
  898. BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
  899. TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
  900. DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
  901. const DataLayout *DL, OptimizationRemarkEmitter *ORE)
  902. : BatchAA(*Aa), F(Func), SE(Se), TTI(Tti), TLI(TLi), LI(Li),
  903. DT(Dt), AC(AC), DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
  904. CodeMetrics::collectEphemeralValues(F, AC, EphValues);
  905. // Use the vector register size specified by the target unless overridden
  906. // by a command-line option.
  907. // TODO: It would be better to limit the vectorization factor based on
  908. // data type rather than just register size. For example, x86 AVX has
  909. // 256-bit registers, but it does not support integer operations
  910. // at that width (that requires AVX2).
  911. if (MaxVectorRegSizeOption.getNumOccurrences())
  912. MaxVecRegSize = MaxVectorRegSizeOption;
  913. else
  914. MaxVecRegSize =
  915. TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
  916. .getFixedValue();
  917. if (MinVectorRegSizeOption.getNumOccurrences())
  918. MinVecRegSize = MinVectorRegSizeOption;
  919. else
  920. MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
  921. }
  922. /// Vectorize the tree that starts with the elements in \p VL.
  923. /// Returns the vectorized root.
  924. Value *vectorizeTree();
  925. /// Vectorize the tree but with the list of externally used values \p
  926. /// ExternallyUsedValues. Values in this MapVector can be replaced but the
  927. /// generated extractvalue instructions.
  928. Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues,
  929. Instruction *ReductionRoot = nullptr);
  930. /// \returns the cost incurred by unwanted spills and fills, caused by
  931. /// holding live values over call sites.
  932. InstructionCost getSpillCost() const;
  933. /// \returns the vectorization cost of the subtree that starts at \p VL.
  934. /// A negative number means that this is profitable.
  935. InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = std::nullopt);
  936. /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
  937. /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
  938. void buildTree(ArrayRef<Value *> Roots,
  939. const SmallDenseSet<Value *> &UserIgnoreLst);
  940. /// Construct a vectorizable tree that starts at \p Roots.
  941. void buildTree(ArrayRef<Value *> Roots);
  942. /// Checks if the very first tree node is going to be vectorized.
  943. bool isVectorizedFirstNode() const {
  944. return !VectorizableTree.empty() &&
  945. VectorizableTree.front()->State == TreeEntry::Vectorize;
  946. }
  947. /// Returns the main instruction for the very first node.
  948. Instruction *getFirstNodeMainOp() const {
  949. assert(!VectorizableTree.empty() && "No tree to get the first node from");
  950. return VectorizableTree.front()->getMainOp();
  951. }
  952. /// Returns whether the root node has in-tree uses.
  953. bool doesRootHaveInTreeUses() const {
  954. return !VectorizableTree.empty() &&
  955. !VectorizableTree.front()->UserTreeIndices.empty();
  956. }
  957. /// Builds external uses of the vectorized scalars, i.e. the list of
  958. /// vectorized scalars to be extracted, their lanes and their scalar users. \p
  959. /// ExternallyUsedValues contains additional list of external uses to handle
  960. /// vectorization of reductions.
  961. void
  962. buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
  963. /// Clear the internal data structures that are created by 'buildTree'.
  964. void deleteTree() {
  965. VectorizableTree.clear();
  966. ScalarToTreeEntry.clear();
  967. MustGather.clear();
  968. EntryToLastInstruction.clear();
  969. ExternalUses.clear();
  970. for (auto &Iter : BlocksSchedules) {
  971. BlockScheduling *BS = Iter.second.get();
  972. BS->clear();
  973. }
  974. MinBWs.clear();
  975. InstrElementSize.clear();
  976. UserIgnoreList = nullptr;
  977. }
  978. unsigned getTreeSize() const { return VectorizableTree.size(); }
  979. /// Perform LICM and CSE on the newly generated gather sequences.
  980. void optimizeGatherSequence();
  981. /// Checks if the specified gather tree entry \p TE can be represented as a
  982. /// shuffled vector entry + (possibly) permutation with other gathers. It
  983. /// implements the checks only for possibly ordered scalars (Loads,
  984. /// ExtractElement, ExtractValue), which can be part of the graph.
  985. std::optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
  986. /// Sort loads into increasing pointers offsets to allow greater clustering.
  987. std::optional<OrdersType> findPartiallyOrderedLoads(const TreeEntry &TE);
  988. /// Gets reordering data for the given tree entry. If the entry is vectorized
  989. /// - just return ReorderIndices, otherwise check if the scalars can be
  990. /// reordered and return the most optimal order.
  991. /// \param TopToBottom If true, include the order of vectorized stores and
  992. /// insertelement nodes, otherwise skip them.
  993. std::optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
  994. /// Reorders the current graph to the most profitable order starting from the
  995. /// root node to the leaf nodes. The best order is chosen only from the nodes
  996. /// of the same size (vectorization factor). Smaller nodes are considered
  997. /// parts of subgraph with smaller VF and they are reordered independently. We
  998. /// can make it because we still need to extend smaller nodes to the wider VF
  999. /// and we can merge reordering shuffles with the widening shuffles.
  1000. void reorderTopToBottom();
  1001. /// Reorders the current graph to the most profitable order starting from
  1002. /// leaves to the root. It allows to rotate small subgraphs and reduce the
  1003. /// number of reshuffles if the leaf nodes use the same order. In this case we
  1004. /// can merge the orders and just shuffle user node instead of shuffling its
  1005. /// operands. Plus, even the leaf nodes have different orders, it allows to
  1006. /// sink reordering in the graph closer to the root node and merge it later
  1007. /// during analysis.
  1008. void reorderBottomToTop(bool IgnoreReorder = false);
  1009. /// \return The vector element size in bits to use when vectorizing the
  1010. /// expression tree ending at \p V. If V is a store, the size is the width of
  1011. /// the stored value. Otherwise, the size is the width of the largest loaded
  1012. /// value reaching V. This method is used by the vectorizer to calculate
  1013. /// vectorization factors.
  1014. unsigned getVectorElementSize(Value *V);
  1015. /// Compute the minimum type sizes required to represent the entries in a
  1016. /// vectorizable tree.
  1017. void computeMinimumValueSizes();
  1018. // \returns maximum vector register size as set by TTI or overridden by cl::opt.
  1019. unsigned getMaxVecRegSize() const {
  1020. return MaxVecRegSize;
  1021. }
  1022. // \returns minimum vector register size as set by cl::opt.
  1023. unsigned getMinVecRegSize() const {
  1024. return MinVecRegSize;
  1025. }
  1026. unsigned getMinVF(unsigned Sz) const {
  1027. return std::max(2U, getMinVecRegSize() / Sz);
  1028. }
  1029. unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
  1030. unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
  1031. MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
  1032. return MaxVF ? MaxVF : UINT_MAX;
  1033. }
  1034. /// Check if homogeneous aggregate is isomorphic to some VectorType.
  1035. /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
  1036. /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
  1037. /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
  1038. ///
  1039. /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
  1040. unsigned canMapToVector(Type *T, const DataLayout &DL) const;
  1041. /// \returns True if the VectorizableTree is both tiny and not fully
  1042. /// vectorizable. We do not vectorize such trees.
  1043. bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
  1044. /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
  1045. /// can be load combined in the backend. Load combining may not be allowed in
  1046. /// the IR optimizer, so we do not want to alter the pattern. For example,
  1047. /// partially transforming a scalar bswap() pattern into vector code is
  1048. /// effectively impossible for the backend to undo.
  1049. /// TODO: If load combining is allowed in the IR optimizer, this analysis
  1050. /// may not be necessary.
  1051. bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
  1052. /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
  1053. /// can be load combined in the backend. Load combining may not be allowed in
  1054. /// the IR optimizer, so we do not want to alter the pattern. For example,
  1055. /// partially transforming a scalar bswap() pattern into vector code is
  1056. /// effectively impossible for the backend to undo.
  1057. /// TODO: If load combining is allowed in the IR optimizer, this analysis
  1058. /// may not be necessary.
  1059. bool isLoadCombineCandidate() const;
  1060. OptimizationRemarkEmitter *getORE() { return ORE; }
  1061. /// This structure holds any data we need about the edges being traversed
  1062. /// during buildTree_rec(). We keep track of:
  1063. /// (i) the user TreeEntry index, and
  1064. /// (ii) the index of the edge.
  1065. struct EdgeInfo {
  1066. EdgeInfo() = default;
  1067. EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
  1068. : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
  1069. /// The user TreeEntry.
  1070. TreeEntry *UserTE = nullptr;
  1071. /// The operand index of the use.
  1072. unsigned EdgeIdx = UINT_MAX;
  1073. #ifndef NDEBUG
  1074. friend inline raw_ostream &operator<<(raw_ostream &OS,
  1075. const BoUpSLP::EdgeInfo &EI) {
  1076. EI.dump(OS);
  1077. return OS;
  1078. }
  1079. /// Debug print.
  1080. void dump(raw_ostream &OS) const {
  1081. OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
  1082. << " EdgeIdx:" << EdgeIdx << "}";
  1083. }
  1084. LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
  1085. #endif
  1086. };
  1087. /// A helper class used for scoring candidates for two consecutive lanes.
  1088. class LookAheadHeuristics {
  1089. const TargetLibraryInfo &TLI;
  1090. const DataLayout &DL;
  1091. ScalarEvolution &SE;
  1092. const BoUpSLP &R;
  1093. int NumLanes; // Total number of lanes (aka vectorization factor).
  1094. int MaxLevel; // The maximum recursion depth for accumulating score.
  1095. public:
  1096. LookAheadHeuristics(const TargetLibraryInfo &TLI, const DataLayout &DL,
  1097. ScalarEvolution &SE, const BoUpSLP &R, int NumLanes,
  1098. int MaxLevel)
  1099. : TLI(TLI), DL(DL), SE(SE), R(R), NumLanes(NumLanes),
  1100. MaxLevel(MaxLevel) {}
  1101. // The hard-coded scores listed here are not very important, though it shall
  1102. // be higher for better matches to improve the resulting cost. When
  1103. // computing the scores of matching one sub-tree with another, we are
  1104. // basically counting the number of values that are matching. So even if all
  1105. // scores are set to 1, we would still get a decent matching result.
  1106. // However, sometimes we have to break ties. For example we may have to
  1107. // choose between matching loads vs matching opcodes. This is what these
  1108. // scores are helping us with: they provide the order of preference. Also,
  1109. // this is important if the scalar is externally used or used in another
  1110. // tree entry node in the different lane.
  1111. /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
  1112. static const int ScoreConsecutiveLoads = 4;
  1113. /// The same load multiple times. This should have a better score than
  1114. /// `ScoreSplat` because it in x86 for a 2-lane vector we can represent it
  1115. /// with `movddup (%reg), xmm0` which has a throughput of 0.5 versus 0.5 for
  1116. /// a vector load and 1.0 for a broadcast.
  1117. static const int ScoreSplatLoads = 3;
  1118. /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
  1119. static const int ScoreReversedLoads = 3;
  1120. /// A load candidate for masked gather.
  1121. static const int ScoreMaskedGatherCandidate = 1;
  1122. /// ExtractElementInst from same vector and consecutive indexes.
  1123. static const int ScoreConsecutiveExtracts = 4;
  1124. /// ExtractElementInst from same vector and reversed indices.
  1125. static const int ScoreReversedExtracts = 3;
  1126. /// Constants.
  1127. static const int ScoreConstants = 2;
  1128. /// Instructions with the same opcode.
  1129. static const int ScoreSameOpcode = 2;
  1130. /// Instructions with alt opcodes (e.g, add + sub).
  1131. static const int ScoreAltOpcodes = 1;
  1132. /// Identical instructions (a.k.a. splat or broadcast).
  1133. static const int ScoreSplat = 1;
  1134. /// Matching with an undef is preferable to failing.
  1135. static const int ScoreUndef = 1;
  1136. /// Score for failing to find a decent match.
  1137. static const int ScoreFail = 0;
  1138. /// Score if all users are vectorized.
  1139. static const int ScoreAllUserVectorized = 1;
  1140. /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
  1141. /// \p U1 and \p U2 are the users of \p V1 and \p V2.
  1142. /// Also, checks if \p V1 and \p V2 are compatible with instructions in \p
  1143. /// MainAltOps.
  1144. int getShallowScore(Value *V1, Value *V2, Instruction *U1, Instruction *U2,
  1145. ArrayRef<Value *> MainAltOps) const {
  1146. if (!isValidElementType(V1->getType()) ||
  1147. !isValidElementType(V2->getType()))
  1148. return LookAheadHeuristics::ScoreFail;
  1149. if (V1 == V2) {
  1150. if (isa<LoadInst>(V1)) {
  1151. // Retruns true if the users of V1 and V2 won't need to be extracted.
  1152. auto AllUsersAreInternal = [U1, U2, this](Value *V1, Value *V2) {
  1153. // Bail out if we have too many uses to save compilation time.
  1154. static constexpr unsigned Limit = 8;
  1155. if (V1->hasNUsesOrMore(Limit) || V2->hasNUsesOrMore(Limit))
  1156. return false;
  1157. auto AllUsersVectorized = [U1, U2, this](Value *V) {
  1158. return llvm::all_of(V->users(), [U1, U2, this](Value *U) {
  1159. return U == U1 || U == U2 || R.getTreeEntry(U) != nullptr;
  1160. });
  1161. };
  1162. return AllUsersVectorized(V1) && AllUsersVectorized(V2);
  1163. };
  1164. // A broadcast of a load can be cheaper on some targets.
  1165. if (R.TTI->isLegalBroadcastLoad(V1->getType(),
  1166. ElementCount::getFixed(NumLanes)) &&
  1167. ((int)V1->getNumUses() == NumLanes ||
  1168. AllUsersAreInternal(V1, V2)))
  1169. return LookAheadHeuristics::ScoreSplatLoads;
  1170. }
  1171. return LookAheadHeuristics::ScoreSplat;
  1172. }
  1173. auto *LI1 = dyn_cast<LoadInst>(V1);
  1174. auto *LI2 = dyn_cast<LoadInst>(V2);
  1175. if (LI1 && LI2) {
  1176. if (LI1->getParent() != LI2->getParent() || !LI1->isSimple() ||
  1177. !LI2->isSimple())
  1178. return LookAheadHeuristics::ScoreFail;
  1179. std::optional<int> Dist = getPointersDiff(
  1180. LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
  1181. LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
  1182. if (!Dist || *Dist == 0) {
  1183. if (getUnderlyingObject(LI1->getPointerOperand()) ==
  1184. getUnderlyingObject(LI2->getPointerOperand()) &&
  1185. R.TTI->isLegalMaskedGather(
  1186. FixedVectorType::get(LI1->getType(), NumLanes),
  1187. LI1->getAlign()))
  1188. return LookAheadHeuristics::ScoreMaskedGatherCandidate;
  1189. return LookAheadHeuristics::ScoreFail;
  1190. }
  1191. // The distance is too large - still may be profitable to use masked
  1192. // loads/gathers.
  1193. if (std::abs(*Dist) > NumLanes / 2)
  1194. return LookAheadHeuristics::ScoreMaskedGatherCandidate;
  1195. // This still will detect consecutive loads, but we might have "holes"
  1196. // in some cases. It is ok for non-power-2 vectorization and may produce
  1197. // better results. It should not affect current vectorization.
  1198. return (*Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveLoads
  1199. : LookAheadHeuristics::ScoreReversedLoads;
  1200. }
  1201. auto *C1 = dyn_cast<Constant>(V1);
  1202. auto *C2 = dyn_cast<Constant>(V2);
  1203. if (C1 && C2)
  1204. return LookAheadHeuristics::ScoreConstants;
  1205. // Extracts from consecutive indexes of the same vector better score as
  1206. // the extracts could be optimized away.
  1207. Value *EV1;
  1208. ConstantInt *Ex1Idx;
  1209. if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
  1210. // Undefs are always profitable for extractelements.
  1211. if (isa<UndefValue>(V2))
  1212. return LookAheadHeuristics::ScoreConsecutiveExtracts;
  1213. Value *EV2 = nullptr;
  1214. ConstantInt *Ex2Idx = nullptr;
  1215. if (match(V2,
  1216. m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
  1217. m_Undef())))) {
  1218. // Undefs are always profitable for extractelements.
  1219. if (!Ex2Idx)
  1220. return LookAheadHeuristics::ScoreConsecutiveExtracts;
  1221. if (isUndefVector(EV2).all() && EV2->getType() == EV1->getType())
  1222. return LookAheadHeuristics::ScoreConsecutiveExtracts;
  1223. if (EV2 == EV1) {
  1224. int Idx1 = Ex1Idx->getZExtValue();
  1225. int Idx2 = Ex2Idx->getZExtValue();
  1226. int Dist = Idx2 - Idx1;
  1227. // The distance is too large - still may be profitable to use
  1228. // shuffles.
  1229. if (std::abs(Dist) == 0)
  1230. return LookAheadHeuristics::ScoreSplat;
  1231. if (std::abs(Dist) > NumLanes / 2)
  1232. return LookAheadHeuristics::ScoreSameOpcode;
  1233. return (Dist > 0) ? LookAheadHeuristics::ScoreConsecutiveExtracts
  1234. : LookAheadHeuristics::ScoreReversedExtracts;
  1235. }
  1236. return LookAheadHeuristics::ScoreAltOpcodes;
  1237. }
  1238. return LookAheadHeuristics::ScoreFail;
  1239. }
  1240. auto *I1 = dyn_cast<Instruction>(V1);
  1241. auto *I2 = dyn_cast<Instruction>(V2);
  1242. if (I1 && I2) {
  1243. if (I1->getParent() != I2->getParent())
  1244. return LookAheadHeuristics::ScoreFail;
  1245. SmallVector<Value *, 4> Ops(MainAltOps.begin(), MainAltOps.end());
  1246. Ops.push_back(I1);
  1247. Ops.push_back(I2);
  1248. InstructionsState S = getSameOpcode(Ops, TLI);
  1249. // Note: Only consider instructions with <= 2 operands to avoid
  1250. // complexity explosion.
  1251. if (S.getOpcode() &&
  1252. (S.MainOp->getNumOperands() <= 2 || !MainAltOps.empty() ||
  1253. !S.isAltShuffle()) &&
  1254. all_of(Ops, [&S](Value *V) {
  1255. return cast<Instruction>(V)->getNumOperands() ==
  1256. S.MainOp->getNumOperands();
  1257. }))
  1258. return S.isAltShuffle() ? LookAheadHeuristics::ScoreAltOpcodes
  1259. : LookAheadHeuristics::ScoreSameOpcode;
  1260. }
  1261. if (isa<UndefValue>(V2))
  1262. return LookAheadHeuristics::ScoreUndef;
  1263. return LookAheadHeuristics::ScoreFail;
  1264. }
  1265. /// Go through the operands of \p LHS and \p RHS recursively until
  1266. /// MaxLevel, and return the cummulative score. \p U1 and \p U2 are
  1267. /// the users of \p LHS and \p RHS (that is \p LHS and \p RHS are operands
  1268. /// of \p U1 and \p U2), except at the beginning of the recursion where
  1269. /// these are set to nullptr.
  1270. ///
  1271. /// For example:
  1272. /// \verbatim
  1273. /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1]
  1274. /// \ / \ / \ / \ /
  1275. /// + + + +
  1276. /// G1 G2 G3 G4
  1277. /// \endverbatim
  1278. /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
  1279. /// each level recursively, accumulating the score. It starts from matching
  1280. /// the additions at level 0, then moves on to the loads (level 1). The
  1281. /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
  1282. /// {B[0],B[1]} match with LookAheadHeuristics::ScoreConsecutiveLoads, while
  1283. /// {A[0],C[0]} has a score of LookAheadHeuristics::ScoreFail.
  1284. /// Please note that the order of the operands does not matter, as we
  1285. /// evaluate the score of all profitable combinations of operands. In
  1286. /// other words the score of G1 and G4 is the same as G1 and G2. This
  1287. /// heuristic is based on ideas described in:
  1288. /// Look-ahead SLP: Auto-vectorization in the presence of commutative
  1289. /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
  1290. /// Luís F. W. Góes
  1291. int getScoreAtLevelRec(Value *LHS, Value *RHS, Instruction *U1,
  1292. Instruction *U2, int CurrLevel,
  1293. ArrayRef<Value *> MainAltOps) const {
  1294. // Get the shallow score of V1 and V2.
  1295. int ShallowScoreAtThisLevel =
  1296. getShallowScore(LHS, RHS, U1, U2, MainAltOps);
  1297. // If reached MaxLevel,
  1298. // or if V1 and V2 are not instructions,
  1299. // or if they are SPLAT,
  1300. // or if they are not consecutive,
  1301. // or if profitable to vectorize loads or extractelements, early return
  1302. // the current cost.
  1303. auto *I1 = dyn_cast<Instruction>(LHS);
  1304. auto *I2 = dyn_cast<Instruction>(RHS);
  1305. if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
  1306. ShallowScoreAtThisLevel == LookAheadHeuristics::ScoreFail ||
  1307. (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
  1308. (I1->getNumOperands() > 2 && I2->getNumOperands() > 2) ||
  1309. (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
  1310. ShallowScoreAtThisLevel))
  1311. return ShallowScoreAtThisLevel;
  1312. assert(I1 && I2 && "Should have early exited.");
  1313. // Contains the I2 operand indexes that got matched with I1 operands.
  1314. SmallSet<unsigned, 4> Op2Used;
  1315. // Recursion towards the operands of I1 and I2. We are trying all possible
  1316. // operand pairs, and keeping track of the best score.
  1317. for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
  1318. OpIdx1 != NumOperands1; ++OpIdx1) {
  1319. // Try to pair op1I with the best operand of I2.
  1320. int MaxTmpScore = 0;
  1321. unsigned MaxOpIdx2 = 0;
  1322. bool FoundBest = false;
  1323. // If I2 is commutative try all combinations.
  1324. unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
  1325. unsigned ToIdx = isCommutative(I2)
  1326. ? I2->getNumOperands()
  1327. : std::min(I2->getNumOperands(), OpIdx1 + 1);
  1328. assert(FromIdx <= ToIdx && "Bad index");
  1329. for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
  1330. // Skip operands already paired with OpIdx1.
  1331. if (Op2Used.count(OpIdx2))
  1332. continue;
  1333. // Recursively calculate the cost at each level
  1334. int TmpScore =
  1335. getScoreAtLevelRec(I1->getOperand(OpIdx1), I2->getOperand(OpIdx2),
  1336. I1, I2, CurrLevel + 1, std::nullopt);
  1337. // Look for the best score.
  1338. if (TmpScore > LookAheadHeuristics::ScoreFail &&
  1339. TmpScore > MaxTmpScore) {
  1340. MaxTmpScore = TmpScore;
  1341. MaxOpIdx2 = OpIdx2;
  1342. FoundBest = true;
  1343. }
  1344. }
  1345. if (FoundBest) {
  1346. // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
  1347. Op2Used.insert(MaxOpIdx2);
  1348. ShallowScoreAtThisLevel += MaxTmpScore;
  1349. }
  1350. }
  1351. return ShallowScoreAtThisLevel;
  1352. }
  1353. };
  1354. /// A helper data structure to hold the operands of a vector of instructions.
  1355. /// This supports a fixed vector length for all operand vectors.
  1356. class VLOperands {
  1357. /// For each operand we need (i) the value, and (ii) the opcode that it
  1358. /// would be attached to if the expression was in a left-linearized form.
  1359. /// This is required to avoid illegal operand reordering.
  1360. /// For example:
  1361. /// \verbatim
  1362. /// 0 Op1
  1363. /// |/
  1364. /// Op1 Op2 Linearized + Op2
  1365. /// \ / ----------> |/
  1366. /// - -
  1367. ///
  1368. /// Op1 - Op2 (0 + Op1) - Op2
  1369. /// \endverbatim
  1370. ///
  1371. /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
  1372. ///
  1373. /// Another way to think of this is to track all the operations across the
  1374. /// path from the operand all the way to the root of the tree and to
  1375. /// calculate the operation that corresponds to this path. For example, the
  1376. /// path from Op2 to the root crosses the RHS of the '-', therefore the
  1377. /// corresponding operation is a '-' (which matches the one in the
  1378. /// linearized tree, as shown above).
  1379. ///
  1380. /// For lack of a better term, we refer to this operation as Accumulated
  1381. /// Path Operation (APO).
  1382. struct OperandData {
  1383. OperandData() = default;
  1384. OperandData(Value *V, bool APO, bool IsUsed)
  1385. : V(V), APO(APO), IsUsed(IsUsed) {}
  1386. /// The operand value.
  1387. Value *V = nullptr;
  1388. /// TreeEntries only allow a single opcode, or an alternate sequence of
  1389. /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
  1390. /// APO. It is set to 'true' if 'V' is attached to an inverse operation
  1391. /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
  1392. /// (e.g., Add/Mul)
  1393. bool APO = false;
  1394. /// Helper data for the reordering function.
  1395. bool IsUsed = false;
  1396. };
  1397. /// During operand reordering, we are trying to select the operand at lane
  1398. /// that matches best with the operand at the neighboring lane. Our
  1399. /// selection is based on the type of value we are looking for. For example,
  1400. /// if the neighboring lane has a load, we need to look for a load that is
  1401. /// accessing a consecutive address. These strategies are summarized in the
  1402. /// 'ReorderingMode' enumerator.
  1403. enum class ReorderingMode {
  1404. Load, ///< Matching loads to consecutive memory addresses
  1405. Opcode, ///< Matching instructions based on opcode (same or alternate)
  1406. Constant, ///< Matching constants
  1407. Splat, ///< Matching the same instruction multiple times (broadcast)
  1408. Failed, ///< We failed to create a vectorizable group
  1409. };
  1410. using OperandDataVec = SmallVector<OperandData, 2>;
  1411. /// A vector of operand vectors.
  1412. SmallVector<OperandDataVec, 4> OpsVec;
  1413. const TargetLibraryInfo &TLI;
  1414. const DataLayout &DL;
  1415. ScalarEvolution &SE;
  1416. const BoUpSLP &R;
  1417. /// \returns the operand data at \p OpIdx and \p Lane.
  1418. OperandData &getData(unsigned OpIdx, unsigned Lane) {
  1419. return OpsVec[OpIdx][Lane];
  1420. }
  1421. /// \returns the operand data at \p OpIdx and \p Lane. Const version.
  1422. const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
  1423. return OpsVec[OpIdx][Lane];
  1424. }
  1425. /// Clears the used flag for all entries.
  1426. void clearUsed() {
  1427. for (unsigned OpIdx = 0, NumOperands = getNumOperands();
  1428. OpIdx != NumOperands; ++OpIdx)
  1429. for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
  1430. ++Lane)
  1431. OpsVec[OpIdx][Lane].IsUsed = false;
  1432. }
  1433. /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
  1434. void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
  1435. std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
  1436. }
  1437. /// \param Lane lane of the operands under analysis.
  1438. /// \param OpIdx operand index in \p Lane lane we're looking the best
  1439. /// candidate for.
  1440. /// \param Idx operand index of the current candidate value.
  1441. /// \returns The additional score due to possible broadcasting of the
  1442. /// elements in the lane. It is more profitable to have power-of-2 unique
  1443. /// elements in the lane, it will be vectorized with higher probability
  1444. /// after removing duplicates. Currently the SLP vectorizer supports only
  1445. /// vectorization of the power-of-2 number of unique scalars.
  1446. int getSplatScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
  1447. Value *IdxLaneV = getData(Idx, Lane).V;
  1448. if (!isa<Instruction>(IdxLaneV) || IdxLaneV == getData(OpIdx, Lane).V)
  1449. return 0;
  1450. SmallPtrSet<Value *, 4> Uniques;
  1451. for (unsigned Ln = 0, E = getNumLanes(); Ln < E; ++Ln) {
  1452. if (Ln == Lane)
  1453. continue;
  1454. Value *OpIdxLnV = getData(OpIdx, Ln).V;
  1455. if (!isa<Instruction>(OpIdxLnV))
  1456. return 0;
  1457. Uniques.insert(OpIdxLnV);
  1458. }
  1459. int UniquesCount = Uniques.size();
  1460. int UniquesCntWithIdxLaneV =
  1461. Uniques.contains(IdxLaneV) ? UniquesCount : UniquesCount + 1;
  1462. Value *OpIdxLaneV = getData(OpIdx, Lane).V;
  1463. int UniquesCntWithOpIdxLaneV =
  1464. Uniques.contains(OpIdxLaneV) ? UniquesCount : UniquesCount + 1;
  1465. if (UniquesCntWithIdxLaneV == UniquesCntWithOpIdxLaneV)
  1466. return 0;
  1467. return (PowerOf2Ceil(UniquesCntWithOpIdxLaneV) -
  1468. UniquesCntWithOpIdxLaneV) -
  1469. (PowerOf2Ceil(UniquesCntWithIdxLaneV) - UniquesCntWithIdxLaneV);
  1470. }
  1471. /// \param Lane lane of the operands under analysis.
  1472. /// \param OpIdx operand index in \p Lane lane we're looking the best
  1473. /// candidate for.
  1474. /// \param Idx operand index of the current candidate value.
  1475. /// \returns The additional score for the scalar which users are all
  1476. /// vectorized.
  1477. int getExternalUseScore(unsigned Lane, unsigned OpIdx, unsigned Idx) const {
  1478. Value *IdxLaneV = getData(Idx, Lane).V;
  1479. Value *OpIdxLaneV = getData(OpIdx, Lane).V;
  1480. // Do not care about number of uses for vector-like instructions
  1481. // (extractelement/extractvalue with constant indices), they are extracts
  1482. // themselves and already externally used. Vectorization of such
  1483. // instructions does not add extra extractelement instruction, just may
  1484. // remove it.
  1485. if (isVectorLikeInstWithConstOps(IdxLaneV) &&
  1486. isVectorLikeInstWithConstOps(OpIdxLaneV))
  1487. return LookAheadHeuristics::ScoreAllUserVectorized;
  1488. auto *IdxLaneI = dyn_cast<Instruction>(IdxLaneV);
  1489. if (!IdxLaneI || !isa<Instruction>(OpIdxLaneV))
  1490. return 0;
  1491. return R.areAllUsersVectorized(IdxLaneI, std::nullopt)
  1492. ? LookAheadHeuristics::ScoreAllUserVectorized
  1493. : 0;
  1494. }
  1495. /// Score scaling factor for fully compatible instructions but with
  1496. /// different number of external uses. Allows better selection of the
  1497. /// instructions with less external uses.
  1498. static const int ScoreScaleFactor = 10;
  1499. /// \Returns the look-ahead score, which tells us how much the sub-trees
  1500. /// rooted at \p LHS and \p RHS match, the more they match the higher the
  1501. /// score. This helps break ties in an informed way when we cannot decide on
  1502. /// the order of the operands by just considering the immediate
  1503. /// predecessors.
  1504. int getLookAheadScore(Value *LHS, Value *RHS, ArrayRef<Value *> MainAltOps,
  1505. int Lane, unsigned OpIdx, unsigned Idx,
  1506. bool &IsUsed) {
  1507. LookAheadHeuristics LookAhead(TLI, DL, SE, R, getNumLanes(),
  1508. LookAheadMaxDepth);
  1509. // Keep track of the instruction stack as we recurse into the operands
  1510. // during the look-ahead score exploration.
  1511. int Score =
  1512. LookAhead.getScoreAtLevelRec(LHS, RHS, /*U1=*/nullptr, /*U2=*/nullptr,
  1513. /*CurrLevel=*/1, MainAltOps);
  1514. if (Score) {
  1515. int SplatScore = getSplatScore(Lane, OpIdx, Idx);
  1516. if (Score <= -SplatScore) {
  1517. // Set the minimum score for splat-like sequence to avoid setting
  1518. // failed state.
  1519. Score = 1;
  1520. } else {
  1521. Score += SplatScore;
  1522. // Scale score to see the difference between different operands
  1523. // and similar operands but all vectorized/not all vectorized
  1524. // uses. It does not affect actual selection of the best
  1525. // compatible operand in general, just allows to select the
  1526. // operand with all vectorized uses.
  1527. Score *= ScoreScaleFactor;
  1528. Score += getExternalUseScore(Lane, OpIdx, Idx);
  1529. IsUsed = true;
  1530. }
  1531. }
  1532. return Score;
  1533. }
  1534. /// Best defined scores per lanes between the passes. Used to choose the
  1535. /// best operand (with the highest score) between the passes.
  1536. /// The key - {Operand Index, Lane}.
  1537. /// The value - the best score between the passes for the lane and the
  1538. /// operand.
  1539. SmallDenseMap<std::pair<unsigned, unsigned>, unsigned, 8>
  1540. BestScoresPerLanes;
  1541. // Search all operands in Ops[*][Lane] for the one that matches best
  1542. // Ops[OpIdx][LastLane] and return its opreand index.
  1543. // If no good match can be found, return std::nullopt.
  1544. std::optional<unsigned> getBestOperand(unsigned OpIdx, int Lane, int LastLane,
  1545. ArrayRef<ReorderingMode> ReorderingModes,
  1546. ArrayRef<Value *> MainAltOps) {
  1547. unsigned NumOperands = getNumOperands();
  1548. // The operand of the previous lane at OpIdx.
  1549. Value *OpLastLane = getData(OpIdx, LastLane).V;
  1550. // Our strategy mode for OpIdx.
  1551. ReorderingMode RMode = ReorderingModes[OpIdx];
  1552. if (RMode == ReorderingMode::Failed)
  1553. return std::nullopt;
  1554. // The linearized opcode of the operand at OpIdx, Lane.
  1555. bool OpIdxAPO = getData(OpIdx, Lane).APO;
  1556. // The best operand index and its score.
  1557. // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
  1558. // are using the score to differentiate between the two.
  1559. struct BestOpData {
  1560. std::optional<unsigned> Idx;
  1561. unsigned Score = 0;
  1562. } BestOp;
  1563. BestOp.Score =
  1564. BestScoresPerLanes.try_emplace(std::make_pair(OpIdx, Lane), 0)
  1565. .first->second;
  1566. // Track if the operand must be marked as used. If the operand is set to
  1567. // Score 1 explicitly (because of non power-of-2 unique scalars, we may
  1568. // want to reestimate the operands again on the following iterations).
  1569. bool IsUsed =
  1570. RMode == ReorderingMode::Splat || RMode == ReorderingMode::Constant;
  1571. // Iterate through all unused operands and look for the best.
  1572. for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
  1573. // Get the operand at Idx and Lane.
  1574. OperandData &OpData = getData(Idx, Lane);
  1575. Value *Op = OpData.V;
  1576. bool OpAPO = OpData.APO;
  1577. // Skip already selected operands.
  1578. if (OpData.IsUsed)
  1579. continue;
  1580. // Skip if we are trying to move the operand to a position with a
  1581. // different opcode in the linearized tree form. This would break the
  1582. // semantics.
  1583. if (OpAPO != OpIdxAPO)
  1584. continue;
  1585. // Look for an operand that matches the current mode.
  1586. switch (RMode) {
  1587. case ReorderingMode::Load:
  1588. case ReorderingMode::Constant:
  1589. case ReorderingMode::Opcode: {
  1590. bool LeftToRight = Lane > LastLane;
  1591. Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
  1592. Value *OpRight = (LeftToRight) ? Op : OpLastLane;
  1593. int Score = getLookAheadScore(OpLeft, OpRight, MainAltOps, Lane,
  1594. OpIdx, Idx, IsUsed);
  1595. if (Score > static_cast<int>(BestOp.Score)) {
  1596. BestOp.Idx = Idx;
  1597. BestOp.Score = Score;
  1598. BestScoresPerLanes[std::make_pair(OpIdx, Lane)] = Score;
  1599. }
  1600. break;
  1601. }
  1602. case ReorderingMode::Splat:
  1603. if (Op == OpLastLane)
  1604. BestOp.Idx = Idx;
  1605. break;
  1606. case ReorderingMode::Failed:
  1607. llvm_unreachable("Not expected Failed reordering mode.");
  1608. }
  1609. }
  1610. if (BestOp.Idx) {
  1611. getData(*BestOp.Idx, Lane).IsUsed = IsUsed;
  1612. return BestOp.Idx;
  1613. }
  1614. // If we could not find a good match return std::nullopt.
  1615. return std::nullopt;
  1616. }
  1617. /// Helper for reorderOperandVecs.
  1618. /// \returns the lane that we should start reordering from. This is the one
  1619. /// which has the least number of operands that can freely move about or
  1620. /// less profitable because it already has the most optimal set of operands.
  1621. unsigned getBestLaneToStartReordering() const {
  1622. unsigned Min = UINT_MAX;
  1623. unsigned SameOpNumber = 0;
  1624. // std::pair<unsigned, unsigned> is used to implement a simple voting
  1625. // algorithm and choose the lane with the least number of operands that
  1626. // can freely move about or less profitable because it already has the
  1627. // most optimal set of operands. The first unsigned is a counter for
  1628. // voting, the second unsigned is the counter of lanes with instructions
  1629. // with same/alternate opcodes and same parent basic block.
  1630. MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
  1631. // Try to be closer to the original results, if we have multiple lanes
  1632. // with same cost. If 2 lanes have the same cost, use the one with the
  1633. // lowest index.
  1634. for (int I = getNumLanes(); I > 0; --I) {
  1635. unsigned Lane = I - 1;
  1636. OperandsOrderData NumFreeOpsHash =
  1637. getMaxNumOperandsThatCanBeReordered(Lane);
  1638. // Compare the number of operands that can move and choose the one with
  1639. // the least number.
  1640. if (NumFreeOpsHash.NumOfAPOs < Min) {
  1641. Min = NumFreeOpsHash.NumOfAPOs;
  1642. SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
  1643. HashMap.clear();
  1644. HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
  1645. } else if (NumFreeOpsHash.NumOfAPOs == Min &&
  1646. NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
  1647. // Select the most optimal lane in terms of number of operands that
  1648. // should be moved around.
  1649. SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
  1650. HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
  1651. } else if (NumFreeOpsHash.NumOfAPOs == Min &&
  1652. NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
  1653. auto It = HashMap.find(NumFreeOpsHash.Hash);
  1654. if (It == HashMap.end())
  1655. HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
  1656. else
  1657. ++It->second.first;
  1658. }
  1659. }
  1660. // Select the lane with the minimum counter.
  1661. unsigned BestLane = 0;
  1662. unsigned CntMin = UINT_MAX;
  1663. for (const auto &Data : reverse(HashMap)) {
  1664. if (Data.second.first < CntMin) {
  1665. CntMin = Data.second.first;
  1666. BestLane = Data.second.second;
  1667. }
  1668. }
  1669. return BestLane;
  1670. }
  1671. /// Data structure that helps to reorder operands.
  1672. struct OperandsOrderData {
  1673. /// The best number of operands with the same APOs, which can be
  1674. /// reordered.
  1675. unsigned NumOfAPOs = UINT_MAX;
  1676. /// Number of operands with the same/alternate instruction opcode and
  1677. /// parent.
  1678. unsigned NumOpsWithSameOpcodeParent = 0;
  1679. /// Hash for the actual operands ordering.
  1680. /// Used to count operands, actually their position id and opcode
  1681. /// value. It is used in the voting mechanism to find the lane with the
  1682. /// least number of operands that can freely move about or less profitable
  1683. /// because it already has the most optimal set of operands. Can be
  1684. /// replaced with SmallVector<unsigned> instead but hash code is faster
  1685. /// and requires less memory.
  1686. unsigned Hash = 0;
  1687. };
  1688. /// \returns the maximum number of operands that are allowed to be reordered
  1689. /// for \p Lane and the number of compatible instructions(with the same
  1690. /// parent/opcode). This is used as a heuristic for selecting the first lane
  1691. /// to start operand reordering.
  1692. OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
  1693. unsigned CntTrue = 0;
  1694. unsigned NumOperands = getNumOperands();
  1695. // Operands with the same APO can be reordered. We therefore need to count
  1696. // how many of them we have for each APO, like this: Cnt[APO] = x.
  1697. // Since we only have two APOs, namely true and false, we can avoid using
  1698. // a map. Instead we can simply count the number of operands that
  1699. // correspond to one of them (in this case the 'true' APO), and calculate
  1700. // the other by subtracting it from the total number of operands.
  1701. // Operands with the same instruction opcode and parent are more
  1702. // profitable since we don't need to move them in many cases, with a high
  1703. // probability such lane already can be vectorized effectively.
  1704. bool AllUndefs = true;
  1705. unsigned NumOpsWithSameOpcodeParent = 0;
  1706. Instruction *OpcodeI = nullptr;
  1707. BasicBlock *Parent = nullptr;
  1708. unsigned Hash = 0;
  1709. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1710. const OperandData &OpData = getData(OpIdx, Lane);
  1711. if (OpData.APO)
  1712. ++CntTrue;
  1713. // Use Boyer-Moore majority voting for finding the majority opcode and
  1714. // the number of times it occurs.
  1715. if (auto *I = dyn_cast<Instruction>(OpData.V)) {
  1716. if (!OpcodeI || !getSameOpcode({OpcodeI, I}, TLI).getOpcode() ||
  1717. I->getParent() != Parent) {
  1718. if (NumOpsWithSameOpcodeParent == 0) {
  1719. NumOpsWithSameOpcodeParent = 1;
  1720. OpcodeI = I;
  1721. Parent = I->getParent();
  1722. } else {
  1723. --NumOpsWithSameOpcodeParent;
  1724. }
  1725. } else {
  1726. ++NumOpsWithSameOpcodeParent;
  1727. }
  1728. }
  1729. Hash = hash_combine(
  1730. Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
  1731. AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
  1732. }
  1733. if (AllUndefs)
  1734. return {};
  1735. OperandsOrderData Data;
  1736. Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
  1737. Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
  1738. Data.Hash = Hash;
  1739. return Data;
  1740. }
  1741. /// Go through the instructions in VL and append their operands.
  1742. void appendOperandsOfVL(ArrayRef<Value *> VL) {
  1743. assert(!VL.empty() && "Bad VL");
  1744. assert((empty() || VL.size() == getNumLanes()) &&
  1745. "Expected same number of lanes");
  1746. assert(isa<Instruction>(VL[0]) && "Expected instruction");
  1747. unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
  1748. OpsVec.resize(NumOperands);
  1749. unsigned NumLanes = VL.size();
  1750. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1751. OpsVec[OpIdx].resize(NumLanes);
  1752. for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
  1753. assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
  1754. // Our tree has just 3 nodes: the root and two operands.
  1755. // It is therefore trivial to get the APO. We only need to check the
  1756. // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
  1757. // RHS operand. The LHS operand of both add and sub is never attached
  1758. // to an inversese operation in the linearized form, therefore its APO
  1759. // is false. The RHS is true only if VL[Lane] is an inverse operation.
  1760. // Since operand reordering is performed on groups of commutative
  1761. // operations or alternating sequences (e.g., +, -), we can safely
  1762. // tell the inverse operations by checking commutativity.
  1763. bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
  1764. bool APO = (OpIdx == 0) ? false : IsInverseOperation;
  1765. OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
  1766. APO, false};
  1767. }
  1768. }
  1769. }
  1770. /// \returns the number of operands.
  1771. unsigned getNumOperands() const { return OpsVec.size(); }
  1772. /// \returns the number of lanes.
  1773. unsigned getNumLanes() const { return OpsVec[0].size(); }
  1774. /// \returns the operand value at \p OpIdx and \p Lane.
  1775. Value *getValue(unsigned OpIdx, unsigned Lane) const {
  1776. return getData(OpIdx, Lane).V;
  1777. }
  1778. /// \returns true if the data structure is empty.
  1779. bool empty() const { return OpsVec.empty(); }
  1780. /// Clears the data.
  1781. void clear() { OpsVec.clear(); }
  1782. /// \Returns true if there are enough operands identical to \p Op to fill
  1783. /// the whole vector.
  1784. /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
  1785. bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
  1786. bool OpAPO = getData(OpIdx, Lane).APO;
  1787. for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
  1788. if (Ln == Lane)
  1789. continue;
  1790. // This is set to true if we found a candidate for broadcast at Lane.
  1791. bool FoundCandidate = false;
  1792. for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
  1793. OperandData &Data = getData(OpI, Ln);
  1794. if (Data.APO != OpAPO || Data.IsUsed)
  1795. continue;
  1796. if (Data.V == Op) {
  1797. FoundCandidate = true;
  1798. Data.IsUsed = true;
  1799. break;
  1800. }
  1801. }
  1802. if (!FoundCandidate)
  1803. return false;
  1804. }
  1805. return true;
  1806. }
  1807. public:
  1808. /// Initialize with all the operands of the instruction vector \p RootVL.
  1809. VLOperands(ArrayRef<Value *> RootVL, const TargetLibraryInfo &TLI,
  1810. const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R)
  1811. : TLI(TLI), DL(DL), SE(SE), R(R) {
  1812. // Append all the operands of RootVL.
  1813. appendOperandsOfVL(RootVL);
  1814. }
  1815. /// \Returns a value vector with the operands across all lanes for the
  1816. /// opearnd at \p OpIdx.
  1817. ValueList getVL(unsigned OpIdx) const {
  1818. ValueList OpVL(OpsVec[OpIdx].size());
  1819. assert(OpsVec[OpIdx].size() == getNumLanes() &&
  1820. "Expected same num of lanes across all operands");
  1821. for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
  1822. OpVL[Lane] = OpsVec[OpIdx][Lane].V;
  1823. return OpVL;
  1824. }
  1825. // Performs operand reordering for 2 or more operands.
  1826. // The original operands are in OrigOps[OpIdx][Lane].
  1827. // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
  1828. void reorder() {
  1829. unsigned NumOperands = getNumOperands();
  1830. unsigned NumLanes = getNumLanes();
  1831. // Each operand has its own mode. We are using this mode to help us select
  1832. // the instructions for each lane, so that they match best with the ones
  1833. // we have selected so far.
  1834. SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
  1835. // This is a greedy single-pass algorithm. We are going over each lane
  1836. // once and deciding on the best order right away with no back-tracking.
  1837. // However, in order to increase its effectiveness, we start with the lane
  1838. // that has operands that can move the least. For example, given the
  1839. // following lanes:
  1840. // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
  1841. // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
  1842. // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
  1843. // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
  1844. // we will start at Lane 1, since the operands of the subtraction cannot
  1845. // be reordered. Then we will visit the rest of the lanes in a circular
  1846. // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
  1847. // Find the first lane that we will start our search from.
  1848. unsigned FirstLane = getBestLaneToStartReordering();
  1849. // Initialize the modes.
  1850. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1851. Value *OpLane0 = getValue(OpIdx, FirstLane);
  1852. // Keep track if we have instructions with all the same opcode on one
  1853. // side.
  1854. if (isa<LoadInst>(OpLane0))
  1855. ReorderingModes[OpIdx] = ReorderingMode::Load;
  1856. else if (isa<Instruction>(OpLane0)) {
  1857. // Check if OpLane0 should be broadcast.
  1858. if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
  1859. ReorderingModes[OpIdx] = ReorderingMode::Splat;
  1860. else
  1861. ReorderingModes[OpIdx] = ReorderingMode::Opcode;
  1862. }
  1863. else if (isa<Constant>(OpLane0))
  1864. ReorderingModes[OpIdx] = ReorderingMode::Constant;
  1865. else if (isa<Argument>(OpLane0))
  1866. // Our best hope is a Splat. It may save some cost in some cases.
  1867. ReorderingModes[OpIdx] = ReorderingMode::Splat;
  1868. else
  1869. // NOTE: This should be unreachable.
  1870. ReorderingModes[OpIdx] = ReorderingMode::Failed;
  1871. }
  1872. // Check that we don't have same operands. No need to reorder if operands
  1873. // are just perfect diamond or shuffled diamond match. Do not do it only
  1874. // for possible broadcasts or non-power of 2 number of scalars (just for
  1875. // now).
  1876. auto &&SkipReordering = [this]() {
  1877. SmallPtrSet<Value *, 4> UniqueValues;
  1878. ArrayRef<OperandData> Op0 = OpsVec.front();
  1879. for (const OperandData &Data : Op0)
  1880. UniqueValues.insert(Data.V);
  1881. for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
  1882. if (any_of(Op, [&UniqueValues](const OperandData &Data) {
  1883. return !UniqueValues.contains(Data.V);
  1884. }))
  1885. return false;
  1886. }
  1887. // TODO: Check if we can remove a check for non-power-2 number of
  1888. // scalars after full support of non-power-2 vectorization.
  1889. return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
  1890. };
  1891. // If the initial strategy fails for any of the operand indexes, then we
  1892. // perform reordering again in a second pass. This helps avoid assigning
  1893. // high priority to the failed strategy, and should improve reordering for
  1894. // the non-failed operand indexes.
  1895. for (int Pass = 0; Pass != 2; ++Pass) {
  1896. // Check if no need to reorder operands since they're are perfect or
  1897. // shuffled diamond match.
  1898. // Need to to do it to avoid extra external use cost counting for
  1899. // shuffled matches, which may cause regressions.
  1900. if (SkipReordering())
  1901. break;
  1902. // Skip the second pass if the first pass did not fail.
  1903. bool StrategyFailed = false;
  1904. // Mark all operand data as free to use.
  1905. clearUsed();
  1906. // We keep the original operand order for the FirstLane, so reorder the
  1907. // rest of the lanes. We are visiting the nodes in a circular fashion,
  1908. // using FirstLane as the center point and increasing the radius
  1909. // distance.
  1910. SmallVector<SmallVector<Value *, 2>> MainAltOps(NumOperands);
  1911. for (unsigned I = 0; I < NumOperands; ++I)
  1912. MainAltOps[I].push_back(getData(I, FirstLane).V);
  1913. for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
  1914. // Visit the lane on the right and then the lane on the left.
  1915. for (int Direction : {+1, -1}) {
  1916. int Lane = FirstLane + Direction * Distance;
  1917. if (Lane < 0 || Lane >= (int)NumLanes)
  1918. continue;
  1919. int LastLane = Lane - Direction;
  1920. assert(LastLane >= 0 && LastLane < (int)NumLanes &&
  1921. "Out of bounds");
  1922. // Look for a good match for each operand.
  1923. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1924. // Search for the operand that matches SortedOps[OpIdx][Lane-1].
  1925. std::optional<unsigned> BestIdx = getBestOperand(
  1926. OpIdx, Lane, LastLane, ReorderingModes, MainAltOps[OpIdx]);
  1927. // By not selecting a value, we allow the operands that follow to
  1928. // select a better matching value. We will get a non-null value in
  1929. // the next run of getBestOperand().
  1930. if (BestIdx) {
  1931. // Swap the current operand with the one returned by
  1932. // getBestOperand().
  1933. swap(OpIdx, *BestIdx, Lane);
  1934. } else {
  1935. // We failed to find a best operand, set mode to 'Failed'.
  1936. ReorderingModes[OpIdx] = ReorderingMode::Failed;
  1937. // Enable the second pass.
  1938. StrategyFailed = true;
  1939. }
  1940. // Try to get the alternate opcode and follow it during analysis.
  1941. if (MainAltOps[OpIdx].size() != 2) {
  1942. OperandData &AltOp = getData(OpIdx, Lane);
  1943. InstructionsState OpS =
  1944. getSameOpcode({MainAltOps[OpIdx].front(), AltOp.V}, TLI);
  1945. if (OpS.getOpcode() && OpS.isAltShuffle())
  1946. MainAltOps[OpIdx].push_back(AltOp.V);
  1947. }
  1948. }
  1949. }
  1950. }
  1951. // Skip second pass if the strategy did not fail.
  1952. if (!StrategyFailed)
  1953. break;
  1954. }
  1955. }
  1956. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1957. LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
  1958. switch (RMode) {
  1959. case ReorderingMode::Load:
  1960. return "Load";
  1961. case ReorderingMode::Opcode:
  1962. return "Opcode";
  1963. case ReorderingMode::Constant:
  1964. return "Constant";
  1965. case ReorderingMode::Splat:
  1966. return "Splat";
  1967. case ReorderingMode::Failed:
  1968. return "Failed";
  1969. }
  1970. llvm_unreachable("Unimplemented Reordering Type");
  1971. }
  1972. LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
  1973. raw_ostream &OS) {
  1974. return OS << getModeStr(RMode);
  1975. }
  1976. /// Debug print.
  1977. LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
  1978. printMode(RMode, dbgs());
  1979. }
  1980. friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
  1981. return printMode(RMode, OS);
  1982. }
  1983. LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
  1984. const unsigned Indent = 2;
  1985. unsigned Cnt = 0;
  1986. for (const OperandDataVec &OpDataVec : OpsVec) {
  1987. OS << "Operand " << Cnt++ << "\n";
  1988. for (const OperandData &OpData : OpDataVec) {
  1989. OS.indent(Indent) << "{";
  1990. if (Value *V = OpData.V)
  1991. OS << *V;
  1992. else
  1993. OS << "null";
  1994. OS << ", APO:" << OpData.APO << "}\n";
  1995. }
  1996. OS << "\n";
  1997. }
  1998. return OS;
  1999. }
  2000. /// Debug print.
  2001. LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
  2002. #endif
  2003. };
  2004. /// Evaluate each pair in \p Candidates and return index into \p Candidates
  2005. /// for a pair which have highest score deemed to have best chance to form
  2006. /// root of profitable tree to vectorize. Return std::nullopt if no candidate
  2007. /// scored above the LookAheadHeuristics::ScoreFail. \param Limit Lower limit
  2008. /// of the cost, considered to be good enough score.
  2009. std::optional<int>
  2010. findBestRootPair(ArrayRef<std::pair<Value *, Value *>> Candidates,
  2011. int Limit = LookAheadHeuristics::ScoreFail) {
  2012. LookAheadHeuristics LookAhead(*TLI, *DL, *SE, *this, /*NumLanes=*/2,
  2013. RootLookAheadMaxDepth);
  2014. int BestScore = Limit;
  2015. std::optional<int> Index;
  2016. for (int I : seq<int>(0, Candidates.size())) {
  2017. int Score = LookAhead.getScoreAtLevelRec(Candidates[I].first,
  2018. Candidates[I].second,
  2019. /*U1=*/nullptr, /*U2=*/nullptr,
  2020. /*Level=*/1, std::nullopt);
  2021. if (Score > BestScore) {
  2022. BestScore = Score;
  2023. Index = I;
  2024. }
  2025. }
  2026. return Index;
  2027. }
  2028. /// Checks if the instruction is marked for deletion.
  2029. bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
  2030. /// Removes an instruction from its block and eventually deletes it.
  2031. /// It's like Instruction::eraseFromParent() except that the actual deletion
  2032. /// is delayed until BoUpSLP is destructed.
  2033. void eraseInstruction(Instruction *I) {
  2034. DeletedInstructions.insert(I);
  2035. }
  2036. /// Checks if the instruction was already analyzed for being possible
  2037. /// reduction root.
  2038. bool isAnalyzedReductionRoot(Instruction *I) const {
  2039. return AnalyzedReductionsRoots.count(I);
  2040. }
  2041. /// Register given instruction as already analyzed for being possible
  2042. /// reduction root.
  2043. void analyzedReductionRoot(Instruction *I) {
  2044. AnalyzedReductionsRoots.insert(I);
  2045. }
  2046. /// Checks if the provided list of reduced values was checked already for
  2047. /// vectorization.
  2048. bool areAnalyzedReductionVals(ArrayRef<Value *> VL) const {
  2049. return AnalyzedReductionVals.contains(hash_value(VL));
  2050. }
  2051. /// Adds the list of reduced values to list of already checked values for the
  2052. /// vectorization.
  2053. void analyzedReductionVals(ArrayRef<Value *> VL) {
  2054. AnalyzedReductionVals.insert(hash_value(VL));
  2055. }
  2056. /// Clear the list of the analyzed reduction root instructions.
  2057. void clearReductionData() {
  2058. AnalyzedReductionsRoots.clear();
  2059. AnalyzedReductionVals.clear();
  2060. }
  2061. /// Checks if the given value is gathered in one of the nodes.
  2062. bool isAnyGathered(const SmallDenseSet<Value *> &Vals) const {
  2063. return any_of(MustGather, [&](Value *V) { return Vals.contains(V); });
  2064. }
  2065. /// Check if the value is vectorized in the tree.
  2066. bool isVectorized(Value *V) const { return getTreeEntry(V); }
  2067. ~BoUpSLP();
  2068. private:
  2069. /// Check if the operands on the edges \p Edges of the \p UserTE allows
  2070. /// reordering (i.e. the operands can be reordered because they have only one
  2071. /// user and reordarable).
  2072. /// \param ReorderableGathers List of all gather nodes that require reordering
  2073. /// (e.g., gather of extractlements or partially vectorizable loads).
  2074. /// \param GatherOps List of gather operand nodes for \p UserTE that require
  2075. /// reordering, subset of \p NonVectorized.
  2076. bool
  2077. canReorderOperands(TreeEntry *UserTE,
  2078. SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
  2079. ArrayRef<TreeEntry *> ReorderableGathers,
  2080. SmallVectorImpl<TreeEntry *> &GatherOps);
  2081. /// Checks if the given \p TE is a gather node with clustered reused scalars
  2082. /// and reorders it per given \p Mask.
  2083. void reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const;
  2084. /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
  2085. /// if any. If it is not vectorized (gather node), returns nullptr.
  2086. TreeEntry *getVectorizedOperand(TreeEntry *UserTE, unsigned OpIdx) {
  2087. ArrayRef<Value *> VL = UserTE->getOperand(OpIdx);
  2088. TreeEntry *TE = nullptr;
  2089. const auto *It = find_if(VL, [this, &TE](Value *V) {
  2090. TE = getTreeEntry(V);
  2091. return TE;
  2092. });
  2093. if (It != VL.end() && TE->isSame(VL))
  2094. return TE;
  2095. return nullptr;
  2096. }
  2097. /// Returns vectorized operand \p OpIdx of the node \p UserTE from the graph,
  2098. /// if any. If it is not vectorized (gather node), returns nullptr.
  2099. const TreeEntry *getVectorizedOperand(const TreeEntry *UserTE,
  2100. unsigned OpIdx) const {
  2101. return const_cast<BoUpSLP *>(this)->getVectorizedOperand(
  2102. const_cast<TreeEntry *>(UserTE), OpIdx);
  2103. }
  2104. /// Checks if all users of \p I are the part of the vectorization tree.
  2105. bool areAllUsersVectorized(Instruction *I,
  2106. ArrayRef<Value *> VectorizedVals) const;
  2107. /// Return information about the vector formed for the specified index
  2108. /// of a vector of (the same) instruction.
  2109. TargetTransformInfo::OperandValueInfo getOperandInfo(ArrayRef<Value *> VL,
  2110. unsigned OpIdx);
  2111. /// \returns the cost of the vectorizable entry.
  2112. InstructionCost getEntryCost(const TreeEntry *E,
  2113. ArrayRef<Value *> VectorizedVals);
  2114. /// This is the recursive part of buildTree.
  2115. void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
  2116. const EdgeInfo &EI);
  2117. /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
  2118. /// be vectorized to use the original vector (or aggregate "bitcast" to a
  2119. /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
  2120. /// returns false, setting \p CurrentOrder to either an empty vector or a
  2121. /// non-identity permutation that allows to reuse extract instructions.
  2122. bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
  2123. SmallVectorImpl<unsigned> &CurrentOrder) const;
  2124. /// Vectorize a single entry in the tree.
  2125. Value *vectorizeTree(TreeEntry *E);
  2126. /// Vectorize a single entry in the tree, the \p Idx-th operand of the entry
  2127. /// \p E.
  2128. Value *vectorizeOperand(TreeEntry *E, unsigned NodeIdx);
  2129. /// Create a new vector from a list of scalar values. Produces a sequence
  2130. /// which exploits values reused across lanes, and arranges the inserts
  2131. /// for ease of later optimization.
  2132. Value *createBuildVector(const TreeEntry *E);
  2133. /// \returns the scalarization cost for this type. Scalarization in this
  2134. /// context means the creation of vectors from a group of scalars. If \p
  2135. /// NeedToShuffle is true, need to add a cost of reshuffling some of the
  2136. /// vector elements.
  2137. InstructionCost getGatherCost(FixedVectorType *Ty,
  2138. const APInt &ShuffledIndices,
  2139. bool NeedToShuffle) const;
  2140. /// Returns the instruction in the bundle, which can be used as a base point
  2141. /// for scheduling. Usually it is the last instruction in the bundle, except
  2142. /// for the case when all operands are external (in this case, it is the first
  2143. /// instruction in the list).
  2144. Instruction &getLastInstructionInBundle(const TreeEntry *E);
  2145. /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
  2146. /// tree entries.
  2147. /// \param TE Tree entry checked for permutation.
  2148. /// \param VL List of scalars (a subset of the TE scalar), checked for
  2149. /// permutations.
  2150. /// \returns ShuffleKind, if gathered values can be represented as shuffles of
  2151. /// previous tree entries. \p Mask is filled with the shuffle mask.
  2152. std::optional<TargetTransformInfo::ShuffleKind>
  2153. isGatherShuffledEntry(const TreeEntry *TE, ArrayRef<Value *> VL,
  2154. SmallVectorImpl<int> &Mask,
  2155. SmallVectorImpl<const TreeEntry *> &Entries);
  2156. /// \returns the scalarization cost for this list of values. Assuming that
  2157. /// this subtree gets vectorized, we may need to extract the values from the
  2158. /// roots. This method calculates the cost of extracting the values.
  2159. InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
  2160. /// Set the Builder insert point to one after the last instruction in
  2161. /// the bundle
  2162. void setInsertPointAfterBundle(const TreeEntry *E);
  2163. /// \returns a vector from a collection of scalars in \p VL.
  2164. Value *gather(ArrayRef<Value *> VL);
  2165. /// \returns whether the VectorizableTree is fully vectorizable and will
  2166. /// be beneficial even the tree height is tiny.
  2167. bool isFullyVectorizableTinyTree(bool ForReduction) const;
  2168. /// Reorder commutative or alt operands to get better probability of
  2169. /// generating vectorized code.
  2170. static void reorderInputsAccordingToOpcode(
  2171. ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left,
  2172. SmallVectorImpl<Value *> &Right, const TargetLibraryInfo &TLI,
  2173. const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R);
  2174. /// Helper for `findExternalStoreUsersReorderIndices()`. It iterates over the
  2175. /// users of \p TE and collects the stores. It returns the map from the store
  2176. /// pointers to the collected stores.
  2177. DenseMap<Value *, SmallVector<StoreInst *, 4>>
  2178. collectUserStores(const BoUpSLP::TreeEntry *TE) const;
  2179. /// Helper for `findExternalStoreUsersReorderIndices()`. It checks if the
  2180. /// stores in \p StoresVec can form a vector instruction. If so it returns true
  2181. /// and populates \p ReorderIndices with the shuffle indices of the the stores
  2182. /// when compared to the sorted vector.
  2183. bool canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
  2184. OrdersType &ReorderIndices) const;
  2185. /// Iterates through the users of \p TE, looking for scalar stores that can be
  2186. /// potentially vectorized in a future SLP-tree. If found, it keeps track of
  2187. /// their order and builds an order index vector for each store bundle. It
  2188. /// returns all these order vectors found.
  2189. /// We run this after the tree has formed, otherwise we may come across user
  2190. /// instructions that are not yet in the tree.
  2191. SmallVector<OrdersType, 1>
  2192. findExternalStoreUsersReorderIndices(TreeEntry *TE) const;
  2193. struct TreeEntry {
  2194. using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
  2195. TreeEntry(VecTreeTy &Container) : Container(Container) {}
  2196. /// \returns true if the scalars in VL are equal to this entry.
  2197. bool isSame(ArrayRef<Value *> VL) const {
  2198. auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
  2199. if (Mask.size() != VL.size() && VL.size() == Scalars.size())
  2200. return std::equal(VL.begin(), VL.end(), Scalars.begin());
  2201. return VL.size() == Mask.size() &&
  2202. std::equal(VL.begin(), VL.end(), Mask.begin(),
  2203. [Scalars](Value *V, int Idx) {
  2204. return (isa<UndefValue>(V) &&
  2205. Idx == UndefMaskElem) ||
  2206. (Idx != UndefMaskElem && V == Scalars[Idx]);
  2207. });
  2208. };
  2209. if (!ReorderIndices.empty()) {
  2210. // TODO: implement matching if the nodes are just reordered, still can
  2211. // treat the vector as the same if the list of scalars matches VL
  2212. // directly, without reordering.
  2213. SmallVector<int> Mask;
  2214. inversePermutation(ReorderIndices, Mask);
  2215. if (VL.size() == Scalars.size())
  2216. return IsSame(Scalars, Mask);
  2217. if (VL.size() == ReuseShuffleIndices.size()) {
  2218. ::addMask(Mask, ReuseShuffleIndices);
  2219. return IsSame(Scalars, Mask);
  2220. }
  2221. return false;
  2222. }
  2223. return IsSame(Scalars, ReuseShuffleIndices);
  2224. }
  2225. bool isOperandGatherNode(const EdgeInfo &UserEI) const {
  2226. return State == TreeEntry::NeedToGather &&
  2227. UserTreeIndices.front().EdgeIdx == UserEI.EdgeIdx &&
  2228. UserTreeIndices.front().UserTE == UserEI.UserTE;
  2229. }
  2230. /// \returns true if current entry has same operands as \p TE.
  2231. bool hasEqualOperands(const TreeEntry &TE) const {
  2232. if (TE.getNumOperands() != getNumOperands())
  2233. return false;
  2234. SmallBitVector Used(getNumOperands());
  2235. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  2236. unsigned PrevCount = Used.count();
  2237. for (unsigned K = 0; K < E; ++K) {
  2238. if (Used.test(K))
  2239. continue;
  2240. if (getOperand(K) == TE.getOperand(I)) {
  2241. Used.set(K);
  2242. break;
  2243. }
  2244. }
  2245. // Check if we actually found the matching operand.
  2246. if (PrevCount == Used.count())
  2247. return false;
  2248. }
  2249. return true;
  2250. }
  2251. /// \return Final vectorization factor for the node. Defined by the total
  2252. /// number of vectorized scalars, including those, used several times in the
  2253. /// entry and counted in the \a ReuseShuffleIndices, if any.
  2254. unsigned getVectorFactor() const {
  2255. if (!ReuseShuffleIndices.empty())
  2256. return ReuseShuffleIndices.size();
  2257. return Scalars.size();
  2258. };
  2259. /// A vector of scalars.
  2260. ValueList Scalars;
  2261. /// The Scalars are vectorized into this value. It is initialized to Null.
  2262. Value *VectorizedValue = nullptr;
  2263. /// Do we need to gather this sequence or vectorize it
  2264. /// (either with vector instruction or with scatter/gather
  2265. /// intrinsics for store/load)?
  2266. enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
  2267. EntryState State;
  2268. /// Does this sequence require some shuffling?
  2269. SmallVector<int, 4> ReuseShuffleIndices;
  2270. /// Does this entry require reordering?
  2271. SmallVector<unsigned, 4> ReorderIndices;
  2272. /// Points back to the VectorizableTree.
  2273. ///
  2274. /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
  2275. /// to be a pointer and needs to be able to initialize the child iterator.
  2276. /// Thus we need a reference back to the container to translate the indices
  2277. /// to entries.
  2278. VecTreeTy &Container;
  2279. /// The TreeEntry index containing the user of this entry. We can actually
  2280. /// have multiple users so the data structure is not truly a tree.
  2281. SmallVector<EdgeInfo, 1> UserTreeIndices;
  2282. /// The index of this treeEntry in VectorizableTree.
  2283. int Idx = -1;
  2284. private:
  2285. /// The operands of each instruction in each lane Operands[op_index][lane].
  2286. /// Note: This helps avoid the replication of the code that performs the
  2287. /// reordering of operands during buildTree_rec() and vectorizeTree().
  2288. SmallVector<ValueList, 2> Operands;
  2289. /// The main/alternate instruction.
  2290. Instruction *MainOp = nullptr;
  2291. Instruction *AltOp = nullptr;
  2292. public:
  2293. /// Set this bundle's \p OpIdx'th operand to \p OpVL.
  2294. void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
  2295. if (Operands.size() < OpIdx + 1)
  2296. Operands.resize(OpIdx + 1);
  2297. assert(Operands[OpIdx].empty() && "Already resized?");
  2298. assert(OpVL.size() <= Scalars.size() &&
  2299. "Number of operands is greater than the number of scalars.");
  2300. Operands[OpIdx].resize(OpVL.size());
  2301. copy(OpVL, Operands[OpIdx].begin());
  2302. }
  2303. /// Set the operands of this bundle in their original order.
  2304. void setOperandsInOrder() {
  2305. assert(Operands.empty() && "Already initialized?");
  2306. auto *I0 = cast<Instruction>(Scalars[0]);
  2307. Operands.resize(I0->getNumOperands());
  2308. unsigned NumLanes = Scalars.size();
  2309. for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
  2310. OpIdx != NumOperands; ++OpIdx) {
  2311. Operands[OpIdx].resize(NumLanes);
  2312. for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
  2313. auto *I = cast<Instruction>(Scalars[Lane]);
  2314. assert(I->getNumOperands() == NumOperands &&
  2315. "Expected same number of operands");
  2316. Operands[OpIdx][Lane] = I->getOperand(OpIdx);
  2317. }
  2318. }
  2319. }
  2320. /// Reorders operands of the node to the given mask \p Mask.
  2321. void reorderOperands(ArrayRef<int> Mask) {
  2322. for (ValueList &Operand : Operands)
  2323. reorderScalars(Operand, Mask);
  2324. }
  2325. /// \returns the \p OpIdx operand of this TreeEntry.
  2326. ValueList &getOperand(unsigned OpIdx) {
  2327. assert(OpIdx < Operands.size() && "Off bounds");
  2328. return Operands[OpIdx];
  2329. }
  2330. /// \returns the \p OpIdx operand of this TreeEntry.
  2331. ArrayRef<Value *> getOperand(unsigned OpIdx) const {
  2332. assert(OpIdx < Operands.size() && "Off bounds");
  2333. return Operands[OpIdx];
  2334. }
  2335. /// \returns the number of operands.
  2336. unsigned getNumOperands() const { return Operands.size(); }
  2337. /// \return the single \p OpIdx operand.
  2338. Value *getSingleOperand(unsigned OpIdx) const {
  2339. assert(OpIdx < Operands.size() && "Off bounds");
  2340. assert(!Operands[OpIdx].empty() && "No operand available");
  2341. return Operands[OpIdx][0];
  2342. }
  2343. /// Some of the instructions in the list have alternate opcodes.
  2344. bool isAltShuffle() const { return MainOp != AltOp; }
  2345. bool isOpcodeOrAlt(Instruction *I) const {
  2346. unsigned CheckedOpcode = I->getOpcode();
  2347. return (getOpcode() == CheckedOpcode ||
  2348. getAltOpcode() == CheckedOpcode);
  2349. }
  2350. /// Chooses the correct key for scheduling data. If \p Op has the same (or
  2351. /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
  2352. /// \p OpValue.
  2353. Value *isOneOf(Value *Op) const {
  2354. auto *I = dyn_cast<Instruction>(Op);
  2355. if (I && isOpcodeOrAlt(I))
  2356. return Op;
  2357. return MainOp;
  2358. }
  2359. void setOperations(const InstructionsState &S) {
  2360. MainOp = S.MainOp;
  2361. AltOp = S.AltOp;
  2362. }
  2363. Instruction *getMainOp() const {
  2364. return MainOp;
  2365. }
  2366. Instruction *getAltOp() const {
  2367. return AltOp;
  2368. }
  2369. /// The main/alternate opcodes for the list of instructions.
  2370. unsigned getOpcode() const {
  2371. return MainOp ? MainOp->getOpcode() : 0;
  2372. }
  2373. unsigned getAltOpcode() const {
  2374. return AltOp ? AltOp->getOpcode() : 0;
  2375. }
  2376. /// When ReuseReorderShuffleIndices is empty it just returns position of \p
  2377. /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
  2378. int findLaneForValue(Value *V) const {
  2379. unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
  2380. assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
  2381. if (!ReorderIndices.empty())
  2382. FoundLane = ReorderIndices[FoundLane];
  2383. assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
  2384. if (!ReuseShuffleIndices.empty()) {
  2385. FoundLane = std::distance(ReuseShuffleIndices.begin(),
  2386. find(ReuseShuffleIndices, FoundLane));
  2387. }
  2388. return FoundLane;
  2389. }
  2390. #ifndef NDEBUG
  2391. /// Debug printer.
  2392. LLVM_DUMP_METHOD void dump() const {
  2393. dbgs() << Idx << ".\n";
  2394. for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
  2395. dbgs() << "Operand " << OpI << ":\n";
  2396. for (const Value *V : Operands[OpI])
  2397. dbgs().indent(2) << *V << "\n";
  2398. }
  2399. dbgs() << "Scalars: \n";
  2400. for (Value *V : Scalars)
  2401. dbgs().indent(2) << *V << "\n";
  2402. dbgs() << "State: ";
  2403. switch (State) {
  2404. case Vectorize:
  2405. dbgs() << "Vectorize\n";
  2406. break;
  2407. case ScatterVectorize:
  2408. dbgs() << "ScatterVectorize\n";
  2409. break;
  2410. case NeedToGather:
  2411. dbgs() << "NeedToGather\n";
  2412. break;
  2413. }
  2414. dbgs() << "MainOp: ";
  2415. if (MainOp)
  2416. dbgs() << *MainOp << "\n";
  2417. else
  2418. dbgs() << "NULL\n";
  2419. dbgs() << "AltOp: ";
  2420. if (AltOp)
  2421. dbgs() << *AltOp << "\n";
  2422. else
  2423. dbgs() << "NULL\n";
  2424. dbgs() << "VectorizedValue: ";
  2425. if (VectorizedValue)
  2426. dbgs() << *VectorizedValue << "\n";
  2427. else
  2428. dbgs() << "NULL\n";
  2429. dbgs() << "ReuseShuffleIndices: ";
  2430. if (ReuseShuffleIndices.empty())
  2431. dbgs() << "Empty";
  2432. else
  2433. for (int ReuseIdx : ReuseShuffleIndices)
  2434. dbgs() << ReuseIdx << ", ";
  2435. dbgs() << "\n";
  2436. dbgs() << "ReorderIndices: ";
  2437. for (unsigned ReorderIdx : ReorderIndices)
  2438. dbgs() << ReorderIdx << ", ";
  2439. dbgs() << "\n";
  2440. dbgs() << "UserTreeIndices: ";
  2441. for (const auto &EInfo : UserTreeIndices)
  2442. dbgs() << EInfo << ", ";
  2443. dbgs() << "\n";
  2444. }
  2445. #endif
  2446. };
  2447. #ifndef NDEBUG
  2448. void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
  2449. InstructionCost VecCost,
  2450. InstructionCost ScalarCost) const {
  2451. dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
  2452. dbgs() << "SLP: Costs:\n";
  2453. dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n";
  2454. dbgs() << "SLP: VectorCost = " << VecCost << "\n";
  2455. dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n";
  2456. dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " <<
  2457. ReuseShuffleCost + VecCost - ScalarCost << "\n";
  2458. }
  2459. #endif
  2460. /// Create a new VectorizableTree entry.
  2461. TreeEntry *newTreeEntry(ArrayRef<Value *> VL, std::optional<ScheduleData *> Bundle,
  2462. const InstructionsState &S,
  2463. const EdgeInfo &UserTreeIdx,
  2464. ArrayRef<int> ReuseShuffleIndices = std::nullopt,
  2465. ArrayRef<unsigned> ReorderIndices = std::nullopt) {
  2466. TreeEntry::EntryState EntryState =
  2467. Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
  2468. return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
  2469. ReuseShuffleIndices, ReorderIndices);
  2470. }
  2471. TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
  2472. TreeEntry::EntryState EntryState,
  2473. std::optional<ScheduleData *> Bundle,
  2474. const InstructionsState &S,
  2475. const EdgeInfo &UserTreeIdx,
  2476. ArrayRef<int> ReuseShuffleIndices = std::nullopt,
  2477. ArrayRef<unsigned> ReorderIndices = std::nullopt) {
  2478. assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
  2479. (Bundle && EntryState != TreeEntry::NeedToGather)) &&
  2480. "Need to vectorize gather entry?");
  2481. VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
  2482. TreeEntry *Last = VectorizableTree.back().get();
  2483. Last->Idx = VectorizableTree.size() - 1;
  2484. Last->State = EntryState;
  2485. Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
  2486. ReuseShuffleIndices.end());
  2487. if (ReorderIndices.empty()) {
  2488. Last->Scalars.assign(VL.begin(), VL.end());
  2489. Last->setOperations(S);
  2490. } else {
  2491. // Reorder scalars and build final mask.
  2492. Last->Scalars.assign(VL.size(), nullptr);
  2493. transform(ReorderIndices, Last->Scalars.begin(),
  2494. [VL](unsigned Idx) -> Value * {
  2495. if (Idx >= VL.size())
  2496. return UndefValue::get(VL.front()->getType());
  2497. return VL[Idx];
  2498. });
  2499. InstructionsState S = getSameOpcode(Last->Scalars, *TLI);
  2500. Last->setOperations(S);
  2501. Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
  2502. }
  2503. if (Last->State != TreeEntry::NeedToGather) {
  2504. for (Value *V : VL) {
  2505. assert(!getTreeEntry(V) && "Scalar already in tree!");
  2506. ScalarToTreeEntry[V] = Last;
  2507. }
  2508. // Update the scheduler bundle to point to this TreeEntry.
  2509. ScheduleData *BundleMember = *Bundle;
  2510. assert((BundleMember || isa<PHINode>(S.MainOp) ||
  2511. isVectorLikeInstWithConstOps(S.MainOp) ||
  2512. doesNotNeedToSchedule(VL)) &&
  2513. "Bundle and VL out of sync");
  2514. if (BundleMember) {
  2515. for (Value *V : VL) {
  2516. if (doesNotNeedToBeScheduled(V))
  2517. continue;
  2518. assert(BundleMember && "Unexpected end of bundle.");
  2519. BundleMember->TE = Last;
  2520. BundleMember = BundleMember->NextInBundle;
  2521. }
  2522. }
  2523. assert(!BundleMember && "Bundle and VL out of sync");
  2524. } else {
  2525. MustGather.insert(VL.begin(), VL.end());
  2526. }
  2527. if (UserTreeIdx.UserTE)
  2528. Last->UserTreeIndices.push_back(UserTreeIdx);
  2529. return Last;
  2530. }
  2531. /// -- Vectorization State --
  2532. /// Holds all of the tree entries.
  2533. TreeEntry::VecTreeTy VectorizableTree;
  2534. #ifndef NDEBUG
  2535. /// Debug printer.
  2536. LLVM_DUMP_METHOD void dumpVectorizableTree() const {
  2537. for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
  2538. VectorizableTree[Id]->dump();
  2539. dbgs() << "\n";
  2540. }
  2541. }
  2542. #endif
  2543. TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
  2544. const TreeEntry *getTreeEntry(Value *V) const {
  2545. return ScalarToTreeEntry.lookup(V);
  2546. }
  2547. /// Maps a specific scalar to its tree entry.
  2548. SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
  2549. /// Maps a value to the proposed vectorizable size.
  2550. SmallDenseMap<Value *, unsigned> InstrElementSize;
  2551. /// A list of scalars that we found that we need to keep as scalars.
  2552. ValueSet MustGather;
  2553. /// A map between the vectorized entries and the last instructions in the
  2554. /// bundles. The bundles are built in use order, not in the def order of the
  2555. /// instructions. So, we cannot rely directly on the last instruction in the
  2556. /// bundle being the last instruction in the program order during
  2557. /// vectorization process since the basic blocks are affected, need to
  2558. /// pre-gather them before.
  2559. DenseMap<const TreeEntry *, Instruction *> EntryToLastInstruction;
  2560. /// This POD struct describes one external user in the vectorized tree.
  2561. struct ExternalUser {
  2562. ExternalUser(Value *S, llvm::User *U, int L)
  2563. : Scalar(S), User(U), Lane(L) {}
  2564. // Which scalar in our function.
  2565. Value *Scalar;
  2566. // Which user that uses the scalar.
  2567. llvm::User *User;
  2568. // Which lane does the scalar belong to.
  2569. int Lane;
  2570. };
  2571. using UserList = SmallVector<ExternalUser, 16>;
  2572. /// Checks if two instructions may access the same memory.
  2573. ///
  2574. /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
  2575. /// is invariant in the calling loop.
  2576. bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
  2577. Instruction *Inst2) {
  2578. // First check if the result is already in the cache.
  2579. AliasCacheKey key = std::make_pair(Inst1, Inst2);
  2580. std::optional<bool> &result = AliasCache[key];
  2581. if (result) {
  2582. return *result;
  2583. }
  2584. bool aliased = true;
  2585. if (Loc1.Ptr && isSimple(Inst1))
  2586. aliased = isModOrRefSet(BatchAA.getModRefInfo(Inst2, Loc1));
  2587. // Store the result in the cache.
  2588. result = aliased;
  2589. return aliased;
  2590. }
  2591. using AliasCacheKey = std::pair<Instruction *, Instruction *>;
  2592. /// Cache for alias results.
  2593. /// TODO: consider moving this to the AliasAnalysis itself.
  2594. DenseMap<AliasCacheKey, std::optional<bool>> AliasCache;
  2595. // Cache for pointerMayBeCaptured calls inside AA. This is preserved
  2596. // globally through SLP because we don't perform any action which
  2597. // invalidates capture results.
  2598. BatchAAResults BatchAA;
  2599. /// Temporary store for deleted instructions. Instructions will be deleted
  2600. /// eventually when the BoUpSLP is destructed. The deferral is required to
  2601. /// ensure that there are no incorrect collisions in the AliasCache, which
  2602. /// can happen if a new instruction is allocated at the same address as a
  2603. /// previously deleted instruction.
  2604. DenseSet<Instruction *> DeletedInstructions;
  2605. /// Set of the instruction, being analyzed already for reductions.
  2606. SmallPtrSet<Instruction *, 16> AnalyzedReductionsRoots;
  2607. /// Set of hashes for the list of reduction values already being analyzed.
  2608. DenseSet<size_t> AnalyzedReductionVals;
  2609. /// A list of values that need to extracted out of the tree.
  2610. /// This list holds pairs of (Internal Scalar : External User). External User
  2611. /// can be nullptr, it means that this Internal Scalar will be used later,
  2612. /// after vectorization.
  2613. UserList ExternalUses;
  2614. /// Values used only by @llvm.assume calls.
  2615. SmallPtrSet<const Value *, 32> EphValues;
  2616. /// Holds all of the instructions that we gathered, shuffle instructions and
  2617. /// extractelements.
  2618. SetVector<Instruction *> GatherShuffleExtractSeq;
  2619. /// A list of blocks that we are going to CSE.
  2620. SetVector<BasicBlock *> CSEBlocks;
  2621. /// Contains all scheduling relevant data for an instruction.
  2622. /// A ScheduleData either represents a single instruction or a member of an
  2623. /// instruction bundle (= a group of instructions which is combined into a
  2624. /// vector instruction).
  2625. struct ScheduleData {
  2626. // The initial value for the dependency counters. It means that the
  2627. // dependencies are not calculated yet.
  2628. enum { InvalidDeps = -1 };
  2629. ScheduleData() = default;
  2630. void init(int BlockSchedulingRegionID, Value *OpVal) {
  2631. FirstInBundle = this;
  2632. NextInBundle = nullptr;
  2633. NextLoadStore = nullptr;
  2634. IsScheduled = false;
  2635. SchedulingRegionID = BlockSchedulingRegionID;
  2636. clearDependencies();
  2637. OpValue = OpVal;
  2638. TE = nullptr;
  2639. }
  2640. /// Verify basic self consistency properties
  2641. void verify() {
  2642. if (hasValidDependencies()) {
  2643. assert(UnscheduledDeps <= Dependencies && "invariant");
  2644. } else {
  2645. assert(UnscheduledDeps == Dependencies && "invariant");
  2646. }
  2647. if (IsScheduled) {
  2648. assert(isSchedulingEntity() &&
  2649. "unexpected scheduled state");
  2650. for (const ScheduleData *BundleMember = this; BundleMember;
  2651. BundleMember = BundleMember->NextInBundle) {
  2652. assert(BundleMember->hasValidDependencies() &&
  2653. BundleMember->UnscheduledDeps == 0 &&
  2654. "unexpected scheduled state");
  2655. assert((BundleMember == this || !BundleMember->IsScheduled) &&
  2656. "only bundle is marked scheduled");
  2657. }
  2658. }
  2659. assert(Inst->getParent() == FirstInBundle->Inst->getParent() &&
  2660. "all bundle members must be in same basic block");
  2661. }
  2662. /// Returns true if the dependency information has been calculated.
  2663. /// Note that depenendency validity can vary between instructions within
  2664. /// a single bundle.
  2665. bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
  2666. /// Returns true for single instructions and for bundle representatives
  2667. /// (= the head of a bundle).
  2668. bool isSchedulingEntity() const { return FirstInBundle == this; }
  2669. /// Returns true if it represents an instruction bundle and not only a
  2670. /// single instruction.
  2671. bool isPartOfBundle() const {
  2672. return NextInBundle != nullptr || FirstInBundle != this || TE;
  2673. }
  2674. /// Returns true if it is ready for scheduling, i.e. it has no more
  2675. /// unscheduled depending instructions/bundles.
  2676. bool isReady() const {
  2677. assert(isSchedulingEntity() &&
  2678. "can't consider non-scheduling entity for ready list");
  2679. return unscheduledDepsInBundle() == 0 && !IsScheduled;
  2680. }
  2681. /// Modifies the number of unscheduled dependencies for this instruction,
  2682. /// and returns the number of remaining dependencies for the containing
  2683. /// bundle.
  2684. int incrementUnscheduledDeps(int Incr) {
  2685. assert(hasValidDependencies() &&
  2686. "increment of unscheduled deps would be meaningless");
  2687. UnscheduledDeps += Incr;
  2688. return FirstInBundle->unscheduledDepsInBundle();
  2689. }
  2690. /// Sets the number of unscheduled dependencies to the number of
  2691. /// dependencies.
  2692. void resetUnscheduledDeps() {
  2693. UnscheduledDeps = Dependencies;
  2694. }
  2695. /// Clears all dependency information.
  2696. void clearDependencies() {
  2697. Dependencies = InvalidDeps;
  2698. resetUnscheduledDeps();
  2699. MemoryDependencies.clear();
  2700. ControlDependencies.clear();
  2701. }
  2702. int unscheduledDepsInBundle() const {
  2703. assert(isSchedulingEntity() && "only meaningful on the bundle");
  2704. int Sum = 0;
  2705. for (const ScheduleData *BundleMember = this; BundleMember;
  2706. BundleMember = BundleMember->NextInBundle) {
  2707. if (BundleMember->UnscheduledDeps == InvalidDeps)
  2708. return InvalidDeps;
  2709. Sum += BundleMember->UnscheduledDeps;
  2710. }
  2711. return Sum;
  2712. }
  2713. void dump(raw_ostream &os) const {
  2714. if (!isSchedulingEntity()) {
  2715. os << "/ " << *Inst;
  2716. } else if (NextInBundle) {
  2717. os << '[' << *Inst;
  2718. ScheduleData *SD = NextInBundle;
  2719. while (SD) {
  2720. os << ';' << *SD->Inst;
  2721. SD = SD->NextInBundle;
  2722. }
  2723. os << ']';
  2724. } else {
  2725. os << *Inst;
  2726. }
  2727. }
  2728. Instruction *Inst = nullptr;
  2729. /// Opcode of the current instruction in the schedule data.
  2730. Value *OpValue = nullptr;
  2731. /// The TreeEntry that this instruction corresponds to.
  2732. TreeEntry *TE = nullptr;
  2733. /// Points to the head in an instruction bundle (and always to this for
  2734. /// single instructions).
  2735. ScheduleData *FirstInBundle = nullptr;
  2736. /// Single linked list of all instructions in a bundle. Null if it is a
  2737. /// single instruction.
  2738. ScheduleData *NextInBundle = nullptr;
  2739. /// Single linked list of all memory instructions (e.g. load, store, call)
  2740. /// in the block - until the end of the scheduling region.
  2741. ScheduleData *NextLoadStore = nullptr;
  2742. /// The dependent memory instructions.
  2743. /// This list is derived on demand in calculateDependencies().
  2744. SmallVector<ScheduleData *, 4> MemoryDependencies;
  2745. /// List of instructions which this instruction could be control dependent
  2746. /// on. Allowing such nodes to be scheduled below this one could introduce
  2747. /// a runtime fault which didn't exist in the original program.
  2748. /// ex: this is a load or udiv following a readonly call which inf loops
  2749. SmallVector<ScheduleData *, 4> ControlDependencies;
  2750. /// This ScheduleData is in the current scheduling region if this matches
  2751. /// the current SchedulingRegionID of BlockScheduling.
  2752. int SchedulingRegionID = 0;
  2753. /// Used for getting a "good" final ordering of instructions.
  2754. int SchedulingPriority = 0;
  2755. /// The number of dependencies. Constitutes of the number of users of the
  2756. /// instruction plus the number of dependent memory instructions (if any).
  2757. /// This value is calculated on demand.
  2758. /// If InvalidDeps, the number of dependencies is not calculated yet.
  2759. int Dependencies = InvalidDeps;
  2760. /// The number of dependencies minus the number of dependencies of scheduled
  2761. /// instructions. As soon as this is zero, the instruction/bundle gets ready
  2762. /// for scheduling.
  2763. /// Note that this is negative as long as Dependencies is not calculated.
  2764. int UnscheduledDeps = InvalidDeps;
  2765. /// True if this instruction is scheduled (or considered as scheduled in the
  2766. /// dry-run).
  2767. bool IsScheduled = false;
  2768. };
  2769. #ifndef NDEBUG
  2770. friend inline raw_ostream &operator<<(raw_ostream &os,
  2771. const BoUpSLP::ScheduleData &SD) {
  2772. SD.dump(os);
  2773. return os;
  2774. }
  2775. #endif
  2776. friend struct GraphTraits<BoUpSLP *>;
  2777. friend struct DOTGraphTraits<BoUpSLP *>;
  2778. /// Contains all scheduling data for a basic block.
  2779. /// It does not schedules instructions, which are not memory read/write
  2780. /// instructions and their operands are either constants, or arguments, or
  2781. /// phis, or instructions from others blocks, or their users are phis or from
  2782. /// the other blocks. The resulting vector instructions can be placed at the
  2783. /// beginning of the basic block without scheduling (if operands does not need
  2784. /// to be scheduled) or at the end of the block (if users are outside of the
  2785. /// block). It allows to save some compile time and memory used by the
  2786. /// compiler.
  2787. /// ScheduleData is assigned for each instruction in between the boundaries of
  2788. /// the tree entry, even for those, which are not part of the graph. It is
  2789. /// required to correctly follow the dependencies between the instructions and
  2790. /// their correct scheduling. The ScheduleData is not allocated for the
  2791. /// instructions, which do not require scheduling, like phis, nodes with
  2792. /// extractelements/insertelements only or nodes with instructions, with
  2793. /// uses/operands outside of the block.
  2794. struct BlockScheduling {
  2795. BlockScheduling(BasicBlock *BB)
  2796. : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
  2797. void clear() {
  2798. ReadyInsts.clear();
  2799. ScheduleStart = nullptr;
  2800. ScheduleEnd = nullptr;
  2801. FirstLoadStoreInRegion = nullptr;
  2802. LastLoadStoreInRegion = nullptr;
  2803. RegionHasStackSave = false;
  2804. // Reduce the maximum schedule region size by the size of the
  2805. // previous scheduling run.
  2806. ScheduleRegionSizeLimit -= ScheduleRegionSize;
  2807. if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
  2808. ScheduleRegionSizeLimit = MinScheduleRegionSize;
  2809. ScheduleRegionSize = 0;
  2810. // Make a new scheduling region, i.e. all existing ScheduleData is not
  2811. // in the new region yet.
  2812. ++SchedulingRegionID;
  2813. }
  2814. ScheduleData *getScheduleData(Instruction *I) {
  2815. if (BB != I->getParent())
  2816. // Avoid lookup if can't possibly be in map.
  2817. return nullptr;
  2818. ScheduleData *SD = ScheduleDataMap.lookup(I);
  2819. if (SD && isInSchedulingRegion(SD))
  2820. return SD;
  2821. return nullptr;
  2822. }
  2823. ScheduleData *getScheduleData(Value *V) {
  2824. if (auto *I = dyn_cast<Instruction>(V))
  2825. return getScheduleData(I);
  2826. return nullptr;
  2827. }
  2828. ScheduleData *getScheduleData(Value *V, Value *Key) {
  2829. if (V == Key)
  2830. return getScheduleData(V);
  2831. auto I = ExtraScheduleDataMap.find(V);
  2832. if (I != ExtraScheduleDataMap.end()) {
  2833. ScheduleData *SD = I->second.lookup(Key);
  2834. if (SD && isInSchedulingRegion(SD))
  2835. return SD;
  2836. }
  2837. return nullptr;
  2838. }
  2839. bool isInSchedulingRegion(ScheduleData *SD) const {
  2840. return SD->SchedulingRegionID == SchedulingRegionID;
  2841. }
  2842. /// Marks an instruction as scheduled and puts all dependent ready
  2843. /// instructions into the ready-list.
  2844. template <typename ReadyListType>
  2845. void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
  2846. SD->IsScheduled = true;
  2847. LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
  2848. for (ScheduleData *BundleMember = SD; BundleMember;
  2849. BundleMember = BundleMember->NextInBundle) {
  2850. if (BundleMember->Inst != BundleMember->OpValue)
  2851. continue;
  2852. // Handle the def-use chain dependencies.
  2853. // Decrement the unscheduled counter and insert to ready list if ready.
  2854. auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
  2855. doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
  2856. if (OpDef && OpDef->hasValidDependencies() &&
  2857. OpDef->incrementUnscheduledDeps(-1) == 0) {
  2858. // There are no more unscheduled dependencies after
  2859. // decrementing, so we can put the dependent instruction
  2860. // into the ready list.
  2861. ScheduleData *DepBundle = OpDef->FirstInBundle;
  2862. assert(!DepBundle->IsScheduled &&
  2863. "already scheduled bundle gets ready");
  2864. ReadyList.insert(DepBundle);
  2865. LLVM_DEBUG(dbgs()
  2866. << "SLP: gets ready (def): " << *DepBundle << "\n");
  2867. }
  2868. });
  2869. };
  2870. // If BundleMember is a vector bundle, its operands may have been
  2871. // reordered during buildTree(). We therefore need to get its operands
  2872. // through the TreeEntry.
  2873. if (TreeEntry *TE = BundleMember->TE) {
  2874. // Need to search for the lane since the tree entry can be reordered.
  2875. int Lane = std::distance(TE->Scalars.begin(),
  2876. find(TE->Scalars, BundleMember->Inst));
  2877. assert(Lane >= 0 && "Lane not set");
  2878. // Since vectorization tree is being built recursively this assertion
  2879. // ensures that the tree entry has all operands set before reaching
  2880. // this code. Couple of exceptions known at the moment are extracts
  2881. // where their second (immediate) operand is not added. Since
  2882. // immediates do not affect scheduler behavior this is considered
  2883. // okay.
  2884. auto *In = BundleMember->Inst;
  2885. assert(In &&
  2886. (isa<ExtractValueInst, ExtractElementInst>(In) ||
  2887. In->getNumOperands() == TE->getNumOperands()) &&
  2888. "Missed TreeEntry operands?");
  2889. (void)In; // fake use to avoid build failure when assertions disabled
  2890. for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
  2891. OpIdx != NumOperands; ++OpIdx)
  2892. if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
  2893. DecrUnsched(I);
  2894. } else {
  2895. // If BundleMember is a stand-alone instruction, no operand reordering
  2896. // has taken place, so we directly access its operands.
  2897. for (Use &U : BundleMember->Inst->operands())
  2898. if (auto *I = dyn_cast<Instruction>(U.get()))
  2899. DecrUnsched(I);
  2900. }
  2901. // Handle the memory dependencies.
  2902. for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
  2903. if (MemoryDepSD->hasValidDependencies() &&
  2904. MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
  2905. // There are no more unscheduled dependencies after decrementing,
  2906. // so we can put the dependent instruction into the ready list.
  2907. ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
  2908. assert(!DepBundle->IsScheduled &&
  2909. "already scheduled bundle gets ready");
  2910. ReadyList.insert(DepBundle);
  2911. LLVM_DEBUG(dbgs()
  2912. << "SLP: gets ready (mem): " << *DepBundle << "\n");
  2913. }
  2914. }
  2915. // Handle the control dependencies.
  2916. for (ScheduleData *DepSD : BundleMember->ControlDependencies) {
  2917. if (DepSD->incrementUnscheduledDeps(-1) == 0) {
  2918. // There are no more unscheduled dependencies after decrementing,
  2919. // so we can put the dependent instruction into the ready list.
  2920. ScheduleData *DepBundle = DepSD->FirstInBundle;
  2921. assert(!DepBundle->IsScheduled &&
  2922. "already scheduled bundle gets ready");
  2923. ReadyList.insert(DepBundle);
  2924. LLVM_DEBUG(dbgs()
  2925. << "SLP: gets ready (ctl): " << *DepBundle << "\n");
  2926. }
  2927. }
  2928. }
  2929. }
  2930. /// Verify basic self consistency properties of the data structure.
  2931. void verify() {
  2932. if (!ScheduleStart)
  2933. return;
  2934. assert(ScheduleStart->getParent() == ScheduleEnd->getParent() &&
  2935. ScheduleStart->comesBefore(ScheduleEnd) &&
  2936. "Not a valid scheduling region?");
  2937. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  2938. auto *SD = getScheduleData(I);
  2939. if (!SD)
  2940. continue;
  2941. assert(isInSchedulingRegion(SD) &&
  2942. "primary schedule data not in window?");
  2943. assert(isInSchedulingRegion(SD->FirstInBundle) &&
  2944. "entire bundle in window!");
  2945. (void)SD;
  2946. doForAllOpcodes(I, [](ScheduleData *SD) { SD->verify(); });
  2947. }
  2948. for (auto *SD : ReadyInsts) {
  2949. assert(SD->isSchedulingEntity() && SD->isReady() &&
  2950. "item in ready list not ready?");
  2951. (void)SD;
  2952. }
  2953. }
  2954. void doForAllOpcodes(Value *V,
  2955. function_ref<void(ScheduleData *SD)> Action) {
  2956. if (ScheduleData *SD = getScheduleData(V))
  2957. Action(SD);
  2958. auto I = ExtraScheduleDataMap.find(V);
  2959. if (I != ExtraScheduleDataMap.end())
  2960. for (auto &P : I->second)
  2961. if (isInSchedulingRegion(P.second))
  2962. Action(P.second);
  2963. }
  2964. /// Put all instructions into the ReadyList which are ready for scheduling.
  2965. template <typename ReadyListType>
  2966. void initialFillReadyList(ReadyListType &ReadyList) {
  2967. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  2968. doForAllOpcodes(I, [&](ScheduleData *SD) {
  2969. if (SD->isSchedulingEntity() && SD->hasValidDependencies() &&
  2970. SD->isReady()) {
  2971. ReadyList.insert(SD);
  2972. LLVM_DEBUG(dbgs()
  2973. << "SLP: initially in ready list: " << *SD << "\n");
  2974. }
  2975. });
  2976. }
  2977. }
  2978. /// Build a bundle from the ScheduleData nodes corresponding to the
  2979. /// scalar instruction for each lane.
  2980. ScheduleData *buildBundle(ArrayRef<Value *> VL);
  2981. /// Checks if a bundle of instructions can be scheduled, i.e. has no
  2982. /// cyclic dependencies. This is only a dry-run, no instructions are
  2983. /// actually moved at this stage.
  2984. /// \returns the scheduling bundle. The returned Optional value is not
  2985. /// std::nullopt if \p VL is allowed to be scheduled.
  2986. std::optional<ScheduleData *>
  2987. tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
  2988. const InstructionsState &S);
  2989. /// Un-bundles a group of instructions.
  2990. void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
  2991. /// Allocates schedule data chunk.
  2992. ScheduleData *allocateScheduleDataChunks();
  2993. /// Extends the scheduling region so that V is inside the region.
  2994. /// \returns true if the region size is within the limit.
  2995. bool extendSchedulingRegion(Value *V, const InstructionsState &S);
  2996. /// Initialize the ScheduleData structures for new instructions in the
  2997. /// scheduling region.
  2998. void initScheduleData(Instruction *FromI, Instruction *ToI,
  2999. ScheduleData *PrevLoadStore,
  3000. ScheduleData *NextLoadStore);
  3001. /// Updates the dependency information of a bundle and of all instructions/
  3002. /// bundles which depend on the original bundle.
  3003. void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
  3004. BoUpSLP *SLP);
  3005. /// Sets all instruction in the scheduling region to un-scheduled.
  3006. void resetSchedule();
  3007. BasicBlock *BB;
  3008. /// Simple memory allocation for ScheduleData.
  3009. std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
  3010. /// The size of a ScheduleData array in ScheduleDataChunks.
  3011. int ChunkSize;
  3012. /// The allocator position in the current chunk, which is the last entry
  3013. /// of ScheduleDataChunks.
  3014. int ChunkPos;
  3015. /// Attaches ScheduleData to Instruction.
  3016. /// Note that the mapping survives during all vectorization iterations, i.e.
  3017. /// ScheduleData structures are recycled.
  3018. DenseMap<Instruction *, ScheduleData *> ScheduleDataMap;
  3019. /// Attaches ScheduleData to Instruction with the leading key.
  3020. DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
  3021. ExtraScheduleDataMap;
  3022. /// The ready-list for scheduling (only used for the dry-run).
  3023. SetVector<ScheduleData *> ReadyInsts;
  3024. /// The first instruction of the scheduling region.
  3025. Instruction *ScheduleStart = nullptr;
  3026. /// The first instruction _after_ the scheduling region.
  3027. Instruction *ScheduleEnd = nullptr;
  3028. /// The first memory accessing instruction in the scheduling region
  3029. /// (can be null).
  3030. ScheduleData *FirstLoadStoreInRegion = nullptr;
  3031. /// The last memory accessing instruction in the scheduling region
  3032. /// (can be null).
  3033. ScheduleData *LastLoadStoreInRegion = nullptr;
  3034. /// Is there an llvm.stacksave or llvm.stackrestore in the scheduling
  3035. /// region? Used to optimize the dependence calculation for the
  3036. /// common case where there isn't.
  3037. bool RegionHasStackSave = false;
  3038. /// The current size of the scheduling region.
  3039. int ScheduleRegionSize = 0;
  3040. /// The maximum size allowed for the scheduling region.
  3041. int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
  3042. /// The ID of the scheduling region. For a new vectorization iteration this
  3043. /// is incremented which "removes" all ScheduleData from the region.
  3044. /// Make sure that the initial SchedulingRegionID is greater than the
  3045. /// initial SchedulingRegionID in ScheduleData (which is 0).
  3046. int SchedulingRegionID = 1;
  3047. };
  3048. /// Attaches the BlockScheduling structures to basic blocks.
  3049. MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
  3050. /// Performs the "real" scheduling. Done before vectorization is actually
  3051. /// performed in a basic block.
  3052. void scheduleBlock(BlockScheduling *BS);
  3053. /// List of users to ignore during scheduling and that don't need extracting.
  3054. const SmallDenseSet<Value *> *UserIgnoreList = nullptr;
  3055. /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
  3056. /// sorted SmallVectors of unsigned.
  3057. struct OrdersTypeDenseMapInfo {
  3058. static OrdersType getEmptyKey() {
  3059. OrdersType V;
  3060. V.push_back(~1U);
  3061. return V;
  3062. }
  3063. static OrdersType getTombstoneKey() {
  3064. OrdersType V;
  3065. V.push_back(~2U);
  3066. return V;
  3067. }
  3068. static unsigned getHashValue(const OrdersType &V) {
  3069. return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
  3070. }
  3071. static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
  3072. return LHS == RHS;
  3073. }
  3074. };
  3075. // Analysis and block reference.
  3076. Function *F;
  3077. ScalarEvolution *SE;
  3078. TargetTransformInfo *TTI;
  3079. TargetLibraryInfo *TLI;
  3080. LoopInfo *LI;
  3081. DominatorTree *DT;
  3082. AssumptionCache *AC;
  3083. DemandedBits *DB;
  3084. const DataLayout *DL;
  3085. OptimizationRemarkEmitter *ORE;
  3086. unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
  3087. unsigned MinVecRegSize; // Set by cl::opt (default: 128).
  3088. /// Instruction builder to construct the vectorized tree.
  3089. IRBuilder<> Builder;
  3090. /// A map of scalar integer values to the smallest bit width with which they
  3091. /// can legally be represented. The values map to (width, signed) pairs,
  3092. /// where "width" indicates the minimum bit width and "signed" is True if the
  3093. /// value must be signed-extended, rather than zero-extended, back to its
  3094. /// original width.
  3095. MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
  3096. };
  3097. } // end namespace slpvectorizer
  3098. template <> struct GraphTraits<BoUpSLP *> {
  3099. using TreeEntry = BoUpSLP::TreeEntry;
  3100. /// NodeRef has to be a pointer per the GraphWriter.
  3101. using NodeRef = TreeEntry *;
  3102. using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
  3103. /// Add the VectorizableTree to the index iterator to be able to return
  3104. /// TreeEntry pointers.
  3105. struct ChildIteratorType
  3106. : public iterator_adaptor_base<
  3107. ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
  3108. ContainerTy &VectorizableTree;
  3109. ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
  3110. ContainerTy &VT)
  3111. : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
  3112. NodeRef operator*() { return I->UserTE; }
  3113. };
  3114. static NodeRef getEntryNode(BoUpSLP &R) {
  3115. return R.VectorizableTree[0].get();
  3116. }
  3117. static ChildIteratorType child_begin(NodeRef N) {
  3118. return {N->UserTreeIndices.begin(), N->Container};
  3119. }
  3120. static ChildIteratorType child_end(NodeRef N) {
  3121. return {N->UserTreeIndices.end(), N->Container};
  3122. }
  3123. /// For the node iterator we just need to turn the TreeEntry iterator into a
  3124. /// TreeEntry* iterator so that it dereferences to NodeRef.
  3125. class nodes_iterator {
  3126. using ItTy = ContainerTy::iterator;
  3127. ItTy It;
  3128. public:
  3129. nodes_iterator(const ItTy &It2) : It(It2) {}
  3130. NodeRef operator*() { return It->get(); }
  3131. nodes_iterator operator++() {
  3132. ++It;
  3133. return *this;
  3134. }
  3135. bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
  3136. };
  3137. static nodes_iterator nodes_begin(BoUpSLP *R) {
  3138. return nodes_iterator(R->VectorizableTree.begin());
  3139. }
  3140. static nodes_iterator nodes_end(BoUpSLP *R) {
  3141. return nodes_iterator(R->VectorizableTree.end());
  3142. }
  3143. static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
  3144. };
  3145. template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
  3146. using TreeEntry = BoUpSLP::TreeEntry;
  3147. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  3148. std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
  3149. std::string Str;
  3150. raw_string_ostream OS(Str);
  3151. OS << Entry->Idx << ".\n";
  3152. if (isSplat(Entry->Scalars))
  3153. OS << "<splat> ";
  3154. for (auto *V : Entry->Scalars) {
  3155. OS << *V;
  3156. if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
  3157. return EU.Scalar == V;
  3158. }))
  3159. OS << " <extract>";
  3160. OS << "\n";
  3161. }
  3162. return Str;
  3163. }
  3164. static std::string getNodeAttributes(const TreeEntry *Entry,
  3165. const BoUpSLP *) {
  3166. if (Entry->State == TreeEntry::NeedToGather)
  3167. return "color=red";
  3168. if (Entry->State == TreeEntry::ScatterVectorize)
  3169. return "color=blue";
  3170. return "";
  3171. }
  3172. };
  3173. } // end namespace llvm
  3174. BoUpSLP::~BoUpSLP() {
  3175. SmallVector<WeakTrackingVH> DeadInsts;
  3176. for (auto *I : DeletedInstructions) {
  3177. for (Use &U : I->operands()) {
  3178. auto *Op = dyn_cast<Instruction>(U.get());
  3179. if (Op && !DeletedInstructions.count(Op) && Op->hasOneUser() &&
  3180. wouldInstructionBeTriviallyDead(Op, TLI))
  3181. DeadInsts.emplace_back(Op);
  3182. }
  3183. I->dropAllReferences();
  3184. }
  3185. for (auto *I : DeletedInstructions) {
  3186. assert(I->use_empty() &&
  3187. "trying to erase instruction with users.");
  3188. I->eraseFromParent();
  3189. }
  3190. // Cleanup any dead scalar code feeding the vectorized instructions
  3191. RecursivelyDeleteTriviallyDeadInstructions(DeadInsts, TLI);
  3192. #ifdef EXPENSIVE_CHECKS
  3193. // If we could guarantee that this call is not extremely slow, we could
  3194. // remove the ifdef limitation (see PR47712).
  3195. assert(!verifyFunction(*F, &dbgs()));
  3196. #endif
  3197. }
  3198. /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
  3199. /// contains original mask for the scalars reused in the node. Procedure
  3200. /// transform this mask in accordance with the given \p Mask.
  3201. static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
  3202. assert(!Mask.empty() && Reuses.size() == Mask.size() &&
  3203. "Expected non-empty mask.");
  3204. SmallVector<int> Prev(Reuses.begin(), Reuses.end());
  3205. Prev.swap(Reuses);
  3206. for (unsigned I = 0, E = Prev.size(); I < E; ++I)
  3207. if (Mask[I] != UndefMaskElem)
  3208. Reuses[Mask[I]] = Prev[I];
  3209. }
  3210. /// Reorders the given \p Order according to the given \p Mask. \p Order - is
  3211. /// the original order of the scalars. Procedure transforms the provided order
  3212. /// in accordance with the given \p Mask. If the resulting \p Order is just an
  3213. /// identity order, \p Order is cleared.
  3214. static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
  3215. assert(!Mask.empty() && "Expected non-empty mask.");
  3216. SmallVector<int> MaskOrder;
  3217. if (Order.empty()) {
  3218. MaskOrder.resize(Mask.size());
  3219. std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
  3220. } else {
  3221. inversePermutation(Order, MaskOrder);
  3222. }
  3223. reorderReuses(MaskOrder, Mask);
  3224. if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
  3225. Order.clear();
  3226. return;
  3227. }
  3228. Order.assign(Mask.size(), Mask.size());
  3229. for (unsigned I = 0, E = Mask.size(); I < E; ++I)
  3230. if (MaskOrder[I] != UndefMaskElem)
  3231. Order[MaskOrder[I]] = I;
  3232. fixupOrderingIndices(Order);
  3233. }
  3234. std::optional<BoUpSLP::OrdersType>
  3235. BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
  3236. assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
  3237. unsigned NumScalars = TE.Scalars.size();
  3238. OrdersType CurrentOrder(NumScalars, NumScalars);
  3239. SmallVector<int> Positions;
  3240. SmallBitVector UsedPositions(NumScalars);
  3241. const TreeEntry *STE = nullptr;
  3242. // Try to find all gathered scalars that are gets vectorized in other
  3243. // vectorize node. Here we can have only one single tree vector node to
  3244. // correctly identify order of the gathered scalars.
  3245. for (unsigned I = 0; I < NumScalars; ++I) {
  3246. Value *V = TE.Scalars[I];
  3247. if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
  3248. continue;
  3249. if (const auto *LocalSTE = getTreeEntry(V)) {
  3250. if (!STE)
  3251. STE = LocalSTE;
  3252. else if (STE != LocalSTE)
  3253. // Take the order only from the single vector node.
  3254. return std::nullopt;
  3255. unsigned Lane =
  3256. std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
  3257. if (Lane >= NumScalars)
  3258. return std::nullopt;
  3259. if (CurrentOrder[Lane] != NumScalars) {
  3260. if (Lane != I)
  3261. continue;
  3262. UsedPositions.reset(CurrentOrder[Lane]);
  3263. }
  3264. // The partial identity (where only some elements of the gather node are
  3265. // in the identity order) is good.
  3266. CurrentOrder[Lane] = I;
  3267. UsedPositions.set(I);
  3268. }
  3269. }
  3270. // Need to keep the order if we have a vector entry and at least 2 scalars or
  3271. // the vectorized entry has just 2 scalars.
  3272. if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
  3273. auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
  3274. for (unsigned I = 0; I < NumScalars; ++I)
  3275. if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
  3276. return false;
  3277. return true;
  3278. };
  3279. if (IsIdentityOrder(CurrentOrder)) {
  3280. CurrentOrder.clear();
  3281. return CurrentOrder;
  3282. }
  3283. auto *It = CurrentOrder.begin();
  3284. for (unsigned I = 0; I < NumScalars;) {
  3285. if (UsedPositions.test(I)) {
  3286. ++I;
  3287. continue;
  3288. }
  3289. if (*It == NumScalars) {
  3290. *It = I;
  3291. ++I;
  3292. }
  3293. ++It;
  3294. }
  3295. return CurrentOrder;
  3296. }
  3297. return std::nullopt;
  3298. }
  3299. namespace {
  3300. /// Tracks the state we can represent the loads in the given sequence.
  3301. enum class LoadsState { Gather, Vectorize, ScatterVectorize };
  3302. } // anonymous namespace
  3303. static bool arePointersCompatible(Value *Ptr1, Value *Ptr2,
  3304. const TargetLibraryInfo &TLI,
  3305. bool CompareOpcodes = true) {
  3306. if (getUnderlyingObject(Ptr1) != getUnderlyingObject(Ptr2))
  3307. return false;
  3308. auto *GEP1 = dyn_cast<GetElementPtrInst>(Ptr1);
  3309. if (!GEP1)
  3310. return false;
  3311. auto *GEP2 = dyn_cast<GetElementPtrInst>(Ptr2);
  3312. if (!GEP2)
  3313. return false;
  3314. return GEP1->getNumOperands() == 2 && GEP2->getNumOperands() == 2 &&
  3315. ((isConstant(GEP1->getOperand(1)) &&
  3316. isConstant(GEP2->getOperand(1))) ||
  3317. !CompareOpcodes ||
  3318. getSameOpcode({GEP1->getOperand(1), GEP2->getOperand(1)}, TLI)
  3319. .getOpcode());
  3320. }
  3321. /// Checks if the given array of loads can be represented as a vectorized,
  3322. /// scatter or just simple gather.
  3323. static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
  3324. const TargetTransformInfo &TTI,
  3325. const DataLayout &DL, ScalarEvolution &SE,
  3326. LoopInfo &LI, const TargetLibraryInfo &TLI,
  3327. SmallVectorImpl<unsigned> &Order,
  3328. SmallVectorImpl<Value *> &PointerOps) {
  3329. // Check that a vectorized load would load the same memory as a scalar
  3330. // load. For example, we don't want to vectorize loads that are smaller
  3331. // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
  3332. // treats loading/storing it as an i8 struct. If we vectorize loads/stores
  3333. // from such a struct, we read/write packed bits disagreeing with the
  3334. // unvectorized version.
  3335. Type *ScalarTy = VL0->getType();
  3336. if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
  3337. return LoadsState::Gather;
  3338. // Make sure all loads in the bundle are simple - we can't vectorize
  3339. // atomic or volatile loads.
  3340. PointerOps.clear();
  3341. PointerOps.resize(VL.size());
  3342. auto *POIter = PointerOps.begin();
  3343. for (Value *V : VL) {
  3344. auto *L = cast<LoadInst>(V);
  3345. if (!L->isSimple())
  3346. return LoadsState::Gather;
  3347. *POIter = L->getPointerOperand();
  3348. ++POIter;
  3349. }
  3350. Order.clear();
  3351. // Check the order of pointer operands or that all pointers are the same.
  3352. bool IsSorted = sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order);
  3353. if (IsSorted || all_of(PointerOps, [&](Value *P) {
  3354. return arePointersCompatible(P, PointerOps.front(), TLI);
  3355. })) {
  3356. if (IsSorted) {
  3357. Value *Ptr0;
  3358. Value *PtrN;
  3359. if (Order.empty()) {
  3360. Ptr0 = PointerOps.front();
  3361. PtrN = PointerOps.back();
  3362. } else {
  3363. Ptr0 = PointerOps[Order.front()];
  3364. PtrN = PointerOps[Order.back()];
  3365. }
  3366. std::optional<int> Diff =
  3367. getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
  3368. // Check that the sorted loads are consecutive.
  3369. if (static_cast<unsigned>(*Diff) == VL.size() - 1)
  3370. return LoadsState::Vectorize;
  3371. }
  3372. // TODO: need to improve analysis of the pointers, if not all of them are
  3373. // GEPs or have > 2 operands, we end up with a gather node, which just
  3374. // increases the cost.
  3375. Loop *L = LI.getLoopFor(cast<LoadInst>(VL0)->getParent());
  3376. bool ProfitableGatherPointers =
  3377. static_cast<unsigned>(count_if(PointerOps, [L](Value *V) {
  3378. return L && L->isLoopInvariant(V);
  3379. })) <= VL.size() / 2 && VL.size() > 2;
  3380. if (ProfitableGatherPointers || all_of(PointerOps, [IsSorted](Value *P) {
  3381. auto *GEP = dyn_cast<GetElementPtrInst>(P);
  3382. return (IsSorted && !GEP && doesNotNeedToBeScheduled(P)) ||
  3383. (GEP && GEP->getNumOperands() == 2);
  3384. })) {
  3385. Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
  3386. for (Value *V : VL)
  3387. CommonAlignment =
  3388. std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
  3389. auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
  3390. if (TTI.isLegalMaskedGather(VecTy, CommonAlignment) &&
  3391. !TTI.forceScalarizeMaskedGather(VecTy, CommonAlignment))
  3392. return LoadsState::ScatterVectorize;
  3393. }
  3394. }
  3395. return LoadsState::Gather;
  3396. }
  3397. bool clusterSortPtrAccesses(ArrayRef<Value *> VL, Type *ElemTy,
  3398. const DataLayout &DL, ScalarEvolution &SE,
  3399. SmallVectorImpl<unsigned> &SortedIndices) {
  3400. assert(llvm::all_of(
  3401. VL, [](const Value *V) { return V->getType()->isPointerTy(); }) &&
  3402. "Expected list of pointer operands.");
  3403. // Map from bases to a vector of (Ptr, Offset, OrigIdx), which we insert each
  3404. // Ptr into, sort and return the sorted indices with values next to one
  3405. // another.
  3406. MapVector<Value *, SmallVector<std::tuple<Value *, int, unsigned>>> Bases;
  3407. Bases[VL[0]].push_back(std::make_tuple(VL[0], 0U, 0U));
  3408. unsigned Cnt = 1;
  3409. for (Value *Ptr : VL.drop_front()) {
  3410. bool Found = any_of(Bases, [&](auto &Base) {
  3411. std::optional<int> Diff =
  3412. getPointersDiff(ElemTy, Base.first, ElemTy, Ptr, DL, SE,
  3413. /*StrictCheck=*/true);
  3414. if (!Diff)
  3415. return false;
  3416. Base.second.emplace_back(Ptr, *Diff, Cnt++);
  3417. return true;
  3418. });
  3419. if (!Found) {
  3420. // If we haven't found enough to usefully cluster, return early.
  3421. if (Bases.size() > VL.size() / 2 - 1)
  3422. return false;
  3423. // Not found already - add a new Base
  3424. Bases[Ptr].emplace_back(Ptr, 0, Cnt++);
  3425. }
  3426. }
  3427. // For each of the bases sort the pointers by Offset and check if any of the
  3428. // base become consecutively allocated.
  3429. bool AnyConsecutive = false;
  3430. for (auto &Base : Bases) {
  3431. auto &Vec = Base.second;
  3432. if (Vec.size() > 1) {
  3433. llvm::stable_sort(Vec, [](const std::tuple<Value *, int, unsigned> &X,
  3434. const std::tuple<Value *, int, unsigned> &Y) {
  3435. return std::get<1>(X) < std::get<1>(Y);
  3436. });
  3437. int InitialOffset = std::get<1>(Vec[0]);
  3438. AnyConsecutive |= all_of(enumerate(Vec), [InitialOffset](auto &P) {
  3439. return std::get<1>(P.value()) == int(P.index()) + InitialOffset;
  3440. });
  3441. }
  3442. }
  3443. // Fill SortedIndices array only if it looks worth-while to sort the ptrs.
  3444. SortedIndices.clear();
  3445. if (!AnyConsecutive)
  3446. return false;
  3447. for (auto &Base : Bases) {
  3448. for (auto &T : Base.second)
  3449. SortedIndices.push_back(std::get<2>(T));
  3450. }
  3451. assert(SortedIndices.size() == VL.size() &&
  3452. "Expected SortedIndices to be the size of VL");
  3453. return true;
  3454. }
  3455. std::optional<BoUpSLP::OrdersType>
  3456. BoUpSLP::findPartiallyOrderedLoads(const BoUpSLP::TreeEntry &TE) {
  3457. assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
  3458. Type *ScalarTy = TE.Scalars[0]->getType();
  3459. SmallVector<Value *> Ptrs;
  3460. Ptrs.reserve(TE.Scalars.size());
  3461. for (Value *V : TE.Scalars) {
  3462. auto *L = dyn_cast<LoadInst>(V);
  3463. if (!L || !L->isSimple())
  3464. return std::nullopt;
  3465. Ptrs.push_back(L->getPointerOperand());
  3466. }
  3467. BoUpSLP::OrdersType Order;
  3468. if (clusterSortPtrAccesses(Ptrs, ScalarTy, *DL, *SE, Order))
  3469. return Order;
  3470. return std::nullopt;
  3471. }
  3472. /// Check if two insertelement instructions are from the same buildvector.
  3473. static bool areTwoInsertFromSameBuildVector(
  3474. InsertElementInst *VU, InsertElementInst *V,
  3475. function_ref<Value *(InsertElementInst *)> GetBaseOperand) {
  3476. // Instructions must be from the same basic blocks.
  3477. if (VU->getParent() != V->getParent())
  3478. return false;
  3479. // Checks if 2 insertelements are from the same buildvector.
  3480. if (VU->getType() != V->getType())
  3481. return false;
  3482. // Multiple used inserts are separate nodes.
  3483. if (!VU->hasOneUse() && !V->hasOneUse())
  3484. return false;
  3485. auto *IE1 = VU;
  3486. auto *IE2 = V;
  3487. std::optional<unsigned> Idx1 = getInsertIndex(IE1);
  3488. std::optional<unsigned> Idx2 = getInsertIndex(IE2);
  3489. if (Idx1 == std::nullopt || Idx2 == std::nullopt)
  3490. return false;
  3491. // Go through the vector operand of insertelement instructions trying to find
  3492. // either VU as the original vector for IE2 or V as the original vector for
  3493. // IE1.
  3494. do {
  3495. if (IE2 == VU)
  3496. return VU->hasOneUse();
  3497. if (IE1 == V)
  3498. return V->hasOneUse();
  3499. if (IE1) {
  3500. if ((IE1 != VU && !IE1->hasOneUse()) ||
  3501. getInsertIndex(IE1).value_or(*Idx2) == *Idx2)
  3502. IE1 = nullptr;
  3503. else
  3504. IE1 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE1));
  3505. }
  3506. if (IE2) {
  3507. if ((IE2 != V && !IE2->hasOneUse()) ||
  3508. getInsertIndex(IE2).value_or(*Idx1) == *Idx1)
  3509. IE2 = nullptr;
  3510. else
  3511. IE2 = dyn_cast_or_null<InsertElementInst>(GetBaseOperand(IE2));
  3512. }
  3513. } while (IE1 || IE2);
  3514. return false;
  3515. }
  3516. std::optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
  3517. bool TopToBottom) {
  3518. // No need to reorder if need to shuffle reuses, still need to shuffle the
  3519. // node.
  3520. if (!TE.ReuseShuffleIndices.empty()) {
  3521. // Check if reuse shuffle indices can be improved by reordering.
  3522. // For this, check that reuse mask is "clustered", i.e. each scalar values
  3523. // is used once in each submask of size <number_of_scalars>.
  3524. // Example: 4 scalar values.
  3525. // ReuseShuffleIndices mask: 0, 1, 2, 3, 3, 2, 0, 1 - clustered.
  3526. // 0, 1, 2, 3, 3, 3, 1, 0 - not clustered, because
  3527. // element 3 is used twice in the second submask.
  3528. unsigned Sz = TE.Scalars.size();
  3529. if (!ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
  3530. Sz))
  3531. return std::nullopt;
  3532. unsigned VF = TE.getVectorFactor();
  3533. // Try build correct order for extractelement instructions.
  3534. SmallVector<int> ReusedMask(TE.ReuseShuffleIndices.begin(),
  3535. TE.ReuseShuffleIndices.end());
  3536. if (TE.getOpcode() == Instruction::ExtractElement && !TE.isAltShuffle() &&
  3537. all_of(TE.Scalars, [Sz](Value *V) {
  3538. std::optional<unsigned> Idx = getExtractIndex(cast<Instruction>(V));
  3539. return Idx && *Idx < Sz;
  3540. })) {
  3541. SmallVector<int> ReorderMask(Sz, UndefMaskElem);
  3542. if (TE.ReorderIndices.empty())
  3543. std::iota(ReorderMask.begin(), ReorderMask.end(), 0);
  3544. else
  3545. inversePermutation(TE.ReorderIndices, ReorderMask);
  3546. for (unsigned I = 0; I < VF; ++I) {
  3547. int &Idx = ReusedMask[I];
  3548. if (Idx == UndefMaskElem)
  3549. continue;
  3550. Value *V = TE.Scalars[ReorderMask[Idx]];
  3551. std::optional<unsigned> EI = getExtractIndex(cast<Instruction>(V));
  3552. Idx = std::distance(ReorderMask.begin(), find(ReorderMask, *EI));
  3553. }
  3554. }
  3555. // Build the order of the VF size, need to reorder reuses shuffles, they are
  3556. // always of VF size.
  3557. OrdersType ResOrder(VF);
  3558. std::iota(ResOrder.begin(), ResOrder.end(), 0);
  3559. auto *It = ResOrder.begin();
  3560. for (unsigned K = 0; K < VF; K += Sz) {
  3561. OrdersType CurrentOrder(TE.ReorderIndices);
  3562. SmallVector<int> SubMask{ArrayRef(ReusedMask).slice(K, Sz)};
  3563. if (SubMask.front() == UndefMaskElem)
  3564. std::iota(SubMask.begin(), SubMask.end(), 0);
  3565. reorderOrder(CurrentOrder, SubMask);
  3566. transform(CurrentOrder, It, [K](unsigned Pos) { return Pos + K; });
  3567. std::advance(It, Sz);
  3568. }
  3569. if (all_of(enumerate(ResOrder),
  3570. [](const auto &Data) { return Data.index() == Data.value(); }))
  3571. return {}; // Use identity order.
  3572. return ResOrder;
  3573. }
  3574. if (TE.State == TreeEntry::Vectorize &&
  3575. (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
  3576. (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
  3577. !TE.isAltShuffle())
  3578. return TE.ReorderIndices;
  3579. if (TE.State == TreeEntry::Vectorize && TE.getOpcode() == Instruction::PHI) {
  3580. auto PHICompare = [](llvm::Value *V1, llvm::Value *V2) {
  3581. if (!V1->hasOneUse() || !V2->hasOneUse())
  3582. return false;
  3583. auto *FirstUserOfPhi1 = cast<Instruction>(*V1->user_begin());
  3584. auto *FirstUserOfPhi2 = cast<Instruction>(*V2->user_begin());
  3585. if (auto *IE1 = dyn_cast<InsertElementInst>(FirstUserOfPhi1))
  3586. if (auto *IE2 = dyn_cast<InsertElementInst>(FirstUserOfPhi2)) {
  3587. if (!areTwoInsertFromSameBuildVector(
  3588. IE1, IE2,
  3589. [](InsertElementInst *II) { return II->getOperand(0); }))
  3590. return false;
  3591. std::optional<unsigned> Idx1 = getInsertIndex(IE1);
  3592. std::optional<unsigned> Idx2 = getInsertIndex(IE2);
  3593. if (Idx1 == std::nullopt || Idx2 == std::nullopt)
  3594. return false;
  3595. return *Idx1 < *Idx2;
  3596. }
  3597. if (auto *EE1 = dyn_cast<ExtractElementInst>(FirstUserOfPhi1))
  3598. if (auto *EE2 = dyn_cast<ExtractElementInst>(FirstUserOfPhi2)) {
  3599. if (EE1->getOperand(0) != EE2->getOperand(0))
  3600. return false;
  3601. std::optional<unsigned> Idx1 = getExtractIndex(EE1);
  3602. std::optional<unsigned> Idx2 = getExtractIndex(EE2);
  3603. if (Idx1 == std::nullopt || Idx2 == std::nullopt)
  3604. return false;
  3605. return *Idx1 < *Idx2;
  3606. }
  3607. return false;
  3608. };
  3609. auto IsIdentityOrder = [](const OrdersType &Order) {
  3610. for (unsigned Idx : seq<unsigned>(0, Order.size()))
  3611. if (Idx != Order[Idx])
  3612. return false;
  3613. return true;
  3614. };
  3615. if (!TE.ReorderIndices.empty())
  3616. return TE.ReorderIndices;
  3617. DenseMap<Value *, unsigned> PhiToId;
  3618. SmallVector<Value *, 4> Phis;
  3619. OrdersType ResOrder(TE.Scalars.size());
  3620. for (unsigned Id = 0, Sz = TE.Scalars.size(); Id < Sz; ++Id) {
  3621. PhiToId[TE.Scalars[Id]] = Id;
  3622. Phis.push_back(TE.Scalars[Id]);
  3623. }
  3624. llvm::stable_sort(Phis, PHICompare);
  3625. for (unsigned Id = 0, Sz = Phis.size(); Id < Sz; ++Id)
  3626. ResOrder[Id] = PhiToId[Phis[Id]];
  3627. if (IsIdentityOrder(ResOrder))
  3628. return {};
  3629. return ResOrder;
  3630. }
  3631. if (TE.State == TreeEntry::NeedToGather) {
  3632. // TODO: add analysis of other gather nodes with extractelement
  3633. // instructions and other values/instructions, not only undefs.
  3634. if (((TE.getOpcode() == Instruction::ExtractElement &&
  3635. !TE.isAltShuffle()) ||
  3636. (all_of(TE.Scalars,
  3637. [](Value *V) {
  3638. return isa<UndefValue, ExtractElementInst>(V);
  3639. }) &&
  3640. any_of(TE.Scalars,
  3641. [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
  3642. all_of(TE.Scalars,
  3643. [](Value *V) {
  3644. auto *EE = dyn_cast<ExtractElementInst>(V);
  3645. return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
  3646. }) &&
  3647. allSameType(TE.Scalars)) {
  3648. // Check that gather of extractelements can be represented as
  3649. // just a shuffle of a single vector.
  3650. OrdersType CurrentOrder;
  3651. bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
  3652. if (Reuse || !CurrentOrder.empty()) {
  3653. if (!CurrentOrder.empty())
  3654. fixupOrderingIndices(CurrentOrder);
  3655. return CurrentOrder;
  3656. }
  3657. }
  3658. if (std::optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
  3659. return CurrentOrder;
  3660. if (TE.Scalars.size() >= 4)
  3661. if (std::optional<OrdersType> Order = findPartiallyOrderedLoads(TE))
  3662. return Order;
  3663. }
  3664. return std::nullopt;
  3665. }
  3666. /// Checks if the given mask is a "clustered" mask with the same clusters of
  3667. /// size \p Sz, which are not identity submasks.
  3668. static bool isRepeatedNonIdentityClusteredMask(ArrayRef<int> Mask,
  3669. unsigned Sz) {
  3670. ArrayRef<int> FirstCluster = Mask.slice(0, Sz);
  3671. if (ShuffleVectorInst::isIdentityMask(FirstCluster))
  3672. return false;
  3673. for (unsigned I = Sz, E = Mask.size(); I < E; I += Sz) {
  3674. ArrayRef<int> Cluster = Mask.slice(I, Sz);
  3675. if (Cluster != FirstCluster)
  3676. return false;
  3677. }
  3678. return true;
  3679. }
  3680. void BoUpSLP::reorderNodeWithReuses(TreeEntry &TE, ArrayRef<int> Mask) const {
  3681. // Reorder reuses mask.
  3682. reorderReuses(TE.ReuseShuffleIndices, Mask);
  3683. const unsigned Sz = TE.Scalars.size();
  3684. // For vectorized and non-clustered reused no need to do anything else.
  3685. if (TE.State != TreeEntry::NeedToGather ||
  3686. !ShuffleVectorInst::isOneUseSingleSourceMask(TE.ReuseShuffleIndices,
  3687. Sz) ||
  3688. !isRepeatedNonIdentityClusteredMask(TE.ReuseShuffleIndices, Sz))
  3689. return;
  3690. SmallVector<int> NewMask;
  3691. inversePermutation(TE.ReorderIndices, NewMask);
  3692. addMask(NewMask, TE.ReuseShuffleIndices);
  3693. // Clear reorder since it is going to be applied to the new mask.
  3694. TE.ReorderIndices.clear();
  3695. // Try to improve gathered nodes with clustered reuses, if possible.
  3696. ArrayRef<int> Slice = ArrayRef(NewMask).slice(0, Sz);
  3697. SmallVector<unsigned> NewOrder(Slice.begin(), Slice.end());
  3698. inversePermutation(NewOrder, NewMask);
  3699. reorderScalars(TE.Scalars, NewMask);
  3700. // Fill the reuses mask with the identity submasks.
  3701. for (auto *It = TE.ReuseShuffleIndices.begin(),
  3702. *End = TE.ReuseShuffleIndices.end();
  3703. It != End; std::advance(It, Sz))
  3704. std::iota(It, std::next(It, Sz), 0);
  3705. }
  3706. void BoUpSLP::reorderTopToBottom() {
  3707. // Maps VF to the graph nodes.
  3708. DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
  3709. // ExtractElement gather nodes which can be vectorized and need to handle
  3710. // their ordering.
  3711. DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
  3712. // Phi nodes can have preferred ordering based on their result users
  3713. DenseMap<const TreeEntry *, OrdersType> PhisToOrders;
  3714. // AltShuffles can also have a preferred ordering that leads to fewer
  3715. // instructions, e.g., the addsub instruction in x86.
  3716. DenseMap<const TreeEntry *, OrdersType> AltShufflesToOrders;
  3717. // Maps a TreeEntry to the reorder indices of external users.
  3718. DenseMap<const TreeEntry *, SmallVector<OrdersType, 1>>
  3719. ExternalUserReorderMap;
  3720. // FIXME: Workaround for syntax error reported by MSVC buildbots.
  3721. TargetTransformInfo &TTIRef = *TTI;
  3722. // Find all reorderable nodes with the given VF.
  3723. // Currently the are vectorized stores,loads,extracts + some gathering of
  3724. // extracts.
  3725. for_each(VectorizableTree, [this, &TTIRef, &VFToOrderedEntries,
  3726. &GathersToOrders, &ExternalUserReorderMap,
  3727. &AltShufflesToOrders, &PhisToOrders](
  3728. const std::unique_ptr<TreeEntry> &TE) {
  3729. // Look for external users that will probably be vectorized.
  3730. SmallVector<OrdersType, 1> ExternalUserReorderIndices =
  3731. findExternalStoreUsersReorderIndices(TE.get());
  3732. if (!ExternalUserReorderIndices.empty()) {
  3733. VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
  3734. ExternalUserReorderMap.try_emplace(TE.get(),
  3735. std::move(ExternalUserReorderIndices));
  3736. }
  3737. // Patterns like [fadd,fsub] can be combined into a single instruction in
  3738. // x86. Reordering them into [fsub,fadd] blocks this pattern. So we need
  3739. // to take into account their order when looking for the most used order.
  3740. if (TE->isAltShuffle()) {
  3741. VectorType *VecTy =
  3742. FixedVectorType::get(TE->Scalars[0]->getType(), TE->Scalars.size());
  3743. unsigned Opcode0 = TE->getOpcode();
  3744. unsigned Opcode1 = TE->getAltOpcode();
  3745. // The opcode mask selects between the two opcodes.
  3746. SmallBitVector OpcodeMask(TE->Scalars.size(), false);
  3747. for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size()))
  3748. if (cast<Instruction>(TE->Scalars[Lane])->getOpcode() == Opcode1)
  3749. OpcodeMask.set(Lane);
  3750. // If this pattern is supported by the target then we consider the order.
  3751. if (TTIRef.isLegalAltInstr(VecTy, Opcode0, Opcode1, OpcodeMask)) {
  3752. VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
  3753. AltShufflesToOrders.try_emplace(TE.get(), OrdersType());
  3754. }
  3755. // TODO: Check the reverse order too.
  3756. }
  3757. if (std::optional<OrdersType> CurrentOrder =
  3758. getReorderingData(*TE, /*TopToBottom=*/true)) {
  3759. // Do not include ordering for nodes used in the alt opcode vectorization,
  3760. // better to reorder them during bottom-to-top stage. If follow the order
  3761. // here, it causes reordering of the whole graph though actually it is
  3762. // profitable just to reorder the subgraph that starts from the alternate
  3763. // opcode vectorization node. Such nodes already end-up with the shuffle
  3764. // instruction and it is just enough to change this shuffle rather than
  3765. // rotate the scalars for the whole graph.
  3766. unsigned Cnt = 0;
  3767. const TreeEntry *UserTE = TE.get();
  3768. while (UserTE && Cnt < RecursionMaxDepth) {
  3769. if (UserTE->UserTreeIndices.size() != 1)
  3770. break;
  3771. if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
  3772. return EI.UserTE->State == TreeEntry::Vectorize &&
  3773. EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
  3774. }))
  3775. return;
  3776. UserTE = UserTE->UserTreeIndices.back().UserTE;
  3777. ++Cnt;
  3778. }
  3779. VFToOrderedEntries[TE->getVectorFactor()].insert(TE.get());
  3780. if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
  3781. GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
  3782. if (TE->State == TreeEntry::Vectorize &&
  3783. TE->getOpcode() == Instruction::PHI)
  3784. PhisToOrders.try_emplace(TE.get(), *CurrentOrder);
  3785. }
  3786. });
  3787. // Reorder the graph nodes according to their vectorization factor.
  3788. for (unsigned VF = VectorizableTree.front()->getVectorFactor(); VF > 1;
  3789. VF /= 2) {
  3790. auto It = VFToOrderedEntries.find(VF);
  3791. if (It == VFToOrderedEntries.end())
  3792. continue;
  3793. // Try to find the most profitable order. We just are looking for the most
  3794. // used order and reorder scalar elements in the nodes according to this
  3795. // mostly used order.
  3796. ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
  3797. // All operands are reordered and used only in this node - propagate the
  3798. // most used order to the user node.
  3799. MapVector<OrdersType, unsigned,
  3800. DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
  3801. OrdersUses;
  3802. SmallPtrSet<const TreeEntry *, 4> VisitedOps;
  3803. for (const TreeEntry *OpTE : OrderedEntries) {
  3804. // No need to reorder this nodes, still need to extend and to use shuffle,
  3805. // just need to merge reordering shuffle and the reuse shuffle.
  3806. if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
  3807. continue;
  3808. // Count number of orders uses.
  3809. const auto &Order = [OpTE, &GathersToOrders, &AltShufflesToOrders,
  3810. &PhisToOrders]() -> const OrdersType & {
  3811. if (OpTE->State == TreeEntry::NeedToGather ||
  3812. !OpTE->ReuseShuffleIndices.empty()) {
  3813. auto It = GathersToOrders.find(OpTE);
  3814. if (It != GathersToOrders.end())
  3815. return It->second;
  3816. }
  3817. if (OpTE->isAltShuffle()) {
  3818. auto It = AltShufflesToOrders.find(OpTE);
  3819. if (It != AltShufflesToOrders.end())
  3820. return It->second;
  3821. }
  3822. if (OpTE->State == TreeEntry::Vectorize &&
  3823. OpTE->getOpcode() == Instruction::PHI) {
  3824. auto It = PhisToOrders.find(OpTE);
  3825. if (It != PhisToOrders.end())
  3826. return It->second;
  3827. }
  3828. return OpTE->ReorderIndices;
  3829. }();
  3830. // First consider the order of the external scalar users.
  3831. auto It = ExternalUserReorderMap.find(OpTE);
  3832. if (It != ExternalUserReorderMap.end()) {
  3833. const auto &ExternalUserReorderIndices = It->second;
  3834. // If the OpTE vector factor != number of scalars - use natural order,
  3835. // it is an attempt to reorder node with reused scalars but with
  3836. // external uses.
  3837. if (OpTE->getVectorFactor() != OpTE->Scalars.size()) {
  3838. OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
  3839. ExternalUserReorderIndices.size();
  3840. } else {
  3841. for (const OrdersType &ExtOrder : ExternalUserReorderIndices)
  3842. ++OrdersUses.insert(std::make_pair(ExtOrder, 0)).first->second;
  3843. }
  3844. // No other useful reorder data in this entry.
  3845. if (Order.empty())
  3846. continue;
  3847. }
  3848. // Stores actually store the mask, not the order, need to invert.
  3849. if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
  3850. OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
  3851. SmallVector<int> Mask;
  3852. inversePermutation(Order, Mask);
  3853. unsigned E = Order.size();
  3854. OrdersType CurrentOrder(E, E);
  3855. transform(Mask, CurrentOrder.begin(), [E](int Idx) {
  3856. return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
  3857. });
  3858. fixupOrderingIndices(CurrentOrder);
  3859. ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
  3860. } else {
  3861. ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
  3862. }
  3863. }
  3864. // Set order of the user node.
  3865. if (OrdersUses.empty())
  3866. continue;
  3867. // Choose the most used order.
  3868. ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
  3869. unsigned Cnt = OrdersUses.front().second;
  3870. for (const auto &Pair : drop_begin(OrdersUses)) {
  3871. if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
  3872. BestOrder = Pair.first;
  3873. Cnt = Pair.second;
  3874. }
  3875. }
  3876. // Set order of the user node.
  3877. if (BestOrder.empty())
  3878. continue;
  3879. SmallVector<int> Mask;
  3880. inversePermutation(BestOrder, Mask);
  3881. SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
  3882. unsigned E = BestOrder.size();
  3883. transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
  3884. return I < E ? static_cast<int>(I) : UndefMaskElem;
  3885. });
  3886. // Do an actual reordering, if profitable.
  3887. for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
  3888. // Just do the reordering for the nodes with the given VF.
  3889. if (TE->Scalars.size() != VF) {
  3890. if (TE->ReuseShuffleIndices.size() == VF) {
  3891. // Need to reorder the reuses masks of the operands with smaller VF to
  3892. // be able to find the match between the graph nodes and scalar
  3893. // operands of the given node during vectorization/cost estimation.
  3894. assert(all_of(TE->UserTreeIndices,
  3895. [VF, &TE](const EdgeInfo &EI) {
  3896. return EI.UserTE->Scalars.size() == VF ||
  3897. EI.UserTE->Scalars.size() ==
  3898. TE->Scalars.size();
  3899. }) &&
  3900. "All users must be of VF size.");
  3901. // Update ordering of the operands with the smaller VF than the given
  3902. // one.
  3903. reorderNodeWithReuses(*TE, Mask);
  3904. }
  3905. continue;
  3906. }
  3907. if (TE->State == TreeEntry::Vectorize &&
  3908. isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
  3909. InsertElementInst>(TE->getMainOp()) &&
  3910. !TE->isAltShuffle()) {
  3911. // Build correct orders for extract{element,value}, loads and
  3912. // stores.
  3913. reorderOrder(TE->ReorderIndices, Mask);
  3914. if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
  3915. TE->reorderOperands(Mask);
  3916. } else {
  3917. // Reorder the node and its operands.
  3918. TE->reorderOperands(Mask);
  3919. assert(TE->ReorderIndices.empty() &&
  3920. "Expected empty reorder sequence.");
  3921. reorderScalars(TE->Scalars, Mask);
  3922. }
  3923. if (!TE->ReuseShuffleIndices.empty()) {
  3924. // Apply reversed order to keep the original ordering of the reused
  3925. // elements to avoid extra reorder indices shuffling.
  3926. OrdersType CurrentOrder;
  3927. reorderOrder(CurrentOrder, MaskOrder);
  3928. SmallVector<int> NewReuses;
  3929. inversePermutation(CurrentOrder, NewReuses);
  3930. addMask(NewReuses, TE->ReuseShuffleIndices);
  3931. TE->ReuseShuffleIndices.swap(NewReuses);
  3932. }
  3933. }
  3934. }
  3935. }
  3936. bool BoUpSLP::canReorderOperands(
  3937. TreeEntry *UserTE, SmallVectorImpl<std::pair<unsigned, TreeEntry *>> &Edges,
  3938. ArrayRef<TreeEntry *> ReorderableGathers,
  3939. SmallVectorImpl<TreeEntry *> &GatherOps) {
  3940. for (unsigned I = 0, E = UserTE->getNumOperands(); I < E; ++I) {
  3941. if (any_of(Edges, [I](const std::pair<unsigned, TreeEntry *> &OpData) {
  3942. return OpData.first == I &&
  3943. OpData.second->State == TreeEntry::Vectorize;
  3944. }))
  3945. continue;
  3946. if (TreeEntry *TE = getVectorizedOperand(UserTE, I)) {
  3947. // Do not reorder if operand node is used by many user nodes.
  3948. if (any_of(TE->UserTreeIndices,
  3949. [UserTE](const EdgeInfo &EI) { return EI.UserTE != UserTE; }))
  3950. return false;
  3951. // Add the node to the list of the ordered nodes with the identity
  3952. // order.
  3953. Edges.emplace_back(I, TE);
  3954. // Add ScatterVectorize nodes to the list of operands, where just
  3955. // reordering of the scalars is required. Similar to the gathers, so
  3956. // simply add to the list of gathered ops.
  3957. // If there are reused scalars, process this node as a regular vectorize
  3958. // node, just reorder reuses mask.
  3959. if (TE->State != TreeEntry::Vectorize && TE->ReuseShuffleIndices.empty())
  3960. GatherOps.push_back(TE);
  3961. continue;
  3962. }
  3963. TreeEntry *Gather = nullptr;
  3964. if (count_if(ReorderableGathers,
  3965. [&Gather, UserTE, I](TreeEntry *TE) {
  3966. assert(TE->State != TreeEntry::Vectorize &&
  3967. "Only non-vectorized nodes are expected.");
  3968. if (any_of(TE->UserTreeIndices,
  3969. [UserTE, I](const EdgeInfo &EI) {
  3970. return EI.UserTE == UserTE && EI.EdgeIdx == I;
  3971. })) {
  3972. assert(TE->isSame(UserTE->getOperand(I)) &&
  3973. "Operand entry does not match operands.");
  3974. Gather = TE;
  3975. return true;
  3976. }
  3977. return false;
  3978. }) > 1 &&
  3979. !all_of(UserTE->getOperand(I), isConstant))
  3980. return false;
  3981. if (Gather)
  3982. GatherOps.push_back(Gather);
  3983. }
  3984. return true;
  3985. }
  3986. void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
  3987. SetVector<TreeEntry *> OrderedEntries;
  3988. DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
  3989. // Find all reorderable leaf nodes with the given VF.
  3990. // Currently the are vectorized loads,extracts without alternate operands +
  3991. // some gathering of extracts.
  3992. SmallVector<TreeEntry *> NonVectorized;
  3993. for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
  3994. &NonVectorized](
  3995. const std::unique_ptr<TreeEntry> &TE) {
  3996. if (TE->State != TreeEntry::Vectorize)
  3997. NonVectorized.push_back(TE.get());
  3998. if (std::optional<OrdersType> CurrentOrder =
  3999. getReorderingData(*TE, /*TopToBottom=*/false)) {
  4000. OrderedEntries.insert(TE.get());
  4001. if (TE->State != TreeEntry::Vectorize || !TE->ReuseShuffleIndices.empty())
  4002. GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
  4003. }
  4004. });
  4005. // 1. Propagate order to the graph nodes, which use only reordered nodes.
  4006. // I.e., if the node has operands, that are reordered, try to make at least
  4007. // one operand order in the natural order and reorder others + reorder the
  4008. // user node itself.
  4009. SmallPtrSet<const TreeEntry *, 4> Visited;
  4010. while (!OrderedEntries.empty()) {
  4011. // 1. Filter out only reordered nodes.
  4012. // 2. If the entry has multiple uses - skip it and jump to the next node.
  4013. DenseMap<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
  4014. SmallVector<TreeEntry *> Filtered;
  4015. for (TreeEntry *TE : OrderedEntries) {
  4016. if (!(TE->State == TreeEntry::Vectorize ||
  4017. (TE->State == TreeEntry::NeedToGather &&
  4018. GathersToOrders.count(TE))) ||
  4019. TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
  4020. !all_of(drop_begin(TE->UserTreeIndices),
  4021. [TE](const EdgeInfo &EI) {
  4022. return EI.UserTE == TE->UserTreeIndices.front().UserTE;
  4023. }) ||
  4024. !Visited.insert(TE).second) {
  4025. Filtered.push_back(TE);
  4026. continue;
  4027. }
  4028. // Build a map between user nodes and their operands order to speedup
  4029. // search. The graph currently does not provide this dependency directly.
  4030. for (EdgeInfo &EI : TE->UserTreeIndices) {
  4031. TreeEntry *UserTE = EI.UserTE;
  4032. auto It = Users.find(UserTE);
  4033. if (It == Users.end())
  4034. It = Users.insert({UserTE, {}}).first;
  4035. It->second.emplace_back(EI.EdgeIdx, TE);
  4036. }
  4037. }
  4038. // Erase filtered entries.
  4039. for_each(Filtered,
  4040. [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
  4041. SmallVector<
  4042. std::pair<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>>>
  4043. UsersVec(Users.begin(), Users.end());
  4044. sort(UsersVec, [](const auto &Data1, const auto &Data2) {
  4045. return Data1.first->Idx > Data2.first->Idx;
  4046. });
  4047. for (auto &Data : UsersVec) {
  4048. // Check that operands are used only in the User node.
  4049. SmallVector<TreeEntry *> GatherOps;
  4050. if (!canReorderOperands(Data.first, Data.second, NonVectorized,
  4051. GatherOps)) {
  4052. for_each(Data.second,
  4053. [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
  4054. OrderedEntries.remove(Op.second);
  4055. });
  4056. continue;
  4057. }
  4058. // All operands are reordered and used only in this node - propagate the
  4059. // most used order to the user node.
  4060. MapVector<OrdersType, unsigned,
  4061. DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
  4062. OrdersUses;
  4063. // Do the analysis for each tree entry only once, otherwise the order of
  4064. // the same node my be considered several times, though might be not
  4065. // profitable.
  4066. SmallPtrSet<const TreeEntry *, 4> VisitedOps;
  4067. SmallPtrSet<const TreeEntry *, 4> VisitedUsers;
  4068. for (const auto &Op : Data.second) {
  4069. TreeEntry *OpTE = Op.second;
  4070. if (!VisitedOps.insert(OpTE).second)
  4071. continue;
  4072. if (!OpTE->ReuseShuffleIndices.empty() && !GathersToOrders.count(OpTE))
  4073. continue;
  4074. const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
  4075. if (OpTE->State == TreeEntry::NeedToGather ||
  4076. !OpTE->ReuseShuffleIndices.empty())
  4077. return GathersToOrders.find(OpTE)->second;
  4078. return OpTE->ReorderIndices;
  4079. }();
  4080. unsigned NumOps = count_if(
  4081. Data.second, [OpTE](const std::pair<unsigned, TreeEntry *> &P) {
  4082. return P.second == OpTE;
  4083. });
  4084. // Stores actually store the mask, not the order, need to invert.
  4085. if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
  4086. OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
  4087. SmallVector<int> Mask;
  4088. inversePermutation(Order, Mask);
  4089. unsigned E = Order.size();
  4090. OrdersType CurrentOrder(E, E);
  4091. transform(Mask, CurrentOrder.begin(), [E](int Idx) {
  4092. return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
  4093. });
  4094. fixupOrderingIndices(CurrentOrder);
  4095. OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second +=
  4096. NumOps;
  4097. } else {
  4098. OrdersUses.insert(std::make_pair(Order, 0)).first->second += NumOps;
  4099. }
  4100. auto Res = OrdersUses.insert(std::make_pair(OrdersType(), 0));
  4101. const auto &&AllowsReordering = [IgnoreReorder, &GathersToOrders](
  4102. const TreeEntry *TE) {
  4103. if (!TE->ReorderIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
  4104. (TE->State == TreeEntry::Vectorize && TE->isAltShuffle()) ||
  4105. (IgnoreReorder && TE->Idx == 0))
  4106. return true;
  4107. if (TE->State == TreeEntry::NeedToGather) {
  4108. auto It = GathersToOrders.find(TE);
  4109. if (It != GathersToOrders.end())
  4110. return !It->second.empty();
  4111. return true;
  4112. }
  4113. return false;
  4114. };
  4115. for (const EdgeInfo &EI : OpTE->UserTreeIndices) {
  4116. TreeEntry *UserTE = EI.UserTE;
  4117. if (!VisitedUsers.insert(UserTE).second)
  4118. continue;
  4119. // May reorder user node if it requires reordering, has reused
  4120. // scalars, is an alternate op vectorize node or its op nodes require
  4121. // reordering.
  4122. if (AllowsReordering(UserTE))
  4123. continue;
  4124. // Check if users allow reordering.
  4125. // Currently look up just 1 level of operands to avoid increase of
  4126. // the compile time.
  4127. // Profitable to reorder if definitely more operands allow
  4128. // reordering rather than those with natural order.
  4129. ArrayRef<std::pair<unsigned, TreeEntry *>> Ops = Users[UserTE];
  4130. if (static_cast<unsigned>(count_if(
  4131. Ops, [UserTE, &AllowsReordering](
  4132. const std::pair<unsigned, TreeEntry *> &Op) {
  4133. return AllowsReordering(Op.second) &&
  4134. all_of(Op.second->UserTreeIndices,
  4135. [UserTE](const EdgeInfo &EI) {
  4136. return EI.UserTE == UserTE;
  4137. });
  4138. })) <= Ops.size() / 2)
  4139. ++Res.first->second;
  4140. }
  4141. }
  4142. // If no orders - skip current nodes and jump to the next one, if any.
  4143. if (OrdersUses.empty()) {
  4144. for_each(Data.second,
  4145. [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
  4146. OrderedEntries.remove(Op.second);
  4147. });
  4148. continue;
  4149. }
  4150. // Choose the best order.
  4151. ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
  4152. unsigned Cnt = OrdersUses.front().second;
  4153. for (const auto &Pair : drop_begin(OrdersUses)) {
  4154. if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
  4155. BestOrder = Pair.first;
  4156. Cnt = Pair.second;
  4157. }
  4158. }
  4159. // Set order of the user node (reordering of operands and user nodes).
  4160. if (BestOrder.empty()) {
  4161. for_each(Data.second,
  4162. [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
  4163. OrderedEntries.remove(Op.second);
  4164. });
  4165. continue;
  4166. }
  4167. // Erase operands from OrderedEntries list and adjust their orders.
  4168. VisitedOps.clear();
  4169. SmallVector<int> Mask;
  4170. inversePermutation(BestOrder, Mask);
  4171. SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
  4172. unsigned E = BestOrder.size();
  4173. transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
  4174. return I < E ? static_cast<int>(I) : UndefMaskElem;
  4175. });
  4176. for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
  4177. TreeEntry *TE = Op.second;
  4178. OrderedEntries.remove(TE);
  4179. if (!VisitedOps.insert(TE).second)
  4180. continue;
  4181. if (TE->ReuseShuffleIndices.size() == BestOrder.size()) {
  4182. reorderNodeWithReuses(*TE, Mask);
  4183. continue;
  4184. }
  4185. // Gathers are processed separately.
  4186. if (TE->State != TreeEntry::Vectorize)
  4187. continue;
  4188. assert((BestOrder.size() == TE->ReorderIndices.size() ||
  4189. TE->ReorderIndices.empty()) &&
  4190. "Non-matching sizes of user/operand entries.");
  4191. reorderOrder(TE->ReorderIndices, Mask);
  4192. if (IgnoreReorder && TE == VectorizableTree.front().get())
  4193. IgnoreReorder = false;
  4194. }
  4195. // For gathers just need to reorder its scalars.
  4196. for (TreeEntry *Gather : GatherOps) {
  4197. assert(Gather->ReorderIndices.empty() &&
  4198. "Unexpected reordering of gathers.");
  4199. if (!Gather->ReuseShuffleIndices.empty()) {
  4200. // Just reorder reuses indices.
  4201. reorderReuses(Gather->ReuseShuffleIndices, Mask);
  4202. continue;
  4203. }
  4204. reorderScalars(Gather->Scalars, Mask);
  4205. OrderedEntries.remove(Gather);
  4206. }
  4207. // Reorder operands of the user node and set the ordering for the user
  4208. // node itself.
  4209. if (Data.first->State != TreeEntry::Vectorize ||
  4210. !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
  4211. Data.first->getMainOp()) ||
  4212. Data.first->isAltShuffle())
  4213. Data.first->reorderOperands(Mask);
  4214. if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
  4215. Data.first->isAltShuffle()) {
  4216. reorderScalars(Data.first->Scalars, Mask);
  4217. reorderOrder(Data.first->ReorderIndices, MaskOrder);
  4218. if (Data.first->ReuseShuffleIndices.empty() &&
  4219. !Data.first->ReorderIndices.empty() &&
  4220. !Data.first->isAltShuffle()) {
  4221. // Insert user node to the list to try to sink reordering deeper in
  4222. // the graph.
  4223. OrderedEntries.insert(Data.first);
  4224. }
  4225. } else {
  4226. reorderOrder(Data.first->ReorderIndices, Mask);
  4227. }
  4228. }
  4229. }
  4230. // If the reordering is unnecessary, just remove the reorder.
  4231. if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
  4232. VectorizableTree.front()->ReuseShuffleIndices.empty())
  4233. VectorizableTree.front()->ReorderIndices.clear();
  4234. }
  4235. void BoUpSLP::buildExternalUses(
  4236. const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
  4237. // Collect the values that we need to extract from the tree.
  4238. for (auto &TEPtr : VectorizableTree) {
  4239. TreeEntry *Entry = TEPtr.get();
  4240. // No need to handle users of gathered values.
  4241. if (Entry->State == TreeEntry::NeedToGather)
  4242. continue;
  4243. // For each lane:
  4244. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  4245. Value *Scalar = Entry->Scalars[Lane];
  4246. int FoundLane = Entry->findLaneForValue(Scalar);
  4247. // Check if the scalar is externally used as an extra arg.
  4248. auto ExtI = ExternallyUsedValues.find(Scalar);
  4249. if (ExtI != ExternallyUsedValues.end()) {
  4250. LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
  4251. << Lane << " from " << *Scalar << ".\n");
  4252. ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
  4253. }
  4254. for (User *U : Scalar->users()) {
  4255. LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
  4256. Instruction *UserInst = dyn_cast<Instruction>(U);
  4257. if (!UserInst)
  4258. continue;
  4259. if (isDeleted(UserInst))
  4260. continue;
  4261. // Skip in-tree scalars that become vectors
  4262. if (TreeEntry *UseEntry = getTreeEntry(U)) {
  4263. Value *UseScalar = UseEntry->Scalars[0];
  4264. // Some in-tree scalars will remain as scalar in vectorized
  4265. // instructions. If that is the case, the one in Lane 0 will
  4266. // be used.
  4267. if (UseScalar != U ||
  4268. UseEntry->State == TreeEntry::ScatterVectorize ||
  4269. !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
  4270. LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
  4271. << ".\n");
  4272. assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
  4273. continue;
  4274. }
  4275. }
  4276. // Ignore users in the user ignore list.
  4277. if (UserIgnoreList && UserIgnoreList->contains(UserInst))
  4278. continue;
  4279. LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
  4280. << Lane << " from " << *Scalar << ".\n");
  4281. ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
  4282. }
  4283. }
  4284. }
  4285. }
  4286. DenseMap<Value *, SmallVector<StoreInst *, 4>>
  4287. BoUpSLP::collectUserStores(const BoUpSLP::TreeEntry *TE) const {
  4288. DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap;
  4289. for (unsigned Lane : seq<unsigned>(0, TE->Scalars.size())) {
  4290. Value *V = TE->Scalars[Lane];
  4291. // To save compilation time we don't visit if we have too many users.
  4292. static constexpr unsigned UsersLimit = 4;
  4293. if (V->hasNUsesOrMore(UsersLimit))
  4294. break;
  4295. // Collect stores per pointer object.
  4296. for (User *U : V->users()) {
  4297. auto *SI = dyn_cast<StoreInst>(U);
  4298. if (SI == nullptr || !SI->isSimple() ||
  4299. !isValidElementType(SI->getValueOperand()->getType()))
  4300. continue;
  4301. // Skip entry if already
  4302. if (getTreeEntry(U))
  4303. continue;
  4304. Value *Ptr = getUnderlyingObject(SI->getPointerOperand());
  4305. auto &StoresVec = PtrToStoresMap[Ptr];
  4306. // For now just keep one store per pointer object per lane.
  4307. // TODO: Extend this to support multiple stores per pointer per lane
  4308. if (StoresVec.size() > Lane)
  4309. continue;
  4310. // Skip if in different BBs.
  4311. if (!StoresVec.empty() &&
  4312. SI->getParent() != StoresVec.back()->getParent())
  4313. continue;
  4314. // Make sure that the stores are of the same type.
  4315. if (!StoresVec.empty() &&
  4316. SI->getValueOperand()->getType() !=
  4317. StoresVec.back()->getValueOperand()->getType())
  4318. continue;
  4319. StoresVec.push_back(SI);
  4320. }
  4321. }
  4322. return PtrToStoresMap;
  4323. }
  4324. bool BoUpSLP::canFormVector(const SmallVector<StoreInst *, 4> &StoresVec,
  4325. OrdersType &ReorderIndices) const {
  4326. // We check whether the stores in StoreVec can form a vector by sorting them
  4327. // and checking whether they are consecutive.
  4328. // To avoid calling getPointersDiff() while sorting we create a vector of
  4329. // pairs {store, offset from first} and sort this instead.
  4330. SmallVector<std::pair<StoreInst *, int>, 4> StoreOffsetVec(StoresVec.size());
  4331. StoreInst *S0 = StoresVec[0];
  4332. StoreOffsetVec[0] = {S0, 0};
  4333. Type *S0Ty = S0->getValueOperand()->getType();
  4334. Value *S0Ptr = S0->getPointerOperand();
  4335. for (unsigned Idx : seq<unsigned>(1, StoresVec.size())) {
  4336. StoreInst *SI = StoresVec[Idx];
  4337. std::optional<int> Diff =
  4338. getPointersDiff(S0Ty, S0Ptr, SI->getValueOperand()->getType(),
  4339. SI->getPointerOperand(), *DL, *SE,
  4340. /*StrictCheck=*/true);
  4341. // We failed to compare the pointers so just abandon this StoresVec.
  4342. if (!Diff)
  4343. return false;
  4344. StoreOffsetVec[Idx] = {StoresVec[Idx], *Diff};
  4345. }
  4346. // Sort the vector based on the pointers. We create a copy because we may
  4347. // need the original later for calculating the reorder (shuffle) indices.
  4348. stable_sort(StoreOffsetVec, [](const std::pair<StoreInst *, int> &Pair1,
  4349. const std::pair<StoreInst *, int> &Pair2) {
  4350. int Offset1 = Pair1.second;
  4351. int Offset2 = Pair2.second;
  4352. return Offset1 < Offset2;
  4353. });
  4354. // Check if the stores are consecutive by checking if their difference is 1.
  4355. for (unsigned Idx : seq<unsigned>(1, StoreOffsetVec.size()))
  4356. if (StoreOffsetVec[Idx].second != StoreOffsetVec[Idx-1].second + 1)
  4357. return false;
  4358. // Calculate the shuffle indices according to their offset against the sorted
  4359. // StoreOffsetVec.
  4360. ReorderIndices.reserve(StoresVec.size());
  4361. for (StoreInst *SI : StoresVec) {
  4362. unsigned Idx = find_if(StoreOffsetVec,
  4363. [SI](const std::pair<StoreInst *, int> &Pair) {
  4364. return Pair.first == SI;
  4365. }) -
  4366. StoreOffsetVec.begin();
  4367. ReorderIndices.push_back(Idx);
  4368. }
  4369. // Identity order (e.g., {0,1,2,3}) is modeled as an empty OrdersType in
  4370. // reorderTopToBottom() and reorderBottomToTop(), so we are following the
  4371. // same convention here.
  4372. auto IsIdentityOrder = [](const OrdersType &Order) {
  4373. for (unsigned Idx : seq<unsigned>(0, Order.size()))
  4374. if (Idx != Order[Idx])
  4375. return false;
  4376. return true;
  4377. };
  4378. if (IsIdentityOrder(ReorderIndices))
  4379. ReorderIndices.clear();
  4380. return true;
  4381. }
  4382. #ifndef NDEBUG
  4383. LLVM_DUMP_METHOD static void dumpOrder(const BoUpSLP::OrdersType &Order) {
  4384. for (unsigned Idx : Order)
  4385. dbgs() << Idx << ", ";
  4386. dbgs() << "\n";
  4387. }
  4388. #endif
  4389. SmallVector<BoUpSLP::OrdersType, 1>
  4390. BoUpSLP::findExternalStoreUsersReorderIndices(TreeEntry *TE) const {
  4391. unsigned NumLanes = TE->Scalars.size();
  4392. DenseMap<Value *, SmallVector<StoreInst *, 4>> PtrToStoresMap =
  4393. collectUserStores(TE);
  4394. // Holds the reorder indices for each candidate store vector that is a user of
  4395. // the current TreeEntry.
  4396. SmallVector<OrdersType, 1> ExternalReorderIndices;
  4397. // Now inspect the stores collected per pointer and look for vectorization
  4398. // candidates. For each candidate calculate the reorder index vector and push
  4399. // it into `ExternalReorderIndices`
  4400. for (const auto &Pair : PtrToStoresMap) {
  4401. auto &StoresVec = Pair.second;
  4402. // If we have fewer than NumLanes stores, then we can't form a vector.
  4403. if (StoresVec.size() != NumLanes)
  4404. continue;
  4405. // If the stores are not consecutive then abandon this StoresVec.
  4406. OrdersType ReorderIndices;
  4407. if (!canFormVector(StoresVec, ReorderIndices))
  4408. continue;
  4409. // We now know that the scalars in StoresVec can form a vector instruction,
  4410. // so set the reorder indices.
  4411. ExternalReorderIndices.push_back(ReorderIndices);
  4412. }
  4413. return ExternalReorderIndices;
  4414. }
  4415. void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
  4416. const SmallDenseSet<Value *> &UserIgnoreLst) {
  4417. deleteTree();
  4418. UserIgnoreList = &UserIgnoreLst;
  4419. if (!allSameType(Roots))
  4420. return;
  4421. buildTree_rec(Roots, 0, EdgeInfo());
  4422. }
  4423. void BoUpSLP::buildTree(ArrayRef<Value *> Roots) {
  4424. deleteTree();
  4425. if (!allSameType(Roots))
  4426. return;
  4427. buildTree_rec(Roots, 0, EdgeInfo());
  4428. }
  4429. /// \return true if the specified list of values has only one instruction that
  4430. /// requires scheduling, false otherwise.
  4431. #ifndef NDEBUG
  4432. static bool needToScheduleSingleInstruction(ArrayRef<Value *> VL) {
  4433. Value *NeedsScheduling = nullptr;
  4434. for (Value *V : VL) {
  4435. if (doesNotNeedToBeScheduled(V))
  4436. continue;
  4437. if (!NeedsScheduling) {
  4438. NeedsScheduling = V;
  4439. continue;
  4440. }
  4441. return false;
  4442. }
  4443. return NeedsScheduling;
  4444. }
  4445. #endif
  4446. /// Generates key/subkey pair for the given value to provide effective sorting
  4447. /// of the values and better detection of the vectorizable values sequences. The
  4448. /// keys/subkeys can be used for better sorting of the values themselves (keys)
  4449. /// and in values subgroups (subkeys).
  4450. static std::pair<size_t, size_t> generateKeySubkey(
  4451. Value *V, const TargetLibraryInfo *TLI,
  4452. function_ref<hash_code(size_t, LoadInst *)> LoadsSubkeyGenerator,
  4453. bool AllowAlternate) {
  4454. hash_code Key = hash_value(V->getValueID() + 2);
  4455. hash_code SubKey = hash_value(0);
  4456. // Sort the loads by the distance between the pointers.
  4457. if (auto *LI = dyn_cast<LoadInst>(V)) {
  4458. Key = hash_combine(LI->getType(), hash_value(Instruction::Load), Key);
  4459. if (LI->isSimple())
  4460. SubKey = hash_value(LoadsSubkeyGenerator(Key, LI));
  4461. else
  4462. Key = SubKey = hash_value(LI);
  4463. } else if (isVectorLikeInstWithConstOps(V)) {
  4464. // Sort extracts by the vector operands.
  4465. if (isa<ExtractElementInst, UndefValue>(V))
  4466. Key = hash_value(Value::UndefValueVal + 1);
  4467. if (auto *EI = dyn_cast<ExtractElementInst>(V)) {
  4468. if (!isUndefVector(EI->getVectorOperand()).all() &&
  4469. !isa<UndefValue>(EI->getIndexOperand()))
  4470. SubKey = hash_value(EI->getVectorOperand());
  4471. }
  4472. } else if (auto *I = dyn_cast<Instruction>(V)) {
  4473. // Sort other instructions just by the opcodes except for CMPInst.
  4474. // For CMP also sort by the predicate kind.
  4475. if ((isa<BinaryOperator, CastInst>(I)) &&
  4476. isValidForAlternation(I->getOpcode())) {
  4477. if (AllowAlternate)
  4478. Key = hash_value(isa<BinaryOperator>(I) ? 1 : 0);
  4479. else
  4480. Key = hash_combine(hash_value(I->getOpcode()), Key);
  4481. SubKey = hash_combine(
  4482. hash_value(I->getOpcode()), hash_value(I->getType()),
  4483. hash_value(isa<BinaryOperator>(I)
  4484. ? I->getType()
  4485. : cast<CastInst>(I)->getOperand(0)->getType()));
  4486. // For casts, look through the only operand to improve compile time.
  4487. if (isa<CastInst>(I)) {
  4488. std::pair<size_t, size_t> OpVals =
  4489. generateKeySubkey(I->getOperand(0), TLI, LoadsSubkeyGenerator,
  4490. /*AllowAlternate=*/true);
  4491. Key = hash_combine(OpVals.first, Key);
  4492. SubKey = hash_combine(OpVals.first, SubKey);
  4493. }
  4494. } else if (auto *CI = dyn_cast<CmpInst>(I)) {
  4495. CmpInst::Predicate Pred = CI->getPredicate();
  4496. if (CI->isCommutative())
  4497. Pred = std::min(Pred, CmpInst::getInversePredicate(Pred));
  4498. CmpInst::Predicate SwapPred = CmpInst::getSwappedPredicate(Pred);
  4499. SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Pred),
  4500. hash_value(SwapPred),
  4501. hash_value(CI->getOperand(0)->getType()));
  4502. } else if (auto *Call = dyn_cast<CallInst>(I)) {
  4503. Intrinsic::ID ID = getVectorIntrinsicIDForCall(Call, TLI);
  4504. if (isTriviallyVectorizable(ID)) {
  4505. SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(ID));
  4506. } else if (!VFDatabase(*Call).getMappings(*Call).empty()) {
  4507. SubKey = hash_combine(hash_value(I->getOpcode()),
  4508. hash_value(Call->getCalledFunction()));
  4509. } else {
  4510. Key = hash_combine(hash_value(Call), Key);
  4511. SubKey = hash_combine(hash_value(I->getOpcode()), hash_value(Call));
  4512. }
  4513. for (const CallBase::BundleOpInfo &Op : Call->bundle_op_infos())
  4514. SubKey = hash_combine(hash_value(Op.Begin), hash_value(Op.End),
  4515. hash_value(Op.Tag), SubKey);
  4516. } else if (auto *Gep = dyn_cast<GetElementPtrInst>(I)) {
  4517. if (Gep->getNumOperands() == 2 && isa<ConstantInt>(Gep->getOperand(1)))
  4518. SubKey = hash_value(Gep->getPointerOperand());
  4519. else
  4520. SubKey = hash_value(Gep);
  4521. } else if (BinaryOperator::isIntDivRem(I->getOpcode()) &&
  4522. !isa<ConstantInt>(I->getOperand(1))) {
  4523. // Do not try to vectorize instructions with potentially high cost.
  4524. SubKey = hash_value(I);
  4525. } else {
  4526. SubKey = hash_value(I->getOpcode());
  4527. }
  4528. Key = hash_combine(hash_value(I->getParent()), Key);
  4529. }
  4530. return std::make_pair(Key, SubKey);
  4531. }
  4532. /// Checks if the specified instruction \p I is an alternate operation for
  4533. /// the given \p MainOp and \p AltOp instructions.
  4534. static bool isAlternateInstruction(const Instruction *I,
  4535. const Instruction *MainOp,
  4536. const Instruction *AltOp,
  4537. const TargetLibraryInfo &TLI);
  4538. void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
  4539. const EdgeInfo &UserTreeIdx) {
  4540. assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
  4541. SmallVector<int> ReuseShuffleIndicies;
  4542. SmallVector<Value *> UniqueValues;
  4543. auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
  4544. &UserTreeIdx,
  4545. this](const InstructionsState &S) {
  4546. // Check that every instruction appears once in this bundle.
  4547. DenseMap<Value *, unsigned> UniquePositions(VL.size());
  4548. for (Value *V : VL) {
  4549. if (isConstant(V)) {
  4550. ReuseShuffleIndicies.emplace_back(
  4551. isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
  4552. UniqueValues.emplace_back(V);
  4553. continue;
  4554. }
  4555. auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
  4556. ReuseShuffleIndicies.emplace_back(Res.first->second);
  4557. if (Res.second)
  4558. UniqueValues.emplace_back(V);
  4559. }
  4560. size_t NumUniqueScalarValues = UniqueValues.size();
  4561. if (NumUniqueScalarValues == VL.size()) {
  4562. ReuseShuffleIndicies.clear();
  4563. } else {
  4564. LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
  4565. if (NumUniqueScalarValues <= 1 ||
  4566. (UniquePositions.size() == 1 && all_of(UniqueValues,
  4567. [](Value *V) {
  4568. return isa<UndefValue>(V) ||
  4569. !isConstant(V);
  4570. })) ||
  4571. !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
  4572. LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
  4573. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
  4574. return false;
  4575. }
  4576. VL = UniqueValues;
  4577. }
  4578. return true;
  4579. };
  4580. InstructionsState S = getSameOpcode(VL, *TLI);
  4581. // Gather if we hit the RecursionMaxDepth, unless this is a load (or z/sext of
  4582. // a load), in which case peek through to include it in the tree, without
  4583. // ballooning over-budget.
  4584. if (Depth >= RecursionMaxDepth &&
  4585. !(S.MainOp && isa<Instruction>(S.MainOp) && S.MainOp == S.AltOp &&
  4586. VL.size() >= 4 &&
  4587. (match(S.MainOp, m_Load(m_Value())) || all_of(VL, [&S](const Value *I) {
  4588. return match(I,
  4589. m_OneUse(m_ZExtOrSExt(m_OneUse(m_Load(m_Value()))))) &&
  4590. cast<Instruction>(I)->getOpcode() ==
  4591. cast<Instruction>(S.MainOp)->getOpcode();
  4592. })))) {
  4593. LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
  4594. if (TryToFindDuplicates(S))
  4595. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4596. ReuseShuffleIndicies);
  4597. return;
  4598. }
  4599. // Don't handle scalable vectors
  4600. if (S.getOpcode() == Instruction::ExtractElement &&
  4601. isa<ScalableVectorType>(
  4602. cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
  4603. LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
  4604. if (TryToFindDuplicates(S))
  4605. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4606. ReuseShuffleIndicies);
  4607. return;
  4608. }
  4609. // Don't handle vectors.
  4610. if (S.OpValue->getType()->isVectorTy() &&
  4611. !isa<InsertElementInst>(S.OpValue)) {
  4612. LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
  4613. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
  4614. return;
  4615. }
  4616. if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
  4617. if (SI->getValueOperand()->getType()->isVectorTy()) {
  4618. LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
  4619. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
  4620. return;
  4621. }
  4622. // If all of the operands are identical or constant we have a simple solution.
  4623. // If we deal with insert/extract instructions, they all must have constant
  4624. // indices, otherwise we should gather them, not try to vectorize.
  4625. // If alternate op node with 2 elements with gathered operands - do not
  4626. // vectorize.
  4627. auto &&NotProfitableForVectorization = [&S, this,
  4628. Depth](ArrayRef<Value *> VL) {
  4629. if (!S.getOpcode() || !S.isAltShuffle() || VL.size() > 2)
  4630. return false;
  4631. if (VectorizableTree.size() < MinTreeSize)
  4632. return false;
  4633. if (Depth >= RecursionMaxDepth - 1)
  4634. return true;
  4635. // Check if all operands are extracts, part of vector node or can build a
  4636. // regular vectorize node.
  4637. SmallVector<unsigned, 2> InstsCount(VL.size(), 0);
  4638. for (Value *V : VL) {
  4639. auto *I = cast<Instruction>(V);
  4640. InstsCount.push_back(count_if(I->operand_values(), [](Value *Op) {
  4641. return isa<Instruction>(Op) || isVectorLikeInstWithConstOps(Op);
  4642. }));
  4643. }
  4644. bool IsCommutative = isCommutative(S.MainOp) || isCommutative(S.AltOp);
  4645. if ((IsCommutative &&
  4646. std::accumulate(InstsCount.begin(), InstsCount.end(), 0) < 2) ||
  4647. (!IsCommutative &&
  4648. all_of(InstsCount, [](unsigned ICnt) { return ICnt < 2; })))
  4649. return true;
  4650. assert(VL.size() == 2 && "Expected only 2 alternate op instructions.");
  4651. SmallVector<SmallVector<std::pair<Value *, Value *>>> Candidates;
  4652. auto *I1 = cast<Instruction>(VL.front());
  4653. auto *I2 = cast<Instruction>(VL.back());
  4654. for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
  4655. Candidates.emplace_back().emplace_back(I1->getOperand(Op),
  4656. I2->getOperand(Op));
  4657. if (static_cast<unsigned>(count_if(
  4658. Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
  4659. return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
  4660. })) >= S.MainOp->getNumOperands() / 2)
  4661. return false;
  4662. if (S.MainOp->getNumOperands() > 2)
  4663. return true;
  4664. if (IsCommutative) {
  4665. // Check permuted operands.
  4666. Candidates.clear();
  4667. for (int Op = 0, E = S.MainOp->getNumOperands(); Op < E; ++Op)
  4668. Candidates.emplace_back().emplace_back(I1->getOperand(Op),
  4669. I2->getOperand((Op + 1) % E));
  4670. if (any_of(
  4671. Candidates, [this](ArrayRef<std::pair<Value *, Value *>> Cand) {
  4672. return findBestRootPair(Cand, LookAheadHeuristics::ScoreSplat);
  4673. }))
  4674. return false;
  4675. }
  4676. return true;
  4677. };
  4678. SmallVector<unsigned> SortedIndices;
  4679. BasicBlock *BB = nullptr;
  4680. bool IsScatterVectorizeUserTE =
  4681. UserTreeIdx.UserTE &&
  4682. UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize;
  4683. bool AreAllSameInsts =
  4684. (S.getOpcode() && allSameBlock(VL)) ||
  4685. (S.OpValue->getType()->isPointerTy() && IsScatterVectorizeUserTE &&
  4686. VL.size() > 2 &&
  4687. all_of(VL,
  4688. [&BB](Value *V) {
  4689. auto *I = dyn_cast<GetElementPtrInst>(V);
  4690. if (!I)
  4691. return doesNotNeedToBeScheduled(V);
  4692. if (!BB)
  4693. BB = I->getParent();
  4694. return BB == I->getParent() && I->getNumOperands() == 2;
  4695. }) &&
  4696. BB &&
  4697. sortPtrAccesses(VL, UserTreeIdx.UserTE->getMainOp()->getType(), *DL, *SE,
  4698. SortedIndices));
  4699. if (!AreAllSameInsts || allConstant(VL) || isSplat(VL) ||
  4700. (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(
  4701. S.OpValue) &&
  4702. !all_of(VL, isVectorLikeInstWithConstOps)) ||
  4703. NotProfitableForVectorization(VL)) {
  4704. LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O, small shuffle. \n");
  4705. if (TryToFindDuplicates(S))
  4706. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4707. ReuseShuffleIndicies);
  4708. return;
  4709. }
  4710. // We now know that this is a vector of instructions of the same type from
  4711. // the same block.
  4712. // Don't vectorize ephemeral values.
  4713. if (!EphValues.empty()) {
  4714. for (Value *V : VL) {
  4715. if (EphValues.count(V)) {
  4716. LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
  4717. << ") is ephemeral.\n");
  4718. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
  4719. return;
  4720. }
  4721. }
  4722. }
  4723. // Check if this is a duplicate of another entry.
  4724. if (TreeEntry *E = getTreeEntry(S.OpValue)) {
  4725. LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
  4726. if (!E->isSame(VL)) {
  4727. LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
  4728. if (TryToFindDuplicates(S))
  4729. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4730. ReuseShuffleIndicies);
  4731. return;
  4732. }
  4733. // Record the reuse of the tree node. FIXME, currently this is only used to
  4734. // properly draw the graph rather than for the actual vectorization.
  4735. E->UserTreeIndices.push_back(UserTreeIdx);
  4736. LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
  4737. << ".\n");
  4738. return;
  4739. }
  4740. // Check that none of the instructions in the bundle are already in the tree.
  4741. for (Value *V : VL) {
  4742. if (!IsScatterVectorizeUserTE && !isa<Instruction>(V))
  4743. continue;
  4744. if (getTreeEntry(V)) {
  4745. LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
  4746. << ") is already in tree.\n");
  4747. if (TryToFindDuplicates(S))
  4748. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4749. ReuseShuffleIndicies);
  4750. return;
  4751. }
  4752. }
  4753. // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
  4754. if (UserIgnoreList && !UserIgnoreList->empty()) {
  4755. for (Value *V : VL) {
  4756. if (UserIgnoreList && UserIgnoreList->contains(V)) {
  4757. LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
  4758. if (TryToFindDuplicates(S))
  4759. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4760. ReuseShuffleIndicies);
  4761. return;
  4762. }
  4763. }
  4764. }
  4765. // Special processing for sorted pointers for ScatterVectorize node with
  4766. // constant indeces only.
  4767. if (AreAllSameInsts && UserTreeIdx.UserTE &&
  4768. UserTreeIdx.UserTE->State == TreeEntry::ScatterVectorize &&
  4769. !(S.getOpcode() && allSameBlock(VL))) {
  4770. assert(S.OpValue->getType()->isPointerTy() &&
  4771. count_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); }) >=
  4772. 2 &&
  4773. "Expected pointers only.");
  4774. // Reset S to make it GetElementPtr kind of node.
  4775. const auto *It = find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); });
  4776. assert(It != VL.end() && "Expected at least one GEP.");
  4777. S = getSameOpcode(*It, *TLI);
  4778. }
  4779. // Check that all of the users of the scalars that we want to vectorize are
  4780. // schedulable.
  4781. auto *VL0 = cast<Instruction>(S.OpValue);
  4782. BB = VL0->getParent();
  4783. if (!DT->isReachableFromEntry(BB)) {
  4784. // Don't go into unreachable blocks. They may contain instructions with
  4785. // dependency cycles which confuse the final scheduling.
  4786. LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
  4787. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
  4788. return;
  4789. }
  4790. // Don't go into catchswitch blocks, which can happen with PHIs.
  4791. // Such blocks can only have PHIs and the catchswitch. There is no
  4792. // place to insert a shuffle if we need to, so just avoid that issue.
  4793. if (isa<CatchSwitchInst>(BB->getTerminator())) {
  4794. LLVM_DEBUG(dbgs() << "SLP: bundle in catchswitch block.\n");
  4795. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
  4796. return;
  4797. }
  4798. // Check that every instruction appears once in this bundle.
  4799. if (!TryToFindDuplicates(S))
  4800. return;
  4801. auto &BSRef = BlocksSchedules[BB];
  4802. if (!BSRef)
  4803. BSRef = std::make_unique<BlockScheduling>(BB);
  4804. BlockScheduling &BS = *BSRef;
  4805. std::optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
  4806. #ifdef EXPENSIVE_CHECKS
  4807. // Make sure we didn't break any internal invariants
  4808. BS.verify();
  4809. #endif
  4810. if (!Bundle) {
  4811. LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
  4812. assert((!BS.getScheduleData(VL0) ||
  4813. !BS.getScheduleData(VL0)->isPartOfBundle()) &&
  4814. "tryScheduleBundle should cancelScheduling on failure");
  4815. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4816. ReuseShuffleIndicies);
  4817. return;
  4818. }
  4819. LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
  4820. unsigned ShuffleOrOp = S.isAltShuffle() ?
  4821. (unsigned) Instruction::ShuffleVector : S.getOpcode();
  4822. switch (ShuffleOrOp) {
  4823. case Instruction::PHI: {
  4824. auto *PH = cast<PHINode>(VL0);
  4825. // Check for terminator values (e.g. invoke).
  4826. for (Value *V : VL)
  4827. for (Value *Incoming : cast<PHINode>(V)->incoming_values()) {
  4828. Instruction *Term = dyn_cast<Instruction>(Incoming);
  4829. if (Term && Term->isTerminator()) {
  4830. LLVM_DEBUG(dbgs()
  4831. << "SLP: Need to swizzle PHINodes (terminator use).\n");
  4832. BS.cancelScheduling(VL, VL0);
  4833. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4834. ReuseShuffleIndicies);
  4835. return;
  4836. }
  4837. }
  4838. TreeEntry *TE =
  4839. newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
  4840. LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
  4841. // Keeps the reordered operands to avoid code duplication.
  4842. SmallVector<ValueList, 2> OperandsVec;
  4843. for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
  4844. if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
  4845. ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
  4846. TE->setOperand(I, Operands);
  4847. OperandsVec.push_back(Operands);
  4848. continue;
  4849. }
  4850. ValueList Operands;
  4851. // Prepare the operand vector.
  4852. for (Value *V : VL)
  4853. Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
  4854. PH->getIncomingBlock(I)));
  4855. TE->setOperand(I, Operands);
  4856. OperandsVec.push_back(Operands);
  4857. }
  4858. for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
  4859. buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
  4860. return;
  4861. }
  4862. case Instruction::ExtractValue:
  4863. case Instruction::ExtractElement: {
  4864. OrdersType CurrentOrder;
  4865. bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
  4866. if (Reuse) {
  4867. LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
  4868. newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  4869. ReuseShuffleIndicies);
  4870. // This is a special case, as it does not gather, but at the same time
  4871. // we are not extending buildTree_rec() towards the operands.
  4872. ValueList Op0;
  4873. Op0.assign(VL.size(), VL0->getOperand(0));
  4874. VectorizableTree.back()->setOperand(0, Op0);
  4875. return;
  4876. }
  4877. if (!CurrentOrder.empty()) {
  4878. LLVM_DEBUG({
  4879. dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
  4880. "with order";
  4881. for (unsigned Idx : CurrentOrder)
  4882. dbgs() << " " << Idx;
  4883. dbgs() << "\n";
  4884. });
  4885. fixupOrderingIndices(CurrentOrder);
  4886. // Insert new order with initial value 0, if it does not exist,
  4887. // otherwise return the iterator to the existing one.
  4888. newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  4889. ReuseShuffleIndicies, CurrentOrder);
  4890. // This is a special case, as it does not gather, but at the same time
  4891. // we are not extending buildTree_rec() towards the operands.
  4892. ValueList Op0;
  4893. Op0.assign(VL.size(), VL0->getOperand(0));
  4894. VectorizableTree.back()->setOperand(0, Op0);
  4895. return;
  4896. }
  4897. LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
  4898. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4899. ReuseShuffleIndicies);
  4900. BS.cancelScheduling(VL, VL0);
  4901. return;
  4902. }
  4903. case Instruction::InsertElement: {
  4904. assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
  4905. // Check that we have a buildvector and not a shuffle of 2 or more
  4906. // different vectors.
  4907. ValueSet SourceVectors;
  4908. for (Value *V : VL) {
  4909. SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
  4910. assert(getInsertIndex(V) != std::nullopt &&
  4911. "Non-constant or undef index?");
  4912. }
  4913. if (count_if(VL, [&SourceVectors](Value *V) {
  4914. return !SourceVectors.contains(V);
  4915. }) >= 2) {
  4916. // Found 2nd source vector - cancel.
  4917. LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
  4918. "different source vectors.\n");
  4919. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx);
  4920. BS.cancelScheduling(VL, VL0);
  4921. return;
  4922. }
  4923. auto OrdCompare = [](const std::pair<int, int> &P1,
  4924. const std::pair<int, int> &P2) {
  4925. return P1.first > P2.first;
  4926. };
  4927. PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
  4928. decltype(OrdCompare)>
  4929. Indices(OrdCompare);
  4930. for (int I = 0, E = VL.size(); I < E; ++I) {
  4931. unsigned Idx = *getInsertIndex(VL[I]);
  4932. Indices.emplace(Idx, I);
  4933. }
  4934. OrdersType CurrentOrder(VL.size(), VL.size());
  4935. bool IsIdentity = true;
  4936. for (int I = 0, E = VL.size(); I < E; ++I) {
  4937. CurrentOrder[Indices.top().second] = I;
  4938. IsIdentity &= Indices.top().second == I;
  4939. Indices.pop();
  4940. }
  4941. if (IsIdentity)
  4942. CurrentOrder.clear();
  4943. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  4944. std::nullopt, CurrentOrder);
  4945. LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
  4946. constexpr int NumOps = 2;
  4947. ValueList VectorOperands[NumOps];
  4948. for (int I = 0; I < NumOps; ++I) {
  4949. for (Value *V : VL)
  4950. VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
  4951. TE->setOperand(I, VectorOperands[I]);
  4952. }
  4953. buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
  4954. return;
  4955. }
  4956. case Instruction::Load: {
  4957. // Check that a vectorized load would load the same memory as a scalar
  4958. // load. For example, we don't want to vectorize loads that are smaller
  4959. // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
  4960. // treats loading/storing it as an i8 struct. If we vectorize loads/stores
  4961. // from such a struct, we read/write packed bits disagreeing with the
  4962. // unvectorized version.
  4963. SmallVector<Value *> PointerOps;
  4964. OrdersType CurrentOrder;
  4965. TreeEntry *TE = nullptr;
  4966. switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, *LI, *TLI,
  4967. CurrentOrder, PointerOps)) {
  4968. case LoadsState::Vectorize:
  4969. if (CurrentOrder.empty()) {
  4970. // Original loads are consecutive and does not require reordering.
  4971. TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  4972. ReuseShuffleIndicies);
  4973. LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
  4974. } else {
  4975. fixupOrderingIndices(CurrentOrder);
  4976. // Need to reorder.
  4977. TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  4978. ReuseShuffleIndicies, CurrentOrder);
  4979. LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
  4980. }
  4981. TE->setOperandsInOrder();
  4982. break;
  4983. case LoadsState::ScatterVectorize:
  4984. // Vectorizing non-consecutive loads with `llvm.masked.gather`.
  4985. TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
  4986. UserTreeIdx, ReuseShuffleIndicies);
  4987. TE->setOperandsInOrder();
  4988. buildTree_rec(PointerOps, Depth + 1, {TE, 0});
  4989. LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
  4990. break;
  4991. case LoadsState::Gather:
  4992. BS.cancelScheduling(VL, VL0);
  4993. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  4994. ReuseShuffleIndicies);
  4995. #ifndef NDEBUG
  4996. Type *ScalarTy = VL0->getType();
  4997. if (DL->getTypeSizeInBits(ScalarTy) !=
  4998. DL->getTypeAllocSizeInBits(ScalarTy))
  4999. LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
  5000. else if (any_of(VL, [](Value *V) {
  5001. return !cast<LoadInst>(V)->isSimple();
  5002. }))
  5003. LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
  5004. else
  5005. LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
  5006. #endif // NDEBUG
  5007. break;
  5008. }
  5009. return;
  5010. }
  5011. case Instruction::ZExt:
  5012. case Instruction::SExt:
  5013. case Instruction::FPToUI:
  5014. case Instruction::FPToSI:
  5015. case Instruction::FPExt:
  5016. case Instruction::PtrToInt:
  5017. case Instruction::IntToPtr:
  5018. case Instruction::SIToFP:
  5019. case Instruction::UIToFP:
  5020. case Instruction::Trunc:
  5021. case Instruction::FPTrunc:
  5022. case Instruction::BitCast: {
  5023. Type *SrcTy = VL0->getOperand(0)->getType();
  5024. for (Value *V : VL) {
  5025. Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
  5026. if (Ty != SrcTy || !isValidElementType(Ty)) {
  5027. BS.cancelScheduling(VL, VL0);
  5028. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5029. ReuseShuffleIndicies);
  5030. LLVM_DEBUG(dbgs()
  5031. << "SLP: Gathering casts with different src types.\n");
  5032. return;
  5033. }
  5034. }
  5035. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  5036. ReuseShuffleIndicies);
  5037. LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
  5038. TE->setOperandsInOrder();
  5039. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  5040. ValueList Operands;
  5041. // Prepare the operand vector.
  5042. for (Value *V : VL)
  5043. Operands.push_back(cast<Instruction>(V)->getOperand(i));
  5044. buildTree_rec(Operands, Depth + 1, {TE, i});
  5045. }
  5046. return;
  5047. }
  5048. case Instruction::ICmp:
  5049. case Instruction::FCmp: {
  5050. // Check that all of the compares have the same predicate.
  5051. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  5052. CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
  5053. Type *ComparedTy = VL0->getOperand(0)->getType();
  5054. for (Value *V : VL) {
  5055. CmpInst *Cmp = cast<CmpInst>(V);
  5056. if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
  5057. Cmp->getOperand(0)->getType() != ComparedTy) {
  5058. BS.cancelScheduling(VL, VL0);
  5059. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5060. ReuseShuffleIndicies);
  5061. LLVM_DEBUG(dbgs()
  5062. << "SLP: Gathering cmp with different predicate.\n");
  5063. return;
  5064. }
  5065. }
  5066. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  5067. ReuseShuffleIndicies);
  5068. LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
  5069. ValueList Left, Right;
  5070. if (cast<CmpInst>(VL0)->isCommutative()) {
  5071. // Commutative predicate - collect + sort operands of the instructions
  5072. // so that each side is more likely to have the same opcode.
  5073. assert(P0 == SwapP0 && "Commutative Predicate mismatch");
  5074. reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE, *this);
  5075. } else {
  5076. // Collect operands - commute if it uses the swapped predicate.
  5077. for (Value *V : VL) {
  5078. auto *Cmp = cast<CmpInst>(V);
  5079. Value *LHS = Cmp->getOperand(0);
  5080. Value *RHS = Cmp->getOperand(1);
  5081. if (Cmp->getPredicate() != P0)
  5082. std::swap(LHS, RHS);
  5083. Left.push_back(LHS);
  5084. Right.push_back(RHS);
  5085. }
  5086. }
  5087. TE->setOperand(0, Left);
  5088. TE->setOperand(1, Right);
  5089. buildTree_rec(Left, Depth + 1, {TE, 0});
  5090. buildTree_rec(Right, Depth + 1, {TE, 1});
  5091. return;
  5092. }
  5093. case Instruction::Select:
  5094. case Instruction::FNeg:
  5095. case Instruction::Add:
  5096. case Instruction::FAdd:
  5097. case Instruction::Sub:
  5098. case Instruction::FSub:
  5099. case Instruction::Mul:
  5100. case Instruction::FMul:
  5101. case Instruction::UDiv:
  5102. case Instruction::SDiv:
  5103. case Instruction::FDiv:
  5104. case Instruction::URem:
  5105. case Instruction::SRem:
  5106. case Instruction::FRem:
  5107. case Instruction::Shl:
  5108. case Instruction::LShr:
  5109. case Instruction::AShr:
  5110. case Instruction::And:
  5111. case Instruction::Or:
  5112. case Instruction::Xor: {
  5113. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  5114. ReuseShuffleIndicies);
  5115. LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
  5116. // Sort operands of the instructions so that each side is more likely to
  5117. // have the same opcode.
  5118. if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
  5119. ValueList Left, Right;
  5120. reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE, *this);
  5121. TE->setOperand(0, Left);
  5122. TE->setOperand(1, Right);
  5123. buildTree_rec(Left, Depth + 1, {TE, 0});
  5124. buildTree_rec(Right, Depth + 1, {TE, 1});
  5125. return;
  5126. }
  5127. TE->setOperandsInOrder();
  5128. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  5129. ValueList Operands;
  5130. // Prepare the operand vector.
  5131. for (Value *V : VL)
  5132. Operands.push_back(cast<Instruction>(V)->getOperand(i));
  5133. buildTree_rec(Operands, Depth + 1, {TE, i});
  5134. }
  5135. return;
  5136. }
  5137. case Instruction::GetElementPtr: {
  5138. // We don't combine GEPs with complicated (nested) indexing.
  5139. for (Value *V : VL) {
  5140. auto *I = dyn_cast<GetElementPtrInst>(V);
  5141. if (!I)
  5142. continue;
  5143. if (I->getNumOperands() != 2) {
  5144. LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
  5145. BS.cancelScheduling(VL, VL0);
  5146. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5147. ReuseShuffleIndicies);
  5148. return;
  5149. }
  5150. }
  5151. // We can't combine several GEPs into one vector if they operate on
  5152. // different types.
  5153. Type *Ty0 = cast<GEPOperator>(VL0)->getSourceElementType();
  5154. for (Value *V : VL) {
  5155. auto *GEP = dyn_cast<GEPOperator>(V);
  5156. if (!GEP)
  5157. continue;
  5158. Type *CurTy = GEP->getSourceElementType();
  5159. if (Ty0 != CurTy) {
  5160. LLVM_DEBUG(dbgs()
  5161. << "SLP: not-vectorizable GEP (different types).\n");
  5162. BS.cancelScheduling(VL, VL0);
  5163. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5164. ReuseShuffleIndicies);
  5165. return;
  5166. }
  5167. }
  5168. // We don't combine GEPs with non-constant indexes.
  5169. Type *Ty1 = VL0->getOperand(1)->getType();
  5170. for (Value *V : VL) {
  5171. auto *I = dyn_cast<GetElementPtrInst>(V);
  5172. if (!I)
  5173. continue;
  5174. auto *Op = I->getOperand(1);
  5175. if ((!IsScatterVectorizeUserTE && !isa<ConstantInt>(Op)) ||
  5176. (Op->getType() != Ty1 &&
  5177. ((IsScatterVectorizeUserTE && !isa<ConstantInt>(Op)) ||
  5178. Op->getType()->getScalarSizeInBits() >
  5179. DL->getIndexSizeInBits(
  5180. V->getType()->getPointerAddressSpace())))) {
  5181. LLVM_DEBUG(dbgs()
  5182. << "SLP: not-vectorizable GEP (non-constant indexes).\n");
  5183. BS.cancelScheduling(VL, VL0);
  5184. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5185. ReuseShuffleIndicies);
  5186. return;
  5187. }
  5188. }
  5189. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  5190. ReuseShuffleIndicies);
  5191. LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
  5192. SmallVector<ValueList, 2> Operands(2);
  5193. // Prepare the operand vector for pointer operands.
  5194. for (Value *V : VL) {
  5195. auto *GEP = dyn_cast<GetElementPtrInst>(V);
  5196. if (!GEP) {
  5197. Operands.front().push_back(V);
  5198. continue;
  5199. }
  5200. Operands.front().push_back(GEP->getPointerOperand());
  5201. }
  5202. TE->setOperand(0, Operands.front());
  5203. // Need to cast all indices to the same type before vectorization to
  5204. // avoid crash.
  5205. // Required to be able to find correct matches between different gather
  5206. // nodes and reuse the vectorized values rather than trying to gather them
  5207. // again.
  5208. int IndexIdx = 1;
  5209. Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
  5210. Type *Ty = all_of(VL,
  5211. [VL0Ty, IndexIdx](Value *V) {
  5212. auto *GEP = dyn_cast<GetElementPtrInst>(V);
  5213. if (!GEP)
  5214. return true;
  5215. return VL0Ty == GEP->getOperand(IndexIdx)->getType();
  5216. })
  5217. ? VL0Ty
  5218. : DL->getIndexType(cast<GetElementPtrInst>(VL0)
  5219. ->getPointerOperandType()
  5220. ->getScalarType());
  5221. // Prepare the operand vector.
  5222. for (Value *V : VL) {
  5223. auto *I = dyn_cast<GetElementPtrInst>(V);
  5224. if (!I) {
  5225. Operands.back().push_back(
  5226. ConstantInt::get(Ty, 0, /*isSigned=*/false));
  5227. continue;
  5228. }
  5229. auto *Op = I->getOperand(IndexIdx);
  5230. auto *CI = dyn_cast<ConstantInt>(Op);
  5231. if (!CI)
  5232. Operands.back().push_back(Op);
  5233. else
  5234. Operands.back().push_back(ConstantExpr::getIntegerCast(
  5235. CI, Ty, CI->getValue().isSignBitSet()));
  5236. }
  5237. TE->setOperand(IndexIdx, Operands.back());
  5238. for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
  5239. buildTree_rec(Operands[I], Depth + 1, {TE, I});
  5240. return;
  5241. }
  5242. case Instruction::Store: {
  5243. // Check if the stores are consecutive or if we need to swizzle them.
  5244. llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
  5245. // Avoid types that are padded when being allocated as scalars, while
  5246. // being packed together in a vector (such as i1).
  5247. if (DL->getTypeSizeInBits(ScalarTy) !=
  5248. DL->getTypeAllocSizeInBits(ScalarTy)) {
  5249. BS.cancelScheduling(VL, VL0);
  5250. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5251. ReuseShuffleIndicies);
  5252. LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
  5253. return;
  5254. }
  5255. // Make sure all stores in the bundle are simple - we can't vectorize
  5256. // atomic or volatile stores.
  5257. SmallVector<Value *, 4> PointerOps(VL.size());
  5258. ValueList Operands(VL.size());
  5259. auto POIter = PointerOps.begin();
  5260. auto OIter = Operands.begin();
  5261. for (Value *V : VL) {
  5262. auto *SI = cast<StoreInst>(V);
  5263. if (!SI->isSimple()) {
  5264. BS.cancelScheduling(VL, VL0);
  5265. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5266. ReuseShuffleIndicies);
  5267. LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
  5268. return;
  5269. }
  5270. *POIter = SI->getPointerOperand();
  5271. *OIter = SI->getValueOperand();
  5272. ++POIter;
  5273. ++OIter;
  5274. }
  5275. OrdersType CurrentOrder;
  5276. // Check the order of pointer operands.
  5277. if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
  5278. Value *Ptr0;
  5279. Value *PtrN;
  5280. if (CurrentOrder.empty()) {
  5281. Ptr0 = PointerOps.front();
  5282. PtrN = PointerOps.back();
  5283. } else {
  5284. Ptr0 = PointerOps[CurrentOrder.front()];
  5285. PtrN = PointerOps[CurrentOrder.back()];
  5286. }
  5287. std::optional<int> Dist =
  5288. getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
  5289. // Check that the sorted pointer operands are consecutive.
  5290. if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
  5291. if (CurrentOrder.empty()) {
  5292. // Original stores are consecutive and does not require reordering.
  5293. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
  5294. UserTreeIdx, ReuseShuffleIndicies);
  5295. TE->setOperandsInOrder();
  5296. buildTree_rec(Operands, Depth + 1, {TE, 0});
  5297. LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
  5298. } else {
  5299. fixupOrderingIndices(CurrentOrder);
  5300. TreeEntry *TE =
  5301. newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  5302. ReuseShuffleIndicies, CurrentOrder);
  5303. TE->setOperandsInOrder();
  5304. buildTree_rec(Operands, Depth + 1, {TE, 0});
  5305. LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
  5306. }
  5307. return;
  5308. }
  5309. }
  5310. BS.cancelScheduling(VL, VL0);
  5311. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5312. ReuseShuffleIndicies);
  5313. LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
  5314. return;
  5315. }
  5316. case Instruction::Call: {
  5317. // Check if the calls are all to the same vectorizable intrinsic or
  5318. // library function.
  5319. CallInst *CI = cast<CallInst>(VL0);
  5320. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5321. VFShape Shape = VFShape::get(
  5322. *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
  5323. false /*HasGlobalPred*/);
  5324. Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
  5325. if (!VecFunc && !isTriviallyVectorizable(ID)) {
  5326. BS.cancelScheduling(VL, VL0);
  5327. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5328. ReuseShuffleIndicies);
  5329. LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
  5330. return;
  5331. }
  5332. Function *F = CI->getCalledFunction();
  5333. unsigned NumArgs = CI->arg_size();
  5334. SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
  5335. for (unsigned j = 0; j != NumArgs; ++j)
  5336. if (isVectorIntrinsicWithScalarOpAtArg(ID, j))
  5337. ScalarArgs[j] = CI->getArgOperand(j);
  5338. for (Value *V : VL) {
  5339. CallInst *CI2 = dyn_cast<CallInst>(V);
  5340. if (!CI2 || CI2->getCalledFunction() != F ||
  5341. getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
  5342. (VecFunc &&
  5343. VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
  5344. !CI->hasIdenticalOperandBundleSchema(*CI2)) {
  5345. BS.cancelScheduling(VL, VL0);
  5346. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5347. ReuseShuffleIndicies);
  5348. LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
  5349. << "\n");
  5350. return;
  5351. }
  5352. // Some intrinsics have scalar arguments and should be same in order for
  5353. // them to be vectorized.
  5354. for (unsigned j = 0; j != NumArgs; ++j) {
  5355. if (isVectorIntrinsicWithScalarOpAtArg(ID, j)) {
  5356. Value *A1J = CI2->getArgOperand(j);
  5357. if (ScalarArgs[j] != A1J) {
  5358. BS.cancelScheduling(VL, VL0);
  5359. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5360. ReuseShuffleIndicies);
  5361. LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
  5362. << " argument " << ScalarArgs[j] << "!=" << A1J
  5363. << "\n");
  5364. return;
  5365. }
  5366. }
  5367. }
  5368. // Verify that the bundle operands are identical between the two calls.
  5369. if (CI->hasOperandBundles() &&
  5370. !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
  5371. CI->op_begin() + CI->getBundleOperandsEndIndex(),
  5372. CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
  5373. BS.cancelScheduling(VL, VL0);
  5374. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5375. ReuseShuffleIndicies);
  5376. LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
  5377. << *CI << "!=" << *V << '\n');
  5378. return;
  5379. }
  5380. }
  5381. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  5382. ReuseShuffleIndicies);
  5383. TE->setOperandsInOrder();
  5384. for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
  5385. // For scalar operands no need to to create an entry since no need to
  5386. // vectorize it.
  5387. if (isVectorIntrinsicWithScalarOpAtArg(ID, i))
  5388. continue;
  5389. ValueList Operands;
  5390. // Prepare the operand vector.
  5391. for (Value *V : VL) {
  5392. auto *CI2 = cast<CallInst>(V);
  5393. Operands.push_back(CI2->getArgOperand(i));
  5394. }
  5395. buildTree_rec(Operands, Depth + 1, {TE, i});
  5396. }
  5397. return;
  5398. }
  5399. case Instruction::ShuffleVector: {
  5400. // If this is not an alternate sequence of opcode like add-sub
  5401. // then do not vectorize this instruction.
  5402. if (!S.isAltShuffle()) {
  5403. BS.cancelScheduling(VL, VL0);
  5404. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5405. ReuseShuffleIndicies);
  5406. LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
  5407. return;
  5408. }
  5409. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  5410. ReuseShuffleIndicies);
  5411. LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
  5412. // Reorder operands if reordering would enable vectorization.
  5413. auto *CI = dyn_cast<CmpInst>(VL0);
  5414. if (isa<BinaryOperator>(VL0) || CI) {
  5415. ValueList Left, Right;
  5416. if (!CI || all_of(VL, [](Value *V) {
  5417. return cast<CmpInst>(V)->isCommutative();
  5418. })) {
  5419. reorderInputsAccordingToOpcode(VL, Left, Right, *TLI, *DL, *SE,
  5420. *this);
  5421. } else {
  5422. auto *MainCI = cast<CmpInst>(S.MainOp);
  5423. auto *AltCI = cast<CmpInst>(S.AltOp);
  5424. CmpInst::Predicate MainP = MainCI->getPredicate();
  5425. CmpInst::Predicate AltP = AltCI->getPredicate();
  5426. assert(MainP != AltP &&
  5427. "Expected different main/alternate predicates.");
  5428. // Collect operands - commute if it uses the swapped predicate or
  5429. // alternate operation.
  5430. for (Value *V : VL) {
  5431. auto *Cmp = cast<CmpInst>(V);
  5432. Value *LHS = Cmp->getOperand(0);
  5433. Value *RHS = Cmp->getOperand(1);
  5434. if (isAlternateInstruction(Cmp, MainCI, AltCI, *TLI)) {
  5435. if (AltP == CmpInst::getSwappedPredicate(Cmp->getPredicate()))
  5436. std::swap(LHS, RHS);
  5437. } else {
  5438. if (MainP == CmpInst::getSwappedPredicate(Cmp->getPredicate()))
  5439. std::swap(LHS, RHS);
  5440. }
  5441. Left.push_back(LHS);
  5442. Right.push_back(RHS);
  5443. }
  5444. }
  5445. TE->setOperand(0, Left);
  5446. TE->setOperand(1, Right);
  5447. buildTree_rec(Left, Depth + 1, {TE, 0});
  5448. buildTree_rec(Right, Depth + 1, {TE, 1});
  5449. return;
  5450. }
  5451. TE->setOperandsInOrder();
  5452. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  5453. ValueList Operands;
  5454. // Prepare the operand vector.
  5455. for (Value *V : VL)
  5456. Operands.push_back(cast<Instruction>(V)->getOperand(i));
  5457. buildTree_rec(Operands, Depth + 1, {TE, i});
  5458. }
  5459. return;
  5460. }
  5461. default:
  5462. BS.cancelScheduling(VL, VL0);
  5463. newTreeEntry(VL, std::nullopt /*not vectorized*/, S, UserTreeIdx,
  5464. ReuseShuffleIndicies);
  5465. LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
  5466. return;
  5467. }
  5468. }
  5469. unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
  5470. unsigned N = 1;
  5471. Type *EltTy = T;
  5472. while (isa<StructType, ArrayType, VectorType>(EltTy)) {
  5473. if (auto *ST = dyn_cast<StructType>(EltTy)) {
  5474. // Check that struct is homogeneous.
  5475. for (const auto *Ty : ST->elements())
  5476. if (Ty != *ST->element_begin())
  5477. return 0;
  5478. N *= ST->getNumElements();
  5479. EltTy = *ST->element_begin();
  5480. } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
  5481. N *= AT->getNumElements();
  5482. EltTy = AT->getElementType();
  5483. } else {
  5484. auto *VT = cast<FixedVectorType>(EltTy);
  5485. N *= VT->getNumElements();
  5486. EltTy = VT->getElementType();
  5487. }
  5488. }
  5489. if (!isValidElementType(EltTy))
  5490. return 0;
  5491. uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
  5492. if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
  5493. return 0;
  5494. return N;
  5495. }
  5496. bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
  5497. SmallVectorImpl<unsigned> &CurrentOrder) const {
  5498. const auto *It = find_if(VL, [](Value *V) {
  5499. return isa<ExtractElementInst, ExtractValueInst>(V);
  5500. });
  5501. assert(It != VL.end() && "Expected at least one extract instruction.");
  5502. auto *E0 = cast<Instruction>(*It);
  5503. assert(all_of(VL,
  5504. [](Value *V) {
  5505. return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
  5506. V);
  5507. }) &&
  5508. "Invalid opcode");
  5509. // Check if all of the extracts come from the same vector and from the
  5510. // correct offset.
  5511. Value *Vec = E0->getOperand(0);
  5512. CurrentOrder.clear();
  5513. // We have to extract from a vector/aggregate with the same number of elements.
  5514. unsigned NElts;
  5515. if (E0->getOpcode() == Instruction::ExtractValue) {
  5516. const DataLayout &DL = E0->getModule()->getDataLayout();
  5517. NElts = canMapToVector(Vec->getType(), DL);
  5518. if (!NElts)
  5519. return false;
  5520. // Check if load can be rewritten as load of vector.
  5521. LoadInst *LI = dyn_cast<LoadInst>(Vec);
  5522. if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
  5523. return false;
  5524. } else {
  5525. NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
  5526. }
  5527. if (NElts != VL.size())
  5528. return false;
  5529. // Check that all of the indices extract from the correct offset.
  5530. bool ShouldKeepOrder = true;
  5531. unsigned E = VL.size();
  5532. // Assign to all items the initial value E + 1 so we can check if the extract
  5533. // instruction index was used already.
  5534. // Also, later we can check that all the indices are used and we have a
  5535. // consecutive access in the extract instructions, by checking that no
  5536. // element of CurrentOrder still has value E + 1.
  5537. CurrentOrder.assign(E, E);
  5538. unsigned I = 0;
  5539. for (; I < E; ++I) {
  5540. auto *Inst = dyn_cast<Instruction>(VL[I]);
  5541. if (!Inst)
  5542. continue;
  5543. if (Inst->getOperand(0) != Vec)
  5544. break;
  5545. if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
  5546. if (isa<UndefValue>(EE->getIndexOperand()))
  5547. continue;
  5548. std::optional<unsigned> Idx = getExtractIndex(Inst);
  5549. if (!Idx)
  5550. break;
  5551. const unsigned ExtIdx = *Idx;
  5552. if (ExtIdx != I) {
  5553. if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
  5554. break;
  5555. ShouldKeepOrder = false;
  5556. CurrentOrder[ExtIdx] = I;
  5557. } else {
  5558. if (CurrentOrder[I] != E)
  5559. break;
  5560. CurrentOrder[I] = I;
  5561. }
  5562. }
  5563. if (I < E) {
  5564. CurrentOrder.clear();
  5565. return false;
  5566. }
  5567. if (ShouldKeepOrder)
  5568. CurrentOrder.clear();
  5569. return ShouldKeepOrder;
  5570. }
  5571. bool BoUpSLP::areAllUsersVectorized(Instruction *I,
  5572. ArrayRef<Value *> VectorizedVals) const {
  5573. return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
  5574. all_of(I->users(), [this](User *U) {
  5575. return ScalarToTreeEntry.count(U) > 0 ||
  5576. isVectorLikeInstWithConstOps(U) ||
  5577. (isa<ExtractElementInst>(U) && MustGather.contains(U));
  5578. });
  5579. }
  5580. static std::pair<InstructionCost, InstructionCost>
  5581. getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
  5582. TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
  5583. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5584. // Calculate the cost of the scalar and vector calls.
  5585. SmallVector<Type *, 4> VecTys;
  5586. for (Use &Arg : CI->args())
  5587. VecTys.push_back(
  5588. FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
  5589. FastMathFlags FMF;
  5590. if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
  5591. FMF = FPCI->getFastMathFlags();
  5592. SmallVector<const Value *> Arguments(CI->args());
  5593. IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
  5594. dyn_cast<IntrinsicInst>(CI));
  5595. auto IntrinsicCost =
  5596. TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
  5597. auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
  5598. VecTy->getNumElements())),
  5599. false /*HasGlobalPred*/);
  5600. Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
  5601. auto LibCost = IntrinsicCost;
  5602. if (!CI->isNoBuiltin() && VecFunc) {
  5603. // Calculate the cost of the vector library call.
  5604. // If the corresponding vector call is cheaper, return its cost.
  5605. LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
  5606. TTI::TCK_RecipThroughput);
  5607. }
  5608. return {IntrinsicCost, LibCost};
  5609. }
  5610. /// Compute the cost of creating a vector of type \p VecTy containing the
  5611. /// extracted values from \p VL.
  5612. static InstructionCost
  5613. computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
  5614. TargetTransformInfo::ShuffleKind ShuffleKind,
  5615. ArrayRef<int> Mask, TargetTransformInfo &TTI) {
  5616. unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
  5617. if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
  5618. VecTy->getNumElements() < NumOfParts)
  5619. return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
  5620. bool AllConsecutive = true;
  5621. unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
  5622. unsigned Idx = -1;
  5623. InstructionCost Cost = 0;
  5624. // Process extracts in blocks of EltsPerVector to check if the source vector
  5625. // operand can be re-used directly. If not, add the cost of creating a shuffle
  5626. // to extract the values into a vector register.
  5627. SmallVector<int> RegMask(EltsPerVector, UndefMaskElem);
  5628. for (auto *V : VL) {
  5629. ++Idx;
  5630. // Reached the start of a new vector registers.
  5631. if (Idx % EltsPerVector == 0) {
  5632. RegMask.assign(EltsPerVector, UndefMaskElem);
  5633. AllConsecutive = true;
  5634. continue;
  5635. }
  5636. // Need to exclude undefs from analysis.
  5637. if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
  5638. continue;
  5639. // Check all extracts for a vector register on the target directly
  5640. // extract values in order.
  5641. unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
  5642. if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
  5643. unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
  5644. AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
  5645. CurrentIdx % EltsPerVector == Idx % EltsPerVector;
  5646. RegMask[Idx % EltsPerVector] = CurrentIdx % EltsPerVector;
  5647. }
  5648. if (AllConsecutive)
  5649. continue;
  5650. // Skip all indices, except for the last index per vector block.
  5651. if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
  5652. continue;
  5653. // If we have a series of extracts which are not consecutive and hence
  5654. // cannot re-use the source vector register directly, compute the shuffle
  5655. // cost to extract the vector with EltsPerVector elements.
  5656. Cost += TTI.getShuffleCost(
  5657. TargetTransformInfo::SK_PermuteSingleSrc,
  5658. FixedVectorType::get(VecTy->getElementType(), EltsPerVector), RegMask);
  5659. }
  5660. return Cost;
  5661. }
  5662. /// Build shuffle mask for shuffle graph entries and lists of main and alternate
  5663. /// operations operands.
  5664. static void
  5665. buildShuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
  5666. ArrayRef<int> ReusesIndices,
  5667. const function_ref<bool(Instruction *)> IsAltOp,
  5668. SmallVectorImpl<int> &Mask,
  5669. SmallVectorImpl<Value *> *OpScalars = nullptr,
  5670. SmallVectorImpl<Value *> *AltScalars = nullptr) {
  5671. unsigned Sz = VL.size();
  5672. Mask.assign(Sz, UndefMaskElem);
  5673. SmallVector<int> OrderMask;
  5674. if (!ReorderIndices.empty())
  5675. inversePermutation(ReorderIndices, OrderMask);
  5676. for (unsigned I = 0; I < Sz; ++I) {
  5677. unsigned Idx = I;
  5678. if (!ReorderIndices.empty())
  5679. Idx = OrderMask[I];
  5680. auto *OpInst = cast<Instruction>(VL[Idx]);
  5681. if (IsAltOp(OpInst)) {
  5682. Mask[I] = Sz + Idx;
  5683. if (AltScalars)
  5684. AltScalars->push_back(OpInst);
  5685. } else {
  5686. Mask[I] = Idx;
  5687. if (OpScalars)
  5688. OpScalars->push_back(OpInst);
  5689. }
  5690. }
  5691. if (!ReusesIndices.empty()) {
  5692. SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
  5693. transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
  5694. return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
  5695. });
  5696. Mask.swap(NewMask);
  5697. }
  5698. }
  5699. static bool isAlternateInstruction(const Instruction *I,
  5700. const Instruction *MainOp,
  5701. const Instruction *AltOp,
  5702. const TargetLibraryInfo &TLI) {
  5703. if (auto *MainCI = dyn_cast<CmpInst>(MainOp)) {
  5704. auto *AltCI = cast<CmpInst>(AltOp);
  5705. CmpInst::Predicate MainP = MainCI->getPredicate();
  5706. CmpInst::Predicate AltP = AltCI->getPredicate();
  5707. assert(MainP != AltP && "Expected different main/alternate predicates.");
  5708. auto *CI = cast<CmpInst>(I);
  5709. if (isCmpSameOrSwapped(MainCI, CI, TLI))
  5710. return false;
  5711. if (isCmpSameOrSwapped(AltCI, CI, TLI))
  5712. return true;
  5713. CmpInst::Predicate P = CI->getPredicate();
  5714. CmpInst::Predicate SwappedP = CmpInst::getSwappedPredicate(P);
  5715. assert((MainP == P || AltP == P || MainP == SwappedP || AltP == SwappedP) &&
  5716. "CmpInst expected to match either main or alternate predicate or "
  5717. "their swap.");
  5718. (void)AltP;
  5719. return MainP != P && MainP != SwappedP;
  5720. }
  5721. return I->getOpcode() == AltOp->getOpcode();
  5722. }
  5723. TTI::OperandValueInfo BoUpSLP::getOperandInfo(ArrayRef<Value *> VL,
  5724. unsigned OpIdx) {
  5725. assert(!VL.empty());
  5726. const auto *I0 = cast<Instruction>(*find_if(VL, Instruction::classof));
  5727. const auto *Op0 = I0->getOperand(OpIdx);
  5728. const bool IsConstant = all_of(VL, [&](Value *V) {
  5729. // TODO: We should allow undef elements here
  5730. const auto *I = dyn_cast<Instruction>(V);
  5731. if (!I)
  5732. return true;
  5733. auto *Op = I->getOperand(OpIdx);
  5734. return isConstant(Op) && !isa<UndefValue>(Op);
  5735. });
  5736. const bool IsUniform = all_of(VL, [&](Value *V) {
  5737. // TODO: We should allow undef elements here
  5738. const auto *I = dyn_cast<Instruction>(V);
  5739. if (!I)
  5740. return false;
  5741. return I->getOperand(OpIdx) == Op0;
  5742. });
  5743. const bool IsPowerOfTwo = all_of(VL, [&](Value *V) {
  5744. // TODO: We should allow undef elements here
  5745. const auto *I = dyn_cast<Instruction>(V);
  5746. if (!I) {
  5747. assert((isa<UndefValue>(V) ||
  5748. I0->getOpcode() == Instruction::GetElementPtr) &&
  5749. "Expected undef or GEP.");
  5750. return true;
  5751. }
  5752. auto *Op = I->getOperand(OpIdx);
  5753. if (auto *CI = dyn_cast<ConstantInt>(Op))
  5754. return CI->getValue().isPowerOf2();
  5755. return false;
  5756. });
  5757. const bool IsNegatedPowerOfTwo = all_of(VL, [&](Value *V) {
  5758. // TODO: We should allow undef elements here
  5759. const auto *I = dyn_cast<Instruction>(V);
  5760. if (!I) {
  5761. assert((isa<UndefValue>(V) ||
  5762. I0->getOpcode() == Instruction::GetElementPtr) &&
  5763. "Expected undef or GEP.");
  5764. return true;
  5765. }
  5766. const auto *Op = I->getOperand(OpIdx);
  5767. if (auto *CI = dyn_cast<ConstantInt>(Op))
  5768. return CI->getValue().isNegatedPowerOf2();
  5769. return false;
  5770. });
  5771. TTI::OperandValueKind VK = TTI::OK_AnyValue;
  5772. if (IsConstant && IsUniform)
  5773. VK = TTI::OK_UniformConstantValue;
  5774. else if (IsConstant)
  5775. VK = TTI::OK_NonUniformConstantValue;
  5776. else if (IsUniform)
  5777. VK = TTI::OK_UniformValue;
  5778. TTI::OperandValueProperties VP = TTI::OP_None;
  5779. VP = IsPowerOfTwo ? TTI::OP_PowerOf2 : VP;
  5780. VP = IsNegatedPowerOfTwo ? TTI::OP_NegatedPowerOf2 : VP;
  5781. return {VK, VP};
  5782. }
  5783. namespace {
  5784. /// The base class for shuffle instruction emission and shuffle cost estimation.
  5785. class BaseShuffleAnalysis {
  5786. protected:
  5787. /// Checks if the mask is an identity mask.
  5788. /// \param IsStrict if is true the function returns false if mask size does
  5789. /// not match vector size.
  5790. static bool isIdentityMask(ArrayRef<int> Mask, const FixedVectorType *VecTy,
  5791. bool IsStrict) {
  5792. int Limit = Mask.size();
  5793. int VF = VecTy->getNumElements();
  5794. return (VF == Limit || !IsStrict) &&
  5795. all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) &&
  5796. ShuffleVectorInst::isIdentityMask(Mask);
  5797. }
  5798. /// Tries to combine 2 different masks into single one.
  5799. /// \param LocalVF Vector length of the permuted input vector. \p Mask may
  5800. /// change the size of the vector, \p LocalVF is the original size of the
  5801. /// shuffled vector.
  5802. static void combineMasks(unsigned LocalVF, SmallVectorImpl<int> &Mask,
  5803. ArrayRef<int> ExtMask) {
  5804. unsigned VF = Mask.size();
  5805. SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem);
  5806. for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
  5807. if (ExtMask[I] == UndefMaskElem)
  5808. continue;
  5809. int MaskedIdx = Mask[ExtMask[I] % VF];
  5810. NewMask[I] =
  5811. MaskedIdx == UndefMaskElem ? UndefMaskElem : MaskedIdx % LocalVF;
  5812. }
  5813. Mask.swap(NewMask);
  5814. }
  5815. /// Looks through shuffles trying to reduce final number of shuffles in the
  5816. /// code. The function looks through the previously emitted shuffle
  5817. /// instructions and properly mark indices in mask as undef.
  5818. /// For example, given the code
  5819. /// \code
  5820. /// %s1 = shufflevector <2 x ty> %0, poison, <1, 0>
  5821. /// %s2 = shufflevector <2 x ty> %1, poison, <1, 0>
  5822. /// \endcode
  5823. /// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 3, 2>, it will
  5824. /// look through %s1 and %s2 and select vectors %0 and %1 with mask
  5825. /// <0, 1, 2, 3> for the shuffle.
  5826. /// If 2 operands are of different size, the smallest one will be resized and
  5827. /// the mask recalculated properly.
  5828. /// For example, given the code
  5829. /// \code
  5830. /// %s1 = shufflevector <2 x ty> %0, poison, <1, 0, 1, 0>
  5831. /// %s2 = shufflevector <2 x ty> %1, poison, <1, 0, 1, 0>
  5832. /// \endcode
  5833. /// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 5, 4>, it will
  5834. /// look through %s1 and %s2 and select vectors %0 and %1 with mask
  5835. /// <0, 1, 2, 3> for the shuffle.
  5836. /// So, it tries to transform permutations to simple vector merge, if
  5837. /// possible.
  5838. /// \param V The input vector which must be shuffled using the given \p Mask.
  5839. /// If the better candidate is found, \p V is set to this best candidate
  5840. /// vector.
  5841. /// \param Mask The input mask for the shuffle. If the best candidate is found
  5842. /// during looking-through-shuffles attempt, it is updated accordingly.
  5843. /// \param SinglePermute true if the shuffle operation is originally a
  5844. /// single-value-permutation. In this case the look-through-shuffles procedure
  5845. /// may look for resizing shuffles as the best candidates.
  5846. /// \return true if the shuffle results in the non-resizing identity shuffle
  5847. /// (and thus can be ignored), false - otherwise.
  5848. static bool peekThroughShuffles(Value *&V, SmallVectorImpl<int> &Mask,
  5849. bool SinglePermute) {
  5850. Value *Op = V;
  5851. ShuffleVectorInst *IdentityOp = nullptr;
  5852. SmallVector<int> IdentityMask;
  5853. while (auto *SV = dyn_cast<ShuffleVectorInst>(Op)) {
  5854. // Exit if not a fixed vector type or changing size shuffle.
  5855. auto *SVTy = dyn_cast<FixedVectorType>(SV->getType());
  5856. if (!SVTy)
  5857. break;
  5858. // Remember the identity or broadcast mask, if it is not a resizing
  5859. // shuffle. If no better candidates are found, this Op and Mask will be
  5860. // used in the final shuffle.
  5861. if (isIdentityMask(Mask, SVTy, /*IsStrict=*/false)) {
  5862. if (!IdentityOp || !SinglePermute ||
  5863. (isIdentityMask(Mask, SVTy, /*IsStrict=*/true) &&
  5864. !ShuffleVectorInst::isZeroEltSplatMask(IdentityMask))) {
  5865. IdentityOp = SV;
  5866. // Store current mask in the IdentityMask so later we did not lost
  5867. // this info if IdentityOp is selected as the best candidate for the
  5868. // permutation.
  5869. IdentityMask.assign(Mask);
  5870. }
  5871. }
  5872. // Remember the broadcast mask. If no better candidates are found, this Op
  5873. // and Mask will be used in the final shuffle.
  5874. // Zero splat can be used as identity too, since it might be used with
  5875. // mask <0, 1, 2, ...>, i.e. identity mask without extra reshuffling.
  5876. // E.g. if need to shuffle the vector with the mask <3, 1, 2, 0>, which is
  5877. // expensive, the analysis founds out, that the source vector is just a
  5878. // broadcast, this original mask can be transformed to identity mask <0,
  5879. // 1, 2, 3>.
  5880. // \code
  5881. // %0 = shuffle %v, poison, zeroinitalizer
  5882. // %res = shuffle %0, poison, <3, 1, 2, 0>
  5883. // \endcode
  5884. // may be transformed to
  5885. // \code
  5886. // %0 = shuffle %v, poison, zeroinitalizer
  5887. // %res = shuffle %0, poison, <0, 1, 2, 3>
  5888. // \endcode
  5889. if (SV->isZeroEltSplat()) {
  5890. IdentityOp = SV;
  5891. IdentityMask.assign(Mask);
  5892. }
  5893. int LocalVF = Mask.size();
  5894. if (auto *SVOpTy =
  5895. dyn_cast<FixedVectorType>(SV->getOperand(0)->getType()))
  5896. LocalVF = SVOpTy->getNumElements();
  5897. SmallVector<int> ExtMask(Mask.size(), UndefMaskElem);
  5898. for (auto [Idx, I] : enumerate(Mask)) {
  5899. if (I == UndefMaskElem)
  5900. continue;
  5901. ExtMask[Idx] = SV->getMaskValue(I);
  5902. }
  5903. bool IsOp1Undef =
  5904. isUndefVector(SV->getOperand(0),
  5905. buildUseMask(LocalVF, ExtMask, UseMask::FirstArg))
  5906. .all();
  5907. bool IsOp2Undef =
  5908. isUndefVector(SV->getOperand(1),
  5909. buildUseMask(LocalVF, ExtMask, UseMask::SecondArg))
  5910. .all();
  5911. if (!IsOp1Undef && !IsOp2Undef) {
  5912. // Update mask and mark undef elems.
  5913. for (int &I : Mask) {
  5914. if (I == UndefMaskElem)
  5915. continue;
  5916. if (SV->getMaskValue(I % SV->getShuffleMask().size()) ==
  5917. UndefMaskElem)
  5918. I = UndefMaskElem;
  5919. }
  5920. break;
  5921. }
  5922. SmallVector<int> ShuffleMask(SV->getShuffleMask().begin(),
  5923. SV->getShuffleMask().end());
  5924. combineMasks(LocalVF, ShuffleMask, Mask);
  5925. Mask.swap(ShuffleMask);
  5926. if (IsOp2Undef)
  5927. Op = SV->getOperand(0);
  5928. else
  5929. Op = SV->getOperand(1);
  5930. }
  5931. if (auto *OpTy = dyn_cast<FixedVectorType>(Op->getType());
  5932. !OpTy || !isIdentityMask(Mask, OpTy, SinglePermute)) {
  5933. if (IdentityOp) {
  5934. V = IdentityOp;
  5935. assert(Mask.size() == IdentityMask.size() &&
  5936. "Expected masks of same sizes.");
  5937. // Clear known poison elements.
  5938. for (auto [I, Idx] : enumerate(Mask))
  5939. if (Idx == UndefMaskElem)
  5940. IdentityMask[I] = UndefMaskElem;
  5941. Mask.swap(IdentityMask);
  5942. auto *Shuffle = dyn_cast<ShuffleVectorInst>(V);
  5943. return SinglePermute &&
  5944. (isIdentityMask(Mask, cast<FixedVectorType>(V->getType()),
  5945. /*IsStrict=*/true) ||
  5946. (Shuffle && Mask.size() == Shuffle->getShuffleMask().size() &&
  5947. Shuffle->isZeroEltSplat() &&
  5948. ShuffleVectorInst::isZeroEltSplatMask(Mask)));
  5949. }
  5950. V = Op;
  5951. return false;
  5952. }
  5953. V = Op;
  5954. return true;
  5955. }
  5956. /// Smart shuffle instruction emission, walks through shuffles trees and
  5957. /// tries to find the best matching vector for the actual shuffle
  5958. /// instruction.
  5959. template <typename ShuffleBuilderTy>
  5960. static Value *createShuffle(Value *V1, Value *V2, ArrayRef<int> Mask,
  5961. ShuffleBuilderTy &Builder) {
  5962. assert(V1 && "Expected at least one vector value.");
  5963. int VF = Mask.size();
  5964. if (auto *FTy = dyn_cast<FixedVectorType>(V1->getType()))
  5965. VF = FTy->getNumElements();
  5966. if (V2 &&
  5967. !isUndefVector(V2, buildUseMask(VF, Mask, UseMask::SecondArg)).all()) {
  5968. // Peek through shuffles.
  5969. Value *Op1 = V1;
  5970. Value *Op2 = V2;
  5971. int VF =
  5972. cast<VectorType>(V1->getType())->getElementCount().getKnownMinValue();
  5973. SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem);
  5974. SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem);
  5975. for (int I = 0, E = Mask.size(); I < E; ++I) {
  5976. if (Mask[I] < VF)
  5977. CombinedMask1[I] = Mask[I];
  5978. else
  5979. CombinedMask2[I] = Mask[I] - VF;
  5980. }
  5981. Value *PrevOp1;
  5982. Value *PrevOp2;
  5983. do {
  5984. PrevOp1 = Op1;
  5985. PrevOp2 = Op2;
  5986. (void)peekThroughShuffles(Op1, CombinedMask1, /*SinglePermute=*/false);
  5987. (void)peekThroughShuffles(Op2, CombinedMask2, /*SinglePermute=*/false);
  5988. // Check if we have 2 resizing shuffles - need to peek through operands
  5989. // again.
  5990. if (auto *SV1 = dyn_cast<ShuffleVectorInst>(Op1))
  5991. if (auto *SV2 = dyn_cast<ShuffleVectorInst>(Op2)) {
  5992. SmallVector<int> ExtMask1(Mask.size(), UndefMaskElem);
  5993. for (auto [Idx, I] : enumerate(CombinedMask1)) {
  5994. if (I == UndefMaskElem)
  5995. continue;
  5996. ExtMask1[Idx] = SV1->getMaskValue(I);
  5997. }
  5998. SmallBitVector UseMask1 = buildUseMask(
  5999. cast<FixedVectorType>(SV1->getOperand(1)->getType())
  6000. ->getNumElements(),
  6001. ExtMask1, UseMask::SecondArg);
  6002. SmallVector<int> ExtMask2(CombinedMask2.size(), UndefMaskElem);
  6003. for (auto [Idx, I] : enumerate(CombinedMask2)) {
  6004. if (I == UndefMaskElem)
  6005. continue;
  6006. ExtMask2[Idx] = SV2->getMaskValue(I);
  6007. }
  6008. SmallBitVector UseMask2 = buildUseMask(
  6009. cast<FixedVectorType>(SV2->getOperand(1)->getType())
  6010. ->getNumElements(),
  6011. ExtMask2, UseMask::SecondArg);
  6012. if (SV1->getOperand(0)->getType() ==
  6013. SV2->getOperand(0)->getType() &&
  6014. SV1->getOperand(0)->getType() != SV1->getType() &&
  6015. isUndefVector(SV1->getOperand(1), UseMask1).all() &&
  6016. isUndefVector(SV2->getOperand(1), UseMask2).all()) {
  6017. Op1 = SV1->getOperand(0);
  6018. Op2 = SV2->getOperand(0);
  6019. SmallVector<int> ShuffleMask1(SV1->getShuffleMask().begin(),
  6020. SV1->getShuffleMask().end());
  6021. int LocalVF = ShuffleMask1.size();
  6022. if (auto *FTy = dyn_cast<FixedVectorType>(Op1->getType()))
  6023. LocalVF = FTy->getNumElements();
  6024. combineMasks(LocalVF, ShuffleMask1, CombinedMask1);
  6025. CombinedMask1.swap(ShuffleMask1);
  6026. SmallVector<int> ShuffleMask2(SV2->getShuffleMask().begin(),
  6027. SV2->getShuffleMask().end());
  6028. LocalVF = ShuffleMask2.size();
  6029. if (auto *FTy = dyn_cast<FixedVectorType>(Op2->getType()))
  6030. LocalVF = FTy->getNumElements();
  6031. combineMasks(LocalVF, ShuffleMask2, CombinedMask2);
  6032. CombinedMask2.swap(ShuffleMask2);
  6033. }
  6034. }
  6035. } while (PrevOp1 != Op1 || PrevOp2 != Op2);
  6036. Builder.resizeToMatch(Op1, Op2);
  6037. VF = std::max(cast<VectorType>(Op1->getType())
  6038. ->getElementCount()
  6039. .getKnownMinValue(),
  6040. cast<VectorType>(Op2->getType())
  6041. ->getElementCount()
  6042. .getKnownMinValue());
  6043. for (int I = 0, E = Mask.size(); I < E; ++I) {
  6044. if (CombinedMask2[I] != UndefMaskElem) {
  6045. assert(CombinedMask1[I] == UndefMaskElem &&
  6046. "Expected undefined mask element");
  6047. CombinedMask1[I] = CombinedMask2[I] + (Op1 == Op2 ? 0 : VF);
  6048. }
  6049. }
  6050. return Builder.createShuffleVector(
  6051. Op1, Op1 == Op2 ? PoisonValue::get(Op1->getType()) : Op2,
  6052. CombinedMask1);
  6053. }
  6054. if (isa<PoisonValue>(V1))
  6055. return PoisonValue::get(FixedVectorType::get(
  6056. cast<VectorType>(V1->getType())->getElementType(), Mask.size()));
  6057. SmallVector<int> NewMask(Mask.begin(), Mask.end());
  6058. bool IsIdentity = peekThroughShuffles(V1, NewMask, /*SinglePermute=*/true);
  6059. assert(V1 && "Expected non-null value after looking through shuffles.");
  6060. if (!IsIdentity)
  6061. return Builder.createShuffleVector(V1, NewMask);
  6062. return V1;
  6063. }
  6064. };
  6065. } // namespace
  6066. InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
  6067. ArrayRef<Value *> VectorizedVals) {
  6068. ArrayRef<Value *> VL = E->Scalars;
  6069. Type *ScalarTy = VL[0]->getType();
  6070. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  6071. ScalarTy = SI->getValueOperand()->getType();
  6072. else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
  6073. ScalarTy = CI->getOperand(0)->getType();
  6074. else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
  6075. ScalarTy = IE->getOperand(1)->getType();
  6076. auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
  6077. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  6078. // If we have computed a smaller type for the expression, update VecTy so
  6079. // that the costs will be accurate.
  6080. if (MinBWs.count(VL[0]))
  6081. VecTy = FixedVectorType::get(
  6082. IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
  6083. unsigned EntryVF = E->getVectorFactor();
  6084. auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
  6085. bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
  6086. // FIXME: it tries to fix a problem with MSVC buildbots.
  6087. TargetTransformInfo *TTI = this->TTI;
  6088. auto AdjustExtractsCost = [=](InstructionCost &Cost) {
  6089. // If the resulting type is scalarized, do not adjust the cost.
  6090. unsigned VecNumParts = TTI->getNumberOfParts(VecTy);
  6091. if (VecNumParts == VecTy->getNumElements())
  6092. return;
  6093. DenseMap<Value *, int> ExtractVectorsTys;
  6094. SmallPtrSet<Value *, 4> CheckedExtracts;
  6095. for (auto *V : VL) {
  6096. if (isa<UndefValue>(V))
  6097. continue;
  6098. // If all users of instruction are going to be vectorized and this
  6099. // instruction itself is not going to be vectorized, consider this
  6100. // instruction as dead and remove its cost from the final cost of the
  6101. // vectorized tree.
  6102. // Also, avoid adjusting the cost for extractelements with multiple uses
  6103. // in different graph entries.
  6104. const TreeEntry *VE = getTreeEntry(V);
  6105. if (!CheckedExtracts.insert(V).second ||
  6106. !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
  6107. (VE && VE != E))
  6108. continue;
  6109. auto *EE = cast<ExtractElementInst>(V);
  6110. std::optional<unsigned> EEIdx = getExtractIndex(EE);
  6111. if (!EEIdx)
  6112. continue;
  6113. unsigned Idx = *EEIdx;
  6114. if (VecNumParts != TTI->getNumberOfParts(EE->getVectorOperandType())) {
  6115. auto It =
  6116. ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
  6117. It->getSecond() = std::min<int>(It->second, Idx);
  6118. }
  6119. // Take credit for instruction that will become dead.
  6120. if (EE->hasOneUse()) {
  6121. Instruction *Ext = EE->user_back();
  6122. if (isa<SExtInst, ZExtInst>(Ext) && all_of(Ext->users(), [](User *U) {
  6123. return isa<GetElementPtrInst>(U);
  6124. })) {
  6125. // Use getExtractWithExtendCost() to calculate the cost of
  6126. // extractelement/ext pair.
  6127. Cost -=
  6128. TTI->getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
  6129. EE->getVectorOperandType(), Idx);
  6130. // Add back the cost of s|zext which is subtracted separately.
  6131. Cost += TTI->getCastInstrCost(
  6132. Ext->getOpcode(), Ext->getType(), EE->getType(),
  6133. TTI::getCastContextHint(Ext), CostKind, Ext);
  6134. continue;
  6135. }
  6136. }
  6137. Cost -= TTI->getVectorInstrCost(*EE, EE->getVectorOperandType(), CostKind,
  6138. Idx);
  6139. }
  6140. // Add a cost for subvector extracts/inserts if required.
  6141. for (const auto &Data : ExtractVectorsTys) {
  6142. auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
  6143. unsigned NumElts = VecTy->getNumElements();
  6144. if (Data.second % NumElts == 0)
  6145. continue;
  6146. if (TTI->getNumberOfParts(EEVTy) > VecNumParts) {
  6147. unsigned Idx = (Data.second / NumElts) * NumElts;
  6148. unsigned EENumElts = EEVTy->getNumElements();
  6149. if (Idx + NumElts <= EENumElts) {
  6150. Cost +=
  6151. TTI->getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  6152. EEVTy, std::nullopt, CostKind, Idx, VecTy);
  6153. } else {
  6154. // Need to round up the subvector type vectorization factor to avoid a
  6155. // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
  6156. // <= EENumElts.
  6157. auto *SubVT =
  6158. FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
  6159. Cost +=
  6160. TTI->getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  6161. EEVTy, std::nullopt, CostKind, Idx, SubVT);
  6162. }
  6163. } else {
  6164. Cost += TTI->getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
  6165. VecTy, std::nullopt, CostKind, 0, EEVTy);
  6166. }
  6167. }
  6168. };
  6169. if (E->State == TreeEntry::NeedToGather) {
  6170. if (allConstant(VL))
  6171. return 0;
  6172. if (isa<InsertElementInst>(VL[0]))
  6173. return InstructionCost::getInvalid();
  6174. SmallVector<Value *> GatheredScalars(E->Scalars.begin(), E->Scalars.end());
  6175. // Build a mask out of the reorder indices and reorder scalars per this
  6176. // mask.
  6177. SmallVector<int> ReorderMask;
  6178. inversePermutation(E->ReorderIndices, ReorderMask);
  6179. if (!ReorderMask.empty())
  6180. reorderScalars(GatheredScalars, ReorderMask);
  6181. SmallVector<int> Mask;
  6182. std::optional<TargetTransformInfo::ShuffleKind> GatherShuffle;
  6183. SmallVector<const TreeEntry *> Entries;
  6184. // Do not try to look for reshuffled loads for gathered loads (they will be
  6185. // handled later), for vectorized scalars, and cases, which are definitely
  6186. // not profitable (splats and small gather nodes.)
  6187. if (E->getOpcode() != Instruction::Load || E->isAltShuffle() ||
  6188. all_of(E->Scalars, [this](Value *V) { return getTreeEntry(V); }) ||
  6189. isSplat(E->Scalars) ||
  6190. (E->Scalars != GatheredScalars && GatheredScalars.size() <= 2))
  6191. GatherShuffle = isGatherShuffledEntry(E, GatheredScalars, Mask, Entries);
  6192. if (GatherShuffle) {
  6193. // Remove shuffled elements from list of gathers.
  6194. for (int I = 0, Sz = Mask.size(); I < Sz; ++I) {
  6195. if (Mask[I] != UndefMaskElem)
  6196. GatheredScalars[I] = PoisonValue::get(ScalarTy);
  6197. }
  6198. assert((Entries.size() == 1 || Entries.size() == 2) &&
  6199. "Expected shuffle of 1 or 2 entries.");
  6200. InstructionCost GatherCost = 0;
  6201. int Limit = Mask.size() * 2;
  6202. if (all_of(Mask, [=](int Idx) { return Idx < Limit; }) &&
  6203. ShuffleVectorInst::isIdentityMask(Mask)) {
  6204. // Perfect match in the graph, will reuse the previously vectorized
  6205. // node. Cost is 0.
  6206. LLVM_DEBUG(
  6207. dbgs()
  6208. << "SLP: perfect diamond match for gather bundle that starts with "
  6209. << *VL.front() << ".\n");
  6210. if (NeedToShuffleReuses)
  6211. GatherCost =
  6212. TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
  6213. FinalVecTy, E->ReuseShuffleIndices);
  6214. } else {
  6215. LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
  6216. << " entries for bundle that starts with "
  6217. << *VL.front() << ".\n");
  6218. // Detected that instead of gather we can emit a shuffle of single/two
  6219. // previously vectorized nodes. Add the cost of the permutation rather
  6220. // than gather.
  6221. ::addMask(Mask, E->ReuseShuffleIndices);
  6222. GatherCost = TTI->getShuffleCost(*GatherShuffle, FinalVecTy, Mask);
  6223. }
  6224. if (!all_of(GatheredScalars, UndefValue::classof))
  6225. GatherCost += getGatherCost(GatheredScalars);
  6226. return GatherCost;
  6227. }
  6228. if ((E->getOpcode() == Instruction::ExtractElement ||
  6229. all_of(E->Scalars,
  6230. [](Value *V) {
  6231. return isa<ExtractElementInst, UndefValue>(V);
  6232. })) &&
  6233. allSameType(VL)) {
  6234. // Check that gather of extractelements can be represented as just a
  6235. // shuffle of a single/two vectors the scalars are extracted from.
  6236. SmallVector<int> Mask;
  6237. std::optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
  6238. isFixedVectorShuffle(VL, Mask);
  6239. if (ShuffleKind) {
  6240. // Found the bunch of extractelement instructions that must be gathered
  6241. // into a vector and can be represented as a permutation elements in a
  6242. // single input vector or of 2 input vectors.
  6243. InstructionCost Cost =
  6244. computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
  6245. AdjustExtractsCost(Cost);
  6246. if (NeedToShuffleReuses)
  6247. Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
  6248. FinalVecTy, E->ReuseShuffleIndices);
  6249. return Cost;
  6250. }
  6251. }
  6252. if (isSplat(VL)) {
  6253. // Found the broadcasting of the single scalar, calculate the cost as the
  6254. // broadcast.
  6255. assert(VecTy == FinalVecTy &&
  6256. "No reused scalars expected for broadcast.");
  6257. const auto *It =
  6258. find_if(VL, [](Value *V) { return !isa<UndefValue>(V); });
  6259. // If all values are undefs - consider cost free.
  6260. if (It == VL.end())
  6261. return TTI::TCC_Free;
  6262. // Add broadcast for non-identity shuffle only.
  6263. bool NeedShuffle =
  6264. VL.front() != *It || !all_of(VL.drop_front(), UndefValue::classof);
  6265. InstructionCost InsertCost =
  6266. TTI->getVectorInstrCost(Instruction::InsertElement, VecTy, CostKind,
  6267. /*Index=*/0, PoisonValue::get(VecTy), *It);
  6268. return InsertCost + (NeedShuffle
  6269. ? TTI->getShuffleCost(
  6270. TargetTransformInfo::SK_Broadcast, VecTy,
  6271. /*Mask=*/std::nullopt, CostKind,
  6272. /*Index=*/0,
  6273. /*SubTp=*/nullptr, /*Args=*/VL[0])
  6274. : TTI::TCC_Free);
  6275. }
  6276. InstructionCost ReuseShuffleCost = 0;
  6277. if (NeedToShuffleReuses)
  6278. ReuseShuffleCost = TTI->getShuffleCost(
  6279. TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
  6280. // Improve gather cost for gather of loads, if we can group some of the
  6281. // loads into vector loads.
  6282. if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
  6283. !E->isAltShuffle()) {
  6284. BoUpSLP::ValueSet VectorizedLoads;
  6285. unsigned StartIdx = 0;
  6286. unsigned VF = VL.size() / 2;
  6287. unsigned VectorizedCnt = 0;
  6288. unsigned ScatterVectorizeCnt = 0;
  6289. const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
  6290. for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
  6291. for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
  6292. Cnt += VF) {
  6293. ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
  6294. if (!VectorizedLoads.count(Slice.front()) &&
  6295. !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
  6296. SmallVector<Value *> PointerOps;
  6297. OrdersType CurrentOrder;
  6298. LoadsState LS =
  6299. canVectorizeLoads(Slice, Slice.front(), *TTI, *DL, *SE, *LI,
  6300. *TLI, CurrentOrder, PointerOps);
  6301. switch (LS) {
  6302. case LoadsState::Vectorize:
  6303. case LoadsState::ScatterVectorize:
  6304. // Mark the vectorized loads so that we don't vectorize them
  6305. // again.
  6306. if (LS == LoadsState::Vectorize)
  6307. ++VectorizedCnt;
  6308. else
  6309. ++ScatterVectorizeCnt;
  6310. VectorizedLoads.insert(Slice.begin(), Slice.end());
  6311. // If we vectorized initial block, no need to try to vectorize it
  6312. // again.
  6313. if (Cnt == StartIdx)
  6314. StartIdx += VF;
  6315. break;
  6316. case LoadsState::Gather:
  6317. break;
  6318. }
  6319. }
  6320. }
  6321. // Check if the whole array was vectorized already - exit.
  6322. if (StartIdx >= VL.size())
  6323. break;
  6324. // Found vectorizable parts - exit.
  6325. if (!VectorizedLoads.empty())
  6326. break;
  6327. }
  6328. if (!VectorizedLoads.empty()) {
  6329. InstructionCost GatherCost = 0;
  6330. unsigned NumParts = TTI->getNumberOfParts(VecTy);
  6331. bool NeedInsertSubvectorAnalysis =
  6332. !NumParts || (VL.size() / VF) > NumParts;
  6333. // Get the cost for gathered loads.
  6334. for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
  6335. if (VectorizedLoads.contains(VL[I]))
  6336. continue;
  6337. GatherCost += getGatherCost(VL.slice(I, VF));
  6338. }
  6339. // The cost for vectorized loads.
  6340. InstructionCost ScalarsCost = 0;
  6341. for (Value *V : VectorizedLoads) {
  6342. auto *LI = cast<LoadInst>(V);
  6343. ScalarsCost +=
  6344. TTI->getMemoryOpCost(Instruction::Load, LI->getType(),
  6345. LI->getAlign(), LI->getPointerAddressSpace(),
  6346. CostKind, TTI::OperandValueInfo(), LI);
  6347. }
  6348. auto *LI = cast<LoadInst>(E->getMainOp());
  6349. auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
  6350. Align Alignment = LI->getAlign();
  6351. GatherCost +=
  6352. VectorizedCnt *
  6353. TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
  6354. LI->getPointerAddressSpace(), CostKind,
  6355. TTI::OperandValueInfo(), LI);
  6356. GatherCost += ScatterVectorizeCnt *
  6357. TTI->getGatherScatterOpCost(
  6358. Instruction::Load, LoadTy, LI->getPointerOperand(),
  6359. /*VariableMask=*/false, Alignment, CostKind, LI);
  6360. if (NeedInsertSubvectorAnalysis) {
  6361. // Add the cost for the subvectors insert.
  6362. for (int I = VF, E = VL.size(); I < E; I += VF)
  6363. GatherCost +=
  6364. TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
  6365. std::nullopt, CostKind, I, LoadTy);
  6366. }
  6367. return ReuseShuffleCost + GatherCost - ScalarsCost;
  6368. }
  6369. }
  6370. return ReuseShuffleCost + getGatherCost(VL);
  6371. }
  6372. InstructionCost CommonCost = 0;
  6373. SmallVector<int> Mask;
  6374. if (!E->ReorderIndices.empty()) {
  6375. SmallVector<int> NewMask;
  6376. if (E->getOpcode() == Instruction::Store) {
  6377. // For stores the order is actually a mask.
  6378. NewMask.resize(E->ReorderIndices.size());
  6379. copy(E->ReorderIndices, NewMask.begin());
  6380. } else {
  6381. inversePermutation(E->ReorderIndices, NewMask);
  6382. }
  6383. ::addMask(Mask, NewMask);
  6384. }
  6385. if (NeedToShuffleReuses)
  6386. ::addMask(Mask, E->ReuseShuffleIndices);
  6387. if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
  6388. CommonCost =
  6389. TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
  6390. assert((E->State == TreeEntry::Vectorize ||
  6391. E->State == TreeEntry::ScatterVectorize) &&
  6392. "Unhandled state");
  6393. assert(E->getOpcode() &&
  6394. ((allSameType(VL) && allSameBlock(VL)) ||
  6395. (E->getOpcode() == Instruction::GetElementPtr &&
  6396. E->getMainOp()->getType()->isPointerTy())) &&
  6397. "Invalid VL");
  6398. Instruction *VL0 = E->getMainOp();
  6399. unsigned ShuffleOrOp =
  6400. E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
  6401. const unsigned Sz = VL.size();
  6402. auto GetCostDiff =
  6403. [=](function_ref<InstructionCost(unsigned)> ScalarEltCost,
  6404. function_ref<InstructionCost(InstructionCost)> VectorCost) {
  6405. // Calculate the cost of this instruction.
  6406. InstructionCost ScalarCost = 0;
  6407. if (isa<CastInst, CmpInst, SelectInst, CallInst>(VL0)) {
  6408. // For some of the instructions no need to calculate cost for each
  6409. // particular instruction, we can use the cost of the single
  6410. // instruction x total number of scalar instructions.
  6411. ScalarCost = Sz * ScalarEltCost(0);
  6412. } else {
  6413. for (unsigned I = 0; I < Sz; ++I)
  6414. ScalarCost += ScalarEltCost(I);
  6415. }
  6416. InstructionCost VecCost = VectorCost(CommonCost);
  6417. LLVM_DEBUG(
  6418. dumpTreeCosts(E, CommonCost, VecCost - CommonCost, ScalarCost));
  6419. // Disable warnings for `this` and `E` are unused. Required for
  6420. // `dumpTreeCosts`.
  6421. (void)this;
  6422. (void)E;
  6423. return VecCost - ScalarCost;
  6424. };
  6425. // Calculate cost difference from vectorizing set of GEPs.
  6426. // Negative value means vectorizing is profitable.
  6427. auto GetGEPCostDiff = [=](ArrayRef<Value *> Ptrs, Value *BasePtr) {
  6428. InstructionCost CostSavings = 0;
  6429. for (Value *V : Ptrs) {
  6430. if (V == BasePtr)
  6431. continue;
  6432. auto *Ptr = dyn_cast<GetElementPtrInst>(V);
  6433. // GEPs may contain just addresses without instructions, considered free.
  6434. // GEPs with all constant indices also considered to have zero cost.
  6435. if (!Ptr || Ptr->hasAllConstantIndices())
  6436. continue;
  6437. // Here we differentiate two cases: when GEPs represent a regular
  6438. // vectorization tree node (and hence vectorized) and when the set is
  6439. // arguments of a set of loads or stores being vectorized. In the former
  6440. // case all the scalar GEPs will be removed as a result of vectorization.
  6441. // For any external uses of some lanes extract element instructions will
  6442. // be generated (which cost is estimated separately). For the latter case
  6443. // since the set of GEPs itself is not vectorized those used more than
  6444. // once will remain staying in vectorized code as well. So we should not
  6445. // count them as savings.
  6446. if (!Ptr->hasOneUse() && isa<LoadInst, StoreInst>(VL0))
  6447. continue;
  6448. // TODO: it is target dependent, so need to implement and then use a TTI
  6449. // interface.
  6450. CostSavings += TTI->getArithmeticInstrCost(Instruction::Add,
  6451. Ptr->getType(), CostKind);
  6452. }
  6453. LLVM_DEBUG(dbgs() << "SLP: Calculated GEPs cost savings or Tree:\n";
  6454. E->dump());
  6455. LLVM_DEBUG(dbgs() << "SLP: GEP cost saving = " << CostSavings << "\n");
  6456. return InstructionCost() - CostSavings;
  6457. };
  6458. switch (ShuffleOrOp) {
  6459. case Instruction::PHI: {
  6460. // Count reused scalars.
  6461. InstructionCost ScalarCost = 0;
  6462. SmallPtrSet<const TreeEntry *, 4> CountedOps;
  6463. for (Value *V : VL) {
  6464. auto *PHI = dyn_cast<PHINode>(V);
  6465. if (!PHI)
  6466. continue;
  6467. ValueList Operands(PHI->getNumIncomingValues(), nullptr);
  6468. for (unsigned I = 0, N = PHI->getNumIncomingValues(); I < N; ++I) {
  6469. Value *Op = PHI->getIncomingValue(I);
  6470. Operands[I] = Op;
  6471. }
  6472. if (const TreeEntry *OpTE = getTreeEntry(Operands.front()))
  6473. if (OpTE->isSame(Operands) && CountedOps.insert(OpTE).second)
  6474. if (!OpTE->ReuseShuffleIndices.empty())
  6475. ScalarCost += TTI::TCC_Basic * (OpTE->ReuseShuffleIndices.size() -
  6476. OpTE->Scalars.size());
  6477. }
  6478. return CommonCost - ScalarCost;
  6479. }
  6480. case Instruction::ExtractValue:
  6481. case Instruction::ExtractElement: {
  6482. auto GetScalarCost = [=](unsigned Idx) {
  6483. auto *I = cast<Instruction>(VL[Idx]);
  6484. VectorType *SrcVecTy;
  6485. if (ShuffleOrOp == Instruction::ExtractElement) {
  6486. auto *EE = cast<ExtractElementInst>(I);
  6487. SrcVecTy = EE->getVectorOperandType();
  6488. } else {
  6489. auto *EV = cast<ExtractValueInst>(I);
  6490. Type *AggregateTy = EV->getAggregateOperand()->getType();
  6491. unsigned NumElts;
  6492. if (auto *ATy = dyn_cast<ArrayType>(AggregateTy))
  6493. NumElts = ATy->getNumElements();
  6494. else
  6495. NumElts = AggregateTy->getStructNumElements();
  6496. SrcVecTy = FixedVectorType::get(ScalarTy, NumElts);
  6497. }
  6498. if (I->hasOneUse()) {
  6499. Instruction *Ext = I->user_back();
  6500. if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  6501. all_of(Ext->users(),
  6502. [](User *U) { return isa<GetElementPtrInst>(U); })) {
  6503. // Use getExtractWithExtendCost() to calculate the cost of
  6504. // extractelement/ext pair.
  6505. InstructionCost Cost = TTI->getExtractWithExtendCost(
  6506. Ext->getOpcode(), Ext->getType(), SrcVecTy, *getExtractIndex(I));
  6507. // Subtract the cost of s|zext which is subtracted separately.
  6508. Cost -= TTI->getCastInstrCost(
  6509. Ext->getOpcode(), Ext->getType(), I->getType(),
  6510. TTI::getCastContextHint(Ext), CostKind, Ext);
  6511. return Cost;
  6512. }
  6513. }
  6514. return TTI->getVectorInstrCost(Instruction::ExtractElement, SrcVecTy,
  6515. CostKind, *getExtractIndex(I));
  6516. };
  6517. auto GetVectorCost = [](InstructionCost CommonCost) { return CommonCost; };
  6518. return GetCostDiff(GetScalarCost, GetVectorCost);
  6519. }
  6520. case Instruction::InsertElement: {
  6521. assert(E->ReuseShuffleIndices.empty() &&
  6522. "Unique insertelements only are expected.");
  6523. auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
  6524. unsigned const NumElts = SrcVecTy->getNumElements();
  6525. unsigned const NumScalars = VL.size();
  6526. unsigned NumOfParts = TTI->getNumberOfParts(SrcVecTy);
  6527. SmallVector<int> InsertMask(NumElts, UndefMaskElem);
  6528. unsigned OffsetBeg = *getInsertIndex(VL.front());
  6529. unsigned OffsetEnd = OffsetBeg;
  6530. InsertMask[OffsetBeg] = 0;
  6531. for (auto [I, V] : enumerate(VL.drop_front())) {
  6532. unsigned Idx = *getInsertIndex(V);
  6533. if (OffsetBeg > Idx)
  6534. OffsetBeg = Idx;
  6535. else if (OffsetEnd < Idx)
  6536. OffsetEnd = Idx;
  6537. InsertMask[Idx] = I + 1;
  6538. }
  6539. unsigned VecScalarsSz = PowerOf2Ceil(NumElts);
  6540. if (NumOfParts > 0)
  6541. VecScalarsSz = PowerOf2Ceil((NumElts + NumOfParts - 1) / NumOfParts);
  6542. unsigned VecSz = (1 + OffsetEnd / VecScalarsSz - OffsetBeg / VecScalarsSz) *
  6543. VecScalarsSz;
  6544. unsigned Offset = VecScalarsSz * (OffsetBeg / VecScalarsSz);
  6545. unsigned InsertVecSz = std::min<unsigned>(
  6546. PowerOf2Ceil(OffsetEnd - OffsetBeg + 1),
  6547. ((OffsetEnd - OffsetBeg + VecScalarsSz) / VecScalarsSz) * VecScalarsSz);
  6548. bool IsWholeSubvector =
  6549. OffsetBeg == Offset && ((OffsetEnd + 1) % VecScalarsSz == 0);
  6550. // Check if we can safely insert a subvector. If it is not possible, just
  6551. // generate a whole-sized vector and shuffle the source vector and the new
  6552. // subvector.
  6553. if (OffsetBeg + InsertVecSz > VecSz) {
  6554. // Align OffsetBeg to generate correct mask.
  6555. OffsetBeg = alignDown(OffsetBeg, VecSz, Offset);
  6556. InsertVecSz = VecSz;
  6557. }
  6558. APInt DemandedElts = APInt::getZero(NumElts);
  6559. // TODO: Add support for Instruction::InsertValue.
  6560. SmallVector<int> Mask;
  6561. if (!E->ReorderIndices.empty()) {
  6562. inversePermutation(E->ReorderIndices, Mask);
  6563. Mask.append(InsertVecSz - Mask.size(), UndefMaskElem);
  6564. } else {
  6565. Mask.assign(VecSz, UndefMaskElem);
  6566. std::iota(Mask.begin(), std::next(Mask.begin(), InsertVecSz), 0);
  6567. }
  6568. bool IsIdentity = true;
  6569. SmallVector<int> PrevMask(InsertVecSz, UndefMaskElem);
  6570. Mask.swap(PrevMask);
  6571. for (unsigned I = 0; I < NumScalars; ++I) {
  6572. unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
  6573. DemandedElts.setBit(InsertIdx);
  6574. IsIdentity &= InsertIdx - OffsetBeg == I;
  6575. Mask[InsertIdx - OffsetBeg] = I;
  6576. }
  6577. assert(Offset < NumElts && "Failed to find vector index offset");
  6578. InstructionCost Cost = 0;
  6579. Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
  6580. /*Insert*/ true, /*Extract*/ false,
  6581. CostKind);
  6582. // First cost - resize to actual vector size if not identity shuffle or
  6583. // need to shift the vector.
  6584. // Do not calculate the cost if the actual size is the register size and
  6585. // we can merge this shuffle with the following SK_Select.
  6586. auto *InsertVecTy =
  6587. FixedVectorType::get(SrcVecTy->getElementType(), InsertVecSz);
  6588. if (!IsIdentity)
  6589. Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
  6590. InsertVecTy, Mask);
  6591. auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
  6592. return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
  6593. }));
  6594. // Second cost - permutation with subvector, if some elements are from the
  6595. // initial vector or inserting a subvector.
  6596. // TODO: Implement the analysis of the FirstInsert->getOperand(0)
  6597. // subvector of ActualVecTy.
  6598. SmallBitVector InMask =
  6599. isUndefVector(FirstInsert->getOperand(0),
  6600. buildUseMask(NumElts, InsertMask, UseMask::UndefsAsMask));
  6601. if (!InMask.all() && NumScalars != NumElts && !IsWholeSubvector) {
  6602. if (InsertVecSz != VecSz) {
  6603. auto *ActualVecTy =
  6604. FixedVectorType::get(SrcVecTy->getElementType(), VecSz);
  6605. Cost += TTI->getShuffleCost(TTI::SK_InsertSubvector, ActualVecTy,
  6606. std::nullopt, CostKind, OffsetBeg - Offset,
  6607. InsertVecTy);
  6608. } else {
  6609. for (unsigned I = 0, End = OffsetBeg - Offset; I < End; ++I)
  6610. Mask[I] = InMask.test(I) ? UndefMaskElem : I;
  6611. for (unsigned I = OffsetBeg - Offset, End = OffsetEnd - Offset;
  6612. I <= End; ++I)
  6613. if (Mask[I] != UndefMaskElem)
  6614. Mask[I] = I + VecSz;
  6615. for (unsigned I = OffsetEnd + 1 - Offset; I < VecSz; ++I)
  6616. Mask[I] =
  6617. ((I >= InMask.size()) || InMask.test(I)) ? UndefMaskElem : I;
  6618. Cost += TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, InsertVecTy, Mask);
  6619. }
  6620. }
  6621. return Cost;
  6622. }
  6623. case Instruction::ZExt:
  6624. case Instruction::SExt:
  6625. case Instruction::FPToUI:
  6626. case Instruction::FPToSI:
  6627. case Instruction::FPExt:
  6628. case Instruction::PtrToInt:
  6629. case Instruction::IntToPtr:
  6630. case Instruction::SIToFP:
  6631. case Instruction::UIToFP:
  6632. case Instruction::Trunc:
  6633. case Instruction::FPTrunc:
  6634. case Instruction::BitCast: {
  6635. auto GetScalarCost = [=](unsigned Idx) {
  6636. auto *VI = cast<Instruction>(VL[Idx]);
  6637. return TTI->getCastInstrCost(E->getOpcode(), ScalarTy,
  6638. VI->getOperand(0)->getType(),
  6639. TTI::getCastContextHint(VI), CostKind, VI);
  6640. };
  6641. auto GetVectorCost = [=](InstructionCost CommonCost) {
  6642. Type *SrcTy = VL0->getOperand(0)->getType();
  6643. auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
  6644. InstructionCost VecCost = CommonCost;
  6645. // Check if the values are candidates to demote.
  6646. if (!MinBWs.count(VL0) || VecTy != SrcVecTy)
  6647. VecCost +=
  6648. TTI->getCastInstrCost(E->getOpcode(), VecTy, SrcVecTy,
  6649. TTI::getCastContextHint(VL0), CostKind, VL0);
  6650. return VecCost;
  6651. };
  6652. return GetCostDiff(GetScalarCost, GetVectorCost);
  6653. }
  6654. case Instruction::FCmp:
  6655. case Instruction::ICmp:
  6656. case Instruction::Select: {
  6657. CmpInst::Predicate VecPred, SwappedVecPred;
  6658. auto MatchCmp = m_Cmp(VecPred, m_Value(), m_Value());
  6659. if (match(VL0, m_Select(MatchCmp, m_Value(), m_Value())) ||
  6660. match(VL0, MatchCmp))
  6661. SwappedVecPred = CmpInst::getSwappedPredicate(VecPred);
  6662. else
  6663. SwappedVecPred = VecPred = ScalarTy->isFloatingPointTy()
  6664. ? CmpInst::BAD_FCMP_PREDICATE
  6665. : CmpInst::BAD_ICMP_PREDICATE;
  6666. auto GetScalarCost = [&](unsigned Idx) {
  6667. auto *VI = cast<Instruction>(VL[Idx]);
  6668. CmpInst::Predicate CurrentPred = ScalarTy->isFloatingPointTy()
  6669. ? CmpInst::BAD_FCMP_PREDICATE
  6670. : CmpInst::BAD_ICMP_PREDICATE;
  6671. auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
  6672. if ((!match(VI, m_Select(MatchCmp, m_Value(), m_Value())) &&
  6673. !match(VI, MatchCmp)) ||
  6674. (CurrentPred != VecPred && CurrentPred != SwappedVecPred))
  6675. VecPred = SwappedVecPred = ScalarTy->isFloatingPointTy()
  6676. ? CmpInst::BAD_FCMP_PREDICATE
  6677. : CmpInst::BAD_ICMP_PREDICATE;
  6678. return TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
  6679. Builder.getInt1Ty(), CurrentPred, CostKind,
  6680. VI);
  6681. };
  6682. auto GetVectorCost = [&](InstructionCost CommonCost) {
  6683. auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
  6684. InstructionCost VecCost = TTI->getCmpSelInstrCost(
  6685. E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
  6686. // Check if it is possible and profitable to use min/max for selects
  6687. // in VL.
  6688. //
  6689. auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
  6690. if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
  6691. IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
  6692. {VecTy, VecTy});
  6693. InstructionCost IntrinsicCost =
  6694. TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
  6695. // If the selects are the only uses of the compares, they will be
  6696. // dead and we can adjust the cost by removing their cost.
  6697. if (IntrinsicAndUse.second)
  6698. IntrinsicCost -= TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy,
  6699. MaskTy, VecPred, CostKind);
  6700. VecCost = std::min(VecCost, IntrinsicCost);
  6701. }
  6702. return VecCost + CommonCost;
  6703. };
  6704. return GetCostDiff(GetScalarCost, GetVectorCost);
  6705. }
  6706. case Instruction::FNeg:
  6707. case Instruction::Add:
  6708. case Instruction::FAdd:
  6709. case Instruction::Sub:
  6710. case Instruction::FSub:
  6711. case Instruction::Mul:
  6712. case Instruction::FMul:
  6713. case Instruction::UDiv:
  6714. case Instruction::SDiv:
  6715. case Instruction::FDiv:
  6716. case Instruction::URem:
  6717. case Instruction::SRem:
  6718. case Instruction::FRem:
  6719. case Instruction::Shl:
  6720. case Instruction::LShr:
  6721. case Instruction::AShr:
  6722. case Instruction::And:
  6723. case Instruction::Or:
  6724. case Instruction::Xor: {
  6725. auto GetScalarCost = [=](unsigned Idx) {
  6726. auto *VI = cast<Instruction>(VL[Idx]);
  6727. unsigned OpIdx = isa<UnaryOperator>(VI) ? 0 : 1;
  6728. TTI::OperandValueInfo Op1Info = TTI::getOperandInfo(VI->getOperand(0));
  6729. TTI::OperandValueInfo Op2Info =
  6730. TTI::getOperandInfo(VI->getOperand(OpIdx));
  6731. SmallVector<const Value *> Operands(VI->operand_values());
  6732. return TTI->getArithmeticInstrCost(ShuffleOrOp, ScalarTy, CostKind,
  6733. Op1Info, Op2Info, Operands, VI);
  6734. };
  6735. auto GetVectorCost = [=](InstructionCost CommonCost) {
  6736. unsigned OpIdx = isa<UnaryOperator>(VL0) ? 0 : 1;
  6737. TTI::OperandValueInfo Op1Info = getOperandInfo(VL, 0);
  6738. TTI::OperandValueInfo Op2Info = getOperandInfo(VL, OpIdx);
  6739. return TTI->getArithmeticInstrCost(ShuffleOrOp, VecTy, CostKind, Op1Info,
  6740. Op2Info) +
  6741. CommonCost;
  6742. };
  6743. return GetCostDiff(GetScalarCost, GetVectorCost);
  6744. }
  6745. case Instruction::GetElementPtr: {
  6746. return CommonCost + GetGEPCostDiff(VL, VL0);
  6747. }
  6748. case Instruction::Load: {
  6749. auto GetScalarCost = [=](unsigned Idx) {
  6750. auto *VI = cast<LoadInst>(VL[Idx]);
  6751. return TTI->getMemoryOpCost(Instruction::Load, ScalarTy, VI->getAlign(),
  6752. VI->getPointerAddressSpace(), CostKind,
  6753. TTI::OperandValueInfo(), VI);
  6754. };
  6755. auto *LI0 = cast<LoadInst>(VL0);
  6756. auto GetVectorCost = [=](InstructionCost CommonCost) {
  6757. InstructionCost VecLdCost;
  6758. if (E->State == TreeEntry::Vectorize) {
  6759. VecLdCost = TTI->getMemoryOpCost(
  6760. Instruction::Load, VecTy, LI0->getAlign(),
  6761. LI0->getPointerAddressSpace(), CostKind, TTI::OperandValueInfo());
  6762. } else {
  6763. assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
  6764. Align CommonAlignment = LI0->getAlign();
  6765. for (Value *V : VL)
  6766. CommonAlignment =
  6767. std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
  6768. VecLdCost = TTI->getGatherScatterOpCost(
  6769. Instruction::Load, VecTy, LI0->getPointerOperand(),
  6770. /*VariableMask=*/false, CommonAlignment, CostKind);
  6771. }
  6772. return VecLdCost + CommonCost;
  6773. };
  6774. InstructionCost Cost = GetCostDiff(GetScalarCost, GetVectorCost);
  6775. // If this node generates masked gather load then it is not a terminal node.
  6776. // Hence address operand cost is estimated separately.
  6777. if (E->State == TreeEntry::ScatterVectorize)
  6778. return Cost;
  6779. // Estimate cost of GEPs since this tree node is a terminator.
  6780. SmallVector<Value *> PointerOps(VL.size());
  6781. for (auto [I, V] : enumerate(VL))
  6782. PointerOps[I] = cast<LoadInst>(V)->getPointerOperand();
  6783. return Cost + GetGEPCostDiff(PointerOps, LI0->getPointerOperand());
  6784. }
  6785. case Instruction::Store: {
  6786. bool IsReorder = !E->ReorderIndices.empty();
  6787. auto GetScalarCost = [=](unsigned Idx) {
  6788. auto *VI = cast<StoreInst>(VL[Idx]);
  6789. TTI::OperandValueInfo OpInfo = getOperandInfo(VI, 0);
  6790. return TTI->getMemoryOpCost(Instruction::Store, ScalarTy, VI->getAlign(),
  6791. VI->getPointerAddressSpace(), CostKind,
  6792. OpInfo, VI);
  6793. };
  6794. auto *BaseSI =
  6795. cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
  6796. auto GetVectorCost = [=](InstructionCost CommonCost) {
  6797. // We know that we can merge the stores. Calculate the cost.
  6798. TTI::OperandValueInfo OpInfo = getOperandInfo(VL, 0);
  6799. return TTI->getMemoryOpCost(Instruction::Store, VecTy, BaseSI->getAlign(),
  6800. BaseSI->getPointerAddressSpace(), CostKind,
  6801. OpInfo) +
  6802. CommonCost;
  6803. };
  6804. SmallVector<Value *> PointerOps(VL.size());
  6805. for (auto [I, V] : enumerate(VL)) {
  6806. unsigned Idx = IsReorder ? E->ReorderIndices[I] : I;
  6807. PointerOps[Idx] = cast<StoreInst>(V)->getPointerOperand();
  6808. }
  6809. return GetCostDiff(GetScalarCost, GetVectorCost) +
  6810. GetGEPCostDiff(PointerOps, BaseSI->getPointerOperand());
  6811. }
  6812. case Instruction::Call: {
  6813. auto GetScalarCost = [=](unsigned Idx) {
  6814. auto *CI = cast<CallInst>(VL[Idx]);
  6815. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  6816. if (ID != Intrinsic::not_intrinsic) {
  6817. IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
  6818. return TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
  6819. }
  6820. return TTI->getCallInstrCost(CI->getCalledFunction(),
  6821. CI->getFunctionType()->getReturnType(),
  6822. CI->getFunctionType()->params(), CostKind);
  6823. };
  6824. auto GetVectorCost = [=](InstructionCost CommonCost) {
  6825. auto *CI = cast<CallInst>(VL0);
  6826. auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
  6827. return std::min(VecCallCosts.first, VecCallCosts.second) + CommonCost;
  6828. };
  6829. return GetCostDiff(GetScalarCost, GetVectorCost);
  6830. }
  6831. case Instruction::ShuffleVector: {
  6832. assert(E->isAltShuffle() &&
  6833. ((Instruction::isBinaryOp(E->getOpcode()) &&
  6834. Instruction::isBinaryOp(E->getAltOpcode())) ||
  6835. (Instruction::isCast(E->getOpcode()) &&
  6836. Instruction::isCast(E->getAltOpcode())) ||
  6837. (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
  6838. "Invalid Shuffle Vector Operand");
  6839. // Try to find the previous shuffle node with the same operands and same
  6840. // main/alternate ops.
  6841. auto TryFindNodeWithEqualOperands = [=]() {
  6842. for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
  6843. if (TE.get() == E)
  6844. break;
  6845. if (TE->isAltShuffle() &&
  6846. ((TE->getOpcode() == E->getOpcode() &&
  6847. TE->getAltOpcode() == E->getAltOpcode()) ||
  6848. (TE->getOpcode() == E->getAltOpcode() &&
  6849. TE->getAltOpcode() == E->getOpcode())) &&
  6850. TE->hasEqualOperands(*E))
  6851. return true;
  6852. }
  6853. return false;
  6854. };
  6855. auto GetScalarCost = [=](unsigned Idx) {
  6856. auto *VI = cast<Instruction>(VL[Idx]);
  6857. assert(E->isOpcodeOrAlt(VI) && "Unexpected main/alternate opcode");
  6858. (void)E;
  6859. return TTI->getInstructionCost(VI, CostKind);
  6860. };
  6861. // Need to clear CommonCost since the final shuffle cost is included into
  6862. // vector cost.
  6863. auto GetVectorCost = [&](InstructionCost) {
  6864. // VecCost is equal to sum of the cost of creating 2 vectors
  6865. // and the cost of creating shuffle.
  6866. InstructionCost VecCost = 0;
  6867. if (TryFindNodeWithEqualOperands()) {
  6868. LLVM_DEBUG({
  6869. dbgs() << "SLP: diamond match for alternate node found.\n";
  6870. E->dump();
  6871. });
  6872. // No need to add new vector costs here since we're going to reuse
  6873. // same main/alternate vector ops, just do different shuffling.
  6874. } else if (Instruction::isBinaryOp(E->getOpcode())) {
  6875. VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
  6876. VecCost +=
  6877. TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy, CostKind);
  6878. } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
  6879. VecCost = TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy,
  6880. Builder.getInt1Ty(),
  6881. CI0->getPredicate(), CostKind, VL0);
  6882. VecCost += TTI->getCmpSelInstrCost(
  6883. E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
  6884. cast<CmpInst>(E->getAltOp())->getPredicate(), CostKind,
  6885. E->getAltOp());
  6886. } else {
  6887. Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
  6888. Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
  6889. auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
  6890. auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
  6891. VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
  6892. TTI::CastContextHint::None, CostKind);
  6893. VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
  6894. TTI::CastContextHint::None, CostKind);
  6895. }
  6896. if (E->ReuseShuffleIndices.empty()) {
  6897. VecCost +=
  6898. TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy);
  6899. } else {
  6900. SmallVector<int> Mask;
  6901. buildShuffleEntryMask(
  6902. E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
  6903. [E](Instruction *I) {
  6904. assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
  6905. return I->getOpcode() == E->getAltOpcode();
  6906. },
  6907. Mask);
  6908. VecCost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteTwoSrc,
  6909. FinalVecTy, Mask);
  6910. }
  6911. return VecCost;
  6912. };
  6913. return GetCostDiff(GetScalarCost, GetVectorCost);
  6914. }
  6915. default:
  6916. llvm_unreachable("Unknown instruction");
  6917. }
  6918. }
  6919. bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
  6920. LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
  6921. << VectorizableTree.size() << " is fully vectorizable .\n");
  6922. auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
  6923. SmallVector<int> Mask;
  6924. return TE->State == TreeEntry::NeedToGather &&
  6925. !any_of(TE->Scalars,
  6926. [this](Value *V) { return EphValues.contains(V); }) &&
  6927. (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
  6928. TE->Scalars.size() < Limit ||
  6929. ((TE->getOpcode() == Instruction::ExtractElement ||
  6930. all_of(TE->Scalars,
  6931. [](Value *V) {
  6932. return isa<ExtractElementInst, UndefValue>(V);
  6933. })) &&
  6934. isFixedVectorShuffle(TE->Scalars, Mask)) ||
  6935. (TE->State == TreeEntry::NeedToGather &&
  6936. TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
  6937. };
  6938. // We only handle trees of heights 1 and 2.
  6939. if (VectorizableTree.size() == 1 &&
  6940. (VectorizableTree[0]->State == TreeEntry::Vectorize ||
  6941. (ForReduction &&
  6942. AreVectorizableGathers(VectorizableTree[0].get(),
  6943. VectorizableTree[0]->Scalars.size()) &&
  6944. VectorizableTree[0]->getVectorFactor() > 2)))
  6945. return true;
  6946. if (VectorizableTree.size() != 2)
  6947. return false;
  6948. // Handle splat and all-constants stores. Also try to vectorize tiny trees
  6949. // with the second gather nodes if they have less scalar operands rather than
  6950. // the initial tree element (may be profitable to shuffle the second gather)
  6951. // or they are extractelements, which form shuffle.
  6952. SmallVector<int> Mask;
  6953. if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
  6954. AreVectorizableGathers(VectorizableTree[1].get(),
  6955. VectorizableTree[0]->Scalars.size()))
  6956. return true;
  6957. // Gathering cost would be too much for tiny trees.
  6958. if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
  6959. (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
  6960. VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
  6961. return false;
  6962. return true;
  6963. }
  6964. static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
  6965. TargetTransformInfo *TTI,
  6966. bool MustMatchOrInst) {
  6967. // Look past the root to find a source value. Arbitrarily follow the
  6968. // path through operand 0 of any 'or'. Also, peek through optional
  6969. // shift-left-by-multiple-of-8-bits.
  6970. Value *ZextLoad = Root;
  6971. const APInt *ShAmtC;
  6972. bool FoundOr = false;
  6973. while (!isa<ConstantExpr>(ZextLoad) &&
  6974. (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
  6975. (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
  6976. ShAmtC->urem(8) == 0))) {
  6977. auto *BinOp = cast<BinaryOperator>(ZextLoad);
  6978. ZextLoad = BinOp->getOperand(0);
  6979. if (BinOp->getOpcode() == Instruction::Or)
  6980. FoundOr = true;
  6981. }
  6982. // Check if the input is an extended load of the required or/shift expression.
  6983. Value *Load;
  6984. if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
  6985. !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
  6986. return false;
  6987. // Require that the total load bit width is a legal integer type.
  6988. // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
  6989. // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
  6990. Type *SrcTy = Load->getType();
  6991. unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
  6992. if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
  6993. return false;
  6994. // Everything matched - assume that we can fold the whole sequence using
  6995. // load combining.
  6996. LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
  6997. << *(cast<Instruction>(Root)) << "\n");
  6998. return true;
  6999. }
  7000. bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
  7001. if (RdxKind != RecurKind::Or)
  7002. return false;
  7003. unsigned NumElts = VectorizableTree[0]->Scalars.size();
  7004. Value *FirstReduced = VectorizableTree[0]->Scalars[0];
  7005. return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
  7006. /* MatchOr */ false);
  7007. }
  7008. bool BoUpSLP::isLoadCombineCandidate() const {
  7009. // Peek through a final sequence of stores and check if all operations are
  7010. // likely to be load-combined.
  7011. unsigned NumElts = VectorizableTree[0]->Scalars.size();
  7012. for (Value *Scalar : VectorizableTree[0]->Scalars) {
  7013. Value *X;
  7014. if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
  7015. !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
  7016. return false;
  7017. }
  7018. return true;
  7019. }
  7020. bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
  7021. // No need to vectorize inserts of gathered values.
  7022. if (VectorizableTree.size() == 2 &&
  7023. isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
  7024. VectorizableTree[1]->State == TreeEntry::NeedToGather &&
  7025. (VectorizableTree[1]->getVectorFactor() <= 2 ||
  7026. !(isSplat(VectorizableTree[1]->Scalars) ||
  7027. allConstant(VectorizableTree[1]->Scalars))))
  7028. return true;
  7029. // We can vectorize the tree if its size is greater than or equal to the
  7030. // minimum size specified by the MinTreeSize command line option.
  7031. if (VectorizableTree.size() >= MinTreeSize)
  7032. return false;
  7033. // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
  7034. // can vectorize it if we can prove it fully vectorizable.
  7035. if (isFullyVectorizableTinyTree(ForReduction))
  7036. return false;
  7037. assert(VectorizableTree.empty()
  7038. ? ExternalUses.empty()
  7039. : true && "We shouldn't have any external users");
  7040. // Otherwise, we can't vectorize the tree. It is both tiny and not fully
  7041. // vectorizable.
  7042. return true;
  7043. }
  7044. InstructionCost BoUpSLP::getSpillCost() const {
  7045. // Walk from the bottom of the tree to the top, tracking which values are
  7046. // live. When we see a call instruction that is not part of our tree,
  7047. // query TTI to see if there is a cost to keeping values live over it
  7048. // (for example, if spills and fills are required).
  7049. unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
  7050. InstructionCost Cost = 0;
  7051. SmallPtrSet<Instruction*, 4> LiveValues;
  7052. Instruction *PrevInst = nullptr;
  7053. // The entries in VectorizableTree are not necessarily ordered by their
  7054. // position in basic blocks. Collect them and order them by dominance so later
  7055. // instructions are guaranteed to be visited first. For instructions in
  7056. // different basic blocks, we only scan to the beginning of the block, so
  7057. // their order does not matter, as long as all instructions in a basic block
  7058. // are grouped together. Using dominance ensures a deterministic order.
  7059. SmallVector<Instruction *, 16> OrderedScalars;
  7060. for (const auto &TEPtr : VectorizableTree) {
  7061. Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
  7062. if (!Inst)
  7063. continue;
  7064. OrderedScalars.push_back(Inst);
  7065. }
  7066. llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
  7067. auto *NodeA = DT->getNode(A->getParent());
  7068. auto *NodeB = DT->getNode(B->getParent());
  7069. assert(NodeA && "Should only process reachable instructions");
  7070. assert(NodeB && "Should only process reachable instructions");
  7071. assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
  7072. "Different nodes should have different DFS numbers");
  7073. if (NodeA != NodeB)
  7074. return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
  7075. return B->comesBefore(A);
  7076. });
  7077. for (Instruction *Inst : OrderedScalars) {
  7078. if (!PrevInst) {
  7079. PrevInst = Inst;
  7080. continue;
  7081. }
  7082. // Update LiveValues.
  7083. LiveValues.erase(PrevInst);
  7084. for (auto &J : PrevInst->operands()) {
  7085. if (isa<Instruction>(&*J) && getTreeEntry(&*J))
  7086. LiveValues.insert(cast<Instruction>(&*J));
  7087. }
  7088. LLVM_DEBUG({
  7089. dbgs() << "SLP: #LV: " << LiveValues.size();
  7090. for (auto *X : LiveValues)
  7091. dbgs() << " " << X->getName();
  7092. dbgs() << ", Looking at ";
  7093. Inst->dump();
  7094. });
  7095. // Now find the sequence of instructions between PrevInst and Inst.
  7096. unsigned NumCalls = 0;
  7097. BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
  7098. PrevInstIt =
  7099. PrevInst->getIterator().getReverse();
  7100. while (InstIt != PrevInstIt) {
  7101. if (PrevInstIt == PrevInst->getParent()->rend()) {
  7102. PrevInstIt = Inst->getParent()->rbegin();
  7103. continue;
  7104. }
  7105. auto NoCallIntrinsic = [this](Instruction *I) {
  7106. if (auto *II = dyn_cast<IntrinsicInst>(I)) {
  7107. if (II->isAssumeLikeIntrinsic())
  7108. return true;
  7109. FastMathFlags FMF;
  7110. SmallVector<Type *, 4> Tys;
  7111. for (auto &ArgOp : II->args())
  7112. Tys.push_back(ArgOp->getType());
  7113. if (auto *FPMO = dyn_cast<FPMathOperator>(II))
  7114. FMF = FPMO->getFastMathFlags();
  7115. IntrinsicCostAttributes ICA(II->getIntrinsicID(), II->getType(), Tys,
  7116. FMF);
  7117. InstructionCost IntrCost =
  7118. TTI->getIntrinsicInstrCost(ICA, TTI::TCK_RecipThroughput);
  7119. InstructionCost CallCost = TTI->getCallInstrCost(
  7120. nullptr, II->getType(), Tys, TTI::TCK_RecipThroughput);
  7121. if (IntrCost < CallCost)
  7122. return true;
  7123. }
  7124. return false;
  7125. };
  7126. // Debug information does not impact spill cost.
  7127. if (isa<CallInst>(&*PrevInstIt) && !NoCallIntrinsic(&*PrevInstIt) &&
  7128. &*PrevInstIt != PrevInst)
  7129. NumCalls++;
  7130. ++PrevInstIt;
  7131. }
  7132. if (NumCalls) {
  7133. SmallVector<Type*, 4> V;
  7134. for (auto *II : LiveValues) {
  7135. auto *ScalarTy = II->getType();
  7136. if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
  7137. ScalarTy = VectorTy->getElementType();
  7138. V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
  7139. }
  7140. Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
  7141. }
  7142. PrevInst = Inst;
  7143. }
  7144. return Cost;
  7145. }
  7146. /// Checks if the \p IE1 instructions is followed by \p IE2 instruction in the
  7147. /// buildvector sequence.
  7148. static bool isFirstInsertElement(const InsertElementInst *IE1,
  7149. const InsertElementInst *IE2) {
  7150. if (IE1 == IE2)
  7151. return false;
  7152. const auto *I1 = IE1;
  7153. const auto *I2 = IE2;
  7154. const InsertElementInst *PrevI1;
  7155. const InsertElementInst *PrevI2;
  7156. unsigned Idx1 = *getInsertIndex(IE1);
  7157. unsigned Idx2 = *getInsertIndex(IE2);
  7158. do {
  7159. if (I2 == IE1)
  7160. return true;
  7161. if (I1 == IE2)
  7162. return false;
  7163. PrevI1 = I1;
  7164. PrevI2 = I2;
  7165. if (I1 && (I1 == IE1 || I1->hasOneUse()) &&
  7166. getInsertIndex(I1).value_or(Idx2) != Idx2)
  7167. I1 = dyn_cast<InsertElementInst>(I1->getOperand(0));
  7168. if (I2 && ((I2 == IE2 || I2->hasOneUse())) &&
  7169. getInsertIndex(I2).value_or(Idx1) != Idx1)
  7170. I2 = dyn_cast<InsertElementInst>(I2->getOperand(0));
  7171. } while ((I1 && PrevI1 != I1) || (I2 && PrevI2 != I2));
  7172. llvm_unreachable("Two different buildvectors not expected.");
  7173. }
  7174. namespace {
  7175. /// Returns incoming Value *, if the requested type is Value * too, or a default
  7176. /// value, otherwise.
  7177. struct ValueSelect {
  7178. template <typename U>
  7179. static std::enable_if_t<std::is_same_v<Value *, U>, Value *> get(Value *V) {
  7180. return V;
  7181. }
  7182. template <typename U>
  7183. static std::enable_if_t<!std::is_same_v<Value *, U>, U> get(Value *) {
  7184. return U();
  7185. }
  7186. };
  7187. } // namespace
  7188. /// Does the analysis of the provided shuffle masks and performs the requested
  7189. /// actions on the vectors with the given shuffle masks. It tries to do it in
  7190. /// several steps.
  7191. /// 1. If the Base vector is not undef vector, resizing the very first mask to
  7192. /// have common VF and perform action for 2 input vectors (including non-undef
  7193. /// Base). Other shuffle masks are combined with the resulting after the 1 stage
  7194. /// and processed as a shuffle of 2 elements.
  7195. /// 2. If the Base is undef vector and have only 1 shuffle mask, perform the
  7196. /// action only for 1 vector with the given mask, if it is not the identity
  7197. /// mask.
  7198. /// 3. If > 2 masks are used, perform the remaining shuffle actions for 2
  7199. /// vectors, combing the masks properly between the steps.
  7200. template <typename T>
  7201. static T *performExtractsShuffleAction(
  7202. MutableArrayRef<std::pair<T *, SmallVector<int>>> ShuffleMask, Value *Base,
  7203. function_ref<unsigned(T *)> GetVF,
  7204. function_ref<std::pair<T *, bool>(T *, ArrayRef<int>, bool)> ResizeAction,
  7205. function_ref<T *(ArrayRef<int>, ArrayRef<T *>)> Action) {
  7206. assert(!ShuffleMask.empty() && "Empty list of shuffles for inserts.");
  7207. SmallVector<int> Mask(ShuffleMask.begin()->second);
  7208. auto VMIt = std::next(ShuffleMask.begin());
  7209. T *Prev = nullptr;
  7210. SmallBitVector UseMask =
  7211. buildUseMask(Mask.size(), Mask, UseMask::UndefsAsMask);
  7212. SmallBitVector IsBaseUndef = isUndefVector(Base, UseMask);
  7213. if (!IsBaseUndef.all()) {
  7214. // Base is not undef, need to combine it with the next subvectors.
  7215. std::pair<T *, bool> Res =
  7216. ResizeAction(ShuffleMask.begin()->first, Mask, /*ForSingleMask=*/false);
  7217. SmallBitVector IsBasePoison = isUndefVector<true>(Base, UseMask);
  7218. for (unsigned Idx = 0, VF = Mask.size(); Idx < VF; ++Idx) {
  7219. if (Mask[Idx] == UndefMaskElem)
  7220. Mask[Idx] = IsBasePoison.test(Idx) ? UndefMaskElem : Idx;
  7221. else
  7222. Mask[Idx] = (Res.second ? Idx : Mask[Idx]) + VF;
  7223. }
  7224. auto *V = ValueSelect::get<T *>(Base);
  7225. (void)V;
  7226. assert((!V || GetVF(V) == Mask.size()) &&
  7227. "Expected base vector of VF number of elements.");
  7228. Prev = Action(Mask, {nullptr, Res.first});
  7229. } else if (ShuffleMask.size() == 1) {
  7230. // Base is undef and only 1 vector is shuffled - perform the action only for
  7231. // single vector, if the mask is not the identity mask.
  7232. std::pair<T *, bool> Res = ResizeAction(ShuffleMask.begin()->first, Mask,
  7233. /*ForSingleMask=*/true);
  7234. if (Res.second)
  7235. // Identity mask is found.
  7236. Prev = Res.first;
  7237. else
  7238. Prev = Action(Mask, {ShuffleMask.begin()->first});
  7239. } else {
  7240. // Base is undef and at least 2 input vectors shuffled - perform 2 vectors
  7241. // shuffles step by step, combining shuffle between the steps.
  7242. unsigned Vec1VF = GetVF(ShuffleMask.begin()->first);
  7243. unsigned Vec2VF = GetVF(VMIt->first);
  7244. if (Vec1VF == Vec2VF) {
  7245. // No need to resize the input vectors since they are of the same size, we
  7246. // can shuffle them directly.
  7247. ArrayRef<int> SecMask = VMIt->second;
  7248. for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
  7249. if (SecMask[I] != UndefMaskElem) {
  7250. assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
  7251. Mask[I] = SecMask[I] + Vec1VF;
  7252. }
  7253. }
  7254. Prev = Action(Mask, {ShuffleMask.begin()->first, VMIt->first});
  7255. } else {
  7256. // Vectors of different sizes - resize and reshuffle.
  7257. std::pair<T *, bool> Res1 = ResizeAction(ShuffleMask.begin()->first, Mask,
  7258. /*ForSingleMask=*/false);
  7259. std::pair<T *, bool> Res2 =
  7260. ResizeAction(VMIt->first, VMIt->second, /*ForSingleMask=*/false);
  7261. ArrayRef<int> SecMask = VMIt->second;
  7262. for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
  7263. if (Mask[I] != UndefMaskElem) {
  7264. assert(SecMask[I] == UndefMaskElem && "Multiple uses of scalars.");
  7265. if (Res1.second)
  7266. Mask[I] = I;
  7267. } else if (SecMask[I] != UndefMaskElem) {
  7268. assert(Mask[I] == UndefMaskElem && "Multiple uses of scalars.");
  7269. Mask[I] = (Res2.second ? I : SecMask[I]) + VF;
  7270. }
  7271. }
  7272. Prev = Action(Mask, {Res1.first, Res2.first});
  7273. }
  7274. VMIt = std::next(VMIt);
  7275. }
  7276. bool IsBaseNotUndef = !IsBaseUndef.all();
  7277. (void)IsBaseNotUndef;
  7278. // Perform requested actions for the remaining masks/vectors.
  7279. for (auto E = ShuffleMask.end(); VMIt != E; ++VMIt) {
  7280. // Shuffle other input vectors, if any.
  7281. std::pair<T *, bool> Res =
  7282. ResizeAction(VMIt->first, VMIt->second, /*ForSingleMask=*/false);
  7283. ArrayRef<int> SecMask = VMIt->second;
  7284. for (unsigned I = 0, VF = Mask.size(); I < VF; ++I) {
  7285. if (SecMask[I] != UndefMaskElem) {
  7286. assert((Mask[I] == UndefMaskElem || IsBaseNotUndef) &&
  7287. "Multiple uses of scalars.");
  7288. Mask[I] = (Res.second ? I : SecMask[I]) + VF;
  7289. } else if (Mask[I] != UndefMaskElem) {
  7290. Mask[I] = I;
  7291. }
  7292. }
  7293. Prev = Action(Mask, {Prev, Res.first});
  7294. }
  7295. return Prev;
  7296. }
  7297. InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
  7298. InstructionCost Cost = 0;
  7299. LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
  7300. << VectorizableTree.size() << ".\n");
  7301. unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
  7302. for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
  7303. TreeEntry &TE = *VectorizableTree[I];
  7304. if (TE.State == TreeEntry::NeedToGather) {
  7305. if (const TreeEntry *E = getTreeEntry(TE.getMainOp());
  7306. E && E->getVectorFactor() == TE.getVectorFactor() &&
  7307. E->isSame(TE.Scalars)) {
  7308. // Some gather nodes might be absolutely the same as some vectorizable
  7309. // nodes after reordering, need to handle it.
  7310. LLVM_DEBUG(dbgs() << "SLP: Adding cost 0 for bundle that starts with "
  7311. << *TE.Scalars[0] << ".\n"
  7312. << "SLP: Current total cost = " << Cost << "\n");
  7313. continue;
  7314. }
  7315. }
  7316. InstructionCost C = getEntryCost(&TE, VectorizedVals);
  7317. Cost += C;
  7318. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  7319. << " for bundle that starts with " << *TE.Scalars[0]
  7320. << ".\n"
  7321. << "SLP: Current total cost = " << Cost << "\n");
  7322. }
  7323. SmallPtrSet<Value *, 16> ExtractCostCalculated;
  7324. InstructionCost ExtractCost = 0;
  7325. SmallVector<MapVector<const TreeEntry *, SmallVector<int>>> ShuffleMasks;
  7326. SmallVector<std::pair<Value *, const TreeEntry *>> FirstUsers;
  7327. SmallVector<APInt> DemandedElts;
  7328. for (ExternalUser &EU : ExternalUses) {
  7329. // We only add extract cost once for the same scalar.
  7330. if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
  7331. !ExtractCostCalculated.insert(EU.Scalar).second)
  7332. continue;
  7333. // Uses by ephemeral values are free (because the ephemeral value will be
  7334. // removed prior to code generation, and so the extraction will be
  7335. // removed as well).
  7336. if (EphValues.count(EU.User))
  7337. continue;
  7338. // No extract cost for vector "scalar"
  7339. if (isa<FixedVectorType>(EU.Scalar->getType()))
  7340. continue;
  7341. // If found user is an insertelement, do not calculate extract cost but try
  7342. // to detect it as a final shuffled/identity match.
  7343. if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
  7344. if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
  7345. std::optional<unsigned> InsertIdx = getInsertIndex(VU);
  7346. if (InsertIdx) {
  7347. const TreeEntry *ScalarTE = getTreeEntry(EU.Scalar);
  7348. auto *It = find_if(
  7349. FirstUsers,
  7350. [this, VU](const std::pair<Value *, const TreeEntry *> &Pair) {
  7351. return areTwoInsertFromSameBuildVector(
  7352. VU, cast<InsertElementInst>(Pair.first),
  7353. [this](InsertElementInst *II) -> Value * {
  7354. Value *Op0 = II->getOperand(0);
  7355. if (getTreeEntry(II) && !getTreeEntry(Op0))
  7356. return nullptr;
  7357. return Op0;
  7358. });
  7359. });
  7360. int VecId = -1;
  7361. if (It == FirstUsers.end()) {
  7362. (void)ShuffleMasks.emplace_back();
  7363. SmallVectorImpl<int> &Mask = ShuffleMasks.back()[ScalarTE];
  7364. if (Mask.empty())
  7365. Mask.assign(FTy->getNumElements(), UndefMaskElem);
  7366. // Find the insertvector, vectorized in tree, if any.
  7367. Value *Base = VU;
  7368. while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
  7369. if (IEBase != EU.User &&
  7370. (!IEBase->hasOneUse() ||
  7371. getInsertIndex(IEBase).value_or(*InsertIdx) == *InsertIdx))
  7372. break;
  7373. // Build the mask for the vectorized insertelement instructions.
  7374. if (const TreeEntry *E = getTreeEntry(IEBase)) {
  7375. VU = IEBase;
  7376. do {
  7377. IEBase = cast<InsertElementInst>(Base);
  7378. int Idx = *getInsertIndex(IEBase);
  7379. assert(Mask[Idx] == UndefMaskElem &&
  7380. "InsertElementInstruction used already.");
  7381. Mask[Idx] = Idx;
  7382. Base = IEBase->getOperand(0);
  7383. } while (E == getTreeEntry(Base));
  7384. break;
  7385. }
  7386. Base = cast<InsertElementInst>(Base)->getOperand(0);
  7387. }
  7388. FirstUsers.emplace_back(VU, ScalarTE);
  7389. DemandedElts.push_back(APInt::getZero(FTy->getNumElements()));
  7390. VecId = FirstUsers.size() - 1;
  7391. } else {
  7392. if (isFirstInsertElement(VU, cast<InsertElementInst>(It->first)))
  7393. It->first = VU;
  7394. VecId = std::distance(FirstUsers.begin(), It);
  7395. }
  7396. int InIdx = *InsertIdx;
  7397. SmallVectorImpl<int> &Mask = ShuffleMasks[VecId][ScalarTE];
  7398. if (Mask.empty())
  7399. Mask.assign(FTy->getNumElements(), UndefMaskElem);
  7400. Mask[InIdx] = EU.Lane;
  7401. DemandedElts[VecId].setBit(InIdx);
  7402. continue;
  7403. }
  7404. }
  7405. }
  7406. // If we plan to rewrite the tree in a smaller type, we will need to sign
  7407. // extend the extracted value back to the original type. Here, we account
  7408. // for the extract and the added cost of the sign extend if needed.
  7409. auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
  7410. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  7411. auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
  7412. if (MinBWs.count(ScalarRoot)) {
  7413. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  7414. auto Extend =
  7415. MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
  7416. VecTy = FixedVectorType::get(MinTy, BundleWidth);
  7417. ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
  7418. VecTy, EU.Lane);
  7419. } else {
  7420. ExtractCost += TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy,
  7421. CostKind, EU.Lane);
  7422. }
  7423. }
  7424. InstructionCost SpillCost = getSpillCost();
  7425. Cost += SpillCost + ExtractCost;
  7426. auto &&ResizeToVF = [this, &Cost](const TreeEntry *TE, ArrayRef<int> Mask,
  7427. bool) {
  7428. InstructionCost C = 0;
  7429. unsigned VF = Mask.size();
  7430. unsigned VecVF = TE->getVectorFactor();
  7431. if (VF != VecVF &&
  7432. (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); }) ||
  7433. (all_of(Mask,
  7434. [VF](int Idx) { return Idx < 2 * static_cast<int>(VF); }) &&
  7435. !ShuffleVectorInst::isIdentityMask(Mask)))) {
  7436. SmallVector<int> OrigMask(VecVF, UndefMaskElem);
  7437. std::copy(Mask.begin(), std::next(Mask.begin(), std::min(VF, VecVF)),
  7438. OrigMask.begin());
  7439. C = TTI->getShuffleCost(
  7440. TTI::SK_PermuteSingleSrc,
  7441. FixedVectorType::get(TE->getMainOp()->getType(), VecVF), OrigMask);
  7442. LLVM_DEBUG(
  7443. dbgs() << "SLP: Adding cost " << C
  7444. << " for final shuffle of insertelement external users.\n";
  7445. TE->dump(); dbgs() << "SLP: Current total cost = " << Cost << "\n");
  7446. Cost += C;
  7447. return std::make_pair(TE, true);
  7448. }
  7449. return std::make_pair(TE, false);
  7450. };
  7451. // Calculate the cost of the reshuffled vectors, if any.
  7452. for (int I = 0, E = FirstUsers.size(); I < E; ++I) {
  7453. Value *Base = cast<Instruction>(FirstUsers[I].first)->getOperand(0);
  7454. unsigned VF = ShuffleMasks[I].begin()->second.size();
  7455. auto *FTy = FixedVectorType::get(
  7456. cast<VectorType>(FirstUsers[I].first->getType())->getElementType(), VF);
  7457. auto Vector = ShuffleMasks[I].takeVector();
  7458. auto &&EstimateShufflesCost = [this, FTy,
  7459. &Cost](ArrayRef<int> Mask,
  7460. ArrayRef<const TreeEntry *> TEs) {
  7461. assert((TEs.size() == 1 || TEs.size() == 2) &&
  7462. "Expected exactly 1 or 2 tree entries.");
  7463. if (TEs.size() == 1) {
  7464. int Limit = 2 * Mask.size();
  7465. if (!all_of(Mask, [Limit](int Idx) { return Idx < Limit; }) ||
  7466. !ShuffleVectorInst::isIdentityMask(Mask)) {
  7467. InstructionCost C =
  7468. TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FTy, Mask);
  7469. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  7470. << " for final shuffle of insertelement "
  7471. "external users.\n";
  7472. TEs.front()->dump();
  7473. dbgs() << "SLP: Current total cost = " << Cost << "\n");
  7474. Cost += C;
  7475. }
  7476. } else {
  7477. InstructionCost C =
  7478. TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, FTy, Mask);
  7479. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  7480. << " for final shuffle of vector node and external "
  7481. "insertelement users.\n";
  7482. if (TEs.front()) { TEs.front()->dump(); } TEs.back()->dump();
  7483. dbgs() << "SLP: Current total cost = " << Cost << "\n");
  7484. Cost += C;
  7485. }
  7486. return TEs.back();
  7487. };
  7488. (void)performExtractsShuffleAction<const TreeEntry>(
  7489. MutableArrayRef(Vector.data(), Vector.size()), Base,
  7490. [](const TreeEntry *E) { return E->getVectorFactor(); }, ResizeToVF,
  7491. EstimateShufflesCost);
  7492. InstructionCost InsertCost = TTI->getScalarizationOverhead(
  7493. cast<FixedVectorType>(FirstUsers[I].first->getType()), DemandedElts[I],
  7494. /*Insert*/ true, /*Extract*/ false, TTI::TCK_RecipThroughput);
  7495. Cost -= InsertCost;
  7496. }
  7497. #ifndef NDEBUG
  7498. SmallString<256> Str;
  7499. {
  7500. raw_svector_ostream OS(Str);
  7501. OS << "SLP: Spill Cost = " << SpillCost << ".\n"
  7502. << "SLP: Extract Cost = " << ExtractCost << ".\n"
  7503. << "SLP: Total Cost = " << Cost << ".\n";
  7504. }
  7505. LLVM_DEBUG(dbgs() << Str);
  7506. if (ViewSLPTree)
  7507. ViewGraph(this, "SLP" + F->getName(), false, Str);
  7508. #endif
  7509. return Cost;
  7510. }
  7511. std::optional<TargetTransformInfo::ShuffleKind>
  7512. BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, ArrayRef<Value *> VL,
  7513. SmallVectorImpl<int> &Mask,
  7514. SmallVectorImpl<const TreeEntry *> &Entries) {
  7515. Entries.clear();
  7516. // No need to check for the topmost gather node.
  7517. if (TE == VectorizableTree.front().get())
  7518. return std::nullopt;
  7519. Mask.assign(VL.size(), UndefMaskElem);
  7520. assert(TE->UserTreeIndices.size() == 1 &&
  7521. "Expected only single user of the gather node.");
  7522. // TODO: currently checking only for Scalars in the tree entry, need to count
  7523. // reused elements too for better cost estimation.
  7524. Instruction &UserInst =
  7525. getLastInstructionInBundle(TE->UserTreeIndices.front().UserTE);
  7526. auto *PHI = dyn_cast<PHINode>(&UserInst);
  7527. auto *NodeUI = DT->getNode(
  7528. PHI ? PHI->getIncomingBlock(TE->UserTreeIndices.front().EdgeIdx)
  7529. : UserInst.getParent());
  7530. assert(NodeUI && "Should only process reachable instructions");
  7531. SmallPtrSet<Value *, 4> GatheredScalars(VL.begin(), VL.end());
  7532. auto CheckOrdering = [&](Instruction *LastEI) {
  7533. // Check if the user node of the TE comes after user node of EntryPtr,
  7534. // otherwise EntryPtr depends on TE.
  7535. // Gather nodes usually are not scheduled and inserted before their first
  7536. // user node. So, instead of checking dependency between the gather nodes
  7537. // themselves, we check the dependency between their user nodes.
  7538. // If one user node comes before the second one, we cannot use the second
  7539. // gather node as the source vector for the first gather node, because in
  7540. // the list of instructions it will be emitted later.
  7541. auto *EntryParent = LastEI->getParent();
  7542. auto *NodeEUI = DT->getNode(EntryParent);
  7543. if (!NodeEUI)
  7544. return false;
  7545. assert((NodeUI == NodeEUI) ==
  7546. (NodeUI->getDFSNumIn() == NodeEUI->getDFSNumIn()) &&
  7547. "Different nodes should have different DFS numbers");
  7548. // Check the order of the gather nodes users.
  7549. if (UserInst.getParent() != EntryParent &&
  7550. (DT->dominates(NodeUI, NodeEUI) || !DT->dominates(NodeEUI, NodeUI)))
  7551. return false;
  7552. if (UserInst.getParent() == EntryParent && UserInst.comesBefore(LastEI))
  7553. return false;
  7554. return true;
  7555. };
  7556. // Build a lists of values to tree entries.
  7557. DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
  7558. for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
  7559. if (EntryPtr.get() == TE)
  7560. continue;
  7561. if (EntryPtr->State != TreeEntry::NeedToGather)
  7562. continue;
  7563. if (!any_of(EntryPtr->Scalars, [&GatheredScalars](Value *V) {
  7564. return GatheredScalars.contains(V);
  7565. }))
  7566. continue;
  7567. assert(EntryPtr->UserTreeIndices.size() == 1 &&
  7568. "Expected only single user of the gather node.");
  7569. Instruction &EntryUserInst =
  7570. getLastInstructionInBundle(EntryPtr->UserTreeIndices.front().UserTE);
  7571. if (&UserInst == &EntryUserInst) {
  7572. // If 2 gathers are operands of the same entry, compare operands indices,
  7573. // use the earlier one as the base.
  7574. if (TE->UserTreeIndices.front().UserTE ==
  7575. EntryPtr->UserTreeIndices.front().UserTE &&
  7576. TE->UserTreeIndices.front().EdgeIdx <
  7577. EntryPtr->UserTreeIndices.front().EdgeIdx)
  7578. continue;
  7579. }
  7580. // Check if the user node of the TE comes after user node of EntryPtr,
  7581. // otherwise EntryPtr depends on TE.
  7582. auto *EntryPHI = dyn_cast<PHINode>(&EntryUserInst);
  7583. auto *EntryI =
  7584. EntryPHI
  7585. ? EntryPHI
  7586. ->getIncomingBlock(EntryPtr->UserTreeIndices.front().EdgeIdx)
  7587. ->getTerminator()
  7588. : &EntryUserInst;
  7589. if (!CheckOrdering(EntryI))
  7590. continue;
  7591. for (Value *V : EntryPtr->Scalars)
  7592. if (!isConstant(V))
  7593. ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
  7594. }
  7595. // Find all tree entries used by the gathered values. If no common entries
  7596. // found - not a shuffle.
  7597. // Here we build a set of tree nodes for each gathered value and trying to
  7598. // find the intersection between these sets. If we have at least one common
  7599. // tree node for each gathered value - we have just a permutation of the
  7600. // single vector. If we have 2 different sets, we're in situation where we
  7601. // have a permutation of 2 input vectors.
  7602. SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
  7603. DenseMap<Value *, int> UsedValuesEntry;
  7604. for (Value *V : TE->Scalars) {
  7605. if (isConstant(V))
  7606. continue;
  7607. // Build a list of tree entries where V is used.
  7608. SmallPtrSet<const TreeEntry *, 4> VToTEs;
  7609. auto It = ValueToTEs.find(V);
  7610. if (It != ValueToTEs.end())
  7611. VToTEs = It->second;
  7612. if (const TreeEntry *VTE = getTreeEntry(V))
  7613. VToTEs.insert(VTE);
  7614. if (VToTEs.empty())
  7615. continue;
  7616. if (UsedTEs.empty()) {
  7617. // The first iteration, just insert the list of nodes to vector.
  7618. UsedTEs.push_back(VToTEs);
  7619. UsedValuesEntry.try_emplace(V, 0);
  7620. } else {
  7621. // Need to check if there are any previously used tree nodes which use V.
  7622. // If there are no such nodes, consider that we have another one input
  7623. // vector.
  7624. SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
  7625. unsigned Idx = 0;
  7626. for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
  7627. // Do we have a non-empty intersection of previously listed tree entries
  7628. // and tree entries using current V?
  7629. set_intersect(VToTEs, Set);
  7630. if (!VToTEs.empty()) {
  7631. // Yes, write the new subset and continue analysis for the next
  7632. // scalar.
  7633. Set.swap(VToTEs);
  7634. break;
  7635. }
  7636. VToTEs = SavedVToTEs;
  7637. ++Idx;
  7638. }
  7639. // No non-empty intersection found - need to add a second set of possible
  7640. // source vectors.
  7641. if (Idx == UsedTEs.size()) {
  7642. // If the number of input vectors is greater than 2 - not a permutation,
  7643. // fallback to the regular gather.
  7644. // TODO: support multiple reshuffled nodes.
  7645. if (UsedTEs.size() == 2)
  7646. continue;
  7647. UsedTEs.push_back(SavedVToTEs);
  7648. Idx = UsedTEs.size() - 1;
  7649. }
  7650. UsedValuesEntry.try_emplace(V, Idx);
  7651. }
  7652. }
  7653. if (UsedTEs.empty())
  7654. return std::nullopt;
  7655. unsigned VF = 0;
  7656. if (UsedTEs.size() == 1) {
  7657. // Keep the order to avoid non-determinism.
  7658. SmallVector<const TreeEntry *> FirstEntries(UsedTEs.front().begin(),
  7659. UsedTEs.front().end());
  7660. sort(FirstEntries, [](const TreeEntry *TE1, const TreeEntry *TE2) {
  7661. return TE1->Idx < TE2->Idx;
  7662. });
  7663. // Try to find the perfect match in another gather node at first.
  7664. auto *It = find_if(FirstEntries, [=](const TreeEntry *EntryPtr) {
  7665. return EntryPtr->isSame(VL) || EntryPtr->isSame(TE->Scalars);
  7666. });
  7667. if (It != FirstEntries.end()) {
  7668. Entries.push_back(*It);
  7669. std::iota(Mask.begin(), Mask.end(), 0);
  7670. // Clear undef scalars.
  7671. for (int I = 0, Sz = VL.size(); I < Sz; ++I)
  7672. if (isa<PoisonValue>(TE->Scalars[I]))
  7673. Mask[I] = UndefMaskElem;
  7674. return TargetTransformInfo::SK_PermuteSingleSrc;
  7675. }
  7676. // No perfect match, just shuffle, so choose the first tree node from the
  7677. // tree.
  7678. Entries.push_back(FirstEntries.front());
  7679. } else {
  7680. // Try to find nodes with the same vector factor.
  7681. assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
  7682. // Keep the order of tree nodes to avoid non-determinism.
  7683. DenseMap<int, const TreeEntry *> VFToTE;
  7684. for (const TreeEntry *TE : UsedTEs.front()) {
  7685. unsigned VF = TE->getVectorFactor();
  7686. auto It = VFToTE.find(VF);
  7687. if (It != VFToTE.end()) {
  7688. if (It->second->Idx > TE->Idx)
  7689. It->getSecond() = TE;
  7690. continue;
  7691. }
  7692. VFToTE.try_emplace(VF, TE);
  7693. }
  7694. // Same, keep the order to avoid non-determinism.
  7695. SmallVector<const TreeEntry *> SecondEntries(UsedTEs.back().begin(),
  7696. UsedTEs.back().end());
  7697. sort(SecondEntries, [](const TreeEntry *TE1, const TreeEntry *TE2) {
  7698. return TE1->Idx < TE2->Idx;
  7699. });
  7700. for (const TreeEntry *TE : SecondEntries) {
  7701. auto It = VFToTE.find(TE->getVectorFactor());
  7702. if (It != VFToTE.end()) {
  7703. VF = It->first;
  7704. Entries.push_back(It->second);
  7705. Entries.push_back(TE);
  7706. break;
  7707. }
  7708. }
  7709. // No 2 source vectors with the same vector factor - give up and do regular
  7710. // gather.
  7711. if (Entries.empty())
  7712. return std::nullopt;
  7713. }
  7714. bool IsSplatOrUndefs = isSplat(VL) || all_of(VL, UndefValue::classof);
  7715. // Checks if the 2 PHIs are compatible in terms of high possibility to be
  7716. // vectorized.
  7717. auto AreCompatiblePHIs = [&](Value *V, Value *V1) {
  7718. auto *PHI = cast<PHINode>(V);
  7719. auto *PHI1 = cast<PHINode>(V1);
  7720. // Check that all incoming values are compatible/from same parent (if they
  7721. // are instructions).
  7722. // The incoming values are compatible if they all are constants, or
  7723. // instruction with the same/alternate opcodes from the same basic block.
  7724. for (int I = 0, E = PHI->getNumIncomingValues(); I < E; ++I) {
  7725. Value *In = PHI->getIncomingValue(I);
  7726. Value *In1 = PHI1->getIncomingValue(I);
  7727. if (isConstant(In) && isConstant(In1))
  7728. continue;
  7729. if (!getSameOpcode({In, In1}, *TLI).getOpcode())
  7730. return false;
  7731. if (cast<Instruction>(In)->getParent() !=
  7732. cast<Instruction>(In1)->getParent())
  7733. return false;
  7734. }
  7735. return true;
  7736. };
  7737. // Check if the value can be ignored during analysis for shuffled gathers.
  7738. // We suppose it is better to ignore instruction, which do not form splats,
  7739. // are not vectorized/not extractelements (these instructions will be handled
  7740. // by extractelements processing) or may form vector node in future.
  7741. auto MightBeIgnored = [=](Value *V) {
  7742. auto *I = dyn_cast<Instruction>(V);
  7743. SmallVector<Value *> IgnoredVals;
  7744. if (UserIgnoreList)
  7745. IgnoredVals.assign(UserIgnoreList->begin(), UserIgnoreList->end());
  7746. return I && !IsSplatOrUndefs && !ScalarToTreeEntry.count(I) &&
  7747. !isVectorLikeInstWithConstOps(I) &&
  7748. !areAllUsersVectorized(I, IgnoredVals) && isSimple(I);
  7749. };
  7750. // Check that the neighbor instruction may form a full vector node with the
  7751. // current instruction V. It is possible, if they have same/alternate opcode
  7752. // and same parent basic block.
  7753. auto NeighborMightBeIgnored = [&](Value *V, int Idx) {
  7754. Value *V1 = VL[Idx];
  7755. bool UsedInSameVTE = false;
  7756. auto It = UsedValuesEntry.find(V1);
  7757. if (It != UsedValuesEntry.end())
  7758. UsedInSameVTE = It->second == UsedValuesEntry.find(V)->second;
  7759. return V != V1 && MightBeIgnored(V1) && !UsedInSameVTE &&
  7760. getSameOpcode({V, V1}, *TLI).getOpcode() &&
  7761. cast<Instruction>(V)->getParent() ==
  7762. cast<Instruction>(V1)->getParent() &&
  7763. (!isa<PHINode>(V1) || AreCompatiblePHIs(V, V1));
  7764. };
  7765. // Build a shuffle mask for better cost estimation and vector emission.
  7766. SmallBitVector UsedIdxs(Entries.size());
  7767. SmallVector<std::pair<unsigned, int>> EntryLanes;
  7768. for (int I = 0, E = VL.size(); I < E; ++I) {
  7769. Value *V = VL[I];
  7770. auto It = UsedValuesEntry.find(V);
  7771. if (It == UsedValuesEntry.end())
  7772. continue;
  7773. // Do not try to shuffle scalars, if they are constants, or instructions
  7774. // that can be vectorized as a result of the following vector build
  7775. // vectorization.
  7776. if (isConstant(V) || (MightBeIgnored(V) &&
  7777. ((I > 0 && NeighborMightBeIgnored(V, I - 1)) ||
  7778. (I != E - 1 && NeighborMightBeIgnored(V, I + 1)))))
  7779. continue;
  7780. unsigned Idx = It->second;
  7781. EntryLanes.emplace_back(Idx, I);
  7782. UsedIdxs.set(Idx);
  7783. }
  7784. // Iterate through all shuffled scalars and select entries, which can be used
  7785. // for final shuffle.
  7786. SmallVector<const TreeEntry *> TempEntries;
  7787. for (unsigned I = 0, Sz = Entries.size(); I < Sz; ++I) {
  7788. if (!UsedIdxs.test(I))
  7789. continue;
  7790. // Fix the entry number for the given scalar. If it is the first entry, set
  7791. // Pair.first to 0, otherwise to 1 (currently select at max 2 nodes).
  7792. // These indices are used when calculating final shuffle mask as the vector
  7793. // offset.
  7794. for (std::pair<unsigned, int> &Pair : EntryLanes)
  7795. if (Pair.first == I)
  7796. Pair.first = TempEntries.size();
  7797. TempEntries.push_back(Entries[I]);
  7798. }
  7799. Entries.swap(TempEntries);
  7800. if (EntryLanes.size() == Entries.size() && !VL.equals(TE->Scalars)) {
  7801. // We may have here 1 or 2 entries only. If the number of scalars is equal
  7802. // to the number of entries, no need to do the analysis, it is not very
  7803. // profitable. Since VL is not the same as TE->Scalars, it means we already
  7804. // have some shuffles before. Cut off not profitable case.
  7805. Entries.clear();
  7806. return std::nullopt;
  7807. }
  7808. // Build the final mask, check for the identity shuffle, if possible.
  7809. bool IsIdentity = Entries.size() == 1;
  7810. // Pair.first is the offset to the vector, while Pair.second is the index of
  7811. // scalar in the list.
  7812. for (const std::pair<unsigned, int> &Pair : EntryLanes) {
  7813. Mask[Pair.second] = Pair.first * VF +
  7814. Entries[Pair.first]->findLaneForValue(VL[Pair.second]);
  7815. IsIdentity &= Mask[Pair.second] == Pair.second;
  7816. }
  7817. switch (Entries.size()) {
  7818. case 1:
  7819. if (IsIdentity || EntryLanes.size() > 1 || VL.size() <= 2)
  7820. return TargetTransformInfo::SK_PermuteSingleSrc;
  7821. break;
  7822. case 2:
  7823. if (EntryLanes.size() > 2 || VL.size() <= 2)
  7824. return TargetTransformInfo::SK_PermuteTwoSrc;
  7825. break;
  7826. default:
  7827. break;
  7828. }
  7829. Entries.clear();
  7830. return std::nullopt;
  7831. }
  7832. InstructionCost BoUpSLP::getGatherCost(FixedVectorType *Ty,
  7833. const APInt &ShuffledIndices,
  7834. bool NeedToShuffle) const {
  7835. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  7836. InstructionCost Cost =
  7837. TTI->getScalarizationOverhead(Ty, ~ShuffledIndices, /*Insert*/ true,
  7838. /*Extract*/ false, CostKind);
  7839. if (NeedToShuffle)
  7840. Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
  7841. return Cost;
  7842. }
  7843. InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
  7844. // Find the type of the operands in VL.
  7845. Type *ScalarTy = VL[0]->getType();
  7846. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  7847. ScalarTy = SI->getValueOperand()->getType();
  7848. auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
  7849. bool DuplicateNonConst = false;
  7850. // Find the cost of inserting/extracting values from the vector.
  7851. // Check if the same elements are inserted several times and count them as
  7852. // shuffle candidates.
  7853. APInt ShuffledElements = APInt::getZero(VL.size());
  7854. DenseSet<Value *> UniqueElements;
  7855. // Iterate in reverse order to consider insert elements with the high cost.
  7856. for (unsigned I = VL.size(); I > 0; --I) {
  7857. unsigned Idx = I - 1;
  7858. // No need to shuffle duplicates for constants.
  7859. if (isConstant(VL[Idx])) {
  7860. ShuffledElements.setBit(Idx);
  7861. continue;
  7862. }
  7863. if (!UniqueElements.insert(VL[Idx]).second) {
  7864. DuplicateNonConst = true;
  7865. ShuffledElements.setBit(Idx);
  7866. }
  7867. }
  7868. return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
  7869. }
  7870. // Perform operand reordering on the instructions in VL and return the reordered
  7871. // operands in Left and Right.
  7872. void BoUpSLP::reorderInputsAccordingToOpcode(
  7873. ArrayRef<Value *> VL, SmallVectorImpl<Value *> &Left,
  7874. SmallVectorImpl<Value *> &Right, const TargetLibraryInfo &TLI,
  7875. const DataLayout &DL, ScalarEvolution &SE, const BoUpSLP &R) {
  7876. if (VL.empty())
  7877. return;
  7878. VLOperands Ops(VL, TLI, DL, SE, R);
  7879. // Reorder the operands in place.
  7880. Ops.reorder();
  7881. Left = Ops.getVL(0);
  7882. Right = Ops.getVL(1);
  7883. }
  7884. Instruction &BoUpSLP::getLastInstructionInBundle(const TreeEntry *E) {
  7885. // Get the basic block this bundle is in. All instructions in the bundle
  7886. // should be in this block (except for extractelement-like instructions with
  7887. // constant indeces).
  7888. auto *Front = E->getMainOp();
  7889. auto *BB = Front->getParent();
  7890. assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
  7891. if (E->getOpcode() == Instruction::GetElementPtr &&
  7892. !isa<GetElementPtrInst>(V))
  7893. return true;
  7894. auto *I = cast<Instruction>(V);
  7895. return !E->isOpcodeOrAlt(I) || I->getParent() == BB ||
  7896. isVectorLikeInstWithConstOps(I);
  7897. }));
  7898. auto &&FindLastInst = [E, Front, this, &BB]() {
  7899. Instruction *LastInst = Front;
  7900. for (Value *V : E->Scalars) {
  7901. auto *I = dyn_cast<Instruction>(V);
  7902. if (!I)
  7903. continue;
  7904. if (LastInst->getParent() == I->getParent()) {
  7905. if (LastInst->comesBefore(I))
  7906. LastInst = I;
  7907. continue;
  7908. }
  7909. assert(isVectorLikeInstWithConstOps(LastInst) &&
  7910. isVectorLikeInstWithConstOps(I) &&
  7911. "Expected vector-like insts only.");
  7912. if (!DT->isReachableFromEntry(LastInst->getParent())) {
  7913. LastInst = I;
  7914. continue;
  7915. }
  7916. if (!DT->isReachableFromEntry(I->getParent()))
  7917. continue;
  7918. auto *NodeA = DT->getNode(LastInst->getParent());
  7919. auto *NodeB = DT->getNode(I->getParent());
  7920. assert(NodeA && "Should only process reachable instructions");
  7921. assert(NodeB && "Should only process reachable instructions");
  7922. assert((NodeA == NodeB) ==
  7923. (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
  7924. "Different nodes should have different DFS numbers");
  7925. if (NodeA->getDFSNumIn() < NodeB->getDFSNumIn())
  7926. LastInst = I;
  7927. }
  7928. BB = LastInst->getParent();
  7929. return LastInst;
  7930. };
  7931. auto &&FindFirstInst = [E, Front, this]() {
  7932. Instruction *FirstInst = Front;
  7933. for (Value *V : E->Scalars) {
  7934. auto *I = dyn_cast<Instruction>(V);
  7935. if (!I)
  7936. continue;
  7937. if (FirstInst->getParent() == I->getParent()) {
  7938. if (I->comesBefore(FirstInst))
  7939. FirstInst = I;
  7940. continue;
  7941. }
  7942. assert(isVectorLikeInstWithConstOps(FirstInst) &&
  7943. isVectorLikeInstWithConstOps(I) &&
  7944. "Expected vector-like insts only.");
  7945. if (!DT->isReachableFromEntry(FirstInst->getParent())) {
  7946. FirstInst = I;
  7947. continue;
  7948. }
  7949. if (!DT->isReachableFromEntry(I->getParent()))
  7950. continue;
  7951. auto *NodeA = DT->getNode(FirstInst->getParent());
  7952. auto *NodeB = DT->getNode(I->getParent());
  7953. assert(NodeA && "Should only process reachable instructions");
  7954. assert(NodeB && "Should only process reachable instructions");
  7955. assert((NodeA == NodeB) ==
  7956. (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
  7957. "Different nodes should have different DFS numbers");
  7958. if (NodeA->getDFSNumIn() > NodeB->getDFSNumIn())
  7959. FirstInst = I;
  7960. }
  7961. return FirstInst;
  7962. };
  7963. // Set the insert point to the beginning of the basic block if the entry
  7964. // should not be scheduled.
  7965. if (E->State != TreeEntry::NeedToGather &&
  7966. (doesNotNeedToSchedule(E->Scalars) ||
  7967. all_of(E->Scalars, isVectorLikeInstWithConstOps))) {
  7968. Instruction *InsertInst;
  7969. if (all_of(E->Scalars, [](Value *V) {
  7970. return !isVectorLikeInstWithConstOps(V) && isUsedOutsideBlock(V);
  7971. }))
  7972. InsertInst = FindLastInst();
  7973. else
  7974. InsertInst = FindFirstInst();
  7975. return *InsertInst;
  7976. }
  7977. // The last instruction in the bundle in program order.
  7978. Instruction *LastInst = nullptr;
  7979. // Find the last instruction. The common case should be that BB has been
  7980. // scheduled, and the last instruction is VL.back(). So we start with
  7981. // VL.back() and iterate over schedule data until we reach the end of the
  7982. // bundle. The end of the bundle is marked by null ScheduleData.
  7983. if (BlocksSchedules.count(BB)) {
  7984. Value *V = E->isOneOf(E->Scalars.back());
  7985. if (doesNotNeedToBeScheduled(V))
  7986. V = *find_if_not(E->Scalars, doesNotNeedToBeScheduled);
  7987. auto *Bundle = BlocksSchedules[BB]->getScheduleData(V);
  7988. if (Bundle && Bundle->isPartOfBundle())
  7989. for (; Bundle; Bundle = Bundle->NextInBundle)
  7990. if (Bundle->OpValue == Bundle->Inst)
  7991. LastInst = Bundle->Inst;
  7992. }
  7993. // LastInst can still be null at this point if there's either not an entry
  7994. // for BB in BlocksSchedules or there's no ScheduleData available for
  7995. // VL.back(). This can be the case if buildTree_rec aborts for various
  7996. // reasons (e.g., the maximum recursion depth is reached, the maximum region
  7997. // size is reached, etc.). ScheduleData is initialized in the scheduling
  7998. // "dry-run".
  7999. //
  8000. // If this happens, we can still find the last instruction by brute force. We
  8001. // iterate forwards from Front (inclusive) until we either see all
  8002. // instructions in the bundle or reach the end of the block. If Front is the
  8003. // last instruction in program order, LastInst will be set to Front, and we
  8004. // will visit all the remaining instructions in the block.
  8005. //
  8006. // One of the reasons we exit early from buildTree_rec is to place an upper
  8007. // bound on compile-time. Thus, taking an additional compile-time hit here is
  8008. // not ideal. However, this should be exceedingly rare since it requires that
  8009. // we both exit early from buildTree_rec and that the bundle be out-of-order
  8010. // (causing us to iterate all the way to the end of the block).
  8011. if (!LastInst)
  8012. LastInst = FindLastInst();
  8013. assert(LastInst && "Failed to find last instruction in bundle");
  8014. return *LastInst;
  8015. }
  8016. void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
  8017. auto *Front = E->getMainOp();
  8018. Instruction *LastInst = EntryToLastInstruction.lookup(E);
  8019. assert(LastInst && "Failed to find last instruction in bundle");
  8020. // If the instruction is PHI, set the insert point after all the PHIs.
  8021. bool IsPHI = isa<PHINode>(LastInst);
  8022. if (IsPHI)
  8023. LastInst = LastInst->getParent()->getFirstNonPHI();
  8024. if (IsPHI || (E->State != TreeEntry::NeedToGather &&
  8025. doesNotNeedToSchedule(E->Scalars))) {
  8026. Builder.SetInsertPoint(LastInst);
  8027. } else {
  8028. // Set the insertion point after the last instruction in the bundle. Set the
  8029. // debug location to Front.
  8030. Builder.SetInsertPoint(LastInst->getParent(),
  8031. std::next(LastInst->getIterator()));
  8032. }
  8033. Builder.SetCurrentDebugLocation(Front->getDebugLoc());
  8034. }
  8035. Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
  8036. // List of instructions/lanes from current block and/or the blocks which are
  8037. // part of the current loop. These instructions will be inserted at the end to
  8038. // make it possible to optimize loops and hoist invariant instructions out of
  8039. // the loops body with better chances for success.
  8040. SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
  8041. SmallSet<int, 4> PostponedIndices;
  8042. Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
  8043. auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
  8044. SmallPtrSet<BasicBlock *, 4> Visited;
  8045. while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
  8046. InsertBB = InsertBB->getSinglePredecessor();
  8047. return InsertBB && InsertBB == InstBB;
  8048. };
  8049. for (int I = 0, E = VL.size(); I < E; ++I) {
  8050. if (auto *Inst = dyn_cast<Instruction>(VL[I]))
  8051. if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
  8052. getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
  8053. PostponedIndices.insert(I).second)
  8054. PostponedInsts.emplace_back(Inst, I);
  8055. }
  8056. auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
  8057. Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
  8058. auto *InsElt = dyn_cast<InsertElementInst>(Vec);
  8059. if (!InsElt)
  8060. return Vec;
  8061. GatherShuffleExtractSeq.insert(InsElt);
  8062. CSEBlocks.insert(InsElt->getParent());
  8063. // Add to our 'need-to-extract' list.
  8064. if (TreeEntry *Entry = getTreeEntry(V)) {
  8065. // Find which lane we need to extract.
  8066. unsigned FoundLane = Entry->findLaneForValue(V);
  8067. ExternalUses.emplace_back(V, InsElt, FoundLane);
  8068. }
  8069. return Vec;
  8070. };
  8071. Value *Val0 =
  8072. isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
  8073. FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
  8074. Value *Vec = PoisonValue::get(VecTy);
  8075. SmallVector<int> NonConsts;
  8076. // Insert constant values at first.
  8077. for (int I = 0, E = VL.size(); I < E; ++I) {
  8078. if (PostponedIndices.contains(I))
  8079. continue;
  8080. if (!isConstant(VL[I])) {
  8081. NonConsts.push_back(I);
  8082. continue;
  8083. }
  8084. Vec = CreateInsertElement(Vec, VL[I], I);
  8085. }
  8086. // Insert non-constant values.
  8087. for (int I : NonConsts)
  8088. Vec = CreateInsertElement(Vec, VL[I], I);
  8089. // Append instructions, which are/may be part of the loop, in the end to make
  8090. // it possible to hoist non-loop-based instructions.
  8091. for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
  8092. Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
  8093. return Vec;
  8094. }
  8095. /// Merges shuffle masks and emits final shuffle instruction, if required. It
  8096. /// supports shuffling of 2 input vectors. It implements lazy shuffles emission,
  8097. /// when the actual shuffle instruction is generated only if this is actually
  8098. /// required. Otherwise, the shuffle instruction emission is delayed till the
  8099. /// end of the process, to reduce the number of emitted instructions and further
  8100. /// analysis/transformations.
  8101. /// The class also will look through the previously emitted shuffle instructions
  8102. /// and properly mark indices in mask as undef.
  8103. /// For example, given the code
  8104. /// \code
  8105. /// %s1 = shufflevector <2 x ty> %0, poison, <1, 0>
  8106. /// %s2 = shufflevector <2 x ty> %1, poison, <1, 0>
  8107. /// \endcode
  8108. /// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 3, 2>, it will
  8109. /// look through %s1 and %s2 and emit
  8110. /// \code
  8111. /// %res = shufflevector <2 x ty> %0, %1, <0, 1, 2, 3>
  8112. /// \endcode
  8113. /// instead.
  8114. /// If 2 operands are of different size, the smallest one will be resized and
  8115. /// the mask recalculated properly.
  8116. /// For example, given the code
  8117. /// \code
  8118. /// %s1 = shufflevector <2 x ty> %0, poison, <1, 0, 1, 0>
  8119. /// %s2 = shufflevector <2 x ty> %1, poison, <1, 0, 1, 0>
  8120. /// \endcode
  8121. /// and if need to emit shuffle of %s1 and %s2 with mask <1, 0, 5, 4>, it will
  8122. /// look through %s1 and %s2 and emit
  8123. /// \code
  8124. /// %res = shufflevector <2 x ty> %0, %1, <0, 1, 2, 3>
  8125. /// \endcode
  8126. /// instead.
  8127. class BoUpSLP::ShuffleInstructionBuilder final : public BaseShuffleAnalysis {
  8128. bool IsFinalized = false;
  8129. /// Combined mask for all applied operands and masks. It is built during
  8130. /// analysis and actual emission of shuffle vector instructions.
  8131. SmallVector<int> CommonMask;
  8132. /// List of operands for the shuffle vector instruction. It hold at max 2
  8133. /// operands, if the 3rd is going to be added, the first 2 are combined into
  8134. /// shuffle with \p CommonMask mask, the first operand sets to be the
  8135. /// resulting shuffle and the second operand sets to be the newly added
  8136. /// operand. The \p CommonMask is transformed in the proper way after that.
  8137. SmallVector<Value *, 2> InVectors;
  8138. IRBuilderBase &Builder;
  8139. BoUpSLP &R;
  8140. class ShuffleIRBuilder {
  8141. IRBuilderBase &Builder;
  8142. /// Holds all of the instructions that we gathered.
  8143. SetVector<Instruction *> &GatherShuffleExtractSeq;
  8144. /// A list of blocks that we are going to CSE.
  8145. SetVector<BasicBlock *> &CSEBlocks;
  8146. public:
  8147. ShuffleIRBuilder(IRBuilderBase &Builder,
  8148. SetVector<Instruction *> &GatherShuffleExtractSeq,
  8149. SetVector<BasicBlock *> &CSEBlocks)
  8150. : Builder(Builder), GatherShuffleExtractSeq(GatherShuffleExtractSeq),
  8151. CSEBlocks(CSEBlocks) {}
  8152. ~ShuffleIRBuilder() = default;
  8153. /// Creates shufflevector for the 2 operands with the given mask.
  8154. Value *createShuffleVector(Value *V1, Value *V2, ArrayRef<int> Mask) {
  8155. Value *Vec = Builder.CreateShuffleVector(V1, V2, Mask);
  8156. if (auto *I = dyn_cast<Instruction>(Vec)) {
  8157. GatherShuffleExtractSeq.insert(I);
  8158. CSEBlocks.insert(I->getParent());
  8159. }
  8160. return Vec;
  8161. }
  8162. /// Creates permutation of the single vector operand with the given mask, if
  8163. /// it is not identity mask.
  8164. Value *createShuffleVector(Value *V1, ArrayRef<int> Mask) {
  8165. if (Mask.empty())
  8166. return V1;
  8167. unsigned VF = Mask.size();
  8168. unsigned LocalVF = cast<FixedVectorType>(V1->getType())->getNumElements();
  8169. if (VF == LocalVF && ShuffleVectorInst::isIdentityMask(Mask))
  8170. return V1;
  8171. Value *Vec = Builder.CreateShuffleVector(V1, Mask);
  8172. if (auto *I = dyn_cast<Instruction>(Vec)) {
  8173. GatherShuffleExtractSeq.insert(I);
  8174. CSEBlocks.insert(I->getParent());
  8175. }
  8176. return Vec;
  8177. }
  8178. /// Resizes 2 input vector to match the sizes, if the they are not equal
  8179. /// yet. The smallest vector is resized to the size of the larger vector.
  8180. void resizeToMatch(Value *&V1, Value *&V2) {
  8181. if (V1->getType() == V2->getType())
  8182. return;
  8183. int V1VF = cast<FixedVectorType>(V1->getType())->getNumElements();
  8184. int V2VF = cast<FixedVectorType>(V2->getType())->getNumElements();
  8185. int VF = std::max(V1VF, V2VF);
  8186. int MinVF = std::min(V1VF, V2VF);
  8187. SmallVector<int> IdentityMask(VF, UndefMaskElem);
  8188. std::iota(IdentityMask.begin(), std::next(IdentityMask.begin(), MinVF),
  8189. 0);
  8190. Value *&Op = MinVF == V1VF ? V1 : V2;
  8191. Op = Builder.CreateShuffleVector(Op, IdentityMask);
  8192. if (auto *I = dyn_cast<Instruction>(Op)) {
  8193. GatherShuffleExtractSeq.insert(I);
  8194. CSEBlocks.insert(I->getParent());
  8195. }
  8196. if (MinVF == V1VF)
  8197. V1 = Op;
  8198. else
  8199. V2 = Op;
  8200. }
  8201. };
  8202. /// Smart shuffle instruction emission, walks through shuffles trees and
  8203. /// tries to find the best matching vector for the actual shuffle
  8204. /// instruction.
  8205. Value *createShuffle(Value *V1, Value *V2, ArrayRef<int> Mask) {
  8206. assert(V1 && "Expected at least one vector value.");
  8207. ShuffleIRBuilder ShuffleBuilder(Builder, R.GatherShuffleExtractSeq,
  8208. R.CSEBlocks);
  8209. return BaseShuffleAnalysis::createShuffle(V1, V2, Mask, ShuffleBuilder);
  8210. }
  8211. /// Transforms mask \p CommonMask per given \p Mask to make proper set after
  8212. /// shuffle emission.
  8213. static void transformMaskAfterShuffle(MutableArrayRef<int> CommonMask,
  8214. ArrayRef<int> Mask) {
  8215. for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
  8216. if (Mask[Idx] != UndefMaskElem)
  8217. CommonMask[Idx] = Idx;
  8218. }
  8219. public:
  8220. ShuffleInstructionBuilder(IRBuilderBase &Builder, BoUpSLP &R)
  8221. : Builder(Builder), R(R) {}
  8222. /// Adds 2 input vectors and the mask for their shuffling.
  8223. void add(Value *V1, Value *V2, ArrayRef<int> Mask) {
  8224. assert(V1 && V2 && !Mask.empty() && "Expected non-empty input vectors.");
  8225. if (InVectors.empty()) {
  8226. InVectors.push_back(V1);
  8227. InVectors.push_back(V2);
  8228. CommonMask.assign(Mask.begin(), Mask.end());
  8229. return;
  8230. }
  8231. Value *Vec = InVectors.front();
  8232. if (InVectors.size() == 2) {
  8233. Vec = createShuffle(Vec, InVectors.back(), CommonMask);
  8234. transformMaskAfterShuffle(CommonMask, Mask);
  8235. } else if (cast<FixedVectorType>(Vec->getType())->getNumElements() !=
  8236. Mask.size()) {
  8237. Vec = createShuffle(Vec, nullptr, CommonMask);
  8238. transformMaskAfterShuffle(CommonMask, Mask);
  8239. }
  8240. V1 = createShuffle(V1, V2, Mask);
  8241. for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
  8242. if (Mask[Idx] != UndefMaskElem)
  8243. CommonMask[Idx] = Idx + Sz;
  8244. InVectors.front() = Vec;
  8245. if (InVectors.size() == 2)
  8246. InVectors.back() = V1;
  8247. else
  8248. InVectors.push_back(V1);
  8249. }
  8250. /// Adds another one input vector and the mask for the shuffling.
  8251. void add(Value *V1, ArrayRef<int> Mask) {
  8252. if (InVectors.empty()) {
  8253. if (!isa<FixedVectorType>(V1->getType())) {
  8254. V1 = createShuffle(V1, nullptr, CommonMask);
  8255. CommonMask.assign(Mask.size(), UndefMaskElem);
  8256. transformMaskAfterShuffle(CommonMask, Mask);
  8257. }
  8258. InVectors.push_back(V1);
  8259. CommonMask.assign(Mask.begin(), Mask.end());
  8260. return;
  8261. }
  8262. const auto *It = find(InVectors, V1);
  8263. if (It == InVectors.end()) {
  8264. if (InVectors.size() == 2 ||
  8265. InVectors.front()->getType() != V1->getType() ||
  8266. !isa<FixedVectorType>(V1->getType())) {
  8267. Value *V = InVectors.front();
  8268. if (InVectors.size() == 2) {
  8269. V = createShuffle(InVectors.front(), InVectors.back(), CommonMask);
  8270. transformMaskAfterShuffle(CommonMask, CommonMask);
  8271. } else if (cast<FixedVectorType>(V->getType())->getNumElements() !=
  8272. CommonMask.size()) {
  8273. V = createShuffle(InVectors.front(), nullptr, CommonMask);
  8274. transformMaskAfterShuffle(CommonMask, CommonMask);
  8275. }
  8276. for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
  8277. if (CommonMask[Idx] == UndefMaskElem && Mask[Idx] != UndefMaskElem)
  8278. CommonMask[Idx] =
  8279. V->getType() != V1->getType()
  8280. ? Idx + Sz
  8281. : Mask[Idx] + cast<FixedVectorType>(V1->getType())
  8282. ->getNumElements();
  8283. if (V->getType() != V1->getType())
  8284. V1 = createShuffle(V1, nullptr, Mask);
  8285. InVectors.front() = V;
  8286. if (InVectors.size() == 2)
  8287. InVectors.back() = V1;
  8288. else
  8289. InVectors.push_back(V1);
  8290. return;
  8291. }
  8292. // Check if second vector is required if the used elements are already
  8293. // used from the first one.
  8294. for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
  8295. if (Mask[Idx] != UndefMaskElem && CommonMask[Idx] == UndefMaskElem) {
  8296. InVectors.push_back(V1);
  8297. break;
  8298. }
  8299. }
  8300. int VF = CommonMask.size();
  8301. if (auto *FTy = dyn_cast<FixedVectorType>(V1->getType()))
  8302. VF = FTy->getNumElements();
  8303. for (unsigned Idx = 0, Sz = CommonMask.size(); Idx < Sz; ++Idx)
  8304. if (Mask[Idx] != UndefMaskElem && CommonMask[Idx] == UndefMaskElem)
  8305. CommonMask[Idx] = Mask[Idx] + (It == InVectors.begin() ? 0 : VF);
  8306. }
  8307. /// Adds another one input vector and the mask for the shuffling.
  8308. void addOrdered(Value *V1, ArrayRef<unsigned> Order) {
  8309. SmallVector<int> NewMask;
  8310. inversePermutation(Order, NewMask);
  8311. add(V1, NewMask);
  8312. }
  8313. /// Finalize emission of the shuffles.
  8314. Value *
  8315. finalize(ArrayRef<int> ExtMask = std::nullopt) {
  8316. IsFinalized = true;
  8317. if (!ExtMask.empty()) {
  8318. if (CommonMask.empty()) {
  8319. CommonMask.assign(ExtMask.begin(), ExtMask.end());
  8320. } else {
  8321. SmallVector<int> NewMask(ExtMask.size(), UndefMaskElem);
  8322. for (int I = 0, Sz = ExtMask.size(); I < Sz; ++I) {
  8323. if (ExtMask[I] == UndefMaskElem)
  8324. continue;
  8325. NewMask[I] = CommonMask[ExtMask[I]];
  8326. }
  8327. CommonMask.swap(NewMask);
  8328. }
  8329. }
  8330. if (CommonMask.empty()) {
  8331. assert(InVectors.size() == 1 && "Expected only one vector with no mask");
  8332. return InVectors.front();
  8333. }
  8334. if (InVectors.size() == 2)
  8335. return createShuffle(InVectors.front(), InVectors.back(), CommonMask);
  8336. return createShuffle(InVectors.front(), nullptr, CommonMask);
  8337. }
  8338. ~ShuffleInstructionBuilder() {
  8339. assert((IsFinalized || CommonMask.empty()) &&
  8340. "Shuffle construction must be finalized.");
  8341. }
  8342. };
  8343. Value *BoUpSLP::vectorizeOperand(TreeEntry *E, unsigned NodeIdx) {
  8344. ArrayRef<Value *> VL = E->getOperand(NodeIdx);
  8345. const unsigned VF = VL.size();
  8346. InstructionsState S = getSameOpcode(VL, *TLI);
  8347. // Special processing for GEPs bundle, which may include non-gep values.
  8348. if (!S.getOpcode() && VL.front()->getType()->isPointerTy()) {
  8349. const auto *It =
  8350. find_if(VL, [](Value *V) { return isa<GetElementPtrInst>(V); });
  8351. if (It != VL.end())
  8352. S = getSameOpcode(*It, *TLI);
  8353. }
  8354. if (S.getOpcode()) {
  8355. if (TreeEntry *VE = getTreeEntry(S.OpValue);
  8356. VE && VE->isSame(VL) &&
  8357. (any_of(VE->UserTreeIndices,
  8358. [E, NodeIdx](const EdgeInfo &EI) {
  8359. return EI.UserTE == E && EI.EdgeIdx == NodeIdx;
  8360. }) ||
  8361. any_of(VectorizableTree,
  8362. [E, NodeIdx, VE](const std::unique_ptr<TreeEntry> &TE) {
  8363. return TE->isOperandGatherNode({E, NodeIdx}) &&
  8364. VE->isSame(TE->Scalars);
  8365. }))) {
  8366. auto FinalShuffle = [&](Value *V, ArrayRef<int> Mask) {
  8367. ShuffleInstructionBuilder ShuffleBuilder(Builder, *this);
  8368. ShuffleBuilder.add(V, Mask);
  8369. return ShuffleBuilder.finalize(std::nullopt);
  8370. };
  8371. Value *V = vectorizeTree(VE);
  8372. if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
  8373. if (!VE->ReuseShuffleIndices.empty()) {
  8374. // Reshuffle to get only unique values.
  8375. // If some of the scalars are duplicated in the vectorization
  8376. // tree entry, we do not vectorize them but instead generate a
  8377. // mask for the reuses. But if there are several users of the
  8378. // same entry, they may have different vectorization factors.
  8379. // This is especially important for PHI nodes. In this case, we
  8380. // need to adapt the resulting instruction for the user
  8381. // vectorization factor and have to reshuffle it again to take
  8382. // only unique elements of the vector. Without this code the
  8383. // function incorrectly returns reduced vector instruction with
  8384. // the same elements, not with the unique ones.
  8385. // block:
  8386. // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
  8387. // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
  8388. // ... (use %2)
  8389. // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
  8390. // br %block
  8391. SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
  8392. SmallSet<int, 4> UsedIdxs;
  8393. int Pos = 0;
  8394. for (int Idx : VE->ReuseShuffleIndices) {
  8395. if (Idx != static_cast<int>(VF) && Idx != UndefMaskElem &&
  8396. UsedIdxs.insert(Idx).second)
  8397. UniqueIdxs[Idx] = Pos;
  8398. ++Pos;
  8399. }
  8400. assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
  8401. "less than original vector size.");
  8402. UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
  8403. V = FinalShuffle(V, UniqueIdxs);
  8404. } else {
  8405. assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
  8406. "Expected vectorization factor less "
  8407. "than original vector size.");
  8408. SmallVector<int> UniformMask(VF, 0);
  8409. std::iota(UniformMask.begin(), UniformMask.end(), 0);
  8410. V = FinalShuffle(V, UniformMask);
  8411. }
  8412. }
  8413. return V;
  8414. }
  8415. }
  8416. // Find the corresponding gather entry and vectorize it.
  8417. // Allows to be more accurate with tree/graph transformations, checks for the
  8418. // correctness of the transformations in many cases.
  8419. auto *I = find_if(VectorizableTree,
  8420. [E, NodeIdx](const std::unique_ptr<TreeEntry> &TE) {
  8421. return TE->isOperandGatherNode({E, NodeIdx});
  8422. });
  8423. assert(I != VectorizableTree.end() && "Gather node is not in the graph.");
  8424. assert(I->get()->UserTreeIndices.size() == 1 &&
  8425. "Expected only single user for the gather node.");
  8426. assert(I->get()->isSame(VL) && "Expected same list of scalars.");
  8427. IRBuilder<>::InsertPointGuard Guard(Builder);
  8428. if (E->getOpcode() != Instruction::InsertElement &&
  8429. E->getOpcode() != Instruction::PHI) {
  8430. Instruction *LastInst = EntryToLastInstruction.lookup(E);
  8431. assert(LastInst && "Failed to find last instruction in bundle");
  8432. Builder.SetInsertPoint(LastInst);
  8433. }
  8434. return vectorizeTree(I->get());
  8435. }
  8436. Value *BoUpSLP::createBuildVector(const TreeEntry *E) {
  8437. assert(E->State == TreeEntry::NeedToGather && "Expected gather node.");
  8438. unsigned VF = E->getVectorFactor();
  8439. ShuffleInstructionBuilder ShuffleBuilder(Builder, *this);
  8440. SmallVector<Value *> Gathered(
  8441. VF, PoisonValue::get(E->Scalars.front()->getType()));
  8442. bool NeedFreeze = false;
  8443. SmallVector<Value *> VL(E->Scalars.begin(), E->Scalars.end());
  8444. // Build a mask out of the redorder indices and reorder scalars per this mask.
  8445. SmallVector<int> ReorderMask;
  8446. inversePermutation(E->ReorderIndices, ReorderMask);
  8447. if (!ReorderMask.empty())
  8448. reorderScalars(VL, ReorderMask);
  8449. SmallVector<int> ReuseMask(VF, UndefMaskElem);
  8450. if (!allConstant(VL)) {
  8451. // For splats with can emit broadcasts instead of gathers, so try to find
  8452. // such sequences.
  8453. bool IsSplat = isSplat(VL) && (VL.size() > 2 || VL.front() == VL.back());
  8454. SmallVector<int> UndefPos;
  8455. DenseMap<Value *, unsigned> UniquePositions;
  8456. // Gather unique non-const values and all constant values.
  8457. // For repeated values, just shuffle them.
  8458. for (auto [I, V] : enumerate(VL)) {
  8459. if (isa<UndefValue>(V)) {
  8460. if (!isa<PoisonValue>(V)) {
  8461. Gathered[I] = V;
  8462. ReuseMask[I] = I;
  8463. UndefPos.push_back(I);
  8464. }
  8465. continue;
  8466. }
  8467. if (isConstant(V)) {
  8468. Gathered[I] = V;
  8469. ReuseMask[I] = I;
  8470. continue;
  8471. }
  8472. if (IsSplat) {
  8473. Gathered.front() = V;
  8474. ReuseMask[I] = 0;
  8475. } else {
  8476. const auto Res = UniquePositions.try_emplace(V, I);
  8477. Gathered[Res.first->second] = V;
  8478. ReuseMask[I] = Res.first->second;
  8479. }
  8480. }
  8481. if (!UndefPos.empty() && IsSplat) {
  8482. // For undef values, try to replace them with the simple broadcast.
  8483. // We can do it if the broadcasted value is guaranteed to be
  8484. // non-poisonous, or by freezing the incoming scalar value first.
  8485. auto *It = find_if(Gathered, [this, E](Value *V) {
  8486. return !isa<UndefValue>(V) &&
  8487. (getTreeEntry(V) || isGuaranteedNotToBePoison(V) ||
  8488. any_of(V->uses(), [E](const Use &U) {
  8489. // Check if the value already used in the same operation in
  8490. // one of the nodes already.
  8491. return E->UserTreeIndices.size() == 1 &&
  8492. is_contained(
  8493. E->UserTreeIndices.front().UserTE->Scalars,
  8494. U.getUser()) &&
  8495. E->UserTreeIndices.front().EdgeIdx != U.getOperandNo();
  8496. }));
  8497. });
  8498. if (It != Gathered.end()) {
  8499. // Replace undefs by the non-poisoned scalars and emit broadcast.
  8500. int Pos = std::distance(Gathered.begin(), It);
  8501. for_each(UndefPos, [&](int I) {
  8502. // Set the undef position to the non-poisoned scalar.
  8503. ReuseMask[I] = Pos;
  8504. // Replace the undef by the poison, in the mask it is replaced by non-poisoned scalar already.
  8505. if (I != Pos)
  8506. Gathered[I] = PoisonValue::get(Gathered[I]->getType());
  8507. });
  8508. } else {
  8509. // Replace undefs by the poisons, emit broadcast and then emit
  8510. // freeze.
  8511. for_each(UndefPos, [&](int I) {
  8512. ReuseMask[I] = UndefMaskElem;
  8513. if (isa<UndefValue>(Gathered[I]))
  8514. Gathered[I] = PoisonValue::get(Gathered[I]->getType());
  8515. });
  8516. NeedFreeze = true;
  8517. }
  8518. }
  8519. } else {
  8520. ReuseMask.clear();
  8521. copy(VL, Gathered.begin());
  8522. }
  8523. // Gather unique scalars and all constants.
  8524. Value *Vec = gather(Gathered);
  8525. ShuffleBuilder.add(Vec, ReuseMask);
  8526. Vec = ShuffleBuilder.finalize(E->ReuseShuffleIndices);
  8527. if (NeedFreeze)
  8528. Vec = Builder.CreateFreeze(Vec);
  8529. return Vec;
  8530. }
  8531. Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
  8532. IRBuilder<>::InsertPointGuard Guard(Builder);
  8533. if (E->VectorizedValue) {
  8534. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
  8535. return E->VectorizedValue;
  8536. }
  8537. auto FinalShuffle = [&](Value *V, const TreeEntry *E) {
  8538. ShuffleInstructionBuilder ShuffleBuilder(Builder, *this);
  8539. if (E->State != TreeEntry::NeedToGather &&
  8540. E->getOpcode() == Instruction::Store) {
  8541. ArrayRef<int> Mask =
  8542. ArrayRef(reinterpret_cast<const int *>(E->ReorderIndices.begin()),
  8543. E->ReorderIndices.size());
  8544. ShuffleBuilder.add(V, Mask);
  8545. } else {
  8546. ShuffleBuilder.addOrdered(V, E->ReorderIndices);
  8547. }
  8548. return ShuffleBuilder.finalize(E->ReuseShuffleIndices);
  8549. };
  8550. if (E->State == TreeEntry::NeedToGather) {
  8551. if (E->Idx > 0) {
  8552. // We are in the middle of a vectorizable chain. We need to gather the
  8553. // scalars from the users.
  8554. Value *Vec = createBuildVector(E);
  8555. E->VectorizedValue = Vec;
  8556. return Vec;
  8557. }
  8558. if (E->getMainOp())
  8559. setInsertPointAfterBundle(E);
  8560. SmallVector<Value *> GatheredScalars(E->Scalars.begin(), E->Scalars.end());
  8561. // Build a mask out of the reorder indices and reorder scalars per this
  8562. // mask.
  8563. SmallVector<int> ReorderMask;
  8564. inversePermutation(E->ReorderIndices, ReorderMask);
  8565. if (!ReorderMask.empty())
  8566. reorderScalars(GatheredScalars, ReorderMask);
  8567. Value *Vec;
  8568. SmallVector<int> Mask;
  8569. SmallVector<const TreeEntry *> Entries;
  8570. std::optional<TargetTransformInfo::ShuffleKind> Shuffle =
  8571. isGatherShuffledEntry(E, GatheredScalars, Mask, Entries);
  8572. if (Shuffle) {
  8573. assert((Entries.size() == 1 || Entries.size() == 2) &&
  8574. "Expected shuffle of 1 or 2 entries.");
  8575. Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
  8576. Entries.back()->VectorizedValue, Mask);
  8577. if (auto *I = dyn_cast<Instruction>(Vec)) {
  8578. GatherShuffleExtractSeq.insert(I);
  8579. CSEBlocks.insert(I->getParent());
  8580. }
  8581. } else {
  8582. Vec = gather(E->Scalars);
  8583. }
  8584. Vec = FinalShuffle(Vec, E);
  8585. E->VectorizedValue = Vec;
  8586. return Vec;
  8587. }
  8588. assert((E->State == TreeEntry::Vectorize ||
  8589. E->State == TreeEntry::ScatterVectorize) &&
  8590. "Unhandled state");
  8591. unsigned ShuffleOrOp =
  8592. E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
  8593. Instruction *VL0 = E->getMainOp();
  8594. Type *ScalarTy = VL0->getType();
  8595. if (auto *Store = dyn_cast<StoreInst>(VL0))
  8596. ScalarTy = Store->getValueOperand()->getType();
  8597. else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
  8598. ScalarTy = IE->getOperand(1)->getType();
  8599. auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
  8600. switch (ShuffleOrOp) {
  8601. case Instruction::PHI: {
  8602. assert((E->ReorderIndices.empty() ||
  8603. E != VectorizableTree.front().get() ||
  8604. !E->UserTreeIndices.empty()) &&
  8605. "PHI reordering is free.");
  8606. auto *PH = cast<PHINode>(VL0);
  8607. Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
  8608. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  8609. PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
  8610. Value *V = NewPhi;
  8611. // Adjust insertion point once all PHI's have been generated.
  8612. Builder.SetInsertPoint(&*PH->getParent()->getFirstInsertionPt());
  8613. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  8614. V = FinalShuffle(V, E);
  8615. E->VectorizedValue = V;
  8616. // PHINodes may have multiple entries from the same block. We want to
  8617. // visit every block once.
  8618. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  8619. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  8620. ValueList Operands;
  8621. BasicBlock *IBB = PH->getIncomingBlock(i);
  8622. // Stop emission if all incoming values are generated.
  8623. if (NewPhi->getNumIncomingValues() == PH->getNumIncomingValues()) {
  8624. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8625. return V;
  8626. }
  8627. if (!VisitedBBs.insert(IBB).second) {
  8628. NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
  8629. continue;
  8630. }
  8631. Builder.SetInsertPoint(IBB->getTerminator());
  8632. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  8633. Value *Vec = vectorizeOperand(E, i);
  8634. NewPhi->addIncoming(Vec, IBB);
  8635. }
  8636. assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
  8637. "Invalid number of incoming values");
  8638. return V;
  8639. }
  8640. case Instruction::ExtractElement: {
  8641. Value *V = E->getSingleOperand(0);
  8642. setInsertPointAfterBundle(E);
  8643. V = FinalShuffle(V, E);
  8644. E->VectorizedValue = V;
  8645. return V;
  8646. }
  8647. case Instruction::ExtractValue: {
  8648. auto *LI = cast<LoadInst>(E->getSingleOperand(0));
  8649. Builder.SetInsertPoint(LI);
  8650. auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
  8651. Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
  8652. LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
  8653. Value *NewV = propagateMetadata(V, E->Scalars);
  8654. NewV = FinalShuffle(NewV, E);
  8655. E->VectorizedValue = NewV;
  8656. return NewV;
  8657. }
  8658. case Instruction::InsertElement: {
  8659. assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
  8660. Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
  8661. Value *V = vectorizeOperand(E, 1);
  8662. // Create InsertVector shuffle if necessary
  8663. auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
  8664. return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
  8665. }));
  8666. const unsigned NumElts =
  8667. cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
  8668. const unsigned NumScalars = E->Scalars.size();
  8669. unsigned Offset = *getInsertIndex(VL0);
  8670. assert(Offset < NumElts && "Failed to find vector index offset");
  8671. // Create shuffle to resize vector
  8672. SmallVector<int> Mask;
  8673. if (!E->ReorderIndices.empty()) {
  8674. inversePermutation(E->ReorderIndices, Mask);
  8675. Mask.append(NumElts - NumScalars, UndefMaskElem);
  8676. } else {
  8677. Mask.assign(NumElts, UndefMaskElem);
  8678. std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
  8679. }
  8680. // Create InsertVector shuffle if necessary
  8681. bool IsIdentity = true;
  8682. SmallVector<int> PrevMask(NumElts, UndefMaskElem);
  8683. Mask.swap(PrevMask);
  8684. for (unsigned I = 0; I < NumScalars; ++I) {
  8685. Value *Scalar = E->Scalars[PrevMask[I]];
  8686. unsigned InsertIdx = *getInsertIndex(Scalar);
  8687. IsIdentity &= InsertIdx - Offset == I;
  8688. Mask[InsertIdx - Offset] = I;
  8689. }
  8690. if (!IsIdentity || NumElts != NumScalars) {
  8691. V = Builder.CreateShuffleVector(V, Mask);
  8692. if (auto *I = dyn_cast<Instruction>(V)) {
  8693. GatherShuffleExtractSeq.insert(I);
  8694. CSEBlocks.insert(I->getParent());
  8695. }
  8696. }
  8697. SmallVector<int> InsertMask(NumElts, UndefMaskElem);
  8698. for (unsigned I = 0; I < NumElts; I++) {
  8699. if (Mask[I] != UndefMaskElem)
  8700. InsertMask[Offset + I] = I;
  8701. }
  8702. SmallBitVector UseMask =
  8703. buildUseMask(NumElts, InsertMask, UseMask::UndefsAsMask);
  8704. SmallBitVector IsFirstUndef =
  8705. isUndefVector(FirstInsert->getOperand(0), UseMask);
  8706. if ((!IsIdentity || Offset != 0 || !IsFirstUndef.all()) &&
  8707. NumElts != NumScalars) {
  8708. if (IsFirstUndef.all()) {
  8709. if (!ShuffleVectorInst::isIdentityMask(InsertMask)) {
  8710. SmallBitVector IsFirstPoison =
  8711. isUndefVector<true>(FirstInsert->getOperand(0), UseMask);
  8712. if (!IsFirstPoison.all()) {
  8713. for (unsigned I = 0; I < NumElts; I++) {
  8714. if (InsertMask[I] == UndefMaskElem && !IsFirstPoison.test(I))
  8715. InsertMask[I] = I + NumElts;
  8716. }
  8717. }
  8718. V = Builder.CreateShuffleVector(
  8719. V,
  8720. IsFirstPoison.all() ? PoisonValue::get(V->getType())
  8721. : FirstInsert->getOperand(0),
  8722. InsertMask, cast<Instruction>(E->Scalars.back())->getName());
  8723. if (auto *I = dyn_cast<Instruction>(V)) {
  8724. GatherShuffleExtractSeq.insert(I);
  8725. CSEBlocks.insert(I->getParent());
  8726. }
  8727. }
  8728. } else {
  8729. SmallBitVector IsFirstPoison =
  8730. isUndefVector<true>(FirstInsert->getOperand(0), UseMask);
  8731. for (unsigned I = 0; I < NumElts; I++) {
  8732. if (InsertMask[I] == UndefMaskElem)
  8733. InsertMask[I] = IsFirstPoison.test(I) ? UndefMaskElem : I;
  8734. else
  8735. InsertMask[I] += NumElts;
  8736. }
  8737. V = Builder.CreateShuffleVector(
  8738. FirstInsert->getOperand(0), V, InsertMask,
  8739. cast<Instruction>(E->Scalars.back())->getName());
  8740. if (auto *I = dyn_cast<Instruction>(V)) {
  8741. GatherShuffleExtractSeq.insert(I);
  8742. CSEBlocks.insert(I->getParent());
  8743. }
  8744. }
  8745. }
  8746. ++NumVectorInstructions;
  8747. E->VectorizedValue = V;
  8748. return V;
  8749. }
  8750. case Instruction::ZExt:
  8751. case Instruction::SExt:
  8752. case Instruction::FPToUI:
  8753. case Instruction::FPToSI:
  8754. case Instruction::FPExt:
  8755. case Instruction::PtrToInt:
  8756. case Instruction::IntToPtr:
  8757. case Instruction::SIToFP:
  8758. case Instruction::UIToFP:
  8759. case Instruction::Trunc:
  8760. case Instruction::FPTrunc:
  8761. case Instruction::BitCast: {
  8762. setInsertPointAfterBundle(E);
  8763. Value *InVec = vectorizeOperand(E, 0);
  8764. if (E->VectorizedValue) {
  8765. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8766. return E->VectorizedValue;
  8767. }
  8768. auto *CI = cast<CastInst>(VL0);
  8769. Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
  8770. V = FinalShuffle(V, E);
  8771. E->VectorizedValue = V;
  8772. ++NumVectorInstructions;
  8773. return V;
  8774. }
  8775. case Instruction::FCmp:
  8776. case Instruction::ICmp: {
  8777. setInsertPointAfterBundle(E);
  8778. Value *L = vectorizeOperand(E, 0);
  8779. if (E->VectorizedValue) {
  8780. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8781. return E->VectorizedValue;
  8782. }
  8783. Value *R = vectorizeOperand(E, 1);
  8784. if (E->VectorizedValue) {
  8785. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8786. return E->VectorizedValue;
  8787. }
  8788. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  8789. Value *V = Builder.CreateCmp(P0, L, R);
  8790. propagateIRFlags(V, E->Scalars, VL0);
  8791. V = FinalShuffle(V, E);
  8792. E->VectorizedValue = V;
  8793. ++NumVectorInstructions;
  8794. return V;
  8795. }
  8796. case Instruction::Select: {
  8797. setInsertPointAfterBundle(E);
  8798. Value *Cond = vectorizeOperand(E, 0);
  8799. if (E->VectorizedValue) {
  8800. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8801. return E->VectorizedValue;
  8802. }
  8803. Value *True = vectorizeOperand(E, 1);
  8804. if (E->VectorizedValue) {
  8805. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8806. return E->VectorizedValue;
  8807. }
  8808. Value *False = vectorizeOperand(E, 2);
  8809. if (E->VectorizedValue) {
  8810. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8811. return E->VectorizedValue;
  8812. }
  8813. Value *V = Builder.CreateSelect(Cond, True, False);
  8814. V = FinalShuffle(V, E);
  8815. E->VectorizedValue = V;
  8816. ++NumVectorInstructions;
  8817. return V;
  8818. }
  8819. case Instruction::FNeg: {
  8820. setInsertPointAfterBundle(E);
  8821. Value *Op = vectorizeOperand(E, 0);
  8822. if (E->VectorizedValue) {
  8823. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8824. return E->VectorizedValue;
  8825. }
  8826. Value *V = Builder.CreateUnOp(
  8827. static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
  8828. propagateIRFlags(V, E->Scalars, VL0);
  8829. if (auto *I = dyn_cast<Instruction>(V))
  8830. V = propagateMetadata(I, E->Scalars);
  8831. V = FinalShuffle(V, E);
  8832. E->VectorizedValue = V;
  8833. ++NumVectorInstructions;
  8834. return V;
  8835. }
  8836. case Instruction::Add:
  8837. case Instruction::FAdd:
  8838. case Instruction::Sub:
  8839. case Instruction::FSub:
  8840. case Instruction::Mul:
  8841. case Instruction::FMul:
  8842. case Instruction::UDiv:
  8843. case Instruction::SDiv:
  8844. case Instruction::FDiv:
  8845. case Instruction::URem:
  8846. case Instruction::SRem:
  8847. case Instruction::FRem:
  8848. case Instruction::Shl:
  8849. case Instruction::LShr:
  8850. case Instruction::AShr:
  8851. case Instruction::And:
  8852. case Instruction::Or:
  8853. case Instruction::Xor: {
  8854. setInsertPointAfterBundle(E);
  8855. Value *LHS = vectorizeOperand(E, 0);
  8856. if (E->VectorizedValue) {
  8857. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8858. return E->VectorizedValue;
  8859. }
  8860. Value *RHS = vectorizeOperand(E, 1);
  8861. if (E->VectorizedValue) {
  8862. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8863. return E->VectorizedValue;
  8864. }
  8865. Value *V = Builder.CreateBinOp(
  8866. static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
  8867. RHS);
  8868. propagateIRFlags(V, E->Scalars, VL0);
  8869. if (auto *I = dyn_cast<Instruction>(V))
  8870. V = propagateMetadata(I, E->Scalars);
  8871. V = FinalShuffle(V, E);
  8872. E->VectorizedValue = V;
  8873. ++NumVectorInstructions;
  8874. return V;
  8875. }
  8876. case Instruction::Load: {
  8877. // Loads are inserted at the head of the tree because we don't want to
  8878. // sink them all the way down past store instructions.
  8879. setInsertPointAfterBundle(E);
  8880. LoadInst *LI = cast<LoadInst>(VL0);
  8881. Instruction *NewLI;
  8882. unsigned AS = LI->getPointerAddressSpace();
  8883. Value *PO = LI->getPointerOperand();
  8884. if (E->State == TreeEntry::Vectorize) {
  8885. Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
  8886. NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
  8887. // The pointer operand uses an in-tree scalar so we add the new BitCast
  8888. // or LoadInst to ExternalUses list to make sure that an extract will
  8889. // be generated in the future.
  8890. if (TreeEntry *Entry = getTreeEntry(PO)) {
  8891. // Find which lane we need to extract.
  8892. unsigned FoundLane = Entry->findLaneForValue(PO);
  8893. ExternalUses.emplace_back(
  8894. PO, PO != VecPtr ? cast<User>(VecPtr) : NewLI, FoundLane);
  8895. }
  8896. } else {
  8897. assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
  8898. Value *VecPtr = vectorizeOperand(E, 0);
  8899. if (E->VectorizedValue) {
  8900. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8901. return E->VectorizedValue;
  8902. }
  8903. // Use the minimum alignment of the gathered loads.
  8904. Align CommonAlignment = LI->getAlign();
  8905. for (Value *V : E->Scalars)
  8906. CommonAlignment =
  8907. std::min(CommonAlignment, cast<LoadInst>(V)->getAlign());
  8908. NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
  8909. }
  8910. Value *V = propagateMetadata(NewLI, E->Scalars);
  8911. V = FinalShuffle(V, E);
  8912. E->VectorizedValue = V;
  8913. ++NumVectorInstructions;
  8914. return V;
  8915. }
  8916. case Instruction::Store: {
  8917. auto *SI = cast<StoreInst>(VL0);
  8918. unsigned AS = SI->getPointerAddressSpace();
  8919. setInsertPointAfterBundle(E);
  8920. Value *VecValue = vectorizeOperand(E, 0);
  8921. VecValue = FinalShuffle(VecValue, E);
  8922. Value *ScalarPtr = SI->getPointerOperand();
  8923. Value *VecPtr = Builder.CreateBitCast(
  8924. ScalarPtr, VecValue->getType()->getPointerTo(AS));
  8925. StoreInst *ST =
  8926. Builder.CreateAlignedStore(VecValue, VecPtr, SI->getAlign());
  8927. // The pointer operand uses an in-tree scalar, so add the new BitCast or
  8928. // StoreInst to ExternalUses to make sure that an extract will be
  8929. // generated in the future.
  8930. if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
  8931. // Find which lane we need to extract.
  8932. unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
  8933. ExternalUses.push_back(ExternalUser(
  8934. ScalarPtr, ScalarPtr != VecPtr ? cast<User>(VecPtr) : ST,
  8935. FoundLane));
  8936. }
  8937. Value *V = propagateMetadata(ST, E->Scalars);
  8938. E->VectorizedValue = V;
  8939. ++NumVectorInstructions;
  8940. return V;
  8941. }
  8942. case Instruction::GetElementPtr: {
  8943. auto *GEP0 = cast<GetElementPtrInst>(VL0);
  8944. setInsertPointAfterBundle(E);
  8945. Value *Op0 = vectorizeOperand(E, 0);
  8946. if (E->VectorizedValue) {
  8947. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8948. return E->VectorizedValue;
  8949. }
  8950. SmallVector<Value *> OpVecs;
  8951. for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
  8952. Value *OpVec = vectorizeOperand(E, J);
  8953. if (E->VectorizedValue) {
  8954. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  8955. return E->VectorizedValue;
  8956. }
  8957. OpVecs.push_back(OpVec);
  8958. }
  8959. Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
  8960. if (Instruction *I = dyn_cast<GetElementPtrInst>(V)) {
  8961. SmallVector<Value *> GEPs;
  8962. for (Value *V : E->Scalars) {
  8963. if (isa<GetElementPtrInst>(V))
  8964. GEPs.push_back(V);
  8965. }
  8966. V = propagateMetadata(I, GEPs);
  8967. }
  8968. V = FinalShuffle(V, E);
  8969. E->VectorizedValue = V;
  8970. ++NumVectorInstructions;
  8971. return V;
  8972. }
  8973. case Instruction::Call: {
  8974. CallInst *CI = cast<CallInst>(VL0);
  8975. setInsertPointAfterBundle(E);
  8976. Intrinsic::ID IID = Intrinsic::not_intrinsic;
  8977. if (Function *FI = CI->getCalledFunction())
  8978. IID = FI->getIntrinsicID();
  8979. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  8980. auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
  8981. bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
  8982. VecCallCosts.first <= VecCallCosts.second;
  8983. Value *ScalarArg = nullptr;
  8984. std::vector<Value *> OpVecs;
  8985. SmallVector<Type *, 2> TysForDecl =
  8986. {FixedVectorType::get(CI->getType(), E->Scalars.size())};
  8987. for (int j = 0, e = CI->arg_size(); j < e; ++j) {
  8988. ValueList OpVL;
  8989. // Some intrinsics have scalar arguments. This argument should not be
  8990. // vectorized.
  8991. if (UseIntrinsic && isVectorIntrinsicWithScalarOpAtArg(IID, j)) {
  8992. CallInst *CEI = cast<CallInst>(VL0);
  8993. ScalarArg = CEI->getArgOperand(j);
  8994. OpVecs.push_back(CEI->getArgOperand(j));
  8995. if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
  8996. TysForDecl.push_back(ScalarArg->getType());
  8997. continue;
  8998. }
  8999. Value *OpVec = vectorizeOperand(E, j);
  9000. if (E->VectorizedValue) {
  9001. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  9002. return E->VectorizedValue;
  9003. }
  9004. LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
  9005. OpVecs.push_back(OpVec);
  9006. if (isVectorIntrinsicWithOverloadTypeAtArg(IID, j))
  9007. TysForDecl.push_back(OpVec->getType());
  9008. }
  9009. Function *CF;
  9010. if (!UseIntrinsic) {
  9011. VFShape Shape =
  9012. VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
  9013. VecTy->getNumElements())),
  9014. false /*HasGlobalPred*/);
  9015. CF = VFDatabase(*CI).getVectorizedFunction(Shape);
  9016. } else {
  9017. CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
  9018. }
  9019. SmallVector<OperandBundleDef, 1> OpBundles;
  9020. CI->getOperandBundlesAsDefs(OpBundles);
  9021. Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
  9022. // The scalar argument uses an in-tree scalar so we add the new vectorized
  9023. // call to ExternalUses list to make sure that an extract will be
  9024. // generated in the future.
  9025. if (ScalarArg) {
  9026. if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
  9027. // Find which lane we need to extract.
  9028. unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
  9029. ExternalUses.push_back(
  9030. ExternalUser(ScalarArg, cast<User>(V), FoundLane));
  9031. }
  9032. }
  9033. propagateIRFlags(V, E->Scalars, VL0);
  9034. V = FinalShuffle(V, E);
  9035. E->VectorizedValue = V;
  9036. ++NumVectorInstructions;
  9037. return V;
  9038. }
  9039. case Instruction::ShuffleVector: {
  9040. assert(E->isAltShuffle() &&
  9041. ((Instruction::isBinaryOp(E->getOpcode()) &&
  9042. Instruction::isBinaryOp(E->getAltOpcode())) ||
  9043. (Instruction::isCast(E->getOpcode()) &&
  9044. Instruction::isCast(E->getAltOpcode())) ||
  9045. (isa<CmpInst>(VL0) && isa<CmpInst>(E->getAltOp()))) &&
  9046. "Invalid Shuffle Vector Operand");
  9047. Value *LHS = nullptr, *RHS = nullptr;
  9048. if (Instruction::isBinaryOp(E->getOpcode()) || isa<CmpInst>(VL0)) {
  9049. setInsertPointAfterBundle(E);
  9050. LHS = vectorizeOperand(E, 0);
  9051. if (E->VectorizedValue) {
  9052. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  9053. return E->VectorizedValue;
  9054. }
  9055. RHS = vectorizeOperand(E, 1);
  9056. } else {
  9057. setInsertPointAfterBundle(E);
  9058. LHS = vectorizeOperand(E, 0);
  9059. }
  9060. if (E->VectorizedValue) {
  9061. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  9062. return E->VectorizedValue;
  9063. }
  9064. Value *V0, *V1;
  9065. if (Instruction::isBinaryOp(E->getOpcode())) {
  9066. V0 = Builder.CreateBinOp(
  9067. static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
  9068. V1 = Builder.CreateBinOp(
  9069. static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
  9070. } else if (auto *CI0 = dyn_cast<CmpInst>(VL0)) {
  9071. V0 = Builder.CreateCmp(CI0->getPredicate(), LHS, RHS);
  9072. auto *AltCI = cast<CmpInst>(E->getAltOp());
  9073. CmpInst::Predicate AltPred = AltCI->getPredicate();
  9074. V1 = Builder.CreateCmp(AltPred, LHS, RHS);
  9075. } else {
  9076. V0 = Builder.CreateCast(
  9077. static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
  9078. V1 = Builder.CreateCast(
  9079. static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
  9080. }
  9081. // Add V0 and V1 to later analysis to try to find and remove matching
  9082. // instruction, if any.
  9083. for (Value *V : {V0, V1}) {
  9084. if (auto *I = dyn_cast<Instruction>(V)) {
  9085. GatherShuffleExtractSeq.insert(I);
  9086. CSEBlocks.insert(I->getParent());
  9087. }
  9088. }
  9089. // Create shuffle to take alternate operations from the vector.
  9090. // Also, gather up main and alt scalar ops to propagate IR flags to
  9091. // each vector operation.
  9092. ValueList OpScalars, AltScalars;
  9093. SmallVector<int> Mask;
  9094. buildShuffleEntryMask(
  9095. E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
  9096. [E, this](Instruction *I) {
  9097. assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
  9098. return isAlternateInstruction(I, E->getMainOp(), E->getAltOp(),
  9099. *TLI);
  9100. },
  9101. Mask, &OpScalars, &AltScalars);
  9102. propagateIRFlags(V0, OpScalars);
  9103. propagateIRFlags(V1, AltScalars);
  9104. Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
  9105. if (auto *I = dyn_cast<Instruction>(V)) {
  9106. V = propagateMetadata(I, E->Scalars);
  9107. GatherShuffleExtractSeq.insert(I);
  9108. CSEBlocks.insert(I->getParent());
  9109. }
  9110. E->VectorizedValue = V;
  9111. ++NumVectorInstructions;
  9112. return V;
  9113. }
  9114. default:
  9115. llvm_unreachable("unknown inst");
  9116. }
  9117. return nullptr;
  9118. }
  9119. Value *BoUpSLP::vectorizeTree() {
  9120. ExtraValueToDebugLocsMap ExternallyUsedValues;
  9121. return vectorizeTree(ExternallyUsedValues);
  9122. }
  9123. namespace {
  9124. /// Data type for handling buildvector sequences with the reused scalars from
  9125. /// other tree entries.
  9126. struct ShuffledInsertData {
  9127. /// List of insertelements to be replaced by shuffles.
  9128. SmallVector<InsertElementInst *> InsertElements;
  9129. /// The parent vectors and shuffle mask for the given list of inserts.
  9130. MapVector<Value *, SmallVector<int>> ValueMasks;
  9131. };
  9132. } // namespace
  9133. Value *BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues,
  9134. Instruction *ReductionRoot) {
  9135. // All blocks must be scheduled before any instructions are inserted.
  9136. for (auto &BSIter : BlocksSchedules) {
  9137. scheduleBlock(BSIter.second.get());
  9138. }
  9139. // Pre-gather last instructions.
  9140. for (const std::unique_ptr<TreeEntry> &E : VectorizableTree) {
  9141. if ((E->State == TreeEntry::NeedToGather &&
  9142. (!E->getMainOp() || E->Idx > 0)) ||
  9143. (E->State != TreeEntry::NeedToGather &&
  9144. E->getOpcode() == Instruction::ExtractValue) ||
  9145. E->getOpcode() == Instruction::InsertElement)
  9146. continue;
  9147. Instruction *LastInst = &getLastInstructionInBundle(E.get());
  9148. EntryToLastInstruction.try_emplace(E.get(), LastInst);
  9149. }
  9150. Builder.SetInsertPoint(ReductionRoot ? ReductionRoot
  9151. : &F->getEntryBlock().front());
  9152. auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
  9153. // If the vectorized tree can be rewritten in a smaller type, we truncate the
  9154. // vectorized root. InstCombine will then rewrite the entire expression. We
  9155. // sign extend the extracted values below.
  9156. auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
  9157. if (MinBWs.count(ScalarRoot)) {
  9158. if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
  9159. // If current instr is a phi and not the last phi, insert it after the
  9160. // last phi node.
  9161. if (isa<PHINode>(I))
  9162. Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
  9163. else
  9164. Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
  9165. }
  9166. auto BundleWidth = VectorizableTree[0]->Scalars.size();
  9167. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  9168. auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
  9169. auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
  9170. VectorizableTree[0]->VectorizedValue = Trunc;
  9171. }
  9172. LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
  9173. << " values .\n");
  9174. SmallVector<ShuffledInsertData> ShuffledInserts;
  9175. // Maps vector instruction to original insertelement instruction
  9176. DenseMap<Value *, InsertElementInst *> VectorToInsertElement;
  9177. // Maps extract Scalar to the corresponding extractelement instruction in the
  9178. // basic block. Only one extractelement per block should be emitted.
  9179. DenseMap<Value *, DenseMap<BasicBlock *, Instruction *>> ScalarToEEs;
  9180. // Extract all of the elements with the external uses.
  9181. for (const auto &ExternalUse : ExternalUses) {
  9182. Value *Scalar = ExternalUse.Scalar;
  9183. llvm::User *User = ExternalUse.User;
  9184. // Skip users that we already RAUW. This happens when one instruction
  9185. // has multiple uses of the same value.
  9186. if (User && !is_contained(Scalar->users(), User))
  9187. continue;
  9188. TreeEntry *E = getTreeEntry(Scalar);
  9189. assert(E && "Invalid scalar");
  9190. assert(E->State != TreeEntry::NeedToGather &&
  9191. "Extracting from a gather list");
  9192. // Non-instruction pointers are not deleted, just skip them.
  9193. if (E->getOpcode() == Instruction::GetElementPtr &&
  9194. !isa<GetElementPtrInst>(Scalar))
  9195. continue;
  9196. Value *Vec = E->VectorizedValue;
  9197. assert(Vec && "Can't find vectorizable value");
  9198. Value *Lane = Builder.getInt32(ExternalUse.Lane);
  9199. auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
  9200. if (Scalar->getType() != Vec->getType()) {
  9201. Value *Ex = nullptr;
  9202. auto It = ScalarToEEs.find(Scalar);
  9203. if (It != ScalarToEEs.end()) {
  9204. // No need to emit many extracts, just move the only one in the
  9205. // current block.
  9206. auto EEIt = It->second.find(Builder.GetInsertBlock());
  9207. if (EEIt != It->second.end()) {
  9208. Instruction *I = EEIt->second;
  9209. if (Builder.GetInsertPoint() != Builder.GetInsertBlock()->end() &&
  9210. Builder.GetInsertPoint()->comesBefore(I))
  9211. I->moveBefore(&*Builder.GetInsertPoint());
  9212. Ex = I;
  9213. }
  9214. }
  9215. if (!Ex) {
  9216. // "Reuse" the existing extract to improve final codegen.
  9217. if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
  9218. Ex = Builder.CreateExtractElement(ES->getOperand(0),
  9219. ES->getOperand(1));
  9220. } else {
  9221. Ex = Builder.CreateExtractElement(Vec, Lane);
  9222. }
  9223. if (auto *I = dyn_cast<Instruction>(Ex))
  9224. ScalarToEEs[Scalar].try_emplace(Builder.GetInsertBlock(), I);
  9225. }
  9226. // The then branch of the previous if may produce constants, since 0
  9227. // operand might be a constant.
  9228. if (auto *ExI = dyn_cast<Instruction>(Ex)) {
  9229. GatherShuffleExtractSeq.insert(ExI);
  9230. CSEBlocks.insert(ExI->getParent());
  9231. }
  9232. // If necessary, sign-extend or zero-extend ScalarRoot
  9233. // to the larger type.
  9234. if (!MinBWs.count(ScalarRoot))
  9235. return Ex;
  9236. if (MinBWs[ScalarRoot].second)
  9237. return Builder.CreateSExt(Ex, Scalar->getType());
  9238. return Builder.CreateZExt(Ex, Scalar->getType());
  9239. }
  9240. assert(isa<FixedVectorType>(Scalar->getType()) &&
  9241. isa<InsertElementInst>(Scalar) &&
  9242. "In-tree scalar of vector type is not insertelement?");
  9243. auto *IE = cast<InsertElementInst>(Scalar);
  9244. VectorToInsertElement.try_emplace(Vec, IE);
  9245. return Vec;
  9246. };
  9247. // If User == nullptr, the Scalar is used as extra arg. Generate
  9248. // ExtractElement instruction and update the record for this scalar in
  9249. // ExternallyUsedValues.
  9250. if (!User) {
  9251. assert(ExternallyUsedValues.count(Scalar) &&
  9252. "Scalar with nullptr as an external user must be registered in "
  9253. "ExternallyUsedValues map");
  9254. if (auto *VecI = dyn_cast<Instruction>(Vec)) {
  9255. if (auto *PHI = dyn_cast<PHINode>(VecI))
  9256. Builder.SetInsertPoint(PHI->getParent()->getFirstNonPHI());
  9257. else
  9258. Builder.SetInsertPoint(VecI->getParent(),
  9259. std::next(VecI->getIterator()));
  9260. } else {
  9261. Builder.SetInsertPoint(&F->getEntryBlock().front());
  9262. }
  9263. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  9264. auto &NewInstLocs = ExternallyUsedValues[NewInst];
  9265. auto It = ExternallyUsedValues.find(Scalar);
  9266. assert(It != ExternallyUsedValues.end() &&
  9267. "Externally used scalar is not found in ExternallyUsedValues");
  9268. NewInstLocs.append(It->second);
  9269. ExternallyUsedValues.erase(Scalar);
  9270. // Required to update internally referenced instructions.
  9271. Scalar->replaceAllUsesWith(NewInst);
  9272. continue;
  9273. }
  9274. if (auto *VU = dyn_cast<InsertElementInst>(User)) {
  9275. // Skip if the scalar is another vector op or Vec is not an instruction.
  9276. if (!Scalar->getType()->isVectorTy() && isa<Instruction>(Vec)) {
  9277. if (auto *FTy = dyn_cast<FixedVectorType>(User->getType())) {
  9278. std::optional<unsigned> InsertIdx = getInsertIndex(VU);
  9279. if (InsertIdx) {
  9280. // Need to use original vector, if the root is truncated.
  9281. if (MinBWs.count(Scalar) &&
  9282. VectorizableTree[0]->VectorizedValue == Vec)
  9283. Vec = VectorRoot;
  9284. auto *It =
  9285. find_if(ShuffledInserts, [VU](const ShuffledInsertData &Data) {
  9286. // Checks if 2 insertelements are from the same buildvector.
  9287. InsertElementInst *VecInsert = Data.InsertElements.front();
  9288. return areTwoInsertFromSameBuildVector(
  9289. VU, VecInsert,
  9290. [](InsertElementInst *II) { return II->getOperand(0); });
  9291. });
  9292. unsigned Idx = *InsertIdx;
  9293. if (It == ShuffledInserts.end()) {
  9294. (void)ShuffledInserts.emplace_back();
  9295. It = std::next(ShuffledInserts.begin(),
  9296. ShuffledInserts.size() - 1);
  9297. SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
  9298. if (Mask.empty())
  9299. Mask.assign(FTy->getNumElements(), UndefMaskElem);
  9300. // Find the insertvector, vectorized in tree, if any.
  9301. Value *Base = VU;
  9302. while (auto *IEBase = dyn_cast<InsertElementInst>(Base)) {
  9303. if (IEBase != User &&
  9304. (!IEBase->hasOneUse() ||
  9305. getInsertIndex(IEBase).value_or(Idx) == Idx))
  9306. break;
  9307. // Build the mask for the vectorized insertelement instructions.
  9308. if (const TreeEntry *E = getTreeEntry(IEBase)) {
  9309. do {
  9310. IEBase = cast<InsertElementInst>(Base);
  9311. int IEIdx = *getInsertIndex(IEBase);
  9312. assert(Mask[Idx] == UndefMaskElem &&
  9313. "InsertElementInstruction used already.");
  9314. Mask[IEIdx] = IEIdx;
  9315. Base = IEBase->getOperand(0);
  9316. } while (E == getTreeEntry(Base));
  9317. break;
  9318. }
  9319. Base = cast<InsertElementInst>(Base)->getOperand(0);
  9320. // After the vectorization the def-use chain has changed, need
  9321. // to look through original insertelement instructions, if they
  9322. // get replaced by vector instructions.
  9323. auto It = VectorToInsertElement.find(Base);
  9324. if (It != VectorToInsertElement.end())
  9325. Base = It->second;
  9326. }
  9327. }
  9328. SmallVectorImpl<int> &Mask = It->ValueMasks[Vec];
  9329. if (Mask.empty())
  9330. Mask.assign(FTy->getNumElements(), UndefMaskElem);
  9331. Mask[Idx] = ExternalUse.Lane;
  9332. It->InsertElements.push_back(cast<InsertElementInst>(User));
  9333. continue;
  9334. }
  9335. }
  9336. }
  9337. }
  9338. // Generate extracts for out-of-tree users.
  9339. // Find the insertion point for the extractelement lane.
  9340. if (auto *VecI = dyn_cast<Instruction>(Vec)) {
  9341. if (PHINode *PH = dyn_cast<PHINode>(User)) {
  9342. for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
  9343. if (PH->getIncomingValue(i) == Scalar) {
  9344. Instruction *IncomingTerminator =
  9345. PH->getIncomingBlock(i)->getTerminator();
  9346. if (isa<CatchSwitchInst>(IncomingTerminator)) {
  9347. Builder.SetInsertPoint(VecI->getParent(),
  9348. std::next(VecI->getIterator()));
  9349. } else {
  9350. Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
  9351. }
  9352. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  9353. PH->setOperand(i, NewInst);
  9354. }
  9355. }
  9356. } else {
  9357. Builder.SetInsertPoint(cast<Instruction>(User));
  9358. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  9359. User->replaceUsesOfWith(Scalar, NewInst);
  9360. }
  9361. } else {
  9362. Builder.SetInsertPoint(&F->getEntryBlock().front());
  9363. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  9364. User->replaceUsesOfWith(Scalar, NewInst);
  9365. }
  9366. LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
  9367. }
  9368. auto CreateShuffle = [&](Value *V1, Value *V2, ArrayRef<int> Mask) {
  9369. SmallVector<int> CombinedMask1(Mask.size(), UndefMaskElem);
  9370. SmallVector<int> CombinedMask2(Mask.size(), UndefMaskElem);
  9371. int VF = cast<FixedVectorType>(V1->getType())->getNumElements();
  9372. for (int I = 0, E = Mask.size(); I < E; ++I) {
  9373. if (Mask[I] < VF)
  9374. CombinedMask1[I] = Mask[I];
  9375. else
  9376. CombinedMask2[I] = Mask[I] - VF;
  9377. }
  9378. ShuffleInstructionBuilder ShuffleBuilder(Builder, *this);
  9379. ShuffleBuilder.add(V1, CombinedMask1);
  9380. if (V2)
  9381. ShuffleBuilder.add(V2, CombinedMask2);
  9382. return ShuffleBuilder.finalize(std::nullopt);
  9383. };
  9384. auto &&ResizeToVF = [&CreateShuffle](Value *Vec, ArrayRef<int> Mask,
  9385. bool ForSingleMask) {
  9386. unsigned VF = Mask.size();
  9387. unsigned VecVF = cast<FixedVectorType>(Vec->getType())->getNumElements();
  9388. if (VF != VecVF) {
  9389. if (any_of(Mask, [VF](int Idx) { return Idx >= static_cast<int>(VF); })) {
  9390. Vec = CreateShuffle(Vec, nullptr, Mask);
  9391. return std::make_pair(Vec, true);
  9392. }
  9393. if (!ForSingleMask) {
  9394. SmallVector<int> ResizeMask(VF, UndefMaskElem);
  9395. for (unsigned I = 0; I < VF; ++I) {
  9396. if (Mask[I] != UndefMaskElem)
  9397. ResizeMask[Mask[I]] = Mask[I];
  9398. }
  9399. Vec = CreateShuffle(Vec, nullptr, ResizeMask);
  9400. }
  9401. }
  9402. return std::make_pair(Vec, false);
  9403. };
  9404. // Perform shuffling of the vectorize tree entries for better handling of
  9405. // external extracts.
  9406. for (int I = 0, E = ShuffledInserts.size(); I < E; ++I) {
  9407. // Find the first and the last instruction in the list of insertelements.
  9408. sort(ShuffledInserts[I].InsertElements, isFirstInsertElement);
  9409. InsertElementInst *FirstInsert = ShuffledInserts[I].InsertElements.front();
  9410. InsertElementInst *LastInsert = ShuffledInserts[I].InsertElements.back();
  9411. Builder.SetInsertPoint(LastInsert);
  9412. auto Vector = ShuffledInserts[I].ValueMasks.takeVector();
  9413. Value *NewInst = performExtractsShuffleAction<Value>(
  9414. MutableArrayRef(Vector.data(), Vector.size()),
  9415. FirstInsert->getOperand(0),
  9416. [](Value *Vec) {
  9417. return cast<VectorType>(Vec->getType())
  9418. ->getElementCount()
  9419. .getKnownMinValue();
  9420. },
  9421. ResizeToVF,
  9422. [FirstInsert, &CreateShuffle](ArrayRef<int> Mask,
  9423. ArrayRef<Value *> Vals) {
  9424. assert((Vals.size() == 1 || Vals.size() == 2) &&
  9425. "Expected exactly 1 or 2 input values.");
  9426. if (Vals.size() == 1) {
  9427. // Do not create shuffle if the mask is a simple identity
  9428. // non-resizing mask.
  9429. if (Mask.size() != cast<FixedVectorType>(Vals.front()->getType())
  9430. ->getNumElements() ||
  9431. !ShuffleVectorInst::isIdentityMask(Mask))
  9432. return CreateShuffle(Vals.front(), nullptr, Mask);
  9433. return Vals.front();
  9434. }
  9435. return CreateShuffle(Vals.front() ? Vals.front()
  9436. : FirstInsert->getOperand(0),
  9437. Vals.back(), Mask);
  9438. });
  9439. auto It = ShuffledInserts[I].InsertElements.rbegin();
  9440. // Rebuild buildvector chain.
  9441. InsertElementInst *II = nullptr;
  9442. if (It != ShuffledInserts[I].InsertElements.rend())
  9443. II = *It;
  9444. SmallVector<Instruction *> Inserts;
  9445. while (It != ShuffledInserts[I].InsertElements.rend()) {
  9446. assert(II && "Must be an insertelement instruction.");
  9447. if (*It == II)
  9448. ++It;
  9449. else
  9450. Inserts.push_back(cast<Instruction>(II));
  9451. II = dyn_cast<InsertElementInst>(II->getOperand(0));
  9452. }
  9453. for (Instruction *II : reverse(Inserts)) {
  9454. II->replaceUsesOfWith(II->getOperand(0), NewInst);
  9455. if (auto *NewI = dyn_cast<Instruction>(NewInst))
  9456. if (II->getParent() == NewI->getParent() && II->comesBefore(NewI))
  9457. II->moveAfter(NewI);
  9458. NewInst = II;
  9459. }
  9460. LastInsert->replaceAllUsesWith(NewInst);
  9461. for (InsertElementInst *IE : reverse(ShuffledInserts[I].InsertElements)) {
  9462. IE->replaceUsesOfWith(IE->getOperand(0),
  9463. PoisonValue::get(IE->getOperand(0)->getType()));
  9464. IE->replaceUsesOfWith(IE->getOperand(1),
  9465. PoisonValue::get(IE->getOperand(1)->getType()));
  9466. eraseInstruction(IE);
  9467. }
  9468. CSEBlocks.insert(LastInsert->getParent());
  9469. }
  9470. SmallVector<Instruction *> RemovedInsts;
  9471. // For each vectorized value:
  9472. for (auto &TEPtr : VectorizableTree) {
  9473. TreeEntry *Entry = TEPtr.get();
  9474. // No need to handle users of gathered values.
  9475. if (Entry->State == TreeEntry::NeedToGather)
  9476. continue;
  9477. assert(Entry->VectorizedValue && "Can't find vectorizable value");
  9478. // For each lane:
  9479. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  9480. Value *Scalar = Entry->Scalars[Lane];
  9481. if (Entry->getOpcode() == Instruction::GetElementPtr &&
  9482. !isa<GetElementPtrInst>(Scalar))
  9483. continue;
  9484. #ifndef NDEBUG
  9485. Type *Ty = Scalar->getType();
  9486. if (!Ty->isVoidTy()) {
  9487. for (User *U : Scalar->users()) {
  9488. LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
  9489. // It is legal to delete users in the ignorelist.
  9490. assert((getTreeEntry(U) ||
  9491. (UserIgnoreList && UserIgnoreList->contains(U)) ||
  9492. (isa_and_nonnull<Instruction>(U) &&
  9493. isDeleted(cast<Instruction>(U)))) &&
  9494. "Deleting out-of-tree value");
  9495. }
  9496. }
  9497. #endif
  9498. LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
  9499. eraseInstruction(cast<Instruction>(Scalar));
  9500. // Retain to-be-deleted instructions for some debug-info
  9501. // bookkeeping. NOTE: eraseInstruction only marks the instruction for
  9502. // deletion - instructions are not deleted until later.
  9503. RemovedInsts.push_back(cast<Instruction>(Scalar));
  9504. }
  9505. }
  9506. // Merge the DIAssignIDs from the about-to-be-deleted instructions into the
  9507. // new vector instruction.
  9508. if (auto *V = dyn_cast<Instruction>(VectorizableTree[0]->VectorizedValue))
  9509. V->mergeDIAssignID(RemovedInsts);
  9510. Builder.ClearInsertionPoint();
  9511. InstrElementSize.clear();
  9512. return VectorizableTree[0]->VectorizedValue;
  9513. }
  9514. void BoUpSLP::optimizeGatherSequence() {
  9515. LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleExtractSeq.size()
  9516. << " gather sequences instructions.\n");
  9517. // LICM InsertElementInst sequences.
  9518. for (Instruction *I : GatherShuffleExtractSeq) {
  9519. if (isDeleted(I))
  9520. continue;
  9521. // Check if this block is inside a loop.
  9522. Loop *L = LI->getLoopFor(I->getParent());
  9523. if (!L)
  9524. continue;
  9525. // Check if it has a preheader.
  9526. BasicBlock *PreHeader = L->getLoopPreheader();
  9527. if (!PreHeader)
  9528. continue;
  9529. // If the vector or the element that we insert into it are
  9530. // instructions that are defined in this basic block then we can't
  9531. // hoist this instruction.
  9532. if (any_of(I->operands(), [L](Value *V) {
  9533. auto *OpI = dyn_cast<Instruction>(V);
  9534. return OpI && L->contains(OpI);
  9535. }))
  9536. continue;
  9537. // We can hoist this instruction. Move it to the pre-header.
  9538. I->moveBefore(PreHeader->getTerminator());
  9539. CSEBlocks.insert(PreHeader);
  9540. }
  9541. // Make a list of all reachable blocks in our CSE queue.
  9542. SmallVector<const DomTreeNode *, 8> CSEWorkList;
  9543. CSEWorkList.reserve(CSEBlocks.size());
  9544. for (BasicBlock *BB : CSEBlocks)
  9545. if (DomTreeNode *N = DT->getNode(BB)) {
  9546. assert(DT->isReachableFromEntry(N));
  9547. CSEWorkList.push_back(N);
  9548. }
  9549. // Sort blocks by domination. This ensures we visit a block after all blocks
  9550. // dominating it are visited.
  9551. llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
  9552. assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
  9553. "Different nodes should have different DFS numbers");
  9554. return A->getDFSNumIn() < B->getDFSNumIn();
  9555. });
  9556. // Less defined shuffles can be replaced by the more defined copies.
  9557. // Between two shuffles one is less defined if it has the same vector operands
  9558. // and its mask indeces are the same as in the first one or undefs. E.g.
  9559. // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
  9560. // poison, <0, 0, 0, 0>.
  9561. auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
  9562. SmallVectorImpl<int> &NewMask) {
  9563. if (I1->getType() != I2->getType())
  9564. return false;
  9565. auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
  9566. auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
  9567. if (!SI1 || !SI2)
  9568. return I1->isIdenticalTo(I2);
  9569. if (SI1->isIdenticalTo(SI2))
  9570. return true;
  9571. for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
  9572. if (SI1->getOperand(I) != SI2->getOperand(I))
  9573. return false;
  9574. // Check if the second instruction is more defined than the first one.
  9575. NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
  9576. ArrayRef<int> SM1 = SI1->getShuffleMask();
  9577. // Count trailing undefs in the mask to check the final number of used
  9578. // registers.
  9579. unsigned LastUndefsCnt = 0;
  9580. for (int I = 0, E = NewMask.size(); I < E; ++I) {
  9581. if (SM1[I] == UndefMaskElem)
  9582. ++LastUndefsCnt;
  9583. else
  9584. LastUndefsCnt = 0;
  9585. if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
  9586. NewMask[I] != SM1[I])
  9587. return false;
  9588. if (NewMask[I] == UndefMaskElem)
  9589. NewMask[I] = SM1[I];
  9590. }
  9591. // Check if the last undefs actually change the final number of used vector
  9592. // registers.
  9593. return SM1.size() - LastUndefsCnt > 1 &&
  9594. TTI->getNumberOfParts(SI1->getType()) ==
  9595. TTI->getNumberOfParts(
  9596. FixedVectorType::get(SI1->getType()->getElementType(),
  9597. SM1.size() - LastUndefsCnt));
  9598. };
  9599. // Perform O(N^2) search over the gather/shuffle sequences and merge identical
  9600. // instructions. TODO: We can further optimize this scan if we split the
  9601. // instructions into different buckets based on the insert lane.
  9602. SmallVector<Instruction *, 16> Visited;
  9603. for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
  9604. assert(*I &&
  9605. (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
  9606. "Worklist not sorted properly!");
  9607. BasicBlock *BB = (*I)->getBlock();
  9608. // For all instructions in blocks containing gather sequences:
  9609. for (Instruction &In : llvm::make_early_inc_range(*BB)) {
  9610. if (isDeleted(&In))
  9611. continue;
  9612. if (!isa<InsertElementInst, ExtractElementInst, ShuffleVectorInst>(&In) &&
  9613. !GatherShuffleExtractSeq.contains(&In))
  9614. continue;
  9615. // Check if we can replace this instruction with any of the
  9616. // visited instructions.
  9617. bool Replaced = false;
  9618. for (Instruction *&V : Visited) {
  9619. SmallVector<int> NewMask;
  9620. if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
  9621. DT->dominates(V->getParent(), In.getParent())) {
  9622. In.replaceAllUsesWith(V);
  9623. eraseInstruction(&In);
  9624. if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
  9625. if (!NewMask.empty())
  9626. SI->setShuffleMask(NewMask);
  9627. Replaced = true;
  9628. break;
  9629. }
  9630. if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
  9631. GatherShuffleExtractSeq.contains(V) &&
  9632. IsIdenticalOrLessDefined(V, &In, NewMask) &&
  9633. DT->dominates(In.getParent(), V->getParent())) {
  9634. In.moveAfter(V);
  9635. V->replaceAllUsesWith(&In);
  9636. eraseInstruction(V);
  9637. if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
  9638. if (!NewMask.empty())
  9639. SI->setShuffleMask(NewMask);
  9640. V = &In;
  9641. Replaced = true;
  9642. break;
  9643. }
  9644. }
  9645. if (!Replaced) {
  9646. assert(!is_contained(Visited, &In));
  9647. Visited.push_back(&In);
  9648. }
  9649. }
  9650. }
  9651. CSEBlocks.clear();
  9652. GatherShuffleExtractSeq.clear();
  9653. }
  9654. BoUpSLP::ScheduleData *
  9655. BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
  9656. ScheduleData *Bundle = nullptr;
  9657. ScheduleData *PrevInBundle = nullptr;
  9658. for (Value *V : VL) {
  9659. if (doesNotNeedToBeScheduled(V))
  9660. continue;
  9661. ScheduleData *BundleMember = getScheduleData(V);
  9662. assert(BundleMember &&
  9663. "no ScheduleData for bundle member "
  9664. "(maybe not in same basic block)");
  9665. assert(BundleMember->isSchedulingEntity() &&
  9666. "bundle member already part of other bundle");
  9667. if (PrevInBundle) {
  9668. PrevInBundle->NextInBundle = BundleMember;
  9669. } else {
  9670. Bundle = BundleMember;
  9671. }
  9672. // Group the instructions to a bundle.
  9673. BundleMember->FirstInBundle = Bundle;
  9674. PrevInBundle = BundleMember;
  9675. }
  9676. assert(Bundle && "Failed to find schedule bundle");
  9677. return Bundle;
  9678. }
  9679. // Groups the instructions to a bundle (which is then a single scheduling entity)
  9680. // and schedules instructions until the bundle gets ready.
  9681. std::optional<BoUpSLP::ScheduleData *>
  9682. BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
  9683. const InstructionsState &S) {
  9684. // No need to schedule PHIs, insertelement, extractelement and extractvalue
  9685. // instructions.
  9686. if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue) ||
  9687. doesNotNeedToSchedule(VL))
  9688. return nullptr;
  9689. // Initialize the instruction bundle.
  9690. Instruction *OldScheduleEnd = ScheduleEnd;
  9691. LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n");
  9692. auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
  9693. ScheduleData *Bundle) {
  9694. // The scheduling region got new instructions at the lower end (or it is a
  9695. // new region for the first bundle). This makes it necessary to
  9696. // recalculate all dependencies.
  9697. // It is seldom that this needs to be done a second time after adding the
  9698. // initial bundle to the region.
  9699. if (ScheduleEnd != OldScheduleEnd) {
  9700. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
  9701. doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
  9702. ReSchedule = true;
  9703. }
  9704. if (Bundle) {
  9705. LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
  9706. << " in block " << BB->getName() << "\n");
  9707. calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
  9708. }
  9709. if (ReSchedule) {
  9710. resetSchedule();
  9711. initialFillReadyList(ReadyInsts);
  9712. }
  9713. // Now try to schedule the new bundle or (if no bundle) just calculate
  9714. // dependencies. As soon as the bundle is "ready" it means that there are no
  9715. // cyclic dependencies and we can schedule it. Note that's important that we
  9716. // don't "schedule" the bundle yet (see cancelScheduling).
  9717. while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
  9718. !ReadyInsts.empty()) {
  9719. ScheduleData *Picked = ReadyInsts.pop_back_val();
  9720. assert(Picked->isSchedulingEntity() && Picked->isReady() &&
  9721. "must be ready to schedule");
  9722. schedule(Picked, ReadyInsts);
  9723. }
  9724. };
  9725. // Make sure that the scheduling region contains all
  9726. // instructions of the bundle.
  9727. for (Value *V : VL) {
  9728. if (doesNotNeedToBeScheduled(V))
  9729. continue;
  9730. if (!extendSchedulingRegion(V, S)) {
  9731. // If the scheduling region got new instructions at the lower end (or it
  9732. // is a new region for the first bundle). This makes it necessary to
  9733. // recalculate all dependencies.
  9734. // Otherwise the compiler may crash trying to incorrectly calculate
  9735. // dependencies and emit instruction in the wrong order at the actual
  9736. // scheduling.
  9737. TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
  9738. return std::nullopt;
  9739. }
  9740. }
  9741. bool ReSchedule = false;
  9742. for (Value *V : VL) {
  9743. if (doesNotNeedToBeScheduled(V))
  9744. continue;
  9745. ScheduleData *BundleMember = getScheduleData(V);
  9746. assert(BundleMember &&
  9747. "no ScheduleData for bundle member (maybe not in same basic block)");
  9748. // Make sure we don't leave the pieces of the bundle in the ready list when
  9749. // whole bundle might not be ready.
  9750. ReadyInsts.remove(BundleMember);
  9751. if (!BundleMember->IsScheduled)
  9752. continue;
  9753. // A bundle member was scheduled as single instruction before and now
  9754. // needs to be scheduled as part of the bundle. We just get rid of the
  9755. // existing schedule.
  9756. LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
  9757. << " was already scheduled\n");
  9758. ReSchedule = true;
  9759. }
  9760. auto *Bundle = buildBundle(VL);
  9761. TryScheduleBundleImpl(ReSchedule, Bundle);
  9762. if (!Bundle->isReady()) {
  9763. cancelScheduling(VL, S.OpValue);
  9764. return std::nullopt;
  9765. }
  9766. return Bundle;
  9767. }
  9768. void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
  9769. Value *OpValue) {
  9770. if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue) ||
  9771. doesNotNeedToSchedule(VL))
  9772. return;
  9773. if (doesNotNeedToBeScheduled(OpValue))
  9774. OpValue = *find_if_not(VL, doesNotNeedToBeScheduled);
  9775. ScheduleData *Bundle = getScheduleData(OpValue);
  9776. LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
  9777. assert(!Bundle->IsScheduled &&
  9778. "Can't cancel bundle which is already scheduled");
  9779. assert(Bundle->isSchedulingEntity() &&
  9780. (Bundle->isPartOfBundle() || needToScheduleSingleInstruction(VL)) &&
  9781. "tried to unbundle something which is not a bundle");
  9782. // Remove the bundle from the ready list.
  9783. if (Bundle->isReady())
  9784. ReadyInsts.remove(Bundle);
  9785. // Un-bundle: make single instructions out of the bundle.
  9786. ScheduleData *BundleMember = Bundle;
  9787. while (BundleMember) {
  9788. assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
  9789. BundleMember->FirstInBundle = BundleMember;
  9790. ScheduleData *Next = BundleMember->NextInBundle;
  9791. BundleMember->NextInBundle = nullptr;
  9792. BundleMember->TE = nullptr;
  9793. if (BundleMember->unscheduledDepsInBundle() == 0) {
  9794. ReadyInsts.insert(BundleMember);
  9795. }
  9796. BundleMember = Next;
  9797. }
  9798. }
  9799. BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
  9800. // Allocate a new ScheduleData for the instruction.
  9801. if (ChunkPos >= ChunkSize) {
  9802. ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
  9803. ChunkPos = 0;
  9804. }
  9805. return &(ScheduleDataChunks.back()[ChunkPos++]);
  9806. }
  9807. bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
  9808. const InstructionsState &S) {
  9809. if (getScheduleData(V, isOneOf(S, V)))
  9810. return true;
  9811. Instruction *I = dyn_cast<Instruction>(V);
  9812. assert(I && "bundle member must be an instruction");
  9813. assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
  9814. !doesNotNeedToBeScheduled(I) &&
  9815. "phi nodes/insertelements/extractelements/extractvalues don't need to "
  9816. "be scheduled");
  9817. auto &&CheckScheduleForI = [this, &S](Instruction *I) -> bool {
  9818. ScheduleData *ISD = getScheduleData(I);
  9819. if (!ISD)
  9820. return false;
  9821. assert(isInSchedulingRegion(ISD) &&
  9822. "ScheduleData not in scheduling region");
  9823. ScheduleData *SD = allocateScheduleDataChunks();
  9824. SD->Inst = I;
  9825. SD->init(SchedulingRegionID, S.OpValue);
  9826. ExtraScheduleDataMap[I][S.OpValue] = SD;
  9827. return true;
  9828. };
  9829. if (CheckScheduleForI(I))
  9830. return true;
  9831. if (!ScheduleStart) {
  9832. // It's the first instruction in the new region.
  9833. initScheduleData(I, I->getNextNode(), nullptr, nullptr);
  9834. ScheduleStart = I;
  9835. ScheduleEnd = I->getNextNode();
  9836. if (isOneOf(S, I) != I)
  9837. CheckScheduleForI(I);
  9838. assert(ScheduleEnd && "tried to vectorize a terminator?");
  9839. LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
  9840. return true;
  9841. }
  9842. // Search up and down at the same time, because we don't know if the new
  9843. // instruction is above or below the existing scheduling region.
  9844. BasicBlock::reverse_iterator UpIter =
  9845. ++ScheduleStart->getIterator().getReverse();
  9846. BasicBlock::reverse_iterator UpperEnd = BB->rend();
  9847. BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
  9848. BasicBlock::iterator LowerEnd = BB->end();
  9849. while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
  9850. &*DownIter != I) {
  9851. if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
  9852. LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
  9853. return false;
  9854. }
  9855. ++UpIter;
  9856. ++DownIter;
  9857. }
  9858. if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
  9859. assert(I->getParent() == ScheduleStart->getParent() &&
  9860. "Instruction is in wrong basic block.");
  9861. initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
  9862. ScheduleStart = I;
  9863. if (isOneOf(S, I) != I)
  9864. CheckScheduleForI(I);
  9865. LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I
  9866. << "\n");
  9867. return true;
  9868. }
  9869. assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
  9870. "Expected to reach top of the basic block or instruction down the "
  9871. "lower end.");
  9872. assert(I->getParent() == ScheduleEnd->getParent() &&
  9873. "Instruction is in wrong basic block.");
  9874. initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
  9875. nullptr);
  9876. ScheduleEnd = I->getNextNode();
  9877. if (isOneOf(S, I) != I)
  9878. CheckScheduleForI(I);
  9879. assert(ScheduleEnd && "tried to vectorize a terminator?");
  9880. LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
  9881. return true;
  9882. }
  9883. void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
  9884. Instruction *ToI,
  9885. ScheduleData *PrevLoadStore,
  9886. ScheduleData *NextLoadStore) {
  9887. ScheduleData *CurrentLoadStore = PrevLoadStore;
  9888. for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
  9889. // No need to allocate data for non-schedulable instructions.
  9890. if (doesNotNeedToBeScheduled(I))
  9891. continue;
  9892. ScheduleData *SD = ScheduleDataMap.lookup(I);
  9893. if (!SD) {
  9894. SD = allocateScheduleDataChunks();
  9895. ScheduleDataMap[I] = SD;
  9896. SD->Inst = I;
  9897. }
  9898. assert(!isInSchedulingRegion(SD) &&
  9899. "new ScheduleData already in scheduling region");
  9900. SD->init(SchedulingRegionID, I);
  9901. if (I->mayReadOrWriteMemory() &&
  9902. (!isa<IntrinsicInst>(I) ||
  9903. (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
  9904. cast<IntrinsicInst>(I)->getIntrinsicID() !=
  9905. Intrinsic::pseudoprobe))) {
  9906. // Update the linked list of memory accessing instructions.
  9907. if (CurrentLoadStore) {
  9908. CurrentLoadStore->NextLoadStore = SD;
  9909. } else {
  9910. FirstLoadStoreInRegion = SD;
  9911. }
  9912. CurrentLoadStore = SD;
  9913. }
  9914. if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
  9915. match(I, m_Intrinsic<Intrinsic::stackrestore>()))
  9916. RegionHasStackSave = true;
  9917. }
  9918. if (NextLoadStore) {
  9919. if (CurrentLoadStore)
  9920. CurrentLoadStore->NextLoadStore = NextLoadStore;
  9921. } else {
  9922. LastLoadStoreInRegion = CurrentLoadStore;
  9923. }
  9924. }
  9925. void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
  9926. bool InsertInReadyList,
  9927. BoUpSLP *SLP) {
  9928. assert(SD->isSchedulingEntity());
  9929. SmallVector<ScheduleData *, 10> WorkList;
  9930. WorkList.push_back(SD);
  9931. while (!WorkList.empty()) {
  9932. ScheduleData *SD = WorkList.pop_back_val();
  9933. for (ScheduleData *BundleMember = SD; BundleMember;
  9934. BundleMember = BundleMember->NextInBundle) {
  9935. assert(isInSchedulingRegion(BundleMember));
  9936. if (BundleMember->hasValidDependencies())
  9937. continue;
  9938. LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember
  9939. << "\n");
  9940. BundleMember->Dependencies = 0;
  9941. BundleMember->resetUnscheduledDeps();
  9942. // Handle def-use chain dependencies.
  9943. if (BundleMember->OpValue != BundleMember->Inst) {
  9944. if (ScheduleData *UseSD = getScheduleData(BundleMember->Inst)) {
  9945. BundleMember->Dependencies++;
  9946. ScheduleData *DestBundle = UseSD->FirstInBundle;
  9947. if (!DestBundle->IsScheduled)
  9948. BundleMember->incrementUnscheduledDeps(1);
  9949. if (!DestBundle->hasValidDependencies())
  9950. WorkList.push_back(DestBundle);
  9951. }
  9952. } else {
  9953. for (User *U : BundleMember->Inst->users()) {
  9954. if (ScheduleData *UseSD = getScheduleData(cast<Instruction>(U))) {
  9955. BundleMember->Dependencies++;
  9956. ScheduleData *DestBundle = UseSD->FirstInBundle;
  9957. if (!DestBundle->IsScheduled)
  9958. BundleMember->incrementUnscheduledDeps(1);
  9959. if (!DestBundle->hasValidDependencies())
  9960. WorkList.push_back(DestBundle);
  9961. }
  9962. }
  9963. }
  9964. auto makeControlDependent = [&](Instruction *I) {
  9965. auto *DepDest = getScheduleData(I);
  9966. assert(DepDest && "must be in schedule window");
  9967. DepDest->ControlDependencies.push_back(BundleMember);
  9968. BundleMember->Dependencies++;
  9969. ScheduleData *DestBundle = DepDest->FirstInBundle;
  9970. if (!DestBundle->IsScheduled)
  9971. BundleMember->incrementUnscheduledDeps(1);
  9972. if (!DestBundle->hasValidDependencies())
  9973. WorkList.push_back(DestBundle);
  9974. };
  9975. // Any instruction which isn't safe to speculate at the beginning of the
  9976. // block is control dependend on any early exit or non-willreturn call
  9977. // which proceeds it.
  9978. if (!isGuaranteedToTransferExecutionToSuccessor(BundleMember->Inst)) {
  9979. for (Instruction *I = BundleMember->Inst->getNextNode();
  9980. I != ScheduleEnd; I = I->getNextNode()) {
  9981. if (isSafeToSpeculativelyExecute(I, &*BB->begin(), SLP->AC))
  9982. continue;
  9983. // Add the dependency
  9984. makeControlDependent(I);
  9985. if (!isGuaranteedToTransferExecutionToSuccessor(I))
  9986. // Everything past here must be control dependent on I.
  9987. break;
  9988. }
  9989. }
  9990. if (RegionHasStackSave) {
  9991. // If we have an inalloc alloca instruction, it needs to be scheduled
  9992. // after any preceeding stacksave. We also need to prevent any alloca
  9993. // from reordering above a preceeding stackrestore.
  9994. if (match(BundleMember->Inst, m_Intrinsic<Intrinsic::stacksave>()) ||
  9995. match(BundleMember->Inst, m_Intrinsic<Intrinsic::stackrestore>())) {
  9996. for (Instruction *I = BundleMember->Inst->getNextNode();
  9997. I != ScheduleEnd; I = I->getNextNode()) {
  9998. if (match(I, m_Intrinsic<Intrinsic::stacksave>()) ||
  9999. match(I, m_Intrinsic<Intrinsic::stackrestore>()))
  10000. // Any allocas past here must be control dependent on I, and I
  10001. // must be memory dependend on BundleMember->Inst.
  10002. break;
  10003. if (!isa<AllocaInst>(I))
  10004. continue;
  10005. // Add the dependency
  10006. makeControlDependent(I);
  10007. }
  10008. }
  10009. // In addition to the cases handle just above, we need to prevent
  10010. // allocas and loads/stores from moving below a stacksave or a
  10011. // stackrestore. Avoiding moving allocas below stackrestore is currently
  10012. // thought to be conservatism. Moving loads/stores below a stackrestore
  10013. // can lead to incorrect code.
  10014. if (isa<AllocaInst>(BundleMember->Inst) ||
  10015. BundleMember->Inst->mayReadOrWriteMemory()) {
  10016. for (Instruction *I = BundleMember->Inst->getNextNode();
  10017. I != ScheduleEnd; I = I->getNextNode()) {
  10018. if (!match(I, m_Intrinsic<Intrinsic::stacksave>()) &&
  10019. !match(I, m_Intrinsic<Intrinsic::stackrestore>()))
  10020. continue;
  10021. // Add the dependency
  10022. makeControlDependent(I);
  10023. break;
  10024. }
  10025. }
  10026. }
  10027. // Handle the memory dependencies (if any).
  10028. ScheduleData *DepDest = BundleMember->NextLoadStore;
  10029. if (!DepDest)
  10030. continue;
  10031. Instruction *SrcInst = BundleMember->Inst;
  10032. assert(SrcInst->mayReadOrWriteMemory() &&
  10033. "NextLoadStore list for non memory effecting bundle?");
  10034. MemoryLocation SrcLoc = getLocation(SrcInst);
  10035. bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
  10036. unsigned numAliased = 0;
  10037. unsigned DistToSrc = 1;
  10038. for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
  10039. assert(isInSchedulingRegion(DepDest));
  10040. // We have two limits to reduce the complexity:
  10041. // 1) AliasedCheckLimit: It's a small limit to reduce calls to
  10042. // SLP->isAliased (which is the expensive part in this loop).
  10043. // 2) MaxMemDepDistance: It's for very large blocks and it aborts
  10044. // the whole loop (even if the loop is fast, it's quadratic).
  10045. // It's important for the loop break condition (see below) to
  10046. // check this limit even between two read-only instructions.
  10047. if (DistToSrc >= MaxMemDepDistance ||
  10048. ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
  10049. (numAliased >= AliasedCheckLimit ||
  10050. SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
  10051. // We increment the counter only if the locations are aliased
  10052. // (instead of counting all alias checks). This gives a better
  10053. // balance between reduced runtime and accurate dependencies.
  10054. numAliased++;
  10055. DepDest->MemoryDependencies.push_back(BundleMember);
  10056. BundleMember->Dependencies++;
  10057. ScheduleData *DestBundle = DepDest->FirstInBundle;
  10058. if (!DestBundle->IsScheduled) {
  10059. BundleMember->incrementUnscheduledDeps(1);
  10060. }
  10061. if (!DestBundle->hasValidDependencies()) {
  10062. WorkList.push_back(DestBundle);
  10063. }
  10064. }
  10065. // Example, explaining the loop break condition: Let's assume our
  10066. // starting instruction is i0 and MaxMemDepDistance = 3.
  10067. //
  10068. // +--------v--v--v
  10069. // i0,i1,i2,i3,i4,i5,i6,i7,i8
  10070. // +--------^--^--^
  10071. //
  10072. // MaxMemDepDistance let us stop alias-checking at i3 and we add
  10073. // dependencies from i0 to i3,i4,.. (even if they are not aliased).
  10074. // Previously we already added dependencies from i3 to i6,i7,i8
  10075. // (because of MaxMemDepDistance). As we added a dependency from
  10076. // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
  10077. // and we can abort this loop at i6.
  10078. if (DistToSrc >= 2 * MaxMemDepDistance)
  10079. break;
  10080. DistToSrc++;
  10081. }
  10082. }
  10083. if (InsertInReadyList && SD->isReady()) {
  10084. ReadyInsts.insert(SD);
  10085. LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst
  10086. << "\n");
  10087. }
  10088. }
  10089. }
  10090. void BoUpSLP::BlockScheduling::resetSchedule() {
  10091. assert(ScheduleStart &&
  10092. "tried to reset schedule on block which has not been scheduled");
  10093. for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  10094. doForAllOpcodes(I, [&](ScheduleData *SD) {
  10095. assert(isInSchedulingRegion(SD) &&
  10096. "ScheduleData not in scheduling region");
  10097. SD->IsScheduled = false;
  10098. SD->resetUnscheduledDeps();
  10099. });
  10100. }
  10101. ReadyInsts.clear();
  10102. }
  10103. void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
  10104. if (!BS->ScheduleStart)
  10105. return;
  10106. LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
  10107. // A key point - if we got here, pre-scheduling was able to find a valid
  10108. // scheduling of the sub-graph of the scheduling window which consists
  10109. // of all vector bundles and their transitive users. As such, we do not
  10110. // need to reschedule anything *outside of* that subgraph.
  10111. BS->resetSchedule();
  10112. // For the real scheduling we use a more sophisticated ready-list: it is
  10113. // sorted by the original instruction location. This lets the final schedule
  10114. // be as close as possible to the original instruction order.
  10115. // WARNING: If changing this order causes a correctness issue, that means
  10116. // there is some missing dependence edge in the schedule data graph.
  10117. struct ScheduleDataCompare {
  10118. bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
  10119. return SD2->SchedulingPriority < SD1->SchedulingPriority;
  10120. }
  10121. };
  10122. std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
  10123. // Ensure that all dependency data is updated (for nodes in the sub-graph)
  10124. // and fill the ready-list with initial instructions.
  10125. int Idx = 0;
  10126. for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
  10127. I = I->getNextNode()) {
  10128. BS->doForAllOpcodes(I, [this, &Idx, BS](ScheduleData *SD) {
  10129. TreeEntry *SDTE = getTreeEntry(SD->Inst);
  10130. (void)SDTE;
  10131. assert((isVectorLikeInstWithConstOps(SD->Inst) ||
  10132. SD->isPartOfBundle() ==
  10133. (SDTE && !doesNotNeedToSchedule(SDTE->Scalars))) &&
  10134. "scheduler and vectorizer bundle mismatch");
  10135. SD->FirstInBundle->SchedulingPriority = Idx++;
  10136. if (SD->isSchedulingEntity() && SD->isPartOfBundle())
  10137. BS->calculateDependencies(SD, false, this);
  10138. });
  10139. }
  10140. BS->initialFillReadyList(ReadyInsts);
  10141. Instruction *LastScheduledInst = BS->ScheduleEnd;
  10142. // Do the "real" scheduling.
  10143. while (!ReadyInsts.empty()) {
  10144. ScheduleData *picked = *ReadyInsts.begin();
  10145. ReadyInsts.erase(ReadyInsts.begin());
  10146. // Move the scheduled instruction(s) to their dedicated places, if not
  10147. // there yet.
  10148. for (ScheduleData *BundleMember = picked; BundleMember;
  10149. BundleMember = BundleMember->NextInBundle) {
  10150. Instruction *pickedInst = BundleMember->Inst;
  10151. if (pickedInst->getNextNode() != LastScheduledInst)
  10152. pickedInst->moveBefore(LastScheduledInst);
  10153. LastScheduledInst = pickedInst;
  10154. }
  10155. BS->schedule(picked, ReadyInsts);
  10156. }
  10157. // Check that we didn't break any of our invariants.
  10158. #ifdef EXPENSIVE_CHECKS
  10159. BS->verify();
  10160. #endif
  10161. #if !defined(NDEBUG) || defined(EXPENSIVE_CHECKS)
  10162. // Check that all schedulable entities got scheduled
  10163. for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd; I = I->getNextNode()) {
  10164. BS->doForAllOpcodes(I, [&](ScheduleData *SD) {
  10165. if (SD->isSchedulingEntity() && SD->hasValidDependencies()) {
  10166. assert(SD->IsScheduled && "must be scheduled at this point");
  10167. }
  10168. });
  10169. }
  10170. #endif
  10171. // Avoid duplicate scheduling of the block.
  10172. BS->ScheduleStart = nullptr;
  10173. }
  10174. unsigned BoUpSLP::getVectorElementSize(Value *V) {
  10175. // If V is a store, just return the width of the stored value (or value
  10176. // truncated just before storing) without traversing the expression tree.
  10177. // This is the common case.
  10178. if (auto *Store = dyn_cast<StoreInst>(V))
  10179. return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
  10180. if (auto *IEI = dyn_cast<InsertElementInst>(V))
  10181. return getVectorElementSize(IEI->getOperand(1));
  10182. auto E = InstrElementSize.find(V);
  10183. if (E != InstrElementSize.end())
  10184. return E->second;
  10185. // If V is not a store, we can traverse the expression tree to find loads
  10186. // that feed it. The type of the loaded value may indicate a more suitable
  10187. // width than V's type. We want to base the vector element size on the width
  10188. // of memory operations where possible.
  10189. SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
  10190. SmallPtrSet<Instruction *, 16> Visited;
  10191. if (auto *I = dyn_cast<Instruction>(V)) {
  10192. Worklist.emplace_back(I, I->getParent());
  10193. Visited.insert(I);
  10194. }
  10195. // Traverse the expression tree in bottom-up order looking for loads. If we
  10196. // encounter an instruction we don't yet handle, we give up.
  10197. auto Width = 0u;
  10198. while (!Worklist.empty()) {
  10199. Instruction *I;
  10200. BasicBlock *Parent;
  10201. std::tie(I, Parent) = Worklist.pop_back_val();
  10202. // We should only be looking at scalar instructions here. If the current
  10203. // instruction has a vector type, skip.
  10204. auto *Ty = I->getType();
  10205. if (isa<VectorType>(Ty))
  10206. continue;
  10207. // If the current instruction is a load, update MaxWidth to reflect the
  10208. // width of the loaded value.
  10209. if (isa<LoadInst, ExtractElementInst, ExtractValueInst>(I))
  10210. Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
  10211. // Otherwise, we need to visit the operands of the instruction. We only
  10212. // handle the interesting cases from buildTree here. If an operand is an
  10213. // instruction we haven't yet visited and from the same basic block as the
  10214. // user or the use is a PHI node, we add it to the worklist.
  10215. else if (isa<PHINode, CastInst, GetElementPtrInst, CmpInst, SelectInst,
  10216. BinaryOperator, UnaryOperator>(I)) {
  10217. for (Use &U : I->operands())
  10218. if (auto *J = dyn_cast<Instruction>(U.get()))
  10219. if (Visited.insert(J).second &&
  10220. (isa<PHINode>(I) || J->getParent() == Parent))
  10221. Worklist.emplace_back(J, J->getParent());
  10222. } else {
  10223. break;
  10224. }
  10225. }
  10226. // If we didn't encounter a memory access in the expression tree, or if we
  10227. // gave up for some reason, just return the width of V. Otherwise, return the
  10228. // maximum width we found.
  10229. if (!Width) {
  10230. if (auto *CI = dyn_cast<CmpInst>(V))
  10231. V = CI->getOperand(0);
  10232. Width = DL->getTypeSizeInBits(V->getType());
  10233. }
  10234. for (Instruction *I : Visited)
  10235. InstrElementSize[I] = Width;
  10236. return Width;
  10237. }
  10238. // Determine if a value V in a vectorizable expression Expr can be demoted to a
  10239. // smaller type with a truncation. We collect the values that will be demoted
  10240. // in ToDemote and additional roots that require investigating in Roots.
  10241. static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
  10242. SmallVectorImpl<Value *> &ToDemote,
  10243. SmallVectorImpl<Value *> &Roots) {
  10244. // We can always demote constants.
  10245. if (isa<Constant>(V)) {
  10246. ToDemote.push_back(V);
  10247. return true;
  10248. }
  10249. // If the value is not an instruction in the expression with only one use, it
  10250. // cannot be demoted.
  10251. auto *I = dyn_cast<Instruction>(V);
  10252. if (!I || !I->hasOneUse() || !Expr.count(I))
  10253. return false;
  10254. switch (I->getOpcode()) {
  10255. // We can always demote truncations and extensions. Since truncations can
  10256. // seed additional demotion, we save the truncated value.
  10257. case Instruction::Trunc:
  10258. Roots.push_back(I->getOperand(0));
  10259. break;
  10260. case Instruction::ZExt:
  10261. case Instruction::SExt:
  10262. if (isa<ExtractElementInst, InsertElementInst>(I->getOperand(0)))
  10263. return false;
  10264. break;
  10265. // We can demote certain binary operations if we can demote both of their
  10266. // operands.
  10267. case Instruction::Add:
  10268. case Instruction::Sub:
  10269. case Instruction::Mul:
  10270. case Instruction::And:
  10271. case Instruction::Or:
  10272. case Instruction::Xor:
  10273. if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
  10274. !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
  10275. return false;
  10276. break;
  10277. // We can demote selects if we can demote their true and false values.
  10278. case Instruction::Select: {
  10279. SelectInst *SI = cast<SelectInst>(I);
  10280. if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
  10281. !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
  10282. return false;
  10283. break;
  10284. }
  10285. // We can demote phis if we can demote all their incoming operands. Note that
  10286. // we don't need to worry about cycles since we ensure single use above.
  10287. case Instruction::PHI: {
  10288. PHINode *PN = cast<PHINode>(I);
  10289. for (Value *IncValue : PN->incoming_values())
  10290. if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
  10291. return false;
  10292. break;
  10293. }
  10294. // Otherwise, conservatively give up.
  10295. default:
  10296. return false;
  10297. }
  10298. // Record the value that we can demote.
  10299. ToDemote.push_back(V);
  10300. return true;
  10301. }
  10302. void BoUpSLP::computeMinimumValueSizes() {
  10303. // If there are no external uses, the expression tree must be rooted by a
  10304. // store. We can't demote in-memory values, so there is nothing to do here.
  10305. if (ExternalUses.empty())
  10306. return;
  10307. // We only attempt to truncate integer expressions.
  10308. auto &TreeRoot = VectorizableTree[0]->Scalars;
  10309. auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
  10310. if (!TreeRootIT)
  10311. return;
  10312. // If the expression is not rooted by a store, these roots should have
  10313. // external uses. We will rely on InstCombine to rewrite the expression in
  10314. // the narrower type. However, InstCombine only rewrites single-use values.
  10315. // This means that if a tree entry other than a root is used externally, it
  10316. // must have multiple uses and InstCombine will not rewrite it. The code
  10317. // below ensures that only the roots are used externally.
  10318. SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
  10319. for (auto &EU : ExternalUses)
  10320. if (!Expr.erase(EU.Scalar))
  10321. return;
  10322. if (!Expr.empty())
  10323. return;
  10324. // Collect the scalar values of the vectorizable expression. We will use this
  10325. // context to determine which values can be demoted. If we see a truncation,
  10326. // we mark it as seeding another demotion.
  10327. for (auto &EntryPtr : VectorizableTree)
  10328. Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
  10329. // Ensure the roots of the vectorizable tree don't form a cycle. They must
  10330. // have a single external user that is not in the vectorizable tree.
  10331. for (auto *Root : TreeRoot)
  10332. if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
  10333. return;
  10334. // Conservatively determine if we can actually truncate the roots of the
  10335. // expression. Collect the values that can be demoted in ToDemote and
  10336. // additional roots that require investigating in Roots.
  10337. SmallVector<Value *, 32> ToDemote;
  10338. SmallVector<Value *, 4> Roots;
  10339. for (auto *Root : TreeRoot)
  10340. if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
  10341. return;
  10342. // The maximum bit width required to represent all the values that can be
  10343. // demoted without loss of precision. It would be safe to truncate the roots
  10344. // of the expression to this width.
  10345. auto MaxBitWidth = 8u;
  10346. // We first check if all the bits of the roots are demanded. If they're not,
  10347. // we can truncate the roots to this narrower type.
  10348. for (auto *Root : TreeRoot) {
  10349. auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
  10350. MaxBitWidth = std::max<unsigned>(
  10351. Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
  10352. }
  10353. // True if the roots can be zero-extended back to their original type, rather
  10354. // than sign-extended. We know that if the leading bits are not demanded, we
  10355. // can safely zero-extend. So we initialize IsKnownPositive to True.
  10356. bool IsKnownPositive = true;
  10357. // If all the bits of the roots are demanded, we can try a little harder to
  10358. // compute a narrower type. This can happen, for example, if the roots are
  10359. // getelementptr indices. InstCombine promotes these indices to the pointer
  10360. // width. Thus, all their bits are technically demanded even though the
  10361. // address computation might be vectorized in a smaller type.
  10362. //
  10363. // We start by looking at each entry that can be demoted. We compute the
  10364. // maximum bit width required to store the scalar by using ValueTracking to
  10365. // compute the number of high-order bits we can truncate.
  10366. if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
  10367. llvm::all_of(TreeRoot, [](Value *R) {
  10368. assert(R->hasOneUse() && "Root should have only one use!");
  10369. return isa<GetElementPtrInst>(R->user_back());
  10370. })) {
  10371. MaxBitWidth = 8u;
  10372. // Determine if the sign bit of all the roots is known to be zero. If not,
  10373. // IsKnownPositive is set to False.
  10374. IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
  10375. KnownBits Known = computeKnownBits(R, *DL);
  10376. return Known.isNonNegative();
  10377. });
  10378. // Determine the maximum number of bits required to store the scalar
  10379. // values.
  10380. for (auto *Scalar : ToDemote) {
  10381. auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
  10382. auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
  10383. MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
  10384. }
  10385. // If we can't prove that the sign bit is zero, we must add one to the
  10386. // maximum bit width to account for the unknown sign bit. This preserves
  10387. // the existing sign bit so we can safely sign-extend the root back to the
  10388. // original type. Otherwise, if we know the sign bit is zero, we will
  10389. // zero-extend the root instead.
  10390. //
  10391. // FIXME: This is somewhat suboptimal, as there will be cases where adding
  10392. // one to the maximum bit width will yield a larger-than-necessary
  10393. // type. In general, we need to add an extra bit only if we can't
  10394. // prove that the upper bit of the original type is equal to the
  10395. // upper bit of the proposed smaller type. If these two bits are the
  10396. // same (either zero or one) we know that sign-extending from the
  10397. // smaller type will result in the same value. Here, since we can't
  10398. // yet prove this, we are just making the proposed smaller type
  10399. // larger to ensure correctness.
  10400. if (!IsKnownPositive)
  10401. ++MaxBitWidth;
  10402. }
  10403. // Round MaxBitWidth up to the next power-of-two.
  10404. if (!isPowerOf2_64(MaxBitWidth))
  10405. MaxBitWidth = NextPowerOf2(MaxBitWidth);
  10406. // If the maximum bit width we compute is less than the with of the roots'
  10407. // type, we can proceed with the narrowing. Otherwise, do nothing.
  10408. if (MaxBitWidth >= TreeRootIT->getBitWidth())
  10409. return;
  10410. // If we can truncate the root, we must collect additional values that might
  10411. // be demoted as a result. That is, those seeded by truncations we will
  10412. // modify.
  10413. while (!Roots.empty())
  10414. collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
  10415. // Finally, map the values we can demote to the maximum bit with we computed.
  10416. for (auto *Scalar : ToDemote)
  10417. MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
  10418. }
  10419. namespace {
  10420. /// The SLPVectorizer Pass.
  10421. struct SLPVectorizer : public FunctionPass {
  10422. SLPVectorizerPass Impl;
  10423. /// Pass identification, replacement for typeid
  10424. static char ID;
  10425. explicit SLPVectorizer() : FunctionPass(ID) {
  10426. initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
  10427. }
  10428. bool doInitialization(Module &M) override { return false; }
  10429. bool runOnFunction(Function &F) override {
  10430. if (skipFunction(F))
  10431. return false;
  10432. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  10433. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  10434. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  10435. auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
  10436. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  10437. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  10438. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  10439. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  10440. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  10441. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  10442. return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
  10443. }
  10444. void getAnalysisUsage(AnalysisUsage &AU) const override {
  10445. FunctionPass::getAnalysisUsage(AU);
  10446. AU.addRequired<AssumptionCacheTracker>();
  10447. AU.addRequired<ScalarEvolutionWrapperPass>();
  10448. AU.addRequired<AAResultsWrapperPass>();
  10449. AU.addRequired<TargetTransformInfoWrapperPass>();
  10450. AU.addRequired<LoopInfoWrapperPass>();
  10451. AU.addRequired<DominatorTreeWrapperPass>();
  10452. AU.addRequired<DemandedBitsWrapperPass>();
  10453. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  10454. AU.addRequired<InjectTLIMappingsLegacy>();
  10455. AU.addPreserved<LoopInfoWrapperPass>();
  10456. AU.addPreserved<DominatorTreeWrapperPass>();
  10457. AU.addPreserved<AAResultsWrapperPass>();
  10458. AU.addPreserved<GlobalsAAWrapperPass>();
  10459. AU.setPreservesCFG();
  10460. }
  10461. };
  10462. } // end anonymous namespace
  10463. PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
  10464. auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
  10465. auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
  10466. auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
  10467. auto *AA = &AM.getResult<AAManager>(F);
  10468. auto *LI = &AM.getResult<LoopAnalysis>(F);
  10469. auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
  10470. auto *AC = &AM.getResult<AssumptionAnalysis>(F);
  10471. auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
  10472. auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  10473. bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
  10474. if (!Changed)
  10475. return PreservedAnalyses::all();
  10476. PreservedAnalyses PA;
  10477. PA.preserveSet<CFGAnalyses>();
  10478. return PA;
  10479. }
  10480. bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
  10481. TargetTransformInfo *TTI_,
  10482. TargetLibraryInfo *TLI_, AAResults *AA_,
  10483. LoopInfo *LI_, DominatorTree *DT_,
  10484. AssumptionCache *AC_, DemandedBits *DB_,
  10485. OptimizationRemarkEmitter *ORE_) {
  10486. if (!RunSLPVectorization)
  10487. return false;
  10488. SE = SE_;
  10489. TTI = TTI_;
  10490. TLI = TLI_;
  10491. AA = AA_;
  10492. LI = LI_;
  10493. DT = DT_;
  10494. AC = AC_;
  10495. DB = DB_;
  10496. DL = &F.getParent()->getDataLayout();
  10497. Stores.clear();
  10498. GEPs.clear();
  10499. bool Changed = false;
  10500. // If the target claims to have no vector registers don't attempt
  10501. // vectorization.
  10502. if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
  10503. LLVM_DEBUG(
  10504. dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
  10505. return false;
  10506. }
  10507. // Don't vectorize when the attribute NoImplicitFloat is used.
  10508. if (F.hasFnAttribute(Attribute::NoImplicitFloat))
  10509. return false;
  10510. LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
  10511. // Use the bottom up slp vectorizer to construct chains that start with
  10512. // store instructions.
  10513. BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
  10514. // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
  10515. // delete instructions.
  10516. // Update DFS numbers now so that we can use them for ordering.
  10517. DT->updateDFSNumbers();
  10518. // Scan the blocks in the function in post order.
  10519. for (auto *BB : post_order(&F.getEntryBlock())) {
  10520. // Start new block - clear the list of reduction roots.
  10521. R.clearReductionData();
  10522. collectSeedInstructions(BB);
  10523. // Vectorize trees that end at stores.
  10524. if (!Stores.empty()) {
  10525. LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
  10526. << " underlying objects.\n");
  10527. Changed |= vectorizeStoreChains(R);
  10528. }
  10529. // Vectorize trees that end at reductions.
  10530. Changed |= vectorizeChainsInBlock(BB, R);
  10531. // Vectorize the index computations of getelementptr instructions. This
  10532. // is primarily intended to catch gather-like idioms ending at
  10533. // non-consecutive loads.
  10534. if (!GEPs.empty()) {
  10535. LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
  10536. << " underlying objects.\n");
  10537. Changed |= vectorizeGEPIndices(BB, R);
  10538. }
  10539. }
  10540. if (Changed) {
  10541. R.optimizeGatherSequence();
  10542. LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
  10543. }
  10544. return Changed;
  10545. }
  10546. bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
  10547. unsigned Idx, unsigned MinVF) {
  10548. LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
  10549. << "\n");
  10550. const unsigned Sz = R.getVectorElementSize(Chain[0]);
  10551. unsigned VF = Chain.size();
  10552. if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
  10553. return false;
  10554. LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
  10555. << "\n");
  10556. R.buildTree(Chain);
  10557. if (R.isTreeTinyAndNotFullyVectorizable())
  10558. return false;
  10559. if (R.isLoadCombineCandidate())
  10560. return false;
  10561. R.reorderTopToBottom();
  10562. R.reorderBottomToTop();
  10563. R.buildExternalUses();
  10564. R.computeMinimumValueSizes();
  10565. InstructionCost Cost = R.getTreeCost();
  10566. LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF=" << VF << "\n");
  10567. if (Cost < -SLPCostThreshold) {
  10568. LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
  10569. using namespace ore;
  10570. R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
  10571. cast<StoreInst>(Chain[0]))
  10572. << "Stores SLP vectorized with cost " << NV("Cost", Cost)
  10573. << " and with tree size "
  10574. << NV("TreeSize", R.getTreeSize()));
  10575. R.vectorizeTree();
  10576. return true;
  10577. }
  10578. return false;
  10579. }
  10580. bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
  10581. BoUpSLP &R) {
  10582. // We may run into multiple chains that merge into a single chain. We mark the
  10583. // stores that we vectorized so that we don't visit the same store twice.
  10584. BoUpSLP::ValueSet VectorizedStores;
  10585. bool Changed = false;
  10586. int E = Stores.size();
  10587. SmallBitVector Tails(E, false);
  10588. int MaxIter = MaxStoreLookup.getValue();
  10589. SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
  10590. E, std::make_pair(E, INT_MAX));
  10591. SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
  10592. int IterCnt;
  10593. auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
  10594. &CheckedPairs,
  10595. &ConsecutiveChain](int K, int Idx) {
  10596. if (IterCnt >= MaxIter)
  10597. return true;
  10598. if (CheckedPairs[Idx].test(K))
  10599. return ConsecutiveChain[K].second == 1 &&
  10600. ConsecutiveChain[K].first == Idx;
  10601. ++IterCnt;
  10602. CheckedPairs[Idx].set(K);
  10603. CheckedPairs[K].set(Idx);
  10604. std::optional<int> Diff = getPointersDiff(
  10605. Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
  10606. Stores[Idx]->getValueOperand()->getType(),
  10607. Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
  10608. if (!Diff || *Diff == 0)
  10609. return false;
  10610. int Val = *Diff;
  10611. if (Val < 0) {
  10612. if (ConsecutiveChain[Idx].second > -Val) {
  10613. Tails.set(K);
  10614. ConsecutiveChain[Idx] = std::make_pair(K, -Val);
  10615. }
  10616. return false;
  10617. }
  10618. if (ConsecutiveChain[K].second <= Val)
  10619. return false;
  10620. Tails.set(Idx);
  10621. ConsecutiveChain[K] = std::make_pair(Idx, Val);
  10622. return Val == 1;
  10623. };
  10624. // Do a quadratic search on all of the given stores in reverse order and find
  10625. // all of the pairs of stores that follow each other.
  10626. for (int Idx = E - 1; Idx >= 0; --Idx) {
  10627. // If a store has multiple consecutive store candidates, search according
  10628. // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
  10629. // This is because usually pairing with immediate succeeding or preceding
  10630. // candidate create the best chance to find slp vectorization opportunity.
  10631. const int MaxLookDepth = std::max(E - Idx, Idx + 1);
  10632. IterCnt = 0;
  10633. for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
  10634. if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
  10635. (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
  10636. break;
  10637. }
  10638. // Tracks if we tried to vectorize stores starting from the given tail
  10639. // already.
  10640. SmallBitVector TriedTails(E, false);
  10641. // For stores that start but don't end a link in the chain:
  10642. for (int Cnt = E; Cnt > 0; --Cnt) {
  10643. int I = Cnt - 1;
  10644. if (ConsecutiveChain[I].first == E || Tails.test(I))
  10645. continue;
  10646. // We found a store instr that starts a chain. Now follow the chain and try
  10647. // to vectorize it.
  10648. BoUpSLP::ValueList Operands;
  10649. // Collect the chain into a list.
  10650. while (I != E && !VectorizedStores.count(Stores[I])) {
  10651. Operands.push_back(Stores[I]);
  10652. Tails.set(I);
  10653. if (ConsecutiveChain[I].second != 1) {
  10654. // Mark the new end in the chain and go back, if required. It might be
  10655. // required if the original stores come in reversed order, for example.
  10656. if (ConsecutiveChain[I].first != E &&
  10657. Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
  10658. !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
  10659. TriedTails.set(I);
  10660. Tails.reset(ConsecutiveChain[I].first);
  10661. if (Cnt < ConsecutiveChain[I].first + 2)
  10662. Cnt = ConsecutiveChain[I].first + 2;
  10663. }
  10664. break;
  10665. }
  10666. // Move to the next value in the chain.
  10667. I = ConsecutiveChain[I].first;
  10668. }
  10669. assert(!Operands.empty() && "Expected non-empty list of stores.");
  10670. unsigned MaxVecRegSize = R.getMaxVecRegSize();
  10671. unsigned EltSize = R.getVectorElementSize(Operands[0]);
  10672. unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
  10673. unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
  10674. MaxElts);
  10675. auto *Store = cast<StoreInst>(Operands[0]);
  10676. Type *StoreTy = Store->getValueOperand()->getType();
  10677. Type *ValueTy = StoreTy;
  10678. if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
  10679. ValueTy = Trunc->getSrcTy();
  10680. unsigned MinVF = TTI->getStoreMinimumVF(
  10681. R.getMinVF(DL->getTypeSizeInBits(ValueTy)), StoreTy, ValueTy);
  10682. if (MaxVF <= MinVF) {
  10683. LLVM_DEBUG(dbgs() << "SLP: Vectorization infeasible as MaxVF (" << MaxVF << ") <= "
  10684. << "MinVF (" << MinVF << ")\n");
  10685. }
  10686. // FIXME: Is division-by-2 the correct step? Should we assert that the
  10687. // register size is a power-of-2?
  10688. unsigned StartIdx = 0;
  10689. for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
  10690. for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
  10691. ArrayRef<Value *> Slice = ArrayRef(Operands).slice(Cnt, Size);
  10692. if (!VectorizedStores.count(Slice.front()) &&
  10693. !VectorizedStores.count(Slice.back()) &&
  10694. vectorizeStoreChain(Slice, R, Cnt, MinVF)) {
  10695. // Mark the vectorized stores so that we don't vectorize them again.
  10696. VectorizedStores.insert(Slice.begin(), Slice.end());
  10697. Changed = true;
  10698. // If we vectorized initial block, no need to try to vectorize it
  10699. // again.
  10700. if (Cnt == StartIdx)
  10701. StartIdx += Size;
  10702. Cnt += Size;
  10703. continue;
  10704. }
  10705. ++Cnt;
  10706. }
  10707. // Check if the whole array was vectorized already - exit.
  10708. if (StartIdx >= Operands.size())
  10709. break;
  10710. }
  10711. }
  10712. return Changed;
  10713. }
  10714. void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
  10715. // Initialize the collections. We will make a single pass over the block.
  10716. Stores.clear();
  10717. GEPs.clear();
  10718. // Visit the store and getelementptr instructions in BB and organize them in
  10719. // Stores and GEPs according to the underlying objects of their pointer
  10720. // operands.
  10721. for (Instruction &I : *BB) {
  10722. // Ignore store instructions that are volatile or have a pointer operand
  10723. // that doesn't point to a scalar type.
  10724. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  10725. if (!SI->isSimple())
  10726. continue;
  10727. if (!isValidElementType(SI->getValueOperand()->getType()))
  10728. continue;
  10729. Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
  10730. }
  10731. // Ignore getelementptr instructions that have more than one index, a
  10732. // constant index, or a pointer operand that doesn't point to a scalar
  10733. // type.
  10734. else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  10735. auto Idx = GEP->idx_begin()->get();
  10736. if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
  10737. continue;
  10738. if (!isValidElementType(Idx->getType()))
  10739. continue;
  10740. if (GEP->getType()->isVectorTy())
  10741. continue;
  10742. GEPs[GEP->getPointerOperand()].push_back(GEP);
  10743. }
  10744. }
  10745. }
  10746. bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
  10747. if (!A || !B)
  10748. return false;
  10749. if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
  10750. return false;
  10751. Value *VL[] = {A, B};
  10752. return tryToVectorizeList(VL, R);
  10753. }
  10754. bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
  10755. bool LimitForRegisterSize) {
  10756. if (VL.size() < 2)
  10757. return false;
  10758. LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
  10759. << VL.size() << ".\n");
  10760. // Check that all of the parts are instructions of the same type,
  10761. // we permit an alternate opcode via InstructionsState.
  10762. InstructionsState S = getSameOpcode(VL, *TLI);
  10763. if (!S.getOpcode())
  10764. return false;
  10765. Instruction *I0 = cast<Instruction>(S.OpValue);
  10766. // Make sure invalid types (including vector type) are rejected before
  10767. // determining vectorization factor for scalar instructions.
  10768. for (Value *V : VL) {
  10769. Type *Ty = V->getType();
  10770. if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
  10771. // NOTE: the following will give user internal llvm type name, which may
  10772. // not be useful.
  10773. R.getORE()->emit([&]() {
  10774. std::string type_str;
  10775. llvm::raw_string_ostream rso(type_str);
  10776. Ty->print(rso);
  10777. return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
  10778. << "Cannot SLP vectorize list: type "
  10779. << rso.str() + " is unsupported by vectorizer";
  10780. });
  10781. return false;
  10782. }
  10783. }
  10784. unsigned Sz = R.getVectorElementSize(I0);
  10785. unsigned MinVF = R.getMinVF(Sz);
  10786. unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
  10787. MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
  10788. if (MaxVF < 2) {
  10789. R.getORE()->emit([&]() {
  10790. return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
  10791. << "Cannot SLP vectorize list: vectorization factor "
  10792. << "less than 2 is not supported";
  10793. });
  10794. return false;
  10795. }
  10796. bool Changed = false;
  10797. bool CandidateFound = false;
  10798. InstructionCost MinCost = SLPCostThreshold.getValue();
  10799. Type *ScalarTy = VL[0]->getType();
  10800. if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
  10801. ScalarTy = IE->getOperand(1)->getType();
  10802. unsigned NextInst = 0, MaxInst = VL.size();
  10803. for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
  10804. // No actual vectorization should happen, if number of parts is the same as
  10805. // provided vectorization factor (i.e. the scalar type is used for vector
  10806. // code during codegen).
  10807. auto *VecTy = FixedVectorType::get(ScalarTy, VF);
  10808. if (TTI->getNumberOfParts(VecTy) == VF)
  10809. continue;
  10810. for (unsigned I = NextInst; I < MaxInst; ++I) {
  10811. unsigned OpsWidth = 0;
  10812. if (I + VF > MaxInst)
  10813. OpsWidth = MaxInst - I;
  10814. else
  10815. OpsWidth = VF;
  10816. if (!isPowerOf2_32(OpsWidth))
  10817. continue;
  10818. if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
  10819. (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
  10820. break;
  10821. ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
  10822. // Check that a previous iteration of this loop did not delete the Value.
  10823. if (llvm::any_of(Ops, [&R](Value *V) {
  10824. auto *I = dyn_cast<Instruction>(V);
  10825. return I && R.isDeleted(I);
  10826. }))
  10827. continue;
  10828. LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
  10829. << "\n");
  10830. R.buildTree(Ops);
  10831. if (R.isTreeTinyAndNotFullyVectorizable())
  10832. continue;
  10833. R.reorderTopToBottom();
  10834. R.reorderBottomToTop(
  10835. /*IgnoreReorder=*/!isa<InsertElementInst>(Ops.front()) &&
  10836. !R.doesRootHaveInTreeUses());
  10837. R.buildExternalUses();
  10838. R.computeMinimumValueSizes();
  10839. InstructionCost Cost = R.getTreeCost();
  10840. CandidateFound = true;
  10841. MinCost = std::min(MinCost, Cost);
  10842. LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost
  10843. << " for VF=" << OpsWidth << "\n");
  10844. if (Cost < -SLPCostThreshold) {
  10845. LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
  10846. R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
  10847. cast<Instruction>(Ops[0]))
  10848. << "SLP vectorized with cost " << ore::NV("Cost", Cost)
  10849. << " and with tree size "
  10850. << ore::NV("TreeSize", R.getTreeSize()));
  10851. R.vectorizeTree();
  10852. // Move to the next bundle.
  10853. I += VF - 1;
  10854. NextInst = I + 1;
  10855. Changed = true;
  10856. }
  10857. }
  10858. }
  10859. if (!Changed && CandidateFound) {
  10860. R.getORE()->emit([&]() {
  10861. return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
  10862. << "List vectorization was possible but not beneficial with cost "
  10863. << ore::NV("Cost", MinCost) << " >= "
  10864. << ore::NV("Treshold", -SLPCostThreshold);
  10865. });
  10866. } else if (!Changed) {
  10867. R.getORE()->emit([&]() {
  10868. return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
  10869. << "Cannot SLP vectorize list: vectorization was impossible"
  10870. << " with available vectorization factors";
  10871. });
  10872. }
  10873. return Changed;
  10874. }
  10875. bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
  10876. if (!I)
  10877. return false;
  10878. if (!isa<BinaryOperator, CmpInst>(I) || isa<VectorType>(I->getType()))
  10879. return false;
  10880. Value *P = I->getParent();
  10881. // Vectorize in current basic block only.
  10882. auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
  10883. auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
  10884. if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
  10885. return false;
  10886. // First collect all possible candidates
  10887. SmallVector<std::pair<Value *, Value *>, 4> Candidates;
  10888. Candidates.emplace_back(Op0, Op1);
  10889. auto *A = dyn_cast<BinaryOperator>(Op0);
  10890. auto *B = dyn_cast<BinaryOperator>(Op1);
  10891. // Try to skip B.
  10892. if (A && B && B->hasOneUse()) {
  10893. auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
  10894. auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
  10895. if (B0 && B0->getParent() == P)
  10896. Candidates.emplace_back(A, B0);
  10897. if (B1 && B1->getParent() == P)
  10898. Candidates.emplace_back(A, B1);
  10899. }
  10900. // Try to skip A.
  10901. if (B && A && A->hasOneUse()) {
  10902. auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
  10903. auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
  10904. if (A0 && A0->getParent() == P)
  10905. Candidates.emplace_back(A0, B);
  10906. if (A1 && A1->getParent() == P)
  10907. Candidates.emplace_back(A1, B);
  10908. }
  10909. if (Candidates.size() == 1)
  10910. return tryToVectorizePair(Op0, Op1, R);
  10911. // We have multiple options. Try to pick the single best.
  10912. std::optional<int> BestCandidate = R.findBestRootPair(Candidates);
  10913. if (!BestCandidate)
  10914. return false;
  10915. return tryToVectorizePair(Candidates[*BestCandidate].first,
  10916. Candidates[*BestCandidate].second, R);
  10917. }
  10918. namespace {
  10919. /// Model horizontal reductions.
  10920. ///
  10921. /// A horizontal reduction is a tree of reduction instructions that has values
  10922. /// that can be put into a vector as its leaves. For example:
  10923. ///
  10924. /// mul mul mul mul
  10925. /// \ / \ /
  10926. /// + +
  10927. /// \ /
  10928. /// +
  10929. /// This tree has "mul" as its leaf values and "+" as its reduction
  10930. /// instructions. A reduction can feed into a store or a binary operation
  10931. /// feeding a phi.
  10932. /// ...
  10933. /// \ /
  10934. /// +
  10935. /// |
  10936. /// phi +=
  10937. ///
  10938. /// Or:
  10939. /// ...
  10940. /// \ /
  10941. /// +
  10942. /// |
  10943. /// *p =
  10944. ///
  10945. class HorizontalReduction {
  10946. using ReductionOpsType = SmallVector<Value *, 16>;
  10947. using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
  10948. ReductionOpsListType ReductionOps;
  10949. /// List of possibly reduced values.
  10950. SmallVector<SmallVector<Value *>> ReducedVals;
  10951. /// Maps reduced value to the corresponding reduction operation.
  10952. DenseMap<Value *, SmallVector<Instruction *>> ReducedValsToOps;
  10953. // Use map vector to make stable output.
  10954. MapVector<Instruction *, Value *> ExtraArgs;
  10955. WeakTrackingVH ReductionRoot;
  10956. /// The type of reduction operation.
  10957. RecurKind RdxKind;
  10958. static bool isCmpSelMinMax(Instruction *I) {
  10959. return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
  10960. RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
  10961. }
  10962. // And/or are potentially poison-safe logical patterns like:
  10963. // select x, y, false
  10964. // select x, true, y
  10965. static bool isBoolLogicOp(Instruction *I) {
  10966. return isa<SelectInst>(I) &&
  10967. (match(I, m_LogicalAnd()) || match(I, m_LogicalOr()));
  10968. }
  10969. /// Checks if instruction is associative and can be vectorized.
  10970. static bool isVectorizable(RecurKind Kind, Instruction *I) {
  10971. if (Kind == RecurKind::None)
  10972. return false;
  10973. // Integer ops that map to select instructions or intrinsics are fine.
  10974. if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
  10975. isBoolLogicOp(I))
  10976. return true;
  10977. if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
  10978. // FP min/max are associative except for NaN and -0.0. We do not
  10979. // have to rule out -0.0 here because the intrinsic semantics do not
  10980. // specify a fixed result for it.
  10981. return I->getFastMathFlags().noNaNs();
  10982. }
  10983. return I->isAssociative();
  10984. }
  10985. static Value *getRdxOperand(Instruction *I, unsigned Index) {
  10986. // Poison-safe 'or' takes the form: select X, true, Y
  10987. // To make that work with the normal operand processing, we skip the
  10988. // true value operand.
  10989. // TODO: Change the code and data structures to handle this without a hack.
  10990. if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
  10991. return I->getOperand(2);
  10992. return I->getOperand(Index);
  10993. }
  10994. /// Creates reduction operation with the current opcode.
  10995. static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
  10996. Value *RHS, const Twine &Name, bool UseSelect) {
  10997. unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
  10998. switch (Kind) {
  10999. case RecurKind::Or:
  11000. if (UseSelect &&
  11001. LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
  11002. return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
  11003. return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
  11004. Name);
  11005. case RecurKind::And:
  11006. if (UseSelect &&
  11007. LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
  11008. return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
  11009. return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
  11010. Name);
  11011. case RecurKind::Add:
  11012. case RecurKind::Mul:
  11013. case RecurKind::Xor:
  11014. case RecurKind::FAdd:
  11015. case RecurKind::FMul:
  11016. return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
  11017. Name);
  11018. case RecurKind::FMax:
  11019. return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
  11020. case RecurKind::FMin:
  11021. return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
  11022. case RecurKind::SMax:
  11023. if (UseSelect) {
  11024. Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
  11025. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  11026. }
  11027. return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
  11028. case RecurKind::SMin:
  11029. if (UseSelect) {
  11030. Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
  11031. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  11032. }
  11033. return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
  11034. case RecurKind::UMax:
  11035. if (UseSelect) {
  11036. Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
  11037. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  11038. }
  11039. return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
  11040. case RecurKind::UMin:
  11041. if (UseSelect) {
  11042. Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
  11043. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  11044. }
  11045. return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
  11046. default:
  11047. llvm_unreachable("Unknown reduction operation.");
  11048. }
  11049. }
  11050. /// Creates reduction operation with the current opcode with the IR flags
  11051. /// from \p ReductionOps, dropping nuw/nsw flags.
  11052. static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
  11053. Value *RHS, const Twine &Name,
  11054. const ReductionOpsListType &ReductionOps) {
  11055. bool UseSelect = ReductionOps.size() == 2 ||
  11056. // Logical or/and.
  11057. (ReductionOps.size() == 1 &&
  11058. isa<SelectInst>(ReductionOps.front().front()));
  11059. assert((!UseSelect || ReductionOps.size() != 2 ||
  11060. isa<SelectInst>(ReductionOps[1][0])) &&
  11061. "Expected cmp + select pairs for reduction");
  11062. Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
  11063. if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
  11064. if (auto *Sel = dyn_cast<SelectInst>(Op)) {
  11065. propagateIRFlags(Sel->getCondition(), ReductionOps[0], nullptr,
  11066. /*IncludeWrapFlags=*/false);
  11067. propagateIRFlags(Op, ReductionOps[1], nullptr,
  11068. /*IncludeWrapFlags=*/false);
  11069. return Op;
  11070. }
  11071. }
  11072. propagateIRFlags(Op, ReductionOps[0], nullptr, /*IncludeWrapFlags=*/false);
  11073. return Op;
  11074. }
  11075. static RecurKind getRdxKind(Value *V) {
  11076. auto *I = dyn_cast<Instruction>(V);
  11077. if (!I)
  11078. return RecurKind::None;
  11079. if (match(I, m_Add(m_Value(), m_Value())))
  11080. return RecurKind::Add;
  11081. if (match(I, m_Mul(m_Value(), m_Value())))
  11082. return RecurKind::Mul;
  11083. if (match(I, m_And(m_Value(), m_Value())) ||
  11084. match(I, m_LogicalAnd(m_Value(), m_Value())))
  11085. return RecurKind::And;
  11086. if (match(I, m_Or(m_Value(), m_Value())) ||
  11087. match(I, m_LogicalOr(m_Value(), m_Value())))
  11088. return RecurKind::Or;
  11089. if (match(I, m_Xor(m_Value(), m_Value())))
  11090. return RecurKind::Xor;
  11091. if (match(I, m_FAdd(m_Value(), m_Value())))
  11092. return RecurKind::FAdd;
  11093. if (match(I, m_FMul(m_Value(), m_Value())))
  11094. return RecurKind::FMul;
  11095. if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
  11096. return RecurKind::FMax;
  11097. if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
  11098. return RecurKind::FMin;
  11099. // This matches either cmp+select or intrinsics. SLP is expected to handle
  11100. // either form.
  11101. // TODO: If we are canonicalizing to intrinsics, we can remove several
  11102. // special-case paths that deal with selects.
  11103. if (match(I, m_SMax(m_Value(), m_Value())))
  11104. return RecurKind::SMax;
  11105. if (match(I, m_SMin(m_Value(), m_Value())))
  11106. return RecurKind::SMin;
  11107. if (match(I, m_UMax(m_Value(), m_Value())))
  11108. return RecurKind::UMax;
  11109. if (match(I, m_UMin(m_Value(), m_Value())))
  11110. return RecurKind::UMin;
  11111. if (auto *Select = dyn_cast<SelectInst>(I)) {
  11112. // Try harder: look for min/max pattern based on instructions producing
  11113. // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
  11114. // During the intermediate stages of SLP, it's very common to have
  11115. // pattern like this (since optimizeGatherSequence is run only once
  11116. // at the end):
  11117. // %1 = extractelement <2 x i32> %a, i32 0
  11118. // %2 = extractelement <2 x i32> %a, i32 1
  11119. // %cond = icmp sgt i32 %1, %2
  11120. // %3 = extractelement <2 x i32> %a, i32 0
  11121. // %4 = extractelement <2 x i32> %a, i32 1
  11122. // %select = select i1 %cond, i32 %3, i32 %4
  11123. CmpInst::Predicate Pred;
  11124. Instruction *L1;
  11125. Instruction *L2;
  11126. Value *LHS = Select->getTrueValue();
  11127. Value *RHS = Select->getFalseValue();
  11128. Value *Cond = Select->getCondition();
  11129. // TODO: Support inverse predicates.
  11130. if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
  11131. if (!isa<ExtractElementInst>(RHS) ||
  11132. !L2->isIdenticalTo(cast<Instruction>(RHS)))
  11133. return RecurKind::None;
  11134. } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
  11135. if (!isa<ExtractElementInst>(LHS) ||
  11136. !L1->isIdenticalTo(cast<Instruction>(LHS)))
  11137. return RecurKind::None;
  11138. } else {
  11139. if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
  11140. return RecurKind::None;
  11141. if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
  11142. !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
  11143. !L2->isIdenticalTo(cast<Instruction>(RHS)))
  11144. return RecurKind::None;
  11145. }
  11146. switch (Pred) {
  11147. default:
  11148. return RecurKind::None;
  11149. case CmpInst::ICMP_SGT:
  11150. case CmpInst::ICMP_SGE:
  11151. return RecurKind::SMax;
  11152. case CmpInst::ICMP_SLT:
  11153. case CmpInst::ICMP_SLE:
  11154. return RecurKind::SMin;
  11155. case CmpInst::ICMP_UGT:
  11156. case CmpInst::ICMP_UGE:
  11157. return RecurKind::UMax;
  11158. case CmpInst::ICMP_ULT:
  11159. case CmpInst::ICMP_ULE:
  11160. return RecurKind::UMin;
  11161. }
  11162. }
  11163. return RecurKind::None;
  11164. }
  11165. /// Get the index of the first operand.
  11166. static unsigned getFirstOperandIndex(Instruction *I) {
  11167. return isCmpSelMinMax(I) ? 1 : 0;
  11168. }
  11169. /// Total number of operands in the reduction operation.
  11170. static unsigned getNumberOfOperands(Instruction *I) {
  11171. return isCmpSelMinMax(I) ? 3 : 2;
  11172. }
  11173. /// Checks if the instruction is in basic block \p BB.
  11174. /// For a cmp+sel min/max reduction check that both ops are in \p BB.
  11175. static bool hasSameParent(Instruction *I, BasicBlock *BB) {
  11176. if (isCmpSelMinMax(I) || isBoolLogicOp(I)) {
  11177. auto *Sel = cast<SelectInst>(I);
  11178. auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
  11179. return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
  11180. }
  11181. return I->getParent() == BB;
  11182. }
  11183. /// Expected number of uses for reduction operations/reduced values.
  11184. static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
  11185. if (IsCmpSelMinMax) {
  11186. // SelectInst must be used twice while the condition op must have single
  11187. // use only.
  11188. if (auto *Sel = dyn_cast<SelectInst>(I))
  11189. return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
  11190. return I->hasNUses(2);
  11191. }
  11192. // Arithmetic reduction operation must be used once only.
  11193. return I->hasOneUse();
  11194. }
  11195. /// Initializes the list of reduction operations.
  11196. void initReductionOps(Instruction *I) {
  11197. if (isCmpSelMinMax(I))
  11198. ReductionOps.assign(2, ReductionOpsType());
  11199. else
  11200. ReductionOps.assign(1, ReductionOpsType());
  11201. }
  11202. /// Add all reduction operations for the reduction instruction \p I.
  11203. void addReductionOps(Instruction *I) {
  11204. if (isCmpSelMinMax(I)) {
  11205. ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
  11206. ReductionOps[1].emplace_back(I);
  11207. } else {
  11208. ReductionOps[0].emplace_back(I);
  11209. }
  11210. }
  11211. static Value *getLHS(RecurKind Kind, Instruction *I) {
  11212. if (Kind == RecurKind::None)
  11213. return nullptr;
  11214. return I->getOperand(getFirstOperandIndex(I));
  11215. }
  11216. static Value *getRHS(RecurKind Kind, Instruction *I) {
  11217. if (Kind == RecurKind::None)
  11218. return nullptr;
  11219. return I->getOperand(getFirstOperandIndex(I) + 1);
  11220. }
  11221. static bool isGoodForReduction(ArrayRef<Value *> Data) {
  11222. int Sz = Data.size();
  11223. auto *I = dyn_cast<Instruction>(Data.front());
  11224. return Sz > 1 || isConstant(Data.front()) ||
  11225. (I && !isa<LoadInst>(I) && isValidForAlternation(I->getOpcode()));
  11226. }
  11227. public:
  11228. HorizontalReduction() = default;
  11229. /// Try to find a reduction tree.
  11230. bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst,
  11231. ScalarEvolution &SE, const DataLayout &DL,
  11232. const TargetLibraryInfo &TLI) {
  11233. assert((!Phi || is_contained(Phi->operands(), Inst)) &&
  11234. "Phi needs to use the binary operator");
  11235. assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
  11236. isa<IntrinsicInst>(Inst)) &&
  11237. "Expected binop, select, or intrinsic for reduction matching");
  11238. RdxKind = getRdxKind(Inst);
  11239. // We could have a initial reductions that is not an add.
  11240. // r *= v1 + v2 + v3 + v4
  11241. // In such a case start looking for a tree rooted in the first '+'.
  11242. if (Phi) {
  11243. if (getLHS(RdxKind, Inst) == Phi) {
  11244. Phi = nullptr;
  11245. Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
  11246. if (!Inst)
  11247. return false;
  11248. RdxKind = getRdxKind(Inst);
  11249. } else if (getRHS(RdxKind, Inst) == Phi) {
  11250. Phi = nullptr;
  11251. Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
  11252. if (!Inst)
  11253. return false;
  11254. RdxKind = getRdxKind(Inst);
  11255. }
  11256. }
  11257. if (!isVectorizable(RdxKind, Inst))
  11258. return false;
  11259. // Analyze "regular" integer/FP types for reductions - no target-specific
  11260. // types or pointers.
  11261. Type *Ty = Inst->getType();
  11262. if (!isValidElementType(Ty) || Ty->isPointerTy())
  11263. return false;
  11264. // Though the ultimate reduction may have multiple uses, its condition must
  11265. // have only single use.
  11266. if (auto *Sel = dyn_cast<SelectInst>(Inst))
  11267. if (!Sel->getCondition()->hasOneUse())
  11268. return false;
  11269. ReductionRoot = Inst;
  11270. // Iterate through all the operands of the possible reduction tree and
  11271. // gather all the reduced values, sorting them by their value id.
  11272. BasicBlock *BB = Inst->getParent();
  11273. bool IsCmpSelMinMax = isCmpSelMinMax(Inst);
  11274. SmallVector<Instruction *> Worklist(1, Inst);
  11275. // Checks if the operands of the \p TreeN instruction are also reduction
  11276. // operations or should be treated as reduced values or an extra argument,
  11277. // which is not part of the reduction.
  11278. auto &&CheckOperands = [this, IsCmpSelMinMax,
  11279. BB](Instruction *TreeN,
  11280. SmallVectorImpl<Value *> &ExtraArgs,
  11281. SmallVectorImpl<Value *> &PossibleReducedVals,
  11282. SmallVectorImpl<Instruction *> &ReductionOps) {
  11283. for (int I = getFirstOperandIndex(TreeN),
  11284. End = getNumberOfOperands(TreeN);
  11285. I < End; ++I) {
  11286. Value *EdgeVal = getRdxOperand(TreeN, I);
  11287. ReducedValsToOps[EdgeVal].push_back(TreeN);
  11288. auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
  11289. // Edge has wrong parent - mark as an extra argument.
  11290. if (EdgeInst && !isVectorLikeInstWithConstOps(EdgeInst) &&
  11291. !hasSameParent(EdgeInst, BB)) {
  11292. ExtraArgs.push_back(EdgeVal);
  11293. continue;
  11294. }
  11295. // If the edge is not an instruction, or it is different from the main
  11296. // reduction opcode or has too many uses - possible reduced value.
  11297. if (!EdgeInst || getRdxKind(EdgeInst) != RdxKind ||
  11298. IsCmpSelMinMax != isCmpSelMinMax(EdgeInst) ||
  11299. !hasRequiredNumberOfUses(IsCmpSelMinMax, EdgeInst) ||
  11300. !isVectorizable(getRdxKind(EdgeInst), EdgeInst)) {
  11301. PossibleReducedVals.push_back(EdgeVal);
  11302. continue;
  11303. }
  11304. ReductionOps.push_back(EdgeInst);
  11305. }
  11306. };
  11307. // Try to regroup reduced values so that it gets more profitable to try to
  11308. // reduce them. Values are grouped by their value ids, instructions - by
  11309. // instruction op id and/or alternate op id, plus do extra analysis for
  11310. // loads (grouping them by the distabce between pointers) and cmp
  11311. // instructions (grouping them by the predicate).
  11312. MapVector<size_t, MapVector<size_t, MapVector<Value *, unsigned>>>
  11313. PossibleReducedVals;
  11314. initReductionOps(Inst);
  11315. DenseMap<Value *, SmallVector<LoadInst *>> LoadsMap;
  11316. SmallSet<size_t, 2> LoadKeyUsed;
  11317. SmallPtrSet<Value *, 4> DoNotReverseVals;
  11318. while (!Worklist.empty()) {
  11319. Instruction *TreeN = Worklist.pop_back_val();
  11320. SmallVector<Value *> Args;
  11321. SmallVector<Value *> PossibleRedVals;
  11322. SmallVector<Instruction *> PossibleReductionOps;
  11323. CheckOperands(TreeN, Args, PossibleRedVals, PossibleReductionOps);
  11324. // If too many extra args - mark the instruction itself as a reduction
  11325. // value, not a reduction operation.
  11326. if (Args.size() < 2) {
  11327. addReductionOps(TreeN);
  11328. // Add extra args.
  11329. if (!Args.empty()) {
  11330. assert(Args.size() == 1 && "Expected only single argument.");
  11331. ExtraArgs[TreeN] = Args.front();
  11332. }
  11333. // Add reduction values. The values are sorted for better vectorization
  11334. // results.
  11335. for (Value *V : PossibleRedVals) {
  11336. size_t Key, Idx;
  11337. std::tie(Key, Idx) = generateKeySubkey(
  11338. V, &TLI,
  11339. [&](size_t Key, LoadInst *LI) {
  11340. Value *Ptr = getUnderlyingObject(LI->getPointerOperand());
  11341. if (LoadKeyUsed.contains(Key)) {
  11342. auto LIt = LoadsMap.find(Ptr);
  11343. if (LIt != LoadsMap.end()) {
  11344. for (LoadInst *RLI: LIt->second) {
  11345. if (getPointersDiff(
  11346. RLI->getType(), RLI->getPointerOperand(),
  11347. LI->getType(), LI->getPointerOperand(), DL, SE,
  11348. /*StrictCheck=*/true))
  11349. return hash_value(RLI->getPointerOperand());
  11350. }
  11351. for (LoadInst *RLI : LIt->second) {
  11352. if (arePointersCompatible(RLI->getPointerOperand(),
  11353. LI->getPointerOperand(), TLI)) {
  11354. hash_code SubKey = hash_value(RLI->getPointerOperand());
  11355. DoNotReverseVals.insert(RLI);
  11356. return SubKey;
  11357. }
  11358. }
  11359. if (LIt->second.size() > 2) {
  11360. hash_code SubKey =
  11361. hash_value(LIt->second.back()->getPointerOperand());
  11362. DoNotReverseVals.insert(LIt->second.back());
  11363. return SubKey;
  11364. }
  11365. }
  11366. }
  11367. LoadKeyUsed.insert(Key);
  11368. LoadsMap.try_emplace(Ptr).first->second.push_back(LI);
  11369. return hash_value(LI->getPointerOperand());
  11370. },
  11371. /*AllowAlternate=*/false);
  11372. ++PossibleReducedVals[Key][Idx]
  11373. .insert(std::make_pair(V, 0))
  11374. .first->second;
  11375. }
  11376. Worklist.append(PossibleReductionOps.rbegin(),
  11377. PossibleReductionOps.rend());
  11378. } else {
  11379. size_t Key, Idx;
  11380. std::tie(Key, Idx) = generateKeySubkey(
  11381. TreeN, &TLI,
  11382. [&](size_t Key, LoadInst *LI) {
  11383. Value *Ptr = getUnderlyingObject(LI->getPointerOperand());
  11384. if (LoadKeyUsed.contains(Key)) {
  11385. auto LIt = LoadsMap.find(Ptr);
  11386. if (LIt != LoadsMap.end()) {
  11387. for (LoadInst *RLI: LIt->second) {
  11388. if (getPointersDiff(RLI->getType(),
  11389. RLI->getPointerOperand(), LI->getType(),
  11390. LI->getPointerOperand(), DL, SE,
  11391. /*StrictCheck=*/true))
  11392. return hash_value(RLI->getPointerOperand());
  11393. }
  11394. for (LoadInst *RLI : LIt->second) {
  11395. if (arePointersCompatible(RLI->getPointerOperand(),
  11396. LI->getPointerOperand(), TLI)) {
  11397. hash_code SubKey = hash_value(RLI->getPointerOperand());
  11398. DoNotReverseVals.insert(RLI);
  11399. return SubKey;
  11400. }
  11401. }
  11402. if (LIt->second.size() > 2) {
  11403. hash_code SubKey = hash_value(LIt->second.back()->getPointerOperand());
  11404. DoNotReverseVals.insert(LIt->second.back());
  11405. return SubKey;
  11406. }
  11407. }
  11408. }
  11409. LoadKeyUsed.insert(Key);
  11410. LoadsMap.try_emplace(Ptr).first->second.push_back(LI);
  11411. return hash_value(LI->getPointerOperand());
  11412. },
  11413. /*AllowAlternate=*/false);
  11414. ++PossibleReducedVals[Key][Idx]
  11415. .insert(std::make_pair(TreeN, 0))
  11416. .first->second;
  11417. }
  11418. }
  11419. auto PossibleReducedValsVect = PossibleReducedVals.takeVector();
  11420. // Sort values by the total number of values kinds to start the reduction
  11421. // from the longest possible reduced values sequences.
  11422. for (auto &PossibleReducedVals : PossibleReducedValsVect) {
  11423. auto PossibleRedVals = PossibleReducedVals.second.takeVector();
  11424. SmallVector<SmallVector<Value *>> PossibleRedValsVect;
  11425. for (auto It = PossibleRedVals.begin(), E = PossibleRedVals.end();
  11426. It != E; ++It) {
  11427. PossibleRedValsVect.emplace_back();
  11428. auto RedValsVect = It->second.takeVector();
  11429. stable_sort(RedValsVect, llvm::less_second());
  11430. for (const std::pair<Value *, unsigned> &Data : RedValsVect)
  11431. PossibleRedValsVect.back().append(Data.second, Data.first);
  11432. }
  11433. stable_sort(PossibleRedValsVect, [](const auto &P1, const auto &P2) {
  11434. return P1.size() > P2.size();
  11435. });
  11436. int NewIdx = -1;
  11437. for (ArrayRef<Value *> Data : PossibleRedValsVect) {
  11438. if (isGoodForReduction(Data) ||
  11439. (isa<LoadInst>(Data.front()) && NewIdx >= 0 &&
  11440. isa<LoadInst>(ReducedVals[NewIdx].front()) &&
  11441. getUnderlyingObject(
  11442. cast<LoadInst>(Data.front())->getPointerOperand()) ==
  11443. getUnderlyingObject(cast<LoadInst>(ReducedVals[NewIdx].front())
  11444. ->getPointerOperand()))) {
  11445. if (NewIdx < 0) {
  11446. NewIdx = ReducedVals.size();
  11447. ReducedVals.emplace_back();
  11448. }
  11449. if (DoNotReverseVals.contains(Data.front()))
  11450. ReducedVals[NewIdx].append(Data.begin(), Data.end());
  11451. else
  11452. ReducedVals[NewIdx].append(Data.rbegin(), Data.rend());
  11453. } else {
  11454. ReducedVals.emplace_back().append(Data.rbegin(), Data.rend());
  11455. }
  11456. }
  11457. }
  11458. // Sort the reduced values by number of same/alternate opcode and/or pointer
  11459. // operand.
  11460. stable_sort(ReducedVals, [](ArrayRef<Value *> P1, ArrayRef<Value *> P2) {
  11461. return P1.size() > P2.size();
  11462. });
  11463. return true;
  11464. }
  11465. /// Attempt to vectorize the tree found by matchAssociativeReduction.
  11466. Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI,
  11467. const TargetLibraryInfo &TLI) {
  11468. constexpr int ReductionLimit = 4;
  11469. constexpr unsigned RegMaxNumber = 4;
  11470. constexpr unsigned RedValsMaxNumber = 128;
  11471. // If there are a sufficient number of reduction values, reduce
  11472. // to a nearby power-of-2. We can safely generate oversized
  11473. // vectors and rely on the backend to split them to legal sizes.
  11474. size_t NumReducedVals =
  11475. std::accumulate(ReducedVals.begin(), ReducedVals.end(), 0,
  11476. [](size_t Num, ArrayRef<Value *> Vals) {
  11477. if (!isGoodForReduction(Vals))
  11478. return Num;
  11479. return Num + Vals.size();
  11480. });
  11481. if (NumReducedVals < ReductionLimit) {
  11482. for (ReductionOpsType &RdxOps : ReductionOps)
  11483. for (Value *RdxOp : RdxOps)
  11484. V.analyzedReductionRoot(cast<Instruction>(RdxOp));
  11485. return nullptr;
  11486. }
  11487. IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
  11488. // Track the reduced values in case if they are replaced by extractelement
  11489. // because of the vectorization.
  11490. DenseMap<Value *, WeakTrackingVH> TrackedVals(
  11491. ReducedVals.size() * ReducedVals.front().size() + ExtraArgs.size());
  11492. BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
  11493. ExternallyUsedValues.reserve(ExtraArgs.size() + 1);
  11494. // The same extra argument may be used several times, so log each attempt
  11495. // to use it.
  11496. for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
  11497. assert(Pair.first && "DebugLoc must be set.");
  11498. ExternallyUsedValues[Pair.second].push_back(Pair.first);
  11499. TrackedVals.try_emplace(Pair.second, Pair.second);
  11500. }
  11501. // The compare instruction of a min/max is the insertion point for new
  11502. // instructions and may be replaced with a new compare instruction.
  11503. auto &&GetCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
  11504. assert(isa<SelectInst>(RdxRootInst) &&
  11505. "Expected min/max reduction to have select root instruction");
  11506. Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
  11507. assert(isa<Instruction>(ScalarCond) &&
  11508. "Expected min/max reduction to have compare condition");
  11509. return cast<Instruction>(ScalarCond);
  11510. };
  11511. // The reduction root is used as the insertion point for new instructions,
  11512. // so set it as externally used to prevent it from being deleted.
  11513. ExternallyUsedValues[ReductionRoot];
  11514. SmallDenseSet<Value *> IgnoreList(ReductionOps.size() *
  11515. ReductionOps.front().size());
  11516. for (ReductionOpsType &RdxOps : ReductionOps)
  11517. for (Value *RdxOp : RdxOps) {
  11518. if (!RdxOp)
  11519. continue;
  11520. IgnoreList.insert(RdxOp);
  11521. }
  11522. bool IsCmpSelMinMax = isCmpSelMinMax(cast<Instruction>(ReductionRoot));
  11523. // Need to track reduced vals, they may be changed during vectorization of
  11524. // subvectors.
  11525. for (ArrayRef<Value *> Candidates : ReducedVals)
  11526. for (Value *V : Candidates)
  11527. TrackedVals.try_emplace(V, V);
  11528. DenseMap<Value *, unsigned> VectorizedVals(ReducedVals.size());
  11529. // List of the values that were reduced in other trees as part of gather
  11530. // nodes and thus requiring extract if fully vectorized in other trees.
  11531. SmallPtrSet<Value *, 4> RequiredExtract;
  11532. Value *VectorizedTree = nullptr;
  11533. bool CheckForReusedReductionOps = false;
  11534. // Try to vectorize elements based on their type.
  11535. for (unsigned I = 0, E = ReducedVals.size(); I < E; ++I) {
  11536. ArrayRef<Value *> OrigReducedVals = ReducedVals[I];
  11537. InstructionsState S = getSameOpcode(OrigReducedVals, TLI);
  11538. SmallVector<Value *> Candidates;
  11539. Candidates.reserve(2 * OrigReducedVals.size());
  11540. DenseMap<Value *, Value *> TrackedToOrig(2 * OrigReducedVals.size());
  11541. for (unsigned Cnt = 0, Sz = OrigReducedVals.size(); Cnt < Sz; ++Cnt) {
  11542. Value *RdxVal = TrackedVals.find(OrigReducedVals[Cnt])->second;
  11543. // Check if the reduction value was not overriden by the extractelement
  11544. // instruction because of the vectorization and exclude it, if it is not
  11545. // compatible with other values.
  11546. if (auto *Inst = dyn_cast<Instruction>(RdxVal))
  11547. if (isVectorLikeInstWithConstOps(Inst) &&
  11548. (!S.getOpcode() || !S.isOpcodeOrAlt(Inst)))
  11549. continue;
  11550. Candidates.push_back(RdxVal);
  11551. TrackedToOrig.try_emplace(RdxVal, OrigReducedVals[Cnt]);
  11552. }
  11553. bool ShuffledExtracts = false;
  11554. // Try to handle shuffled extractelements.
  11555. if (S.getOpcode() == Instruction::ExtractElement && !S.isAltShuffle() &&
  11556. I + 1 < E) {
  11557. InstructionsState NextS = getSameOpcode(ReducedVals[I + 1], TLI);
  11558. if (NextS.getOpcode() == Instruction::ExtractElement &&
  11559. !NextS.isAltShuffle()) {
  11560. SmallVector<Value *> CommonCandidates(Candidates);
  11561. for (Value *RV : ReducedVals[I + 1]) {
  11562. Value *RdxVal = TrackedVals.find(RV)->second;
  11563. // Check if the reduction value was not overriden by the
  11564. // extractelement instruction because of the vectorization and
  11565. // exclude it, if it is not compatible with other values.
  11566. if (auto *Inst = dyn_cast<Instruction>(RdxVal))
  11567. if (!NextS.getOpcode() || !NextS.isOpcodeOrAlt(Inst))
  11568. continue;
  11569. CommonCandidates.push_back(RdxVal);
  11570. TrackedToOrig.try_emplace(RdxVal, RV);
  11571. }
  11572. SmallVector<int> Mask;
  11573. if (isFixedVectorShuffle(CommonCandidates, Mask)) {
  11574. ++I;
  11575. Candidates.swap(CommonCandidates);
  11576. ShuffledExtracts = true;
  11577. }
  11578. }
  11579. }
  11580. unsigned NumReducedVals = Candidates.size();
  11581. if (NumReducedVals < ReductionLimit)
  11582. continue;
  11583. unsigned MaxVecRegSize = V.getMaxVecRegSize();
  11584. unsigned EltSize = V.getVectorElementSize(Candidates[0]);
  11585. unsigned MaxElts = RegMaxNumber * PowerOf2Floor(MaxVecRegSize / EltSize);
  11586. unsigned ReduxWidth = std::min<unsigned>(
  11587. PowerOf2Floor(NumReducedVals), std::max(RedValsMaxNumber, MaxElts));
  11588. unsigned Start = 0;
  11589. unsigned Pos = Start;
  11590. // Restarts vectorization attempt with lower vector factor.
  11591. unsigned PrevReduxWidth = ReduxWidth;
  11592. bool CheckForReusedReductionOpsLocal = false;
  11593. auto &&AdjustReducedVals = [&Pos, &Start, &ReduxWidth, NumReducedVals,
  11594. &CheckForReusedReductionOpsLocal,
  11595. &PrevReduxWidth, &V,
  11596. &IgnoreList](bool IgnoreVL = false) {
  11597. bool IsAnyRedOpGathered = !IgnoreVL && V.isAnyGathered(IgnoreList);
  11598. if (!CheckForReusedReductionOpsLocal && PrevReduxWidth == ReduxWidth) {
  11599. // Check if any of the reduction ops are gathered. If so, worth
  11600. // trying again with less number of reduction ops.
  11601. CheckForReusedReductionOpsLocal |= IsAnyRedOpGathered;
  11602. }
  11603. ++Pos;
  11604. if (Pos < NumReducedVals - ReduxWidth + 1)
  11605. return IsAnyRedOpGathered;
  11606. Pos = Start;
  11607. ReduxWidth /= 2;
  11608. return IsAnyRedOpGathered;
  11609. };
  11610. while (Pos < NumReducedVals - ReduxWidth + 1 &&
  11611. ReduxWidth >= ReductionLimit) {
  11612. // Dependency in tree of the reduction ops - drop this attempt, try
  11613. // later.
  11614. if (CheckForReusedReductionOpsLocal && PrevReduxWidth != ReduxWidth &&
  11615. Start == 0) {
  11616. CheckForReusedReductionOps = true;
  11617. break;
  11618. }
  11619. PrevReduxWidth = ReduxWidth;
  11620. ArrayRef<Value *> VL(std::next(Candidates.begin(), Pos), ReduxWidth);
  11621. // Beeing analyzed already - skip.
  11622. if (V.areAnalyzedReductionVals(VL)) {
  11623. (void)AdjustReducedVals(/*IgnoreVL=*/true);
  11624. continue;
  11625. }
  11626. // Early exit if any of the reduction values were deleted during
  11627. // previous vectorization attempts.
  11628. if (any_of(VL, [&V](Value *RedVal) {
  11629. auto *RedValI = dyn_cast<Instruction>(RedVal);
  11630. if (!RedValI)
  11631. return false;
  11632. return V.isDeleted(RedValI);
  11633. }))
  11634. break;
  11635. V.buildTree(VL, IgnoreList);
  11636. if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true)) {
  11637. if (!AdjustReducedVals())
  11638. V.analyzedReductionVals(VL);
  11639. continue;
  11640. }
  11641. if (V.isLoadCombineReductionCandidate(RdxKind)) {
  11642. if (!AdjustReducedVals())
  11643. V.analyzedReductionVals(VL);
  11644. continue;
  11645. }
  11646. V.reorderTopToBottom();
  11647. // No need to reorder the root node at all.
  11648. V.reorderBottomToTop(/*IgnoreReorder=*/true);
  11649. // Keep extracted other reduction values, if they are used in the
  11650. // vectorization trees.
  11651. BoUpSLP::ExtraValueToDebugLocsMap LocalExternallyUsedValues(
  11652. ExternallyUsedValues);
  11653. for (unsigned Cnt = 0, Sz = ReducedVals.size(); Cnt < Sz; ++Cnt) {
  11654. if (Cnt == I || (ShuffledExtracts && Cnt == I - 1))
  11655. continue;
  11656. for_each(ReducedVals[Cnt],
  11657. [&LocalExternallyUsedValues, &TrackedVals](Value *V) {
  11658. if (isa<Instruction>(V))
  11659. LocalExternallyUsedValues[TrackedVals[V]];
  11660. });
  11661. }
  11662. // Number of uses of the candidates in the vector of values.
  11663. SmallDenseMap<Value *, unsigned> NumUses(Candidates.size());
  11664. for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) {
  11665. Value *V = Candidates[Cnt];
  11666. ++NumUses.try_emplace(V, 0).first->getSecond();
  11667. }
  11668. for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) {
  11669. Value *V = Candidates[Cnt];
  11670. ++NumUses.try_emplace(V, 0).first->getSecond();
  11671. }
  11672. SmallPtrSet<Value *, 4> VLScalars(VL.begin(), VL.end());
  11673. // Gather externally used values.
  11674. SmallPtrSet<Value *, 4> Visited;
  11675. for (unsigned Cnt = 0; Cnt < Pos; ++Cnt) {
  11676. Value *RdxVal = Candidates[Cnt];
  11677. if (!Visited.insert(RdxVal).second)
  11678. continue;
  11679. // Check if the scalar was vectorized as part of the vectorization
  11680. // tree but not the top node.
  11681. if (!VLScalars.contains(RdxVal) && V.isVectorized(RdxVal)) {
  11682. LocalExternallyUsedValues[RdxVal];
  11683. continue;
  11684. }
  11685. unsigned NumOps = VectorizedVals.lookup(RdxVal) + NumUses[RdxVal];
  11686. if (NumOps != ReducedValsToOps.find(RdxVal)->second.size())
  11687. LocalExternallyUsedValues[RdxVal];
  11688. }
  11689. for (unsigned Cnt = Pos + ReduxWidth; Cnt < NumReducedVals; ++Cnt) {
  11690. Value *RdxVal = Candidates[Cnt];
  11691. if (!Visited.insert(RdxVal).second)
  11692. continue;
  11693. // Check if the scalar was vectorized as part of the vectorization
  11694. // tree but not the top node.
  11695. if (!VLScalars.contains(RdxVal) && V.isVectorized(RdxVal)) {
  11696. LocalExternallyUsedValues[RdxVal];
  11697. continue;
  11698. }
  11699. unsigned NumOps = VectorizedVals.lookup(RdxVal) + NumUses[RdxVal];
  11700. if (NumOps != ReducedValsToOps.find(RdxVal)->second.size())
  11701. LocalExternallyUsedValues[RdxVal];
  11702. }
  11703. for (Value *RdxVal : VL)
  11704. if (RequiredExtract.contains(RdxVal))
  11705. LocalExternallyUsedValues[RdxVal];
  11706. V.buildExternalUses(LocalExternallyUsedValues);
  11707. V.computeMinimumValueSizes();
  11708. // Intersect the fast-math-flags from all reduction operations.
  11709. FastMathFlags RdxFMF;
  11710. RdxFMF.set();
  11711. for (Value *U : IgnoreList)
  11712. if (auto *FPMO = dyn_cast<FPMathOperator>(U))
  11713. RdxFMF &= FPMO->getFastMathFlags();
  11714. // Estimate cost.
  11715. InstructionCost TreeCost = V.getTreeCost(VL);
  11716. InstructionCost ReductionCost =
  11717. getReductionCost(TTI, VL, ReduxWidth, RdxFMF);
  11718. if (V.isVectorizedFirstNode() && isa<LoadInst>(VL.front())) {
  11719. Instruction *MainOp = V.getFirstNodeMainOp();
  11720. for (Value *V : VL) {
  11721. auto *VI = dyn_cast<LoadInst>(V);
  11722. // Add the costs of scalar GEP pointers, to be removed from the
  11723. // code.
  11724. if (!VI || VI == MainOp)
  11725. continue;
  11726. auto *Ptr = dyn_cast<GetElementPtrInst>(VI->getPointerOperand());
  11727. if (!Ptr || !Ptr->hasOneUse() || Ptr->hasAllConstantIndices())
  11728. continue;
  11729. TreeCost -= TTI->getArithmeticInstrCost(
  11730. Instruction::Add, Ptr->getType(), TTI::TCK_RecipThroughput);
  11731. }
  11732. }
  11733. InstructionCost Cost = TreeCost + ReductionCost;
  11734. LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for reduction\n");
  11735. if (!Cost.isValid())
  11736. return nullptr;
  11737. if (Cost >= -SLPCostThreshold) {
  11738. V.getORE()->emit([&]() {
  11739. return OptimizationRemarkMissed(
  11740. SV_NAME, "HorSLPNotBeneficial",
  11741. ReducedValsToOps.find(VL[0])->second.front())
  11742. << "Vectorizing horizontal reduction is possible "
  11743. << "but not beneficial with cost " << ore::NV("Cost", Cost)
  11744. << " and threshold "
  11745. << ore::NV("Threshold", -SLPCostThreshold);
  11746. });
  11747. if (!AdjustReducedVals())
  11748. V.analyzedReductionVals(VL);
  11749. continue;
  11750. }
  11751. LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
  11752. << Cost << ". (HorRdx)\n");
  11753. V.getORE()->emit([&]() {
  11754. return OptimizationRemark(
  11755. SV_NAME, "VectorizedHorizontalReduction",
  11756. ReducedValsToOps.find(VL[0])->second.front())
  11757. << "Vectorized horizontal reduction with cost "
  11758. << ore::NV("Cost", Cost) << " and with tree size "
  11759. << ore::NV("TreeSize", V.getTreeSize());
  11760. });
  11761. Builder.setFastMathFlags(RdxFMF);
  11762. // Emit a reduction. If the root is a select (min/max idiom), the insert
  11763. // point is the compare condition of that select.
  11764. Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
  11765. Instruction *InsertPt = RdxRootInst;
  11766. if (IsCmpSelMinMax)
  11767. InsertPt = GetCmpForMinMaxReduction(RdxRootInst);
  11768. // Vectorize a tree.
  11769. Value *VectorizedRoot =
  11770. V.vectorizeTree(LocalExternallyUsedValues, InsertPt);
  11771. Builder.SetInsertPoint(InsertPt);
  11772. // To prevent poison from leaking across what used to be sequential,
  11773. // safe, scalar boolean logic operations, the reduction operand must be
  11774. // frozen.
  11775. if (isBoolLogicOp(RdxRootInst))
  11776. VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
  11777. Value *ReducedSubTree =
  11778. emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
  11779. if (!VectorizedTree) {
  11780. // Initialize the final value in the reduction.
  11781. VectorizedTree = ReducedSubTree;
  11782. } else {
  11783. // Update the final value in the reduction.
  11784. Builder.SetCurrentDebugLocation(
  11785. cast<Instruction>(ReductionOps.front().front())->getDebugLoc());
  11786. VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
  11787. ReducedSubTree, "op.rdx", ReductionOps);
  11788. }
  11789. // Count vectorized reduced values to exclude them from final reduction.
  11790. for (Value *RdxVal : VL) {
  11791. ++VectorizedVals.try_emplace(TrackedToOrig.find(RdxVal)->second, 0)
  11792. .first->getSecond();
  11793. if (!V.isVectorized(RdxVal))
  11794. RequiredExtract.insert(RdxVal);
  11795. }
  11796. Pos += ReduxWidth;
  11797. Start = Pos;
  11798. ReduxWidth = PowerOf2Floor(NumReducedVals - Pos);
  11799. }
  11800. }
  11801. if (VectorizedTree) {
  11802. // Reorder operands of bool logical op in the natural order to avoid
  11803. // possible problem with poison propagation. If not possible to reorder
  11804. // (both operands are originally RHS), emit an extra freeze instruction
  11805. // for the LHS operand.
  11806. //I.e., if we have original code like this:
  11807. // RedOp1 = select i1 ?, i1 LHS, i1 false
  11808. // RedOp2 = select i1 RHS, i1 ?, i1 false
  11809. // Then, we swap LHS/RHS to create a new op that matches the poison
  11810. // semantics of the original code.
  11811. // If we have original code like this and both values could be poison:
  11812. // RedOp1 = select i1 ?, i1 LHS, i1 false
  11813. // RedOp2 = select i1 ?, i1 RHS, i1 false
  11814. // Then, we must freeze LHS in the new op.
  11815. auto &&FixBoolLogicalOps =
  11816. [&Builder, VectorizedTree](Value *&LHS, Value *&RHS,
  11817. Instruction *RedOp1, Instruction *RedOp2) {
  11818. if (!isBoolLogicOp(RedOp1))
  11819. return;
  11820. if (LHS == VectorizedTree || getRdxOperand(RedOp1, 0) == LHS ||
  11821. isGuaranteedNotToBePoison(LHS))
  11822. return;
  11823. if (!isBoolLogicOp(RedOp2))
  11824. return;
  11825. if (RHS == VectorizedTree || getRdxOperand(RedOp2, 0) == RHS ||
  11826. isGuaranteedNotToBePoison(RHS)) {
  11827. std::swap(LHS, RHS);
  11828. return;
  11829. }
  11830. LHS = Builder.CreateFreeze(LHS);
  11831. };
  11832. // Finish the reduction.
  11833. // Need to add extra arguments and not vectorized possible reduction
  11834. // values.
  11835. // Try to avoid dependencies between the scalar remainders after
  11836. // reductions.
  11837. auto &&FinalGen =
  11838. [this, &Builder, &TrackedVals, &FixBoolLogicalOps](
  11839. ArrayRef<std::pair<Instruction *, Value *>> InstVals) {
  11840. unsigned Sz = InstVals.size();
  11841. SmallVector<std::pair<Instruction *, Value *>> ExtraReds(Sz / 2 +
  11842. Sz % 2);
  11843. for (unsigned I = 0, E = (Sz / 2) * 2; I < E; I += 2) {
  11844. Instruction *RedOp = InstVals[I + 1].first;
  11845. Builder.SetCurrentDebugLocation(RedOp->getDebugLoc());
  11846. Value *RdxVal1 = InstVals[I].second;
  11847. Value *StableRdxVal1 = RdxVal1;
  11848. auto It1 = TrackedVals.find(RdxVal1);
  11849. if (It1 != TrackedVals.end())
  11850. StableRdxVal1 = It1->second;
  11851. Value *RdxVal2 = InstVals[I + 1].second;
  11852. Value *StableRdxVal2 = RdxVal2;
  11853. auto It2 = TrackedVals.find(RdxVal2);
  11854. if (It2 != TrackedVals.end())
  11855. StableRdxVal2 = It2->second;
  11856. // To prevent poison from leaking across what used to be
  11857. // sequential, safe, scalar boolean logic operations, the
  11858. // reduction operand must be frozen.
  11859. FixBoolLogicalOps(StableRdxVal1, StableRdxVal2, InstVals[I].first,
  11860. RedOp);
  11861. Value *ExtraRed = createOp(Builder, RdxKind, StableRdxVal1,
  11862. StableRdxVal2, "op.rdx", ReductionOps);
  11863. ExtraReds[I / 2] = std::make_pair(InstVals[I].first, ExtraRed);
  11864. }
  11865. if (Sz % 2 == 1)
  11866. ExtraReds[Sz / 2] = InstVals.back();
  11867. return ExtraReds;
  11868. };
  11869. SmallVector<std::pair<Instruction *, Value *>> ExtraReductions;
  11870. ExtraReductions.emplace_back(cast<Instruction>(ReductionRoot),
  11871. VectorizedTree);
  11872. SmallPtrSet<Value *, 8> Visited;
  11873. for (ArrayRef<Value *> Candidates : ReducedVals) {
  11874. for (Value *RdxVal : Candidates) {
  11875. if (!Visited.insert(RdxVal).second)
  11876. continue;
  11877. unsigned NumOps = VectorizedVals.lookup(RdxVal);
  11878. for (Instruction *RedOp :
  11879. ArrayRef(ReducedValsToOps.find(RdxVal)->second)
  11880. .drop_back(NumOps))
  11881. ExtraReductions.emplace_back(RedOp, RdxVal);
  11882. }
  11883. }
  11884. for (auto &Pair : ExternallyUsedValues) {
  11885. // Add each externally used value to the final reduction.
  11886. for (auto *I : Pair.second)
  11887. ExtraReductions.emplace_back(I, Pair.first);
  11888. }
  11889. // Iterate through all not-vectorized reduction values/extra arguments.
  11890. while (ExtraReductions.size() > 1) {
  11891. VectorizedTree = ExtraReductions.front().second;
  11892. SmallVector<std::pair<Instruction *, Value *>> NewReds =
  11893. FinalGen(ExtraReductions);
  11894. ExtraReductions.swap(NewReds);
  11895. }
  11896. VectorizedTree = ExtraReductions.front().second;
  11897. ReductionRoot->replaceAllUsesWith(VectorizedTree);
  11898. // The original scalar reduction is expected to have no remaining
  11899. // uses outside the reduction tree itself. Assert that we got this
  11900. // correct, replace internal uses with undef, and mark for eventual
  11901. // deletion.
  11902. #ifndef NDEBUG
  11903. SmallSet<Value *, 4> IgnoreSet;
  11904. for (ArrayRef<Value *> RdxOps : ReductionOps)
  11905. IgnoreSet.insert(RdxOps.begin(), RdxOps.end());
  11906. #endif
  11907. for (ArrayRef<Value *> RdxOps : ReductionOps) {
  11908. for (Value *Ignore : RdxOps) {
  11909. if (!Ignore)
  11910. continue;
  11911. #ifndef NDEBUG
  11912. for (auto *U : Ignore->users()) {
  11913. assert(IgnoreSet.count(U) &&
  11914. "All users must be either in the reduction ops list.");
  11915. }
  11916. #endif
  11917. if (!Ignore->use_empty()) {
  11918. Value *Undef = UndefValue::get(Ignore->getType());
  11919. Ignore->replaceAllUsesWith(Undef);
  11920. }
  11921. V.eraseInstruction(cast<Instruction>(Ignore));
  11922. }
  11923. }
  11924. } else if (!CheckForReusedReductionOps) {
  11925. for (ReductionOpsType &RdxOps : ReductionOps)
  11926. for (Value *RdxOp : RdxOps)
  11927. V.analyzedReductionRoot(cast<Instruction>(RdxOp));
  11928. }
  11929. return VectorizedTree;
  11930. }
  11931. private:
  11932. /// Calculate the cost of a reduction.
  11933. InstructionCost getReductionCost(TargetTransformInfo *TTI,
  11934. ArrayRef<Value *> ReducedVals,
  11935. unsigned ReduxWidth, FastMathFlags FMF) {
  11936. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  11937. Value *FirstReducedVal = ReducedVals.front();
  11938. Type *ScalarTy = FirstReducedVal->getType();
  11939. FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
  11940. InstructionCost VectorCost = 0, ScalarCost;
  11941. // If all of the reduced values are constant, the vector cost is 0, since
  11942. // the reduction value can be calculated at the compile time.
  11943. bool AllConsts = all_of(ReducedVals, isConstant);
  11944. switch (RdxKind) {
  11945. case RecurKind::Add:
  11946. case RecurKind::Mul:
  11947. case RecurKind::Or:
  11948. case RecurKind::And:
  11949. case RecurKind::Xor:
  11950. case RecurKind::FAdd:
  11951. case RecurKind::FMul: {
  11952. unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
  11953. if (!AllConsts)
  11954. VectorCost =
  11955. TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
  11956. ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
  11957. break;
  11958. }
  11959. case RecurKind::FMax:
  11960. case RecurKind::FMin: {
  11961. auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
  11962. if (!AllConsts) {
  11963. auto *VecCondTy =
  11964. cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
  11965. VectorCost =
  11966. TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
  11967. /*IsUnsigned=*/false, CostKind);
  11968. }
  11969. CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
  11970. ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
  11971. SclCondTy, RdxPred, CostKind) +
  11972. TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
  11973. SclCondTy, RdxPred, CostKind);
  11974. break;
  11975. }
  11976. case RecurKind::SMax:
  11977. case RecurKind::SMin:
  11978. case RecurKind::UMax:
  11979. case RecurKind::UMin: {
  11980. auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
  11981. if (!AllConsts) {
  11982. auto *VecCondTy =
  11983. cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
  11984. bool IsUnsigned =
  11985. RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
  11986. VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
  11987. IsUnsigned, CostKind);
  11988. }
  11989. CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
  11990. ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
  11991. SclCondTy, RdxPred, CostKind) +
  11992. TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
  11993. SclCondTy, RdxPred, CostKind);
  11994. break;
  11995. }
  11996. default:
  11997. llvm_unreachable("Expected arithmetic or min/max reduction operation");
  11998. }
  11999. // Scalar cost is repeated for N-1 elements.
  12000. ScalarCost *= (ReduxWidth - 1);
  12001. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
  12002. << " for reduction that starts with " << *FirstReducedVal
  12003. << " (It is a splitting reduction)\n");
  12004. return VectorCost - ScalarCost;
  12005. }
  12006. /// Emit a horizontal reduction of the vectorized value.
  12007. Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
  12008. unsigned ReduxWidth, const TargetTransformInfo *TTI) {
  12009. assert(VectorizedValue && "Need to have a vectorized tree node");
  12010. assert(isPowerOf2_32(ReduxWidth) &&
  12011. "We only handle power-of-two reductions for now");
  12012. assert(RdxKind != RecurKind::FMulAdd &&
  12013. "A call to the llvm.fmuladd intrinsic is not handled yet");
  12014. ++NumVectorInstructions;
  12015. return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
  12016. }
  12017. };
  12018. } // end anonymous namespace
  12019. static std::optional<unsigned> getAggregateSize(Instruction *InsertInst) {
  12020. if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
  12021. return cast<FixedVectorType>(IE->getType())->getNumElements();
  12022. unsigned AggregateSize = 1;
  12023. auto *IV = cast<InsertValueInst>(InsertInst);
  12024. Type *CurrentType = IV->getType();
  12025. do {
  12026. if (auto *ST = dyn_cast<StructType>(CurrentType)) {
  12027. for (auto *Elt : ST->elements())
  12028. if (Elt != ST->getElementType(0)) // check homogeneity
  12029. return std::nullopt;
  12030. AggregateSize *= ST->getNumElements();
  12031. CurrentType = ST->getElementType(0);
  12032. } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
  12033. AggregateSize *= AT->getNumElements();
  12034. CurrentType = AT->getElementType();
  12035. } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
  12036. AggregateSize *= VT->getNumElements();
  12037. return AggregateSize;
  12038. } else if (CurrentType->isSingleValueType()) {
  12039. return AggregateSize;
  12040. } else {
  12041. return std::nullopt;
  12042. }
  12043. } while (true);
  12044. }
  12045. static void findBuildAggregate_rec(Instruction *LastInsertInst,
  12046. TargetTransformInfo *TTI,
  12047. SmallVectorImpl<Value *> &BuildVectorOpds,
  12048. SmallVectorImpl<Value *> &InsertElts,
  12049. unsigned OperandOffset) {
  12050. do {
  12051. Value *InsertedOperand = LastInsertInst->getOperand(1);
  12052. std::optional<unsigned> OperandIndex =
  12053. getInsertIndex(LastInsertInst, OperandOffset);
  12054. if (!OperandIndex)
  12055. return;
  12056. if (isa<InsertElementInst, InsertValueInst>(InsertedOperand)) {
  12057. findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
  12058. BuildVectorOpds, InsertElts, *OperandIndex);
  12059. } else {
  12060. BuildVectorOpds[*OperandIndex] = InsertedOperand;
  12061. InsertElts[*OperandIndex] = LastInsertInst;
  12062. }
  12063. LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
  12064. } while (LastInsertInst != nullptr &&
  12065. isa<InsertValueInst, InsertElementInst>(LastInsertInst) &&
  12066. LastInsertInst->hasOneUse());
  12067. }
  12068. /// Recognize construction of vectors like
  12069. /// %ra = insertelement <4 x float> poison, float %s0, i32 0
  12070. /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
  12071. /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
  12072. /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
  12073. /// starting from the last insertelement or insertvalue instruction.
  12074. ///
  12075. /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
  12076. /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
  12077. /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
  12078. ///
  12079. /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
  12080. ///
  12081. /// \return true if it matches.
  12082. static bool findBuildAggregate(Instruction *LastInsertInst,
  12083. TargetTransformInfo *TTI,
  12084. SmallVectorImpl<Value *> &BuildVectorOpds,
  12085. SmallVectorImpl<Value *> &InsertElts) {
  12086. assert((isa<InsertElementInst>(LastInsertInst) ||
  12087. isa<InsertValueInst>(LastInsertInst)) &&
  12088. "Expected insertelement or insertvalue instruction!");
  12089. assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
  12090. "Expected empty result vectors!");
  12091. std::optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
  12092. if (!AggregateSize)
  12093. return false;
  12094. BuildVectorOpds.resize(*AggregateSize);
  12095. InsertElts.resize(*AggregateSize);
  12096. findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
  12097. llvm::erase_value(BuildVectorOpds, nullptr);
  12098. llvm::erase_value(InsertElts, nullptr);
  12099. if (BuildVectorOpds.size() >= 2)
  12100. return true;
  12101. return false;
  12102. }
  12103. /// Try and get a reduction value from a phi node.
  12104. ///
  12105. /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
  12106. /// if they come from either \p ParentBB or a containing loop latch.
  12107. ///
  12108. /// \returns A candidate reduction value if possible, or \code nullptr \endcode
  12109. /// if not possible.
  12110. static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
  12111. BasicBlock *ParentBB, LoopInfo *LI) {
  12112. // There are situations where the reduction value is not dominated by the
  12113. // reduction phi. Vectorizing such cases has been reported to cause
  12114. // miscompiles. See PR25787.
  12115. auto DominatedReduxValue = [&](Value *R) {
  12116. return isa<Instruction>(R) &&
  12117. DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
  12118. };
  12119. Value *Rdx = nullptr;
  12120. // Return the incoming value if it comes from the same BB as the phi node.
  12121. if (P->getIncomingBlock(0) == ParentBB) {
  12122. Rdx = P->getIncomingValue(0);
  12123. } else if (P->getIncomingBlock(1) == ParentBB) {
  12124. Rdx = P->getIncomingValue(1);
  12125. }
  12126. if (Rdx && DominatedReduxValue(Rdx))
  12127. return Rdx;
  12128. // Otherwise, check whether we have a loop latch to look at.
  12129. Loop *BBL = LI->getLoopFor(ParentBB);
  12130. if (!BBL)
  12131. return nullptr;
  12132. BasicBlock *BBLatch = BBL->getLoopLatch();
  12133. if (!BBLatch)
  12134. return nullptr;
  12135. // There is a loop latch, return the incoming value if it comes from
  12136. // that. This reduction pattern occasionally turns up.
  12137. if (P->getIncomingBlock(0) == BBLatch) {
  12138. Rdx = P->getIncomingValue(0);
  12139. } else if (P->getIncomingBlock(1) == BBLatch) {
  12140. Rdx = P->getIncomingValue(1);
  12141. }
  12142. if (Rdx && DominatedReduxValue(Rdx))
  12143. return Rdx;
  12144. return nullptr;
  12145. }
  12146. static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
  12147. if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
  12148. return true;
  12149. if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
  12150. return true;
  12151. if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
  12152. return true;
  12153. if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
  12154. return true;
  12155. if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
  12156. return true;
  12157. if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
  12158. return true;
  12159. if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
  12160. return true;
  12161. return false;
  12162. }
  12163. bool SLPVectorizerPass::vectorizeHorReduction(
  12164. PHINode *P, Value *V, BasicBlock *BB, BoUpSLP &R, TargetTransformInfo *TTI,
  12165. SmallVectorImpl<WeakTrackingVH> &PostponedInsts) {
  12166. if (!ShouldVectorizeHor)
  12167. return false;
  12168. auto *Root = dyn_cast_or_null<Instruction>(V);
  12169. if (!Root)
  12170. return false;
  12171. if (!isa<BinaryOperator>(Root))
  12172. P = nullptr;
  12173. if (Root->getParent() != BB || isa<PHINode>(Root))
  12174. return false;
  12175. // Start analysis starting from Root instruction. If horizontal reduction is
  12176. // found, try to vectorize it. If it is not a horizontal reduction or
  12177. // vectorization is not possible or not effective, and currently analyzed
  12178. // instruction is a binary operation, try to vectorize the operands, using
  12179. // pre-order DFS traversal order. If the operands were not vectorized, repeat
  12180. // the same procedure considering each operand as a possible root of the
  12181. // horizontal reduction.
  12182. // Interrupt the process if the Root instruction itself was vectorized or all
  12183. // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
  12184. // If a horizintal reduction was not matched or vectorized we collect
  12185. // instructions for possible later attempts for vectorization.
  12186. std::queue<std::pair<Instruction *, unsigned>> Stack;
  12187. Stack.emplace(Root, 0);
  12188. SmallPtrSet<Value *, 8> VisitedInstrs;
  12189. bool Res = false;
  12190. auto &&TryToReduce = [this, TTI, &P, &R](Instruction *Inst, Value *&B0,
  12191. Value *&B1) -> Value * {
  12192. if (R.isAnalyzedReductionRoot(Inst))
  12193. return nullptr;
  12194. bool IsBinop = matchRdxBop(Inst, B0, B1);
  12195. bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
  12196. if (IsBinop || IsSelect) {
  12197. HorizontalReduction HorRdx;
  12198. if (HorRdx.matchAssociativeReduction(P, Inst, *SE, *DL, *TLI))
  12199. return HorRdx.tryToReduce(R, TTI, *TLI);
  12200. }
  12201. return nullptr;
  12202. };
  12203. while (!Stack.empty()) {
  12204. Instruction *Inst;
  12205. unsigned Level;
  12206. std::tie(Inst, Level) = Stack.front();
  12207. Stack.pop();
  12208. // Do not try to analyze instruction that has already been vectorized.
  12209. // This may happen when we vectorize instruction operands on a previous
  12210. // iteration while stack was populated before that happened.
  12211. if (R.isDeleted(Inst))
  12212. continue;
  12213. Value *B0 = nullptr, *B1 = nullptr;
  12214. if (Value *V = TryToReduce(Inst, B0, B1)) {
  12215. Res = true;
  12216. // Set P to nullptr to avoid re-analysis of phi node in
  12217. // matchAssociativeReduction function unless this is the root node.
  12218. P = nullptr;
  12219. if (auto *I = dyn_cast<Instruction>(V)) {
  12220. // Try to find another reduction.
  12221. Stack.emplace(I, Level);
  12222. continue;
  12223. }
  12224. } else {
  12225. bool IsBinop = B0 && B1;
  12226. if (P && IsBinop) {
  12227. Inst = dyn_cast<Instruction>(B0);
  12228. if (Inst == P)
  12229. Inst = dyn_cast<Instruction>(B1);
  12230. if (!Inst) {
  12231. // Set P to nullptr to avoid re-analysis of phi node in
  12232. // matchAssociativeReduction function unless this is the root node.
  12233. P = nullptr;
  12234. continue;
  12235. }
  12236. }
  12237. // Set P to nullptr to avoid re-analysis of phi node in
  12238. // matchAssociativeReduction function unless this is the root node.
  12239. P = nullptr;
  12240. // Do not collect CmpInst or InsertElementInst/InsertValueInst as their
  12241. // analysis is done separately.
  12242. if (!isa<CmpInst, InsertElementInst, InsertValueInst>(Inst))
  12243. PostponedInsts.push_back(Inst);
  12244. }
  12245. // Try to vectorize operands.
  12246. // Continue analysis for the instruction from the same basic block only to
  12247. // save compile time.
  12248. if (++Level < RecursionMaxDepth)
  12249. for (auto *Op : Inst->operand_values())
  12250. if (VisitedInstrs.insert(Op).second)
  12251. if (auto *I = dyn_cast<Instruction>(Op))
  12252. // Do not try to vectorize CmpInst operands, this is done
  12253. // separately.
  12254. if (!isa<PHINode, CmpInst, InsertElementInst, InsertValueInst>(I) &&
  12255. !R.isDeleted(I) && I->getParent() == BB)
  12256. Stack.emplace(I, Level);
  12257. }
  12258. return Res;
  12259. }
  12260. bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
  12261. BasicBlock *BB, BoUpSLP &R,
  12262. TargetTransformInfo *TTI) {
  12263. SmallVector<WeakTrackingVH> PostponedInsts;
  12264. bool Res = vectorizeHorReduction(P, V, BB, R, TTI, PostponedInsts);
  12265. Res |= tryToVectorize(PostponedInsts, R);
  12266. return Res;
  12267. }
  12268. bool SLPVectorizerPass::tryToVectorize(ArrayRef<WeakTrackingVH> Insts,
  12269. BoUpSLP &R) {
  12270. bool Res = false;
  12271. for (Value *V : Insts)
  12272. if (auto *Inst = dyn_cast<Instruction>(V); Inst && !R.isDeleted(Inst))
  12273. Res |= tryToVectorize(Inst, R);
  12274. return Res;
  12275. }
  12276. bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
  12277. BasicBlock *BB, BoUpSLP &R) {
  12278. const DataLayout &DL = BB->getModule()->getDataLayout();
  12279. if (!R.canMapToVector(IVI->getType(), DL))
  12280. return false;
  12281. SmallVector<Value *, 16> BuildVectorOpds;
  12282. SmallVector<Value *, 16> BuildVectorInsts;
  12283. if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
  12284. return false;
  12285. LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
  12286. // Aggregate value is unlikely to be processed in vector register.
  12287. return tryToVectorizeList(BuildVectorOpds, R);
  12288. }
  12289. bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
  12290. BasicBlock *BB, BoUpSLP &R) {
  12291. SmallVector<Value *, 16> BuildVectorInsts;
  12292. SmallVector<Value *, 16> BuildVectorOpds;
  12293. SmallVector<int> Mask;
  12294. if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
  12295. (llvm::all_of(
  12296. BuildVectorOpds,
  12297. [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
  12298. isFixedVectorShuffle(BuildVectorOpds, Mask)))
  12299. return false;
  12300. LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
  12301. return tryToVectorizeList(BuildVectorInsts, R);
  12302. }
  12303. template <typename T>
  12304. static bool
  12305. tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
  12306. function_ref<unsigned(T *)> Limit,
  12307. function_ref<bool(T *, T *)> Comparator,
  12308. function_ref<bool(T *, T *)> AreCompatible,
  12309. function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
  12310. bool LimitForRegisterSize) {
  12311. bool Changed = false;
  12312. // Sort by type, parent, operands.
  12313. stable_sort(Incoming, Comparator);
  12314. // Try to vectorize elements base on their type.
  12315. SmallVector<T *> Candidates;
  12316. for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
  12317. // Look for the next elements with the same type, parent and operand
  12318. // kinds.
  12319. auto *SameTypeIt = IncIt;
  12320. while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
  12321. ++SameTypeIt;
  12322. // Try to vectorize them.
  12323. unsigned NumElts = (SameTypeIt - IncIt);
  12324. LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
  12325. << NumElts << ")\n");
  12326. // The vectorization is a 3-state attempt:
  12327. // 1. Try to vectorize instructions with the same/alternate opcodes with the
  12328. // size of maximal register at first.
  12329. // 2. Try to vectorize remaining instructions with the same type, if
  12330. // possible. This may result in the better vectorization results rather than
  12331. // if we try just to vectorize instructions with the same/alternate opcodes.
  12332. // 3. Final attempt to try to vectorize all instructions with the
  12333. // same/alternate ops only, this may result in some extra final
  12334. // vectorization.
  12335. if (NumElts > 1 &&
  12336. TryToVectorizeHelper(ArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
  12337. // Success start over because instructions might have been changed.
  12338. Changed = true;
  12339. } else if (NumElts < Limit(*IncIt) &&
  12340. (Candidates.empty() ||
  12341. Candidates.front()->getType() == (*IncIt)->getType())) {
  12342. Candidates.append(IncIt, std::next(IncIt, NumElts));
  12343. }
  12344. // Final attempt to vectorize instructions with the same types.
  12345. if (Candidates.size() > 1 &&
  12346. (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
  12347. if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
  12348. // Success start over because instructions might have been changed.
  12349. Changed = true;
  12350. } else if (LimitForRegisterSize) {
  12351. // Try to vectorize using small vectors.
  12352. for (auto *It = Candidates.begin(), *End = Candidates.end();
  12353. It != End;) {
  12354. auto *SameTypeIt = It;
  12355. while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
  12356. ++SameTypeIt;
  12357. unsigned NumElts = (SameTypeIt - It);
  12358. if (NumElts > 1 &&
  12359. TryToVectorizeHelper(ArrayRef(It, NumElts),
  12360. /*LimitForRegisterSize=*/false))
  12361. Changed = true;
  12362. It = SameTypeIt;
  12363. }
  12364. }
  12365. Candidates.clear();
  12366. }
  12367. // Start over at the next instruction of a different type (or the end).
  12368. IncIt = SameTypeIt;
  12369. }
  12370. return Changed;
  12371. }
  12372. /// Compare two cmp instructions. If IsCompatibility is true, function returns
  12373. /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
  12374. /// operands. If IsCompatibility is false, function implements strict weak
  12375. /// ordering relation between two cmp instructions, returning true if the first
  12376. /// instruction is "less" than the second, i.e. its predicate is less than the
  12377. /// predicate of the second or the operands IDs are less than the operands IDs
  12378. /// of the second cmp instruction.
  12379. template <bool IsCompatibility>
  12380. static bool compareCmp(Value *V, Value *V2, TargetLibraryInfo &TLI,
  12381. function_ref<bool(Instruction *)> IsDeleted) {
  12382. auto *CI1 = cast<CmpInst>(V);
  12383. auto *CI2 = cast<CmpInst>(V2);
  12384. if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
  12385. return false;
  12386. if (CI1->getOperand(0)->getType()->getTypeID() <
  12387. CI2->getOperand(0)->getType()->getTypeID())
  12388. return !IsCompatibility;
  12389. if (CI1->getOperand(0)->getType()->getTypeID() >
  12390. CI2->getOperand(0)->getType()->getTypeID())
  12391. return false;
  12392. CmpInst::Predicate Pred1 = CI1->getPredicate();
  12393. CmpInst::Predicate Pred2 = CI2->getPredicate();
  12394. CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
  12395. CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
  12396. CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
  12397. CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
  12398. if (BasePred1 < BasePred2)
  12399. return !IsCompatibility;
  12400. if (BasePred1 > BasePred2)
  12401. return false;
  12402. // Compare operands.
  12403. bool LEPreds = Pred1 <= Pred2;
  12404. bool GEPreds = Pred1 >= Pred2;
  12405. for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
  12406. auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
  12407. auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
  12408. if (Op1->getValueID() < Op2->getValueID())
  12409. return !IsCompatibility;
  12410. if (Op1->getValueID() > Op2->getValueID())
  12411. return false;
  12412. if (auto *I1 = dyn_cast<Instruction>(Op1))
  12413. if (auto *I2 = dyn_cast<Instruction>(Op2)) {
  12414. if (I1->getParent() != I2->getParent())
  12415. return false;
  12416. InstructionsState S = getSameOpcode({I1, I2}, TLI);
  12417. if (S.getOpcode())
  12418. continue;
  12419. return false;
  12420. }
  12421. }
  12422. return IsCompatibility;
  12423. }
  12424. bool SLPVectorizerPass::vectorizeSimpleInstructions(InstSetVector &Instructions,
  12425. BasicBlock *BB, BoUpSLP &R,
  12426. bool AtTerminator) {
  12427. bool OpsChanged = false;
  12428. SmallVector<Instruction *, 4> PostponedCmps;
  12429. SmallVector<WeakTrackingVH> PostponedInsts;
  12430. // pass1 - try to vectorize reductions only
  12431. for (auto *I : reverse(Instructions)) {
  12432. if (R.isDeleted(I))
  12433. continue;
  12434. if (isa<CmpInst>(I)) {
  12435. PostponedCmps.push_back(I);
  12436. continue;
  12437. }
  12438. OpsChanged |= vectorizeHorReduction(nullptr, I, BB, R, TTI, PostponedInsts);
  12439. }
  12440. // pass2 - try to match and vectorize a buildvector sequence.
  12441. for (auto *I : reverse(Instructions)) {
  12442. if (R.isDeleted(I) || isa<CmpInst>(I))
  12443. continue;
  12444. if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I)) {
  12445. OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
  12446. } else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I)) {
  12447. OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
  12448. }
  12449. }
  12450. // Now try to vectorize postponed instructions.
  12451. OpsChanged |= tryToVectorize(PostponedInsts, R);
  12452. if (AtTerminator) {
  12453. // Try to find reductions first.
  12454. for (Instruction *I : PostponedCmps) {
  12455. if (R.isDeleted(I))
  12456. continue;
  12457. for (Value *Op : I->operands())
  12458. OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
  12459. }
  12460. // Try to vectorize operands as vector bundles.
  12461. for (Instruction *I : PostponedCmps) {
  12462. if (R.isDeleted(I))
  12463. continue;
  12464. OpsChanged |= tryToVectorize(I, R);
  12465. }
  12466. // Try to vectorize list of compares.
  12467. // Sort by type, compare predicate, etc.
  12468. auto CompareSorter = [&](Value *V, Value *V2) {
  12469. return compareCmp<false>(V, V2, *TLI,
  12470. [&R](Instruction *I) { return R.isDeleted(I); });
  12471. };
  12472. auto AreCompatibleCompares = [&](Value *V1, Value *V2) {
  12473. if (V1 == V2)
  12474. return true;
  12475. return compareCmp<true>(V1, V2, *TLI,
  12476. [&R](Instruction *I) { return R.isDeleted(I); });
  12477. };
  12478. auto Limit = [&R](Value *V) {
  12479. unsigned EltSize = R.getVectorElementSize(V);
  12480. return std::max(2U, R.getMaxVecRegSize() / EltSize);
  12481. };
  12482. SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
  12483. OpsChanged |= tryToVectorizeSequence<Value>(
  12484. Vals, Limit, CompareSorter, AreCompatibleCompares,
  12485. [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
  12486. // Exclude possible reductions from other blocks.
  12487. bool ArePossiblyReducedInOtherBlock =
  12488. any_of(Candidates, [](Value *V) {
  12489. return any_of(V->users(), [V](User *U) {
  12490. return isa<SelectInst>(U) &&
  12491. cast<SelectInst>(U)->getParent() !=
  12492. cast<Instruction>(V)->getParent();
  12493. });
  12494. });
  12495. if (ArePossiblyReducedInOtherBlock)
  12496. return false;
  12497. return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
  12498. },
  12499. /*LimitForRegisterSize=*/true);
  12500. Instructions.clear();
  12501. } else {
  12502. Instructions.clear();
  12503. // Insert in reverse order since the PostponedCmps vector was filled in
  12504. // reverse order.
  12505. Instructions.insert(PostponedCmps.rbegin(), PostponedCmps.rend());
  12506. }
  12507. return OpsChanged;
  12508. }
  12509. bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
  12510. bool Changed = false;
  12511. SmallVector<Value *, 4> Incoming;
  12512. SmallPtrSet<Value *, 16> VisitedInstrs;
  12513. // Maps phi nodes to the non-phi nodes found in the use tree for each phi
  12514. // node. Allows better to identify the chains that can be vectorized in the
  12515. // better way.
  12516. DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
  12517. auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
  12518. assert(isValidElementType(V1->getType()) &&
  12519. isValidElementType(V2->getType()) &&
  12520. "Expected vectorizable types only.");
  12521. // It is fine to compare type IDs here, since we expect only vectorizable
  12522. // types, like ints, floats and pointers, we don't care about other type.
  12523. if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
  12524. return true;
  12525. if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
  12526. return false;
  12527. ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
  12528. ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
  12529. if (Opcodes1.size() < Opcodes2.size())
  12530. return true;
  12531. if (Opcodes1.size() > Opcodes2.size())
  12532. return false;
  12533. std::optional<bool> ConstOrder;
  12534. for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
  12535. // Undefs are compatible with any other value.
  12536. if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
  12537. if (!ConstOrder)
  12538. ConstOrder =
  12539. !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
  12540. continue;
  12541. }
  12542. if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
  12543. if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
  12544. DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
  12545. DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
  12546. if (!NodeI1)
  12547. return NodeI2 != nullptr;
  12548. if (!NodeI2)
  12549. return false;
  12550. assert((NodeI1 == NodeI2) ==
  12551. (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
  12552. "Different nodes should have different DFS numbers");
  12553. if (NodeI1 != NodeI2)
  12554. return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
  12555. InstructionsState S = getSameOpcode({I1, I2}, *TLI);
  12556. if (S.getOpcode())
  12557. continue;
  12558. return I1->getOpcode() < I2->getOpcode();
  12559. }
  12560. if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
  12561. if (!ConstOrder)
  12562. ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
  12563. continue;
  12564. }
  12565. if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
  12566. return true;
  12567. if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
  12568. return false;
  12569. }
  12570. return ConstOrder && *ConstOrder;
  12571. };
  12572. auto AreCompatiblePHIs = [&PHIToOpcodes, this](Value *V1, Value *V2) {
  12573. if (V1 == V2)
  12574. return true;
  12575. if (V1->getType() != V2->getType())
  12576. return false;
  12577. ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
  12578. ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
  12579. if (Opcodes1.size() != Opcodes2.size())
  12580. return false;
  12581. for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
  12582. // Undefs are compatible with any other value.
  12583. if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
  12584. continue;
  12585. if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
  12586. if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
  12587. if (I1->getParent() != I2->getParent())
  12588. return false;
  12589. InstructionsState S = getSameOpcode({I1, I2}, *TLI);
  12590. if (S.getOpcode())
  12591. continue;
  12592. return false;
  12593. }
  12594. if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
  12595. continue;
  12596. if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
  12597. return false;
  12598. }
  12599. return true;
  12600. };
  12601. auto Limit = [&R](Value *V) {
  12602. unsigned EltSize = R.getVectorElementSize(V);
  12603. return std::max(2U, R.getMaxVecRegSize() / EltSize);
  12604. };
  12605. bool HaveVectorizedPhiNodes = false;
  12606. do {
  12607. // Collect the incoming values from the PHIs.
  12608. Incoming.clear();
  12609. for (Instruction &I : *BB) {
  12610. PHINode *P = dyn_cast<PHINode>(&I);
  12611. if (!P)
  12612. break;
  12613. // No need to analyze deleted, vectorized and non-vectorizable
  12614. // instructions.
  12615. if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
  12616. isValidElementType(P->getType()))
  12617. Incoming.push_back(P);
  12618. }
  12619. // Find the corresponding non-phi nodes for better matching when trying to
  12620. // build the tree.
  12621. for (Value *V : Incoming) {
  12622. SmallVectorImpl<Value *> &Opcodes =
  12623. PHIToOpcodes.try_emplace(V).first->getSecond();
  12624. if (!Opcodes.empty())
  12625. continue;
  12626. SmallVector<Value *, 4> Nodes(1, V);
  12627. SmallPtrSet<Value *, 4> Visited;
  12628. while (!Nodes.empty()) {
  12629. auto *PHI = cast<PHINode>(Nodes.pop_back_val());
  12630. if (!Visited.insert(PHI).second)
  12631. continue;
  12632. for (Value *V : PHI->incoming_values()) {
  12633. if (auto *PHI1 = dyn_cast<PHINode>((V))) {
  12634. Nodes.push_back(PHI1);
  12635. continue;
  12636. }
  12637. Opcodes.emplace_back(V);
  12638. }
  12639. }
  12640. }
  12641. HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
  12642. Incoming, Limit, PHICompare, AreCompatiblePHIs,
  12643. [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
  12644. return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
  12645. },
  12646. /*LimitForRegisterSize=*/true);
  12647. Changed |= HaveVectorizedPhiNodes;
  12648. VisitedInstrs.insert(Incoming.begin(), Incoming.end());
  12649. } while (HaveVectorizedPhiNodes);
  12650. VisitedInstrs.clear();
  12651. InstSetVector PostProcessInstructions;
  12652. SmallDenseSet<Instruction *, 4> KeyNodes;
  12653. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  12654. // Skip instructions with scalable type. The num of elements is unknown at
  12655. // compile-time for scalable type.
  12656. if (isa<ScalableVectorType>(it->getType()))
  12657. continue;
  12658. // Skip instructions marked for the deletion.
  12659. if (R.isDeleted(&*it))
  12660. continue;
  12661. // We may go through BB multiple times so skip the one we have checked.
  12662. if (!VisitedInstrs.insert(&*it).second) {
  12663. if (it->use_empty() && KeyNodes.contains(&*it) &&
  12664. vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
  12665. it->isTerminator())) {
  12666. // We would like to start over since some instructions are deleted
  12667. // and the iterator may become invalid value.
  12668. Changed = true;
  12669. it = BB->begin();
  12670. e = BB->end();
  12671. }
  12672. continue;
  12673. }
  12674. if (isa<DbgInfoIntrinsic>(it))
  12675. continue;
  12676. // Try to vectorize reductions that use PHINodes.
  12677. if (PHINode *P = dyn_cast<PHINode>(it)) {
  12678. // Check that the PHI is a reduction PHI.
  12679. if (P->getNumIncomingValues() == 2) {
  12680. // Try to match and vectorize a horizontal reduction.
  12681. if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
  12682. TTI)) {
  12683. Changed = true;
  12684. it = BB->begin();
  12685. e = BB->end();
  12686. continue;
  12687. }
  12688. }
  12689. // Try to vectorize the incoming values of the PHI, to catch reductions
  12690. // that feed into PHIs.
  12691. for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
  12692. // Skip if the incoming block is the current BB for now. Also, bypass
  12693. // unreachable IR for efficiency and to avoid crashing.
  12694. // TODO: Collect the skipped incoming values and try to vectorize them
  12695. // after processing BB.
  12696. if (BB == P->getIncomingBlock(I) ||
  12697. !DT->isReachableFromEntry(P->getIncomingBlock(I)))
  12698. continue;
  12699. // Postponed instructions should not be vectorized here, delay their
  12700. // vectorization.
  12701. if (auto *PI = dyn_cast<Instruction>(P->getIncomingValue(I));
  12702. PI && !PostProcessInstructions.contains(PI))
  12703. Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
  12704. P->getIncomingBlock(I), R, TTI);
  12705. }
  12706. continue;
  12707. }
  12708. // Ran into an instruction without users, like terminator, or function call
  12709. // with ignored return value, store. Ignore unused instructions (basing on
  12710. // instruction type, except for CallInst and InvokeInst).
  12711. if (it->use_empty() &&
  12712. (it->getType()->isVoidTy() || isa<CallInst, InvokeInst>(it))) {
  12713. KeyNodes.insert(&*it);
  12714. bool OpsChanged = false;
  12715. auto *SI = dyn_cast<StoreInst>(it);
  12716. bool TryToVectorizeRoot = ShouldStartVectorizeHorAtStore || !SI;
  12717. if (SI) {
  12718. auto I = Stores.find(getUnderlyingObject(SI->getPointerOperand()));
  12719. // Try to vectorize chain in store, if this is the only store to the
  12720. // address in the block.
  12721. // TODO: This is just a temporarily solution to save compile time. Need
  12722. // to investigate if we can safely turn on slp-vectorize-hor-store
  12723. // instead to allow lookup for reduction chains in all non-vectorized
  12724. // stores (need to check side effects and compile time).
  12725. TryToVectorizeRoot = (I == Stores.end() || I->second.size() == 1) &&
  12726. SI->getValueOperand()->hasOneUse();
  12727. }
  12728. if (TryToVectorizeRoot) {
  12729. for (auto *V : it->operand_values()) {
  12730. // Postponed instructions should not be vectorized here, delay their
  12731. // vectorization.
  12732. if (auto *VI = dyn_cast<Instruction>(V);
  12733. VI && !PostProcessInstructions.contains(VI))
  12734. // Try to match and vectorize a horizontal reduction.
  12735. OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
  12736. }
  12737. }
  12738. // Start vectorization of post-process list of instructions from the
  12739. // top-tree instructions to try to vectorize as many instructions as
  12740. // possible.
  12741. OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
  12742. it->isTerminator());
  12743. if (OpsChanged) {
  12744. // We would like to start over since some instructions are deleted
  12745. // and the iterator may become invalid value.
  12746. Changed = true;
  12747. it = BB->begin();
  12748. e = BB->end();
  12749. continue;
  12750. }
  12751. }
  12752. if (isa<CmpInst, InsertElementInst, InsertValueInst>(it))
  12753. PostProcessInstructions.insert(&*it);
  12754. }
  12755. return Changed;
  12756. }
  12757. bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
  12758. auto Changed = false;
  12759. for (auto &Entry : GEPs) {
  12760. // If the getelementptr list has fewer than two elements, there's nothing
  12761. // to do.
  12762. if (Entry.second.size() < 2)
  12763. continue;
  12764. LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
  12765. << Entry.second.size() << ".\n");
  12766. // Process the GEP list in chunks suitable for the target's supported
  12767. // vector size. If a vector register can't hold 1 element, we are done. We
  12768. // are trying to vectorize the index computations, so the maximum number of
  12769. // elements is based on the size of the index expression, rather than the
  12770. // size of the GEP itself (the target's pointer size).
  12771. unsigned MaxVecRegSize = R.getMaxVecRegSize();
  12772. unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
  12773. if (MaxVecRegSize < EltSize)
  12774. continue;
  12775. unsigned MaxElts = MaxVecRegSize / EltSize;
  12776. for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
  12777. auto Len = std::min<unsigned>(BE - BI, MaxElts);
  12778. ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
  12779. // Initialize a set a candidate getelementptrs. Note that we use a
  12780. // SetVector here to preserve program order. If the index computations
  12781. // are vectorizable and begin with loads, we want to minimize the chance
  12782. // of having to reorder them later.
  12783. SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
  12784. // Some of the candidates may have already been vectorized after we
  12785. // initially collected them. If so, they are marked as deleted, so remove
  12786. // them from the set of candidates.
  12787. Candidates.remove_if(
  12788. [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
  12789. // Remove from the set of candidates all pairs of getelementptrs with
  12790. // constant differences. Such getelementptrs are likely not good
  12791. // candidates for vectorization in a bottom-up phase since one can be
  12792. // computed from the other. We also ensure all candidate getelementptr
  12793. // indices are unique.
  12794. for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
  12795. auto *GEPI = GEPList[I];
  12796. if (!Candidates.count(GEPI))
  12797. continue;
  12798. auto *SCEVI = SE->getSCEV(GEPList[I]);
  12799. for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
  12800. auto *GEPJ = GEPList[J];
  12801. auto *SCEVJ = SE->getSCEV(GEPList[J]);
  12802. if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
  12803. Candidates.remove(GEPI);
  12804. Candidates.remove(GEPJ);
  12805. } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
  12806. Candidates.remove(GEPJ);
  12807. }
  12808. }
  12809. }
  12810. // We break out of the above computation as soon as we know there are
  12811. // fewer than two candidates remaining.
  12812. if (Candidates.size() < 2)
  12813. continue;
  12814. // Add the single, non-constant index of each candidate to the bundle. We
  12815. // ensured the indices met these constraints when we originally collected
  12816. // the getelementptrs.
  12817. SmallVector<Value *, 16> Bundle(Candidates.size());
  12818. auto BundleIndex = 0u;
  12819. for (auto *V : Candidates) {
  12820. auto *GEP = cast<GetElementPtrInst>(V);
  12821. auto *GEPIdx = GEP->idx_begin()->get();
  12822. assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
  12823. Bundle[BundleIndex++] = GEPIdx;
  12824. }
  12825. // Try and vectorize the indices. We are currently only interested in
  12826. // gather-like cases of the form:
  12827. //
  12828. // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
  12829. //
  12830. // where the loads of "a", the loads of "b", and the subtractions can be
  12831. // performed in parallel. It's likely that detecting this pattern in a
  12832. // bottom-up phase will be simpler and less costly than building a
  12833. // full-blown top-down phase beginning at the consecutive loads.
  12834. Changed |= tryToVectorizeList(Bundle, R);
  12835. }
  12836. }
  12837. return Changed;
  12838. }
  12839. bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
  12840. bool Changed = false;
  12841. // Sort by type, base pointers and values operand. Value operands must be
  12842. // compatible (have the same opcode, same parent), otherwise it is
  12843. // definitely not profitable to try to vectorize them.
  12844. auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
  12845. if (V->getPointerOperandType()->getTypeID() <
  12846. V2->getPointerOperandType()->getTypeID())
  12847. return true;
  12848. if (V->getPointerOperandType()->getTypeID() >
  12849. V2->getPointerOperandType()->getTypeID())
  12850. return false;
  12851. // UndefValues are compatible with all other values.
  12852. if (isa<UndefValue>(V->getValueOperand()) ||
  12853. isa<UndefValue>(V2->getValueOperand()))
  12854. return false;
  12855. if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
  12856. if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
  12857. DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
  12858. DT->getNode(I1->getParent());
  12859. DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
  12860. DT->getNode(I2->getParent());
  12861. assert(NodeI1 && "Should only process reachable instructions");
  12862. assert(NodeI2 && "Should only process reachable instructions");
  12863. assert((NodeI1 == NodeI2) ==
  12864. (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
  12865. "Different nodes should have different DFS numbers");
  12866. if (NodeI1 != NodeI2)
  12867. return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
  12868. InstructionsState S = getSameOpcode({I1, I2}, *TLI);
  12869. if (S.getOpcode())
  12870. return false;
  12871. return I1->getOpcode() < I2->getOpcode();
  12872. }
  12873. if (isa<Constant>(V->getValueOperand()) &&
  12874. isa<Constant>(V2->getValueOperand()))
  12875. return false;
  12876. return V->getValueOperand()->getValueID() <
  12877. V2->getValueOperand()->getValueID();
  12878. };
  12879. auto &&AreCompatibleStores = [this](StoreInst *V1, StoreInst *V2) {
  12880. if (V1 == V2)
  12881. return true;
  12882. if (V1->getPointerOperandType() != V2->getPointerOperandType())
  12883. return false;
  12884. // Undefs are compatible with any other value.
  12885. if (isa<UndefValue>(V1->getValueOperand()) ||
  12886. isa<UndefValue>(V2->getValueOperand()))
  12887. return true;
  12888. if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
  12889. if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
  12890. if (I1->getParent() != I2->getParent())
  12891. return false;
  12892. InstructionsState S = getSameOpcode({I1, I2}, *TLI);
  12893. return S.getOpcode() > 0;
  12894. }
  12895. if (isa<Constant>(V1->getValueOperand()) &&
  12896. isa<Constant>(V2->getValueOperand()))
  12897. return true;
  12898. return V1->getValueOperand()->getValueID() ==
  12899. V2->getValueOperand()->getValueID();
  12900. };
  12901. auto Limit = [&R, this](StoreInst *SI) {
  12902. unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
  12903. return R.getMinVF(EltSize);
  12904. };
  12905. // Attempt to sort and vectorize each of the store-groups.
  12906. for (auto &Pair : Stores) {
  12907. if (Pair.second.size() < 2)
  12908. continue;
  12909. LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
  12910. << Pair.second.size() << ".\n");
  12911. if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
  12912. continue;
  12913. Changed |= tryToVectorizeSequence<StoreInst>(
  12914. Pair.second, Limit, StoreSorter, AreCompatibleStores,
  12915. [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
  12916. return vectorizeStores(Candidates, R);
  12917. },
  12918. /*LimitForRegisterSize=*/false);
  12919. }
  12920. return Changed;
  12921. }
  12922. char SLPVectorizer::ID = 0;
  12923. static const char lv_name[] = "SLP Vectorizer";
  12924. INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
  12925. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  12926. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  12927. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  12928. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  12929. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  12930. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  12931. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  12932. INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
  12933. INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
  12934. Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }