LoopVectorize.cpp 311 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655
  1. //===- LoopVectorize.cpp - A Loop 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 is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
  10. // and generates target-independent LLVM-IR.
  11. // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
  12. // of instructions in order to estimate the profitability of vectorization.
  13. //
  14. // The loop vectorizer combines consecutive loop iterations into a single
  15. // 'wide' iteration. After this transformation the index is incremented
  16. // by the SIMD vector width, and not by one.
  17. //
  18. // This pass has three parts:
  19. // 1. The main loop pass that drives the different parts.
  20. // 2. LoopVectorizationLegality - A unit that checks for the legality
  21. // of the vectorization.
  22. // 3. InnerLoopVectorizer - A unit that performs the actual
  23. // widening of instructions.
  24. // 4. LoopVectorizationCostModel - A unit that checks for the profitability
  25. // of vectorization. It decides on the optimal vector width, which
  26. // can be one, if vectorization is not profitable.
  27. //
  28. // There is a development effort going on to migrate loop vectorizer to the
  29. // VPlan infrastructure and to introduce outer loop vectorization support (see
  30. // docs/Proposal/VectorizationPlan.rst and
  31. // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
  32. // purpose, we temporarily introduced the VPlan-native vectorization path: an
  33. // alternative vectorization path that is natively implemented on top of the
  34. // VPlan infrastructure. See EnableVPlanNativePath for enabling.
  35. //
  36. //===----------------------------------------------------------------------===//
  37. //
  38. // The reduction-variable vectorization is based on the paper:
  39. // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
  40. //
  41. // Variable uniformity checks are inspired by:
  42. // Karrenberg, R. and Hack, S. Whole Function Vectorization.
  43. //
  44. // The interleaved access vectorization is based on the paper:
  45. // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
  46. // Data for SIMD
  47. //
  48. // Other ideas/concepts are from:
  49. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  50. //
  51. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  52. // Vectorizing Compilers.
  53. //
  54. //===----------------------------------------------------------------------===//
  55. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  56. #include "LoopVectorizationPlanner.h"
  57. #include "VPRecipeBuilder.h"
  58. #include "VPlanHCFGBuilder.h"
  59. #include "VPlanHCFGTransforms.h"
  60. #include "VPlanPredicator.h"
  61. #include "llvm/ADT/APInt.h"
  62. #include "llvm/ADT/ArrayRef.h"
  63. #include "llvm/ADT/DenseMap.h"
  64. #include "llvm/ADT/DenseMapInfo.h"
  65. #include "llvm/ADT/Hashing.h"
  66. #include "llvm/ADT/MapVector.h"
  67. #include "llvm/ADT/None.h"
  68. #include "llvm/ADT/Optional.h"
  69. #include "llvm/ADT/STLExtras.h"
  70. #include "llvm/ADT/SetVector.h"
  71. #include "llvm/ADT/SmallPtrSet.h"
  72. #include "llvm/ADT/SmallVector.h"
  73. #include "llvm/ADT/Statistic.h"
  74. #include "llvm/ADT/StringRef.h"
  75. #include "llvm/ADT/Twine.h"
  76. #include "llvm/ADT/iterator_range.h"
  77. #include "llvm/Analysis/AssumptionCache.h"
  78. #include "llvm/Analysis/BasicAliasAnalysis.h"
  79. #include "llvm/Analysis/BlockFrequencyInfo.h"
  80. #include "llvm/Analysis/CFG.h"
  81. #include "llvm/Analysis/CodeMetrics.h"
  82. #include "llvm/Analysis/DemandedBits.h"
  83. #include "llvm/Analysis/GlobalsModRef.h"
  84. #include "llvm/Analysis/LoopAccessAnalysis.h"
  85. #include "llvm/Analysis/LoopAnalysisManager.h"
  86. #include "llvm/Analysis/LoopInfo.h"
  87. #include "llvm/Analysis/LoopIterator.h"
  88. #include "llvm/Analysis/MemorySSA.h"
  89. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  90. #include "llvm/Analysis/ProfileSummaryInfo.h"
  91. #include "llvm/Analysis/ScalarEvolution.h"
  92. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  93. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  94. #include "llvm/Analysis/TargetLibraryInfo.h"
  95. #include "llvm/Analysis/TargetTransformInfo.h"
  96. #include "llvm/Analysis/VectorUtils.h"
  97. #include "llvm/IR/Attributes.h"
  98. #include "llvm/IR/BasicBlock.h"
  99. #include "llvm/IR/CFG.h"
  100. #include "llvm/IR/Constant.h"
  101. #include "llvm/IR/Constants.h"
  102. #include "llvm/IR/DataLayout.h"
  103. #include "llvm/IR/DebugInfoMetadata.h"
  104. #include "llvm/IR/DebugLoc.h"
  105. #include "llvm/IR/DerivedTypes.h"
  106. #include "llvm/IR/DiagnosticInfo.h"
  107. #include "llvm/IR/Dominators.h"
  108. #include "llvm/IR/Function.h"
  109. #include "llvm/IR/IRBuilder.h"
  110. #include "llvm/IR/InstrTypes.h"
  111. #include "llvm/IR/Instruction.h"
  112. #include "llvm/IR/Instructions.h"
  113. #include "llvm/IR/IntrinsicInst.h"
  114. #include "llvm/IR/Intrinsics.h"
  115. #include "llvm/IR/LLVMContext.h"
  116. #include "llvm/IR/Metadata.h"
  117. #include "llvm/IR/Module.h"
  118. #include "llvm/IR/Operator.h"
  119. #include "llvm/IR/Type.h"
  120. #include "llvm/IR/Use.h"
  121. #include "llvm/IR/User.h"
  122. #include "llvm/IR/Value.h"
  123. #include "llvm/IR/ValueHandle.h"
  124. #include "llvm/IR/Verifier.h"
  125. #include "llvm/Pass.h"
  126. #include "llvm/Support/Casting.h"
  127. #include "llvm/Support/CommandLine.h"
  128. #include "llvm/Support/Compiler.h"
  129. #include "llvm/Support/Debug.h"
  130. #include "llvm/Support/ErrorHandling.h"
  131. #include "llvm/Support/MathExtras.h"
  132. #include "llvm/Support/raw_ostream.h"
  133. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  134. #include "llvm/Transforms/Utils/LoopSimplify.h"
  135. #include "llvm/Transforms/Utils/LoopUtils.h"
  136. #include "llvm/Transforms/Utils/LoopVersioning.h"
  137. #include "llvm/Transforms/Utils/SizeOpts.h"
  138. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  139. #include <algorithm>
  140. #include <cassert>
  141. #include <cstdint>
  142. #include <cstdlib>
  143. #include <functional>
  144. #include <iterator>
  145. #include <limits>
  146. #include <memory>
  147. #include <string>
  148. #include <tuple>
  149. #include <utility>
  150. #include <vector>
  151. using namespace llvm;
  152. #define LV_NAME "loop-vectorize"
  153. #define DEBUG_TYPE LV_NAME
  154. /// @{
  155. /// Metadata attribute names
  156. static const char *const LLVMLoopVectorizeFollowupAll =
  157. "llvm.loop.vectorize.followup_all";
  158. static const char *const LLVMLoopVectorizeFollowupVectorized =
  159. "llvm.loop.vectorize.followup_vectorized";
  160. static const char *const LLVMLoopVectorizeFollowupEpilogue =
  161. "llvm.loop.vectorize.followup_epilogue";
  162. /// @}
  163. STATISTIC(LoopsVectorized, "Number of loops vectorized");
  164. STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
  165. /// Loops with a known constant trip count below this number are vectorized only
  166. /// if no scalar iteration overheads are incurred.
  167. static cl::opt<unsigned> TinyTripCountVectorThreshold(
  168. "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
  169. cl::desc("Loops with a constant trip count that is smaller than this "
  170. "value are vectorized only if no scalar iteration overheads "
  171. "are incurred."));
  172. static cl::opt<bool> MaximizeBandwidth(
  173. "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
  174. cl::desc("Maximize bandwidth when selecting vectorization factor which "
  175. "will be determined by the smallest type in loop."));
  176. static cl::opt<bool> EnableInterleavedMemAccesses(
  177. "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  178. cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
  179. /// An interleave-group may need masking if it resides in a block that needs
  180. /// predication, or in order to mask away gaps.
  181. static cl::opt<bool> EnableMaskedInterleavedMemAccesses(
  182. "enable-masked-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  183. cl::desc("Enable vectorization on masked interleaved memory accesses in a loop"));
  184. /// We don't interleave loops with a known constant trip count below this
  185. /// number.
  186. static const unsigned TinyTripCountInterleaveThreshold = 128;
  187. static cl::opt<unsigned> ForceTargetNumScalarRegs(
  188. "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
  189. cl::desc("A flag that overrides the target's number of scalar registers."));
  190. static cl::opt<unsigned> ForceTargetNumVectorRegs(
  191. "force-target-num-vector-regs", cl::init(0), cl::Hidden,
  192. cl::desc("A flag that overrides the target's number of vector registers."));
  193. static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
  194. "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
  195. cl::desc("A flag that overrides the target's max interleave factor for "
  196. "scalar loops."));
  197. static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
  198. "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
  199. cl::desc("A flag that overrides the target's max interleave factor for "
  200. "vectorized loops."));
  201. static cl::opt<unsigned> ForceTargetInstructionCost(
  202. "force-target-instruction-cost", cl::init(0), cl::Hidden,
  203. cl::desc("A flag that overrides the target's expected cost for "
  204. "an instruction to a single constant value. Mostly "
  205. "useful for getting consistent testing."));
  206. static cl::opt<unsigned> SmallLoopCost(
  207. "small-loop-cost", cl::init(20), cl::Hidden,
  208. cl::desc(
  209. "The cost of a loop that is considered 'small' by the interleaver."));
  210. static cl::opt<bool> LoopVectorizeWithBlockFrequency(
  211. "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
  212. cl::desc("Enable the use of the block frequency analysis to access PGO "
  213. "heuristics minimizing code growth in cold regions and being more "
  214. "aggressive in hot regions."));
  215. // Runtime interleave loops for load/store throughput.
  216. static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
  217. "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
  218. cl::desc(
  219. "Enable runtime interleaving until load/store ports are saturated"));
  220. /// The number of stores in a loop that are allowed to need predication.
  221. static cl::opt<unsigned> NumberOfStoresToPredicate(
  222. "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
  223. cl::desc("Max number of stores to be predicated behind an if."));
  224. static cl::opt<bool> EnableIndVarRegisterHeur(
  225. "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
  226. cl::desc("Count the induction variable only once when interleaving"));
  227. static cl::opt<bool> EnableCondStoresVectorization(
  228. "enable-cond-stores-vec", cl::init(true), cl::Hidden,
  229. cl::desc("Enable if predication of stores during vectorization."));
  230. static cl::opt<unsigned> MaxNestedScalarReductionIC(
  231. "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
  232. cl::desc("The maximum interleave count to use when interleaving a scalar "
  233. "reduction in a nested loop."));
  234. cl::opt<bool> EnableVPlanNativePath(
  235. "enable-vplan-native-path", cl::init(false), cl::Hidden,
  236. cl::desc("Enable VPlan-native vectorization path with "
  237. "support for outer loop vectorization."));
  238. // FIXME: Remove this switch once we have divergence analysis. Currently we
  239. // assume divergent non-backedge branches when this switch is true.
  240. cl::opt<bool> EnableVPlanPredication(
  241. "enable-vplan-predication", cl::init(false), cl::Hidden,
  242. cl::desc("Enable VPlan-native vectorization path predicator with "
  243. "support for outer loop vectorization."));
  244. // This flag enables the stress testing of the VPlan H-CFG construction in the
  245. // VPlan-native vectorization path. It must be used in conjuction with
  246. // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
  247. // verification of the H-CFGs built.
  248. static cl::opt<bool> VPlanBuildStressTest(
  249. "vplan-build-stress-test", cl::init(false), cl::Hidden,
  250. cl::desc(
  251. "Build VPlan for every supported loop nest in the function and bail "
  252. "out right after the build (stress test the VPlan H-CFG construction "
  253. "in the VPlan-native vectorization path)."));
  254. cl::opt<bool> llvm::EnableLoopInterleaving(
  255. "interleave-loops", cl::init(true), cl::Hidden,
  256. cl::desc("Enable loop interleaving in Loop vectorization passes"));
  257. cl::opt<bool> llvm::EnableLoopVectorization(
  258. "vectorize-loops", cl::init(true), cl::Hidden,
  259. cl::desc("Run the Loop vectorization passes"));
  260. /// A helper function for converting Scalar types to vector types.
  261. /// If the incoming type is void, we return void. If the VF is 1, we return
  262. /// the scalar type.
  263. static Type *ToVectorTy(Type *Scalar, unsigned VF) {
  264. if (Scalar->isVoidTy() || VF == 1)
  265. return Scalar;
  266. return VectorType::get(Scalar, VF);
  267. }
  268. /// A helper function that returns the type of loaded or stored value.
  269. static Type *getMemInstValueType(Value *I) {
  270. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  271. "Expected Load or Store instruction");
  272. if (auto *LI = dyn_cast<LoadInst>(I))
  273. return LI->getType();
  274. return cast<StoreInst>(I)->getValueOperand()->getType();
  275. }
  276. /// A helper function that returns true if the given type is irregular. The
  277. /// type is irregular if its allocated size doesn't equal the store size of an
  278. /// element of the corresponding vector type at the given vectorization factor.
  279. static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
  280. // Determine if an array of VF elements of type Ty is "bitcast compatible"
  281. // with a <VF x Ty> vector.
  282. if (VF > 1) {
  283. auto *VectorTy = VectorType::get(Ty, VF);
  284. return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
  285. }
  286. // If the vectorization factor is one, we just check if an array of type Ty
  287. // requires padding between elements.
  288. return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
  289. }
  290. /// A helper function that returns the reciprocal of the block probability of
  291. /// predicated blocks. If we return X, we are assuming the predicated block
  292. /// will execute once for every X iterations of the loop header.
  293. ///
  294. /// TODO: We should use actual block probability here, if available. Currently,
  295. /// we always assume predicated blocks have a 50% chance of executing.
  296. static unsigned getReciprocalPredBlockProb() { return 2; }
  297. /// A helper function that adds a 'fast' flag to floating-point operations.
  298. static Value *addFastMathFlag(Value *V) {
  299. if (isa<FPMathOperator>(V))
  300. cast<Instruction>(V)->setFastMathFlags(FastMathFlags::getFast());
  301. return V;
  302. }
  303. static Value *addFastMathFlag(Value *V, FastMathFlags FMF) {
  304. if (isa<FPMathOperator>(V))
  305. cast<Instruction>(V)->setFastMathFlags(FMF);
  306. return V;
  307. }
  308. /// A helper function that returns an integer or floating-point constant with
  309. /// value C.
  310. static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
  311. return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
  312. : ConstantFP::get(Ty, C);
  313. }
  314. namespace llvm {
  315. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  316. /// block to a specified vectorization factor (VF).
  317. /// This class performs the widening of scalars into vectors, or multiple
  318. /// scalars. This class also implements the following features:
  319. /// * It inserts an epilogue loop for handling loops that don't have iteration
  320. /// counts that are known to be a multiple of the vectorization factor.
  321. /// * It handles the code generation for reduction variables.
  322. /// * Scalarization (implementation using scalars) of un-vectorizable
  323. /// instructions.
  324. /// InnerLoopVectorizer does not perform any vectorization-legality
  325. /// checks, and relies on the caller to check for the different legality
  326. /// aspects. The InnerLoopVectorizer relies on the
  327. /// LoopVectorizationLegality class to provide information about the induction
  328. /// and reduction variables that were found to a given vectorization factor.
  329. class InnerLoopVectorizer {
  330. public:
  331. InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  332. LoopInfo *LI, DominatorTree *DT,
  333. const TargetLibraryInfo *TLI,
  334. const TargetTransformInfo *TTI, AssumptionCache *AC,
  335. OptimizationRemarkEmitter *ORE, unsigned VecWidth,
  336. unsigned UnrollFactor, LoopVectorizationLegality *LVL,
  337. LoopVectorizationCostModel *CM)
  338. : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
  339. AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
  340. Builder(PSE.getSE()->getContext()),
  341. VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
  342. virtual ~InnerLoopVectorizer() = default;
  343. /// Create a new empty loop. Unlink the old loop and connect the new one.
  344. /// Return the pre-header block of the new loop.
  345. BasicBlock *createVectorizedLoopSkeleton();
  346. /// Widen a single instruction within the innermost loop.
  347. void widenInstruction(Instruction &I);
  348. /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
  349. void fixVectorizedLoop();
  350. // Return true if any runtime check is added.
  351. bool areSafetyChecksAdded() { return AddedSafetyChecks; }
  352. /// A type for vectorized values in the new loop. Each value from the
  353. /// original loop, when vectorized, is represented by UF vector values in the
  354. /// new unrolled loop, where UF is the unroll factor.
  355. using VectorParts = SmallVector<Value *, 2>;
  356. /// Vectorize a single PHINode in a block. This method handles the induction
  357. /// variable canonicalization. It supports both VF = 1 for unrolled loops and
  358. /// arbitrary length vectors.
  359. void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
  360. /// A helper function to scalarize a single Instruction in the innermost loop.
  361. /// Generates a sequence of scalar instances for each lane between \p MinLane
  362. /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
  363. /// inclusive..
  364. void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
  365. bool IfPredicateInstr);
  366. /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
  367. /// is provided, the integer induction variable will first be truncated to
  368. /// the corresponding type.
  369. void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
  370. /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
  371. /// vector or scalar value on-demand if one is not yet available. When
  372. /// vectorizing a loop, we visit the definition of an instruction before its
  373. /// uses. When visiting the definition, we either vectorize or scalarize the
  374. /// instruction, creating an entry for it in the corresponding map. (In some
  375. /// cases, such as induction variables, we will create both vector and scalar
  376. /// entries.) Then, as we encounter uses of the definition, we derive values
  377. /// for each scalar or vector use unless such a value is already available.
  378. /// For example, if we scalarize a definition and one of its uses is vector,
  379. /// we build the required vector on-demand with an insertelement sequence
  380. /// when visiting the use. Otherwise, if the use is scalar, we can use the
  381. /// existing scalar definition.
  382. ///
  383. /// Return a value in the new loop corresponding to \p V from the original
  384. /// loop at unroll index \p Part. If the value has already been vectorized,
  385. /// the corresponding vector entry in VectorLoopValueMap is returned. If,
  386. /// however, the value has a scalar entry in VectorLoopValueMap, we construct
  387. /// a new vector value on-demand by inserting the scalar values into a vector
  388. /// with an insertelement sequence. If the value has been neither vectorized
  389. /// nor scalarized, it must be loop invariant, so we simply broadcast the
  390. /// value into a vector.
  391. Value *getOrCreateVectorValue(Value *V, unsigned Part);
  392. /// Return a value in the new loop corresponding to \p V from the original
  393. /// loop at unroll and vector indices \p Instance. If the value has been
  394. /// vectorized but not scalarized, the necessary extractelement instruction
  395. /// will be generated.
  396. Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
  397. /// Construct the vector value of a scalarized value \p V one lane at a time.
  398. void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
  399. /// Try to vectorize the interleaved access group that \p Instr belongs to,
  400. /// optionally masking the vector operations if \p BlockInMask is non-null.
  401. void vectorizeInterleaveGroup(Instruction *Instr,
  402. VectorParts *BlockInMask = nullptr);
  403. /// Vectorize Load and Store instructions, optionally masking the vector
  404. /// operations if \p BlockInMask is non-null.
  405. void vectorizeMemoryInstruction(Instruction *Instr,
  406. VectorParts *BlockInMask = nullptr);
  407. /// Set the debug location in the builder using the debug location in
  408. /// the instruction.
  409. void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
  410. /// Fix the non-induction PHIs in the OrigPHIsToFix vector.
  411. void fixNonInductionPHIs(void);
  412. protected:
  413. friend class LoopVectorizationPlanner;
  414. /// A small list of PHINodes.
  415. using PhiVector = SmallVector<PHINode *, 4>;
  416. /// A type for scalarized values in the new loop. Each value from the
  417. /// original loop, when scalarized, is represented by UF x VF scalar values
  418. /// in the new unrolled loop, where UF is the unroll factor and VF is the
  419. /// vectorization factor.
  420. using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
  421. /// Set up the values of the IVs correctly when exiting the vector loop.
  422. void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
  423. Value *CountRoundDown, Value *EndValue,
  424. BasicBlock *MiddleBlock);
  425. /// Create a new induction variable inside L.
  426. PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
  427. Value *Step, Instruction *DL);
  428. /// Handle all cross-iteration phis in the header.
  429. void fixCrossIterationPHIs();
  430. /// Fix a first-order recurrence. This is the second phase of vectorizing
  431. /// this phi node.
  432. void fixFirstOrderRecurrence(PHINode *Phi);
  433. /// Fix a reduction cross-iteration phi. This is the second phase of
  434. /// vectorizing this phi node.
  435. void fixReduction(PHINode *Phi);
  436. /// The Loop exit block may have single value PHI nodes with some
  437. /// incoming value. While vectorizing we only handled real values
  438. /// that were defined inside the loop and we should have one value for
  439. /// each predecessor of its parent basic block. See PR14725.
  440. void fixLCSSAPHIs();
  441. /// Iteratively sink the scalarized operands of a predicated instruction into
  442. /// the block that was created for it.
  443. void sinkScalarOperands(Instruction *PredInst);
  444. /// Shrinks vector element sizes to the smallest bitwidth they can be legally
  445. /// represented as.
  446. void truncateToMinimalBitwidths();
  447. /// Insert the new loop to the loop hierarchy and pass manager
  448. /// and update the analysis passes.
  449. void updateAnalysis();
  450. /// Create a broadcast instruction. This method generates a broadcast
  451. /// instruction (shuffle) for loop invariant values and for the induction
  452. /// value. If this is the induction variable then we extend it to N, N+1, ...
  453. /// this is needed because each iteration in the loop corresponds to a SIMD
  454. /// element.
  455. virtual Value *getBroadcastInstrs(Value *V);
  456. /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
  457. /// to each vector element of Val. The sequence starts at StartIndex.
  458. /// \p Opcode is relevant for FP induction variable.
  459. virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  460. Instruction::BinaryOps Opcode =
  461. Instruction::BinaryOpsEnd);
  462. /// Compute scalar induction steps. \p ScalarIV is the scalar induction
  463. /// variable on which to base the steps, \p Step is the size of the step, and
  464. /// \p EntryVal is the value from the original loop that maps to the steps.
  465. /// Note that \p EntryVal doesn't have to be an induction variable - it
  466. /// can also be a truncate instruction.
  467. void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
  468. const InductionDescriptor &ID);
  469. /// Create a vector induction phi node based on an existing scalar one. \p
  470. /// EntryVal is the value from the original loop that maps to the vector phi
  471. /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
  472. /// truncate instruction, instead of widening the original IV, we widen a
  473. /// version of the IV truncated to \p EntryVal's type.
  474. void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
  475. Value *Step, Instruction *EntryVal);
  476. /// Returns true if an instruction \p I should be scalarized instead of
  477. /// vectorized for the chosen vectorization factor.
  478. bool shouldScalarizeInstruction(Instruction *I) const;
  479. /// Returns true if we should generate a scalar version of \p IV.
  480. bool needsScalarInduction(Instruction *IV) const;
  481. /// If there is a cast involved in the induction variable \p ID, which should
  482. /// be ignored in the vectorized loop body, this function records the
  483. /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
  484. /// cast. We had already proved that the casted Phi is equal to the uncasted
  485. /// Phi in the vectorized loop (under a runtime guard), and therefore
  486. /// there is no need to vectorize the cast - the same value can be used in the
  487. /// vector loop for both the Phi and the cast.
  488. /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
  489. /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
  490. ///
  491. /// \p EntryVal is the value from the original loop that maps to the vector
  492. /// phi node and is used to distinguish what is the IV currently being
  493. /// processed - original one (if \p EntryVal is a phi corresponding to the
  494. /// original IV) or the "newly-created" one based on the proof mentioned above
  495. /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
  496. /// latter case \p EntryVal is a TruncInst and we must not record anything for
  497. /// that IV, but it's error-prone to expect callers of this routine to care
  498. /// about that, hence this explicit parameter.
  499. void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID,
  500. const Instruction *EntryVal,
  501. Value *VectorLoopValue,
  502. unsigned Part,
  503. unsigned Lane = UINT_MAX);
  504. /// Generate a shuffle sequence that will reverse the vector Vec.
  505. virtual Value *reverseVector(Value *Vec);
  506. /// Returns (and creates if needed) the original loop trip count.
  507. Value *getOrCreateTripCount(Loop *NewLoop);
  508. /// Returns (and creates if needed) the trip count of the widened loop.
  509. Value *getOrCreateVectorTripCount(Loop *NewLoop);
  510. /// Returns a bitcasted value to the requested vector type.
  511. /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
  512. Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
  513. const DataLayout &DL);
  514. /// Emit a bypass check to see if the vector trip count is zero, including if
  515. /// it overflows.
  516. void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
  517. /// Emit a bypass check to see if all of the SCEV assumptions we've
  518. /// had to make are correct.
  519. void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
  520. /// Emit bypass checks to check any memory assumptions we may have made.
  521. void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
  522. /// Compute the transformed value of Index at offset StartValue using step
  523. /// StepValue.
  524. /// For integer induction, returns StartValue + Index * StepValue.
  525. /// For pointer induction, returns StartValue[Index * StepValue].
  526. /// FIXME: The newly created binary instructions should contain nsw/nuw
  527. /// flags, which can be found from the original scalar operations.
  528. Value *emitTransformedIndex(IRBuilder<> &B, Value *Index, ScalarEvolution *SE,
  529. const DataLayout &DL,
  530. const InductionDescriptor &ID) const;
  531. /// Add additional metadata to \p To that was not present on \p Orig.
  532. ///
  533. /// Currently this is used to add the noalias annotations based on the
  534. /// inserted memchecks. Use this for instructions that are *cloned* into the
  535. /// vector loop.
  536. void addNewMetadata(Instruction *To, const Instruction *Orig);
  537. /// Add metadata from one instruction to another.
  538. ///
  539. /// This includes both the original MDs from \p From and additional ones (\see
  540. /// addNewMetadata). Use this for *newly created* instructions in the vector
  541. /// loop.
  542. void addMetadata(Instruction *To, Instruction *From);
  543. /// Similar to the previous function but it adds the metadata to a
  544. /// vector of instructions.
  545. void addMetadata(ArrayRef<Value *> To, Instruction *From);
  546. /// The original loop.
  547. Loop *OrigLoop;
  548. /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
  549. /// dynamic knowledge to simplify SCEV expressions and converts them to a
  550. /// more usable form.
  551. PredicatedScalarEvolution &PSE;
  552. /// Loop Info.
  553. LoopInfo *LI;
  554. /// Dominator Tree.
  555. DominatorTree *DT;
  556. /// Alias Analysis.
  557. AliasAnalysis *AA;
  558. /// Target Library Info.
  559. const TargetLibraryInfo *TLI;
  560. /// Target Transform Info.
  561. const TargetTransformInfo *TTI;
  562. /// Assumption Cache.
  563. AssumptionCache *AC;
  564. /// Interface to emit optimization remarks.
  565. OptimizationRemarkEmitter *ORE;
  566. /// LoopVersioning. It's only set up (non-null) if memchecks were
  567. /// used.
  568. ///
  569. /// This is currently only used to add no-alias metadata based on the
  570. /// memchecks. The actually versioning is performed manually.
  571. std::unique_ptr<LoopVersioning> LVer;
  572. /// The vectorization SIMD factor to use. Each vector will have this many
  573. /// vector elements.
  574. unsigned VF;
  575. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  576. /// many different vector instructions.
  577. unsigned UF;
  578. /// The builder that we use
  579. IRBuilder<> Builder;
  580. // --- Vectorization state ---
  581. /// The vector-loop preheader.
  582. BasicBlock *LoopVectorPreHeader;
  583. /// The scalar-loop preheader.
  584. BasicBlock *LoopScalarPreHeader;
  585. /// Middle Block between the vector and the scalar.
  586. BasicBlock *LoopMiddleBlock;
  587. /// The ExitBlock of the scalar loop.
  588. BasicBlock *LoopExitBlock;
  589. /// The vector loop body.
  590. BasicBlock *LoopVectorBody;
  591. /// The scalar loop body.
  592. BasicBlock *LoopScalarBody;
  593. /// A list of all bypass blocks. The first block is the entry of the loop.
  594. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  595. /// The new Induction variable which was added to the new block.
  596. PHINode *Induction = nullptr;
  597. /// The induction variable of the old basic block.
  598. PHINode *OldInduction = nullptr;
  599. /// Maps values from the original loop to their corresponding values in the
  600. /// vectorized loop. A key value can map to either vector values, scalar
  601. /// values or both kinds of values, depending on whether the key was
  602. /// vectorized and scalarized.
  603. VectorizerValueMap VectorLoopValueMap;
  604. /// Store instructions that were predicated.
  605. SmallVector<Instruction *, 4> PredicatedInstructions;
  606. /// Trip count of the original loop.
  607. Value *TripCount = nullptr;
  608. /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
  609. Value *VectorTripCount = nullptr;
  610. /// The legality analysis.
  611. LoopVectorizationLegality *Legal;
  612. /// The profitablity analysis.
  613. LoopVectorizationCostModel *Cost;
  614. // Record whether runtime checks are added.
  615. bool AddedSafetyChecks = false;
  616. // Holds the end values for each induction variable. We save the end values
  617. // so we can later fix-up the external users of the induction variables.
  618. DenseMap<PHINode *, Value *> IVEndValues;
  619. // Vector of original scalar PHIs whose corresponding widened PHIs need to be
  620. // fixed up at the end of vector code generation.
  621. SmallVector<PHINode *, 8> OrigPHIsToFix;
  622. };
  623. class InnerLoopUnroller : public InnerLoopVectorizer {
  624. public:
  625. InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  626. LoopInfo *LI, DominatorTree *DT,
  627. const TargetLibraryInfo *TLI,
  628. const TargetTransformInfo *TTI, AssumptionCache *AC,
  629. OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
  630. LoopVectorizationLegality *LVL,
  631. LoopVectorizationCostModel *CM)
  632. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
  633. UnrollFactor, LVL, CM) {}
  634. private:
  635. Value *getBroadcastInstrs(Value *V) override;
  636. Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  637. Instruction::BinaryOps Opcode =
  638. Instruction::BinaryOpsEnd) override;
  639. Value *reverseVector(Value *Vec) override;
  640. };
  641. } // end namespace llvm
  642. /// Look for a meaningful debug location on the instruction or it's
  643. /// operands.
  644. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  645. if (!I)
  646. return I;
  647. DebugLoc Empty;
  648. if (I->getDebugLoc() != Empty)
  649. return I;
  650. for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
  651. if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
  652. if (OpInst->getDebugLoc() != Empty)
  653. return OpInst;
  654. }
  655. return I;
  656. }
  657. void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
  658. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
  659. const DILocation *DIL = Inst->getDebugLoc();
  660. if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
  661. !isa<DbgInfoIntrinsic>(Inst)) {
  662. auto NewDIL = DIL->cloneByMultiplyingDuplicationFactor(UF * VF);
  663. if (NewDIL)
  664. B.SetCurrentDebugLocation(NewDIL.getValue());
  665. else
  666. LLVM_DEBUG(dbgs()
  667. << "Failed to create new discriminator: "
  668. << DIL->getFilename() << " Line: " << DIL->getLine());
  669. }
  670. else
  671. B.SetCurrentDebugLocation(DIL);
  672. } else
  673. B.SetCurrentDebugLocation(DebugLoc());
  674. }
  675. #ifndef NDEBUG
  676. /// \return string containing a file name and a line # for the given loop.
  677. static std::string getDebugLocString(const Loop *L) {
  678. std::string Result;
  679. if (L) {
  680. raw_string_ostream OS(Result);
  681. if (const DebugLoc LoopDbgLoc = L->getStartLoc())
  682. LoopDbgLoc.print(OS);
  683. else
  684. // Just print the module name.
  685. OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
  686. OS.flush();
  687. }
  688. return Result;
  689. }
  690. #endif
  691. void InnerLoopVectorizer::addNewMetadata(Instruction *To,
  692. const Instruction *Orig) {
  693. // If the loop was versioned with memchecks, add the corresponding no-alias
  694. // metadata.
  695. if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
  696. LVer->annotateInstWithNoAlias(To, Orig);
  697. }
  698. void InnerLoopVectorizer::addMetadata(Instruction *To,
  699. Instruction *From) {
  700. propagateMetadata(To, From);
  701. addNewMetadata(To, From);
  702. }
  703. void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
  704. Instruction *From) {
  705. for (Value *V : To) {
  706. if (Instruction *I = dyn_cast<Instruction>(V))
  707. addMetadata(I, From);
  708. }
  709. }
  710. namespace llvm {
  711. /// LoopVectorizationCostModel - estimates the expected speedups due to
  712. /// vectorization.
  713. /// In many cases vectorization is not profitable. This can happen because of
  714. /// a number of reasons. In this class we mainly attempt to predict the
  715. /// expected speedup/slowdowns due to the supported instruction set. We use the
  716. /// TargetTransformInfo to query the different backends for the cost of
  717. /// different operations.
  718. class LoopVectorizationCostModel {
  719. public:
  720. LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
  721. LoopInfo *LI, LoopVectorizationLegality *Legal,
  722. const TargetTransformInfo &TTI,
  723. const TargetLibraryInfo *TLI, DemandedBits *DB,
  724. AssumptionCache *AC,
  725. OptimizationRemarkEmitter *ORE, const Function *F,
  726. const LoopVectorizeHints *Hints,
  727. InterleavedAccessInfo &IAI)
  728. : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
  729. AC(AC), ORE(ORE), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {}
  730. /// \return An upper bound for the vectorization factor, or None if
  731. /// vectorization and interleaving should be avoided up front.
  732. Optional<unsigned> computeMaxVF(bool OptForSize);
  733. /// \return The most profitable vectorization factor and the cost of that VF.
  734. /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
  735. /// then this vectorization factor will be selected if vectorization is
  736. /// possible.
  737. VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
  738. /// Setup cost-based decisions for user vectorization factor.
  739. void selectUserVectorizationFactor(unsigned UserVF) {
  740. collectUniformsAndScalars(UserVF);
  741. collectInstsToScalarize(UserVF);
  742. }
  743. /// \return The size (in bits) of the smallest and widest types in the code
  744. /// that needs to be vectorized. We ignore values that remain scalar such as
  745. /// 64 bit loop indices.
  746. std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
  747. /// \return The desired interleave count.
  748. /// If interleave count has been specified by metadata it will be returned.
  749. /// Otherwise, the interleave count is computed and returned. VF and LoopCost
  750. /// are the selected vectorization factor and the cost of the selected VF.
  751. unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
  752. unsigned LoopCost);
  753. /// Memory access instruction may be vectorized in more than one way.
  754. /// Form of instruction after vectorization depends on cost.
  755. /// This function takes cost-based decisions for Load/Store instructions
  756. /// and collects them in a map. This decisions map is used for building
  757. /// the lists of loop-uniform and loop-scalar instructions.
  758. /// The calculated cost is saved with widening decision in order to
  759. /// avoid redundant calculations.
  760. void setCostBasedWideningDecision(unsigned VF);
  761. /// A struct that represents some properties of the register usage
  762. /// of a loop.
  763. struct RegisterUsage {
  764. /// Holds the number of loop invariant values that are used in the loop.
  765. unsigned LoopInvariantRegs;
  766. /// Holds the maximum number of concurrent live intervals in the loop.
  767. unsigned MaxLocalUsers;
  768. };
  769. /// \return Returns information about the register usages of the loop for the
  770. /// given vectorization factors.
  771. SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
  772. /// Collect values we want to ignore in the cost model.
  773. void collectValuesToIgnore();
  774. /// \returns The smallest bitwidth each instruction can be represented with.
  775. /// The vector equivalents of these instructions should be truncated to this
  776. /// type.
  777. const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
  778. return MinBWs;
  779. }
  780. /// \returns True if it is more profitable to scalarize instruction \p I for
  781. /// vectorization factor \p VF.
  782. bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
  783. assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.");
  784. // Cost model is not run in the VPlan-native path - return conservative
  785. // result until this changes.
  786. if (EnableVPlanNativePath)
  787. return false;
  788. auto Scalars = InstsToScalarize.find(VF);
  789. assert(Scalars != InstsToScalarize.end() &&
  790. "VF not yet analyzed for scalarization profitability");
  791. return Scalars->second.find(I) != Scalars->second.end();
  792. }
  793. /// Returns true if \p I is known to be uniform after vectorization.
  794. bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
  795. if (VF == 1)
  796. return true;
  797. // Cost model is not run in the VPlan-native path - return conservative
  798. // result until this changes.
  799. if (EnableVPlanNativePath)
  800. return false;
  801. auto UniformsPerVF = Uniforms.find(VF);
  802. assert(UniformsPerVF != Uniforms.end() &&
  803. "VF not yet analyzed for uniformity");
  804. return UniformsPerVF->second.find(I) != UniformsPerVF->second.end();
  805. }
  806. /// Returns true if \p I is known to be scalar after vectorization.
  807. bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
  808. if (VF == 1)
  809. return true;
  810. // Cost model is not run in the VPlan-native path - return conservative
  811. // result until this changes.
  812. if (EnableVPlanNativePath)
  813. return false;
  814. auto ScalarsPerVF = Scalars.find(VF);
  815. assert(ScalarsPerVF != Scalars.end() &&
  816. "Scalar values are not calculated for VF");
  817. return ScalarsPerVF->second.find(I) != ScalarsPerVF->second.end();
  818. }
  819. /// \returns True if instruction \p I can be truncated to a smaller bitwidth
  820. /// for vectorization factor \p VF.
  821. bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
  822. return VF > 1 && MinBWs.find(I) != MinBWs.end() &&
  823. !isProfitableToScalarize(I, VF) &&
  824. !isScalarAfterVectorization(I, VF);
  825. }
  826. /// Decision that was taken during cost calculation for memory instruction.
  827. enum InstWidening {
  828. CM_Unknown,
  829. CM_Widen, // For consecutive accesses with stride +1.
  830. CM_Widen_Reverse, // For consecutive accesses with stride -1.
  831. CM_Interleave,
  832. CM_GatherScatter,
  833. CM_Scalarize
  834. };
  835. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  836. /// instruction \p I and vector width \p VF.
  837. void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
  838. unsigned Cost) {
  839. assert(VF >= 2 && "Expected VF >=2");
  840. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  841. }
  842. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  843. /// interleaving group \p Grp and vector width \p VF.
  844. void setWideningDecision(const InterleaveGroup<Instruction> *Grp, unsigned VF,
  845. InstWidening W, unsigned Cost) {
  846. assert(VF >= 2 && "Expected VF >=2");
  847. /// Broadcast this decicion to all instructions inside the group.
  848. /// But the cost will be assigned to one instruction only.
  849. for (unsigned i = 0; i < Grp->getFactor(); ++i) {
  850. if (auto *I = Grp->getMember(i)) {
  851. if (Grp->getInsertPos() == I)
  852. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  853. else
  854. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
  855. }
  856. }
  857. }
  858. /// Return the cost model decision for the given instruction \p I and vector
  859. /// width \p VF. Return CM_Unknown if this instruction did not pass
  860. /// through the cost modeling.
  861. InstWidening getWideningDecision(Instruction *I, unsigned VF) {
  862. assert(VF >= 2 && "Expected VF >=2");
  863. // Cost model is not run in the VPlan-native path - return conservative
  864. // result until this changes.
  865. if (EnableVPlanNativePath)
  866. return CM_GatherScatter;
  867. std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
  868. auto Itr = WideningDecisions.find(InstOnVF);
  869. if (Itr == WideningDecisions.end())
  870. return CM_Unknown;
  871. return Itr->second.first;
  872. }
  873. /// Return the vectorization cost for the given instruction \p I and vector
  874. /// width \p VF.
  875. unsigned getWideningCost(Instruction *I, unsigned VF) {
  876. assert(VF >= 2 && "Expected VF >=2");
  877. std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
  878. assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
  879. "The cost is not calculated");
  880. return WideningDecisions[InstOnVF].second;
  881. }
  882. /// Return True if instruction \p I is an optimizable truncate whose operand
  883. /// is an induction variable. Such a truncate will be removed by adding a new
  884. /// induction variable with the destination type.
  885. bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
  886. // If the instruction is not a truncate, return false.
  887. auto *Trunc = dyn_cast<TruncInst>(I);
  888. if (!Trunc)
  889. return false;
  890. // Get the source and destination types of the truncate.
  891. Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
  892. Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
  893. // If the truncate is free for the given types, return false. Replacing a
  894. // free truncate with an induction variable would add an induction variable
  895. // update instruction to each iteration of the loop. We exclude from this
  896. // check the primary induction variable since it will need an update
  897. // instruction regardless.
  898. Value *Op = Trunc->getOperand(0);
  899. if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
  900. return false;
  901. // If the truncated value is not an induction variable, return false.
  902. return Legal->isInductionPhi(Op);
  903. }
  904. /// Collects the instructions to scalarize for each predicated instruction in
  905. /// the loop.
  906. void collectInstsToScalarize(unsigned VF);
  907. /// Collect Uniform and Scalar values for the given \p VF.
  908. /// The sets depend on CM decision for Load/Store instructions
  909. /// that may be vectorized as interleave, gather-scatter or scalarized.
  910. void collectUniformsAndScalars(unsigned VF) {
  911. // Do the analysis once.
  912. if (VF == 1 || Uniforms.find(VF) != Uniforms.end())
  913. return;
  914. setCostBasedWideningDecision(VF);
  915. collectLoopUniforms(VF);
  916. collectLoopScalars(VF);
  917. }
  918. /// Returns true if the target machine supports masked store operation
  919. /// for the given \p DataType and kind of access to \p Ptr.
  920. bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
  921. return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType);
  922. }
  923. /// Returns true if the target machine supports masked load operation
  924. /// for the given \p DataType and kind of access to \p Ptr.
  925. bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
  926. return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType);
  927. }
  928. /// Returns true if the target machine supports masked scatter operation
  929. /// for the given \p DataType.
  930. bool isLegalMaskedScatter(Type *DataType) {
  931. return TTI.isLegalMaskedScatter(DataType);
  932. }
  933. /// Returns true if the target machine supports masked gather operation
  934. /// for the given \p DataType.
  935. bool isLegalMaskedGather(Type *DataType) {
  936. return TTI.isLegalMaskedGather(DataType);
  937. }
  938. /// Returns true if the target machine can represent \p V as a masked gather
  939. /// or scatter operation.
  940. bool isLegalGatherOrScatter(Value *V) {
  941. bool LI = isa<LoadInst>(V);
  942. bool SI = isa<StoreInst>(V);
  943. if (!LI && !SI)
  944. return false;
  945. auto *Ty = getMemInstValueType(V);
  946. return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
  947. }
  948. /// Returns true if \p I is an instruction that will be scalarized with
  949. /// predication. Such instructions include conditional stores and
  950. /// instructions that may divide by zero.
  951. /// If a non-zero VF has been calculated, we check if I will be scalarized
  952. /// predication for that VF.
  953. bool isScalarWithPredication(Instruction *I, unsigned VF = 1);
  954. // Returns true if \p I is an instruction that will be predicated either
  955. // through scalar predication or masked load/store or masked gather/scatter.
  956. // Superset of instructions that return true for isScalarWithPredication.
  957. bool isPredicatedInst(Instruction *I) {
  958. if (!blockNeedsPredication(I->getParent()))
  959. return false;
  960. // Loads and stores that need some form of masked operation are predicated
  961. // instructions.
  962. if (isa<LoadInst>(I) || isa<StoreInst>(I))
  963. return Legal->isMaskRequired(I);
  964. return isScalarWithPredication(I);
  965. }
  966. /// Returns true if \p I is a memory instruction with consecutive memory
  967. /// access that can be widened.
  968. bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
  969. /// Returns true if \p I is a memory instruction in an interleaved-group
  970. /// of memory accesses that can be vectorized with wide vector loads/stores
  971. /// and shuffles.
  972. bool interleavedAccessCanBeWidened(Instruction *I, unsigned VF = 1);
  973. /// Check if \p Instr belongs to any interleaved access group.
  974. bool isAccessInterleaved(Instruction *Instr) {
  975. return InterleaveInfo.isInterleaved(Instr);
  976. }
  977. /// Get the interleaved access group that \p Instr belongs to.
  978. const InterleaveGroup<Instruction> *
  979. getInterleavedAccessGroup(Instruction *Instr) {
  980. return InterleaveInfo.getInterleaveGroup(Instr);
  981. }
  982. /// Returns true if an interleaved group requires a scalar iteration
  983. /// to handle accesses with gaps, and there is nothing preventing us from
  984. /// creating a scalar epilogue.
  985. bool requiresScalarEpilogue() const {
  986. return IsScalarEpilogueAllowed && InterleaveInfo.requiresScalarEpilogue();
  987. }
  988. /// Returns true if a scalar epilogue is not allowed due to optsize.
  989. bool isScalarEpilogueAllowed() const { return IsScalarEpilogueAllowed; }
  990. /// Returns true if all loop blocks should be masked to fold tail loop.
  991. bool foldTailByMasking() const { return FoldTailByMasking; }
  992. bool blockNeedsPredication(BasicBlock *BB) {
  993. return foldTailByMasking() || Legal->blockNeedsPredication(BB);
  994. }
  995. private:
  996. unsigned NumPredStores = 0;
  997. /// \return An upper bound for the vectorization factor, larger than zero.
  998. /// One is returned if vectorization should best be avoided due to cost.
  999. unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
  1000. /// The vectorization cost is a combination of the cost itself and a boolean
  1001. /// indicating whether any of the contributing operations will actually
  1002. /// operate on
  1003. /// vector values after type legalization in the backend. If this latter value
  1004. /// is
  1005. /// false, then all operations will be scalarized (i.e. no vectorization has
  1006. /// actually taken place).
  1007. using VectorizationCostTy = std::pair<unsigned, bool>;
  1008. /// Returns the expected execution cost. The unit of the cost does
  1009. /// not matter because we use the 'cost' units to compare different
  1010. /// vector widths. The cost that is returned is *not* normalized by
  1011. /// the factor width.
  1012. VectorizationCostTy expectedCost(unsigned VF);
  1013. /// Returns the execution time cost of an instruction for a given vector
  1014. /// width. Vector width of one means scalar.
  1015. VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
  1016. /// The cost-computation logic from getInstructionCost which provides
  1017. /// the vector type as an output parameter.
  1018. unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
  1019. /// Calculate vectorization cost of memory instruction \p I.
  1020. unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
  1021. /// The cost computation for scalarized memory instruction.
  1022. unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
  1023. /// The cost computation for interleaving group of memory instructions.
  1024. unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
  1025. /// The cost computation for Gather/Scatter instruction.
  1026. unsigned getGatherScatterCost(Instruction *I, unsigned VF);
  1027. /// The cost computation for widening instruction \p I with consecutive
  1028. /// memory access.
  1029. unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
  1030. /// The cost calculation for Load/Store instruction \p I with uniform pointer -
  1031. /// Load: scalar load + broadcast.
  1032. /// Store: scalar store + (loop invariant value stored? 0 : extract of last
  1033. /// element)
  1034. unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
  1035. /// Returns whether the instruction is a load or store and will be a emitted
  1036. /// as a vector operation.
  1037. bool isConsecutiveLoadOrStore(Instruction *I);
  1038. /// Returns true if an artificially high cost for emulated masked memrefs
  1039. /// should be used.
  1040. bool useEmulatedMaskMemRefHack(Instruction *I);
  1041. /// Create an analysis remark that explains why vectorization failed
  1042. ///
  1043. /// \p RemarkName is the identifier for the remark. \return the remark object
  1044. /// that can be streamed to.
  1045. OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
  1046. return createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(),
  1047. RemarkName, TheLoop);
  1048. }
  1049. /// Map of scalar integer values to the smallest bitwidth they can be legally
  1050. /// represented as. The vector equivalents of these values should be truncated
  1051. /// to this type.
  1052. MapVector<Instruction *, uint64_t> MinBWs;
  1053. /// A type representing the costs for instructions if they were to be
  1054. /// scalarized rather than vectorized. The entries are Instruction-Cost
  1055. /// pairs.
  1056. using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
  1057. /// A set containing all BasicBlocks that are known to present after
  1058. /// vectorization as a predicated block.
  1059. SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
  1060. /// Records whether it is allowed to have the original scalar loop execute at
  1061. /// least once. This may be needed as a fallback loop in case runtime
  1062. /// aliasing/dependence checks fail, or to handle the tail/remainder
  1063. /// iterations when the trip count is unknown or doesn't divide by the VF,
  1064. /// or as a peel-loop to handle gaps in interleave-groups.
  1065. /// Under optsize and when the trip count is very small we don't allow any
  1066. /// iterations to execute in the scalar loop.
  1067. bool IsScalarEpilogueAllowed = true;
  1068. /// All blocks of loop are to be masked to fold tail of scalar iterations.
  1069. bool FoldTailByMasking = false;
  1070. /// A map holding scalar costs for different vectorization factors. The
  1071. /// presence of a cost for an instruction in the mapping indicates that the
  1072. /// instruction will be scalarized when vectorizing with the associated
  1073. /// vectorization factor. The entries are VF-ScalarCostTy pairs.
  1074. DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
  1075. /// Holds the instructions known to be uniform after vectorization.
  1076. /// The data is collected per VF.
  1077. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
  1078. /// Holds the instructions known to be scalar after vectorization.
  1079. /// The data is collected per VF.
  1080. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
  1081. /// Holds the instructions (address computations) that are forced to be
  1082. /// scalarized.
  1083. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
  1084. /// Returns the expected difference in cost from scalarizing the expression
  1085. /// feeding a predicated instruction \p PredInst. The instructions to
  1086. /// scalarize and their scalar costs are collected in \p ScalarCosts. A
  1087. /// non-negative return value implies the expression will be scalarized.
  1088. /// Currently, only single-use chains are considered for scalarization.
  1089. int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
  1090. unsigned VF);
  1091. /// Collect the instructions that are uniform after vectorization. An
  1092. /// instruction is uniform if we represent it with a single scalar value in
  1093. /// the vectorized loop corresponding to each vector iteration. Examples of
  1094. /// uniform instructions include pointer operands of consecutive or
  1095. /// interleaved memory accesses. Note that although uniformity implies an
  1096. /// instruction will be scalar, the reverse is not true. In general, a
  1097. /// scalarized instruction will be represented by VF scalar values in the
  1098. /// vectorized loop, each corresponding to an iteration of the original
  1099. /// scalar loop.
  1100. void collectLoopUniforms(unsigned VF);
  1101. /// Collect the instructions that are scalar after vectorization. An
  1102. /// instruction is scalar if it is known to be uniform or will be scalarized
  1103. /// during vectorization. Non-uniform scalarized instructions will be
  1104. /// represented by VF values in the vectorized loop, each corresponding to an
  1105. /// iteration of the original scalar loop.
  1106. void collectLoopScalars(unsigned VF);
  1107. /// Keeps cost model vectorization decision and cost for instructions.
  1108. /// Right now it is used for memory instructions only.
  1109. using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
  1110. std::pair<InstWidening, unsigned>>;
  1111. DecisionList WideningDecisions;
  1112. public:
  1113. /// The loop that we evaluate.
  1114. Loop *TheLoop;
  1115. /// Predicated scalar evolution analysis.
  1116. PredicatedScalarEvolution &PSE;
  1117. /// Loop Info analysis.
  1118. LoopInfo *LI;
  1119. /// Vectorization legality.
  1120. LoopVectorizationLegality *Legal;
  1121. /// Vector target information.
  1122. const TargetTransformInfo &TTI;
  1123. /// Target Library Info.
  1124. const TargetLibraryInfo *TLI;
  1125. /// Demanded bits analysis.
  1126. DemandedBits *DB;
  1127. /// Assumption cache.
  1128. AssumptionCache *AC;
  1129. /// Interface to emit optimization remarks.
  1130. OptimizationRemarkEmitter *ORE;
  1131. const Function *TheFunction;
  1132. /// Loop Vectorize Hint.
  1133. const LoopVectorizeHints *Hints;
  1134. /// The interleave access information contains groups of interleaved accesses
  1135. /// with the same stride and close to each other.
  1136. InterleavedAccessInfo &InterleaveInfo;
  1137. /// Values to ignore in the cost model.
  1138. SmallPtrSet<const Value *, 16> ValuesToIgnore;
  1139. /// Values to ignore in the cost model when VF > 1.
  1140. SmallPtrSet<const Value *, 16> VecValuesToIgnore;
  1141. };
  1142. } // end namespace llvm
  1143. // Return true if \p OuterLp is an outer loop annotated with hints for explicit
  1144. // vectorization. The loop needs to be annotated with #pragma omp simd
  1145. // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
  1146. // vector length information is not provided, vectorization is not considered
  1147. // explicit. Interleave hints are not allowed either. These limitations will be
  1148. // relaxed in the future.
  1149. // Please, note that we are currently forced to abuse the pragma 'clang
  1150. // vectorize' semantics. This pragma provides *auto-vectorization hints*
  1151. // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
  1152. // provides *explicit vectorization hints* (LV can bypass legal checks and
  1153. // assume that vectorization is legal). However, both hints are implemented
  1154. // using the same metadata (llvm.loop.vectorize, processed by
  1155. // LoopVectorizeHints). This will be fixed in the future when the native IR
  1156. // representation for pragma 'omp simd' is introduced.
  1157. static bool isExplicitVecOuterLoop(Loop *OuterLp,
  1158. OptimizationRemarkEmitter *ORE) {
  1159. assert(!OuterLp->empty() && "This is not an outer loop");
  1160. LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
  1161. // Only outer loops with an explicit vectorization hint are supported.
  1162. // Unannotated outer loops are ignored.
  1163. if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
  1164. return false;
  1165. Function *Fn = OuterLp->getHeader()->getParent();
  1166. if (!Hints.allowVectorization(Fn, OuterLp,
  1167. true /*VectorizeOnlyWhenForced*/)) {
  1168. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
  1169. return false;
  1170. }
  1171. if (Hints.getInterleave() > 1) {
  1172. // TODO: Interleave support is future work.
  1173. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
  1174. "outer loops.\n");
  1175. Hints.emitRemarkWithHints();
  1176. return false;
  1177. }
  1178. return true;
  1179. }
  1180. static void collectSupportedLoops(Loop &L, LoopInfo *LI,
  1181. OptimizationRemarkEmitter *ORE,
  1182. SmallVectorImpl<Loop *> &V) {
  1183. // Collect inner loops and outer loops without irreducible control flow. For
  1184. // now, only collect outer loops that have explicit vectorization hints. If we
  1185. // are stress testing the VPlan H-CFG construction, we collect the outermost
  1186. // loop of every loop nest.
  1187. if (L.empty() || VPlanBuildStressTest ||
  1188. (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
  1189. LoopBlocksRPO RPOT(&L);
  1190. RPOT.perform(LI);
  1191. if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
  1192. V.push_back(&L);
  1193. // TODO: Collect inner loops inside marked outer loops in case
  1194. // vectorization fails for the outer loop. Do not invoke
  1195. // 'containsIrreducibleCFG' again for inner loops when the outer loop is
  1196. // already known to be reducible. We can use an inherited attribute for
  1197. // that.
  1198. return;
  1199. }
  1200. }
  1201. for (Loop *InnerL : L)
  1202. collectSupportedLoops(*InnerL, LI, ORE, V);
  1203. }
  1204. namespace {
  1205. /// The LoopVectorize Pass.
  1206. struct LoopVectorize : public FunctionPass {
  1207. /// Pass identification, replacement for typeid
  1208. static char ID;
  1209. LoopVectorizePass Impl;
  1210. explicit LoopVectorize(bool InterleaveOnlyWhenForced = false,
  1211. bool VectorizeOnlyWhenForced = false)
  1212. : FunctionPass(ID) {
  1213. Impl.InterleaveOnlyWhenForced = InterleaveOnlyWhenForced;
  1214. Impl.VectorizeOnlyWhenForced = VectorizeOnlyWhenForced;
  1215. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  1216. }
  1217. bool runOnFunction(Function &F) override {
  1218. if (skipFunction(F))
  1219. return false;
  1220. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1221. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1222. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1223. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1224. auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
  1225. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1226. auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
  1227. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1228. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1229. auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
  1230. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  1231. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  1232. auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  1233. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  1234. [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
  1235. return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
  1236. GetLAA, *ORE, PSI);
  1237. }
  1238. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1239. AU.addRequired<AssumptionCacheTracker>();
  1240. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  1241. AU.addRequired<DominatorTreeWrapperPass>();
  1242. AU.addRequired<LoopInfoWrapperPass>();
  1243. AU.addRequired<ScalarEvolutionWrapperPass>();
  1244. AU.addRequired<TargetTransformInfoWrapperPass>();
  1245. AU.addRequired<AAResultsWrapperPass>();
  1246. AU.addRequired<LoopAccessLegacyAnalysis>();
  1247. AU.addRequired<DemandedBitsWrapperPass>();
  1248. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  1249. // We currently do not preserve loopinfo/dominator analyses with outer loop
  1250. // vectorization. Until this is addressed, mark these analyses as preserved
  1251. // only for non-VPlan-native path.
  1252. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  1253. if (!EnableVPlanNativePath) {
  1254. AU.addPreserved<LoopInfoWrapperPass>();
  1255. AU.addPreserved<DominatorTreeWrapperPass>();
  1256. }
  1257. AU.addPreserved<BasicAAWrapperPass>();
  1258. AU.addPreserved<GlobalsAAWrapperPass>();
  1259. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  1260. }
  1261. };
  1262. } // end anonymous namespace
  1263. //===----------------------------------------------------------------------===//
  1264. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  1265. // LoopVectorizationCostModel and LoopVectorizationPlanner.
  1266. //===----------------------------------------------------------------------===//
  1267. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  1268. // We need to place the broadcast of invariant variables outside the loop,
  1269. // but only if it's proven safe to do so. Else, broadcast will be inside
  1270. // vector loop body.
  1271. Instruction *Instr = dyn_cast<Instruction>(V);
  1272. bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
  1273. (!Instr ||
  1274. DT->dominates(Instr->getParent(), LoopVectorPreHeader));
  1275. // Place the code for broadcasting invariant variables in the new preheader.
  1276. IRBuilder<>::InsertPointGuard Guard(Builder);
  1277. if (SafeToHoist)
  1278. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1279. // Broadcast the scalar into all locations in the vector.
  1280. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  1281. return Shuf;
  1282. }
  1283. void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
  1284. const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
  1285. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1286. "Expected either an induction phi-node or a truncate of it!");
  1287. Value *Start = II.getStartValue();
  1288. // Construct the initial value of the vector IV in the vector loop preheader
  1289. auto CurrIP = Builder.saveIP();
  1290. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1291. if (isa<TruncInst>(EntryVal)) {
  1292. assert(Start->getType()->isIntegerTy() &&
  1293. "Truncation requires an integer type");
  1294. auto *TruncType = cast<IntegerType>(EntryVal->getType());
  1295. Step = Builder.CreateTrunc(Step, TruncType);
  1296. Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
  1297. }
  1298. Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
  1299. Value *SteppedStart =
  1300. getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
  1301. // We create vector phi nodes for both integer and floating-point induction
  1302. // variables. Here, we determine the kind of arithmetic we will perform.
  1303. Instruction::BinaryOps AddOp;
  1304. Instruction::BinaryOps MulOp;
  1305. if (Step->getType()->isIntegerTy()) {
  1306. AddOp = Instruction::Add;
  1307. MulOp = Instruction::Mul;
  1308. } else {
  1309. AddOp = II.getInductionOpcode();
  1310. MulOp = Instruction::FMul;
  1311. }
  1312. // Multiply the vectorization factor by the step using integer or
  1313. // floating-point arithmetic as appropriate.
  1314. Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
  1315. Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
  1316. // Create a vector splat to use in the induction update.
  1317. //
  1318. // FIXME: If the step is non-constant, we create the vector splat with
  1319. // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
  1320. // handle a constant vector splat.
  1321. Value *SplatVF = isa<Constant>(Mul)
  1322. ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
  1323. : Builder.CreateVectorSplat(VF, Mul);
  1324. Builder.restoreIP(CurrIP);
  1325. // We may need to add the step a number of times, depending on the unroll
  1326. // factor. The last of those goes into the PHI.
  1327. PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
  1328. &*LoopVectorBody->getFirstInsertionPt());
  1329. VecInd->setDebugLoc(EntryVal->getDebugLoc());
  1330. Instruction *LastInduction = VecInd;
  1331. for (unsigned Part = 0; Part < UF; ++Part) {
  1332. VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
  1333. if (isa<TruncInst>(EntryVal))
  1334. addMetadata(LastInduction, EntryVal);
  1335. recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
  1336. LastInduction = cast<Instruction>(addFastMathFlag(
  1337. Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
  1338. LastInduction->setDebugLoc(EntryVal->getDebugLoc());
  1339. }
  1340. // Move the last step to the end of the latch block. This ensures consistent
  1341. // placement of all induction updates.
  1342. auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
  1343. auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
  1344. auto *ICmp = cast<Instruction>(Br->getCondition());
  1345. LastInduction->moveBefore(ICmp);
  1346. LastInduction->setName("vec.ind.next");
  1347. VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
  1348. VecInd->addIncoming(LastInduction, LoopVectorLatch);
  1349. }
  1350. bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
  1351. return Cost->isScalarAfterVectorization(I, VF) ||
  1352. Cost->isProfitableToScalarize(I, VF);
  1353. }
  1354. bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
  1355. if (shouldScalarizeInstruction(IV))
  1356. return true;
  1357. auto isScalarInst = [&](User *U) -> bool {
  1358. auto *I = cast<Instruction>(U);
  1359. return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
  1360. };
  1361. return llvm::any_of(IV->users(), isScalarInst);
  1362. }
  1363. void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
  1364. const InductionDescriptor &ID, const Instruction *EntryVal,
  1365. Value *VectorLoopVal, unsigned Part, unsigned Lane) {
  1366. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1367. "Expected either an induction phi-node or a truncate of it!");
  1368. // This induction variable is not the phi from the original loop but the
  1369. // newly-created IV based on the proof that casted Phi is equal to the
  1370. // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
  1371. // re-uses the same InductionDescriptor that original IV uses but we don't
  1372. // have to do any recording in this case - that is done when original IV is
  1373. // processed.
  1374. if (isa<TruncInst>(EntryVal))
  1375. return;
  1376. const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
  1377. if (Casts.empty())
  1378. return;
  1379. // Only the first Cast instruction in the Casts vector is of interest.
  1380. // The rest of the Casts (if exist) have no uses outside the
  1381. // induction update chain itself.
  1382. Instruction *CastInst = *Casts.begin();
  1383. if (Lane < UINT_MAX)
  1384. VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
  1385. else
  1386. VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
  1387. }
  1388. void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
  1389. assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
  1390. "Primary induction variable must have an integer type");
  1391. auto II = Legal->getInductionVars()->find(IV);
  1392. assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
  1393. auto ID = II->second;
  1394. assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
  1395. // The scalar value to broadcast. This will be derived from the canonical
  1396. // induction variable.
  1397. Value *ScalarIV = nullptr;
  1398. // The value from the original loop to which we are mapping the new induction
  1399. // variable.
  1400. Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
  1401. // True if we have vectorized the induction variable.
  1402. auto VectorizedIV = false;
  1403. // Determine if we want a scalar version of the induction variable. This is
  1404. // true if the induction variable itself is not widened, or if it has at
  1405. // least one user in the loop that is not widened.
  1406. auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
  1407. // Generate code for the induction step. Note that induction steps are
  1408. // required to be loop-invariant
  1409. assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
  1410. "Induction step should be loop invariant");
  1411. auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  1412. Value *Step = nullptr;
  1413. if (PSE.getSE()->isSCEVable(IV->getType())) {
  1414. SCEVExpander Exp(*PSE.getSE(), DL, "induction");
  1415. Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
  1416. LoopVectorPreHeader->getTerminator());
  1417. } else {
  1418. Step = cast<SCEVUnknown>(ID.getStep())->getValue();
  1419. }
  1420. // Try to create a new independent vector induction variable. If we can't
  1421. // create the phi node, we will splat the scalar induction variable in each
  1422. // loop iteration.
  1423. if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
  1424. createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
  1425. VectorizedIV = true;
  1426. }
  1427. // If we haven't yet vectorized the induction variable, or if we will create
  1428. // a scalar one, we need to define the scalar induction variable and step
  1429. // values. If we were given a truncation type, truncate the canonical
  1430. // induction variable and step. Otherwise, derive these values from the
  1431. // induction descriptor.
  1432. if (!VectorizedIV || NeedsScalarIV) {
  1433. ScalarIV = Induction;
  1434. if (IV != OldInduction) {
  1435. ScalarIV = IV->getType()->isIntegerTy()
  1436. ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
  1437. : Builder.CreateCast(Instruction::SIToFP, Induction,
  1438. IV->getType());
  1439. ScalarIV = emitTransformedIndex(Builder, ScalarIV, PSE.getSE(), DL, ID);
  1440. ScalarIV->setName("offset.idx");
  1441. }
  1442. if (Trunc) {
  1443. auto *TruncType = cast<IntegerType>(Trunc->getType());
  1444. assert(Step->getType()->isIntegerTy() &&
  1445. "Truncation requires an integer step");
  1446. ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
  1447. Step = Builder.CreateTrunc(Step, TruncType);
  1448. }
  1449. }
  1450. // If we haven't yet vectorized the induction variable, splat the scalar
  1451. // induction variable, and build the necessary step vectors.
  1452. // TODO: Don't do it unless the vectorized IV is really required.
  1453. if (!VectorizedIV) {
  1454. Value *Broadcasted = getBroadcastInstrs(ScalarIV);
  1455. for (unsigned Part = 0; Part < UF; ++Part) {
  1456. Value *EntryPart =
  1457. getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
  1458. VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
  1459. if (Trunc)
  1460. addMetadata(EntryPart, Trunc);
  1461. recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
  1462. }
  1463. }
  1464. // If an induction variable is only used for counting loop iterations or
  1465. // calculating addresses, it doesn't need to be widened. Create scalar steps
  1466. // that can be used by instructions we will later scalarize. Note that the
  1467. // addition of the scalar steps will not increase the number of instructions
  1468. // in the loop in the common case prior to InstCombine. We will be trading
  1469. // one vector extract for each scalar step.
  1470. if (NeedsScalarIV)
  1471. buildScalarSteps(ScalarIV, Step, EntryVal, ID);
  1472. }
  1473. Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
  1474. Instruction::BinaryOps BinOp) {
  1475. // Create and check the types.
  1476. assert(Val->getType()->isVectorTy() && "Must be a vector");
  1477. int VLen = Val->getType()->getVectorNumElements();
  1478. Type *STy = Val->getType()->getScalarType();
  1479. assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
  1480. "Induction Step must be an integer or FP");
  1481. assert(Step->getType() == STy && "Step has wrong type");
  1482. SmallVector<Constant *, 8> Indices;
  1483. if (STy->isIntegerTy()) {
  1484. // Create a vector of consecutive numbers from zero to VF.
  1485. for (int i = 0; i < VLen; ++i)
  1486. Indices.push_back(ConstantInt::get(STy, StartIdx + i));
  1487. // Add the consecutive indices to the vector value.
  1488. Constant *Cv = ConstantVector::get(Indices);
  1489. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  1490. Step = Builder.CreateVectorSplat(VLen, Step);
  1491. assert(Step->getType() == Val->getType() && "Invalid step vec");
  1492. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  1493. // which can be found from the original scalar operations.
  1494. Step = Builder.CreateMul(Cv, Step);
  1495. return Builder.CreateAdd(Val, Step, "induction");
  1496. }
  1497. // Floating point induction.
  1498. assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
  1499. "Binary Opcode should be specified for FP induction");
  1500. // Create a vector of consecutive numbers from zero to VF.
  1501. for (int i = 0; i < VLen; ++i)
  1502. Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
  1503. // Add the consecutive indices to the vector value.
  1504. Constant *Cv = ConstantVector::get(Indices);
  1505. Step = Builder.CreateVectorSplat(VLen, Step);
  1506. // Floating point operations had to be 'fast' to enable the induction.
  1507. FastMathFlags Flags;
  1508. Flags.setFast();
  1509. Value *MulOp = Builder.CreateFMul(Cv, Step);
  1510. if (isa<Instruction>(MulOp))
  1511. // Have to check, MulOp may be a constant
  1512. cast<Instruction>(MulOp)->setFastMathFlags(Flags);
  1513. Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
  1514. if (isa<Instruction>(BOp))
  1515. cast<Instruction>(BOp)->setFastMathFlags(Flags);
  1516. return BOp;
  1517. }
  1518. void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
  1519. Instruction *EntryVal,
  1520. const InductionDescriptor &ID) {
  1521. // We shouldn't have to build scalar steps if we aren't vectorizing.
  1522. assert(VF > 1 && "VF should be greater than one");
  1523. // Get the value type and ensure it and the step have the same integer type.
  1524. Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
  1525. assert(ScalarIVTy == Step->getType() &&
  1526. "Val and Step should have the same type");
  1527. // We build scalar steps for both integer and floating-point induction
  1528. // variables. Here, we determine the kind of arithmetic we will perform.
  1529. Instruction::BinaryOps AddOp;
  1530. Instruction::BinaryOps MulOp;
  1531. if (ScalarIVTy->isIntegerTy()) {
  1532. AddOp = Instruction::Add;
  1533. MulOp = Instruction::Mul;
  1534. } else {
  1535. AddOp = ID.getInductionOpcode();
  1536. MulOp = Instruction::FMul;
  1537. }
  1538. // Determine the number of scalars we need to generate for each unroll
  1539. // iteration. If EntryVal is uniform, we only need to generate the first
  1540. // lane. Otherwise, we generate all VF values.
  1541. unsigned Lanes =
  1542. Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
  1543. : VF;
  1544. // Compute the scalar steps and save the results in VectorLoopValueMap.
  1545. for (unsigned Part = 0; Part < UF; ++Part) {
  1546. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  1547. auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
  1548. auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
  1549. auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
  1550. VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
  1551. recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
  1552. }
  1553. }
  1554. }
  1555. Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
  1556. assert(V != Induction && "The new induction variable should not be used.");
  1557. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  1558. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  1559. // If we have a stride that is replaced by one, do it here. Defer this for
  1560. // the VPlan-native path until we start running Legal checks in that path.
  1561. if (!EnableVPlanNativePath && Legal->hasStride(V))
  1562. V = ConstantInt::get(V->getType(), 1);
  1563. // If we have a vector mapped to this value, return it.
  1564. if (VectorLoopValueMap.hasVectorValue(V, Part))
  1565. return VectorLoopValueMap.getVectorValue(V, Part);
  1566. // If the value has not been vectorized, check if it has been scalarized
  1567. // instead. If it has been scalarized, and we actually need the value in
  1568. // vector form, we will construct the vector values on demand.
  1569. if (VectorLoopValueMap.hasAnyScalarValue(V)) {
  1570. Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
  1571. // If we've scalarized a value, that value should be an instruction.
  1572. auto *I = cast<Instruction>(V);
  1573. // If we aren't vectorizing, we can just copy the scalar map values over to
  1574. // the vector map.
  1575. if (VF == 1) {
  1576. VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
  1577. return ScalarValue;
  1578. }
  1579. // Get the last scalar instruction we generated for V and Part. If the value
  1580. // is known to be uniform after vectorization, this corresponds to lane zero
  1581. // of the Part unroll iteration. Otherwise, the last instruction is the one
  1582. // we created for the last vector lane of the Part unroll iteration.
  1583. unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
  1584. auto *LastInst = cast<Instruction>(
  1585. VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
  1586. // Set the insert point after the last scalarized instruction. This ensures
  1587. // the insertelement sequence will directly follow the scalar definitions.
  1588. auto OldIP = Builder.saveIP();
  1589. auto NewIP = std::next(BasicBlock::iterator(LastInst));
  1590. Builder.SetInsertPoint(&*NewIP);
  1591. // However, if we are vectorizing, we need to construct the vector values.
  1592. // If the value is known to be uniform after vectorization, we can just
  1593. // broadcast the scalar value corresponding to lane zero for each unroll
  1594. // iteration. Otherwise, we construct the vector values using insertelement
  1595. // instructions. Since the resulting vectors are stored in
  1596. // VectorLoopValueMap, we will only generate the insertelements once.
  1597. Value *VectorValue = nullptr;
  1598. if (Cost->isUniformAfterVectorization(I, VF)) {
  1599. VectorValue = getBroadcastInstrs(ScalarValue);
  1600. VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
  1601. } else {
  1602. // Initialize packing with insertelements to start from undef.
  1603. Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
  1604. VectorLoopValueMap.setVectorValue(V, Part, Undef);
  1605. for (unsigned Lane = 0; Lane < VF; ++Lane)
  1606. packScalarIntoVectorValue(V, {Part, Lane});
  1607. VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
  1608. }
  1609. Builder.restoreIP(OldIP);
  1610. return VectorValue;
  1611. }
  1612. // If this scalar is unknown, assume that it is a constant or that it is
  1613. // loop invariant. Broadcast V and save the value for future uses.
  1614. Value *B = getBroadcastInstrs(V);
  1615. VectorLoopValueMap.setVectorValue(V, Part, B);
  1616. return B;
  1617. }
  1618. Value *
  1619. InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
  1620. const VPIteration &Instance) {
  1621. // If the value is not an instruction contained in the loop, it should
  1622. // already be scalar.
  1623. if (OrigLoop->isLoopInvariant(V))
  1624. return V;
  1625. assert(Instance.Lane > 0
  1626. ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
  1627. : true && "Uniform values only have lane zero");
  1628. // If the value from the original loop has not been vectorized, it is
  1629. // represented by UF x VF scalar values in the new loop. Return the requested
  1630. // scalar value.
  1631. if (VectorLoopValueMap.hasScalarValue(V, Instance))
  1632. return VectorLoopValueMap.getScalarValue(V, Instance);
  1633. // If the value has not been scalarized, get its entry in VectorLoopValueMap
  1634. // for the given unroll part. If this entry is not a vector type (i.e., the
  1635. // vectorization factor is one), there is no need to generate an
  1636. // extractelement instruction.
  1637. auto *U = getOrCreateVectorValue(V, Instance.Part);
  1638. if (!U->getType()->isVectorTy()) {
  1639. assert(VF == 1 && "Value not scalarized has non-vector type");
  1640. return U;
  1641. }
  1642. // Otherwise, the value from the original loop has been vectorized and is
  1643. // represented by UF vector values. Extract and return the requested scalar
  1644. // value from the appropriate vector lane.
  1645. return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
  1646. }
  1647. void InnerLoopVectorizer::packScalarIntoVectorValue(
  1648. Value *V, const VPIteration &Instance) {
  1649. assert(V != Induction && "The new induction variable should not be used.");
  1650. assert(!V->getType()->isVectorTy() && "Can't pack a vector");
  1651. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  1652. Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
  1653. Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
  1654. VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
  1655. Builder.getInt32(Instance.Lane));
  1656. VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
  1657. }
  1658. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  1659. assert(Vec->getType()->isVectorTy() && "Invalid type");
  1660. SmallVector<Constant *, 8> ShuffleMask;
  1661. for (unsigned i = 0; i < VF; ++i)
  1662. ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
  1663. return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
  1664. ConstantVector::get(ShuffleMask),
  1665. "reverse");
  1666. }
  1667. // Return whether we allow using masked interleave-groups (for dealing with
  1668. // strided loads/stores that reside in predicated blocks, or for dealing
  1669. // with gaps).
  1670. static bool useMaskedInterleavedAccesses(const TargetTransformInfo &TTI) {
  1671. // If an override option has been passed in for interleaved accesses, use it.
  1672. if (EnableMaskedInterleavedMemAccesses.getNumOccurrences() > 0)
  1673. return EnableMaskedInterleavedMemAccesses;
  1674. return TTI.enableMaskedInterleavedAccessVectorization();
  1675. }
  1676. // Try to vectorize the interleave group that \p Instr belongs to.
  1677. //
  1678. // E.g. Translate following interleaved load group (factor = 3):
  1679. // for (i = 0; i < N; i+=3) {
  1680. // R = Pic[i]; // Member of index 0
  1681. // G = Pic[i+1]; // Member of index 1
  1682. // B = Pic[i+2]; // Member of index 2
  1683. // ... // do something to R, G, B
  1684. // }
  1685. // To:
  1686. // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
  1687. // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
  1688. // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
  1689. // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
  1690. //
  1691. // Or translate following interleaved store group (factor = 3):
  1692. // for (i = 0; i < N; i+=3) {
  1693. // ... do something to R, G, B
  1694. // Pic[i] = R; // Member of index 0
  1695. // Pic[i+1] = G; // Member of index 1
  1696. // Pic[i+2] = B; // Member of index 2
  1697. // }
  1698. // To:
  1699. // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
  1700. // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
  1701. // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
  1702. // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
  1703. // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
  1704. void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr,
  1705. VectorParts *BlockInMask) {
  1706. const InterleaveGroup<Instruction> *Group =
  1707. Cost->getInterleavedAccessGroup(Instr);
  1708. assert(Group && "Fail to get an interleaved access group.");
  1709. // Skip if current instruction is not the insert position.
  1710. if (Instr != Group->getInsertPos())
  1711. return;
  1712. const DataLayout &DL = Instr->getModule()->getDataLayout();
  1713. Value *Ptr = getLoadStorePointerOperand(Instr);
  1714. // Prepare for the vector type of the interleaved load/store.
  1715. Type *ScalarTy = getMemInstValueType(Instr);
  1716. unsigned InterleaveFactor = Group->getFactor();
  1717. Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
  1718. Type *PtrTy = VecTy->getPointerTo(getLoadStoreAddressSpace(Instr));
  1719. // Prepare for the new pointers.
  1720. setDebugLocFromInst(Builder, Ptr);
  1721. SmallVector<Value *, 2> NewPtrs;
  1722. unsigned Index = Group->getIndex(Instr);
  1723. VectorParts Mask;
  1724. bool IsMaskForCondRequired = BlockInMask;
  1725. if (IsMaskForCondRequired) {
  1726. Mask = *BlockInMask;
  1727. // TODO: extend the masked interleaved-group support to reversed access.
  1728. assert(!Group->isReverse() && "Reversed masked interleave-group "
  1729. "not supported.");
  1730. }
  1731. // If the group is reverse, adjust the index to refer to the last vector lane
  1732. // instead of the first. We adjust the index from the first vector lane,
  1733. // rather than directly getting the pointer for lane VF - 1, because the
  1734. // pointer operand of the interleaved access is supposed to be uniform. For
  1735. // uniform instructions, we're only required to generate a value for the
  1736. // first vector lane in each unroll iteration.
  1737. if (Group->isReverse())
  1738. Index += (VF - 1) * Group->getFactor();
  1739. bool InBounds = false;
  1740. if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
  1741. InBounds = gep->isInBounds();
  1742. for (unsigned Part = 0; Part < UF; Part++) {
  1743. Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
  1744. // Notice current instruction could be any index. Need to adjust the address
  1745. // to the member of index 0.
  1746. //
  1747. // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
  1748. // b = A[i]; // Member of index 0
  1749. // Current pointer is pointed to A[i+1], adjust it to A[i].
  1750. //
  1751. // E.g. A[i+1] = a; // Member of index 1
  1752. // A[i] = b; // Member of index 0
  1753. // A[i+2] = c; // Member of index 2 (Current instruction)
  1754. // Current pointer is pointed to A[i+2], adjust it to A[i].
  1755. NewPtr = Builder.CreateGEP(ScalarTy, NewPtr, Builder.getInt32(-Index));
  1756. if (InBounds)
  1757. cast<GetElementPtrInst>(NewPtr)->setIsInBounds(true);
  1758. // Cast to the vector pointer type.
  1759. NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
  1760. }
  1761. setDebugLocFromInst(Builder, Instr);
  1762. Value *UndefVec = UndefValue::get(VecTy);
  1763. Value *MaskForGaps = nullptr;
  1764. if (Group->requiresScalarEpilogue() && !Cost->isScalarEpilogueAllowed()) {
  1765. MaskForGaps = createBitMaskForGaps(Builder, VF, *Group);
  1766. assert(MaskForGaps && "Mask for Gaps is required but it is null");
  1767. }
  1768. // Vectorize the interleaved load group.
  1769. if (isa<LoadInst>(Instr)) {
  1770. // For each unroll part, create a wide load for the group.
  1771. SmallVector<Value *, 2> NewLoads;
  1772. for (unsigned Part = 0; Part < UF; Part++) {
  1773. Instruction *NewLoad;
  1774. if (IsMaskForCondRequired || MaskForGaps) {
  1775. assert(useMaskedInterleavedAccesses(*TTI) &&
  1776. "masked interleaved groups are not allowed.");
  1777. Value *GroupMask = MaskForGaps;
  1778. if (IsMaskForCondRequired) {
  1779. auto *Undefs = UndefValue::get(Mask[Part]->getType());
  1780. auto *RepMask = createReplicatedMask(Builder, InterleaveFactor, VF);
  1781. Value *ShuffledMask = Builder.CreateShuffleVector(
  1782. Mask[Part], Undefs, RepMask, "interleaved.mask");
  1783. GroupMask = MaskForGaps
  1784. ? Builder.CreateBinOp(Instruction::And, ShuffledMask,
  1785. MaskForGaps)
  1786. : ShuffledMask;
  1787. }
  1788. NewLoad =
  1789. Builder.CreateMaskedLoad(NewPtrs[Part], Group->getAlignment(),
  1790. GroupMask, UndefVec, "wide.masked.vec");
  1791. }
  1792. else
  1793. NewLoad = Builder.CreateAlignedLoad(VecTy, NewPtrs[Part],
  1794. Group->getAlignment(), "wide.vec");
  1795. Group->addMetadata(NewLoad);
  1796. NewLoads.push_back(NewLoad);
  1797. }
  1798. // For each member in the group, shuffle out the appropriate data from the
  1799. // wide loads.
  1800. for (unsigned I = 0; I < InterleaveFactor; ++I) {
  1801. Instruction *Member = Group->getMember(I);
  1802. // Skip the gaps in the group.
  1803. if (!Member)
  1804. continue;
  1805. Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
  1806. for (unsigned Part = 0; Part < UF; Part++) {
  1807. Value *StridedVec = Builder.CreateShuffleVector(
  1808. NewLoads[Part], UndefVec, StrideMask, "strided.vec");
  1809. // If this member has different type, cast the result type.
  1810. if (Member->getType() != ScalarTy) {
  1811. VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
  1812. StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
  1813. }
  1814. if (Group->isReverse())
  1815. StridedVec = reverseVector(StridedVec);
  1816. VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
  1817. }
  1818. }
  1819. return;
  1820. }
  1821. // The sub vector type for current instruction.
  1822. VectorType *SubVT = VectorType::get(ScalarTy, VF);
  1823. // Vectorize the interleaved store group.
  1824. for (unsigned Part = 0; Part < UF; Part++) {
  1825. // Collect the stored vector from each member.
  1826. SmallVector<Value *, 4> StoredVecs;
  1827. for (unsigned i = 0; i < InterleaveFactor; i++) {
  1828. // Interleaved store group doesn't allow a gap, so each index has a member
  1829. Instruction *Member = Group->getMember(i);
  1830. assert(Member && "Fail to get a member from an interleaved store group");
  1831. Value *StoredVec = getOrCreateVectorValue(
  1832. cast<StoreInst>(Member)->getValueOperand(), Part);
  1833. if (Group->isReverse())
  1834. StoredVec = reverseVector(StoredVec);
  1835. // If this member has different type, cast it to a unified type.
  1836. if (StoredVec->getType() != SubVT)
  1837. StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
  1838. StoredVecs.push_back(StoredVec);
  1839. }
  1840. // Concatenate all vectors into a wide vector.
  1841. Value *WideVec = concatenateVectors(Builder, StoredVecs);
  1842. // Interleave the elements in the wide vector.
  1843. Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
  1844. Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
  1845. "interleaved.vec");
  1846. Instruction *NewStoreInstr;
  1847. if (IsMaskForCondRequired) {
  1848. auto *Undefs = UndefValue::get(Mask[Part]->getType());
  1849. auto *RepMask = createReplicatedMask(Builder, InterleaveFactor, VF);
  1850. Value *ShuffledMask = Builder.CreateShuffleVector(
  1851. Mask[Part], Undefs, RepMask, "interleaved.mask");
  1852. NewStoreInstr = Builder.CreateMaskedStore(
  1853. IVec, NewPtrs[Part], Group->getAlignment(), ShuffledMask);
  1854. }
  1855. else
  1856. NewStoreInstr = Builder.CreateAlignedStore(IVec, NewPtrs[Part],
  1857. Group->getAlignment());
  1858. Group->addMetadata(NewStoreInstr);
  1859. }
  1860. }
  1861. void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
  1862. VectorParts *BlockInMask) {
  1863. // Attempt to issue a wide load.
  1864. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  1865. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  1866. assert((LI || SI) && "Invalid Load/Store instruction");
  1867. LoopVectorizationCostModel::InstWidening Decision =
  1868. Cost->getWideningDecision(Instr, VF);
  1869. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  1870. "CM decision should be taken at this point");
  1871. if (Decision == LoopVectorizationCostModel::CM_Interleave)
  1872. return vectorizeInterleaveGroup(Instr);
  1873. Type *ScalarDataTy = getMemInstValueType(Instr);
  1874. Type *DataTy = VectorType::get(ScalarDataTy, VF);
  1875. Value *Ptr = getLoadStorePointerOperand(Instr);
  1876. unsigned Alignment = getLoadStoreAlignment(Instr);
  1877. // An alignment of 0 means target abi alignment. We need to use the scalar's
  1878. // target abi alignment in such a case.
  1879. const DataLayout &DL = Instr->getModule()->getDataLayout();
  1880. if (!Alignment)
  1881. Alignment = DL.getABITypeAlignment(ScalarDataTy);
  1882. unsigned AddressSpace = getLoadStoreAddressSpace(Instr);
  1883. // Determine if the pointer operand of the access is either consecutive or
  1884. // reverse consecutive.
  1885. bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
  1886. bool ConsecutiveStride =
  1887. Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
  1888. bool CreateGatherScatter =
  1889. (Decision == LoopVectorizationCostModel::CM_GatherScatter);
  1890. // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
  1891. // gather/scatter. Otherwise Decision should have been to Scalarize.
  1892. assert((ConsecutiveStride || CreateGatherScatter) &&
  1893. "The instruction should be scalarized");
  1894. // Handle consecutive loads/stores.
  1895. if (ConsecutiveStride)
  1896. Ptr = getOrCreateScalarValue(Ptr, {0, 0});
  1897. VectorParts Mask;
  1898. bool isMaskRequired = BlockInMask;
  1899. if (isMaskRequired)
  1900. Mask = *BlockInMask;
  1901. bool InBounds = false;
  1902. if (auto *gep = dyn_cast<GetElementPtrInst>(
  1903. getLoadStorePointerOperand(Instr)->stripPointerCasts()))
  1904. InBounds = gep->isInBounds();
  1905. const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
  1906. // Calculate the pointer for the specific unroll-part.
  1907. GetElementPtrInst *PartPtr = nullptr;
  1908. if (Reverse) {
  1909. // If the address is consecutive but reversed, then the
  1910. // wide store needs to start at the last vector element.
  1911. PartPtr = cast<GetElementPtrInst>(
  1912. Builder.CreateGEP(ScalarDataTy, Ptr, Builder.getInt32(-Part * VF)));
  1913. PartPtr->setIsInBounds(InBounds);
  1914. PartPtr = cast<GetElementPtrInst>(
  1915. Builder.CreateGEP(ScalarDataTy, PartPtr, Builder.getInt32(1 - VF)));
  1916. PartPtr->setIsInBounds(InBounds);
  1917. if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
  1918. Mask[Part] = reverseVector(Mask[Part]);
  1919. } else {
  1920. PartPtr = cast<GetElementPtrInst>(
  1921. Builder.CreateGEP(ScalarDataTy, Ptr, Builder.getInt32(Part * VF)));
  1922. PartPtr->setIsInBounds(InBounds);
  1923. }
  1924. return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
  1925. };
  1926. // Handle Stores:
  1927. if (SI) {
  1928. setDebugLocFromInst(Builder, SI);
  1929. for (unsigned Part = 0; Part < UF; ++Part) {
  1930. Instruction *NewSI = nullptr;
  1931. Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
  1932. if (CreateGatherScatter) {
  1933. Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
  1934. Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
  1935. NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
  1936. MaskPart);
  1937. } else {
  1938. if (Reverse) {
  1939. // If we store to reverse consecutive memory locations, then we need
  1940. // to reverse the order of elements in the stored value.
  1941. StoredVal = reverseVector(StoredVal);
  1942. // We don't want to update the value in the map as it might be used in
  1943. // another expression. So don't call resetVectorValue(StoredVal).
  1944. }
  1945. auto *VecPtr = CreateVecPtr(Part, Ptr);
  1946. if (isMaskRequired)
  1947. NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
  1948. Mask[Part]);
  1949. else
  1950. NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
  1951. }
  1952. addMetadata(NewSI, SI);
  1953. }
  1954. return;
  1955. }
  1956. // Handle loads.
  1957. assert(LI && "Must have a load instruction");
  1958. setDebugLocFromInst(Builder, LI);
  1959. for (unsigned Part = 0; Part < UF; ++Part) {
  1960. Value *NewLI;
  1961. if (CreateGatherScatter) {
  1962. Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
  1963. Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
  1964. NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
  1965. nullptr, "wide.masked.gather");
  1966. addMetadata(NewLI, LI);
  1967. } else {
  1968. auto *VecPtr = CreateVecPtr(Part, Ptr);
  1969. if (isMaskRequired)
  1970. NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
  1971. UndefValue::get(DataTy),
  1972. "wide.masked.load");
  1973. else
  1974. NewLI =
  1975. Builder.CreateAlignedLoad(DataTy, VecPtr, Alignment, "wide.load");
  1976. // Add metadata to the load, but setVectorValue to the reverse shuffle.
  1977. addMetadata(NewLI, LI);
  1978. if (Reverse)
  1979. NewLI = reverseVector(NewLI);
  1980. }
  1981. VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
  1982. }
  1983. }
  1984. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
  1985. const VPIteration &Instance,
  1986. bool IfPredicateInstr) {
  1987. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  1988. setDebugLocFromInst(Builder, Instr);
  1989. // Does this instruction return a value ?
  1990. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  1991. Instruction *Cloned = Instr->clone();
  1992. if (!IsVoidRetTy)
  1993. Cloned->setName(Instr->getName() + ".cloned");
  1994. // Replace the operands of the cloned instructions with their scalar
  1995. // equivalents in the new loop.
  1996. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  1997. auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
  1998. Cloned->setOperand(op, NewOp);
  1999. }
  2000. addNewMetadata(Cloned, Instr);
  2001. // Place the cloned scalar in the new loop.
  2002. Builder.Insert(Cloned);
  2003. // Add the cloned scalar to the scalar map entry.
  2004. VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
  2005. // If we just cloned a new assumption, add it the assumption cache.
  2006. if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
  2007. if (II->getIntrinsicID() == Intrinsic::assume)
  2008. AC->registerAssumption(II);
  2009. // End if-block.
  2010. if (IfPredicateInstr)
  2011. PredicatedInstructions.push_back(Cloned);
  2012. }
  2013. PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
  2014. Value *End, Value *Step,
  2015. Instruction *DL) {
  2016. BasicBlock *Header = L->getHeader();
  2017. BasicBlock *Latch = L->getLoopLatch();
  2018. // As we're just creating this loop, it's possible no latch exists
  2019. // yet. If so, use the header as this will be a single block loop.
  2020. if (!Latch)
  2021. Latch = Header;
  2022. IRBuilder<> Builder(&*Header->getFirstInsertionPt());
  2023. Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
  2024. setDebugLocFromInst(Builder, OldInst);
  2025. auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
  2026. Builder.SetInsertPoint(Latch->getTerminator());
  2027. setDebugLocFromInst(Builder, OldInst);
  2028. // Create i+1 and fill the PHINode.
  2029. Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
  2030. Induction->addIncoming(Start, L->getLoopPreheader());
  2031. Induction->addIncoming(Next, Latch);
  2032. // Create the compare.
  2033. Value *ICmp = Builder.CreateICmpEQ(Next, End);
  2034. Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
  2035. // Now we have two terminators. Remove the old one from the block.
  2036. Latch->getTerminator()->eraseFromParent();
  2037. return Induction;
  2038. }
  2039. Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
  2040. if (TripCount)
  2041. return TripCount;
  2042. assert(L && "Create Trip Count for null loop.");
  2043. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2044. // Find the loop boundaries.
  2045. ScalarEvolution *SE = PSE.getSE();
  2046. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  2047. assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
  2048. "Invalid loop count");
  2049. Type *IdxTy = Legal->getWidestInductionType();
  2050. assert(IdxTy && "No type for induction");
  2051. // The exit count might have the type of i64 while the phi is i32. This can
  2052. // happen if we have an induction variable that is sign extended before the
  2053. // compare. The only way that we get a backedge taken count is that the
  2054. // induction variable was signed and as such will not overflow. In such a case
  2055. // truncation is legal.
  2056. if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
  2057. IdxTy->getPrimitiveSizeInBits())
  2058. BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
  2059. BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
  2060. // Get the total trip count from the count by adding 1.
  2061. const SCEV *ExitCount = SE->getAddExpr(
  2062. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  2063. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  2064. // Expand the trip count and place the new instructions in the preheader.
  2065. // Notice that the pre-header does not change, only the loop body.
  2066. SCEVExpander Exp(*SE, DL, "induction");
  2067. // Count holds the overall loop count (N).
  2068. TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  2069. L->getLoopPreheader()->getTerminator());
  2070. if (TripCount->getType()->isPointerTy())
  2071. TripCount =
  2072. CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
  2073. L->getLoopPreheader()->getTerminator());
  2074. return TripCount;
  2075. }
  2076. Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
  2077. if (VectorTripCount)
  2078. return VectorTripCount;
  2079. Value *TC = getOrCreateTripCount(L);
  2080. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2081. Type *Ty = TC->getType();
  2082. Constant *Step = ConstantInt::get(Ty, VF * UF);
  2083. // If the tail is to be folded by masking, round the number of iterations N
  2084. // up to a multiple of Step instead of rounding down. This is done by first
  2085. // adding Step-1 and then rounding down. Note that it's ok if this addition
  2086. // overflows: the vector induction variable will eventually wrap to zero given
  2087. // that it starts at zero and its Step is a power of two; the loop will then
  2088. // exit, with the last early-exit vector comparison also producing all-true.
  2089. if (Cost->foldTailByMasking()) {
  2090. assert(isPowerOf2_32(VF * UF) &&
  2091. "VF*UF must be a power of 2 when folding tail by masking");
  2092. TC = Builder.CreateAdd(TC, ConstantInt::get(Ty, VF * UF - 1), "n.rnd.up");
  2093. }
  2094. // Now we need to generate the expression for the part of the loop that the
  2095. // vectorized body will execute. This is equal to N - (N % Step) if scalar
  2096. // iterations are not required for correctness, or N - Step, otherwise. Step
  2097. // is equal to the vectorization factor (number of SIMD elements) times the
  2098. // unroll factor (number of SIMD instructions).
  2099. Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
  2100. // If there is a non-reversed interleaved group that may speculatively access
  2101. // memory out-of-bounds, we need to ensure that there will be at least one
  2102. // iteration of the scalar epilogue loop. Thus, if the step evenly divides
  2103. // the trip count, we set the remainder to be equal to the step. If the step
  2104. // does not evenly divide the trip count, no adjustment is necessary since
  2105. // there will already be scalar iterations. Note that the minimum iterations
  2106. // check ensures that N >= Step.
  2107. if (VF > 1 && Cost->requiresScalarEpilogue()) {
  2108. auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
  2109. R = Builder.CreateSelect(IsZero, Step, R);
  2110. }
  2111. VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
  2112. return VectorTripCount;
  2113. }
  2114. Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
  2115. const DataLayout &DL) {
  2116. // Verify that V is a vector type with same number of elements as DstVTy.
  2117. unsigned VF = DstVTy->getNumElements();
  2118. VectorType *SrcVecTy = cast<VectorType>(V->getType());
  2119. assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
  2120. Type *SrcElemTy = SrcVecTy->getElementType();
  2121. Type *DstElemTy = DstVTy->getElementType();
  2122. assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
  2123. "Vector elements must have same size");
  2124. // Do a direct cast if element types are castable.
  2125. if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
  2126. return Builder.CreateBitOrPointerCast(V, DstVTy);
  2127. }
  2128. // V cannot be directly casted to desired vector type.
  2129. // May happen when V is a floating point vector but DstVTy is a vector of
  2130. // pointers or vice-versa. Handle this using a two-step bitcast using an
  2131. // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
  2132. assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
  2133. "Only one type should be a pointer type");
  2134. assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
  2135. "Only one type should be a floating point type");
  2136. Type *IntTy =
  2137. IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
  2138. VectorType *VecIntTy = VectorType::get(IntTy, VF);
  2139. Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
  2140. return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
  2141. }
  2142. void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
  2143. BasicBlock *Bypass) {
  2144. Value *Count = getOrCreateTripCount(L);
  2145. BasicBlock *BB = L->getLoopPreheader();
  2146. IRBuilder<> Builder(BB->getTerminator());
  2147. // Generate code to check if the loop's trip count is less than VF * UF, or
  2148. // equal to it in case a scalar epilogue is required; this implies that the
  2149. // vector trip count is zero. This check also covers the case where adding one
  2150. // to the backedge-taken count overflowed leading to an incorrect trip count
  2151. // of zero. In this case we will also jump to the scalar loop.
  2152. auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
  2153. : ICmpInst::ICMP_ULT;
  2154. // If tail is to be folded, vector loop takes care of all iterations.
  2155. Value *CheckMinIters = Builder.getFalse();
  2156. if (!Cost->foldTailByMasking())
  2157. CheckMinIters = Builder.CreateICmp(
  2158. P, Count, ConstantInt::get(Count->getType(), VF * UF),
  2159. "min.iters.check");
  2160. BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2161. // Update dominator tree immediately if the generated block is a
  2162. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2163. // checks may query it before the current function is finished.
  2164. DT->addNewBlock(NewBB, BB);
  2165. if (L->getParentLoop())
  2166. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2167. ReplaceInstWithInst(BB->getTerminator(),
  2168. BranchInst::Create(Bypass, NewBB, CheckMinIters));
  2169. LoopBypassBlocks.push_back(BB);
  2170. }
  2171. void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
  2172. BasicBlock *BB = L->getLoopPreheader();
  2173. // Generate the code to check that the SCEV assumptions that we made.
  2174. // We want the new basic block to start at the first instruction in a
  2175. // sequence of instructions that form a check.
  2176. SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
  2177. "scev.check");
  2178. Value *SCEVCheck =
  2179. Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
  2180. if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
  2181. if (C->isZero())
  2182. return;
  2183. assert(!Cost->foldTailByMasking() &&
  2184. "Cannot SCEV check stride or overflow when folding tail");
  2185. // Create a new block containing the stride check.
  2186. BB->setName("vector.scevcheck");
  2187. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2188. // Update dominator tree immediately if the generated block is a
  2189. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2190. // checks may query it before the current function is finished.
  2191. DT->addNewBlock(NewBB, BB);
  2192. if (L->getParentLoop())
  2193. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2194. ReplaceInstWithInst(BB->getTerminator(),
  2195. BranchInst::Create(Bypass, NewBB, SCEVCheck));
  2196. LoopBypassBlocks.push_back(BB);
  2197. AddedSafetyChecks = true;
  2198. }
  2199. void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
  2200. // VPlan-native path does not do any analysis for runtime checks currently.
  2201. if (EnableVPlanNativePath)
  2202. return;
  2203. BasicBlock *BB = L->getLoopPreheader();
  2204. // Generate the code that checks in runtime if arrays overlap. We put the
  2205. // checks into a separate block to make the more common case of few elements
  2206. // faster.
  2207. Instruction *FirstCheckInst;
  2208. Instruction *MemRuntimeCheck;
  2209. std::tie(FirstCheckInst, MemRuntimeCheck) =
  2210. Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
  2211. if (!MemRuntimeCheck)
  2212. return;
  2213. assert(!Cost->foldTailByMasking() && "Cannot check memory when folding tail");
  2214. // Create a new block containing the memory check.
  2215. BB->setName("vector.memcheck");
  2216. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2217. // Update dominator tree immediately if the generated block is a
  2218. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2219. // checks may query it before the current function is finished.
  2220. DT->addNewBlock(NewBB, BB);
  2221. if (L->getParentLoop())
  2222. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2223. ReplaceInstWithInst(BB->getTerminator(),
  2224. BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
  2225. LoopBypassBlocks.push_back(BB);
  2226. AddedSafetyChecks = true;
  2227. // We currently don't use LoopVersioning for the actual loop cloning but we
  2228. // still use it to add the noalias metadata.
  2229. LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
  2230. PSE.getSE());
  2231. LVer->prepareNoAliasMetadata();
  2232. }
  2233. Value *InnerLoopVectorizer::emitTransformedIndex(
  2234. IRBuilder<> &B, Value *Index, ScalarEvolution *SE, const DataLayout &DL,
  2235. const InductionDescriptor &ID) const {
  2236. SCEVExpander Exp(*SE, DL, "induction");
  2237. auto Step = ID.getStep();
  2238. auto StartValue = ID.getStartValue();
  2239. assert(Index->getType() == Step->getType() &&
  2240. "Index type does not match StepValue type");
  2241. // Note: the IR at this point is broken. We cannot use SE to create any new
  2242. // SCEV and then expand it, hoping that SCEV's simplification will give us
  2243. // a more optimal code. Unfortunately, attempt of doing so on invalid IR may
  2244. // lead to various SCEV crashes. So all we can do is to use builder and rely
  2245. // on InstCombine for future simplifications. Here we handle some trivial
  2246. // cases only.
  2247. auto CreateAdd = [&B](Value *X, Value *Y) {
  2248. assert(X->getType() == Y->getType() && "Types don't match!");
  2249. if (auto *CX = dyn_cast<ConstantInt>(X))
  2250. if (CX->isZero())
  2251. return Y;
  2252. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2253. if (CY->isZero())
  2254. return X;
  2255. return B.CreateAdd(X, Y);
  2256. };
  2257. auto CreateMul = [&B](Value *X, Value *Y) {
  2258. assert(X->getType() == Y->getType() && "Types don't match!");
  2259. if (auto *CX = dyn_cast<ConstantInt>(X))
  2260. if (CX->isOne())
  2261. return Y;
  2262. if (auto *CY = dyn_cast<ConstantInt>(Y))
  2263. if (CY->isOne())
  2264. return X;
  2265. return B.CreateMul(X, Y);
  2266. };
  2267. switch (ID.getKind()) {
  2268. case InductionDescriptor::IK_IntInduction: {
  2269. assert(Index->getType() == StartValue->getType() &&
  2270. "Index type does not match StartValue type");
  2271. if (ID.getConstIntStepValue() && ID.getConstIntStepValue()->isMinusOne())
  2272. return B.CreateSub(StartValue, Index);
  2273. auto *Offset = CreateMul(
  2274. Index, Exp.expandCodeFor(Step, Index->getType(), &*B.GetInsertPoint()));
  2275. return CreateAdd(StartValue, Offset);
  2276. }
  2277. case InductionDescriptor::IK_PtrInduction: {
  2278. assert(isa<SCEVConstant>(Step) &&
  2279. "Expected constant step for pointer induction");
  2280. return B.CreateGEP(
  2281. StartValue->getType()->getPointerElementType(), StartValue,
  2282. CreateMul(Index, Exp.expandCodeFor(Step, Index->getType(),
  2283. &*B.GetInsertPoint())));
  2284. }
  2285. case InductionDescriptor::IK_FpInduction: {
  2286. assert(Step->getType()->isFloatingPointTy() && "Expected FP Step value");
  2287. auto InductionBinOp = ID.getInductionBinOp();
  2288. assert(InductionBinOp &&
  2289. (InductionBinOp->getOpcode() == Instruction::FAdd ||
  2290. InductionBinOp->getOpcode() == Instruction::FSub) &&
  2291. "Original bin op should be defined for FP induction");
  2292. Value *StepValue = cast<SCEVUnknown>(Step)->getValue();
  2293. // Floating point operations had to be 'fast' to enable the induction.
  2294. FastMathFlags Flags;
  2295. Flags.setFast();
  2296. Value *MulExp = B.CreateFMul(StepValue, Index);
  2297. if (isa<Instruction>(MulExp))
  2298. // We have to check, the MulExp may be a constant.
  2299. cast<Instruction>(MulExp)->setFastMathFlags(Flags);
  2300. Value *BOp = B.CreateBinOp(InductionBinOp->getOpcode(), StartValue, MulExp,
  2301. "induction");
  2302. if (isa<Instruction>(BOp))
  2303. cast<Instruction>(BOp)->setFastMathFlags(Flags);
  2304. return BOp;
  2305. }
  2306. case InductionDescriptor::IK_NoInduction:
  2307. return nullptr;
  2308. }
  2309. llvm_unreachable("invalid enum");
  2310. }
  2311. BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
  2312. /*
  2313. In this function we generate a new loop. The new loop will contain
  2314. the vectorized instructions while the old loop will continue to run the
  2315. scalar remainder.
  2316. [ ] <-- loop iteration number check.
  2317. / |
  2318. / v
  2319. | [ ] <-- vector loop bypass (may consist of multiple blocks).
  2320. | / |
  2321. | / v
  2322. || [ ] <-- vector pre header.
  2323. |/ |
  2324. | v
  2325. | [ ] \
  2326. | [ ]_| <-- vector loop.
  2327. | |
  2328. | v
  2329. | -[ ] <--- middle-block.
  2330. | / |
  2331. | / v
  2332. -|- >[ ] <--- new preheader.
  2333. | |
  2334. | v
  2335. | [ ] \
  2336. | [ ]_| <-- old scalar loop to handle remainder.
  2337. \ |
  2338. \ v
  2339. >[ ] <-- exit block.
  2340. ...
  2341. */
  2342. BasicBlock *OldBasicBlock = OrigLoop->getHeader();
  2343. BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
  2344. BasicBlock *ExitBlock = OrigLoop->getExitBlock();
  2345. MDNode *OrigLoopID = OrigLoop->getLoopID();
  2346. assert(VectorPH && "Invalid loop structure");
  2347. assert(ExitBlock && "Must have an exit block");
  2348. // Some loops have a single integer induction variable, while other loops
  2349. // don't. One example is c++ iterators that often have multiple pointer
  2350. // induction variables. In the code below we also support a case where we
  2351. // don't have a single induction variable.
  2352. //
  2353. // We try to obtain an induction variable from the original loop as hard
  2354. // as possible. However if we don't find one that:
  2355. // - is an integer
  2356. // - counts from zero, stepping by one
  2357. // - is the size of the widest induction variable type
  2358. // then we create a new one.
  2359. OldInduction = Legal->getPrimaryInduction();
  2360. Type *IdxTy = Legal->getWidestInductionType();
  2361. // Split the single block loop into the two loop structure described above.
  2362. BasicBlock *VecBody =
  2363. VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
  2364. BasicBlock *MiddleBlock =
  2365. VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
  2366. BasicBlock *ScalarPH =
  2367. MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
  2368. // Create and register the new vector loop.
  2369. Loop *Lp = LI->AllocateLoop();
  2370. Loop *ParentLoop = OrigLoop->getParentLoop();
  2371. // Insert the new loop into the loop nest and register the new basic blocks
  2372. // before calling any utilities such as SCEV that require valid LoopInfo.
  2373. if (ParentLoop) {
  2374. ParentLoop->addChildLoop(Lp);
  2375. ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
  2376. ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
  2377. } else {
  2378. LI->addTopLevelLoop(Lp);
  2379. }
  2380. Lp->addBasicBlockToLoop(VecBody, *LI);
  2381. // Find the loop boundaries.
  2382. Value *Count = getOrCreateTripCount(Lp);
  2383. Value *StartIdx = ConstantInt::get(IdxTy, 0);
  2384. // Now, compare the new count to zero. If it is zero skip the vector loop and
  2385. // jump to the scalar loop. This check also covers the case where the
  2386. // backedge-taken count is uint##_max: adding one to it will overflow leading
  2387. // to an incorrect trip count of zero. In this (rare) case we will also jump
  2388. // to the scalar loop.
  2389. emitMinimumIterationCountCheck(Lp, ScalarPH);
  2390. // Generate the code to check any assumptions that we've made for SCEV
  2391. // expressions.
  2392. emitSCEVChecks(Lp, ScalarPH);
  2393. // Generate the code that checks in runtime if arrays overlap. We put the
  2394. // checks into a separate block to make the more common case of few elements
  2395. // faster.
  2396. emitMemRuntimeChecks(Lp, ScalarPH);
  2397. // Generate the induction variable.
  2398. // The loop step is equal to the vectorization factor (num of SIMD elements)
  2399. // times the unroll factor (num of SIMD instructions).
  2400. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  2401. Constant *Step = ConstantInt::get(IdxTy, VF * UF);
  2402. Induction =
  2403. createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
  2404. getDebugLocFromInstOrOperands(OldInduction));
  2405. // We are going to resume the execution of the scalar loop.
  2406. // Go over all of the induction variables that we found and fix the
  2407. // PHIs that are left in the scalar version of the loop.
  2408. // The starting values of PHI nodes depend on the counter of the last
  2409. // iteration in the vectorized loop.
  2410. // If we come from a bypass edge then we need to start from the original
  2411. // start value.
  2412. // This variable saves the new starting index for the scalar loop. It is used
  2413. // to test if there are any tail iterations left once the vector loop has
  2414. // completed.
  2415. LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
  2416. for (auto &InductionEntry : *List) {
  2417. PHINode *OrigPhi = InductionEntry.first;
  2418. InductionDescriptor II = InductionEntry.second;
  2419. // Create phi nodes to merge from the backedge-taken check block.
  2420. PHINode *BCResumeVal = PHINode::Create(
  2421. OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
  2422. // Copy original phi DL over to the new one.
  2423. BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
  2424. Value *&EndValue = IVEndValues[OrigPhi];
  2425. if (OrigPhi == OldInduction) {
  2426. // We know what the end value is.
  2427. EndValue = CountRoundDown;
  2428. } else {
  2429. IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
  2430. Type *StepType = II.getStep()->getType();
  2431. Instruction::CastOps CastOp =
  2432. CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
  2433. Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
  2434. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  2435. EndValue = emitTransformedIndex(B, CRD, PSE.getSE(), DL, II);
  2436. EndValue->setName("ind.end");
  2437. }
  2438. // The new PHI merges the original incoming value, in case of a bypass,
  2439. // or the value at the end of the vectorized loop.
  2440. BCResumeVal->addIncoming(EndValue, MiddleBlock);
  2441. // Fix the scalar body counter (PHI node).
  2442. unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
  2443. // The old induction's phi node in the scalar body needs the truncated
  2444. // value.
  2445. for (BasicBlock *BB : LoopBypassBlocks)
  2446. BCResumeVal->addIncoming(II.getStartValue(), BB);
  2447. OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
  2448. }
  2449. // We need the OrigLoop (scalar loop part) latch terminator to help
  2450. // produce correct debug info for the middle block BB instructions.
  2451. // The legality check stage guarantees that the loop will have a single
  2452. // latch.
  2453. assert(isa<BranchInst>(OrigLoop->getLoopLatch()->getTerminator()) &&
  2454. "Scalar loop latch terminator isn't a branch");
  2455. BranchInst *ScalarLatchBr =
  2456. cast<BranchInst>(OrigLoop->getLoopLatch()->getTerminator());
  2457. // Add a check in the middle block to see if we have completed
  2458. // all of the iterations in the first vector loop.
  2459. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  2460. // If tail is to be folded, we know we don't need to run the remainder.
  2461. Value *CmpN = Builder.getTrue();
  2462. if (!Cost->foldTailByMasking()) {
  2463. CmpN =
  2464. CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
  2465. CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
  2466. // Here we use the same DebugLoc as the scalar loop latch branch instead
  2467. // of the corresponding compare because they may have ended up with
  2468. // different line numbers and we want to avoid awkward line stepping while
  2469. // debugging. Eg. if the compare has got a line number inside the loop.
  2470. cast<Instruction>(CmpN)->setDebugLoc(ScalarLatchBr->getDebugLoc());
  2471. }
  2472. BranchInst *BrInst = BranchInst::Create(ExitBlock, ScalarPH, CmpN);
  2473. BrInst->setDebugLoc(ScalarLatchBr->getDebugLoc());
  2474. ReplaceInstWithInst(MiddleBlock->getTerminator(), BrInst);
  2475. // Get ready to start creating new instructions into the vectorized body.
  2476. Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
  2477. // Save the state.
  2478. LoopVectorPreHeader = Lp->getLoopPreheader();
  2479. LoopScalarPreHeader = ScalarPH;
  2480. LoopMiddleBlock = MiddleBlock;
  2481. LoopExitBlock = ExitBlock;
  2482. LoopVectorBody = VecBody;
  2483. LoopScalarBody = OldBasicBlock;
  2484. Optional<MDNode *> VectorizedLoopID =
  2485. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  2486. LLVMLoopVectorizeFollowupVectorized});
  2487. if (VectorizedLoopID.hasValue()) {
  2488. Lp->setLoopID(VectorizedLoopID.getValue());
  2489. // Do not setAlreadyVectorized if loop attributes have been defined
  2490. // explicitly.
  2491. return LoopVectorPreHeader;
  2492. }
  2493. // Keep all loop hints from the original loop on the vector loop (we'll
  2494. // replace the vectorizer-specific hints below).
  2495. if (MDNode *LID = OrigLoop->getLoopID())
  2496. Lp->setLoopID(LID);
  2497. LoopVectorizeHints Hints(Lp, true, *ORE);
  2498. Hints.setAlreadyVectorized();
  2499. return LoopVectorPreHeader;
  2500. }
  2501. // Fix up external users of the induction variable. At this point, we are
  2502. // in LCSSA form, with all external PHIs that use the IV having one input value,
  2503. // coming from the remainder loop. We need those PHIs to also have a correct
  2504. // value for the IV when arriving directly from the middle block.
  2505. void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
  2506. const InductionDescriptor &II,
  2507. Value *CountRoundDown, Value *EndValue,
  2508. BasicBlock *MiddleBlock) {
  2509. // There are two kinds of external IV usages - those that use the value
  2510. // computed in the last iteration (the PHI) and those that use the penultimate
  2511. // value (the value that feeds into the phi from the loop latch).
  2512. // We allow both, but they, obviously, have different values.
  2513. assert(OrigLoop->getExitBlock() && "Expected a single exit block");
  2514. DenseMap<Value *, Value *> MissingVals;
  2515. // An external user of the last iteration's value should see the value that
  2516. // the remainder loop uses to initialize its own IV.
  2517. Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
  2518. for (User *U : PostInc->users()) {
  2519. Instruction *UI = cast<Instruction>(U);
  2520. if (!OrigLoop->contains(UI)) {
  2521. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  2522. MissingVals[UI] = EndValue;
  2523. }
  2524. }
  2525. // An external user of the penultimate value need to see EndValue - Step.
  2526. // The simplest way to get this is to recompute it from the constituent SCEVs,
  2527. // that is Start + (Step * (CRD - 1)).
  2528. for (User *U : OrigPhi->users()) {
  2529. auto *UI = cast<Instruction>(U);
  2530. if (!OrigLoop->contains(UI)) {
  2531. const DataLayout &DL =
  2532. OrigLoop->getHeader()->getModule()->getDataLayout();
  2533. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  2534. IRBuilder<> B(MiddleBlock->getTerminator());
  2535. Value *CountMinusOne = B.CreateSub(
  2536. CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
  2537. Value *CMO =
  2538. !II.getStep()->getType()->isIntegerTy()
  2539. ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
  2540. II.getStep()->getType())
  2541. : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
  2542. CMO->setName("cast.cmo");
  2543. Value *Escape = emitTransformedIndex(B, CMO, PSE.getSE(), DL, II);
  2544. Escape->setName("ind.escape");
  2545. MissingVals[UI] = Escape;
  2546. }
  2547. }
  2548. for (auto &I : MissingVals) {
  2549. PHINode *PHI = cast<PHINode>(I.first);
  2550. // One corner case we have to handle is two IVs "chasing" each-other,
  2551. // that is %IV2 = phi [...], [ %IV1, %latch ]
  2552. // In this case, if IV1 has an external use, we need to avoid adding both
  2553. // "last value of IV1" and "penultimate value of IV2". So, verify that we
  2554. // don't already have an incoming value for the middle block.
  2555. if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
  2556. PHI->addIncoming(I.second, MiddleBlock);
  2557. }
  2558. }
  2559. namespace {
  2560. struct CSEDenseMapInfo {
  2561. static bool canHandle(const Instruction *I) {
  2562. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  2563. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  2564. }
  2565. static inline Instruction *getEmptyKey() {
  2566. return DenseMapInfo<Instruction *>::getEmptyKey();
  2567. }
  2568. static inline Instruction *getTombstoneKey() {
  2569. return DenseMapInfo<Instruction *>::getTombstoneKey();
  2570. }
  2571. static unsigned getHashValue(const Instruction *I) {
  2572. assert(canHandle(I) && "Unknown instruction!");
  2573. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  2574. I->value_op_end()));
  2575. }
  2576. static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
  2577. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  2578. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  2579. return LHS == RHS;
  2580. return LHS->isIdenticalTo(RHS);
  2581. }
  2582. };
  2583. } // end anonymous namespace
  2584. ///Perform cse of induction variable instructions.
  2585. static void cse(BasicBlock *BB) {
  2586. // Perform simple cse.
  2587. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  2588. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  2589. Instruction *In = &*I++;
  2590. if (!CSEDenseMapInfo::canHandle(In))
  2591. continue;
  2592. // Check if we can replace this instruction with any of the
  2593. // visited instructions.
  2594. if (Instruction *V = CSEMap.lookup(In)) {
  2595. In->replaceAllUsesWith(V);
  2596. In->eraseFromParent();
  2597. continue;
  2598. }
  2599. CSEMap[In] = In;
  2600. }
  2601. }
  2602. /// Estimate the overhead of scalarizing an instruction. This is a
  2603. /// convenience wrapper for the type-based getScalarizationOverhead API.
  2604. static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
  2605. const TargetTransformInfo &TTI) {
  2606. if (VF == 1)
  2607. return 0;
  2608. unsigned Cost = 0;
  2609. Type *RetTy = ToVectorTy(I->getType(), VF);
  2610. if (!RetTy->isVoidTy() &&
  2611. (!isa<LoadInst>(I) ||
  2612. !TTI.supportsEfficientVectorElementLoadStore()))
  2613. Cost += TTI.getScalarizationOverhead(RetTy, true, false);
  2614. // Some targets keep addresses scalar.
  2615. if (isa<LoadInst>(I) && !TTI.prefersVectorizedAddressing())
  2616. return Cost;
  2617. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  2618. SmallVector<const Value *, 4> Operands(CI->arg_operands());
  2619. Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
  2620. }
  2621. else if (!isa<StoreInst>(I) ||
  2622. !TTI.supportsEfficientVectorElementLoadStore()) {
  2623. SmallVector<const Value *, 4> Operands(I->operand_values());
  2624. Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
  2625. }
  2626. return Cost;
  2627. }
  2628. // Estimate cost of a call instruction CI if it were vectorized with factor VF.
  2629. // Return the cost of the instruction, including scalarization overhead if it's
  2630. // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
  2631. // i.e. either vector version isn't available, or is too expensive.
  2632. static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
  2633. const TargetTransformInfo &TTI,
  2634. const TargetLibraryInfo *TLI,
  2635. bool &NeedToScalarize) {
  2636. Function *F = CI->getCalledFunction();
  2637. StringRef FnName = CI->getCalledFunction()->getName();
  2638. Type *ScalarRetTy = CI->getType();
  2639. SmallVector<Type *, 4> Tys, ScalarTys;
  2640. for (auto &ArgOp : CI->arg_operands())
  2641. ScalarTys.push_back(ArgOp->getType());
  2642. // Estimate cost of scalarized vector call. The source operands are assumed
  2643. // to be vectors, so we need to extract individual elements from there,
  2644. // execute VF scalar calls, and then gather the result into the vector return
  2645. // value.
  2646. unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
  2647. if (VF == 1)
  2648. return ScalarCallCost;
  2649. // Compute corresponding vector type for return value and arguments.
  2650. Type *RetTy = ToVectorTy(ScalarRetTy, VF);
  2651. for (Type *ScalarTy : ScalarTys)
  2652. Tys.push_back(ToVectorTy(ScalarTy, VF));
  2653. // Compute costs of unpacking argument values for the scalar calls and
  2654. // packing the return values to a vector.
  2655. unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
  2656. unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
  2657. // If we can't emit a vector call for this function, then the currently found
  2658. // cost is the cost we need to return.
  2659. NeedToScalarize = true;
  2660. if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
  2661. return Cost;
  2662. // If the corresponding vector cost is cheaper, return its cost.
  2663. unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
  2664. if (VectorCallCost < Cost) {
  2665. NeedToScalarize = false;
  2666. return VectorCallCost;
  2667. }
  2668. return Cost;
  2669. }
  2670. // Estimate cost of an intrinsic call instruction CI if it were vectorized with
  2671. // factor VF. Return the cost of the instruction, including scalarization
  2672. // overhead if it's needed.
  2673. static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
  2674. const TargetTransformInfo &TTI,
  2675. const TargetLibraryInfo *TLI) {
  2676. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  2677. assert(ID && "Expected intrinsic call!");
  2678. FastMathFlags FMF;
  2679. if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
  2680. FMF = FPMO->getFastMathFlags();
  2681. SmallVector<Value *, 4> Operands(CI->arg_operands());
  2682. return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
  2683. }
  2684. static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
  2685. auto *I1 = cast<IntegerType>(T1->getVectorElementType());
  2686. auto *I2 = cast<IntegerType>(T2->getVectorElementType());
  2687. return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
  2688. }
  2689. static Type *largestIntegerVectorType(Type *T1, Type *T2) {
  2690. auto *I1 = cast<IntegerType>(T1->getVectorElementType());
  2691. auto *I2 = cast<IntegerType>(T2->getVectorElementType());
  2692. return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
  2693. }
  2694. void InnerLoopVectorizer::truncateToMinimalBitwidths() {
  2695. // For every instruction `I` in MinBWs, truncate the operands, create a
  2696. // truncated version of `I` and reextend its result. InstCombine runs
  2697. // later and will remove any ext/trunc pairs.
  2698. SmallPtrSet<Value *, 4> Erased;
  2699. for (const auto &KV : Cost->getMinimalBitwidths()) {
  2700. // If the value wasn't vectorized, we must maintain the original scalar
  2701. // type. The absence of the value from VectorLoopValueMap indicates that it
  2702. // wasn't vectorized.
  2703. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  2704. continue;
  2705. for (unsigned Part = 0; Part < UF; ++Part) {
  2706. Value *I = getOrCreateVectorValue(KV.first, Part);
  2707. if (Erased.find(I) != Erased.end() || I->use_empty() ||
  2708. !isa<Instruction>(I))
  2709. continue;
  2710. Type *OriginalTy = I->getType();
  2711. Type *ScalarTruncatedTy =
  2712. IntegerType::get(OriginalTy->getContext(), KV.second);
  2713. Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
  2714. OriginalTy->getVectorNumElements());
  2715. if (TruncatedTy == OriginalTy)
  2716. continue;
  2717. IRBuilder<> B(cast<Instruction>(I));
  2718. auto ShrinkOperand = [&](Value *V) -> Value * {
  2719. if (auto *ZI = dyn_cast<ZExtInst>(V))
  2720. if (ZI->getSrcTy() == TruncatedTy)
  2721. return ZI->getOperand(0);
  2722. return B.CreateZExtOrTrunc(V, TruncatedTy);
  2723. };
  2724. // The actual instruction modification depends on the instruction type,
  2725. // unfortunately.
  2726. Value *NewI = nullptr;
  2727. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  2728. NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
  2729. ShrinkOperand(BO->getOperand(1)));
  2730. // Any wrapping introduced by shrinking this operation shouldn't be
  2731. // considered undefined behavior. So, we can't unconditionally copy
  2732. // arithmetic wrapping flags to NewI.
  2733. cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
  2734. } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
  2735. NewI =
  2736. B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
  2737. ShrinkOperand(CI->getOperand(1)));
  2738. } else if (auto *SI = dyn_cast<SelectInst>(I)) {
  2739. NewI = B.CreateSelect(SI->getCondition(),
  2740. ShrinkOperand(SI->getTrueValue()),
  2741. ShrinkOperand(SI->getFalseValue()));
  2742. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  2743. switch (CI->getOpcode()) {
  2744. default:
  2745. llvm_unreachable("Unhandled cast!");
  2746. case Instruction::Trunc:
  2747. NewI = ShrinkOperand(CI->getOperand(0));
  2748. break;
  2749. case Instruction::SExt:
  2750. NewI = B.CreateSExtOrTrunc(
  2751. CI->getOperand(0),
  2752. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  2753. break;
  2754. case Instruction::ZExt:
  2755. NewI = B.CreateZExtOrTrunc(
  2756. CI->getOperand(0),
  2757. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  2758. break;
  2759. }
  2760. } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
  2761. auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
  2762. auto *O0 = B.CreateZExtOrTrunc(
  2763. SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
  2764. auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
  2765. auto *O1 = B.CreateZExtOrTrunc(
  2766. SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
  2767. NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
  2768. } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
  2769. // Don't do anything with the operands, just extend the result.
  2770. continue;
  2771. } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  2772. auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
  2773. auto *O0 = B.CreateZExtOrTrunc(
  2774. IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2775. auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
  2776. NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
  2777. } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
  2778. auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
  2779. auto *O0 = B.CreateZExtOrTrunc(
  2780. EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2781. NewI = B.CreateExtractElement(O0, EE->getOperand(2));
  2782. } else {
  2783. // If we don't know what to do, be conservative and don't do anything.
  2784. continue;
  2785. }
  2786. // Lastly, extend the result.
  2787. NewI->takeName(cast<Instruction>(I));
  2788. Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
  2789. I->replaceAllUsesWith(Res);
  2790. cast<Instruction>(I)->eraseFromParent();
  2791. Erased.insert(I);
  2792. VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
  2793. }
  2794. }
  2795. // We'll have created a bunch of ZExts that are now parentless. Clean up.
  2796. for (const auto &KV : Cost->getMinimalBitwidths()) {
  2797. // If the value wasn't vectorized, we must maintain the original scalar
  2798. // type. The absence of the value from VectorLoopValueMap indicates that it
  2799. // wasn't vectorized.
  2800. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  2801. continue;
  2802. for (unsigned Part = 0; Part < UF; ++Part) {
  2803. Value *I = getOrCreateVectorValue(KV.first, Part);
  2804. ZExtInst *Inst = dyn_cast<ZExtInst>(I);
  2805. if (Inst && Inst->use_empty()) {
  2806. Value *NewI = Inst->getOperand(0);
  2807. Inst->eraseFromParent();
  2808. VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
  2809. }
  2810. }
  2811. }
  2812. }
  2813. void InnerLoopVectorizer::fixVectorizedLoop() {
  2814. // Insert truncates and extends for any truncated instructions as hints to
  2815. // InstCombine.
  2816. if (VF > 1)
  2817. truncateToMinimalBitwidths();
  2818. // Fix widened non-induction PHIs by setting up the PHI operands.
  2819. if (OrigPHIsToFix.size()) {
  2820. assert(EnableVPlanNativePath &&
  2821. "Unexpected non-induction PHIs for fixup in non VPlan-native path");
  2822. fixNonInductionPHIs();
  2823. }
  2824. // At this point every instruction in the original loop is widened to a
  2825. // vector form. Now we need to fix the recurrences in the loop. These PHI
  2826. // nodes are currently empty because we did not want to introduce cycles.
  2827. // This is the second stage of vectorizing recurrences.
  2828. fixCrossIterationPHIs();
  2829. // Update the dominator tree.
  2830. //
  2831. // FIXME: After creating the structure of the new loop, the dominator tree is
  2832. // no longer up-to-date, and it remains that way until we update it
  2833. // here. An out-of-date dominator tree is problematic for SCEV,
  2834. // because SCEVExpander uses it to guide code generation. The
  2835. // vectorizer use SCEVExpanders in several places. Instead, we should
  2836. // keep the dominator tree up-to-date as we go.
  2837. updateAnalysis();
  2838. // Fix-up external users of the induction variables.
  2839. for (auto &Entry : *Legal->getInductionVars())
  2840. fixupIVUsers(Entry.first, Entry.second,
  2841. getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
  2842. IVEndValues[Entry.first], LoopMiddleBlock);
  2843. fixLCSSAPHIs();
  2844. for (Instruction *PI : PredicatedInstructions)
  2845. sinkScalarOperands(&*PI);
  2846. // Remove redundant induction instructions.
  2847. cse(LoopVectorBody);
  2848. }
  2849. void InnerLoopVectorizer::fixCrossIterationPHIs() {
  2850. // In order to support recurrences we need to be able to vectorize Phi nodes.
  2851. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  2852. // stage #2: We now need to fix the recurrences by adding incoming edges to
  2853. // the currently empty PHI nodes. At this point every instruction in the
  2854. // original loop is widened to a vector form so we can use them to construct
  2855. // the incoming edges.
  2856. for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
  2857. // Handle first-order recurrences and reductions that need to be fixed.
  2858. if (Legal->isFirstOrderRecurrence(&Phi))
  2859. fixFirstOrderRecurrence(&Phi);
  2860. else if (Legal->isReductionVariable(&Phi))
  2861. fixReduction(&Phi);
  2862. }
  2863. }
  2864. void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
  2865. // This is the second phase of vectorizing first-order recurrences. An
  2866. // overview of the transformation is described below. Suppose we have the
  2867. // following loop.
  2868. //
  2869. // for (int i = 0; i < n; ++i)
  2870. // b[i] = a[i] - a[i - 1];
  2871. //
  2872. // There is a first-order recurrence on "a". For this loop, the shorthand
  2873. // scalar IR looks like:
  2874. //
  2875. // scalar.ph:
  2876. // s_init = a[-1]
  2877. // br scalar.body
  2878. //
  2879. // scalar.body:
  2880. // i = phi [0, scalar.ph], [i+1, scalar.body]
  2881. // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
  2882. // s2 = a[i]
  2883. // b[i] = s2 - s1
  2884. // br cond, scalar.body, ...
  2885. //
  2886. // In this example, s1 is a recurrence because it's value depends on the
  2887. // previous iteration. In the first phase of vectorization, we created a
  2888. // temporary value for s1. We now complete the vectorization and produce the
  2889. // shorthand vector IR shown below (for VF = 4, UF = 1).
  2890. //
  2891. // vector.ph:
  2892. // v_init = vector(..., ..., ..., a[-1])
  2893. // br vector.body
  2894. //
  2895. // vector.body
  2896. // i = phi [0, vector.ph], [i+4, vector.body]
  2897. // v1 = phi [v_init, vector.ph], [v2, vector.body]
  2898. // v2 = a[i, i+1, i+2, i+3];
  2899. // v3 = vector(v1(3), v2(0, 1, 2))
  2900. // b[i, i+1, i+2, i+3] = v2 - v3
  2901. // br cond, vector.body, middle.block
  2902. //
  2903. // middle.block:
  2904. // x = v2(3)
  2905. // br scalar.ph
  2906. //
  2907. // scalar.ph:
  2908. // s_init = phi [x, middle.block], [a[-1], otherwise]
  2909. // br scalar.body
  2910. //
  2911. // After execution completes the vector loop, we extract the next value of
  2912. // the recurrence (x) to use as the initial value in the scalar loop.
  2913. // Get the original loop preheader and single loop latch.
  2914. auto *Preheader = OrigLoop->getLoopPreheader();
  2915. auto *Latch = OrigLoop->getLoopLatch();
  2916. // Get the initial and previous values of the scalar recurrence.
  2917. auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
  2918. auto *Previous = Phi->getIncomingValueForBlock(Latch);
  2919. // Create a vector from the initial value.
  2920. auto *VectorInit = ScalarInit;
  2921. if (VF > 1) {
  2922. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  2923. VectorInit = Builder.CreateInsertElement(
  2924. UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
  2925. Builder.getInt32(VF - 1), "vector.recur.init");
  2926. }
  2927. // We constructed a temporary phi node in the first phase of vectorization.
  2928. // This phi node will eventually be deleted.
  2929. Builder.SetInsertPoint(
  2930. cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
  2931. // Create a phi node for the new recurrence. The current value will either be
  2932. // the initial value inserted into a vector or loop-varying vector value.
  2933. auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
  2934. VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
  2935. // Get the vectorized previous value of the last part UF - 1. It appears last
  2936. // among all unrolled iterations, due to the order of their construction.
  2937. Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
  2938. // Set the insertion point after the previous value if it is an instruction.
  2939. // Note that the previous value may have been constant-folded so it is not
  2940. // guaranteed to be an instruction in the vector loop. Also, if the previous
  2941. // value is a phi node, we should insert after all the phi nodes to avoid
  2942. // breaking basic block verification.
  2943. if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
  2944. isa<PHINode>(PreviousLastPart))
  2945. Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
  2946. else
  2947. Builder.SetInsertPoint(
  2948. &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
  2949. // We will construct a vector for the recurrence by combining the values for
  2950. // the current and previous iterations. This is the required shuffle mask.
  2951. SmallVector<Constant *, 8> ShuffleMask(VF);
  2952. ShuffleMask[0] = Builder.getInt32(VF - 1);
  2953. for (unsigned I = 1; I < VF; ++I)
  2954. ShuffleMask[I] = Builder.getInt32(I + VF - 1);
  2955. // The vector from which to take the initial value for the current iteration
  2956. // (actual or unrolled). Initially, this is the vector phi node.
  2957. Value *Incoming = VecPhi;
  2958. // Shuffle the current and previous vector and update the vector parts.
  2959. for (unsigned Part = 0; Part < UF; ++Part) {
  2960. Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
  2961. Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
  2962. auto *Shuffle =
  2963. VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
  2964. ConstantVector::get(ShuffleMask))
  2965. : Incoming;
  2966. PhiPart->replaceAllUsesWith(Shuffle);
  2967. cast<Instruction>(PhiPart)->eraseFromParent();
  2968. VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
  2969. Incoming = PreviousPart;
  2970. }
  2971. // Fix the latch value of the new recurrence in the vector loop.
  2972. VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  2973. // Extract the last vector element in the middle block. This will be the
  2974. // initial value for the recurrence when jumping to the scalar loop.
  2975. auto *ExtractForScalar = Incoming;
  2976. if (VF > 1) {
  2977. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  2978. ExtractForScalar = Builder.CreateExtractElement(
  2979. ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
  2980. }
  2981. // Extract the second last element in the middle block if the
  2982. // Phi is used outside the loop. We need to extract the phi itself
  2983. // and not the last element (the phi update in the current iteration). This
  2984. // will be the value when jumping to the exit block from the LoopMiddleBlock,
  2985. // when the scalar loop is not run at all.
  2986. Value *ExtractForPhiUsedOutsideLoop = nullptr;
  2987. if (VF > 1)
  2988. ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
  2989. Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
  2990. // When loop is unrolled without vectorizing, initialize
  2991. // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
  2992. // `Incoming`. This is analogous to the vectorized case above: extracting the
  2993. // second last element when VF > 1.
  2994. else if (UF > 1)
  2995. ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
  2996. // Fix the initial value of the original recurrence in the scalar loop.
  2997. Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
  2998. auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
  2999. for (auto *BB : predecessors(LoopScalarPreHeader)) {
  3000. auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
  3001. Start->addIncoming(Incoming, BB);
  3002. }
  3003. Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
  3004. Phi->setName("scalar.recur");
  3005. // Finally, fix users of the recurrence outside the loop. The users will need
  3006. // either the last value of the scalar recurrence or the last value of the
  3007. // vector recurrence we extracted in the middle block. Since the loop is in
  3008. // LCSSA form, we just need to find all the phi nodes for the original scalar
  3009. // recurrence in the exit block, and then add an edge for the middle block.
  3010. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3011. if (LCSSAPhi.getIncomingValue(0) == Phi) {
  3012. LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
  3013. }
  3014. }
  3015. }
  3016. void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
  3017. Constant *Zero = Builder.getInt32(0);
  3018. // Get it's reduction variable descriptor.
  3019. assert(Legal->isReductionVariable(Phi) &&
  3020. "Unable to find the reduction variable");
  3021. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
  3022. RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
  3023. TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
  3024. Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
  3025. RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
  3026. RdxDesc.getMinMaxRecurrenceKind();
  3027. setDebugLocFromInst(Builder, ReductionStartValue);
  3028. // We need to generate a reduction vector from the incoming scalar.
  3029. // To do so, we need to generate the 'identity' vector and override
  3030. // one of the elements with the incoming scalar reduction. We need
  3031. // to do it in the vector-loop preheader.
  3032. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  3033. // This is the vector-clone of the value that leaves the loop.
  3034. Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
  3035. // Find the reduction identity variable. Zero for addition, or, xor,
  3036. // one for multiplication, -1 for And.
  3037. Value *Identity;
  3038. Value *VectorStart;
  3039. if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
  3040. RK == RecurrenceDescriptor::RK_FloatMinMax) {
  3041. // MinMax reduction have the start value as their identify.
  3042. if (VF == 1) {
  3043. VectorStart = Identity = ReductionStartValue;
  3044. } else {
  3045. VectorStart = Identity =
  3046. Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
  3047. }
  3048. } else {
  3049. // Handle other reduction kinds:
  3050. Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
  3051. RK, VecTy->getScalarType());
  3052. if (VF == 1) {
  3053. Identity = Iden;
  3054. // This vector is the Identity vector where the first element is the
  3055. // incoming scalar reduction.
  3056. VectorStart = ReductionStartValue;
  3057. } else {
  3058. Identity = ConstantVector::getSplat(VF, Iden);
  3059. // This vector is the Identity vector where the first element is the
  3060. // incoming scalar reduction.
  3061. VectorStart =
  3062. Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
  3063. }
  3064. }
  3065. // Fix the vector-loop phi.
  3066. // Reductions do not have to start at zero. They can start with
  3067. // any loop invariant values.
  3068. BasicBlock *Latch = OrigLoop->getLoopLatch();
  3069. Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
  3070. for (unsigned Part = 0; Part < UF; ++Part) {
  3071. Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
  3072. Value *Val = getOrCreateVectorValue(LoopVal, Part);
  3073. // Make sure to add the reduction stat value only to the
  3074. // first unroll part.
  3075. Value *StartVal = (Part == 0) ? VectorStart : Identity;
  3076. cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
  3077. cast<PHINode>(VecRdxPhi)
  3078. ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3079. }
  3080. // Before each round, move the insertion point right between
  3081. // the PHIs and the values we are going to write.
  3082. // This allows us to write both PHINodes and the extractelement
  3083. // instructions.
  3084. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3085. setDebugLocFromInst(Builder, LoopExitInst);
  3086. // If the vector reduction can be performed in a smaller type, we truncate
  3087. // then extend the loop exit value to enable InstCombine to evaluate the
  3088. // entire expression in the smaller type.
  3089. if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
  3090. Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
  3091. Builder.SetInsertPoint(
  3092. LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
  3093. VectorParts RdxParts(UF);
  3094. for (unsigned Part = 0; Part < UF; ++Part) {
  3095. RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3096. Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3097. Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
  3098. : Builder.CreateZExt(Trunc, VecTy);
  3099. for (Value::user_iterator UI = RdxParts[Part]->user_begin();
  3100. UI != RdxParts[Part]->user_end();)
  3101. if (*UI != Trunc) {
  3102. (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
  3103. RdxParts[Part] = Extnd;
  3104. } else {
  3105. ++UI;
  3106. }
  3107. }
  3108. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3109. for (unsigned Part = 0; Part < UF; ++Part) {
  3110. RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3111. VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
  3112. }
  3113. }
  3114. // Reduce all of the unrolled parts into a single vector.
  3115. Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
  3116. unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
  3117. // The middle block terminator has already been assigned a DebugLoc here (the
  3118. // OrigLoop's single latch terminator). We want the whole middle block to
  3119. // appear to execute on this line because: (a) it is all compiler generated,
  3120. // (b) these instructions are always executed after evaluating the latch
  3121. // conditional branch, and (c) other passes may add new predecessors which
  3122. // terminate on this line. This is the easiest way to ensure we don't
  3123. // accidently cause an extra step back into the loop while debugging.
  3124. setDebugLocFromInst(Builder, LoopMiddleBlock->getTerminator());
  3125. for (unsigned Part = 1; Part < UF; ++Part) {
  3126. Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3127. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  3128. // Floating point operations had to be 'fast' to enable the reduction.
  3129. ReducedPartRdx = addFastMathFlag(
  3130. Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
  3131. ReducedPartRdx, "bin.rdx"),
  3132. RdxDesc.getFastMathFlags());
  3133. else
  3134. ReducedPartRdx = createMinMaxOp(Builder, MinMaxKind, ReducedPartRdx,
  3135. RdxPart);
  3136. }
  3137. if (VF > 1) {
  3138. bool NoNaN = Legal->hasFunNoNaNAttr();
  3139. ReducedPartRdx =
  3140. createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
  3141. // If the reduction can be performed in a smaller type, we need to extend
  3142. // the reduction to the wider type before we branch to the original loop.
  3143. if (Phi->getType() != RdxDesc.getRecurrenceType())
  3144. ReducedPartRdx =
  3145. RdxDesc.isSigned()
  3146. ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
  3147. : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
  3148. }
  3149. // Create a phi node that merges control-flow from the backedge-taken check
  3150. // block and the middle block.
  3151. PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
  3152. LoopScalarPreHeader->getTerminator());
  3153. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  3154. BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
  3155. BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3156. // Now, we need to fix the users of the reduction variable
  3157. // inside and outside of the scalar remainder loop.
  3158. // We know that the loop is in LCSSA form. We need to update the
  3159. // PHI nodes in the exit blocks.
  3160. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3161. // All PHINodes need to have a single entry edge, or two if
  3162. // we already fixed them.
  3163. assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
  3164. // We found a reduction value exit-PHI. Update it with the
  3165. // incoming bypass edge.
  3166. if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
  3167. LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3168. } // end of the LCSSA phi scan.
  3169. // Fix the scalar loop reduction variable with the incoming reduction sum
  3170. // from the vector body and from the backedge value.
  3171. int IncomingEdgeBlockIdx =
  3172. Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
  3173. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  3174. // Pick the other block.
  3175. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  3176. Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
  3177. Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
  3178. }
  3179. void InnerLoopVectorizer::fixLCSSAPHIs() {
  3180. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3181. if (LCSSAPhi.getNumIncomingValues() == 1) {
  3182. auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
  3183. // Non-instruction incoming values will have only one value.
  3184. unsigned LastLane = 0;
  3185. if (isa<Instruction>(IncomingValue))
  3186. LastLane = Cost->isUniformAfterVectorization(
  3187. cast<Instruction>(IncomingValue), VF)
  3188. ? 0
  3189. : VF - 1;
  3190. // Can be a loop invariant incoming value or the last scalar value to be
  3191. // extracted from the vectorized loop.
  3192. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3193. Value *lastIncomingValue =
  3194. getOrCreateScalarValue(IncomingValue, { UF - 1, LastLane });
  3195. LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
  3196. }
  3197. }
  3198. }
  3199. void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
  3200. // The basic block and loop containing the predicated instruction.
  3201. auto *PredBB = PredInst->getParent();
  3202. auto *VectorLoop = LI->getLoopFor(PredBB);
  3203. // Initialize a worklist with the operands of the predicated instruction.
  3204. SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
  3205. // Holds instructions that we need to analyze again. An instruction may be
  3206. // reanalyzed if we don't yet know if we can sink it or not.
  3207. SmallVector<Instruction *, 8> InstsToReanalyze;
  3208. // Returns true if a given use occurs in the predicated block. Phi nodes use
  3209. // their operands in their corresponding predecessor blocks.
  3210. auto isBlockOfUsePredicated = [&](Use &U) -> bool {
  3211. auto *I = cast<Instruction>(U.getUser());
  3212. BasicBlock *BB = I->getParent();
  3213. if (auto *Phi = dyn_cast<PHINode>(I))
  3214. BB = Phi->getIncomingBlock(
  3215. PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
  3216. return BB == PredBB;
  3217. };
  3218. // Iteratively sink the scalarized operands of the predicated instruction
  3219. // into the block we created for it. When an instruction is sunk, it's
  3220. // operands are then added to the worklist. The algorithm ends after one pass
  3221. // through the worklist doesn't sink a single instruction.
  3222. bool Changed;
  3223. do {
  3224. // Add the instructions that need to be reanalyzed to the worklist, and
  3225. // reset the changed indicator.
  3226. Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
  3227. InstsToReanalyze.clear();
  3228. Changed = false;
  3229. while (!Worklist.empty()) {
  3230. auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
  3231. // We can't sink an instruction if it is a phi node, is already in the
  3232. // predicated block, is not in the loop, or may have side effects.
  3233. if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
  3234. !VectorLoop->contains(I) || I->mayHaveSideEffects())
  3235. continue;
  3236. // It's legal to sink the instruction if all its uses occur in the
  3237. // predicated block. Otherwise, there's nothing to do yet, and we may
  3238. // need to reanalyze the instruction.
  3239. if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
  3240. InstsToReanalyze.push_back(I);
  3241. continue;
  3242. }
  3243. // Move the instruction to the beginning of the predicated block, and add
  3244. // it's operands to the worklist.
  3245. I->moveBefore(&*PredBB->getFirstInsertionPt());
  3246. Worklist.insert(I->op_begin(), I->op_end());
  3247. // The sinking may have enabled other instructions to be sunk, so we will
  3248. // need to iterate.
  3249. Changed = true;
  3250. }
  3251. } while (Changed);
  3252. }
  3253. void InnerLoopVectorizer::fixNonInductionPHIs() {
  3254. for (PHINode *OrigPhi : OrigPHIsToFix) {
  3255. PHINode *NewPhi =
  3256. cast<PHINode>(VectorLoopValueMap.getVectorValue(OrigPhi, 0));
  3257. unsigned NumIncomingValues = OrigPhi->getNumIncomingValues();
  3258. SmallVector<BasicBlock *, 2> ScalarBBPredecessors(
  3259. predecessors(OrigPhi->getParent()));
  3260. SmallVector<BasicBlock *, 2> VectorBBPredecessors(
  3261. predecessors(NewPhi->getParent()));
  3262. assert(ScalarBBPredecessors.size() == VectorBBPredecessors.size() &&
  3263. "Scalar and Vector BB should have the same number of predecessors");
  3264. // The insertion point in Builder may be invalidated by the time we get
  3265. // here. Force the Builder insertion point to something valid so that we do
  3266. // not run into issues during insertion point restore in
  3267. // getOrCreateVectorValue calls below.
  3268. Builder.SetInsertPoint(NewPhi);
  3269. // The predecessor order is preserved and we can rely on mapping between
  3270. // scalar and vector block predecessors.
  3271. for (unsigned i = 0; i < NumIncomingValues; ++i) {
  3272. BasicBlock *NewPredBB = VectorBBPredecessors[i];
  3273. // When looking up the new scalar/vector values to fix up, use incoming
  3274. // values from original phi.
  3275. Value *ScIncV =
  3276. OrigPhi->getIncomingValueForBlock(ScalarBBPredecessors[i]);
  3277. // Scalar incoming value may need a broadcast
  3278. Value *NewIncV = getOrCreateVectorValue(ScIncV, 0);
  3279. NewPhi->addIncoming(NewIncV, NewPredBB);
  3280. }
  3281. }
  3282. }
  3283. void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
  3284. unsigned VF) {
  3285. PHINode *P = cast<PHINode>(PN);
  3286. if (EnableVPlanNativePath) {
  3287. // Currently we enter here in the VPlan-native path for non-induction
  3288. // PHIs where all control flow is uniform. We simply widen these PHIs.
  3289. // Create a vector phi with no operands - the vector phi operands will be
  3290. // set at the end of vector code generation.
  3291. Type *VecTy =
  3292. (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
  3293. Value *VecPhi = Builder.CreatePHI(VecTy, PN->getNumOperands(), "vec.phi");
  3294. VectorLoopValueMap.setVectorValue(P, 0, VecPhi);
  3295. OrigPHIsToFix.push_back(P);
  3296. return;
  3297. }
  3298. assert(PN->getParent() == OrigLoop->getHeader() &&
  3299. "Non-header phis should have been handled elsewhere");
  3300. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3301. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  3302. // stage #1: We create a new vector PHI node with no incoming edges. We'll use
  3303. // this value when we vectorize all of the instructions that use the PHI.
  3304. if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
  3305. for (unsigned Part = 0; Part < UF; ++Part) {
  3306. // This is phase one of vectorizing PHIs.
  3307. Type *VecTy =
  3308. (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
  3309. Value *EntryPart = PHINode::Create(
  3310. VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
  3311. VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
  3312. }
  3313. return;
  3314. }
  3315. setDebugLocFromInst(Builder, P);
  3316. // This PHINode must be an induction variable.
  3317. // Make sure that we know about it.
  3318. assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
  3319. InductionDescriptor II = Legal->getInductionVars()->lookup(P);
  3320. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  3321. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  3322. // which can be found from the original scalar operations.
  3323. switch (II.getKind()) {
  3324. case InductionDescriptor::IK_NoInduction:
  3325. llvm_unreachable("Unknown induction");
  3326. case InductionDescriptor::IK_IntInduction:
  3327. case InductionDescriptor::IK_FpInduction:
  3328. llvm_unreachable("Integer/fp induction is handled elsewhere.");
  3329. case InductionDescriptor::IK_PtrInduction: {
  3330. // Handle the pointer induction variable case.
  3331. assert(P->getType()->isPointerTy() && "Unexpected type.");
  3332. // This is the normalized GEP that starts counting at zero.
  3333. Value *PtrInd = Induction;
  3334. PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
  3335. // Determine the number of scalars we need to generate for each unroll
  3336. // iteration. If the instruction is uniform, we only need to generate the
  3337. // first lane. Otherwise, we generate all VF values.
  3338. unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
  3339. // These are the scalar results. Notice that we don't generate vector GEPs
  3340. // because scalar GEPs result in better code.
  3341. for (unsigned Part = 0; Part < UF; ++Part) {
  3342. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  3343. Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
  3344. Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
  3345. Value *SclrGep =
  3346. emitTransformedIndex(Builder, GlobalIdx, PSE.getSE(), DL, II);
  3347. SclrGep->setName("next.gep");
  3348. VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
  3349. }
  3350. }
  3351. return;
  3352. }
  3353. }
  3354. }
  3355. /// A helper function for checking whether an integer division-related
  3356. /// instruction may divide by zero (in which case it must be predicated if
  3357. /// executed conditionally in the scalar code).
  3358. /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
  3359. /// Non-zero divisors that are non compile-time constants will not be
  3360. /// converted into multiplication, so we will still end up scalarizing
  3361. /// the division, but can do so w/o predication.
  3362. static bool mayDivideByZero(Instruction &I) {
  3363. assert((I.getOpcode() == Instruction::UDiv ||
  3364. I.getOpcode() == Instruction::SDiv ||
  3365. I.getOpcode() == Instruction::URem ||
  3366. I.getOpcode() == Instruction::SRem) &&
  3367. "Unexpected instruction");
  3368. Value *Divisor = I.getOperand(1);
  3369. auto *CInt = dyn_cast<ConstantInt>(Divisor);
  3370. return !CInt || CInt->isZero();
  3371. }
  3372. void InnerLoopVectorizer::widenInstruction(Instruction &I) {
  3373. switch (I.getOpcode()) {
  3374. case Instruction::Br:
  3375. case Instruction::PHI:
  3376. llvm_unreachable("This instruction is handled by a different recipe.");
  3377. case Instruction::GetElementPtr: {
  3378. // Construct a vector GEP by widening the operands of the scalar GEP as
  3379. // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
  3380. // results in a vector of pointers when at least one operand of the GEP
  3381. // is vector-typed. Thus, to keep the representation compact, we only use
  3382. // vector-typed operands for loop-varying values.
  3383. auto *GEP = cast<GetElementPtrInst>(&I);
  3384. if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
  3385. // If we are vectorizing, but the GEP has only loop-invariant operands,
  3386. // the GEP we build (by only using vector-typed operands for
  3387. // loop-varying values) would be a scalar pointer. Thus, to ensure we
  3388. // produce a vector of pointers, we need to either arbitrarily pick an
  3389. // operand to broadcast, or broadcast a clone of the original GEP.
  3390. // Here, we broadcast a clone of the original.
  3391. //
  3392. // TODO: If at some point we decide to scalarize instructions having
  3393. // loop-invariant operands, this special case will no longer be
  3394. // required. We would add the scalarization decision to
  3395. // collectLoopScalars() and teach getVectorValue() to broadcast
  3396. // the lane-zero scalar value.
  3397. auto *Clone = Builder.Insert(GEP->clone());
  3398. for (unsigned Part = 0; Part < UF; ++Part) {
  3399. Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
  3400. VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
  3401. addMetadata(EntryPart, GEP);
  3402. }
  3403. } else {
  3404. // If the GEP has at least one loop-varying operand, we are sure to
  3405. // produce a vector of pointers. But if we are only unrolling, we want
  3406. // to produce a scalar GEP for each unroll part. Thus, the GEP we
  3407. // produce with the code below will be scalar (if VF == 1) or vector
  3408. // (otherwise). Note that for the unroll-only case, we still maintain
  3409. // values in the vector mapping with initVector, as we do for other
  3410. // instructions.
  3411. for (unsigned Part = 0; Part < UF; ++Part) {
  3412. // The pointer operand of the new GEP. If it's loop-invariant, we
  3413. // won't broadcast it.
  3414. auto *Ptr =
  3415. OrigLoop->isLoopInvariant(GEP->getPointerOperand())
  3416. ? GEP->getPointerOperand()
  3417. : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
  3418. // Collect all the indices for the new GEP. If any index is
  3419. // loop-invariant, we won't broadcast it.
  3420. SmallVector<Value *, 4> Indices;
  3421. for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
  3422. if (OrigLoop->isLoopInvariant(U.get()))
  3423. Indices.push_back(U.get());
  3424. else
  3425. Indices.push_back(getOrCreateVectorValue(U.get(), Part));
  3426. }
  3427. // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
  3428. // but it should be a vector, otherwise.
  3429. auto *NewGEP =
  3430. GEP->isInBounds()
  3431. ? Builder.CreateInBoundsGEP(GEP->getSourceElementType(), Ptr,
  3432. Indices)
  3433. : Builder.CreateGEP(GEP->getSourceElementType(), Ptr, Indices);
  3434. assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
  3435. "NewGEP is not a pointer vector");
  3436. VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
  3437. addMetadata(NewGEP, GEP);
  3438. }
  3439. }
  3440. break;
  3441. }
  3442. case Instruction::UDiv:
  3443. case Instruction::SDiv:
  3444. case Instruction::SRem:
  3445. case Instruction::URem:
  3446. case Instruction::Add:
  3447. case Instruction::FAdd:
  3448. case Instruction::Sub:
  3449. case Instruction::FSub:
  3450. case Instruction::Mul:
  3451. case Instruction::FMul:
  3452. case Instruction::FDiv:
  3453. case Instruction::FRem:
  3454. case Instruction::Shl:
  3455. case Instruction::LShr:
  3456. case Instruction::AShr:
  3457. case Instruction::And:
  3458. case Instruction::Or:
  3459. case Instruction::Xor: {
  3460. // Just widen binops.
  3461. auto *BinOp = cast<BinaryOperator>(&I);
  3462. setDebugLocFromInst(Builder, BinOp);
  3463. for (unsigned Part = 0; Part < UF; ++Part) {
  3464. Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
  3465. Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
  3466. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
  3467. if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
  3468. VecOp->copyIRFlags(BinOp);
  3469. // Use this vector value for all users of the original instruction.
  3470. VectorLoopValueMap.setVectorValue(&I, Part, V);
  3471. addMetadata(V, BinOp);
  3472. }
  3473. break;
  3474. }
  3475. case Instruction::Select: {
  3476. // Widen selects.
  3477. // If the selector is loop invariant we can create a select
  3478. // instruction with a scalar condition. Otherwise, use vector-select.
  3479. auto *SE = PSE.getSE();
  3480. bool InvariantCond =
  3481. SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
  3482. setDebugLocFromInst(Builder, &I);
  3483. // The condition can be loop invariant but still defined inside the
  3484. // loop. This means that we can't just use the original 'cond' value.
  3485. // We have to take the 'vectorized' value and pick the first lane.
  3486. // Instcombine will make this a no-op.
  3487. auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
  3488. for (unsigned Part = 0; Part < UF; ++Part) {
  3489. Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
  3490. Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
  3491. Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
  3492. Value *Sel =
  3493. Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
  3494. VectorLoopValueMap.setVectorValue(&I, Part, Sel);
  3495. addMetadata(Sel, &I);
  3496. }
  3497. break;
  3498. }
  3499. case Instruction::ICmp:
  3500. case Instruction::FCmp: {
  3501. // Widen compares. Generate vector compares.
  3502. bool FCmp = (I.getOpcode() == Instruction::FCmp);
  3503. auto *Cmp = dyn_cast<CmpInst>(&I);
  3504. setDebugLocFromInst(Builder, Cmp);
  3505. for (unsigned Part = 0; Part < UF; ++Part) {
  3506. Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
  3507. Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
  3508. Value *C = nullptr;
  3509. if (FCmp) {
  3510. // Propagate fast math flags.
  3511. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  3512. Builder.setFastMathFlags(Cmp->getFastMathFlags());
  3513. C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
  3514. } else {
  3515. C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
  3516. }
  3517. VectorLoopValueMap.setVectorValue(&I, Part, C);
  3518. addMetadata(C, &I);
  3519. }
  3520. break;
  3521. }
  3522. case Instruction::ZExt:
  3523. case Instruction::SExt:
  3524. case Instruction::FPToUI:
  3525. case Instruction::FPToSI:
  3526. case Instruction::FPExt:
  3527. case Instruction::PtrToInt:
  3528. case Instruction::IntToPtr:
  3529. case Instruction::SIToFP:
  3530. case Instruction::UIToFP:
  3531. case Instruction::Trunc:
  3532. case Instruction::FPTrunc:
  3533. case Instruction::BitCast: {
  3534. auto *CI = dyn_cast<CastInst>(&I);
  3535. setDebugLocFromInst(Builder, CI);
  3536. /// Vectorize casts.
  3537. Type *DestTy =
  3538. (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
  3539. for (unsigned Part = 0; Part < UF; ++Part) {
  3540. Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
  3541. Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
  3542. VectorLoopValueMap.setVectorValue(&I, Part, Cast);
  3543. addMetadata(Cast, &I);
  3544. }
  3545. break;
  3546. }
  3547. case Instruction::Call: {
  3548. // Ignore dbg intrinsics.
  3549. if (isa<DbgInfoIntrinsic>(I))
  3550. break;
  3551. setDebugLocFromInst(Builder, &I);
  3552. Module *M = I.getParent()->getParent()->getParent();
  3553. auto *CI = cast<CallInst>(&I);
  3554. StringRef FnName = CI->getCalledFunction()->getName();
  3555. Function *F = CI->getCalledFunction();
  3556. Type *RetTy = ToVectorTy(CI->getType(), VF);
  3557. SmallVector<Type *, 4> Tys;
  3558. for (Value *ArgOperand : CI->arg_operands())
  3559. Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
  3560. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3561. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  3562. // version of the instruction.
  3563. // Is it beneficial to perform intrinsic call compared to lib call?
  3564. bool NeedToScalarize;
  3565. unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
  3566. bool UseVectorIntrinsic =
  3567. ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
  3568. assert((UseVectorIntrinsic || !NeedToScalarize) &&
  3569. "Instruction should be scalarized elsewhere.");
  3570. for (unsigned Part = 0; Part < UF; ++Part) {
  3571. SmallVector<Value *, 4> Args;
  3572. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  3573. Value *Arg = CI->getArgOperand(i);
  3574. // Some intrinsics have a scalar argument - don't replace it with a
  3575. // vector.
  3576. if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
  3577. Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
  3578. Args.push_back(Arg);
  3579. }
  3580. Function *VectorF;
  3581. if (UseVectorIntrinsic) {
  3582. // Use vector version of the intrinsic.
  3583. Type *TysForDecl[] = {CI->getType()};
  3584. if (VF > 1)
  3585. TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  3586. VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
  3587. } else {
  3588. // Use vector version of the library call.
  3589. StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
  3590. assert(!VFnName.empty() && "Vector function name is empty.");
  3591. VectorF = M->getFunction(VFnName);
  3592. if (!VectorF) {
  3593. // Generate a declaration
  3594. FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
  3595. VectorF =
  3596. Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
  3597. VectorF->copyAttributesFrom(F);
  3598. }
  3599. }
  3600. assert(VectorF && "Can't create vector function.");
  3601. SmallVector<OperandBundleDef, 1> OpBundles;
  3602. CI->getOperandBundlesAsDefs(OpBundles);
  3603. CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
  3604. if (isa<FPMathOperator>(V))
  3605. V->copyFastMathFlags(CI);
  3606. VectorLoopValueMap.setVectorValue(&I, Part, V);
  3607. addMetadata(V, &I);
  3608. }
  3609. break;
  3610. }
  3611. default:
  3612. // This instruction is not vectorized by simple widening.
  3613. LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
  3614. llvm_unreachable("Unhandled instruction!");
  3615. } // end of switch.
  3616. }
  3617. void InnerLoopVectorizer::updateAnalysis() {
  3618. // Forget the original basic block.
  3619. PSE.getSE()->forgetLoop(OrigLoop);
  3620. // DT is not kept up-to-date for outer loop vectorization
  3621. if (EnableVPlanNativePath)
  3622. return;
  3623. // Update the dominator tree information.
  3624. assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
  3625. "Entry does not dominate exit.");
  3626. DT->addNewBlock(LoopMiddleBlock,
  3627. LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3628. DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
  3629. DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
  3630. DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
  3631. assert(DT->verify(DominatorTree::VerificationLevel::Fast));
  3632. }
  3633. void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
  3634. // We should not collect Scalars more than once per VF. Right now, this
  3635. // function is called from collectUniformsAndScalars(), which already does
  3636. // this check. Collecting Scalars for VF=1 does not make any sense.
  3637. assert(VF >= 2 && Scalars.find(VF) == Scalars.end() &&
  3638. "This function should not be visited twice for the same VF");
  3639. SmallSetVector<Instruction *, 8> Worklist;
  3640. // These sets are used to seed the analysis with pointers used by memory
  3641. // accesses that will remain scalar.
  3642. SmallSetVector<Instruction *, 8> ScalarPtrs;
  3643. SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
  3644. // A helper that returns true if the use of Ptr by MemAccess will be scalar.
  3645. // The pointer operands of loads and stores will be scalar as long as the
  3646. // memory access is not a gather or scatter operation. The value operand of a
  3647. // store will remain scalar if the store is scalarized.
  3648. auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
  3649. InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
  3650. assert(WideningDecision != CM_Unknown &&
  3651. "Widening decision should be ready at this moment");
  3652. if (auto *Store = dyn_cast<StoreInst>(MemAccess))
  3653. if (Ptr == Store->getValueOperand())
  3654. return WideningDecision == CM_Scalarize;
  3655. assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
  3656. "Ptr is neither a value or pointer operand");
  3657. return WideningDecision != CM_GatherScatter;
  3658. };
  3659. // A helper that returns true if the given value is a bitcast or
  3660. // getelementptr instruction contained in the loop.
  3661. auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
  3662. return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
  3663. isa<GetElementPtrInst>(V)) &&
  3664. !TheLoop->isLoopInvariant(V);
  3665. };
  3666. // A helper that evaluates a memory access's use of a pointer. If the use
  3667. // will be a scalar use, and the pointer is only used by memory accesses, we
  3668. // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
  3669. // PossibleNonScalarPtrs.
  3670. auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
  3671. // We only care about bitcast and getelementptr instructions contained in
  3672. // the loop.
  3673. if (!isLoopVaryingBitCastOrGEP(Ptr))
  3674. return;
  3675. // If the pointer has already been identified as scalar (e.g., if it was
  3676. // also identified as uniform), there's nothing to do.
  3677. auto *I = cast<Instruction>(Ptr);
  3678. if (Worklist.count(I))
  3679. return;
  3680. // If the use of the pointer will be a scalar use, and all users of the
  3681. // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
  3682. // place the pointer in PossibleNonScalarPtrs.
  3683. if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
  3684. return isa<LoadInst>(U) || isa<StoreInst>(U);
  3685. }))
  3686. ScalarPtrs.insert(I);
  3687. else
  3688. PossibleNonScalarPtrs.insert(I);
  3689. };
  3690. // We seed the scalars analysis with three classes of instructions: (1)
  3691. // instructions marked uniform-after-vectorization, (2) bitcast and
  3692. // getelementptr instructions used by memory accesses requiring a scalar use,
  3693. // and (3) pointer induction variables and their update instructions (we
  3694. // currently only scalarize these).
  3695. //
  3696. // (1) Add to the worklist all instructions that have been identified as
  3697. // uniform-after-vectorization.
  3698. Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
  3699. // (2) Add to the worklist all bitcast and getelementptr instructions used by
  3700. // memory accesses requiring a scalar use. The pointer operands of loads and
  3701. // stores will be scalar as long as the memory accesses is not a gather or
  3702. // scatter operation. The value operand of a store will remain scalar if the
  3703. // store is scalarized.
  3704. for (auto *BB : TheLoop->blocks())
  3705. for (auto &I : *BB) {
  3706. if (auto *Load = dyn_cast<LoadInst>(&I)) {
  3707. evaluatePtrUse(Load, Load->getPointerOperand());
  3708. } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
  3709. evaluatePtrUse(Store, Store->getPointerOperand());
  3710. evaluatePtrUse(Store, Store->getValueOperand());
  3711. }
  3712. }
  3713. for (auto *I : ScalarPtrs)
  3714. if (PossibleNonScalarPtrs.find(I) == PossibleNonScalarPtrs.end()) {
  3715. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
  3716. Worklist.insert(I);
  3717. }
  3718. // (3) Add to the worklist all pointer induction variables and their update
  3719. // instructions.
  3720. //
  3721. // TODO: Once we are able to vectorize pointer induction variables we should
  3722. // no longer insert them into the worklist here.
  3723. auto *Latch = TheLoop->getLoopLatch();
  3724. for (auto &Induction : *Legal->getInductionVars()) {
  3725. auto *Ind = Induction.first;
  3726. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3727. if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
  3728. continue;
  3729. Worklist.insert(Ind);
  3730. Worklist.insert(IndUpdate);
  3731. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  3732. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  3733. << "\n");
  3734. }
  3735. // Insert the forced scalars.
  3736. // FIXME: Currently widenPHIInstruction() often creates a dead vector
  3737. // induction variable when the PHI user is scalarized.
  3738. auto ForcedScalar = ForcedScalars.find(VF);
  3739. if (ForcedScalar != ForcedScalars.end())
  3740. for (auto *I : ForcedScalar->second)
  3741. Worklist.insert(I);
  3742. // Expand the worklist by looking through any bitcasts and getelementptr
  3743. // instructions we've already identified as scalar. This is similar to the
  3744. // expansion step in collectLoopUniforms(); however, here we're only
  3745. // expanding to include additional bitcasts and getelementptr instructions.
  3746. unsigned Idx = 0;
  3747. while (Idx != Worklist.size()) {
  3748. Instruction *Dst = Worklist[Idx++];
  3749. if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
  3750. continue;
  3751. auto *Src = cast<Instruction>(Dst->getOperand(0));
  3752. if (llvm::all_of(Src->users(), [&](User *U) -> bool {
  3753. auto *J = cast<Instruction>(U);
  3754. return !TheLoop->contains(J) || Worklist.count(J) ||
  3755. ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
  3756. isScalarUse(J, Src));
  3757. })) {
  3758. Worklist.insert(Src);
  3759. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
  3760. }
  3761. }
  3762. // An induction variable will remain scalar if all users of the induction
  3763. // variable and induction variable update remain scalar.
  3764. for (auto &Induction : *Legal->getInductionVars()) {
  3765. auto *Ind = Induction.first;
  3766. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3767. // We already considered pointer induction variables, so there's no reason
  3768. // to look at their users again.
  3769. //
  3770. // TODO: Once we are able to vectorize pointer induction variables we
  3771. // should no longer skip over them here.
  3772. if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
  3773. continue;
  3774. // Determine if all users of the induction variable are scalar after
  3775. // vectorization.
  3776. auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  3777. auto *I = cast<Instruction>(U);
  3778. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
  3779. });
  3780. if (!ScalarInd)
  3781. continue;
  3782. // Determine if all users of the induction variable update instruction are
  3783. // scalar after vectorization.
  3784. auto ScalarIndUpdate =
  3785. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  3786. auto *I = cast<Instruction>(U);
  3787. return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
  3788. });
  3789. if (!ScalarIndUpdate)
  3790. continue;
  3791. // The induction variable and its update instruction will remain scalar.
  3792. Worklist.insert(Ind);
  3793. Worklist.insert(IndUpdate);
  3794. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  3795. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  3796. << "\n");
  3797. }
  3798. Scalars[VF].insert(Worklist.begin(), Worklist.end());
  3799. }
  3800. bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I, unsigned VF) {
  3801. if (!blockNeedsPredication(I->getParent()))
  3802. return false;
  3803. switch(I->getOpcode()) {
  3804. default:
  3805. break;
  3806. case Instruction::Load:
  3807. case Instruction::Store: {
  3808. if (!Legal->isMaskRequired(I))
  3809. return false;
  3810. auto *Ptr = getLoadStorePointerOperand(I);
  3811. auto *Ty = getMemInstValueType(I);
  3812. // We have already decided how to vectorize this instruction, get that
  3813. // result.
  3814. if (VF > 1) {
  3815. InstWidening WideningDecision = getWideningDecision(I, VF);
  3816. assert(WideningDecision != CM_Unknown &&
  3817. "Widening decision should be ready at this moment");
  3818. return WideningDecision == CM_Scalarize;
  3819. }
  3820. return isa<LoadInst>(I) ?
  3821. !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty))
  3822. : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
  3823. }
  3824. case Instruction::UDiv:
  3825. case Instruction::SDiv:
  3826. case Instruction::SRem:
  3827. case Instruction::URem:
  3828. return mayDivideByZero(*I);
  3829. }
  3830. return false;
  3831. }
  3832. bool LoopVectorizationCostModel::interleavedAccessCanBeWidened(Instruction *I,
  3833. unsigned VF) {
  3834. assert(isAccessInterleaved(I) && "Expecting interleaved access.");
  3835. assert(getWideningDecision(I, VF) == CM_Unknown &&
  3836. "Decision should not be set yet.");
  3837. auto *Group = getInterleavedAccessGroup(I);
  3838. assert(Group && "Must have a group.");
  3839. // Check if masking is required.
  3840. // A Group may need masking for one of two reasons: it resides in a block that
  3841. // needs predication, or it was decided to use masking to deal with gaps.
  3842. bool PredicatedAccessRequiresMasking =
  3843. Legal->blockNeedsPredication(I->getParent()) && Legal->isMaskRequired(I);
  3844. bool AccessWithGapsRequiresMasking =
  3845. Group->requiresScalarEpilogue() && !IsScalarEpilogueAllowed;
  3846. if (!PredicatedAccessRequiresMasking && !AccessWithGapsRequiresMasking)
  3847. return true;
  3848. // If masked interleaving is required, we expect that the user/target had
  3849. // enabled it, because otherwise it either wouldn't have been created or
  3850. // it should have been invalidated by the CostModel.
  3851. assert(useMaskedInterleavedAccesses(TTI) &&
  3852. "Masked interleave-groups for predicated accesses are not enabled.");
  3853. auto *Ty = getMemInstValueType(I);
  3854. return isa<LoadInst>(I) ? TTI.isLegalMaskedLoad(Ty)
  3855. : TTI.isLegalMaskedStore(Ty);
  3856. }
  3857. bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I,
  3858. unsigned VF) {
  3859. // Get and ensure we have a valid memory instruction.
  3860. LoadInst *LI = dyn_cast<LoadInst>(I);
  3861. StoreInst *SI = dyn_cast<StoreInst>(I);
  3862. assert((LI || SI) && "Invalid memory instruction");
  3863. auto *Ptr = getLoadStorePointerOperand(I);
  3864. // In order to be widened, the pointer should be consecutive, first of all.
  3865. if (!Legal->isConsecutivePtr(Ptr))
  3866. return false;
  3867. // If the instruction is a store located in a predicated block, it will be
  3868. // scalarized.
  3869. if (isScalarWithPredication(I))
  3870. return false;
  3871. // If the instruction's allocated size doesn't equal it's type size, it
  3872. // requires padding and will be scalarized.
  3873. auto &DL = I->getModule()->getDataLayout();
  3874. auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  3875. if (hasIrregularType(ScalarTy, DL, VF))
  3876. return false;
  3877. return true;
  3878. }
  3879. void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
  3880. // We should not collect Uniforms more than once per VF. Right now,
  3881. // this function is called from collectUniformsAndScalars(), which
  3882. // already does this check. Collecting Uniforms for VF=1 does not make any
  3883. // sense.
  3884. assert(VF >= 2 && Uniforms.find(VF) == Uniforms.end() &&
  3885. "This function should not be visited twice for the same VF");
  3886. // Visit the list of Uniforms. If we'll not find any uniform value, we'll
  3887. // not analyze again. Uniforms.count(VF) will return 1.
  3888. Uniforms[VF].clear();
  3889. // We now know that the loop is vectorizable!
  3890. // Collect instructions inside the loop that will remain uniform after
  3891. // vectorization.
  3892. // Global values, params and instructions outside of current loop are out of
  3893. // scope.
  3894. auto isOutOfScope = [&](Value *V) -> bool {
  3895. Instruction *I = dyn_cast<Instruction>(V);
  3896. return (!I || !TheLoop->contains(I));
  3897. };
  3898. SetVector<Instruction *> Worklist;
  3899. BasicBlock *Latch = TheLoop->getLoopLatch();
  3900. // Start with the conditional branch. If the branch condition is an
  3901. // instruction contained in the loop that is only used by the branch, it is
  3902. // uniform.
  3903. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  3904. if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
  3905. Worklist.insert(Cmp);
  3906. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
  3907. }
  3908. // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
  3909. // are pointers that are treated like consecutive pointers during
  3910. // vectorization. The pointer operands of interleaved accesses are an
  3911. // example.
  3912. SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
  3913. // Holds pointer operands of instructions that are possibly non-uniform.
  3914. SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
  3915. auto isUniformDecision = [&](Instruction *I, unsigned VF) {
  3916. InstWidening WideningDecision = getWideningDecision(I, VF);
  3917. assert(WideningDecision != CM_Unknown &&
  3918. "Widening decision should be ready at this moment");
  3919. return (WideningDecision == CM_Widen ||
  3920. WideningDecision == CM_Widen_Reverse ||
  3921. WideningDecision == CM_Interleave);
  3922. };
  3923. // Iterate over the instructions in the loop, and collect all
  3924. // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
  3925. // that a consecutive-like pointer operand will be scalarized, we collect it
  3926. // in PossibleNonUniformPtrs instead. We use two sets here because a single
  3927. // getelementptr instruction can be used by both vectorized and scalarized
  3928. // memory instructions. For example, if a loop loads and stores from the same
  3929. // location, but the store is conditional, the store will be scalarized, and
  3930. // the getelementptr won't remain uniform.
  3931. for (auto *BB : TheLoop->blocks())
  3932. for (auto &I : *BB) {
  3933. // If there's no pointer operand, there's nothing to do.
  3934. auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  3935. if (!Ptr)
  3936. continue;
  3937. // True if all users of Ptr are memory accesses that have Ptr as their
  3938. // pointer operand.
  3939. auto UsersAreMemAccesses =
  3940. llvm::all_of(Ptr->users(), [&](User *U) -> bool {
  3941. return getLoadStorePointerOperand(U) == Ptr;
  3942. });
  3943. // Ensure the memory instruction will not be scalarized or used by
  3944. // gather/scatter, making its pointer operand non-uniform. If the pointer
  3945. // operand is used by any instruction other than a memory access, we
  3946. // conservatively assume the pointer operand may be non-uniform.
  3947. if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
  3948. PossibleNonUniformPtrs.insert(Ptr);
  3949. // If the memory instruction will be vectorized and its pointer operand
  3950. // is consecutive-like, or interleaving - the pointer operand should
  3951. // remain uniform.
  3952. else
  3953. ConsecutiveLikePtrs.insert(Ptr);
  3954. }
  3955. // Add to the Worklist all consecutive and consecutive-like pointers that
  3956. // aren't also identified as possibly non-uniform.
  3957. for (auto *V : ConsecutiveLikePtrs)
  3958. if (PossibleNonUniformPtrs.find(V) == PossibleNonUniformPtrs.end()) {
  3959. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
  3960. Worklist.insert(V);
  3961. }
  3962. // Expand Worklist in topological order: whenever a new instruction
  3963. // is added , its users should be already inside Worklist. It ensures
  3964. // a uniform instruction will only be used by uniform instructions.
  3965. unsigned idx = 0;
  3966. while (idx != Worklist.size()) {
  3967. Instruction *I = Worklist[idx++];
  3968. for (auto OV : I->operand_values()) {
  3969. // isOutOfScope operands cannot be uniform instructions.
  3970. if (isOutOfScope(OV))
  3971. continue;
  3972. // First order recurrence Phi's should typically be considered
  3973. // non-uniform.
  3974. auto *OP = dyn_cast<PHINode>(OV);
  3975. if (OP && Legal->isFirstOrderRecurrence(OP))
  3976. continue;
  3977. // If all the users of the operand are uniform, then add the
  3978. // operand into the uniform worklist.
  3979. auto *OI = cast<Instruction>(OV);
  3980. if (llvm::all_of(OI->users(), [&](User *U) -> bool {
  3981. auto *J = cast<Instruction>(U);
  3982. return Worklist.count(J) ||
  3983. (OI == getLoadStorePointerOperand(J) &&
  3984. isUniformDecision(J, VF));
  3985. })) {
  3986. Worklist.insert(OI);
  3987. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
  3988. }
  3989. }
  3990. }
  3991. // Returns true if Ptr is the pointer operand of a memory access instruction
  3992. // I, and I is known to not require scalarization.
  3993. auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
  3994. return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
  3995. };
  3996. // For an instruction to be added into Worklist above, all its users inside
  3997. // the loop should also be in Worklist. However, this condition cannot be
  3998. // true for phi nodes that form a cyclic dependence. We must process phi
  3999. // nodes separately. An induction variable will remain uniform if all users
  4000. // of the induction variable and induction variable update remain uniform.
  4001. // The code below handles both pointer and non-pointer induction variables.
  4002. for (auto &Induction : *Legal->getInductionVars()) {
  4003. auto *Ind = Induction.first;
  4004. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  4005. // Determine if all users of the induction variable are uniform after
  4006. // vectorization.
  4007. auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  4008. auto *I = cast<Instruction>(U);
  4009. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
  4010. isVectorizedMemAccessUse(I, Ind);
  4011. });
  4012. if (!UniformInd)
  4013. continue;
  4014. // Determine if all users of the induction variable update instruction are
  4015. // uniform after vectorization.
  4016. auto UniformIndUpdate =
  4017. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  4018. auto *I = cast<Instruction>(U);
  4019. return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
  4020. isVectorizedMemAccessUse(I, IndUpdate);
  4021. });
  4022. if (!UniformIndUpdate)
  4023. continue;
  4024. // The induction variable and its update instruction will remain uniform.
  4025. Worklist.insert(Ind);
  4026. Worklist.insert(IndUpdate);
  4027. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
  4028. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate
  4029. << "\n");
  4030. }
  4031. Uniforms[VF].insert(Worklist.begin(), Worklist.end());
  4032. }
  4033. Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
  4034. if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
  4035. // TODO: It may by useful to do since it's still likely to be dynamically
  4036. // uniform if the target can skip.
  4037. LLVM_DEBUG(
  4038. dbgs() << "LV: Not inserting runtime ptr check for divergent target");
  4039. ORE->emit(
  4040. createMissedAnalysis("CantVersionLoopWithDivergentTarget")
  4041. << "runtime pointer checks needed. Not enabled for divergent target");
  4042. return None;
  4043. }
  4044. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4045. if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
  4046. return computeFeasibleMaxVF(OptForSize, TC);
  4047. if (Legal->getRuntimePointerChecking()->Need) {
  4048. ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
  4049. << "runtime pointer checks needed. Enable vectorization of this "
  4050. "loop with '#pragma clang loop vectorize(enable)' when "
  4051. "compiling with -Os/-Oz");
  4052. LLVM_DEBUG(
  4053. dbgs()
  4054. << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
  4055. return None;
  4056. }
  4057. if (!PSE.getUnionPredicate().getPredicates().empty()) {
  4058. ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
  4059. << "runtime SCEV checks needed. Enable vectorization of this "
  4060. "loop with '#pragma clang loop vectorize(enable)' when "
  4061. "compiling with -Os/-Oz");
  4062. LLVM_DEBUG(
  4063. dbgs()
  4064. << "LV: Aborting. Runtime SCEV check is required with -Os/-Oz.\n");
  4065. return None;
  4066. }
  4067. // FIXME: Avoid specializing for stride==1 instead of bailing out.
  4068. if (!Legal->getLAI()->getSymbolicStrides().empty()) {
  4069. ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
  4070. << "runtime stride == 1 checks needed. Enable vectorization of "
  4071. "this loop with '#pragma clang loop vectorize(enable)' when "
  4072. "compiling with -Os/-Oz");
  4073. LLVM_DEBUG(
  4074. dbgs()
  4075. << "LV: Aborting. Runtime stride check is required with -Os/-Oz.\n");
  4076. return None;
  4077. }
  4078. // If we optimize the program for size, avoid creating the tail loop.
  4079. LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4080. if (TC == 1) {
  4081. ORE->emit(createMissedAnalysis("SingleIterationLoop")
  4082. << "loop trip count is one, irrelevant for vectorization");
  4083. LLVM_DEBUG(dbgs() << "LV: Aborting, single iteration (non) loop.\n");
  4084. return None;
  4085. }
  4086. // Record that scalar epilogue is not allowed.
  4087. LLVM_DEBUG(dbgs() << "LV: Not allowing scalar epilogue due to -Os/-Oz.\n");
  4088. IsScalarEpilogueAllowed = !OptForSize;
  4089. // We don't create an epilogue when optimizing for size.
  4090. // Invalidate interleave groups that require an epilogue if we can't mask
  4091. // the interleave-group.
  4092. if (!useMaskedInterleavedAccesses(TTI))
  4093. InterleaveInfo.invalidateGroupsRequiringScalarEpilogue();
  4094. unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
  4095. if (TC > 0 && TC % MaxVF == 0) {
  4096. LLVM_DEBUG(dbgs() << "LV: No tail will remain for any chosen VF.\n");
  4097. return MaxVF;
  4098. }
  4099. // If we don't know the precise trip count, or if the trip count that we
  4100. // found modulo the vectorization factor is not zero, try to fold the tail
  4101. // by masking.
  4102. // FIXME: look for a smaller MaxVF that does divide TC rather than masking.
  4103. if (Legal->canFoldTailByMasking()) {
  4104. FoldTailByMasking = true;
  4105. return MaxVF;
  4106. }
  4107. if (TC == 0) {
  4108. ORE->emit(
  4109. createMissedAnalysis("UnknownLoopCountComplexCFG")
  4110. << "unable to calculate the loop count due to complex control flow");
  4111. return None;
  4112. }
  4113. ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
  4114. << "cannot optimize for size and vectorize at the same time. "
  4115. "Enable vectorization of this loop with '#pragma clang loop "
  4116. "vectorize(enable)' when compiling with -Os/-Oz");
  4117. return None;
  4118. }
  4119. unsigned
  4120. LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
  4121. unsigned ConstTripCount) {
  4122. MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
  4123. unsigned SmallestType, WidestType;
  4124. std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
  4125. unsigned WidestRegister = TTI.getRegisterBitWidth(true);
  4126. // Get the maximum safe dependence distance in bits computed by LAA.
  4127. // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
  4128. // the memory accesses that is most restrictive (involved in the smallest
  4129. // dependence distance).
  4130. unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
  4131. WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
  4132. unsigned MaxVectorSize = WidestRegister / WidestType;
  4133. LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
  4134. << " / " << WidestType << " bits.\n");
  4135. LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
  4136. << WidestRegister << " bits.\n");
  4137. assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"
  4138. " into one vector!");
  4139. if (MaxVectorSize == 0) {
  4140. LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
  4141. MaxVectorSize = 1;
  4142. return MaxVectorSize;
  4143. } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
  4144. isPowerOf2_32(ConstTripCount)) {
  4145. // We need to clamp the VF to be the ConstTripCount. There is no point in
  4146. // choosing a higher viable VF as done in the loop below.
  4147. LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
  4148. << ConstTripCount << "\n");
  4149. MaxVectorSize = ConstTripCount;
  4150. return MaxVectorSize;
  4151. }
  4152. unsigned MaxVF = MaxVectorSize;
  4153. if (TTI.shouldMaximizeVectorBandwidth(OptForSize) ||
  4154. (MaximizeBandwidth && !OptForSize)) {
  4155. // Collect all viable vectorization factors larger than the default MaxVF
  4156. // (i.e. MaxVectorSize).
  4157. SmallVector<unsigned, 8> VFs;
  4158. unsigned NewMaxVectorSize = WidestRegister / SmallestType;
  4159. for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
  4160. VFs.push_back(VS);
  4161. // For each VF calculate its register usage.
  4162. auto RUs = calculateRegisterUsage(VFs);
  4163. // Select the largest VF which doesn't require more registers than existing
  4164. // ones.
  4165. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
  4166. for (int i = RUs.size() - 1; i >= 0; --i) {
  4167. if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
  4168. MaxVF = VFs[i];
  4169. break;
  4170. }
  4171. }
  4172. if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
  4173. if (MaxVF < MinVF) {
  4174. LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
  4175. << ") with target's minimum: " << MinVF << '\n');
  4176. MaxVF = MinVF;
  4177. }
  4178. }
  4179. }
  4180. return MaxVF;
  4181. }
  4182. VectorizationFactor
  4183. LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
  4184. float Cost = expectedCost(1).first;
  4185. const float ScalarCost = Cost;
  4186. unsigned Width = 1;
  4187. LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
  4188. bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
  4189. if (ForceVectorization && MaxVF > 1) {
  4190. // Ignore scalar width, because the user explicitly wants vectorization.
  4191. // Initialize cost to max so that VF = 2 is, at least, chosen during cost
  4192. // evaluation.
  4193. Cost = std::numeric_limits<float>::max();
  4194. }
  4195. for (unsigned i = 2; i <= MaxVF; i *= 2) {
  4196. // Notice that the vector loop needs to be executed less times, so
  4197. // we need to divide the cost of the vector loops by the width of
  4198. // the vector elements.
  4199. VectorizationCostTy C = expectedCost(i);
  4200. float VectorCost = C.first / (float)i;
  4201. LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
  4202. << " costs: " << (int)VectorCost << ".\n");
  4203. if (!C.second && !ForceVectorization) {
  4204. LLVM_DEBUG(
  4205. dbgs() << "LV: Not considering vector loop of width " << i
  4206. << " because it will not generate any vector instructions.\n");
  4207. continue;
  4208. }
  4209. if (VectorCost < Cost) {
  4210. Cost = VectorCost;
  4211. Width = i;
  4212. }
  4213. }
  4214. if (!EnableCondStoresVectorization && NumPredStores) {
  4215. ORE->emit(createMissedAnalysis("ConditionalStore")
  4216. << "store that is conditionally executed prevents vectorization");
  4217. LLVM_DEBUG(
  4218. dbgs() << "LV: No vectorization. There are conditional stores.\n");
  4219. Width = 1;
  4220. Cost = ScalarCost;
  4221. }
  4222. LLVM_DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
  4223. << "LV: Vectorization seems to be not beneficial, "
  4224. << "but was forced by a user.\n");
  4225. LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
  4226. VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
  4227. return Factor;
  4228. }
  4229. std::pair<unsigned, unsigned>
  4230. LoopVectorizationCostModel::getSmallestAndWidestTypes() {
  4231. unsigned MinWidth = -1U;
  4232. unsigned MaxWidth = 8;
  4233. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4234. // For each block.
  4235. for (BasicBlock *BB : TheLoop->blocks()) {
  4236. // For each instruction in the loop.
  4237. for (Instruction &I : BB->instructionsWithoutDebug()) {
  4238. Type *T = I.getType();
  4239. // Skip ignored values.
  4240. if (ValuesToIgnore.find(&I) != ValuesToIgnore.end())
  4241. continue;
  4242. // Only examine Loads, Stores and PHINodes.
  4243. if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
  4244. continue;
  4245. // Examine PHI nodes that are reduction variables. Update the type to
  4246. // account for the recurrence type.
  4247. if (auto *PN = dyn_cast<PHINode>(&I)) {
  4248. if (!Legal->isReductionVariable(PN))
  4249. continue;
  4250. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
  4251. T = RdxDesc.getRecurrenceType();
  4252. }
  4253. // Examine the stored values.
  4254. if (auto *ST = dyn_cast<StoreInst>(&I))
  4255. T = ST->getValueOperand()->getType();
  4256. // Ignore loaded pointer types and stored pointer types that are not
  4257. // vectorizable.
  4258. //
  4259. // FIXME: The check here attempts to predict whether a load or store will
  4260. // be vectorized. We only know this for certain after a VF has
  4261. // been selected. Here, we assume that if an access can be
  4262. // vectorized, it will be. We should also look at extending this
  4263. // optimization to non-pointer types.
  4264. //
  4265. if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
  4266. !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
  4267. continue;
  4268. MinWidth = std::min(MinWidth,
  4269. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4270. MaxWidth = std::max(MaxWidth,
  4271. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4272. }
  4273. }
  4274. return {MinWidth, MaxWidth};
  4275. }
  4276. unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
  4277. unsigned VF,
  4278. unsigned LoopCost) {
  4279. // -- The interleave heuristics --
  4280. // We interleave the loop in order to expose ILP and reduce the loop overhead.
  4281. // There are many micro-architectural considerations that we can't predict
  4282. // at this level. For example, frontend pressure (on decode or fetch) due to
  4283. // code size, or the number and capabilities of the execution ports.
  4284. //
  4285. // We use the following heuristics to select the interleave count:
  4286. // 1. If the code has reductions, then we interleave to break the cross
  4287. // iteration dependency.
  4288. // 2. If the loop is really small, then we interleave to reduce the loop
  4289. // overhead.
  4290. // 3. We don't interleave if we think that we will spill registers to memory
  4291. // due to the increased register pressure.
  4292. // When we optimize for size, we don't interleave.
  4293. if (OptForSize)
  4294. return 1;
  4295. // We used the distance for the interleave count.
  4296. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4297. return 1;
  4298. // Do not interleave loops with a relatively small trip count.
  4299. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4300. if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
  4301. return 1;
  4302. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
  4303. LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
  4304. << " registers\n");
  4305. if (VF == 1) {
  4306. if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
  4307. TargetNumRegisters = ForceTargetNumScalarRegs;
  4308. } else {
  4309. if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
  4310. TargetNumRegisters = ForceTargetNumVectorRegs;
  4311. }
  4312. RegisterUsage R = calculateRegisterUsage({VF})[0];
  4313. // We divide by these constants so assume that we have at least one
  4314. // instruction that uses at least one register.
  4315. R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
  4316. // We calculate the interleave count using the following formula.
  4317. // Subtract the number of loop invariants from the number of available
  4318. // registers. These registers are used by all of the interleaved instances.
  4319. // Next, divide the remaining registers by the number of registers that is
  4320. // required by the loop, in order to estimate how many parallel instances
  4321. // fit without causing spills. All of this is rounded down if necessary to be
  4322. // a power of two. We want power of two interleave count to simplify any
  4323. // addressing operations or alignment considerations.
  4324. // We also want power of two interleave counts to ensure that the induction
  4325. // variable of the vector loop wraps to zero, when tail is folded by masking;
  4326. // this currently happens when OptForSize, in which case IC is set to 1 above.
  4327. unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
  4328. R.MaxLocalUsers);
  4329. // Don't count the induction variable as interleaved.
  4330. if (EnableIndVarRegisterHeur)
  4331. IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
  4332. std::max(1U, (R.MaxLocalUsers - 1)));
  4333. // Clamp the interleave ranges to reasonable counts.
  4334. unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
  4335. // Check if the user has overridden the max.
  4336. if (VF == 1) {
  4337. if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
  4338. MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
  4339. } else {
  4340. if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
  4341. MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
  4342. }
  4343. // If we did not calculate the cost for VF (because the user selected the VF)
  4344. // then we calculate the cost of VF here.
  4345. if (LoopCost == 0)
  4346. LoopCost = expectedCost(VF).first;
  4347. // Clamp the calculated IC to be between the 1 and the max interleave count
  4348. // that the target allows.
  4349. if (IC > MaxInterleaveCount)
  4350. IC = MaxInterleaveCount;
  4351. else if (IC < 1)
  4352. IC = 1;
  4353. // Interleave if we vectorized this loop and there is a reduction that could
  4354. // benefit from interleaving.
  4355. if (VF > 1 && !Legal->getReductionVars()->empty()) {
  4356. LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
  4357. return IC;
  4358. }
  4359. // Note that if we've already vectorized the loop we will have done the
  4360. // runtime check and so interleaving won't require further checks.
  4361. bool InterleavingRequiresRuntimePointerCheck =
  4362. (VF == 1 && Legal->getRuntimePointerChecking()->Need);
  4363. // We want to interleave small loops in order to reduce the loop overhead and
  4364. // potentially expose ILP opportunities.
  4365. LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
  4366. if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
  4367. // We assume that the cost overhead is 1 and we use the cost model
  4368. // to estimate the cost of the loop and interleave until the cost of the
  4369. // loop overhead is about 5% of the cost of the loop.
  4370. unsigned SmallIC =
  4371. std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
  4372. // Interleave until store/load ports (estimated by max interleave count) are
  4373. // saturated.
  4374. unsigned NumStores = Legal->getNumStores();
  4375. unsigned NumLoads = Legal->getNumLoads();
  4376. unsigned StoresIC = IC / (NumStores ? NumStores : 1);
  4377. unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
  4378. // If we have a scalar reduction (vector reductions are already dealt with
  4379. // by this point), we can increase the critical path length if the loop
  4380. // we're interleaving is inside another loop. Limit, by default to 2, so the
  4381. // critical path only gets increased by one reduction operation.
  4382. if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) {
  4383. unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
  4384. SmallIC = std::min(SmallIC, F);
  4385. StoresIC = std::min(StoresIC, F);
  4386. LoadsIC = std::min(LoadsIC, F);
  4387. }
  4388. if (EnableLoadStoreRuntimeInterleave &&
  4389. std::max(StoresIC, LoadsIC) > SmallIC) {
  4390. LLVM_DEBUG(
  4391. dbgs() << "LV: Interleaving to saturate store or load ports.\n");
  4392. return std::max(StoresIC, LoadsIC);
  4393. }
  4394. LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
  4395. return SmallIC;
  4396. }
  4397. // Interleave if this is a large loop (small loops are already dealt with by
  4398. // this point) that could benefit from interleaving.
  4399. bool HasReductions = !Legal->getReductionVars()->empty();
  4400. if (TTI.enableAggressiveInterleaving(HasReductions)) {
  4401. LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  4402. return IC;
  4403. }
  4404. LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
  4405. return 1;
  4406. }
  4407. SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
  4408. LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
  4409. // This function calculates the register usage by measuring the highest number
  4410. // of values that are alive at a single location. Obviously, this is a very
  4411. // rough estimation. We scan the loop in a topological order in order and
  4412. // assign a number to each instruction. We use RPO to ensure that defs are
  4413. // met before their users. We assume that each instruction that has in-loop
  4414. // users starts an interval. We record every time that an in-loop value is
  4415. // used, so we have a list of the first and last occurrences of each
  4416. // instruction. Next, we transpose this data structure into a multi map that
  4417. // holds the list of intervals that *end* at a specific location. This multi
  4418. // map allows us to perform a linear search. We scan the instructions linearly
  4419. // and record each time that a new interval starts, by placing it in a set.
  4420. // If we find this value in the multi-map then we remove it from the set.
  4421. // The max register usage is the maximum size of the set.
  4422. // We also search for instructions that are defined outside the loop, but are
  4423. // used inside the loop. We need this number separately from the max-interval
  4424. // usage number because when we unroll, loop-invariant values do not take
  4425. // more register.
  4426. LoopBlocksDFS DFS(TheLoop);
  4427. DFS.perform(LI);
  4428. RegisterUsage RU;
  4429. // Each 'key' in the map opens a new interval. The values
  4430. // of the map are the index of the 'last seen' usage of the
  4431. // instruction that is the key.
  4432. using IntervalMap = DenseMap<Instruction *, unsigned>;
  4433. // Maps instruction to its index.
  4434. SmallVector<Instruction *, 64> IdxToInstr;
  4435. // Marks the end of each interval.
  4436. IntervalMap EndPoint;
  4437. // Saves the list of instruction indices that are used in the loop.
  4438. SmallPtrSet<Instruction *, 8> Ends;
  4439. // Saves the list of values that are used in the loop but are
  4440. // defined outside the loop, such as arguments and constants.
  4441. SmallPtrSet<Value *, 8> LoopInvariants;
  4442. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  4443. for (Instruction &I : BB->instructionsWithoutDebug()) {
  4444. IdxToInstr.push_back(&I);
  4445. // Save the end location of each USE.
  4446. for (Value *U : I.operands()) {
  4447. auto *Instr = dyn_cast<Instruction>(U);
  4448. // Ignore non-instruction values such as arguments, constants, etc.
  4449. if (!Instr)
  4450. continue;
  4451. // If this instruction is outside the loop then record it and continue.
  4452. if (!TheLoop->contains(Instr)) {
  4453. LoopInvariants.insert(Instr);
  4454. continue;
  4455. }
  4456. // Overwrite previous end points.
  4457. EndPoint[Instr] = IdxToInstr.size();
  4458. Ends.insert(Instr);
  4459. }
  4460. }
  4461. }
  4462. // Saves the list of intervals that end with the index in 'key'.
  4463. using InstrList = SmallVector<Instruction *, 2>;
  4464. DenseMap<unsigned, InstrList> TransposeEnds;
  4465. // Transpose the EndPoints to a list of values that end at each index.
  4466. for (auto &Interval : EndPoint)
  4467. TransposeEnds[Interval.second].push_back(Interval.first);
  4468. SmallPtrSet<Instruction *, 8> OpenIntervals;
  4469. // Get the size of the widest register.
  4470. unsigned MaxSafeDepDist = -1U;
  4471. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4472. MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
  4473. unsigned WidestRegister =
  4474. std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
  4475. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4476. SmallVector<RegisterUsage, 8> RUs(VFs.size());
  4477. SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
  4478. LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  4479. // A lambda that gets the register usage for the given type and VF.
  4480. auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
  4481. if (Ty->isTokenTy())
  4482. return 0U;
  4483. unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
  4484. return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
  4485. };
  4486. for (unsigned int i = 0, s = IdxToInstr.size(); i < s; ++i) {
  4487. Instruction *I = IdxToInstr[i];
  4488. // Remove all of the instructions that end at this location.
  4489. InstrList &List = TransposeEnds[i];
  4490. for (Instruction *ToRemove : List)
  4491. OpenIntervals.erase(ToRemove);
  4492. // Ignore instructions that are never used within the loop.
  4493. if (Ends.find(I) == Ends.end())
  4494. continue;
  4495. // Skip ignored values.
  4496. if (ValuesToIgnore.find(I) != ValuesToIgnore.end())
  4497. continue;
  4498. // For each VF find the maximum usage of registers.
  4499. for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
  4500. if (VFs[j] == 1) {
  4501. MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
  4502. continue;
  4503. }
  4504. collectUniformsAndScalars(VFs[j]);
  4505. // Count the number of live intervals.
  4506. unsigned RegUsage = 0;
  4507. for (auto Inst : OpenIntervals) {
  4508. // Skip ignored values for VF > 1.
  4509. if (VecValuesToIgnore.find(Inst) != VecValuesToIgnore.end() ||
  4510. isScalarAfterVectorization(Inst, VFs[j]))
  4511. continue;
  4512. RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
  4513. }
  4514. MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
  4515. }
  4516. LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
  4517. << OpenIntervals.size() << '\n');
  4518. // Add the current instruction to the list of open intervals.
  4519. OpenIntervals.insert(I);
  4520. }
  4521. for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
  4522. unsigned Invariant = 0;
  4523. if (VFs[i] == 1)
  4524. Invariant = LoopInvariants.size();
  4525. else {
  4526. for (auto Inst : LoopInvariants)
  4527. Invariant += GetRegUsage(Inst->getType(), VFs[i]);
  4528. }
  4529. LLVM_DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
  4530. LLVM_DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
  4531. LLVM_DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant
  4532. << '\n');
  4533. RU.LoopInvariantRegs = Invariant;
  4534. RU.MaxLocalUsers = MaxUsages[i];
  4535. RUs[i] = RU;
  4536. }
  4537. return RUs;
  4538. }
  4539. bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
  4540. // TODO: Cost model for emulated masked load/store is completely
  4541. // broken. This hack guides the cost model to use an artificially
  4542. // high enough value to practically disable vectorization with such
  4543. // operations, except where previously deployed legality hack allowed
  4544. // using very low cost values. This is to avoid regressions coming simply
  4545. // from moving "masked load/store" check from legality to cost model.
  4546. // Masked Load/Gather emulation was previously never allowed.
  4547. // Limited number of Masked Store/Scatter emulation was allowed.
  4548. assert(isPredicatedInst(I) && "Expecting a scalar emulated instruction");
  4549. return isa<LoadInst>(I) ||
  4550. (isa<StoreInst>(I) &&
  4551. NumPredStores > NumberOfStoresToPredicate);
  4552. }
  4553. void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
  4554. // If we aren't vectorizing the loop, or if we've already collected the
  4555. // instructions to scalarize, there's nothing to do. Collection may already
  4556. // have occurred if we have a user-selected VF and are now computing the
  4557. // expected cost for interleaving.
  4558. if (VF < 2 || InstsToScalarize.find(VF) != InstsToScalarize.end())
  4559. return;
  4560. // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
  4561. // not profitable to scalarize any instructions, the presence of VF in the
  4562. // map will indicate that we've analyzed it already.
  4563. ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
  4564. // Find all the instructions that are scalar with predication in the loop and
  4565. // determine if it would be better to not if-convert the blocks they are in.
  4566. // If so, we also record the instructions to scalarize.
  4567. for (BasicBlock *BB : TheLoop->blocks()) {
  4568. if (!blockNeedsPredication(BB))
  4569. continue;
  4570. for (Instruction &I : *BB)
  4571. if (isScalarWithPredication(&I)) {
  4572. ScalarCostsTy ScalarCosts;
  4573. // Do not apply discount logic if hacked cost is needed
  4574. // for emulated masked memrefs.
  4575. if (!useEmulatedMaskMemRefHack(&I) &&
  4576. computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
  4577. ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
  4578. // Remember that BB will remain after vectorization.
  4579. PredicatedBBsAfterVectorization.insert(BB);
  4580. }
  4581. }
  4582. }
  4583. int LoopVectorizationCostModel::computePredInstDiscount(
  4584. Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
  4585. unsigned VF) {
  4586. assert(!isUniformAfterVectorization(PredInst, VF) &&
  4587. "Instruction marked uniform-after-vectorization will be predicated");
  4588. // Initialize the discount to zero, meaning that the scalar version and the
  4589. // vector version cost the same.
  4590. int Discount = 0;
  4591. // Holds instructions to analyze. The instructions we visit are mapped in
  4592. // ScalarCosts. Those instructions are the ones that would be scalarized if
  4593. // we find that the scalar version costs less.
  4594. SmallVector<Instruction *, 8> Worklist;
  4595. // Returns true if the given instruction can be scalarized.
  4596. auto canBeScalarized = [&](Instruction *I) -> bool {
  4597. // We only attempt to scalarize instructions forming a single-use chain
  4598. // from the original predicated block that would otherwise be vectorized.
  4599. // Although not strictly necessary, we give up on instructions we know will
  4600. // already be scalar to avoid traversing chains that are unlikely to be
  4601. // beneficial.
  4602. if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
  4603. isScalarAfterVectorization(I, VF))
  4604. return false;
  4605. // If the instruction is scalar with predication, it will be analyzed
  4606. // separately. We ignore it within the context of PredInst.
  4607. if (isScalarWithPredication(I))
  4608. return false;
  4609. // If any of the instruction's operands are uniform after vectorization,
  4610. // the instruction cannot be scalarized. This prevents, for example, a
  4611. // masked load from being scalarized.
  4612. //
  4613. // We assume we will only emit a value for lane zero of an instruction
  4614. // marked uniform after vectorization, rather than VF identical values.
  4615. // Thus, if we scalarize an instruction that uses a uniform, we would
  4616. // create uses of values corresponding to the lanes we aren't emitting code
  4617. // for. This behavior can be changed by allowing getScalarValue to clone
  4618. // the lane zero values for uniforms rather than asserting.
  4619. for (Use &U : I->operands())
  4620. if (auto *J = dyn_cast<Instruction>(U.get()))
  4621. if (isUniformAfterVectorization(J, VF))
  4622. return false;
  4623. // Otherwise, we can scalarize the instruction.
  4624. return true;
  4625. };
  4626. // Returns true if an operand that cannot be scalarized must be extracted
  4627. // from a vector. We will account for this scalarization overhead below. Note
  4628. // that the non-void predicated instructions are placed in their own blocks,
  4629. // and their return values are inserted into vectors. Thus, an extract would
  4630. // still be required.
  4631. auto needsExtract = [&](Instruction *I) -> bool {
  4632. return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
  4633. };
  4634. // Compute the expected cost discount from scalarizing the entire expression
  4635. // feeding the predicated instruction. We currently only consider expressions
  4636. // that are single-use instruction chains.
  4637. Worklist.push_back(PredInst);
  4638. while (!Worklist.empty()) {
  4639. Instruction *I = Worklist.pop_back_val();
  4640. // If we've already analyzed the instruction, there's nothing to do.
  4641. if (ScalarCosts.find(I) != ScalarCosts.end())
  4642. continue;
  4643. // Compute the cost of the vector instruction. Note that this cost already
  4644. // includes the scalarization overhead of the predicated instruction.
  4645. unsigned VectorCost = getInstructionCost(I, VF).first;
  4646. // Compute the cost of the scalarized instruction. This cost is the cost of
  4647. // the instruction as if it wasn't if-converted and instead remained in the
  4648. // predicated block. We will scale this cost by block probability after
  4649. // computing the scalarization overhead.
  4650. unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
  4651. // Compute the scalarization overhead of needed insertelement instructions
  4652. // and phi nodes.
  4653. if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
  4654. ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
  4655. true, false);
  4656. ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
  4657. }
  4658. // Compute the scalarization overhead of needed extractelement
  4659. // instructions. For each of the instruction's operands, if the operand can
  4660. // be scalarized, add it to the worklist; otherwise, account for the
  4661. // overhead.
  4662. for (Use &U : I->operands())
  4663. if (auto *J = dyn_cast<Instruction>(U.get())) {
  4664. assert(VectorType::isValidElementType(J->getType()) &&
  4665. "Instruction has non-scalar type");
  4666. if (canBeScalarized(J))
  4667. Worklist.push_back(J);
  4668. else if (needsExtract(J))
  4669. ScalarCost += TTI.getScalarizationOverhead(
  4670. ToVectorTy(J->getType(),VF), false, true);
  4671. }
  4672. // Scale the total scalar cost by block probability.
  4673. ScalarCost /= getReciprocalPredBlockProb();
  4674. // Compute the discount. A non-negative discount means the vector version
  4675. // of the instruction costs more, and scalarizing would be beneficial.
  4676. Discount += VectorCost - ScalarCost;
  4677. ScalarCosts[I] = ScalarCost;
  4678. }
  4679. return Discount;
  4680. }
  4681. LoopVectorizationCostModel::VectorizationCostTy
  4682. LoopVectorizationCostModel::expectedCost(unsigned VF) {
  4683. VectorizationCostTy Cost;
  4684. // For each block.
  4685. for (BasicBlock *BB : TheLoop->blocks()) {
  4686. VectorizationCostTy BlockCost;
  4687. // For each instruction in the old loop.
  4688. for (Instruction &I : BB->instructionsWithoutDebug()) {
  4689. // Skip ignored values.
  4690. if (ValuesToIgnore.find(&I) != ValuesToIgnore.end() ||
  4691. (VF > 1 && VecValuesToIgnore.find(&I) != VecValuesToIgnore.end()))
  4692. continue;
  4693. VectorizationCostTy C = getInstructionCost(&I, VF);
  4694. // Check if we should override the cost.
  4695. if (ForceTargetInstructionCost.getNumOccurrences() > 0)
  4696. C.first = ForceTargetInstructionCost;
  4697. BlockCost.first += C.first;
  4698. BlockCost.second |= C.second;
  4699. LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
  4700. << " for VF " << VF << " For instruction: " << I
  4701. << '\n');
  4702. }
  4703. // If we are vectorizing a predicated block, it will have been
  4704. // if-converted. This means that the block's instructions (aside from
  4705. // stores and instructions that may divide by zero) will now be
  4706. // unconditionally executed. For the scalar case, we may not always execute
  4707. // the predicated block. Thus, scale the block's cost by the probability of
  4708. // executing it.
  4709. if (VF == 1 && blockNeedsPredication(BB))
  4710. BlockCost.first /= getReciprocalPredBlockProb();
  4711. Cost.first += BlockCost.first;
  4712. Cost.second |= BlockCost.second;
  4713. }
  4714. return Cost;
  4715. }
  4716. /// Gets Address Access SCEV after verifying that the access pattern
  4717. /// is loop invariant except the induction variable dependence.
  4718. ///
  4719. /// This SCEV can be sent to the Target in order to estimate the address
  4720. /// calculation cost.
  4721. static const SCEV *getAddressAccessSCEV(
  4722. Value *Ptr,
  4723. LoopVectorizationLegality *Legal,
  4724. PredicatedScalarEvolution &PSE,
  4725. const Loop *TheLoop) {
  4726. auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  4727. if (!Gep)
  4728. return nullptr;
  4729. // We are looking for a gep with all loop invariant indices except for one
  4730. // which should be an induction variable.
  4731. auto SE = PSE.getSE();
  4732. unsigned NumOperands = Gep->getNumOperands();
  4733. for (unsigned i = 1; i < NumOperands; ++i) {
  4734. Value *Opd = Gep->getOperand(i);
  4735. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  4736. !Legal->isInductionVariable(Opd))
  4737. return nullptr;
  4738. }
  4739. // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
  4740. return PSE.getSCEV(Ptr);
  4741. }
  4742. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  4743. return Legal->hasStride(I->getOperand(0)) ||
  4744. Legal->hasStride(I->getOperand(1));
  4745. }
  4746. unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
  4747. unsigned VF) {
  4748. assert(VF > 1 && "Scalarization cost of instruction implies vectorization.");
  4749. Type *ValTy = getMemInstValueType(I);
  4750. auto SE = PSE.getSE();
  4751. unsigned Alignment = getLoadStoreAlignment(I);
  4752. unsigned AS = getLoadStoreAddressSpace(I);
  4753. Value *Ptr = getLoadStorePointerOperand(I);
  4754. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  4755. // Figure out whether the access is strided and get the stride value
  4756. // if it's known in compile time
  4757. const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
  4758. // Get the cost of the scalar memory instruction and address computation.
  4759. unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
  4760. // Don't pass *I here, since it is scalar but will actually be part of a
  4761. // vectorized loop where the user of it is a vectorized instruction.
  4762. Cost += VF *
  4763. TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
  4764. AS);
  4765. // Get the overhead of the extractelement and insertelement instructions
  4766. // we might create due to scalarization.
  4767. Cost += getScalarizationOverhead(I, VF, TTI);
  4768. // If we have a predicated store, it may not be executed for each vector
  4769. // lane. Scale the cost by the probability of executing the predicated
  4770. // block.
  4771. if (isPredicatedInst(I)) {
  4772. Cost /= getReciprocalPredBlockProb();
  4773. if (useEmulatedMaskMemRefHack(I))
  4774. // Artificially setting to a high enough value to practically disable
  4775. // vectorization with such operations.
  4776. Cost = 3000000;
  4777. }
  4778. return Cost;
  4779. }
  4780. unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
  4781. unsigned VF) {
  4782. Type *ValTy = getMemInstValueType(I);
  4783. Type *VectorTy = ToVectorTy(ValTy, VF);
  4784. unsigned Alignment = getLoadStoreAlignment(I);
  4785. Value *Ptr = getLoadStorePointerOperand(I);
  4786. unsigned AS = getLoadStoreAddressSpace(I);
  4787. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  4788. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  4789. "Stride should be 1 or -1 for consecutive memory access");
  4790. unsigned Cost = 0;
  4791. if (Legal->isMaskRequired(I))
  4792. Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  4793. else
  4794. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
  4795. bool Reverse = ConsecutiveStride < 0;
  4796. if (Reverse)
  4797. Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  4798. return Cost;
  4799. }
  4800. unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
  4801. unsigned VF) {
  4802. Type *ValTy = getMemInstValueType(I);
  4803. Type *VectorTy = ToVectorTy(ValTy, VF);
  4804. unsigned Alignment = getLoadStoreAlignment(I);
  4805. unsigned AS = getLoadStoreAddressSpace(I);
  4806. if (isa<LoadInst>(I)) {
  4807. return TTI.getAddressComputationCost(ValTy) +
  4808. TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
  4809. TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
  4810. }
  4811. StoreInst *SI = cast<StoreInst>(I);
  4812. bool isLoopInvariantStoreValue = Legal->isUniform(SI->getValueOperand());
  4813. return TTI.getAddressComputationCost(ValTy) +
  4814. TTI.getMemoryOpCost(Instruction::Store, ValTy, Alignment, AS) +
  4815. (isLoopInvariantStoreValue ? 0 : TTI.getVectorInstrCost(
  4816. Instruction::ExtractElement,
  4817. VectorTy, VF - 1));
  4818. }
  4819. unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
  4820. unsigned VF) {
  4821. Type *ValTy = getMemInstValueType(I);
  4822. Type *VectorTy = ToVectorTy(ValTy, VF);
  4823. unsigned Alignment = getLoadStoreAlignment(I);
  4824. Value *Ptr = getLoadStorePointerOperand(I);
  4825. return TTI.getAddressComputationCost(VectorTy) +
  4826. TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
  4827. Legal->isMaskRequired(I), Alignment);
  4828. }
  4829. unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
  4830. unsigned VF) {
  4831. Type *ValTy = getMemInstValueType(I);
  4832. Type *VectorTy = ToVectorTy(ValTy, VF);
  4833. unsigned AS = getLoadStoreAddressSpace(I);
  4834. auto Group = getInterleavedAccessGroup(I);
  4835. assert(Group && "Fail to get an interleaved access group.");
  4836. unsigned InterleaveFactor = Group->getFactor();
  4837. Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
  4838. // Holds the indices of existing members in an interleaved load group.
  4839. // An interleaved store group doesn't need this as it doesn't allow gaps.
  4840. SmallVector<unsigned, 4> Indices;
  4841. if (isa<LoadInst>(I)) {
  4842. for (unsigned i = 0; i < InterleaveFactor; i++)
  4843. if (Group->getMember(i))
  4844. Indices.push_back(i);
  4845. }
  4846. // Calculate the cost of the whole interleaved group.
  4847. bool UseMaskForGaps =
  4848. Group->requiresScalarEpilogue() && !IsScalarEpilogueAllowed;
  4849. unsigned Cost = TTI.getInterleavedMemoryOpCost(
  4850. I->getOpcode(), WideVecTy, Group->getFactor(), Indices,
  4851. Group->getAlignment(), AS, Legal->isMaskRequired(I), UseMaskForGaps);
  4852. if (Group->isReverse()) {
  4853. // TODO: Add support for reversed masked interleaved access.
  4854. assert(!Legal->isMaskRequired(I) &&
  4855. "Reverse masked interleaved access not supported.");
  4856. Cost += Group->getNumMembers() *
  4857. TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  4858. }
  4859. return Cost;
  4860. }
  4861. unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
  4862. unsigned VF) {
  4863. // Calculate scalar cost only. Vectorization cost should be ready at this
  4864. // moment.
  4865. if (VF == 1) {
  4866. Type *ValTy = getMemInstValueType(I);
  4867. unsigned Alignment = getLoadStoreAlignment(I);
  4868. unsigned AS = getLoadStoreAddressSpace(I);
  4869. return TTI.getAddressComputationCost(ValTy) +
  4870. TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
  4871. }
  4872. return getWideningCost(I, VF);
  4873. }
  4874. LoopVectorizationCostModel::VectorizationCostTy
  4875. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
  4876. // If we know that this instruction will remain uniform, check the cost of
  4877. // the scalar version.
  4878. if (isUniformAfterVectorization(I, VF))
  4879. VF = 1;
  4880. if (VF > 1 && isProfitableToScalarize(I, VF))
  4881. return VectorizationCostTy(InstsToScalarize[VF][I], false);
  4882. // Forced scalars do not have any scalarization overhead.
  4883. auto ForcedScalar = ForcedScalars.find(VF);
  4884. if (VF > 1 && ForcedScalar != ForcedScalars.end()) {
  4885. auto InstSet = ForcedScalar->second;
  4886. if (InstSet.find(I) != InstSet.end())
  4887. return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false);
  4888. }
  4889. Type *VectorTy;
  4890. unsigned C = getInstructionCost(I, VF, VectorTy);
  4891. bool TypeNotScalarized =
  4892. VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF;
  4893. return VectorizationCostTy(C, TypeNotScalarized);
  4894. }
  4895. void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
  4896. if (VF == 1)
  4897. return;
  4898. NumPredStores = 0;
  4899. for (BasicBlock *BB : TheLoop->blocks()) {
  4900. // For each instruction in the old loop.
  4901. for (Instruction &I : *BB) {
  4902. Value *Ptr = getLoadStorePointerOperand(&I);
  4903. if (!Ptr)
  4904. continue;
  4905. // TODO: We should generate better code and update the cost model for
  4906. // predicated uniform stores. Today they are treated as any other
  4907. // predicated store (see added test cases in
  4908. // invariant-store-vectorization.ll).
  4909. if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
  4910. NumPredStores++;
  4911. if (Legal->isUniform(Ptr) &&
  4912. // Conditional loads and stores should be scalarized and predicated.
  4913. // isScalarWithPredication cannot be used here since masked
  4914. // gather/scatters are not considered scalar with predication.
  4915. !Legal->blockNeedsPredication(I.getParent())) {
  4916. // TODO: Avoid replicating loads and stores instead of
  4917. // relying on instcombine to remove them.
  4918. // Load: Scalar load + broadcast
  4919. // Store: Scalar store + isLoopInvariantStoreValue ? 0 : extract
  4920. unsigned Cost = getUniformMemOpCost(&I, VF);
  4921. setWideningDecision(&I, VF, CM_Scalarize, Cost);
  4922. continue;
  4923. }
  4924. // We assume that widening is the best solution when possible.
  4925. if (memoryInstructionCanBeWidened(&I, VF)) {
  4926. unsigned Cost = getConsecutiveMemOpCost(&I, VF);
  4927. int ConsecutiveStride =
  4928. Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
  4929. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  4930. "Expected consecutive stride.");
  4931. InstWidening Decision =
  4932. ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
  4933. setWideningDecision(&I, VF, Decision, Cost);
  4934. continue;
  4935. }
  4936. // Choose between Interleaving, Gather/Scatter or Scalarization.
  4937. unsigned InterleaveCost = std::numeric_limits<unsigned>::max();
  4938. unsigned NumAccesses = 1;
  4939. if (isAccessInterleaved(&I)) {
  4940. auto Group = getInterleavedAccessGroup(&I);
  4941. assert(Group && "Fail to get an interleaved access group.");
  4942. // Make one decision for the whole group.
  4943. if (getWideningDecision(&I, VF) != CM_Unknown)
  4944. continue;
  4945. NumAccesses = Group->getNumMembers();
  4946. if (interleavedAccessCanBeWidened(&I, VF))
  4947. InterleaveCost = getInterleaveGroupCost(&I, VF);
  4948. }
  4949. unsigned GatherScatterCost =
  4950. isLegalGatherOrScatter(&I)
  4951. ? getGatherScatterCost(&I, VF) * NumAccesses
  4952. : std::numeric_limits<unsigned>::max();
  4953. unsigned ScalarizationCost =
  4954. getMemInstScalarizationCost(&I, VF) * NumAccesses;
  4955. // Choose better solution for the current VF,
  4956. // write down this decision and use it during vectorization.
  4957. unsigned Cost;
  4958. InstWidening Decision;
  4959. if (InterleaveCost <= GatherScatterCost &&
  4960. InterleaveCost < ScalarizationCost) {
  4961. Decision = CM_Interleave;
  4962. Cost = InterleaveCost;
  4963. } else if (GatherScatterCost < ScalarizationCost) {
  4964. Decision = CM_GatherScatter;
  4965. Cost = GatherScatterCost;
  4966. } else {
  4967. Decision = CM_Scalarize;
  4968. Cost = ScalarizationCost;
  4969. }
  4970. // If the instructions belongs to an interleave group, the whole group
  4971. // receives the same decision. The whole group receives the cost, but
  4972. // the cost will actually be assigned to one instruction.
  4973. if (auto Group = getInterleavedAccessGroup(&I))
  4974. setWideningDecision(Group, VF, Decision, Cost);
  4975. else
  4976. setWideningDecision(&I, VF, Decision, Cost);
  4977. }
  4978. }
  4979. // Make sure that any load of address and any other address computation
  4980. // remains scalar unless there is gather/scatter support. This avoids
  4981. // inevitable extracts into address registers, and also has the benefit of
  4982. // activating LSR more, since that pass can't optimize vectorized
  4983. // addresses.
  4984. if (TTI.prefersVectorizedAddressing())
  4985. return;
  4986. // Start with all scalar pointer uses.
  4987. SmallPtrSet<Instruction *, 8> AddrDefs;
  4988. for (BasicBlock *BB : TheLoop->blocks())
  4989. for (Instruction &I : *BB) {
  4990. Instruction *PtrDef =
  4991. dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  4992. if (PtrDef && TheLoop->contains(PtrDef) &&
  4993. getWideningDecision(&I, VF) != CM_GatherScatter)
  4994. AddrDefs.insert(PtrDef);
  4995. }
  4996. // Add all instructions used to generate the addresses.
  4997. SmallVector<Instruction *, 4> Worklist;
  4998. for (auto *I : AddrDefs)
  4999. Worklist.push_back(I);
  5000. while (!Worklist.empty()) {
  5001. Instruction *I = Worklist.pop_back_val();
  5002. for (auto &Op : I->operands())
  5003. if (auto *InstOp = dyn_cast<Instruction>(Op))
  5004. if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
  5005. AddrDefs.insert(InstOp).second)
  5006. Worklist.push_back(InstOp);
  5007. }
  5008. for (auto *I : AddrDefs) {
  5009. if (isa<LoadInst>(I)) {
  5010. // Setting the desired widening decision should ideally be handled in
  5011. // by cost functions, but since this involves the task of finding out
  5012. // if the loaded register is involved in an address computation, it is
  5013. // instead changed here when we know this is the case.
  5014. InstWidening Decision = getWideningDecision(I, VF);
  5015. if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
  5016. // Scalarize a widened load of address.
  5017. setWideningDecision(I, VF, CM_Scalarize,
  5018. (VF * getMemoryInstructionCost(I, 1)));
  5019. else if (auto Group = getInterleavedAccessGroup(I)) {
  5020. // Scalarize an interleave group of address loads.
  5021. for (unsigned I = 0; I < Group->getFactor(); ++I) {
  5022. if (Instruction *Member = Group->getMember(I))
  5023. setWideningDecision(Member, VF, CM_Scalarize,
  5024. (VF * getMemoryInstructionCost(Member, 1)));
  5025. }
  5026. }
  5027. } else
  5028. // Make sure I gets scalarized and a cost estimate without
  5029. // scalarization overhead.
  5030. ForcedScalars[VF].insert(I);
  5031. }
  5032. }
  5033. unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
  5034. unsigned VF,
  5035. Type *&VectorTy) {
  5036. Type *RetTy = I->getType();
  5037. if (canTruncateToMinimalBitwidth(I, VF))
  5038. RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
  5039. VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
  5040. auto SE = PSE.getSE();
  5041. // TODO: We need to estimate the cost of intrinsic calls.
  5042. switch (I->getOpcode()) {
  5043. case Instruction::GetElementPtr:
  5044. // We mark this instruction as zero-cost because the cost of GEPs in
  5045. // vectorized code depends on whether the corresponding memory instruction
  5046. // is scalarized or not. Therefore, we handle GEPs with the memory
  5047. // instruction cost.
  5048. return 0;
  5049. case Instruction::Br: {
  5050. // In cases of scalarized and predicated instructions, there will be VF
  5051. // predicated blocks in the vectorized loop. Each branch around these
  5052. // blocks requires also an extract of its vector compare i1 element.
  5053. bool ScalarPredicatedBB = false;
  5054. BranchInst *BI = cast<BranchInst>(I);
  5055. if (VF > 1 && BI->isConditional() &&
  5056. (PredicatedBBsAfterVectorization.find(BI->getSuccessor(0)) !=
  5057. PredicatedBBsAfterVectorization.end() ||
  5058. PredicatedBBsAfterVectorization.find(BI->getSuccessor(1)) !=
  5059. PredicatedBBsAfterVectorization.end()))
  5060. ScalarPredicatedBB = true;
  5061. if (ScalarPredicatedBB) {
  5062. // Return cost for branches around scalarized and predicated blocks.
  5063. Type *Vec_i1Ty =
  5064. VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
  5065. return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
  5066. (TTI.getCFInstrCost(Instruction::Br) * VF));
  5067. } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
  5068. // The back-edge branch will remain, as will all scalar branches.
  5069. return TTI.getCFInstrCost(Instruction::Br);
  5070. else
  5071. // This branch will be eliminated by if-conversion.
  5072. return 0;
  5073. // Note: We currently assume zero cost for an unconditional branch inside
  5074. // a predicated block since it will become a fall-through, although we
  5075. // may decide in the future to call TTI for all branches.
  5076. }
  5077. case Instruction::PHI: {
  5078. auto *Phi = cast<PHINode>(I);
  5079. // First-order recurrences are replaced by vector shuffles inside the loop.
  5080. // NOTE: Don't use ToVectorTy as SK_ExtractSubvector expects a vector type.
  5081. if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
  5082. return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  5083. VectorTy, VF - 1, VectorType::get(RetTy, 1));
  5084. // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
  5085. // converted into select instructions. We require N - 1 selects per phi
  5086. // node, where N is the number of incoming values.
  5087. if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
  5088. return (Phi->getNumIncomingValues() - 1) *
  5089. TTI.getCmpSelInstrCost(
  5090. Instruction::Select, ToVectorTy(Phi->getType(), VF),
  5091. ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF));
  5092. return TTI.getCFInstrCost(Instruction::PHI);
  5093. }
  5094. case Instruction::UDiv:
  5095. case Instruction::SDiv:
  5096. case Instruction::URem:
  5097. case Instruction::SRem:
  5098. // If we have a predicated instruction, it may not be executed for each
  5099. // vector lane. Get the scalarization cost and scale this amount by the
  5100. // probability of executing the predicated block. If the instruction is not
  5101. // predicated, we fall through to the next case.
  5102. if (VF > 1 && isScalarWithPredication(I)) {
  5103. unsigned Cost = 0;
  5104. // These instructions have a non-void type, so account for the phi nodes
  5105. // that we will create. This cost is likely to be zero. The phi node
  5106. // cost, if any, should be scaled by the block probability because it
  5107. // models a copy at the end of each predicated block.
  5108. Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
  5109. // The cost of the non-predicated instruction.
  5110. Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
  5111. // The cost of insertelement and extractelement instructions needed for
  5112. // scalarization.
  5113. Cost += getScalarizationOverhead(I, VF, TTI);
  5114. // Scale the cost by the probability of executing the predicated blocks.
  5115. // This assumes the predicated block for each vector lane is equally
  5116. // likely.
  5117. return Cost / getReciprocalPredBlockProb();
  5118. }
  5119. LLVM_FALLTHROUGH;
  5120. case Instruction::Add:
  5121. case Instruction::FAdd:
  5122. case Instruction::Sub:
  5123. case Instruction::FSub:
  5124. case Instruction::Mul:
  5125. case Instruction::FMul:
  5126. case Instruction::FDiv:
  5127. case Instruction::FRem:
  5128. case Instruction::Shl:
  5129. case Instruction::LShr:
  5130. case Instruction::AShr:
  5131. case Instruction::And:
  5132. case Instruction::Or:
  5133. case Instruction::Xor: {
  5134. // Since we will replace the stride by 1 the multiplication should go away.
  5135. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  5136. return 0;
  5137. // Certain instructions can be cheaper to vectorize if they have a constant
  5138. // second vector operand. One example of this are shifts on x86.
  5139. Value *Op2 = I->getOperand(1);
  5140. TargetTransformInfo::OperandValueProperties Op2VP;
  5141. TargetTransformInfo::OperandValueKind Op2VK =
  5142. TTI.getOperandInfo(Op2, Op2VP);
  5143. if (Op2VK == TargetTransformInfo::OK_AnyValue && Legal->isUniform(Op2))
  5144. Op2VK = TargetTransformInfo::OK_UniformValue;
  5145. SmallVector<const Value *, 4> Operands(I->operand_values());
  5146. unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
  5147. return N * TTI.getArithmeticInstrCost(
  5148. I->getOpcode(), VectorTy, TargetTransformInfo::OK_AnyValue,
  5149. Op2VK, TargetTransformInfo::OP_None, Op2VP, Operands);
  5150. }
  5151. case Instruction::Select: {
  5152. SelectInst *SI = cast<SelectInst>(I);
  5153. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  5154. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  5155. Type *CondTy = SI->getCondition()->getType();
  5156. if (!ScalarCond)
  5157. CondTy = VectorType::get(CondTy, VF);
  5158. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
  5159. }
  5160. case Instruction::ICmp:
  5161. case Instruction::FCmp: {
  5162. Type *ValTy = I->getOperand(0)->getType();
  5163. Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
  5164. if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
  5165. ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
  5166. VectorTy = ToVectorTy(ValTy, VF);
  5167. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
  5168. }
  5169. case Instruction::Store:
  5170. case Instruction::Load: {
  5171. unsigned Width = VF;
  5172. if (Width > 1) {
  5173. InstWidening Decision = getWideningDecision(I, Width);
  5174. assert(Decision != CM_Unknown &&
  5175. "CM decision should be taken at this point");
  5176. if (Decision == CM_Scalarize)
  5177. Width = 1;
  5178. }
  5179. VectorTy = ToVectorTy(getMemInstValueType(I), Width);
  5180. return getMemoryInstructionCost(I, VF);
  5181. }
  5182. case Instruction::ZExt:
  5183. case Instruction::SExt:
  5184. case Instruction::FPToUI:
  5185. case Instruction::FPToSI:
  5186. case Instruction::FPExt:
  5187. case Instruction::PtrToInt:
  5188. case Instruction::IntToPtr:
  5189. case Instruction::SIToFP:
  5190. case Instruction::UIToFP:
  5191. case Instruction::Trunc:
  5192. case Instruction::FPTrunc:
  5193. case Instruction::BitCast: {
  5194. // We optimize the truncation of induction variables having constant
  5195. // integer steps. The cost of these truncations is the same as the scalar
  5196. // operation.
  5197. if (isOptimizableIVTruncate(I, VF)) {
  5198. auto *Trunc = cast<TruncInst>(I);
  5199. return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
  5200. Trunc->getSrcTy(), Trunc);
  5201. }
  5202. Type *SrcScalarTy = I->getOperand(0)->getType();
  5203. Type *SrcVecTy =
  5204. VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
  5205. if (canTruncateToMinimalBitwidth(I, VF)) {
  5206. // This cast is going to be shrunk. This may remove the cast or it might
  5207. // turn it into slightly different cast. For example, if MinBW == 16,
  5208. // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
  5209. //
  5210. // Calculate the modified src and dest types.
  5211. Type *MinVecTy = VectorTy;
  5212. if (I->getOpcode() == Instruction::Trunc) {
  5213. SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
  5214. VectorTy =
  5215. largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  5216. } else if (I->getOpcode() == Instruction::ZExt ||
  5217. I->getOpcode() == Instruction::SExt) {
  5218. SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
  5219. VectorTy =
  5220. smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  5221. }
  5222. }
  5223. unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
  5224. return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
  5225. }
  5226. case Instruction::Call: {
  5227. bool NeedToScalarize;
  5228. CallInst *CI = cast<CallInst>(I);
  5229. unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
  5230. if (getVectorIntrinsicIDForCall(CI, TLI))
  5231. return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
  5232. return CallCost;
  5233. }
  5234. default:
  5235. // The cost of executing VF copies of the scalar instruction. This opcode
  5236. // is unknown. Assume that it is the same as 'mul'.
  5237. return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
  5238. getScalarizationOverhead(I, VF, TTI);
  5239. } // end of switch.
  5240. }
  5241. char LoopVectorize::ID = 0;
  5242. static const char lv_name[] = "Loop Vectorization";
  5243. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  5244. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  5245. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  5246. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  5247. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  5248. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  5249. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  5250. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  5251. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  5252. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  5253. INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
  5254. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  5255. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  5256. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  5257. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  5258. namespace llvm {
  5259. Pass *createLoopVectorizePass() { return new LoopVectorize(); }
  5260. Pass *createLoopVectorizePass(bool InterleaveOnlyWhenForced,
  5261. bool VectorizeOnlyWhenForced) {
  5262. return new LoopVectorize(InterleaveOnlyWhenForced, VectorizeOnlyWhenForced);
  5263. }
  5264. } // end namespace llvm
  5265. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  5266. // Check if the pointer operand of a load or store instruction is
  5267. // consecutive.
  5268. if (auto *Ptr = getLoadStorePointerOperand(Inst))
  5269. return Legal->isConsecutivePtr(Ptr);
  5270. return false;
  5271. }
  5272. void LoopVectorizationCostModel::collectValuesToIgnore() {
  5273. // Ignore ephemeral values.
  5274. CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
  5275. // Ignore type-promoting instructions we identified during reduction
  5276. // detection.
  5277. for (auto &Reduction : *Legal->getReductionVars()) {
  5278. RecurrenceDescriptor &RedDes = Reduction.second;
  5279. SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
  5280. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  5281. }
  5282. // Ignore type-casting instructions we identified during induction
  5283. // detection.
  5284. for (auto &Induction : *Legal->getInductionVars()) {
  5285. InductionDescriptor &IndDes = Induction.second;
  5286. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  5287. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  5288. }
  5289. }
  5290. // TODO: we could return a pair of values that specify the max VF and
  5291. // min VF, to be used in `buildVPlans(MinVF, MaxVF)` instead of
  5292. // `buildVPlans(VF, VF)`. We cannot do it because VPLAN at the moment
  5293. // doesn't have a cost model that can choose which plan to execute if
  5294. // more than one is generated.
  5295. static unsigned determineVPlanVF(const unsigned WidestVectorRegBits,
  5296. LoopVectorizationCostModel &CM) {
  5297. unsigned WidestType;
  5298. std::tie(std::ignore, WidestType) = CM.getSmallestAndWidestTypes();
  5299. return WidestVectorRegBits / WidestType;
  5300. }
  5301. VectorizationFactor
  5302. LoopVectorizationPlanner::planInVPlanNativePath(bool OptForSize,
  5303. unsigned UserVF) {
  5304. unsigned VF = UserVF;
  5305. // Outer loop handling: They may require CFG and instruction level
  5306. // transformations before even evaluating whether vectorization is profitable.
  5307. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  5308. // the vectorization pipeline.
  5309. if (!OrigLoop->empty()) {
  5310. // If the user doesn't provide a vectorization factor, determine a
  5311. // reasonable one.
  5312. if (!UserVF) {
  5313. VF = determineVPlanVF(TTI->getRegisterBitWidth(true /* Vector*/), CM);
  5314. LLVM_DEBUG(dbgs() << "LV: VPlan computed VF " << VF << ".\n");
  5315. // Make sure we have a VF > 1 for stress testing.
  5316. if (VPlanBuildStressTest && VF < 2) {
  5317. LLVM_DEBUG(dbgs() << "LV: VPlan stress testing: "
  5318. << "overriding computed VF.\n");
  5319. VF = 4;
  5320. }
  5321. }
  5322. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  5323. assert(isPowerOf2_32(VF) && "VF needs to be a power of two");
  5324. LLVM_DEBUG(dbgs() << "LV: Using " << (UserVF ? "user " : "") << "VF " << VF
  5325. << " to build VPlans.\n");
  5326. buildVPlans(VF, VF);
  5327. // For VPlan build stress testing, we bail out after VPlan construction.
  5328. if (VPlanBuildStressTest)
  5329. return VectorizationFactor::Disabled();
  5330. return {VF, 0};
  5331. }
  5332. LLVM_DEBUG(
  5333. dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
  5334. "VPlan-native path.\n");
  5335. return VectorizationFactor::Disabled();
  5336. }
  5337. Optional<VectorizationFactor> LoopVectorizationPlanner::plan(bool OptForSize,
  5338. unsigned UserVF) {
  5339. assert(OrigLoop->empty() && "Inner loop expected.");
  5340. Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
  5341. if (!MaybeMaxVF) // Cases that should not to be vectorized nor interleaved.
  5342. return None;
  5343. // Invalidate interleave groups if all blocks of loop will be predicated.
  5344. if (CM.blockNeedsPredication(OrigLoop->getHeader()) &&
  5345. !useMaskedInterleavedAccesses(*TTI)) {
  5346. LLVM_DEBUG(
  5347. dbgs()
  5348. << "LV: Invalidate all interleaved groups due to fold-tail by masking "
  5349. "which requires masked-interleaved support.\n");
  5350. CM.InterleaveInfo.reset();
  5351. }
  5352. if (UserVF) {
  5353. LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  5354. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  5355. // Collect the instructions (and their associated costs) that will be more
  5356. // profitable to scalarize.
  5357. CM.selectUserVectorizationFactor(UserVF);
  5358. buildVPlansWithVPRecipes(UserVF, UserVF);
  5359. LLVM_DEBUG(printPlans(dbgs()));
  5360. return {{UserVF, 0}};
  5361. }
  5362. unsigned MaxVF = MaybeMaxVF.getValue();
  5363. assert(MaxVF != 0 && "MaxVF is zero.");
  5364. for (unsigned VF = 1; VF <= MaxVF; VF *= 2) {
  5365. // Collect Uniform and Scalar instructions after vectorization with VF.
  5366. CM.collectUniformsAndScalars(VF);
  5367. // Collect the instructions (and their associated costs) that will be more
  5368. // profitable to scalarize.
  5369. if (VF > 1)
  5370. CM.collectInstsToScalarize(VF);
  5371. }
  5372. buildVPlansWithVPRecipes(1, MaxVF);
  5373. LLVM_DEBUG(printPlans(dbgs()));
  5374. if (MaxVF == 1)
  5375. return VectorizationFactor::Disabled();
  5376. // Select the optimal vectorization factor.
  5377. return CM.selectVectorizationFactor(MaxVF);
  5378. }
  5379. void LoopVectorizationPlanner::setBestPlan(unsigned VF, unsigned UF) {
  5380. LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
  5381. << '\n');
  5382. BestVF = VF;
  5383. BestUF = UF;
  5384. erase_if(VPlans, [VF](const VPlanPtr &Plan) {
  5385. return !Plan->hasVF(VF);
  5386. });
  5387. assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
  5388. }
  5389. void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
  5390. DominatorTree *DT) {
  5391. // Perform the actual loop transformation.
  5392. // 1. Create a new empty loop. Unlink the old loop and connect the new one.
  5393. VPCallbackILV CallbackILV(ILV);
  5394. VPTransformState State{BestVF, BestUF, LI,
  5395. DT, ILV.Builder, ILV.VectorLoopValueMap,
  5396. &ILV, CallbackILV};
  5397. State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
  5398. State.TripCount = ILV.getOrCreateTripCount(nullptr);
  5399. //===------------------------------------------------===//
  5400. //
  5401. // Notice: any optimization or new instruction that go
  5402. // into the code below should also be implemented in
  5403. // the cost-model.
  5404. //
  5405. //===------------------------------------------------===//
  5406. // 2. Copy and widen instructions from the old loop into the new loop.
  5407. assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
  5408. VPlans.front()->execute(&State);
  5409. // 3. Fix the vectorized code: take care of header phi's, live-outs,
  5410. // predication, updating analyses.
  5411. ILV.fixVectorizedLoop();
  5412. }
  5413. void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
  5414. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  5415. BasicBlock *Latch = OrigLoop->getLoopLatch();
  5416. // We create new control-flow for the vectorized loop, so the original
  5417. // condition will be dead after vectorization if it's only used by the
  5418. // branch.
  5419. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  5420. if (Cmp && Cmp->hasOneUse())
  5421. DeadInstructions.insert(Cmp);
  5422. // We create new "steps" for induction variable updates to which the original
  5423. // induction variables map. An original update instruction will be dead if
  5424. // all its users except the induction variable are dead.
  5425. for (auto &Induction : *Legal->getInductionVars()) {
  5426. PHINode *Ind = Induction.first;
  5427. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  5428. if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  5429. return U == Ind || DeadInstructions.find(cast<Instruction>(U)) !=
  5430. DeadInstructions.end();
  5431. }))
  5432. DeadInstructions.insert(IndUpdate);
  5433. // We record as "Dead" also the type-casting instructions we had identified
  5434. // during induction analysis. We don't need any handling for them in the
  5435. // vectorized loop because we have proven that, under a proper runtime
  5436. // test guarding the vectorized loop, the value of the phi, and the casted
  5437. // value of the phi, are the same. The last instruction in this casting chain
  5438. // will get its scalar/vector/widened def from the scalar/vector/widened def
  5439. // of the respective phi node. Any other casts in the induction def-use chain
  5440. // have no other uses outside the phi update chain, and will be ignored.
  5441. InductionDescriptor &IndDes = Induction.second;
  5442. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  5443. DeadInstructions.insert(Casts.begin(), Casts.end());
  5444. }
  5445. }
  5446. Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
  5447. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
  5448. Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
  5449. Instruction::BinaryOps BinOp) {
  5450. // When unrolling and the VF is 1, we only need to add a simple scalar.
  5451. Type *Ty = Val->getType();
  5452. assert(!Ty->isVectorTy() && "Val must be a scalar");
  5453. if (Ty->isFloatingPointTy()) {
  5454. Constant *C = ConstantFP::get(Ty, (double)StartIdx);
  5455. // Floating point operations had to be 'fast' to enable the unrolling.
  5456. Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
  5457. return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
  5458. }
  5459. Constant *C = ConstantInt::get(Ty, StartIdx);
  5460. return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
  5461. }
  5462. static void AddRuntimeUnrollDisableMetaData(Loop *L) {
  5463. SmallVector<Metadata *, 4> MDs;
  5464. // Reserve first location for self reference to the LoopID metadata node.
  5465. MDs.push_back(nullptr);
  5466. bool IsUnrollMetadata = false;
  5467. MDNode *LoopID = L->getLoopID();
  5468. if (LoopID) {
  5469. // First find existing loop unrolling disable metadata.
  5470. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  5471. auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  5472. if (MD) {
  5473. const auto *S = dyn_cast<MDString>(MD->getOperand(0));
  5474. IsUnrollMetadata =
  5475. S && S->getString().startswith("llvm.loop.unroll.disable");
  5476. }
  5477. MDs.push_back(LoopID->getOperand(i));
  5478. }
  5479. }
  5480. if (!IsUnrollMetadata) {
  5481. // Add runtime unroll disable metadata.
  5482. LLVMContext &Context = L->getHeader()->getContext();
  5483. SmallVector<Metadata *, 1> DisableOperands;
  5484. DisableOperands.push_back(
  5485. MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
  5486. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  5487. MDs.push_back(DisableNode);
  5488. MDNode *NewLoopID = MDNode::get(Context, MDs);
  5489. // Set operand 0 to refer to the loop id itself.
  5490. NewLoopID->replaceOperandWith(0, NewLoopID);
  5491. L->setLoopID(NewLoopID);
  5492. }
  5493. }
  5494. bool LoopVectorizationPlanner::getDecisionAndClampRange(
  5495. const std::function<bool(unsigned)> &Predicate, VFRange &Range) {
  5496. assert(Range.End > Range.Start && "Trying to test an empty VF range.");
  5497. bool PredicateAtRangeStart = Predicate(Range.Start);
  5498. for (unsigned TmpVF = Range.Start * 2; TmpVF < Range.End; TmpVF *= 2)
  5499. if (Predicate(TmpVF) != PredicateAtRangeStart) {
  5500. Range.End = TmpVF;
  5501. break;
  5502. }
  5503. return PredicateAtRangeStart;
  5504. }
  5505. /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
  5506. /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
  5507. /// of VF's starting at a given VF and extending it as much as possible. Each
  5508. /// vectorization decision can potentially shorten this sub-range during
  5509. /// buildVPlan().
  5510. void LoopVectorizationPlanner::buildVPlans(unsigned MinVF, unsigned MaxVF) {
  5511. for (unsigned VF = MinVF; VF < MaxVF + 1;) {
  5512. VFRange SubRange = {VF, MaxVF + 1};
  5513. VPlans.push_back(buildVPlan(SubRange));
  5514. VF = SubRange.End;
  5515. }
  5516. }
  5517. VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
  5518. VPlanPtr &Plan) {
  5519. assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
  5520. // Look for cached value.
  5521. std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
  5522. EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
  5523. if (ECEntryIt != EdgeMaskCache.end())
  5524. return ECEntryIt->second;
  5525. VPValue *SrcMask = createBlockInMask(Src, Plan);
  5526. // The terminator has to be a branch inst!
  5527. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  5528. assert(BI && "Unexpected terminator found");
  5529. if (!BI->isConditional())
  5530. return EdgeMaskCache[Edge] = SrcMask;
  5531. VPValue *EdgeMask = Plan->getVPValue(BI->getCondition());
  5532. assert(EdgeMask && "No Edge Mask found for condition");
  5533. if (BI->getSuccessor(0) != Dst)
  5534. EdgeMask = Builder.createNot(EdgeMask);
  5535. if (SrcMask) // Otherwise block in-mask is all-one, no need to AND.
  5536. EdgeMask = Builder.createAnd(EdgeMask, SrcMask);
  5537. return EdgeMaskCache[Edge] = EdgeMask;
  5538. }
  5539. VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
  5540. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  5541. // Look for cached value.
  5542. BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
  5543. if (BCEntryIt != BlockMaskCache.end())
  5544. return BCEntryIt->second;
  5545. // All-one mask is modelled as no-mask following the convention for masked
  5546. // load/store/gather/scatter. Initialize BlockMask to no-mask.
  5547. VPValue *BlockMask = nullptr;
  5548. if (OrigLoop->getHeader() == BB) {
  5549. if (!CM.blockNeedsPredication(BB))
  5550. return BlockMaskCache[BB] = BlockMask; // Loop incoming mask is all-one.
  5551. // Introduce the early-exit compare IV <= BTC to form header block mask.
  5552. // This is used instead of IV < TC because TC may wrap, unlike BTC.
  5553. VPValue *IV = Plan->getVPValue(Legal->getPrimaryInduction());
  5554. VPValue *BTC = Plan->getOrCreateBackedgeTakenCount();
  5555. BlockMask = Builder.createNaryOp(VPInstruction::ICmpULE, {IV, BTC});
  5556. return BlockMaskCache[BB] = BlockMask;
  5557. }
  5558. // This is the block mask. We OR all incoming edges.
  5559. for (auto *Predecessor : predecessors(BB)) {
  5560. VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
  5561. if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
  5562. return BlockMaskCache[BB] = EdgeMask;
  5563. if (!BlockMask) { // BlockMask has its initialized nullptr value.
  5564. BlockMask = EdgeMask;
  5565. continue;
  5566. }
  5567. BlockMask = Builder.createOr(BlockMask, EdgeMask);
  5568. }
  5569. return BlockMaskCache[BB] = BlockMask;
  5570. }
  5571. VPInterleaveRecipe *VPRecipeBuilder::tryToInterleaveMemory(Instruction *I,
  5572. VFRange &Range,
  5573. VPlanPtr &Plan) {
  5574. const InterleaveGroup<Instruction> *IG = CM.getInterleavedAccessGroup(I);
  5575. if (!IG)
  5576. return nullptr;
  5577. // Now check if IG is relevant for VF's in the given range.
  5578. auto isIGMember = [&](Instruction *I) -> std::function<bool(unsigned)> {
  5579. return [=](unsigned VF) -> bool {
  5580. return (VF >= 2 && // Query is illegal for VF == 1
  5581. CM.getWideningDecision(I, VF) ==
  5582. LoopVectorizationCostModel::CM_Interleave);
  5583. };
  5584. };
  5585. if (!LoopVectorizationPlanner::getDecisionAndClampRange(isIGMember(I), Range))
  5586. return nullptr;
  5587. // I is a member of an InterleaveGroup for VF's in the (possibly trimmed)
  5588. // range. If it's the primary member of the IG construct a VPInterleaveRecipe.
  5589. // Otherwise, it's an adjunct member of the IG, do not construct any Recipe.
  5590. assert(I == IG->getInsertPos() &&
  5591. "Generating a recipe for an adjunct member of an interleave group");
  5592. VPValue *Mask = nullptr;
  5593. if (Legal->isMaskRequired(I))
  5594. Mask = createBlockInMask(I->getParent(), Plan);
  5595. return new VPInterleaveRecipe(IG, Mask);
  5596. }
  5597. VPWidenMemoryInstructionRecipe *
  5598. VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range,
  5599. VPlanPtr &Plan) {
  5600. if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
  5601. return nullptr;
  5602. auto willWiden = [&](unsigned VF) -> bool {
  5603. if (VF == 1)
  5604. return false;
  5605. if (CM.isScalarAfterVectorization(I, VF) ||
  5606. CM.isProfitableToScalarize(I, VF))
  5607. return false;
  5608. LoopVectorizationCostModel::InstWidening Decision =
  5609. CM.getWideningDecision(I, VF);
  5610. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  5611. "CM decision should be taken at this point.");
  5612. assert(Decision != LoopVectorizationCostModel::CM_Interleave &&
  5613. "Interleave memory opportunity should be caught earlier.");
  5614. return Decision != LoopVectorizationCostModel::CM_Scalarize;
  5615. };
  5616. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  5617. return nullptr;
  5618. VPValue *Mask = nullptr;
  5619. if (Legal->isMaskRequired(I))
  5620. Mask = createBlockInMask(I->getParent(), Plan);
  5621. return new VPWidenMemoryInstructionRecipe(*I, Mask);
  5622. }
  5623. VPWidenIntOrFpInductionRecipe *
  5624. VPRecipeBuilder::tryToOptimizeInduction(Instruction *I, VFRange &Range) {
  5625. if (PHINode *Phi = dyn_cast<PHINode>(I)) {
  5626. // Check if this is an integer or fp induction. If so, build the recipe that
  5627. // produces its scalar and vector values.
  5628. InductionDescriptor II = Legal->getInductionVars()->lookup(Phi);
  5629. if (II.getKind() == InductionDescriptor::IK_IntInduction ||
  5630. II.getKind() == InductionDescriptor::IK_FpInduction)
  5631. return new VPWidenIntOrFpInductionRecipe(Phi);
  5632. return nullptr;
  5633. }
  5634. // Optimize the special case where the source is a constant integer
  5635. // induction variable. Notice that we can only optimize the 'trunc' case
  5636. // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
  5637. // (c) other casts depend on pointer size.
  5638. // Determine whether \p K is a truncation based on an induction variable that
  5639. // can be optimized.
  5640. auto isOptimizableIVTruncate =
  5641. [&](Instruction *K) -> std::function<bool(unsigned)> {
  5642. return
  5643. [=](unsigned VF) -> bool { return CM.isOptimizableIVTruncate(K, VF); };
  5644. };
  5645. if (isa<TruncInst>(I) && LoopVectorizationPlanner::getDecisionAndClampRange(
  5646. isOptimizableIVTruncate(I), Range))
  5647. return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
  5648. cast<TruncInst>(I));
  5649. return nullptr;
  5650. }
  5651. VPBlendRecipe *VPRecipeBuilder::tryToBlend(Instruction *I, VPlanPtr &Plan) {
  5652. PHINode *Phi = dyn_cast<PHINode>(I);
  5653. if (!Phi || Phi->getParent() == OrigLoop->getHeader())
  5654. return nullptr;
  5655. // We know that all PHIs in non-header blocks are converted into selects, so
  5656. // we don't have to worry about the insertion order and we can just use the
  5657. // builder. At this point we generate the predication tree. There may be
  5658. // duplications since this is a simple recursive scan, but future
  5659. // optimizations will clean it up.
  5660. SmallVector<VPValue *, 2> Masks;
  5661. unsigned NumIncoming = Phi->getNumIncomingValues();
  5662. for (unsigned In = 0; In < NumIncoming; In++) {
  5663. VPValue *EdgeMask =
  5664. createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
  5665. assert((EdgeMask || NumIncoming == 1) &&
  5666. "Multiple predecessors with one having a full mask");
  5667. if (EdgeMask)
  5668. Masks.push_back(EdgeMask);
  5669. }
  5670. return new VPBlendRecipe(Phi, Masks);
  5671. }
  5672. bool VPRecipeBuilder::tryToWiden(Instruction *I, VPBasicBlock *VPBB,
  5673. VFRange &Range) {
  5674. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  5675. [&](unsigned VF) { return CM.isScalarWithPredication(I, VF); }, Range);
  5676. if (IsPredicated)
  5677. return false;
  5678. auto IsVectorizableOpcode = [](unsigned Opcode) {
  5679. switch (Opcode) {
  5680. case Instruction::Add:
  5681. case Instruction::And:
  5682. case Instruction::AShr:
  5683. case Instruction::BitCast:
  5684. case Instruction::Br:
  5685. case Instruction::Call:
  5686. case Instruction::FAdd:
  5687. case Instruction::FCmp:
  5688. case Instruction::FDiv:
  5689. case Instruction::FMul:
  5690. case Instruction::FPExt:
  5691. case Instruction::FPToSI:
  5692. case Instruction::FPToUI:
  5693. case Instruction::FPTrunc:
  5694. case Instruction::FRem:
  5695. case Instruction::FSub:
  5696. case Instruction::GetElementPtr:
  5697. case Instruction::ICmp:
  5698. case Instruction::IntToPtr:
  5699. case Instruction::Load:
  5700. case Instruction::LShr:
  5701. case Instruction::Mul:
  5702. case Instruction::Or:
  5703. case Instruction::PHI:
  5704. case Instruction::PtrToInt:
  5705. case Instruction::SDiv:
  5706. case Instruction::Select:
  5707. case Instruction::SExt:
  5708. case Instruction::Shl:
  5709. case Instruction::SIToFP:
  5710. case Instruction::SRem:
  5711. case Instruction::Store:
  5712. case Instruction::Sub:
  5713. case Instruction::Trunc:
  5714. case Instruction::UDiv:
  5715. case Instruction::UIToFP:
  5716. case Instruction::URem:
  5717. case Instruction::Xor:
  5718. case Instruction::ZExt:
  5719. return true;
  5720. }
  5721. return false;
  5722. };
  5723. if (!IsVectorizableOpcode(I->getOpcode()))
  5724. return false;
  5725. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  5726. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5727. if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
  5728. ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
  5729. return false;
  5730. }
  5731. auto willWiden = [&](unsigned VF) -> bool {
  5732. if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
  5733. CM.isProfitableToScalarize(I, VF)))
  5734. return false;
  5735. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  5736. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5737. // The following case may be scalarized depending on the VF.
  5738. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  5739. // version of the instruction.
  5740. // Is it beneficial to perform intrinsic call compared to lib call?
  5741. bool NeedToScalarize;
  5742. unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
  5743. bool UseVectorIntrinsic =
  5744. ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
  5745. return UseVectorIntrinsic || !NeedToScalarize;
  5746. }
  5747. if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
  5748. assert(CM.getWideningDecision(I, VF) ==
  5749. LoopVectorizationCostModel::CM_Scalarize &&
  5750. "Memory widening decisions should have been taken care by now");
  5751. return false;
  5752. }
  5753. return true;
  5754. };
  5755. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  5756. return false;
  5757. // Success: widen this instruction. We optimize the common case where
  5758. // consecutive instructions can be represented by a single recipe.
  5759. if (!VPBB->empty()) {
  5760. VPWidenRecipe *LastWidenRecipe = dyn_cast<VPWidenRecipe>(&VPBB->back());
  5761. if (LastWidenRecipe && LastWidenRecipe->appendInstruction(I))
  5762. return true;
  5763. }
  5764. VPBB->appendRecipe(new VPWidenRecipe(I));
  5765. return true;
  5766. }
  5767. VPBasicBlock *VPRecipeBuilder::handleReplication(
  5768. Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
  5769. DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
  5770. VPlanPtr &Plan) {
  5771. bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
  5772. [&](unsigned VF) { return CM.isUniformAfterVectorization(I, VF); },
  5773. Range);
  5774. bool IsPredicated = LoopVectorizationPlanner::getDecisionAndClampRange(
  5775. [&](unsigned VF) { return CM.isScalarWithPredication(I, VF); }, Range);
  5776. auto *Recipe = new VPReplicateRecipe(I, IsUniform, IsPredicated);
  5777. // Find if I uses a predicated instruction. If so, it will use its scalar
  5778. // value. Avoid hoisting the insert-element which packs the scalar value into
  5779. // a vector value, as that happens iff all users use the vector value.
  5780. for (auto &Op : I->operands())
  5781. if (auto *PredInst = dyn_cast<Instruction>(Op))
  5782. if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
  5783. PredInst2Recipe[PredInst]->setAlsoPack(false);
  5784. // Finalize the recipe for Instr, first if it is not predicated.
  5785. if (!IsPredicated) {
  5786. LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
  5787. VPBB->appendRecipe(Recipe);
  5788. return VPBB;
  5789. }
  5790. LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
  5791. assert(VPBB->getSuccessors().empty() &&
  5792. "VPBB has successors when handling predicated replication.");
  5793. // Record predicated instructions for above packing optimizations.
  5794. PredInst2Recipe[I] = Recipe;
  5795. VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
  5796. VPBlockUtils::insertBlockAfter(Region, VPBB);
  5797. auto *RegSucc = new VPBasicBlock();
  5798. VPBlockUtils::insertBlockAfter(RegSucc, Region);
  5799. return RegSucc;
  5800. }
  5801. VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
  5802. VPRecipeBase *PredRecipe,
  5803. VPlanPtr &Plan) {
  5804. // Instructions marked for predication are replicated and placed under an
  5805. // if-then construct to prevent side-effects.
  5806. // Generate recipes to compute the block mask for this region.
  5807. VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
  5808. // Build the triangular if-then region.
  5809. std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
  5810. assert(Instr->getParent() && "Predicated instruction not in any basic block");
  5811. auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
  5812. auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
  5813. auto *PHIRecipe =
  5814. Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr);
  5815. auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
  5816. auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
  5817. VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
  5818. // Note: first set Entry as region entry and then connect successors starting
  5819. // from it in order, to propagate the "parent" of each VPBasicBlock.
  5820. VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
  5821. VPBlockUtils::connectBlocks(Pred, Exit);
  5822. return Region;
  5823. }
  5824. bool VPRecipeBuilder::tryToCreateRecipe(Instruction *Instr, VFRange &Range,
  5825. VPlanPtr &Plan, VPBasicBlock *VPBB) {
  5826. VPRecipeBase *Recipe = nullptr;
  5827. // Check if Instr should belong to an interleave memory recipe, or already
  5828. // does. In the latter case Instr is irrelevant.
  5829. if ((Recipe = tryToInterleaveMemory(Instr, Range, Plan))) {
  5830. VPBB->appendRecipe(Recipe);
  5831. return true;
  5832. }
  5833. // Check if Instr is a memory operation that should be widened.
  5834. if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) {
  5835. VPBB->appendRecipe(Recipe);
  5836. return true;
  5837. }
  5838. // Check if Instr should form some PHI recipe.
  5839. if ((Recipe = tryToOptimizeInduction(Instr, Range))) {
  5840. VPBB->appendRecipe(Recipe);
  5841. return true;
  5842. }
  5843. if ((Recipe = tryToBlend(Instr, Plan))) {
  5844. VPBB->appendRecipe(Recipe);
  5845. return true;
  5846. }
  5847. if (PHINode *Phi = dyn_cast<PHINode>(Instr)) {
  5848. VPBB->appendRecipe(new VPWidenPHIRecipe(Phi));
  5849. return true;
  5850. }
  5851. // Check if Instr is to be widened by a general VPWidenRecipe, after
  5852. // having first checked for specific widening recipes that deal with
  5853. // Interleave Groups, Inductions and Phi nodes.
  5854. if (tryToWiden(Instr, VPBB, Range))
  5855. return true;
  5856. return false;
  5857. }
  5858. void LoopVectorizationPlanner::buildVPlansWithVPRecipes(unsigned MinVF,
  5859. unsigned MaxVF) {
  5860. assert(OrigLoop->empty() && "Inner loop expected.");
  5861. // Collect conditions feeding internal conditional branches; they need to be
  5862. // represented in VPlan for it to model masking.
  5863. SmallPtrSet<Value *, 1> NeedDef;
  5864. auto *Latch = OrigLoop->getLoopLatch();
  5865. for (BasicBlock *BB : OrigLoop->blocks()) {
  5866. if (BB == Latch)
  5867. continue;
  5868. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  5869. if (Branch && Branch->isConditional())
  5870. NeedDef.insert(Branch->getCondition());
  5871. }
  5872. // If the tail is to be folded by masking, the primary induction variable
  5873. // needs to be represented in VPlan for it to model early-exit masking.
  5874. if (CM.foldTailByMasking())
  5875. NeedDef.insert(Legal->getPrimaryInduction());
  5876. // Collect instructions from the original loop that will become trivially dead
  5877. // in the vectorized loop. We don't need to vectorize these instructions. For
  5878. // example, original induction update instructions can become dead because we
  5879. // separately emit induction "steps" when generating code for the new loop.
  5880. // Similarly, we create a new latch condition when setting up the structure
  5881. // of the new loop, so the old one can become dead.
  5882. SmallPtrSet<Instruction *, 4> DeadInstructions;
  5883. collectTriviallyDeadInstructions(DeadInstructions);
  5884. for (unsigned VF = MinVF; VF < MaxVF + 1;) {
  5885. VFRange SubRange = {VF, MaxVF + 1};
  5886. VPlans.push_back(
  5887. buildVPlanWithVPRecipes(SubRange, NeedDef, DeadInstructions));
  5888. VF = SubRange.End;
  5889. }
  5890. }
  5891. LoopVectorizationPlanner::VPlanPtr
  5892. LoopVectorizationPlanner::buildVPlanWithVPRecipes(
  5893. VFRange &Range, SmallPtrSetImpl<Value *> &NeedDef,
  5894. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  5895. // Hold a mapping from predicated instructions to their recipes, in order to
  5896. // fix their AlsoPack behavior if a user is determined to replicate and use a
  5897. // scalar instead of vector value.
  5898. DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
  5899. DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
  5900. DenseMap<Instruction *, Instruction *> SinkAfterInverse;
  5901. // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
  5902. VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
  5903. auto Plan = llvm::make_unique<VPlan>(VPBB);
  5904. VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, TTI, Legal, CM, Builder);
  5905. // Represent values that will have defs inside VPlan.
  5906. for (Value *V : NeedDef)
  5907. Plan->addVPValue(V);
  5908. // Scan the body of the loop in a topological order to visit each basic block
  5909. // after having visited its predecessor basic blocks.
  5910. LoopBlocksDFS DFS(OrigLoop);
  5911. DFS.perform(LI);
  5912. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  5913. // Relevant instructions from basic block BB will be grouped into VPRecipe
  5914. // ingredients and fill a new VPBasicBlock.
  5915. unsigned VPBBsForBB = 0;
  5916. auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
  5917. VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
  5918. VPBB = FirstVPBBForBB;
  5919. Builder.setInsertPoint(VPBB);
  5920. std::vector<Instruction *> Ingredients;
  5921. // Organize the ingredients to vectorize from current basic block in the
  5922. // right order.
  5923. for (Instruction &I : BB->instructionsWithoutDebug()) {
  5924. Instruction *Instr = &I;
  5925. // First filter out irrelevant instructions, to ensure no recipes are
  5926. // built for them.
  5927. if (isa<BranchInst>(Instr) ||
  5928. DeadInstructions.find(Instr) != DeadInstructions.end())
  5929. continue;
  5930. // I is a member of an InterleaveGroup for Range.Start. If it's an adjunct
  5931. // member of the IG, do not construct any Recipe for it.
  5932. const InterleaveGroup<Instruction> *IG =
  5933. CM.getInterleavedAccessGroup(Instr);
  5934. if (IG && Instr != IG->getInsertPos() &&
  5935. Range.Start >= 2 && // Query is illegal for VF == 1
  5936. CM.getWideningDecision(Instr, Range.Start) ==
  5937. LoopVectorizationCostModel::CM_Interleave) {
  5938. auto SinkCandidate = SinkAfterInverse.find(Instr);
  5939. if (SinkCandidate != SinkAfterInverse.end())
  5940. Ingredients.push_back(SinkCandidate->second);
  5941. continue;
  5942. }
  5943. // Move instructions to handle first-order recurrences, step 1: avoid
  5944. // handling this instruction until after we've handled the instruction it
  5945. // should follow.
  5946. auto SAIt = SinkAfter.find(Instr);
  5947. if (SAIt != SinkAfter.end()) {
  5948. LLVM_DEBUG(dbgs() << "Sinking" << *SAIt->first << " after"
  5949. << *SAIt->second
  5950. << " to vectorize a 1st order recurrence.\n");
  5951. SinkAfterInverse[SAIt->second] = Instr;
  5952. continue;
  5953. }
  5954. Ingredients.push_back(Instr);
  5955. // Move instructions to handle first-order recurrences, step 2: push the
  5956. // instruction to be sunk at its insertion point.
  5957. auto SAInvIt = SinkAfterInverse.find(Instr);
  5958. if (SAInvIt != SinkAfterInverse.end())
  5959. Ingredients.push_back(SAInvIt->second);
  5960. }
  5961. // Introduce each ingredient into VPlan.
  5962. for (Instruction *Instr : Ingredients) {
  5963. if (RecipeBuilder.tryToCreateRecipe(Instr, Range, Plan, VPBB))
  5964. continue;
  5965. // Otherwise, if all widening options failed, Instruction is to be
  5966. // replicated. This may create a successor for VPBB.
  5967. VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
  5968. Instr, Range, VPBB, PredInst2Recipe, Plan);
  5969. if (NextVPBB != VPBB) {
  5970. VPBB = NextVPBB;
  5971. VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
  5972. : "");
  5973. }
  5974. }
  5975. }
  5976. // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
  5977. // may also be empty, such as the last one VPBB, reflecting original
  5978. // basic-blocks with no recipes.
  5979. VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
  5980. assert(PreEntry->empty() && "Expecting empty pre-entry block.");
  5981. VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
  5982. VPBlockUtils::disconnectBlocks(PreEntry, Entry);
  5983. delete PreEntry;
  5984. std::string PlanName;
  5985. raw_string_ostream RSO(PlanName);
  5986. unsigned VF = Range.Start;
  5987. Plan->addVF(VF);
  5988. RSO << "Initial VPlan for VF={" << VF;
  5989. for (VF *= 2; VF < Range.End; VF *= 2) {
  5990. Plan->addVF(VF);
  5991. RSO << "," << VF;
  5992. }
  5993. RSO << "},UF>=1";
  5994. RSO.flush();
  5995. Plan->setName(PlanName);
  5996. return Plan;
  5997. }
  5998. LoopVectorizationPlanner::VPlanPtr
  5999. LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
  6000. // Outer loop handling: They may require CFG and instruction level
  6001. // transformations before even evaluating whether vectorization is profitable.
  6002. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  6003. // the vectorization pipeline.
  6004. assert(!OrigLoop->empty());
  6005. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  6006. // Create new empty VPlan
  6007. auto Plan = llvm::make_unique<VPlan>();
  6008. // Build hierarchical CFG
  6009. VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
  6010. HCFGBuilder.buildHierarchicalCFG();
  6011. for (unsigned VF = Range.Start; VF < Range.End; VF *= 2)
  6012. Plan->addVF(VF);
  6013. if (EnableVPlanPredication) {
  6014. VPlanPredicator VPP(*Plan);
  6015. VPP.predicate();
  6016. // Avoid running transformation to recipes until masked code generation in
  6017. // VPlan-native path is in place.
  6018. return Plan;
  6019. }
  6020. SmallPtrSet<Instruction *, 1> DeadInstructions;
  6021. VPlanHCFGTransforms::VPInstructionsToVPRecipes(
  6022. Plan, Legal->getInductionVars(), DeadInstructions);
  6023. return Plan;
  6024. }
  6025. Value* LoopVectorizationPlanner::VPCallbackILV::
  6026. getOrCreateVectorValues(Value *V, unsigned Part) {
  6027. return ILV.getOrCreateVectorValue(V, Part);
  6028. }
  6029. void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent) const {
  6030. O << " +\n"
  6031. << Indent << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
  6032. IG->getInsertPos()->printAsOperand(O, false);
  6033. if (User) {
  6034. O << ", ";
  6035. User->getOperand(0)->printAsOperand(O);
  6036. }
  6037. O << "\\l\"";
  6038. for (unsigned i = 0; i < IG->getFactor(); ++i)
  6039. if (Instruction *I = IG->getMember(i))
  6040. O << " +\n"
  6041. << Indent << "\" " << VPlanIngredient(I) << " " << i << "\\l\"";
  6042. }
  6043. void VPWidenRecipe::execute(VPTransformState &State) {
  6044. for (auto &Instr : make_range(Begin, End))
  6045. State.ILV->widenInstruction(Instr);
  6046. }
  6047. void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
  6048. assert(!State.Instance && "Int or FP induction being replicated.");
  6049. State.ILV->widenIntOrFpInduction(IV, Trunc);
  6050. }
  6051. void VPWidenPHIRecipe::execute(VPTransformState &State) {
  6052. State.ILV->widenPHIInstruction(Phi, State.UF, State.VF);
  6053. }
  6054. void VPBlendRecipe::execute(VPTransformState &State) {
  6055. State.ILV->setDebugLocFromInst(State.Builder, Phi);
  6056. // We know that all PHIs in non-header blocks are converted into
  6057. // selects, so we don't have to worry about the insertion order and we
  6058. // can just use the builder.
  6059. // At this point we generate the predication tree. There may be
  6060. // duplications since this is a simple recursive scan, but future
  6061. // optimizations will clean it up.
  6062. unsigned NumIncoming = Phi->getNumIncomingValues();
  6063. assert((User || NumIncoming == 1) &&
  6064. "Multiple predecessors with predecessors having a full mask");
  6065. // Generate a sequence of selects of the form:
  6066. // SELECT(Mask3, In3,
  6067. // SELECT(Mask2, In2,
  6068. // ( ...)))
  6069. InnerLoopVectorizer::VectorParts Entry(State.UF);
  6070. for (unsigned In = 0; In < NumIncoming; ++In) {
  6071. for (unsigned Part = 0; Part < State.UF; ++Part) {
  6072. // We might have single edge PHIs (blocks) - use an identity
  6073. // 'select' for the first PHI operand.
  6074. Value *In0 =
  6075. State.ILV->getOrCreateVectorValue(Phi->getIncomingValue(In), Part);
  6076. if (In == 0)
  6077. Entry[Part] = In0; // Initialize with the first incoming value.
  6078. else {
  6079. // Select between the current value and the previous incoming edge
  6080. // based on the incoming mask.
  6081. Value *Cond = State.get(User->getOperand(In), Part);
  6082. Entry[Part] =
  6083. State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
  6084. }
  6085. }
  6086. }
  6087. for (unsigned Part = 0; Part < State.UF; ++Part)
  6088. State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
  6089. }
  6090. void VPInterleaveRecipe::execute(VPTransformState &State) {
  6091. assert(!State.Instance && "Interleave group being replicated.");
  6092. if (!User)
  6093. return State.ILV->vectorizeInterleaveGroup(IG->getInsertPos());
  6094. // Last (and currently only) operand is a mask.
  6095. InnerLoopVectorizer::VectorParts MaskValues(State.UF);
  6096. VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
  6097. for (unsigned Part = 0; Part < State.UF; ++Part)
  6098. MaskValues[Part] = State.get(Mask, Part);
  6099. State.ILV->vectorizeInterleaveGroup(IG->getInsertPos(), &MaskValues);
  6100. }
  6101. void VPReplicateRecipe::execute(VPTransformState &State) {
  6102. if (State.Instance) { // Generate a single instance.
  6103. State.ILV->scalarizeInstruction(Ingredient, *State.Instance, IsPredicated);
  6104. // Insert scalar instance packing it into a vector.
  6105. if (AlsoPack && State.VF > 1) {
  6106. // If we're constructing lane 0, initialize to start from undef.
  6107. if (State.Instance->Lane == 0) {
  6108. Value *Undef =
  6109. UndefValue::get(VectorType::get(Ingredient->getType(), State.VF));
  6110. State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef);
  6111. }
  6112. State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance);
  6113. }
  6114. return;
  6115. }
  6116. // Generate scalar instances for all VF lanes of all UF parts, unless the
  6117. // instruction is uniform inwhich case generate only the first lane for each
  6118. // of the UF parts.
  6119. unsigned EndLane = IsUniform ? 1 : State.VF;
  6120. for (unsigned Part = 0; Part < State.UF; ++Part)
  6121. for (unsigned Lane = 0; Lane < EndLane; ++Lane)
  6122. State.ILV->scalarizeInstruction(Ingredient, {Part, Lane}, IsPredicated);
  6123. }
  6124. void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
  6125. assert(State.Instance && "Branch on Mask works only on single instance.");
  6126. unsigned Part = State.Instance->Part;
  6127. unsigned Lane = State.Instance->Lane;
  6128. Value *ConditionBit = nullptr;
  6129. if (!User) // Block in mask is all-one.
  6130. ConditionBit = State.Builder.getTrue();
  6131. else {
  6132. VPValue *BlockInMask = User->getOperand(0);
  6133. ConditionBit = State.get(BlockInMask, Part);
  6134. if (ConditionBit->getType()->isVectorTy())
  6135. ConditionBit = State.Builder.CreateExtractElement(
  6136. ConditionBit, State.Builder.getInt32(Lane));
  6137. }
  6138. // Replace the temporary unreachable terminator with a new conditional branch,
  6139. // whose two destinations will be set later when they are created.
  6140. auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
  6141. assert(isa<UnreachableInst>(CurrentTerminator) &&
  6142. "Expected to replace unreachable terminator with conditional branch.");
  6143. auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
  6144. CondBr->setSuccessor(0, nullptr);
  6145. ReplaceInstWithInst(CurrentTerminator, CondBr);
  6146. }
  6147. void VPPredInstPHIRecipe::execute(VPTransformState &State) {
  6148. assert(State.Instance && "Predicated instruction PHI works per instance.");
  6149. Instruction *ScalarPredInst = cast<Instruction>(
  6150. State.ValueMap.getScalarValue(PredInst, *State.Instance));
  6151. BasicBlock *PredicatedBB = ScalarPredInst->getParent();
  6152. BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
  6153. assert(PredicatingBB && "Predicated block has no single predecessor.");
  6154. // By current pack/unpack logic we need to generate only a single phi node: if
  6155. // a vector value for the predicated instruction exists at this point it means
  6156. // the instruction has vector users only, and a phi for the vector value is
  6157. // needed. In this case the recipe of the predicated instruction is marked to
  6158. // also do that packing, thereby "hoisting" the insert-element sequence.
  6159. // Otherwise, a phi node for the scalar value is needed.
  6160. unsigned Part = State.Instance->Part;
  6161. if (State.ValueMap.hasVectorValue(PredInst, Part)) {
  6162. Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
  6163. InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
  6164. PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
  6165. VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
  6166. VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
  6167. State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
  6168. } else {
  6169. Type *PredInstType = PredInst->getType();
  6170. PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
  6171. Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB);
  6172. Phi->addIncoming(ScalarPredInst, PredicatedBB);
  6173. State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
  6174. }
  6175. }
  6176. void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
  6177. if (!User)
  6178. return State.ILV->vectorizeMemoryInstruction(&Instr);
  6179. // Last (and currently only) operand is a mask.
  6180. InnerLoopVectorizer::VectorParts MaskValues(State.UF);
  6181. VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
  6182. for (unsigned Part = 0; Part < State.UF; ++Part)
  6183. MaskValues[Part] = State.get(Mask, Part);
  6184. State.ILV->vectorizeMemoryInstruction(&Instr, &MaskValues);
  6185. }
  6186. // Process the loop in the VPlan-native vectorization path. This path builds
  6187. // VPlan upfront in the vectorization pipeline, which allows to apply
  6188. // VPlan-to-VPlan transformations from the very beginning without modifying the
  6189. // input LLVM IR.
  6190. static bool processLoopInVPlanNativePath(
  6191. Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
  6192. LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
  6193. TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
  6194. OptimizationRemarkEmitter *ORE, BlockFrequencyInfo *BFI,
  6195. ProfileSummaryInfo *PSI, LoopVectorizeHints &Hints) {
  6196. assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
  6197. Function *F = L->getHeader()->getParent();
  6198. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
  6199. LoopVectorizationCostModel CM(L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
  6200. &Hints, IAI);
  6201. // Use the planner for outer loop vectorization.
  6202. // TODO: CM is not used at this point inside the planner. Turn CM into an
  6203. // optional argument if we don't need it in the future.
  6204. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM);
  6205. // Get user vectorization factor.
  6206. const unsigned UserVF = Hints.getWidth();
  6207. // Check the function attributes and profiles to find out if this function
  6208. // should be optimized for size.
  6209. bool OptForSize =
  6210. Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  6211. (F->hasOptSize() ||
  6212. llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI));
  6213. // Plan how to best vectorize, return the best VF and its cost.
  6214. const VectorizationFactor VF = LVP.planInVPlanNativePath(OptForSize, UserVF);
  6215. // If we are stress testing VPlan builds, do not attempt to generate vector
  6216. // code. Masked vector code generation support will follow soon.
  6217. // Also, do not attempt to vectorize if no vector code will be produced.
  6218. if (VPlanBuildStressTest || EnableVPlanPredication ||
  6219. VectorizationFactor::Disabled() == VF)
  6220. return false;
  6221. LVP.setBestPlan(VF.Width, 1);
  6222. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, 1, LVL,
  6223. &CM);
  6224. LLVM_DEBUG(dbgs() << "Vectorizing outer loop in \""
  6225. << L->getHeader()->getParent()->getName() << "\"\n");
  6226. LVP.executePlan(LB, DT);
  6227. // Mark the loop as already vectorized to avoid vectorizing again.
  6228. Hints.setAlreadyVectorized();
  6229. LLVM_DEBUG(verifyFunction(*L->getHeader()->getParent()));
  6230. return true;
  6231. }
  6232. bool LoopVectorizePass::processLoop(Loop *L) {
  6233. assert((EnableVPlanNativePath || L->empty()) &&
  6234. "VPlan-native path is not enabled. Only process inner loops.");
  6235. #ifndef NDEBUG
  6236. const std::string DebugLocStr = getDebugLocString(L);
  6237. #endif /* NDEBUG */
  6238. LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
  6239. << L->getHeader()->getParent()->getName() << "\" from "
  6240. << DebugLocStr << "\n");
  6241. LoopVectorizeHints Hints(L, InterleaveOnlyWhenForced, *ORE);
  6242. LLVM_DEBUG(
  6243. dbgs() << "LV: Loop hints:"
  6244. << " force="
  6245. << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
  6246. ? "disabled"
  6247. : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
  6248. ? "enabled"
  6249. : "?"))
  6250. << " width=" << Hints.getWidth()
  6251. << " unroll=" << Hints.getInterleave() << "\n");
  6252. // Function containing loop
  6253. Function *F = L->getHeader()->getParent();
  6254. // Looking at the diagnostic output is the only way to determine if a loop
  6255. // was vectorized (other than looking at the IR or machine code), so it
  6256. // is important to generate an optimization remark for each loop. Most of
  6257. // these messages are generated as OptimizationRemarkAnalysis. Remarks
  6258. // generated as OptimizationRemark and OptimizationRemarkMissed are
  6259. // less verbose reporting vectorized loops and unvectorized loops that may
  6260. // benefit from vectorization, respectively.
  6261. if (!Hints.allowVectorization(F, L, VectorizeOnlyWhenForced)) {
  6262. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
  6263. return false;
  6264. }
  6265. PredicatedScalarEvolution PSE(*SE, *L);
  6266. // Check if it is legal to vectorize the loop.
  6267. LoopVectorizationRequirements Requirements(*ORE);
  6268. LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, GetLAA, LI, ORE,
  6269. &Requirements, &Hints, DB, AC);
  6270. if (!LVL.canVectorize(EnableVPlanNativePath)) {
  6271. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  6272. Hints.emitRemarkWithHints();
  6273. return false;
  6274. }
  6275. // Check the function attributes and profiles to find out if this function
  6276. // should be optimized for size.
  6277. bool OptForSize =
  6278. Hints.getForce() != LoopVectorizeHints::FK_Enabled &&
  6279. (F->hasOptSize() ||
  6280. llvm::shouldOptimizeForSize(L->getHeader(), PSI, BFI));
  6281. // Entrance to the VPlan-native vectorization path. Outer loops are processed
  6282. // here. They may require CFG and instruction level transformations before
  6283. // even evaluating whether vectorization is profitable. Since we cannot modify
  6284. // the incoming IR, we need to build VPlan upfront in the vectorization
  6285. // pipeline.
  6286. if (!L->empty())
  6287. return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
  6288. ORE, BFI, PSI, Hints);
  6289. assert(L->empty() && "Inner loop expected.");
  6290. // Check the loop for a trip count threshold: vectorize loops with a tiny trip
  6291. // count by optimizing for size, to minimize overheads.
  6292. // Prefer constant trip counts over profile data, over upper bound estimate.
  6293. unsigned ExpectedTC = 0;
  6294. bool HasExpectedTC = false;
  6295. if (const SCEVConstant *ConstExits =
  6296. dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) {
  6297. const APInt &ExitsCount = ConstExits->getAPInt();
  6298. // We are interested in small values for ExpectedTC. Skip over those that
  6299. // can't fit an unsigned.
  6300. if (ExitsCount.ult(std::numeric_limits<unsigned>::max())) {
  6301. ExpectedTC = static_cast<unsigned>(ExitsCount.getZExtValue()) + 1;
  6302. HasExpectedTC = true;
  6303. }
  6304. }
  6305. // ExpectedTC may be large because it's bound by a variable. Check
  6306. // profiling information to validate we should vectorize.
  6307. if (!HasExpectedTC && LoopVectorizeWithBlockFrequency) {
  6308. auto EstimatedTC = getLoopEstimatedTripCount(L);
  6309. if (EstimatedTC) {
  6310. ExpectedTC = *EstimatedTC;
  6311. HasExpectedTC = true;
  6312. }
  6313. }
  6314. if (!HasExpectedTC) {
  6315. ExpectedTC = SE->getSmallConstantMaxTripCount(L);
  6316. HasExpectedTC = (ExpectedTC > 0);
  6317. }
  6318. if (HasExpectedTC && ExpectedTC < TinyTripCountVectorThreshold) {
  6319. LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
  6320. << "This loop is worth vectorizing only if no scalar "
  6321. << "iteration overheads are incurred.");
  6322. if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
  6323. LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
  6324. else {
  6325. LLVM_DEBUG(dbgs() << "\n");
  6326. // Loops with a very small trip count are considered for vectorization
  6327. // under OptForSize, thereby making sure the cost of their loop body is
  6328. // dominant, free of runtime guards and scalar iteration overheads.
  6329. OptForSize = true;
  6330. }
  6331. }
  6332. // Check the function attributes to see if implicit floats are allowed.
  6333. // FIXME: This check doesn't seem possibly correct -- what if the loop is
  6334. // an integer loop and the vector instructions selected are purely integer
  6335. // vector instructions?
  6336. if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
  6337. LLVM_DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
  6338. "attribute is used.\n");
  6339. ORE->emit(createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(),
  6340. "NoImplicitFloat", L)
  6341. << "loop not vectorized due to NoImplicitFloat attribute");
  6342. Hints.emitRemarkWithHints();
  6343. return false;
  6344. }
  6345. // Check if the target supports potentially unsafe FP vectorization.
  6346. // FIXME: Add a check for the type of safety issue (denormal, signaling)
  6347. // for the target we're vectorizing for, to make sure none of the
  6348. // additional fp-math flags can help.
  6349. if (Hints.isPotentiallyUnsafe() &&
  6350. TTI->isFPVectorizationPotentiallyUnsafe()) {
  6351. LLVM_DEBUG(
  6352. dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
  6353. ORE->emit(
  6354. createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
  6355. << "loop not vectorized due to unsafe FP support.");
  6356. Hints.emitRemarkWithHints();
  6357. return false;
  6358. }
  6359. bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
  6360. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
  6361. // If an override option has been passed in for interleaved accesses, use it.
  6362. if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
  6363. UseInterleaved = EnableInterleavedMemAccesses;
  6364. // Analyze interleaved memory accesses.
  6365. if (UseInterleaved) {
  6366. IAI.analyzeInterleaving(useMaskedInterleavedAccesses(*TTI));
  6367. }
  6368. // Use the cost model.
  6369. LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
  6370. &Hints, IAI);
  6371. CM.collectValuesToIgnore();
  6372. // Use the planner for vectorization.
  6373. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM);
  6374. // Get user vectorization factor.
  6375. unsigned UserVF = Hints.getWidth();
  6376. // Plan how to best vectorize, return the best VF and its cost.
  6377. Optional<VectorizationFactor> MaybeVF = LVP.plan(OptForSize, UserVF);
  6378. VectorizationFactor VF = VectorizationFactor::Disabled();
  6379. unsigned IC = 1;
  6380. unsigned UserIC = Hints.getInterleave();
  6381. if (MaybeVF) {
  6382. VF = *MaybeVF;
  6383. // Select the interleave count.
  6384. IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
  6385. }
  6386. // Identify the diagnostic messages that should be produced.
  6387. std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
  6388. bool VectorizeLoop = true, InterleaveLoop = true;
  6389. if (Requirements.doesNotMeet(F, L, Hints)) {
  6390. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
  6391. "requirements.\n");
  6392. Hints.emitRemarkWithHints();
  6393. return false;
  6394. }
  6395. if (VF.Width == 1) {
  6396. LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  6397. VecDiagMsg = std::make_pair(
  6398. "VectorizationNotBeneficial",
  6399. "the cost-model indicates that vectorization is not beneficial");
  6400. VectorizeLoop = false;
  6401. }
  6402. if (!MaybeVF && UserIC > 1) {
  6403. // Tell the user interleaving was avoided up-front, despite being explicitly
  6404. // requested.
  6405. LLVM_DEBUG(dbgs() << "LV: Ignoring UserIC, because vectorization and "
  6406. "interleaving should be avoided up front\n");
  6407. IntDiagMsg = std::make_pair(
  6408. "InterleavingAvoided",
  6409. "Ignoring UserIC, because interleaving was avoided up front");
  6410. InterleaveLoop = false;
  6411. } else if (IC == 1 && UserIC <= 1) {
  6412. // Tell the user interleaving is not beneficial.
  6413. LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
  6414. IntDiagMsg = std::make_pair(
  6415. "InterleavingNotBeneficial",
  6416. "the cost-model indicates that interleaving is not beneficial");
  6417. InterleaveLoop = false;
  6418. if (UserIC == 1) {
  6419. IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
  6420. IntDiagMsg.second +=
  6421. " and is explicitly disabled or interleave count is set to 1";
  6422. }
  6423. } else if (IC > 1 && UserIC == 1) {
  6424. // Tell the user interleaving is beneficial, but it explicitly disabled.
  6425. LLVM_DEBUG(
  6426. dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
  6427. IntDiagMsg = std::make_pair(
  6428. "InterleavingBeneficialButDisabled",
  6429. "the cost-model indicates that interleaving is beneficial "
  6430. "but is explicitly disabled or interleave count is set to 1");
  6431. InterleaveLoop = false;
  6432. }
  6433. // Override IC if user provided an interleave count.
  6434. IC = UserIC > 0 ? UserIC : IC;
  6435. // Emit diagnostic messages, if any.
  6436. const char *VAPassName = Hints.vectorizeAnalysisPassName();
  6437. if (!VectorizeLoop && !InterleaveLoop) {
  6438. // Do not vectorize or interleaving the loop.
  6439. ORE->emit([&]() {
  6440. return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
  6441. L->getStartLoc(), L->getHeader())
  6442. << VecDiagMsg.second;
  6443. });
  6444. ORE->emit([&]() {
  6445. return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
  6446. L->getStartLoc(), L->getHeader())
  6447. << IntDiagMsg.second;
  6448. });
  6449. return false;
  6450. } else if (!VectorizeLoop && InterleaveLoop) {
  6451. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  6452. ORE->emit([&]() {
  6453. return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
  6454. L->getStartLoc(), L->getHeader())
  6455. << VecDiagMsg.second;
  6456. });
  6457. } else if (VectorizeLoop && !InterleaveLoop) {
  6458. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  6459. << ") in " << DebugLocStr << '\n');
  6460. ORE->emit([&]() {
  6461. return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
  6462. L->getStartLoc(), L->getHeader())
  6463. << IntDiagMsg.second;
  6464. });
  6465. } else if (VectorizeLoop && InterleaveLoop) {
  6466. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  6467. << ") in " << DebugLocStr << '\n');
  6468. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  6469. }
  6470. LVP.setBestPlan(VF.Width, IC);
  6471. using namespace ore;
  6472. bool DisableRuntimeUnroll = false;
  6473. MDNode *OrigLoopID = L->getLoopID();
  6474. if (!VectorizeLoop) {
  6475. assert(IC > 1 && "interleave count should not be 1 or 0");
  6476. // If we decided that it is not legal to vectorize the loop, then
  6477. // interleave it.
  6478. InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
  6479. &CM);
  6480. LVP.executePlan(Unroller, DT);
  6481. ORE->emit([&]() {
  6482. return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
  6483. L->getHeader())
  6484. << "interleaved loop (interleaved count: "
  6485. << NV("InterleaveCount", IC) << ")";
  6486. });
  6487. } else {
  6488. // If we decided that it is *legal* to vectorize the loop, then do it.
  6489. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
  6490. &LVL, &CM);
  6491. LVP.executePlan(LB, DT);
  6492. ++LoopsVectorized;
  6493. // Add metadata to disable runtime unrolling a scalar loop when there are
  6494. // no runtime checks about strides and memory. A scalar loop that is
  6495. // rarely used is not worth unrolling.
  6496. if (!LB.areSafetyChecksAdded())
  6497. DisableRuntimeUnroll = true;
  6498. // Report the vectorization decision.
  6499. ORE->emit([&]() {
  6500. return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
  6501. L->getHeader())
  6502. << "vectorized loop (vectorization width: "
  6503. << NV("VectorizationFactor", VF.Width)
  6504. << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
  6505. });
  6506. }
  6507. Optional<MDNode *> RemainderLoopID =
  6508. makeFollowupLoopID(OrigLoopID, {LLVMLoopVectorizeFollowupAll,
  6509. LLVMLoopVectorizeFollowupEpilogue});
  6510. if (RemainderLoopID.hasValue()) {
  6511. L->setLoopID(RemainderLoopID.getValue());
  6512. } else {
  6513. if (DisableRuntimeUnroll)
  6514. AddRuntimeUnrollDisableMetaData(L);
  6515. // Mark the loop as already vectorized to avoid vectorizing again.
  6516. Hints.setAlreadyVectorized();
  6517. }
  6518. LLVM_DEBUG(verifyFunction(*L->getHeader()->getParent()));
  6519. return true;
  6520. }
  6521. bool LoopVectorizePass::runImpl(
  6522. Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
  6523. DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
  6524. DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
  6525. std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
  6526. OptimizationRemarkEmitter &ORE_, ProfileSummaryInfo *PSI_) {
  6527. SE = &SE_;
  6528. LI = &LI_;
  6529. TTI = &TTI_;
  6530. DT = &DT_;
  6531. BFI = &BFI_;
  6532. TLI = TLI_;
  6533. AA = &AA_;
  6534. AC = &AC_;
  6535. GetLAA = &GetLAA_;
  6536. DB = &DB_;
  6537. ORE = &ORE_;
  6538. PSI = PSI_;
  6539. // Don't attempt if
  6540. // 1. the target claims to have no vector registers, and
  6541. // 2. interleaving won't help ILP.
  6542. //
  6543. // The second condition is necessary because, even if the target has no
  6544. // vector registers, loop vectorization may still enable scalar
  6545. // interleaving.
  6546. if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
  6547. return false;
  6548. bool Changed = false;
  6549. // The vectorizer requires loops to be in simplified form.
  6550. // Since simplification may add new inner loops, it has to run before the
  6551. // legality and profitability checks. This means running the loop vectorizer
  6552. // will simplify all loops, regardless of whether anything end up being
  6553. // vectorized.
  6554. for (auto &L : *LI)
  6555. Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
  6556. // Build up a worklist of inner-loops to vectorize. This is necessary as
  6557. // the act of vectorizing or partially unrolling a loop creates new loops
  6558. // and can invalidate iterators across the loops.
  6559. SmallVector<Loop *, 8> Worklist;
  6560. for (Loop *L : *LI)
  6561. collectSupportedLoops(*L, LI, ORE, Worklist);
  6562. LoopsAnalyzed += Worklist.size();
  6563. // Now walk the identified inner loops.
  6564. while (!Worklist.empty()) {
  6565. Loop *L = Worklist.pop_back_val();
  6566. // For the inner loops we actually process, form LCSSA to simplify the
  6567. // transform.
  6568. Changed |= formLCSSARecursively(*L, *DT, LI, SE);
  6569. Changed |= processLoop(L);
  6570. }
  6571. // Process each loop nest in the function.
  6572. return Changed;
  6573. }
  6574. PreservedAnalyses LoopVectorizePass::run(Function &F,
  6575. FunctionAnalysisManager &AM) {
  6576. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  6577. auto &LI = AM.getResult<LoopAnalysis>(F);
  6578. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  6579. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  6580. auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
  6581. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  6582. auto &AA = AM.getResult<AAManager>(F);
  6583. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  6584. auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
  6585. auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  6586. MemorySSA *MSSA = EnableMSSALoopDependency
  6587. ? &AM.getResult<MemorySSAAnalysis>(F).getMSSA()
  6588. : nullptr;
  6589. auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
  6590. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  6591. [&](Loop &L) -> const LoopAccessInfo & {
  6592. LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, MSSA};
  6593. return LAM.getResult<LoopAccessAnalysis>(L, AR);
  6594. };
  6595. const ModuleAnalysisManager &MAM =
  6596. AM.getResult<ModuleAnalysisManagerFunctionProxy>(F).getManager();
  6597. ProfileSummaryInfo *PSI =
  6598. MAM.getCachedResult<ProfileSummaryAnalysis>(*F.getParent());
  6599. bool Changed =
  6600. runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE, PSI);
  6601. if (!Changed)
  6602. return PreservedAnalyses::all();
  6603. PreservedAnalyses PA;
  6604. // We currently do not preserve loopinfo/dominator analyses with outer loop
  6605. // vectorization. Until this is addressed, mark these analyses as preserved
  6606. // only for non-VPlan-native path.
  6607. // TODO: Preserve Loop and Dominator analyses for VPlan-native path.
  6608. if (!EnableVPlanNativePath) {
  6609. PA.preserve<LoopAnalysis>();
  6610. PA.preserve<DominatorTreeAnalysis>();
  6611. }
  6612. PA.preserve<BasicAA>();
  6613. PA.preserve<GlobalsAA>();
  6614. return PA;
  6615. }