SLPVectorizer.cpp 253 KB

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