SLPVectorizer.cpp 398 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255
  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/Optional.h"
  22. #include "llvm/ADT/PostOrderIterator.h"
  23. #include "llvm/ADT/PriorityQueue.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SetOperations.h"
  26. #include "llvm/ADT/SetVector.h"
  27. #include "llvm/ADT/SmallBitVector.h"
  28. #include "llvm/ADT/SmallPtrSet.h"
  29. #include "llvm/ADT/SmallSet.h"
  30. #include "llvm/ADT/SmallString.h"
  31. #include "llvm/ADT/Statistic.h"
  32. #include "llvm/ADT/iterator.h"
  33. #include "llvm/ADT/iterator_range.h"
  34. #include "llvm/Analysis/AliasAnalysis.h"
  35. #include "llvm/Analysis/AssumptionCache.h"
  36. #include "llvm/Analysis/CodeMetrics.h"
  37. #include "llvm/Analysis/DemandedBits.h"
  38. #include "llvm/Analysis/GlobalsModRef.h"
  39. #include "llvm/Analysis/IVDescriptors.h"
  40. #include "llvm/Analysis/LoopAccessAnalysis.h"
  41. #include "llvm/Analysis/LoopInfo.h"
  42. #include "llvm/Analysis/MemoryLocation.h"
  43. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  44. #include "llvm/Analysis/ScalarEvolution.h"
  45. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  46. #include "llvm/Analysis/TargetLibraryInfo.h"
  47. #include "llvm/Analysis/TargetTransformInfo.h"
  48. #include "llvm/Analysis/ValueTracking.h"
  49. #include "llvm/Analysis/VectorUtils.h"
  50. #include "llvm/IR/Attributes.h"
  51. #include "llvm/IR/BasicBlock.h"
  52. #include "llvm/IR/Constant.h"
  53. #include "llvm/IR/Constants.h"
  54. #include "llvm/IR/DataLayout.h"
  55. #include "llvm/IR/DebugLoc.h"
  56. #include "llvm/IR/DerivedTypes.h"
  57. #include "llvm/IR/Dominators.h"
  58. #include "llvm/IR/Function.h"
  59. #include "llvm/IR/IRBuilder.h"
  60. #include "llvm/IR/InstrTypes.h"
  61. #include "llvm/IR/Instruction.h"
  62. #include "llvm/IR/Instructions.h"
  63. #include "llvm/IR/IntrinsicInst.h"
  64. #include "llvm/IR/Intrinsics.h"
  65. #include "llvm/IR/Module.h"
  66. #include "llvm/IR/NoFolder.h"
  67. #include "llvm/IR/Operator.h"
  68. #include "llvm/IR/PatternMatch.h"
  69. #include "llvm/IR/Type.h"
  70. #include "llvm/IR/Use.h"
  71. #include "llvm/IR/User.h"
  72. #include "llvm/IR/Value.h"
  73. #include "llvm/IR/ValueHandle.h"
  74. #include "llvm/IR/Verifier.h"
  75. #include "llvm/InitializePasses.h"
  76. #include "llvm/Pass.h"
  77. #include "llvm/Support/Casting.h"
  78. #include "llvm/Support/CommandLine.h"
  79. #include "llvm/Support/Compiler.h"
  80. #include "llvm/Support/DOTGraphTraits.h"
  81. #include "llvm/Support/Debug.h"
  82. #include "llvm/Support/ErrorHandling.h"
  83. #include "llvm/Support/GraphWriter.h"
  84. #include "llvm/Support/InstructionCost.h"
  85. #include "llvm/Support/KnownBits.h"
  86. #include "llvm/Support/MathExtras.h"
  87. #include "llvm/Support/raw_ostream.h"
  88. #include "llvm/Transforms/Utils/InjectTLIMappings.h"
  89. #include "llvm/Transforms/Utils/LoopUtils.h"
  90. #include "llvm/Transforms/Vectorize.h"
  91. #include <algorithm>
  92. #include <cassert>
  93. #include <cstdint>
  94. #include <iterator>
  95. #include <memory>
  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 Look-ahead heuristic goes through the users of the bundle to calculate
  151. // the users cost in getExternalUsesCost(). To avoid compilation time increase
  152. // we limit the number of users visited to this value.
  153. static cl::opt<unsigned> LookAheadUsersBudget(
  154. "slp-look-ahead-users-budget", cl::init(2), cl::Hidden,
  155. cl::desc("The maximum number of users to visit while visiting the "
  156. "predecessors. This prevents compilation time increase."));
  157. static cl::opt<bool>
  158. ViewSLPTree("view-slp-tree", cl::Hidden,
  159. cl::desc("Display the SLP trees with Graphviz"));
  160. // Limit the number of alias checks. The limit is chosen so that
  161. // it has no negative effect on the llvm benchmarks.
  162. static const unsigned AliasedCheckLimit = 10;
  163. // Another limit for the alias checks: The maximum distance between load/store
  164. // instructions where alias checks are done.
  165. // This limit is useful for very large basic blocks.
  166. static const unsigned MaxMemDepDistance = 160;
  167. /// If the ScheduleRegionSizeBudget is exhausted, we allow small scheduling
  168. /// regions to be handled.
  169. static const int MinScheduleRegionSize = 16;
  170. /// Predicate for the element types that the SLP vectorizer supports.
  171. ///
  172. /// The most important thing to filter here are types which are invalid in LLVM
  173. /// vectors. We also filter target specific types which have absolutely no
  174. /// meaningful vectorization path such as x86_fp80 and ppc_f128. This just
  175. /// avoids spending time checking the cost model and realizing that they will
  176. /// be inevitably scalarized.
  177. static bool isValidElementType(Type *Ty) {
  178. return VectorType::isValidElementType(Ty) && !Ty->isX86_FP80Ty() &&
  179. !Ty->isPPC_FP128Ty();
  180. }
  181. /// \returns True if the value is a constant (but not globals/constant
  182. /// expressions).
  183. static bool isConstant(Value *V) {
  184. return isa<Constant>(V) && !isa<ConstantExpr>(V) && !isa<GlobalValue>(V);
  185. }
  186. /// Checks if \p V is one of vector-like instructions, i.e. undef,
  187. /// insertelement/extractelement with constant indices for fixed vector type or
  188. /// extractvalue instruction.
  189. static bool isVectorLikeInstWithConstOps(Value *V) {
  190. if (!isa<InsertElementInst, ExtractElementInst>(V) &&
  191. !isa<ExtractValueInst, UndefValue>(V))
  192. return false;
  193. auto *I = dyn_cast<Instruction>(V);
  194. if (!I || isa<ExtractValueInst>(I))
  195. return true;
  196. if (!isa<FixedVectorType>(I->getOperand(0)->getType()))
  197. return false;
  198. if (isa<ExtractElementInst>(I))
  199. return isConstant(I->getOperand(1));
  200. assert(isa<InsertElementInst>(V) && "Expected only insertelement.");
  201. return isConstant(I->getOperand(2));
  202. }
  203. /// \returns true if all of the instructions in \p VL are in the same block or
  204. /// false otherwise.
  205. static bool allSameBlock(ArrayRef<Value *> VL) {
  206. Instruction *I0 = dyn_cast<Instruction>(VL[0]);
  207. if (!I0)
  208. return false;
  209. if (all_of(VL, isVectorLikeInstWithConstOps))
  210. return true;
  211. BasicBlock *BB = I0->getParent();
  212. for (int I = 1, E = VL.size(); I < E; I++) {
  213. auto *II = dyn_cast<Instruction>(VL[I]);
  214. if (!II)
  215. return false;
  216. if (BB != II->getParent())
  217. return false;
  218. }
  219. return true;
  220. }
  221. /// \returns True if all of the values in \p VL are constants (but not
  222. /// globals/constant expressions).
  223. static bool allConstant(ArrayRef<Value *> VL) {
  224. // Constant expressions and globals can't be vectorized like normal integer/FP
  225. // constants.
  226. return all_of(VL, isConstant);
  227. }
  228. /// \returns True if all of the values in \p VL are identical or some of them
  229. /// are UndefValue.
  230. static bool isSplat(ArrayRef<Value *> VL) {
  231. Value *FirstNonUndef = nullptr;
  232. for (Value *V : VL) {
  233. if (isa<UndefValue>(V))
  234. continue;
  235. if (!FirstNonUndef) {
  236. FirstNonUndef = V;
  237. continue;
  238. }
  239. if (V != FirstNonUndef)
  240. return false;
  241. }
  242. return FirstNonUndef != nullptr;
  243. }
  244. /// \returns True if \p I is commutative, handles CmpInst and BinaryOperator.
  245. static bool isCommutative(Instruction *I) {
  246. if (auto *Cmp = dyn_cast<CmpInst>(I))
  247. return Cmp->isCommutative();
  248. if (auto *BO = dyn_cast<BinaryOperator>(I))
  249. return BO->isCommutative();
  250. // TODO: This should check for generic Instruction::isCommutative(), but
  251. // we need to confirm that the caller code correctly handles Intrinsics
  252. // for example (does not have 2 operands).
  253. return false;
  254. }
  255. /// Checks if the given value is actually an undefined constant vector.
  256. static bool isUndefVector(const Value *V) {
  257. if (isa<UndefValue>(V))
  258. return true;
  259. auto *C = dyn_cast<Constant>(V);
  260. if (!C)
  261. return false;
  262. if (!C->containsUndefOrPoisonElement())
  263. return false;
  264. auto *VecTy = dyn_cast<FixedVectorType>(C->getType());
  265. if (!VecTy)
  266. return false;
  267. for (unsigned I = 0, E = VecTy->getNumElements(); I != E; ++I) {
  268. if (Constant *Elem = C->getAggregateElement(I))
  269. if (!isa<UndefValue>(Elem))
  270. return false;
  271. }
  272. return true;
  273. }
  274. /// Checks if the vector of instructions can be represented as a shuffle, like:
  275. /// %x0 = extractelement <4 x i8> %x, i32 0
  276. /// %x3 = extractelement <4 x i8> %x, i32 3
  277. /// %y1 = extractelement <4 x i8> %y, i32 1
  278. /// %y2 = extractelement <4 x i8> %y, i32 2
  279. /// %x0x0 = mul i8 %x0, %x0
  280. /// %x3x3 = mul i8 %x3, %x3
  281. /// %y1y1 = mul i8 %y1, %y1
  282. /// %y2y2 = mul i8 %y2, %y2
  283. /// %ins1 = insertelement <4 x i8> poison, i8 %x0x0, i32 0
  284. /// %ins2 = insertelement <4 x i8> %ins1, i8 %x3x3, i32 1
  285. /// %ins3 = insertelement <4 x i8> %ins2, i8 %y1y1, i32 2
  286. /// %ins4 = insertelement <4 x i8> %ins3, i8 %y2y2, i32 3
  287. /// ret <4 x i8> %ins4
  288. /// can be transformed into:
  289. /// %1 = shufflevector <4 x i8> %x, <4 x i8> %y, <4 x i32> <i32 0, i32 3, i32 5,
  290. /// i32 6>
  291. /// %2 = mul <4 x i8> %1, %1
  292. /// ret <4 x i8> %2
  293. /// We convert this initially to something like:
  294. /// %x0 = extractelement <4 x i8> %x, i32 0
  295. /// %x3 = extractelement <4 x i8> %x, i32 3
  296. /// %y1 = extractelement <4 x i8> %y, i32 1
  297. /// %y2 = extractelement <4 x i8> %y, i32 2
  298. /// %1 = insertelement <4 x i8> poison, i8 %x0, i32 0
  299. /// %2 = insertelement <4 x i8> %1, i8 %x3, i32 1
  300. /// %3 = insertelement <4 x i8> %2, i8 %y1, i32 2
  301. /// %4 = insertelement <4 x i8> %3, i8 %y2, i32 3
  302. /// %5 = mul <4 x i8> %4, %4
  303. /// %6 = extractelement <4 x i8> %5, i32 0
  304. /// %ins1 = insertelement <4 x i8> poison, i8 %6, i32 0
  305. /// %7 = extractelement <4 x i8> %5, i32 1
  306. /// %ins2 = insertelement <4 x i8> %ins1, i8 %7, i32 1
  307. /// %8 = extractelement <4 x i8> %5, i32 2
  308. /// %ins3 = insertelement <4 x i8> %ins2, i8 %8, i32 2
  309. /// %9 = extractelement <4 x i8> %5, i32 3
  310. /// %ins4 = insertelement <4 x i8> %ins3, i8 %9, i32 3
  311. /// ret <4 x i8> %ins4
  312. /// InstCombiner transforms this into a shuffle and vector mul
  313. /// Mask will return the Shuffle Mask equivalent to the extracted elements.
  314. /// TODO: Can we split off and reuse the shuffle mask detection from
  315. /// TargetTransformInfo::getInstructionThroughput?
  316. static Optional<TargetTransformInfo::ShuffleKind>
  317. isFixedVectorShuffle(ArrayRef<Value *> VL, SmallVectorImpl<int> &Mask) {
  318. const auto *It =
  319. find_if(VL, [](Value *V) { return isa<ExtractElementInst>(V); });
  320. if (It == VL.end())
  321. return None;
  322. auto *EI0 = cast<ExtractElementInst>(*It);
  323. if (isa<ScalableVectorType>(EI0->getVectorOperandType()))
  324. return None;
  325. unsigned Size =
  326. cast<FixedVectorType>(EI0->getVectorOperandType())->getNumElements();
  327. Value *Vec1 = nullptr;
  328. Value *Vec2 = nullptr;
  329. enum ShuffleMode { Unknown, Select, Permute };
  330. ShuffleMode CommonShuffleMode = Unknown;
  331. Mask.assign(VL.size(), UndefMaskElem);
  332. for (unsigned I = 0, E = VL.size(); I < E; ++I) {
  333. // Undef can be represented as an undef element in a vector.
  334. if (isa<UndefValue>(VL[I]))
  335. continue;
  336. auto *EI = cast<ExtractElementInst>(VL[I]);
  337. if (isa<ScalableVectorType>(EI->getVectorOperandType()))
  338. return None;
  339. auto *Vec = EI->getVectorOperand();
  340. // We can extractelement from undef or poison vector.
  341. if (isUndefVector(Vec))
  342. continue;
  343. // All vector operands must have the same number of vector elements.
  344. if (cast<FixedVectorType>(Vec->getType())->getNumElements() != Size)
  345. return None;
  346. if (isa<UndefValue>(EI->getIndexOperand()))
  347. continue;
  348. auto *Idx = dyn_cast<ConstantInt>(EI->getIndexOperand());
  349. if (!Idx)
  350. return None;
  351. // Undefined behavior if Idx is negative or >= Size.
  352. if (Idx->getValue().uge(Size))
  353. continue;
  354. unsigned IntIdx = Idx->getValue().getZExtValue();
  355. Mask[I] = IntIdx;
  356. // For correct shuffling we have to have at most 2 different vector operands
  357. // in all extractelement instructions.
  358. if (!Vec1 || Vec1 == Vec) {
  359. Vec1 = Vec;
  360. } else if (!Vec2 || Vec2 == Vec) {
  361. Vec2 = Vec;
  362. Mask[I] += Size;
  363. } else {
  364. return None;
  365. }
  366. if (CommonShuffleMode == Permute)
  367. continue;
  368. // If the extract index is not the same as the operation number, it is a
  369. // permutation.
  370. if (IntIdx != I) {
  371. CommonShuffleMode = Permute;
  372. continue;
  373. }
  374. CommonShuffleMode = Select;
  375. }
  376. // If we're not crossing lanes in different vectors, consider it as blending.
  377. if (CommonShuffleMode == Select && Vec2)
  378. return TargetTransformInfo::SK_Select;
  379. // If Vec2 was never used, we have a permutation of a single vector, otherwise
  380. // we have permutation of 2 vectors.
  381. return Vec2 ? TargetTransformInfo::SK_PermuteTwoSrc
  382. : TargetTransformInfo::SK_PermuteSingleSrc;
  383. }
  384. namespace {
  385. /// Main data required for vectorization of instructions.
  386. struct InstructionsState {
  387. /// The very first instruction in the list with the main opcode.
  388. Value *OpValue = nullptr;
  389. /// The main/alternate instruction.
  390. Instruction *MainOp = nullptr;
  391. Instruction *AltOp = nullptr;
  392. /// The main/alternate opcodes for the list of instructions.
  393. unsigned getOpcode() const {
  394. return MainOp ? MainOp->getOpcode() : 0;
  395. }
  396. unsigned getAltOpcode() const {
  397. return AltOp ? AltOp->getOpcode() : 0;
  398. }
  399. /// Some of the instructions in the list have alternate opcodes.
  400. bool isAltShuffle() const { return AltOp != MainOp; }
  401. bool isOpcodeOrAlt(Instruction *I) const {
  402. unsigned CheckedOpcode = I->getOpcode();
  403. return getOpcode() == CheckedOpcode || getAltOpcode() == CheckedOpcode;
  404. }
  405. InstructionsState() = delete;
  406. InstructionsState(Value *OpValue, Instruction *MainOp, Instruction *AltOp)
  407. : OpValue(OpValue), MainOp(MainOp), AltOp(AltOp) {}
  408. };
  409. } // end anonymous namespace
  410. /// Chooses the correct key for scheduling data. If \p Op has the same (or
  411. /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is \p
  412. /// OpValue.
  413. static Value *isOneOf(const InstructionsState &S, Value *Op) {
  414. auto *I = dyn_cast<Instruction>(Op);
  415. if (I && S.isOpcodeOrAlt(I))
  416. return Op;
  417. return S.OpValue;
  418. }
  419. /// \returns true if \p Opcode is allowed as part of of the main/alternate
  420. /// instruction for SLP vectorization.
  421. ///
  422. /// Example of unsupported opcode is SDIV that can potentially cause UB if the
  423. /// "shuffled out" lane would result in division by zero.
  424. static bool isValidForAlternation(unsigned Opcode) {
  425. if (Instruction::isIntDivRem(Opcode))
  426. return false;
  427. return true;
  428. }
  429. /// \returns analysis of the Instructions in \p VL described in
  430. /// InstructionsState, the Opcode that we suppose the whole list
  431. /// could be vectorized even if its structure is diverse.
  432. static InstructionsState getSameOpcode(ArrayRef<Value *> VL,
  433. unsigned BaseIndex = 0) {
  434. // Make sure these are all Instructions.
  435. if (llvm::any_of(VL, [](Value *V) { return !isa<Instruction>(V); }))
  436. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  437. bool IsCastOp = isa<CastInst>(VL[BaseIndex]);
  438. bool IsBinOp = isa<BinaryOperator>(VL[BaseIndex]);
  439. unsigned Opcode = cast<Instruction>(VL[BaseIndex])->getOpcode();
  440. unsigned AltOpcode = Opcode;
  441. unsigned AltIndex = BaseIndex;
  442. // Check for one alternate opcode from another BinaryOperator.
  443. // TODO - generalize to support all operators (types, calls etc.).
  444. for (int Cnt = 0, E = VL.size(); Cnt < E; Cnt++) {
  445. unsigned InstOpcode = cast<Instruction>(VL[Cnt])->getOpcode();
  446. if (IsBinOp && isa<BinaryOperator>(VL[Cnt])) {
  447. if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  448. continue;
  449. if (Opcode == AltOpcode && isValidForAlternation(InstOpcode) &&
  450. isValidForAlternation(Opcode)) {
  451. AltOpcode = InstOpcode;
  452. AltIndex = Cnt;
  453. continue;
  454. }
  455. } else if (IsCastOp && isa<CastInst>(VL[Cnt])) {
  456. Type *Ty0 = cast<Instruction>(VL[BaseIndex])->getOperand(0)->getType();
  457. Type *Ty1 = cast<Instruction>(VL[Cnt])->getOperand(0)->getType();
  458. if (Ty0 == Ty1) {
  459. if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  460. continue;
  461. if (Opcode == AltOpcode) {
  462. assert(isValidForAlternation(Opcode) &&
  463. isValidForAlternation(InstOpcode) &&
  464. "Cast isn't safe for alternation, logic needs to be updated!");
  465. AltOpcode = InstOpcode;
  466. AltIndex = Cnt;
  467. continue;
  468. }
  469. }
  470. } else if (InstOpcode == Opcode || InstOpcode == AltOpcode)
  471. continue;
  472. return InstructionsState(VL[BaseIndex], nullptr, nullptr);
  473. }
  474. return InstructionsState(VL[BaseIndex], cast<Instruction>(VL[BaseIndex]),
  475. cast<Instruction>(VL[AltIndex]));
  476. }
  477. /// \returns true if all of the values in \p VL have the same type or false
  478. /// otherwise.
  479. static bool allSameType(ArrayRef<Value *> VL) {
  480. Type *Ty = VL[0]->getType();
  481. for (int i = 1, e = VL.size(); i < e; i++)
  482. if (VL[i]->getType() != Ty)
  483. return false;
  484. return true;
  485. }
  486. /// \returns True if Extract{Value,Element} instruction extracts element Idx.
  487. static Optional<unsigned> getExtractIndex(Instruction *E) {
  488. unsigned Opcode = E->getOpcode();
  489. assert((Opcode == Instruction::ExtractElement ||
  490. Opcode == Instruction::ExtractValue) &&
  491. "Expected extractelement or extractvalue instruction.");
  492. if (Opcode == Instruction::ExtractElement) {
  493. auto *CI = dyn_cast<ConstantInt>(E->getOperand(1));
  494. if (!CI)
  495. return None;
  496. return CI->getZExtValue();
  497. }
  498. ExtractValueInst *EI = cast<ExtractValueInst>(E);
  499. if (EI->getNumIndices() != 1)
  500. return None;
  501. return *EI->idx_begin();
  502. }
  503. /// \returns True if in-tree use also needs extract. This refers to
  504. /// possible scalar operand in vectorized instruction.
  505. static bool InTreeUserNeedToExtract(Value *Scalar, Instruction *UserInst,
  506. TargetLibraryInfo *TLI) {
  507. unsigned Opcode = UserInst->getOpcode();
  508. switch (Opcode) {
  509. case Instruction::Load: {
  510. LoadInst *LI = cast<LoadInst>(UserInst);
  511. return (LI->getPointerOperand() == Scalar);
  512. }
  513. case Instruction::Store: {
  514. StoreInst *SI = cast<StoreInst>(UserInst);
  515. return (SI->getPointerOperand() == Scalar);
  516. }
  517. case Instruction::Call: {
  518. CallInst *CI = cast<CallInst>(UserInst);
  519. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  520. for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
  521. if (hasVectorInstrinsicScalarOpd(ID, i))
  522. return (CI->getArgOperand(i) == Scalar);
  523. }
  524. LLVM_FALLTHROUGH;
  525. }
  526. default:
  527. return false;
  528. }
  529. }
  530. /// \returns the AA location that is being access by the instruction.
  531. static MemoryLocation getLocation(Instruction *I) {
  532. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  533. return MemoryLocation::get(SI);
  534. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  535. return MemoryLocation::get(LI);
  536. return MemoryLocation();
  537. }
  538. /// \returns True if the instruction is not a volatile or atomic load/store.
  539. static bool isSimple(Instruction *I) {
  540. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  541. return LI->isSimple();
  542. if (StoreInst *SI = dyn_cast<StoreInst>(I))
  543. return SI->isSimple();
  544. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(I))
  545. return !MI->isVolatile();
  546. return true;
  547. }
  548. /// Shuffles \p Mask in accordance with the given \p SubMask.
  549. static void addMask(SmallVectorImpl<int> &Mask, ArrayRef<int> SubMask) {
  550. if (SubMask.empty())
  551. return;
  552. if (Mask.empty()) {
  553. Mask.append(SubMask.begin(), SubMask.end());
  554. return;
  555. }
  556. SmallVector<int> NewMask(SubMask.size(), UndefMaskElem);
  557. int TermValue = std::min(Mask.size(), SubMask.size());
  558. for (int I = 0, E = SubMask.size(); I < E; ++I) {
  559. if (SubMask[I] >= TermValue || SubMask[I] == UndefMaskElem ||
  560. Mask[SubMask[I]] >= TermValue)
  561. continue;
  562. NewMask[I] = Mask[SubMask[I]];
  563. }
  564. Mask.swap(NewMask);
  565. }
  566. /// Order may have elements assigned special value (size) which is out of
  567. /// bounds. Such indices only appear on places which correspond to undef values
  568. /// (see canReuseExtract for details) and used in order to avoid undef values
  569. /// have effect on operands ordering.
  570. /// The first loop below simply finds all unused indices and then the next loop
  571. /// nest assigns these indices for undef values positions.
  572. /// As an example below Order has two undef positions and they have assigned
  573. /// values 3 and 7 respectively:
  574. /// before: 6 9 5 4 9 2 1 0
  575. /// after: 6 3 5 4 7 2 1 0
  576. static void fixupOrderingIndices(SmallVectorImpl<unsigned> &Order) {
  577. const unsigned Sz = Order.size();
  578. SmallBitVector UnusedIndices(Sz, /*t=*/true);
  579. SmallBitVector MaskedIndices(Sz);
  580. for (unsigned I = 0; I < Sz; ++I) {
  581. if (Order[I] < Sz)
  582. UnusedIndices.reset(Order[I]);
  583. else
  584. MaskedIndices.set(I);
  585. }
  586. if (MaskedIndices.none())
  587. return;
  588. assert(UnusedIndices.count() == MaskedIndices.count() &&
  589. "Non-synced masked/available indices.");
  590. int Idx = UnusedIndices.find_first();
  591. int MIdx = MaskedIndices.find_first();
  592. while (MIdx >= 0) {
  593. assert(Idx >= 0 && "Indices must be synced.");
  594. Order[MIdx] = Idx;
  595. Idx = UnusedIndices.find_next(Idx);
  596. MIdx = MaskedIndices.find_next(MIdx);
  597. }
  598. }
  599. namespace llvm {
  600. static void inversePermutation(ArrayRef<unsigned> Indices,
  601. SmallVectorImpl<int> &Mask) {
  602. Mask.clear();
  603. const unsigned E = Indices.size();
  604. Mask.resize(E, UndefMaskElem);
  605. for (unsigned I = 0; I < E; ++I)
  606. Mask[Indices[I]] = I;
  607. }
  608. /// \returns inserting index of InsertElement or InsertValue instruction,
  609. /// using Offset as base offset for index.
  610. static Optional<unsigned> getInsertIndex(Value *InsertInst,
  611. unsigned Offset = 0) {
  612. int Index = Offset;
  613. if (auto *IE = dyn_cast<InsertElementInst>(InsertInst)) {
  614. if (auto *CI = dyn_cast<ConstantInt>(IE->getOperand(2))) {
  615. auto *VT = cast<FixedVectorType>(IE->getType());
  616. if (CI->getValue().uge(VT->getNumElements()))
  617. return None;
  618. Index *= VT->getNumElements();
  619. Index += CI->getZExtValue();
  620. return Index;
  621. }
  622. return None;
  623. }
  624. auto *IV = cast<InsertValueInst>(InsertInst);
  625. Type *CurrentType = IV->getType();
  626. for (unsigned I : IV->indices()) {
  627. if (auto *ST = dyn_cast<StructType>(CurrentType)) {
  628. Index *= ST->getNumElements();
  629. CurrentType = ST->getElementType(I);
  630. } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
  631. Index *= AT->getNumElements();
  632. CurrentType = AT->getElementType();
  633. } else {
  634. return None;
  635. }
  636. Index += I;
  637. }
  638. return Index;
  639. }
  640. /// Reorders the list of scalars in accordance with the given \p Order and then
  641. /// the \p Mask. \p Order - is the original order of the scalars, need to
  642. /// reorder scalars into an unordered state at first according to the given
  643. /// order. Then the ordered scalars are shuffled once again in accordance with
  644. /// the provided mask.
  645. static void reorderScalars(SmallVectorImpl<Value *> &Scalars,
  646. ArrayRef<int> Mask) {
  647. assert(!Mask.empty() && "Expected non-empty mask.");
  648. SmallVector<Value *> Prev(Scalars.size(),
  649. UndefValue::get(Scalars.front()->getType()));
  650. Prev.swap(Scalars);
  651. for (unsigned I = 0, E = Prev.size(); I < E; ++I)
  652. if (Mask[I] != UndefMaskElem)
  653. Scalars[Mask[I]] = Prev[I];
  654. }
  655. namespace slpvectorizer {
  656. /// Bottom Up SLP Vectorizer.
  657. class BoUpSLP {
  658. struct TreeEntry;
  659. struct ScheduleData;
  660. public:
  661. using ValueList = SmallVector<Value *, 8>;
  662. using InstrList = SmallVector<Instruction *, 16>;
  663. using ValueSet = SmallPtrSet<Value *, 16>;
  664. using StoreList = SmallVector<StoreInst *, 8>;
  665. using ExtraValueToDebugLocsMap =
  666. MapVector<Value *, SmallVector<Instruction *, 2>>;
  667. using OrdersType = SmallVector<unsigned, 4>;
  668. BoUpSLP(Function *Func, ScalarEvolution *Se, TargetTransformInfo *Tti,
  669. TargetLibraryInfo *TLi, AAResults *Aa, LoopInfo *Li,
  670. DominatorTree *Dt, AssumptionCache *AC, DemandedBits *DB,
  671. const DataLayout *DL, OptimizationRemarkEmitter *ORE)
  672. : F(Func), SE(Se), TTI(Tti), TLI(TLi), AA(Aa), LI(Li), DT(Dt), AC(AC),
  673. DB(DB), DL(DL), ORE(ORE), Builder(Se->getContext()) {
  674. CodeMetrics::collectEphemeralValues(F, AC, EphValues);
  675. // Use the vector register size specified by the target unless overridden
  676. // by a command-line option.
  677. // TODO: It would be better to limit the vectorization factor based on
  678. // data type rather than just register size. For example, x86 AVX has
  679. // 256-bit registers, but it does not support integer operations
  680. // at that width (that requires AVX2).
  681. if (MaxVectorRegSizeOption.getNumOccurrences())
  682. MaxVecRegSize = MaxVectorRegSizeOption;
  683. else
  684. MaxVecRegSize =
  685. TTI->getRegisterBitWidth(TargetTransformInfo::RGK_FixedWidthVector)
  686. .getFixedSize();
  687. if (MinVectorRegSizeOption.getNumOccurrences())
  688. MinVecRegSize = MinVectorRegSizeOption;
  689. else
  690. MinVecRegSize = TTI->getMinVectorRegisterBitWidth();
  691. }
  692. /// Vectorize the tree that starts with the elements in \p VL.
  693. /// Returns the vectorized root.
  694. Value *vectorizeTree();
  695. /// Vectorize the tree but with the list of externally used values \p
  696. /// ExternallyUsedValues. Values in this MapVector can be replaced but the
  697. /// generated extractvalue instructions.
  698. Value *vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues);
  699. /// \returns the cost incurred by unwanted spills and fills, caused by
  700. /// holding live values over call sites.
  701. InstructionCost getSpillCost() const;
  702. /// \returns the vectorization cost of the subtree that starts at \p VL.
  703. /// A negative number means that this is profitable.
  704. InstructionCost getTreeCost(ArrayRef<Value *> VectorizedVals = None);
  705. /// Construct a vectorizable tree that starts at \p Roots, ignoring users for
  706. /// the purpose of scheduling and extraction in the \p UserIgnoreLst.
  707. void buildTree(ArrayRef<Value *> Roots,
  708. ArrayRef<Value *> UserIgnoreLst = None);
  709. /// Builds external uses of the vectorized scalars, i.e. the list of
  710. /// vectorized scalars to be extracted, their lanes and their scalar users. \p
  711. /// ExternallyUsedValues contains additional list of external uses to handle
  712. /// vectorization of reductions.
  713. void
  714. buildExternalUses(const ExtraValueToDebugLocsMap &ExternallyUsedValues = {});
  715. /// Clear the internal data structures that are created by 'buildTree'.
  716. void deleteTree() {
  717. VectorizableTree.clear();
  718. ScalarToTreeEntry.clear();
  719. MustGather.clear();
  720. ExternalUses.clear();
  721. for (auto &Iter : BlocksSchedules) {
  722. BlockScheduling *BS = Iter.second.get();
  723. BS->clear();
  724. }
  725. MinBWs.clear();
  726. InstrElementSize.clear();
  727. }
  728. unsigned getTreeSize() const { return VectorizableTree.size(); }
  729. /// Perform LICM and CSE on the newly generated gather sequences.
  730. void optimizeGatherSequence();
  731. /// Checks if the specified gather tree entry \p TE can be represented as a
  732. /// shuffled vector entry + (possibly) permutation with other gathers. It
  733. /// implements the checks only for possibly ordered scalars (Loads,
  734. /// ExtractElement, ExtractValue), which can be part of the graph.
  735. Optional<OrdersType> findReusedOrderedScalars(const TreeEntry &TE);
  736. /// Gets reordering data for the given tree entry. If the entry is vectorized
  737. /// - just return ReorderIndices, otherwise check if the scalars can be
  738. /// reordered and return the most optimal order.
  739. /// \param TopToBottom If true, include the order of vectorized stores and
  740. /// insertelement nodes, otherwise skip them.
  741. Optional<OrdersType> getReorderingData(const TreeEntry &TE, bool TopToBottom);
  742. /// Reorders the current graph to the most profitable order starting from the
  743. /// root node to the leaf nodes. The best order is chosen only from the nodes
  744. /// of the same size (vectorization factor). Smaller nodes are considered
  745. /// parts of subgraph with smaller VF and they are reordered independently. We
  746. /// can make it because we still need to extend smaller nodes to the wider VF
  747. /// and we can merge reordering shuffles with the widening shuffles.
  748. void reorderTopToBottom();
  749. /// Reorders the current graph to the most profitable order starting from
  750. /// leaves to the root. It allows to rotate small subgraphs and reduce the
  751. /// number of reshuffles if the leaf nodes use the same order. In this case we
  752. /// can merge the orders and just shuffle user node instead of shuffling its
  753. /// operands. Plus, even the leaf nodes have different orders, it allows to
  754. /// sink reordering in the graph closer to the root node and merge it later
  755. /// during analysis.
  756. void reorderBottomToTop(bool IgnoreReorder = false);
  757. /// \return The vector element size in bits to use when vectorizing the
  758. /// expression tree ending at \p V. If V is a store, the size is the width of
  759. /// the stored value. Otherwise, the size is the width of the largest loaded
  760. /// value reaching V. This method is used by the vectorizer to calculate
  761. /// vectorization factors.
  762. unsigned getVectorElementSize(Value *V);
  763. /// Compute the minimum type sizes required to represent the entries in a
  764. /// vectorizable tree.
  765. void computeMinimumValueSizes();
  766. // \returns maximum vector register size as set by TTI or overridden by cl::opt.
  767. unsigned getMaxVecRegSize() const {
  768. return MaxVecRegSize;
  769. }
  770. // \returns minimum vector register size as set by cl::opt.
  771. unsigned getMinVecRegSize() const {
  772. return MinVecRegSize;
  773. }
  774. unsigned getMinVF(unsigned Sz) const {
  775. return std::max(2U, getMinVecRegSize() / Sz);
  776. }
  777. unsigned getMaximumVF(unsigned ElemWidth, unsigned Opcode) const {
  778. unsigned MaxVF = MaxVFOption.getNumOccurrences() ?
  779. MaxVFOption : TTI->getMaximumVF(ElemWidth, Opcode);
  780. return MaxVF ? MaxVF : UINT_MAX;
  781. }
  782. /// Check if homogeneous aggregate is isomorphic to some VectorType.
  783. /// Accepts homogeneous multidimensional aggregate of scalars/vectors like
  784. /// {[4 x i16], [4 x i16]}, { <2 x float>, <2 x float> },
  785. /// {{{i16, i16}, {i16, i16}}, {{i16, i16}, {i16, i16}}} and so on.
  786. ///
  787. /// \returns number of elements in vector if isomorphism exists, 0 otherwise.
  788. unsigned canMapToVector(Type *T, const DataLayout &DL) const;
  789. /// \returns True if the VectorizableTree is both tiny and not fully
  790. /// vectorizable. We do not vectorize such trees.
  791. bool isTreeTinyAndNotFullyVectorizable(bool ForReduction = false) const;
  792. /// Assume that a legal-sized 'or'-reduction of shifted/zexted loaded values
  793. /// can be load combined in the backend. Load combining may not be allowed in
  794. /// the IR optimizer, so we do not want to alter the pattern. For example,
  795. /// partially transforming a scalar bswap() pattern into vector code is
  796. /// effectively impossible for the backend to undo.
  797. /// TODO: If load combining is allowed in the IR optimizer, this analysis
  798. /// may not be necessary.
  799. bool isLoadCombineReductionCandidate(RecurKind RdxKind) const;
  800. /// Assume that a vector of stores of bitwise-or/shifted/zexted loaded values
  801. /// can be load combined in the backend. Load combining may not be allowed in
  802. /// the IR optimizer, so we do not want to alter the pattern. For example,
  803. /// partially transforming a scalar bswap() pattern into vector code is
  804. /// effectively impossible for the backend to undo.
  805. /// TODO: If load combining is allowed in the IR optimizer, this analysis
  806. /// may not be necessary.
  807. bool isLoadCombineCandidate() const;
  808. OptimizationRemarkEmitter *getORE() { return ORE; }
  809. /// This structure holds any data we need about the edges being traversed
  810. /// during buildTree_rec(). We keep track of:
  811. /// (i) the user TreeEntry index, and
  812. /// (ii) the index of the edge.
  813. struct EdgeInfo {
  814. EdgeInfo() = default;
  815. EdgeInfo(TreeEntry *UserTE, unsigned EdgeIdx)
  816. : UserTE(UserTE), EdgeIdx(EdgeIdx) {}
  817. /// The user TreeEntry.
  818. TreeEntry *UserTE = nullptr;
  819. /// The operand index of the use.
  820. unsigned EdgeIdx = UINT_MAX;
  821. #ifndef NDEBUG
  822. friend inline raw_ostream &operator<<(raw_ostream &OS,
  823. const BoUpSLP::EdgeInfo &EI) {
  824. EI.dump(OS);
  825. return OS;
  826. }
  827. /// Debug print.
  828. void dump(raw_ostream &OS) const {
  829. OS << "{User:" << (UserTE ? std::to_string(UserTE->Idx) : "null")
  830. << " EdgeIdx:" << EdgeIdx << "}";
  831. }
  832. LLVM_DUMP_METHOD void dump() const { dump(dbgs()); }
  833. #endif
  834. };
  835. /// A helper data structure to hold the operands of a vector of instructions.
  836. /// This supports a fixed vector length for all operand vectors.
  837. class VLOperands {
  838. /// For each operand we need (i) the value, and (ii) the opcode that it
  839. /// would be attached to if the expression was in a left-linearized form.
  840. /// This is required to avoid illegal operand reordering.
  841. /// For example:
  842. /// \verbatim
  843. /// 0 Op1
  844. /// |/
  845. /// Op1 Op2 Linearized + Op2
  846. /// \ / ----------> |/
  847. /// - -
  848. ///
  849. /// Op1 - Op2 (0 + Op1) - Op2
  850. /// \endverbatim
  851. ///
  852. /// Value Op1 is attached to a '+' operation, and Op2 to a '-'.
  853. ///
  854. /// Another way to think of this is to track all the operations across the
  855. /// path from the operand all the way to the root of the tree and to
  856. /// calculate the operation that corresponds to this path. For example, the
  857. /// path from Op2 to the root crosses the RHS of the '-', therefore the
  858. /// corresponding operation is a '-' (which matches the one in the
  859. /// linearized tree, as shown above).
  860. ///
  861. /// For lack of a better term, we refer to this operation as Accumulated
  862. /// Path Operation (APO).
  863. struct OperandData {
  864. OperandData() = default;
  865. OperandData(Value *V, bool APO, bool IsUsed)
  866. : V(V), APO(APO), IsUsed(IsUsed) {}
  867. /// The operand value.
  868. Value *V = nullptr;
  869. /// TreeEntries only allow a single opcode, or an alternate sequence of
  870. /// them (e.g, +, -). Therefore, we can safely use a boolean value for the
  871. /// APO. It is set to 'true' if 'V' is attached to an inverse operation
  872. /// in the left-linearized form (e.g., Sub/Div), and 'false' otherwise
  873. /// (e.g., Add/Mul)
  874. bool APO = false;
  875. /// Helper data for the reordering function.
  876. bool IsUsed = false;
  877. };
  878. /// During operand reordering, we are trying to select the operand at lane
  879. /// that matches best with the operand at the neighboring lane. Our
  880. /// selection is based on the type of value we are looking for. For example,
  881. /// if the neighboring lane has a load, we need to look for a load that is
  882. /// accessing a consecutive address. These strategies are summarized in the
  883. /// 'ReorderingMode' enumerator.
  884. enum class ReorderingMode {
  885. Load, ///< Matching loads to consecutive memory addresses
  886. Opcode, ///< Matching instructions based on opcode (same or alternate)
  887. Constant, ///< Matching constants
  888. Splat, ///< Matching the same instruction multiple times (broadcast)
  889. Failed, ///< We failed to create a vectorizable group
  890. };
  891. using OperandDataVec = SmallVector<OperandData, 2>;
  892. /// A vector of operand vectors.
  893. SmallVector<OperandDataVec, 4> OpsVec;
  894. const DataLayout &DL;
  895. ScalarEvolution &SE;
  896. const BoUpSLP &R;
  897. /// \returns the operand data at \p OpIdx and \p Lane.
  898. OperandData &getData(unsigned OpIdx, unsigned Lane) {
  899. return OpsVec[OpIdx][Lane];
  900. }
  901. /// \returns the operand data at \p OpIdx and \p Lane. Const version.
  902. const OperandData &getData(unsigned OpIdx, unsigned Lane) const {
  903. return OpsVec[OpIdx][Lane];
  904. }
  905. /// Clears the used flag for all entries.
  906. void clearUsed() {
  907. for (unsigned OpIdx = 0, NumOperands = getNumOperands();
  908. OpIdx != NumOperands; ++OpIdx)
  909. for (unsigned Lane = 0, NumLanes = getNumLanes(); Lane != NumLanes;
  910. ++Lane)
  911. OpsVec[OpIdx][Lane].IsUsed = false;
  912. }
  913. /// Swap the operand at \p OpIdx1 with that one at \p OpIdx2.
  914. void swap(unsigned OpIdx1, unsigned OpIdx2, unsigned Lane) {
  915. std::swap(OpsVec[OpIdx1][Lane], OpsVec[OpIdx2][Lane]);
  916. }
  917. // The hard-coded scores listed here are not very important, though it shall
  918. // be higher for better matches to improve the resulting cost. When
  919. // computing the scores of matching one sub-tree with another, we are
  920. // basically counting the number of values that are matching. So even if all
  921. // scores are set to 1, we would still get a decent matching result.
  922. // However, sometimes we have to break ties. For example we may have to
  923. // choose between matching loads vs matching opcodes. This is what these
  924. // scores are helping us with: they provide the order of preference. Also,
  925. // this is important if the scalar is externally used or used in another
  926. // tree entry node in the different lane.
  927. /// Loads from consecutive memory addresses, e.g. load(A[i]), load(A[i+1]).
  928. static const int ScoreConsecutiveLoads = 4;
  929. /// Loads from reversed memory addresses, e.g. load(A[i+1]), load(A[i]).
  930. static const int ScoreReversedLoads = 3;
  931. /// ExtractElementInst from same vector and consecutive indexes.
  932. static const int ScoreConsecutiveExtracts = 4;
  933. /// ExtractElementInst from same vector and reversed indices.
  934. static const int ScoreReversedExtracts = 3;
  935. /// Constants.
  936. static const int ScoreConstants = 2;
  937. /// Instructions with the same opcode.
  938. static const int ScoreSameOpcode = 2;
  939. /// Instructions with alt opcodes (e.g, add + sub).
  940. static const int ScoreAltOpcodes = 1;
  941. /// Identical instructions (a.k.a. splat or broadcast).
  942. static const int ScoreSplat = 1;
  943. /// Matching with an undef is preferable to failing.
  944. static const int ScoreUndef = 1;
  945. /// Score for failing to find a decent match.
  946. static const int ScoreFail = 0;
  947. /// User exteranl to the vectorized code.
  948. static const int ExternalUseCost = 1;
  949. /// The user is internal but in a different lane.
  950. static const int UserInDiffLaneCost = ExternalUseCost;
  951. /// \returns the score of placing \p V1 and \p V2 in consecutive lanes.
  952. static int getShallowScore(Value *V1, Value *V2, const DataLayout &DL,
  953. ScalarEvolution &SE, int NumLanes) {
  954. if (V1 == V2)
  955. return VLOperands::ScoreSplat;
  956. auto *LI1 = dyn_cast<LoadInst>(V1);
  957. auto *LI2 = dyn_cast<LoadInst>(V2);
  958. if (LI1 && LI2) {
  959. if (LI1->getParent() != LI2->getParent())
  960. return VLOperands::ScoreFail;
  961. Optional<int> Dist = getPointersDiff(
  962. LI1->getType(), LI1->getPointerOperand(), LI2->getType(),
  963. LI2->getPointerOperand(), DL, SE, /*StrictCheck=*/true);
  964. if (!Dist)
  965. return VLOperands::ScoreFail;
  966. // The distance is too large - still may be profitable to use masked
  967. // loads/gathers.
  968. if (std::abs(*Dist) > NumLanes / 2)
  969. return VLOperands::ScoreAltOpcodes;
  970. // This still will detect consecutive loads, but we might have "holes"
  971. // in some cases. It is ok for non-power-2 vectorization and may produce
  972. // better results. It should not affect current vectorization.
  973. return (*Dist > 0) ? VLOperands::ScoreConsecutiveLoads
  974. : VLOperands::ScoreReversedLoads;
  975. }
  976. auto *C1 = dyn_cast<Constant>(V1);
  977. auto *C2 = dyn_cast<Constant>(V2);
  978. if (C1 && C2)
  979. return VLOperands::ScoreConstants;
  980. // Extracts from consecutive indexes of the same vector better score as
  981. // the extracts could be optimized away.
  982. Value *EV1;
  983. ConstantInt *Ex1Idx;
  984. if (match(V1, m_ExtractElt(m_Value(EV1), m_ConstantInt(Ex1Idx)))) {
  985. // Undefs are always profitable for extractelements.
  986. if (isa<UndefValue>(V2))
  987. return VLOperands::ScoreConsecutiveExtracts;
  988. Value *EV2 = nullptr;
  989. ConstantInt *Ex2Idx = nullptr;
  990. if (match(V2,
  991. m_ExtractElt(m_Value(EV2), m_CombineOr(m_ConstantInt(Ex2Idx),
  992. m_Undef())))) {
  993. // Undefs are always profitable for extractelements.
  994. if (!Ex2Idx)
  995. return VLOperands::ScoreConsecutiveExtracts;
  996. if (isUndefVector(EV2) && EV2->getType() == EV1->getType())
  997. return VLOperands::ScoreConsecutiveExtracts;
  998. if (EV2 == EV1) {
  999. int Idx1 = Ex1Idx->getZExtValue();
  1000. int Idx2 = Ex2Idx->getZExtValue();
  1001. int Dist = Idx2 - Idx1;
  1002. // The distance is too large - still may be profitable to use
  1003. // shuffles.
  1004. if (std::abs(Dist) > NumLanes / 2)
  1005. return VLOperands::ScoreAltOpcodes;
  1006. return (Dist > 0) ? VLOperands::ScoreConsecutiveExtracts
  1007. : VLOperands::ScoreReversedExtracts;
  1008. }
  1009. }
  1010. }
  1011. auto *I1 = dyn_cast<Instruction>(V1);
  1012. auto *I2 = dyn_cast<Instruction>(V2);
  1013. if (I1 && I2) {
  1014. if (I1->getParent() != I2->getParent())
  1015. return VLOperands::ScoreFail;
  1016. InstructionsState S = getSameOpcode({I1, I2});
  1017. // Note: Only consider instructions with <= 2 operands to avoid
  1018. // complexity explosion.
  1019. if (S.getOpcode() && S.MainOp->getNumOperands() <= 2)
  1020. return S.isAltShuffle() ? VLOperands::ScoreAltOpcodes
  1021. : VLOperands::ScoreSameOpcode;
  1022. }
  1023. if (isa<UndefValue>(V2))
  1024. return VLOperands::ScoreUndef;
  1025. return VLOperands::ScoreFail;
  1026. }
  1027. /// Holds the values and their lanes that are taking part in the look-ahead
  1028. /// score calculation. This is used in the external uses cost calculation.
  1029. /// Need to hold all the lanes in case of splat/broadcast at least to
  1030. /// correctly check for the use in the different lane.
  1031. SmallDenseMap<Value *, SmallSet<int, 4>> InLookAheadValues;
  1032. /// \returns the additional cost due to uses of \p LHS and \p RHS that are
  1033. /// either external to the vectorized code, or require shuffling.
  1034. int getExternalUsesCost(const std::pair<Value *, int> &LHS,
  1035. const std::pair<Value *, int> &RHS) {
  1036. int Cost = 0;
  1037. std::array<std::pair<Value *, int>, 2> Values = {{LHS, RHS}};
  1038. for (int Idx = 0, IdxE = Values.size(); Idx != IdxE; ++Idx) {
  1039. Value *V = Values[Idx].first;
  1040. if (isa<Constant>(V)) {
  1041. // Since this is a function pass, it doesn't make semantic sense to
  1042. // walk the users of a subclass of Constant. The users could be in
  1043. // another function, or even another module that happens to be in
  1044. // the same LLVMContext.
  1045. continue;
  1046. }
  1047. // Calculate the absolute lane, using the minimum relative lane of LHS
  1048. // and RHS as base and Idx as the offset.
  1049. int Ln = std::min(LHS.second, RHS.second) + Idx;
  1050. assert(Ln >= 0 && "Bad lane calculation");
  1051. unsigned UsersBudget = LookAheadUsersBudget;
  1052. for (User *U : V->users()) {
  1053. if (const TreeEntry *UserTE = R.getTreeEntry(U)) {
  1054. // The user is in the VectorizableTree. Check if we need to insert.
  1055. int UserLn = UserTE->findLaneForValue(U);
  1056. assert(UserLn >= 0 && "Bad lane");
  1057. // If the values are different, check just the line of the current
  1058. // value. If the values are the same, need to add UserInDiffLaneCost
  1059. // only if UserLn does not match both line numbers.
  1060. if ((LHS.first != RHS.first && UserLn != Ln) ||
  1061. (LHS.first == RHS.first && UserLn != LHS.second &&
  1062. UserLn != RHS.second)) {
  1063. Cost += UserInDiffLaneCost;
  1064. break;
  1065. }
  1066. } else {
  1067. // Check if the user is in the look-ahead code.
  1068. auto It2 = InLookAheadValues.find(U);
  1069. if (It2 != InLookAheadValues.end()) {
  1070. // The user is in the look-ahead code. Check the lane.
  1071. if (!It2->getSecond().contains(Ln)) {
  1072. Cost += UserInDiffLaneCost;
  1073. break;
  1074. }
  1075. } else {
  1076. // The user is neither in SLP tree nor in the look-ahead code.
  1077. Cost += ExternalUseCost;
  1078. break;
  1079. }
  1080. }
  1081. // Limit the number of visited uses to cap compilation time.
  1082. if (--UsersBudget == 0)
  1083. break;
  1084. }
  1085. }
  1086. return Cost;
  1087. }
  1088. /// Go through the operands of \p LHS and \p RHS recursively until \p
  1089. /// MaxLevel, and return the cummulative score. For example:
  1090. /// \verbatim
  1091. /// A[0] B[0] A[1] B[1] C[0] D[0] B[1] A[1]
  1092. /// \ / \ / \ / \ /
  1093. /// + + + +
  1094. /// G1 G2 G3 G4
  1095. /// \endverbatim
  1096. /// The getScoreAtLevelRec(G1, G2) function will try to match the nodes at
  1097. /// each level recursively, accumulating the score. It starts from matching
  1098. /// the additions at level 0, then moves on to the loads (level 1). The
  1099. /// score of G1 and G2 is higher than G1 and G3, because {A[0],A[1]} and
  1100. /// {B[0],B[1]} match with VLOperands::ScoreConsecutiveLoads, while
  1101. /// {A[0],C[0]} has a score of VLOperands::ScoreFail.
  1102. /// Please note that the order of the operands does not matter, as we
  1103. /// evaluate the score of all profitable combinations of operands. In
  1104. /// other words the score of G1 and G4 is the same as G1 and G2. This
  1105. /// heuristic is based on ideas described in:
  1106. /// Look-ahead SLP: Auto-vectorization in the presence of commutative
  1107. /// operations, CGO 2018 by Vasileios Porpodas, Rodrigo C. O. Rocha,
  1108. /// Luís F. W. Góes
  1109. int getScoreAtLevelRec(const std::pair<Value *, int> &LHS,
  1110. const std::pair<Value *, int> &RHS, int CurrLevel,
  1111. int MaxLevel) {
  1112. Value *V1 = LHS.first;
  1113. Value *V2 = RHS.first;
  1114. // Get the shallow score of V1 and V2.
  1115. int ShallowScoreAtThisLevel = std::max(
  1116. (int)ScoreFail, getShallowScore(V1, V2, DL, SE, getNumLanes()) -
  1117. getExternalUsesCost(LHS, RHS));
  1118. int Lane1 = LHS.second;
  1119. int Lane2 = RHS.second;
  1120. // If reached MaxLevel,
  1121. // or if V1 and V2 are not instructions,
  1122. // or if they are SPLAT,
  1123. // or if they are not consecutive,
  1124. // or if profitable to vectorize loads or extractelements, early return
  1125. // the current cost.
  1126. auto *I1 = dyn_cast<Instruction>(V1);
  1127. auto *I2 = dyn_cast<Instruction>(V2);
  1128. if (CurrLevel == MaxLevel || !(I1 && I2) || I1 == I2 ||
  1129. ShallowScoreAtThisLevel == VLOperands::ScoreFail ||
  1130. (((isa<LoadInst>(I1) && isa<LoadInst>(I2)) ||
  1131. (isa<ExtractElementInst>(I1) && isa<ExtractElementInst>(I2))) &&
  1132. ShallowScoreAtThisLevel))
  1133. return ShallowScoreAtThisLevel;
  1134. assert(I1 && I2 && "Should have early exited.");
  1135. // Keep track of in-tree values for determining the external-use cost.
  1136. InLookAheadValues[V1].insert(Lane1);
  1137. InLookAheadValues[V2].insert(Lane2);
  1138. // Contains the I2 operand indexes that got matched with I1 operands.
  1139. SmallSet<unsigned, 4> Op2Used;
  1140. // Recursion towards the operands of I1 and I2. We are trying all possible
  1141. // operand pairs, and keeping track of the best score.
  1142. for (unsigned OpIdx1 = 0, NumOperands1 = I1->getNumOperands();
  1143. OpIdx1 != NumOperands1; ++OpIdx1) {
  1144. // Try to pair op1I with the best operand of I2.
  1145. int MaxTmpScore = 0;
  1146. unsigned MaxOpIdx2 = 0;
  1147. bool FoundBest = false;
  1148. // If I2 is commutative try all combinations.
  1149. unsigned FromIdx = isCommutative(I2) ? 0 : OpIdx1;
  1150. unsigned ToIdx = isCommutative(I2)
  1151. ? I2->getNumOperands()
  1152. : std::min(I2->getNumOperands(), OpIdx1 + 1);
  1153. assert(FromIdx <= ToIdx && "Bad index");
  1154. for (unsigned OpIdx2 = FromIdx; OpIdx2 != ToIdx; ++OpIdx2) {
  1155. // Skip operands already paired with OpIdx1.
  1156. if (Op2Used.count(OpIdx2))
  1157. continue;
  1158. // Recursively calculate the cost at each level
  1159. int TmpScore = getScoreAtLevelRec({I1->getOperand(OpIdx1), Lane1},
  1160. {I2->getOperand(OpIdx2), Lane2},
  1161. CurrLevel + 1, MaxLevel);
  1162. // Look for the best score.
  1163. if (TmpScore > VLOperands::ScoreFail && TmpScore > MaxTmpScore) {
  1164. MaxTmpScore = TmpScore;
  1165. MaxOpIdx2 = OpIdx2;
  1166. FoundBest = true;
  1167. }
  1168. }
  1169. if (FoundBest) {
  1170. // Pair {OpIdx1, MaxOpIdx2} was found to be best. Never revisit it.
  1171. Op2Used.insert(MaxOpIdx2);
  1172. ShallowScoreAtThisLevel += MaxTmpScore;
  1173. }
  1174. }
  1175. return ShallowScoreAtThisLevel;
  1176. }
  1177. /// \Returns the look-ahead score, which tells us how much the sub-trees
  1178. /// rooted at \p LHS and \p RHS match, the more they match the higher the
  1179. /// score. This helps break ties in an informed way when we cannot decide on
  1180. /// the order of the operands by just considering the immediate
  1181. /// predecessors.
  1182. int getLookAheadScore(const std::pair<Value *, int> &LHS,
  1183. const std::pair<Value *, int> &RHS) {
  1184. InLookAheadValues.clear();
  1185. return getScoreAtLevelRec(LHS, RHS, 1, LookAheadMaxDepth);
  1186. }
  1187. // Search all operands in Ops[*][Lane] for the one that matches best
  1188. // Ops[OpIdx][LastLane] and return its opreand index.
  1189. // If no good match can be found, return None.
  1190. Optional<unsigned>
  1191. getBestOperand(unsigned OpIdx, int Lane, int LastLane,
  1192. ArrayRef<ReorderingMode> ReorderingModes) {
  1193. unsigned NumOperands = getNumOperands();
  1194. // The operand of the previous lane at OpIdx.
  1195. Value *OpLastLane = getData(OpIdx, LastLane).V;
  1196. // Our strategy mode for OpIdx.
  1197. ReorderingMode RMode = ReorderingModes[OpIdx];
  1198. // The linearized opcode of the operand at OpIdx, Lane.
  1199. bool OpIdxAPO = getData(OpIdx, Lane).APO;
  1200. // The best operand index and its score.
  1201. // Sometimes we have more than one option (e.g., Opcode and Undefs), so we
  1202. // are using the score to differentiate between the two.
  1203. struct BestOpData {
  1204. Optional<unsigned> Idx = None;
  1205. unsigned Score = 0;
  1206. } BestOp;
  1207. // Iterate through all unused operands and look for the best.
  1208. for (unsigned Idx = 0; Idx != NumOperands; ++Idx) {
  1209. // Get the operand at Idx and Lane.
  1210. OperandData &OpData = getData(Idx, Lane);
  1211. Value *Op = OpData.V;
  1212. bool OpAPO = OpData.APO;
  1213. // Skip already selected operands.
  1214. if (OpData.IsUsed)
  1215. continue;
  1216. // Skip if we are trying to move the operand to a position with a
  1217. // different opcode in the linearized tree form. This would break the
  1218. // semantics.
  1219. if (OpAPO != OpIdxAPO)
  1220. continue;
  1221. // Look for an operand that matches the current mode.
  1222. switch (RMode) {
  1223. case ReorderingMode::Load:
  1224. case ReorderingMode::Constant:
  1225. case ReorderingMode::Opcode: {
  1226. bool LeftToRight = Lane > LastLane;
  1227. Value *OpLeft = (LeftToRight) ? OpLastLane : Op;
  1228. Value *OpRight = (LeftToRight) ? Op : OpLastLane;
  1229. unsigned Score =
  1230. getLookAheadScore({OpLeft, LastLane}, {OpRight, Lane});
  1231. if (Score > BestOp.Score) {
  1232. BestOp.Idx = Idx;
  1233. BestOp.Score = Score;
  1234. }
  1235. break;
  1236. }
  1237. case ReorderingMode::Splat:
  1238. if (Op == OpLastLane)
  1239. BestOp.Idx = Idx;
  1240. break;
  1241. case ReorderingMode::Failed:
  1242. return None;
  1243. }
  1244. }
  1245. if (BestOp.Idx) {
  1246. getData(BestOp.Idx.getValue(), Lane).IsUsed = true;
  1247. return BestOp.Idx;
  1248. }
  1249. // If we could not find a good match return None.
  1250. return None;
  1251. }
  1252. /// Helper for reorderOperandVecs.
  1253. /// \returns the lane that we should start reordering from. This is the one
  1254. /// which has the least number of operands that can freely move about or
  1255. /// less profitable because it already has the most optimal set of operands.
  1256. unsigned getBestLaneToStartReordering() const {
  1257. unsigned Min = UINT_MAX;
  1258. unsigned SameOpNumber = 0;
  1259. // std::pair<unsigned, unsigned> is used to implement a simple voting
  1260. // algorithm and choose the lane with the least number of operands that
  1261. // can freely move about or less profitable because it already has the
  1262. // most optimal set of operands. The first unsigned is a counter for
  1263. // voting, the second unsigned is the counter of lanes with instructions
  1264. // with same/alternate opcodes and same parent basic block.
  1265. MapVector<unsigned, std::pair<unsigned, unsigned>> HashMap;
  1266. // Try to be closer to the original results, if we have multiple lanes
  1267. // with same cost. If 2 lanes have the same cost, use the one with the
  1268. // lowest index.
  1269. for (int I = getNumLanes(); I > 0; --I) {
  1270. unsigned Lane = I - 1;
  1271. OperandsOrderData NumFreeOpsHash =
  1272. getMaxNumOperandsThatCanBeReordered(Lane);
  1273. // Compare the number of operands that can move and choose the one with
  1274. // the least number.
  1275. if (NumFreeOpsHash.NumOfAPOs < Min) {
  1276. Min = NumFreeOpsHash.NumOfAPOs;
  1277. SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
  1278. HashMap.clear();
  1279. HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
  1280. } else if (NumFreeOpsHash.NumOfAPOs == Min &&
  1281. NumFreeOpsHash.NumOpsWithSameOpcodeParent < SameOpNumber) {
  1282. // Select the most optimal lane in terms of number of operands that
  1283. // should be moved around.
  1284. SameOpNumber = NumFreeOpsHash.NumOpsWithSameOpcodeParent;
  1285. HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
  1286. } else if (NumFreeOpsHash.NumOfAPOs == Min &&
  1287. NumFreeOpsHash.NumOpsWithSameOpcodeParent == SameOpNumber) {
  1288. auto It = HashMap.find(NumFreeOpsHash.Hash);
  1289. if (It == HashMap.end())
  1290. HashMap[NumFreeOpsHash.Hash] = std::make_pair(1, Lane);
  1291. else
  1292. ++It->second.first;
  1293. }
  1294. }
  1295. // Select the lane with the minimum counter.
  1296. unsigned BestLane = 0;
  1297. unsigned CntMin = UINT_MAX;
  1298. for (const auto &Data : reverse(HashMap)) {
  1299. if (Data.second.first < CntMin) {
  1300. CntMin = Data.second.first;
  1301. BestLane = Data.second.second;
  1302. }
  1303. }
  1304. return BestLane;
  1305. }
  1306. /// Data structure that helps to reorder operands.
  1307. struct OperandsOrderData {
  1308. /// The best number of operands with the same APOs, which can be
  1309. /// reordered.
  1310. unsigned NumOfAPOs = UINT_MAX;
  1311. /// Number of operands with the same/alternate instruction opcode and
  1312. /// parent.
  1313. unsigned NumOpsWithSameOpcodeParent = 0;
  1314. /// Hash for the actual operands ordering.
  1315. /// Used to count operands, actually their position id and opcode
  1316. /// value. It is used in the voting mechanism to find the lane with the
  1317. /// least number of operands that can freely move about or less profitable
  1318. /// because it already has the most optimal set of operands. Can be
  1319. /// replaced with SmallVector<unsigned> instead but hash code is faster
  1320. /// and requires less memory.
  1321. unsigned Hash = 0;
  1322. };
  1323. /// \returns the maximum number of operands that are allowed to be reordered
  1324. /// for \p Lane and the number of compatible instructions(with the same
  1325. /// parent/opcode). This is used as a heuristic for selecting the first lane
  1326. /// to start operand reordering.
  1327. OperandsOrderData getMaxNumOperandsThatCanBeReordered(unsigned Lane) const {
  1328. unsigned CntTrue = 0;
  1329. unsigned NumOperands = getNumOperands();
  1330. // Operands with the same APO can be reordered. We therefore need to count
  1331. // how many of them we have for each APO, like this: Cnt[APO] = x.
  1332. // Since we only have two APOs, namely true and false, we can avoid using
  1333. // a map. Instead we can simply count the number of operands that
  1334. // correspond to one of them (in this case the 'true' APO), and calculate
  1335. // the other by subtracting it from the total number of operands.
  1336. // Operands with the same instruction opcode and parent are more
  1337. // profitable since we don't need to move them in many cases, with a high
  1338. // probability such lane already can be vectorized effectively.
  1339. bool AllUndefs = true;
  1340. unsigned NumOpsWithSameOpcodeParent = 0;
  1341. Instruction *OpcodeI = nullptr;
  1342. BasicBlock *Parent = nullptr;
  1343. unsigned Hash = 0;
  1344. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1345. const OperandData &OpData = getData(OpIdx, Lane);
  1346. if (OpData.APO)
  1347. ++CntTrue;
  1348. // Use Boyer-Moore majority voting for finding the majority opcode and
  1349. // the number of times it occurs.
  1350. if (auto *I = dyn_cast<Instruction>(OpData.V)) {
  1351. if (!OpcodeI || !getSameOpcode({OpcodeI, I}).getOpcode() ||
  1352. I->getParent() != Parent) {
  1353. if (NumOpsWithSameOpcodeParent == 0) {
  1354. NumOpsWithSameOpcodeParent = 1;
  1355. OpcodeI = I;
  1356. Parent = I->getParent();
  1357. } else {
  1358. --NumOpsWithSameOpcodeParent;
  1359. }
  1360. } else {
  1361. ++NumOpsWithSameOpcodeParent;
  1362. }
  1363. }
  1364. Hash = hash_combine(
  1365. Hash, hash_value((OpIdx + 1) * (OpData.V->getValueID() + 1)));
  1366. AllUndefs = AllUndefs && isa<UndefValue>(OpData.V);
  1367. }
  1368. if (AllUndefs)
  1369. return {};
  1370. OperandsOrderData Data;
  1371. Data.NumOfAPOs = std::max(CntTrue, NumOperands - CntTrue);
  1372. Data.NumOpsWithSameOpcodeParent = NumOpsWithSameOpcodeParent;
  1373. Data.Hash = Hash;
  1374. return Data;
  1375. }
  1376. /// Go through the instructions in VL and append their operands.
  1377. void appendOperandsOfVL(ArrayRef<Value *> VL) {
  1378. assert(!VL.empty() && "Bad VL");
  1379. assert((empty() || VL.size() == getNumLanes()) &&
  1380. "Expected same number of lanes");
  1381. assert(isa<Instruction>(VL[0]) && "Expected instruction");
  1382. unsigned NumOperands = cast<Instruction>(VL[0])->getNumOperands();
  1383. OpsVec.resize(NumOperands);
  1384. unsigned NumLanes = VL.size();
  1385. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1386. OpsVec[OpIdx].resize(NumLanes);
  1387. for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
  1388. assert(isa<Instruction>(VL[Lane]) && "Expected instruction");
  1389. // Our tree has just 3 nodes: the root and two operands.
  1390. // It is therefore trivial to get the APO. We only need to check the
  1391. // opcode of VL[Lane] and whether the operand at OpIdx is the LHS or
  1392. // RHS operand. The LHS operand of both add and sub is never attached
  1393. // to an inversese operation in the linearized form, therefore its APO
  1394. // is false. The RHS is true only if VL[Lane] is an inverse operation.
  1395. // Since operand reordering is performed on groups of commutative
  1396. // operations or alternating sequences (e.g., +, -), we can safely
  1397. // tell the inverse operations by checking commutativity.
  1398. bool IsInverseOperation = !isCommutative(cast<Instruction>(VL[Lane]));
  1399. bool APO = (OpIdx == 0) ? false : IsInverseOperation;
  1400. OpsVec[OpIdx][Lane] = {cast<Instruction>(VL[Lane])->getOperand(OpIdx),
  1401. APO, false};
  1402. }
  1403. }
  1404. }
  1405. /// \returns the number of operands.
  1406. unsigned getNumOperands() const { return OpsVec.size(); }
  1407. /// \returns the number of lanes.
  1408. unsigned getNumLanes() const { return OpsVec[0].size(); }
  1409. /// \returns the operand value at \p OpIdx and \p Lane.
  1410. Value *getValue(unsigned OpIdx, unsigned Lane) const {
  1411. return getData(OpIdx, Lane).V;
  1412. }
  1413. /// \returns true if the data structure is empty.
  1414. bool empty() const { return OpsVec.empty(); }
  1415. /// Clears the data.
  1416. void clear() { OpsVec.clear(); }
  1417. /// \Returns true if there are enough operands identical to \p Op to fill
  1418. /// the whole vector.
  1419. /// Note: This modifies the 'IsUsed' flag, so a cleanUsed() must follow.
  1420. bool shouldBroadcast(Value *Op, unsigned OpIdx, unsigned Lane) {
  1421. bool OpAPO = getData(OpIdx, Lane).APO;
  1422. for (unsigned Ln = 0, Lns = getNumLanes(); Ln != Lns; ++Ln) {
  1423. if (Ln == Lane)
  1424. continue;
  1425. // This is set to true if we found a candidate for broadcast at Lane.
  1426. bool FoundCandidate = false;
  1427. for (unsigned OpI = 0, OpE = getNumOperands(); OpI != OpE; ++OpI) {
  1428. OperandData &Data = getData(OpI, Ln);
  1429. if (Data.APO != OpAPO || Data.IsUsed)
  1430. continue;
  1431. if (Data.V == Op) {
  1432. FoundCandidate = true;
  1433. Data.IsUsed = true;
  1434. break;
  1435. }
  1436. }
  1437. if (!FoundCandidate)
  1438. return false;
  1439. }
  1440. return true;
  1441. }
  1442. public:
  1443. /// Initialize with all the operands of the instruction vector \p RootVL.
  1444. VLOperands(ArrayRef<Value *> RootVL, const DataLayout &DL,
  1445. ScalarEvolution &SE, const BoUpSLP &R)
  1446. : DL(DL), SE(SE), R(R) {
  1447. // Append all the operands of RootVL.
  1448. appendOperandsOfVL(RootVL);
  1449. }
  1450. /// \Returns a value vector with the operands across all lanes for the
  1451. /// opearnd at \p OpIdx.
  1452. ValueList getVL(unsigned OpIdx) const {
  1453. ValueList OpVL(OpsVec[OpIdx].size());
  1454. assert(OpsVec[OpIdx].size() == getNumLanes() &&
  1455. "Expected same num of lanes across all operands");
  1456. for (unsigned Lane = 0, Lanes = getNumLanes(); Lane != Lanes; ++Lane)
  1457. OpVL[Lane] = OpsVec[OpIdx][Lane].V;
  1458. return OpVL;
  1459. }
  1460. // Performs operand reordering for 2 or more operands.
  1461. // The original operands are in OrigOps[OpIdx][Lane].
  1462. // The reordered operands are returned in 'SortedOps[OpIdx][Lane]'.
  1463. void reorder() {
  1464. unsigned NumOperands = getNumOperands();
  1465. unsigned NumLanes = getNumLanes();
  1466. // Each operand has its own mode. We are using this mode to help us select
  1467. // the instructions for each lane, so that they match best with the ones
  1468. // we have selected so far.
  1469. SmallVector<ReorderingMode, 2> ReorderingModes(NumOperands);
  1470. // This is a greedy single-pass algorithm. We are going over each lane
  1471. // once and deciding on the best order right away with no back-tracking.
  1472. // However, in order to increase its effectiveness, we start with the lane
  1473. // that has operands that can move the least. For example, given the
  1474. // following lanes:
  1475. // Lane 0 : A[0] = B[0] + C[0] // Visited 3rd
  1476. // Lane 1 : A[1] = C[1] - B[1] // Visited 1st
  1477. // Lane 2 : A[2] = B[2] + C[2] // Visited 2nd
  1478. // Lane 3 : A[3] = C[3] - B[3] // Visited 4th
  1479. // we will start at Lane 1, since the operands of the subtraction cannot
  1480. // be reordered. Then we will visit the rest of the lanes in a circular
  1481. // fashion. That is, Lanes 2, then Lane 0, and finally Lane 3.
  1482. // Find the first lane that we will start our search from.
  1483. unsigned FirstLane = getBestLaneToStartReordering();
  1484. // Initialize the modes.
  1485. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1486. Value *OpLane0 = getValue(OpIdx, FirstLane);
  1487. // Keep track if we have instructions with all the same opcode on one
  1488. // side.
  1489. if (isa<LoadInst>(OpLane0))
  1490. ReorderingModes[OpIdx] = ReorderingMode::Load;
  1491. else if (isa<Instruction>(OpLane0)) {
  1492. // Check if OpLane0 should be broadcast.
  1493. if (shouldBroadcast(OpLane0, OpIdx, FirstLane))
  1494. ReorderingModes[OpIdx] = ReorderingMode::Splat;
  1495. else
  1496. ReorderingModes[OpIdx] = ReorderingMode::Opcode;
  1497. }
  1498. else if (isa<Constant>(OpLane0))
  1499. ReorderingModes[OpIdx] = ReorderingMode::Constant;
  1500. else if (isa<Argument>(OpLane0))
  1501. // Our best hope is a Splat. It may save some cost in some cases.
  1502. ReorderingModes[OpIdx] = ReorderingMode::Splat;
  1503. else
  1504. // NOTE: This should be unreachable.
  1505. ReorderingModes[OpIdx] = ReorderingMode::Failed;
  1506. }
  1507. // Check that we don't have same operands. No need to reorder if operands
  1508. // are just perfect diamond or shuffled diamond match. Do not do it only
  1509. // for possible broadcasts or non-power of 2 number of scalars (just for
  1510. // now).
  1511. auto &&SkipReordering = [this]() {
  1512. SmallPtrSet<Value *, 4> UniqueValues;
  1513. ArrayRef<OperandData> Op0 = OpsVec.front();
  1514. for (const OperandData &Data : Op0)
  1515. UniqueValues.insert(Data.V);
  1516. for (ArrayRef<OperandData> Op : drop_begin(OpsVec, 1)) {
  1517. if (any_of(Op, [&UniqueValues](const OperandData &Data) {
  1518. return !UniqueValues.contains(Data.V);
  1519. }))
  1520. return false;
  1521. }
  1522. // TODO: Check if we can remove a check for non-power-2 number of
  1523. // scalars after full support of non-power-2 vectorization.
  1524. return UniqueValues.size() != 2 && isPowerOf2_32(UniqueValues.size());
  1525. };
  1526. // If the initial strategy fails for any of the operand indexes, then we
  1527. // perform reordering again in a second pass. This helps avoid assigning
  1528. // high priority to the failed strategy, and should improve reordering for
  1529. // the non-failed operand indexes.
  1530. for (int Pass = 0; Pass != 2; ++Pass) {
  1531. // Check if no need to reorder operands since they're are perfect or
  1532. // shuffled diamond match.
  1533. // Need to to do it to avoid extra external use cost counting for
  1534. // shuffled matches, which may cause regressions.
  1535. if (SkipReordering())
  1536. break;
  1537. // Skip the second pass if the first pass did not fail.
  1538. bool StrategyFailed = false;
  1539. // Mark all operand data as free to use.
  1540. clearUsed();
  1541. // We keep the original operand order for the FirstLane, so reorder the
  1542. // rest of the lanes. We are visiting the nodes in a circular fashion,
  1543. // using FirstLane as the center point and increasing the radius
  1544. // distance.
  1545. for (unsigned Distance = 1; Distance != NumLanes; ++Distance) {
  1546. // Visit the lane on the right and then the lane on the left.
  1547. for (int Direction : {+1, -1}) {
  1548. int Lane = FirstLane + Direction * Distance;
  1549. if (Lane < 0 || Lane >= (int)NumLanes)
  1550. continue;
  1551. int LastLane = Lane - Direction;
  1552. assert(LastLane >= 0 && LastLane < (int)NumLanes &&
  1553. "Out of bounds");
  1554. // Look for a good match for each operand.
  1555. for (unsigned OpIdx = 0; OpIdx != NumOperands; ++OpIdx) {
  1556. // Search for the operand that matches SortedOps[OpIdx][Lane-1].
  1557. Optional<unsigned> BestIdx =
  1558. getBestOperand(OpIdx, Lane, LastLane, ReorderingModes);
  1559. // By not selecting a value, we allow the operands that follow to
  1560. // select a better matching value. We will get a non-null value in
  1561. // the next run of getBestOperand().
  1562. if (BestIdx) {
  1563. // Swap the current operand with the one returned by
  1564. // getBestOperand().
  1565. swap(OpIdx, BestIdx.getValue(), Lane);
  1566. } else {
  1567. // We failed to find a best operand, set mode to 'Failed'.
  1568. ReorderingModes[OpIdx] = ReorderingMode::Failed;
  1569. // Enable the second pass.
  1570. StrategyFailed = true;
  1571. }
  1572. }
  1573. }
  1574. }
  1575. // Skip second pass if the strategy did not fail.
  1576. if (!StrategyFailed)
  1577. break;
  1578. }
  1579. }
  1580. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1581. LLVM_DUMP_METHOD static StringRef getModeStr(ReorderingMode RMode) {
  1582. switch (RMode) {
  1583. case ReorderingMode::Load:
  1584. return "Load";
  1585. case ReorderingMode::Opcode:
  1586. return "Opcode";
  1587. case ReorderingMode::Constant:
  1588. return "Constant";
  1589. case ReorderingMode::Splat:
  1590. return "Splat";
  1591. case ReorderingMode::Failed:
  1592. return "Failed";
  1593. }
  1594. llvm_unreachable("Unimplemented Reordering Type");
  1595. }
  1596. LLVM_DUMP_METHOD static raw_ostream &printMode(ReorderingMode RMode,
  1597. raw_ostream &OS) {
  1598. return OS << getModeStr(RMode);
  1599. }
  1600. /// Debug print.
  1601. LLVM_DUMP_METHOD static void dumpMode(ReorderingMode RMode) {
  1602. printMode(RMode, dbgs());
  1603. }
  1604. friend raw_ostream &operator<<(raw_ostream &OS, ReorderingMode RMode) {
  1605. return printMode(RMode, OS);
  1606. }
  1607. LLVM_DUMP_METHOD raw_ostream &print(raw_ostream &OS) const {
  1608. const unsigned Indent = 2;
  1609. unsigned Cnt = 0;
  1610. for (const OperandDataVec &OpDataVec : OpsVec) {
  1611. OS << "Operand " << Cnt++ << "\n";
  1612. for (const OperandData &OpData : OpDataVec) {
  1613. OS.indent(Indent) << "{";
  1614. if (Value *V = OpData.V)
  1615. OS << *V;
  1616. else
  1617. OS << "null";
  1618. OS << ", APO:" << OpData.APO << "}\n";
  1619. }
  1620. OS << "\n";
  1621. }
  1622. return OS;
  1623. }
  1624. /// Debug print.
  1625. LLVM_DUMP_METHOD void dump() const { print(dbgs()); }
  1626. #endif
  1627. };
  1628. /// Checks if the instruction is marked for deletion.
  1629. bool isDeleted(Instruction *I) const { return DeletedInstructions.count(I); }
  1630. /// Marks values operands for later deletion by replacing them with Undefs.
  1631. void eraseInstructions(ArrayRef<Value *> AV);
  1632. ~BoUpSLP();
  1633. private:
  1634. /// Checks if all users of \p I are the part of the vectorization tree.
  1635. bool areAllUsersVectorized(Instruction *I,
  1636. ArrayRef<Value *> VectorizedVals) const;
  1637. /// \returns the cost of the vectorizable entry.
  1638. InstructionCost getEntryCost(const TreeEntry *E,
  1639. ArrayRef<Value *> VectorizedVals);
  1640. /// This is the recursive part of buildTree.
  1641. void buildTree_rec(ArrayRef<Value *> Roots, unsigned Depth,
  1642. const EdgeInfo &EI);
  1643. /// \returns true if the ExtractElement/ExtractValue instructions in \p VL can
  1644. /// be vectorized to use the original vector (or aggregate "bitcast" to a
  1645. /// vector) and sets \p CurrentOrder to the identity permutation; otherwise
  1646. /// returns false, setting \p CurrentOrder to either an empty vector or a
  1647. /// non-identity permutation that allows to reuse extract instructions.
  1648. bool canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
  1649. SmallVectorImpl<unsigned> &CurrentOrder) const;
  1650. /// Vectorize a single entry in the tree.
  1651. Value *vectorizeTree(TreeEntry *E);
  1652. /// Vectorize a single entry in the tree, starting in \p VL.
  1653. Value *vectorizeTree(ArrayRef<Value *> VL);
  1654. /// \returns the scalarization cost for this type. Scalarization in this
  1655. /// context means the creation of vectors from a group of scalars. If \p
  1656. /// NeedToShuffle is true, need to add a cost of reshuffling some of the
  1657. /// vector elements.
  1658. InstructionCost getGatherCost(FixedVectorType *Ty,
  1659. const DenseSet<unsigned> &ShuffledIndices,
  1660. bool NeedToShuffle) const;
  1661. /// Checks if the gathered \p VL can be represented as shuffle(s) of previous
  1662. /// tree entries.
  1663. /// \returns ShuffleKind, if gathered values can be represented as shuffles of
  1664. /// previous tree entries. \p Mask is filled with the shuffle mask.
  1665. Optional<TargetTransformInfo::ShuffleKind>
  1666. isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
  1667. SmallVectorImpl<const TreeEntry *> &Entries);
  1668. /// \returns the scalarization cost for this list of values. Assuming that
  1669. /// this subtree gets vectorized, we may need to extract the values from the
  1670. /// roots. This method calculates the cost of extracting the values.
  1671. InstructionCost getGatherCost(ArrayRef<Value *> VL) const;
  1672. /// Set the Builder insert point to one after the last instruction in
  1673. /// the bundle
  1674. void setInsertPointAfterBundle(const TreeEntry *E);
  1675. /// \returns a vector from a collection of scalars in \p VL.
  1676. Value *gather(ArrayRef<Value *> VL);
  1677. /// \returns whether the VectorizableTree is fully vectorizable and will
  1678. /// be beneficial even the tree height is tiny.
  1679. bool isFullyVectorizableTinyTree(bool ForReduction) const;
  1680. /// Reorder commutative or alt operands to get better probability of
  1681. /// generating vectorized code.
  1682. static void reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
  1683. SmallVectorImpl<Value *> &Left,
  1684. SmallVectorImpl<Value *> &Right,
  1685. const DataLayout &DL,
  1686. ScalarEvolution &SE,
  1687. const BoUpSLP &R);
  1688. struct TreeEntry {
  1689. using VecTreeTy = SmallVector<std::unique_ptr<TreeEntry>, 8>;
  1690. TreeEntry(VecTreeTy &Container) : Container(Container) {}
  1691. /// \returns true if the scalars in VL are equal to this entry.
  1692. bool isSame(ArrayRef<Value *> VL) const {
  1693. auto &&IsSame = [VL](ArrayRef<Value *> Scalars, ArrayRef<int> Mask) {
  1694. if (Mask.size() != VL.size() && VL.size() == Scalars.size())
  1695. return std::equal(VL.begin(), VL.end(), Scalars.begin());
  1696. return VL.size() == Mask.size() &&
  1697. std::equal(VL.begin(), VL.end(), Mask.begin(),
  1698. [Scalars](Value *V, int Idx) {
  1699. return (isa<UndefValue>(V) &&
  1700. Idx == UndefMaskElem) ||
  1701. (Idx != UndefMaskElem && V == Scalars[Idx]);
  1702. });
  1703. };
  1704. if (!ReorderIndices.empty()) {
  1705. // TODO: implement matching if the nodes are just reordered, still can
  1706. // treat the vector as the same if the list of scalars matches VL
  1707. // directly, without reordering.
  1708. SmallVector<int> Mask;
  1709. inversePermutation(ReorderIndices, Mask);
  1710. if (VL.size() == Scalars.size())
  1711. return IsSame(Scalars, Mask);
  1712. if (VL.size() == ReuseShuffleIndices.size()) {
  1713. ::addMask(Mask, ReuseShuffleIndices);
  1714. return IsSame(Scalars, Mask);
  1715. }
  1716. return false;
  1717. }
  1718. return IsSame(Scalars, ReuseShuffleIndices);
  1719. }
  1720. /// \returns true if current entry has same operands as \p TE.
  1721. bool hasEqualOperands(const TreeEntry &TE) const {
  1722. if (TE.getNumOperands() != getNumOperands())
  1723. return false;
  1724. SmallBitVector Used(getNumOperands());
  1725. for (unsigned I = 0, E = getNumOperands(); I < E; ++I) {
  1726. unsigned PrevCount = Used.count();
  1727. for (unsigned K = 0; K < E; ++K) {
  1728. if (Used.test(K))
  1729. continue;
  1730. if (getOperand(K) == TE.getOperand(I)) {
  1731. Used.set(K);
  1732. break;
  1733. }
  1734. }
  1735. // Check if we actually found the matching operand.
  1736. if (PrevCount == Used.count())
  1737. return false;
  1738. }
  1739. return true;
  1740. }
  1741. /// \return Final vectorization factor for the node. Defined by the total
  1742. /// number of vectorized scalars, including those, used several times in the
  1743. /// entry and counted in the \a ReuseShuffleIndices, if any.
  1744. unsigned getVectorFactor() const {
  1745. if (!ReuseShuffleIndices.empty())
  1746. return ReuseShuffleIndices.size();
  1747. return Scalars.size();
  1748. };
  1749. /// A vector of scalars.
  1750. ValueList Scalars;
  1751. /// The Scalars are vectorized into this value. It is initialized to Null.
  1752. Value *VectorizedValue = nullptr;
  1753. /// Do we need to gather this sequence or vectorize it
  1754. /// (either with vector instruction or with scatter/gather
  1755. /// intrinsics for store/load)?
  1756. enum EntryState { Vectorize, ScatterVectorize, NeedToGather };
  1757. EntryState State;
  1758. /// Does this sequence require some shuffling?
  1759. SmallVector<int, 4> ReuseShuffleIndices;
  1760. /// Does this entry require reordering?
  1761. SmallVector<unsigned, 4> ReorderIndices;
  1762. /// Points back to the VectorizableTree.
  1763. ///
  1764. /// Only used for Graphviz right now. Unfortunately GraphTrait::NodeRef has
  1765. /// to be a pointer and needs to be able to initialize the child iterator.
  1766. /// Thus we need a reference back to the container to translate the indices
  1767. /// to entries.
  1768. VecTreeTy &Container;
  1769. /// The TreeEntry index containing the user of this entry. We can actually
  1770. /// have multiple users so the data structure is not truly a tree.
  1771. SmallVector<EdgeInfo, 1> UserTreeIndices;
  1772. /// The index of this treeEntry in VectorizableTree.
  1773. int Idx = -1;
  1774. private:
  1775. /// The operands of each instruction in each lane Operands[op_index][lane].
  1776. /// Note: This helps avoid the replication of the code that performs the
  1777. /// reordering of operands during buildTree_rec() and vectorizeTree().
  1778. SmallVector<ValueList, 2> Operands;
  1779. /// The main/alternate instruction.
  1780. Instruction *MainOp = nullptr;
  1781. Instruction *AltOp = nullptr;
  1782. public:
  1783. /// Set this bundle's \p OpIdx'th operand to \p OpVL.
  1784. void setOperand(unsigned OpIdx, ArrayRef<Value *> OpVL) {
  1785. if (Operands.size() < OpIdx + 1)
  1786. Operands.resize(OpIdx + 1);
  1787. assert(Operands[OpIdx].empty() && "Already resized?");
  1788. assert(OpVL.size() <= Scalars.size() &&
  1789. "Number of operands is greater than the number of scalars.");
  1790. Operands[OpIdx].resize(OpVL.size());
  1791. copy(OpVL, Operands[OpIdx].begin());
  1792. }
  1793. /// Set the operands of this bundle in their original order.
  1794. void setOperandsInOrder() {
  1795. assert(Operands.empty() && "Already initialized?");
  1796. auto *I0 = cast<Instruction>(Scalars[0]);
  1797. Operands.resize(I0->getNumOperands());
  1798. unsigned NumLanes = Scalars.size();
  1799. for (unsigned OpIdx = 0, NumOperands = I0->getNumOperands();
  1800. OpIdx != NumOperands; ++OpIdx) {
  1801. Operands[OpIdx].resize(NumLanes);
  1802. for (unsigned Lane = 0; Lane != NumLanes; ++Lane) {
  1803. auto *I = cast<Instruction>(Scalars[Lane]);
  1804. assert(I->getNumOperands() == NumOperands &&
  1805. "Expected same number of operands");
  1806. Operands[OpIdx][Lane] = I->getOperand(OpIdx);
  1807. }
  1808. }
  1809. }
  1810. /// Reorders operands of the node to the given mask \p Mask.
  1811. void reorderOperands(ArrayRef<int> Mask) {
  1812. for (ValueList &Operand : Operands)
  1813. reorderScalars(Operand, Mask);
  1814. }
  1815. /// \returns the \p OpIdx operand of this TreeEntry.
  1816. ValueList &getOperand(unsigned OpIdx) {
  1817. assert(OpIdx < Operands.size() && "Off bounds");
  1818. return Operands[OpIdx];
  1819. }
  1820. /// \returns the \p OpIdx operand of this TreeEntry.
  1821. ArrayRef<Value *> getOperand(unsigned OpIdx) const {
  1822. assert(OpIdx < Operands.size() && "Off bounds");
  1823. return Operands[OpIdx];
  1824. }
  1825. /// \returns the number of operands.
  1826. unsigned getNumOperands() const { return Operands.size(); }
  1827. /// \return the single \p OpIdx operand.
  1828. Value *getSingleOperand(unsigned OpIdx) const {
  1829. assert(OpIdx < Operands.size() && "Off bounds");
  1830. assert(!Operands[OpIdx].empty() && "No operand available");
  1831. return Operands[OpIdx][0];
  1832. }
  1833. /// Some of the instructions in the list have alternate opcodes.
  1834. bool isAltShuffle() const { return MainOp != AltOp; }
  1835. bool isOpcodeOrAlt(Instruction *I) const {
  1836. unsigned CheckedOpcode = I->getOpcode();
  1837. return (getOpcode() == CheckedOpcode ||
  1838. getAltOpcode() == CheckedOpcode);
  1839. }
  1840. /// Chooses the correct key for scheduling data. If \p Op has the same (or
  1841. /// alternate) opcode as \p OpValue, the key is \p Op. Otherwise the key is
  1842. /// \p OpValue.
  1843. Value *isOneOf(Value *Op) const {
  1844. auto *I = dyn_cast<Instruction>(Op);
  1845. if (I && isOpcodeOrAlt(I))
  1846. return Op;
  1847. return MainOp;
  1848. }
  1849. void setOperations(const InstructionsState &S) {
  1850. MainOp = S.MainOp;
  1851. AltOp = S.AltOp;
  1852. }
  1853. Instruction *getMainOp() const {
  1854. return MainOp;
  1855. }
  1856. Instruction *getAltOp() const {
  1857. return AltOp;
  1858. }
  1859. /// The main/alternate opcodes for the list of instructions.
  1860. unsigned getOpcode() const {
  1861. return MainOp ? MainOp->getOpcode() : 0;
  1862. }
  1863. unsigned getAltOpcode() const {
  1864. return AltOp ? AltOp->getOpcode() : 0;
  1865. }
  1866. /// When ReuseReorderShuffleIndices is empty it just returns position of \p
  1867. /// V within vector of Scalars. Otherwise, try to remap on its reuse index.
  1868. int findLaneForValue(Value *V) const {
  1869. unsigned FoundLane = std::distance(Scalars.begin(), find(Scalars, V));
  1870. assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
  1871. if (!ReorderIndices.empty())
  1872. FoundLane = ReorderIndices[FoundLane];
  1873. assert(FoundLane < Scalars.size() && "Couldn't find extract lane");
  1874. if (!ReuseShuffleIndices.empty()) {
  1875. FoundLane = std::distance(ReuseShuffleIndices.begin(),
  1876. find(ReuseShuffleIndices, FoundLane));
  1877. }
  1878. return FoundLane;
  1879. }
  1880. #ifndef NDEBUG
  1881. /// Debug printer.
  1882. LLVM_DUMP_METHOD void dump() const {
  1883. dbgs() << Idx << ".\n";
  1884. for (unsigned OpI = 0, OpE = Operands.size(); OpI != OpE; ++OpI) {
  1885. dbgs() << "Operand " << OpI << ":\n";
  1886. for (const Value *V : Operands[OpI])
  1887. dbgs().indent(2) << *V << "\n";
  1888. }
  1889. dbgs() << "Scalars: \n";
  1890. for (Value *V : Scalars)
  1891. dbgs().indent(2) << *V << "\n";
  1892. dbgs() << "State: ";
  1893. switch (State) {
  1894. case Vectorize:
  1895. dbgs() << "Vectorize\n";
  1896. break;
  1897. case ScatterVectorize:
  1898. dbgs() << "ScatterVectorize\n";
  1899. break;
  1900. case NeedToGather:
  1901. dbgs() << "NeedToGather\n";
  1902. break;
  1903. }
  1904. dbgs() << "MainOp: ";
  1905. if (MainOp)
  1906. dbgs() << *MainOp << "\n";
  1907. else
  1908. dbgs() << "NULL\n";
  1909. dbgs() << "AltOp: ";
  1910. if (AltOp)
  1911. dbgs() << *AltOp << "\n";
  1912. else
  1913. dbgs() << "NULL\n";
  1914. dbgs() << "VectorizedValue: ";
  1915. if (VectorizedValue)
  1916. dbgs() << *VectorizedValue << "\n";
  1917. else
  1918. dbgs() << "NULL\n";
  1919. dbgs() << "ReuseShuffleIndices: ";
  1920. if (ReuseShuffleIndices.empty())
  1921. dbgs() << "Empty";
  1922. else
  1923. for (int ReuseIdx : ReuseShuffleIndices)
  1924. dbgs() << ReuseIdx << ", ";
  1925. dbgs() << "\n";
  1926. dbgs() << "ReorderIndices: ";
  1927. for (unsigned ReorderIdx : ReorderIndices)
  1928. dbgs() << ReorderIdx << ", ";
  1929. dbgs() << "\n";
  1930. dbgs() << "UserTreeIndices: ";
  1931. for (const auto &EInfo : UserTreeIndices)
  1932. dbgs() << EInfo << ", ";
  1933. dbgs() << "\n";
  1934. }
  1935. #endif
  1936. };
  1937. #ifndef NDEBUG
  1938. void dumpTreeCosts(const TreeEntry *E, InstructionCost ReuseShuffleCost,
  1939. InstructionCost VecCost,
  1940. InstructionCost ScalarCost) const {
  1941. dbgs() << "SLP: Calculated costs for Tree:\n"; E->dump();
  1942. dbgs() << "SLP: Costs:\n";
  1943. dbgs() << "SLP: ReuseShuffleCost = " << ReuseShuffleCost << "\n";
  1944. dbgs() << "SLP: VectorCost = " << VecCost << "\n";
  1945. dbgs() << "SLP: ScalarCost = " << ScalarCost << "\n";
  1946. dbgs() << "SLP: ReuseShuffleCost + VecCost - ScalarCost = " <<
  1947. ReuseShuffleCost + VecCost - ScalarCost << "\n";
  1948. }
  1949. #endif
  1950. /// Create a new VectorizableTree entry.
  1951. TreeEntry *newTreeEntry(ArrayRef<Value *> VL, Optional<ScheduleData *> Bundle,
  1952. const InstructionsState &S,
  1953. const EdgeInfo &UserTreeIdx,
  1954. ArrayRef<int> ReuseShuffleIndices = None,
  1955. ArrayRef<unsigned> ReorderIndices = None) {
  1956. TreeEntry::EntryState EntryState =
  1957. Bundle ? TreeEntry::Vectorize : TreeEntry::NeedToGather;
  1958. return newTreeEntry(VL, EntryState, Bundle, S, UserTreeIdx,
  1959. ReuseShuffleIndices, ReorderIndices);
  1960. }
  1961. TreeEntry *newTreeEntry(ArrayRef<Value *> VL,
  1962. TreeEntry::EntryState EntryState,
  1963. Optional<ScheduleData *> Bundle,
  1964. const InstructionsState &S,
  1965. const EdgeInfo &UserTreeIdx,
  1966. ArrayRef<int> ReuseShuffleIndices = None,
  1967. ArrayRef<unsigned> ReorderIndices = None) {
  1968. assert(((!Bundle && EntryState == TreeEntry::NeedToGather) ||
  1969. (Bundle && EntryState != TreeEntry::NeedToGather)) &&
  1970. "Need to vectorize gather entry?");
  1971. VectorizableTree.push_back(std::make_unique<TreeEntry>(VectorizableTree));
  1972. TreeEntry *Last = VectorizableTree.back().get();
  1973. Last->Idx = VectorizableTree.size() - 1;
  1974. Last->State = EntryState;
  1975. Last->ReuseShuffleIndices.append(ReuseShuffleIndices.begin(),
  1976. ReuseShuffleIndices.end());
  1977. if (ReorderIndices.empty()) {
  1978. Last->Scalars.assign(VL.begin(), VL.end());
  1979. Last->setOperations(S);
  1980. } else {
  1981. // Reorder scalars and build final mask.
  1982. Last->Scalars.assign(VL.size(), nullptr);
  1983. transform(ReorderIndices, Last->Scalars.begin(),
  1984. [VL](unsigned Idx) -> Value * {
  1985. if (Idx >= VL.size())
  1986. return UndefValue::get(VL.front()->getType());
  1987. return VL[Idx];
  1988. });
  1989. InstructionsState S = getSameOpcode(Last->Scalars);
  1990. Last->setOperations(S);
  1991. Last->ReorderIndices.append(ReorderIndices.begin(), ReorderIndices.end());
  1992. }
  1993. if (Last->State != TreeEntry::NeedToGather) {
  1994. for (Value *V : VL) {
  1995. assert(!getTreeEntry(V) && "Scalar already in tree!");
  1996. ScalarToTreeEntry[V] = Last;
  1997. }
  1998. // Update the scheduler bundle to point to this TreeEntry.
  1999. unsigned Lane = 0;
  2000. for (ScheduleData *BundleMember = Bundle.getValue(); BundleMember;
  2001. BundleMember = BundleMember->NextInBundle) {
  2002. BundleMember->TE = Last;
  2003. BundleMember->Lane = Lane;
  2004. ++Lane;
  2005. }
  2006. assert((!Bundle.getValue() || Lane == VL.size()) &&
  2007. "Bundle and VL out of sync");
  2008. } else {
  2009. MustGather.insert(VL.begin(), VL.end());
  2010. }
  2011. if (UserTreeIdx.UserTE)
  2012. Last->UserTreeIndices.push_back(UserTreeIdx);
  2013. return Last;
  2014. }
  2015. /// -- Vectorization State --
  2016. /// Holds all of the tree entries.
  2017. TreeEntry::VecTreeTy VectorizableTree;
  2018. #ifndef NDEBUG
  2019. /// Debug printer.
  2020. LLVM_DUMP_METHOD void dumpVectorizableTree() const {
  2021. for (unsigned Id = 0, IdE = VectorizableTree.size(); Id != IdE; ++Id) {
  2022. VectorizableTree[Id]->dump();
  2023. dbgs() << "\n";
  2024. }
  2025. }
  2026. #endif
  2027. TreeEntry *getTreeEntry(Value *V) { return ScalarToTreeEntry.lookup(V); }
  2028. const TreeEntry *getTreeEntry(Value *V) const {
  2029. return ScalarToTreeEntry.lookup(V);
  2030. }
  2031. /// Maps a specific scalar to its tree entry.
  2032. SmallDenseMap<Value*, TreeEntry *> ScalarToTreeEntry;
  2033. /// Maps a value to the proposed vectorizable size.
  2034. SmallDenseMap<Value *, unsigned> InstrElementSize;
  2035. /// A list of scalars that we found that we need to keep as scalars.
  2036. ValueSet MustGather;
  2037. /// This POD struct describes one external user in the vectorized tree.
  2038. struct ExternalUser {
  2039. ExternalUser(Value *S, llvm::User *U, int L)
  2040. : Scalar(S), User(U), Lane(L) {}
  2041. // Which scalar in our function.
  2042. Value *Scalar;
  2043. // Which user that uses the scalar.
  2044. llvm::User *User;
  2045. // Which lane does the scalar belong to.
  2046. int Lane;
  2047. };
  2048. using UserList = SmallVector<ExternalUser, 16>;
  2049. /// Checks if two instructions may access the same memory.
  2050. ///
  2051. /// \p Loc1 is the location of \p Inst1. It is passed explicitly because it
  2052. /// is invariant in the calling loop.
  2053. bool isAliased(const MemoryLocation &Loc1, Instruction *Inst1,
  2054. Instruction *Inst2) {
  2055. // First check if the result is already in the cache.
  2056. AliasCacheKey key = std::make_pair(Inst1, Inst2);
  2057. Optional<bool> &result = AliasCache[key];
  2058. if (result.hasValue()) {
  2059. return result.getValue();
  2060. }
  2061. bool aliased = true;
  2062. if (Loc1.Ptr && isSimple(Inst1))
  2063. aliased = isModOrRefSet(AA->getModRefInfo(Inst2, Loc1));
  2064. // Store the result in the cache.
  2065. result = aliased;
  2066. return aliased;
  2067. }
  2068. using AliasCacheKey = std::pair<Instruction *, Instruction *>;
  2069. /// Cache for alias results.
  2070. /// TODO: consider moving this to the AliasAnalysis itself.
  2071. DenseMap<AliasCacheKey, Optional<bool>> AliasCache;
  2072. /// Removes an instruction from its block and eventually deletes it.
  2073. /// It's like Instruction::eraseFromParent() except that the actual deletion
  2074. /// is delayed until BoUpSLP is destructed.
  2075. /// This is required to ensure that there are no incorrect collisions in the
  2076. /// AliasCache, which can happen if a new instruction is allocated at the
  2077. /// same address as a previously deleted instruction.
  2078. void eraseInstruction(Instruction *I, bool ReplaceOpsWithUndef = false) {
  2079. auto It = DeletedInstructions.try_emplace(I, ReplaceOpsWithUndef).first;
  2080. It->getSecond() = It->getSecond() && ReplaceOpsWithUndef;
  2081. }
  2082. /// Temporary store for deleted instructions. Instructions will be deleted
  2083. /// eventually when the BoUpSLP is destructed.
  2084. DenseMap<Instruction *, bool> DeletedInstructions;
  2085. /// A list of values that need to extracted out of the tree.
  2086. /// This list holds pairs of (Internal Scalar : External User). External User
  2087. /// can be nullptr, it means that this Internal Scalar will be used later,
  2088. /// after vectorization.
  2089. UserList ExternalUses;
  2090. /// Values used only by @llvm.assume calls.
  2091. SmallPtrSet<const Value *, 32> EphValues;
  2092. /// Holds all of the instructions that we gathered.
  2093. SetVector<Instruction *> GatherShuffleSeq;
  2094. /// A list of blocks that we are going to CSE.
  2095. SetVector<BasicBlock *> CSEBlocks;
  2096. /// Contains all scheduling relevant data for an instruction.
  2097. /// A ScheduleData either represents a single instruction or a member of an
  2098. /// instruction bundle (= a group of instructions which is combined into a
  2099. /// vector instruction).
  2100. struct ScheduleData {
  2101. // The initial value for the dependency counters. It means that the
  2102. // dependencies are not calculated yet.
  2103. enum { InvalidDeps = -1 };
  2104. ScheduleData() = default;
  2105. void init(int BlockSchedulingRegionID, Value *OpVal) {
  2106. FirstInBundle = this;
  2107. NextInBundle = nullptr;
  2108. NextLoadStore = nullptr;
  2109. IsScheduled = false;
  2110. SchedulingRegionID = BlockSchedulingRegionID;
  2111. UnscheduledDepsInBundle = UnscheduledDeps;
  2112. clearDependencies();
  2113. OpValue = OpVal;
  2114. TE = nullptr;
  2115. Lane = -1;
  2116. }
  2117. /// Returns true if the dependency information has been calculated.
  2118. bool hasValidDependencies() const { return Dependencies != InvalidDeps; }
  2119. /// Returns true for single instructions and for bundle representatives
  2120. /// (= the head of a bundle).
  2121. bool isSchedulingEntity() const { return FirstInBundle == this; }
  2122. /// Returns true if it represents an instruction bundle and not only a
  2123. /// single instruction.
  2124. bool isPartOfBundle() const {
  2125. return NextInBundle != nullptr || FirstInBundle != this;
  2126. }
  2127. /// Returns true if it is ready for scheduling, i.e. it has no more
  2128. /// unscheduled depending instructions/bundles.
  2129. bool isReady() const {
  2130. assert(isSchedulingEntity() &&
  2131. "can't consider non-scheduling entity for ready list");
  2132. return UnscheduledDepsInBundle == 0 && !IsScheduled;
  2133. }
  2134. /// Modifies the number of unscheduled dependencies, also updating it for
  2135. /// the whole bundle.
  2136. int incrementUnscheduledDeps(int Incr) {
  2137. UnscheduledDeps += Incr;
  2138. return FirstInBundle->UnscheduledDepsInBundle += Incr;
  2139. }
  2140. /// Sets the number of unscheduled dependencies to the number of
  2141. /// dependencies.
  2142. void resetUnscheduledDeps() {
  2143. incrementUnscheduledDeps(Dependencies - UnscheduledDeps);
  2144. }
  2145. /// Clears all dependency information.
  2146. void clearDependencies() {
  2147. Dependencies = InvalidDeps;
  2148. resetUnscheduledDeps();
  2149. MemoryDependencies.clear();
  2150. }
  2151. void dump(raw_ostream &os) const {
  2152. if (!isSchedulingEntity()) {
  2153. os << "/ " << *Inst;
  2154. } else if (NextInBundle) {
  2155. os << '[' << *Inst;
  2156. ScheduleData *SD = NextInBundle;
  2157. while (SD) {
  2158. os << ';' << *SD->Inst;
  2159. SD = SD->NextInBundle;
  2160. }
  2161. os << ']';
  2162. } else {
  2163. os << *Inst;
  2164. }
  2165. }
  2166. Instruction *Inst = nullptr;
  2167. /// Points to the head in an instruction bundle (and always to this for
  2168. /// single instructions).
  2169. ScheduleData *FirstInBundle = nullptr;
  2170. /// Single linked list of all instructions in a bundle. Null if it is a
  2171. /// single instruction.
  2172. ScheduleData *NextInBundle = nullptr;
  2173. /// Single linked list of all memory instructions (e.g. load, store, call)
  2174. /// in the block - until the end of the scheduling region.
  2175. ScheduleData *NextLoadStore = nullptr;
  2176. /// The dependent memory instructions.
  2177. /// This list is derived on demand in calculateDependencies().
  2178. SmallVector<ScheduleData *, 4> MemoryDependencies;
  2179. /// This ScheduleData is in the current scheduling region if this matches
  2180. /// the current SchedulingRegionID of BlockScheduling.
  2181. int SchedulingRegionID = 0;
  2182. /// Used for getting a "good" final ordering of instructions.
  2183. int SchedulingPriority = 0;
  2184. /// The number of dependencies. Constitutes of the number of users of the
  2185. /// instruction plus the number of dependent memory instructions (if any).
  2186. /// This value is calculated on demand.
  2187. /// If InvalidDeps, the number of dependencies is not calculated yet.
  2188. int Dependencies = InvalidDeps;
  2189. /// The number of dependencies minus the number of dependencies of scheduled
  2190. /// instructions. As soon as this is zero, the instruction/bundle gets ready
  2191. /// for scheduling.
  2192. /// Note that this is negative as long as Dependencies is not calculated.
  2193. int UnscheduledDeps = InvalidDeps;
  2194. /// The sum of UnscheduledDeps in a bundle. Equals to UnscheduledDeps for
  2195. /// single instructions.
  2196. int UnscheduledDepsInBundle = InvalidDeps;
  2197. /// True if this instruction is scheduled (or considered as scheduled in the
  2198. /// dry-run).
  2199. bool IsScheduled = false;
  2200. /// Opcode of the current instruction in the schedule data.
  2201. Value *OpValue = nullptr;
  2202. /// The TreeEntry that this instruction corresponds to.
  2203. TreeEntry *TE = nullptr;
  2204. /// The lane of this node in the TreeEntry.
  2205. int Lane = -1;
  2206. };
  2207. #ifndef NDEBUG
  2208. friend inline raw_ostream &operator<<(raw_ostream &os,
  2209. const BoUpSLP::ScheduleData &SD) {
  2210. SD.dump(os);
  2211. return os;
  2212. }
  2213. #endif
  2214. friend struct GraphTraits<BoUpSLP *>;
  2215. friend struct DOTGraphTraits<BoUpSLP *>;
  2216. /// Contains all scheduling data for a basic block.
  2217. struct BlockScheduling {
  2218. BlockScheduling(BasicBlock *BB)
  2219. : BB(BB), ChunkSize(BB->size()), ChunkPos(ChunkSize) {}
  2220. void clear() {
  2221. ReadyInsts.clear();
  2222. ScheduleStart = nullptr;
  2223. ScheduleEnd = nullptr;
  2224. FirstLoadStoreInRegion = nullptr;
  2225. LastLoadStoreInRegion = nullptr;
  2226. // Reduce the maximum schedule region size by the size of the
  2227. // previous scheduling run.
  2228. ScheduleRegionSizeLimit -= ScheduleRegionSize;
  2229. if (ScheduleRegionSizeLimit < MinScheduleRegionSize)
  2230. ScheduleRegionSizeLimit = MinScheduleRegionSize;
  2231. ScheduleRegionSize = 0;
  2232. // Make a new scheduling region, i.e. all existing ScheduleData is not
  2233. // in the new region yet.
  2234. ++SchedulingRegionID;
  2235. }
  2236. ScheduleData *getScheduleData(Value *V) {
  2237. ScheduleData *SD = ScheduleDataMap[V];
  2238. if (SD && SD->SchedulingRegionID == SchedulingRegionID)
  2239. return SD;
  2240. return nullptr;
  2241. }
  2242. ScheduleData *getScheduleData(Value *V, Value *Key) {
  2243. if (V == Key)
  2244. return getScheduleData(V);
  2245. auto I = ExtraScheduleDataMap.find(V);
  2246. if (I != ExtraScheduleDataMap.end()) {
  2247. ScheduleData *SD = I->second[Key];
  2248. if (SD && SD->SchedulingRegionID == SchedulingRegionID)
  2249. return SD;
  2250. }
  2251. return nullptr;
  2252. }
  2253. bool isInSchedulingRegion(ScheduleData *SD) const {
  2254. return SD->SchedulingRegionID == SchedulingRegionID;
  2255. }
  2256. /// Marks an instruction as scheduled and puts all dependent ready
  2257. /// instructions into the ready-list.
  2258. template <typename ReadyListType>
  2259. void schedule(ScheduleData *SD, ReadyListType &ReadyList) {
  2260. SD->IsScheduled = true;
  2261. LLVM_DEBUG(dbgs() << "SLP: schedule " << *SD << "\n");
  2262. for (ScheduleData *BundleMember = SD; BundleMember;
  2263. BundleMember = BundleMember->NextInBundle) {
  2264. if (BundleMember->Inst != BundleMember->OpValue)
  2265. continue;
  2266. // Handle the def-use chain dependencies.
  2267. // Decrement the unscheduled counter and insert to ready list if ready.
  2268. auto &&DecrUnsched = [this, &ReadyList](Instruction *I) {
  2269. doForAllOpcodes(I, [&ReadyList](ScheduleData *OpDef) {
  2270. if (OpDef && OpDef->hasValidDependencies() &&
  2271. OpDef->incrementUnscheduledDeps(-1) == 0) {
  2272. // There are no more unscheduled dependencies after
  2273. // decrementing, so we can put the dependent instruction
  2274. // into the ready list.
  2275. ScheduleData *DepBundle = OpDef->FirstInBundle;
  2276. assert(!DepBundle->IsScheduled &&
  2277. "already scheduled bundle gets ready");
  2278. ReadyList.insert(DepBundle);
  2279. LLVM_DEBUG(dbgs()
  2280. << "SLP: gets ready (def): " << *DepBundle << "\n");
  2281. }
  2282. });
  2283. };
  2284. // If BundleMember is a vector bundle, its operands may have been
  2285. // reordered duiring buildTree(). We therefore need to get its operands
  2286. // through the TreeEntry.
  2287. if (TreeEntry *TE = BundleMember->TE) {
  2288. int Lane = BundleMember->Lane;
  2289. assert(Lane >= 0 && "Lane not set");
  2290. // Since vectorization tree is being built recursively this assertion
  2291. // ensures that the tree entry has all operands set before reaching
  2292. // this code. Couple of exceptions known at the moment are extracts
  2293. // where their second (immediate) operand is not added. Since
  2294. // immediates do not affect scheduler behavior this is considered
  2295. // okay.
  2296. auto *In = TE->getMainOp();
  2297. assert(In &&
  2298. (isa<ExtractValueInst>(In) || isa<ExtractElementInst>(In) ||
  2299. In->getNumOperands() == TE->getNumOperands()) &&
  2300. "Missed TreeEntry operands?");
  2301. (void)In; // fake use to avoid build failure when assertions disabled
  2302. for (unsigned OpIdx = 0, NumOperands = TE->getNumOperands();
  2303. OpIdx != NumOperands; ++OpIdx)
  2304. if (auto *I = dyn_cast<Instruction>(TE->getOperand(OpIdx)[Lane]))
  2305. DecrUnsched(I);
  2306. } else {
  2307. // If BundleMember is a stand-alone instruction, no operand reordering
  2308. // has taken place, so we directly access its operands.
  2309. for (Use &U : BundleMember->Inst->operands())
  2310. if (auto *I = dyn_cast<Instruction>(U.get()))
  2311. DecrUnsched(I);
  2312. }
  2313. // Handle the memory dependencies.
  2314. for (ScheduleData *MemoryDepSD : BundleMember->MemoryDependencies) {
  2315. if (MemoryDepSD->incrementUnscheduledDeps(-1) == 0) {
  2316. // There are no more unscheduled dependencies after decrementing,
  2317. // so we can put the dependent instruction into the ready list.
  2318. ScheduleData *DepBundle = MemoryDepSD->FirstInBundle;
  2319. assert(!DepBundle->IsScheduled &&
  2320. "already scheduled bundle gets ready");
  2321. ReadyList.insert(DepBundle);
  2322. LLVM_DEBUG(dbgs()
  2323. << "SLP: gets ready (mem): " << *DepBundle << "\n");
  2324. }
  2325. }
  2326. }
  2327. }
  2328. void doForAllOpcodes(Value *V,
  2329. function_ref<void(ScheduleData *SD)> Action) {
  2330. if (ScheduleData *SD = getScheduleData(V))
  2331. Action(SD);
  2332. auto I = ExtraScheduleDataMap.find(V);
  2333. if (I != ExtraScheduleDataMap.end())
  2334. for (auto &P : I->second)
  2335. if (P.second->SchedulingRegionID == SchedulingRegionID)
  2336. Action(P.second);
  2337. }
  2338. /// Put all instructions into the ReadyList which are ready for scheduling.
  2339. template <typename ReadyListType>
  2340. void initialFillReadyList(ReadyListType &ReadyList) {
  2341. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  2342. doForAllOpcodes(I, [&](ScheduleData *SD) {
  2343. if (SD->isSchedulingEntity() && SD->isReady()) {
  2344. ReadyList.insert(SD);
  2345. LLVM_DEBUG(dbgs()
  2346. << "SLP: initially in ready list: " << *I << "\n");
  2347. }
  2348. });
  2349. }
  2350. }
  2351. /// Build a bundle from the ScheduleData nodes corresponding to the
  2352. /// scalar instruction for each lane.
  2353. ScheduleData *buildBundle(ArrayRef<Value *> VL);
  2354. /// Checks if a bundle of instructions can be scheduled, i.e. has no
  2355. /// cyclic dependencies. This is only a dry-run, no instructions are
  2356. /// actually moved at this stage.
  2357. /// \returns the scheduling bundle. The returned Optional value is non-None
  2358. /// if \p VL is allowed to be scheduled.
  2359. Optional<ScheduleData *>
  2360. tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
  2361. const InstructionsState &S);
  2362. /// Un-bundles a group of instructions.
  2363. void cancelScheduling(ArrayRef<Value *> VL, Value *OpValue);
  2364. /// Allocates schedule data chunk.
  2365. ScheduleData *allocateScheduleDataChunks();
  2366. /// Extends the scheduling region so that V is inside the region.
  2367. /// \returns true if the region size is within the limit.
  2368. bool extendSchedulingRegion(Value *V, const InstructionsState &S);
  2369. /// Initialize the ScheduleData structures for new instructions in the
  2370. /// scheduling region.
  2371. void initScheduleData(Instruction *FromI, Instruction *ToI,
  2372. ScheduleData *PrevLoadStore,
  2373. ScheduleData *NextLoadStore);
  2374. /// Updates the dependency information of a bundle and of all instructions/
  2375. /// bundles which depend on the original bundle.
  2376. void calculateDependencies(ScheduleData *SD, bool InsertInReadyList,
  2377. BoUpSLP *SLP);
  2378. /// Sets all instruction in the scheduling region to un-scheduled.
  2379. void resetSchedule();
  2380. BasicBlock *BB;
  2381. /// Simple memory allocation for ScheduleData.
  2382. std::vector<std::unique_ptr<ScheduleData[]>> ScheduleDataChunks;
  2383. /// The size of a ScheduleData array in ScheduleDataChunks.
  2384. int ChunkSize;
  2385. /// The allocator position in the current chunk, which is the last entry
  2386. /// of ScheduleDataChunks.
  2387. int ChunkPos;
  2388. /// Attaches ScheduleData to Instruction.
  2389. /// Note that the mapping survives during all vectorization iterations, i.e.
  2390. /// ScheduleData structures are recycled.
  2391. DenseMap<Value *, ScheduleData *> ScheduleDataMap;
  2392. /// Attaches ScheduleData to Instruction with the leading key.
  2393. DenseMap<Value *, SmallDenseMap<Value *, ScheduleData *>>
  2394. ExtraScheduleDataMap;
  2395. struct ReadyList : SmallVector<ScheduleData *, 8> {
  2396. void insert(ScheduleData *SD) { push_back(SD); }
  2397. };
  2398. /// The ready-list for scheduling (only used for the dry-run).
  2399. ReadyList ReadyInsts;
  2400. /// The first instruction of the scheduling region.
  2401. Instruction *ScheduleStart = nullptr;
  2402. /// The first instruction _after_ the scheduling region.
  2403. Instruction *ScheduleEnd = nullptr;
  2404. /// The first memory accessing instruction in the scheduling region
  2405. /// (can be null).
  2406. ScheduleData *FirstLoadStoreInRegion = nullptr;
  2407. /// The last memory accessing instruction in the scheduling region
  2408. /// (can be null).
  2409. ScheduleData *LastLoadStoreInRegion = nullptr;
  2410. /// The current size of the scheduling region.
  2411. int ScheduleRegionSize = 0;
  2412. /// The maximum size allowed for the scheduling region.
  2413. int ScheduleRegionSizeLimit = ScheduleRegionSizeBudget;
  2414. /// The ID of the scheduling region. For a new vectorization iteration this
  2415. /// is incremented which "removes" all ScheduleData from the region.
  2416. // Make sure that the initial SchedulingRegionID is greater than the
  2417. // initial SchedulingRegionID in ScheduleData (which is 0).
  2418. int SchedulingRegionID = 1;
  2419. };
  2420. /// Attaches the BlockScheduling structures to basic blocks.
  2421. MapVector<BasicBlock *, std::unique_ptr<BlockScheduling>> BlocksSchedules;
  2422. /// Performs the "real" scheduling. Done before vectorization is actually
  2423. /// performed in a basic block.
  2424. void scheduleBlock(BlockScheduling *BS);
  2425. /// List of users to ignore during scheduling and that don't need extracting.
  2426. ArrayRef<Value *> UserIgnoreList;
  2427. /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of
  2428. /// sorted SmallVectors of unsigned.
  2429. struct OrdersTypeDenseMapInfo {
  2430. static OrdersType getEmptyKey() {
  2431. OrdersType V;
  2432. V.push_back(~1U);
  2433. return V;
  2434. }
  2435. static OrdersType getTombstoneKey() {
  2436. OrdersType V;
  2437. V.push_back(~2U);
  2438. return V;
  2439. }
  2440. static unsigned getHashValue(const OrdersType &V) {
  2441. return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
  2442. }
  2443. static bool isEqual(const OrdersType &LHS, const OrdersType &RHS) {
  2444. return LHS == RHS;
  2445. }
  2446. };
  2447. // Analysis and block reference.
  2448. Function *F;
  2449. ScalarEvolution *SE;
  2450. TargetTransformInfo *TTI;
  2451. TargetLibraryInfo *TLI;
  2452. AAResults *AA;
  2453. LoopInfo *LI;
  2454. DominatorTree *DT;
  2455. AssumptionCache *AC;
  2456. DemandedBits *DB;
  2457. const DataLayout *DL;
  2458. OptimizationRemarkEmitter *ORE;
  2459. unsigned MaxVecRegSize; // This is set by TTI or overridden by cl::opt.
  2460. unsigned MinVecRegSize; // Set by cl::opt (default: 128).
  2461. /// Instruction builder to construct the vectorized tree.
  2462. IRBuilder<> Builder;
  2463. /// A map of scalar integer values to the smallest bit width with which they
  2464. /// can legally be represented. The values map to (width, signed) pairs,
  2465. /// where "width" indicates the minimum bit width and "signed" is True if the
  2466. /// value must be signed-extended, rather than zero-extended, back to its
  2467. /// original width.
  2468. MapVector<Value *, std::pair<uint64_t, bool>> MinBWs;
  2469. };
  2470. } // end namespace slpvectorizer
  2471. template <> struct GraphTraits<BoUpSLP *> {
  2472. using TreeEntry = BoUpSLP::TreeEntry;
  2473. /// NodeRef has to be a pointer per the GraphWriter.
  2474. using NodeRef = TreeEntry *;
  2475. using ContainerTy = BoUpSLP::TreeEntry::VecTreeTy;
  2476. /// Add the VectorizableTree to the index iterator to be able to return
  2477. /// TreeEntry pointers.
  2478. struct ChildIteratorType
  2479. : public iterator_adaptor_base<
  2480. ChildIteratorType, SmallVector<BoUpSLP::EdgeInfo, 1>::iterator> {
  2481. ContainerTy &VectorizableTree;
  2482. ChildIteratorType(SmallVector<BoUpSLP::EdgeInfo, 1>::iterator W,
  2483. ContainerTy &VT)
  2484. : ChildIteratorType::iterator_adaptor_base(W), VectorizableTree(VT) {}
  2485. NodeRef operator*() { return I->UserTE; }
  2486. };
  2487. static NodeRef getEntryNode(BoUpSLP &R) {
  2488. return R.VectorizableTree[0].get();
  2489. }
  2490. static ChildIteratorType child_begin(NodeRef N) {
  2491. return {N->UserTreeIndices.begin(), N->Container};
  2492. }
  2493. static ChildIteratorType child_end(NodeRef N) {
  2494. return {N->UserTreeIndices.end(), N->Container};
  2495. }
  2496. /// For the node iterator we just need to turn the TreeEntry iterator into a
  2497. /// TreeEntry* iterator so that it dereferences to NodeRef.
  2498. class nodes_iterator {
  2499. using ItTy = ContainerTy::iterator;
  2500. ItTy It;
  2501. public:
  2502. nodes_iterator(const ItTy &It2) : It(It2) {}
  2503. NodeRef operator*() { return It->get(); }
  2504. nodes_iterator operator++() {
  2505. ++It;
  2506. return *this;
  2507. }
  2508. bool operator!=(const nodes_iterator &N2) const { return N2.It != It; }
  2509. };
  2510. static nodes_iterator nodes_begin(BoUpSLP *R) {
  2511. return nodes_iterator(R->VectorizableTree.begin());
  2512. }
  2513. static nodes_iterator nodes_end(BoUpSLP *R) {
  2514. return nodes_iterator(R->VectorizableTree.end());
  2515. }
  2516. static unsigned size(BoUpSLP *R) { return R->VectorizableTree.size(); }
  2517. };
  2518. template <> struct DOTGraphTraits<BoUpSLP *> : public DefaultDOTGraphTraits {
  2519. using TreeEntry = BoUpSLP::TreeEntry;
  2520. DOTGraphTraits(bool isSimple = false) : DefaultDOTGraphTraits(isSimple) {}
  2521. std::string getNodeLabel(const TreeEntry *Entry, const BoUpSLP *R) {
  2522. std::string Str;
  2523. raw_string_ostream OS(Str);
  2524. if (isSplat(Entry->Scalars))
  2525. OS << "<splat> ";
  2526. for (auto V : Entry->Scalars) {
  2527. OS << *V;
  2528. if (llvm::any_of(R->ExternalUses, [&](const BoUpSLP::ExternalUser &EU) {
  2529. return EU.Scalar == V;
  2530. }))
  2531. OS << " <extract>";
  2532. OS << "\n";
  2533. }
  2534. return Str;
  2535. }
  2536. static std::string getNodeAttributes(const TreeEntry *Entry,
  2537. const BoUpSLP *) {
  2538. if (Entry->State == TreeEntry::NeedToGather)
  2539. return "color=red";
  2540. return "";
  2541. }
  2542. };
  2543. } // end namespace llvm
  2544. BoUpSLP::~BoUpSLP() {
  2545. for (const auto &Pair : DeletedInstructions) {
  2546. // Replace operands of ignored instructions with Undefs in case if they were
  2547. // marked for deletion.
  2548. if (Pair.getSecond()) {
  2549. Value *Undef = UndefValue::get(Pair.getFirst()->getType());
  2550. Pair.getFirst()->replaceAllUsesWith(Undef);
  2551. }
  2552. Pair.getFirst()->dropAllReferences();
  2553. }
  2554. for (const auto &Pair : DeletedInstructions) {
  2555. assert(Pair.getFirst()->use_empty() &&
  2556. "trying to erase instruction with users.");
  2557. Pair.getFirst()->eraseFromParent();
  2558. }
  2559. #ifdef EXPENSIVE_CHECKS
  2560. // If we could guarantee that this call is not extremely slow, we could
  2561. // remove the ifdef limitation (see PR47712).
  2562. assert(!verifyFunction(*F, &dbgs()));
  2563. #endif
  2564. }
  2565. void BoUpSLP::eraseInstructions(ArrayRef<Value *> AV) {
  2566. for (auto *V : AV) {
  2567. if (auto *I = dyn_cast<Instruction>(V))
  2568. eraseInstruction(I, /*ReplaceOpsWithUndef=*/true);
  2569. };
  2570. }
  2571. /// Reorders the given \p Reuses mask according to the given \p Mask. \p Reuses
  2572. /// contains original mask for the scalars reused in the node. Procedure
  2573. /// transform this mask in accordance with the given \p Mask.
  2574. static void reorderReuses(SmallVectorImpl<int> &Reuses, ArrayRef<int> Mask) {
  2575. assert(!Mask.empty() && Reuses.size() == Mask.size() &&
  2576. "Expected non-empty mask.");
  2577. SmallVector<int> Prev(Reuses.begin(), Reuses.end());
  2578. Prev.swap(Reuses);
  2579. for (unsigned I = 0, E = Prev.size(); I < E; ++I)
  2580. if (Mask[I] != UndefMaskElem)
  2581. Reuses[Mask[I]] = Prev[I];
  2582. }
  2583. /// Reorders the given \p Order according to the given \p Mask. \p Order - is
  2584. /// the original order of the scalars. Procedure transforms the provided order
  2585. /// in accordance with the given \p Mask. If the resulting \p Order is just an
  2586. /// identity order, \p Order is cleared.
  2587. static void reorderOrder(SmallVectorImpl<unsigned> &Order, ArrayRef<int> Mask) {
  2588. assert(!Mask.empty() && "Expected non-empty mask.");
  2589. SmallVector<int> MaskOrder;
  2590. if (Order.empty()) {
  2591. MaskOrder.resize(Mask.size());
  2592. std::iota(MaskOrder.begin(), MaskOrder.end(), 0);
  2593. } else {
  2594. inversePermutation(Order, MaskOrder);
  2595. }
  2596. reorderReuses(MaskOrder, Mask);
  2597. if (ShuffleVectorInst::isIdentityMask(MaskOrder)) {
  2598. Order.clear();
  2599. return;
  2600. }
  2601. Order.assign(Mask.size(), Mask.size());
  2602. for (unsigned I = 0, E = Mask.size(); I < E; ++I)
  2603. if (MaskOrder[I] != UndefMaskElem)
  2604. Order[MaskOrder[I]] = I;
  2605. fixupOrderingIndices(Order);
  2606. }
  2607. Optional<BoUpSLP::OrdersType>
  2608. BoUpSLP::findReusedOrderedScalars(const BoUpSLP::TreeEntry &TE) {
  2609. assert(TE.State == TreeEntry::NeedToGather && "Expected gather node only.");
  2610. unsigned NumScalars = TE.Scalars.size();
  2611. OrdersType CurrentOrder(NumScalars, NumScalars);
  2612. SmallVector<int> Positions;
  2613. SmallBitVector UsedPositions(NumScalars);
  2614. const TreeEntry *STE = nullptr;
  2615. // Try to find all gathered scalars that are gets vectorized in other
  2616. // vectorize node. Here we can have only one single tree vector node to
  2617. // correctly identify order of the gathered scalars.
  2618. for (unsigned I = 0; I < NumScalars; ++I) {
  2619. Value *V = TE.Scalars[I];
  2620. if (!isa<LoadInst, ExtractElementInst, ExtractValueInst>(V))
  2621. continue;
  2622. if (const auto *LocalSTE = getTreeEntry(V)) {
  2623. if (!STE)
  2624. STE = LocalSTE;
  2625. else if (STE != LocalSTE)
  2626. // Take the order only from the single vector node.
  2627. return None;
  2628. unsigned Lane =
  2629. std::distance(STE->Scalars.begin(), find(STE->Scalars, V));
  2630. if (Lane >= NumScalars)
  2631. return None;
  2632. if (CurrentOrder[Lane] != NumScalars) {
  2633. if (Lane != I)
  2634. continue;
  2635. UsedPositions.reset(CurrentOrder[Lane]);
  2636. }
  2637. // The partial identity (where only some elements of the gather node are
  2638. // in the identity order) is good.
  2639. CurrentOrder[Lane] = I;
  2640. UsedPositions.set(I);
  2641. }
  2642. }
  2643. // Need to keep the order if we have a vector entry and at least 2 scalars or
  2644. // the vectorized entry has just 2 scalars.
  2645. if (STE && (UsedPositions.count() > 1 || STE->Scalars.size() == 2)) {
  2646. auto &&IsIdentityOrder = [NumScalars](ArrayRef<unsigned> CurrentOrder) {
  2647. for (unsigned I = 0; I < NumScalars; ++I)
  2648. if (CurrentOrder[I] != I && CurrentOrder[I] != NumScalars)
  2649. return false;
  2650. return true;
  2651. };
  2652. if (IsIdentityOrder(CurrentOrder)) {
  2653. CurrentOrder.clear();
  2654. return CurrentOrder;
  2655. }
  2656. auto *It = CurrentOrder.begin();
  2657. for (unsigned I = 0; I < NumScalars;) {
  2658. if (UsedPositions.test(I)) {
  2659. ++I;
  2660. continue;
  2661. }
  2662. if (*It == NumScalars) {
  2663. *It = I;
  2664. ++I;
  2665. }
  2666. ++It;
  2667. }
  2668. return CurrentOrder;
  2669. }
  2670. return None;
  2671. }
  2672. Optional<BoUpSLP::OrdersType> BoUpSLP::getReorderingData(const TreeEntry &TE,
  2673. bool TopToBottom) {
  2674. // No need to reorder if need to shuffle reuses, still need to shuffle the
  2675. // node.
  2676. if (!TE.ReuseShuffleIndices.empty())
  2677. return None;
  2678. if (TE.State == TreeEntry::Vectorize &&
  2679. (isa<LoadInst, ExtractElementInst, ExtractValueInst>(TE.getMainOp()) ||
  2680. (TopToBottom && isa<StoreInst, InsertElementInst>(TE.getMainOp()))) &&
  2681. !TE.isAltShuffle())
  2682. return TE.ReorderIndices;
  2683. if (TE.State == TreeEntry::NeedToGather) {
  2684. // TODO: add analysis of other gather nodes with extractelement
  2685. // instructions and other values/instructions, not only undefs.
  2686. if (((TE.getOpcode() == Instruction::ExtractElement &&
  2687. !TE.isAltShuffle()) ||
  2688. (all_of(TE.Scalars,
  2689. [](Value *V) {
  2690. return isa<UndefValue, ExtractElementInst>(V);
  2691. }) &&
  2692. any_of(TE.Scalars,
  2693. [](Value *V) { return isa<ExtractElementInst>(V); }))) &&
  2694. all_of(TE.Scalars,
  2695. [](Value *V) {
  2696. auto *EE = dyn_cast<ExtractElementInst>(V);
  2697. return !EE || isa<FixedVectorType>(EE->getVectorOperandType());
  2698. }) &&
  2699. allSameType(TE.Scalars)) {
  2700. // Check that gather of extractelements can be represented as
  2701. // just a shuffle of a single vector.
  2702. OrdersType CurrentOrder;
  2703. bool Reuse = canReuseExtract(TE.Scalars, TE.getMainOp(), CurrentOrder);
  2704. if (Reuse || !CurrentOrder.empty()) {
  2705. if (!CurrentOrder.empty())
  2706. fixupOrderingIndices(CurrentOrder);
  2707. return CurrentOrder;
  2708. }
  2709. }
  2710. if (Optional<OrdersType> CurrentOrder = findReusedOrderedScalars(TE))
  2711. return CurrentOrder;
  2712. }
  2713. return None;
  2714. }
  2715. void BoUpSLP::reorderTopToBottom() {
  2716. // Maps VF to the graph nodes.
  2717. DenseMap<unsigned, SetVector<TreeEntry *>> VFToOrderedEntries;
  2718. // ExtractElement gather nodes which can be vectorized and need to handle
  2719. // their ordering.
  2720. DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
  2721. // Find all reorderable nodes with the given VF.
  2722. // Currently the are vectorized stores,loads,extracts + some gathering of
  2723. // extracts.
  2724. for_each(VectorizableTree, [this, &VFToOrderedEntries, &GathersToOrders](
  2725. const std::unique_ptr<TreeEntry> &TE) {
  2726. if (Optional<OrdersType> CurrentOrder =
  2727. getReorderingData(*TE.get(), /*TopToBottom=*/true)) {
  2728. // Do not include ordering for nodes used in the alt opcode vectorization,
  2729. // better to reorder them during bottom-to-top stage. If follow the order
  2730. // here, it causes reordering of the whole graph though actually it is
  2731. // profitable just to reorder the subgraph that starts from the alternate
  2732. // opcode vectorization node. Such nodes already end-up with the shuffle
  2733. // instruction and it is just enough to change this shuffle rather than
  2734. // rotate the scalars for the whole graph.
  2735. unsigned Cnt = 0;
  2736. const TreeEntry *UserTE = TE.get();
  2737. while (UserTE && Cnt < RecursionMaxDepth) {
  2738. if (UserTE->UserTreeIndices.size() != 1)
  2739. break;
  2740. if (all_of(UserTE->UserTreeIndices, [](const EdgeInfo &EI) {
  2741. return EI.UserTE->State == TreeEntry::Vectorize &&
  2742. EI.UserTE->isAltShuffle() && EI.UserTE->Idx != 0;
  2743. }))
  2744. return;
  2745. if (UserTE->UserTreeIndices.empty())
  2746. UserTE = nullptr;
  2747. else
  2748. UserTE = UserTE->UserTreeIndices.back().UserTE;
  2749. ++Cnt;
  2750. }
  2751. VFToOrderedEntries[TE->Scalars.size()].insert(TE.get());
  2752. if (TE->State != TreeEntry::Vectorize)
  2753. GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
  2754. }
  2755. });
  2756. // Reorder the graph nodes according to their vectorization factor.
  2757. for (unsigned VF = VectorizableTree.front()->Scalars.size(); VF > 1;
  2758. VF /= 2) {
  2759. auto It = VFToOrderedEntries.find(VF);
  2760. if (It == VFToOrderedEntries.end())
  2761. continue;
  2762. // Try to find the most profitable order. We just are looking for the most
  2763. // used order and reorder scalar elements in the nodes according to this
  2764. // mostly used order.
  2765. ArrayRef<TreeEntry *> OrderedEntries = It->second.getArrayRef();
  2766. // All operands are reordered and used only in this node - propagate the
  2767. // most used order to the user node.
  2768. MapVector<OrdersType, unsigned,
  2769. DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
  2770. OrdersUses;
  2771. SmallPtrSet<const TreeEntry *, 4> VisitedOps;
  2772. for (const TreeEntry *OpTE : OrderedEntries) {
  2773. // No need to reorder this nodes, still need to extend and to use shuffle,
  2774. // just need to merge reordering shuffle and the reuse shuffle.
  2775. if (!OpTE->ReuseShuffleIndices.empty())
  2776. continue;
  2777. // Count number of orders uses.
  2778. const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
  2779. if (OpTE->State == TreeEntry::NeedToGather)
  2780. return GathersToOrders.find(OpTE)->second;
  2781. return OpTE->ReorderIndices;
  2782. }();
  2783. // Stores actually store the mask, not the order, need to invert.
  2784. if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
  2785. OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
  2786. SmallVector<int> Mask;
  2787. inversePermutation(Order, Mask);
  2788. unsigned E = Order.size();
  2789. OrdersType CurrentOrder(E, E);
  2790. transform(Mask, CurrentOrder.begin(), [E](int Idx) {
  2791. return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
  2792. });
  2793. fixupOrderingIndices(CurrentOrder);
  2794. ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
  2795. } else {
  2796. ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
  2797. }
  2798. }
  2799. // Set order of the user node.
  2800. if (OrdersUses.empty())
  2801. continue;
  2802. // Choose the most used order.
  2803. ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
  2804. unsigned Cnt = OrdersUses.front().second;
  2805. for (const auto &Pair : drop_begin(OrdersUses)) {
  2806. if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
  2807. BestOrder = Pair.first;
  2808. Cnt = Pair.second;
  2809. }
  2810. }
  2811. // Set order of the user node.
  2812. if (BestOrder.empty())
  2813. continue;
  2814. SmallVector<int> Mask;
  2815. inversePermutation(BestOrder, Mask);
  2816. SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
  2817. unsigned E = BestOrder.size();
  2818. transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
  2819. return I < E ? static_cast<int>(I) : UndefMaskElem;
  2820. });
  2821. // Do an actual reordering, if profitable.
  2822. for (std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
  2823. // Just do the reordering for the nodes with the given VF.
  2824. if (TE->Scalars.size() != VF) {
  2825. if (TE->ReuseShuffleIndices.size() == VF) {
  2826. // Need to reorder the reuses masks of the operands with smaller VF to
  2827. // be able to find the match between the graph nodes and scalar
  2828. // operands of the given node during vectorization/cost estimation.
  2829. assert(all_of(TE->UserTreeIndices,
  2830. [VF, &TE](const EdgeInfo &EI) {
  2831. return EI.UserTE->Scalars.size() == VF ||
  2832. EI.UserTE->Scalars.size() ==
  2833. TE->Scalars.size();
  2834. }) &&
  2835. "All users must be of VF size.");
  2836. // Update ordering of the operands with the smaller VF than the given
  2837. // one.
  2838. reorderReuses(TE->ReuseShuffleIndices, Mask);
  2839. }
  2840. continue;
  2841. }
  2842. if (TE->State == TreeEntry::Vectorize &&
  2843. isa<ExtractElementInst, ExtractValueInst, LoadInst, StoreInst,
  2844. InsertElementInst>(TE->getMainOp()) &&
  2845. !TE->isAltShuffle()) {
  2846. // Build correct orders for extract{element,value}, loads and
  2847. // stores.
  2848. reorderOrder(TE->ReorderIndices, Mask);
  2849. if (isa<InsertElementInst, StoreInst>(TE->getMainOp()))
  2850. TE->reorderOperands(Mask);
  2851. } else {
  2852. // Reorder the node and its operands.
  2853. TE->reorderOperands(Mask);
  2854. assert(TE->ReorderIndices.empty() &&
  2855. "Expected empty reorder sequence.");
  2856. reorderScalars(TE->Scalars, Mask);
  2857. }
  2858. if (!TE->ReuseShuffleIndices.empty()) {
  2859. // Apply reversed order to keep the original ordering of the reused
  2860. // elements to avoid extra reorder indices shuffling.
  2861. OrdersType CurrentOrder;
  2862. reorderOrder(CurrentOrder, MaskOrder);
  2863. SmallVector<int> NewReuses;
  2864. inversePermutation(CurrentOrder, NewReuses);
  2865. addMask(NewReuses, TE->ReuseShuffleIndices);
  2866. TE->ReuseShuffleIndices.swap(NewReuses);
  2867. }
  2868. }
  2869. }
  2870. }
  2871. void BoUpSLP::reorderBottomToTop(bool IgnoreReorder) {
  2872. SetVector<TreeEntry *> OrderedEntries;
  2873. DenseMap<const TreeEntry *, OrdersType> GathersToOrders;
  2874. // Find all reorderable leaf nodes with the given VF.
  2875. // Currently the are vectorized loads,extracts without alternate operands +
  2876. // some gathering of extracts.
  2877. SmallVector<TreeEntry *> NonVectorized;
  2878. for_each(VectorizableTree, [this, &OrderedEntries, &GathersToOrders,
  2879. &NonVectorized](
  2880. const std::unique_ptr<TreeEntry> &TE) {
  2881. if (TE->State != TreeEntry::Vectorize)
  2882. NonVectorized.push_back(TE.get());
  2883. if (Optional<OrdersType> CurrentOrder =
  2884. getReorderingData(*TE.get(), /*TopToBottom=*/false)) {
  2885. OrderedEntries.insert(TE.get());
  2886. if (TE->State != TreeEntry::Vectorize)
  2887. GathersToOrders.try_emplace(TE.get(), *CurrentOrder);
  2888. }
  2889. });
  2890. // Checks if the operands of the users are reordarable and have only single
  2891. // use.
  2892. auto &&CheckOperands =
  2893. [this, &NonVectorized](const auto &Data,
  2894. SmallVectorImpl<TreeEntry *> &GatherOps) {
  2895. for (unsigned I = 0, E = Data.first->getNumOperands(); I < E; ++I) {
  2896. if (any_of(Data.second,
  2897. [I](const std::pair<unsigned, TreeEntry *> &OpData) {
  2898. return OpData.first == I &&
  2899. OpData.second->State == TreeEntry::Vectorize;
  2900. }))
  2901. continue;
  2902. ArrayRef<Value *> VL = Data.first->getOperand(I);
  2903. const TreeEntry *TE = nullptr;
  2904. const auto *It = find_if(VL, [this, &TE](Value *V) {
  2905. TE = getTreeEntry(V);
  2906. return TE;
  2907. });
  2908. if (It != VL.end() && TE->isSame(VL))
  2909. return false;
  2910. TreeEntry *Gather = nullptr;
  2911. if (count_if(NonVectorized, [VL, &Gather](TreeEntry *TE) {
  2912. assert(TE->State != TreeEntry::Vectorize &&
  2913. "Only non-vectorized nodes are expected.");
  2914. if (TE->isSame(VL)) {
  2915. Gather = TE;
  2916. return true;
  2917. }
  2918. return false;
  2919. }) > 1)
  2920. return false;
  2921. if (Gather)
  2922. GatherOps.push_back(Gather);
  2923. }
  2924. return true;
  2925. };
  2926. // 1. Propagate order to the graph nodes, which use only reordered nodes.
  2927. // I.e., if the node has operands, that are reordered, try to make at least
  2928. // one operand order in the natural order and reorder others + reorder the
  2929. // user node itself.
  2930. SmallPtrSet<const TreeEntry *, 4> Visited;
  2931. while (!OrderedEntries.empty()) {
  2932. // 1. Filter out only reordered nodes.
  2933. // 2. If the entry has multiple uses - skip it and jump to the next node.
  2934. MapVector<TreeEntry *, SmallVector<std::pair<unsigned, TreeEntry *>>> Users;
  2935. SmallVector<TreeEntry *> Filtered;
  2936. for (TreeEntry *TE : OrderedEntries) {
  2937. if (!(TE->State == TreeEntry::Vectorize ||
  2938. (TE->State == TreeEntry::NeedToGather &&
  2939. GathersToOrders.count(TE))) ||
  2940. TE->UserTreeIndices.empty() || !TE->ReuseShuffleIndices.empty() ||
  2941. !all_of(drop_begin(TE->UserTreeIndices),
  2942. [TE](const EdgeInfo &EI) {
  2943. return EI.UserTE == TE->UserTreeIndices.front().UserTE;
  2944. }) ||
  2945. !Visited.insert(TE).second) {
  2946. Filtered.push_back(TE);
  2947. continue;
  2948. }
  2949. // Build a map between user nodes and their operands order to speedup
  2950. // search. The graph currently does not provide this dependency directly.
  2951. for (EdgeInfo &EI : TE->UserTreeIndices) {
  2952. TreeEntry *UserTE = EI.UserTE;
  2953. auto It = Users.find(UserTE);
  2954. if (It == Users.end())
  2955. It = Users.insert({UserTE, {}}).first;
  2956. It->second.emplace_back(EI.EdgeIdx, TE);
  2957. }
  2958. }
  2959. // Erase filtered entries.
  2960. for_each(Filtered,
  2961. [&OrderedEntries](TreeEntry *TE) { OrderedEntries.remove(TE); });
  2962. for (const auto &Data : Users) {
  2963. // Check that operands are used only in the User node.
  2964. SmallVector<TreeEntry *> GatherOps;
  2965. if (!CheckOperands(Data, GatherOps)) {
  2966. for_each(Data.second,
  2967. [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
  2968. OrderedEntries.remove(Op.second);
  2969. });
  2970. continue;
  2971. }
  2972. // All operands are reordered and used only in this node - propagate the
  2973. // most used order to the user node.
  2974. MapVector<OrdersType, unsigned,
  2975. DenseMap<OrdersType, unsigned, OrdersTypeDenseMapInfo>>
  2976. OrdersUses;
  2977. // Do the analysis for each tree entry only once, otherwise the order of
  2978. // the same node my be considered several times, though might be not
  2979. // profitable.
  2980. SmallPtrSet<const TreeEntry *, 4> VisitedOps;
  2981. for (const auto &Op : Data.second) {
  2982. TreeEntry *OpTE = Op.second;
  2983. if (!VisitedOps.insert(OpTE).second)
  2984. continue;
  2985. if (!OpTE->ReuseShuffleIndices.empty() ||
  2986. (IgnoreReorder && OpTE == VectorizableTree.front().get()))
  2987. continue;
  2988. const auto &Order = [OpTE, &GathersToOrders]() -> const OrdersType & {
  2989. if (OpTE->State == TreeEntry::NeedToGather)
  2990. return GathersToOrders.find(OpTE)->second;
  2991. return OpTE->ReorderIndices;
  2992. }();
  2993. // Stores actually store the mask, not the order, need to invert.
  2994. if (OpTE->State == TreeEntry::Vectorize && !OpTE->isAltShuffle() &&
  2995. OpTE->getOpcode() == Instruction::Store && !Order.empty()) {
  2996. SmallVector<int> Mask;
  2997. inversePermutation(Order, Mask);
  2998. unsigned E = Order.size();
  2999. OrdersType CurrentOrder(E, E);
  3000. transform(Mask, CurrentOrder.begin(), [E](int Idx) {
  3001. return Idx == UndefMaskElem ? E : static_cast<unsigned>(Idx);
  3002. });
  3003. fixupOrderingIndices(CurrentOrder);
  3004. ++OrdersUses.insert(std::make_pair(CurrentOrder, 0)).first->second;
  3005. } else {
  3006. ++OrdersUses.insert(std::make_pair(Order, 0)).first->second;
  3007. }
  3008. OrdersUses.insert(std::make_pair(OrdersType(), 0)).first->second +=
  3009. OpTE->UserTreeIndices.size();
  3010. assert(OrdersUses[{}] > 0 && "Counter cannot be less than 0.");
  3011. --OrdersUses[{}];
  3012. }
  3013. // If no orders - skip current nodes and jump to the next one, if any.
  3014. if (OrdersUses.empty()) {
  3015. for_each(Data.second,
  3016. [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
  3017. OrderedEntries.remove(Op.second);
  3018. });
  3019. continue;
  3020. }
  3021. // Choose the best order.
  3022. ArrayRef<unsigned> BestOrder = OrdersUses.front().first;
  3023. unsigned Cnt = OrdersUses.front().second;
  3024. for (const auto &Pair : drop_begin(OrdersUses)) {
  3025. if (Cnt < Pair.second || (Cnt == Pair.second && Pair.first.empty())) {
  3026. BestOrder = Pair.first;
  3027. Cnt = Pair.second;
  3028. }
  3029. }
  3030. // Set order of the user node (reordering of operands and user nodes).
  3031. if (BestOrder.empty()) {
  3032. for_each(Data.second,
  3033. [&OrderedEntries](const std::pair<unsigned, TreeEntry *> &Op) {
  3034. OrderedEntries.remove(Op.second);
  3035. });
  3036. continue;
  3037. }
  3038. // Erase operands from OrderedEntries list and adjust their orders.
  3039. VisitedOps.clear();
  3040. SmallVector<int> Mask;
  3041. inversePermutation(BestOrder, Mask);
  3042. SmallVector<int> MaskOrder(BestOrder.size(), UndefMaskElem);
  3043. unsigned E = BestOrder.size();
  3044. transform(BestOrder, MaskOrder.begin(), [E](unsigned I) {
  3045. return I < E ? static_cast<int>(I) : UndefMaskElem;
  3046. });
  3047. for (const std::pair<unsigned, TreeEntry *> &Op : Data.second) {
  3048. TreeEntry *TE = Op.second;
  3049. OrderedEntries.remove(TE);
  3050. if (!VisitedOps.insert(TE).second)
  3051. continue;
  3052. if (!TE->ReuseShuffleIndices.empty() && TE->ReorderIndices.empty()) {
  3053. // Just reorder reuses indices.
  3054. reorderReuses(TE->ReuseShuffleIndices, Mask);
  3055. continue;
  3056. }
  3057. // Gathers are processed separately.
  3058. if (TE->State != TreeEntry::Vectorize)
  3059. continue;
  3060. assert((BestOrder.size() == TE->ReorderIndices.size() ||
  3061. TE->ReorderIndices.empty()) &&
  3062. "Non-matching sizes of user/operand entries.");
  3063. reorderOrder(TE->ReorderIndices, Mask);
  3064. }
  3065. // For gathers just need to reorder its scalars.
  3066. for (TreeEntry *Gather : GatherOps) {
  3067. assert(Gather->ReorderIndices.empty() &&
  3068. "Unexpected reordering of gathers.");
  3069. if (!Gather->ReuseShuffleIndices.empty()) {
  3070. // Just reorder reuses indices.
  3071. reorderReuses(Gather->ReuseShuffleIndices, Mask);
  3072. continue;
  3073. }
  3074. reorderScalars(Gather->Scalars, Mask);
  3075. OrderedEntries.remove(Gather);
  3076. }
  3077. // Reorder operands of the user node and set the ordering for the user
  3078. // node itself.
  3079. if (Data.first->State != TreeEntry::Vectorize ||
  3080. !isa<ExtractElementInst, ExtractValueInst, LoadInst>(
  3081. Data.first->getMainOp()) ||
  3082. Data.first->isAltShuffle())
  3083. Data.first->reorderOperands(Mask);
  3084. if (!isa<InsertElementInst, StoreInst>(Data.first->getMainOp()) ||
  3085. Data.first->isAltShuffle()) {
  3086. reorderScalars(Data.first->Scalars, Mask);
  3087. reorderOrder(Data.first->ReorderIndices, MaskOrder);
  3088. if (Data.first->ReuseShuffleIndices.empty() &&
  3089. !Data.first->ReorderIndices.empty() &&
  3090. !Data.first->isAltShuffle()) {
  3091. // Insert user node to the list to try to sink reordering deeper in
  3092. // the graph.
  3093. OrderedEntries.insert(Data.first);
  3094. }
  3095. } else {
  3096. reorderOrder(Data.first->ReorderIndices, Mask);
  3097. }
  3098. }
  3099. }
  3100. // If the reordering is unnecessary, just remove the reorder.
  3101. if (IgnoreReorder && !VectorizableTree.front()->ReorderIndices.empty() &&
  3102. VectorizableTree.front()->ReuseShuffleIndices.empty())
  3103. VectorizableTree.front()->ReorderIndices.clear();
  3104. }
  3105. void BoUpSLP::buildExternalUses(
  3106. const ExtraValueToDebugLocsMap &ExternallyUsedValues) {
  3107. // Collect the values that we need to extract from the tree.
  3108. for (auto &TEPtr : VectorizableTree) {
  3109. TreeEntry *Entry = TEPtr.get();
  3110. // No need to handle users of gathered values.
  3111. if (Entry->State == TreeEntry::NeedToGather)
  3112. continue;
  3113. // For each lane:
  3114. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  3115. Value *Scalar = Entry->Scalars[Lane];
  3116. int FoundLane = Entry->findLaneForValue(Scalar);
  3117. // Check if the scalar is externally used as an extra arg.
  3118. auto ExtI = ExternallyUsedValues.find(Scalar);
  3119. if (ExtI != ExternallyUsedValues.end()) {
  3120. LLVM_DEBUG(dbgs() << "SLP: Need to extract: Extra arg from lane "
  3121. << Lane << " from " << *Scalar << ".\n");
  3122. ExternalUses.emplace_back(Scalar, nullptr, FoundLane);
  3123. }
  3124. for (User *U : Scalar->users()) {
  3125. LLVM_DEBUG(dbgs() << "SLP: Checking user:" << *U << ".\n");
  3126. Instruction *UserInst = dyn_cast<Instruction>(U);
  3127. if (!UserInst)
  3128. continue;
  3129. if (isDeleted(UserInst))
  3130. continue;
  3131. // Skip in-tree scalars that become vectors
  3132. if (TreeEntry *UseEntry = getTreeEntry(U)) {
  3133. Value *UseScalar = UseEntry->Scalars[0];
  3134. // Some in-tree scalars will remain as scalar in vectorized
  3135. // instructions. If that is the case, the one in Lane 0 will
  3136. // be used.
  3137. if (UseScalar != U ||
  3138. UseEntry->State == TreeEntry::ScatterVectorize ||
  3139. !InTreeUserNeedToExtract(Scalar, UserInst, TLI)) {
  3140. LLVM_DEBUG(dbgs() << "SLP: \tInternal user will be removed:" << *U
  3141. << ".\n");
  3142. assert(UseEntry->State != TreeEntry::NeedToGather && "Bad state");
  3143. continue;
  3144. }
  3145. }
  3146. // Ignore users in the user ignore list.
  3147. if (is_contained(UserIgnoreList, UserInst))
  3148. continue;
  3149. LLVM_DEBUG(dbgs() << "SLP: Need to extract:" << *U << " from lane "
  3150. << Lane << " from " << *Scalar << ".\n");
  3151. ExternalUses.push_back(ExternalUser(Scalar, U, FoundLane));
  3152. }
  3153. }
  3154. }
  3155. }
  3156. void BoUpSLP::buildTree(ArrayRef<Value *> Roots,
  3157. ArrayRef<Value *> UserIgnoreLst) {
  3158. deleteTree();
  3159. UserIgnoreList = UserIgnoreLst;
  3160. if (!allSameType(Roots))
  3161. return;
  3162. buildTree_rec(Roots, 0, EdgeInfo());
  3163. }
  3164. namespace {
  3165. /// Tracks the state we can represent the loads in the given sequence.
  3166. enum class LoadsState { Gather, Vectorize, ScatterVectorize };
  3167. } // anonymous namespace
  3168. /// Checks if the given array of loads can be represented as a vectorized,
  3169. /// scatter or just simple gather.
  3170. static LoadsState canVectorizeLoads(ArrayRef<Value *> VL, const Value *VL0,
  3171. const TargetTransformInfo &TTI,
  3172. const DataLayout &DL, ScalarEvolution &SE,
  3173. SmallVectorImpl<unsigned> &Order,
  3174. SmallVectorImpl<Value *> &PointerOps) {
  3175. // Check that a vectorized load would load the same memory as a scalar
  3176. // load. For example, we don't want to vectorize loads that are smaller
  3177. // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
  3178. // treats loading/storing it as an i8 struct. If we vectorize loads/stores
  3179. // from such a struct, we read/write packed bits disagreeing with the
  3180. // unvectorized version.
  3181. Type *ScalarTy = VL0->getType();
  3182. if (DL.getTypeSizeInBits(ScalarTy) != DL.getTypeAllocSizeInBits(ScalarTy))
  3183. return LoadsState::Gather;
  3184. // Make sure all loads in the bundle are simple - we can't vectorize
  3185. // atomic or volatile loads.
  3186. PointerOps.clear();
  3187. PointerOps.resize(VL.size());
  3188. auto *POIter = PointerOps.begin();
  3189. for (Value *V : VL) {
  3190. auto *L = cast<LoadInst>(V);
  3191. if (!L->isSimple())
  3192. return LoadsState::Gather;
  3193. *POIter = L->getPointerOperand();
  3194. ++POIter;
  3195. }
  3196. Order.clear();
  3197. // Check the order of pointer operands.
  3198. if (llvm::sortPtrAccesses(PointerOps, ScalarTy, DL, SE, Order)) {
  3199. Value *Ptr0;
  3200. Value *PtrN;
  3201. if (Order.empty()) {
  3202. Ptr0 = PointerOps.front();
  3203. PtrN = PointerOps.back();
  3204. } else {
  3205. Ptr0 = PointerOps[Order.front()];
  3206. PtrN = PointerOps[Order.back()];
  3207. }
  3208. Optional<int> Diff =
  3209. getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, DL, SE);
  3210. // Check that the sorted loads are consecutive.
  3211. if (static_cast<unsigned>(*Diff) == VL.size() - 1)
  3212. return LoadsState::Vectorize;
  3213. Align CommonAlignment = cast<LoadInst>(VL0)->getAlign();
  3214. for (Value *V : VL)
  3215. CommonAlignment =
  3216. commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
  3217. if (TTI.isLegalMaskedGather(FixedVectorType::get(ScalarTy, VL.size()),
  3218. CommonAlignment))
  3219. return LoadsState::ScatterVectorize;
  3220. }
  3221. return LoadsState::Gather;
  3222. }
  3223. void BoUpSLP::buildTree_rec(ArrayRef<Value *> VL, unsigned Depth,
  3224. const EdgeInfo &UserTreeIdx) {
  3225. assert((allConstant(VL) || allSameType(VL)) && "Invalid types!");
  3226. SmallVector<int> ReuseShuffleIndicies;
  3227. SmallVector<Value *> UniqueValues;
  3228. auto &&TryToFindDuplicates = [&VL, &ReuseShuffleIndicies, &UniqueValues,
  3229. &UserTreeIdx,
  3230. this](const InstructionsState &S) {
  3231. // Check that every instruction appears once in this bundle.
  3232. DenseMap<Value *, unsigned> UniquePositions;
  3233. for (Value *V : VL) {
  3234. if (isConstant(V)) {
  3235. ReuseShuffleIndicies.emplace_back(
  3236. isa<UndefValue>(V) ? UndefMaskElem : UniqueValues.size());
  3237. UniqueValues.emplace_back(V);
  3238. continue;
  3239. }
  3240. auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
  3241. ReuseShuffleIndicies.emplace_back(Res.first->second);
  3242. if (Res.second)
  3243. UniqueValues.emplace_back(V);
  3244. }
  3245. size_t NumUniqueScalarValues = UniqueValues.size();
  3246. if (NumUniqueScalarValues == VL.size()) {
  3247. ReuseShuffleIndicies.clear();
  3248. } else {
  3249. LLVM_DEBUG(dbgs() << "SLP: Shuffle for reused scalars.\n");
  3250. if (NumUniqueScalarValues <= 1 ||
  3251. (UniquePositions.size() == 1 && all_of(UniqueValues,
  3252. [](Value *V) {
  3253. return isa<UndefValue>(V) ||
  3254. !isConstant(V);
  3255. })) ||
  3256. !llvm::isPowerOf2_32(NumUniqueScalarValues)) {
  3257. LLVM_DEBUG(dbgs() << "SLP: Scalar used twice in bundle.\n");
  3258. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
  3259. return false;
  3260. }
  3261. VL = UniqueValues;
  3262. }
  3263. return true;
  3264. };
  3265. InstructionsState S = getSameOpcode(VL);
  3266. if (Depth == RecursionMaxDepth) {
  3267. LLVM_DEBUG(dbgs() << "SLP: Gathering due to max recursion depth.\n");
  3268. if (TryToFindDuplicates(S))
  3269. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3270. ReuseShuffleIndicies);
  3271. return;
  3272. }
  3273. // Don't handle scalable vectors
  3274. if (S.getOpcode() == Instruction::ExtractElement &&
  3275. isa<ScalableVectorType>(
  3276. cast<ExtractElementInst>(S.OpValue)->getVectorOperandType())) {
  3277. LLVM_DEBUG(dbgs() << "SLP: Gathering due to scalable vector type.\n");
  3278. if (TryToFindDuplicates(S))
  3279. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3280. ReuseShuffleIndicies);
  3281. return;
  3282. }
  3283. // Don't handle vectors.
  3284. if (S.OpValue->getType()->isVectorTy() &&
  3285. !isa<InsertElementInst>(S.OpValue)) {
  3286. LLVM_DEBUG(dbgs() << "SLP: Gathering due to vector type.\n");
  3287. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
  3288. return;
  3289. }
  3290. if (StoreInst *SI = dyn_cast<StoreInst>(S.OpValue))
  3291. if (SI->getValueOperand()->getType()->isVectorTy()) {
  3292. LLVM_DEBUG(dbgs() << "SLP: Gathering due to store vector type.\n");
  3293. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
  3294. return;
  3295. }
  3296. // If all of the operands are identical or constant we have a simple solution.
  3297. // If we deal with insert/extract instructions, they all must have constant
  3298. // indices, otherwise we should gather them, not try to vectorize.
  3299. if (allConstant(VL) || isSplat(VL) || !allSameBlock(VL) || !S.getOpcode() ||
  3300. (isa<InsertElementInst, ExtractValueInst, ExtractElementInst>(S.MainOp) &&
  3301. !all_of(VL, isVectorLikeInstWithConstOps))) {
  3302. LLVM_DEBUG(dbgs() << "SLP: Gathering due to C,S,B,O. \n");
  3303. if (TryToFindDuplicates(S))
  3304. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3305. ReuseShuffleIndicies);
  3306. return;
  3307. }
  3308. // We now know that this is a vector of instructions of the same type from
  3309. // the same block.
  3310. // Don't vectorize ephemeral values.
  3311. for (Value *V : VL) {
  3312. if (EphValues.count(V)) {
  3313. LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
  3314. << ") is ephemeral.\n");
  3315. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
  3316. return;
  3317. }
  3318. }
  3319. // Check if this is a duplicate of another entry.
  3320. if (TreeEntry *E = getTreeEntry(S.OpValue)) {
  3321. LLVM_DEBUG(dbgs() << "SLP: \tChecking bundle: " << *S.OpValue << ".\n");
  3322. if (!E->isSame(VL)) {
  3323. LLVM_DEBUG(dbgs() << "SLP: Gathering due to partial overlap.\n");
  3324. if (TryToFindDuplicates(S))
  3325. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3326. ReuseShuffleIndicies);
  3327. return;
  3328. }
  3329. // Record the reuse of the tree node. FIXME, currently this is only used to
  3330. // properly draw the graph rather than for the actual vectorization.
  3331. E->UserTreeIndices.push_back(UserTreeIdx);
  3332. LLVM_DEBUG(dbgs() << "SLP: Perfect diamond merge at " << *S.OpValue
  3333. << ".\n");
  3334. return;
  3335. }
  3336. // Check that none of the instructions in the bundle are already in the tree.
  3337. for (Value *V : VL) {
  3338. auto *I = dyn_cast<Instruction>(V);
  3339. if (!I)
  3340. continue;
  3341. if (getTreeEntry(I)) {
  3342. LLVM_DEBUG(dbgs() << "SLP: The instruction (" << *V
  3343. << ") is already in tree.\n");
  3344. if (TryToFindDuplicates(S))
  3345. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3346. ReuseShuffleIndicies);
  3347. return;
  3348. }
  3349. }
  3350. // The reduction nodes (stored in UserIgnoreList) also should stay scalar.
  3351. for (Value *V : VL) {
  3352. if (is_contained(UserIgnoreList, V)) {
  3353. LLVM_DEBUG(dbgs() << "SLP: Gathering due to gathered scalar.\n");
  3354. if (TryToFindDuplicates(S))
  3355. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3356. ReuseShuffleIndicies);
  3357. return;
  3358. }
  3359. }
  3360. // Check that all of the users of the scalars that we want to vectorize are
  3361. // schedulable.
  3362. auto *VL0 = cast<Instruction>(S.OpValue);
  3363. BasicBlock *BB = VL0->getParent();
  3364. if (!DT->isReachableFromEntry(BB)) {
  3365. // Don't go into unreachable blocks. They may contain instructions with
  3366. // dependency cycles which confuse the final scheduling.
  3367. LLVM_DEBUG(dbgs() << "SLP: bundle in unreachable block.\n");
  3368. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
  3369. return;
  3370. }
  3371. // Check that every instruction appears once in this bundle.
  3372. if (!TryToFindDuplicates(S))
  3373. return;
  3374. auto &BSRef = BlocksSchedules[BB];
  3375. if (!BSRef)
  3376. BSRef = std::make_unique<BlockScheduling>(BB);
  3377. BlockScheduling &BS = *BSRef.get();
  3378. Optional<ScheduleData *> Bundle = BS.tryScheduleBundle(VL, this, S);
  3379. if (!Bundle) {
  3380. LLVM_DEBUG(dbgs() << "SLP: We are not able to schedule this bundle!\n");
  3381. assert((!BS.getScheduleData(VL0) ||
  3382. !BS.getScheduleData(VL0)->isPartOfBundle()) &&
  3383. "tryScheduleBundle should cancelScheduling on failure");
  3384. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3385. ReuseShuffleIndicies);
  3386. return;
  3387. }
  3388. LLVM_DEBUG(dbgs() << "SLP: We are able to schedule this bundle.\n");
  3389. unsigned ShuffleOrOp = S.isAltShuffle() ?
  3390. (unsigned) Instruction::ShuffleVector : S.getOpcode();
  3391. switch (ShuffleOrOp) {
  3392. case Instruction::PHI: {
  3393. auto *PH = cast<PHINode>(VL0);
  3394. // Check for terminator values (e.g. invoke).
  3395. for (Value *V : VL)
  3396. for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
  3397. Instruction *Term = dyn_cast<Instruction>(
  3398. cast<PHINode>(V)->getIncomingValueForBlock(
  3399. PH->getIncomingBlock(I)));
  3400. if (Term && Term->isTerminator()) {
  3401. LLVM_DEBUG(dbgs()
  3402. << "SLP: Need to swizzle PHINodes (terminator use).\n");
  3403. BS.cancelScheduling(VL, VL0);
  3404. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3405. ReuseShuffleIndicies);
  3406. return;
  3407. }
  3408. }
  3409. TreeEntry *TE =
  3410. newTreeEntry(VL, Bundle, S, UserTreeIdx, ReuseShuffleIndicies);
  3411. LLVM_DEBUG(dbgs() << "SLP: added a vector of PHINodes.\n");
  3412. // Keeps the reordered operands to avoid code duplication.
  3413. SmallVector<ValueList, 2> OperandsVec;
  3414. for (unsigned I = 0, E = PH->getNumIncomingValues(); I < E; ++I) {
  3415. if (!DT->isReachableFromEntry(PH->getIncomingBlock(I))) {
  3416. ValueList Operands(VL.size(), PoisonValue::get(PH->getType()));
  3417. TE->setOperand(I, Operands);
  3418. OperandsVec.push_back(Operands);
  3419. continue;
  3420. }
  3421. ValueList Operands;
  3422. // Prepare the operand vector.
  3423. for (Value *V : VL)
  3424. Operands.push_back(cast<PHINode>(V)->getIncomingValueForBlock(
  3425. PH->getIncomingBlock(I)));
  3426. TE->setOperand(I, Operands);
  3427. OperandsVec.push_back(Operands);
  3428. }
  3429. for (unsigned OpIdx = 0, OpE = OperandsVec.size(); OpIdx != OpE; ++OpIdx)
  3430. buildTree_rec(OperandsVec[OpIdx], Depth + 1, {TE, OpIdx});
  3431. return;
  3432. }
  3433. case Instruction::ExtractValue:
  3434. case Instruction::ExtractElement: {
  3435. OrdersType CurrentOrder;
  3436. bool Reuse = canReuseExtract(VL, VL0, CurrentOrder);
  3437. if (Reuse) {
  3438. LLVM_DEBUG(dbgs() << "SLP: Reusing or shuffling extract sequence.\n");
  3439. newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3440. ReuseShuffleIndicies);
  3441. // This is a special case, as it does not gather, but at the same time
  3442. // we are not extending buildTree_rec() towards the operands.
  3443. ValueList Op0;
  3444. Op0.assign(VL.size(), VL0->getOperand(0));
  3445. VectorizableTree.back()->setOperand(0, Op0);
  3446. return;
  3447. }
  3448. if (!CurrentOrder.empty()) {
  3449. LLVM_DEBUG({
  3450. dbgs() << "SLP: Reusing or shuffling of reordered extract sequence "
  3451. "with order";
  3452. for (unsigned Idx : CurrentOrder)
  3453. dbgs() << " " << Idx;
  3454. dbgs() << "\n";
  3455. });
  3456. fixupOrderingIndices(CurrentOrder);
  3457. // Insert new order with initial value 0, if it does not exist,
  3458. // otherwise return the iterator to the existing one.
  3459. newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3460. ReuseShuffleIndicies, CurrentOrder);
  3461. // This is a special case, as it does not gather, but at the same time
  3462. // we are not extending buildTree_rec() towards the operands.
  3463. ValueList Op0;
  3464. Op0.assign(VL.size(), VL0->getOperand(0));
  3465. VectorizableTree.back()->setOperand(0, Op0);
  3466. return;
  3467. }
  3468. LLVM_DEBUG(dbgs() << "SLP: Gather extract sequence.\n");
  3469. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3470. ReuseShuffleIndicies);
  3471. BS.cancelScheduling(VL, VL0);
  3472. return;
  3473. }
  3474. case Instruction::InsertElement: {
  3475. assert(ReuseShuffleIndicies.empty() && "All inserts should be unique");
  3476. // Check that we have a buildvector and not a shuffle of 2 or more
  3477. // different vectors.
  3478. ValueSet SourceVectors;
  3479. for (Value *V : VL) {
  3480. SourceVectors.insert(cast<Instruction>(V)->getOperand(0));
  3481. assert(getInsertIndex(V) != None && "Non-constant or undef index?");
  3482. }
  3483. if (count_if(VL, [&SourceVectors](Value *V) {
  3484. return !SourceVectors.contains(V);
  3485. }) >= 2) {
  3486. // Found 2nd source vector - cancel.
  3487. LLVM_DEBUG(dbgs() << "SLP: Gather of insertelement vectors with "
  3488. "different source vectors.\n");
  3489. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx);
  3490. BS.cancelScheduling(VL, VL0);
  3491. return;
  3492. }
  3493. auto OrdCompare = [](const std::pair<int, int> &P1,
  3494. const std::pair<int, int> &P2) {
  3495. return P1.first > P2.first;
  3496. };
  3497. PriorityQueue<std::pair<int, int>, SmallVector<std::pair<int, int>>,
  3498. decltype(OrdCompare)>
  3499. Indices(OrdCompare);
  3500. for (int I = 0, E = VL.size(); I < E; ++I) {
  3501. unsigned Idx = *getInsertIndex(VL[I]);
  3502. Indices.emplace(Idx, I);
  3503. }
  3504. OrdersType CurrentOrder(VL.size(), VL.size());
  3505. bool IsIdentity = true;
  3506. for (int I = 0, E = VL.size(); I < E; ++I) {
  3507. CurrentOrder[Indices.top().second] = I;
  3508. IsIdentity &= Indices.top().second == I;
  3509. Indices.pop();
  3510. }
  3511. if (IsIdentity)
  3512. CurrentOrder.clear();
  3513. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3514. None, CurrentOrder);
  3515. LLVM_DEBUG(dbgs() << "SLP: added inserts bundle.\n");
  3516. constexpr int NumOps = 2;
  3517. ValueList VectorOperands[NumOps];
  3518. for (int I = 0; I < NumOps; ++I) {
  3519. for (Value *V : VL)
  3520. VectorOperands[I].push_back(cast<Instruction>(V)->getOperand(I));
  3521. TE->setOperand(I, VectorOperands[I]);
  3522. }
  3523. buildTree_rec(VectorOperands[NumOps - 1], Depth + 1, {TE, NumOps - 1});
  3524. return;
  3525. }
  3526. case Instruction::Load: {
  3527. // Check that a vectorized load would load the same memory as a scalar
  3528. // load. For example, we don't want to vectorize loads that are smaller
  3529. // than 8-bit. Even though we have a packed struct {<i2, i2, i2, i2>} LLVM
  3530. // treats loading/storing it as an i8 struct. If we vectorize loads/stores
  3531. // from such a struct, we read/write packed bits disagreeing with the
  3532. // unvectorized version.
  3533. SmallVector<Value *> PointerOps;
  3534. OrdersType CurrentOrder;
  3535. TreeEntry *TE = nullptr;
  3536. switch (canVectorizeLoads(VL, VL0, *TTI, *DL, *SE, CurrentOrder,
  3537. PointerOps)) {
  3538. case LoadsState::Vectorize:
  3539. if (CurrentOrder.empty()) {
  3540. // Original loads are consecutive and does not require reordering.
  3541. TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3542. ReuseShuffleIndicies);
  3543. LLVM_DEBUG(dbgs() << "SLP: added a vector of loads.\n");
  3544. } else {
  3545. fixupOrderingIndices(CurrentOrder);
  3546. // Need to reorder.
  3547. TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3548. ReuseShuffleIndicies, CurrentOrder);
  3549. LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled loads.\n");
  3550. }
  3551. TE->setOperandsInOrder();
  3552. break;
  3553. case LoadsState::ScatterVectorize:
  3554. // Vectorizing non-consecutive loads with `llvm.masked.gather`.
  3555. TE = newTreeEntry(VL, TreeEntry::ScatterVectorize, Bundle, S,
  3556. UserTreeIdx, ReuseShuffleIndicies);
  3557. TE->setOperandsInOrder();
  3558. buildTree_rec(PointerOps, Depth + 1, {TE, 0});
  3559. LLVM_DEBUG(dbgs() << "SLP: added a vector of non-consecutive loads.\n");
  3560. break;
  3561. case LoadsState::Gather:
  3562. BS.cancelScheduling(VL, VL0);
  3563. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3564. ReuseShuffleIndicies);
  3565. #ifndef NDEBUG
  3566. Type *ScalarTy = VL0->getType();
  3567. if (DL->getTypeSizeInBits(ScalarTy) !=
  3568. DL->getTypeAllocSizeInBits(ScalarTy))
  3569. LLVM_DEBUG(dbgs() << "SLP: Gathering loads of non-packed type.\n");
  3570. else if (any_of(VL, [](Value *V) {
  3571. return !cast<LoadInst>(V)->isSimple();
  3572. }))
  3573. LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple loads.\n");
  3574. else
  3575. LLVM_DEBUG(dbgs() << "SLP: Gathering non-consecutive loads.\n");
  3576. #endif // NDEBUG
  3577. break;
  3578. }
  3579. return;
  3580. }
  3581. case Instruction::ZExt:
  3582. case Instruction::SExt:
  3583. case Instruction::FPToUI:
  3584. case Instruction::FPToSI:
  3585. case Instruction::FPExt:
  3586. case Instruction::PtrToInt:
  3587. case Instruction::IntToPtr:
  3588. case Instruction::SIToFP:
  3589. case Instruction::UIToFP:
  3590. case Instruction::Trunc:
  3591. case Instruction::FPTrunc:
  3592. case Instruction::BitCast: {
  3593. Type *SrcTy = VL0->getOperand(0)->getType();
  3594. for (Value *V : VL) {
  3595. Type *Ty = cast<Instruction>(V)->getOperand(0)->getType();
  3596. if (Ty != SrcTy || !isValidElementType(Ty)) {
  3597. BS.cancelScheduling(VL, VL0);
  3598. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3599. ReuseShuffleIndicies);
  3600. LLVM_DEBUG(dbgs()
  3601. << "SLP: Gathering casts with different src types.\n");
  3602. return;
  3603. }
  3604. }
  3605. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3606. ReuseShuffleIndicies);
  3607. LLVM_DEBUG(dbgs() << "SLP: added a vector of casts.\n");
  3608. TE->setOperandsInOrder();
  3609. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  3610. ValueList Operands;
  3611. // Prepare the operand vector.
  3612. for (Value *V : VL)
  3613. Operands.push_back(cast<Instruction>(V)->getOperand(i));
  3614. buildTree_rec(Operands, Depth + 1, {TE, i});
  3615. }
  3616. return;
  3617. }
  3618. case Instruction::ICmp:
  3619. case Instruction::FCmp: {
  3620. // Check that all of the compares have the same predicate.
  3621. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  3622. CmpInst::Predicate SwapP0 = CmpInst::getSwappedPredicate(P0);
  3623. Type *ComparedTy = VL0->getOperand(0)->getType();
  3624. for (Value *V : VL) {
  3625. CmpInst *Cmp = cast<CmpInst>(V);
  3626. if ((Cmp->getPredicate() != P0 && Cmp->getPredicate() != SwapP0) ||
  3627. Cmp->getOperand(0)->getType() != ComparedTy) {
  3628. BS.cancelScheduling(VL, VL0);
  3629. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3630. ReuseShuffleIndicies);
  3631. LLVM_DEBUG(dbgs()
  3632. << "SLP: Gathering cmp with different predicate.\n");
  3633. return;
  3634. }
  3635. }
  3636. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3637. ReuseShuffleIndicies);
  3638. LLVM_DEBUG(dbgs() << "SLP: added a vector of compares.\n");
  3639. ValueList Left, Right;
  3640. if (cast<CmpInst>(VL0)->isCommutative()) {
  3641. // Commutative predicate - collect + sort operands of the instructions
  3642. // so that each side is more likely to have the same opcode.
  3643. assert(P0 == SwapP0 && "Commutative Predicate mismatch");
  3644. reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
  3645. } else {
  3646. // Collect operands - commute if it uses the swapped predicate.
  3647. for (Value *V : VL) {
  3648. auto *Cmp = cast<CmpInst>(V);
  3649. Value *LHS = Cmp->getOperand(0);
  3650. Value *RHS = Cmp->getOperand(1);
  3651. if (Cmp->getPredicate() != P0)
  3652. std::swap(LHS, RHS);
  3653. Left.push_back(LHS);
  3654. Right.push_back(RHS);
  3655. }
  3656. }
  3657. TE->setOperand(0, Left);
  3658. TE->setOperand(1, Right);
  3659. buildTree_rec(Left, Depth + 1, {TE, 0});
  3660. buildTree_rec(Right, Depth + 1, {TE, 1});
  3661. return;
  3662. }
  3663. case Instruction::Select:
  3664. case Instruction::FNeg:
  3665. case Instruction::Add:
  3666. case Instruction::FAdd:
  3667. case Instruction::Sub:
  3668. case Instruction::FSub:
  3669. case Instruction::Mul:
  3670. case Instruction::FMul:
  3671. case Instruction::UDiv:
  3672. case Instruction::SDiv:
  3673. case Instruction::FDiv:
  3674. case Instruction::URem:
  3675. case Instruction::SRem:
  3676. case Instruction::FRem:
  3677. case Instruction::Shl:
  3678. case Instruction::LShr:
  3679. case Instruction::AShr:
  3680. case Instruction::And:
  3681. case Instruction::Or:
  3682. case Instruction::Xor: {
  3683. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3684. ReuseShuffleIndicies);
  3685. LLVM_DEBUG(dbgs() << "SLP: added a vector of un/bin op.\n");
  3686. // Sort operands of the instructions so that each side is more likely to
  3687. // have the same opcode.
  3688. if (isa<BinaryOperator>(VL0) && VL0->isCommutative()) {
  3689. ValueList Left, Right;
  3690. reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
  3691. TE->setOperand(0, Left);
  3692. TE->setOperand(1, Right);
  3693. buildTree_rec(Left, Depth + 1, {TE, 0});
  3694. buildTree_rec(Right, Depth + 1, {TE, 1});
  3695. return;
  3696. }
  3697. TE->setOperandsInOrder();
  3698. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  3699. ValueList Operands;
  3700. // Prepare the operand vector.
  3701. for (Value *V : VL)
  3702. Operands.push_back(cast<Instruction>(V)->getOperand(i));
  3703. buildTree_rec(Operands, Depth + 1, {TE, i});
  3704. }
  3705. return;
  3706. }
  3707. case Instruction::GetElementPtr: {
  3708. // We don't combine GEPs with complicated (nested) indexing.
  3709. for (Value *V : VL) {
  3710. if (cast<Instruction>(V)->getNumOperands() != 2) {
  3711. LLVM_DEBUG(dbgs() << "SLP: not-vectorizable GEP (nested indexes).\n");
  3712. BS.cancelScheduling(VL, VL0);
  3713. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3714. ReuseShuffleIndicies);
  3715. return;
  3716. }
  3717. }
  3718. // We can't combine several GEPs into one vector if they operate on
  3719. // different types.
  3720. Type *Ty0 = VL0->getOperand(0)->getType();
  3721. for (Value *V : VL) {
  3722. Type *CurTy = cast<Instruction>(V)->getOperand(0)->getType();
  3723. if (Ty0 != CurTy) {
  3724. LLVM_DEBUG(dbgs()
  3725. << "SLP: not-vectorizable GEP (different types).\n");
  3726. BS.cancelScheduling(VL, VL0);
  3727. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3728. ReuseShuffleIndicies);
  3729. return;
  3730. }
  3731. }
  3732. // We don't combine GEPs with non-constant indexes.
  3733. Type *Ty1 = VL0->getOperand(1)->getType();
  3734. for (Value *V : VL) {
  3735. auto Op = cast<Instruction>(V)->getOperand(1);
  3736. if (!isa<ConstantInt>(Op) ||
  3737. (Op->getType() != Ty1 &&
  3738. Op->getType()->getScalarSizeInBits() >
  3739. DL->getIndexSizeInBits(
  3740. V->getType()->getPointerAddressSpace()))) {
  3741. LLVM_DEBUG(dbgs()
  3742. << "SLP: not-vectorizable GEP (non-constant indexes).\n");
  3743. BS.cancelScheduling(VL, VL0);
  3744. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3745. ReuseShuffleIndicies);
  3746. return;
  3747. }
  3748. }
  3749. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3750. ReuseShuffleIndicies);
  3751. LLVM_DEBUG(dbgs() << "SLP: added a vector of GEPs.\n");
  3752. SmallVector<ValueList, 2> Operands(2);
  3753. // Prepare the operand vector for pointer operands.
  3754. for (Value *V : VL)
  3755. Operands.front().push_back(
  3756. cast<GetElementPtrInst>(V)->getPointerOperand());
  3757. TE->setOperand(0, Operands.front());
  3758. // Need to cast all indices to the same type before vectorization to
  3759. // avoid crash.
  3760. // Required to be able to find correct matches between different gather
  3761. // nodes and reuse the vectorized values rather than trying to gather them
  3762. // again.
  3763. int IndexIdx = 1;
  3764. Type *VL0Ty = VL0->getOperand(IndexIdx)->getType();
  3765. Type *Ty = all_of(VL,
  3766. [VL0Ty, IndexIdx](Value *V) {
  3767. return VL0Ty == cast<GetElementPtrInst>(V)
  3768. ->getOperand(IndexIdx)
  3769. ->getType();
  3770. })
  3771. ? VL0Ty
  3772. : DL->getIndexType(cast<GetElementPtrInst>(VL0)
  3773. ->getPointerOperandType()
  3774. ->getScalarType());
  3775. // Prepare the operand vector.
  3776. for (Value *V : VL) {
  3777. auto *Op = cast<Instruction>(V)->getOperand(IndexIdx);
  3778. auto *CI = cast<ConstantInt>(Op);
  3779. Operands.back().push_back(ConstantExpr::getIntegerCast(
  3780. CI, Ty, CI->getValue().isSignBitSet()));
  3781. }
  3782. TE->setOperand(IndexIdx, Operands.back());
  3783. for (unsigned I = 0, Ops = Operands.size(); I < Ops; ++I)
  3784. buildTree_rec(Operands[I], Depth + 1, {TE, I});
  3785. return;
  3786. }
  3787. case Instruction::Store: {
  3788. // Check if the stores are consecutive or if we need to swizzle them.
  3789. llvm::Type *ScalarTy = cast<StoreInst>(VL0)->getValueOperand()->getType();
  3790. // Avoid types that are padded when being allocated as scalars, while
  3791. // being packed together in a vector (such as i1).
  3792. if (DL->getTypeSizeInBits(ScalarTy) !=
  3793. DL->getTypeAllocSizeInBits(ScalarTy)) {
  3794. BS.cancelScheduling(VL, VL0);
  3795. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3796. ReuseShuffleIndicies);
  3797. LLVM_DEBUG(dbgs() << "SLP: Gathering stores of non-packed type.\n");
  3798. return;
  3799. }
  3800. // Make sure all stores in the bundle are simple - we can't vectorize
  3801. // atomic or volatile stores.
  3802. SmallVector<Value *, 4> PointerOps(VL.size());
  3803. ValueList Operands(VL.size());
  3804. auto POIter = PointerOps.begin();
  3805. auto OIter = Operands.begin();
  3806. for (Value *V : VL) {
  3807. auto *SI = cast<StoreInst>(V);
  3808. if (!SI->isSimple()) {
  3809. BS.cancelScheduling(VL, VL0);
  3810. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3811. ReuseShuffleIndicies);
  3812. LLVM_DEBUG(dbgs() << "SLP: Gathering non-simple stores.\n");
  3813. return;
  3814. }
  3815. *POIter = SI->getPointerOperand();
  3816. *OIter = SI->getValueOperand();
  3817. ++POIter;
  3818. ++OIter;
  3819. }
  3820. OrdersType CurrentOrder;
  3821. // Check the order of pointer operands.
  3822. if (llvm::sortPtrAccesses(PointerOps, ScalarTy, *DL, *SE, CurrentOrder)) {
  3823. Value *Ptr0;
  3824. Value *PtrN;
  3825. if (CurrentOrder.empty()) {
  3826. Ptr0 = PointerOps.front();
  3827. PtrN = PointerOps.back();
  3828. } else {
  3829. Ptr0 = PointerOps[CurrentOrder.front()];
  3830. PtrN = PointerOps[CurrentOrder.back()];
  3831. }
  3832. Optional<int> Dist =
  3833. getPointersDiff(ScalarTy, Ptr0, ScalarTy, PtrN, *DL, *SE);
  3834. // Check that the sorted pointer operands are consecutive.
  3835. if (static_cast<unsigned>(*Dist) == VL.size() - 1) {
  3836. if (CurrentOrder.empty()) {
  3837. // Original stores are consecutive and does not require reordering.
  3838. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S,
  3839. UserTreeIdx, ReuseShuffleIndicies);
  3840. TE->setOperandsInOrder();
  3841. buildTree_rec(Operands, Depth + 1, {TE, 0});
  3842. LLVM_DEBUG(dbgs() << "SLP: added a vector of stores.\n");
  3843. } else {
  3844. fixupOrderingIndices(CurrentOrder);
  3845. TreeEntry *TE =
  3846. newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3847. ReuseShuffleIndicies, CurrentOrder);
  3848. TE->setOperandsInOrder();
  3849. buildTree_rec(Operands, Depth + 1, {TE, 0});
  3850. LLVM_DEBUG(dbgs() << "SLP: added a vector of jumbled stores.\n");
  3851. }
  3852. return;
  3853. }
  3854. }
  3855. BS.cancelScheduling(VL, VL0);
  3856. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3857. ReuseShuffleIndicies);
  3858. LLVM_DEBUG(dbgs() << "SLP: Non-consecutive store.\n");
  3859. return;
  3860. }
  3861. case Instruction::Call: {
  3862. // Check if the calls are all to the same vectorizable intrinsic or
  3863. // library function.
  3864. CallInst *CI = cast<CallInst>(VL0);
  3865. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3866. VFShape Shape = VFShape::get(
  3867. *CI, ElementCount::getFixed(static_cast<unsigned int>(VL.size())),
  3868. false /*HasGlobalPred*/);
  3869. Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
  3870. if (!VecFunc && !isTriviallyVectorizable(ID)) {
  3871. BS.cancelScheduling(VL, VL0);
  3872. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3873. ReuseShuffleIndicies);
  3874. LLVM_DEBUG(dbgs() << "SLP: Non-vectorizable call.\n");
  3875. return;
  3876. }
  3877. Function *F = CI->getCalledFunction();
  3878. unsigned NumArgs = CI->arg_size();
  3879. SmallVector<Value*, 4> ScalarArgs(NumArgs, nullptr);
  3880. for (unsigned j = 0; j != NumArgs; ++j)
  3881. if (hasVectorInstrinsicScalarOpd(ID, j))
  3882. ScalarArgs[j] = CI->getArgOperand(j);
  3883. for (Value *V : VL) {
  3884. CallInst *CI2 = dyn_cast<CallInst>(V);
  3885. if (!CI2 || CI2->getCalledFunction() != F ||
  3886. getVectorIntrinsicIDForCall(CI2, TLI) != ID ||
  3887. (VecFunc &&
  3888. VecFunc != VFDatabase(*CI2).getVectorizedFunction(Shape)) ||
  3889. !CI->hasIdenticalOperandBundleSchema(*CI2)) {
  3890. BS.cancelScheduling(VL, VL0);
  3891. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3892. ReuseShuffleIndicies);
  3893. LLVM_DEBUG(dbgs() << "SLP: mismatched calls:" << *CI << "!=" << *V
  3894. << "\n");
  3895. return;
  3896. }
  3897. // Some intrinsics have scalar arguments and should be same in order for
  3898. // them to be vectorized.
  3899. for (unsigned j = 0; j != NumArgs; ++j) {
  3900. if (hasVectorInstrinsicScalarOpd(ID, j)) {
  3901. Value *A1J = CI2->getArgOperand(j);
  3902. if (ScalarArgs[j] != A1J) {
  3903. BS.cancelScheduling(VL, VL0);
  3904. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3905. ReuseShuffleIndicies);
  3906. LLVM_DEBUG(dbgs() << "SLP: mismatched arguments in call:" << *CI
  3907. << " argument " << ScalarArgs[j] << "!=" << A1J
  3908. << "\n");
  3909. return;
  3910. }
  3911. }
  3912. }
  3913. // Verify that the bundle operands are identical between the two calls.
  3914. if (CI->hasOperandBundles() &&
  3915. !std::equal(CI->op_begin() + CI->getBundleOperandsStartIndex(),
  3916. CI->op_begin() + CI->getBundleOperandsEndIndex(),
  3917. CI2->op_begin() + CI2->getBundleOperandsStartIndex())) {
  3918. BS.cancelScheduling(VL, VL0);
  3919. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3920. ReuseShuffleIndicies);
  3921. LLVM_DEBUG(dbgs() << "SLP: mismatched bundle operands in calls:"
  3922. << *CI << "!=" << *V << '\n');
  3923. return;
  3924. }
  3925. }
  3926. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3927. ReuseShuffleIndicies);
  3928. TE->setOperandsInOrder();
  3929. for (unsigned i = 0, e = CI->arg_size(); i != e; ++i) {
  3930. // For scalar operands no need to to create an entry since no need to
  3931. // vectorize it.
  3932. if (hasVectorInstrinsicScalarOpd(ID, i))
  3933. continue;
  3934. ValueList Operands;
  3935. // Prepare the operand vector.
  3936. for (Value *V : VL) {
  3937. auto *CI2 = cast<CallInst>(V);
  3938. Operands.push_back(CI2->getArgOperand(i));
  3939. }
  3940. buildTree_rec(Operands, Depth + 1, {TE, i});
  3941. }
  3942. return;
  3943. }
  3944. case Instruction::ShuffleVector: {
  3945. // If this is not an alternate sequence of opcode like add-sub
  3946. // then do not vectorize this instruction.
  3947. if (!S.isAltShuffle()) {
  3948. BS.cancelScheduling(VL, VL0);
  3949. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3950. ReuseShuffleIndicies);
  3951. LLVM_DEBUG(dbgs() << "SLP: ShuffleVector are not vectorized.\n");
  3952. return;
  3953. }
  3954. TreeEntry *TE = newTreeEntry(VL, Bundle /*vectorized*/, S, UserTreeIdx,
  3955. ReuseShuffleIndicies);
  3956. LLVM_DEBUG(dbgs() << "SLP: added a ShuffleVector op.\n");
  3957. // Reorder operands if reordering would enable vectorization.
  3958. if (isa<BinaryOperator>(VL0)) {
  3959. ValueList Left, Right;
  3960. reorderInputsAccordingToOpcode(VL, Left, Right, *DL, *SE, *this);
  3961. TE->setOperand(0, Left);
  3962. TE->setOperand(1, Right);
  3963. buildTree_rec(Left, Depth + 1, {TE, 0});
  3964. buildTree_rec(Right, Depth + 1, {TE, 1});
  3965. return;
  3966. }
  3967. TE->setOperandsInOrder();
  3968. for (unsigned i = 0, e = VL0->getNumOperands(); i < e; ++i) {
  3969. ValueList Operands;
  3970. // Prepare the operand vector.
  3971. for (Value *V : VL)
  3972. Operands.push_back(cast<Instruction>(V)->getOperand(i));
  3973. buildTree_rec(Operands, Depth + 1, {TE, i});
  3974. }
  3975. return;
  3976. }
  3977. default:
  3978. BS.cancelScheduling(VL, VL0);
  3979. newTreeEntry(VL, None /*not vectorized*/, S, UserTreeIdx,
  3980. ReuseShuffleIndicies);
  3981. LLVM_DEBUG(dbgs() << "SLP: Gathering unknown instruction.\n");
  3982. return;
  3983. }
  3984. }
  3985. unsigned BoUpSLP::canMapToVector(Type *T, const DataLayout &DL) const {
  3986. unsigned N = 1;
  3987. Type *EltTy = T;
  3988. while (isa<StructType>(EltTy) || isa<ArrayType>(EltTy) ||
  3989. isa<VectorType>(EltTy)) {
  3990. if (auto *ST = dyn_cast<StructType>(EltTy)) {
  3991. // Check that struct is homogeneous.
  3992. for (const auto *Ty : ST->elements())
  3993. if (Ty != *ST->element_begin())
  3994. return 0;
  3995. N *= ST->getNumElements();
  3996. EltTy = *ST->element_begin();
  3997. } else if (auto *AT = dyn_cast<ArrayType>(EltTy)) {
  3998. N *= AT->getNumElements();
  3999. EltTy = AT->getElementType();
  4000. } else {
  4001. auto *VT = cast<FixedVectorType>(EltTy);
  4002. N *= VT->getNumElements();
  4003. EltTy = VT->getElementType();
  4004. }
  4005. }
  4006. if (!isValidElementType(EltTy))
  4007. return 0;
  4008. uint64_t VTSize = DL.getTypeStoreSizeInBits(FixedVectorType::get(EltTy, N));
  4009. if (VTSize < MinVecRegSize || VTSize > MaxVecRegSize || VTSize != DL.getTypeStoreSizeInBits(T))
  4010. return 0;
  4011. return N;
  4012. }
  4013. bool BoUpSLP::canReuseExtract(ArrayRef<Value *> VL, Value *OpValue,
  4014. SmallVectorImpl<unsigned> &CurrentOrder) const {
  4015. const auto *It = find_if(VL, [](Value *V) {
  4016. return isa<ExtractElementInst, ExtractValueInst>(V);
  4017. });
  4018. assert(It != VL.end() && "Expected at least one extract instruction.");
  4019. auto *E0 = cast<Instruction>(*It);
  4020. assert(all_of(VL,
  4021. [](Value *V) {
  4022. return isa<UndefValue, ExtractElementInst, ExtractValueInst>(
  4023. V);
  4024. }) &&
  4025. "Invalid opcode");
  4026. // Check if all of the extracts come from the same vector and from the
  4027. // correct offset.
  4028. Value *Vec = E0->getOperand(0);
  4029. CurrentOrder.clear();
  4030. // We have to extract from a vector/aggregate with the same number of elements.
  4031. unsigned NElts;
  4032. if (E0->getOpcode() == Instruction::ExtractValue) {
  4033. const DataLayout &DL = E0->getModule()->getDataLayout();
  4034. NElts = canMapToVector(Vec->getType(), DL);
  4035. if (!NElts)
  4036. return false;
  4037. // Check if load can be rewritten as load of vector.
  4038. LoadInst *LI = dyn_cast<LoadInst>(Vec);
  4039. if (!LI || !LI->isSimple() || !LI->hasNUses(VL.size()))
  4040. return false;
  4041. } else {
  4042. NElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
  4043. }
  4044. if (NElts != VL.size())
  4045. return false;
  4046. // Check that all of the indices extract from the correct offset.
  4047. bool ShouldKeepOrder = true;
  4048. unsigned E = VL.size();
  4049. // Assign to all items the initial value E + 1 so we can check if the extract
  4050. // instruction index was used already.
  4051. // Also, later we can check that all the indices are used and we have a
  4052. // consecutive access in the extract instructions, by checking that no
  4053. // element of CurrentOrder still has value E + 1.
  4054. CurrentOrder.assign(E, E);
  4055. unsigned I = 0;
  4056. for (; I < E; ++I) {
  4057. auto *Inst = dyn_cast<Instruction>(VL[I]);
  4058. if (!Inst)
  4059. continue;
  4060. if (Inst->getOperand(0) != Vec)
  4061. break;
  4062. if (auto *EE = dyn_cast<ExtractElementInst>(Inst))
  4063. if (isa<UndefValue>(EE->getIndexOperand()))
  4064. continue;
  4065. Optional<unsigned> Idx = getExtractIndex(Inst);
  4066. if (!Idx)
  4067. break;
  4068. const unsigned ExtIdx = *Idx;
  4069. if (ExtIdx != I) {
  4070. if (ExtIdx >= E || CurrentOrder[ExtIdx] != E)
  4071. break;
  4072. ShouldKeepOrder = false;
  4073. CurrentOrder[ExtIdx] = I;
  4074. } else {
  4075. if (CurrentOrder[I] != E)
  4076. break;
  4077. CurrentOrder[I] = I;
  4078. }
  4079. }
  4080. if (I < E) {
  4081. CurrentOrder.clear();
  4082. return false;
  4083. }
  4084. if (ShouldKeepOrder)
  4085. CurrentOrder.clear();
  4086. return ShouldKeepOrder;
  4087. }
  4088. bool BoUpSLP::areAllUsersVectorized(Instruction *I,
  4089. ArrayRef<Value *> VectorizedVals) const {
  4090. return (I->hasOneUse() && is_contained(VectorizedVals, I)) ||
  4091. all_of(I->users(), [this](User *U) {
  4092. return ScalarToTreeEntry.count(U) > 0 || MustGather.contains(U);
  4093. });
  4094. }
  4095. static std::pair<InstructionCost, InstructionCost>
  4096. getVectorCallCosts(CallInst *CI, FixedVectorType *VecTy,
  4097. TargetTransformInfo *TTI, TargetLibraryInfo *TLI) {
  4098. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  4099. // Calculate the cost of the scalar and vector calls.
  4100. SmallVector<Type *, 4> VecTys;
  4101. for (Use &Arg : CI->args())
  4102. VecTys.push_back(
  4103. FixedVectorType::get(Arg->getType(), VecTy->getNumElements()));
  4104. FastMathFlags FMF;
  4105. if (auto *FPCI = dyn_cast<FPMathOperator>(CI))
  4106. FMF = FPCI->getFastMathFlags();
  4107. SmallVector<const Value *> Arguments(CI->args());
  4108. IntrinsicCostAttributes CostAttrs(ID, VecTy, Arguments, VecTys, FMF,
  4109. dyn_cast<IntrinsicInst>(CI));
  4110. auto IntrinsicCost =
  4111. TTI->getIntrinsicInstrCost(CostAttrs, TTI::TCK_RecipThroughput);
  4112. auto Shape = VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
  4113. VecTy->getNumElements())),
  4114. false /*HasGlobalPred*/);
  4115. Function *VecFunc = VFDatabase(*CI).getVectorizedFunction(Shape);
  4116. auto LibCost = IntrinsicCost;
  4117. if (!CI->isNoBuiltin() && VecFunc) {
  4118. // Calculate the cost of the vector library call.
  4119. // If the corresponding vector call is cheaper, return its cost.
  4120. LibCost = TTI->getCallInstrCost(nullptr, VecTy, VecTys,
  4121. TTI::TCK_RecipThroughput);
  4122. }
  4123. return {IntrinsicCost, LibCost};
  4124. }
  4125. /// Compute the cost of creating a vector of type \p VecTy containing the
  4126. /// extracted values from \p VL.
  4127. static InstructionCost
  4128. computeExtractCost(ArrayRef<Value *> VL, FixedVectorType *VecTy,
  4129. TargetTransformInfo::ShuffleKind ShuffleKind,
  4130. ArrayRef<int> Mask, TargetTransformInfo &TTI) {
  4131. unsigned NumOfParts = TTI.getNumberOfParts(VecTy);
  4132. if (ShuffleKind != TargetTransformInfo::SK_PermuteSingleSrc || !NumOfParts ||
  4133. VecTy->getNumElements() < NumOfParts)
  4134. return TTI.getShuffleCost(ShuffleKind, VecTy, Mask);
  4135. bool AllConsecutive = true;
  4136. unsigned EltsPerVector = VecTy->getNumElements() / NumOfParts;
  4137. unsigned Idx = -1;
  4138. InstructionCost Cost = 0;
  4139. // Process extracts in blocks of EltsPerVector to check if the source vector
  4140. // operand can be re-used directly. If not, add the cost of creating a shuffle
  4141. // to extract the values into a vector register.
  4142. for (auto *V : VL) {
  4143. ++Idx;
  4144. // Need to exclude undefs from analysis.
  4145. if (isa<UndefValue>(V) || Mask[Idx] == UndefMaskElem)
  4146. continue;
  4147. // Reached the start of a new vector registers.
  4148. if (Idx % EltsPerVector == 0) {
  4149. AllConsecutive = true;
  4150. continue;
  4151. }
  4152. // Check all extracts for a vector register on the target directly
  4153. // extract values in order.
  4154. unsigned CurrentIdx = *getExtractIndex(cast<Instruction>(V));
  4155. if (!isa<UndefValue>(VL[Idx - 1]) && Mask[Idx - 1] != UndefMaskElem) {
  4156. unsigned PrevIdx = *getExtractIndex(cast<Instruction>(VL[Idx - 1]));
  4157. AllConsecutive &= PrevIdx + 1 == CurrentIdx &&
  4158. CurrentIdx % EltsPerVector == Idx % EltsPerVector;
  4159. }
  4160. if (AllConsecutive)
  4161. continue;
  4162. // Skip all indices, except for the last index per vector block.
  4163. if ((Idx + 1) % EltsPerVector != 0 && Idx + 1 != VL.size())
  4164. continue;
  4165. // If we have a series of extracts which are not consecutive and hence
  4166. // cannot re-use the source vector register directly, compute the shuffle
  4167. // cost to extract the a vector with EltsPerVector elements.
  4168. Cost += TTI.getShuffleCost(
  4169. TargetTransformInfo::SK_PermuteSingleSrc,
  4170. FixedVectorType::get(VecTy->getElementType(), EltsPerVector));
  4171. }
  4172. return Cost;
  4173. }
  4174. /// Build shuffle mask for shuffle graph entries and lists of main and alternate
  4175. /// operations operands.
  4176. static void
  4177. buildSuffleEntryMask(ArrayRef<Value *> VL, ArrayRef<unsigned> ReorderIndices,
  4178. ArrayRef<int> ReusesIndices,
  4179. const function_ref<bool(Instruction *)> IsAltOp,
  4180. SmallVectorImpl<int> &Mask,
  4181. SmallVectorImpl<Value *> *OpScalars = nullptr,
  4182. SmallVectorImpl<Value *> *AltScalars = nullptr) {
  4183. unsigned Sz = VL.size();
  4184. Mask.assign(Sz, UndefMaskElem);
  4185. SmallVector<int> OrderMask;
  4186. if (!ReorderIndices.empty())
  4187. inversePermutation(ReorderIndices, OrderMask);
  4188. for (unsigned I = 0; I < Sz; ++I) {
  4189. unsigned Idx = I;
  4190. if (!ReorderIndices.empty())
  4191. Idx = OrderMask[I];
  4192. auto *OpInst = cast<Instruction>(VL[Idx]);
  4193. if (IsAltOp(OpInst)) {
  4194. Mask[I] = Sz + Idx;
  4195. if (AltScalars)
  4196. AltScalars->push_back(OpInst);
  4197. } else {
  4198. Mask[I] = Idx;
  4199. if (OpScalars)
  4200. OpScalars->push_back(OpInst);
  4201. }
  4202. }
  4203. if (!ReusesIndices.empty()) {
  4204. SmallVector<int> NewMask(ReusesIndices.size(), UndefMaskElem);
  4205. transform(ReusesIndices, NewMask.begin(), [&Mask](int Idx) {
  4206. return Idx != UndefMaskElem ? Mask[Idx] : UndefMaskElem;
  4207. });
  4208. Mask.swap(NewMask);
  4209. }
  4210. }
  4211. InstructionCost BoUpSLP::getEntryCost(const TreeEntry *E,
  4212. ArrayRef<Value *> VectorizedVals) {
  4213. ArrayRef<Value*> VL = E->Scalars;
  4214. Type *ScalarTy = VL[0]->getType();
  4215. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  4216. ScalarTy = SI->getValueOperand()->getType();
  4217. else if (CmpInst *CI = dyn_cast<CmpInst>(VL[0]))
  4218. ScalarTy = CI->getOperand(0)->getType();
  4219. else if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
  4220. ScalarTy = IE->getOperand(1)->getType();
  4221. auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
  4222. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  4223. // If we have computed a smaller type for the expression, update VecTy so
  4224. // that the costs will be accurate.
  4225. if (MinBWs.count(VL[0]))
  4226. VecTy = FixedVectorType::get(
  4227. IntegerType::get(F->getContext(), MinBWs[VL[0]].first), VL.size());
  4228. unsigned EntryVF = E->getVectorFactor();
  4229. auto *FinalVecTy = FixedVectorType::get(VecTy->getElementType(), EntryVF);
  4230. bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
  4231. // FIXME: it tries to fix a problem with MSVC buildbots.
  4232. TargetTransformInfo &TTIRef = *TTI;
  4233. auto &&AdjustExtractsCost = [this, &TTIRef, CostKind, VL, VecTy,
  4234. VectorizedVals, E](InstructionCost &Cost) {
  4235. DenseMap<Value *, int> ExtractVectorsTys;
  4236. SmallPtrSet<Value *, 4> CheckedExtracts;
  4237. for (auto *V : VL) {
  4238. if (isa<UndefValue>(V))
  4239. continue;
  4240. // If all users of instruction are going to be vectorized and this
  4241. // instruction itself is not going to be vectorized, consider this
  4242. // instruction as dead and remove its cost from the final cost of the
  4243. // vectorized tree.
  4244. // Also, avoid adjusting the cost for extractelements with multiple uses
  4245. // in different graph entries.
  4246. const TreeEntry *VE = getTreeEntry(V);
  4247. if (!CheckedExtracts.insert(V).second ||
  4248. !areAllUsersVectorized(cast<Instruction>(V), VectorizedVals) ||
  4249. (VE && VE != E))
  4250. continue;
  4251. auto *EE = cast<ExtractElementInst>(V);
  4252. Optional<unsigned> EEIdx = getExtractIndex(EE);
  4253. if (!EEIdx)
  4254. continue;
  4255. unsigned Idx = *EEIdx;
  4256. if (TTIRef.getNumberOfParts(VecTy) !=
  4257. TTIRef.getNumberOfParts(EE->getVectorOperandType())) {
  4258. auto It =
  4259. ExtractVectorsTys.try_emplace(EE->getVectorOperand(), Idx).first;
  4260. It->getSecond() = std::min<int>(It->second, Idx);
  4261. }
  4262. // Take credit for instruction that will become dead.
  4263. if (EE->hasOneUse()) {
  4264. Instruction *Ext = EE->user_back();
  4265. if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  4266. all_of(Ext->users(),
  4267. [](User *U) { return isa<GetElementPtrInst>(U); })) {
  4268. // Use getExtractWithExtendCost() to calculate the cost of
  4269. // extractelement/ext pair.
  4270. Cost -=
  4271. TTIRef.getExtractWithExtendCost(Ext->getOpcode(), Ext->getType(),
  4272. EE->getVectorOperandType(), Idx);
  4273. // Add back the cost of s|zext which is subtracted separately.
  4274. Cost += TTIRef.getCastInstrCost(
  4275. Ext->getOpcode(), Ext->getType(), EE->getType(),
  4276. TTI::getCastContextHint(Ext), CostKind, Ext);
  4277. continue;
  4278. }
  4279. }
  4280. Cost -= TTIRef.getVectorInstrCost(Instruction::ExtractElement,
  4281. EE->getVectorOperandType(), Idx);
  4282. }
  4283. // Add a cost for subvector extracts/inserts if required.
  4284. for (const auto &Data : ExtractVectorsTys) {
  4285. auto *EEVTy = cast<FixedVectorType>(Data.first->getType());
  4286. unsigned NumElts = VecTy->getNumElements();
  4287. if (Data.second % NumElts == 0)
  4288. continue;
  4289. if (TTIRef.getNumberOfParts(EEVTy) > TTIRef.getNumberOfParts(VecTy)) {
  4290. unsigned Idx = (Data.second / NumElts) * NumElts;
  4291. unsigned EENumElts = EEVTy->getNumElements();
  4292. if (Idx + NumElts <= EENumElts) {
  4293. Cost +=
  4294. TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  4295. EEVTy, None, Idx, VecTy);
  4296. } else {
  4297. // Need to round up the subvector type vectorization factor to avoid a
  4298. // crash in cost model functions. Make SubVT so that Idx + VF of SubVT
  4299. // <= EENumElts.
  4300. auto *SubVT =
  4301. FixedVectorType::get(VecTy->getElementType(), EENumElts - Idx);
  4302. Cost +=
  4303. TTIRef.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  4304. EEVTy, None, Idx, SubVT);
  4305. }
  4306. } else {
  4307. Cost += TTIRef.getShuffleCost(TargetTransformInfo::SK_InsertSubvector,
  4308. VecTy, None, 0, EEVTy);
  4309. }
  4310. }
  4311. };
  4312. if (E->State == TreeEntry::NeedToGather) {
  4313. if (allConstant(VL))
  4314. return 0;
  4315. if (isa<InsertElementInst>(VL[0]))
  4316. return InstructionCost::getInvalid();
  4317. SmallVector<int> Mask;
  4318. SmallVector<const TreeEntry *> Entries;
  4319. Optional<TargetTransformInfo::ShuffleKind> Shuffle =
  4320. isGatherShuffledEntry(E, Mask, Entries);
  4321. if (Shuffle.hasValue()) {
  4322. InstructionCost GatherCost = 0;
  4323. if (ShuffleVectorInst::isIdentityMask(Mask)) {
  4324. // Perfect match in the graph, will reuse the previously vectorized
  4325. // node. Cost is 0.
  4326. LLVM_DEBUG(
  4327. dbgs()
  4328. << "SLP: perfect diamond match for gather bundle that starts with "
  4329. << *VL.front() << ".\n");
  4330. if (NeedToShuffleReuses)
  4331. GatherCost =
  4332. TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
  4333. FinalVecTy, E->ReuseShuffleIndices);
  4334. } else {
  4335. LLVM_DEBUG(dbgs() << "SLP: shuffled " << Entries.size()
  4336. << " entries for bundle that starts with "
  4337. << *VL.front() << ".\n");
  4338. // Detected that instead of gather we can emit a shuffle of single/two
  4339. // previously vectorized nodes. Add the cost of the permutation rather
  4340. // than gather.
  4341. ::addMask(Mask, E->ReuseShuffleIndices);
  4342. GatherCost = TTI->getShuffleCost(*Shuffle, FinalVecTy, Mask);
  4343. }
  4344. return GatherCost;
  4345. }
  4346. if ((E->getOpcode() == Instruction::ExtractElement ||
  4347. all_of(E->Scalars,
  4348. [](Value *V) {
  4349. return isa<ExtractElementInst, UndefValue>(V);
  4350. })) &&
  4351. allSameType(VL)) {
  4352. // Check that gather of extractelements can be represented as just a
  4353. // shuffle of a single/two vectors the scalars are extracted from.
  4354. SmallVector<int> Mask;
  4355. Optional<TargetTransformInfo::ShuffleKind> ShuffleKind =
  4356. isFixedVectorShuffle(VL, Mask);
  4357. if (ShuffleKind.hasValue()) {
  4358. // Found the bunch of extractelement instructions that must be gathered
  4359. // into a vector and can be represented as a permutation elements in a
  4360. // single input vector or of 2 input vectors.
  4361. InstructionCost Cost =
  4362. computeExtractCost(VL, VecTy, *ShuffleKind, Mask, *TTI);
  4363. AdjustExtractsCost(Cost);
  4364. if (NeedToShuffleReuses)
  4365. Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc,
  4366. FinalVecTy, E->ReuseShuffleIndices);
  4367. return Cost;
  4368. }
  4369. }
  4370. if (isSplat(VL)) {
  4371. // Found the broadcasting of the single scalar, calculate the cost as the
  4372. // broadcast.
  4373. assert(VecTy == FinalVecTy &&
  4374. "No reused scalars expected for broadcast.");
  4375. return TTI->getShuffleCost(TargetTransformInfo::SK_Broadcast, VecTy);
  4376. }
  4377. InstructionCost ReuseShuffleCost = 0;
  4378. if (NeedToShuffleReuses)
  4379. ReuseShuffleCost = TTI->getShuffleCost(
  4380. TTI::SK_PermuteSingleSrc, FinalVecTy, E->ReuseShuffleIndices);
  4381. // Improve gather cost for gather of loads, if we can group some of the
  4382. // loads into vector loads.
  4383. if (VL.size() > 2 && E->getOpcode() == Instruction::Load &&
  4384. !E->isAltShuffle()) {
  4385. BoUpSLP::ValueSet VectorizedLoads;
  4386. unsigned StartIdx = 0;
  4387. unsigned VF = VL.size() / 2;
  4388. unsigned VectorizedCnt = 0;
  4389. unsigned ScatterVectorizeCnt = 0;
  4390. const unsigned Sz = DL->getTypeSizeInBits(E->getMainOp()->getType());
  4391. for (unsigned MinVF = getMinVF(2 * Sz); VF >= MinVF; VF /= 2) {
  4392. for (unsigned Cnt = StartIdx, End = VL.size(); Cnt + VF <= End;
  4393. Cnt += VF) {
  4394. ArrayRef<Value *> Slice = VL.slice(Cnt, VF);
  4395. if (!VectorizedLoads.count(Slice.front()) &&
  4396. !VectorizedLoads.count(Slice.back()) && allSameBlock(Slice)) {
  4397. SmallVector<Value *> PointerOps;
  4398. OrdersType CurrentOrder;
  4399. LoadsState LS = canVectorizeLoads(Slice, Slice.front(), *TTI, *DL,
  4400. *SE, CurrentOrder, PointerOps);
  4401. switch (LS) {
  4402. case LoadsState::Vectorize:
  4403. case LoadsState::ScatterVectorize:
  4404. // Mark the vectorized loads so that we don't vectorize them
  4405. // again.
  4406. if (LS == LoadsState::Vectorize)
  4407. ++VectorizedCnt;
  4408. else
  4409. ++ScatterVectorizeCnt;
  4410. VectorizedLoads.insert(Slice.begin(), Slice.end());
  4411. // If we vectorized initial block, no need to try to vectorize it
  4412. // again.
  4413. if (Cnt == StartIdx)
  4414. StartIdx += VF;
  4415. break;
  4416. case LoadsState::Gather:
  4417. break;
  4418. }
  4419. }
  4420. }
  4421. // Check if the whole array was vectorized already - exit.
  4422. if (StartIdx >= VL.size())
  4423. break;
  4424. // Found vectorizable parts - exit.
  4425. if (!VectorizedLoads.empty())
  4426. break;
  4427. }
  4428. if (!VectorizedLoads.empty()) {
  4429. InstructionCost GatherCost = 0;
  4430. unsigned NumParts = TTI->getNumberOfParts(VecTy);
  4431. bool NeedInsertSubvectorAnalysis =
  4432. !NumParts || (VL.size() / VF) > NumParts;
  4433. // Get the cost for gathered loads.
  4434. for (unsigned I = 0, End = VL.size(); I < End; I += VF) {
  4435. if (VectorizedLoads.contains(VL[I]))
  4436. continue;
  4437. GatherCost += getGatherCost(VL.slice(I, VF));
  4438. }
  4439. // The cost for vectorized loads.
  4440. InstructionCost ScalarsCost = 0;
  4441. for (Value *V : VectorizedLoads) {
  4442. auto *LI = cast<LoadInst>(V);
  4443. ScalarsCost += TTI->getMemoryOpCost(
  4444. Instruction::Load, LI->getType(), LI->getAlign(),
  4445. LI->getPointerAddressSpace(), CostKind, LI);
  4446. }
  4447. auto *LI = cast<LoadInst>(E->getMainOp());
  4448. auto *LoadTy = FixedVectorType::get(LI->getType(), VF);
  4449. Align Alignment = LI->getAlign();
  4450. GatherCost +=
  4451. VectorizedCnt *
  4452. TTI->getMemoryOpCost(Instruction::Load, LoadTy, Alignment,
  4453. LI->getPointerAddressSpace(), CostKind, LI);
  4454. GatherCost += ScatterVectorizeCnt *
  4455. TTI->getGatherScatterOpCost(
  4456. Instruction::Load, LoadTy, LI->getPointerOperand(),
  4457. /*VariableMask=*/false, Alignment, CostKind, LI);
  4458. if (NeedInsertSubvectorAnalysis) {
  4459. // Add the cost for the subvectors insert.
  4460. for (int I = VF, E = VL.size(); I < E; I += VF)
  4461. GatherCost += TTI->getShuffleCost(TTI::SK_InsertSubvector, VecTy,
  4462. None, I, LoadTy);
  4463. }
  4464. return ReuseShuffleCost + GatherCost - ScalarsCost;
  4465. }
  4466. }
  4467. return ReuseShuffleCost + getGatherCost(VL);
  4468. }
  4469. InstructionCost CommonCost = 0;
  4470. SmallVector<int> Mask;
  4471. if (!E->ReorderIndices.empty()) {
  4472. SmallVector<int> NewMask;
  4473. if (E->getOpcode() == Instruction::Store) {
  4474. // For stores the order is actually a mask.
  4475. NewMask.resize(E->ReorderIndices.size());
  4476. copy(E->ReorderIndices, NewMask.begin());
  4477. } else {
  4478. inversePermutation(E->ReorderIndices, NewMask);
  4479. }
  4480. ::addMask(Mask, NewMask);
  4481. }
  4482. if (NeedToShuffleReuses)
  4483. ::addMask(Mask, E->ReuseShuffleIndices);
  4484. if (!Mask.empty() && !ShuffleVectorInst::isIdentityMask(Mask))
  4485. CommonCost =
  4486. TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, FinalVecTy, Mask);
  4487. assert((E->State == TreeEntry::Vectorize ||
  4488. E->State == TreeEntry::ScatterVectorize) &&
  4489. "Unhandled state");
  4490. assert(E->getOpcode() && allSameType(VL) && allSameBlock(VL) && "Invalid VL");
  4491. Instruction *VL0 = E->getMainOp();
  4492. unsigned ShuffleOrOp =
  4493. E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
  4494. switch (ShuffleOrOp) {
  4495. case Instruction::PHI:
  4496. return 0;
  4497. case Instruction::ExtractValue:
  4498. case Instruction::ExtractElement: {
  4499. // The common cost of removal ExtractElement/ExtractValue instructions +
  4500. // the cost of shuffles, if required to resuffle the original vector.
  4501. if (NeedToShuffleReuses) {
  4502. unsigned Idx = 0;
  4503. for (unsigned I : E->ReuseShuffleIndices) {
  4504. if (ShuffleOrOp == Instruction::ExtractElement) {
  4505. auto *EE = cast<ExtractElementInst>(VL[I]);
  4506. CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
  4507. EE->getVectorOperandType(),
  4508. *getExtractIndex(EE));
  4509. } else {
  4510. CommonCost -= TTI->getVectorInstrCost(Instruction::ExtractElement,
  4511. VecTy, Idx);
  4512. ++Idx;
  4513. }
  4514. }
  4515. Idx = EntryVF;
  4516. for (Value *V : VL) {
  4517. if (ShuffleOrOp == Instruction::ExtractElement) {
  4518. auto *EE = cast<ExtractElementInst>(V);
  4519. CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
  4520. EE->getVectorOperandType(),
  4521. *getExtractIndex(EE));
  4522. } else {
  4523. --Idx;
  4524. CommonCost += TTI->getVectorInstrCost(Instruction::ExtractElement,
  4525. VecTy, Idx);
  4526. }
  4527. }
  4528. }
  4529. if (ShuffleOrOp == Instruction::ExtractValue) {
  4530. for (unsigned I = 0, E = VL.size(); I < E; ++I) {
  4531. auto *EI = cast<Instruction>(VL[I]);
  4532. // Take credit for instruction that will become dead.
  4533. if (EI->hasOneUse()) {
  4534. Instruction *Ext = EI->user_back();
  4535. if ((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  4536. all_of(Ext->users(),
  4537. [](User *U) { return isa<GetElementPtrInst>(U); })) {
  4538. // Use getExtractWithExtendCost() to calculate the cost of
  4539. // extractelement/ext pair.
  4540. CommonCost -= TTI->getExtractWithExtendCost(
  4541. Ext->getOpcode(), Ext->getType(), VecTy, I);
  4542. // Add back the cost of s|zext which is subtracted separately.
  4543. CommonCost += TTI->getCastInstrCost(
  4544. Ext->getOpcode(), Ext->getType(), EI->getType(),
  4545. TTI::getCastContextHint(Ext), CostKind, Ext);
  4546. continue;
  4547. }
  4548. }
  4549. CommonCost -=
  4550. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, I);
  4551. }
  4552. } else {
  4553. AdjustExtractsCost(CommonCost);
  4554. }
  4555. return CommonCost;
  4556. }
  4557. case Instruction::InsertElement: {
  4558. assert(E->ReuseShuffleIndices.empty() &&
  4559. "Unique insertelements only are expected.");
  4560. auto *SrcVecTy = cast<FixedVectorType>(VL0->getType());
  4561. unsigned const NumElts = SrcVecTy->getNumElements();
  4562. unsigned const NumScalars = VL.size();
  4563. APInt DemandedElts = APInt::getZero(NumElts);
  4564. // TODO: Add support for Instruction::InsertValue.
  4565. SmallVector<int> Mask;
  4566. if (!E->ReorderIndices.empty()) {
  4567. inversePermutation(E->ReorderIndices, Mask);
  4568. Mask.append(NumElts - NumScalars, UndefMaskElem);
  4569. } else {
  4570. Mask.assign(NumElts, UndefMaskElem);
  4571. std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
  4572. }
  4573. unsigned Offset = *getInsertIndex(VL0, 0);
  4574. bool IsIdentity = true;
  4575. SmallVector<int> PrevMask(NumElts, UndefMaskElem);
  4576. Mask.swap(PrevMask);
  4577. for (unsigned I = 0; I < NumScalars; ++I) {
  4578. unsigned InsertIdx = *getInsertIndex(VL[PrevMask[I]]);
  4579. DemandedElts.setBit(InsertIdx);
  4580. IsIdentity &= InsertIdx - Offset == I;
  4581. Mask[InsertIdx - Offset] = I;
  4582. }
  4583. assert(Offset < NumElts && "Failed to find vector index offset");
  4584. InstructionCost Cost = 0;
  4585. Cost -= TTI->getScalarizationOverhead(SrcVecTy, DemandedElts,
  4586. /*Insert*/ true, /*Extract*/ false);
  4587. if (IsIdentity && NumElts != NumScalars && Offset % NumScalars != 0) {
  4588. // FIXME: Replace with SK_InsertSubvector once it is properly supported.
  4589. unsigned Sz = PowerOf2Ceil(Offset + NumScalars);
  4590. Cost += TTI->getShuffleCost(
  4591. TargetTransformInfo::SK_PermuteSingleSrc,
  4592. FixedVectorType::get(SrcVecTy->getElementType(), Sz));
  4593. } else if (!IsIdentity) {
  4594. auto *FirstInsert =
  4595. cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
  4596. return !is_contained(E->Scalars,
  4597. cast<Instruction>(V)->getOperand(0));
  4598. }));
  4599. if (isUndefVector(FirstInsert->getOperand(0))) {
  4600. Cost += TTI->getShuffleCost(TTI::SK_PermuteSingleSrc, SrcVecTy, Mask);
  4601. } else {
  4602. SmallVector<int> InsertMask(NumElts);
  4603. std::iota(InsertMask.begin(), InsertMask.end(), 0);
  4604. for (unsigned I = 0; I < NumElts; I++) {
  4605. if (Mask[I] != UndefMaskElem)
  4606. InsertMask[Offset + I] = NumElts + I;
  4607. }
  4608. Cost +=
  4609. TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, SrcVecTy, InsertMask);
  4610. }
  4611. }
  4612. return Cost;
  4613. }
  4614. case Instruction::ZExt:
  4615. case Instruction::SExt:
  4616. case Instruction::FPToUI:
  4617. case Instruction::FPToSI:
  4618. case Instruction::FPExt:
  4619. case Instruction::PtrToInt:
  4620. case Instruction::IntToPtr:
  4621. case Instruction::SIToFP:
  4622. case Instruction::UIToFP:
  4623. case Instruction::Trunc:
  4624. case Instruction::FPTrunc:
  4625. case Instruction::BitCast: {
  4626. Type *SrcTy = VL0->getOperand(0)->getType();
  4627. InstructionCost ScalarEltCost =
  4628. TTI->getCastInstrCost(E->getOpcode(), ScalarTy, SrcTy,
  4629. TTI::getCastContextHint(VL0), CostKind, VL0);
  4630. if (NeedToShuffleReuses) {
  4631. CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
  4632. }
  4633. // Calculate the cost of this instruction.
  4634. InstructionCost ScalarCost = VL.size() * ScalarEltCost;
  4635. auto *SrcVecTy = FixedVectorType::get(SrcTy, VL.size());
  4636. InstructionCost VecCost = 0;
  4637. // Check if the values are candidates to demote.
  4638. if (!MinBWs.count(VL0) || VecTy != SrcVecTy) {
  4639. VecCost = CommonCost + TTI->getCastInstrCost(
  4640. E->getOpcode(), VecTy, SrcVecTy,
  4641. TTI::getCastContextHint(VL0), CostKind, VL0);
  4642. }
  4643. LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
  4644. return VecCost - ScalarCost;
  4645. }
  4646. case Instruction::FCmp:
  4647. case Instruction::ICmp:
  4648. case Instruction::Select: {
  4649. // Calculate the cost of this instruction.
  4650. InstructionCost ScalarEltCost =
  4651. TTI->getCmpSelInstrCost(E->getOpcode(), ScalarTy, Builder.getInt1Ty(),
  4652. CmpInst::BAD_ICMP_PREDICATE, CostKind, VL0);
  4653. if (NeedToShuffleReuses) {
  4654. CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
  4655. }
  4656. auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(), VL.size());
  4657. InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
  4658. // Check if all entries in VL are either compares or selects with compares
  4659. // as condition that have the same predicates.
  4660. CmpInst::Predicate VecPred = CmpInst::BAD_ICMP_PREDICATE;
  4661. bool First = true;
  4662. for (auto *V : VL) {
  4663. CmpInst::Predicate CurrentPred;
  4664. auto MatchCmp = m_Cmp(CurrentPred, m_Value(), m_Value());
  4665. if ((!match(V, m_Select(MatchCmp, m_Value(), m_Value())) &&
  4666. !match(V, MatchCmp)) ||
  4667. (!First && VecPred != CurrentPred)) {
  4668. VecPred = CmpInst::BAD_ICMP_PREDICATE;
  4669. break;
  4670. }
  4671. First = false;
  4672. VecPred = CurrentPred;
  4673. }
  4674. InstructionCost VecCost = TTI->getCmpSelInstrCost(
  4675. E->getOpcode(), VecTy, MaskTy, VecPred, CostKind, VL0);
  4676. // Check if it is possible and profitable to use min/max for selects in
  4677. // VL.
  4678. //
  4679. auto IntrinsicAndUse = canConvertToMinOrMaxIntrinsic(VL);
  4680. if (IntrinsicAndUse.first != Intrinsic::not_intrinsic) {
  4681. IntrinsicCostAttributes CostAttrs(IntrinsicAndUse.first, VecTy,
  4682. {VecTy, VecTy});
  4683. InstructionCost IntrinsicCost =
  4684. TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
  4685. // If the selects are the only uses of the compares, they will be dead
  4686. // and we can adjust the cost by removing their cost.
  4687. if (IntrinsicAndUse.second)
  4688. IntrinsicCost -=
  4689. TTI->getCmpSelInstrCost(Instruction::ICmp, VecTy, MaskTy,
  4690. CmpInst::BAD_ICMP_PREDICATE, CostKind);
  4691. VecCost = std::min(VecCost, IntrinsicCost);
  4692. }
  4693. LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
  4694. return CommonCost + VecCost - ScalarCost;
  4695. }
  4696. case Instruction::FNeg:
  4697. case Instruction::Add:
  4698. case Instruction::FAdd:
  4699. case Instruction::Sub:
  4700. case Instruction::FSub:
  4701. case Instruction::Mul:
  4702. case Instruction::FMul:
  4703. case Instruction::UDiv:
  4704. case Instruction::SDiv:
  4705. case Instruction::FDiv:
  4706. case Instruction::URem:
  4707. case Instruction::SRem:
  4708. case Instruction::FRem:
  4709. case Instruction::Shl:
  4710. case Instruction::LShr:
  4711. case Instruction::AShr:
  4712. case Instruction::And:
  4713. case Instruction::Or:
  4714. case Instruction::Xor: {
  4715. // Certain instructions can be cheaper to vectorize if they have a
  4716. // constant second vector operand.
  4717. TargetTransformInfo::OperandValueKind Op1VK =
  4718. TargetTransformInfo::OK_AnyValue;
  4719. TargetTransformInfo::OperandValueKind Op2VK =
  4720. TargetTransformInfo::OK_UniformConstantValue;
  4721. TargetTransformInfo::OperandValueProperties Op1VP =
  4722. TargetTransformInfo::OP_None;
  4723. TargetTransformInfo::OperandValueProperties Op2VP =
  4724. TargetTransformInfo::OP_PowerOf2;
  4725. // If all operands are exactly the same ConstantInt then set the
  4726. // operand kind to OK_UniformConstantValue.
  4727. // If instead not all operands are constants, then set the operand kind
  4728. // to OK_AnyValue. If all operands are constants but not the same,
  4729. // then set the operand kind to OK_NonUniformConstantValue.
  4730. ConstantInt *CInt0 = nullptr;
  4731. for (unsigned i = 0, e = VL.size(); i < e; ++i) {
  4732. const Instruction *I = cast<Instruction>(VL[i]);
  4733. unsigned OpIdx = isa<BinaryOperator>(I) ? 1 : 0;
  4734. ConstantInt *CInt = dyn_cast<ConstantInt>(I->getOperand(OpIdx));
  4735. if (!CInt) {
  4736. Op2VK = TargetTransformInfo::OK_AnyValue;
  4737. Op2VP = TargetTransformInfo::OP_None;
  4738. break;
  4739. }
  4740. if (Op2VP == TargetTransformInfo::OP_PowerOf2 &&
  4741. !CInt->getValue().isPowerOf2())
  4742. Op2VP = TargetTransformInfo::OP_None;
  4743. if (i == 0) {
  4744. CInt0 = CInt;
  4745. continue;
  4746. }
  4747. if (CInt0 != CInt)
  4748. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  4749. }
  4750. SmallVector<const Value *, 4> Operands(VL0->operand_values());
  4751. InstructionCost ScalarEltCost =
  4752. TTI->getArithmeticInstrCost(E->getOpcode(), ScalarTy, CostKind, Op1VK,
  4753. Op2VK, Op1VP, Op2VP, Operands, VL0);
  4754. if (NeedToShuffleReuses) {
  4755. CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
  4756. }
  4757. InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
  4758. InstructionCost VecCost =
  4759. TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind, Op1VK,
  4760. Op2VK, Op1VP, Op2VP, Operands, VL0);
  4761. LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
  4762. return CommonCost + VecCost - ScalarCost;
  4763. }
  4764. case Instruction::GetElementPtr: {
  4765. TargetTransformInfo::OperandValueKind Op1VK =
  4766. TargetTransformInfo::OK_AnyValue;
  4767. TargetTransformInfo::OperandValueKind Op2VK =
  4768. TargetTransformInfo::OK_UniformConstantValue;
  4769. InstructionCost ScalarEltCost = TTI->getArithmeticInstrCost(
  4770. Instruction::Add, ScalarTy, CostKind, Op1VK, Op2VK);
  4771. if (NeedToShuffleReuses) {
  4772. CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
  4773. }
  4774. InstructionCost ScalarCost = VecTy->getNumElements() * ScalarEltCost;
  4775. InstructionCost VecCost = TTI->getArithmeticInstrCost(
  4776. Instruction::Add, VecTy, CostKind, Op1VK, Op2VK);
  4777. LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
  4778. return CommonCost + VecCost - ScalarCost;
  4779. }
  4780. case Instruction::Load: {
  4781. // Cost of wide load - cost of scalar loads.
  4782. Align Alignment = cast<LoadInst>(VL0)->getAlign();
  4783. InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
  4784. Instruction::Load, ScalarTy, Alignment, 0, CostKind, VL0);
  4785. if (NeedToShuffleReuses) {
  4786. CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
  4787. }
  4788. InstructionCost ScalarLdCost = VecTy->getNumElements() * ScalarEltCost;
  4789. InstructionCost VecLdCost;
  4790. if (E->State == TreeEntry::Vectorize) {
  4791. VecLdCost = TTI->getMemoryOpCost(Instruction::Load, VecTy, Alignment, 0,
  4792. CostKind, VL0);
  4793. } else {
  4794. assert(E->State == TreeEntry::ScatterVectorize && "Unknown EntryState");
  4795. Align CommonAlignment = Alignment;
  4796. for (Value *V : VL)
  4797. CommonAlignment =
  4798. commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
  4799. VecLdCost = TTI->getGatherScatterOpCost(
  4800. Instruction::Load, VecTy, cast<LoadInst>(VL0)->getPointerOperand(),
  4801. /*VariableMask=*/false, CommonAlignment, CostKind, VL0);
  4802. }
  4803. LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecLdCost, ScalarLdCost));
  4804. return CommonCost + VecLdCost - ScalarLdCost;
  4805. }
  4806. case Instruction::Store: {
  4807. // We know that we can merge the stores. Calculate the cost.
  4808. bool IsReorder = !E->ReorderIndices.empty();
  4809. auto *SI =
  4810. cast<StoreInst>(IsReorder ? VL[E->ReorderIndices.front()] : VL0);
  4811. Align Alignment = SI->getAlign();
  4812. InstructionCost ScalarEltCost = TTI->getMemoryOpCost(
  4813. Instruction::Store, ScalarTy, Alignment, 0, CostKind, VL0);
  4814. InstructionCost ScalarStCost = VecTy->getNumElements() * ScalarEltCost;
  4815. InstructionCost VecStCost = TTI->getMemoryOpCost(
  4816. Instruction::Store, VecTy, Alignment, 0, CostKind, VL0);
  4817. LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecStCost, ScalarStCost));
  4818. return CommonCost + VecStCost - ScalarStCost;
  4819. }
  4820. case Instruction::Call: {
  4821. CallInst *CI = cast<CallInst>(VL0);
  4822. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  4823. // Calculate the cost of the scalar and vector calls.
  4824. IntrinsicCostAttributes CostAttrs(ID, *CI, 1);
  4825. InstructionCost ScalarEltCost =
  4826. TTI->getIntrinsicInstrCost(CostAttrs, CostKind);
  4827. if (NeedToShuffleReuses) {
  4828. CommonCost -= (EntryVF - VL.size()) * ScalarEltCost;
  4829. }
  4830. InstructionCost ScalarCallCost = VecTy->getNumElements() * ScalarEltCost;
  4831. auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
  4832. InstructionCost VecCallCost =
  4833. std::min(VecCallCosts.first, VecCallCosts.second);
  4834. LLVM_DEBUG(dbgs() << "SLP: Call cost " << VecCallCost - ScalarCallCost
  4835. << " (" << VecCallCost << "-" << ScalarCallCost << ")"
  4836. << " for " << *CI << "\n");
  4837. return CommonCost + VecCallCost - ScalarCallCost;
  4838. }
  4839. case Instruction::ShuffleVector: {
  4840. assert(E->isAltShuffle() &&
  4841. ((Instruction::isBinaryOp(E->getOpcode()) &&
  4842. Instruction::isBinaryOp(E->getAltOpcode())) ||
  4843. (Instruction::isCast(E->getOpcode()) &&
  4844. Instruction::isCast(E->getAltOpcode()))) &&
  4845. "Invalid Shuffle Vector Operand");
  4846. InstructionCost ScalarCost = 0;
  4847. if (NeedToShuffleReuses) {
  4848. for (unsigned Idx : E->ReuseShuffleIndices) {
  4849. Instruction *I = cast<Instruction>(VL[Idx]);
  4850. CommonCost -= TTI->getInstructionCost(I, CostKind);
  4851. }
  4852. for (Value *V : VL) {
  4853. Instruction *I = cast<Instruction>(V);
  4854. CommonCost += TTI->getInstructionCost(I, CostKind);
  4855. }
  4856. }
  4857. for (Value *V : VL) {
  4858. Instruction *I = cast<Instruction>(V);
  4859. assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
  4860. ScalarCost += TTI->getInstructionCost(I, CostKind);
  4861. }
  4862. // VecCost is equal to sum of the cost of creating 2 vectors
  4863. // and the cost of creating shuffle.
  4864. InstructionCost VecCost = 0;
  4865. // Try to find the previous shuffle node with the same operands and same
  4866. // main/alternate ops.
  4867. auto &&TryFindNodeWithEqualOperands = [this, E]() {
  4868. for (const std::unique_ptr<TreeEntry> &TE : VectorizableTree) {
  4869. if (TE.get() == E)
  4870. break;
  4871. if (TE->isAltShuffle() &&
  4872. ((TE->getOpcode() == E->getOpcode() &&
  4873. TE->getAltOpcode() == E->getAltOpcode()) ||
  4874. (TE->getOpcode() == E->getAltOpcode() &&
  4875. TE->getAltOpcode() == E->getOpcode())) &&
  4876. TE->hasEqualOperands(*E))
  4877. return true;
  4878. }
  4879. return false;
  4880. };
  4881. if (TryFindNodeWithEqualOperands()) {
  4882. LLVM_DEBUG({
  4883. dbgs() << "SLP: diamond match for alternate node found.\n";
  4884. E->dump();
  4885. });
  4886. // No need to add new vector costs here since we're going to reuse
  4887. // same main/alternate vector ops, just do different shuffling.
  4888. } else if (Instruction::isBinaryOp(E->getOpcode())) {
  4889. VecCost = TTI->getArithmeticInstrCost(E->getOpcode(), VecTy, CostKind);
  4890. VecCost += TTI->getArithmeticInstrCost(E->getAltOpcode(), VecTy,
  4891. CostKind);
  4892. } else {
  4893. Type *Src0SclTy = E->getMainOp()->getOperand(0)->getType();
  4894. Type *Src1SclTy = E->getAltOp()->getOperand(0)->getType();
  4895. auto *Src0Ty = FixedVectorType::get(Src0SclTy, VL.size());
  4896. auto *Src1Ty = FixedVectorType::get(Src1SclTy, VL.size());
  4897. VecCost = TTI->getCastInstrCost(E->getOpcode(), VecTy, Src0Ty,
  4898. TTI::CastContextHint::None, CostKind);
  4899. VecCost += TTI->getCastInstrCost(E->getAltOpcode(), VecTy, Src1Ty,
  4900. TTI::CastContextHint::None, CostKind);
  4901. }
  4902. SmallVector<int> Mask;
  4903. buildSuffleEntryMask(
  4904. E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
  4905. [E](Instruction *I) {
  4906. assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
  4907. return I->getOpcode() == E->getAltOpcode();
  4908. },
  4909. Mask);
  4910. CommonCost =
  4911. TTI->getShuffleCost(TargetTransformInfo::SK_Select, FinalVecTy, Mask);
  4912. LLVM_DEBUG(dumpTreeCosts(E, CommonCost, VecCost, ScalarCost));
  4913. return CommonCost + VecCost - ScalarCost;
  4914. }
  4915. default:
  4916. llvm_unreachable("Unknown instruction");
  4917. }
  4918. }
  4919. bool BoUpSLP::isFullyVectorizableTinyTree(bool ForReduction) const {
  4920. LLVM_DEBUG(dbgs() << "SLP: Check whether the tree with height "
  4921. << VectorizableTree.size() << " is fully vectorizable .\n");
  4922. auto &&AreVectorizableGathers = [this](const TreeEntry *TE, unsigned Limit) {
  4923. SmallVector<int> Mask;
  4924. return TE->State == TreeEntry::NeedToGather &&
  4925. !any_of(TE->Scalars,
  4926. [this](Value *V) { return EphValues.contains(V); }) &&
  4927. (allConstant(TE->Scalars) || isSplat(TE->Scalars) ||
  4928. TE->Scalars.size() < Limit ||
  4929. ((TE->getOpcode() == Instruction::ExtractElement ||
  4930. all_of(TE->Scalars,
  4931. [](Value *V) {
  4932. return isa<ExtractElementInst, UndefValue>(V);
  4933. })) &&
  4934. isFixedVectorShuffle(TE->Scalars, Mask)) ||
  4935. (TE->State == TreeEntry::NeedToGather &&
  4936. TE->getOpcode() == Instruction::Load && !TE->isAltShuffle()));
  4937. };
  4938. // We only handle trees of heights 1 and 2.
  4939. if (VectorizableTree.size() == 1 &&
  4940. (VectorizableTree[0]->State == TreeEntry::Vectorize ||
  4941. (ForReduction &&
  4942. AreVectorizableGathers(VectorizableTree[0].get(),
  4943. VectorizableTree[0]->Scalars.size()) &&
  4944. VectorizableTree[0]->getVectorFactor() > 2)))
  4945. return true;
  4946. if (VectorizableTree.size() != 2)
  4947. return false;
  4948. // Handle splat and all-constants stores. Also try to vectorize tiny trees
  4949. // with the second gather nodes if they have less scalar operands rather than
  4950. // the initial tree element (may be profitable to shuffle the second gather)
  4951. // or they are extractelements, which form shuffle.
  4952. SmallVector<int> Mask;
  4953. if (VectorizableTree[0]->State == TreeEntry::Vectorize &&
  4954. AreVectorizableGathers(VectorizableTree[1].get(),
  4955. VectorizableTree[0]->Scalars.size()))
  4956. return true;
  4957. // Gathering cost would be too much for tiny trees.
  4958. if (VectorizableTree[0]->State == TreeEntry::NeedToGather ||
  4959. (VectorizableTree[1]->State == TreeEntry::NeedToGather &&
  4960. VectorizableTree[0]->State != TreeEntry::ScatterVectorize))
  4961. return false;
  4962. return true;
  4963. }
  4964. static bool isLoadCombineCandidateImpl(Value *Root, unsigned NumElts,
  4965. TargetTransformInfo *TTI,
  4966. bool MustMatchOrInst) {
  4967. // Look past the root to find a source value. Arbitrarily follow the
  4968. // path through operand 0 of any 'or'. Also, peek through optional
  4969. // shift-left-by-multiple-of-8-bits.
  4970. Value *ZextLoad = Root;
  4971. const APInt *ShAmtC;
  4972. bool FoundOr = false;
  4973. while (!isa<ConstantExpr>(ZextLoad) &&
  4974. (match(ZextLoad, m_Or(m_Value(), m_Value())) ||
  4975. (match(ZextLoad, m_Shl(m_Value(), m_APInt(ShAmtC))) &&
  4976. ShAmtC->urem(8) == 0))) {
  4977. auto *BinOp = cast<BinaryOperator>(ZextLoad);
  4978. ZextLoad = BinOp->getOperand(0);
  4979. if (BinOp->getOpcode() == Instruction::Or)
  4980. FoundOr = true;
  4981. }
  4982. // Check if the input is an extended load of the required or/shift expression.
  4983. Value *Load;
  4984. if ((MustMatchOrInst && !FoundOr) || ZextLoad == Root ||
  4985. !match(ZextLoad, m_ZExt(m_Value(Load))) || !isa<LoadInst>(Load))
  4986. return false;
  4987. // Require that the total load bit width is a legal integer type.
  4988. // For example, <8 x i8> --> i64 is a legal integer on a 64-bit target.
  4989. // But <16 x i8> --> i128 is not, so the backend probably can't reduce it.
  4990. Type *SrcTy = Load->getType();
  4991. unsigned LoadBitWidth = SrcTy->getIntegerBitWidth() * NumElts;
  4992. if (!TTI->isTypeLegal(IntegerType::get(Root->getContext(), LoadBitWidth)))
  4993. return false;
  4994. // Everything matched - assume that we can fold the whole sequence using
  4995. // load combining.
  4996. LLVM_DEBUG(dbgs() << "SLP: Assume load combining for tree starting at "
  4997. << *(cast<Instruction>(Root)) << "\n");
  4998. return true;
  4999. }
  5000. bool BoUpSLP::isLoadCombineReductionCandidate(RecurKind RdxKind) const {
  5001. if (RdxKind != RecurKind::Or)
  5002. return false;
  5003. unsigned NumElts = VectorizableTree[0]->Scalars.size();
  5004. Value *FirstReduced = VectorizableTree[0]->Scalars[0];
  5005. return isLoadCombineCandidateImpl(FirstReduced, NumElts, TTI,
  5006. /* MatchOr */ false);
  5007. }
  5008. bool BoUpSLP::isLoadCombineCandidate() const {
  5009. // Peek through a final sequence of stores and check if all operations are
  5010. // likely to be load-combined.
  5011. unsigned NumElts = VectorizableTree[0]->Scalars.size();
  5012. for (Value *Scalar : VectorizableTree[0]->Scalars) {
  5013. Value *X;
  5014. if (!match(Scalar, m_Store(m_Value(X), m_Value())) ||
  5015. !isLoadCombineCandidateImpl(X, NumElts, TTI, /* MatchOr */ true))
  5016. return false;
  5017. }
  5018. return true;
  5019. }
  5020. bool BoUpSLP::isTreeTinyAndNotFullyVectorizable(bool ForReduction) const {
  5021. // No need to vectorize inserts of gathered values.
  5022. if (VectorizableTree.size() == 2 &&
  5023. isa<InsertElementInst>(VectorizableTree[0]->Scalars[0]) &&
  5024. VectorizableTree[1]->State == TreeEntry::NeedToGather)
  5025. return true;
  5026. // We can vectorize the tree if its size is greater than or equal to the
  5027. // minimum size specified by the MinTreeSize command line option.
  5028. if (VectorizableTree.size() >= MinTreeSize)
  5029. return false;
  5030. // If we have a tiny tree (a tree whose size is less than MinTreeSize), we
  5031. // can vectorize it if we can prove it fully vectorizable.
  5032. if (isFullyVectorizableTinyTree(ForReduction))
  5033. return false;
  5034. assert(VectorizableTree.empty()
  5035. ? ExternalUses.empty()
  5036. : true && "We shouldn't have any external users");
  5037. // Otherwise, we can't vectorize the tree. It is both tiny and not fully
  5038. // vectorizable.
  5039. return true;
  5040. }
  5041. InstructionCost BoUpSLP::getSpillCost() const {
  5042. // Walk from the bottom of the tree to the top, tracking which values are
  5043. // live. When we see a call instruction that is not part of our tree,
  5044. // query TTI to see if there is a cost to keeping values live over it
  5045. // (for example, if spills and fills are required).
  5046. unsigned BundleWidth = VectorizableTree.front()->Scalars.size();
  5047. InstructionCost Cost = 0;
  5048. SmallPtrSet<Instruction*, 4> LiveValues;
  5049. Instruction *PrevInst = nullptr;
  5050. // The entries in VectorizableTree are not necessarily ordered by their
  5051. // position in basic blocks. Collect them and order them by dominance so later
  5052. // instructions are guaranteed to be visited first. For instructions in
  5053. // different basic blocks, we only scan to the beginning of the block, so
  5054. // their order does not matter, as long as all instructions in a basic block
  5055. // are grouped together. Using dominance ensures a deterministic order.
  5056. SmallVector<Instruction *, 16> OrderedScalars;
  5057. for (const auto &TEPtr : VectorizableTree) {
  5058. Instruction *Inst = dyn_cast<Instruction>(TEPtr->Scalars[0]);
  5059. if (!Inst)
  5060. continue;
  5061. OrderedScalars.push_back(Inst);
  5062. }
  5063. llvm::sort(OrderedScalars, [&](Instruction *A, Instruction *B) {
  5064. auto *NodeA = DT->getNode(A->getParent());
  5065. auto *NodeB = DT->getNode(B->getParent());
  5066. assert(NodeA && "Should only process reachable instructions");
  5067. assert(NodeB && "Should only process reachable instructions");
  5068. assert((NodeA == NodeB) == (NodeA->getDFSNumIn() == NodeB->getDFSNumIn()) &&
  5069. "Different nodes should have different DFS numbers");
  5070. if (NodeA != NodeB)
  5071. return NodeA->getDFSNumIn() < NodeB->getDFSNumIn();
  5072. return B->comesBefore(A);
  5073. });
  5074. for (Instruction *Inst : OrderedScalars) {
  5075. if (!PrevInst) {
  5076. PrevInst = Inst;
  5077. continue;
  5078. }
  5079. // Update LiveValues.
  5080. LiveValues.erase(PrevInst);
  5081. for (auto &J : PrevInst->operands()) {
  5082. if (isa<Instruction>(&*J) && getTreeEntry(&*J))
  5083. LiveValues.insert(cast<Instruction>(&*J));
  5084. }
  5085. LLVM_DEBUG({
  5086. dbgs() << "SLP: #LV: " << LiveValues.size();
  5087. for (auto *X : LiveValues)
  5088. dbgs() << " " << X->getName();
  5089. dbgs() << ", Looking at ";
  5090. Inst->dump();
  5091. });
  5092. // Now find the sequence of instructions between PrevInst and Inst.
  5093. unsigned NumCalls = 0;
  5094. BasicBlock::reverse_iterator InstIt = ++Inst->getIterator().getReverse(),
  5095. PrevInstIt =
  5096. PrevInst->getIterator().getReverse();
  5097. while (InstIt != PrevInstIt) {
  5098. if (PrevInstIt == PrevInst->getParent()->rend()) {
  5099. PrevInstIt = Inst->getParent()->rbegin();
  5100. continue;
  5101. }
  5102. // Debug information does not impact spill cost.
  5103. if ((isa<CallInst>(&*PrevInstIt) &&
  5104. !isa<DbgInfoIntrinsic>(&*PrevInstIt)) &&
  5105. &*PrevInstIt != PrevInst)
  5106. NumCalls++;
  5107. ++PrevInstIt;
  5108. }
  5109. if (NumCalls) {
  5110. SmallVector<Type*, 4> V;
  5111. for (auto *II : LiveValues) {
  5112. auto *ScalarTy = II->getType();
  5113. if (auto *VectorTy = dyn_cast<FixedVectorType>(ScalarTy))
  5114. ScalarTy = VectorTy->getElementType();
  5115. V.push_back(FixedVectorType::get(ScalarTy, BundleWidth));
  5116. }
  5117. Cost += NumCalls * TTI->getCostOfKeepingLiveOverCall(V);
  5118. }
  5119. PrevInst = Inst;
  5120. }
  5121. return Cost;
  5122. }
  5123. /// Check if two insertelement instructions are from the same buildvector.
  5124. static bool areTwoInsertFromSameBuildVector(InsertElementInst *VU,
  5125. InsertElementInst *V) {
  5126. // Instructions must be from the same basic blocks.
  5127. if (VU->getParent() != V->getParent())
  5128. return false;
  5129. // Checks if 2 insertelements are from the same buildvector.
  5130. if (VU->getType() != V->getType())
  5131. return false;
  5132. // Multiple used inserts are separate nodes.
  5133. if (!VU->hasOneUse() && !V->hasOneUse())
  5134. return false;
  5135. auto *IE1 = VU;
  5136. auto *IE2 = V;
  5137. // Go through the vector operand of insertelement instructions trying to find
  5138. // either VU as the original vector for IE2 or V as the original vector for
  5139. // IE1.
  5140. do {
  5141. if (IE2 == VU || IE1 == V)
  5142. return true;
  5143. if (IE1) {
  5144. if (IE1 != VU && !IE1->hasOneUse())
  5145. IE1 = nullptr;
  5146. else
  5147. IE1 = dyn_cast<InsertElementInst>(IE1->getOperand(0));
  5148. }
  5149. if (IE2) {
  5150. if (IE2 != V && !IE2->hasOneUse())
  5151. IE2 = nullptr;
  5152. else
  5153. IE2 = dyn_cast<InsertElementInst>(IE2->getOperand(0));
  5154. }
  5155. } while (IE1 || IE2);
  5156. return false;
  5157. }
  5158. InstructionCost BoUpSLP::getTreeCost(ArrayRef<Value *> VectorizedVals) {
  5159. InstructionCost Cost = 0;
  5160. LLVM_DEBUG(dbgs() << "SLP: Calculating cost for tree of size "
  5161. << VectorizableTree.size() << ".\n");
  5162. unsigned BundleWidth = VectorizableTree[0]->Scalars.size();
  5163. for (unsigned I = 0, E = VectorizableTree.size(); I < E; ++I) {
  5164. TreeEntry &TE = *VectorizableTree[I].get();
  5165. InstructionCost C = getEntryCost(&TE, VectorizedVals);
  5166. Cost += C;
  5167. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  5168. << " for bundle that starts with " << *TE.Scalars[0]
  5169. << ".\n"
  5170. << "SLP: Current total cost = " << Cost << "\n");
  5171. }
  5172. SmallPtrSet<Value *, 16> ExtractCostCalculated;
  5173. InstructionCost ExtractCost = 0;
  5174. SmallVector<unsigned> VF;
  5175. SmallVector<SmallVector<int>> ShuffleMask;
  5176. SmallVector<Value *> FirstUsers;
  5177. SmallVector<APInt> DemandedElts;
  5178. for (ExternalUser &EU : ExternalUses) {
  5179. // We only add extract cost once for the same scalar.
  5180. if (!isa_and_nonnull<InsertElementInst>(EU.User) &&
  5181. !ExtractCostCalculated.insert(EU.Scalar).second)
  5182. continue;
  5183. // Uses by ephemeral values are free (because the ephemeral value will be
  5184. // removed prior to code generation, and so the extraction will be
  5185. // removed as well).
  5186. if (EphValues.count(EU.User))
  5187. continue;
  5188. // No extract cost for vector "scalar"
  5189. if (isa<FixedVectorType>(EU.Scalar->getType()))
  5190. continue;
  5191. // Already counted the cost for external uses when tried to adjust the cost
  5192. // for extractelements, no need to add it again.
  5193. if (isa<ExtractElementInst>(EU.Scalar))
  5194. continue;
  5195. // If found user is an insertelement, do not calculate extract cost but try
  5196. // to detect it as a final shuffled/identity match.
  5197. if (auto *VU = dyn_cast_or_null<InsertElementInst>(EU.User)) {
  5198. if (auto *FTy = dyn_cast<FixedVectorType>(VU->getType())) {
  5199. Optional<unsigned> InsertIdx = getInsertIndex(VU);
  5200. if (InsertIdx) {
  5201. auto *It = find_if(FirstUsers, [VU](Value *V) {
  5202. return areTwoInsertFromSameBuildVector(VU,
  5203. cast<InsertElementInst>(V));
  5204. });
  5205. int VecId = -1;
  5206. if (It == FirstUsers.end()) {
  5207. VF.push_back(FTy->getNumElements());
  5208. ShuffleMask.emplace_back(VF.back(), UndefMaskElem);
  5209. // Find the insertvector, vectorized in tree, if any.
  5210. Value *Base = VU;
  5211. while (isa<InsertElementInst>(Base)) {
  5212. // Build the mask for the vectorized insertelement instructions.
  5213. if (const TreeEntry *E = getTreeEntry(Base)) {
  5214. VU = cast<InsertElementInst>(Base);
  5215. do {
  5216. int Idx = E->findLaneForValue(Base);
  5217. ShuffleMask.back()[Idx] = Idx;
  5218. Base = cast<InsertElementInst>(Base)->getOperand(0);
  5219. } while (E == getTreeEntry(Base));
  5220. break;
  5221. }
  5222. Base = cast<InsertElementInst>(Base)->getOperand(0);
  5223. }
  5224. FirstUsers.push_back(VU);
  5225. DemandedElts.push_back(APInt::getZero(VF.back()));
  5226. VecId = FirstUsers.size() - 1;
  5227. } else {
  5228. VecId = std::distance(FirstUsers.begin(), It);
  5229. }
  5230. ShuffleMask[VecId][*InsertIdx] = EU.Lane;
  5231. DemandedElts[VecId].setBit(*InsertIdx);
  5232. continue;
  5233. }
  5234. }
  5235. }
  5236. // If we plan to rewrite the tree in a smaller type, we will need to sign
  5237. // extend the extracted value back to the original type. Here, we account
  5238. // for the extract and the added cost of the sign extend if needed.
  5239. auto *VecTy = FixedVectorType::get(EU.Scalar->getType(), BundleWidth);
  5240. auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
  5241. if (MinBWs.count(ScalarRoot)) {
  5242. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  5243. auto Extend =
  5244. MinBWs[ScalarRoot].second ? Instruction::SExt : Instruction::ZExt;
  5245. VecTy = FixedVectorType::get(MinTy, BundleWidth);
  5246. ExtractCost += TTI->getExtractWithExtendCost(Extend, EU.Scalar->getType(),
  5247. VecTy, EU.Lane);
  5248. } else {
  5249. ExtractCost +=
  5250. TTI->getVectorInstrCost(Instruction::ExtractElement, VecTy, EU.Lane);
  5251. }
  5252. }
  5253. InstructionCost SpillCost = getSpillCost();
  5254. Cost += SpillCost + ExtractCost;
  5255. if (FirstUsers.size() == 1) {
  5256. int Limit = ShuffleMask.front().size() * 2;
  5257. if (all_of(ShuffleMask.front(), [Limit](int Idx) { return Idx < Limit; }) &&
  5258. !ShuffleVectorInst::isIdentityMask(ShuffleMask.front())) {
  5259. InstructionCost C = TTI->getShuffleCost(
  5260. TTI::SK_PermuteSingleSrc,
  5261. cast<FixedVectorType>(FirstUsers.front()->getType()),
  5262. ShuffleMask.front());
  5263. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  5264. << " for final shuffle of insertelement external users "
  5265. << *VectorizableTree.front()->Scalars.front() << ".\n"
  5266. << "SLP: Current total cost = " << Cost << "\n");
  5267. Cost += C;
  5268. }
  5269. InstructionCost InsertCost = TTI->getScalarizationOverhead(
  5270. cast<FixedVectorType>(FirstUsers.front()->getType()),
  5271. DemandedElts.front(), /*Insert*/ true, /*Extract*/ false);
  5272. LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
  5273. << " for insertelements gather.\n"
  5274. << "SLP: Current total cost = " << Cost << "\n");
  5275. Cost -= InsertCost;
  5276. } else if (FirstUsers.size() >= 2) {
  5277. unsigned MaxVF = *std::max_element(VF.begin(), VF.end());
  5278. // Combined masks of the first 2 vectors.
  5279. SmallVector<int> CombinedMask(MaxVF, UndefMaskElem);
  5280. copy(ShuffleMask.front(), CombinedMask.begin());
  5281. APInt CombinedDemandedElts = DemandedElts.front().zextOrSelf(MaxVF);
  5282. auto *VecTy = FixedVectorType::get(
  5283. cast<VectorType>(FirstUsers.front()->getType())->getElementType(),
  5284. MaxVF);
  5285. for (int I = 0, E = ShuffleMask[1].size(); I < E; ++I) {
  5286. if (ShuffleMask[1][I] != UndefMaskElem) {
  5287. CombinedMask[I] = ShuffleMask[1][I] + MaxVF;
  5288. CombinedDemandedElts.setBit(I);
  5289. }
  5290. }
  5291. InstructionCost C =
  5292. TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
  5293. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  5294. << " for final shuffle of vector node and external "
  5295. "insertelement users "
  5296. << *VectorizableTree.front()->Scalars.front() << ".\n"
  5297. << "SLP: Current total cost = " << Cost << "\n");
  5298. Cost += C;
  5299. InstructionCost InsertCost = TTI->getScalarizationOverhead(
  5300. VecTy, CombinedDemandedElts, /*Insert*/ true, /*Extract*/ false);
  5301. LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
  5302. << " for insertelements gather.\n"
  5303. << "SLP: Current total cost = " << Cost << "\n");
  5304. Cost -= InsertCost;
  5305. for (int I = 2, E = FirstUsers.size(); I < E; ++I) {
  5306. // Other elements - permutation of 2 vectors (the initial one and the
  5307. // next Ith incoming vector).
  5308. unsigned VF = ShuffleMask[I].size();
  5309. for (unsigned Idx = 0; Idx < VF; ++Idx) {
  5310. int Mask = ShuffleMask[I][Idx];
  5311. if (Mask != UndefMaskElem)
  5312. CombinedMask[Idx] = MaxVF + Mask;
  5313. else if (CombinedMask[Idx] != UndefMaskElem)
  5314. CombinedMask[Idx] = Idx;
  5315. }
  5316. for (unsigned Idx = VF; Idx < MaxVF; ++Idx)
  5317. if (CombinedMask[Idx] != UndefMaskElem)
  5318. CombinedMask[Idx] = Idx;
  5319. InstructionCost C =
  5320. TTI->getShuffleCost(TTI::SK_PermuteTwoSrc, VecTy, CombinedMask);
  5321. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << C
  5322. << " for final shuffle of vector node and external "
  5323. "insertelement users "
  5324. << *VectorizableTree.front()->Scalars.front() << ".\n"
  5325. << "SLP: Current total cost = " << Cost << "\n");
  5326. Cost += C;
  5327. InstructionCost InsertCost = TTI->getScalarizationOverhead(
  5328. cast<FixedVectorType>(FirstUsers[I]->getType()), DemandedElts[I],
  5329. /*Insert*/ true, /*Extract*/ false);
  5330. LLVM_DEBUG(dbgs() << "SLP: subtracting the cost " << InsertCost
  5331. << " for insertelements gather.\n"
  5332. << "SLP: Current total cost = " << Cost << "\n");
  5333. Cost -= InsertCost;
  5334. }
  5335. }
  5336. #ifndef NDEBUG
  5337. SmallString<256> Str;
  5338. {
  5339. raw_svector_ostream OS(Str);
  5340. OS << "SLP: Spill Cost = " << SpillCost << ".\n"
  5341. << "SLP: Extract Cost = " << ExtractCost << ".\n"
  5342. << "SLP: Total Cost = " << Cost << ".\n";
  5343. }
  5344. LLVM_DEBUG(dbgs() << Str);
  5345. if (ViewSLPTree)
  5346. ViewGraph(this, "SLP" + F->getName(), false, Str);
  5347. #endif
  5348. return Cost;
  5349. }
  5350. Optional<TargetTransformInfo::ShuffleKind>
  5351. BoUpSLP::isGatherShuffledEntry(const TreeEntry *TE, SmallVectorImpl<int> &Mask,
  5352. SmallVectorImpl<const TreeEntry *> &Entries) {
  5353. // TODO: currently checking only for Scalars in the tree entry, need to count
  5354. // reused elements too for better cost estimation.
  5355. Mask.assign(TE->Scalars.size(), UndefMaskElem);
  5356. Entries.clear();
  5357. // Build a lists of values to tree entries.
  5358. DenseMap<Value *, SmallPtrSet<const TreeEntry *, 4>> ValueToTEs;
  5359. for (const std::unique_ptr<TreeEntry> &EntryPtr : VectorizableTree) {
  5360. if (EntryPtr.get() == TE)
  5361. break;
  5362. if (EntryPtr->State != TreeEntry::NeedToGather)
  5363. continue;
  5364. for (Value *V : EntryPtr->Scalars)
  5365. ValueToTEs.try_emplace(V).first->getSecond().insert(EntryPtr.get());
  5366. }
  5367. // Find all tree entries used by the gathered values. If no common entries
  5368. // found - not a shuffle.
  5369. // Here we build a set of tree nodes for each gathered value and trying to
  5370. // find the intersection between these sets. If we have at least one common
  5371. // tree node for each gathered value - we have just a permutation of the
  5372. // single vector. If we have 2 different sets, we're in situation where we
  5373. // have a permutation of 2 input vectors.
  5374. SmallVector<SmallPtrSet<const TreeEntry *, 4>> UsedTEs;
  5375. DenseMap<Value *, int> UsedValuesEntry;
  5376. for (Value *V : TE->Scalars) {
  5377. if (isa<UndefValue>(V))
  5378. continue;
  5379. // Build a list of tree entries where V is used.
  5380. SmallPtrSet<const TreeEntry *, 4> VToTEs;
  5381. auto It = ValueToTEs.find(V);
  5382. if (It != ValueToTEs.end())
  5383. VToTEs = It->second;
  5384. if (const TreeEntry *VTE = getTreeEntry(V))
  5385. VToTEs.insert(VTE);
  5386. if (VToTEs.empty())
  5387. return None;
  5388. if (UsedTEs.empty()) {
  5389. // The first iteration, just insert the list of nodes to vector.
  5390. UsedTEs.push_back(VToTEs);
  5391. } else {
  5392. // Need to check if there are any previously used tree nodes which use V.
  5393. // If there are no such nodes, consider that we have another one input
  5394. // vector.
  5395. SmallPtrSet<const TreeEntry *, 4> SavedVToTEs(VToTEs);
  5396. unsigned Idx = 0;
  5397. for (SmallPtrSet<const TreeEntry *, 4> &Set : UsedTEs) {
  5398. // Do we have a non-empty intersection of previously listed tree entries
  5399. // and tree entries using current V?
  5400. set_intersect(VToTEs, Set);
  5401. if (!VToTEs.empty()) {
  5402. // Yes, write the new subset and continue analysis for the next
  5403. // scalar.
  5404. Set.swap(VToTEs);
  5405. break;
  5406. }
  5407. VToTEs = SavedVToTEs;
  5408. ++Idx;
  5409. }
  5410. // No non-empty intersection found - need to add a second set of possible
  5411. // source vectors.
  5412. if (Idx == UsedTEs.size()) {
  5413. // If the number of input vectors is greater than 2 - not a permutation,
  5414. // fallback to the regular gather.
  5415. if (UsedTEs.size() == 2)
  5416. return None;
  5417. UsedTEs.push_back(SavedVToTEs);
  5418. Idx = UsedTEs.size() - 1;
  5419. }
  5420. UsedValuesEntry.try_emplace(V, Idx);
  5421. }
  5422. }
  5423. unsigned VF = 0;
  5424. if (UsedTEs.size() == 1) {
  5425. // Try to find the perfect match in another gather node at first.
  5426. auto It = find_if(UsedTEs.front(), [TE](const TreeEntry *EntryPtr) {
  5427. return EntryPtr->isSame(TE->Scalars);
  5428. });
  5429. if (It != UsedTEs.front().end()) {
  5430. Entries.push_back(*It);
  5431. std::iota(Mask.begin(), Mask.end(), 0);
  5432. return TargetTransformInfo::SK_PermuteSingleSrc;
  5433. }
  5434. // No perfect match, just shuffle, so choose the first tree node.
  5435. Entries.push_back(*UsedTEs.front().begin());
  5436. } else {
  5437. // Try to find nodes with the same vector factor.
  5438. assert(UsedTEs.size() == 2 && "Expected at max 2 permuted entries.");
  5439. DenseMap<int, const TreeEntry *> VFToTE;
  5440. for (const TreeEntry *TE : UsedTEs.front())
  5441. VFToTE.try_emplace(TE->getVectorFactor(), TE);
  5442. for (const TreeEntry *TE : UsedTEs.back()) {
  5443. auto It = VFToTE.find(TE->getVectorFactor());
  5444. if (It != VFToTE.end()) {
  5445. VF = It->first;
  5446. Entries.push_back(It->second);
  5447. Entries.push_back(TE);
  5448. break;
  5449. }
  5450. }
  5451. // No 2 source vectors with the same vector factor - give up and do regular
  5452. // gather.
  5453. if (Entries.empty())
  5454. return None;
  5455. }
  5456. // Build a shuffle mask for better cost estimation and vector emission.
  5457. for (int I = 0, E = TE->Scalars.size(); I < E; ++I) {
  5458. Value *V = TE->Scalars[I];
  5459. if (isa<UndefValue>(V))
  5460. continue;
  5461. unsigned Idx = UsedValuesEntry.lookup(V);
  5462. const TreeEntry *VTE = Entries[Idx];
  5463. int FoundLane = VTE->findLaneForValue(V);
  5464. Mask[I] = Idx * VF + FoundLane;
  5465. // Extra check required by isSingleSourceMaskImpl function (called by
  5466. // ShuffleVectorInst::isSingleSourceMask).
  5467. if (Mask[I] >= 2 * E)
  5468. return None;
  5469. }
  5470. switch (Entries.size()) {
  5471. case 1:
  5472. return TargetTransformInfo::SK_PermuteSingleSrc;
  5473. case 2:
  5474. return TargetTransformInfo::SK_PermuteTwoSrc;
  5475. default:
  5476. break;
  5477. }
  5478. return None;
  5479. }
  5480. InstructionCost
  5481. BoUpSLP::getGatherCost(FixedVectorType *Ty,
  5482. const DenseSet<unsigned> &ShuffledIndices,
  5483. bool NeedToShuffle) const {
  5484. unsigned NumElts = Ty->getNumElements();
  5485. APInt DemandedElts = APInt::getZero(NumElts);
  5486. for (unsigned I = 0; I < NumElts; ++I)
  5487. if (!ShuffledIndices.count(I))
  5488. DemandedElts.setBit(I);
  5489. InstructionCost Cost =
  5490. TTI->getScalarizationOverhead(Ty, DemandedElts, /*Insert*/ true,
  5491. /*Extract*/ false);
  5492. if (NeedToShuffle)
  5493. Cost += TTI->getShuffleCost(TargetTransformInfo::SK_PermuteSingleSrc, Ty);
  5494. return Cost;
  5495. }
  5496. InstructionCost BoUpSLP::getGatherCost(ArrayRef<Value *> VL) const {
  5497. // Find the type of the operands in VL.
  5498. Type *ScalarTy = VL[0]->getType();
  5499. if (StoreInst *SI = dyn_cast<StoreInst>(VL[0]))
  5500. ScalarTy = SI->getValueOperand()->getType();
  5501. auto *VecTy = FixedVectorType::get(ScalarTy, VL.size());
  5502. bool DuplicateNonConst = false;
  5503. // Find the cost of inserting/extracting values from the vector.
  5504. // Check if the same elements are inserted several times and count them as
  5505. // shuffle candidates.
  5506. DenseSet<unsigned> ShuffledElements;
  5507. DenseSet<Value *> UniqueElements;
  5508. // Iterate in reverse order to consider insert elements with the high cost.
  5509. for (unsigned I = VL.size(); I > 0; --I) {
  5510. unsigned Idx = I - 1;
  5511. // No need to shuffle duplicates for constants.
  5512. if (isConstant(VL[Idx])) {
  5513. ShuffledElements.insert(Idx);
  5514. continue;
  5515. }
  5516. if (!UniqueElements.insert(VL[Idx]).second) {
  5517. DuplicateNonConst = true;
  5518. ShuffledElements.insert(Idx);
  5519. }
  5520. }
  5521. return getGatherCost(VecTy, ShuffledElements, DuplicateNonConst);
  5522. }
  5523. // Perform operand reordering on the instructions in VL and return the reordered
  5524. // operands in Left and Right.
  5525. void BoUpSLP::reorderInputsAccordingToOpcode(ArrayRef<Value *> VL,
  5526. SmallVectorImpl<Value *> &Left,
  5527. SmallVectorImpl<Value *> &Right,
  5528. const DataLayout &DL,
  5529. ScalarEvolution &SE,
  5530. const BoUpSLP &R) {
  5531. if (VL.empty())
  5532. return;
  5533. VLOperands Ops(VL, DL, SE, R);
  5534. // Reorder the operands in place.
  5535. Ops.reorder();
  5536. Left = Ops.getVL(0);
  5537. Right = Ops.getVL(1);
  5538. }
  5539. void BoUpSLP::setInsertPointAfterBundle(const TreeEntry *E) {
  5540. // Get the basic block this bundle is in. All instructions in the bundle
  5541. // should be in this block.
  5542. auto *Front = E->getMainOp();
  5543. auto *BB = Front->getParent();
  5544. assert(llvm::all_of(E->Scalars, [=](Value *V) -> bool {
  5545. auto *I = cast<Instruction>(V);
  5546. return !E->isOpcodeOrAlt(I) || I->getParent() == BB;
  5547. }));
  5548. // The last instruction in the bundle in program order.
  5549. Instruction *LastInst = nullptr;
  5550. // Find the last instruction. The common case should be that BB has been
  5551. // scheduled, and the last instruction is VL.back(). So we start with
  5552. // VL.back() and iterate over schedule data until we reach the end of the
  5553. // bundle. The end of the bundle is marked by null ScheduleData.
  5554. if (BlocksSchedules.count(BB)) {
  5555. auto *Bundle =
  5556. BlocksSchedules[BB]->getScheduleData(E->isOneOf(E->Scalars.back()));
  5557. if (Bundle && Bundle->isPartOfBundle())
  5558. for (; Bundle; Bundle = Bundle->NextInBundle)
  5559. if (Bundle->OpValue == Bundle->Inst)
  5560. LastInst = Bundle->Inst;
  5561. }
  5562. // LastInst can still be null at this point if there's either not an entry
  5563. // for BB in BlocksSchedules or there's no ScheduleData available for
  5564. // VL.back(). This can be the case if buildTree_rec aborts for various
  5565. // reasons (e.g., the maximum recursion depth is reached, the maximum region
  5566. // size is reached, etc.). ScheduleData is initialized in the scheduling
  5567. // "dry-run".
  5568. //
  5569. // If this happens, we can still find the last instruction by brute force. We
  5570. // iterate forwards from Front (inclusive) until we either see all
  5571. // instructions in the bundle or reach the end of the block. If Front is the
  5572. // last instruction in program order, LastInst will be set to Front, and we
  5573. // will visit all the remaining instructions in the block.
  5574. //
  5575. // One of the reasons we exit early from buildTree_rec is to place an upper
  5576. // bound on compile-time. Thus, taking an additional compile-time hit here is
  5577. // not ideal. However, this should be exceedingly rare since it requires that
  5578. // we both exit early from buildTree_rec and that the bundle be out-of-order
  5579. // (causing us to iterate all the way to the end of the block).
  5580. if (!LastInst) {
  5581. SmallPtrSet<Value *, 16> Bundle(E->Scalars.begin(), E->Scalars.end());
  5582. for (auto &I : make_range(BasicBlock::iterator(Front), BB->end())) {
  5583. if (Bundle.erase(&I) && E->isOpcodeOrAlt(&I))
  5584. LastInst = &I;
  5585. if (Bundle.empty())
  5586. break;
  5587. }
  5588. }
  5589. assert(LastInst && "Failed to find last instruction in bundle");
  5590. // Set the insertion point after the last instruction in the bundle. Set the
  5591. // debug location to Front.
  5592. Builder.SetInsertPoint(BB, ++LastInst->getIterator());
  5593. Builder.SetCurrentDebugLocation(Front->getDebugLoc());
  5594. }
  5595. Value *BoUpSLP::gather(ArrayRef<Value *> VL) {
  5596. // List of instructions/lanes from current block and/or the blocks which are
  5597. // part of the current loop. These instructions will be inserted at the end to
  5598. // make it possible to optimize loops and hoist invariant instructions out of
  5599. // the loops body with better chances for success.
  5600. SmallVector<std::pair<Value *, unsigned>, 4> PostponedInsts;
  5601. SmallSet<int, 4> PostponedIndices;
  5602. Loop *L = LI->getLoopFor(Builder.GetInsertBlock());
  5603. auto &&CheckPredecessor = [](BasicBlock *InstBB, BasicBlock *InsertBB) {
  5604. SmallPtrSet<BasicBlock *, 4> Visited;
  5605. while (InsertBB && InsertBB != InstBB && Visited.insert(InsertBB).second)
  5606. InsertBB = InsertBB->getSinglePredecessor();
  5607. return InsertBB && InsertBB == InstBB;
  5608. };
  5609. for (int I = 0, E = VL.size(); I < E; ++I) {
  5610. if (auto *Inst = dyn_cast<Instruction>(VL[I]))
  5611. if ((CheckPredecessor(Inst->getParent(), Builder.GetInsertBlock()) ||
  5612. getTreeEntry(Inst) || (L && (L->contains(Inst)))) &&
  5613. PostponedIndices.insert(I).second)
  5614. PostponedInsts.emplace_back(Inst, I);
  5615. }
  5616. auto &&CreateInsertElement = [this](Value *Vec, Value *V, unsigned Pos) {
  5617. Vec = Builder.CreateInsertElement(Vec, V, Builder.getInt32(Pos));
  5618. auto *InsElt = dyn_cast<InsertElementInst>(Vec);
  5619. if (!InsElt)
  5620. return Vec;
  5621. GatherShuffleSeq.insert(InsElt);
  5622. CSEBlocks.insert(InsElt->getParent());
  5623. // Add to our 'need-to-extract' list.
  5624. if (TreeEntry *Entry = getTreeEntry(V)) {
  5625. // Find which lane we need to extract.
  5626. unsigned FoundLane = Entry->findLaneForValue(V);
  5627. ExternalUses.emplace_back(V, InsElt, FoundLane);
  5628. }
  5629. return Vec;
  5630. };
  5631. Value *Val0 =
  5632. isa<StoreInst>(VL[0]) ? cast<StoreInst>(VL[0])->getValueOperand() : VL[0];
  5633. FixedVectorType *VecTy = FixedVectorType::get(Val0->getType(), VL.size());
  5634. Value *Vec = PoisonValue::get(VecTy);
  5635. SmallVector<int> NonConsts;
  5636. // Insert constant values at first.
  5637. for (int I = 0, E = VL.size(); I < E; ++I) {
  5638. if (PostponedIndices.contains(I))
  5639. continue;
  5640. if (!isConstant(VL[I])) {
  5641. NonConsts.push_back(I);
  5642. continue;
  5643. }
  5644. Vec = CreateInsertElement(Vec, VL[I], I);
  5645. }
  5646. // Insert non-constant values.
  5647. for (int I : NonConsts)
  5648. Vec = CreateInsertElement(Vec, VL[I], I);
  5649. // Append instructions, which are/may be part of the loop, in the end to make
  5650. // it possible to hoist non-loop-based instructions.
  5651. for (const std::pair<Value *, unsigned> &Pair : PostponedInsts)
  5652. Vec = CreateInsertElement(Vec, Pair.first, Pair.second);
  5653. return Vec;
  5654. }
  5655. namespace {
  5656. /// Merges shuffle masks and emits final shuffle instruction, if required.
  5657. class ShuffleInstructionBuilder {
  5658. IRBuilderBase &Builder;
  5659. const unsigned VF = 0;
  5660. bool IsFinalized = false;
  5661. SmallVector<int, 4> Mask;
  5662. /// Holds all of the instructions that we gathered.
  5663. SetVector<Instruction *> &GatherShuffleSeq;
  5664. /// A list of blocks that we are going to CSE.
  5665. SetVector<BasicBlock *> &CSEBlocks;
  5666. public:
  5667. ShuffleInstructionBuilder(IRBuilderBase &Builder, unsigned VF,
  5668. SetVector<Instruction *> &GatherShuffleSeq,
  5669. SetVector<BasicBlock *> &CSEBlocks)
  5670. : Builder(Builder), VF(VF), GatherShuffleSeq(GatherShuffleSeq),
  5671. CSEBlocks(CSEBlocks) {}
  5672. /// Adds a mask, inverting it before applying.
  5673. void addInversedMask(ArrayRef<unsigned> SubMask) {
  5674. if (SubMask.empty())
  5675. return;
  5676. SmallVector<int, 4> NewMask;
  5677. inversePermutation(SubMask, NewMask);
  5678. addMask(NewMask);
  5679. }
  5680. /// Functions adds masks, merging them into single one.
  5681. void addMask(ArrayRef<unsigned> SubMask) {
  5682. SmallVector<int, 4> NewMask(SubMask.begin(), SubMask.end());
  5683. addMask(NewMask);
  5684. }
  5685. void addMask(ArrayRef<int> SubMask) { ::addMask(Mask, SubMask); }
  5686. Value *finalize(Value *V) {
  5687. IsFinalized = true;
  5688. unsigned ValueVF = cast<FixedVectorType>(V->getType())->getNumElements();
  5689. if (VF == ValueVF && Mask.empty())
  5690. return V;
  5691. SmallVector<int, 4> NormalizedMask(VF, UndefMaskElem);
  5692. std::iota(NormalizedMask.begin(), NormalizedMask.end(), 0);
  5693. addMask(NormalizedMask);
  5694. if (VF == ValueVF && ShuffleVectorInst::isIdentityMask(Mask))
  5695. return V;
  5696. Value *Vec = Builder.CreateShuffleVector(V, Mask, "shuffle");
  5697. if (auto *I = dyn_cast<Instruction>(Vec)) {
  5698. GatherShuffleSeq.insert(I);
  5699. CSEBlocks.insert(I->getParent());
  5700. }
  5701. return Vec;
  5702. }
  5703. ~ShuffleInstructionBuilder() {
  5704. assert((IsFinalized || Mask.empty()) &&
  5705. "Shuffle construction must be finalized.");
  5706. }
  5707. };
  5708. } // namespace
  5709. Value *BoUpSLP::vectorizeTree(ArrayRef<Value *> VL) {
  5710. unsigned VF = VL.size();
  5711. InstructionsState S = getSameOpcode(VL);
  5712. if (S.getOpcode()) {
  5713. if (TreeEntry *E = getTreeEntry(S.OpValue))
  5714. if (E->isSame(VL)) {
  5715. Value *V = vectorizeTree(E);
  5716. if (VF != cast<FixedVectorType>(V->getType())->getNumElements()) {
  5717. if (!E->ReuseShuffleIndices.empty()) {
  5718. // Reshuffle to get only unique values.
  5719. // If some of the scalars are duplicated in the vectorization tree
  5720. // entry, we do not vectorize them but instead generate a mask for
  5721. // the reuses. But if there are several users of the same entry,
  5722. // they may have different vectorization factors. This is especially
  5723. // important for PHI nodes. In this case, we need to adapt the
  5724. // resulting instruction for the user vectorization factor and have
  5725. // to reshuffle it again to take only unique elements of the vector.
  5726. // Without this code the function incorrectly returns reduced vector
  5727. // instruction with the same elements, not with the unique ones.
  5728. // block:
  5729. // %phi = phi <2 x > { .., %entry} {%shuffle, %block}
  5730. // %2 = shuffle <2 x > %phi, poison, <4 x > <1, 1, 0, 0>
  5731. // ... (use %2)
  5732. // %shuffle = shuffle <2 x> %2, poison, <2 x> {2, 0}
  5733. // br %block
  5734. SmallVector<int> UniqueIdxs(VF, UndefMaskElem);
  5735. SmallSet<int, 4> UsedIdxs;
  5736. int Pos = 0;
  5737. int Sz = VL.size();
  5738. for (int Idx : E->ReuseShuffleIndices) {
  5739. if (Idx != Sz && Idx != UndefMaskElem &&
  5740. UsedIdxs.insert(Idx).second)
  5741. UniqueIdxs[Idx] = Pos;
  5742. ++Pos;
  5743. }
  5744. assert(VF >= UsedIdxs.size() && "Expected vectorization factor "
  5745. "less than original vector size.");
  5746. UniqueIdxs.append(VF - UsedIdxs.size(), UndefMaskElem);
  5747. V = Builder.CreateShuffleVector(V, UniqueIdxs, "shrink.shuffle");
  5748. } else {
  5749. assert(VF < cast<FixedVectorType>(V->getType())->getNumElements() &&
  5750. "Expected vectorization factor less "
  5751. "than original vector size.");
  5752. SmallVector<int> UniformMask(VF, 0);
  5753. std::iota(UniformMask.begin(), UniformMask.end(), 0);
  5754. V = Builder.CreateShuffleVector(V, UniformMask, "shrink.shuffle");
  5755. }
  5756. if (auto *I = dyn_cast<Instruction>(V)) {
  5757. GatherShuffleSeq.insert(I);
  5758. CSEBlocks.insert(I->getParent());
  5759. }
  5760. }
  5761. return V;
  5762. }
  5763. }
  5764. // Check that every instruction appears once in this bundle.
  5765. SmallVector<int> ReuseShuffleIndicies;
  5766. SmallVector<Value *> UniqueValues;
  5767. if (VL.size() > 2) {
  5768. DenseMap<Value *, unsigned> UniquePositions;
  5769. unsigned NumValues =
  5770. std::distance(VL.begin(), find_if(reverse(VL), [](Value *V) {
  5771. return !isa<UndefValue>(V);
  5772. }).base());
  5773. VF = std::max<unsigned>(VF, PowerOf2Ceil(NumValues));
  5774. int UniqueVals = 0;
  5775. for (Value *V : VL.drop_back(VL.size() - VF)) {
  5776. if (isa<UndefValue>(V)) {
  5777. ReuseShuffleIndicies.emplace_back(UndefMaskElem);
  5778. continue;
  5779. }
  5780. if (isConstant(V)) {
  5781. ReuseShuffleIndicies.emplace_back(UniqueValues.size());
  5782. UniqueValues.emplace_back(V);
  5783. continue;
  5784. }
  5785. auto Res = UniquePositions.try_emplace(V, UniqueValues.size());
  5786. ReuseShuffleIndicies.emplace_back(Res.first->second);
  5787. if (Res.second) {
  5788. UniqueValues.emplace_back(V);
  5789. ++UniqueVals;
  5790. }
  5791. }
  5792. if (UniqueVals == 1 && UniqueValues.size() == 1) {
  5793. // Emit pure splat vector.
  5794. ReuseShuffleIndicies.append(VF - ReuseShuffleIndicies.size(),
  5795. UndefMaskElem);
  5796. } else if (UniqueValues.size() >= VF - 1 || UniqueValues.size() <= 1) {
  5797. ReuseShuffleIndicies.clear();
  5798. UniqueValues.clear();
  5799. UniqueValues.append(VL.begin(), std::next(VL.begin(), NumValues));
  5800. }
  5801. UniqueValues.append(VF - UniqueValues.size(),
  5802. PoisonValue::get(VL[0]->getType()));
  5803. VL = UniqueValues;
  5804. }
  5805. ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
  5806. CSEBlocks);
  5807. Value *Vec = gather(VL);
  5808. if (!ReuseShuffleIndicies.empty()) {
  5809. ShuffleBuilder.addMask(ReuseShuffleIndicies);
  5810. Vec = ShuffleBuilder.finalize(Vec);
  5811. }
  5812. return Vec;
  5813. }
  5814. Value *BoUpSLP::vectorizeTree(TreeEntry *E) {
  5815. IRBuilder<>::InsertPointGuard Guard(Builder);
  5816. if (E->VectorizedValue) {
  5817. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *E->Scalars[0] << ".\n");
  5818. return E->VectorizedValue;
  5819. }
  5820. bool NeedToShuffleReuses = !E->ReuseShuffleIndices.empty();
  5821. unsigned VF = E->getVectorFactor();
  5822. ShuffleInstructionBuilder ShuffleBuilder(Builder, VF, GatherShuffleSeq,
  5823. CSEBlocks);
  5824. if (E->State == TreeEntry::NeedToGather) {
  5825. if (E->getMainOp())
  5826. setInsertPointAfterBundle(E);
  5827. Value *Vec;
  5828. SmallVector<int> Mask;
  5829. SmallVector<const TreeEntry *> Entries;
  5830. Optional<TargetTransformInfo::ShuffleKind> Shuffle =
  5831. isGatherShuffledEntry(E, Mask, Entries);
  5832. if (Shuffle.hasValue()) {
  5833. assert((Entries.size() == 1 || Entries.size() == 2) &&
  5834. "Expected shuffle of 1 or 2 entries.");
  5835. Vec = Builder.CreateShuffleVector(Entries.front()->VectorizedValue,
  5836. Entries.back()->VectorizedValue, Mask);
  5837. if (auto *I = dyn_cast<Instruction>(Vec)) {
  5838. GatherShuffleSeq.insert(I);
  5839. CSEBlocks.insert(I->getParent());
  5840. }
  5841. } else {
  5842. Vec = gather(E->Scalars);
  5843. }
  5844. if (NeedToShuffleReuses) {
  5845. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  5846. Vec = ShuffleBuilder.finalize(Vec);
  5847. }
  5848. E->VectorizedValue = Vec;
  5849. return Vec;
  5850. }
  5851. assert((E->State == TreeEntry::Vectorize ||
  5852. E->State == TreeEntry::ScatterVectorize) &&
  5853. "Unhandled state");
  5854. unsigned ShuffleOrOp =
  5855. E->isAltShuffle() ? (unsigned)Instruction::ShuffleVector : E->getOpcode();
  5856. Instruction *VL0 = E->getMainOp();
  5857. Type *ScalarTy = VL0->getType();
  5858. if (auto *Store = dyn_cast<StoreInst>(VL0))
  5859. ScalarTy = Store->getValueOperand()->getType();
  5860. else if (auto *IE = dyn_cast<InsertElementInst>(VL0))
  5861. ScalarTy = IE->getOperand(1)->getType();
  5862. auto *VecTy = FixedVectorType::get(ScalarTy, E->Scalars.size());
  5863. switch (ShuffleOrOp) {
  5864. case Instruction::PHI: {
  5865. assert(
  5866. (E->ReorderIndices.empty() || E != VectorizableTree.front().get()) &&
  5867. "PHI reordering is free.");
  5868. auto *PH = cast<PHINode>(VL0);
  5869. Builder.SetInsertPoint(PH->getParent()->getFirstNonPHI());
  5870. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  5871. PHINode *NewPhi = Builder.CreatePHI(VecTy, PH->getNumIncomingValues());
  5872. Value *V = NewPhi;
  5873. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  5874. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  5875. V = ShuffleBuilder.finalize(V);
  5876. E->VectorizedValue = V;
  5877. // PHINodes may have multiple entries from the same block. We want to
  5878. // visit every block once.
  5879. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  5880. for (unsigned i = 0, e = PH->getNumIncomingValues(); i < e; ++i) {
  5881. ValueList Operands;
  5882. BasicBlock *IBB = PH->getIncomingBlock(i);
  5883. if (!VisitedBBs.insert(IBB).second) {
  5884. NewPhi->addIncoming(NewPhi->getIncomingValueForBlock(IBB), IBB);
  5885. continue;
  5886. }
  5887. Builder.SetInsertPoint(IBB->getTerminator());
  5888. Builder.SetCurrentDebugLocation(PH->getDebugLoc());
  5889. Value *Vec = vectorizeTree(E->getOperand(i));
  5890. NewPhi->addIncoming(Vec, IBB);
  5891. }
  5892. assert(NewPhi->getNumIncomingValues() == PH->getNumIncomingValues() &&
  5893. "Invalid number of incoming values");
  5894. return V;
  5895. }
  5896. case Instruction::ExtractElement: {
  5897. Value *V = E->getSingleOperand(0);
  5898. Builder.SetInsertPoint(VL0);
  5899. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  5900. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  5901. V = ShuffleBuilder.finalize(V);
  5902. E->VectorizedValue = V;
  5903. return V;
  5904. }
  5905. case Instruction::ExtractValue: {
  5906. auto *LI = cast<LoadInst>(E->getSingleOperand(0));
  5907. Builder.SetInsertPoint(LI);
  5908. auto *PtrTy = PointerType::get(VecTy, LI->getPointerAddressSpace());
  5909. Value *Ptr = Builder.CreateBitCast(LI->getOperand(0), PtrTy);
  5910. LoadInst *V = Builder.CreateAlignedLoad(VecTy, Ptr, LI->getAlign());
  5911. Value *NewV = propagateMetadata(V, E->Scalars);
  5912. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  5913. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  5914. NewV = ShuffleBuilder.finalize(NewV);
  5915. E->VectorizedValue = NewV;
  5916. return NewV;
  5917. }
  5918. case Instruction::InsertElement: {
  5919. assert(E->ReuseShuffleIndices.empty() && "All inserts should be unique");
  5920. Builder.SetInsertPoint(cast<Instruction>(E->Scalars.back()));
  5921. Value *V = vectorizeTree(E->getOperand(1));
  5922. // Create InsertVector shuffle if necessary
  5923. auto *FirstInsert = cast<Instruction>(*find_if(E->Scalars, [E](Value *V) {
  5924. return !is_contained(E->Scalars, cast<Instruction>(V)->getOperand(0));
  5925. }));
  5926. const unsigned NumElts =
  5927. cast<FixedVectorType>(FirstInsert->getType())->getNumElements();
  5928. const unsigned NumScalars = E->Scalars.size();
  5929. unsigned Offset = *getInsertIndex(VL0, 0);
  5930. assert(Offset < NumElts && "Failed to find vector index offset");
  5931. // Create shuffle to resize vector
  5932. SmallVector<int> Mask;
  5933. if (!E->ReorderIndices.empty()) {
  5934. inversePermutation(E->ReorderIndices, Mask);
  5935. Mask.append(NumElts - NumScalars, UndefMaskElem);
  5936. } else {
  5937. Mask.assign(NumElts, UndefMaskElem);
  5938. std::iota(Mask.begin(), std::next(Mask.begin(), NumScalars), 0);
  5939. }
  5940. // Create InsertVector shuffle if necessary
  5941. bool IsIdentity = true;
  5942. SmallVector<int> PrevMask(NumElts, UndefMaskElem);
  5943. Mask.swap(PrevMask);
  5944. for (unsigned I = 0; I < NumScalars; ++I) {
  5945. Value *Scalar = E->Scalars[PrevMask[I]];
  5946. unsigned InsertIdx = *getInsertIndex(Scalar);
  5947. IsIdentity &= InsertIdx - Offset == I;
  5948. Mask[InsertIdx - Offset] = I;
  5949. }
  5950. if (!IsIdentity || NumElts != NumScalars) {
  5951. V = Builder.CreateShuffleVector(V, Mask);
  5952. if (auto *I = dyn_cast<Instruction>(V)) {
  5953. GatherShuffleSeq.insert(I);
  5954. CSEBlocks.insert(I->getParent());
  5955. }
  5956. }
  5957. if ((!IsIdentity || Offset != 0 ||
  5958. !isUndefVector(FirstInsert->getOperand(0))) &&
  5959. NumElts != NumScalars) {
  5960. SmallVector<int> InsertMask(NumElts);
  5961. std::iota(InsertMask.begin(), InsertMask.end(), 0);
  5962. for (unsigned I = 0; I < NumElts; I++) {
  5963. if (Mask[I] != UndefMaskElem)
  5964. InsertMask[Offset + I] = NumElts + I;
  5965. }
  5966. V = Builder.CreateShuffleVector(
  5967. FirstInsert->getOperand(0), V, InsertMask,
  5968. cast<Instruction>(E->Scalars.back())->getName());
  5969. if (auto *I = dyn_cast<Instruction>(V)) {
  5970. GatherShuffleSeq.insert(I);
  5971. CSEBlocks.insert(I->getParent());
  5972. }
  5973. }
  5974. ++NumVectorInstructions;
  5975. E->VectorizedValue = V;
  5976. return V;
  5977. }
  5978. case Instruction::ZExt:
  5979. case Instruction::SExt:
  5980. case Instruction::FPToUI:
  5981. case Instruction::FPToSI:
  5982. case Instruction::FPExt:
  5983. case Instruction::PtrToInt:
  5984. case Instruction::IntToPtr:
  5985. case Instruction::SIToFP:
  5986. case Instruction::UIToFP:
  5987. case Instruction::Trunc:
  5988. case Instruction::FPTrunc:
  5989. case Instruction::BitCast: {
  5990. setInsertPointAfterBundle(E);
  5991. Value *InVec = vectorizeTree(E->getOperand(0));
  5992. if (E->VectorizedValue) {
  5993. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  5994. return E->VectorizedValue;
  5995. }
  5996. auto *CI = cast<CastInst>(VL0);
  5997. Value *V = Builder.CreateCast(CI->getOpcode(), InVec, VecTy);
  5998. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  5999. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6000. V = ShuffleBuilder.finalize(V);
  6001. E->VectorizedValue = V;
  6002. ++NumVectorInstructions;
  6003. return V;
  6004. }
  6005. case Instruction::FCmp:
  6006. case Instruction::ICmp: {
  6007. setInsertPointAfterBundle(E);
  6008. Value *L = vectorizeTree(E->getOperand(0));
  6009. Value *R = vectorizeTree(E->getOperand(1));
  6010. if (E->VectorizedValue) {
  6011. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  6012. return E->VectorizedValue;
  6013. }
  6014. CmpInst::Predicate P0 = cast<CmpInst>(VL0)->getPredicate();
  6015. Value *V = Builder.CreateCmp(P0, L, R);
  6016. propagateIRFlags(V, E->Scalars, VL0);
  6017. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  6018. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6019. V = ShuffleBuilder.finalize(V);
  6020. E->VectorizedValue = V;
  6021. ++NumVectorInstructions;
  6022. return V;
  6023. }
  6024. case Instruction::Select: {
  6025. setInsertPointAfterBundle(E);
  6026. Value *Cond = vectorizeTree(E->getOperand(0));
  6027. Value *True = vectorizeTree(E->getOperand(1));
  6028. Value *False = vectorizeTree(E->getOperand(2));
  6029. if (E->VectorizedValue) {
  6030. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  6031. return E->VectorizedValue;
  6032. }
  6033. Value *V = Builder.CreateSelect(Cond, True, False);
  6034. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  6035. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6036. V = ShuffleBuilder.finalize(V);
  6037. E->VectorizedValue = V;
  6038. ++NumVectorInstructions;
  6039. return V;
  6040. }
  6041. case Instruction::FNeg: {
  6042. setInsertPointAfterBundle(E);
  6043. Value *Op = vectorizeTree(E->getOperand(0));
  6044. if (E->VectorizedValue) {
  6045. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  6046. return E->VectorizedValue;
  6047. }
  6048. Value *V = Builder.CreateUnOp(
  6049. static_cast<Instruction::UnaryOps>(E->getOpcode()), Op);
  6050. propagateIRFlags(V, E->Scalars, VL0);
  6051. if (auto *I = dyn_cast<Instruction>(V))
  6052. V = propagateMetadata(I, E->Scalars);
  6053. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  6054. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6055. V = ShuffleBuilder.finalize(V);
  6056. E->VectorizedValue = V;
  6057. ++NumVectorInstructions;
  6058. return V;
  6059. }
  6060. case Instruction::Add:
  6061. case Instruction::FAdd:
  6062. case Instruction::Sub:
  6063. case Instruction::FSub:
  6064. case Instruction::Mul:
  6065. case Instruction::FMul:
  6066. case Instruction::UDiv:
  6067. case Instruction::SDiv:
  6068. case Instruction::FDiv:
  6069. case Instruction::URem:
  6070. case Instruction::SRem:
  6071. case Instruction::FRem:
  6072. case Instruction::Shl:
  6073. case Instruction::LShr:
  6074. case Instruction::AShr:
  6075. case Instruction::And:
  6076. case Instruction::Or:
  6077. case Instruction::Xor: {
  6078. setInsertPointAfterBundle(E);
  6079. Value *LHS = vectorizeTree(E->getOperand(0));
  6080. Value *RHS = vectorizeTree(E->getOperand(1));
  6081. if (E->VectorizedValue) {
  6082. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  6083. return E->VectorizedValue;
  6084. }
  6085. Value *V = Builder.CreateBinOp(
  6086. static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS,
  6087. RHS);
  6088. propagateIRFlags(V, E->Scalars, VL0);
  6089. if (auto *I = dyn_cast<Instruction>(V))
  6090. V = propagateMetadata(I, E->Scalars);
  6091. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  6092. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6093. V = ShuffleBuilder.finalize(V);
  6094. E->VectorizedValue = V;
  6095. ++NumVectorInstructions;
  6096. return V;
  6097. }
  6098. case Instruction::Load: {
  6099. // Loads are inserted at the head of the tree because we don't want to
  6100. // sink them all the way down past store instructions.
  6101. setInsertPointAfterBundle(E);
  6102. LoadInst *LI = cast<LoadInst>(VL0);
  6103. Instruction *NewLI;
  6104. unsigned AS = LI->getPointerAddressSpace();
  6105. Value *PO = LI->getPointerOperand();
  6106. if (E->State == TreeEntry::Vectorize) {
  6107. Value *VecPtr = Builder.CreateBitCast(PO, VecTy->getPointerTo(AS));
  6108. // The pointer operand uses an in-tree scalar so we add the new BitCast
  6109. // to ExternalUses list to make sure that an extract will be generated
  6110. // in the future.
  6111. if (TreeEntry *Entry = getTreeEntry(PO)) {
  6112. // Find which lane we need to extract.
  6113. unsigned FoundLane = Entry->findLaneForValue(PO);
  6114. ExternalUses.emplace_back(PO, cast<User>(VecPtr), FoundLane);
  6115. }
  6116. NewLI = Builder.CreateAlignedLoad(VecTy, VecPtr, LI->getAlign());
  6117. } else {
  6118. assert(E->State == TreeEntry::ScatterVectorize && "Unhandled state");
  6119. Value *VecPtr = vectorizeTree(E->getOperand(0));
  6120. // Use the minimum alignment of the gathered loads.
  6121. Align CommonAlignment = LI->getAlign();
  6122. for (Value *V : E->Scalars)
  6123. CommonAlignment =
  6124. commonAlignment(CommonAlignment, cast<LoadInst>(V)->getAlign());
  6125. NewLI = Builder.CreateMaskedGather(VecTy, VecPtr, CommonAlignment);
  6126. }
  6127. Value *V = propagateMetadata(NewLI, E->Scalars);
  6128. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  6129. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6130. V = ShuffleBuilder.finalize(V);
  6131. E->VectorizedValue = V;
  6132. ++NumVectorInstructions;
  6133. return V;
  6134. }
  6135. case Instruction::Store: {
  6136. auto *SI = cast<StoreInst>(VL0);
  6137. unsigned AS = SI->getPointerAddressSpace();
  6138. setInsertPointAfterBundle(E);
  6139. Value *VecValue = vectorizeTree(E->getOperand(0));
  6140. ShuffleBuilder.addMask(E->ReorderIndices);
  6141. VecValue = ShuffleBuilder.finalize(VecValue);
  6142. Value *ScalarPtr = SI->getPointerOperand();
  6143. Value *VecPtr = Builder.CreateBitCast(
  6144. ScalarPtr, VecValue->getType()->getPointerTo(AS));
  6145. StoreInst *ST = Builder.CreateAlignedStore(VecValue, VecPtr,
  6146. SI->getAlign());
  6147. // The pointer operand uses an in-tree scalar, so add the new BitCast to
  6148. // ExternalUses to make sure that an extract will be generated in the
  6149. // future.
  6150. if (TreeEntry *Entry = getTreeEntry(ScalarPtr)) {
  6151. // Find which lane we need to extract.
  6152. unsigned FoundLane = Entry->findLaneForValue(ScalarPtr);
  6153. ExternalUses.push_back(
  6154. ExternalUser(ScalarPtr, cast<User>(VecPtr), FoundLane));
  6155. }
  6156. Value *V = propagateMetadata(ST, E->Scalars);
  6157. E->VectorizedValue = V;
  6158. ++NumVectorInstructions;
  6159. return V;
  6160. }
  6161. case Instruction::GetElementPtr: {
  6162. auto *GEP0 = cast<GetElementPtrInst>(VL0);
  6163. setInsertPointAfterBundle(E);
  6164. Value *Op0 = vectorizeTree(E->getOperand(0));
  6165. SmallVector<Value *> OpVecs;
  6166. for (int J = 1, N = GEP0->getNumOperands(); J < N; ++J) {
  6167. Value *OpVec = vectorizeTree(E->getOperand(J));
  6168. OpVecs.push_back(OpVec);
  6169. }
  6170. Value *V = Builder.CreateGEP(GEP0->getSourceElementType(), Op0, OpVecs);
  6171. if (Instruction *I = dyn_cast<Instruction>(V))
  6172. V = propagateMetadata(I, E->Scalars);
  6173. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  6174. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6175. V = ShuffleBuilder.finalize(V);
  6176. E->VectorizedValue = V;
  6177. ++NumVectorInstructions;
  6178. return V;
  6179. }
  6180. case Instruction::Call: {
  6181. CallInst *CI = cast<CallInst>(VL0);
  6182. setInsertPointAfterBundle(E);
  6183. Intrinsic::ID IID = Intrinsic::not_intrinsic;
  6184. if (Function *FI = CI->getCalledFunction())
  6185. IID = FI->getIntrinsicID();
  6186. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  6187. auto VecCallCosts = getVectorCallCosts(CI, VecTy, TTI, TLI);
  6188. bool UseIntrinsic = ID != Intrinsic::not_intrinsic &&
  6189. VecCallCosts.first <= VecCallCosts.second;
  6190. Value *ScalarArg = nullptr;
  6191. std::vector<Value *> OpVecs;
  6192. SmallVector<Type *, 2> TysForDecl =
  6193. {FixedVectorType::get(CI->getType(), E->Scalars.size())};
  6194. for (int j = 0, e = CI->arg_size(); j < e; ++j) {
  6195. ValueList OpVL;
  6196. // Some intrinsics have scalar arguments. This argument should not be
  6197. // vectorized.
  6198. if (UseIntrinsic && hasVectorInstrinsicScalarOpd(IID, j)) {
  6199. CallInst *CEI = cast<CallInst>(VL0);
  6200. ScalarArg = CEI->getArgOperand(j);
  6201. OpVecs.push_back(CEI->getArgOperand(j));
  6202. if (hasVectorInstrinsicOverloadedScalarOpd(IID, j))
  6203. TysForDecl.push_back(ScalarArg->getType());
  6204. continue;
  6205. }
  6206. Value *OpVec = vectorizeTree(E->getOperand(j));
  6207. LLVM_DEBUG(dbgs() << "SLP: OpVec[" << j << "]: " << *OpVec << "\n");
  6208. OpVecs.push_back(OpVec);
  6209. }
  6210. Function *CF;
  6211. if (!UseIntrinsic) {
  6212. VFShape Shape =
  6213. VFShape::get(*CI, ElementCount::getFixed(static_cast<unsigned>(
  6214. VecTy->getNumElements())),
  6215. false /*HasGlobalPred*/);
  6216. CF = VFDatabase(*CI).getVectorizedFunction(Shape);
  6217. } else {
  6218. CF = Intrinsic::getDeclaration(F->getParent(), ID, TysForDecl);
  6219. }
  6220. SmallVector<OperandBundleDef, 1> OpBundles;
  6221. CI->getOperandBundlesAsDefs(OpBundles);
  6222. Value *V = Builder.CreateCall(CF, OpVecs, OpBundles);
  6223. // The scalar argument uses an in-tree scalar so we add the new vectorized
  6224. // call to ExternalUses list to make sure that an extract will be
  6225. // generated in the future.
  6226. if (ScalarArg) {
  6227. if (TreeEntry *Entry = getTreeEntry(ScalarArg)) {
  6228. // Find which lane we need to extract.
  6229. unsigned FoundLane = Entry->findLaneForValue(ScalarArg);
  6230. ExternalUses.push_back(
  6231. ExternalUser(ScalarArg, cast<User>(V), FoundLane));
  6232. }
  6233. }
  6234. propagateIRFlags(V, E->Scalars, VL0);
  6235. ShuffleBuilder.addInversedMask(E->ReorderIndices);
  6236. ShuffleBuilder.addMask(E->ReuseShuffleIndices);
  6237. V = ShuffleBuilder.finalize(V);
  6238. E->VectorizedValue = V;
  6239. ++NumVectorInstructions;
  6240. return V;
  6241. }
  6242. case Instruction::ShuffleVector: {
  6243. assert(E->isAltShuffle() &&
  6244. ((Instruction::isBinaryOp(E->getOpcode()) &&
  6245. Instruction::isBinaryOp(E->getAltOpcode())) ||
  6246. (Instruction::isCast(E->getOpcode()) &&
  6247. Instruction::isCast(E->getAltOpcode()))) &&
  6248. "Invalid Shuffle Vector Operand");
  6249. Value *LHS = nullptr, *RHS = nullptr;
  6250. if (Instruction::isBinaryOp(E->getOpcode())) {
  6251. setInsertPointAfterBundle(E);
  6252. LHS = vectorizeTree(E->getOperand(0));
  6253. RHS = vectorizeTree(E->getOperand(1));
  6254. } else {
  6255. setInsertPointAfterBundle(E);
  6256. LHS = vectorizeTree(E->getOperand(0));
  6257. }
  6258. if (E->VectorizedValue) {
  6259. LLVM_DEBUG(dbgs() << "SLP: Diamond merged for " << *VL0 << ".\n");
  6260. return E->VectorizedValue;
  6261. }
  6262. Value *V0, *V1;
  6263. if (Instruction::isBinaryOp(E->getOpcode())) {
  6264. V0 = Builder.CreateBinOp(
  6265. static_cast<Instruction::BinaryOps>(E->getOpcode()), LHS, RHS);
  6266. V1 = Builder.CreateBinOp(
  6267. static_cast<Instruction::BinaryOps>(E->getAltOpcode()), LHS, RHS);
  6268. } else {
  6269. V0 = Builder.CreateCast(
  6270. static_cast<Instruction::CastOps>(E->getOpcode()), LHS, VecTy);
  6271. V1 = Builder.CreateCast(
  6272. static_cast<Instruction::CastOps>(E->getAltOpcode()), LHS, VecTy);
  6273. }
  6274. // Add V0 and V1 to later analysis to try to find and remove matching
  6275. // instruction, if any.
  6276. for (Value *V : {V0, V1}) {
  6277. if (auto *I = dyn_cast<Instruction>(V)) {
  6278. GatherShuffleSeq.insert(I);
  6279. CSEBlocks.insert(I->getParent());
  6280. }
  6281. }
  6282. // Create shuffle to take alternate operations from the vector.
  6283. // Also, gather up main and alt scalar ops to propagate IR flags to
  6284. // each vector operation.
  6285. ValueList OpScalars, AltScalars;
  6286. SmallVector<int> Mask;
  6287. buildSuffleEntryMask(
  6288. E->Scalars, E->ReorderIndices, E->ReuseShuffleIndices,
  6289. [E](Instruction *I) {
  6290. assert(E->isOpcodeOrAlt(I) && "Unexpected main/alternate opcode");
  6291. return I->getOpcode() == E->getAltOpcode();
  6292. },
  6293. Mask, &OpScalars, &AltScalars);
  6294. propagateIRFlags(V0, OpScalars);
  6295. propagateIRFlags(V1, AltScalars);
  6296. Value *V = Builder.CreateShuffleVector(V0, V1, Mask);
  6297. if (auto *I = dyn_cast<Instruction>(V)) {
  6298. V = propagateMetadata(I, E->Scalars);
  6299. GatherShuffleSeq.insert(I);
  6300. CSEBlocks.insert(I->getParent());
  6301. }
  6302. V = ShuffleBuilder.finalize(V);
  6303. E->VectorizedValue = V;
  6304. ++NumVectorInstructions;
  6305. return V;
  6306. }
  6307. default:
  6308. llvm_unreachable("unknown inst");
  6309. }
  6310. return nullptr;
  6311. }
  6312. Value *BoUpSLP::vectorizeTree() {
  6313. ExtraValueToDebugLocsMap ExternallyUsedValues;
  6314. return vectorizeTree(ExternallyUsedValues);
  6315. }
  6316. Value *
  6317. BoUpSLP::vectorizeTree(ExtraValueToDebugLocsMap &ExternallyUsedValues) {
  6318. // All blocks must be scheduled before any instructions are inserted.
  6319. for (auto &BSIter : BlocksSchedules) {
  6320. scheduleBlock(BSIter.second.get());
  6321. }
  6322. Builder.SetInsertPoint(&F->getEntryBlock().front());
  6323. auto *VectorRoot = vectorizeTree(VectorizableTree[0].get());
  6324. // If the vectorized tree can be rewritten in a smaller type, we truncate the
  6325. // vectorized root. InstCombine will then rewrite the entire expression. We
  6326. // sign extend the extracted values below.
  6327. auto *ScalarRoot = VectorizableTree[0]->Scalars[0];
  6328. if (MinBWs.count(ScalarRoot)) {
  6329. if (auto *I = dyn_cast<Instruction>(VectorRoot)) {
  6330. // If current instr is a phi and not the last phi, insert it after the
  6331. // last phi node.
  6332. if (isa<PHINode>(I))
  6333. Builder.SetInsertPoint(&*I->getParent()->getFirstInsertionPt());
  6334. else
  6335. Builder.SetInsertPoint(&*++BasicBlock::iterator(I));
  6336. }
  6337. auto BundleWidth = VectorizableTree[0]->Scalars.size();
  6338. auto *MinTy = IntegerType::get(F->getContext(), MinBWs[ScalarRoot].first);
  6339. auto *VecTy = FixedVectorType::get(MinTy, BundleWidth);
  6340. auto *Trunc = Builder.CreateTrunc(VectorRoot, VecTy);
  6341. VectorizableTree[0]->VectorizedValue = Trunc;
  6342. }
  6343. LLVM_DEBUG(dbgs() << "SLP: Extracting " << ExternalUses.size()
  6344. << " values .\n");
  6345. // Extract all of the elements with the external uses.
  6346. for (const auto &ExternalUse : ExternalUses) {
  6347. Value *Scalar = ExternalUse.Scalar;
  6348. llvm::User *User = ExternalUse.User;
  6349. // Skip users that we already RAUW. This happens when one instruction
  6350. // has multiple uses of the same value.
  6351. if (User && !is_contained(Scalar->users(), User))
  6352. continue;
  6353. TreeEntry *E = getTreeEntry(Scalar);
  6354. assert(E && "Invalid scalar");
  6355. assert(E->State != TreeEntry::NeedToGather &&
  6356. "Extracting from a gather list");
  6357. Value *Vec = E->VectorizedValue;
  6358. assert(Vec && "Can't find vectorizable value");
  6359. Value *Lane = Builder.getInt32(ExternalUse.Lane);
  6360. auto ExtractAndExtendIfNeeded = [&](Value *Vec) {
  6361. if (Scalar->getType() != Vec->getType()) {
  6362. Value *Ex;
  6363. // "Reuse" the existing extract to improve final codegen.
  6364. if (auto *ES = dyn_cast<ExtractElementInst>(Scalar)) {
  6365. Ex = Builder.CreateExtractElement(ES->getOperand(0),
  6366. ES->getOperand(1));
  6367. } else {
  6368. Ex = Builder.CreateExtractElement(Vec, Lane);
  6369. }
  6370. // If necessary, sign-extend or zero-extend ScalarRoot
  6371. // to the larger type.
  6372. if (!MinBWs.count(ScalarRoot))
  6373. return Ex;
  6374. if (MinBWs[ScalarRoot].second)
  6375. return Builder.CreateSExt(Ex, Scalar->getType());
  6376. return Builder.CreateZExt(Ex, Scalar->getType());
  6377. }
  6378. assert(isa<FixedVectorType>(Scalar->getType()) &&
  6379. isa<InsertElementInst>(Scalar) &&
  6380. "In-tree scalar of vector type is not insertelement?");
  6381. return Vec;
  6382. };
  6383. // If User == nullptr, the Scalar is used as extra arg. Generate
  6384. // ExtractElement instruction and update the record for this scalar in
  6385. // ExternallyUsedValues.
  6386. if (!User) {
  6387. assert(ExternallyUsedValues.count(Scalar) &&
  6388. "Scalar with nullptr as an external user must be registered in "
  6389. "ExternallyUsedValues map");
  6390. if (auto *VecI = dyn_cast<Instruction>(Vec)) {
  6391. Builder.SetInsertPoint(VecI->getParent(),
  6392. std::next(VecI->getIterator()));
  6393. } else {
  6394. Builder.SetInsertPoint(&F->getEntryBlock().front());
  6395. }
  6396. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  6397. CSEBlocks.insert(cast<Instruction>(Scalar)->getParent());
  6398. auto &NewInstLocs = ExternallyUsedValues[NewInst];
  6399. auto It = ExternallyUsedValues.find(Scalar);
  6400. assert(It != ExternallyUsedValues.end() &&
  6401. "Externally used scalar is not found in ExternallyUsedValues");
  6402. NewInstLocs.append(It->second);
  6403. ExternallyUsedValues.erase(Scalar);
  6404. // Required to update internally referenced instructions.
  6405. Scalar->replaceAllUsesWith(NewInst);
  6406. continue;
  6407. }
  6408. // Generate extracts for out-of-tree users.
  6409. // Find the insertion point for the extractelement lane.
  6410. if (auto *VecI = dyn_cast<Instruction>(Vec)) {
  6411. if (PHINode *PH = dyn_cast<PHINode>(User)) {
  6412. for (int i = 0, e = PH->getNumIncomingValues(); i != e; ++i) {
  6413. if (PH->getIncomingValue(i) == Scalar) {
  6414. Instruction *IncomingTerminator =
  6415. PH->getIncomingBlock(i)->getTerminator();
  6416. if (isa<CatchSwitchInst>(IncomingTerminator)) {
  6417. Builder.SetInsertPoint(VecI->getParent(),
  6418. std::next(VecI->getIterator()));
  6419. } else {
  6420. Builder.SetInsertPoint(PH->getIncomingBlock(i)->getTerminator());
  6421. }
  6422. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  6423. CSEBlocks.insert(PH->getIncomingBlock(i));
  6424. PH->setOperand(i, NewInst);
  6425. }
  6426. }
  6427. } else {
  6428. Builder.SetInsertPoint(cast<Instruction>(User));
  6429. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  6430. CSEBlocks.insert(cast<Instruction>(User)->getParent());
  6431. User->replaceUsesOfWith(Scalar, NewInst);
  6432. }
  6433. } else {
  6434. Builder.SetInsertPoint(&F->getEntryBlock().front());
  6435. Value *NewInst = ExtractAndExtendIfNeeded(Vec);
  6436. CSEBlocks.insert(&F->getEntryBlock());
  6437. User->replaceUsesOfWith(Scalar, NewInst);
  6438. }
  6439. LLVM_DEBUG(dbgs() << "SLP: Replaced:" << *User << ".\n");
  6440. }
  6441. // For each vectorized value:
  6442. for (auto &TEPtr : VectorizableTree) {
  6443. TreeEntry *Entry = TEPtr.get();
  6444. // No need to handle users of gathered values.
  6445. if (Entry->State == TreeEntry::NeedToGather)
  6446. continue;
  6447. assert(Entry->VectorizedValue && "Can't find vectorizable value");
  6448. // For each lane:
  6449. for (int Lane = 0, LE = Entry->Scalars.size(); Lane != LE; ++Lane) {
  6450. Value *Scalar = Entry->Scalars[Lane];
  6451. #ifndef NDEBUG
  6452. Type *Ty = Scalar->getType();
  6453. if (!Ty->isVoidTy()) {
  6454. for (User *U : Scalar->users()) {
  6455. LLVM_DEBUG(dbgs() << "SLP: \tvalidating user:" << *U << ".\n");
  6456. // It is legal to delete users in the ignorelist.
  6457. assert((getTreeEntry(U) || is_contained(UserIgnoreList, U) ||
  6458. (isa_and_nonnull<Instruction>(U) &&
  6459. isDeleted(cast<Instruction>(U)))) &&
  6460. "Deleting out-of-tree value");
  6461. }
  6462. }
  6463. #endif
  6464. LLVM_DEBUG(dbgs() << "SLP: \tErasing scalar:" << *Scalar << ".\n");
  6465. eraseInstruction(cast<Instruction>(Scalar));
  6466. }
  6467. }
  6468. Builder.ClearInsertionPoint();
  6469. InstrElementSize.clear();
  6470. return VectorizableTree[0]->VectorizedValue;
  6471. }
  6472. void BoUpSLP::optimizeGatherSequence() {
  6473. LLVM_DEBUG(dbgs() << "SLP: Optimizing " << GatherShuffleSeq.size()
  6474. << " gather sequences instructions.\n");
  6475. // LICM InsertElementInst sequences.
  6476. for (Instruction *I : GatherShuffleSeq) {
  6477. if (isDeleted(I))
  6478. continue;
  6479. // Check if this block is inside a loop.
  6480. Loop *L = LI->getLoopFor(I->getParent());
  6481. if (!L)
  6482. continue;
  6483. // Check if it has a preheader.
  6484. BasicBlock *PreHeader = L->getLoopPreheader();
  6485. if (!PreHeader)
  6486. continue;
  6487. // If the vector or the element that we insert into it are
  6488. // instructions that are defined in this basic block then we can't
  6489. // hoist this instruction.
  6490. if (any_of(I->operands(), [L](Value *V) {
  6491. auto *OpI = dyn_cast<Instruction>(V);
  6492. return OpI && L->contains(OpI);
  6493. }))
  6494. continue;
  6495. // We can hoist this instruction. Move it to the pre-header.
  6496. I->moveBefore(PreHeader->getTerminator());
  6497. }
  6498. // Make a list of all reachable blocks in our CSE queue.
  6499. SmallVector<const DomTreeNode *, 8> CSEWorkList;
  6500. CSEWorkList.reserve(CSEBlocks.size());
  6501. for (BasicBlock *BB : CSEBlocks)
  6502. if (DomTreeNode *N = DT->getNode(BB)) {
  6503. assert(DT->isReachableFromEntry(N));
  6504. CSEWorkList.push_back(N);
  6505. }
  6506. // Sort blocks by domination. This ensures we visit a block after all blocks
  6507. // dominating it are visited.
  6508. llvm::sort(CSEWorkList, [](const DomTreeNode *A, const DomTreeNode *B) {
  6509. assert((A == B) == (A->getDFSNumIn() == B->getDFSNumIn()) &&
  6510. "Different nodes should have different DFS numbers");
  6511. return A->getDFSNumIn() < B->getDFSNumIn();
  6512. });
  6513. // Less defined shuffles can be replaced by the more defined copies.
  6514. // Between two shuffles one is less defined if it has the same vector operands
  6515. // and its mask indeces are the same as in the first one or undefs. E.g.
  6516. // shuffle %0, poison, <0, 0, 0, undef> is less defined than shuffle %0,
  6517. // poison, <0, 0, 0, 0>.
  6518. auto &&IsIdenticalOrLessDefined = [this](Instruction *I1, Instruction *I2,
  6519. SmallVectorImpl<int> &NewMask) {
  6520. if (I1->getType() != I2->getType())
  6521. return false;
  6522. auto *SI1 = dyn_cast<ShuffleVectorInst>(I1);
  6523. auto *SI2 = dyn_cast<ShuffleVectorInst>(I2);
  6524. if (!SI1 || !SI2)
  6525. return I1->isIdenticalTo(I2);
  6526. if (SI1->isIdenticalTo(SI2))
  6527. return true;
  6528. for (int I = 0, E = SI1->getNumOperands(); I < E; ++I)
  6529. if (SI1->getOperand(I) != SI2->getOperand(I))
  6530. return false;
  6531. // Check if the second instruction is more defined than the first one.
  6532. NewMask.assign(SI2->getShuffleMask().begin(), SI2->getShuffleMask().end());
  6533. ArrayRef<int> SM1 = SI1->getShuffleMask();
  6534. // Count trailing undefs in the mask to check the final number of used
  6535. // registers.
  6536. unsigned LastUndefsCnt = 0;
  6537. for (int I = 0, E = NewMask.size(); I < E; ++I) {
  6538. if (SM1[I] == UndefMaskElem)
  6539. ++LastUndefsCnt;
  6540. else
  6541. LastUndefsCnt = 0;
  6542. if (NewMask[I] != UndefMaskElem && SM1[I] != UndefMaskElem &&
  6543. NewMask[I] != SM1[I])
  6544. return false;
  6545. if (NewMask[I] == UndefMaskElem)
  6546. NewMask[I] = SM1[I];
  6547. }
  6548. // Check if the last undefs actually change the final number of used vector
  6549. // registers.
  6550. return SM1.size() - LastUndefsCnt > 1 &&
  6551. TTI->getNumberOfParts(SI1->getType()) ==
  6552. TTI->getNumberOfParts(
  6553. FixedVectorType::get(SI1->getType()->getElementType(),
  6554. SM1.size() - LastUndefsCnt));
  6555. };
  6556. // Perform O(N^2) search over the gather/shuffle sequences and merge identical
  6557. // instructions. TODO: We can further optimize this scan if we split the
  6558. // instructions into different buckets based on the insert lane.
  6559. SmallVector<Instruction *, 16> Visited;
  6560. for (auto I = CSEWorkList.begin(), E = CSEWorkList.end(); I != E; ++I) {
  6561. assert(*I &&
  6562. (I == CSEWorkList.begin() || !DT->dominates(*I, *std::prev(I))) &&
  6563. "Worklist not sorted properly!");
  6564. BasicBlock *BB = (*I)->getBlock();
  6565. // For all instructions in blocks containing gather sequences:
  6566. for (Instruction &In : llvm::make_early_inc_range(*BB)) {
  6567. if (isDeleted(&In))
  6568. continue;
  6569. if (!isa<InsertElementInst>(&In) && !isa<ExtractElementInst>(&In) &&
  6570. !isa<ShuffleVectorInst>(&In) && !GatherShuffleSeq.contains(&In))
  6571. continue;
  6572. // Check if we can replace this instruction with any of the
  6573. // visited instructions.
  6574. bool Replaced = false;
  6575. for (Instruction *&V : Visited) {
  6576. SmallVector<int> NewMask;
  6577. if (IsIdenticalOrLessDefined(&In, V, NewMask) &&
  6578. DT->dominates(V->getParent(), In.getParent())) {
  6579. In.replaceAllUsesWith(V);
  6580. eraseInstruction(&In);
  6581. if (auto *SI = dyn_cast<ShuffleVectorInst>(V))
  6582. if (!NewMask.empty())
  6583. SI->setShuffleMask(NewMask);
  6584. Replaced = true;
  6585. break;
  6586. }
  6587. if (isa<ShuffleVectorInst>(In) && isa<ShuffleVectorInst>(V) &&
  6588. GatherShuffleSeq.contains(V) &&
  6589. IsIdenticalOrLessDefined(V, &In, NewMask) &&
  6590. DT->dominates(In.getParent(), V->getParent())) {
  6591. In.moveAfter(V);
  6592. V->replaceAllUsesWith(&In);
  6593. eraseInstruction(V);
  6594. if (auto *SI = dyn_cast<ShuffleVectorInst>(&In))
  6595. if (!NewMask.empty())
  6596. SI->setShuffleMask(NewMask);
  6597. V = &In;
  6598. Replaced = true;
  6599. break;
  6600. }
  6601. }
  6602. if (!Replaced) {
  6603. assert(!is_contained(Visited, &In));
  6604. Visited.push_back(&In);
  6605. }
  6606. }
  6607. }
  6608. CSEBlocks.clear();
  6609. GatherShuffleSeq.clear();
  6610. }
  6611. BoUpSLP::ScheduleData *
  6612. BoUpSLP::BlockScheduling::buildBundle(ArrayRef<Value *> VL) {
  6613. ScheduleData *Bundle = nullptr;
  6614. ScheduleData *PrevInBundle = nullptr;
  6615. for (Value *V : VL) {
  6616. ScheduleData *BundleMember = getScheduleData(V);
  6617. assert(BundleMember &&
  6618. "no ScheduleData for bundle member "
  6619. "(maybe not in same basic block)");
  6620. assert(BundleMember->isSchedulingEntity() &&
  6621. "bundle member already part of other bundle");
  6622. if (PrevInBundle) {
  6623. PrevInBundle->NextInBundle = BundleMember;
  6624. } else {
  6625. Bundle = BundleMember;
  6626. }
  6627. BundleMember->UnscheduledDepsInBundle = 0;
  6628. Bundle->UnscheduledDepsInBundle += BundleMember->UnscheduledDeps;
  6629. // Group the instructions to a bundle.
  6630. BundleMember->FirstInBundle = Bundle;
  6631. PrevInBundle = BundleMember;
  6632. }
  6633. assert(Bundle && "Failed to find schedule bundle");
  6634. return Bundle;
  6635. }
  6636. // Groups the instructions to a bundle (which is then a single scheduling entity)
  6637. // and schedules instructions until the bundle gets ready.
  6638. Optional<BoUpSLP::ScheduleData *>
  6639. BoUpSLP::BlockScheduling::tryScheduleBundle(ArrayRef<Value *> VL, BoUpSLP *SLP,
  6640. const InstructionsState &S) {
  6641. // No need to schedule PHIs, insertelement, extractelement and extractvalue
  6642. // instructions.
  6643. if (isa<PHINode>(S.OpValue) || isVectorLikeInstWithConstOps(S.OpValue))
  6644. return nullptr;
  6645. // Initialize the instruction bundle.
  6646. Instruction *OldScheduleEnd = ScheduleEnd;
  6647. LLVM_DEBUG(dbgs() << "SLP: bundle: " << *S.OpValue << "\n");
  6648. auto TryScheduleBundleImpl = [this, OldScheduleEnd, SLP](bool ReSchedule,
  6649. ScheduleData *Bundle) {
  6650. // The scheduling region got new instructions at the lower end (or it is a
  6651. // new region for the first bundle). This makes it necessary to
  6652. // recalculate all dependencies.
  6653. // It is seldom that this needs to be done a second time after adding the
  6654. // initial bundle to the region.
  6655. if (ScheduleEnd != OldScheduleEnd) {
  6656. for (auto *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode())
  6657. doForAllOpcodes(I, [](ScheduleData *SD) { SD->clearDependencies(); });
  6658. ReSchedule = true;
  6659. }
  6660. if (ReSchedule) {
  6661. resetSchedule();
  6662. initialFillReadyList(ReadyInsts);
  6663. }
  6664. if (Bundle) {
  6665. LLVM_DEBUG(dbgs() << "SLP: try schedule bundle " << *Bundle
  6666. << " in block " << BB->getName() << "\n");
  6667. calculateDependencies(Bundle, /*InsertInReadyList=*/true, SLP);
  6668. }
  6669. // Now try to schedule the new bundle or (if no bundle) just calculate
  6670. // dependencies. As soon as the bundle is "ready" it means that there are no
  6671. // cyclic dependencies and we can schedule it. Note that's important that we
  6672. // don't "schedule" the bundle yet (see cancelScheduling).
  6673. while (((!Bundle && ReSchedule) || (Bundle && !Bundle->isReady())) &&
  6674. !ReadyInsts.empty()) {
  6675. ScheduleData *Picked = ReadyInsts.pop_back_val();
  6676. if (Picked->isSchedulingEntity() && Picked->isReady())
  6677. schedule(Picked, ReadyInsts);
  6678. }
  6679. };
  6680. // Make sure that the scheduling region contains all
  6681. // instructions of the bundle.
  6682. for (Value *V : VL) {
  6683. if (!extendSchedulingRegion(V, S)) {
  6684. // If the scheduling region got new instructions at the lower end (or it
  6685. // is a new region for the first bundle). This makes it necessary to
  6686. // recalculate all dependencies.
  6687. // Otherwise the compiler may crash trying to incorrectly calculate
  6688. // dependencies and emit instruction in the wrong order at the actual
  6689. // scheduling.
  6690. TryScheduleBundleImpl(/*ReSchedule=*/false, nullptr);
  6691. return None;
  6692. }
  6693. }
  6694. bool ReSchedule = false;
  6695. for (Value *V : VL) {
  6696. ScheduleData *BundleMember = getScheduleData(V);
  6697. assert(BundleMember &&
  6698. "no ScheduleData for bundle member (maybe not in same basic block)");
  6699. if (!BundleMember->IsScheduled)
  6700. continue;
  6701. // A bundle member was scheduled as single instruction before and now
  6702. // needs to be scheduled as part of the bundle. We just get rid of the
  6703. // existing schedule.
  6704. LLVM_DEBUG(dbgs() << "SLP: reset schedule because " << *BundleMember
  6705. << " was already scheduled\n");
  6706. ReSchedule = true;
  6707. }
  6708. auto *Bundle = buildBundle(VL);
  6709. TryScheduleBundleImpl(ReSchedule, Bundle);
  6710. if (!Bundle->isReady()) {
  6711. cancelScheduling(VL, S.OpValue);
  6712. return None;
  6713. }
  6714. return Bundle;
  6715. }
  6716. void BoUpSLP::BlockScheduling::cancelScheduling(ArrayRef<Value *> VL,
  6717. Value *OpValue) {
  6718. if (isa<PHINode>(OpValue) || isVectorLikeInstWithConstOps(OpValue))
  6719. return;
  6720. ScheduleData *Bundle = getScheduleData(OpValue);
  6721. LLVM_DEBUG(dbgs() << "SLP: cancel scheduling of " << *Bundle << "\n");
  6722. assert(!Bundle->IsScheduled &&
  6723. "Can't cancel bundle which is already scheduled");
  6724. assert(Bundle->isSchedulingEntity() && Bundle->isPartOfBundle() &&
  6725. "tried to unbundle something which is not a bundle");
  6726. // Un-bundle: make single instructions out of the bundle.
  6727. ScheduleData *BundleMember = Bundle;
  6728. while (BundleMember) {
  6729. assert(BundleMember->FirstInBundle == Bundle && "corrupt bundle links");
  6730. BundleMember->FirstInBundle = BundleMember;
  6731. ScheduleData *Next = BundleMember->NextInBundle;
  6732. BundleMember->NextInBundle = nullptr;
  6733. BundleMember->UnscheduledDepsInBundle = BundleMember->UnscheduledDeps;
  6734. if (BundleMember->UnscheduledDepsInBundle == 0) {
  6735. ReadyInsts.insert(BundleMember);
  6736. }
  6737. BundleMember = Next;
  6738. }
  6739. }
  6740. BoUpSLP::ScheduleData *BoUpSLP::BlockScheduling::allocateScheduleDataChunks() {
  6741. // Allocate a new ScheduleData for the instruction.
  6742. if (ChunkPos >= ChunkSize) {
  6743. ScheduleDataChunks.push_back(std::make_unique<ScheduleData[]>(ChunkSize));
  6744. ChunkPos = 0;
  6745. }
  6746. return &(ScheduleDataChunks.back()[ChunkPos++]);
  6747. }
  6748. bool BoUpSLP::BlockScheduling::extendSchedulingRegion(Value *V,
  6749. const InstructionsState &S) {
  6750. if (getScheduleData(V, isOneOf(S, V)))
  6751. return true;
  6752. Instruction *I = dyn_cast<Instruction>(V);
  6753. assert(I && "bundle member must be an instruction");
  6754. assert(!isa<PHINode>(I) && !isVectorLikeInstWithConstOps(I) &&
  6755. "phi nodes/insertelements/extractelements/extractvalues don't need to "
  6756. "be scheduled");
  6757. auto &&CheckSheduleForI = [this, &S](Instruction *I) -> bool {
  6758. ScheduleData *ISD = getScheduleData(I);
  6759. if (!ISD)
  6760. return false;
  6761. assert(isInSchedulingRegion(ISD) &&
  6762. "ScheduleData not in scheduling region");
  6763. ScheduleData *SD = allocateScheduleDataChunks();
  6764. SD->Inst = I;
  6765. SD->init(SchedulingRegionID, S.OpValue);
  6766. ExtraScheduleDataMap[I][S.OpValue] = SD;
  6767. return true;
  6768. };
  6769. if (CheckSheduleForI(I))
  6770. return true;
  6771. if (!ScheduleStart) {
  6772. // It's the first instruction in the new region.
  6773. initScheduleData(I, I->getNextNode(), nullptr, nullptr);
  6774. ScheduleStart = I;
  6775. ScheduleEnd = I->getNextNode();
  6776. if (isOneOf(S, I) != I)
  6777. CheckSheduleForI(I);
  6778. assert(ScheduleEnd && "tried to vectorize a terminator?");
  6779. LLVM_DEBUG(dbgs() << "SLP: initialize schedule region to " << *I << "\n");
  6780. return true;
  6781. }
  6782. // Search up and down at the same time, because we don't know if the new
  6783. // instruction is above or below the existing scheduling region.
  6784. BasicBlock::reverse_iterator UpIter =
  6785. ++ScheduleStart->getIterator().getReverse();
  6786. BasicBlock::reverse_iterator UpperEnd = BB->rend();
  6787. BasicBlock::iterator DownIter = ScheduleEnd->getIterator();
  6788. BasicBlock::iterator LowerEnd = BB->end();
  6789. while (UpIter != UpperEnd && DownIter != LowerEnd && &*UpIter != I &&
  6790. &*DownIter != I) {
  6791. if (++ScheduleRegionSize > ScheduleRegionSizeLimit) {
  6792. LLVM_DEBUG(dbgs() << "SLP: exceeded schedule region size limit\n");
  6793. return false;
  6794. }
  6795. ++UpIter;
  6796. ++DownIter;
  6797. }
  6798. if (DownIter == LowerEnd || (UpIter != UpperEnd && &*UpIter == I)) {
  6799. assert(I->getParent() == ScheduleStart->getParent() &&
  6800. "Instruction is in wrong basic block.");
  6801. initScheduleData(I, ScheduleStart, nullptr, FirstLoadStoreInRegion);
  6802. ScheduleStart = I;
  6803. if (isOneOf(S, I) != I)
  6804. CheckSheduleForI(I);
  6805. LLVM_DEBUG(dbgs() << "SLP: extend schedule region start to " << *I
  6806. << "\n");
  6807. return true;
  6808. }
  6809. assert((UpIter == UpperEnd || (DownIter != LowerEnd && &*DownIter == I)) &&
  6810. "Expected to reach top of the basic block or instruction down the "
  6811. "lower end.");
  6812. assert(I->getParent() == ScheduleEnd->getParent() &&
  6813. "Instruction is in wrong basic block.");
  6814. initScheduleData(ScheduleEnd, I->getNextNode(), LastLoadStoreInRegion,
  6815. nullptr);
  6816. ScheduleEnd = I->getNextNode();
  6817. if (isOneOf(S, I) != I)
  6818. CheckSheduleForI(I);
  6819. assert(ScheduleEnd && "tried to vectorize a terminator?");
  6820. LLVM_DEBUG(dbgs() << "SLP: extend schedule region end to " << *I << "\n");
  6821. return true;
  6822. }
  6823. void BoUpSLP::BlockScheduling::initScheduleData(Instruction *FromI,
  6824. Instruction *ToI,
  6825. ScheduleData *PrevLoadStore,
  6826. ScheduleData *NextLoadStore) {
  6827. ScheduleData *CurrentLoadStore = PrevLoadStore;
  6828. for (Instruction *I = FromI; I != ToI; I = I->getNextNode()) {
  6829. ScheduleData *SD = ScheduleDataMap[I];
  6830. if (!SD) {
  6831. SD = allocateScheduleDataChunks();
  6832. ScheduleDataMap[I] = SD;
  6833. SD->Inst = I;
  6834. }
  6835. assert(!isInSchedulingRegion(SD) &&
  6836. "new ScheduleData already in scheduling region");
  6837. SD->init(SchedulingRegionID, I);
  6838. if (I->mayReadOrWriteMemory() &&
  6839. (!isa<IntrinsicInst>(I) ||
  6840. (cast<IntrinsicInst>(I)->getIntrinsicID() != Intrinsic::sideeffect &&
  6841. cast<IntrinsicInst>(I)->getIntrinsicID() !=
  6842. Intrinsic::pseudoprobe))) {
  6843. // Update the linked list of memory accessing instructions.
  6844. if (CurrentLoadStore) {
  6845. CurrentLoadStore->NextLoadStore = SD;
  6846. } else {
  6847. FirstLoadStoreInRegion = SD;
  6848. }
  6849. CurrentLoadStore = SD;
  6850. }
  6851. }
  6852. if (NextLoadStore) {
  6853. if (CurrentLoadStore)
  6854. CurrentLoadStore->NextLoadStore = NextLoadStore;
  6855. } else {
  6856. LastLoadStoreInRegion = CurrentLoadStore;
  6857. }
  6858. }
  6859. void BoUpSLP::BlockScheduling::calculateDependencies(ScheduleData *SD,
  6860. bool InsertInReadyList,
  6861. BoUpSLP *SLP) {
  6862. assert(SD->isSchedulingEntity());
  6863. SmallVector<ScheduleData *, 10> WorkList;
  6864. WorkList.push_back(SD);
  6865. while (!WorkList.empty()) {
  6866. ScheduleData *SD = WorkList.pop_back_val();
  6867. for (ScheduleData *BundleMember = SD; BundleMember;
  6868. BundleMember = BundleMember->NextInBundle) {
  6869. assert(isInSchedulingRegion(BundleMember));
  6870. if (BundleMember->hasValidDependencies())
  6871. continue;
  6872. LLVM_DEBUG(dbgs() << "SLP: update deps of " << *BundleMember
  6873. << "\n");
  6874. BundleMember->Dependencies = 0;
  6875. BundleMember->resetUnscheduledDeps();
  6876. // Handle def-use chain dependencies.
  6877. if (BundleMember->OpValue != BundleMember->Inst) {
  6878. ScheduleData *UseSD = getScheduleData(BundleMember->Inst);
  6879. if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
  6880. BundleMember->Dependencies++;
  6881. ScheduleData *DestBundle = UseSD->FirstInBundle;
  6882. if (!DestBundle->IsScheduled)
  6883. BundleMember->incrementUnscheduledDeps(1);
  6884. if (!DestBundle->hasValidDependencies())
  6885. WorkList.push_back(DestBundle);
  6886. }
  6887. } else {
  6888. for (User *U : BundleMember->Inst->users()) {
  6889. assert(isa<Instruction>(U) &&
  6890. "user of instruction must be instruction");
  6891. ScheduleData *UseSD = getScheduleData(U);
  6892. if (UseSD && isInSchedulingRegion(UseSD->FirstInBundle)) {
  6893. BundleMember->Dependencies++;
  6894. ScheduleData *DestBundle = UseSD->FirstInBundle;
  6895. if (!DestBundle->IsScheduled)
  6896. BundleMember->incrementUnscheduledDeps(1);
  6897. if (!DestBundle->hasValidDependencies())
  6898. WorkList.push_back(DestBundle);
  6899. }
  6900. }
  6901. }
  6902. // Handle the memory dependencies (if any).
  6903. ScheduleData *DepDest = BundleMember->NextLoadStore;
  6904. if (!DepDest)
  6905. continue;
  6906. Instruction *SrcInst = BundleMember->Inst;
  6907. assert(SrcInst->mayReadOrWriteMemory() &&
  6908. "NextLoadStore list for non memory effecting bundle?");
  6909. MemoryLocation SrcLoc = getLocation(SrcInst);
  6910. bool SrcMayWrite = BundleMember->Inst->mayWriteToMemory();
  6911. unsigned numAliased = 0;
  6912. unsigned DistToSrc = 1;
  6913. for ( ; DepDest; DepDest = DepDest->NextLoadStore) {
  6914. assert(isInSchedulingRegion(DepDest));
  6915. // We have two limits to reduce the complexity:
  6916. // 1) AliasedCheckLimit: It's a small limit to reduce calls to
  6917. // SLP->isAliased (which is the expensive part in this loop).
  6918. // 2) MaxMemDepDistance: It's for very large blocks and it aborts
  6919. // the whole loop (even if the loop is fast, it's quadratic).
  6920. // It's important for the loop break condition (see below) to
  6921. // check this limit even between two read-only instructions.
  6922. if (DistToSrc >= MaxMemDepDistance ||
  6923. ((SrcMayWrite || DepDest->Inst->mayWriteToMemory()) &&
  6924. (numAliased >= AliasedCheckLimit ||
  6925. SLP->isAliased(SrcLoc, SrcInst, DepDest->Inst)))) {
  6926. // We increment the counter only if the locations are aliased
  6927. // (instead of counting all alias checks). This gives a better
  6928. // balance between reduced runtime and accurate dependencies.
  6929. numAliased++;
  6930. DepDest->MemoryDependencies.push_back(BundleMember);
  6931. BundleMember->Dependencies++;
  6932. ScheduleData *DestBundle = DepDest->FirstInBundle;
  6933. if (!DestBundle->IsScheduled) {
  6934. BundleMember->incrementUnscheduledDeps(1);
  6935. }
  6936. if (!DestBundle->hasValidDependencies()) {
  6937. WorkList.push_back(DestBundle);
  6938. }
  6939. }
  6940. // Example, explaining the loop break condition: Let's assume our
  6941. // starting instruction is i0 and MaxMemDepDistance = 3.
  6942. //
  6943. // +--------v--v--v
  6944. // i0,i1,i2,i3,i4,i5,i6,i7,i8
  6945. // +--------^--^--^
  6946. //
  6947. // MaxMemDepDistance let us stop alias-checking at i3 and we add
  6948. // dependencies from i0 to i3,i4,.. (even if they are not aliased).
  6949. // Previously we already added dependencies from i3 to i6,i7,i8
  6950. // (because of MaxMemDepDistance). As we added a dependency from
  6951. // i0 to i3, we have transitive dependencies from i0 to i6,i7,i8
  6952. // and we can abort this loop at i6.
  6953. if (DistToSrc >= 2 * MaxMemDepDistance)
  6954. break;
  6955. DistToSrc++;
  6956. }
  6957. }
  6958. if (InsertInReadyList && SD->isReady()) {
  6959. ReadyInsts.push_back(SD);
  6960. LLVM_DEBUG(dbgs() << "SLP: gets ready on update: " << *SD->Inst
  6961. << "\n");
  6962. }
  6963. }
  6964. }
  6965. void BoUpSLP::BlockScheduling::resetSchedule() {
  6966. assert(ScheduleStart &&
  6967. "tried to reset schedule on block which has not been scheduled");
  6968. for (Instruction *I = ScheduleStart; I != ScheduleEnd; I = I->getNextNode()) {
  6969. doForAllOpcodes(I, [&](ScheduleData *SD) {
  6970. assert(isInSchedulingRegion(SD) &&
  6971. "ScheduleData not in scheduling region");
  6972. SD->IsScheduled = false;
  6973. SD->resetUnscheduledDeps();
  6974. });
  6975. }
  6976. ReadyInsts.clear();
  6977. }
  6978. void BoUpSLP::scheduleBlock(BlockScheduling *BS) {
  6979. if (!BS->ScheduleStart)
  6980. return;
  6981. LLVM_DEBUG(dbgs() << "SLP: schedule block " << BS->BB->getName() << "\n");
  6982. BS->resetSchedule();
  6983. // For the real scheduling we use a more sophisticated ready-list: it is
  6984. // sorted by the original instruction location. This lets the final schedule
  6985. // be as close as possible to the original instruction order.
  6986. struct ScheduleDataCompare {
  6987. bool operator()(ScheduleData *SD1, ScheduleData *SD2) const {
  6988. return SD2->SchedulingPriority < SD1->SchedulingPriority;
  6989. }
  6990. };
  6991. std::set<ScheduleData *, ScheduleDataCompare> ReadyInsts;
  6992. // Ensure that all dependency data is updated and fill the ready-list with
  6993. // initial instructions.
  6994. int Idx = 0;
  6995. int NumToSchedule = 0;
  6996. for (auto *I = BS->ScheduleStart; I != BS->ScheduleEnd;
  6997. I = I->getNextNode()) {
  6998. BS->doForAllOpcodes(I, [this, &Idx, &NumToSchedule, BS](ScheduleData *SD) {
  6999. assert((isVectorLikeInstWithConstOps(SD->Inst) ||
  7000. SD->isPartOfBundle() == (getTreeEntry(SD->Inst) != nullptr)) &&
  7001. "scheduler and vectorizer bundle mismatch");
  7002. SD->FirstInBundle->SchedulingPriority = Idx++;
  7003. if (SD->isSchedulingEntity()) {
  7004. BS->calculateDependencies(SD, false, this);
  7005. NumToSchedule++;
  7006. }
  7007. });
  7008. }
  7009. BS->initialFillReadyList(ReadyInsts);
  7010. Instruction *LastScheduledInst = BS->ScheduleEnd;
  7011. // Do the "real" scheduling.
  7012. while (!ReadyInsts.empty()) {
  7013. ScheduleData *picked = *ReadyInsts.begin();
  7014. ReadyInsts.erase(ReadyInsts.begin());
  7015. // Move the scheduled instruction(s) to their dedicated places, if not
  7016. // there yet.
  7017. for (ScheduleData *BundleMember = picked; BundleMember;
  7018. BundleMember = BundleMember->NextInBundle) {
  7019. Instruction *pickedInst = BundleMember->Inst;
  7020. if (pickedInst->getNextNode() != LastScheduledInst)
  7021. pickedInst->moveBefore(LastScheduledInst);
  7022. LastScheduledInst = pickedInst;
  7023. }
  7024. BS->schedule(picked, ReadyInsts);
  7025. NumToSchedule--;
  7026. }
  7027. assert(NumToSchedule == 0 && "could not schedule all instructions");
  7028. // Avoid duplicate scheduling of the block.
  7029. BS->ScheduleStart = nullptr;
  7030. }
  7031. unsigned BoUpSLP::getVectorElementSize(Value *V) {
  7032. // If V is a store, just return the width of the stored value (or value
  7033. // truncated just before storing) without traversing the expression tree.
  7034. // This is the common case.
  7035. if (auto *Store = dyn_cast<StoreInst>(V)) {
  7036. if (auto *Trunc = dyn_cast<TruncInst>(Store->getValueOperand()))
  7037. return DL->getTypeSizeInBits(Trunc->getSrcTy());
  7038. return DL->getTypeSizeInBits(Store->getValueOperand()->getType());
  7039. }
  7040. if (auto *IEI = dyn_cast<InsertElementInst>(V))
  7041. return getVectorElementSize(IEI->getOperand(1));
  7042. auto E = InstrElementSize.find(V);
  7043. if (E != InstrElementSize.end())
  7044. return E->second;
  7045. // If V is not a store, we can traverse the expression tree to find loads
  7046. // that feed it. The type of the loaded value may indicate a more suitable
  7047. // width than V's type. We want to base the vector element size on the width
  7048. // of memory operations where possible.
  7049. SmallVector<std::pair<Instruction *, BasicBlock *>, 16> Worklist;
  7050. SmallPtrSet<Instruction *, 16> Visited;
  7051. if (auto *I = dyn_cast<Instruction>(V)) {
  7052. Worklist.emplace_back(I, I->getParent());
  7053. Visited.insert(I);
  7054. }
  7055. // Traverse the expression tree in bottom-up order looking for loads. If we
  7056. // encounter an instruction we don't yet handle, we give up.
  7057. auto Width = 0u;
  7058. while (!Worklist.empty()) {
  7059. Instruction *I;
  7060. BasicBlock *Parent;
  7061. std::tie(I, Parent) = Worklist.pop_back_val();
  7062. // We should only be looking at scalar instructions here. If the current
  7063. // instruction has a vector type, skip.
  7064. auto *Ty = I->getType();
  7065. if (isa<VectorType>(Ty))
  7066. continue;
  7067. // If the current instruction is a load, update MaxWidth to reflect the
  7068. // width of the loaded value.
  7069. if (isa<LoadInst>(I) || isa<ExtractElementInst>(I) ||
  7070. isa<ExtractValueInst>(I))
  7071. Width = std::max<unsigned>(Width, DL->getTypeSizeInBits(Ty));
  7072. // Otherwise, we need to visit the operands of the instruction. We only
  7073. // handle the interesting cases from buildTree here. If an operand is an
  7074. // instruction we haven't yet visited and from the same basic block as the
  7075. // user or the use is a PHI node, we add it to the worklist.
  7076. else if (isa<PHINode>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I) ||
  7077. isa<CmpInst>(I) || isa<SelectInst>(I) || isa<BinaryOperator>(I) ||
  7078. isa<UnaryOperator>(I)) {
  7079. for (Use &U : I->operands())
  7080. if (auto *J = dyn_cast<Instruction>(U.get()))
  7081. if (Visited.insert(J).second &&
  7082. (isa<PHINode>(I) || J->getParent() == Parent))
  7083. Worklist.emplace_back(J, J->getParent());
  7084. } else {
  7085. break;
  7086. }
  7087. }
  7088. // If we didn't encounter a memory access in the expression tree, or if we
  7089. // gave up for some reason, just return the width of V. Otherwise, return the
  7090. // maximum width we found.
  7091. if (!Width) {
  7092. if (auto *CI = dyn_cast<CmpInst>(V))
  7093. V = CI->getOperand(0);
  7094. Width = DL->getTypeSizeInBits(V->getType());
  7095. }
  7096. for (Instruction *I : Visited)
  7097. InstrElementSize[I] = Width;
  7098. return Width;
  7099. }
  7100. // Determine if a value V in a vectorizable expression Expr can be demoted to a
  7101. // smaller type with a truncation. We collect the values that will be demoted
  7102. // in ToDemote and additional roots that require investigating in Roots.
  7103. static bool collectValuesToDemote(Value *V, SmallPtrSetImpl<Value *> &Expr,
  7104. SmallVectorImpl<Value *> &ToDemote,
  7105. SmallVectorImpl<Value *> &Roots) {
  7106. // We can always demote constants.
  7107. if (isa<Constant>(V)) {
  7108. ToDemote.push_back(V);
  7109. return true;
  7110. }
  7111. // If the value is not an instruction in the expression with only one use, it
  7112. // cannot be demoted.
  7113. auto *I = dyn_cast<Instruction>(V);
  7114. if (!I || !I->hasOneUse() || !Expr.count(I))
  7115. return false;
  7116. switch (I->getOpcode()) {
  7117. // We can always demote truncations and extensions. Since truncations can
  7118. // seed additional demotion, we save the truncated value.
  7119. case Instruction::Trunc:
  7120. Roots.push_back(I->getOperand(0));
  7121. break;
  7122. case Instruction::ZExt:
  7123. case Instruction::SExt:
  7124. if (isa<ExtractElementInst>(I->getOperand(0)) ||
  7125. isa<InsertElementInst>(I->getOperand(0)))
  7126. return false;
  7127. break;
  7128. // We can demote certain binary operations if we can demote both of their
  7129. // operands.
  7130. case Instruction::Add:
  7131. case Instruction::Sub:
  7132. case Instruction::Mul:
  7133. case Instruction::And:
  7134. case Instruction::Or:
  7135. case Instruction::Xor:
  7136. if (!collectValuesToDemote(I->getOperand(0), Expr, ToDemote, Roots) ||
  7137. !collectValuesToDemote(I->getOperand(1), Expr, ToDemote, Roots))
  7138. return false;
  7139. break;
  7140. // We can demote selects if we can demote their true and false values.
  7141. case Instruction::Select: {
  7142. SelectInst *SI = cast<SelectInst>(I);
  7143. if (!collectValuesToDemote(SI->getTrueValue(), Expr, ToDemote, Roots) ||
  7144. !collectValuesToDemote(SI->getFalseValue(), Expr, ToDemote, Roots))
  7145. return false;
  7146. break;
  7147. }
  7148. // We can demote phis if we can demote all their incoming operands. Note that
  7149. // we don't need to worry about cycles since we ensure single use above.
  7150. case Instruction::PHI: {
  7151. PHINode *PN = cast<PHINode>(I);
  7152. for (Value *IncValue : PN->incoming_values())
  7153. if (!collectValuesToDemote(IncValue, Expr, ToDemote, Roots))
  7154. return false;
  7155. break;
  7156. }
  7157. // Otherwise, conservatively give up.
  7158. default:
  7159. return false;
  7160. }
  7161. // Record the value that we can demote.
  7162. ToDemote.push_back(V);
  7163. return true;
  7164. }
  7165. void BoUpSLP::computeMinimumValueSizes() {
  7166. // If there are no external uses, the expression tree must be rooted by a
  7167. // store. We can't demote in-memory values, so there is nothing to do here.
  7168. if (ExternalUses.empty())
  7169. return;
  7170. // We only attempt to truncate integer expressions.
  7171. auto &TreeRoot = VectorizableTree[0]->Scalars;
  7172. auto *TreeRootIT = dyn_cast<IntegerType>(TreeRoot[0]->getType());
  7173. if (!TreeRootIT)
  7174. return;
  7175. // If the expression is not rooted by a store, these roots should have
  7176. // external uses. We will rely on InstCombine to rewrite the expression in
  7177. // the narrower type. However, InstCombine only rewrites single-use values.
  7178. // This means that if a tree entry other than a root is used externally, it
  7179. // must have multiple uses and InstCombine will not rewrite it. The code
  7180. // below ensures that only the roots are used externally.
  7181. SmallPtrSet<Value *, 32> Expr(TreeRoot.begin(), TreeRoot.end());
  7182. for (auto &EU : ExternalUses)
  7183. if (!Expr.erase(EU.Scalar))
  7184. return;
  7185. if (!Expr.empty())
  7186. return;
  7187. // Collect the scalar values of the vectorizable expression. We will use this
  7188. // context to determine which values can be demoted. If we see a truncation,
  7189. // we mark it as seeding another demotion.
  7190. for (auto &EntryPtr : VectorizableTree)
  7191. Expr.insert(EntryPtr->Scalars.begin(), EntryPtr->Scalars.end());
  7192. // Ensure the roots of the vectorizable tree don't form a cycle. They must
  7193. // have a single external user that is not in the vectorizable tree.
  7194. for (auto *Root : TreeRoot)
  7195. if (!Root->hasOneUse() || Expr.count(*Root->user_begin()))
  7196. return;
  7197. // Conservatively determine if we can actually truncate the roots of the
  7198. // expression. Collect the values that can be demoted in ToDemote and
  7199. // additional roots that require investigating in Roots.
  7200. SmallVector<Value *, 32> ToDemote;
  7201. SmallVector<Value *, 4> Roots;
  7202. for (auto *Root : TreeRoot)
  7203. if (!collectValuesToDemote(Root, Expr, ToDemote, Roots))
  7204. return;
  7205. // The maximum bit width required to represent all the values that can be
  7206. // demoted without loss of precision. It would be safe to truncate the roots
  7207. // of the expression to this width.
  7208. auto MaxBitWidth = 8u;
  7209. // We first check if all the bits of the roots are demanded. If they're not,
  7210. // we can truncate the roots to this narrower type.
  7211. for (auto *Root : TreeRoot) {
  7212. auto Mask = DB->getDemandedBits(cast<Instruction>(Root));
  7213. MaxBitWidth = std::max<unsigned>(
  7214. Mask.getBitWidth() - Mask.countLeadingZeros(), MaxBitWidth);
  7215. }
  7216. // True if the roots can be zero-extended back to their original type, rather
  7217. // than sign-extended. We know that if the leading bits are not demanded, we
  7218. // can safely zero-extend. So we initialize IsKnownPositive to True.
  7219. bool IsKnownPositive = true;
  7220. // If all the bits of the roots are demanded, we can try a little harder to
  7221. // compute a narrower type. This can happen, for example, if the roots are
  7222. // getelementptr indices. InstCombine promotes these indices to the pointer
  7223. // width. Thus, all their bits are technically demanded even though the
  7224. // address computation might be vectorized in a smaller type.
  7225. //
  7226. // We start by looking at each entry that can be demoted. We compute the
  7227. // maximum bit width required to store the scalar by using ValueTracking to
  7228. // compute the number of high-order bits we can truncate.
  7229. if (MaxBitWidth == DL->getTypeSizeInBits(TreeRoot[0]->getType()) &&
  7230. llvm::all_of(TreeRoot, [](Value *R) {
  7231. assert(R->hasOneUse() && "Root should have only one use!");
  7232. return isa<GetElementPtrInst>(R->user_back());
  7233. })) {
  7234. MaxBitWidth = 8u;
  7235. // Determine if the sign bit of all the roots is known to be zero. If not,
  7236. // IsKnownPositive is set to False.
  7237. IsKnownPositive = llvm::all_of(TreeRoot, [&](Value *R) {
  7238. KnownBits Known = computeKnownBits(R, *DL);
  7239. return Known.isNonNegative();
  7240. });
  7241. // Determine the maximum number of bits required to store the scalar
  7242. // values.
  7243. for (auto *Scalar : ToDemote) {
  7244. auto NumSignBits = ComputeNumSignBits(Scalar, *DL, 0, AC, nullptr, DT);
  7245. auto NumTypeBits = DL->getTypeSizeInBits(Scalar->getType());
  7246. MaxBitWidth = std::max<unsigned>(NumTypeBits - NumSignBits, MaxBitWidth);
  7247. }
  7248. // If we can't prove that the sign bit is zero, we must add one to the
  7249. // maximum bit width to account for the unknown sign bit. This preserves
  7250. // the existing sign bit so we can safely sign-extend the root back to the
  7251. // original type. Otherwise, if we know the sign bit is zero, we will
  7252. // zero-extend the root instead.
  7253. //
  7254. // FIXME: This is somewhat suboptimal, as there will be cases where adding
  7255. // one to the maximum bit width will yield a larger-than-necessary
  7256. // type. In general, we need to add an extra bit only if we can't
  7257. // prove that the upper bit of the original type is equal to the
  7258. // upper bit of the proposed smaller type. If these two bits are the
  7259. // same (either zero or one) we know that sign-extending from the
  7260. // smaller type will result in the same value. Here, since we can't
  7261. // yet prove this, we are just making the proposed smaller type
  7262. // larger to ensure correctness.
  7263. if (!IsKnownPositive)
  7264. ++MaxBitWidth;
  7265. }
  7266. // Round MaxBitWidth up to the next power-of-two.
  7267. if (!isPowerOf2_64(MaxBitWidth))
  7268. MaxBitWidth = NextPowerOf2(MaxBitWidth);
  7269. // If the maximum bit width we compute is less than the with of the roots'
  7270. // type, we can proceed with the narrowing. Otherwise, do nothing.
  7271. if (MaxBitWidth >= TreeRootIT->getBitWidth())
  7272. return;
  7273. // If we can truncate the root, we must collect additional values that might
  7274. // be demoted as a result. That is, those seeded by truncations we will
  7275. // modify.
  7276. while (!Roots.empty())
  7277. collectValuesToDemote(Roots.pop_back_val(), Expr, ToDemote, Roots);
  7278. // Finally, map the values we can demote to the maximum bit with we computed.
  7279. for (auto *Scalar : ToDemote)
  7280. MinBWs[Scalar] = std::make_pair(MaxBitWidth, !IsKnownPositive);
  7281. }
  7282. namespace {
  7283. /// The SLPVectorizer Pass.
  7284. struct SLPVectorizer : public FunctionPass {
  7285. SLPVectorizerPass Impl;
  7286. /// Pass identification, replacement for typeid
  7287. static char ID;
  7288. explicit SLPVectorizer() : FunctionPass(ID) {
  7289. initializeSLPVectorizerPass(*PassRegistry::getPassRegistry());
  7290. }
  7291. bool doInitialization(Module &M) override { return false; }
  7292. bool runOnFunction(Function &F) override {
  7293. if (skipFunction(F))
  7294. return false;
  7295. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  7296. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  7297. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  7298. auto *TLI = TLIP ? &TLIP->getTLI(F) : nullptr;
  7299. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  7300. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  7301. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  7302. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  7303. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  7304. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  7305. return Impl.runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
  7306. }
  7307. void getAnalysisUsage(AnalysisUsage &AU) const override {
  7308. FunctionPass::getAnalysisUsage(AU);
  7309. AU.addRequired<AssumptionCacheTracker>();
  7310. AU.addRequired<ScalarEvolutionWrapperPass>();
  7311. AU.addRequired<AAResultsWrapperPass>();
  7312. AU.addRequired<TargetTransformInfoWrapperPass>();
  7313. AU.addRequired<LoopInfoWrapperPass>();
  7314. AU.addRequired<DominatorTreeWrapperPass>();
  7315. AU.addRequired<DemandedBitsWrapperPass>();
  7316. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  7317. AU.addRequired<InjectTLIMappingsLegacy>();
  7318. AU.addPreserved<LoopInfoWrapperPass>();
  7319. AU.addPreserved<DominatorTreeWrapperPass>();
  7320. AU.addPreserved<AAResultsWrapperPass>();
  7321. AU.addPreserved<GlobalsAAWrapperPass>();
  7322. AU.setPreservesCFG();
  7323. }
  7324. };
  7325. } // end anonymous namespace
  7326. PreservedAnalyses SLPVectorizerPass::run(Function &F, FunctionAnalysisManager &AM) {
  7327. auto *SE = &AM.getResult<ScalarEvolutionAnalysis>(F);
  7328. auto *TTI = &AM.getResult<TargetIRAnalysis>(F);
  7329. auto *TLI = AM.getCachedResult<TargetLibraryAnalysis>(F);
  7330. auto *AA = &AM.getResult<AAManager>(F);
  7331. auto *LI = &AM.getResult<LoopAnalysis>(F);
  7332. auto *DT = &AM.getResult<DominatorTreeAnalysis>(F);
  7333. auto *AC = &AM.getResult<AssumptionAnalysis>(F);
  7334. auto *DB = &AM.getResult<DemandedBitsAnalysis>(F);
  7335. auto *ORE = &AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  7336. bool Changed = runImpl(F, SE, TTI, TLI, AA, LI, DT, AC, DB, ORE);
  7337. if (!Changed)
  7338. return PreservedAnalyses::all();
  7339. PreservedAnalyses PA;
  7340. PA.preserveSet<CFGAnalyses>();
  7341. return PA;
  7342. }
  7343. bool SLPVectorizerPass::runImpl(Function &F, ScalarEvolution *SE_,
  7344. TargetTransformInfo *TTI_,
  7345. TargetLibraryInfo *TLI_, AAResults *AA_,
  7346. LoopInfo *LI_, DominatorTree *DT_,
  7347. AssumptionCache *AC_, DemandedBits *DB_,
  7348. OptimizationRemarkEmitter *ORE_) {
  7349. if (!RunSLPVectorization)
  7350. return false;
  7351. SE = SE_;
  7352. TTI = TTI_;
  7353. TLI = TLI_;
  7354. AA = AA_;
  7355. LI = LI_;
  7356. DT = DT_;
  7357. AC = AC_;
  7358. DB = DB_;
  7359. DL = &F.getParent()->getDataLayout();
  7360. Stores.clear();
  7361. GEPs.clear();
  7362. bool Changed = false;
  7363. // If the target claims to have no vector registers don't attempt
  7364. // vectorization.
  7365. if (!TTI->getNumberOfRegisters(TTI->getRegisterClassForType(true))) {
  7366. LLVM_DEBUG(
  7367. dbgs() << "SLP: Didn't find any vector registers for target, abort.\n");
  7368. return false;
  7369. }
  7370. // Don't vectorize when the attribute NoImplicitFloat is used.
  7371. if (F.hasFnAttribute(Attribute::NoImplicitFloat))
  7372. return false;
  7373. LLVM_DEBUG(dbgs() << "SLP: Analyzing blocks in " << F.getName() << ".\n");
  7374. // Use the bottom up slp vectorizer to construct chains that start with
  7375. // store instructions.
  7376. BoUpSLP R(&F, SE, TTI, TLI, AA, LI, DT, AC, DB, DL, ORE_);
  7377. // A general note: the vectorizer must use BoUpSLP::eraseInstruction() to
  7378. // delete instructions.
  7379. // Update DFS numbers now so that we can use them for ordering.
  7380. DT->updateDFSNumbers();
  7381. // Scan the blocks in the function in post order.
  7382. for (auto BB : post_order(&F.getEntryBlock())) {
  7383. collectSeedInstructions(BB);
  7384. // Vectorize trees that end at stores.
  7385. if (!Stores.empty()) {
  7386. LLVM_DEBUG(dbgs() << "SLP: Found stores for " << Stores.size()
  7387. << " underlying objects.\n");
  7388. Changed |= vectorizeStoreChains(R);
  7389. }
  7390. // Vectorize trees that end at reductions.
  7391. Changed |= vectorizeChainsInBlock(BB, R);
  7392. // Vectorize the index computations of getelementptr instructions. This
  7393. // is primarily intended to catch gather-like idioms ending at
  7394. // non-consecutive loads.
  7395. if (!GEPs.empty()) {
  7396. LLVM_DEBUG(dbgs() << "SLP: Found GEPs for " << GEPs.size()
  7397. << " underlying objects.\n");
  7398. Changed |= vectorizeGEPIndices(BB, R);
  7399. }
  7400. }
  7401. if (Changed) {
  7402. R.optimizeGatherSequence();
  7403. LLVM_DEBUG(dbgs() << "SLP: vectorized \"" << F.getName() << "\"\n");
  7404. }
  7405. return Changed;
  7406. }
  7407. bool SLPVectorizerPass::vectorizeStoreChain(ArrayRef<Value *> Chain, BoUpSLP &R,
  7408. unsigned Idx) {
  7409. LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length " << Chain.size()
  7410. << "\n");
  7411. const unsigned Sz = R.getVectorElementSize(Chain[0]);
  7412. const unsigned MinVF = R.getMinVecRegSize() / Sz;
  7413. unsigned VF = Chain.size();
  7414. if (!isPowerOf2_32(Sz) || !isPowerOf2_32(VF) || VF < 2 || VF < MinVF)
  7415. return false;
  7416. LLVM_DEBUG(dbgs() << "SLP: Analyzing " << VF << " stores at offset " << Idx
  7417. << "\n");
  7418. R.buildTree(Chain);
  7419. if (R.isTreeTinyAndNotFullyVectorizable())
  7420. return false;
  7421. if (R.isLoadCombineCandidate())
  7422. return false;
  7423. R.reorderTopToBottom();
  7424. R.reorderBottomToTop();
  7425. R.buildExternalUses();
  7426. R.computeMinimumValueSizes();
  7427. InstructionCost Cost = R.getTreeCost();
  7428. LLVM_DEBUG(dbgs() << "SLP: Found cost = " << Cost << " for VF =" << VF << "\n");
  7429. if (Cost < -SLPCostThreshold) {
  7430. LLVM_DEBUG(dbgs() << "SLP: Decided to vectorize cost = " << Cost << "\n");
  7431. using namespace ore;
  7432. R.getORE()->emit(OptimizationRemark(SV_NAME, "StoresVectorized",
  7433. cast<StoreInst>(Chain[0]))
  7434. << "Stores SLP vectorized with cost " << NV("Cost", Cost)
  7435. << " and with tree size "
  7436. << NV("TreeSize", R.getTreeSize()));
  7437. R.vectorizeTree();
  7438. return true;
  7439. }
  7440. return false;
  7441. }
  7442. bool SLPVectorizerPass::vectorizeStores(ArrayRef<StoreInst *> Stores,
  7443. BoUpSLP &R) {
  7444. // We may run into multiple chains that merge into a single chain. We mark the
  7445. // stores that we vectorized so that we don't visit the same store twice.
  7446. BoUpSLP::ValueSet VectorizedStores;
  7447. bool Changed = false;
  7448. int E = Stores.size();
  7449. SmallBitVector Tails(E, false);
  7450. int MaxIter = MaxStoreLookup.getValue();
  7451. SmallVector<std::pair<int, int>, 16> ConsecutiveChain(
  7452. E, std::make_pair(E, INT_MAX));
  7453. SmallVector<SmallBitVector, 4> CheckedPairs(E, SmallBitVector(E, false));
  7454. int IterCnt;
  7455. auto &&FindConsecutiveAccess = [this, &Stores, &Tails, &IterCnt, MaxIter,
  7456. &CheckedPairs,
  7457. &ConsecutiveChain](int K, int Idx) {
  7458. if (IterCnt >= MaxIter)
  7459. return true;
  7460. if (CheckedPairs[Idx].test(K))
  7461. return ConsecutiveChain[K].second == 1 &&
  7462. ConsecutiveChain[K].first == Idx;
  7463. ++IterCnt;
  7464. CheckedPairs[Idx].set(K);
  7465. CheckedPairs[K].set(Idx);
  7466. Optional<int> Diff = getPointersDiff(
  7467. Stores[K]->getValueOperand()->getType(), Stores[K]->getPointerOperand(),
  7468. Stores[Idx]->getValueOperand()->getType(),
  7469. Stores[Idx]->getPointerOperand(), *DL, *SE, /*StrictCheck=*/true);
  7470. if (!Diff || *Diff == 0)
  7471. return false;
  7472. int Val = *Diff;
  7473. if (Val < 0) {
  7474. if (ConsecutiveChain[Idx].second > -Val) {
  7475. Tails.set(K);
  7476. ConsecutiveChain[Idx] = std::make_pair(K, -Val);
  7477. }
  7478. return false;
  7479. }
  7480. if (ConsecutiveChain[K].second <= Val)
  7481. return false;
  7482. Tails.set(Idx);
  7483. ConsecutiveChain[K] = std::make_pair(Idx, Val);
  7484. return Val == 1;
  7485. };
  7486. // Do a quadratic search on all of the given stores in reverse order and find
  7487. // all of the pairs of stores that follow each other.
  7488. for (int Idx = E - 1; Idx >= 0; --Idx) {
  7489. // If a store has multiple consecutive store candidates, search according
  7490. // to the sequence: Idx-1, Idx+1, Idx-2, Idx+2, ...
  7491. // This is because usually pairing with immediate succeeding or preceding
  7492. // candidate create the best chance to find slp vectorization opportunity.
  7493. const int MaxLookDepth = std::max(E - Idx, Idx + 1);
  7494. IterCnt = 0;
  7495. for (int Offset = 1, F = MaxLookDepth; Offset < F; ++Offset)
  7496. if ((Idx >= Offset && FindConsecutiveAccess(Idx - Offset, Idx)) ||
  7497. (Idx + Offset < E && FindConsecutiveAccess(Idx + Offset, Idx)))
  7498. break;
  7499. }
  7500. // Tracks if we tried to vectorize stores starting from the given tail
  7501. // already.
  7502. SmallBitVector TriedTails(E, false);
  7503. // For stores that start but don't end a link in the chain:
  7504. for (int Cnt = E; Cnt > 0; --Cnt) {
  7505. int I = Cnt - 1;
  7506. if (ConsecutiveChain[I].first == E || Tails.test(I))
  7507. continue;
  7508. // We found a store instr that starts a chain. Now follow the chain and try
  7509. // to vectorize it.
  7510. BoUpSLP::ValueList Operands;
  7511. // Collect the chain into a list.
  7512. while (I != E && !VectorizedStores.count(Stores[I])) {
  7513. Operands.push_back(Stores[I]);
  7514. Tails.set(I);
  7515. if (ConsecutiveChain[I].second != 1) {
  7516. // Mark the new end in the chain and go back, if required. It might be
  7517. // required if the original stores come in reversed order, for example.
  7518. if (ConsecutiveChain[I].first != E &&
  7519. Tails.test(ConsecutiveChain[I].first) && !TriedTails.test(I) &&
  7520. !VectorizedStores.count(Stores[ConsecutiveChain[I].first])) {
  7521. TriedTails.set(I);
  7522. Tails.reset(ConsecutiveChain[I].first);
  7523. if (Cnt < ConsecutiveChain[I].first + 2)
  7524. Cnt = ConsecutiveChain[I].first + 2;
  7525. }
  7526. break;
  7527. }
  7528. // Move to the next value in the chain.
  7529. I = ConsecutiveChain[I].first;
  7530. }
  7531. assert(!Operands.empty() && "Expected non-empty list of stores.");
  7532. unsigned MaxVecRegSize = R.getMaxVecRegSize();
  7533. unsigned EltSize = R.getVectorElementSize(Operands[0]);
  7534. unsigned MaxElts = llvm::PowerOf2Floor(MaxVecRegSize / EltSize);
  7535. unsigned MinVF = R.getMinVF(EltSize);
  7536. unsigned MaxVF = std::min(R.getMaximumVF(EltSize, Instruction::Store),
  7537. MaxElts);
  7538. // FIXME: Is division-by-2 the correct step? Should we assert that the
  7539. // register size is a power-of-2?
  7540. unsigned StartIdx = 0;
  7541. for (unsigned Size = MaxVF; Size >= MinVF; Size /= 2) {
  7542. for (unsigned Cnt = StartIdx, E = Operands.size(); Cnt + Size <= E;) {
  7543. ArrayRef<Value *> Slice = makeArrayRef(Operands).slice(Cnt, Size);
  7544. if (!VectorizedStores.count(Slice.front()) &&
  7545. !VectorizedStores.count(Slice.back()) &&
  7546. vectorizeStoreChain(Slice, R, Cnt)) {
  7547. // Mark the vectorized stores so that we don't vectorize them again.
  7548. VectorizedStores.insert(Slice.begin(), Slice.end());
  7549. Changed = true;
  7550. // If we vectorized initial block, no need to try to vectorize it
  7551. // again.
  7552. if (Cnt == StartIdx)
  7553. StartIdx += Size;
  7554. Cnt += Size;
  7555. continue;
  7556. }
  7557. ++Cnt;
  7558. }
  7559. // Check if the whole array was vectorized already - exit.
  7560. if (StartIdx >= Operands.size())
  7561. break;
  7562. }
  7563. }
  7564. return Changed;
  7565. }
  7566. void SLPVectorizerPass::collectSeedInstructions(BasicBlock *BB) {
  7567. // Initialize the collections. We will make a single pass over the block.
  7568. Stores.clear();
  7569. GEPs.clear();
  7570. // Visit the store and getelementptr instructions in BB and organize them in
  7571. // Stores and GEPs according to the underlying objects of their pointer
  7572. // operands.
  7573. for (Instruction &I : *BB) {
  7574. // Ignore store instructions that are volatile or have a pointer operand
  7575. // that doesn't point to a scalar type.
  7576. if (auto *SI = dyn_cast<StoreInst>(&I)) {
  7577. if (!SI->isSimple())
  7578. continue;
  7579. if (!isValidElementType(SI->getValueOperand()->getType()))
  7580. continue;
  7581. Stores[getUnderlyingObject(SI->getPointerOperand())].push_back(SI);
  7582. }
  7583. // Ignore getelementptr instructions that have more than one index, a
  7584. // constant index, or a pointer operand that doesn't point to a scalar
  7585. // type.
  7586. else if (auto *GEP = dyn_cast<GetElementPtrInst>(&I)) {
  7587. auto Idx = GEP->idx_begin()->get();
  7588. if (GEP->getNumIndices() > 1 || isa<Constant>(Idx))
  7589. continue;
  7590. if (!isValidElementType(Idx->getType()))
  7591. continue;
  7592. if (GEP->getType()->isVectorTy())
  7593. continue;
  7594. GEPs[GEP->getPointerOperand()].push_back(GEP);
  7595. }
  7596. }
  7597. }
  7598. bool SLPVectorizerPass::tryToVectorizePair(Value *A, Value *B, BoUpSLP &R) {
  7599. if (!A || !B)
  7600. return false;
  7601. if (isa<InsertElementInst>(A) || isa<InsertElementInst>(B))
  7602. return false;
  7603. Value *VL[] = {A, B};
  7604. return tryToVectorizeList(VL, R);
  7605. }
  7606. bool SLPVectorizerPass::tryToVectorizeList(ArrayRef<Value *> VL, BoUpSLP &R,
  7607. bool LimitForRegisterSize) {
  7608. if (VL.size() < 2)
  7609. return false;
  7610. LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize a list of length = "
  7611. << VL.size() << ".\n");
  7612. // Check that all of the parts are instructions of the same type,
  7613. // we permit an alternate opcode via InstructionsState.
  7614. InstructionsState S = getSameOpcode(VL);
  7615. if (!S.getOpcode())
  7616. return false;
  7617. Instruction *I0 = cast<Instruction>(S.OpValue);
  7618. // Make sure invalid types (including vector type) are rejected before
  7619. // determining vectorization factor for scalar instructions.
  7620. for (Value *V : VL) {
  7621. Type *Ty = V->getType();
  7622. if (!isa<InsertElementInst>(V) && !isValidElementType(Ty)) {
  7623. // NOTE: the following will give user internal llvm type name, which may
  7624. // not be useful.
  7625. R.getORE()->emit([&]() {
  7626. std::string type_str;
  7627. llvm::raw_string_ostream rso(type_str);
  7628. Ty->print(rso);
  7629. return OptimizationRemarkMissed(SV_NAME, "UnsupportedType", I0)
  7630. << "Cannot SLP vectorize list: type "
  7631. << rso.str() + " is unsupported by vectorizer";
  7632. });
  7633. return false;
  7634. }
  7635. }
  7636. unsigned Sz = R.getVectorElementSize(I0);
  7637. unsigned MinVF = R.getMinVF(Sz);
  7638. unsigned MaxVF = std::max<unsigned>(PowerOf2Floor(VL.size()), MinVF);
  7639. MaxVF = std::min(R.getMaximumVF(Sz, S.getOpcode()), MaxVF);
  7640. if (MaxVF < 2) {
  7641. R.getORE()->emit([&]() {
  7642. return OptimizationRemarkMissed(SV_NAME, "SmallVF", I0)
  7643. << "Cannot SLP vectorize list: vectorization factor "
  7644. << "less than 2 is not supported";
  7645. });
  7646. return false;
  7647. }
  7648. bool Changed = false;
  7649. bool CandidateFound = false;
  7650. InstructionCost MinCost = SLPCostThreshold.getValue();
  7651. Type *ScalarTy = VL[0]->getType();
  7652. if (auto *IE = dyn_cast<InsertElementInst>(VL[0]))
  7653. ScalarTy = IE->getOperand(1)->getType();
  7654. unsigned NextInst = 0, MaxInst = VL.size();
  7655. for (unsigned VF = MaxVF; NextInst + 1 < MaxInst && VF >= MinVF; VF /= 2) {
  7656. // No actual vectorization should happen, if number of parts is the same as
  7657. // provided vectorization factor (i.e. the scalar type is used for vector
  7658. // code during codegen).
  7659. auto *VecTy = FixedVectorType::get(ScalarTy, VF);
  7660. if (TTI->getNumberOfParts(VecTy) == VF)
  7661. continue;
  7662. for (unsigned I = NextInst; I < MaxInst; ++I) {
  7663. unsigned OpsWidth = 0;
  7664. if (I + VF > MaxInst)
  7665. OpsWidth = MaxInst - I;
  7666. else
  7667. OpsWidth = VF;
  7668. if (!isPowerOf2_32(OpsWidth))
  7669. continue;
  7670. if ((LimitForRegisterSize && OpsWidth < MaxVF) ||
  7671. (VF > MinVF && OpsWidth <= VF / 2) || (VF == MinVF && OpsWidth < 2))
  7672. break;
  7673. ArrayRef<Value *> Ops = VL.slice(I, OpsWidth);
  7674. // Check that a previous iteration of this loop did not delete the Value.
  7675. if (llvm::any_of(Ops, [&R](Value *V) {
  7676. auto *I = dyn_cast<Instruction>(V);
  7677. return I && R.isDeleted(I);
  7678. }))
  7679. continue;
  7680. LLVM_DEBUG(dbgs() << "SLP: Analyzing " << OpsWidth << " operations "
  7681. << "\n");
  7682. R.buildTree(Ops);
  7683. if (R.isTreeTinyAndNotFullyVectorizable())
  7684. continue;
  7685. R.reorderTopToBottom();
  7686. R.reorderBottomToTop(!isa<InsertElementInst>(Ops.front()));
  7687. R.buildExternalUses();
  7688. R.computeMinimumValueSizes();
  7689. InstructionCost Cost = R.getTreeCost();
  7690. CandidateFound = true;
  7691. MinCost = std::min(MinCost, Cost);
  7692. if (Cost < -SLPCostThreshold) {
  7693. LLVM_DEBUG(dbgs() << "SLP: Vectorizing list at cost:" << Cost << ".\n");
  7694. R.getORE()->emit(OptimizationRemark(SV_NAME, "VectorizedList",
  7695. cast<Instruction>(Ops[0]))
  7696. << "SLP vectorized with cost " << ore::NV("Cost", Cost)
  7697. << " and with tree size "
  7698. << ore::NV("TreeSize", R.getTreeSize()));
  7699. R.vectorizeTree();
  7700. // Move to the next bundle.
  7701. I += VF - 1;
  7702. NextInst = I + 1;
  7703. Changed = true;
  7704. }
  7705. }
  7706. }
  7707. if (!Changed && CandidateFound) {
  7708. R.getORE()->emit([&]() {
  7709. return OptimizationRemarkMissed(SV_NAME, "NotBeneficial", I0)
  7710. << "List vectorization was possible but not beneficial with cost "
  7711. << ore::NV("Cost", MinCost) << " >= "
  7712. << ore::NV("Treshold", -SLPCostThreshold);
  7713. });
  7714. } else if (!Changed) {
  7715. R.getORE()->emit([&]() {
  7716. return OptimizationRemarkMissed(SV_NAME, "NotPossible", I0)
  7717. << "Cannot SLP vectorize list: vectorization was impossible"
  7718. << " with available vectorization factors";
  7719. });
  7720. }
  7721. return Changed;
  7722. }
  7723. bool SLPVectorizerPass::tryToVectorize(Instruction *I, BoUpSLP &R) {
  7724. if (!I)
  7725. return false;
  7726. if (!isa<BinaryOperator>(I) && !isa<CmpInst>(I))
  7727. return false;
  7728. Value *P = I->getParent();
  7729. // Vectorize in current basic block only.
  7730. auto *Op0 = dyn_cast<Instruction>(I->getOperand(0));
  7731. auto *Op1 = dyn_cast<Instruction>(I->getOperand(1));
  7732. if (!Op0 || !Op1 || Op0->getParent() != P || Op1->getParent() != P)
  7733. return false;
  7734. // Try to vectorize V.
  7735. if (tryToVectorizePair(Op0, Op1, R))
  7736. return true;
  7737. auto *A = dyn_cast<BinaryOperator>(Op0);
  7738. auto *B = dyn_cast<BinaryOperator>(Op1);
  7739. // Try to skip B.
  7740. if (B && B->hasOneUse()) {
  7741. auto *B0 = dyn_cast<BinaryOperator>(B->getOperand(0));
  7742. auto *B1 = dyn_cast<BinaryOperator>(B->getOperand(1));
  7743. if (B0 && B0->getParent() == P && tryToVectorizePair(A, B0, R))
  7744. return true;
  7745. if (B1 && B1->getParent() == P && tryToVectorizePair(A, B1, R))
  7746. return true;
  7747. }
  7748. // Try to skip A.
  7749. if (A && A->hasOneUse()) {
  7750. auto *A0 = dyn_cast<BinaryOperator>(A->getOperand(0));
  7751. auto *A1 = dyn_cast<BinaryOperator>(A->getOperand(1));
  7752. if (A0 && A0->getParent() == P && tryToVectorizePair(A0, B, R))
  7753. return true;
  7754. if (A1 && A1->getParent() == P && tryToVectorizePair(A1, B, R))
  7755. return true;
  7756. }
  7757. return false;
  7758. }
  7759. namespace {
  7760. /// Model horizontal reductions.
  7761. ///
  7762. /// A horizontal reduction is a tree of reduction instructions that has values
  7763. /// that can be put into a vector as its leaves. For example:
  7764. ///
  7765. /// mul mul mul mul
  7766. /// \ / \ /
  7767. /// + +
  7768. /// \ /
  7769. /// +
  7770. /// This tree has "mul" as its leaf values and "+" as its reduction
  7771. /// instructions. A reduction can feed into a store or a binary operation
  7772. /// feeding a phi.
  7773. /// ...
  7774. /// \ /
  7775. /// +
  7776. /// |
  7777. /// phi +=
  7778. ///
  7779. /// Or:
  7780. /// ...
  7781. /// \ /
  7782. /// +
  7783. /// |
  7784. /// *p =
  7785. ///
  7786. class HorizontalReduction {
  7787. using ReductionOpsType = SmallVector<Value *, 16>;
  7788. using ReductionOpsListType = SmallVector<ReductionOpsType, 2>;
  7789. ReductionOpsListType ReductionOps;
  7790. SmallVector<Value *, 32> ReducedVals;
  7791. // Use map vector to make stable output.
  7792. MapVector<Instruction *, Value *> ExtraArgs;
  7793. WeakTrackingVH ReductionRoot;
  7794. /// The type of reduction operation.
  7795. RecurKind RdxKind;
  7796. const unsigned INVALID_OPERAND_INDEX = std::numeric_limits<unsigned>::max();
  7797. static bool isCmpSelMinMax(Instruction *I) {
  7798. return match(I, m_Select(m_Cmp(), m_Value(), m_Value())) &&
  7799. RecurrenceDescriptor::isMinMaxRecurrenceKind(getRdxKind(I));
  7800. }
  7801. // And/or are potentially poison-safe logical patterns like:
  7802. // select x, y, false
  7803. // select x, true, y
  7804. static bool isBoolLogicOp(Instruction *I) {
  7805. return match(I, m_LogicalAnd(m_Value(), m_Value())) ||
  7806. match(I, m_LogicalOr(m_Value(), m_Value()));
  7807. }
  7808. /// Checks if instruction is associative and can be vectorized.
  7809. static bool isVectorizable(RecurKind Kind, Instruction *I) {
  7810. if (Kind == RecurKind::None)
  7811. return false;
  7812. // Integer ops that map to select instructions or intrinsics are fine.
  7813. if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(Kind) ||
  7814. isBoolLogicOp(I))
  7815. return true;
  7816. if (Kind == RecurKind::FMax || Kind == RecurKind::FMin) {
  7817. // FP min/max are associative except for NaN and -0.0. We do not
  7818. // have to rule out -0.0 here because the intrinsic semantics do not
  7819. // specify a fixed result for it.
  7820. return I->getFastMathFlags().noNaNs();
  7821. }
  7822. return I->isAssociative();
  7823. }
  7824. static Value *getRdxOperand(Instruction *I, unsigned Index) {
  7825. // Poison-safe 'or' takes the form: select X, true, Y
  7826. // To make that work with the normal operand processing, we skip the
  7827. // true value operand.
  7828. // TODO: Change the code and data structures to handle this without a hack.
  7829. if (getRdxKind(I) == RecurKind::Or && isa<SelectInst>(I) && Index == 1)
  7830. return I->getOperand(2);
  7831. return I->getOperand(Index);
  7832. }
  7833. /// Checks if the ParentStackElem.first should be marked as a reduction
  7834. /// operation with an extra argument or as extra argument itself.
  7835. void markExtraArg(std::pair<Instruction *, unsigned> &ParentStackElem,
  7836. Value *ExtraArg) {
  7837. if (ExtraArgs.count(ParentStackElem.first)) {
  7838. ExtraArgs[ParentStackElem.first] = nullptr;
  7839. // We ran into something like:
  7840. // ParentStackElem.first = ExtraArgs[ParentStackElem.first] + ExtraArg.
  7841. // The whole ParentStackElem.first should be considered as an extra value
  7842. // in this case.
  7843. // Do not perform analysis of remaining operands of ParentStackElem.first
  7844. // instruction, this whole instruction is an extra argument.
  7845. ParentStackElem.second = INVALID_OPERAND_INDEX;
  7846. } else {
  7847. // We ran into something like:
  7848. // ParentStackElem.first += ... + ExtraArg + ...
  7849. ExtraArgs[ParentStackElem.first] = ExtraArg;
  7850. }
  7851. }
  7852. /// Creates reduction operation with the current opcode.
  7853. static Value *createOp(IRBuilder<> &Builder, RecurKind Kind, Value *LHS,
  7854. Value *RHS, const Twine &Name, bool UseSelect) {
  7855. unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(Kind);
  7856. switch (Kind) {
  7857. case RecurKind::Or:
  7858. if (UseSelect &&
  7859. LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
  7860. return Builder.CreateSelect(LHS, Builder.getTrue(), RHS, Name);
  7861. return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
  7862. Name);
  7863. case RecurKind::And:
  7864. if (UseSelect &&
  7865. LHS->getType() == CmpInst::makeCmpResultType(LHS->getType()))
  7866. return Builder.CreateSelect(LHS, RHS, Builder.getFalse(), Name);
  7867. return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
  7868. Name);
  7869. case RecurKind::Add:
  7870. case RecurKind::Mul:
  7871. case RecurKind::Xor:
  7872. case RecurKind::FAdd:
  7873. case RecurKind::FMul:
  7874. return Builder.CreateBinOp((Instruction::BinaryOps)RdxOpcode, LHS, RHS,
  7875. Name);
  7876. case RecurKind::FMax:
  7877. return Builder.CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS);
  7878. case RecurKind::FMin:
  7879. return Builder.CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS);
  7880. case RecurKind::SMax:
  7881. if (UseSelect) {
  7882. Value *Cmp = Builder.CreateICmpSGT(LHS, RHS, Name);
  7883. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  7884. }
  7885. return Builder.CreateBinaryIntrinsic(Intrinsic::smax, LHS, RHS);
  7886. case RecurKind::SMin:
  7887. if (UseSelect) {
  7888. Value *Cmp = Builder.CreateICmpSLT(LHS, RHS, Name);
  7889. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  7890. }
  7891. return Builder.CreateBinaryIntrinsic(Intrinsic::smin, LHS, RHS);
  7892. case RecurKind::UMax:
  7893. if (UseSelect) {
  7894. Value *Cmp = Builder.CreateICmpUGT(LHS, RHS, Name);
  7895. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  7896. }
  7897. return Builder.CreateBinaryIntrinsic(Intrinsic::umax, LHS, RHS);
  7898. case RecurKind::UMin:
  7899. if (UseSelect) {
  7900. Value *Cmp = Builder.CreateICmpULT(LHS, RHS, Name);
  7901. return Builder.CreateSelect(Cmp, LHS, RHS, Name);
  7902. }
  7903. return Builder.CreateBinaryIntrinsic(Intrinsic::umin, LHS, RHS);
  7904. default:
  7905. llvm_unreachable("Unknown reduction operation.");
  7906. }
  7907. }
  7908. /// Creates reduction operation with the current opcode with the IR flags
  7909. /// from \p ReductionOps.
  7910. static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
  7911. Value *RHS, const Twine &Name,
  7912. const ReductionOpsListType &ReductionOps) {
  7913. bool UseSelect = ReductionOps.size() == 2 ||
  7914. // Logical or/and.
  7915. (ReductionOps.size() == 1 &&
  7916. isa<SelectInst>(ReductionOps.front().front()));
  7917. assert((!UseSelect || ReductionOps.size() != 2 ||
  7918. isa<SelectInst>(ReductionOps[1][0])) &&
  7919. "Expected cmp + select pairs for reduction");
  7920. Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, UseSelect);
  7921. if (RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
  7922. if (auto *Sel = dyn_cast<SelectInst>(Op)) {
  7923. propagateIRFlags(Sel->getCondition(), ReductionOps[0]);
  7924. propagateIRFlags(Op, ReductionOps[1]);
  7925. return Op;
  7926. }
  7927. }
  7928. propagateIRFlags(Op, ReductionOps[0]);
  7929. return Op;
  7930. }
  7931. /// Creates reduction operation with the current opcode with the IR flags
  7932. /// from \p I.
  7933. static Value *createOp(IRBuilder<> &Builder, RecurKind RdxKind, Value *LHS,
  7934. Value *RHS, const Twine &Name, Instruction *I) {
  7935. auto *SelI = dyn_cast<SelectInst>(I);
  7936. Value *Op = createOp(Builder, RdxKind, LHS, RHS, Name, SelI != nullptr);
  7937. if (SelI && RecurrenceDescriptor::isIntMinMaxRecurrenceKind(RdxKind)) {
  7938. if (auto *Sel = dyn_cast<SelectInst>(Op))
  7939. propagateIRFlags(Sel->getCondition(), SelI->getCondition());
  7940. }
  7941. propagateIRFlags(Op, I);
  7942. return Op;
  7943. }
  7944. static RecurKind getRdxKind(Instruction *I) {
  7945. assert(I && "Expected instruction for reduction matching");
  7946. if (match(I, m_Add(m_Value(), m_Value())))
  7947. return RecurKind::Add;
  7948. if (match(I, m_Mul(m_Value(), m_Value())))
  7949. return RecurKind::Mul;
  7950. if (match(I, m_And(m_Value(), m_Value())) ||
  7951. match(I, m_LogicalAnd(m_Value(), m_Value())))
  7952. return RecurKind::And;
  7953. if (match(I, m_Or(m_Value(), m_Value())) ||
  7954. match(I, m_LogicalOr(m_Value(), m_Value())))
  7955. return RecurKind::Or;
  7956. if (match(I, m_Xor(m_Value(), m_Value())))
  7957. return RecurKind::Xor;
  7958. if (match(I, m_FAdd(m_Value(), m_Value())))
  7959. return RecurKind::FAdd;
  7960. if (match(I, m_FMul(m_Value(), m_Value())))
  7961. return RecurKind::FMul;
  7962. if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_Value())))
  7963. return RecurKind::FMax;
  7964. if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_Value())))
  7965. return RecurKind::FMin;
  7966. // This matches either cmp+select or intrinsics. SLP is expected to handle
  7967. // either form.
  7968. // TODO: If we are canonicalizing to intrinsics, we can remove several
  7969. // special-case paths that deal with selects.
  7970. if (match(I, m_SMax(m_Value(), m_Value())))
  7971. return RecurKind::SMax;
  7972. if (match(I, m_SMin(m_Value(), m_Value())))
  7973. return RecurKind::SMin;
  7974. if (match(I, m_UMax(m_Value(), m_Value())))
  7975. return RecurKind::UMax;
  7976. if (match(I, m_UMin(m_Value(), m_Value())))
  7977. return RecurKind::UMin;
  7978. if (auto *Select = dyn_cast<SelectInst>(I)) {
  7979. // Try harder: look for min/max pattern based on instructions producing
  7980. // same values such as: select ((cmp Inst1, Inst2), Inst1, Inst2).
  7981. // During the intermediate stages of SLP, it's very common to have
  7982. // pattern like this (since optimizeGatherSequence is run only once
  7983. // at the end):
  7984. // %1 = extractelement <2 x i32> %a, i32 0
  7985. // %2 = extractelement <2 x i32> %a, i32 1
  7986. // %cond = icmp sgt i32 %1, %2
  7987. // %3 = extractelement <2 x i32> %a, i32 0
  7988. // %4 = extractelement <2 x i32> %a, i32 1
  7989. // %select = select i1 %cond, i32 %3, i32 %4
  7990. CmpInst::Predicate Pred;
  7991. Instruction *L1;
  7992. Instruction *L2;
  7993. Value *LHS = Select->getTrueValue();
  7994. Value *RHS = Select->getFalseValue();
  7995. Value *Cond = Select->getCondition();
  7996. // TODO: Support inverse predicates.
  7997. if (match(Cond, m_Cmp(Pred, m_Specific(LHS), m_Instruction(L2)))) {
  7998. if (!isa<ExtractElementInst>(RHS) ||
  7999. !L2->isIdenticalTo(cast<Instruction>(RHS)))
  8000. return RecurKind::None;
  8001. } else if (match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Specific(RHS)))) {
  8002. if (!isa<ExtractElementInst>(LHS) ||
  8003. !L1->isIdenticalTo(cast<Instruction>(LHS)))
  8004. return RecurKind::None;
  8005. } else {
  8006. if (!isa<ExtractElementInst>(LHS) || !isa<ExtractElementInst>(RHS))
  8007. return RecurKind::None;
  8008. if (!match(Cond, m_Cmp(Pred, m_Instruction(L1), m_Instruction(L2))) ||
  8009. !L1->isIdenticalTo(cast<Instruction>(LHS)) ||
  8010. !L2->isIdenticalTo(cast<Instruction>(RHS)))
  8011. return RecurKind::None;
  8012. }
  8013. switch (Pred) {
  8014. default:
  8015. return RecurKind::None;
  8016. case CmpInst::ICMP_SGT:
  8017. case CmpInst::ICMP_SGE:
  8018. return RecurKind::SMax;
  8019. case CmpInst::ICMP_SLT:
  8020. case CmpInst::ICMP_SLE:
  8021. return RecurKind::SMin;
  8022. case CmpInst::ICMP_UGT:
  8023. case CmpInst::ICMP_UGE:
  8024. return RecurKind::UMax;
  8025. case CmpInst::ICMP_ULT:
  8026. case CmpInst::ICMP_ULE:
  8027. return RecurKind::UMin;
  8028. }
  8029. }
  8030. return RecurKind::None;
  8031. }
  8032. /// Get the index of the first operand.
  8033. static unsigned getFirstOperandIndex(Instruction *I) {
  8034. return isCmpSelMinMax(I) ? 1 : 0;
  8035. }
  8036. /// Total number of operands in the reduction operation.
  8037. static unsigned getNumberOfOperands(Instruction *I) {
  8038. return isCmpSelMinMax(I) ? 3 : 2;
  8039. }
  8040. /// Checks if the instruction is in basic block \p BB.
  8041. /// For a cmp+sel min/max reduction check that both ops are in \p BB.
  8042. static bool hasSameParent(Instruction *I, BasicBlock *BB) {
  8043. if (isCmpSelMinMax(I) || (isBoolLogicOp(I) && isa<SelectInst>(I))) {
  8044. auto *Sel = cast<SelectInst>(I);
  8045. auto *Cmp = dyn_cast<Instruction>(Sel->getCondition());
  8046. return Sel->getParent() == BB && Cmp && Cmp->getParent() == BB;
  8047. }
  8048. return I->getParent() == BB;
  8049. }
  8050. /// Expected number of uses for reduction operations/reduced values.
  8051. static bool hasRequiredNumberOfUses(bool IsCmpSelMinMax, Instruction *I) {
  8052. if (IsCmpSelMinMax) {
  8053. // SelectInst must be used twice while the condition op must have single
  8054. // use only.
  8055. if (auto *Sel = dyn_cast<SelectInst>(I))
  8056. return Sel->hasNUses(2) && Sel->getCondition()->hasOneUse();
  8057. return I->hasNUses(2);
  8058. }
  8059. // Arithmetic reduction operation must be used once only.
  8060. return I->hasOneUse();
  8061. }
  8062. /// Initializes the list of reduction operations.
  8063. void initReductionOps(Instruction *I) {
  8064. if (isCmpSelMinMax(I))
  8065. ReductionOps.assign(2, ReductionOpsType());
  8066. else
  8067. ReductionOps.assign(1, ReductionOpsType());
  8068. }
  8069. /// Add all reduction operations for the reduction instruction \p I.
  8070. void addReductionOps(Instruction *I) {
  8071. if (isCmpSelMinMax(I)) {
  8072. ReductionOps[0].emplace_back(cast<SelectInst>(I)->getCondition());
  8073. ReductionOps[1].emplace_back(I);
  8074. } else {
  8075. ReductionOps[0].emplace_back(I);
  8076. }
  8077. }
  8078. static Value *getLHS(RecurKind Kind, Instruction *I) {
  8079. if (Kind == RecurKind::None)
  8080. return nullptr;
  8081. return I->getOperand(getFirstOperandIndex(I));
  8082. }
  8083. static Value *getRHS(RecurKind Kind, Instruction *I) {
  8084. if (Kind == RecurKind::None)
  8085. return nullptr;
  8086. return I->getOperand(getFirstOperandIndex(I) + 1);
  8087. }
  8088. public:
  8089. HorizontalReduction() = default;
  8090. /// Try to find a reduction tree.
  8091. bool matchAssociativeReduction(PHINode *Phi, Instruction *Inst) {
  8092. assert((!Phi || is_contained(Phi->operands(), Inst)) &&
  8093. "Phi needs to use the binary operator");
  8094. assert((isa<BinaryOperator>(Inst) || isa<SelectInst>(Inst) ||
  8095. isa<IntrinsicInst>(Inst)) &&
  8096. "Expected binop, select, or intrinsic for reduction matching");
  8097. RdxKind = getRdxKind(Inst);
  8098. // We could have a initial reductions that is not an add.
  8099. // r *= v1 + v2 + v3 + v4
  8100. // In such a case start looking for a tree rooted in the first '+'.
  8101. if (Phi) {
  8102. if (getLHS(RdxKind, Inst) == Phi) {
  8103. Phi = nullptr;
  8104. Inst = dyn_cast<Instruction>(getRHS(RdxKind, Inst));
  8105. if (!Inst)
  8106. return false;
  8107. RdxKind = getRdxKind(Inst);
  8108. } else if (getRHS(RdxKind, Inst) == Phi) {
  8109. Phi = nullptr;
  8110. Inst = dyn_cast<Instruction>(getLHS(RdxKind, Inst));
  8111. if (!Inst)
  8112. return false;
  8113. RdxKind = getRdxKind(Inst);
  8114. }
  8115. }
  8116. if (!isVectorizable(RdxKind, Inst))
  8117. return false;
  8118. // Analyze "regular" integer/FP types for reductions - no target-specific
  8119. // types or pointers.
  8120. Type *Ty = Inst->getType();
  8121. if (!isValidElementType(Ty) || Ty->isPointerTy())
  8122. return false;
  8123. // Though the ultimate reduction may have multiple uses, its condition must
  8124. // have only single use.
  8125. if (auto *Sel = dyn_cast<SelectInst>(Inst))
  8126. if (!Sel->getCondition()->hasOneUse())
  8127. return false;
  8128. ReductionRoot = Inst;
  8129. // The opcode for leaf values that we perform a reduction on.
  8130. // For example: load(x) + load(y) + load(z) + fptoui(w)
  8131. // The leaf opcode for 'w' does not match, so we don't include it as a
  8132. // potential candidate for the reduction.
  8133. unsigned LeafOpcode = 0;
  8134. // Post-order traverse the reduction tree starting at Inst. We only handle
  8135. // true trees containing binary operators or selects.
  8136. SmallVector<std::pair<Instruction *, unsigned>, 32> Stack;
  8137. Stack.push_back(std::make_pair(Inst, getFirstOperandIndex(Inst)));
  8138. initReductionOps(Inst);
  8139. while (!Stack.empty()) {
  8140. Instruction *TreeN = Stack.back().first;
  8141. unsigned EdgeToVisit = Stack.back().second++;
  8142. const RecurKind TreeRdxKind = getRdxKind(TreeN);
  8143. bool IsReducedValue = TreeRdxKind != RdxKind;
  8144. // Postorder visit.
  8145. if (IsReducedValue || EdgeToVisit >= getNumberOfOperands(TreeN)) {
  8146. if (IsReducedValue)
  8147. ReducedVals.push_back(TreeN);
  8148. else {
  8149. auto ExtraArgsIter = ExtraArgs.find(TreeN);
  8150. if (ExtraArgsIter != ExtraArgs.end() && !ExtraArgsIter->second) {
  8151. // Check if TreeN is an extra argument of its parent operation.
  8152. if (Stack.size() <= 1) {
  8153. // TreeN can't be an extra argument as it is a root reduction
  8154. // operation.
  8155. return false;
  8156. }
  8157. // Yes, TreeN is an extra argument, do not add it to a list of
  8158. // reduction operations.
  8159. // Stack[Stack.size() - 2] always points to the parent operation.
  8160. markExtraArg(Stack[Stack.size() - 2], TreeN);
  8161. ExtraArgs.erase(TreeN);
  8162. } else
  8163. addReductionOps(TreeN);
  8164. }
  8165. // Retract.
  8166. Stack.pop_back();
  8167. continue;
  8168. }
  8169. // Visit operands.
  8170. Value *EdgeVal = getRdxOperand(TreeN, EdgeToVisit);
  8171. auto *EdgeInst = dyn_cast<Instruction>(EdgeVal);
  8172. if (!EdgeInst) {
  8173. // Edge value is not a reduction instruction or a leaf instruction.
  8174. // (It may be a constant, function argument, or something else.)
  8175. markExtraArg(Stack.back(), EdgeVal);
  8176. continue;
  8177. }
  8178. RecurKind EdgeRdxKind = getRdxKind(EdgeInst);
  8179. // Continue analysis if the next operand is a reduction operation or
  8180. // (possibly) a leaf value. If the leaf value opcode is not set,
  8181. // the first met operation != reduction operation is considered as the
  8182. // leaf opcode.
  8183. // Only handle trees in the current basic block.
  8184. // Each tree node needs to have minimal number of users except for the
  8185. // ultimate reduction.
  8186. const bool IsRdxInst = EdgeRdxKind == RdxKind;
  8187. if (EdgeInst != Phi && EdgeInst != Inst &&
  8188. hasSameParent(EdgeInst, Inst->getParent()) &&
  8189. hasRequiredNumberOfUses(isCmpSelMinMax(Inst), EdgeInst) &&
  8190. (!LeafOpcode || LeafOpcode == EdgeInst->getOpcode() || IsRdxInst)) {
  8191. if (IsRdxInst) {
  8192. // We need to be able to reassociate the reduction operations.
  8193. if (!isVectorizable(EdgeRdxKind, EdgeInst)) {
  8194. // I is an extra argument for TreeN (its parent operation).
  8195. markExtraArg(Stack.back(), EdgeInst);
  8196. continue;
  8197. }
  8198. } else if (!LeafOpcode) {
  8199. LeafOpcode = EdgeInst->getOpcode();
  8200. }
  8201. Stack.push_back(
  8202. std::make_pair(EdgeInst, getFirstOperandIndex(EdgeInst)));
  8203. continue;
  8204. }
  8205. // I is an extra argument for TreeN (its parent operation).
  8206. markExtraArg(Stack.back(), EdgeInst);
  8207. }
  8208. return true;
  8209. }
  8210. /// Attempt to vectorize the tree found by matchAssociativeReduction.
  8211. Value *tryToReduce(BoUpSLP &V, TargetTransformInfo *TTI) {
  8212. // If there are a sufficient number of reduction values, reduce
  8213. // to a nearby power-of-2. We can safely generate oversized
  8214. // vectors and rely on the backend to split them to legal sizes.
  8215. unsigned NumReducedVals = ReducedVals.size();
  8216. if (NumReducedVals < 4)
  8217. return nullptr;
  8218. // Intersect the fast-math-flags from all reduction operations.
  8219. FastMathFlags RdxFMF;
  8220. RdxFMF.set();
  8221. for (ReductionOpsType &RdxOp : ReductionOps) {
  8222. for (Value *RdxVal : RdxOp) {
  8223. if (auto *FPMO = dyn_cast<FPMathOperator>(RdxVal))
  8224. RdxFMF &= FPMO->getFastMathFlags();
  8225. }
  8226. }
  8227. IRBuilder<> Builder(cast<Instruction>(ReductionRoot));
  8228. Builder.setFastMathFlags(RdxFMF);
  8229. BoUpSLP::ExtraValueToDebugLocsMap ExternallyUsedValues;
  8230. // The same extra argument may be used several times, so log each attempt
  8231. // to use it.
  8232. for (const std::pair<Instruction *, Value *> &Pair : ExtraArgs) {
  8233. assert(Pair.first && "DebugLoc must be set.");
  8234. ExternallyUsedValues[Pair.second].push_back(Pair.first);
  8235. }
  8236. // The compare instruction of a min/max is the insertion point for new
  8237. // instructions and may be replaced with a new compare instruction.
  8238. auto getCmpForMinMaxReduction = [](Instruction *RdxRootInst) {
  8239. assert(isa<SelectInst>(RdxRootInst) &&
  8240. "Expected min/max reduction to have select root instruction");
  8241. Value *ScalarCond = cast<SelectInst>(RdxRootInst)->getCondition();
  8242. assert(isa<Instruction>(ScalarCond) &&
  8243. "Expected min/max reduction to have compare condition");
  8244. return cast<Instruction>(ScalarCond);
  8245. };
  8246. // The reduction root is used as the insertion point for new instructions,
  8247. // so set it as externally used to prevent it from being deleted.
  8248. ExternallyUsedValues[ReductionRoot];
  8249. SmallVector<Value *, 16> IgnoreList;
  8250. for (ReductionOpsType &RdxOp : ReductionOps)
  8251. IgnoreList.append(RdxOp.begin(), RdxOp.end());
  8252. unsigned ReduxWidth = PowerOf2Floor(NumReducedVals);
  8253. if (NumReducedVals > ReduxWidth) {
  8254. // In the loop below, we are building a tree based on a window of
  8255. // 'ReduxWidth' values.
  8256. // If the operands of those values have common traits (compare predicate,
  8257. // constant operand, etc), then we want to group those together to
  8258. // minimize the cost of the reduction.
  8259. // TODO: This should be extended to count common operands for
  8260. // compares and binops.
  8261. // Step 1: Count the number of times each compare predicate occurs.
  8262. SmallDenseMap<unsigned, unsigned> PredCountMap;
  8263. for (Value *RdxVal : ReducedVals) {
  8264. CmpInst::Predicate Pred;
  8265. if (match(RdxVal, m_Cmp(Pred, m_Value(), m_Value())))
  8266. ++PredCountMap[Pred];
  8267. }
  8268. // Step 2: Sort the values so the most common predicates come first.
  8269. stable_sort(ReducedVals, [&PredCountMap](Value *A, Value *B) {
  8270. CmpInst::Predicate PredA, PredB;
  8271. if (match(A, m_Cmp(PredA, m_Value(), m_Value())) &&
  8272. match(B, m_Cmp(PredB, m_Value(), m_Value()))) {
  8273. return PredCountMap[PredA] > PredCountMap[PredB];
  8274. }
  8275. return false;
  8276. });
  8277. }
  8278. Value *VectorizedTree = nullptr;
  8279. unsigned i = 0;
  8280. while (i < NumReducedVals - ReduxWidth + 1 && ReduxWidth > 2) {
  8281. ArrayRef<Value *> VL(&ReducedVals[i], ReduxWidth);
  8282. V.buildTree(VL, IgnoreList);
  8283. if (V.isTreeTinyAndNotFullyVectorizable(/*ForReduction=*/true))
  8284. break;
  8285. if (V.isLoadCombineReductionCandidate(RdxKind))
  8286. break;
  8287. V.reorderTopToBottom();
  8288. V.reorderBottomToTop(/*IgnoreReorder=*/true);
  8289. V.buildExternalUses(ExternallyUsedValues);
  8290. // For a poison-safe boolean logic reduction, do not replace select
  8291. // instructions with logic ops. All reduced values will be frozen (see
  8292. // below) to prevent leaking poison.
  8293. if (isa<SelectInst>(ReductionRoot) &&
  8294. isBoolLogicOp(cast<Instruction>(ReductionRoot)) &&
  8295. NumReducedVals != ReduxWidth)
  8296. break;
  8297. V.computeMinimumValueSizes();
  8298. // Estimate cost.
  8299. InstructionCost TreeCost =
  8300. V.getTreeCost(makeArrayRef(&ReducedVals[i], ReduxWidth));
  8301. InstructionCost ReductionCost =
  8302. getReductionCost(TTI, ReducedVals[i], ReduxWidth, RdxFMF);
  8303. InstructionCost Cost = TreeCost + ReductionCost;
  8304. if (!Cost.isValid()) {
  8305. LLVM_DEBUG(dbgs() << "Encountered invalid baseline cost.\n");
  8306. return nullptr;
  8307. }
  8308. if (Cost >= -SLPCostThreshold) {
  8309. V.getORE()->emit([&]() {
  8310. return OptimizationRemarkMissed(SV_NAME, "HorSLPNotBeneficial",
  8311. cast<Instruction>(VL[0]))
  8312. << "Vectorizing horizontal reduction is possible"
  8313. << "but not beneficial with cost " << ore::NV("Cost", Cost)
  8314. << " and threshold "
  8315. << ore::NV("Threshold", -SLPCostThreshold);
  8316. });
  8317. break;
  8318. }
  8319. LLVM_DEBUG(dbgs() << "SLP: Vectorizing horizontal reduction at cost:"
  8320. << Cost << ". (HorRdx)\n");
  8321. V.getORE()->emit([&]() {
  8322. return OptimizationRemark(SV_NAME, "VectorizedHorizontalReduction",
  8323. cast<Instruction>(VL[0]))
  8324. << "Vectorized horizontal reduction with cost "
  8325. << ore::NV("Cost", Cost) << " and with tree size "
  8326. << ore::NV("TreeSize", V.getTreeSize());
  8327. });
  8328. // Vectorize a tree.
  8329. DebugLoc Loc = cast<Instruction>(ReducedVals[i])->getDebugLoc();
  8330. Value *VectorizedRoot = V.vectorizeTree(ExternallyUsedValues);
  8331. // Emit a reduction. If the root is a select (min/max idiom), the insert
  8332. // point is the compare condition of that select.
  8333. Instruction *RdxRootInst = cast<Instruction>(ReductionRoot);
  8334. if (isCmpSelMinMax(RdxRootInst))
  8335. Builder.SetInsertPoint(getCmpForMinMaxReduction(RdxRootInst));
  8336. else
  8337. Builder.SetInsertPoint(RdxRootInst);
  8338. // To prevent poison from leaking across what used to be sequential, safe,
  8339. // scalar boolean logic operations, the reduction operand must be frozen.
  8340. if (isa<SelectInst>(RdxRootInst) && isBoolLogicOp(RdxRootInst))
  8341. VectorizedRoot = Builder.CreateFreeze(VectorizedRoot);
  8342. Value *ReducedSubTree =
  8343. emitReduction(VectorizedRoot, Builder, ReduxWidth, TTI);
  8344. if (!VectorizedTree) {
  8345. // Initialize the final value in the reduction.
  8346. VectorizedTree = ReducedSubTree;
  8347. } else {
  8348. // Update the final value in the reduction.
  8349. Builder.SetCurrentDebugLocation(Loc);
  8350. VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
  8351. ReducedSubTree, "op.rdx", ReductionOps);
  8352. }
  8353. i += ReduxWidth;
  8354. ReduxWidth = PowerOf2Floor(NumReducedVals - i);
  8355. }
  8356. if (VectorizedTree) {
  8357. // Finish the reduction.
  8358. for (; i < NumReducedVals; ++i) {
  8359. auto *I = cast<Instruction>(ReducedVals[i]);
  8360. Builder.SetCurrentDebugLocation(I->getDebugLoc());
  8361. VectorizedTree =
  8362. createOp(Builder, RdxKind, VectorizedTree, I, "", ReductionOps);
  8363. }
  8364. for (auto &Pair : ExternallyUsedValues) {
  8365. // Add each externally used value to the final reduction.
  8366. for (auto *I : Pair.second) {
  8367. Builder.SetCurrentDebugLocation(I->getDebugLoc());
  8368. VectorizedTree = createOp(Builder, RdxKind, VectorizedTree,
  8369. Pair.first, "op.extra", I);
  8370. }
  8371. }
  8372. ReductionRoot->replaceAllUsesWith(VectorizedTree);
  8373. // Mark all scalar reduction ops for deletion, they are replaced by the
  8374. // vector reductions.
  8375. V.eraseInstructions(IgnoreList);
  8376. }
  8377. return VectorizedTree;
  8378. }
  8379. unsigned numReductionValues() const { return ReducedVals.size(); }
  8380. private:
  8381. /// Calculate the cost of a reduction.
  8382. InstructionCost getReductionCost(TargetTransformInfo *TTI,
  8383. Value *FirstReducedVal, unsigned ReduxWidth,
  8384. FastMathFlags FMF) {
  8385. TTI::TargetCostKind CostKind = TTI::TCK_RecipThroughput;
  8386. Type *ScalarTy = FirstReducedVal->getType();
  8387. FixedVectorType *VectorTy = FixedVectorType::get(ScalarTy, ReduxWidth);
  8388. InstructionCost VectorCost, ScalarCost;
  8389. switch (RdxKind) {
  8390. case RecurKind::Add:
  8391. case RecurKind::Mul:
  8392. case RecurKind::Or:
  8393. case RecurKind::And:
  8394. case RecurKind::Xor:
  8395. case RecurKind::FAdd:
  8396. case RecurKind::FMul: {
  8397. unsigned RdxOpcode = RecurrenceDescriptor::getOpcode(RdxKind);
  8398. VectorCost =
  8399. TTI->getArithmeticReductionCost(RdxOpcode, VectorTy, FMF, CostKind);
  8400. ScalarCost = TTI->getArithmeticInstrCost(RdxOpcode, ScalarTy, CostKind);
  8401. break;
  8402. }
  8403. case RecurKind::FMax:
  8404. case RecurKind::FMin: {
  8405. auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
  8406. auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
  8407. VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy,
  8408. /*IsUnsigned=*/false, CostKind);
  8409. CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
  8410. ScalarCost = TTI->getCmpSelInstrCost(Instruction::FCmp, ScalarTy,
  8411. SclCondTy, RdxPred, CostKind) +
  8412. TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
  8413. SclCondTy, RdxPred, CostKind);
  8414. break;
  8415. }
  8416. case RecurKind::SMax:
  8417. case RecurKind::SMin:
  8418. case RecurKind::UMax:
  8419. case RecurKind::UMin: {
  8420. auto *SclCondTy = CmpInst::makeCmpResultType(ScalarTy);
  8421. auto *VecCondTy = cast<VectorType>(CmpInst::makeCmpResultType(VectorTy));
  8422. bool IsUnsigned =
  8423. RdxKind == RecurKind::UMax || RdxKind == RecurKind::UMin;
  8424. VectorCost = TTI->getMinMaxReductionCost(VectorTy, VecCondTy, IsUnsigned,
  8425. CostKind);
  8426. CmpInst::Predicate RdxPred = getMinMaxReductionPredicate(RdxKind);
  8427. ScalarCost = TTI->getCmpSelInstrCost(Instruction::ICmp, ScalarTy,
  8428. SclCondTy, RdxPred, CostKind) +
  8429. TTI->getCmpSelInstrCost(Instruction::Select, ScalarTy,
  8430. SclCondTy, RdxPred, CostKind);
  8431. break;
  8432. }
  8433. default:
  8434. llvm_unreachable("Expected arithmetic or min/max reduction operation");
  8435. }
  8436. // Scalar cost is repeated for N-1 elements.
  8437. ScalarCost *= (ReduxWidth - 1);
  8438. LLVM_DEBUG(dbgs() << "SLP: Adding cost " << VectorCost - ScalarCost
  8439. << " for reduction that starts with " << *FirstReducedVal
  8440. << " (It is a splitting reduction)\n");
  8441. return VectorCost - ScalarCost;
  8442. }
  8443. /// Emit a horizontal reduction of the vectorized value.
  8444. Value *emitReduction(Value *VectorizedValue, IRBuilder<> &Builder,
  8445. unsigned ReduxWidth, const TargetTransformInfo *TTI) {
  8446. assert(VectorizedValue && "Need to have a vectorized tree node");
  8447. assert(isPowerOf2_32(ReduxWidth) &&
  8448. "We only handle power-of-two reductions for now");
  8449. assert(RdxKind != RecurKind::FMulAdd &&
  8450. "A call to the llvm.fmuladd intrinsic is not handled yet");
  8451. ++NumVectorInstructions;
  8452. return createSimpleTargetReduction(Builder, TTI, VectorizedValue, RdxKind);
  8453. }
  8454. };
  8455. } // end anonymous namespace
  8456. static Optional<unsigned> getAggregateSize(Instruction *InsertInst) {
  8457. if (auto *IE = dyn_cast<InsertElementInst>(InsertInst))
  8458. return cast<FixedVectorType>(IE->getType())->getNumElements();
  8459. unsigned AggregateSize = 1;
  8460. auto *IV = cast<InsertValueInst>(InsertInst);
  8461. Type *CurrentType = IV->getType();
  8462. do {
  8463. if (auto *ST = dyn_cast<StructType>(CurrentType)) {
  8464. for (auto *Elt : ST->elements())
  8465. if (Elt != ST->getElementType(0)) // check homogeneity
  8466. return None;
  8467. AggregateSize *= ST->getNumElements();
  8468. CurrentType = ST->getElementType(0);
  8469. } else if (auto *AT = dyn_cast<ArrayType>(CurrentType)) {
  8470. AggregateSize *= AT->getNumElements();
  8471. CurrentType = AT->getElementType();
  8472. } else if (auto *VT = dyn_cast<FixedVectorType>(CurrentType)) {
  8473. AggregateSize *= VT->getNumElements();
  8474. return AggregateSize;
  8475. } else if (CurrentType->isSingleValueType()) {
  8476. return AggregateSize;
  8477. } else {
  8478. return None;
  8479. }
  8480. } while (true);
  8481. }
  8482. static void findBuildAggregate_rec(Instruction *LastInsertInst,
  8483. TargetTransformInfo *TTI,
  8484. SmallVectorImpl<Value *> &BuildVectorOpds,
  8485. SmallVectorImpl<Value *> &InsertElts,
  8486. unsigned OperandOffset) {
  8487. do {
  8488. Value *InsertedOperand = LastInsertInst->getOperand(1);
  8489. Optional<unsigned> OperandIndex =
  8490. getInsertIndex(LastInsertInst, OperandOffset);
  8491. if (!OperandIndex)
  8492. return;
  8493. if (isa<InsertElementInst>(InsertedOperand) ||
  8494. isa<InsertValueInst>(InsertedOperand)) {
  8495. findBuildAggregate_rec(cast<Instruction>(InsertedOperand), TTI,
  8496. BuildVectorOpds, InsertElts, *OperandIndex);
  8497. } else {
  8498. BuildVectorOpds[*OperandIndex] = InsertedOperand;
  8499. InsertElts[*OperandIndex] = LastInsertInst;
  8500. }
  8501. LastInsertInst = dyn_cast<Instruction>(LastInsertInst->getOperand(0));
  8502. } while (LastInsertInst != nullptr &&
  8503. (isa<InsertValueInst>(LastInsertInst) ||
  8504. isa<InsertElementInst>(LastInsertInst)) &&
  8505. LastInsertInst->hasOneUse());
  8506. }
  8507. /// Recognize construction of vectors like
  8508. /// %ra = insertelement <4 x float> poison, float %s0, i32 0
  8509. /// %rb = insertelement <4 x float> %ra, float %s1, i32 1
  8510. /// %rc = insertelement <4 x float> %rb, float %s2, i32 2
  8511. /// %rd = insertelement <4 x float> %rc, float %s3, i32 3
  8512. /// starting from the last insertelement or insertvalue instruction.
  8513. ///
  8514. /// Also recognize homogeneous aggregates like {<2 x float>, <2 x float>},
  8515. /// {{float, float}, {float, float}}, [2 x {float, float}] and so on.
  8516. /// See llvm/test/Transforms/SLPVectorizer/X86/pr42022.ll for examples.
  8517. ///
  8518. /// Assume LastInsertInst is of InsertElementInst or InsertValueInst type.
  8519. ///
  8520. /// \return true if it matches.
  8521. static bool findBuildAggregate(Instruction *LastInsertInst,
  8522. TargetTransformInfo *TTI,
  8523. SmallVectorImpl<Value *> &BuildVectorOpds,
  8524. SmallVectorImpl<Value *> &InsertElts) {
  8525. assert((isa<InsertElementInst>(LastInsertInst) ||
  8526. isa<InsertValueInst>(LastInsertInst)) &&
  8527. "Expected insertelement or insertvalue instruction!");
  8528. assert((BuildVectorOpds.empty() && InsertElts.empty()) &&
  8529. "Expected empty result vectors!");
  8530. Optional<unsigned> AggregateSize = getAggregateSize(LastInsertInst);
  8531. if (!AggregateSize)
  8532. return false;
  8533. BuildVectorOpds.resize(*AggregateSize);
  8534. InsertElts.resize(*AggregateSize);
  8535. findBuildAggregate_rec(LastInsertInst, TTI, BuildVectorOpds, InsertElts, 0);
  8536. llvm::erase_value(BuildVectorOpds, nullptr);
  8537. llvm::erase_value(InsertElts, nullptr);
  8538. if (BuildVectorOpds.size() >= 2)
  8539. return true;
  8540. return false;
  8541. }
  8542. /// Try and get a reduction value from a phi node.
  8543. ///
  8544. /// Given a phi node \p P in a block \p ParentBB, consider possible reductions
  8545. /// if they come from either \p ParentBB or a containing loop latch.
  8546. ///
  8547. /// \returns A candidate reduction value if possible, or \code nullptr \endcode
  8548. /// if not possible.
  8549. static Value *getReductionValue(const DominatorTree *DT, PHINode *P,
  8550. BasicBlock *ParentBB, LoopInfo *LI) {
  8551. // There are situations where the reduction value is not dominated by the
  8552. // reduction phi. Vectorizing such cases has been reported to cause
  8553. // miscompiles. See PR25787.
  8554. auto DominatedReduxValue = [&](Value *R) {
  8555. return isa<Instruction>(R) &&
  8556. DT->dominates(P->getParent(), cast<Instruction>(R)->getParent());
  8557. };
  8558. Value *Rdx = nullptr;
  8559. // Return the incoming value if it comes from the same BB as the phi node.
  8560. if (P->getIncomingBlock(0) == ParentBB) {
  8561. Rdx = P->getIncomingValue(0);
  8562. } else if (P->getIncomingBlock(1) == ParentBB) {
  8563. Rdx = P->getIncomingValue(1);
  8564. }
  8565. if (Rdx && DominatedReduxValue(Rdx))
  8566. return Rdx;
  8567. // Otherwise, check whether we have a loop latch to look at.
  8568. Loop *BBL = LI->getLoopFor(ParentBB);
  8569. if (!BBL)
  8570. return nullptr;
  8571. BasicBlock *BBLatch = BBL->getLoopLatch();
  8572. if (!BBLatch)
  8573. return nullptr;
  8574. // There is a loop latch, return the incoming value if it comes from
  8575. // that. This reduction pattern occasionally turns up.
  8576. if (P->getIncomingBlock(0) == BBLatch) {
  8577. Rdx = P->getIncomingValue(0);
  8578. } else if (P->getIncomingBlock(1) == BBLatch) {
  8579. Rdx = P->getIncomingValue(1);
  8580. }
  8581. if (Rdx && DominatedReduxValue(Rdx))
  8582. return Rdx;
  8583. return nullptr;
  8584. }
  8585. static bool matchRdxBop(Instruction *I, Value *&V0, Value *&V1) {
  8586. if (match(I, m_BinOp(m_Value(V0), m_Value(V1))))
  8587. return true;
  8588. if (match(I, m_Intrinsic<Intrinsic::maxnum>(m_Value(V0), m_Value(V1))))
  8589. return true;
  8590. if (match(I, m_Intrinsic<Intrinsic::minnum>(m_Value(V0), m_Value(V1))))
  8591. return true;
  8592. if (match(I, m_Intrinsic<Intrinsic::smax>(m_Value(V0), m_Value(V1))))
  8593. return true;
  8594. if (match(I, m_Intrinsic<Intrinsic::smin>(m_Value(V0), m_Value(V1))))
  8595. return true;
  8596. if (match(I, m_Intrinsic<Intrinsic::umax>(m_Value(V0), m_Value(V1))))
  8597. return true;
  8598. if (match(I, m_Intrinsic<Intrinsic::umin>(m_Value(V0), m_Value(V1))))
  8599. return true;
  8600. return false;
  8601. }
  8602. /// Attempt to reduce a horizontal reduction.
  8603. /// If it is legal to match a horizontal reduction feeding the phi node \a P
  8604. /// with reduction operators \a Root (or one of its operands) in a basic block
  8605. /// \a BB, then check if it can be done. If horizontal reduction is not found
  8606. /// and root instruction is a binary operation, vectorization of the operands is
  8607. /// attempted.
  8608. /// \returns true if a horizontal reduction was matched and reduced or operands
  8609. /// of one of the binary instruction were vectorized.
  8610. /// \returns false if a horizontal reduction was not matched (or not possible)
  8611. /// or no vectorization of any binary operation feeding \a Root instruction was
  8612. /// performed.
  8613. static bool tryToVectorizeHorReductionOrInstOperands(
  8614. PHINode *P, Instruction *Root, BasicBlock *BB, BoUpSLP &R,
  8615. TargetTransformInfo *TTI,
  8616. const function_ref<bool(Instruction *, BoUpSLP &)> Vectorize) {
  8617. if (!ShouldVectorizeHor)
  8618. return false;
  8619. if (!Root)
  8620. return false;
  8621. if (Root->getParent() != BB || isa<PHINode>(Root))
  8622. return false;
  8623. // Start analysis starting from Root instruction. If horizontal reduction is
  8624. // found, try to vectorize it. If it is not a horizontal reduction or
  8625. // vectorization is not possible or not effective, and currently analyzed
  8626. // instruction is a binary operation, try to vectorize the operands, using
  8627. // pre-order DFS traversal order. If the operands were not vectorized, repeat
  8628. // the same procedure considering each operand as a possible root of the
  8629. // horizontal reduction.
  8630. // Interrupt the process if the Root instruction itself was vectorized or all
  8631. // sub-trees not higher that RecursionMaxDepth were analyzed/vectorized.
  8632. // Skip the analysis of CmpInsts.Compiler implements postanalysis of the
  8633. // CmpInsts so we can skip extra attempts in
  8634. // tryToVectorizeHorReductionOrInstOperands and save compile time.
  8635. std::queue<std::pair<Instruction *, unsigned>> Stack;
  8636. Stack.emplace(Root, 0);
  8637. SmallPtrSet<Value *, 8> VisitedInstrs;
  8638. SmallVector<WeakTrackingVH> PostponedInsts;
  8639. bool Res = false;
  8640. auto &&TryToReduce = [TTI, &P, &R](Instruction *Inst, Value *&B0,
  8641. Value *&B1) -> Value * {
  8642. bool IsBinop = matchRdxBop(Inst, B0, B1);
  8643. bool IsSelect = match(Inst, m_Select(m_Value(), m_Value(), m_Value()));
  8644. if (IsBinop || IsSelect) {
  8645. HorizontalReduction HorRdx;
  8646. if (HorRdx.matchAssociativeReduction(P, Inst))
  8647. return HorRdx.tryToReduce(R, TTI);
  8648. }
  8649. return nullptr;
  8650. };
  8651. while (!Stack.empty()) {
  8652. Instruction *Inst;
  8653. unsigned Level;
  8654. std::tie(Inst, Level) = Stack.front();
  8655. Stack.pop();
  8656. // Do not try to analyze instruction that has already been vectorized.
  8657. // This may happen when we vectorize instruction operands on a previous
  8658. // iteration while stack was populated before that happened.
  8659. if (R.isDeleted(Inst))
  8660. continue;
  8661. Value *B0 = nullptr, *B1 = nullptr;
  8662. if (Value *V = TryToReduce(Inst, B0, B1)) {
  8663. Res = true;
  8664. // Set P to nullptr to avoid re-analysis of phi node in
  8665. // matchAssociativeReduction function unless this is the root node.
  8666. P = nullptr;
  8667. if (auto *I = dyn_cast<Instruction>(V)) {
  8668. // Try to find another reduction.
  8669. Stack.emplace(I, Level);
  8670. continue;
  8671. }
  8672. } else {
  8673. bool IsBinop = B0 && B1;
  8674. if (P && IsBinop) {
  8675. Inst = dyn_cast<Instruction>(B0);
  8676. if (Inst == P)
  8677. Inst = dyn_cast<Instruction>(B1);
  8678. if (!Inst) {
  8679. // Set P to nullptr to avoid re-analysis of phi node in
  8680. // matchAssociativeReduction function unless this is the root node.
  8681. P = nullptr;
  8682. continue;
  8683. }
  8684. }
  8685. // Set P to nullptr to avoid re-analysis of phi node in
  8686. // matchAssociativeReduction function unless this is the root node.
  8687. P = nullptr;
  8688. // Do not try to vectorize CmpInst operands, this is done separately.
  8689. // Final attempt for binop args vectorization should happen after the loop
  8690. // to try to find reductions.
  8691. if (!isa<CmpInst>(Inst))
  8692. PostponedInsts.push_back(Inst);
  8693. }
  8694. // Try to vectorize operands.
  8695. // Continue analysis for the instruction from the same basic block only to
  8696. // save compile time.
  8697. if (++Level < RecursionMaxDepth)
  8698. for (auto *Op : Inst->operand_values())
  8699. if (VisitedInstrs.insert(Op).second)
  8700. if (auto *I = dyn_cast<Instruction>(Op))
  8701. // Do not try to vectorize CmpInst operands, this is done
  8702. // separately.
  8703. if (!isa<PHINode>(I) && !isa<CmpInst>(I) && !R.isDeleted(I) &&
  8704. I->getParent() == BB)
  8705. Stack.emplace(I, Level);
  8706. }
  8707. // Try to vectorized binops where reductions were not found.
  8708. for (Value *V : PostponedInsts)
  8709. if (auto *Inst = dyn_cast<Instruction>(V))
  8710. if (!R.isDeleted(Inst))
  8711. Res |= Vectorize(Inst, R);
  8712. return Res;
  8713. }
  8714. bool SLPVectorizerPass::vectorizeRootInstruction(PHINode *P, Value *V,
  8715. BasicBlock *BB, BoUpSLP &R,
  8716. TargetTransformInfo *TTI) {
  8717. auto *I = dyn_cast_or_null<Instruction>(V);
  8718. if (!I)
  8719. return false;
  8720. if (!isa<BinaryOperator>(I))
  8721. P = nullptr;
  8722. // Try to match and vectorize a horizontal reduction.
  8723. auto &&ExtraVectorization = [this](Instruction *I, BoUpSLP &R) -> bool {
  8724. return tryToVectorize(I, R);
  8725. };
  8726. return tryToVectorizeHorReductionOrInstOperands(P, I, BB, R, TTI,
  8727. ExtraVectorization);
  8728. }
  8729. bool SLPVectorizerPass::vectorizeInsertValueInst(InsertValueInst *IVI,
  8730. BasicBlock *BB, BoUpSLP &R) {
  8731. const DataLayout &DL = BB->getModule()->getDataLayout();
  8732. if (!R.canMapToVector(IVI->getType(), DL))
  8733. return false;
  8734. SmallVector<Value *, 16> BuildVectorOpds;
  8735. SmallVector<Value *, 16> BuildVectorInsts;
  8736. if (!findBuildAggregate(IVI, TTI, BuildVectorOpds, BuildVectorInsts))
  8737. return false;
  8738. LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IVI << "\n");
  8739. // Aggregate value is unlikely to be processed in vector register.
  8740. return tryToVectorizeList(BuildVectorOpds, R);
  8741. }
  8742. bool SLPVectorizerPass::vectorizeInsertElementInst(InsertElementInst *IEI,
  8743. BasicBlock *BB, BoUpSLP &R) {
  8744. SmallVector<Value *, 16> BuildVectorInsts;
  8745. SmallVector<Value *, 16> BuildVectorOpds;
  8746. SmallVector<int> Mask;
  8747. if (!findBuildAggregate(IEI, TTI, BuildVectorOpds, BuildVectorInsts) ||
  8748. (llvm::all_of(
  8749. BuildVectorOpds,
  8750. [](Value *V) { return isa<ExtractElementInst, UndefValue>(V); }) &&
  8751. isFixedVectorShuffle(BuildVectorOpds, Mask)))
  8752. return false;
  8753. LLVM_DEBUG(dbgs() << "SLP: array mappable to vector: " << *IEI << "\n");
  8754. return tryToVectorizeList(BuildVectorInsts, R);
  8755. }
  8756. template <typename T>
  8757. static bool
  8758. tryToVectorizeSequence(SmallVectorImpl<T *> &Incoming,
  8759. function_ref<unsigned(T *)> Limit,
  8760. function_ref<bool(T *, T *)> Comparator,
  8761. function_ref<bool(T *, T *)> AreCompatible,
  8762. function_ref<bool(ArrayRef<T *>, bool)> TryToVectorizeHelper,
  8763. bool LimitForRegisterSize) {
  8764. bool Changed = false;
  8765. // Sort by type, parent, operands.
  8766. stable_sort(Incoming, Comparator);
  8767. // Try to vectorize elements base on their type.
  8768. SmallVector<T *> Candidates;
  8769. for (auto *IncIt = Incoming.begin(), *E = Incoming.end(); IncIt != E;) {
  8770. // Look for the next elements with the same type, parent and operand
  8771. // kinds.
  8772. auto *SameTypeIt = IncIt;
  8773. while (SameTypeIt != E && AreCompatible(*SameTypeIt, *IncIt))
  8774. ++SameTypeIt;
  8775. // Try to vectorize them.
  8776. unsigned NumElts = (SameTypeIt - IncIt);
  8777. LLVM_DEBUG(dbgs() << "SLP: Trying to vectorize starting at nodes ("
  8778. << NumElts << ")\n");
  8779. // The vectorization is a 3-state attempt:
  8780. // 1. Try to vectorize instructions with the same/alternate opcodes with the
  8781. // size of maximal register at first.
  8782. // 2. Try to vectorize remaining instructions with the same type, if
  8783. // possible. This may result in the better vectorization results rather than
  8784. // if we try just to vectorize instructions with the same/alternate opcodes.
  8785. // 3. Final attempt to try to vectorize all instructions with the
  8786. // same/alternate ops only, this may result in some extra final
  8787. // vectorization.
  8788. if (NumElts > 1 &&
  8789. TryToVectorizeHelper(makeArrayRef(IncIt, NumElts), LimitForRegisterSize)) {
  8790. // Success start over because instructions might have been changed.
  8791. Changed = true;
  8792. } else if (NumElts < Limit(*IncIt) &&
  8793. (Candidates.empty() ||
  8794. Candidates.front()->getType() == (*IncIt)->getType())) {
  8795. Candidates.append(IncIt, std::next(IncIt, NumElts));
  8796. }
  8797. // Final attempt to vectorize instructions with the same types.
  8798. if (Candidates.size() > 1 &&
  8799. (SameTypeIt == E || (*SameTypeIt)->getType() != (*IncIt)->getType())) {
  8800. if (TryToVectorizeHelper(Candidates, /*LimitForRegisterSize=*/false)) {
  8801. // Success start over because instructions might have been changed.
  8802. Changed = true;
  8803. } else if (LimitForRegisterSize) {
  8804. // Try to vectorize using small vectors.
  8805. for (auto *It = Candidates.begin(), *End = Candidates.end();
  8806. It != End;) {
  8807. auto *SameTypeIt = It;
  8808. while (SameTypeIt != End && AreCompatible(*SameTypeIt, *It))
  8809. ++SameTypeIt;
  8810. unsigned NumElts = (SameTypeIt - It);
  8811. if (NumElts > 1 && TryToVectorizeHelper(makeArrayRef(It, NumElts),
  8812. /*LimitForRegisterSize=*/false))
  8813. Changed = true;
  8814. It = SameTypeIt;
  8815. }
  8816. }
  8817. Candidates.clear();
  8818. }
  8819. // Start over at the next instruction of a different type (or the end).
  8820. IncIt = SameTypeIt;
  8821. }
  8822. return Changed;
  8823. }
  8824. /// Compare two cmp instructions. If IsCompatibility is true, function returns
  8825. /// true if 2 cmps have same/swapped predicates and mos compatible corresponding
  8826. /// operands. If IsCompatibility is false, function implements strict weak
  8827. /// ordering relation between two cmp instructions, returning true if the first
  8828. /// instruction is "less" than the second, i.e. its predicate is less than the
  8829. /// predicate of the second or the operands IDs are less than the operands IDs
  8830. /// of the second cmp instruction.
  8831. template <bool IsCompatibility>
  8832. static bool compareCmp(Value *V, Value *V2,
  8833. function_ref<bool(Instruction *)> IsDeleted) {
  8834. auto *CI1 = cast<CmpInst>(V);
  8835. auto *CI2 = cast<CmpInst>(V2);
  8836. if (IsDeleted(CI2) || !isValidElementType(CI2->getType()))
  8837. return false;
  8838. if (CI1->getOperand(0)->getType()->getTypeID() <
  8839. CI2->getOperand(0)->getType()->getTypeID())
  8840. return !IsCompatibility;
  8841. if (CI1->getOperand(0)->getType()->getTypeID() >
  8842. CI2->getOperand(0)->getType()->getTypeID())
  8843. return false;
  8844. CmpInst::Predicate Pred1 = CI1->getPredicate();
  8845. CmpInst::Predicate Pred2 = CI2->getPredicate();
  8846. CmpInst::Predicate SwapPred1 = CmpInst::getSwappedPredicate(Pred1);
  8847. CmpInst::Predicate SwapPred2 = CmpInst::getSwappedPredicate(Pred2);
  8848. CmpInst::Predicate BasePred1 = std::min(Pred1, SwapPred1);
  8849. CmpInst::Predicate BasePred2 = std::min(Pred2, SwapPred2);
  8850. if (BasePred1 < BasePred2)
  8851. return !IsCompatibility;
  8852. if (BasePred1 > BasePred2)
  8853. return false;
  8854. // Compare operands.
  8855. bool LEPreds = Pred1 <= Pred2;
  8856. bool GEPreds = Pred1 >= Pred2;
  8857. for (int I = 0, E = CI1->getNumOperands(); I < E; ++I) {
  8858. auto *Op1 = CI1->getOperand(LEPreds ? I : E - I - 1);
  8859. auto *Op2 = CI2->getOperand(GEPreds ? I : E - I - 1);
  8860. if (Op1->getValueID() < Op2->getValueID())
  8861. return !IsCompatibility;
  8862. if (Op1->getValueID() > Op2->getValueID())
  8863. return false;
  8864. if (auto *I1 = dyn_cast<Instruction>(Op1))
  8865. if (auto *I2 = dyn_cast<Instruction>(Op2)) {
  8866. if (I1->getParent() != I2->getParent())
  8867. return false;
  8868. InstructionsState S = getSameOpcode({I1, I2});
  8869. if (S.getOpcode())
  8870. continue;
  8871. return false;
  8872. }
  8873. }
  8874. return IsCompatibility;
  8875. }
  8876. bool SLPVectorizerPass::vectorizeSimpleInstructions(
  8877. SmallVectorImpl<Instruction *> &Instructions, BasicBlock *BB, BoUpSLP &R,
  8878. bool AtTerminator) {
  8879. bool OpsChanged = false;
  8880. SmallVector<Instruction *, 4> PostponedCmps;
  8881. for (auto *I : reverse(Instructions)) {
  8882. if (R.isDeleted(I))
  8883. continue;
  8884. if (auto *LastInsertValue = dyn_cast<InsertValueInst>(I))
  8885. OpsChanged |= vectorizeInsertValueInst(LastInsertValue, BB, R);
  8886. else if (auto *LastInsertElem = dyn_cast<InsertElementInst>(I))
  8887. OpsChanged |= vectorizeInsertElementInst(LastInsertElem, BB, R);
  8888. else if (isa<CmpInst>(I))
  8889. PostponedCmps.push_back(I);
  8890. }
  8891. if (AtTerminator) {
  8892. // Try to find reductions first.
  8893. for (Instruction *I : PostponedCmps) {
  8894. if (R.isDeleted(I))
  8895. continue;
  8896. for (Value *Op : I->operands())
  8897. OpsChanged |= vectorizeRootInstruction(nullptr, Op, BB, R, TTI);
  8898. }
  8899. // Try to vectorize operands as vector bundles.
  8900. for (Instruction *I : PostponedCmps) {
  8901. if (R.isDeleted(I))
  8902. continue;
  8903. OpsChanged |= tryToVectorize(I, R);
  8904. }
  8905. // Try to vectorize list of compares.
  8906. // Sort by type, compare predicate, etc.
  8907. auto &&CompareSorter = [&R](Value *V, Value *V2) {
  8908. return compareCmp<false>(V, V2,
  8909. [&R](Instruction *I) { return R.isDeleted(I); });
  8910. };
  8911. auto &&AreCompatibleCompares = [&R](Value *V1, Value *V2) {
  8912. if (V1 == V2)
  8913. return true;
  8914. return compareCmp<true>(V1, V2,
  8915. [&R](Instruction *I) { return R.isDeleted(I); });
  8916. };
  8917. auto Limit = [&R](Value *V) {
  8918. unsigned EltSize = R.getVectorElementSize(V);
  8919. return std::max(2U, R.getMaxVecRegSize() / EltSize);
  8920. };
  8921. SmallVector<Value *> Vals(PostponedCmps.begin(), PostponedCmps.end());
  8922. OpsChanged |= tryToVectorizeSequence<Value>(
  8923. Vals, Limit, CompareSorter, AreCompatibleCompares,
  8924. [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
  8925. // Exclude possible reductions from other blocks.
  8926. bool ArePossiblyReducedInOtherBlock =
  8927. any_of(Candidates, [](Value *V) {
  8928. return any_of(V->users(), [V](User *U) {
  8929. return isa<SelectInst>(U) &&
  8930. cast<SelectInst>(U)->getParent() !=
  8931. cast<Instruction>(V)->getParent();
  8932. });
  8933. });
  8934. if (ArePossiblyReducedInOtherBlock)
  8935. return false;
  8936. return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
  8937. },
  8938. /*LimitForRegisterSize=*/true);
  8939. Instructions.clear();
  8940. } else {
  8941. // Insert in reverse order since the PostponedCmps vector was filled in
  8942. // reverse order.
  8943. Instructions.assign(PostponedCmps.rbegin(), PostponedCmps.rend());
  8944. }
  8945. return OpsChanged;
  8946. }
  8947. bool SLPVectorizerPass::vectorizeChainsInBlock(BasicBlock *BB, BoUpSLP &R) {
  8948. bool Changed = false;
  8949. SmallVector<Value *, 4> Incoming;
  8950. SmallPtrSet<Value *, 16> VisitedInstrs;
  8951. // Maps phi nodes to the non-phi nodes found in the use tree for each phi
  8952. // node. Allows better to identify the chains that can be vectorized in the
  8953. // better way.
  8954. DenseMap<Value *, SmallVector<Value *, 4>> PHIToOpcodes;
  8955. auto PHICompare = [this, &PHIToOpcodes](Value *V1, Value *V2) {
  8956. assert(isValidElementType(V1->getType()) &&
  8957. isValidElementType(V2->getType()) &&
  8958. "Expected vectorizable types only.");
  8959. // It is fine to compare type IDs here, since we expect only vectorizable
  8960. // types, like ints, floats and pointers, we don't care about other type.
  8961. if (V1->getType()->getTypeID() < V2->getType()->getTypeID())
  8962. return true;
  8963. if (V1->getType()->getTypeID() > V2->getType()->getTypeID())
  8964. return false;
  8965. ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
  8966. ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
  8967. if (Opcodes1.size() < Opcodes2.size())
  8968. return true;
  8969. if (Opcodes1.size() > Opcodes2.size())
  8970. return false;
  8971. Optional<bool> ConstOrder;
  8972. for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
  8973. // Undefs are compatible with any other value.
  8974. if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I])) {
  8975. if (!ConstOrder)
  8976. ConstOrder =
  8977. !isa<UndefValue>(Opcodes1[I]) && isa<UndefValue>(Opcodes2[I]);
  8978. continue;
  8979. }
  8980. if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
  8981. if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
  8982. DomTreeNodeBase<BasicBlock> *NodeI1 = DT->getNode(I1->getParent());
  8983. DomTreeNodeBase<BasicBlock> *NodeI2 = DT->getNode(I2->getParent());
  8984. if (!NodeI1)
  8985. return NodeI2 != nullptr;
  8986. if (!NodeI2)
  8987. return false;
  8988. assert((NodeI1 == NodeI2) ==
  8989. (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
  8990. "Different nodes should have different DFS numbers");
  8991. if (NodeI1 != NodeI2)
  8992. return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
  8993. InstructionsState S = getSameOpcode({I1, I2});
  8994. if (S.getOpcode())
  8995. continue;
  8996. return I1->getOpcode() < I2->getOpcode();
  8997. }
  8998. if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I])) {
  8999. if (!ConstOrder)
  9000. ConstOrder = Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID();
  9001. continue;
  9002. }
  9003. if (Opcodes1[I]->getValueID() < Opcodes2[I]->getValueID())
  9004. return true;
  9005. if (Opcodes1[I]->getValueID() > Opcodes2[I]->getValueID())
  9006. return false;
  9007. }
  9008. return ConstOrder && *ConstOrder;
  9009. };
  9010. auto AreCompatiblePHIs = [&PHIToOpcodes](Value *V1, Value *V2) {
  9011. if (V1 == V2)
  9012. return true;
  9013. if (V1->getType() != V2->getType())
  9014. return false;
  9015. ArrayRef<Value *> Opcodes1 = PHIToOpcodes[V1];
  9016. ArrayRef<Value *> Opcodes2 = PHIToOpcodes[V2];
  9017. if (Opcodes1.size() != Opcodes2.size())
  9018. return false;
  9019. for (int I = 0, E = Opcodes1.size(); I < E; ++I) {
  9020. // Undefs are compatible with any other value.
  9021. if (isa<UndefValue>(Opcodes1[I]) || isa<UndefValue>(Opcodes2[I]))
  9022. continue;
  9023. if (auto *I1 = dyn_cast<Instruction>(Opcodes1[I]))
  9024. if (auto *I2 = dyn_cast<Instruction>(Opcodes2[I])) {
  9025. if (I1->getParent() != I2->getParent())
  9026. return false;
  9027. InstructionsState S = getSameOpcode({I1, I2});
  9028. if (S.getOpcode())
  9029. continue;
  9030. return false;
  9031. }
  9032. if (isa<Constant>(Opcodes1[I]) && isa<Constant>(Opcodes2[I]))
  9033. continue;
  9034. if (Opcodes1[I]->getValueID() != Opcodes2[I]->getValueID())
  9035. return false;
  9036. }
  9037. return true;
  9038. };
  9039. auto Limit = [&R](Value *V) {
  9040. unsigned EltSize = R.getVectorElementSize(V);
  9041. return std::max(2U, R.getMaxVecRegSize() / EltSize);
  9042. };
  9043. bool HaveVectorizedPhiNodes = false;
  9044. do {
  9045. // Collect the incoming values from the PHIs.
  9046. Incoming.clear();
  9047. for (Instruction &I : *BB) {
  9048. PHINode *P = dyn_cast<PHINode>(&I);
  9049. if (!P)
  9050. break;
  9051. // No need to analyze deleted, vectorized and non-vectorizable
  9052. // instructions.
  9053. if (!VisitedInstrs.count(P) && !R.isDeleted(P) &&
  9054. isValidElementType(P->getType()))
  9055. Incoming.push_back(P);
  9056. }
  9057. // Find the corresponding non-phi nodes for better matching when trying to
  9058. // build the tree.
  9059. for (Value *V : Incoming) {
  9060. SmallVectorImpl<Value *> &Opcodes =
  9061. PHIToOpcodes.try_emplace(V).first->getSecond();
  9062. if (!Opcodes.empty())
  9063. continue;
  9064. SmallVector<Value *, 4> Nodes(1, V);
  9065. SmallPtrSet<Value *, 4> Visited;
  9066. while (!Nodes.empty()) {
  9067. auto *PHI = cast<PHINode>(Nodes.pop_back_val());
  9068. if (!Visited.insert(PHI).second)
  9069. continue;
  9070. for (Value *V : PHI->incoming_values()) {
  9071. if (auto *PHI1 = dyn_cast<PHINode>((V))) {
  9072. Nodes.push_back(PHI1);
  9073. continue;
  9074. }
  9075. Opcodes.emplace_back(V);
  9076. }
  9077. }
  9078. }
  9079. HaveVectorizedPhiNodes = tryToVectorizeSequence<Value>(
  9080. Incoming, Limit, PHICompare, AreCompatiblePHIs,
  9081. [this, &R](ArrayRef<Value *> Candidates, bool LimitForRegisterSize) {
  9082. return tryToVectorizeList(Candidates, R, LimitForRegisterSize);
  9083. },
  9084. /*LimitForRegisterSize=*/true);
  9085. Changed |= HaveVectorizedPhiNodes;
  9086. VisitedInstrs.insert(Incoming.begin(), Incoming.end());
  9087. } while (HaveVectorizedPhiNodes);
  9088. VisitedInstrs.clear();
  9089. SmallVector<Instruction *, 8> PostProcessInstructions;
  9090. SmallDenseSet<Instruction *, 4> KeyNodes;
  9091. for (BasicBlock::iterator it = BB->begin(), e = BB->end(); it != e; ++it) {
  9092. // Skip instructions with scalable type. The num of elements is unknown at
  9093. // compile-time for scalable type.
  9094. if (isa<ScalableVectorType>(it->getType()))
  9095. continue;
  9096. // Skip instructions marked for the deletion.
  9097. if (R.isDeleted(&*it))
  9098. continue;
  9099. // We may go through BB multiple times so skip the one we have checked.
  9100. if (!VisitedInstrs.insert(&*it).second) {
  9101. if (it->use_empty() && KeyNodes.contains(&*it) &&
  9102. vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
  9103. it->isTerminator())) {
  9104. // We would like to start over since some instructions are deleted
  9105. // and the iterator may become invalid value.
  9106. Changed = true;
  9107. it = BB->begin();
  9108. e = BB->end();
  9109. }
  9110. continue;
  9111. }
  9112. if (isa<DbgInfoIntrinsic>(it))
  9113. continue;
  9114. // Try to vectorize reductions that use PHINodes.
  9115. if (PHINode *P = dyn_cast<PHINode>(it)) {
  9116. // Check that the PHI is a reduction PHI.
  9117. if (P->getNumIncomingValues() == 2) {
  9118. // Try to match and vectorize a horizontal reduction.
  9119. if (vectorizeRootInstruction(P, getReductionValue(DT, P, BB, LI), BB, R,
  9120. TTI)) {
  9121. Changed = true;
  9122. it = BB->begin();
  9123. e = BB->end();
  9124. continue;
  9125. }
  9126. }
  9127. // Try to vectorize the incoming values of the PHI, to catch reductions
  9128. // that feed into PHIs.
  9129. for (unsigned I = 0, E = P->getNumIncomingValues(); I != E; I++) {
  9130. // Skip if the incoming block is the current BB for now. Also, bypass
  9131. // unreachable IR for efficiency and to avoid crashing.
  9132. // TODO: Collect the skipped incoming values and try to vectorize them
  9133. // after processing BB.
  9134. if (BB == P->getIncomingBlock(I) ||
  9135. !DT->isReachableFromEntry(P->getIncomingBlock(I)))
  9136. continue;
  9137. Changed |= vectorizeRootInstruction(nullptr, P->getIncomingValue(I),
  9138. P->getIncomingBlock(I), R, TTI);
  9139. }
  9140. continue;
  9141. }
  9142. // Ran into an instruction without users, like terminator, or function call
  9143. // with ignored return value, store. Ignore unused instructions (basing on
  9144. // instruction type, except for CallInst and InvokeInst).
  9145. if (it->use_empty() && (it->getType()->isVoidTy() || isa<CallInst>(it) ||
  9146. isa<InvokeInst>(it))) {
  9147. KeyNodes.insert(&*it);
  9148. bool OpsChanged = false;
  9149. if (ShouldStartVectorizeHorAtStore || !isa<StoreInst>(it)) {
  9150. for (auto *V : it->operand_values()) {
  9151. // Try to match and vectorize a horizontal reduction.
  9152. OpsChanged |= vectorizeRootInstruction(nullptr, V, BB, R, TTI);
  9153. }
  9154. }
  9155. // Start vectorization of post-process list of instructions from the
  9156. // top-tree instructions to try to vectorize as many instructions as
  9157. // possible.
  9158. OpsChanged |= vectorizeSimpleInstructions(PostProcessInstructions, BB, R,
  9159. it->isTerminator());
  9160. if (OpsChanged) {
  9161. // We would like to start over since some instructions are deleted
  9162. // and the iterator may become invalid value.
  9163. Changed = true;
  9164. it = BB->begin();
  9165. e = BB->end();
  9166. continue;
  9167. }
  9168. }
  9169. if (isa<InsertElementInst>(it) || isa<CmpInst>(it) ||
  9170. isa<InsertValueInst>(it))
  9171. PostProcessInstructions.push_back(&*it);
  9172. }
  9173. return Changed;
  9174. }
  9175. bool SLPVectorizerPass::vectorizeGEPIndices(BasicBlock *BB, BoUpSLP &R) {
  9176. auto Changed = false;
  9177. for (auto &Entry : GEPs) {
  9178. // If the getelementptr list has fewer than two elements, there's nothing
  9179. // to do.
  9180. if (Entry.second.size() < 2)
  9181. continue;
  9182. LLVM_DEBUG(dbgs() << "SLP: Analyzing a getelementptr list of length "
  9183. << Entry.second.size() << ".\n");
  9184. // Process the GEP list in chunks suitable for the target's supported
  9185. // vector size. If a vector register can't hold 1 element, we are done. We
  9186. // are trying to vectorize the index computations, so the maximum number of
  9187. // elements is based on the size of the index expression, rather than the
  9188. // size of the GEP itself (the target's pointer size).
  9189. unsigned MaxVecRegSize = R.getMaxVecRegSize();
  9190. unsigned EltSize = R.getVectorElementSize(*Entry.second[0]->idx_begin());
  9191. if (MaxVecRegSize < EltSize)
  9192. continue;
  9193. unsigned MaxElts = MaxVecRegSize / EltSize;
  9194. for (unsigned BI = 0, BE = Entry.second.size(); BI < BE; BI += MaxElts) {
  9195. auto Len = std::min<unsigned>(BE - BI, MaxElts);
  9196. ArrayRef<GetElementPtrInst *> GEPList(&Entry.second[BI], Len);
  9197. // Initialize a set a candidate getelementptrs. Note that we use a
  9198. // SetVector here to preserve program order. If the index computations
  9199. // are vectorizable and begin with loads, we want to minimize the chance
  9200. // of having to reorder them later.
  9201. SetVector<Value *> Candidates(GEPList.begin(), GEPList.end());
  9202. // Some of the candidates may have already been vectorized after we
  9203. // initially collected them. If so, they are marked as deleted, so remove
  9204. // them from the set of candidates.
  9205. Candidates.remove_if(
  9206. [&R](Value *I) { return R.isDeleted(cast<Instruction>(I)); });
  9207. // Remove from the set of candidates all pairs of getelementptrs with
  9208. // constant differences. Such getelementptrs are likely not good
  9209. // candidates for vectorization in a bottom-up phase since one can be
  9210. // computed from the other. We also ensure all candidate getelementptr
  9211. // indices are unique.
  9212. for (int I = 0, E = GEPList.size(); I < E && Candidates.size() > 1; ++I) {
  9213. auto *GEPI = GEPList[I];
  9214. if (!Candidates.count(GEPI))
  9215. continue;
  9216. auto *SCEVI = SE->getSCEV(GEPList[I]);
  9217. for (int J = I + 1; J < E && Candidates.size() > 1; ++J) {
  9218. auto *GEPJ = GEPList[J];
  9219. auto *SCEVJ = SE->getSCEV(GEPList[J]);
  9220. if (isa<SCEVConstant>(SE->getMinusSCEV(SCEVI, SCEVJ))) {
  9221. Candidates.remove(GEPI);
  9222. Candidates.remove(GEPJ);
  9223. } else if (GEPI->idx_begin()->get() == GEPJ->idx_begin()->get()) {
  9224. Candidates.remove(GEPJ);
  9225. }
  9226. }
  9227. }
  9228. // We break out of the above computation as soon as we know there are
  9229. // fewer than two candidates remaining.
  9230. if (Candidates.size() < 2)
  9231. continue;
  9232. // Add the single, non-constant index of each candidate to the bundle. We
  9233. // ensured the indices met these constraints when we originally collected
  9234. // the getelementptrs.
  9235. SmallVector<Value *, 16> Bundle(Candidates.size());
  9236. auto BundleIndex = 0u;
  9237. for (auto *V : Candidates) {
  9238. auto *GEP = cast<GetElementPtrInst>(V);
  9239. auto *GEPIdx = GEP->idx_begin()->get();
  9240. assert(GEP->getNumIndices() == 1 || !isa<Constant>(GEPIdx));
  9241. Bundle[BundleIndex++] = GEPIdx;
  9242. }
  9243. // Try and vectorize the indices. We are currently only interested in
  9244. // gather-like cases of the form:
  9245. //
  9246. // ... = g[a[0] - b[0]] + g[a[1] - b[1]] + ...
  9247. //
  9248. // where the loads of "a", the loads of "b", and the subtractions can be
  9249. // performed in parallel. It's likely that detecting this pattern in a
  9250. // bottom-up phase will be simpler and less costly than building a
  9251. // full-blown top-down phase beginning at the consecutive loads.
  9252. Changed |= tryToVectorizeList(Bundle, R);
  9253. }
  9254. }
  9255. return Changed;
  9256. }
  9257. bool SLPVectorizerPass::vectorizeStoreChains(BoUpSLP &R) {
  9258. bool Changed = false;
  9259. // Sort by type, base pointers and values operand. Value operands must be
  9260. // compatible (have the same opcode, same parent), otherwise it is
  9261. // definitely not profitable to try to vectorize them.
  9262. auto &&StoreSorter = [this](StoreInst *V, StoreInst *V2) {
  9263. if (V->getPointerOperandType()->getTypeID() <
  9264. V2->getPointerOperandType()->getTypeID())
  9265. return true;
  9266. if (V->getPointerOperandType()->getTypeID() >
  9267. V2->getPointerOperandType()->getTypeID())
  9268. return false;
  9269. // UndefValues are compatible with all other values.
  9270. if (isa<UndefValue>(V->getValueOperand()) ||
  9271. isa<UndefValue>(V2->getValueOperand()))
  9272. return false;
  9273. if (auto *I1 = dyn_cast<Instruction>(V->getValueOperand()))
  9274. if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
  9275. DomTreeNodeBase<llvm::BasicBlock> *NodeI1 =
  9276. DT->getNode(I1->getParent());
  9277. DomTreeNodeBase<llvm::BasicBlock> *NodeI2 =
  9278. DT->getNode(I2->getParent());
  9279. assert(NodeI1 && "Should only process reachable instructions");
  9280. assert(NodeI1 && "Should only process reachable instructions");
  9281. assert((NodeI1 == NodeI2) ==
  9282. (NodeI1->getDFSNumIn() == NodeI2->getDFSNumIn()) &&
  9283. "Different nodes should have different DFS numbers");
  9284. if (NodeI1 != NodeI2)
  9285. return NodeI1->getDFSNumIn() < NodeI2->getDFSNumIn();
  9286. InstructionsState S = getSameOpcode({I1, I2});
  9287. if (S.getOpcode())
  9288. return false;
  9289. return I1->getOpcode() < I2->getOpcode();
  9290. }
  9291. if (isa<Constant>(V->getValueOperand()) &&
  9292. isa<Constant>(V2->getValueOperand()))
  9293. return false;
  9294. return V->getValueOperand()->getValueID() <
  9295. V2->getValueOperand()->getValueID();
  9296. };
  9297. auto &&AreCompatibleStores = [](StoreInst *V1, StoreInst *V2) {
  9298. if (V1 == V2)
  9299. return true;
  9300. if (V1->getPointerOperandType() != V2->getPointerOperandType())
  9301. return false;
  9302. // Undefs are compatible with any other value.
  9303. if (isa<UndefValue>(V1->getValueOperand()) ||
  9304. isa<UndefValue>(V2->getValueOperand()))
  9305. return true;
  9306. if (auto *I1 = dyn_cast<Instruction>(V1->getValueOperand()))
  9307. if (auto *I2 = dyn_cast<Instruction>(V2->getValueOperand())) {
  9308. if (I1->getParent() != I2->getParent())
  9309. return false;
  9310. InstructionsState S = getSameOpcode({I1, I2});
  9311. return S.getOpcode() > 0;
  9312. }
  9313. if (isa<Constant>(V1->getValueOperand()) &&
  9314. isa<Constant>(V2->getValueOperand()))
  9315. return true;
  9316. return V1->getValueOperand()->getValueID() ==
  9317. V2->getValueOperand()->getValueID();
  9318. };
  9319. auto Limit = [&R, this](StoreInst *SI) {
  9320. unsigned EltSize = DL->getTypeSizeInBits(SI->getValueOperand()->getType());
  9321. return R.getMinVF(EltSize);
  9322. };
  9323. // Attempt to sort and vectorize each of the store-groups.
  9324. for (auto &Pair : Stores) {
  9325. if (Pair.second.size() < 2)
  9326. continue;
  9327. LLVM_DEBUG(dbgs() << "SLP: Analyzing a store chain of length "
  9328. << Pair.second.size() << ".\n");
  9329. if (!isValidElementType(Pair.second.front()->getValueOperand()->getType()))
  9330. continue;
  9331. Changed |= tryToVectorizeSequence<StoreInst>(
  9332. Pair.second, Limit, StoreSorter, AreCompatibleStores,
  9333. [this, &R](ArrayRef<StoreInst *> Candidates, bool) {
  9334. return vectorizeStores(Candidates, R);
  9335. },
  9336. /*LimitForRegisterSize=*/false);
  9337. }
  9338. return Changed;
  9339. }
  9340. char SLPVectorizer::ID = 0;
  9341. static const char lv_name[] = "SLP Vectorizer";
  9342. INITIALIZE_PASS_BEGIN(SLPVectorizer, SV_NAME, lv_name, false, false)
  9343. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  9344. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  9345. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  9346. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  9347. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  9348. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  9349. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  9350. INITIALIZE_PASS_DEPENDENCY(InjectTLIMappingsLegacy)
  9351. INITIALIZE_PASS_END(SLPVectorizer, SV_NAME, lv_name, false, false)
  9352. Pass *llvm::createSLPVectorizerPass() { return new SLPVectorizer(); }