LoopVectorize.cpp 346 KB

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