CodeGenPrepare.cpp 321 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This pass munges the code in the input function to better prepare it for
  10. // SelectionDAG-based code generation. This works around limitations in it's
  11. // basic-block-at-a-time approach. It should eventually be removed.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "llvm/ADT/APInt.h"
  15. #include "llvm/ADT/ArrayRef.h"
  16. #include "llvm/ADT/DenseMap.h"
  17. #include "llvm/ADT/MapVector.h"
  18. #include "llvm/ADT/PointerIntPair.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/SmallVector.h"
  22. #include "llvm/ADT/Statistic.h"
  23. #include "llvm/Analysis/BlockFrequencyInfo.h"
  24. #include "llvm/Analysis/BranchProbabilityInfo.h"
  25. #include "llvm/Analysis/InstructionSimplify.h"
  26. #include "llvm/Analysis/LoopInfo.h"
  27. #include "llvm/Analysis/ProfileSummaryInfo.h"
  28. #include "llvm/Analysis/TargetLibraryInfo.h"
  29. #include "llvm/Analysis/TargetTransformInfo.h"
  30. #include "llvm/Analysis/ValueTracking.h"
  31. #include "llvm/Analysis/VectorUtils.h"
  32. #include "llvm/CodeGen/Analysis.h"
  33. #include "llvm/CodeGen/BasicBlockSectionsProfileReader.h"
  34. #include "llvm/CodeGen/ISDOpcodes.h"
  35. #include "llvm/CodeGen/SelectionDAGNodes.h"
  36. #include "llvm/CodeGen/TargetLowering.h"
  37. #include "llvm/CodeGen/TargetPassConfig.h"
  38. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  39. #include "llvm/CodeGen/ValueTypes.h"
  40. #include "llvm/Config/llvm-config.h"
  41. #include "llvm/IR/Argument.h"
  42. #include "llvm/IR/Attributes.h"
  43. #include "llvm/IR/BasicBlock.h"
  44. #include "llvm/IR/Constant.h"
  45. #include "llvm/IR/Constants.h"
  46. #include "llvm/IR/DataLayout.h"
  47. #include "llvm/IR/DebugInfo.h"
  48. #include "llvm/IR/DerivedTypes.h"
  49. #include "llvm/IR/Dominators.h"
  50. #include "llvm/IR/Function.h"
  51. #include "llvm/IR/GetElementPtrTypeIterator.h"
  52. #include "llvm/IR/GlobalValue.h"
  53. #include "llvm/IR/GlobalVariable.h"
  54. #include "llvm/IR/IRBuilder.h"
  55. #include "llvm/IR/InlineAsm.h"
  56. #include "llvm/IR/InstrTypes.h"
  57. #include "llvm/IR/Instruction.h"
  58. #include "llvm/IR/Instructions.h"
  59. #include "llvm/IR/IntrinsicInst.h"
  60. #include "llvm/IR/Intrinsics.h"
  61. #include "llvm/IR/IntrinsicsAArch64.h"
  62. #include "llvm/IR/LLVMContext.h"
  63. #include "llvm/IR/MDBuilder.h"
  64. #include "llvm/IR/Module.h"
  65. #include "llvm/IR/Operator.h"
  66. #include "llvm/IR/PatternMatch.h"
  67. #include "llvm/IR/ProfDataUtils.h"
  68. #include "llvm/IR/Statepoint.h"
  69. #include "llvm/IR/Type.h"
  70. #include "llvm/IR/Use.h"
  71. #include "llvm/IR/User.h"
  72. #include "llvm/IR/Value.h"
  73. #include "llvm/IR/ValueHandle.h"
  74. #include "llvm/IR/ValueMap.h"
  75. #include "llvm/InitializePasses.h"
  76. #include "llvm/Pass.h"
  77. #include "llvm/Support/BlockFrequency.h"
  78. #include "llvm/Support/BranchProbability.h"
  79. #include "llvm/Support/Casting.h"
  80. #include "llvm/Support/CommandLine.h"
  81. #include "llvm/Support/Compiler.h"
  82. #include "llvm/Support/Debug.h"
  83. #include "llvm/Support/ErrorHandling.h"
  84. #include "llvm/Support/MachineValueType.h"
  85. #include "llvm/Support/MathExtras.h"
  86. #include "llvm/Support/raw_ostream.h"
  87. #include "llvm/Target/TargetMachine.h"
  88. #include "llvm/Target/TargetOptions.h"
  89. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  90. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  91. #include "llvm/Transforms/Utils/Local.h"
  92. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  93. #include "llvm/Transforms/Utils/SizeOpts.h"
  94. #include <algorithm>
  95. #include <cassert>
  96. #include <cstdint>
  97. #include <iterator>
  98. #include <limits>
  99. #include <memory>
  100. #include <optional>
  101. #include <utility>
  102. #include <vector>
  103. using namespace llvm;
  104. using namespace llvm::PatternMatch;
  105. #define DEBUG_TYPE "codegenprepare"
  106. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  107. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  108. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  109. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  110. "sunken Cmps");
  111. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  112. "of sunken Casts");
  113. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  114. "computations were sunk");
  115. STATISTIC(NumMemoryInstsPhiCreated,
  116. "Number of phis created when address "
  117. "computations were sunk to memory instructions");
  118. STATISTIC(NumMemoryInstsSelectCreated,
  119. "Number of select created when address "
  120. "computations were sunk to memory instructions");
  121. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  122. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  123. STATISTIC(NumAndsAdded,
  124. "Number of and mask instructions added to form ext loads");
  125. STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
  126. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  127. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  128. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  129. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  130. static cl::opt<bool> DisableBranchOpts(
  131. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  132. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  133. static cl::opt<bool>
  134. DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
  135. cl::desc("Disable GC optimizations in CodeGenPrepare"));
  136. static cl::opt<bool>
  137. DisableSelectToBranch("disable-cgp-select2branch", cl::Hidden,
  138. cl::init(false),
  139. cl::desc("Disable select to branch conversion."));
  140. static cl::opt<bool>
  141. AddrSinkUsingGEPs("addr-sink-using-gep", cl::Hidden, cl::init(true),
  142. cl::desc("Address sinking in CGP using GEPs."));
  143. static cl::opt<bool>
  144. EnableAndCmpSinking("enable-andcmp-sinking", cl::Hidden, cl::init(true),
  145. cl::desc("Enable sinkinig and/cmp into branches."));
  146. static cl::opt<bool> DisableStoreExtract(
  147. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  148. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  149. static cl::opt<bool> StressStoreExtract(
  150. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  151. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  152. static cl::opt<bool> DisableExtLdPromotion(
  153. "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  154. cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
  155. "CodeGenPrepare"));
  156. static cl::opt<bool> StressExtLdPromotion(
  157. "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  158. cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
  159. "optimization in CodeGenPrepare"));
  160. static cl::opt<bool> DisablePreheaderProtect(
  161. "disable-preheader-prot", cl::Hidden, cl::init(false),
  162. cl::desc("Disable protection against removing loop preheaders"));
  163. static cl::opt<bool> ProfileGuidedSectionPrefix(
  164. "profile-guided-section-prefix", cl::Hidden, cl::init(true),
  165. cl::desc("Use profile info to add section prefix for hot/cold functions"));
  166. static cl::opt<bool> ProfileUnknownInSpecialSection(
  167. "profile-unknown-in-special-section", cl::Hidden,
  168. cl::desc("In profiling mode like sampleFDO, if a function doesn't have "
  169. "profile, we cannot tell the function is cold for sure because "
  170. "it may be a function newly added without ever being sampled. "
  171. "With the flag enabled, compiler can put such profile unknown "
  172. "functions into a special section, so runtime system can choose "
  173. "to handle it in a different way than .text section, to save "
  174. "RAM for example. "));
  175. static cl::opt<bool> BBSectionsGuidedSectionPrefix(
  176. "bbsections-guided-section-prefix", cl::Hidden, cl::init(true),
  177. cl::desc("Use the basic-block-sections profile to determine the text "
  178. "section prefix for hot functions. Functions with "
  179. "basic-block-sections profile will be placed in `.text.hot` "
  180. "regardless of their FDO profile info. Other functions won't be "
  181. "impacted, i.e., their prefixes will be decided by FDO/sampleFDO "
  182. "profiles."));
  183. static cl::opt<unsigned> FreqRatioToSkipMerge(
  184. "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
  185. cl::desc("Skip merging empty blocks if (frequency of empty block) / "
  186. "(frequency of destination block) is greater than this ratio"));
  187. static cl::opt<bool> ForceSplitStore(
  188. "force-split-store", cl::Hidden, cl::init(false),
  189. cl::desc("Force store splitting no matter what the target query says."));
  190. static cl::opt<bool> EnableTypePromotionMerge(
  191. "cgp-type-promotion-merge", cl::Hidden,
  192. cl::desc("Enable merging of redundant sexts when one is dominating"
  193. " the other."),
  194. cl::init(true));
  195. static cl::opt<bool> DisableComplexAddrModes(
  196. "disable-complex-addr-modes", cl::Hidden, cl::init(false),
  197. cl::desc("Disables combining addressing modes with different parts "
  198. "in optimizeMemoryInst."));
  199. static cl::opt<bool>
  200. AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
  201. cl::desc("Allow creation of Phis in Address sinking."));
  202. static cl::opt<bool> AddrSinkNewSelects(
  203. "addr-sink-new-select", cl::Hidden, cl::init(true),
  204. cl::desc("Allow creation of selects in Address sinking."));
  205. static cl::opt<bool> AddrSinkCombineBaseReg(
  206. "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
  207. cl::desc("Allow combining of BaseReg field in Address sinking."));
  208. static cl::opt<bool> AddrSinkCombineBaseGV(
  209. "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
  210. cl::desc("Allow combining of BaseGV field in Address sinking."));
  211. static cl::opt<bool> AddrSinkCombineBaseOffs(
  212. "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
  213. cl::desc("Allow combining of BaseOffs field in Address sinking."));
  214. static cl::opt<bool> AddrSinkCombineScaledReg(
  215. "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
  216. cl::desc("Allow combining of ScaledReg field in Address sinking."));
  217. static cl::opt<bool>
  218. EnableGEPOffsetSplit("cgp-split-large-offset-gep", cl::Hidden,
  219. cl::init(true),
  220. cl::desc("Enable splitting large offset of GEP."));
  221. static cl::opt<bool> EnableICMP_EQToICMP_ST(
  222. "cgp-icmp-eq2icmp-st", cl::Hidden, cl::init(false),
  223. cl::desc("Enable ICMP_EQ to ICMP_S(L|G)T conversion."));
  224. static cl::opt<bool>
  225. VerifyBFIUpdates("cgp-verify-bfi-updates", cl::Hidden, cl::init(false),
  226. cl::desc("Enable BFI update verification for "
  227. "CodeGenPrepare."));
  228. static cl::opt<bool>
  229. OptimizePhiTypes("cgp-optimize-phi-types", cl::Hidden, cl::init(false),
  230. cl::desc("Enable converting phi types in CodeGenPrepare"));
  231. static cl::opt<unsigned>
  232. HugeFuncThresholdInCGPP("cgpp-huge-func", cl::init(10000), cl::Hidden,
  233. cl::desc("Least BB number of huge function."));
  234. namespace {
  235. enum ExtType {
  236. ZeroExtension, // Zero extension has been seen.
  237. SignExtension, // Sign extension has been seen.
  238. BothExtension // This extension type is used if we saw sext after
  239. // ZeroExtension had been set, or if we saw zext after
  240. // SignExtension had been set. It makes the type
  241. // information of a promoted instruction invalid.
  242. };
  243. enum ModifyDT {
  244. NotModifyDT, // Not Modify any DT.
  245. ModifyBBDT, // Modify the Basic Block Dominator Tree.
  246. ModifyInstDT // Modify the Instruction Dominator in a Basic Block,
  247. // This usually means we move/delete/insert instruction
  248. // in a Basic Block. So we should re-iterate instructions
  249. // in such Basic Block.
  250. };
  251. using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
  252. using TypeIsSExt = PointerIntPair<Type *, 2, ExtType>;
  253. using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
  254. using SExts = SmallVector<Instruction *, 16>;
  255. using ValueToSExts = MapVector<Value *, SExts>;
  256. class TypePromotionTransaction;
  257. class CodeGenPrepare : public FunctionPass {
  258. const TargetMachine *TM = nullptr;
  259. const TargetSubtargetInfo *SubtargetInfo;
  260. const TargetLowering *TLI = nullptr;
  261. const TargetRegisterInfo *TRI;
  262. const TargetTransformInfo *TTI = nullptr;
  263. const BasicBlockSectionsProfileReader *BBSectionsProfileReader = nullptr;
  264. const TargetLibraryInfo *TLInfo;
  265. const LoopInfo *LI;
  266. std::unique_ptr<BlockFrequencyInfo> BFI;
  267. std::unique_ptr<BranchProbabilityInfo> BPI;
  268. ProfileSummaryInfo *PSI;
  269. /// As we scan instructions optimizing them, this is the next instruction
  270. /// to optimize. Transforms that can invalidate this should update it.
  271. BasicBlock::iterator CurInstIterator;
  272. /// Keeps track of non-local addresses that have been sunk into a block.
  273. /// This allows us to avoid inserting duplicate code for blocks with
  274. /// multiple load/stores of the same address. The usage of WeakTrackingVH
  275. /// enables SunkAddrs to be treated as a cache whose entries can be
  276. /// invalidated if a sunken address computation has been erased.
  277. ValueMap<Value *, WeakTrackingVH> SunkAddrs;
  278. /// Keeps track of all instructions inserted for the current function.
  279. SetOfInstrs InsertedInsts;
  280. /// Keeps track of the type of the related instruction before their
  281. /// promotion for the current function.
  282. InstrToOrigTy PromotedInsts;
  283. /// Keep track of instructions removed during promotion.
  284. SetOfInstrs RemovedInsts;
  285. /// Keep track of sext chains based on their initial value.
  286. DenseMap<Value *, Instruction *> SeenChainsForSExt;
  287. /// Keep track of GEPs accessing the same data structures such as structs or
  288. /// arrays that are candidates to be split later because of their large
  289. /// size.
  290. MapVector<AssertingVH<Value>,
  291. SmallVector<std::pair<AssertingVH<GetElementPtrInst>, int64_t>, 32>>
  292. LargeOffsetGEPMap;
  293. /// Keep track of new GEP base after splitting the GEPs having large offset.
  294. SmallSet<AssertingVH<Value>, 2> NewGEPBases;
  295. /// Map serial numbers to Large offset GEPs.
  296. DenseMap<AssertingVH<GetElementPtrInst>, int> LargeOffsetGEPID;
  297. /// Keep track of SExt promoted.
  298. ValueToSExts ValToSExtendedUses;
  299. /// True if the function has the OptSize attribute.
  300. bool OptSize;
  301. /// DataLayout for the Function being processed.
  302. const DataLayout *DL = nullptr;
  303. /// Building the dominator tree can be expensive, so we only build it
  304. /// lazily and update it when required.
  305. std::unique_ptr<DominatorTree> DT;
  306. public:
  307. /// If encounter huge function, we need to limit the build time.
  308. bool IsHugeFunc = false;
  309. /// FreshBBs is like worklist, it collected the updated BBs which need
  310. /// to be optimized again.
  311. /// Note: Consider building time in this pass, when a BB updated, we need
  312. /// to insert such BB into FreshBBs for huge function.
  313. SmallSet<BasicBlock *, 32> FreshBBs;
  314. static char ID; // Pass identification, replacement for typeid
  315. CodeGenPrepare() : FunctionPass(ID) {
  316. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  317. }
  318. bool runOnFunction(Function &F) override;
  319. StringRef getPassName() const override { return "CodeGen Prepare"; }
  320. void getAnalysisUsage(AnalysisUsage &AU) const override {
  321. // FIXME: When we can selectively preserve passes, preserve the domtree.
  322. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  323. AU.addRequired<TargetLibraryInfoWrapperPass>();
  324. AU.addRequired<TargetPassConfig>();
  325. AU.addRequired<TargetTransformInfoWrapperPass>();
  326. AU.addRequired<LoopInfoWrapperPass>();
  327. AU.addUsedIfAvailable<BasicBlockSectionsProfileReader>();
  328. }
  329. private:
  330. template <typename F>
  331. void resetIteratorIfInvalidatedWhileCalling(BasicBlock *BB, F f) {
  332. // Substituting can cause recursive simplifications, which can invalidate
  333. // our iterator. Use a WeakTrackingVH to hold onto it in case this
  334. // happens.
  335. Value *CurValue = &*CurInstIterator;
  336. WeakTrackingVH IterHandle(CurValue);
  337. f();
  338. // If the iterator instruction was recursively deleted, start over at the
  339. // start of the block.
  340. if (IterHandle != CurValue) {
  341. CurInstIterator = BB->begin();
  342. SunkAddrs.clear();
  343. }
  344. }
  345. // Get the DominatorTree, building if necessary.
  346. DominatorTree &getDT(Function &F) {
  347. if (!DT)
  348. DT = std::make_unique<DominatorTree>(F);
  349. return *DT;
  350. }
  351. void removeAllAssertingVHReferences(Value *V);
  352. bool eliminateAssumptions(Function &F);
  353. bool eliminateFallThrough(Function &F);
  354. bool eliminateMostlyEmptyBlocks(Function &F);
  355. BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
  356. bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  357. void eliminateMostlyEmptyBlock(BasicBlock *BB);
  358. bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
  359. bool isPreheader);
  360. bool makeBitReverse(Instruction &I);
  361. bool optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT);
  362. bool optimizeInst(Instruction *I, ModifyDT &ModifiedDT);
  363. bool optimizeMemoryInst(Instruction *MemoryInst, Value *Addr, Type *AccessTy,
  364. unsigned AddrSpace);
  365. bool optimizeGatherScatterInst(Instruction *MemoryInst, Value *Ptr);
  366. bool optimizeInlineAsmInst(CallInst *CS);
  367. bool optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT);
  368. bool optimizeExt(Instruction *&I);
  369. bool optimizeExtUses(Instruction *I);
  370. bool optimizeLoadExt(LoadInst *Load);
  371. bool optimizeShiftInst(BinaryOperator *BO);
  372. bool optimizeFunnelShift(IntrinsicInst *Fsh);
  373. bool optimizeSelectInst(SelectInst *SI);
  374. bool optimizeShuffleVectorInst(ShuffleVectorInst *SVI);
  375. bool optimizeSwitchType(SwitchInst *SI);
  376. bool optimizeSwitchPhiConstants(SwitchInst *SI);
  377. bool optimizeSwitchInst(SwitchInst *SI);
  378. bool optimizeExtractElementInst(Instruction *Inst);
  379. bool dupRetToEnableTailCallOpts(BasicBlock *BB, ModifyDT &ModifiedDT);
  380. bool fixupDbgValue(Instruction *I);
  381. bool placeDbgValues(Function &F);
  382. bool placePseudoProbes(Function &F);
  383. bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
  384. LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
  385. bool tryToPromoteExts(TypePromotionTransaction &TPT,
  386. const SmallVectorImpl<Instruction *> &Exts,
  387. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  388. unsigned CreatedInstsCost = 0);
  389. bool mergeSExts(Function &F);
  390. bool splitLargeGEPOffsets();
  391. bool optimizePhiType(PHINode *Inst, SmallPtrSetImpl<PHINode *> &Visited,
  392. SmallPtrSetImpl<Instruction *> &DeletedInstrs);
  393. bool optimizePhiTypes(Function &F);
  394. bool performAddressTypePromotion(
  395. Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
  396. bool HasPromoted, TypePromotionTransaction &TPT,
  397. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
  398. bool splitBranchCondition(Function &F, ModifyDT &ModifiedDT);
  399. bool simplifyOffsetableRelocate(GCStatepointInst &I);
  400. bool tryToSinkFreeOperands(Instruction *I);
  401. bool replaceMathCmpWithIntrinsic(BinaryOperator *BO, Value *Arg0, Value *Arg1,
  402. CmpInst *Cmp, Intrinsic::ID IID);
  403. bool optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT);
  404. bool combineToUSubWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
  405. bool combineToUAddWithOverflow(CmpInst *Cmp, ModifyDT &ModifiedDT);
  406. void verifyBFIUpdates(Function &F);
  407. };
  408. } // end anonymous namespace
  409. char CodeGenPrepare::ID = 0;
  410. INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
  411. "Optimize for code generation", false, false)
  412. INITIALIZE_PASS_DEPENDENCY(BasicBlockSectionsProfileReader)
  413. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  414. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  415. INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
  416. INITIALIZE_PASS_DEPENDENCY(TargetPassConfig)
  417. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  418. INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE, "Optimize for code generation",
  419. false, false)
  420. FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
  421. bool CodeGenPrepare::runOnFunction(Function &F) {
  422. if (skipFunction(F))
  423. return false;
  424. DL = &F.getParent()->getDataLayout();
  425. bool EverMadeChange = false;
  426. // Clear per function information.
  427. InsertedInsts.clear();
  428. PromotedInsts.clear();
  429. FreshBBs.clear();
  430. TM = &getAnalysis<TargetPassConfig>().getTM<TargetMachine>();
  431. SubtargetInfo = TM->getSubtargetImpl(F);
  432. TLI = SubtargetInfo->getTargetLowering();
  433. TRI = SubtargetInfo->getRegisterInfo();
  434. TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
  435. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  436. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  437. BPI.reset(new BranchProbabilityInfo(F, *LI));
  438. BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
  439. PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  440. BBSectionsProfileReader =
  441. getAnalysisIfAvailable<BasicBlockSectionsProfileReader>();
  442. OptSize = F.hasOptSize();
  443. // Use the basic-block-sections profile to promote hot functions to .text.hot
  444. // if requested.
  445. if (BBSectionsGuidedSectionPrefix && BBSectionsProfileReader &&
  446. BBSectionsProfileReader->isFunctionHot(F.getName())) {
  447. F.setSectionPrefix("hot");
  448. } else if (ProfileGuidedSectionPrefix) {
  449. // The hot attribute overwrites profile count based hotness while profile
  450. // counts based hotness overwrite the cold attribute.
  451. // This is a conservative behabvior.
  452. if (F.hasFnAttribute(Attribute::Hot) ||
  453. PSI->isFunctionHotInCallGraph(&F, *BFI))
  454. F.setSectionPrefix("hot");
  455. // If PSI shows this function is not hot, we will placed the function
  456. // into unlikely section if (1) PSI shows this is a cold function, or
  457. // (2) the function has a attribute of cold.
  458. else if (PSI->isFunctionColdInCallGraph(&F, *BFI) ||
  459. F.hasFnAttribute(Attribute::Cold))
  460. F.setSectionPrefix("unlikely");
  461. else if (ProfileUnknownInSpecialSection && PSI->hasPartialSampleProfile() &&
  462. PSI->isFunctionHotnessUnknown(F))
  463. F.setSectionPrefix("unknown");
  464. }
  465. /// This optimization identifies DIV instructions that can be
  466. /// profitably bypassed and carried out with a shorter, faster divide.
  467. if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI->isSlowDivBypassed()) {
  468. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  469. TLI->getBypassSlowDivWidths();
  470. BasicBlock *BB = &*F.begin();
  471. while (BB != nullptr) {
  472. // bypassSlowDivision may create new BBs, but we don't want to reapply the
  473. // optimization to those blocks.
  474. BasicBlock *Next = BB->getNextNode();
  475. // F.hasOptSize is already checked in the outer if statement.
  476. if (!llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
  477. EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
  478. BB = Next;
  479. }
  480. }
  481. // Get rid of @llvm.assume builtins before attempting to eliminate empty
  482. // blocks, since there might be blocks that only contain @llvm.assume calls
  483. // (plus arguments that we can get rid of).
  484. EverMadeChange |= eliminateAssumptions(F);
  485. // Eliminate blocks that contain only PHI nodes and an
  486. // unconditional branch.
  487. EverMadeChange |= eliminateMostlyEmptyBlocks(F);
  488. ModifyDT ModifiedDT = ModifyDT::NotModifyDT;
  489. if (!DisableBranchOpts)
  490. EverMadeChange |= splitBranchCondition(F, ModifiedDT);
  491. // Split some critical edges where one of the sources is an indirect branch,
  492. // to help generate sane code for PHIs involving such edges.
  493. EverMadeChange |=
  494. SplitIndirectBrCriticalEdges(F, /*IgnoreBlocksWithoutPHI=*/true);
  495. // If we are optimzing huge function, we need to consider the build time.
  496. // Because the basic algorithm's complex is near O(N!).
  497. IsHugeFunc = F.size() > HugeFuncThresholdInCGPP;
  498. bool MadeChange = true;
  499. bool FuncIterated = false;
  500. while (MadeChange) {
  501. MadeChange = false;
  502. DT.reset();
  503. for (BasicBlock &BB : llvm::make_early_inc_range(F)) {
  504. if (FuncIterated && !FreshBBs.contains(&BB))
  505. continue;
  506. ModifyDT ModifiedDTOnIteration = ModifyDT::NotModifyDT;
  507. bool Changed = optimizeBlock(BB, ModifiedDTOnIteration);
  508. MadeChange |= Changed;
  509. if (IsHugeFunc) {
  510. // If the BB is updated, it may still has chance to be optimized.
  511. // This usually happen at sink optimization.
  512. // For example:
  513. //
  514. // bb0:
  515. // %and = and i32 %a, 4
  516. // %cmp = icmp eq i32 %and, 0
  517. //
  518. // If the %cmp sink to other BB, the %and will has chance to sink.
  519. if (Changed)
  520. FreshBBs.insert(&BB);
  521. else if (FuncIterated)
  522. FreshBBs.erase(&BB);
  523. if (ModifiedDTOnIteration == ModifyDT::ModifyBBDT)
  524. DT.reset();
  525. } else {
  526. // For small/normal functions, we restart BB iteration if the dominator
  527. // tree of the Function was changed.
  528. if (ModifiedDTOnIteration != ModifyDT::NotModifyDT)
  529. break;
  530. }
  531. }
  532. // We have iterated all the BB in the (only work for huge) function.
  533. FuncIterated = IsHugeFunc;
  534. if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
  535. MadeChange |= mergeSExts(F);
  536. if (!LargeOffsetGEPMap.empty())
  537. MadeChange |= splitLargeGEPOffsets();
  538. MadeChange |= optimizePhiTypes(F);
  539. if (MadeChange)
  540. eliminateFallThrough(F);
  541. // Really free removed instructions during promotion.
  542. for (Instruction *I : RemovedInsts)
  543. I->deleteValue();
  544. EverMadeChange |= MadeChange;
  545. SeenChainsForSExt.clear();
  546. ValToSExtendedUses.clear();
  547. RemovedInsts.clear();
  548. LargeOffsetGEPMap.clear();
  549. LargeOffsetGEPID.clear();
  550. }
  551. NewGEPBases.clear();
  552. SunkAddrs.clear();
  553. if (!DisableBranchOpts) {
  554. MadeChange = false;
  555. // Use a set vector to get deterministic iteration order. The order the
  556. // blocks are removed may affect whether or not PHI nodes in successors
  557. // are removed.
  558. SmallSetVector<BasicBlock *, 8> WorkList;
  559. for (BasicBlock &BB : F) {
  560. SmallVector<BasicBlock *, 2> Successors(successors(&BB));
  561. MadeChange |= ConstantFoldTerminator(&BB, true);
  562. if (!MadeChange)
  563. continue;
  564. for (BasicBlock *Succ : Successors)
  565. if (pred_empty(Succ))
  566. WorkList.insert(Succ);
  567. }
  568. // Delete the dead blocks and any of their dead successors.
  569. MadeChange |= !WorkList.empty();
  570. while (!WorkList.empty()) {
  571. BasicBlock *BB = WorkList.pop_back_val();
  572. SmallVector<BasicBlock *, 2> Successors(successors(BB));
  573. DeleteDeadBlock(BB);
  574. for (BasicBlock *Succ : Successors)
  575. if (pred_empty(Succ))
  576. WorkList.insert(Succ);
  577. }
  578. // Merge pairs of basic blocks with unconditional branches, connected by
  579. // a single edge.
  580. if (EverMadeChange || MadeChange)
  581. MadeChange |= eliminateFallThrough(F);
  582. EverMadeChange |= MadeChange;
  583. }
  584. if (!DisableGCOpts) {
  585. SmallVector<GCStatepointInst *, 2> Statepoints;
  586. for (BasicBlock &BB : F)
  587. for (Instruction &I : BB)
  588. if (auto *SP = dyn_cast<GCStatepointInst>(&I))
  589. Statepoints.push_back(SP);
  590. for (auto &I : Statepoints)
  591. EverMadeChange |= simplifyOffsetableRelocate(*I);
  592. }
  593. // Do this last to clean up use-before-def scenarios introduced by other
  594. // preparatory transforms.
  595. EverMadeChange |= placeDbgValues(F);
  596. EverMadeChange |= placePseudoProbes(F);
  597. #ifndef NDEBUG
  598. if (VerifyBFIUpdates)
  599. verifyBFIUpdates(F);
  600. #endif
  601. return EverMadeChange;
  602. }
  603. bool CodeGenPrepare::eliminateAssumptions(Function &F) {
  604. bool MadeChange = false;
  605. for (BasicBlock &BB : F) {
  606. CurInstIterator = BB.begin();
  607. while (CurInstIterator != BB.end()) {
  608. Instruction *I = &*(CurInstIterator++);
  609. if (auto *Assume = dyn_cast<AssumeInst>(I)) {
  610. MadeChange = true;
  611. Value *Operand = Assume->getOperand(0);
  612. Assume->eraseFromParent();
  613. resetIteratorIfInvalidatedWhileCalling(&BB, [&]() {
  614. RecursivelyDeleteTriviallyDeadInstructions(Operand, TLInfo, nullptr);
  615. });
  616. }
  617. }
  618. }
  619. return MadeChange;
  620. }
  621. /// An instruction is about to be deleted, so remove all references to it in our
  622. /// GEP-tracking data strcutures.
  623. void CodeGenPrepare::removeAllAssertingVHReferences(Value *V) {
  624. LargeOffsetGEPMap.erase(V);
  625. NewGEPBases.erase(V);
  626. auto GEP = dyn_cast<GetElementPtrInst>(V);
  627. if (!GEP)
  628. return;
  629. LargeOffsetGEPID.erase(GEP);
  630. auto VecI = LargeOffsetGEPMap.find(GEP->getPointerOperand());
  631. if (VecI == LargeOffsetGEPMap.end())
  632. return;
  633. auto &GEPVector = VecI->second;
  634. llvm::erase_if(GEPVector, [=](auto &Elt) { return Elt.first == GEP; });
  635. if (GEPVector.empty())
  636. LargeOffsetGEPMap.erase(VecI);
  637. }
  638. // Verify BFI has been updated correctly by recomputing BFI and comparing them.
  639. void LLVM_ATTRIBUTE_UNUSED CodeGenPrepare::verifyBFIUpdates(Function &F) {
  640. DominatorTree NewDT(F);
  641. LoopInfo NewLI(NewDT);
  642. BranchProbabilityInfo NewBPI(F, NewLI, TLInfo);
  643. BlockFrequencyInfo NewBFI(F, NewBPI, NewLI);
  644. NewBFI.verifyMatch(*BFI);
  645. }
  646. /// Merge basic blocks which are connected by a single edge, where one of the
  647. /// basic blocks has a single successor pointing to the other basic block,
  648. /// which has a single predecessor.
  649. bool CodeGenPrepare::eliminateFallThrough(Function &F) {
  650. bool Changed = false;
  651. // Scan all of the blocks in the function, except for the entry block.
  652. // Use a temporary array to avoid iterator being invalidated when
  653. // deleting blocks.
  654. SmallVector<WeakTrackingVH, 16> Blocks;
  655. for (auto &Block : llvm::drop_begin(F))
  656. Blocks.push_back(&Block);
  657. SmallSet<WeakTrackingVH, 16> Preds;
  658. for (auto &Block : Blocks) {
  659. auto *BB = cast_or_null<BasicBlock>(Block);
  660. if (!BB)
  661. continue;
  662. // If the destination block has a single pred, then this is a trivial
  663. // edge, just collapse it.
  664. BasicBlock *SinglePred = BB->getSinglePredecessor();
  665. // Don't merge if BB's address is taken.
  666. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken())
  667. continue;
  668. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  669. if (Term && !Term->isConditional()) {
  670. Changed = true;
  671. LLVM_DEBUG(dbgs() << "To merge:\n" << *BB << "\n\n\n");
  672. // Merge BB into SinglePred and delete it.
  673. MergeBlockIntoPredecessor(BB);
  674. Preds.insert(SinglePred);
  675. if (IsHugeFunc) {
  676. // Update FreshBBs to optimize the merged BB.
  677. FreshBBs.insert(SinglePred);
  678. FreshBBs.erase(BB);
  679. }
  680. }
  681. }
  682. // (Repeatedly) merging blocks into their predecessors can create redundant
  683. // debug intrinsics.
  684. for (const auto &Pred : Preds)
  685. if (auto *BB = cast_or_null<BasicBlock>(Pred))
  686. RemoveRedundantDbgInstrs(BB);
  687. return Changed;
  688. }
  689. /// Find a destination block from BB if BB is mergeable empty block.
  690. BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
  691. // If this block doesn't end with an uncond branch, ignore it.
  692. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  693. if (!BI || !BI->isUnconditional())
  694. return nullptr;
  695. // If the instruction before the branch (skipping debug info) isn't a phi
  696. // node, then other stuff is happening here.
  697. BasicBlock::iterator BBI = BI->getIterator();
  698. if (BBI != BB->begin()) {
  699. --BBI;
  700. while (isa<DbgInfoIntrinsic>(BBI)) {
  701. if (BBI == BB->begin())
  702. break;
  703. --BBI;
  704. }
  705. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  706. return nullptr;
  707. }
  708. // Do not break infinite loops.
  709. BasicBlock *DestBB = BI->getSuccessor(0);
  710. if (DestBB == BB)
  711. return nullptr;
  712. if (!canMergeBlocks(BB, DestBB))
  713. DestBB = nullptr;
  714. return DestBB;
  715. }
  716. /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
  717. /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
  718. /// edges in ways that are non-optimal for isel. Start by eliminating these
  719. /// blocks so we can split them the way we want them.
  720. bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
  721. SmallPtrSet<BasicBlock *, 16> Preheaders;
  722. SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
  723. while (!LoopList.empty()) {
  724. Loop *L = LoopList.pop_back_val();
  725. llvm::append_range(LoopList, *L);
  726. if (BasicBlock *Preheader = L->getLoopPreheader())
  727. Preheaders.insert(Preheader);
  728. }
  729. bool MadeChange = false;
  730. // Copy blocks into a temporary array to avoid iterator invalidation issues
  731. // as we remove them.
  732. // Note that this intentionally skips the entry block.
  733. SmallVector<WeakTrackingVH, 16> Blocks;
  734. for (auto &Block : llvm::drop_begin(F))
  735. Blocks.push_back(&Block);
  736. for (auto &Block : Blocks) {
  737. BasicBlock *BB = cast_or_null<BasicBlock>(Block);
  738. if (!BB)
  739. continue;
  740. BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
  741. if (!DestBB ||
  742. !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
  743. continue;
  744. eliminateMostlyEmptyBlock(BB);
  745. MadeChange = true;
  746. }
  747. return MadeChange;
  748. }
  749. bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
  750. BasicBlock *DestBB,
  751. bool isPreheader) {
  752. // Do not delete loop preheaders if doing so would create a critical edge.
  753. // Loop preheaders can be good locations to spill registers. If the
  754. // preheader is deleted and we create a critical edge, registers may be
  755. // spilled in the loop body instead.
  756. if (!DisablePreheaderProtect && isPreheader &&
  757. !(BB->getSinglePredecessor() &&
  758. BB->getSinglePredecessor()->getSingleSuccessor()))
  759. return false;
  760. // Skip merging if the block's successor is also a successor to any callbr
  761. // that leads to this block.
  762. // FIXME: Is this really needed? Is this a correctness issue?
  763. for (BasicBlock *Pred : predecessors(BB)) {
  764. if (auto *CBI = dyn_cast<CallBrInst>((Pred)->getTerminator()))
  765. for (unsigned i = 0, e = CBI->getNumSuccessors(); i != e; ++i)
  766. if (DestBB == CBI->getSuccessor(i))
  767. return false;
  768. }
  769. // Try to skip merging if the unique predecessor of BB is terminated by a
  770. // switch or indirect branch instruction, and BB is used as an incoming block
  771. // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
  772. // add COPY instructions in the predecessor of BB instead of BB (if it is not
  773. // merged). Note that the critical edge created by merging such blocks wont be
  774. // split in MachineSink because the jump table is not analyzable. By keeping
  775. // such empty block (BB), ISel will place COPY instructions in BB, not in the
  776. // predecessor of BB.
  777. BasicBlock *Pred = BB->getUniquePredecessor();
  778. if (!Pred || !(isa<SwitchInst>(Pred->getTerminator()) ||
  779. isa<IndirectBrInst>(Pred->getTerminator())))
  780. return true;
  781. if (BB->getTerminator() != BB->getFirstNonPHIOrDbg())
  782. return true;
  783. // We use a simple cost heuristic which determine skipping merging is
  784. // profitable if the cost of skipping merging is less than the cost of
  785. // merging : Cost(skipping merging) < Cost(merging BB), where the
  786. // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
  787. // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
  788. // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
  789. // Freq(Pred) / Freq(BB) > 2.
  790. // Note that if there are multiple empty blocks sharing the same incoming
  791. // value for the PHIs in the DestBB, we consider them together. In such
  792. // case, Cost(merging BB) will be the sum of their frequencies.
  793. if (!isa<PHINode>(DestBB->begin()))
  794. return true;
  795. SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
  796. // Find all other incoming blocks from which incoming values of all PHIs in
  797. // DestBB are the same as the ones from BB.
  798. for (BasicBlock *DestBBPred : predecessors(DestBB)) {
  799. if (DestBBPred == BB)
  800. continue;
  801. if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
  802. return DestPN.getIncomingValueForBlock(BB) ==
  803. DestPN.getIncomingValueForBlock(DestBBPred);
  804. }))
  805. SameIncomingValueBBs.insert(DestBBPred);
  806. }
  807. // See if all BB's incoming values are same as the value from Pred. In this
  808. // case, no reason to skip merging because COPYs are expected to be place in
  809. // Pred already.
  810. if (SameIncomingValueBBs.count(Pred))
  811. return true;
  812. BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
  813. BlockFrequency BBFreq = BFI->getBlockFreq(BB);
  814. for (auto *SameValueBB : SameIncomingValueBBs)
  815. if (SameValueBB->getUniquePredecessor() == Pred &&
  816. DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
  817. BBFreq += BFI->getBlockFreq(SameValueBB);
  818. return PredFreq.getFrequency() <=
  819. BBFreq.getFrequency() * FreqRatioToSkipMerge;
  820. }
  821. /// Return true if we can merge BB into DestBB if there is a single
  822. /// unconditional branch between them, and BB contains no other non-phi
  823. /// instructions.
  824. bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
  825. const BasicBlock *DestBB) const {
  826. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  827. // the successor. If there are more complex condition (e.g. preheaders),
  828. // don't mess around with them.
  829. for (const PHINode &PN : BB->phis()) {
  830. for (const User *U : PN.users()) {
  831. const Instruction *UI = cast<Instruction>(U);
  832. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  833. return false;
  834. // If User is inside DestBB block and it is a PHINode then check
  835. // incoming value. If incoming value is not from BB then this is
  836. // a complex condition (e.g. preheaders) we want to avoid here.
  837. if (UI->getParent() == DestBB) {
  838. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  839. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  840. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  841. if (Insn && Insn->getParent() == BB &&
  842. Insn->getParent() != UPN->getIncomingBlock(I))
  843. return false;
  844. }
  845. }
  846. }
  847. }
  848. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  849. // and DestBB may have conflicting incoming values for the block. If so, we
  850. // can't merge the block.
  851. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  852. if (!DestBBPN)
  853. return true; // no conflict.
  854. // Collect the preds of BB.
  855. SmallPtrSet<const BasicBlock *, 16> BBPreds;
  856. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  857. // It is faster to get preds from a PHI than with pred_iterator.
  858. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  859. BBPreds.insert(BBPN->getIncomingBlock(i));
  860. } else {
  861. BBPreds.insert(pred_begin(BB), pred_end(BB));
  862. }
  863. // Walk the preds of DestBB.
  864. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  865. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  866. if (BBPreds.count(Pred)) { // Common predecessor?
  867. for (const PHINode &PN : DestBB->phis()) {
  868. const Value *V1 = PN.getIncomingValueForBlock(Pred);
  869. const Value *V2 = PN.getIncomingValueForBlock(BB);
  870. // If V2 is a phi node in BB, look up what the mapped value will be.
  871. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  872. if (V2PN->getParent() == BB)
  873. V2 = V2PN->getIncomingValueForBlock(Pred);
  874. // If there is a conflict, bail out.
  875. if (V1 != V2)
  876. return false;
  877. }
  878. }
  879. }
  880. return true;
  881. }
  882. /// Replace all old uses with new ones, and push the updated BBs into FreshBBs.
  883. static void replaceAllUsesWith(Value *Old, Value *New,
  884. SmallSet<BasicBlock *, 32> &FreshBBs,
  885. bool IsHuge) {
  886. auto *OldI = dyn_cast<Instruction>(Old);
  887. if (OldI) {
  888. for (Value::user_iterator UI = OldI->user_begin(), E = OldI->user_end();
  889. UI != E; ++UI) {
  890. Instruction *User = cast<Instruction>(*UI);
  891. if (IsHuge)
  892. FreshBBs.insert(User->getParent());
  893. }
  894. }
  895. Old->replaceAllUsesWith(New);
  896. }
  897. /// Eliminate a basic block that has only phi's and an unconditional branch in
  898. /// it.
  899. void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
  900. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  901. BasicBlock *DestBB = BI->getSuccessor(0);
  902. LLVM_DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n"
  903. << *BB << *DestBB);
  904. // If the destination block has a single pred, then this is a trivial edge,
  905. // just collapse it.
  906. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  907. if (SinglePred != DestBB) {
  908. assert(SinglePred == BB &&
  909. "Single predecessor not the same as predecessor");
  910. // Merge DestBB into SinglePred/BB and delete it.
  911. MergeBlockIntoPredecessor(DestBB);
  912. // Note: BB(=SinglePred) will not be deleted on this path.
  913. // DestBB(=its single successor) is the one that was deleted.
  914. LLVM_DEBUG(dbgs() << "AFTER:\n" << *SinglePred << "\n\n\n");
  915. if (IsHugeFunc) {
  916. // Update FreshBBs to optimize the merged BB.
  917. FreshBBs.insert(SinglePred);
  918. FreshBBs.erase(DestBB);
  919. }
  920. return;
  921. }
  922. }
  923. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  924. // to handle the new incoming edges it is about to have.
  925. for (PHINode &PN : DestBB->phis()) {
  926. // Remove the incoming value for BB, and remember it.
  927. Value *InVal = PN.removeIncomingValue(BB, false);
  928. // Two options: either the InVal is a phi node defined in BB or it is some
  929. // value that dominates BB.
  930. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  931. if (InValPhi && InValPhi->getParent() == BB) {
  932. // Add all of the input values of the input PHI as inputs of this phi.
  933. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  934. PN.addIncoming(InValPhi->getIncomingValue(i),
  935. InValPhi->getIncomingBlock(i));
  936. } else {
  937. // Otherwise, add one instance of the dominating value for each edge that
  938. // we will be adding.
  939. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  940. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  941. PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
  942. } else {
  943. for (BasicBlock *Pred : predecessors(BB))
  944. PN.addIncoming(InVal, Pred);
  945. }
  946. }
  947. }
  948. // The PHIs are now updated, change everything that refers to BB to use
  949. // DestBB and remove BB.
  950. BB->replaceAllUsesWith(DestBB);
  951. BB->eraseFromParent();
  952. ++NumBlocksElim;
  953. LLVM_DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  954. }
  955. // Computes a map of base pointer relocation instructions to corresponding
  956. // derived pointer relocation instructions given a vector of all relocate calls
  957. static void computeBaseDerivedRelocateMap(
  958. const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
  959. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
  960. &RelocateInstMap) {
  961. // Collect information in two maps: one primarily for locating the base object
  962. // while filling the second map; the second map is the final structure holding
  963. // a mapping between Base and corresponding Derived relocate calls
  964. DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
  965. for (auto *ThisRelocate : AllRelocateCalls) {
  966. auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
  967. ThisRelocate->getDerivedPtrIndex());
  968. RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
  969. }
  970. for (auto &Item : RelocateIdxMap) {
  971. std::pair<unsigned, unsigned> Key = Item.first;
  972. if (Key.first == Key.second)
  973. // Base relocation: nothing to insert
  974. continue;
  975. GCRelocateInst *I = Item.second;
  976. auto BaseKey = std::make_pair(Key.first, Key.first);
  977. // We're iterating over RelocateIdxMap so we cannot modify it.
  978. auto MaybeBase = RelocateIdxMap.find(BaseKey);
  979. if (MaybeBase == RelocateIdxMap.end())
  980. // TODO: We might want to insert a new base object relocate and gep off
  981. // that, if there are enough derived object relocates.
  982. continue;
  983. RelocateInstMap[MaybeBase->second].push_back(I);
  984. }
  985. }
  986. // Accepts a GEP and extracts the operands into a vector provided they're all
  987. // small integer constants
  988. static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
  989. SmallVectorImpl<Value *> &OffsetV) {
  990. for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
  991. // Only accept small constant integer operands
  992. auto *Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
  993. if (!Op || Op->getZExtValue() > 20)
  994. return false;
  995. }
  996. for (unsigned i = 1; i < GEP->getNumOperands(); i++)
  997. OffsetV.push_back(GEP->getOperand(i));
  998. return true;
  999. }
  1000. // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
  1001. // replace, computes a replacement, and affects it.
  1002. static bool
  1003. simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
  1004. const SmallVectorImpl<GCRelocateInst *> &Targets) {
  1005. bool MadeChange = false;
  1006. // We must ensure the relocation of derived pointer is defined after
  1007. // relocation of base pointer. If we find a relocation corresponding to base
  1008. // defined earlier than relocation of base then we move relocation of base
  1009. // right before found relocation. We consider only relocation in the same
  1010. // basic block as relocation of base. Relocations from other basic block will
  1011. // be skipped by optimization and we do not care about them.
  1012. for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
  1013. &*R != RelocatedBase; ++R)
  1014. if (auto *RI = dyn_cast<GCRelocateInst>(R))
  1015. if (RI->getStatepoint() == RelocatedBase->getStatepoint())
  1016. if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
  1017. RelocatedBase->moveBefore(RI);
  1018. break;
  1019. }
  1020. for (GCRelocateInst *ToReplace : Targets) {
  1021. assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
  1022. "Not relocating a derived object of the original base object");
  1023. if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
  1024. // A duplicate relocate call. TODO: coalesce duplicates.
  1025. continue;
  1026. }
  1027. if (RelocatedBase->getParent() != ToReplace->getParent()) {
  1028. // Base and derived relocates are in different basic blocks.
  1029. // In this case transform is only valid when base dominates derived
  1030. // relocate. However it would be too expensive to check dominance
  1031. // for each such relocate, so we skip the whole transformation.
  1032. continue;
  1033. }
  1034. Value *Base = ToReplace->getBasePtr();
  1035. auto *Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
  1036. if (!Derived || Derived->getPointerOperand() != Base)
  1037. continue;
  1038. SmallVector<Value *, 2> OffsetV;
  1039. if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
  1040. continue;
  1041. // Create a Builder and replace the target callsite with a gep
  1042. assert(RelocatedBase->getNextNode() &&
  1043. "Should always have one since it's not a terminator");
  1044. // Insert after RelocatedBase
  1045. IRBuilder<> Builder(RelocatedBase->getNextNode());
  1046. Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
  1047. // If gc_relocate does not match the actual type, cast it to the right type.
  1048. // In theory, there must be a bitcast after gc_relocate if the type does not
  1049. // match, and we should reuse it to get the derived pointer. But it could be
  1050. // cases like this:
  1051. // bb1:
  1052. // ...
  1053. // %g1 = call coldcc i8 addrspace(1)*
  1054. // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
  1055. //
  1056. // bb2:
  1057. // ...
  1058. // %g2 = call coldcc i8 addrspace(1)*
  1059. // @llvm.experimental.gc.relocate.p1i8(...) br label %merge
  1060. //
  1061. // merge:
  1062. // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
  1063. // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
  1064. //
  1065. // In this case, we can not find the bitcast any more. So we insert a new
  1066. // bitcast no matter there is already one or not. In this way, we can handle
  1067. // all cases, and the extra bitcast should be optimized away in later
  1068. // passes.
  1069. Value *ActualRelocatedBase = RelocatedBase;
  1070. if (RelocatedBase->getType() != Base->getType()) {
  1071. ActualRelocatedBase =
  1072. Builder.CreateBitCast(RelocatedBase, Base->getType());
  1073. }
  1074. Value *Replacement =
  1075. Builder.CreateGEP(Derived->getSourceElementType(), ActualRelocatedBase,
  1076. ArrayRef(OffsetV));
  1077. Replacement->takeName(ToReplace);
  1078. // If the newly generated derived pointer's type does not match the original
  1079. // derived pointer's type, cast the new derived pointer to match it. Same
  1080. // reasoning as above.
  1081. Value *ActualReplacement = Replacement;
  1082. if (Replacement->getType() != ToReplace->getType()) {
  1083. ActualReplacement =
  1084. Builder.CreateBitCast(Replacement, ToReplace->getType());
  1085. }
  1086. ToReplace->replaceAllUsesWith(ActualReplacement);
  1087. ToReplace->eraseFromParent();
  1088. MadeChange = true;
  1089. }
  1090. return MadeChange;
  1091. }
  1092. // Turns this:
  1093. //
  1094. // %base = ...
  1095. // %ptr = gep %base + 15
  1096. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  1097. // %base' = relocate(%tok, i32 4, i32 4)
  1098. // %ptr' = relocate(%tok, i32 4, i32 5)
  1099. // %val = load %ptr'
  1100. //
  1101. // into this:
  1102. //
  1103. // %base = ...
  1104. // %ptr = gep %base + 15
  1105. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  1106. // %base' = gc.relocate(%tok, i32 4, i32 4)
  1107. // %ptr' = gep %base' + 15
  1108. // %val = load %ptr'
  1109. bool CodeGenPrepare::simplifyOffsetableRelocate(GCStatepointInst &I) {
  1110. bool MadeChange = false;
  1111. SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
  1112. for (auto *U : I.users())
  1113. if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
  1114. // Collect all the relocate calls associated with a statepoint
  1115. AllRelocateCalls.push_back(Relocate);
  1116. // We need at least one base pointer relocation + one derived pointer
  1117. // relocation to mangle
  1118. if (AllRelocateCalls.size() < 2)
  1119. return false;
  1120. // RelocateInstMap is a mapping from the base relocate instruction to the
  1121. // corresponding derived relocate instructions
  1122. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
  1123. computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
  1124. if (RelocateInstMap.empty())
  1125. return false;
  1126. for (auto &Item : RelocateInstMap)
  1127. // Item.first is the RelocatedBase to offset against
  1128. // Item.second is the vector of Targets to replace
  1129. MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
  1130. return MadeChange;
  1131. }
  1132. /// Sink the specified cast instruction into its user blocks.
  1133. static bool SinkCast(CastInst *CI) {
  1134. BasicBlock *DefBB = CI->getParent();
  1135. /// InsertedCasts - Only insert a cast in each block once.
  1136. DenseMap<BasicBlock *, CastInst *> InsertedCasts;
  1137. bool MadeChange = false;
  1138. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  1139. UI != E;) {
  1140. Use &TheUse = UI.getUse();
  1141. Instruction *User = cast<Instruction>(*UI);
  1142. // Figure out which BB this cast is used in. For PHI's this is the
  1143. // appropriate predecessor block.
  1144. BasicBlock *UserBB = User->getParent();
  1145. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  1146. UserBB = PN->getIncomingBlock(TheUse);
  1147. }
  1148. // Preincrement use iterator so we don't invalidate it.
  1149. ++UI;
  1150. // The first insertion point of a block containing an EH pad is after the
  1151. // pad. If the pad is the user, we cannot sink the cast past the pad.
  1152. if (User->isEHPad())
  1153. continue;
  1154. // If the block selected to receive the cast is an EH pad that does not
  1155. // allow non-PHI instructions before the terminator, we can't sink the
  1156. // cast.
  1157. if (UserBB->getTerminator()->isEHPad())
  1158. continue;
  1159. // If this user is in the same block as the cast, don't change the cast.
  1160. if (UserBB == DefBB)
  1161. continue;
  1162. // If we have already inserted a cast into this block, use it.
  1163. CastInst *&InsertedCast = InsertedCasts[UserBB];
  1164. if (!InsertedCast) {
  1165. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1166. assert(InsertPt != UserBB->end());
  1167. InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
  1168. CI->getType(), "", &*InsertPt);
  1169. InsertedCast->setDebugLoc(CI->getDebugLoc());
  1170. }
  1171. // Replace a use of the cast with a use of the new cast.
  1172. TheUse = InsertedCast;
  1173. MadeChange = true;
  1174. ++NumCastUses;
  1175. }
  1176. // If we removed all uses, nuke the cast.
  1177. if (CI->use_empty()) {
  1178. salvageDebugInfo(*CI);
  1179. CI->eraseFromParent();
  1180. MadeChange = true;
  1181. }
  1182. return MadeChange;
  1183. }
  1184. /// If the specified cast instruction is a noop copy (e.g. it's casting from
  1185. /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
  1186. /// reduce the number of virtual registers that must be created and coalesced.
  1187. ///
  1188. /// Return true if any changes are made.
  1189. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
  1190. const DataLayout &DL) {
  1191. // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
  1192. // than sinking only nop casts, but is helpful on some platforms.
  1193. if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
  1194. if (!TLI.isFreeAddrSpaceCast(ASC->getSrcAddressSpace(),
  1195. ASC->getDestAddressSpace()))
  1196. return false;
  1197. }
  1198. // If this is a noop copy,
  1199. EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  1200. EVT DstVT = TLI.getValueType(DL, CI->getType());
  1201. // This is an fp<->int conversion?
  1202. if (SrcVT.isInteger() != DstVT.isInteger())
  1203. return false;
  1204. // If this is an extension, it will be a zero or sign extension, which
  1205. // isn't a noop.
  1206. if (SrcVT.bitsLT(DstVT))
  1207. return false;
  1208. // If these values will be promoted, find out what they will be promoted
  1209. // to. This helps us consider truncates on PPC as noop copies when they
  1210. // are.
  1211. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  1212. TargetLowering::TypePromoteInteger)
  1213. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  1214. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  1215. TargetLowering::TypePromoteInteger)
  1216. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  1217. // If, after promotion, these are the same types, this is a noop copy.
  1218. if (SrcVT != DstVT)
  1219. return false;
  1220. return SinkCast(CI);
  1221. }
  1222. // Match a simple increment by constant operation. Note that if a sub is
  1223. // matched, the step is negated (as if the step had been canonicalized to
  1224. // an add, even though we leave the instruction alone.)
  1225. bool matchIncrement(const Instruction *IVInc, Instruction *&LHS,
  1226. Constant *&Step) {
  1227. if (match(IVInc, m_Add(m_Instruction(LHS), m_Constant(Step))) ||
  1228. match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::uadd_with_overflow>(
  1229. m_Instruction(LHS), m_Constant(Step)))))
  1230. return true;
  1231. if (match(IVInc, m_Sub(m_Instruction(LHS), m_Constant(Step))) ||
  1232. match(IVInc, m_ExtractValue<0>(m_Intrinsic<Intrinsic::usub_with_overflow>(
  1233. m_Instruction(LHS), m_Constant(Step))))) {
  1234. Step = ConstantExpr::getNeg(Step);
  1235. return true;
  1236. }
  1237. return false;
  1238. }
  1239. /// If given \p PN is an inductive variable with value IVInc coming from the
  1240. /// backedge, and on each iteration it gets increased by Step, return pair
  1241. /// <IVInc, Step>. Otherwise, return std::nullopt.
  1242. static std::optional<std::pair<Instruction *, Constant *>>
  1243. getIVIncrement(const PHINode *PN, const LoopInfo *LI) {
  1244. const Loop *L = LI->getLoopFor(PN->getParent());
  1245. if (!L || L->getHeader() != PN->getParent() || !L->getLoopLatch())
  1246. return std::nullopt;
  1247. auto *IVInc =
  1248. dyn_cast<Instruction>(PN->getIncomingValueForBlock(L->getLoopLatch()));
  1249. if (!IVInc || LI->getLoopFor(IVInc->getParent()) != L)
  1250. return std::nullopt;
  1251. Instruction *LHS = nullptr;
  1252. Constant *Step = nullptr;
  1253. if (matchIncrement(IVInc, LHS, Step) && LHS == PN)
  1254. return std::make_pair(IVInc, Step);
  1255. return std::nullopt;
  1256. }
  1257. static bool isIVIncrement(const Value *V, const LoopInfo *LI) {
  1258. auto *I = dyn_cast<Instruction>(V);
  1259. if (!I)
  1260. return false;
  1261. Instruction *LHS = nullptr;
  1262. Constant *Step = nullptr;
  1263. if (!matchIncrement(I, LHS, Step))
  1264. return false;
  1265. if (auto *PN = dyn_cast<PHINode>(LHS))
  1266. if (auto IVInc = getIVIncrement(PN, LI))
  1267. return IVInc->first == I;
  1268. return false;
  1269. }
  1270. bool CodeGenPrepare::replaceMathCmpWithIntrinsic(BinaryOperator *BO,
  1271. Value *Arg0, Value *Arg1,
  1272. CmpInst *Cmp,
  1273. Intrinsic::ID IID) {
  1274. auto IsReplacableIVIncrement = [this, &Cmp](BinaryOperator *BO) {
  1275. if (!isIVIncrement(BO, LI))
  1276. return false;
  1277. const Loop *L = LI->getLoopFor(BO->getParent());
  1278. assert(L && "L should not be null after isIVIncrement()");
  1279. // Do not risk on moving increment into a child loop.
  1280. if (LI->getLoopFor(Cmp->getParent()) != L)
  1281. return false;
  1282. // Finally, we need to ensure that the insert point will dominate all
  1283. // existing uses of the increment.
  1284. auto &DT = getDT(*BO->getParent()->getParent());
  1285. if (DT.dominates(Cmp->getParent(), BO->getParent()))
  1286. // If we're moving up the dom tree, all uses are trivially dominated.
  1287. // (This is the common case for code produced by LSR.)
  1288. return true;
  1289. // Otherwise, special case the single use in the phi recurrence.
  1290. return BO->hasOneUse() && DT.dominates(Cmp->getParent(), L->getLoopLatch());
  1291. };
  1292. if (BO->getParent() != Cmp->getParent() && !IsReplacableIVIncrement(BO)) {
  1293. // We used to use a dominator tree here to allow multi-block optimization.
  1294. // But that was problematic because:
  1295. // 1. It could cause a perf regression by hoisting the math op into the
  1296. // critical path.
  1297. // 2. It could cause a perf regression by creating a value that was live
  1298. // across multiple blocks and increasing register pressure.
  1299. // 3. Use of a dominator tree could cause large compile-time regression.
  1300. // This is because we recompute the DT on every change in the main CGP
  1301. // run-loop. The recomputing is probably unnecessary in many cases, so if
  1302. // that was fixed, using a DT here would be ok.
  1303. //
  1304. // There is one important particular case we still want to handle: if BO is
  1305. // the IV increment. Important properties that make it profitable:
  1306. // - We can speculate IV increment anywhere in the loop (as long as the
  1307. // indvar Phi is its only user);
  1308. // - Upon computing Cmp, we effectively compute something equivalent to the
  1309. // IV increment (despite it loops differently in the IR). So moving it up
  1310. // to the cmp point does not really increase register pressure.
  1311. return false;
  1312. }
  1313. // We allow matching the canonical IR (add X, C) back to (usubo X, -C).
  1314. if (BO->getOpcode() == Instruction::Add &&
  1315. IID == Intrinsic::usub_with_overflow) {
  1316. assert(isa<Constant>(Arg1) && "Unexpected input for usubo");
  1317. Arg1 = ConstantExpr::getNeg(cast<Constant>(Arg1));
  1318. }
  1319. // Insert at the first instruction of the pair.
  1320. Instruction *InsertPt = nullptr;
  1321. for (Instruction &Iter : *Cmp->getParent()) {
  1322. // If BO is an XOR, it is not guaranteed that it comes after both inputs to
  1323. // the overflow intrinsic are defined.
  1324. if ((BO->getOpcode() != Instruction::Xor && &Iter == BO) || &Iter == Cmp) {
  1325. InsertPt = &Iter;
  1326. break;
  1327. }
  1328. }
  1329. assert(InsertPt != nullptr && "Parent block did not contain cmp or binop");
  1330. IRBuilder<> Builder(InsertPt);
  1331. Value *MathOV = Builder.CreateBinaryIntrinsic(IID, Arg0, Arg1);
  1332. if (BO->getOpcode() != Instruction::Xor) {
  1333. Value *Math = Builder.CreateExtractValue(MathOV, 0, "math");
  1334. replaceAllUsesWith(BO, Math, FreshBBs, IsHugeFunc);
  1335. } else
  1336. assert(BO->hasOneUse() &&
  1337. "Patterns with XOr should use the BO only in the compare");
  1338. Value *OV = Builder.CreateExtractValue(MathOV, 1, "ov");
  1339. replaceAllUsesWith(Cmp, OV, FreshBBs, IsHugeFunc);
  1340. Cmp->eraseFromParent();
  1341. BO->eraseFromParent();
  1342. return true;
  1343. }
  1344. /// Match special-case patterns that check for unsigned add overflow.
  1345. static bool matchUAddWithOverflowConstantEdgeCases(CmpInst *Cmp,
  1346. BinaryOperator *&Add) {
  1347. // Add = add A, 1; Cmp = icmp eq A,-1 (overflow if A is max val)
  1348. // Add = add A,-1; Cmp = icmp ne A, 0 (overflow if A is non-zero)
  1349. Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
  1350. // We are not expecting non-canonical/degenerate code. Just bail out.
  1351. if (isa<Constant>(A))
  1352. return false;
  1353. ICmpInst::Predicate Pred = Cmp->getPredicate();
  1354. if (Pred == ICmpInst::ICMP_EQ && match(B, m_AllOnes()))
  1355. B = ConstantInt::get(B->getType(), 1);
  1356. else if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt()))
  1357. B = ConstantInt::get(B->getType(), -1);
  1358. else
  1359. return false;
  1360. // Check the users of the variable operand of the compare looking for an add
  1361. // with the adjusted constant.
  1362. for (User *U : A->users()) {
  1363. if (match(U, m_Add(m_Specific(A), m_Specific(B)))) {
  1364. Add = cast<BinaryOperator>(U);
  1365. return true;
  1366. }
  1367. }
  1368. return false;
  1369. }
  1370. /// Try to combine the compare into a call to the llvm.uadd.with.overflow
  1371. /// intrinsic. Return true if any changes were made.
  1372. bool CodeGenPrepare::combineToUAddWithOverflow(CmpInst *Cmp,
  1373. ModifyDT &ModifiedDT) {
  1374. Value *A, *B;
  1375. BinaryOperator *Add;
  1376. if (!match(Cmp, m_UAddWithOverflow(m_Value(A), m_Value(B), m_BinOp(Add)))) {
  1377. if (!matchUAddWithOverflowConstantEdgeCases(Cmp, Add))
  1378. return false;
  1379. // Set A and B in case we match matchUAddWithOverflowConstantEdgeCases.
  1380. A = Add->getOperand(0);
  1381. B = Add->getOperand(1);
  1382. }
  1383. if (!TLI->shouldFormOverflowOp(ISD::UADDO,
  1384. TLI->getValueType(*DL, Add->getType()),
  1385. Add->hasNUsesOrMore(2)))
  1386. return false;
  1387. // We don't want to move around uses of condition values this late, so we
  1388. // check if it is legal to create the call to the intrinsic in the basic
  1389. // block containing the icmp.
  1390. if (Add->getParent() != Cmp->getParent() && !Add->hasOneUse())
  1391. return false;
  1392. if (!replaceMathCmpWithIntrinsic(Add, A, B, Cmp,
  1393. Intrinsic::uadd_with_overflow))
  1394. return false;
  1395. // Reset callers - do not crash by iterating over a dead instruction.
  1396. ModifiedDT = ModifyDT::ModifyInstDT;
  1397. return true;
  1398. }
  1399. bool CodeGenPrepare::combineToUSubWithOverflow(CmpInst *Cmp,
  1400. ModifyDT &ModifiedDT) {
  1401. // We are not expecting non-canonical/degenerate code. Just bail out.
  1402. Value *A = Cmp->getOperand(0), *B = Cmp->getOperand(1);
  1403. if (isa<Constant>(A) && isa<Constant>(B))
  1404. return false;
  1405. // Convert (A u> B) to (A u< B) to simplify pattern matching.
  1406. ICmpInst::Predicate Pred = Cmp->getPredicate();
  1407. if (Pred == ICmpInst::ICMP_UGT) {
  1408. std::swap(A, B);
  1409. Pred = ICmpInst::ICMP_ULT;
  1410. }
  1411. // Convert special-case: (A == 0) is the same as (A u< 1).
  1412. if (Pred == ICmpInst::ICMP_EQ && match(B, m_ZeroInt())) {
  1413. B = ConstantInt::get(B->getType(), 1);
  1414. Pred = ICmpInst::ICMP_ULT;
  1415. }
  1416. // Convert special-case: (A != 0) is the same as (0 u< A).
  1417. if (Pred == ICmpInst::ICMP_NE && match(B, m_ZeroInt())) {
  1418. std::swap(A, B);
  1419. Pred = ICmpInst::ICMP_ULT;
  1420. }
  1421. if (Pred != ICmpInst::ICMP_ULT)
  1422. return false;
  1423. // Walk the users of a variable operand of a compare looking for a subtract or
  1424. // add with that same operand. Also match the 2nd operand of the compare to
  1425. // the add/sub, but that may be a negated constant operand of an add.
  1426. Value *CmpVariableOperand = isa<Constant>(A) ? B : A;
  1427. BinaryOperator *Sub = nullptr;
  1428. for (User *U : CmpVariableOperand->users()) {
  1429. // A - B, A u< B --> usubo(A, B)
  1430. if (match(U, m_Sub(m_Specific(A), m_Specific(B)))) {
  1431. Sub = cast<BinaryOperator>(U);
  1432. break;
  1433. }
  1434. // A + (-C), A u< C (canonicalized form of (sub A, C))
  1435. const APInt *CmpC, *AddC;
  1436. if (match(U, m_Add(m_Specific(A), m_APInt(AddC))) &&
  1437. match(B, m_APInt(CmpC)) && *AddC == -(*CmpC)) {
  1438. Sub = cast<BinaryOperator>(U);
  1439. break;
  1440. }
  1441. }
  1442. if (!Sub)
  1443. return false;
  1444. if (!TLI->shouldFormOverflowOp(ISD::USUBO,
  1445. TLI->getValueType(*DL, Sub->getType()),
  1446. Sub->hasNUsesOrMore(2)))
  1447. return false;
  1448. if (!replaceMathCmpWithIntrinsic(Sub, Sub->getOperand(0), Sub->getOperand(1),
  1449. Cmp, Intrinsic::usub_with_overflow))
  1450. return false;
  1451. // Reset callers - do not crash by iterating over a dead instruction.
  1452. ModifiedDT = ModifyDT::ModifyInstDT;
  1453. return true;
  1454. }
  1455. /// Sink the given CmpInst into user blocks to reduce the number of virtual
  1456. /// registers that must be created and coalesced. This is a clear win except on
  1457. /// targets with multiple condition code registers (PowerPC), where it might
  1458. /// lose; some adjustment may be wanted there.
  1459. ///
  1460. /// Return true if any changes are made.
  1461. static bool sinkCmpExpression(CmpInst *Cmp, const TargetLowering &TLI) {
  1462. if (TLI.hasMultipleConditionRegisters())
  1463. return false;
  1464. // Avoid sinking soft-FP comparisons, since this can move them into a loop.
  1465. if (TLI.useSoftFloat() && isa<FCmpInst>(Cmp))
  1466. return false;
  1467. // Only insert a cmp in each block once.
  1468. DenseMap<BasicBlock *, CmpInst *> InsertedCmps;
  1469. bool MadeChange = false;
  1470. for (Value::user_iterator UI = Cmp->user_begin(), E = Cmp->user_end();
  1471. UI != E;) {
  1472. Use &TheUse = UI.getUse();
  1473. Instruction *User = cast<Instruction>(*UI);
  1474. // Preincrement use iterator so we don't invalidate it.
  1475. ++UI;
  1476. // Don't bother for PHI nodes.
  1477. if (isa<PHINode>(User))
  1478. continue;
  1479. // Figure out which BB this cmp is used in.
  1480. BasicBlock *UserBB = User->getParent();
  1481. BasicBlock *DefBB = Cmp->getParent();
  1482. // If this user is in the same block as the cmp, don't change the cmp.
  1483. if (UserBB == DefBB)
  1484. continue;
  1485. // If we have already inserted a cmp into this block, use it.
  1486. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  1487. if (!InsertedCmp) {
  1488. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1489. assert(InsertPt != UserBB->end());
  1490. InsertedCmp = CmpInst::Create(Cmp->getOpcode(), Cmp->getPredicate(),
  1491. Cmp->getOperand(0), Cmp->getOperand(1), "",
  1492. &*InsertPt);
  1493. // Propagate the debug info.
  1494. InsertedCmp->setDebugLoc(Cmp->getDebugLoc());
  1495. }
  1496. // Replace a use of the cmp with a use of the new cmp.
  1497. TheUse = InsertedCmp;
  1498. MadeChange = true;
  1499. ++NumCmpUses;
  1500. }
  1501. // If we removed all uses, nuke the cmp.
  1502. if (Cmp->use_empty()) {
  1503. Cmp->eraseFromParent();
  1504. MadeChange = true;
  1505. }
  1506. return MadeChange;
  1507. }
  1508. /// For pattern like:
  1509. ///
  1510. /// DomCond = icmp sgt/slt CmpOp0, CmpOp1 (might not be in DomBB)
  1511. /// ...
  1512. /// DomBB:
  1513. /// ...
  1514. /// br DomCond, TrueBB, CmpBB
  1515. /// CmpBB: (with DomBB being the single predecessor)
  1516. /// ...
  1517. /// Cmp = icmp eq CmpOp0, CmpOp1
  1518. /// ...
  1519. ///
  1520. /// It would use two comparison on targets that lowering of icmp sgt/slt is
  1521. /// different from lowering of icmp eq (PowerPC). This function try to convert
  1522. /// 'Cmp = icmp eq CmpOp0, CmpOp1' to ' Cmp = icmp slt/sgt CmpOp0, CmpOp1'.
  1523. /// After that, DomCond and Cmp can use the same comparison so reduce one
  1524. /// comparison.
  1525. ///
  1526. /// Return true if any changes are made.
  1527. static bool foldICmpWithDominatingICmp(CmpInst *Cmp,
  1528. const TargetLowering &TLI) {
  1529. if (!EnableICMP_EQToICMP_ST && TLI.isEqualityCmpFoldedWithSignedCmp())
  1530. return false;
  1531. ICmpInst::Predicate Pred = Cmp->getPredicate();
  1532. if (Pred != ICmpInst::ICMP_EQ)
  1533. return false;
  1534. // If icmp eq has users other than BranchInst and SelectInst, converting it to
  1535. // icmp slt/sgt would introduce more redundant LLVM IR.
  1536. for (User *U : Cmp->users()) {
  1537. if (isa<BranchInst>(U))
  1538. continue;
  1539. if (isa<SelectInst>(U) && cast<SelectInst>(U)->getCondition() == Cmp)
  1540. continue;
  1541. return false;
  1542. }
  1543. // This is a cheap/incomplete check for dominance - just match a single
  1544. // predecessor with a conditional branch.
  1545. BasicBlock *CmpBB = Cmp->getParent();
  1546. BasicBlock *DomBB = CmpBB->getSinglePredecessor();
  1547. if (!DomBB)
  1548. return false;
  1549. // We want to ensure that the only way control gets to the comparison of
  1550. // interest is that a less/greater than comparison on the same operands is
  1551. // false.
  1552. Value *DomCond;
  1553. BasicBlock *TrueBB, *FalseBB;
  1554. if (!match(DomBB->getTerminator(), m_Br(m_Value(DomCond), TrueBB, FalseBB)))
  1555. return false;
  1556. if (CmpBB != FalseBB)
  1557. return false;
  1558. Value *CmpOp0 = Cmp->getOperand(0), *CmpOp1 = Cmp->getOperand(1);
  1559. ICmpInst::Predicate DomPred;
  1560. if (!match(DomCond, m_ICmp(DomPred, m_Specific(CmpOp0), m_Specific(CmpOp1))))
  1561. return false;
  1562. if (DomPred != ICmpInst::ICMP_SGT && DomPred != ICmpInst::ICMP_SLT)
  1563. return false;
  1564. // Convert the equality comparison to the opposite of the dominating
  1565. // comparison and swap the direction for all branch/select users.
  1566. // We have conceptually converted:
  1567. // Res = (a < b) ? <LT_RES> : (a == b) ? <EQ_RES> : <GT_RES>;
  1568. // to
  1569. // Res = (a < b) ? <LT_RES> : (a > b) ? <GT_RES> : <EQ_RES>;
  1570. // And similarly for branches.
  1571. for (User *U : Cmp->users()) {
  1572. if (auto *BI = dyn_cast<BranchInst>(U)) {
  1573. assert(BI->isConditional() && "Must be conditional");
  1574. BI->swapSuccessors();
  1575. continue;
  1576. }
  1577. if (auto *SI = dyn_cast<SelectInst>(U)) {
  1578. // Swap operands
  1579. SI->swapValues();
  1580. SI->swapProfMetadata();
  1581. continue;
  1582. }
  1583. llvm_unreachable("Must be a branch or a select");
  1584. }
  1585. Cmp->setPredicate(CmpInst::getSwappedPredicate(DomPred));
  1586. return true;
  1587. }
  1588. bool CodeGenPrepare::optimizeCmp(CmpInst *Cmp, ModifyDT &ModifiedDT) {
  1589. if (sinkCmpExpression(Cmp, *TLI))
  1590. return true;
  1591. if (combineToUAddWithOverflow(Cmp, ModifiedDT))
  1592. return true;
  1593. if (combineToUSubWithOverflow(Cmp, ModifiedDT))
  1594. return true;
  1595. if (foldICmpWithDominatingICmp(Cmp, *TLI))
  1596. return true;
  1597. return false;
  1598. }
  1599. /// Duplicate and sink the given 'and' instruction into user blocks where it is
  1600. /// used in a compare to allow isel to generate better code for targets where
  1601. /// this operation can be combined.
  1602. ///
  1603. /// Return true if any changes are made.
  1604. static bool sinkAndCmp0Expression(Instruction *AndI, const TargetLowering &TLI,
  1605. SetOfInstrs &InsertedInsts) {
  1606. // Double-check that we're not trying to optimize an instruction that was
  1607. // already optimized by some other part of this pass.
  1608. assert(!InsertedInsts.count(AndI) &&
  1609. "Attempting to optimize already optimized and instruction");
  1610. (void)InsertedInsts;
  1611. // Nothing to do for single use in same basic block.
  1612. if (AndI->hasOneUse() &&
  1613. AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
  1614. return false;
  1615. // Try to avoid cases where sinking/duplicating is likely to increase register
  1616. // pressure.
  1617. if (!isa<ConstantInt>(AndI->getOperand(0)) &&
  1618. !isa<ConstantInt>(AndI->getOperand(1)) &&
  1619. AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
  1620. return false;
  1621. for (auto *U : AndI->users()) {
  1622. Instruction *User = cast<Instruction>(U);
  1623. // Only sink 'and' feeding icmp with 0.
  1624. if (!isa<ICmpInst>(User))
  1625. return false;
  1626. auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
  1627. if (!CmpC || !CmpC->isZero())
  1628. return false;
  1629. }
  1630. if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
  1631. return false;
  1632. LLVM_DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
  1633. LLVM_DEBUG(AndI->getParent()->dump());
  1634. // Push the 'and' into the same block as the icmp 0. There should only be
  1635. // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
  1636. // others, so we don't need to keep track of which BBs we insert into.
  1637. for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
  1638. UI != E;) {
  1639. Use &TheUse = UI.getUse();
  1640. Instruction *User = cast<Instruction>(*UI);
  1641. // Preincrement use iterator so we don't invalidate it.
  1642. ++UI;
  1643. LLVM_DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
  1644. // Keep the 'and' in the same place if the use is already in the same block.
  1645. Instruction *InsertPt =
  1646. User->getParent() == AndI->getParent() ? AndI : User;
  1647. Instruction *InsertedAnd =
  1648. BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
  1649. AndI->getOperand(1), "", InsertPt);
  1650. // Propagate the debug info.
  1651. InsertedAnd->setDebugLoc(AndI->getDebugLoc());
  1652. // Replace a use of the 'and' with a use of the new 'and'.
  1653. TheUse = InsertedAnd;
  1654. ++NumAndUses;
  1655. LLVM_DEBUG(User->getParent()->dump());
  1656. }
  1657. // We removed all uses, nuke the and.
  1658. AndI->eraseFromParent();
  1659. return true;
  1660. }
  1661. /// Check if the candidates could be combined with a shift instruction, which
  1662. /// includes:
  1663. /// 1. Truncate instruction
  1664. /// 2. And instruction and the imm is a mask of the low bits:
  1665. /// imm & (imm+1) == 0
  1666. static bool isExtractBitsCandidateUse(Instruction *User) {
  1667. if (!isa<TruncInst>(User)) {
  1668. if (User->getOpcode() != Instruction::And ||
  1669. !isa<ConstantInt>(User->getOperand(1)))
  1670. return false;
  1671. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  1672. if ((Cimm & (Cimm + 1)).getBoolValue())
  1673. return false;
  1674. }
  1675. return true;
  1676. }
  1677. /// Sink both shift and truncate instruction to the use of truncate's BB.
  1678. static bool
  1679. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  1680. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  1681. const TargetLowering &TLI, const DataLayout &DL) {
  1682. BasicBlock *UserBB = User->getParent();
  1683. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  1684. auto *TruncI = cast<TruncInst>(User);
  1685. bool MadeChange = false;
  1686. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  1687. TruncE = TruncI->user_end();
  1688. TruncUI != TruncE;) {
  1689. Use &TruncTheUse = TruncUI.getUse();
  1690. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  1691. // Preincrement use iterator so we don't invalidate it.
  1692. ++TruncUI;
  1693. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  1694. if (!ISDOpcode)
  1695. continue;
  1696. // If the use is actually a legal node, there will not be an
  1697. // implicit truncate.
  1698. // FIXME: always querying the result type is just an
  1699. // approximation; some nodes' legality is determined by the
  1700. // operand or other means. There's no good way to find out though.
  1701. if (TLI.isOperationLegalOrCustom(
  1702. ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
  1703. continue;
  1704. // Don't bother for PHI nodes.
  1705. if (isa<PHINode>(TruncUser))
  1706. continue;
  1707. BasicBlock *TruncUserBB = TruncUser->getParent();
  1708. if (UserBB == TruncUserBB)
  1709. continue;
  1710. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  1711. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  1712. if (!InsertedShift && !InsertedTrunc) {
  1713. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  1714. assert(InsertPt != TruncUserBB->end());
  1715. // Sink the shift
  1716. if (ShiftI->getOpcode() == Instruction::AShr)
  1717. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1718. "", &*InsertPt);
  1719. else
  1720. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1721. "", &*InsertPt);
  1722. InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
  1723. // Sink the trunc
  1724. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  1725. TruncInsertPt++;
  1726. assert(TruncInsertPt != TruncUserBB->end());
  1727. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  1728. TruncI->getType(), "", &*TruncInsertPt);
  1729. InsertedTrunc->setDebugLoc(TruncI->getDebugLoc());
  1730. MadeChange = true;
  1731. TruncTheUse = InsertedTrunc;
  1732. }
  1733. }
  1734. return MadeChange;
  1735. }
  1736. /// Sink the shift *right* instruction into user blocks if the uses could
  1737. /// potentially be combined with this shift instruction and generate BitExtract
  1738. /// instruction. It will only be applied if the architecture supports BitExtract
  1739. /// instruction. Here is an example:
  1740. /// BB1:
  1741. /// %x.extract.shift = lshr i64 %arg1, 32
  1742. /// BB2:
  1743. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  1744. /// ==>
  1745. ///
  1746. /// BB2:
  1747. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  1748. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  1749. ///
  1750. /// CodeGen will recognize the pattern in BB2 and generate BitExtract
  1751. /// instruction.
  1752. /// Return true if any changes are made.
  1753. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  1754. const TargetLowering &TLI,
  1755. const DataLayout &DL) {
  1756. BasicBlock *DefBB = ShiftI->getParent();
  1757. /// Only insert instructions in each block once.
  1758. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  1759. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
  1760. bool MadeChange = false;
  1761. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  1762. UI != E;) {
  1763. Use &TheUse = UI.getUse();
  1764. Instruction *User = cast<Instruction>(*UI);
  1765. // Preincrement use iterator so we don't invalidate it.
  1766. ++UI;
  1767. // Don't bother for PHI nodes.
  1768. if (isa<PHINode>(User))
  1769. continue;
  1770. if (!isExtractBitsCandidateUse(User))
  1771. continue;
  1772. BasicBlock *UserBB = User->getParent();
  1773. if (UserBB == DefBB) {
  1774. // If the shift and truncate instruction are in the same BB. The use of
  1775. // the truncate(TruncUse) may still introduce another truncate if not
  1776. // legal. In this case, we would like to sink both shift and truncate
  1777. // instruction to the BB of TruncUse.
  1778. // for example:
  1779. // BB1:
  1780. // i64 shift.result = lshr i64 opnd, imm
  1781. // trunc.result = trunc shift.result to i16
  1782. //
  1783. // BB2:
  1784. // ----> We will have an implicit truncate here if the architecture does
  1785. // not have i16 compare.
  1786. // cmp i16 trunc.result, opnd2
  1787. //
  1788. if (isa<TruncInst>(User) &&
  1789. shiftIsLegal
  1790. // If the type of the truncate is legal, no truncate will be
  1791. // introduced in other basic blocks.
  1792. && (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
  1793. MadeChange =
  1794. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
  1795. continue;
  1796. }
  1797. // If we have already inserted a shift into this block, use it.
  1798. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  1799. if (!InsertedShift) {
  1800. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1801. assert(InsertPt != UserBB->end());
  1802. if (ShiftI->getOpcode() == Instruction::AShr)
  1803. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1804. "", &*InsertPt);
  1805. else
  1806. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1807. "", &*InsertPt);
  1808. InsertedShift->setDebugLoc(ShiftI->getDebugLoc());
  1809. MadeChange = true;
  1810. }
  1811. // Replace a use of the shift with a use of the new shift.
  1812. TheUse = InsertedShift;
  1813. }
  1814. // If we removed all uses, or there are none, nuke the shift.
  1815. if (ShiftI->use_empty()) {
  1816. salvageDebugInfo(*ShiftI);
  1817. ShiftI->eraseFromParent();
  1818. MadeChange = true;
  1819. }
  1820. return MadeChange;
  1821. }
  1822. /// If counting leading or trailing zeros is an expensive operation and a zero
  1823. /// input is defined, add a check for zero to avoid calling the intrinsic.
  1824. ///
  1825. /// We want to transform:
  1826. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
  1827. ///
  1828. /// into:
  1829. /// entry:
  1830. /// %cmpz = icmp eq i64 %A, 0
  1831. /// br i1 %cmpz, label %cond.end, label %cond.false
  1832. /// cond.false:
  1833. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
  1834. /// br label %cond.end
  1835. /// cond.end:
  1836. /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
  1837. ///
  1838. /// If the transform is performed, return true and set ModifiedDT to true.
  1839. static bool despeculateCountZeros(IntrinsicInst *CountZeros,
  1840. const TargetLowering *TLI,
  1841. const DataLayout *DL, ModifyDT &ModifiedDT,
  1842. SmallSet<BasicBlock *, 32> &FreshBBs,
  1843. bool IsHugeFunc) {
  1844. // If a zero input is undefined, it doesn't make sense to despeculate that.
  1845. if (match(CountZeros->getOperand(1), m_One()))
  1846. return false;
  1847. // If it's cheap to speculate, there's nothing to do.
  1848. Type *Ty = CountZeros->getType();
  1849. auto IntrinsicID = CountZeros->getIntrinsicID();
  1850. if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz(Ty)) ||
  1851. (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz(Ty)))
  1852. return false;
  1853. // Only handle legal scalar cases. Anything else requires too much work.
  1854. unsigned SizeInBits = Ty->getScalarSizeInBits();
  1855. if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
  1856. return false;
  1857. // Bail if the value is never zero.
  1858. Use &Op = CountZeros->getOperandUse(0);
  1859. if (isKnownNonZero(Op, *DL))
  1860. return false;
  1861. // The intrinsic will be sunk behind a compare against zero and branch.
  1862. BasicBlock *StartBlock = CountZeros->getParent();
  1863. BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
  1864. if (IsHugeFunc)
  1865. FreshBBs.insert(CallBlock);
  1866. // Create another block after the count zero intrinsic. A PHI will be added
  1867. // in this block to select the result of the intrinsic or the bit-width
  1868. // constant if the input to the intrinsic is zero.
  1869. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
  1870. BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
  1871. if (IsHugeFunc)
  1872. FreshBBs.insert(EndBlock);
  1873. // Set up a builder to create a compare, conditional branch, and PHI.
  1874. IRBuilder<> Builder(CountZeros->getContext());
  1875. Builder.SetInsertPoint(StartBlock->getTerminator());
  1876. Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
  1877. // Replace the unconditional branch that was created by the first split with
  1878. // a compare against zero and a conditional branch.
  1879. Value *Zero = Constant::getNullValue(Ty);
  1880. // Avoid introducing branch on poison. This also replaces the ctz operand.
  1881. if (!isGuaranteedNotToBeUndefOrPoison(Op))
  1882. Op = Builder.CreateFreeze(Op, Op->getName() + ".fr");
  1883. Value *Cmp = Builder.CreateICmpEQ(Op, Zero, "cmpz");
  1884. Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
  1885. StartBlock->getTerminator()->eraseFromParent();
  1886. // Create a PHI in the end block to select either the output of the intrinsic
  1887. // or the bit width of the operand.
  1888. Builder.SetInsertPoint(&EndBlock->front());
  1889. PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
  1890. replaceAllUsesWith(CountZeros, PN, FreshBBs, IsHugeFunc);
  1891. Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
  1892. PN->addIncoming(BitWidth, StartBlock);
  1893. PN->addIncoming(CountZeros, CallBlock);
  1894. // We are explicitly handling the zero case, so we can set the intrinsic's
  1895. // undefined zero argument to 'true'. This will also prevent reprocessing the
  1896. // intrinsic; we only despeculate when a zero input is defined.
  1897. CountZeros->setArgOperand(1, Builder.getTrue());
  1898. ModifiedDT = ModifyDT::ModifyBBDT;
  1899. return true;
  1900. }
  1901. bool CodeGenPrepare::optimizeCallInst(CallInst *CI, ModifyDT &ModifiedDT) {
  1902. BasicBlock *BB = CI->getParent();
  1903. // Lower inline assembly if we can.
  1904. // If we found an inline asm expession, and if the target knows how to
  1905. // lower it to normal LLVM code, do so now.
  1906. if (CI->isInlineAsm()) {
  1907. if (TLI->ExpandInlineAsm(CI)) {
  1908. // Avoid invalidating the iterator.
  1909. CurInstIterator = BB->begin();
  1910. // Avoid processing instructions out of order, which could cause
  1911. // reuse before a value is defined.
  1912. SunkAddrs.clear();
  1913. return true;
  1914. }
  1915. // Sink address computing for memory operands into the block.
  1916. if (optimizeInlineAsmInst(CI))
  1917. return true;
  1918. }
  1919. // Align the pointer arguments to this call if the target thinks it's a good
  1920. // idea
  1921. unsigned MinSize;
  1922. Align PrefAlign;
  1923. if (TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
  1924. for (auto &Arg : CI->args()) {
  1925. // We want to align both objects whose address is used directly and
  1926. // objects whose address is used in casts and GEPs, though it only makes
  1927. // sense for GEPs if the offset is a multiple of the desired alignment and
  1928. // if size - offset meets the size threshold.
  1929. if (!Arg->getType()->isPointerTy())
  1930. continue;
  1931. APInt Offset(DL->getIndexSizeInBits(
  1932. cast<PointerType>(Arg->getType())->getAddressSpace()),
  1933. 0);
  1934. Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
  1935. uint64_t Offset2 = Offset.getLimitedValue();
  1936. if (!isAligned(PrefAlign, Offset2))
  1937. continue;
  1938. AllocaInst *AI;
  1939. if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlign() < PrefAlign &&
  1940. DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
  1941. AI->setAlignment(PrefAlign);
  1942. // Global variables can only be aligned if they are defined in this
  1943. // object (i.e. they are uniquely initialized in this object), and
  1944. // over-aligning global variables that have an explicit section is
  1945. // forbidden.
  1946. GlobalVariable *GV;
  1947. if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
  1948. GV->getPointerAlignment(*DL) < PrefAlign &&
  1949. DL->getTypeAllocSize(GV->getValueType()) >= MinSize + Offset2)
  1950. GV->setAlignment(PrefAlign);
  1951. }
  1952. }
  1953. // If this is a memcpy (or similar) then we may be able to improve the
  1954. // alignment.
  1955. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
  1956. Align DestAlign = getKnownAlignment(MI->getDest(), *DL);
  1957. MaybeAlign MIDestAlign = MI->getDestAlign();
  1958. if (!MIDestAlign || DestAlign > *MIDestAlign)
  1959. MI->setDestAlignment(DestAlign);
  1960. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
  1961. MaybeAlign MTISrcAlign = MTI->getSourceAlign();
  1962. Align SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
  1963. if (!MTISrcAlign || SrcAlign > *MTISrcAlign)
  1964. MTI->setSourceAlignment(SrcAlign);
  1965. }
  1966. }
  1967. // If we have a cold call site, try to sink addressing computation into the
  1968. // cold block. This interacts with our handling for loads and stores to
  1969. // ensure that we can fold all uses of a potential addressing computation
  1970. // into their uses. TODO: generalize this to work over profiling data
  1971. if (CI->hasFnAttr(Attribute::Cold) && !OptSize &&
  1972. !llvm::shouldOptimizeForSize(BB, PSI, BFI.get()))
  1973. for (auto &Arg : CI->args()) {
  1974. if (!Arg->getType()->isPointerTy())
  1975. continue;
  1976. unsigned AS = Arg->getType()->getPointerAddressSpace();
  1977. return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
  1978. }
  1979. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  1980. if (II) {
  1981. switch (II->getIntrinsicID()) {
  1982. default:
  1983. break;
  1984. case Intrinsic::assume:
  1985. llvm_unreachable("llvm.assume should have been removed already");
  1986. case Intrinsic::experimental_widenable_condition: {
  1987. // Give up on future widening oppurtunties so that we can fold away dead
  1988. // paths and merge blocks before going into block-local instruction
  1989. // selection.
  1990. if (II->use_empty()) {
  1991. II->eraseFromParent();
  1992. return true;
  1993. }
  1994. Constant *RetVal = ConstantInt::getTrue(II->getContext());
  1995. resetIteratorIfInvalidatedWhileCalling(BB, [&]() {
  1996. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1997. });
  1998. return true;
  1999. }
  2000. case Intrinsic::objectsize:
  2001. llvm_unreachable("llvm.objectsize.* should have been lowered already");
  2002. case Intrinsic::is_constant:
  2003. llvm_unreachable("llvm.is.constant.* should have been lowered already");
  2004. case Intrinsic::aarch64_stlxr:
  2005. case Intrinsic::aarch64_stxr: {
  2006. ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
  2007. if (!ExtVal || !ExtVal->hasOneUse() ||
  2008. ExtVal->getParent() == CI->getParent())
  2009. return false;
  2010. // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
  2011. ExtVal->moveBefore(CI);
  2012. // Mark this instruction as "inserted by CGP", so that other
  2013. // optimizations don't touch it.
  2014. InsertedInsts.insert(ExtVal);
  2015. return true;
  2016. }
  2017. case Intrinsic::launder_invariant_group:
  2018. case Intrinsic::strip_invariant_group: {
  2019. Value *ArgVal = II->getArgOperand(0);
  2020. auto it = LargeOffsetGEPMap.find(II);
  2021. if (it != LargeOffsetGEPMap.end()) {
  2022. // Merge entries in LargeOffsetGEPMap to reflect the RAUW.
  2023. // Make sure not to have to deal with iterator invalidation
  2024. // after possibly adding ArgVal to LargeOffsetGEPMap.
  2025. auto GEPs = std::move(it->second);
  2026. LargeOffsetGEPMap[ArgVal].append(GEPs.begin(), GEPs.end());
  2027. LargeOffsetGEPMap.erase(II);
  2028. }
  2029. replaceAllUsesWith(II, ArgVal, FreshBBs, IsHugeFunc);
  2030. II->eraseFromParent();
  2031. return true;
  2032. }
  2033. case Intrinsic::cttz:
  2034. case Intrinsic::ctlz:
  2035. // If counting zeros is expensive, try to avoid it.
  2036. return despeculateCountZeros(II, TLI, DL, ModifiedDT, FreshBBs,
  2037. IsHugeFunc);
  2038. case Intrinsic::fshl:
  2039. case Intrinsic::fshr:
  2040. return optimizeFunnelShift(II);
  2041. case Intrinsic::dbg_assign:
  2042. case Intrinsic::dbg_value:
  2043. return fixupDbgValue(II);
  2044. case Intrinsic::vscale: {
  2045. // If datalayout has no special restrictions on vector data layout,
  2046. // replace `llvm.vscale` by an equivalent constant expression
  2047. // to benefit from cheap constant propagation.
  2048. Type *ScalableVectorTy =
  2049. VectorType::get(Type::getInt8Ty(II->getContext()), 1, true);
  2050. if (DL->getTypeAllocSize(ScalableVectorTy).getKnownMinValue() == 8) {
  2051. auto *Null = Constant::getNullValue(ScalableVectorTy->getPointerTo());
  2052. auto *One = ConstantInt::getSigned(II->getType(), 1);
  2053. auto *CGep =
  2054. ConstantExpr::getGetElementPtr(ScalableVectorTy, Null, One);
  2055. replaceAllUsesWith(II, ConstantExpr::getPtrToInt(CGep, II->getType()),
  2056. FreshBBs, IsHugeFunc);
  2057. II->eraseFromParent();
  2058. return true;
  2059. }
  2060. break;
  2061. }
  2062. case Intrinsic::masked_gather:
  2063. return optimizeGatherScatterInst(II, II->getArgOperand(0));
  2064. case Intrinsic::masked_scatter:
  2065. return optimizeGatherScatterInst(II, II->getArgOperand(1));
  2066. }
  2067. SmallVector<Value *, 2> PtrOps;
  2068. Type *AccessTy;
  2069. if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
  2070. while (!PtrOps.empty()) {
  2071. Value *PtrVal = PtrOps.pop_back_val();
  2072. unsigned AS = PtrVal->getType()->getPointerAddressSpace();
  2073. if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
  2074. return true;
  2075. }
  2076. }
  2077. // From here on out we're working with named functions.
  2078. if (!CI->getCalledFunction())
  2079. return false;
  2080. // Lower all default uses of _chk calls. This is very similar
  2081. // to what InstCombineCalls does, but here we are only lowering calls
  2082. // to fortified library functions (e.g. __memcpy_chk) that have the default
  2083. // "don't know" as the objectsize. Anything else should be left alone.
  2084. FortifiedLibCallSimplifier Simplifier(TLInfo, true);
  2085. IRBuilder<> Builder(CI);
  2086. if (Value *V = Simplifier.optimizeCall(CI, Builder)) {
  2087. replaceAllUsesWith(CI, V, FreshBBs, IsHugeFunc);
  2088. CI->eraseFromParent();
  2089. return true;
  2090. }
  2091. return false;
  2092. }
  2093. /// Look for opportunities to duplicate return instructions to the predecessor
  2094. /// to enable tail call optimizations. The case it is currently looking for is:
  2095. /// @code
  2096. /// bb0:
  2097. /// %tmp0 = tail call i32 @f0()
  2098. /// br label %return
  2099. /// bb1:
  2100. /// %tmp1 = tail call i32 @f1()
  2101. /// br label %return
  2102. /// bb2:
  2103. /// %tmp2 = tail call i32 @f2()
  2104. /// br label %return
  2105. /// return:
  2106. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  2107. /// ret i32 %retval
  2108. /// @endcode
  2109. ///
  2110. /// =>
  2111. ///
  2112. /// @code
  2113. /// bb0:
  2114. /// %tmp0 = tail call i32 @f0()
  2115. /// ret i32 %tmp0
  2116. /// bb1:
  2117. /// %tmp1 = tail call i32 @f1()
  2118. /// ret i32 %tmp1
  2119. /// bb2:
  2120. /// %tmp2 = tail call i32 @f2()
  2121. /// ret i32 %tmp2
  2122. /// @endcode
  2123. bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB,
  2124. ModifyDT &ModifiedDT) {
  2125. if (!BB->getTerminator())
  2126. return false;
  2127. ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
  2128. if (!RetI)
  2129. return false;
  2130. PHINode *PN = nullptr;
  2131. ExtractValueInst *EVI = nullptr;
  2132. BitCastInst *BCI = nullptr;
  2133. Value *V = RetI->getReturnValue();
  2134. if (V) {
  2135. BCI = dyn_cast<BitCastInst>(V);
  2136. if (BCI)
  2137. V = BCI->getOperand(0);
  2138. EVI = dyn_cast<ExtractValueInst>(V);
  2139. if (EVI) {
  2140. V = EVI->getOperand(0);
  2141. if (!llvm::all_of(EVI->indices(), [](unsigned idx) { return idx == 0; }))
  2142. return false;
  2143. }
  2144. PN = dyn_cast<PHINode>(V);
  2145. if (!PN)
  2146. return false;
  2147. }
  2148. if (PN && PN->getParent() != BB)
  2149. return false;
  2150. auto isLifetimeEndOrBitCastFor = [](const Instruction *Inst) {
  2151. const BitCastInst *BC = dyn_cast<BitCastInst>(Inst);
  2152. if (BC && BC->hasOneUse())
  2153. Inst = BC->user_back();
  2154. if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
  2155. return II->getIntrinsicID() == Intrinsic::lifetime_end;
  2156. return false;
  2157. };
  2158. // Make sure there are no instructions between the first instruction
  2159. // and return.
  2160. const Instruction *BI = BB->getFirstNonPHI();
  2161. // Skip over debug and the bitcast.
  2162. while (isa<DbgInfoIntrinsic>(BI) || BI == BCI || BI == EVI ||
  2163. isa<PseudoProbeInst>(BI) || isLifetimeEndOrBitCastFor(BI))
  2164. BI = BI->getNextNode();
  2165. if (BI != RetI)
  2166. return false;
  2167. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  2168. /// call.
  2169. const Function *F = BB->getParent();
  2170. SmallVector<BasicBlock *, 4> TailCallBBs;
  2171. if (PN) {
  2172. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  2173. // Look through bitcasts.
  2174. Value *IncomingVal = PN->getIncomingValue(I)->stripPointerCasts();
  2175. CallInst *CI = dyn_cast<CallInst>(IncomingVal);
  2176. BasicBlock *PredBB = PN->getIncomingBlock(I);
  2177. // Make sure the phi value is indeed produced by the tail call.
  2178. if (CI && CI->hasOneUse() && CI->getParent() == PredBB &&
  2179. TLI->mayBeEmittedAsTailCall(CI) &&
  2180. attributesPermitTailCall(F, CI, RetI, *TLI))
  2181. TailCallBBs.push_back(PredBB);
  2182. }
  2183. } else {
  2184. SmallPtrSet<BasicBlock *, 4> VisitedBBs;
  2185. for (BasicBlock *Pred : predecessors(BB)) {
  2186. if (!VisitedBBs.insert(Pred).second)
  2187. continue;
  2188. if (Instruction *I = Pred->rbegin()->getPrevNonDebugInstruction(true)) {
  2189. CallInst *CI = dyn_cast<CallInst>(I);
  2190. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
  2191. attributesPermitTailCall(F, CI, RetI, *TLI))
  2192. TailCallBBs.push_back(Pred);
  2193. }
  2194. }
  2195. }
  2196. bool Changed = false;
  2197. for (auto const &TailCallBB : TailCallBBs) {
  2198. // Make sure the call instruction is followed by an unconditional branch to
  2199. // the return block.
  2200. BranchInst *BI = dyn_cast<BranchInst>(TailCallBB->getTerminator());
  2201. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  2202. continue;
  2203. // Duplicate the return into TailCallBB.
  2204. (void)FoldReturnIntoUncondBranch(RetI, BB, TailCallBB);
  2205. assert(!VerifyBFIUpdates ||
  2206. BFI->getBlockFreq(BB) >= BFI->getBlockFreq(TailCallBB));
  2207. BFI->setBlockFreq(
  2208. BB,
  2209. (BFI->getBlockFreq(BB) - BFI->getBlockFreq(TailCallBB)).getFrequency());
  2210. ModifiedDT = ModifyDT::ModifyBBDT;
  2211. Changed = true;
  2212. ++NumRetsDup;
  2213. }
  2214. // If we eliminated all predecessors of the block, delete the block now.
  2215. if (Changed && !BB->hasAddressTaken() && pred_empty(BB))
  2216. BB->eraseFromParent();
  2217. return Changed;
  2218. }
  2219. //===----------------------------------------------------------------------===//
  2220. // Memory Optimization
  2221. //===----------------------------------------------------------------------===//
  2222. namespace {
  2223. /// This is an extended version of TargetLowering::AddrMode
  2224. /// which holds actual Value*'s for register values.
  2225. struct ExtAddrMode : public TargetLowering::AddrMode {
  2226. Value *BaseReg = nullptr;
  2227. Value *ScaledReg = nullptr;
  2228. Value *OriginalValue = nullptr;
  2229. bool InBounds = true;
  2230. enum FieldName {
  2231. NoField = 0x00,
  2232. BaseRegField = 0x01,
  2233. BaseGVField = 0x02,
  2234. BaseOffsField = 0x04,
  2235. ScaledRegField = 0x08,
  2236. ScaleField = 0x10,
  2237. MultipleFields = 0xff
  2238. };
  2239. ExtAddrMode() = default;
  2240. void print(raw_ostream &OS) const;
  2241. void dump() const;
  2242. FieldName compare(const ExtAddrMode &other) {
  2243. // First check that the types are the same on each field, as differing types
  2244. // is something we can't cope with later on.
  2245. if (BaseReg && other.BaseReg &&
  2246. BaseReg->getType() != other.BaseReg->getType())
  2247. return MultipleFields;
  2248. if (BaseGV && other.BaseGV && BaseGV->getType() != other.BaseGV->getType())
  2249. return MultipleFields;
  2250. if (ScaledReg && other.ScaledReg &&
  2251. ScaledReg->getType() != other.ScaledReg->getType())
  2252. return MultipleFields;
  2253. // Conservatively reject 'inbounds' mismatches.
  2254. if (InBounds != other.InBounds)
  2255. return MultipleFields;
  2256. // Check each field to see if it differs.
  2257. unsigned Result = NoField;
  2258. if (BaseReg != other.BaseReg)
  2259. Result |= BaseRegField;
  2260. if (BaseGV != other.BaseGV)
  2261. Result |= BaseGVField;
  2262. if (BaseOffs != other.BaseOffs)
  2263. Result |= BaseOffsField;
  2264. if (ScaledReg != other.ScaledReg)
  2265. Result |= ScaledRegField;
  2266. // Don't count 0 as being a different scale, because that actually means
  2267. // unscaled (which will already be counted by having no ScaledReg).
  2268. if (Scale && other.Scale && Scale != other.Scale)
  2269. Result |= ScaleField;
  2270. if (llvm::popcount(Result) > 1)
  2271. return MultipleFields;
  2272. else
  2273. return static_cast<FieldName>(Result);
  2274. }
  2275. // An AddrMode is trivial if it involves no calculation i.e. it is just a base
  2276. // with no offset.
  2277. bool isTrivial() {
  2278. // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
  2279. // trivial if at most one of these terms is nonzero, except that BaseGV and
  2280. // BaseReg both being zero actually means a null pointer value, which we
  2281. // consider to be 'non-zero' here.
  2282. return !BaseOffs && !Scale && !(BaseGV && BaseReg);
  2283. }
  2284. Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
  2285. switch (Field) {
  2286. default:
  2287. return nullptr;
  2288. case BaseRegField:
  2289. return BaseReg;
  2290. case BaseGVField:
  2291. return BaseGV;
  2292. case ScaledRegField:
  2293. return ScaledReg;
  2294. case BaseOffsField:
  2295. return ConstantInt::get(IntPtrTy, BaseOffs);
  2296. }
  2297. }
  2298. void SetCombinedField(FieldName Field, Value *V,
  2299. const SmallVectorImpl<ExtAddrMode> &AddrModes) {
  2300. switch (Field) {
  2301. default:
  2302. llvm_unreachable("Unhandled fields are expected to be rejected earlier");
  2303. break;
  2304. case ExtAddrMode::BaseRegField:
  2305. BaseReg = V;
  2306. break;
  2307. case ExtAddrMode::BaseGVField:
  2308. // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
  2309. // in the BaseReg field.
  2310. assert(BaseReg == nullptr);
  2311. BaseReg = V;
  2312. BaseGV = nullptr;
  2313. break;
  2314. case ExtAddrMode::ScaledRegField:
  2315. ScaledReg = V;
  2316. // If we have a mix of scaled and unscaled addrmodes then we want scale
  2317. // to be the scale and not zero.
  2318. if (!Scale)
  2319. for (const ExtAddrMode &AM : AddrModes)
  2320. if (AM.Scale) {
  2321. Scale = AM.Scale;
  2322. break;
  2323. }
  2324. break;
  2325. case ExtAddrMode::BaseOffsField:
  2326. // The offset is no longer a constant, so it goes in ScaledReg with a
  2327. // scale of 1.
  2328. assert(ScaledReg == nullptr);
  2329. ScaledReg = V;
  2330. Scale = 1;
  2331. BaseOffs = 0;
  2332. break;
  2333. }
  2334. }
  2335. };
  2336. #ifndef NDEBUG
  2337. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  2338. AM.print(OS);
  2339. return OS;
  2340. }
  2341. #endif
  2342. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  2343. void ExtAddrMode::print(raw_ostream &OS) const {
  2344. bool NeedPlus = false;
  2345. OS << "[";
  2346. if (InBounds)
  2347. OS << "inbounds ";
  2348. if (BaseGV) {
  2349. OS << (NeedPlus ? " + " : "") << "GV:";
  2350. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  2351. NeedPlus = true;
  2352. }
  2353. if (BaseOffs) {
  2354. OS << (NeedPlus ? " + " : "") << BaseOffs;
  2355. NeedPlus = true;
  2356. }
  2357. if (BaseReg) {
  2358. OS << (NeedPlus ? " + " : "") << "Base:";
  2359. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  2360. NeedPlus = true;
  2361. }
  2362. if (Scale) {
  2363. OS << (NeedPlus ? " + " : "") << Scale << "*";
  2364. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  2365. }
  2366. OS << ']';
  2367. }
  2368. LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
  2369. print(dbgs());
  2370. dbgs() << '\n';
  2371. }
  2372. #endif
  2373. } // end anonymous namespace
  2374. namespace {
  2375. /// This class provides transaction based operation on the IR.
  2376. /// Every change made through this class is recorded in the internal state and
  2377. /// can be undone (rollback) until commit is called.
  2378. /// CGP does not check if instructions could be speculatively executed when
  2379. /// moved. Preserving the original location would pessimize the debugging
  2380. /// experience, as well as negatively impact the quality of sample PGO.
  2381. class TypePromotionTransaction {
  2382. /// This represents the common interface of the individual transaction.
  2383. /// Each class implements the logic for doing one specific modification on
  2384. /// the IR via the TypePromotionTransaction.
  2385. class TypePromotionAction {
  2386. protected:
  2387. /// The Instruction modified.
  2388. Instruction *Inst;
  2389. public:
  2390. /// Constructor of the action.
  2391. /// The constructor performs the related action on the IR.
  2392. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  2393. virtual ~TypePromotionAction() = default;
  2394. /// Undo the modification done by this action.
  2395. /// When this method is called, the IR must be in the same state as it was
  2396. /// before this action was applied.
  2397. /// \pre Undoing the action works if and only if the IR is in the exact same
  2398. /// state as it was directly after this action was applied.
  2399. virtual void undo() = 0;
  2400. /// Advocate every change made by this action.
  2401. /// When the results on the IR of the action are to be kept, it is important
  2402. /// to call this function, otherwise hidden information may be kept forever.
  2403. virtual void commit() {
  2404. // Nothing to be done, this action is not doing anything.
  2405. }
  2406. };
  2407. /// Utility to remember the position of an instruction.
  2408. class InsertionHandler {
  2409. /// Position of an instruction.
  2410. /// Either an instruction:
  2411. /// - Is the first in a basic block: BB is used.
  2412. /// - Has a previous instruction: PrevInst is used.
  2413. union {
  2414. Instruction *PrevInst;
  2415. BasicBlock *BB;
  2416. } Point;
  2417. /// Remember whether or not the instruction had a previous instruction.
  2418. bool HasPrevInstruction;
  2419. public:
  2420. /// Record the position of \p Inst.
  2421. InsertionHandler(Instruction *Inst) {
  2422. BasicBlock::iterator It = Inst->getIterator();
  2423. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  2424. if (HasPrevInstruction)
  2425. Point.PrevInst = &*--It;
  2426. else
  2427. Point.BB = Inst->getParent();
  2428. }
  2429. /// Insert \p Inst at the recorded position.
  2430. void insert(Instruction *Inst) {
  2431. if (HasPrevInstruction) {
  2432. if (Inst->getParent())
  2433. Inst->removeFromParent();
  2434. Inst->insertAfter(Point.PrevInst);
  2435. } else {
  2436. Instruction *Position = &*Point.BB->getFirstInsertionPt();
  2437. if (Inst->getParent())
  2438. Inst->moveBefore(Position);
  2439. else
  2440. Inst->insertBefore(Position);
  2441. }
  2442. }
  2443. };
  2444. /// Move an instruction before another.
  2445. class InstructionMoveBefore : public TypePromotionAction {
  2446. /// Original position of the instruction.
  2447. InsertionHandler Position;
  2448. public:
  2449. /// Move \p Inst before \p Before.
  2450. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  2451. : TypePromotionAction(Inst), Position(Inst) {
  2452. LLVM_DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before
  2453. << "\n");
  2454. Inst->moveBefore(Before);
  2455. }
  2456. /// Move the instruction back to its original position.
  2457. void undo() override {
  2458. LLVM_DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  2459. Position.insert(Inst);
  2460. }
  2461. };
  2462. /// Set the operand of an instruction with a new value.
  2463. class OperandSetter : public TypePromotionAction {
  2464. /// Original operand of the instruction.
  2465. Value *Origin;
  2466. /// Index of the modified instruction.
  2467. unsigned Idx;
  2468. public:
  2469. /// Set \p Idx operand of \p Inst with \p NewVal.
  2470. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  2471. : TypePromotionAction(Inst), Idx(Idx) {
  2472. LLVM_DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  2473. << "for:" << *Inst << "\n"
  2474. << "with:" << *NewVal << "\n");
  2475. Origin = Inst->getOperand(Idx);
  2476. Inst->setOperand(Idx, NewVal);
  2477. }
  2478. /// Restore the original value of the instruction.
  2479. void undo() override {
  2480. LLVM_DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  2481. << "for: " << *Inst << "\n"
  2482. << "with: " << *Origin << "\n");
  2483. Inst->setOperand(Idx, Origin);
  2484. }
  2485. };
  2486. /// Hide the operands of an instruction.
  2487. /// Do as if this instruction was not using any of its operands.
  2488. class OperandsHider : public TypePromotionAction {
  2489. /// The list of original operands.
  2490. SmallVector<Value *, 4> OriginalValues;
  2491. public:
  2492. /// Remove \p Inst from the uses of the operands of \p Inst.
  2493. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  2494. LLVM_DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  2495. unsigned NumOpnds = Inst->getNumOperands();
  2496. OriginalValues.reserve(NumOpnds);
  2497. for (unsigned It = 0; It < NumOpnds; ++It) {
  2498. // Save the current operand.
  2499. Value *Val = Inst->getOperand(It);
  2500. OriginalValues.push_back(Val);
  2501. // Set a dummy one.
  2502. // We could use OperandSetter here, but that would imply an overhead
  2503. // that we are not willing to pay.
  2504. Inst->setOperand(It, UndefValue::get(Val->getType()));
  2505. }
  2506. }
  2507. /// Restore the original list of uses.
  2508. void undo() override {
  2509. LLVM_DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  2510. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  2511. Inst->setOperand(It, OriginalValues[It]);
  2512. }
  2513. };
  2514. /// Build a truncate instruction.
  2515. class TruncBuilder : public TypePromotionAction {
  2516. Value *Val;
  2517. public:
  2518. /// Build a truncate instruction of \p Opnd producing a \p Ty
  2519. /// result.
  2520. /// trunc Opnd to Ty.
  2521. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  2522. IRBuilder<> Builder(Opnd);
  2523. Builder.SetCurrentDebugLocation(DebugLoc());
  2524. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  2525. LLVM_DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  2526. }
  2527. /// Get the built value.
  2528. Value *getBuiltValue() { return Val; }
  2529. /// Remove the built instruction.
  2530. void undo() override {
  2531. LLVM_DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  2532. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2533. IVal->eraseFromParent();
  2534. }
  2535. };
  2536. /// Build a sign extension instruction.
  2537. class SExtBuilder : public TypePromotionAction {
  2538. Value *Val;
  2539. public:
  2540. /// Build a sign extension instruction of \p Opnd producing a \p Ty
  2541. /// result.
  2542. /// sext Opnd to Ty.
  2543. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2544. : TypePromotionAction(InsertPt) {
  2545. IRBuilder<> Builder(InsertPt);
  2546. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  2547. LLVM_DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  2548. }
  2549. /// Get the built value.
  2550. Value *getBuiltValue() { return Val; }
  2551. /// Remove the built instruction.
  2552. void undo() override {
  2553. LLVM_DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  2554. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2555. IVal->eraseFromParent();
  2556. }
  2557. };
  2558. /// Build a zero extension instruction.
  2559. class ZExtBuilder : public TypePromotionAction {
  2560. Value *Val;
  2561. public:
  2562. /// Build a zero extension instruction of \p Opnd producing a \p Ty
  2563. /// result.
  2564. /// zext Opnd to Ty.
  2565. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  2566. : TypePromotionAction(InsertPt) {
  2567. IRBuilder<> Builder(InsertPt);
  2568. Builder.SetCurrentDebugLocation(DebugLoc());
  2569. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  2570. LLVM_DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  2571. }
  2572. /// Get the built value.
  2573. Value *getBuiltValue() { return Val; }
  2574. /// Remove the built instruction.
  2575. void undo() override {
  2576. LLVM_DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  2577. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  2578. IVal->eraseFromParent();
  2579. }
  2580. };
  2581. /// Mutate an instruction to another type.
  2582. class TypeMutator : public TypePromotionAction {
  2583. /// Record the original type.
  2584. Type *OrigTy;
  2585. public:
  2586. /// Mutate the type of \p Inst into \p NewTy.
  2587. TypeMutator(Instruction *Inst, Type *NewTy)
  2588. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  2589. LLVM_DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  2590. << "\n");
  2591. Inst->mutateType(NewTy);
  2592. }
  2593. /// Mutate the instruction back to its original type.
  2594. void undo() override {
  2595. LLVM_DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  2596. << "\n");
  2597. Inst->mutateType(OrigTy);
  2598. }
  2599. };
  2600. /// Replace the uses of an instruction by another instruction.
  2601. class UsesReplacer : public TypePromotionAction {
  2602. /// Helper structure to keep track of the replaced uses.
  2603. struct InstructionAndIdx {
  2604. /// The instruction using the instruction.
  2605. Instruction *Inst;
  2606. /// The index where this instruction is used for Inst.
  2607. unsigned Idx;
  2608. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  2609. : Inst(Inst), Idx(Idx) {}
  2610. };
  2611. /// Keep track of the original uses (pair Instruction, Index).
  2612. SmallVector<InstructionAndIdx, 4> OriginalUses;
  2613. /// Keep track of the debug users.
  2614. SmallVector<DbgValueInst *, 1> DbgValues;
  2615. /// Keep track of the new value so that we can undo it by replacing
  2616. /// instances of the new value with the original value.
  2617. Value *New;
  2618. using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
  2619. public:
  2620. /// Replace all the use of \p Inst by \p New.
  2621. UsesReplacer(Instruction *Inst, Value *New)
  2622. : TypePromotionAction(Inst), New(New) {
  2623. LLVM_DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  2624. << "\n");
  2625. // Record the original uses.
  2626. for (Use &U : Inst->uses()) {
  2627. Instruction *UserI = cast<Instruction>(U.getUser());
  2628. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  2629. }
  2630. // Record the debug uses separately. They are not in the instruction's
  2631. // use list, but they are replaced by RAUW.
  2632. findDbgValues(DbgValues, Inst);
  2633. // Now, we can replace the uses.
  2634. Inst->replaceAllUsesWith(New);
  2635. }
  2636. /// Reassign the original uses of Inst to Inst.
  2637. void undo() override {
  2638. LLVM_DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  2639. for (InstructionAndIdx &Use : OriginalUses)
  2640. Use.Inst->setOperand(Use.Idx, Inst);
  2641. // RAUW has replaced all original uses with references to the new value,
  2642. // including the debug uses. Since we are undoing the replacements,
  2643. // the original debug uses must also be reinstated to maintain the
  2644. // correctness and utility of debug value instructions.
  2645. for (auto *DVI : DbgValues)
  2646. DVI->replaceVariableLocationOp(New, Inst);
  2647. }
  2648. };
  2649. /// Remove an instruction from the IR.
  2650. class InstructionRemover : public TypePromotionAction {
  2651. /// Original position of the instruction.
  2652. InsertionHandler Inserter;
  2653. /// Helper structure to hide all the link to the instruction. In other
  2654. /// words, this helps to do as if the instruction was removed.
  2655. OperandsHider Hider;
  2656. /// Keep track of the uses replaced, if any.
  2657. UsesReplacer *Replacer = nullptr;
  2658. /// Keep track of instructions removed.
  2659. SetOfInstrs &RemovedInsts;
  2660. public:
  2661. /// Remove all reference of \p Inst and optionally replace all its
  2662. /// uses with New.
  2663. /// \p RemovedInsts Keep track of the instructions removed by this Action.
  2664. /// \pre If !Inst->use_empty(), then New != nullptr
  2665. InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
  2666. Value *New = nullptr)
  2667. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  2668. RemovedInsts(RemovedInsts) {
  2669. if (New)
  2670. Replacer = new UsesReplacer(Inst, New);
  2671. LLVM_DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  2672. RemovedInsts.insert(Inst);
  2673. /// The instructions removed here will be freed after completing
  2674. /// optimizeBlock() for all blocks as we need to keep track of the
  2675. /// removed instructions during promotion.
  2676. Inst->removeFromParent();
  2677. }
  2678. ~InstructionRemover() override { delete Replacer; }
  2679. /// Resurrect the instruction and reassign it to the proper uses if
  2680. /// new value was provided when build this action.
  2681. void undo() override {
  2682. LLVM_DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  2683. Inserter.insert(Inst);
  2684. if (Replacer)
  2685. Replacer->undo();
  2686. Hider.undo();
  2687. RemovedInsts.erase(Inst);
  2688. }
  2689. };
  2690. public:
  2691. /// Restoration point.
  2692. /// The restoration point is a pointer to an action instead of an iterator
  2693. /// because the iterator may be invalidated but not the pointer.
  2694. using ConstRestorationPt = const TypePromotionAction *;
  2695. TypePromotionTransaction(SetOfInstrs &RemovedInsts)
  2696. : RemovedInsts(RemovedInsts) {}
  2697. /// Advocate every changes made in that transaction. Return true if any change
  2698. /// happen.
  2699. bool commit();
  2700. /// Undo all the changes made after the given point.
  2701. void rollback(ConstRestorationPt Point);
  2702. /// Get the current restoration point.
  2703. ConstRestorationPt getRestorationPoint() const;
  2704. /// \name API for IR modification with state keeping to support rollback.
  2705. /// @{
  2706. /// Same as Instruction::setOperand.
  2707. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  2708. /// Same as Instruction::eraseFromParent.
  2709. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  2710. /// Same as Value::replaceAllUsesWith.
  2711. void replaceAllUsesWith(Instruction *Inst, Value *New);
  2712. /// Same as Value::mutateType.
  2713. void mutateType(Instruction *Inst, Type *NewTy);
  2714. /// Same as IRBuilder::createTrunc.
  2715. Value *createTrunc(Instruction *Opnd, Type *Ty);
  2716. /// Same as IRBuilder::createSExt.
  2717. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2718. /// Same as IRBuilder::createZExt.
  2719. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2720. /// Same as Instruction::moveBefore.
  2721. void moveBefore(Instruction *Inst, Instruction *Before);
  2722. /// @}
  2723. private:
  2724. /// The ordered list of actions made so far.
  2725. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  2726. using CommitPt =
  2727. SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
  2728. SetOfInstrs &RemovedInsts;
  2729. };
  2730. } // end anonymous namespace
  2731. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  2732. Value *NewVal) {
  2733. Actions.push_back(std::make_unique<TypePromotionTransaction::OperandSetter>(
  2734. Inst, Idx, NewVal));
  2735. }
  2736. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  2737. Value *NewVal) {
  2738. Actions.push_back(
  2739. std::make_unique<TypePromotionTransaction::InstructionRemover>(
  2740. Inst, RemovedInsts, NewVal));
  2741. }
  2742. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  2743. Value *New) {
  2744. Actions.push_back(
  2745. std::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  2746. }
  2747. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  2748. Actions.push_back(
  2749. std::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  2750. }
  2751. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd, Type *Ty) {
  2752. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  2753. Value *Val = Ptr->getBuiltValue();
  2754. Actions.push_back(std::move(Ptr));
  2755. return Val;
  2756. }
  2757. Value *TypePromotionTransaction::createSExt(Instruction *Inst, Value *Opnd,
  2758. Type *Ty) {
  2759. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  2760. Value *Val = Ptr->getBuiltValue();
  2761. Actions.push_back(std::move(Ptr));
  2762. return Val;
  2763. }
  2764. Value *TypePromotionTransaction::createZExt(Instruction *Inst, Value *Opnd,
  2765. Type *Ty) {
  2766. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  2767. Value *Val = Ptr->getBuiltValue();
  2768. Actions.push_back(std::move(Ptr));
  2769. return Val;
  2770. }
  2771. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  2772. Instruction *Before) {
  2773. Actions.push_back(
  2774. std::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
  2775. Inst, Before));
  2776. }
  2777. TypePromotionTransaction::ConstRestorationPt
  2778. TypePromotionTransaction::getRestorationPoint() const {
  2779. return !Actions.empty() ? Actions.back().get() : nullptr;
  2780. }
  2781. bool TypePromotionTransaction::commit() {
  2782. for (std::unique_ptr<TypePromotionAction> &Action : Actions)
  2783. Action->commit();
  2784. bool Modified = !Actions.empty();
  2785. Actions.clear();
  2786. return Modified;
  2787. }
  2788. void TypePromotionTransaction::rollback(
  2789. TypePromotionTransaction::ConstRestorationPt Point) {
  2790. while (!Actions.empty() && Point != Actions.back().get()) {
  2791. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  2792. Curr->undo();
  2793. }
  2794. }
  2795. namespace {
  2796. /// A helper class for matching addressing modes.
  2797. ///
  2798. /// This encapsulates the logic for matching the target-legal addressing modes.
  2799. class AddressingModeMatcher {
  2800. SmallVectorImpl<Instruction *> &AddrModeInsts;
  2801. const TargetLowering &TLI;
  2802. const TargetRegisterInfo &TRI;
  2803. const DataLayout &DL;
  2804. const LoopInfo &LI;
  2805. const std::function<const DominatorTree &()> getDTFn;
  2806. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  2807. /// the memory instruction that we're computing this address for.
  2808. Type *AccessTy;
  2809. unsigned AddrSpace;
  2810. Instruction *MemoryInst;
  2811. /// This is the addressing mode that we're building up. This is
  2812. /// part of the return value of this addressing mode matching stuff.
  2813. ExtAddrMode &AddrMode;
  2814. /// The instructions inserted by other CodeGenPrepare optimizations.
  2815. const SetOfInstrs &InsertedInsts;
  2816. /// A map from the instructions to their type before promotion.
  2817. InstrToOrigTy &PromotedInsts;
  2818. /// The ongoing transaction where every action should be registered.
  2819. TypePromotionTransaction &TPT;
  2820. // A GEP which has too large offset to be folded into the addressing mode.
  2821. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP;
  2822. /// This is set to true when we should not do profitability checks.
  2823. /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
  2824. bool IgnoreProfitability;
  2825. /// True if we are optimizing for size.
  2826. bool OptSize;
  2827. ProfileSummaryInfo *PSI;
  2828. BlockFrequencyInfo *BFI;
  2829. AddressingModeMatcher(
  2830. SmallVectorImpl<Instruction *> &AMI, const TargetLowering &TLI,
  2831. const TargetRegisterInfo &TRI, const LoopInfo &LI,
  2832. const std::function<const DominatorTree &()> getDTFn, Type *AT,
  2833. unsigned AS, Instruction *MI, ExtAddrMode &AM,
  2834. const SetOfInstrs &InsertedInsts, InstrToOrigTy &PromotedInsts,
  2835. TypePromotionTransaction &TPT,
  2836. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
  2837. bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI)
  2838. : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
  2839. DL(MI->getModule()->getDataLayout()), LI(LI), getDTFn(getDTFn),
  2840. AccessTy(AT), AddrSpace(AS), MemoryInst(MI), AddrMode(AM),
  2841. InsertedInsts(InsertedInsts), PromotedInsts(PromotedInsts), TPT(TPT),
  2842. LargeOffsetGEP(LargeOffsetGEP), OptSize(OptSize), PSI(PSI), BFI(BFI) {
  2843. IgnoreProfitability = false;
  2844. }
  2845. public:
  2846. /// Find the maximal addressing mode that a load/store of V can fold,
  2847. /// give an access type of AccessTy. This returns a list of involved
  2848. /// instructions in AddrModeInsts.
  2849. /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
  2850. /// optimizations.
  2851. /// \p PromotedInsts maps the instructions to their type before promotion.
  2852. /// \p The ongoing transaction where every action should be registered.
  2853. static ExtAddrMode
  2854. Match(Value *V, Type *AccessTy, unsigned AS, Instruction *MemoryInst,
  2855. SmallVectorImpl<Instruction *> &AddrModeInsts,
  2856. const TargetLowering &TLI, const LoopInfo &LI,
  2857. const std::function<const DominatorTree &()> getDTFn,
  2858. const TargetRegisterInfo &TRI, const SetOfInstrs &InsertedInsts,
  2859. InstrToOrigTy &PromotedInsts, TypePromotionTransaction &TPT,
  2860. std::pair<AssertingVH<GetElementPtrInst>, int64_t> &LargeOffsetGEP,
  2861. bool OptSize, ProfileSummaryInfo *PSI, BlockFrequencyInfo *BFI) {
  2862. ExtAddrMode Result;
  2863. bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI, LI, getDTFn,
  2864. AccessTy, AS, MemoryInst, Result,
  2865. InsertedInsts, PromotedInsts, TPT,
  2866. LargeOffsetGEP, OptSize, PSI, BFI)
  2867. .matchAddr(V, 0);
  2868. (void)Success;
  2869. assert(Success && "Couldn't select *anything*?");
  2870. return Result;
  2871. }
  2872. private:
  2873. bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  2874. bool matchAddr(Value *Addr, unsigned Depth);
  2875. bool matchOperationAddr(User *AddrInst, unsigned Opcode, unsigned Depth,
  2876. bool *MovedAway = nullptr);
  2877. bool isProfitableToFoldIntoAddressingMode(Instruction *I,
  2878. ExtAddrMode &AMBefore,
  2879. ExtAddrMode &AMAfter);
  2880. bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  2881. bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
  2882. Value *PromotedOperand) const;
  2883. };
  2884. class PhiNodeSet;
  2885. /// An iterator for PhiNodeSet.
  2886. class PhiNodeSetIterator {
  2887. PhiNodeSet *const Set;
  2888. size_t CurrentIndex = 0;
  2889. public:
  2890. /// The constructor. Start should point to either a valid element, or be equal
  2891. /// to the size of the underlying SmallVector of the PhiNodeSet.
  2892. PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start);
  2893. PHINode *operator*() const;
  2894. PhiNodeSetIterator &operator++();
  2895. bool operator==(const PhiNodeSetIterator &RHS) const;
  2896. bool operator!=(const PhiNodeSetIterator &RHS) const;
  2897. };
  2898. /// Keeps a set of PHINodes.
  2899. ///
  2900. /// This is a minimal set implementation for a specific use case:
  2901. /// It is very fast when there are very few elements, but also provides good
  2902. /// performance when there are many. It is similar to SmallPtrSet, but also
  2903. /// provides iteration by insertion order, which is deterministic and stable
  2904. /// across runs. It is also similar to SmallSetVector, but provides removing
  2905. /// elements in O(1) time. This is achieved by not actually removing the element
  2906. /// from the underlying vector, so comes at the cost of using more memory, but
  2907. /// that is fine, since PhiNodeSets are used as short lived objects.
  2908. class PhiNodeSet {
  2909. friend class PhiNodeSetIterator;
  2910. using MapType = SmallDenseMap<PHINode *, size_t, 32>;
  2911. using iterator = PhiNodeSetIterator;
  2912. /// Keeps the elements in the order of their insertion in the underlying
  2913. /// vector. To achieve constant time removal, it never deletes any element.
  2914. SmallVector<PHINode *, 32> NodeList;
  2915. /// Keeps the elements in the underlying set implementation. This (and not the
  2916. /// NodeList defined above) is the source of truth on whether an element
  2917. /// is actually in the collection.
  2918. MapType NodeMap;
  2919. /// Points to the first valid (not deleted) element when the set is not empty
  2920. /// and the value is not zero. Equals to the size of the underlying vector
  2921. /// when the set is empty. When the value is 0, as in the beginning, the
  2922. /// first element may or may not be valid.
  2923. size_t FirstValidElement = 0;
  2924. public:
  2925. /// Inserts a new element to the collection.
  2926. /// \returns true if the element is actually added, i.e. was not in the
  2927. /// collection before the operation.
  2928. bool insert(PHINode *Ptr) {
  2929. if (NodeMap.insert(std::make_pair(Ptr, NodeList.size())).second) {
  2930. NodeList.push_back(Ptr);
  2931. return true;
  2932. }
  2933. return false;
  2934. }
  2935. /// Removes the element from the collection.
  2936. /// \returns whether the element is actually removed, i.e. was in the
  2937. /// collection before the operation.
  2938. bool erase(PHINode *Ptr) {
  2939. if (NodeMap.erase(Ptr)) {
  2940. SkipRemovedElements(FirstValidElement);
  2941. return true;
  2942. }
  2943. return false;
  2944. }
  2945. /// Removes all elements and clears the collection.
  2946. void clear() {
  2947. NodeMap.clear();
  2948. NodeList.clear();
  2949. FirstValidElement = 0;
  2950. }
  2951. /// \returns an iterator that will iterate the elements in the order of
  2952. /// insertion.
  2953. iterator begin() {
  2954. if (FirstValidElement == 0)
  2955. SkipRemovedElements(FirstValidElement);
  2956. return PhiNodeSetIterator(this, FirstValidElement);
  2957. }
  2958. /// \returns an iterator that points to the end of the collection.
  2959. iterator end() { return PhiNodeSetIterator(this, NodeList.size()); }
  2960. /// Returns the number of elements in the collection.
  2961. size_t size() const { return NodeMap.size(); }
  2962. /// \returns 1 if the given element is in the collection, and 0 if otherwise.
  2963. size_t count(PHINode *Ptr) const { return NodeMap.count(Ptr); }
  2964. private:
  2965. /// Updates the CurrentIndex so that it will point to a valid element.
  2966. ///
  2967. /// If the element of NodeList at CurrentIndex is valid, it does not
  2968. /// change it. If there are no more valid elements, it updates CurrentIndex
  2969. /// to point to the end of the NodeList.
  2970. void SkipRemovedElements(size_t &CurrentIndex) {
  2971. while (CurrentIndex < NodeList.size()) {
  2972. auto it = NodeMap.find(NodeList[CurrentIndex]);
  2973. // If the element has been deleted and added again later, NodeMap will
  2974. // point to a different index, so CurrentIndex will still be invalid.
  2975. if (it != NodeMap.end() && it->second == CurrentIndex)
  2976. break;
  2977. ++CurrentIndex;
  2978. }
  2979. }
  2980. };
  2981. PhiNodeSetIterator::PhiNodeSetIterator(PhiNodeSet *const Set, size_t Start)
  2982. : Set(Set), CurrentIndex(Start) {}
  2983. PHINode *PhiNodeSetIterator::operator*() const {
  2984. assert(CurrentIndex < Set->NodeList.size() &&
  2985. "PhiNodeSet access out of range");
  2986. return Set->NodeList[CurrentIndex];
  2987. }
  2988. PhiNodeSetIterator &PhiNodeSetIterator::operator++() {
  2989. assert(CurrentIndex < Set->NodeList.size() &&
  2990. "PhiNodeSet access out of range");
  2991. ++CurrentIndex;
  2992. Set->SkipRemovedElements(CurrentIndex);
  2993. return *this;
  2994. }
  2995. bool PhiNodeSetIterator::operator==(const PhiNodeSetIterator &RHS) const {
  2996. return CurrentIndex == RHS.CurrentIndex;
  2997. }
  2998. bool PhiNodeSetIterator::operator!=(const PhiNodeSetIterator &RHS) const {
  2999. return !((*this) == RHS);
  3000. }
  3001. /// Keep track of simplification of Phi nodes.
  3002. /// Accept the set of all phi nodes and erase phi node from this set
  3003. /// if it is simplified.
  3004. class SimplificationTracker {
  3005. DenseMap<Value *, Value *> Storage;
  3006. const SimplifyQuery &SQ;
  3007. // Tracks newly created Phi nodes. The elements are iterated by insertion
  3008. // order.
  3009. PhiNodeSet AllPhiNodes;
  3010. // Tracks newly created Select nodes.
  3011. SmallPtrSet<SelectInst *, 32> AllSelectNodes;
  3012. public:
  3013. SimplificationTracker(const SimplifyQuery &sq) : SQ(sq) {}
  3014. Value *Get(Value *V) {
  3015. do {
  3016. auto SV = Storage.find(V);
  3017. if (SV == Storage.end())
  3018. return V;
  3019. V = SV->second;
  3020. } while (true);
  3021. }
  3022. Value *Simplify(Value *Val) {
  3023. SmallVector<Value *, 32> WorkList;
  3024. SmallPtrSet<Value *, 32> Visited;
  3025. WorkList.push_back(Val);
  3026. while (!WorkList.empty()) {
  3027. auto *P = WorkList.pop_back_val();
  3028. if (!Visited.insert(P).second)
  3029. continue;
  3030. if (auto *PI = dyn_cast<Instruction>(P))
  3031. if (Value *V = simplifyInstruction(cast<Instruction>(PI), SQ)) {
  3032. for (auto *U : PI->users())
  3033. WorkList.push_back(cast<Value>(U));
  3034. Put(PI, V);
  3035. PI->replaceAllUsesWith(V);
  3036. if (auto *PHI = dyn_cast<PHINode>(PI))
  3037. AllPhiNodes.erase(PHI);
  3038. if (auto *Select = dyn_cast<SelectInst>(PI))
  3039. AllSelectNodes.erase(Select);
  3040. PI->eraseFromParent();
  3041. }
  3042. }
  3043. return Get(Val);
  3044. }
  3045. void Put(Value *From, Value *To) { Storage.insert({From, To}); }
  3046. void ReplacePhi(PHINode *From, PHINode *To) {
  3047. Value *OldReplacement = Get(From);
  3048. while (OldReplacement != From) {
  3049. From = To;
  3050. To = dyn_cast<PHINode>(OldReplacement);
  3051. OldReplacement = Get(From);
  3052. }
  3053. assert(To && Get(To) == To && "Replacement PHI node is already replaced.");
  3054. Put(From, To);
  3055. From->replaceAllUsesWith(To);
  3056. AllPhiNodes.erase(From);
  3057. From->eraseFromParent();
  3058. }
  3059. PhiNodeSet &newPhiNodes() { return AllPhiNodes; }
  3060. void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
  3061. void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
  3062. unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
  3063. unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
  3064. void destroyNewNodes(Type *CommonType) {
  3065. // For safe erasing, replace the uses with dummy value first.
  3066. auto *Dummy = PoisonValue::get(CommonType);
  3067. for (auto *I : AllPhiNodes) {
  3068. I->replaceAllUsesWith(Dummy);
  3069. I->eraseFromParent();
  3070. }
  3071. AllPhiNodes.clear();
  3072. for (auto *I : AllSelectNodes) {
  3073. I->replaceAllUsesWith(Dummy);
  3074. I->eraseFromParent();
  3075. }
  3076. AllSelectNodes.clear();
  3077. }
  3078. };
  3079. /// A helper class for combining addressing modes.
  3080. class AddressingModeCombiner {
  3081. typedef DenseMap<Value *, Value *> FoldAddrToValueMapping;
  3082. typedef std::pair<PHINode *, PHINode *> PHIPair;
  3083. private:
  3084. /// The addressing modes we've collected.
  3085. SmallVector<ExtAddrMode, 16> AddrModes;
  3086. /// The field in which the AddrModes differ, when we have more than one.
  3087. ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
  3088. /// Are the AddrModes that we have all just equal to their original values?
  3089. bool AllAddrModesTrivial = true;
  3090. /// Common Type for all different fields in addressing modes.
  3091. Type *CommonType = nullptr;
  3092. /// SimplifyQuery for simplifyInstruction utility.
  3093. const SimplifyQuery &SQ;
  3094. /// Original Address.
  3095. Value *Original;
  3096. public:
  3097. AddressingModeCombiner(const SimplifyQuery &_SQ, Value *OriginalValue)
  3098. : SQ(_SQ), Original(OriginalValue) {}
  3099. /// Get the combined AddrMode
  3100. const ExtAddrMode &getAddrMode() const { return AddrModes[0]; }
  3101. /// Add a new AddrMode if it's compatible with the AddrModes we already
  3102. /// have.
  3103. /// \return True iff we succeeded in doing so.
  3104. bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
  3105. // Take note of if we have any non-trivial AddrModes, as we need to detect
  3106. // when all AddrModes are trivial as then we would introduce a phi or select
  3107. // which just duplicates what's already there.
  3108. AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
  3109. // If this is the first addrmode then everything is fine.
  3110. if (AddrModes.empty()) {
  3111. AddrModes.emplace_back(NewAddrMode);
  3112. return true;
  3113. }
  3114. // Figure out how different this is from the other address modes, which we
  3115. // can do just by comparing against the first one given that we only care
  3116. // about the cumulative difference.
  3117. ExtAddrMode::FieldName ThisDifferentField =
  3118. AddrModes[0].compare(NewAddrMode);
  3119. if (DifferentField == ExtAddrMode::NoField)
  3120. DifferentField = ThisDifferentField;
  3121. else if (DifferentField != ThisDifferentField)
  3122. DifferentField = ExtAddrMode::MultipleFields;
  3123. // If NewAddrMode differs in more than one dimension we cannot handle it.
  3124. bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
  3125. // If Scale Field is different then we reject.
  3126. CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
  3127. // We also must reject the case when base offset is different and
  3128. // scale reg is not null, we cannot handle this case due to merge of
  3129. // different offsets will be used as ScaleReg.
  3130. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
  3131. !NewAddrMode.ScaledReg);
  3132. // We also must reject the case when GV is different and BaseReg installed
  3133. // due to we want to use base reg as a merge of GV values.
  3134. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
  3135. !NewAddrMode.HasBaseReg);
  3136. // Even if NewAddMode is the same we still need to collect it due to
  3137. // original value is different. And later we will need all original values
  3138. // as anchors during finding the common Phi node.
  3139. if (CanHandle)
  3140. AddrModes.emplace_back(NewAddrMode);
  3141. else
  3142. AddrModes.clear();
  3143. return CanHandle;
  3144. }
  3145. /// Combine the addressing modes we've collected into a single
  3146. /// addressing mode.
  3147. /// \return True iff we successfully combined them or we only had one so
  3148. /// didn't need to combine them anyway.
  3149. bool combineAddrModes() {
  3150. // If we have no AddrModes then they can't be combined.
  3151. if (AddrModes.size() == 0)
  3152. return false;
  3153. // A single AddrMode can trivially be combined.
  3154. if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
  3155. return true;
  3156. // If the AddrModes we collected are all just equal to the value they are
  3157. // derived from then combining them wouldn't do anything useful.
  3158. if (AllAddrModesTrivial)
  3159. return false;
  3160. if (!addrModeCombiningAllowed())
  3161. return false;
  3162. // Build a map between <original value, basic block where we saw it> to
  3163. // value of base register.
  3164. // Bail out if there is no common type.
  3165. FoldAddrToValueMapping Map;
  3166. if (!initializeMap(Map))
  3167. return false;
  3168. Value *CommonValue = findCommon(Map);
  3169. if (CommonValue)
  3170. AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
  3171. return CommonValue != nullptr;
  3172. }
  3173. private:
  3174. /// Initialize Map with anchor values. For address seen
  3175. /// we set the value of different field saw in this address.
  3176. /// At the same time we find a common type for different field we will
  3177. /// use to create new Phi/Select nodes. Keep it in CommonType field.
  3178. /// Return false if there is no common type found.
  3179. bool initializeMap(FoldAddrToValueMapping &Map) {
  3180. // Keep track of keys where the value is null. We will need to replace it
  3181. // with constant null when we know the common type.
  3182. SmallVector<Value *, 2> NullValue;
  3183. Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
  3184. for (auto &AM : AddrModes) {
  3185. Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
  3186. if (DV) {
  3187. auto *Type = DV->getType();
  3188. if (CommonType && CommonType != Type)
  3189. return false;
  3190. CommonType = Type;
  3191. Map[AM.OriginalValue] = DV;
  3192. } else {
  3193. NullValue.push_back(AM.OriginalValue);
  3194. }
  3195. }
  3196. assert(CommonType && "At least one non-null value must be!");
  3197. for (auto *V : NullValue)
  3198. Map[V] = Constant::getNullValue(CommonType);
  3199. return true;
  3200. }
  3201. /// We have mapping between value A and other value B where B was a field in
  3202. /// addressing mode represented by A. Also we have an original value C
  3203. /// representing an address we start with. Traversing from C through phi and
  3204. /// selects we ended up with A's in a map. This utility function tries to find
  3205. /// a value V which is a field in addressing mode C and traversing through phi
  3206. /// nodes and selects we will end up in corresponded values B in a map.
  3207. /// The utility will create a new Phi/Selects if needed.
  3208. // The simple example looks as follows:
  3209. // BB1:
  3210. // p1 = b1 + 40
  3211. // br cond BB2, BB3
  3212. // BB2:
  3213. // p2 = b2 + 40
  3214. // br BB3
  3215. // BB3:
  3216. // p = phi [p1, BB1], [p2, BB2]
  3217. // v = load p
  3218. // Map is
  3219. // p1 -> b1
  3220. // p2 -> b2
  3221. // Request is
  3222. // p -> ?
  3223. // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3.
  3224. Value *findCommon(FoldAddrToValueMapping &Map) {
  3225. // Tracks the simplification of newly created phi nodes. The reason we use
  3226. // this mapping is because we will add new created Phi nodes in AddrToBase.
  3227. // Simplification of Phi nodes is recursive, so some Phi node may
  3228. // be simplified after we added it to AddrToBase. In reality this
  3229. // simplification is possible only if original phi/selects were not
  3230. // simplified yet.
  3231. // Using this mapping we can find the current value in AddrToBase.
  3232. SimplificationTracker ST(SQ);
  3233. // First step, DFS to create PHI nodes for all intermediate blocks.
  3234. // Also fill traverse order for the second step.
  3235. SmallVector<Value *, 32> TraverseOrder;
  3236. InsertPlaceholders(Map, TraverseOrder, ST);
  3237. // Second Step, fill new nodes by merged values and simplify if possible.
  3238. FillPlaceholders(Map, TraverseOrder, ST);
  3239. if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
  3240. ST.destroyNewNodes(CommonType);
  3241. return nullptr;
  3242. }
  3243. // Now we'd like to match New Phi nodes to existed ones.
  3244. unsigned PhiNotMatchedCount = 0;
  3245. if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
  3246. ST.destroyNewNodes(CommonType);
  3247. return nullptr;
  3248. }
  3249. auto *Result = ST.Get(Map.find(Original)->second);
  3250. if (Result) {
  3251. NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
  3252. NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
  3253. }
  3254. return Result;
  3255. }
  3256. /// Try to match PHI node to Candidate.
  3257. /// Matcher tracks the matched Phi nodes.
  3258. bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
  3259. SmallSetVector<PHIPair, 8> &Matcher,
  3260. PhiNodeSet &PhiNodesToMatch) {
  3261. SmallVector<PHIPair, 8> WorkList;
  3262. Matcher.insert({PHI, Candidate});
  3263. SmallSet<PHINode *, 8> MatchedPHIs;
  3264. MatchedPHIs.insert(PHI);
  3265. WorkList.push_back({PHI, Candidate});
  3266. SmallSet<PHIPair, 8> Visited;
  3267. while (!WorkList.empty()) {
  3268. auto Item = WorkList.pop_back_val();
  3269. if (!Visited.insert(Item).second)
  3270. continue;
  3271. // We iterate over all incoming values to Phi to compare them.
  3272. // If values are different and both of them Phi and the first one is a
  3273. // Phi we added (subject to match) and both of them is in the same basic
  3274. // block then we can match our pair if values match. So we state that
  3275. // these values match and add it to work list to verify that.
  3276. for (auto *B : Item.first->blocks()) {
  3277. Value *FirstValue = Item.first->getIncomingValueForBlock(B);
  3278. Value *SecondValue = Item.second->getIncomingValueForBlock(B);
  3279. if (FirstValue == SecondValue)
  3280. continue;
  3281. PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
  3282. PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
  3283. // One of them is not Phi or
  3284. // The first one is not Phi node from the set we'd like to match or
  3285. // Phi nodes from different basic blocks then
  3286. // we will not be able to match.
  3287. if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
  3288. FirstPhi->getParent() != SecondPhi->getParent())
  3289. return false;
  3290. // If we already matched them then continue.
  3291. if (Matcher.count({FirstPhi, SecondPhi}))
  3292. continue;
  3293. // So the values are different and does not match. So we need them to
  3294. // match. (But we register no more than one match per PHI node, so that
  3295. // we won't later try to replace them twice.)
  3296. if (MatchedPHIs.insert(FirstPhi).second)
  3297. Matcher.insert({FirstPhi, SecondPhi});
  3298. // But me must check it.
  3299. WorkList.push_back({FirstPhi, SecondPhi});
  3300. }
  3301. }
  3302. return true;
  3303. }
  3304. /// For the given set of PHI nodes (in the SimplificationTracker) try
  3305. /// to find their equivalents.
  3306. /// Returns false if this matching fails and creation of new Phi is disabled.
  3307. bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
  3308. unsigned &PhiNotMatchedCount) {
  3309. // Matched and PhiNodesToMatch iterate their elements in a deterministic
  3310. // order, so the replacements (ReplacePhi) are also done in a deterministic
  3311. // order.
  3312. SmallSetVector<PHIPair, 8> Matched;
  3313. SmallPtrSet<PHINode *, 8> WillNotMatch;
  3314. PhiNodeSet &PhiNodesToMatch = ST.newPhiNodes();
  3315. while (PhiNodesToMatch.size()) {
  3316. PHINode *PHI = *PhiNodesToMatch.begin();
  3317. // Add us, if no Phi nodes in the basic block we do not match.
  3318. WillNotMatch.clear();
  3319. WillNotMatch.insert(PHI);
  3320. // Traverse all Phis until we found equivalent or fail to do that.
  3321. bool IsMatched = false;
  3322. for (auto &P : PHI->getParent()->phis()) {
  3323. // Skip new Phi nodes.
  3324. if (PhiNodesToMatch.count(&P))
  3325. continue;
  3326. if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
  3327. break;
  3328. // If it does not match, collect all Phi nodes from matcher.
  3329. // if we end up with no match, them all these Phi nodes will not match
  3330. // later.
  3331. for (auto M : Matched)
  3332. WillNotMatch.insert(M.first);
  3333. Matched.clear();
  3334. }
  3335. if (IsMatched) {
  3336. // Replace all matched values and erase them.
  3337. for (auto MV : Matched)
  3338. ST.ReplacePhi(MV.first, MV.second);
  3339. Matched.clear();
  3340. continue;
  3341. }
  3342. // If we are not allowed to create new nodes then bail out.
  3343. if (!AllowNewPhiNodes)
  3344. return false;
  3345. // Just remove all seen values in matcher. They will not match anything.
  3346. PhiNotMatchedCount += WillNotMatch.size();
  3347. for (auto *P : WillNotMatch)
  3348. PhiNodesToMatch.erase(P);
  3349. }
  3350. return true;
  3351. }
  3352. /// Fill the placeholders with values from predecessors and simplify them.
  3353. void FillPlaceholders(FoldAddrToValueMapping &Map,
  3354. SmallVectorImpl<Value *> &TraverseOrder,
  3355. SimplificationTracker &ST) {
  3356. while (!TraverseOrder.empty()) {
  3357. Value *Current = TraverseOrder.pop_back_val();
  3358. assert(Map.find(Current) != Map.end() && "No node to fill!!!");
  3359. Value *V = Map[Current];
  3360. if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
  3361. // CurrentValue also must be Select.
  3362. auto *CurrentSelect = cast<SelectInst>(Current);
  3363. auto *TrueValue = CurrentSelect->getTrueValue();
  3364. assert(Map.find(TrueValue) != Map.end() && "No True Value!");
  3365. Select->setTrueValue(ST.Get(Map[TrueValue]));
  3366. auto *FalseValue = CurrentSelect->getFalseValue();
  3367. assert(Map.find(FalseValue) != Map.end() && "No False Value!");
  3368. Select->setFalseValue(ST.Get(Map[FalseValue]));
  3369. } else {
  3370. // Must be a Phi node then.
  3371. auto *PHI = cast<PHINode>(V);
  3372. // Fill the Phi node with values from predecessors.
  3373. for (auto *B : predecessors(PHI->getParent())) {
  3374. Value *PV = cast<PHINode>(Current)->getIncomingValueForBlock(B);
  3375. assert(Map.find(PV) != Map.end() && "No predecessor Value!");
  3376. PHI->addIncoming(ST.Get(Map[PV]), B);
  3377. }
  3378. }
  3379. Map[Current] = ST.Simplify(V);
  3380. }
  3381. }
  3382. /// Starting from original value recursively iterates over def-use chain up to
  3383. /// known ending values represented in a map. For each traversed phi/select
  3384. /// inserts a placeholder Phi or Select.
  3385. /// Reports all new created Phi/Select nodes by adding them to set.
  3386. /// Also reports and order in what values have been traversed.
  3387. void InsertPlaceholders(FoldAddrToValueMapping &Map,
  3388. SmallVectorImpl<Value *> &TraverseOrder,
  3389. SimplificationTracker &ST) {
  3390. SmallVector<Value *, 32> Worklist;
  3391. assert((isa<PHINode>(Original) || isa<SelectInst>(Original)) &&
  3392. "Address must be a Phi or Select node");
  3393. auto *Dummy = PoisonValue::get(CommonType);
  3394. Worklist.push_back(Original);
  3395. while (!Worklist.empty()) {
  3396. Value *Current = Worklist.pop_back_val();
  3397. // if it is already visited or it is an ending value then skip it.
  3398. if (Map.find(Current) != Map.end())
  3399. continue;
  3400. TraverseOrder.push_back(Current);
  3401. // CurrentValue must be a Phi node or select. All others must be covered
  3402. // by anchors.
  3403. if (SelectInst *CurrentSelect = dyn_cast<SelectInst>(Current)) {
  3404. // Is it OK to get metadata from OrigSelect?!
  3405. // Create a Select placeholder with dummy value.
  3406. SelectInst *Select = SelectInst::Create(
  3407. CurrentSelect->getCondition(), Dummy, Dummy,
  3408. CurrentSelect->getName(), CurrentSelect, CurrentSelect);
  3409. Map[Current] = Select;
  3410. ST.insertNewSelect(Select);
  3411. // We are interested in True and False values.
  3412. Worklist.push_back(CurrentSelect->getTrueValue());
  3413. Worklist.push_back(CurrentSelect->getFalseValue());
  3414. } else {
  3415. // It must be a Phi node then.
  3416. PHINode *CurrentPhi = cast<PHINode>(Current);
  3417. unsigned PredCount = CurrentPhi->getNumIncomingValues();
  3418. PHINode *PHI =
  3419. PHINode::Create(CommonType, PredCount, "sunk_phi", CurrentPhi);
  3420. Map[Current] = PHI;
  3421. ST.insertNewPhi(PHI);
  3422. append_range(Worklist, CurrentPhi->incoming_values());
  3423. }
  3424. }
  3425. }
  3426. bool addrModeCombiningAllowed() {
  3427. if (DisableComplexAddrModes)
  3428. return false;
  3429. switch (DifferentField) {
  3430. default:
  3431. return false;
  3432. case ExtAddrMode::BaseRegField:
  3433. return AddrSinkCombineBaseReg;
  3434. case ExtAddrMode::BaseGVField:
  3435. return AddrSinkCombineBaseGV;
  3436. case ExtAddrMode::BaseOffsField:
  3437. return AddrSinkCombineBaseOffs;
  3438. case ExtAddrMode::ScaledRegField:
  3439. return AddrSinkCombineScaledReg;
  3440. }
  3441. }
  3442. };
  3443. } // end anonymous namespace
  3444. /// Try adding ScaleReg*Scale to the current addressing mode.
  3445. /// Return true and update AddrMode if this addr mode is legal for the target,
  3446. /// false if not.
  3447. bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
  3448. unsigned Depth) {
  3449. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  3450. // mode. Just process that directly.
  3451. if (Scale == 1)
  3452. return matchAddr(ScaleReg, Depth);
  3453. // If the scale is 0, it takes nothing to add this.
  3454. if (Scale == 0)
  3455. return true;
  3456. // If we already have a scale of this value, we can add to it, otherwise, we
  3457. // need an available scale field.
  3458. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  3459. return false;
  3460. ExtAddrMode TestAddrMode = AddrMode;
  3461. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  3462. // [A+B + A*7] -> [B+A*8].
  3463. TestAddrMode.Scale += Scale;
  3464. TestAddrMode.ScaledReg = ScaleReg;
  3465. // If the new address isn't legal, bail out.
  3466. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  3467. return false;
  3468. // It was legal, so commit it.
  3469. AddrMode = TestAddrMode;
  3470. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  3471. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  3472. // X*Scale + C*Scale to addr mode. If we found available IV increment, do not
  3473. // go any further: we can reuse it and cannot eliminate it.
  3474. ConstantInt *CI = nullptr;
  3475. Value *AddLHS = nullptr;
  3476. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  3477. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI))) &&
  3478. !isIVIncrement(ScaleReg, &LI) && CI->getValue().isSignedIntN(64)) {
  3479. TestAddrMode.InBounds = false;
  3480. TestAddrMode.ScaledReg = AddLHS;
  3481. TestAddrMode.BaseOffs += CI->getSExtValue() * TestAddrMode.Scale;
  3482. // If this addressing mode is legal, commit it and remember that we folded
  3483. // this instruction.
  3484. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  3485. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  3486. AddrMode = TestAddrMode;
  3487. return true;
  3488. }
  3489. // Restore status quo.
  3490. TestAddrMode = AddrMode;
  3491. }
  3492. // If this is an add recurrence with a constant step, return the increment
  3493. // instruction and the canonicalized step.
  3494. auto GetConstantStep =
  3495. [this](const Value *V) -> std::optional<std::pair<Instruction *, APInt>> {
  3496. auto *PN = dyn_cast<PHINode>(V);
  3497. if (!PN)
  3498. return std::nullopt;
  3499. auto IVInc = getIVIncrement(PN, &LI);
  3500. if (!IVInc)
  3501. return std::nullopt;
  3502. // TODO: The result of the intrinsics above is two-complement. However when
  3503. // IV inc is expressed as add or sub, iv.next is potentially a poison value.
  3504. // If it has nuw or nsw flags, we need to make sure that these flags are
  3505. // inferrable at the point of memory instruction. Otherwise we are replacing
  3506. // well-defined two-complement computation with poison. Currently, to avoid
  3507. // potentially complex analysis needed to prove this, we reject such cases.
  3508. if (auto *OIVInc = dyn_cast<OverflowingBinaryOperator>(IVInc->first))
  3509. if (OIVInc->hasNoSignedWrap() || OIVInc->hasNoUnsignedWrap())
  3510. return std::nullopt;
  3511. if (auto *ConstantStep = dyn_cast<ConstantInt>(IVInc->second))
  3512. return std::make_pair(IVInc->first, ConstantStep->getValue());
  3513. return std::nullopt;
  3514. };
  3515. // Try to account for the following special case:
  3516. // 1. ScaleReg is an inductive variable;
  3517. // 2. We use it with non-zero offset;
  3518. // 3. IV's increment is available at the point of memory instruction.
  3519. //
  3520. // In this case, we may reuse the IV increment instead of the IV Phi to
  3521. // achieve the following advantages:
  3522. // 1. If IV step matches the offset, we will have no need in the offset;
  3523. // 2. Even if they don't match, we will reduce the overlap of living IV
  3524. // and IV increment, that will potentially lead to better register
  3525. // assignment.
  3526. if (AddrMode.BaseOffs) {
  3527. if (auto IVStep = GetConstantStep(ScaleReg)) {
  3528. Instruction *IVInc = IVStep->first;
  3529. // The following assert is important to ensure a lack of infinite loops.
  3530. // This transforms is (intentionally) the inverse of the one just above.
  3531. // If they don't agree on the definition of an increment, we'd alternate
  3532. // back and forth indefinitely.
  3533. assert(isIVIncrement(IVInc, &LI) && "implied by GetConstantStep");
  3534. APInt Step = IVStep->second;
  3535. APInt Offset = Step * AddrMode.Scale;
  3536. if (Offset.isSignedIntN(64)) {
  3537. TestAddrMode.InBounds = false;
  3538. TestAddrMode.ScaledReg = IVInc;
  3539. TestAddrMode.BaseOffs -= Offset.getLimitedValue();
  3540. // If this addressing mode is legal, commit it..
  3541. // (Note that we defer the (expensive) domtree base legality check
  3542. // to the very last possible point.)
  3543. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace) &&
  3544. getDTFn().dominates(IVInc, MemoryInst)) {
  3545. AddrModeInsts.push_back(cast<Instruction>(IVInc));
  3546. AddrMode = TestAddrMode;
  3547. return true;
  3548. }
  3549. // Restore status quo.
  3550. TestAddrMode = AddrMode;
  3551. }
  3552. }
  3553. }
  3554. // Otherwise, just return what we have.
  3555. return true;
  3556. }
  3557. /// This is a little filter, which returns true if an addressing computation
  3558. /// involving I might be folded into a load/store accessing it.
  3559. /// This doesn't need to be perfect, but needs to accept at least
  3560. /// the set of instructions that MatchOperationAddr can.
  3561. static bool MightBeFoldableInst(Instruction *I) {
  3562. switch (I->getOpcode()) {
  3563. case Instruction::BitCast:
  3564. case Instruction::AddrSpaceCast:
  3565. // Don't touch identity bitcasts.
  3566. if (I->getType() == I->getOperand(0)->getType())
  3567. return false;
  3568. return I->getType()->isIntOrPtrTy();
  3569. case Instruction::PtrToInt:
  3570. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3571. return true;
  3572. case Instruction::IntToPtr:
  3573. // We know the input is intptr_t, so this is foldable.
  3574. return true;
  3575. case Instruction::Add:
  3576. return true;
  3577. case Instruction::Mul:
  3578. case Instruction::Shl:
  3579. // Can only handle X*C and X << C.
  3580. return isa<ConstantInt>(I->getOperand(1));
  3581. case Instruction::GetElementPtr:
  3582. return true;
  3583. default:
  3584. return false;
  3585. }
  3586. }
  3587. /// Check whether or not \p Val is a legal instruction for \p TLI.
  3588. /// \note \p Val is assumed to be the product of some type promotion.
  3589. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  3590. /// to be legal, as the non-promoted value would have had the same state.
  3591. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  3592. const DataLayout &DL, Value *Val) {
  3593. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  3594. if (!PromotedInst)
  3595. return false;
  3596. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  3597. // If the ISDOpcode is undefined, it was undefined before the promotion.
  3598. if (!ISDOpcode)
  3599. return true;
  3600. // Otherwise, check if the promoted instruction is legal or not.
  3601. return TLI.isOperationLegalOrCustom(
  3602. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  3603. }
  3604. namespace {
  3605. /// Hepler class to perform type promotion.
  3606. class TypePromotionHelper {
  3607. /// Utility function to add a promoted instruction \p ExtOpnd to
  3608. /// \p PromotedInsts and record the type of extension we have seen.
  3609. static void addPromotedInst(InstrToOrigTy &PromotedInsts,
  3610. Instruction *ExtOpnd, bool IsSExt) {
  3611. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3612. InstrToOrigTy::iterator It = PromotedInsts.find(ExtOpnd);
  3613. if (It != PromotedInsts.end()) {
  3614. // If the new extension is same as original, the information in
  3615. // PromotedInsts[ExtOpnd] is still correct.
  3616. if (It->second.getInt() == ExtTy)
  3617. return;
  3618. // Now the new extension is different from old extension, we make
  3619. // the type information invalid by setting extension type to
  3620. // BothExtension.
  3621. ExtTy = BothExtension;
  3622. }
  3623. PromotedInsts[ExtOpnd] = TypeIsSExt(ExtOpnd->getType(), ExtTy);
  3624. }
  3625. /// Utility function to query the original type of instruction \p Opnd
  3626. /// with a matched extension type. If the extension doesn't match, we
  3627. /// cannot use the information we had on the original type.
  3628. /// BothExtension doesn't match any extension type.
  3629. static const Type *getOrigType(const InstrToOrigTy &PromotedInsts,
  3630. Instruction *Opnd, bool IsSExt) {
  3631. ExtType ExtTy = IsSExt ? SignExtension : ZeroExtension;
  3632. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  3633. if (It != PromotedInsts.end() && It->second.getInt() == ExtTy)
  3634. return It->second.getPointer();
  3635. return nullptr;
  3636. }
  3637. /// Utility function to check whether or not a sign or zero extension
  3638. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  3639. /// either using the operands of \p Inst or promoting \p Inst.
  3640. /// The type of the extension is defined by \p IsSExt.
  3641. /// In other words, check if:
  3642. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  3643. /// #1 Promotion applies:
  3644. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  3645. /// #2 Operand reuses:
  3646. /// ext opnd1 to ConsideredExtType.
  3647. /// \p PromotedInsts maps the instructions to their type before promotion.
  3648. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  3649. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  3650. /// Utility function to determine if \p OpIdx should be promoted when
  3651. /// promoting \p Inst.
  3652. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  3653. return !(isa<SelectInst>(Inst) && OpIdx == 0);
  3654. }
  3655. /// Utility function to promote the operand of \p Ext when this
  3656. /// operand is a promotable trunc or sext or zext.
  3657. /// \p PromotedInsts maps the instructions to their type before promotion.
  3658. /// \p CreatedInstsCost[out] contains the cost of all instructions
  3659. /// created to promote the operand of Ext.
  3660. /// Newly added extensions are inserted in \p Exts.
  3661. /// Newly added truncates are inserted in \p Truncs.
  3662. /// Should never be called directly.
  3663. /// \return The promoted value which is used instead of Ext.
  3664. static Value *promoteOperandForTruncAndAnyExt(
  3665. Instruction *Ext, TypePromotionTransaction &TPT,
  3666. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3667. SmallVectorImpl<Instruction *> *Exts,
  3668. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  3669. /// Utility function to promote the operand of \p Ext when this
  3670. /// operand is promotable and is not a supported trunc or sext.
  3671. /// \p PromotedInsts maps the instructions to their type before promotion.
  3672. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  3673. /// created to promote the operand of Ext.
  3674. /// Newly added extensions are inserted in \p Exts.
  3675. /// Newly added truncates are inserted in \p Truncs.
  3676. /// Should never be called directly.
  3677. /// \return The promoted value which is used instead of Ext.
  3678. static Value *promoteOperandForOther(Instruction *Ext,
  3679. TypePromotionTransaction &TPT,
  3680. InstrToOrigTy &PromotedInsts,
  3681. unsigned &CreatedInstsCost,
  3682. SmallVectorImpl<Instruction *> *Exts,
  3683. SmallVectorImpl<Instruction *> *Truncs,
  3684. const TargetLowering &TLI, bool IsSExt);
  3685. /// \see promoteOperandForOther.
  3686. static Value *signExtendOperandForOther(
  3687. Instruction *Ext, TypePromotionTransaction &TPT,
  3688. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3689. SmallVectorImpl<Instruction *> *Exts,
  3690. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3691. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3692. Exts, Truncs, TLI, true);
  3693. }
  3694. /// \see promoteOperandForOther.
  3695. static Value *zeroExtendOperandForOther(
  3696. Instruction *Ext, TypePromotionTransaction &TPT,
  3697. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3698. SmallVectorImpl<Instruction *> *Exts,
  3699. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3700. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  3701. Exts, Truncs, TLI, false);
  3702. }
  3703. public:
  3704. /// Type for the utility function that promotes the operand of Ext.
  3705. using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
  3706. InstrToOrigTy &PromotedInsts,
  3707. unsigned &CreatedInstsCost,
  3708. SmallVectorImpl<Instruction *> *Exts,
  3709. SmallVectorImpl<Instruction *> *Truncs,
  3710. const TargetLowering &TLI);
  3711. /// Given a sign/zero extend instruction \p Ext, return the appropriate
  3712. /// action to promote the operand of \p Ext instead of using Ext.
  3713. /// \return NULL if no promotable action is possible with the current
  3714. /// sign extension.
  3715. /// \p InsertedInsts keeps track of all the instructions inserted by the
  3716. /// other CodeGenPrepare optimizations. This information is important
  3717. /// because we do not want to promote these instructions as CodeGenPrepare
  3718. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  3719. /// \p PromotedInsts maps the instructions to their type before promotion.
  3720. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3721. const TargetLowering &TLI,
  3722. const InstrToOrigTy &PromotedInsts);
  3723. };
  3724. } // end anonymous namespace
  3725. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  3726. Type *ConsideredExtType,
  3727. const InstrToOrigTy &PromotedInsts,
  3728. bool IsSExt) {
  3729. // The promotion helper does not know how to deal with vector types yet.
  3730. // To be able to fix that, we would need to fix the places where we
  3731. // statically extend, e.g., constants and such.
  3732. if (Inst->getType()->isVectorTy())
  3733. return false;
  3734. // We can always get through zext.
  3735. if (isa<ZExtInst>(Inst))
  3736. return true;
  3737. // sext(sext) is ok too.
  3738. if (IsSExt && isa<SExtInst>(Inst))
  3739. return true;
  3740. // We can get through binary operator, if it is legal. In other words, the
  3741. // binary operator must have a nuw or nsw flag.
  3742. if (const auto *BinOp = dyn_cast<BinaryOperator>(Inst))
  3743. if (isa<OverflowingBinaryOperator>(BinOp) &&
  3744. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  3745. (IsSExt && BinOp->hasNoSignedWrap())))
  3746. return true;
  3747. // ext(and(opnd, cst)) --> and(ext(opnd), ext(cst))
  3748. if ((Inst->getOpcode() == Instruction::And ||
  3749. Inst->getOpcode() == Instruction::Or))
  3750. return true;
  3751. // ext(xor(opnd, cst)) --> xor(ext(opnd), ext(cst))
  3752. if (Inst->getOpcode() == Instruction::Xor) {
  3753. // Make sure it is not a NOT.
  3754. if (const auto *Cst = dyn_cast<ConstantInt>(Inst->getOperand(1)))
  3755. if (!Cst->getValue().isAllOnes())
  3756. return true;
  3757. }
  3758. // zext(shrl(opnd, cst)) --> shrl(zext(opnd), zext(cst))
  3759. // It may change a poisoned value into a regular value, like
  3760. // zext i32 (shrl i8 %val, 12) --> shrl i32 (zext i8 %val), 12
  3761. // poisoned value regular value
  3762. // It should be OK since undef covers valid value.
  3763. if (Inst->getOpcode() == Instruction::LShr && !IsSExt)
  3764. return true;
  3765. // and(ext(shl(opnd, cst)), cst) --> and(shl(ext(opnd), ext(cst)), cst)
  3766. // It may change a poisoned value into a regular value, like
  3767. // zext i32 (shl i8 %val, 12) --> shl i32 (zext i8 %val), 12
  3768. // poisoned value regular value
  3769. // It should be OK since undef covers valid value.
  3770. if (Inst->getOpcode() == Instruction::Shl && Inst->hasOneUse()) {
  3771. const auto *ExtInst = cast<const Instruction>(*Inst->user_begin());
  3772. if (ExtInst->hasOneUse()) {
  3773. const auto *AndInst = dyn_cast<const Instruction>(*ExtInst->user_begin());
  3774. if (AndInst && AndInst->getOpcode() == Instruction::And) {
  3775. const auto *Cst = dyn_cast<ConstantInt>(AndInst->getOperand(1));
  3776. if (Cst &&
  3777. Cst->getValue().isIntN(Inst->getType()->getIntegerBitWidth()))
  3778. return true;
  3779. }
  3780. }
  3781. }
  3782. // Check if we can do the following simplification.
  3783. // ext(trunc(opnd)) --> ext(opnd)
  3784. if (!isa<TruncInst>(Inst))
  3785. return false;
  3786. Value *OpndVal = Inst->getOperand(0);
  3787. // Check if we can use this operand in the extension.
  3788. // If the type is larger than the result type of the extension, we cannot.
  3789. if (!OpndVal->getType()->isIntegerTy() ||
  3790. OpndVal->getType()->getIntegerBitWidth() >
  3791. ConsideredExtType->getIntegerBitWidth())
  3792. return false;
  3793. // If the operand of the truncate is not an instruction, we will not have
  3794. // any information on the dropped bits.
  3795. // (Actually we could for constant but it is not worth the extra logic).
  3796. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  3797. if (!Opnd)
  3798. return false;
  3799. // Check if the source of the type is narrow enough.
  3800. // I.e., check that trunc just drops extended bits of the same kind of
  3801. // the extension.
  3802. // #1 get the type of the operand and check the kind of the extended bits.
  3803. const Type *OpndType = getOrigType(PromotedInsts, Opnd, IsSExt);
  3804. if (OpndType)
  3805. ;
  3806. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  3807. OpndType = Opnd->getOperand(0)->getType();
  3808. else
  3809. return false;
  3810. // #2 check that the truncate just drops extended bits.
  3811. return Inst->getType()->getIntegerBitWidth() >=
  3812. OpndType->getIntegerBitWidth();
  3813. }
  3814. TypePromotionHelper::Action TypePromotionHelper::getAction(
  3815. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  3816. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  3817. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  3818. "Unexpected instruction type");
  3819. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  3820. Type *ExtTy = Ext->getType();
  3821. bool IsSExt = isa<SExtInst>(Ext);
  3822. // If the operand of the extension is not an instruction, we cannot
  3823. // get through.
  3824. // If it, check we can get through.
  3825. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  3826. return nullptr;
  3827. // Do not promote if the operand has been added by codegenprepare.
  3828. // Otherwise, it means we are undoing an optimization that is likely to be
  3829. // redone, thus causing potential infinite loop.
  3830. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  3831. return nullptr;
  3832. // SExt or Trunc instructions.
  3833. // Return the related handler.
  3834. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  3835. isa<ZExtInst>(ExtOpnd))
  3836. return promoteOperandForTruncAndAnyExt;
  3837. // Regular instruction.
  3838. // Abort early if we will have to insert non-free instructions.
  3839. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  3840. return nullptr;
  3841. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  3842. }
  3843. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  3844. Instruction *SExt, TypePromotionTransaction &TPT,
  3845. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3846. SmallVectorImpl<Instruction *> *Exts,
  3847. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  3848. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  3849. // get through it and this method should not be called.
  3850. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  3851. Value *ExtVal = SExt;
  3852. bool HasMergedNonFreeExt = false;
  3853. if (isa<ZExtInst>(SExtOpnd)) {
  3854. // Replace s|zext(zext(opnd))
  3855. // => zext(opnd).
  3856. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  3857. Value *ZExt =
  3858. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  3859. TPT.replaceAllUsesWith(SExt, ZExt);
  3860. TPT.eraseInstruction(SExt);
  3861. ExtVal = ZExt;
  3862. } else {
  3863. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  3864. // => z|sext(opnd).
  3865. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  3866. }
  3867. CreatedInstsCost = 0;
  3868. // Remove dead code.
  3869. if (SExtOpnd->use_empty())
  3870. TPT.eraseInstruction(SExtOpnd);
  3871. // Check if the extension is still needed.
  3872. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  3873. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  3874. if (ExtInst) {
  3875. if (Exts)
  3876. Exts->push_back(ExtInst);
  3877. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  3878. }
  3879. return ExtVal;
  3880. }
  3881. // At this point we have: ext ty opnd to ty.
  3882. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  3883. Value *NextVal = ExtInst->getOperand(0);
  3884. TPT.eraseInstruction(ExtInst, NextVal);
  3885. return NextVal;
  3886. }
  3887. Value *TypePromotionHelper::promoteOperandForOther(
  3888. Instruction *Ext, TypePromotionTransaction &TPT,
  3889. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3890. SmallVectorImpl<Instruction *> *Exts,
  3891. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  3892. bool IsSExt) {
  3893. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  3894. // get through it and this method should not be called.
  3895. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  3896. CreatedInstsCost = 0;
  3897. if (!ExtOpnd->hasOneUse()) {
  3898. // ExtOpnd will be promoted.
  3899. // All its uses, but Ext, will need to use a truncated value of the
  3900. // promoted version.
  3901. // Create the truncate now.
  3902. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  3903. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  3904. // Insert it just after the definition.
  3905. ITrunc->moveAfter(ExtOpnd);
  3906. if (Truncs)
  3907. Truncs->push_back(ITrunc);
  3908. }
  3909. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  3910. // Restore the operand of Ext (which has been replaced by the previous call
  3911. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  3912. TPT.setOperand(Ext, 0, ExtOpnd);
  3913. }
  3914. // Get through the Instruction:
  3915. // 1. Update its type.
  3916. // 2. Replace the uses of Ext by Inst.
  3917. // 3. Extend each operand that needs to be extended.
  3918. // Remember the original type of the instruction before promotion.
  3919. // This is useful to know that the high bits are sign extended bits.
  3920. addPromotedInst(PromotedInsts, ExtOpnd, IsSExt);
  3921. // Step #1.
  3922. TPT.mutateType(ExtOpnd, Ext->getType());
  3923. // Step #2.
  3924. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  3925. // Step #3.
  3926. Instruction *ExtForOpnd = Ext;
  3927. LLVM_DEBUG(dbgs() << "Propagate Ext to operands\n");
  3928. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  3929. ++OpIdx) {
  3930. LLVM_DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  3931. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  3932. !shouldExtOperand(ExtOpnd, OpIdx)) {
  3933. LLVM_DEBUG(dbgs() << "No need to propagate\n");
  3934. continue;
  3935. }
  3936. // Check if we can statically extend the operand.
  3937. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  3938. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  3939. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3940. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  3941. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  3942. : Cst->getValue().zext(BitWidth);
  3943. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  3944. continue;
  3945. }
  3946. // UndefValue are typed, so we have to statically sign extend them.
  3947. if (isa<UndefValue>(Opnd)) {
  3948. LLVM_DEBUG(dbgs() << "Statically extend\n");
  3949. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  3950. continue;
  3951. }
  3952. // Otherwise we have to explicitly sign extend the operand.
  3953. // Check if Ext was reused to extend an operand.
  3954. if (!ExtForOpnd) {
  3955. // If yes, create a new one.
  3956. LLVM_DEBUG(dbgs() << "More operands to ext\n");
  3957. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  3958. : TPT.createZExt(Ext, Opnd, Ext->getType());
  3959. if (!isa<Instruction>(ValForExtOpnd)) {
  3960. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  3961. continue;
  3962. }
  3963. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  3964. }
  3965. if (Exts)
  3966. Exts->push_back(ExtForOpnd);
  3967. TPT.setOperand(ExtForOpnd, 0, Opnd);
  3968. // Move the sign extension before the insertion point.
  3969. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  3970. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  3971. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  3972. // If more sext are required, new instructions will have to be created.
  3973. ExtForOpnd = nullptr;
  3974. }
  3975. if (ExtForOpnd == Ext) {
  3976. LLVM_DEBUG(dbgs() << "Extension is useless now\n");
  3977. TPT.eraseInstruction(Ext);
  3978. }
  3979. return ExtOpnd;
  3980. }
  3981. /// Check whether or not promoting an instruction to a wider type is profitable.
  3982. /// \p NewCost gives the cost of extension instructions created by the
  3983. /// promotion.
  3984. /// \p OldCost gives the cost of extension instructions before the promotion
  3985. /// plus the number of instructions that have been
  3986. /// matched in the addressing mode the promotion.
  3987. /// \p PromotedOperand is the value that has been promoted.
  3988. /// \return True if the promotion is profitable, false otherwise.
  3989. bool AddressingModeMatcher::isPromotionProfitable(
  3990. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  3991. LLVM_DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost
  3992. << '\n');
  3993. // The cost of the new extensions is greater than the cost of the
  3994. // old extension plus what we folded.
  3995. // This is not profitable.
  3996. if (NewCost > OldCost)
  3997. return false;
  3998. if (NewCost < OldCost)
  3999. return true;
  4000. // The promotion is neutral but it may help folding the sign extension in
  4001. // loads for instance.
  4002. // Check that we did not create an illegal instruction.
  4003. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  4004. }
  4005. /// Given an instruction or constant expr, see if we can fold the operation
  4006. /// into the addressing mode. If so, update the addressing mode and return
  4007. /// true, otherwise return false without modifying AddrMode.
  4008. /// If \p MovedAway is not NULL, it contains the information of whether or
  4009. /// not AddrInst has to be folded into the addressing mode on success.
  4010. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  4011. /// because it has been moved away.
  4012. /// Thus AddrInst must not be added in the matched instructions.
  4013. /// This state can happen when AddrInst is a sext, since it may be moved away.
  4014. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  4015. /// not be referenced anymore.
  4016. bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
  4017. unsigned Depth,
  4018. bool *MovedAway) {
  4019. // Avoid exponential behavior on extremely deep expression trees.
  4020. if (Depth >= 5)
  4021. return false;
  4022. // By default, all matched instructions stay in place.
  4023. if (MovedAway)
  4024. *MovedAway = false;
  4025. switch (Opcode) {
  4026. case Instruction::PtrToInt:
  4027. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  4028. return matchAddr(AddrInst->getOperand(0), Depth);
  4029. case Instruction::IntToPtr: {
  4030. auto AS = AddrInst->getType()->getPointerAddressSpace();
  4031. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  4032. // This inttoptr is a no-op if the integer type is pointer sized.
  4033. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  4034. return matchAddr(AddrInst->getOperand(0), Depth);
  4035. return false;
  4036. }
  4037. case Instruction::BitCast:
  4038. // BitCast is always a noop, and we can handle it as long as it is
  4039. // int->int or pointer->pointer (we don't want int<->fp or something).
  4040. if (AddrInst->getOperand(0)->getType()->isIntOrPtrTy() &&
  4041. // Don't touch identity bitcasts. These were probably put here by LSR,
  4042. // and we don't want to mess around with them. Assume it knows what it
  4043. // is doing.
  4044. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  4045. return matchAddr(AddrInst->getOperand(0), Depth);
  4046. return false;
  4047. case Instruction::AddrSpaceCast: {
  4048. unsigned SrcAS =
  4049. AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  4050. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  4051. if (TLI.getTargetMachine().isNoopAddrSpaceCast(SrcAS, DestAS))
  4052. return matchAddr(AddrInst->getOperand(0), Depth);
  4053. return false;
  4054. }
  4055. case Instruction::Add: {
  4056. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  4057. ExtAddrMode BackupAddrMode = AddrMode;
  4058. unsigned OldSize = AddrModeInsts.size();
  4059. // Start a transaction at this point.
  4060. // The LHS may match but not the RHS.
  4061. // Therefore, we need a higher level restoration point to undo partially
  4062. // matched operation.
  4063. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4064. TPT.getRestorationPoint();
  4065. AddrMode.InBounds = false;
  4066. if (matchAddr(AddrInst->getOperand(1), Depth + 1) &&
  4067. matchAddr(AddrInst->getOperand(0), Depth + 1))
  4068. return true;
  4069. // Restore the old addr mode info.
  4070. AddrMode = BackupAddrMode;
  4071. AddrModeInsts.resize(OldSize);
  4072. TPT.rollback(LastKnownGood);
  4073. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  4074. if (matchAddr(AddrInst->getOperand(0), Depth + 1) &&
  4075. matchAddr(AddrInst->getOperand(1), Depth + 1))
  4076. return true;
  4077. // Otherwise we definitely can't merge the ADD in.
  4078. AddrMode = BackupAddrMode;
  4079. AddrModeInsts.resize(OldSize);
  4080. TPT.rollback(LastKnownGood);
  4081. break;
  4082. }
  4083. // case Instruction::Or:
  4084. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  4085. // break;
  4086. case Instruction::Mul:
  4087. case Instruction::Shl: {
  4088. // Can only handle X*C and X << C.
  4089. AddrMode.InBounds = false;
  4090. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  4091. if (!RHS || RHS->getBitWidth() > 64)
  4092. return false;
  4093. int64_t Scale = Opcode == Instruction::Shl
  4094. ? 1LL << RHS->getLimitedValue(RHS->getBitWidth() - 1)
  4095. : RHS->getSExtValue();
  4096. return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  4097. }
  4098. case Instruction::GetElementPtr: {
  4099. // Scan the GEP. We check it if it contains constant offsets and at most
  4100. // one variable offset.
  4101. int VariableOperand = -1;
  4102. unsigned VariableScale = 0;
  4103. int64_t ConstantOffset = 0;
  4104. gep_type_iterator GTI = gep_type_begin(AddrInst);
  4105. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  4106. if (StructType *STy = GTI.getStructTypeOrNull()) {
  4107. const StructLayout *SL = DL.getStructLayout(STy);
  4108. unsigned Idx =
  4109. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  4110. ConstantOffset += SL->getElementOffset(Idx);
  4111. } else {
  4112. TypeSize TS = DL.getTypeAllocSize(GTI.getIndexedType());
  4113. if (TS.isNonZero()) {
  4114. // The optimisations below currently only work for fixed offsets.
  4115. if (TS.isScalable())
  4116. return false;
  4117. int64_t TypeSize = TS.getFixedValue();
  4118. if (ConstantInt *CI =
  4119. dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  4120. const APInt &CVal = CI->getValue();
  4121. if (CVal.getMinSignedBits() <= 64) {
  4122. ConstantOffset += CVal.getSExtValue() * TypeSize;
  4123. continue;
  4124. }
  4125. }
  4126. // We only allow one variable index at the moment.
  4127. if (VariableOperand != -1)
  4128. return false;
  4129. // Remember the variable index.
  4130. VariableOperand = i;
  4131. VariableScale = TypeSize;
  4132. }
  4133. }
  4134. }
  4135. // A common case is for the GEP to only do a constant offset. In this case,
  4136. // just add it to the disp field and check validity.
  4137. if (VariableOperand == -1) {
  4138. AddrMode.BaseOffs += ConstantOffset;
  4139. if (ConstantOffset == 0 ||
  4140. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  4141. // Check to see if we can fold the base pointer in too.
  4142. if (matchAddr(AddrInst->getOperand(0), Depth + 1)) {
  4143. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  4144. AddrMode.InBounds = false;
  4145. return true;
  4146. }
  4147. } else if (EnableGEPOffsetSplit && isa<GetElementPtrInst>(AddrInst) &&
  4148. TLI.shouldConsiderGEPOffsetSplit() && Depth == 0 &&
  4149. ConstantOffset > 0) {
  4150. // Record GEPs with non-zero offsets as candidates for splitting in the
  4151. // event that the offset cannot fit into the r+i addressing mode.
  4152. // Simple and common case that only one GEP is used in calculating the
  4153. // address for the memory access.
  4154. Value *Base = AddrInst->getOperand(0);
  4155. auto *BaseI = dyn_cast<Instruction>(Base);
  4156. auto *GEP = cast<GetElementPtrInst>(AddrInst);
  4157. if (isa<Argument>(Base) || isa<GlobalValue>(Base) ||
  4158. (BaseI && !isa<CastInst>(BaseI) &&
  4159. !isa<GetElementPtrInst>(BaseI))) {
  4160. // Make sure the parent block allows inserting non-PHI instructions
  4161. // before the terminator.
  4162. BasicBlock *Parent =
  4163. BaseI ? BaseI->getParent() : &GEP->getFunction()->getEntryBlock();
  4164. if (!Parent->getTerminator()->isEHPad())
  4165. LargeOffsetGEP = std::make_pair(GEP, ConstantOffset);
  4166. }
  4167. }
  4168. AddrMode.BaseOffs -= ConstantOffset;
  4169. return false;
  4170. }
  4171. // Save the valid addressing mode in case we can't match.
  4172. ExtAddrMode BackupAddrMode = AddrMode;
  4173. unsigned OldSize = AddrModeInsts.size();
  4174. // See if the scale and offset amount is valid for this target.
  4175. AddrMode.BaseOffs += ConstantOffset;
  4176. if (!cast<GEPOperator>(AddrInst)->isInBounds())
  4177. AddrMode.InBounds = false;
  4178. // Match the base operand of the GEP.
  4179. if (!matchAddr(AddrInst->getOperand(0), Depth + 1)) {
  4180. // If it couldn't be matched, just stuff the value in a register.
  4181. if (AddrMode.HasBaseReg) {
  4182. AddrMode = BackupAddrMode;
  4183. AddrModeInsts.resize(OldSize);
  4184. return false;
  4185. }
  4186. AddrMode.HasBaseReg = true;
  4187. AddrMode.BaseReg = AddrInst->getOperand(0);
  4188. }
  4189. // Match the remaining variable portion of the GEP.
  4190. if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  4191. Depth)) {
  4192. // If it couldn't be matched, try stuffing the base into a register
  4193. // instead of matching it, and retrying the match of the scale.
  4194. AddrMode = BackupAddrMode;
  4195. AddrModeInsts.resize(OldSize);
  4196. if (AddrMode.HasBaseReg)
  4197. return false;
  4198. AddrMode.HasBaseReg = true;
  4199. AddrMode.BaseReg = AddrInst->getOperand(0);
  4200. AddrMode.BaseOffs += ConstantOffset;
  4201. if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
  4202. VariableScale, Depth)) {
  4203. // If even that didn't work, bail.
  4204. AddrMode = BackupAddrMode;
  4205. AddrModeInsts.resize(OldSize);
  4206. return false;
  4207. }
  4208. }
  4209. return true;
  4210. }
  4211. case Instruction::SExt:
  4212. case Instruction::ZExt: {
  4213. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  4214. if (!Ext)
  4215. return false;
  4216. // Try to move this ext out of the way of the addressing mode.
  4217. // Ask for a method for doing so.
  4218. TypePromotionHelper::Action TPH =
  4219. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  4220. if (!TPH)
  4221. return false;
  4222. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4223. TPT.getRestorationPoint();
  4224. unsigned CreatedInstsCost = 0;
  4225. unsigned ExtCost = !TLI.isExtFree(Ext);
  4226. Value *PromotedOperand =
  4227. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  4228. // SExt has been moved away.
  4229. // Thus either it will be rematched later in the recursive calls or it is
  4230. // gone. Anyway, we must not fold it into the addressing mode at this point.
  4231. // E.g.,
  4232. // op = add opnd, 1
  4233. // idx = ext op
  4234. // addr = gep base, idx
  4235. // is now:
  4236. // promotedOpnd = ext opnd <- no match here
  4237. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  4238. // addr = gep base, op <- match
  4239. if (MovedAway)
  4240. *MovedAway = true;
  4241. assert(PromotedOperand &&
  4242. "TypePromotionHelper should have filtered out those cases");
  4243. ExtAddrMode BackupAddrMode = AddrMode;
  4244. unsigned OldSize = AddrModeInsts.size();
  4245. if (!matchAddr(PromotedOperand, Depth) ||
  4246. // The total of the new cost is equal to the cost of the created
  4247. // instructions.
  4248. // The total of the old cost is equal to the cost of the extension plus
  4249. // what we have saved in the addressing mode.
  4250. !isPromotionProfitable(CreatedInstsCost,
  4251. ExtCost + (AddrModeInsts.size() - OldSize),
  4252. PromotedOperand)) {
  4253. AddrMode = BackupAddrMode;
  4254. AddrModeInsts.resize(OldSize);
  4255. LLVM_DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  4256. TPT.rollback(LastKnownGood);
  4257. return false;
  4258. }
  4259. return true;
  4260. }
  4261. }
  4262. return false;
  4263. }
  4264. /// If we can, try to add the value of 'Addr' into the current addressing mode.
  4265. /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
  4266. /// unmodified. This assumes that Addr is either a pointer type or intptr_t
  4267. /// for the target.
  4268. ///
  4269. bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
  4270. // Start a transaction at this point that we will rollback if the matching
  4271. // fails.
  4272. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4273. TPT.getRestorationPoint();
  4274. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  4275. if (CI->getValue().isSignedIntN(64)) {
  4276. // Fold in immediates if legal for the target.
  4277. AddrMode.BaseOffs += CI->getSExtValue();
  4278. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  4279. return true;
  4280. AddrMode.BaseOffs -= CI->getSExtValue();
  4281. }
  4282. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  4283. // If this is a global variable, try to fold it into the addressing mode.
  4284. if (!AddrMode.BaseGV) {
  4285. AddrMode.BaseGV = GV;
  4286. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  4287. return true;
  4288. AddrMode.BaseGV = nullptr;
  4289. }
  4290. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  4291. ExtAddrMode BackupAddrMode = AddrMode;
  4292. unsigned OldSize = AddrModeInsts.size();
  4293. // Check to see if it is possible to fold this operation.
  4294. bool MovedAway = false;
  4295. if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  4296. // This instruction may have been moved away. If so, there is nothing
  4297. // to check here.
  4298. if (MovedAway)
  4299. return true;
  4300. // Okay, it's possible to fold this. Check to see if it is actually
  4301. // *profitable* to do so. We use a simple cost model to avoid increasing
  4302. // register pressure too much.
  4303. if (I->hasOneUse() ||
  4304. isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  4305. AddrModeInsts.push_back(I);
  4306. return true;
  4307. }
  4308. // It isn't profitable to do this, roll back.
  4309. AddrMode = BackupAddrMode;
  4310. AddrModeInsts.resize(OldSize);
  4311. TPT.rollback(LastKnownGood);
  4312. }
  4313. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  4314. if (matchOperationAddr(CE, CE->getOpcode(), Depth))
  4315. return true;
  4316. TPT.rollback(LastKnownGood);
  4317. } else if (isa<ConstantPointerNull>(Addr)) {
  4318. // Null pointer gets folded without affecting the addressing mode.
  4319. return true;
  4320. }
  4321. // Worse case, the target should support [reg] addressing modes. :)
  4322. if (!AddrMode.HasBaseReg) {
  4323. AddrMode.HasBaseReg = true;
  4324. AddrMode.BaseReg = Addr;
  4325. // Still check for legality in case the target supports [imm] but not [i+r].
  4326. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  4327. return true;
  4328. AddrMode.HasBaseReg = false;
  4329. AddrMode.BaseReg = nullptr;
  4330. }
  4331. // If the base register is already taken, see if we can do [r+r].
  4332. if (AddrMode.Scale == 0) {
  4333. AddrMode.Scale = 1;
  4334. AddrMode.ScaledReg = Addr;
  4335. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  4336. return true;
  4337. AddrMode.Scale = 0;
  4338. AddrMode.ScaledReg = nullptr;
  4339. }
  4340. // Couldn't match.
  4341. TPT.rollback(LastKnownGood);
  4342. return false;
  4343. }
  4344. /// Check to see if all uses of OpVal by the specified inline asm call are due
  4345. /// to memory operands. If so, return true, otherwise return false.
  4346. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  4347. const TargetLowering &TLI,
  4348. const TargetRegisterInfo &TRI) {
  4349. const Function *F = CI->getFunction();
  4350. TargetLowering::AsmOperandInfoVector TargetConstraints =
  4351. TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI, *CI);
  4352. for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
  4353. // Compute the constraint code and ConstraintType to use.
  4354. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  4355. // If this asm operand is our Value*, and if it isn't an indirect memory
  4356. // operand, we can't fold it! TODO: Also handle C_Address?
  4357. if (OpInfo.CallOperandVal == OpVal &&
  4358. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  4359. !OpInfo.isIndirect))
  4360. return false;
  4361. }
  4362. return true;
  4363. }
  4364. // Max number of memory uses to look at before aborting the search to conserve
  4365. // compile time.
  4366. static constexpr int MaxMemoryUsesToScan = 20;
  4367. /// Recursively walk all the uses of I until we find a memory use.
  4368. /// If we find an obviously non-foldable instruction, return true.
  4369. /// Add accessed addresses and types to MemoryUses.
  4370. static bool FindAllMemoryUses(
  4371. Instruction *I, SmallVectorImpl<std::pair<Value *, Type *>> &MemoryUses,
  4372. SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
  4373. const TargetRegisterInfo &TRI, bool OptSize, ProfileSummaryInfo *PSI,
  4374. BlockFrequencyInfo *BFI, int SeenInsts = 0) {
  4375. // If we already considered this instruction, we're done.
  4376. if (!ConsideredInsts.insert(I).second)
  4377. return false;
  4378. // If this is an obviously unfoldable instruction, bail out.
  4379. if (!MightBeFoldableInst(I))
  4380. return true;
  4381. // Loop over all the uses, recursively processing them.
  4382. for (Use &U : I->uses()) {
  4383. // Conservatively return true if we're seeing a large number or a deep chain
  4384. // of users. This avoids excessive compilation times in pathological cases.
  4385. if (SeenInsts++ >= MaxMemoryUsesToScan)
  4386. return true;
  4387. Instruction *UserI = cast<Instruction>(U.getUser());
  4388. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  4389. MemoryUses.push_back({U.get(), LI->getType()});
  4390. continue;
  4391. }
  4392. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  4393. if (U.getOperandNo() != StoreInst::getPointerOperandIndex())
  4394. return true; // Storing addr, not into addr.
  4395. MemoryUses.push_back({U.get(), SI->getValueOperand()->getType()});
  4396. continue;
  4397. }
  4398. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
  4399. if (U.getOperandNo() != AtomicRMWInst::getPointerOperandIndex())
  4400. return true; // Storing addr, not into addr.
  4401. MemoryUses.push_back({U.get(), RMW->getValOperand()->getType()});
  4402. continue;
  4403. }
  4404. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
  4405. if (U.getOperandNo() != AtomicCmpXchgInst::getPointerOperandIndex())
  4406. return true; // Storing addr, not into addr.
  4407. MemoryUses.push_back({U.get(), CmpX->getCompareOperand()->getType()});
  4408. continue;
  4409. }
  4410. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  4411. if (CI->hasFnAttr(Attribute::Cold)) {
  4412. // If this is a cold call, we can sink the addressing calculation into
  4413. // the cold path. See optimizeCallInst
  4414. bool OptForSize =
  4415. OptSize || llvm::shouldOptimizeForSize(CI->getParent(), PSI, BFI);
  4416. if (!OptForSize)
  4417. continue;
  4418. }
  4419. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledOperand());
  4420. if (!IA)
  4421. return true;
  4422. // If this is a memory operand, we're cool, otherwise bail out.
  4423. if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
  4424. return true;
  4425. continue;
  4426. }
  4427. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI, OptSize,
  4428. PSI, BFI, SeenInsts))
  4429. return true;
  4430. }
  4431. return false;
  4432. }
  4433. /// Return true if Val is already known to be live at the use site that we're
  4434. /// folding it into. If so, there is no cost to include it in the addressing
  4435. /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
  4436. /// instruction already.
  4437. bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,
  4438. Value *KnownLive1,
  4439. Value *KnownLive2) {
  4440. // If Val is either of the known-live values, we know it is live!
  4441. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  4442. return true;
  4443. // All values other than instructions and arguments (e.g. constants) are live.
  4444. if (!isa<Instruction>(Val) && !isa<Argument>(Val))
  4445. return true;
  4446. // If Val is a constant sized alloca in the entry block, it is live, this is
  4447. // true because it is just a reference to the stack/frame pointer, which is
  4448. // live for the whole function.
  4449. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  4450. if (AI->isStaticAlloca())
  4451. return true;
  4452. // Check to see if this value is already used in the memory instruction's
  4453. // block. If so, it's already live into the block at the very least, so we
  4454. // can reasonably fold it.
  4455. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  4456. }
  4457. /// It is possible for the addressing mode of the machine to fold the specified
  4458. /// instruction into a load or store that ultimately uses it.
  4459. /// However, the specified instruction has multiple uses.
  4460. /// Given this, it may actually increase register pressure to fold it
  4461. /// into the load. For example, consider this code:
  4462. ///
  4463. /// X = ...
  4464. /// Y = X+1
  4465. /// use(Y) -> nonload/store
  4466. /// Z = Y+1
  4467. /// load Z
  4468. ///
  4469. /// In this case, Y has multiple uses, and can be folded into the load of Z
  4470. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  4471. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  4472. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  4473. /// number of computations either.
  4474. ///
  4475. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  4476. /// X was live across 'load Z' for other reasons, we actually *would* want to
  4477. /// fold the addressing mode in the Z case. This would make Y die earlier.
  4478. bool AddressingModeMatcher::isProfitableToFoldIntoAddressingMode(
  4479. Instruction *I, ExtAddrMode &AMBefore, ExtAddrMode &AMAfter) {
  4480. if (IgnoreProfitability)
  4481. return true;
  4482. // AMBefore is the addressing mode before this instruction was folded into it,
  4483. // and AMAfter is the addressing mode after the instruction was folded. Get
  4484. // the set of registers referenced by AMAfter and subtract out those
  4485. // referenced by AMBefore: this is the set of values which folding in this
  4486. // address extends the lifetime of.
  4487. //
  4488. // Note that there are only two potential values being referenced here,
  4489. // BaseReg and ScaleReg (global addresses are always available, as are any
  4490. // folded immediates).
  4491. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  4492. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  4493. // lifetime wasn't extended by adding this instruction.
  4494. if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  4495. BaseReg = nullptr;
  4496. if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  4497. ScaledReg = nullptr;
  4498. // If folding this instruction (and it's subexprs) didn't extend any live
  4499. // ranges, we're ok with it.
  4500. if (!BaseReg && !ScaledReg)
  4501. return true;
  4502. // If all uses of this instruction can have the address mode sunk into them,
  4503. // we can remove the addressing mode and effectively trade one live register
  4504. // for another (at worst.) In this context, folding an addressing mode into
  4505. // the use is just a particularly nice way of sinking it.
  4506. SmallVector<std::pair<Value *, Type *>, 16> MemoryUses;
  4507. SmallPtrSet<Instruction *, 16> ConsideredInsts;
  4508. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI, OptSize, PSI,
  4509. BFI))
  4510. return false; // Has a non-memory, non-foldable use!
  4511. // Now that we know that all uses of this instruction are part of a chain of
  4512. // computation involving only operations that could theoretically be folded
  4513. // into a memory use, loop over each of these memory operation uses and see
  4514. // if they could *actually* fold the instruction. The assumption is that
  4515. // addressing modes are cheap and that duplicating the computation involved
  4516. // many times is worthwhile, even on a fastpath. For sinking candidates
  4517. // (i.e. cold call sites), this serves as a way to prevent excessive code
  4518. // growth since most architectures have some reasonable small and fast way to
  4519. // compute an effective address. (i.e LEA on x86)
  4520. SmallVector<Instruction *, 32> MatchedAddrModeInsts;
  4521. for (const std::pair<Value *, Type *> &Pair : MemoryUses) {
  4522. Value *Address = Pair.first;
  4523. Type *AddressAccessTy = Pair.second;
  4524. unsigned AS = Address->getType()->getPointerAddressSpace();
  4525. // Do a match against the root of this address, ignoring profitability. This
  4526. // will tell us if the addressing mode for the memory operation will
  4527. // *actually* cover the shared instruction.
  4528. ExtAddrMode Result;
  4529. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4530. 0);
  4531. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4532. TPT.getRestorationPoint();
  4533. AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI, LI, getDTFn,
  4534. AddressAccessTy, AS, MemoryInst, Result,
  4535. InsertedInsts, PromotedInsts, TPT,
  4536. LargeOffsetGEP, OptSize, PSI, BFI);
  4537. Matcher.IgnoreProfitability = true;
  4538. bool Success = Matcher.matchAddr(Address, 0);
  4539. (void)Success;
  4540. assert(Success && "Couldn't select *anything*?");
  4541. // The match was to check the profitability, the changes made are not
  4542. // part of the original matcher. Therefore, they should be dropped
  4543. // otherwise the original matcher will not present the right state.
  4544. TPT.rollback(LastKnownGood);
  4545. // If the match didn't cover I, then it won't be shared by it.
  4546. if (!is_contained(MatchedAddrModeInsts, I))
  4547. return false;
  4548. MatchedAddrModeInsts.clear();
  4549. }
  4550. return true;
  4551. }
  4552. /// Return true if the specified values are defined in a
  4553. /// different basic block than BB.
  4554. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  4555. if (Instruction *I = dyn_cast<Instruction>(V))
  4556. return I->getParent() != BB;
  4557. return false;
  4558. }
  4559. /// Sink addressing mode computation immediate before MemoryInst if doing so
  4560. /// can be done without increasing register pressure. The need for the
  4561. /// register pressure constraint means this can end up being an all or nothing
  4562. /// decision for all uses of the same addressing computation.
  4563. ///
  4564. /// Load and Store Instructions often have addressing modes that can do
  4565. /// significant amounts of computation. As such, instruction selection will try
  4566. /// to get the load or store to do as much computation as possible for the
  4567. /// program. The problem is that isel can only see within a single block. As
  4568. /// such, we sink as much legal addressing mode work into the block as possible.
  4569. ///
  4570. /// This method is used to optimize both load/store and inline asms with memory
  4571. /// operands. It's also used to sink addressing computations feeding into cold
  4572. /// call sites into their (cold) basic block.
  4573. ///
  4574. /// The motivation for handling sinking into cold blocks is that doing so can
  4575. /// both enable other address mode sinking (by satisfying the register pressure
  4576. /// constraint above), and reduce register pressure globally (by removing the
  4577. /// addressing mode computation from the fast path entirely.).
  4578. bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  4579. Type *AccessTy, unsigned AddrSpace) {
  4580. Value *Repl = Addr;
  4581. // Try to collapse single-value PHI nodes. This is necessary to undo
  4582. // unprofitable PRE transformations.
  4583. SmallVector<Value *, 8> worklist;
  4584. SmallPtrSet<Value *, 16> Visited;
  4585. worklist.push_back(Addr);
  4586. // Use a worklist to iteratively look through PHI and select nodes, and
  4587. // ensure that the addressing mode obtained from the non-PHI/select roots of
  4588. // the graph are compatible.
  4589. bool PhiOrSelectSeen = false;
  4590. SmallVector<Instruction *, 16> AddrModeInsts;
  4591. const SimplifyQuery SQ(*DL, TLInfo);
  4592. AddressingModeCombiner AddrModes(SQ, Addr);
  4593. TypePromotionTransaction TPT(RemovedInsts);
  4594. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4595. TPT.getRestorationPoint();
  4596. while (!worklist.empty()) {
  4597. Value *V = worklist.pop_back_val();
  4598. // We allow traversing cyclic Phi nodes.
  4599. // In case of success after this loop we ensure that traversing through
  4600. // Phi nodes ends up with all cases to compute address of the form
  4601. // BaseGV + Base + Scale * Index + Offset
  4602. // where Scale and Offset are constans and BaseGV, Base and Index
  4603. // are exactly the same Values in all cases.
  4604. // It means that BaseGV, Scale and Offset dominate our memory instruction
  4605. // and have the same value as they had in address computation represented
  4606. // as Phi. So we can safely sink address computation to memory instruction.
  4607. if (!Visited.insert(V).second)
  4608. continue;
  4609. // For a PHI node, push all of its incoming values.
  4610. if (PHINode *P = dyn_cast<PHINode>(V)) {
  4611. append_range(worklist, P->incoming_values());
  4612. PhiOrSelectSeen = true;
  4613. continue;
  4614. }
  4615. // Similar for select.
  4616. if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  4617. worklist.push_back(SI->getFalseValue());
  4618. worklist.push_back(SI->getTrueValue());
  4619. PhiOrSelectSeen = true;
  4620. continue;
  4621. }
  4622. // For non-PHIs, determine the addressing mode being computed. Note that
  4623. // the result may differ depending on what other uses our candidate
  4624. // addressing instructions might have.
  4625. AddrModeInsts.clear();
  4626. std::pair<AssertingVH<GetElementPtrInst>, int64_t> LargeOffsetGEP(nullptr,
  4627. 0);
  4628. // Defer the query (and possible computation of) the dom tree to point of
  4629. // actual use. It's expected that most address matches don't actually need
  4630. // the domtree.
  4631. auto getDTFn = [MemoryInst, this]() -> const DominatorTree & {
  4632. Function *F = MemoryInst->getParent()->getParent();
  4633. return this->getDT(*F);
  4634. };
  4635. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  4636. V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *LI, getDTFn,
  4637. *TRI, InsertedInsts, PromotedInsts, TPT, LargeOffsetGEP, OptSize, PSI,
  4638. BFI.get());
  4639. GetElementPtrInst *GEP = LargeOffsetGEP.first;
  4640. if (GEP && !NewGEPBases.count(GEP)) {
  4641. // If splitting the underlying data structure can reduce the offset of a
  4642. // GEP, collect the GEP. Skip the GEPs that are the new bases of
  4643. // previously split data structures.
  4644. LargeOffsetGEPMap[GEP->getPointerOperand()].push_back(LargeOffsetGEP);
  4645. LargeOffsetGEPID.insert(std::make_pair(GEP, LargeOffsetGEPID.size()));
  4646. }
  4647. NewAddrMode.OriginalValue = V;
  4648. if (!AddrModes.addNewAddrMode(NewAddrMode))
  4649. break;
  4650. }
  4651. // Try to combine the AddrModes we've collected. If we couldn't collect any,
  4652. // or we have multiple but either couldn't combine them or combining them
  4653. // wouldn't do anything useful, bail out now.
  4654. if (!AddrModes.combineAddrModes()) {
  4655. TPT.rollback(LastKnownGood);
  4656. return false;
  4657. }
  4658. bool Modified = TPT.commit();
  4659. // Get the combined AddrMode (or the only AddrMode, if we only had one).
  4660. ExtAddrMode AddrMode = AddrModes.getAddrMode();
  4661. // If all the instructions matched are already in this BB, don't do anything.
  4662. // If we saw a Phi node then it is not local definitely, and if we saw a
  4663. // select then we want to push the address calculation past it even if it's
  4664. // already in this BB.
  4665. if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
  4666. return IsNonLocalValue(V, MemoryInst->getParent());
  4667. })) {
  4668. LLVM_DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode
  4669. << "\n");
  4670. return Modified;
  4671. }
  4672. // Insert this computation right after this user. Since our caller is
  4673. // scanning from the top of the BB to the bottom, reuse of the expr are
  4674. // guaranteed to happen later.
  4675. IRBuilder<> Builder(MemoryInst);
  4676. // Now that we determined the addressing expression we want to use and know
  4677. // that we have to sink it into this block. Check to see if we have already
  4678. // done this for some other load/store instr in this block. If so, reuse
  4679. // the computation. Before attempting reuse, check if the address is valid
  4680. // as it may have been erased.
  4681. WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
  4682. Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
  4683. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4684. if (SunkAddr) {
  4685. LLVM_DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode
  4686. << " for " << *MemoryInst << "\n");
  4687. if (SunkAddr->getType() != Addr->getType()) {
  4688. if (SunkAddr->getType()->getPointerAddressSpace() !=
  4689. Addr->getType()->getPointerAddressSpace() &&
  4690. !DL->isNonIntegralPointerType(Addr->getType())) {
  4691. // There are two reasons the address spaces might not match: a no-op
  4692. // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
  4693. // ptrtoint/inttoptr pair to ensure we match the original semantics.
  4694. // TODO: allow bitcast between different address space pointers with the
  4695. // same size.
  4696. SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
  4697. SunkAddr =
  4698. Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
  4699. } else
  4700. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4701. }
  4702. } else if (AddrSinkUsingGEPs || (!AddrSinkUsingGEPs.getNumOccurrences() &&
  4703. SubtargetInfo->addrSinkUsingGEPs())) {
  4704. // By default, we use the GEP-based method when AA is used later. This
  4705. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  4706. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4707. << " for " << *MemoryInst << "\n");
  4708. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  4709. // First, find the pointer.
  4710. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  4711. ResultPtr = AddrMode.BaseReg;
  4712. AddrMode.BaseReg = nullptr;
  4713. }
  4714. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  4715. // We can't add more than one pointer together, nor can we scale a
  4716. // pointer (both of which seem meaningless).
  4717. if (ResultPtr || AddrMode.Scale != 1)
  4718. return Modified;
  4719. ResultPtr = AddrMode.ScaledReg;
  4720. AddrMode.Scale = 0;
  4721. }
  4722. // It is only safe to sign extend the BaseReg if we know that the math
  4723. // required to create it did not overflow before we extend it. Since
  4724. // the original IR value was tossed in favor of a constant back when
  4725. // the AddrMode was created we need to bail out gracefully if widths
  4726. // do not match instead of extending it.
  4727. //
  4728. // (See below for code to add the scale.)
  4729. if (AddrMode.Scale) {
  4730. Type *ScaledRegTy = AddrMode.ScaledReg->getType();
  4731. if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
  4732. cast<IntegerType>(ScaledRegTy)->getBitWidth())
  4733. return Modified;
  4734. }
  4735. if (AddrMode.BaseGV) {
  4736. if (ResultPtr)
  4737. return Modified;
  4738. ResultPtr = AddrMode.BaseGV;
  4739. }
  4740. // If the real base value actually came from an inttoptr, then the matcher
  4741. // will look through it and provide only the integer value. In that case,
  4742. // use it here.
  4743. if (!DL->isNonIntegralPointerType(Addr->getType())) {
  4744. if (!ResultPtr && AddrMode.BaseReg) {
  4745. ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
  4746. "sunkaddr");
  4747. AddrMode.BaseReg = nullptr;
  4748. } else if (!ResultPtr && AddrMode.Scale == 1) {
  4749. ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
  4750. "sunkaddr");
  4751. AddrMode.Scale = 0;
  4752. }
  4753. }
  4754. if (!ResultPtr && !AddrMode.BaseReg && !AddrMode.Scale &&
  4755. !AddrMode.BaseOffs) {
  4756. SunkAddr = Constant::getNullValue(Addr->getType());
  4757. } else if (!ResultPtr) {
  4758. return Modified;
  4759. } else {
  4760. Type *I8PtrTy =
  4761. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  4762. Type *I8Ty = Builder.getInt8Ty();
  4763. // Start with the base register. Do this first so that subsequent address
  4764. // matching finds it last, which will prevent it from trying to match it
  4765. // as the scaled value in case it happens to be a mul. That would be
  4766. // problematic if we've sunk a different mul for the scale, because then
  4767. // we'd end up sinking both muls.
  4768. if (AddrMode.BaseReg) {
  4769. Value *V = AddrMode.BaseReg;
  4770. if (V->getType() != IntPtrTy)
  4771. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4772. ResultIndex = V;
  4773. }
  4774. // Add the scale value.
  4775. if (AddrMode.Scale) {
  4776. Value *V = AddrMode.ScaledReg;
  4777. if (V->getType() == IntPtrTy) {
  4778. // done.
  4779. } else {
  4780. assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4781. cast<IntegerType>(V->getType())->getBitWidth() &&
  4782. "We can't transform if ScaledReg is too narrow");
  4783. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4784. }
  4785. if (AddrMode.Scale != 1)
  4786. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4787. "sunkaddr");
  4788. if (ResultIndex)
  4789. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  4790. else
  4791. ResultIndex = V;
  4792. }
  4793. // Add in the Base Offset if present.
  4794. if (AddrMode.BaseOffs) {
  4795. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4796. if (ResultIndex) {
  4797. // We need to add this separately from the scale above to help with
  4798. // SDAG consecutive load/store merging.
  4799. if (ResultPtr->getType() != I8PtrTy)
  4800. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4801. ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex,
  4802. "sunkaddr", AddrMode.InBounds);
  4803. }
  4804. ResultIndex = V;
  4805. }
  4806. if (!ResultIndex) {
  4807. SunkAddr = ResultPtr;
  4808. } else {
  4809. if (ResultPtr->getType() != I8PtrTy)
  4810. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  4811. SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr",
  4812. AddrMode.InBounds);
  4813. }
  4814. if (SunkAddr->getType() != Addr->getType()) {
  4815. if (SunkAddr->getType()->getPointerAddressSpace() !=
  4816. Addr->getType()->getPointerAddressSpace() &&
  4817. !DL->isNonIntegralPointerType(Addr->getType())) {
  4818. // There are two reasons the address spaces might not match: a no-op
  4819. // addrspacecast, or a ptrtoint/inttoptr pair. Either way, we emit a
  4820. // ptrtoint/inttoptr pair to ensure we match the original semantics.
  4821. // TODO: allow bitcast between different address space pointers with
  4822. // the same size.
  4823. SunkAddr = Builder.CreatePtrToInt(SunkAddr, IntPtrTy, "sunkaddr");
  4824. SunkAddr =
  4825. Builder.CreateIntToPtr(SunkAddr, Addr->getType(), "sunkaddr");
  4826. } else
  4827. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  4828. }
  4829. }
  4830. } else {
  4831. // We'd require a ptrtoint/inttoptr down the line, which we can't do for
  4832. // non-integral pointers, so in that case bail out now.
  4833. Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
  4834. Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
  4835. PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
  4836. PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
  4837. if (DL->isNonIntegralPointerType(Addr->getType()) ||
  4838. (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
  4839. (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
  4840. (AddrMode.BaseGV &&
  4841. DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
  4842. return Modified;
  4843. LLVM_DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode
  4844. << " for " << *MemoryInst << "\n");
  4845. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  4846. Value *Result = nullptr;
  4847. // Start with the base register. Do this first so that subsequent address
  4848. // matching finds it last, which will prevent it from trying to match it
  4849. // as the scaled value in case it happens to be a mul. That would be
  4850. // problematic if we've sunk a different mul for the scale, because then
  4851. // we'd end up sinking both muls.
  4852. if (AddrMode.BaseReg) {
  4853. Value *V = AddrMode.BaseReg;
  4854. if (V->getType()->isPointerTy())
  4855. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4856. if (V->getType() != IntPtrTy)
  4857. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  4858. Result = V;
  4859. }
  4860. // Add the scale value.
  4861. if (AddrMode.Scale) {
  4862. Value *V = AddrMode.ScaledReg;
  4863. if (V->getType() == IntPtrTy) {
  4864. // done.
  4865. } else if (V->getType()->isPointerTy()) {
  4866. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  4867. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  4868. cast<IntegerType>(V->getType())->getBitWidth()) {
  4869. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  4870. } else {
  4871. // It is only safe to sign extend the BaseReg if we know that the math
  4872. // required to create it did not overflow before we extend it. Since
  4873. // the original IR value was tossed in favor of a constant back when
  4874. // the AddrMode was created we need to bail out gracefully if widths
  4875. // do not match instead of extending it.
  4876. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  4877. if (I && (Result != AddrMode.BaseReg))
  4878. I->eraseFromParent();
  4879. return Modified;
  4880. }
  4881. if (AddrMode.Scale != 1)
  4882. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  4883. "sunkaddr");
  4884. if (Result)
  4885. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4886. else
  4887. Result = V;
  4888. }
  4889. // Add in the BaseGV if present.
  4890. if (AddrMode.BaseGV) {
  4891. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  4892. if (Result)
  4893. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4894. else
  4895. Result = V;
  4896. }
  4897. // Add in the Base Offset if present.
  4898. if (AddrMode.BaseOffs) {
  4899. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  4900. if (Result)
  4901. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  4902. else
  4903. Result = V;
  4904. }
  4905. if (!Result)
  4906. SunkAddr = Constant::getNullValue(Addr->getType());
  4907. else
  4908. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  4909. }
  4910. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  4911. // Store the newly computed address into the cache. In the case we reused a
  4912. // value, this should be idempotent.
  4913. SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
  4914. // If we have no uses, recursively delete the value and all dead instructions
  4915. // using it.
  4916. if (Repl->use_empty()) {
  4917. resetIteratorIfInvalidatedWhileCalling(CurInstIterator->getParent(), [&]() {
  4918. RecursivelyDeleteTriviallyDeadInstructions(
  4919. Repl, TLInfo, nullptr,
  4920. [&](Value *V) { removeAllAssertingVHReferences(V); });
  4921. });
  4922. }
  4923. ++NumMemoryInsts;
  4924. return true;
  4925. }
  4926. /// Rewrite GEP input to gather/scatter to enable SelectionDAGBuilder to find
  4927. /// a uniform base to use for ISD::MGATHER/MSCATTER. SelectionDAGBuilder can
  4928. /// only handle a 2 operand GEP in the same basic block or a splat constant
  4929. /// vector. The 2 operands to the GEP must have a scalar pointer and a vector
  4930. /// index.
  4931. ///
  4932. /// If the existing GEP has a vector base pointer that is splat, we can look
  4933. /// through the splat to find the scalar pointer. If we can't find a scalar
  4934. /// pointer there's nothing we can do.
  4935. ///
  4936. /// If we have a GEP with more than 2 indices where the middle indices are all
  4937. /// zeroes, we can replace it with 2 GEPs where the second has 2 operands.
  4938. ///
  4939. /// If the final index isn't a vector or is a splat, we can emit a scalar GEP
  4940. /// followed by a GEP with an all zeroes vector index. This will enable
  4941. /// SelectionDAGBuilder to use the scalar GEP as the uniform base and have a
  4942. /// zero index.
  4943. bool CodeGenPrepare::optimizeGatherScatterInst(Instruction *MemoryInst,
  4944. Value *Ptr) {
  4945. Value *NewAddr;
  4946. if (const auto *GEP = dyn_cast<GetElementPtrInst>(Ptr)) {
  4947. // Don't optimize GEPs that don't have indices.
  4948. if (!GEP->hasIndices())
  4949. return false;
  4950. // If the GEP and the gather/scatter aren't in the same BB, don't optimize.
  4951. // FIXME: We should support this by sinking the GEP.
  4952. if (MemoryInst->getParent() != GEP->getParent())
  4953. return false;
  4954. SmallVector<Value *, 2> Ops(GEP->operands());
  4955. bool RewriteGEP = false;
  4956. if (Ops[0]->getType()->isVectorTy()) {
  4957. Ops[0] = getSplatValue(Ops[0]);
  4958. if (!Ops[0])
  4959. return false;
  4960. RewriteGEP = true;
  4961. }
  4962. unsigned FinalIndex = Ops.size() - 1;
  4963. // Ensure all but the last index is 0.
  4964. // FIXME: This isn't strictly required. All that's required is that they are
  4965. // all scalars or splats.
  4966. for (unsigned i = 1; i < FinalIndex; ++i) {
  4967. auto *C = dyn_cast<Constant>(Ops[i]);
  4968. if (!C)
  4969. return false;
  4970. if (isa<VectorType>(C->getType()))
  4971. C = C->getSplatValue();
  4972. auto *CI = dyn_cast_or_null<ConstantInt>(C);
  4973. if (!CI || !CI->isZero())
  4974. return false;
  4975. // Scalarize the index if needed.
  4976. Ops[i] = CI;
  4977. }
  4978. // Try to scalarize the final index.
  4979. if (Ops[FinalIndex]->getType()->isVectorTy()) {
  4980. if (Value *V = getSplatValue(Ops[FinalIndex])) {
  4981. auto *C = dyn_cast<ConstantInt>(V);
  4982. // Don't scalarize all zeros vector.
  4983. if (!C || !C->isZero()) {
  4984. Ops[FinalIndex] = V;
  4985. RewriteGEP = true;
  4986. }
  4987. }
  4988. }
  4989. // If we made any changes or the we have extra operands, we need to generate
  4990. // new instructions.
  4991. if (!RewriteGEP && Ops.size() == 2)
  4992. return false;
  4993. auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
  4994. IRBuilder<> Builder(MemoryInst);
  4995. Type *SourceTy = GEP->getSourceElementType();
  4996. Type *ScalarIndexTy = DL->getIndexType(Ops[0]->getType()->getScalarType());
  4997. // If the final index isn't a vector, emit a scalar GEP containing all ops
  4998. // and a vector GEP with all zeroes final index.
  4999. if (!Ops[FinalIndex]->getType()->isVectorTy()) {
  5000. NewAddr = Builder.CreateGEP(SourceTy, Ops[0], ArrayRef(Ops).drop_front());
  5001. auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
  5002. auto *SecondTy = GetElementPtrInst::getIndexedType(
  5003. SourceTy, ArrayRef(Ops).drop_front());
  5004. NewAddr =
  5005. Builder.CreateGEP(SecondTy, NewAddr, Constant::getNullValue(IndexTy));
  5006. } else {
  5007. Value *Base = Ops[0];
  5008. Value *Index = Ops[FinalIndex];
  5009. // Create a scalar GEP if there are more than 2 operands.
  5010. if (Ops.size() != 2) {
  5011. // Replace the last index with 0.
  5012. Ops[FinalIndex] = Constant::getNullValue(ScalarIndexTy);
  5013. Base = Builder.CreateGEP(SourceTy, Base, ArrayRef(Ops).drop_front());
  5014. SourceTy = GetElementPtrInst::getIndexedType(
  5015. SourceTy, ArrayRef(Ops).drop_front());
  5016. }
  5017. // Now create the GEP with scalar pointer and vector index.
  5018. NewAddr = Builder.CreateGEP(SourceTy, Base, Index);
  5019. }
  5020. } else if (!isa<Constant>(Ptr)) {
  5021. // Not a GEP, maybe its a splat and we can create a GEP to enable
  5022. // SelectionDAGBuilder to use it as a uniform base.
  5023. Value *V = getSplatValue(Ptr);
  5024. if (!V)
  5025. return false;
  5026. auto NumElts = cast<VectorType>(Ptr->getType())->getElementCount();
  5027. IRBuilder<> Builder(MemoryInst);
  5028. // Emit a vector GEP with a scalar pointer and all 0s vector index.
  5029. Type *ScalarIndexTy = DL->getIndexType(V->getType()->getScalarType());
  5030. auto *IndexTy = VectorType::get(ScalarIndexTy, NumElts);
  5031. Type *ScalarTy;
  5032. if (cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
  5033. Intrinsic::masked_gather) {
  5034. ScalarTy = MemoryInst->getType()->getScalarType();
  5035. } else {
  5036. assert(cast<IntrinsicInst>(MemoryInst)->getIntrinsicID() ==
  5037. Intrinsic::masked_scatter);
  5038. ScalarTy = MemoryInst->getOperand(0)->getType()->getScalarType();
  5039. }
  5040. NewAddr = Builder.CreateGEP(ScalarTy, V, Constant::getNullValue(IndexTy));
  5041. } else {
  5042. // Constant, SelectionDAGBuilder knows to check if its a splat.
  5043. return false;
  5044. }
  5045. MemoryInst->replaceUsesOfWith(Ptr, NewAddr);
  5046. // If we have no uses, recursively delete the value and all dead instructions
  5047. // using it.
  5048. if (Ptr->use_empty())
  5049. RecursivelyDeleteTriviallyDeadInstructions(
  5050. Ptr, TLInfo, nullptr,
  5051. [&](Value *V) { removeAllAssertingVHReferences(V); });
  5052. return true;
  5053. }
  5054. /// If there are any memory operands, use OptimizeMemoryInst to sink their
  5055. /// address computing into the block when possible / profitable.
  5056. bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
  5057. bool MadeChange = false;
  5058. const TargetRegisterInfo *TRI =
  5059. TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
  5060. TargetLowering::AsmOperandInfoVector TargetConstraints =
  5061. TLI->ParseConstraints(*DL, TRI, *CS);
  5062. unsigned ArgNo = 0;
  5063. for (TargetLowering::AsmOperandInfo &OpInfo : TargetConstraints) {
  5064. // Compute the constraint code and ConstraintType to use.
  5065. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  5066. // TODO: Also handle C_Address?
  5067. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  5068. OpInfo.isIndirect) {
  5069. Value *OpVal = CS->getArgOperand(ArgNo++);
  5070. MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  5071. } else if (OpInfo.Type == InlineAsm::isInput)
  5072. ArgNo++;
  5073. }
  5074. return MadeChange;
  5075. }
  5076. /// Check if all the uses of \p Val are equivalent (or free) zero or
  5077. /// sign extensions.
  5078. static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
  5079. assert(!Val->use_empty() && "Input must have at least one use");
  5080. const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
  5081. bool IsSExt = isa<SExtInst>(FirstUser);
  5082. Type *ExtTy = FirstUser->getType();
  5083. for (const User *U : Val->users()) {
  5084. const Instruction *UI = cast<Instruction>(U);
  5085. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  5086. return false;
  5087. Type *CurTy = UI->getType();
  5088. // Same input and output types: Same instruction after CSE.
  5089. if (CurTy == ExtTy)
  5090. continue;
  5091. // If IsSExt is true, we are in this situation:
  5092. // a = Val
  5093. // b = sext ty1 a to ty2
  5094. // c = sext ty1 a to ty3
  5095. // Assuming ty2 is shorter than ty3, this could be turned into:
  5096. // a = Val
  5097. // b = sext ty1 a to ty2
  5098. // c = sext ty2 b to ty3
  5099. // However, the last sext is not free.
  5100. if (IsSExt)
  5101. return false;
  5102. // This is a ZExt, maybe this is free to extend from one type to another.
  5103. // In that case, we would not account for a different use.
  5104. Type *NarrowTy;
  5105. Type *LargeTy;
  5106. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  5107. CurTy->getScalarType()->getIntegerBitWidth()) {
  5108. NarrowTy = CurTy;
  5109. LargeTy = ExtTy;
  5110. } else {
  5111. NarrowTy = ExtTy;
  5112. LargeTy = CurTy;
  5113. }
  5114. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  5115. return false;
  5116. }
  5117. // All uses are the same or can be derived from one another for free.
  5118. return true;
  5119. }
  5120. /// Try to speculatively promote extensions in \p Exts and continue
  5121. /// promoting through newly promoted operands recursively as far as doing so is
  5122. /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
  5123. /// When some promotion happened, \p TPT contains the proper state to revert
  5124. /// them.
  5125. ///
  5126. /// \return true if some promotion happened, false otherwise.
  5127. bool CodeGenPrepare::tryToPromoteExts(
  5128. TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
  5129. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  5130. unsigned CreatedInstsCost) {
  5131. bool Promoted = false;
  5132. // Iterate over all the extensions to try to promote them.
  5133. for (auto *I : Exts) {
  5134. // Early check if we directly have ext(load).
  5135. if (isa<LoadInst>(I->getOperand(0))) {
  5136. ProfitablyMovedExts.push_back(I);
  5137. continue;
  5138. }
  5139. // Check whether or not we want to do any promotion. The reason we have
  5140. // this check inside the for loop is to catch the case where an extension
  5141. // is directly fed by a load because in such case the extension can be moved
  5142. // up without any promotion on its operands.
  5143. if (!TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  5144. return false;
  5145. // Get the action to perform the promotion.
  5146. TypePromotionHelper::Action TPH =
  5147. TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
  5148. // Check if we can promote.
  5149. if (!TPH) {
  5150. // Save the current extension as we cannot move up through its operand.
  5151. ProfitablyMovedExts.push_back(I);
  5152. continue;
  5153. }
  5154. // Save the current state.
  5155. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  5156. TPT.getRestorationPoint();
  5157. SmallVector<Instruction *, 4> NewExts;
  5158. unsigned NewCreatedInstsCost = 0;
  5159. unsigned ExtCost = !TLI->isExtFree(I);
  5160. // Promote.
  5161. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  5162. &NewExts, nullptr, *TLI);
  5163. assert(PromotedVal &&
  5164. "TypePromotionHelper should have filtered out those cases");
  5165. // We would be able to merge only one extension in a load.
  5166. // Therefore, if we have more than 1 new extension we heuristically
  5167. // cut this search path, because it means we degrade the code quality.
  5168. // With exactly 2, the transformation is neutral, because we will merge
  5169. // one extension but leave one. However, we optimistically keep going,
  5170. // because the new extension may be removed too.
  5171. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  5172. // FIXME: It would be possible to propagate a negative value instead of
  5173. // conservatively ceiling it to 0.
  5174. TotalCreatedInstsCost =
  5175. std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
  5176. if (!StressExtLdPromotion &&
  5177. (TotalCreatedInstsCost > 1 ||
  5178. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  5179. // This promotion is not profitable, rollback to the previous state, and
  5180. // save the current extension in ProfitablyMovedExts as the latest
  5181. // speculative promotion turned out to be unprofitable.
  5182. TPT.rollback(LastKnownGood);
  5183. ProfitablyMovedExts.push_back(I);
  5184. continue;
  5185. }
  5186. // Continue promoting NewExts as far as doing so is profitable.
  5187. SmallVector<Instruction *, 2> NewlyMovedExts;
  5188. (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
  5189. bool NewPromoted = false;
  5190. for (auto *ExtInst : NewlyMovedExts) {
  5191. Instruction *MovedExt = cast<Instruction>(ExtInst);
  5192. Value *ExtOperand = MovedExt->getOperand(0);
  5193. // If we have reached to a load, we need this extra profitability check
  5194. // as it could potentially be merged into an ext(load).
  5195. if (isa<LoadInst>(ExtOperand) &&
  5196. !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  5197. (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
  5198. continue;
  5199. ProfitablyMovedExts.push_back(MovedExt);
  5200. NewPromoted = true;
  5201. }
  5202. // If none of speculative promotions for NewExts is profitable, rollback
  5203. // and save the current extension (I) as the last profitable extension.
  5204. if (!NewPromoted) {
  5205. TPT.rollback(LastKnownGood);
  5206. ProfitablyMovedExts.push_back(I);
  5207. continue;
  5208. }
  5209. // The promotion is profitable.
  5210. Promoted = true;
  5211. }
  5212. return Promoted;
  5213. }
  5214. /// Merging redundant sexts when one is dominating the other.
  5215. bool CodeGenPrepare::mergeSExts(Function &F) {
  5216. bool Changed = false;
  5217. for (auto &Entry : ValToSExtendedUses) {
  5218. SExts &Insts = Entry.second;
  5219. SExts CurPts;
  5220. for (Instruction *Inst : Insts) {
  5221. if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
  5222. Inst->getOperand(0) != Entry.first)
  5223. continue;
  5224. bool inserted = false;
  5225. for (auto &Pt : CurPts) {
  5226. if (getDT(F).dominates(Inst, Pt)) {
  5227. replaceAllUsesWith(Pt, Inst, FreshBBs, IsHugeFunc);
  5228. RemovedInsts.insert(Pt);
  5229. Pt->removeFromParent();
  5230. Pt = Inst;
  5231. inserted = true;
  5232. Changed = true;
  5233. break;
  5234. }
  5235. if (!getDT(F).dominates(Pt, Inst))
  5236. // Give up if we need to merge in a common dominator as the
  5237. // experiments show it is not profitable.
  5238. continue;
  5239. replaceAllUsesWith(Inst, Pt, FreshBBs, IsHugeFunc);
  5240. RemovedInsts.insert(Inst);
  5241. Inst->removeFromParent();
  5242. inserted = true;
  5243. Changed = true;
  5244. break;
  5245. }
  5246. if (!inserted)
  5247. CurPts.push_back(Inst);
  5248. }
  5249. }
  5250. return Changed;
  5251. }
  5252. // Splitting large data structures so that the GEPs accessing them can have
  5253. // smaller offsets so that they can be sunk to the same blocks as their users.
  5254. // For example, a large struct starting from %base is split into two parts
  5255. // where the second part starts from %new_base.
  5256. //
  5257. // Before:
  5258. // BB0:
  5259. // %base =
  5260. //
  5261. // BB1:
  5262. // %gep0 = gep %base, off0
  5263. // %gep1 = gep %base, off1
  5264. // %gep2 = gep %base, off2
  5265. //
  5266. // BB2:
  5267. // %load1 = load %gep0
  5268. // %load2 = load %gep1
  5269. // %load3 = load %gep2
  5270. //
  5271. // After:
  5272. // BB0:
  5273. // %base =
  5274. // %new_base = gep %base, off0
  5275. //
  5276. // BB1:
  5277. // %new_gep0 = %new_base
  5278. // %new_gep1 = gep %new_base, off1 - off0
  5279. // %new_gep2 = gep %new_base, off2 - off0
  5280. //
  5281. // BB2:
  5282. // %load1 = load i32, i32* %new_gep0
  5283. // %load2 = load i32, i32* %new_gep1
  5284. // %load3 = load i32, i32* %new_gep2
  5285. //
  5286. // %new_gep1 and %new_gep2 can be sunk to BB2 now after the splitting because
  5287. // their offsets are smaller enough to fit into the addressing mode.
  5288. bool CodeGenPrepare::splitLargeGEPOffsets() {
  5289. bool Changed = false;
  5290. for (auto &Entry : LargeOffsetGEPMap) {
  5291. Value *OldBase = Entry.first;
  5292. SmallVectorImpl<std::pair<AssertingVH<GetElementPtrInst>, int64_t>>
  5293. &LargeOffsetGEPs = Entry.second;
  5294. auto compareGEPOffset =
  5295. [&](const std::pair<GetElementPtrInst *, int64_t> &LHS,
  5296. const std::pair<GetElementPtrInst *, int64_t> &RHS) {
  5297. if (LHS.first == RHS.first)
  5298. return false;
  5299. if (LHS.second != RHS.second)
  5300. return LHS.second < RHS.second;
  5301. return LargeOffsetGEPID[LHS.first] < LargeOffsetGEPID[RHS.first];
  5302. };
  5303. // Sorting all the GEPs of the same data structures based on the offsets.
  5304. llvm::sort(LargeOffsetGEPs, compareGEPOffset);
  5305. LargeOffsetGEPs.erase(
  5306. std::unique(LargeOffsetGEPs.begin(), LargeOffsetGEPs.end()),
  5307. LargeOffsetGEPs.end());
  5308. // Skip if all the GEPs have the same offsets.
  5309. if (LargeOffsetGEPs.front().second == LargeOffsetGEPs.back().second)
  5310. continue;
  5311. GetElementPtrInst *BaseGEP = LargeOffsetGEPs.begin()->first;
  5312. int64_t BaseOffset = LargeOffsetGEPs.begin()->second;
  5313. Value *NewBaseGEP = nullptr;
  5314. auto *LargeOffsetGEP = LargeOffsetGEPs.begin();
  5315. while (LargeOffsetGEP != LargeOffsetGEPs.end()) {
  5316. GetElementPtrInst *GEP = LargeOffsetGEP->first;
  5317. int64_t Offset = LargeOffsetGEP->second;
  5318. if (Offset != BaseOffset) {
  5319. TargetLowering::AddrMode AddrMode;
  5320. AddrMode.BaseOffs = Offset - BaseOffset;
  5321. // The result type of the GEP might not be the type of the memory
  5322. // access.
  5323. if (!TLI->isLegalAddressingMode(*DL, AddrMode,
  5324. GEP->getResultElementType(),
  5325. GEP->getAddressSpace())) {
  5326. // We need to create a new base if the offset to the current base is
  5327. // too large to fit into the addressing mode. So, a very large struct
  5328. // may be split into several parts.
  5329. BaseGEP = GEP;
  5330. BaseOffset = Offset;
  5331. NewBaseGEP = nullptr;
  5332. }
  5333. }
  5334. // Generate a new GEP to replace the current one.
  5335. LLVMContext &Ctx = GEP->getContext();
  5336. Type *IntPtrTy = DL->getIntPtrType(GEP->getType());
  5337. Type *I8PtrTy =
  5338. Type::getInt8PtrTy(Ctx, GEP->getType()->getPointerAddressSpace());
  5339. Type *I8Ty = Type::getInt8Ty(Ctx);
  5340. if (!NewBaseGEP) {
  5341. // Create a new base if we don't have one yet. Find the insertion
  5342. // pointer for the new base first.
  5343. BasicBlock::iterator NewBaseInsertPt;
  5344. BasicBlock *NewBaseInsertBB;
  5345. if (auto *BaseI = dyn_cast<Instruction>(OldBase)) {
  5346. // If the base of the struct is an instruction, the new base will be
  5347. // inserted close to it.
  5348. NewBaseInsertBB = BaseI->getParent();
  5349. if (isa<PHINode>(BaseI))
  5350. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  5351. else if (InvokeInst *Invoke = dyn_cast<InvokeInst>(BaseI)) {
  5352. NewBaseInsertBB =
  5353. SplitEdge(NewBaseInsertBB, Invoke->getNormalDest());
  5354. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  5355. } else
  5356. NewBaseInsertPt = std::next(BaseI->getIterator());
  5357. } else {
  5358. // If the current base is an argument or global value, the new base
  5359. // will be inserted to the entry block.
  5360. NewBaseInsertBB = &BaseGEP->getFunction()->getEntryBlock();
  5361. NewBaseInsertPt = NewBaseInsertBB->getFirstInsertionPt();
  5362. }
  5363. IRBuilder<> NewBaseBuilder(NewBaseInsertBB, NewBaseInsertPt);
  5364. // Create a new base.
  5365. Value *BaseIndex = ConstantInt::get(IntPtrTy, BaseOffset);
  5366. NewBaseGEP = OldBase;
  5367. if (NewBaseGEP->getType() != I8PtrTy)
  5368. NewBaseGEP = NewBaseBuilder.CreatePointerCast(NewBaseGEP, I8PtrTy);
  5369. NewBaseGEP =
  5370. NewBaseBuilder.CreateGEP(I8Ty, NewBaseGEP, BaseIndex, "splitgep");
  5371. NewGEPBases.insert(NewBaseGEP);
  5372. }
  5373. IRBuilder<> Builder(GEP);
  5374. Value *NewGEP = NewBaseGEP;
  5375. if (Offset == BaseOffset) {
  5376. if (GEP->getType() != I8PtrTy)
  5377. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  5378. } else {
  5379. // Calculate the new offset for the new GEP.
  5380. Value *Index = ConstantInt::get(IntPtrTy, Offset - BaseOffset);
  5381. NewGEP = Builder.CreateGEP(I8Ty, NewBaseGEP, Index);
  5382. if (GEP->getType() != I8PtrTy)
  5383. NewGEP = Builder.CreatePointerCast(NewGEP, GEP->getType());
  5384. }
  5385. replaceAllUsesWith(GEP, NewGEP, FreshBBs, IsHugeFunc);
  5386. LargeOffsetGEPID.erase(GEP);
  5387. LargeOffsetGEP = LargeOffsetGEPs.erase(LargeOffsetGEP);
  5388. GEP->eraseFromParent();
  5389. Changed = true;
  5390. }
  5391. }
  5392. return Changed;
  5393. }
  5394. bool CodeGenPrepare::optimizePhiType(
  5395. PHINode *I, SmallPtrSetImpl<PHINode *> &Visited,
  5396. SmallPtrSetImpl<Instruction *> &DeletedInstrs) {
  5397. // We are looking for a collection on interconnected phi nodes that together
  5398. // only use loads/bitcasts and are used by stores/bitcasts, and the bitcasts
  5399. // are of the same type. Convert the whole set of nodes to the type of the
  5400. // bitcast.
  5401. Type *PhiTy = I->getType();
  5402. Type *ConvertTy = nullptr;
  5403. if (Visited.count(I) ||
  5404. (!I->getType()->isIntegerTy() && !I->getType()->isFloatingPointTy()))
  5405. return false;
  5406. SmallVector<Instruction *, 4> Worklist;
  5407. Worklist.push_back(cast<Instruction>(I));
  5408. SmallPtrSet<PHINode *, 4> PhiNodes;
  5409. SmallPtrSet<ConstantData *, 4> Constants;
  5410. PhiNodes.insert(I);
  5411. Visited.insert(I);
  5412. SmallPtrSet<Instruction *, 4> Defs;
  5413. SmallPtrSet<Instruction *, 4> Uses;
  5414. // This works by adding extra bitcasts between load/stores and removing
  5415. // existing bicasts. If we have a phi(bitcast(load)) or a store(bitcast(phi))
  5416. // we can get in the situation where we remove a bitcast in one iteration
  5417. // just to add it again in the next. We need to ensure that at least one
  5418. // bitcast we remove are anchored to something that will not change back.
  5419. bool AnyAnchored = false;
  5420. while (!Worklist.empty()) {
  5421. Instruction *II = Worklist.pop_back_val();
  5422. if (auto *Phi = dyn_cast<PHINode>(II)) {
  5423. // Handle Defs, which might also be PHI's
  5424. for (Value *V : Phi->incoming_values()) {
  5425. if (auto *OpPhi = dyn_cast<PHINode>(V)) {
  5426. if (!PhiNodes.count(OpPhi)) {
  5427. if (!Visited.insert(OpPhi).second)
  5428. return false;
  5429. PhiNodes.insert(OpPhi);
  5430. Worklist.push_back(OpPhi);
  5431. }
  5432. } else if (auto *OpLoad = dyn_cast<LoadInst>(V)) {
  5433. if (!OpLoad->isSimple())
  5434. return false;
  5435. if (Defs.insert(OpLoad).second)
  5436. Worklist.push_back(OpLoad);
  5437. } else if (auto *OpEx = dyn_cast<ExtractElementInst>(V)) {
  5438. if (Defs.insert(OpEx).second)
  5439. Worklist.push_back(OpEx);
  5440. } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
  5441. if (!ConvertTy)
  5442. ConvertTy = OpBC->getOperand(0)->getType();
  5443. if (OpBC->getOperand(0)->getType() != ConvertTy)
  5444. return false;
  5445. if (Defs.insert(OpBC).second) {
  5446. Worklist.push_back(OpBC);
  5447. AnyAnchored |= !isa<LoadInst>(OpBC->getOperand(0)) &&
  5448. !isa<ExtractElementInst>(OpBC->getOperand(0));
  5449. }
  5450. } else if (auto *OpC = dyn_cast<ConstantData>(V))
  5451. Constants.insert(OpC);
  5452. else
  5453. return false;
  5454. }
  5455. }
  5456. // Handle uses which might also be phi's
  5457. for (User *V : II->users()) {
  5458. if (auto *OpPhi = dyn_cast<PHINode>(V)) {
  5459. if (!PhiNodes.count(OpPhi)) {
  5460. if (Visited.count(OpPhi))
  5461. return false;
  5462. PhiNodes.insert(OpPhi);
  5463. Visited.insert(OpPhi);
  5464. Worklist.push_back(OpPhi);
  5465. }
  5466. } else if (auto *OpStore = dyn_cast<StoreInst>(V)) {
  5467. if (!OpStore->isSimple() || OpStore->getOperand(0) != II)
  5468. return false;
  5469. Uses.insert(OpStore);
  5470. } else if (auto *OpBC = dyn_cast<BitCastInst>(V)) {
  5471. if (!ConvertTy)
  5472. ConvertTy = OpBC->getType();
  5473. if (OpBC->getType() != ConvertTy)
  5474. return false;
  5475. Uses.insert(OpBC);
  5476. AnyAnchored |=
  5477. any_of(OpBC->users(), [](User *U) { return !isa<StoreInst>(U); });
  5478. } else {
  5479. return false;
  5480. }
  5481. }
  5482. }
  5483. if (!ConvertTy || !AnyAnchored ||
  5484. !TLI->shouldConvertPhiType(PhiTy, ConvertTy))
  5485. return false;
  5486. LLVM_DEBUG(dbgs() << "Converting " << *I << "\n and connected nodes to "
  5487. << *ConvertTy << "\n");
  5488. // Create all the new phi nodes of the new type, and bitcast any loads to the
  5489. // correct type.
  5490. ValueToValueMap ValMap;
  5491. for (ConstantData *C : Constants)
  5492. ValMap[C] = ConstantExpr::getCast(Instruction::BitCast, C, ConvertTy);
  5493. for (Instruction *D : Defs) {
  5494. if (isa<BitCastInst>(D)) {
  5495. ValMap[D] = D->getOperand(0);
  5496. DeletedInstrs.insert(D);
  5497. } else {
  5498. ValMap[D] =
  5499. new BitCastInst(D, ConvertTy, D->getName() + ".bc", D->getNextNode());
  5500. }
  5501. }
  5502. for (PHINode *Phi : PhiNodes)
  5503. ValMap[Phi] = PHINode::Create(ConvertTy, Phi->getNumIncomingValues(),
  5504. Phi->getName() + ".tc", Phi);
  5505. // Pipe together all the PhiNodes.
  5506. for (PHINode *Phi : PhiNodes) {
  5507. PHINode *NewPhi = cast<PHINode>(ValMap[Phi]);
  5508. for (int i = 0, e = Phi->getNumIncomingValues(); i < e; i++)
  5509. NewPhi->addIncoming(ValMap[Phi->getIncomingValue(i)],
  5510. Phi->getIncomingBlock(i));
  5511. Visited.insert(NewPhi);
  5512. }
  5513. // And finally pipe up the stores and bitcasts
  5514. for (Instruction *U : Uses) {
  5515. if (isa<BitCastInst>(U)) {
  5516. DeletedInstrs.insert(U);
  5517. replaceAllUsesWith(U, ValMap[U->getOperand(0)], FreshBBs, IsHugeFunc);
  5518. } else {
  5519. U->setOperand(0,
  5520. new BitCastInst(ValMap[U->getOperand(0)], PhiTy, "bc", U));
  5521. }
  5522. }
  5523. // Save the removed phis to be deleted later.
  5524. for (PHINode *Phi : PhiNodes)
  5525. DeletedInstrs.insert(Phi);
  5526. return true;
  5527. }
  5528. bool CodeGenPrepare::optimizePhiTypes(Function &F) {
  5529. if (!OptimizePhiTypes)
  5530. return false;
  5531. bool Changed = false;
  5532. SmallPtrSet<PHINode *, 4> Visited;
  5533. SmallPtrSet<Instruction *, 4> DeletedInstrs;
  5534. // Attempt to optimize all the phis in the functions to the correct type.
  5535. for (auto &BB : F)
  5536. for (auto &Phi : BB.phis())
  5537. Changed |= optimizePhiType(&Phi, Visited, DeletedInstrs);
  5538. // Remove any old phi's that have been converted.
  5539. for (auto *I : DeletedInstrs) {
  5540. replaceAllUsesWith(I, PoisonValue::get(I->getType()), FreshBBs, IsHugeFunc);
  5541. I->eraseFromParent();
  5542. }
  5543. return Changed;
  5544. }
  5545. /// Return true, if an ext(load) can be formed from an extension in
  5546. /// \p MovedExts.
  5547. bool CodeGenPrepare::canFormExtLd(
  5548. const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
  5549. Instruction *&Inst, bool HasPromoted) {
  5550. for (auto *MovedExtInst : MovedExts) {
  5551. if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
  5552. LI = cast<LoadInst>(MovedExtInst->getOperand(0));
  5553. Inst = MovedExtInst;
  5554. break;
  5555. }
  5556. }
  5557. if (!LI)
  5558. return false;
  5559. // If they're already in the same block, there's nothing to do.
  5560. // Make the cheap checks first if we did not promote.
  5561. // If we promoted, we need to check if it is indeed profitable.
  5562. if (!HasPromoted && LI->getParent() == Inst->getParent())
  5563. return false;
  5564. return TLI->isExtLoad(LI, Inst, *DL);
  5565. }
  5566. /// Move a zext or sext fed by a load into the same basic block as the load,
  5567. /// unless conditions are unfavorable. This allows SelectionDAG to fold the
  5568. /// extend into the load.
  5569. ///
  5570. /// E.g.,
  5571. /// \code
  5572. /// %ld = load i32* %addr
  5573. /// %add = add nuw i32 %ld, 4
  5574. /// %zext = zext i32 %add to i64
  5575. // \endcode
  5576. /// =>
  5577. /// \code
  5578. /// %ld = load i32* %addr
  5579. /// %zext = zext i32 %ld to i64
  5580. /// %add = add nuw i64 %zext, 4
  5581. /// \encode
  5582. /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
  5583. /// allow us to match zext(load i32*) to i64.
  5584. ///
  5585. /// Also, try to promote the computations used to obtain a sign extended
  5586. /// value used into memory accesses.
  5587. /// E.g.,
  5588. /// \code
  5589. /// a = add nsw i32 b, 3
  5590. /// d = sext i32 a to i64
  5591. /// e = getelementptr ..., i64 d
  5592. /// \endcode
  5593. /// =>
  5594. /// \code
  5595. /// f = sext i32 b to i64
  5596. /// a = add nsw i64 f, 3
  5597. /// e = getelementptr ..., i64 a
  5598. /// \endcode
  5599. ///
  5600. /// \p Inst[in/out] the extension may be modified during the process if some
  5601. /// promotions apply.
  5602. bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
  5603. bool AllowPromotionWithoutCommonHeader = false;
  5604. /// See if it is an interesting sext operations for the address type
  5605. /// promotion before trying to promote it, e.g., the ones with the right
  5606. /// type and used in memory accesses.
  5607. bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
  5608. *Inst, AllowPromotionWithoutCommonHeader);
  5609. TypePromotionTransaction TPT(RemovedInsts);
  5610. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  5611. TPT.getRestorationPoint();
  5612. SmallVector<Instruction *, 1> Exts;
  5613. SmallVector<Instruction *, 2> SpeculativelyMovedExts;
  5614. Exts.push_back(Inst);
  5615. bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
  5616. // Look for a load being extended.
  5617. LoadInst *LI = nullptr;
  5618. Instruction *ExtFedByLoad;
  5619. // Try to promote a chain of computation if it allows to form an extended
  5620. // load.
  5621. if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
  5622. assert(LI && ExtFedByLoad && "Expect a valid load and extension");
  5623. TPT.commit();
  5624. // Move the extend into the same block as the load.
  5625. ExtFedByLoad->moveAfter(LI);
  5626. ++NumExtsMoved;
  5627. Inst = ExtFedByLoad;
  5628. return true;
  5629. }
  5630. // Continue promoting SExts if known as considerable depending on targets.
  5631. if (ATPConsiderable &&
  5632. performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
  5633. HasPromoted, TPT, SpeculativelyMovedExts))
  5634. return true;
  5635. TPT.rollback(LastKnownGood);
  5636. return false;
  5637. }
  5638. // Perform address type promotion if doing so is profitable.
  5639. // If AllowPromotionWithoutCommonHeader == false, we should find other sext
  5640. // instructions that sign extended the same initial value. However, if
  5641. // AllowPromotionWithoutCommonHeader == true, we expect promoting the
  5642. // extension is just profitable.
  5643. bool CodeGenPrepare::performAddressTypePromotion(
  5644. Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
  5645. bool HasPromoted, TypePromotionTransaction &TPT,
  5646. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
  5647. bool Promoted = false;
  5648. SmallPtrSet<Instruction *, 1> UnhandledExts;
  5649. bool AllSeenFirst = true;
  5650. for (auto *I : SpeculativelyMovedExts) {
  5651. Value *HeadOfChain = I->getOperand(0);
  5652. DenseMap<Value *, Instruction *>::iterator AlreadySeen =
  5653. SeenChainsForSExt.find(HeadOfChain);
  5654. // If there is an unhandled SExt which has the same header, try to promote
  5655. // it as well.
  5656. if (AlreadySeen != SeenChainsForSExt.end()) {
  5657. if (AlreadySeen->second != nullptr)
  5658. UnhandledExts.insert(AlreadySeen->second);
  5659. AllSeenFirst = false;
  5660. }
  5661. }
  5662. if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
  5663. SpeculativelyMovedExts.size() == 1)) {
  5664. TPT.commit();
  5665. if (HasPromoted)
  5666. Promoted = true;
  5667. for (auto *I : SpeculativelyMovedExts) {
  5668. Value *HeadOfChain = I->getOperand(0);
  5669. SeenChainsForSExt[HeadOfChain] = nullptr;
  5670. ValToSExtendedUses[HeadOfChain].push_back(I);
  5671. }
  5672. // Update Inst as promotion happen.
  5673. Inst = SpeculativelyMovedExts.pop_back_val();
  5674. } else {
  5675. // This is the first chain visited from the header, keep the current chain
  5676. // as unhandled. Defer to promote this until we encounter another SExt
  5677. // chain derived from the same header.
  5678. for (auto *I : SpeculativelyMovedExts) {
  5679. Value *HeadOfChain = I->getOperand(0);
  5680. SeenChainsForSExt[HeadOfChain] = Inst;
  5681. }
  5682. return false;
  5683. }
  5684. if (!AllSeenFirst && !UnhandledExts.empty())
  5685. for (auto *VisitedSExt : UnhandledExts) {
  5686. if (RemovedInsts.count(VisitedSExt))
  5687. continue;
  5688. TypePromotionTransaction TPT(RemovedInsts);
  5689. SmallVector<Instruction *, 1> Exts;
  5690. SmallVector<Instruction *, 2> Chains;
  5691. Exts.push_back(VisitedSExt);
  5692. bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
  5693. TPT.commit();
  5694. if (HasPromoted)
  5695. Promoted = true;
  5696. for (auto *I : Chains) {
  5697. Value *HeadOfChain = I->getOperand(0);
  5698. // Mark this as handled.
  5699. SeenChainsForSExt[HeadOfChain] = nullptr;
  5700. ValToSExtendedUses[HeadOfChain].push_back(I);
  5701. }
  5702. }
  5703. return Promoted;
  5704. }
  5705. bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
  5706. BasicBlock *DefBB = I->getParent();
  5707. // If the result of a {s|z}ext and its source are both live out, rewrite all
  5708. // other uses of the source with result of extension.
  5709. Value *Src = I->getOperand(0);
  5710. if (Src->hasOneUse())
  5711. return false;
  5712. // Only do this xform if truncating is free.
  5713. if (!TLI->isTruncateFree(I->getType(), Src->getType()))
  5714. return false;
  5715. // Only safe to perform the optimization if the source is also defined in
  5716. // this block.
  5717. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  5718. return false;
  5719. bool DefIsLiveOut = false;
  5720. for (User *U : I->users()) {
  5721. Instruction *UI = cast<Instruction>(U);
  5722. // Figure out which BB this ext is used in.
  5723. BasicBlock *UserBB = UI->getParent();
  5724. if (UserBB == DefBB)
  5725. continue;
  5726. DefIsLiveOut = true;
  5727. break;
  5728. }
  5729. if (!DefIsLiveOut)
  5730. return false;
  5731. // Make sure none of the uses are PHI nodes.
  5732. for (User *U : Src->users()) {
  5733. Instruction *UI = cast<Instruction>(U);
  5734. BasicBlock *UserBB = UI->getParent();
  5735. if (UserBB == DefBB)
  5736. continue;
  5737. // Be conservative. We don't want this xform to end up introducing
  5738. // reloads just before load / store instructions.
  5739. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  5740. return false;
  5741. }
  5742. // InsertedTruncs - Only insert one trunc in each block once.
  5743. DenseMap<BasicBlock *, Instruction *> InsertedTruncs;
  5744. bool MadeChange = false;
  5745. for (Use &U : Src->uses()) {
  5746. Instruction *User = cast<Instruction>(U.getUser());
  5747. // Figure out which BB this ext is used in.
  5748. BasicBlock *UserBB = User->getParent();
  5749. if (UserBB == DefBB)
  5750. continue;
  5751. // Both src and def are live in this block. Rewrite the use.
  5752. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  5753. if (!InsertedTrunc) {
  5754. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  5755. assert(InsertPt != UserBB->end());
  5756. InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
  5757. InsertedInsts.insert(InsertedTrunc);
  5758. }
  5759. // Replace a use of the {s|z}ext source with a use of the result.
  5760. U = InsertedTrunc;
  5761. ++NumExtUses;
  5762. MadeChange = true;
  5763. }
  5764. return MadeChange;
  5765. }
  5766. // Find loads whose uses only use some of the loaded value's bits. Add an "and"
  5767. // just after the load if the target can fold this into one extload instruction,
  5768. // with the hope of eliminating some of the other later "and" instructions using
  5769. // the loaded value. "and"s that are made trivially redundant by the insertion
  5770. // of the new "and" are removed by this function, while others (e.g. those whose
  5771. // path from the load goes through a phi) are left for isel to potentially
  5772. // remove.
  5773. //
  5774. // For example:
  5775. //
  5776. // b0:
  5777. // x = load i32
  5778. // ...
  5779. // b1:
  5780. // y = and x, 0xff
  5781. // z = use y
  5782. //
  5783. // becomes:
  5784. //
  5785. // b0:
  5786. // x = load i32
  5787. // x' = and x, 0xff
  5788. // ...
  5789. // b1:
  5790. // z = use x'
  5791. //
  5792. // whereas:
  5793. //
  5794. // b0:
  5795. // x1 = load i32
  5796. // ...
  5797. // b1:
  5798. // x2 = load i32
  5799. // ...
  5800. // b2:
  5801. // x = phi x1, x2
  5802. // y = and x, 0xff
  5803. //
  5804. // becomes (after a call to optimizeLoadExt for each load):
  5805. //
  5806. // b0:
  5807. // x1 = load i32
  5808. // x1' = and x1, 0xff
  5809. // ...
  5810. // b1:
  5811. // x2 = load i32
  5812. // x2' = and x2, 0xff
  5813. // ...
  5814. // b2:
  5815. // x = phi x1', x2'
  5816. // y = and x, 0xff
  5817. bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
  5818. if (!Load->isSimple() || !Load->getType()->isIntOrPtrTy())
  5819. return false;
  5820. // Skip loads we've already transformed.
  5821. if (Load->hasOneUse() &&
  5822. InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
  5823. return false;
  5824. // Look at all uses of Load, looking through phis, to determine how many bits
  5825. // of the loaded value are needed.
  5826. SmallVector<Instruction *, 8> WorkList;
  5827. SmallPtrSet<Instruction *, 16> Visited;
  5828. SmallVector<Instruction *, 8> AndsToMaybeRemove;
  5829. for (auto *U : Load->users())
  5830. WorkList.push_back(cast<Instruction>(U));
  5831. EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
  5832. unsigned BitWidth = LoadResultVT.getSizeInBits();
  5833. // If the BitWidth is 0, do not try to optimize the type
  5834. if (BitWidth == 0)
  5835. return false;
  5836. APInt DemandBits(BitWidth, 0);
  5837. APInt WidestAndBits(BitWidth, 0);
  5838. while (!WorkList.empty()) {
  5839. Instruction *I = WorkList.pop_back_val();
  5840. // Break use-def graph loops.
  5841. if (!Visited.insert(I).second)
  5842. continue;
  5843. // For a PHI node, push all of its users.
  5844. if (auto *Phi = dyn_cast<PHINode>(I)) {
  5845. for (auto *U : Phi->users())
  5846. WorkList.push_back(cast<Instruction>(U));
  5847. continue;
  5848. }
  5849. switch (I->getOpcode()) {
  5850. case Instruction::And: {
  5851. auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
  5852. if (!AndC)
  5853. return false;
  5854. APInt AndBits = AndC->getValue();
  5855. DemandBits |= AndBits;
  5856. // Keep track of the widest and mask we see.
  5857. if (AndBits.ugt(WidestAndBits))
  5858. WidestAndBits = AndBits;
  5859. if (AndBits == WidestAndBits && I->getOperand(0) == Load)
  5860. AndsToMaybeRemove.push_back(I);
  5861. break;
  5862. }
  5863. case Instruction::Shl: {
  5864. auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
  5865. if (!ShlC)
  5866. return false;
  5867. uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
  5868. DemandBits.setLowBits(BitWidth - ShiftAmt);
  5869. break;
  5870. }
  5871. case Instruction::Trunc: {
  5872. EVT TruncVT = TLI->getValueType(*DL, I->getType());
  5873. unsigned TruncBitWidth = TruncVT.getSizeInBits();
  5874. DemandBits.setLowBits(TruncBitWidth);
  5875. break;
  5876. }
  5877. default:
  5878. return false;
  5879. }
  5880. }
  5881. uint32_t ActiveBits = DemandBits.getActiveBits();
  5882. // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
  5883. // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
  5884. // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
  5885. // (and (load x) 1) is not matched as a single instruction, rather as a LDR
  5886. // followed by an AND.
  5887. // TODO: Look into removing this restriction by fixing backends to either
  5888. // return false for isLoadExtLegal for i1 or have them select this pattern to
  5889. // a single instruction.
  5890. //
  5891. // Also avoid hoisting if we didn't see any ands with the exact DemandBits
  5892. // mask, since these are the only ands that will be removed by isel.
  5893. if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
  5894. WidestAndBits != DemandBits)
  5895. return false;
  5896. LLVMContext &Ctx = Load->getType()->getContext();
  5897. Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
  5898. EVT TruncVT = TLI->getValueType(*DL, TruncTy);
  5899. // Reject cases that won't be matched as extloads.
  5900. if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
  5901. !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
  5902. return false;
  5903. IRBuilder<> Builder(Load->getNextNode());
  5904. auto *NewAnd = cast<Instruction>(
  5905. Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
  5906. // Mark this instruction as "inserted by CGP", so that other
  5907. // optimizations don't touch it.
  5908. InsertedInsts.insert(NewAnd);
  5909. // Replace all uses of load with new and (except for the use of load in the
  5910. // new and itself).
  5911. replaceAllUsesWith(Load, NewAnd, FreshBBs, IsHugeFunc);
  5912. NewAnd->setOperand(0, Load);
  5913. // Remove any and instructions that are now redundant.
  5914. for (auto *And : AndsToMaybeRemove)
  5915. // Check that the and mask is the same as the one we decided to put on the
  5916. // new and.
  5917. if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
  5918. replaceAllUsesWith(And, NewAnd, FreshBBs, IsHugeFunc);
  5919. if (&*CurInstIterator == And)
  5920. CurInstIterator = std::next(And->getIterator());
  5921. And->eraseFromParent();
  5922. ++NumAndUses;
  5923. }
  5924. ++NumAndsAdded;
  5925. return true;
  5926. }
  5927. /// Check if V (an operand of a select instruction) is an expensive instruction
  5928. /// that is only used once.
  5929. static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
  5930. auto *I = dyn_cast<Instruction>(V);
  5931. // If it's safe to speculatively execute, then it should not have side
  5932. // effects; therefore, it's safe to sink and possibly *not* execute.
  5933. return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
  5934. TTI->isExpensiveToSpeculativelyExecute(I);
  5935. }
  5936. /// Returns true if a SelectInst should be turned into an explicit branch.
  5937. static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
  5938. const TargetLowering *TLI,
  5939. SelectInst *SI) {
  5940. // If even a predictable select is cheap, then a branch can't be cheaper.
  5941. if (!TLI->isPredictableSelectExpensive())
  5942. return false;
  5943. // FIXME: This should use the same heuristics as IfConversion to determine
  5944. // whether a select is better represented as a branch.
  5945. // If metadata tells us that the select condition is obviously predictable,
  5946. // then we want to replace the select with a branch.
  5947. uint64_t TrueWeight, FalseWeight;
  5948. if (extractBranchWeights(*SI, TrueWeight, FalseWeight)) {
  5949. uint64_t Max = std::max(TrueWeight, FalseWeight);
  5950. uint64_t Sum = TrueWeight + FalseWeight;
  5951. if (Sum != 0) {
  5952. auto Probability = BranchProbability::getBranchProbability(Max, Sum);
  5953. if (Probability > TTI->getPredictableBranchThreshold())
  5954. return true;
  5955. }
  5956. }
  5957. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  5958. // If a branch is predictable, an out-of-order CPU can avoid blocking on its
  5959. // comparison condition. If the compare has more than one use, there's
  5960. // probably another cmov or setcc around, so it's not worth emitting a branch.
  5961. if (!Cmp || !Cmp->hasOneUse())
  5962. return false;
  5963. // If either operand of the select is expensive and only needed on one side
  5964. // of the select, we should form a branch.
  5965. if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
  5966. sinkSelectOperand(TTI, SI->getFalseValue()))
  5967. return true;
  5968. return false;
  5969. }
  5970. /// If \p isTrue is true, return the true value of \p SI, otherwise return
  5971. /// false value of \p SI. If the true/false value of \p SI is defined by any
  5972. /// select instructions in \p Selects, look through the defining select
  5973. /// instruction until the true/false value is not defined in \p Selects.
  5974. static Value *
  5975. getTrueOrFalseValue(SelectInst *SI, bool isTrue,
  5976. const SmallPtrSet<const Instruction *, 2> &Selects) {
  5977. Value *V = nullptr;
  5978. for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
  5979. DefSI = dyn_cast<SelectInst>(V)) {
  5980. assert(DefSI->getCondition() == SI->getCondition() &&
  5981. "The condition of DefSI does not match with SI");
  5982. V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
  5983. }
  5984. assert(V && "Failed to get select true/false value");
  5985. return V;
  5986. }
  5987. bool CodeGenPrepare::optimizeShiftInst(BinaryOperator *Shift) {
  5988. assert(Shift->isShift() && "Expected a shift");
  5989. // If this is (1) a vector shift, (2) shifts by scalars are cheaper than
  5990. // general vector shifts, and (3) the shift amount is a select-of-splatted
  5991. // values, hoist the shifts before the select:
  5992. // shift Op0, (select Cond, TVal, FVal) -->
  5993. // select Cond, (shift Op0, TVal), (shift Op0, FVal)
  5994. //
  5995. // This is inverting a generic IR transform when we know that the cost of a
  5996. // general vector shift is more than the cost of 2 shift-by-scalars.
  5997. // We can't do this effectively in SDAG because we may not be able to
  5998. // determine if the select operands are splats from within a basic block.
  5999. Type *Ty = Shift->getType();
  6000. if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty))
  6001. return false;
  6002. Value *Cond, *TVal, *FVal;
  6003. if (!match(Shift->getOperand(1),
  6004. m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
  6005. return false;
  6006. if (!isSplatValue(TVal) || !isSplatValue(FVal))
  6007. return false;
  6008. IRBuilder<> Builder(Shift);
  6009. BinaryOperator::BinaryOps Opcode = Shift->getOpcode();
  6010. Value *NewTVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), TVal);
  6011. Value *NewFVal = Builder.CreateBinOp(Opcode, Shift->getOperand(0), FVal);
  6012. Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
  6013. replaceAllUsesWith(Shift, NewSel, FreshBBs, IsHugeFunc);
  6014. Shift->eraseFromParent();
  6015. return true;
  6016. }
  6017. bool CodeGenPrepare::optimizeFunnelShift(IntrinsicInst *Fsh) {
  6018. Intrinsic::ID Opcode = Fsh->getIntrinsicID();
  6019. assert((Opcode == Intrinsic::fshl || Opcode == Intrinsic::fshr) &&
  6020. "Expected a funnel shift");
  6021. // If this is (1) a vector funnel shift, (2) shifts by scalars are cheaper
  6022. // than general vector shifts, and (3) the shift amount is select-of-splatted
  6023. // values, hoist the funnel shifts before the select:
  6024. // fsh Op0, Op1, (select Cond, TVal, FVal) -->
  6025. // select Cond, (fsh Op0, Op1, TVal), (fsh Op0, Op1, FVal)
  6026. //
  6027. // This is inverting a generic IR transform when we know that the cost of a
  6028. // general vector shift is more than the cost of 2 shift-by-scalars.
  6029. // We can't do this effectively in SDAG because we may not be able to
  6030. // determine if the select operands are splats from within a basic block.
  6031. Type *Ty = Fsh->getType();
  6032. if (!Ty->isVectorTy() || !TLI->isVectorShiftByScalarCheap(Ty))
  6033. return false;
  6034. Value *Cond, *TVal, *FVal;
  6035. if (!match(Fsh->getOperand(2),
  6036. m_OneUse(m_Select(m_Value(Cond), m_Value(TVal), m_Value(FVal)))))
  6037. return false;
  6038. if (!isSplatValue(TVal) || !isSplatValue(FVal))
  6039. return false;
  6040. IRBuilder<> Builder(Fsh);
  6041. Value *X = Fsh->getOperand(0), *Y = Fsh->getOperand(1);
  6042. Value *NewTVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, TVal});
  6043. Value *NewFVal = Builder.CreateIntrinsic(Opcode, Ty, {X, Y, FVal});
  6044. Value *NewSel = Builder.CreateSelect(Cond, NewTVal, NewFVal);
  6045. replaceAllUsesWith(Fsh, NewSel, FreshBBs, IsHugeFunc);
  6046. Fsh->eraseFromParent();
  6047. return true;
  6048. }
  6049. /// If we have a SelectInst that will likely profit from branch prediction,
  6050. /// turn it into a branch.
  6051. bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
  6052. if (DisableSelectToBranch)
  6053. return false;
  6054. // If the SelectOptimize pass is enabled, selects have already been optimized.
  6055. if (!getCGPassBuilderOption().DisableSelectOptimize)
  6056. return false;
  6057. // Find all consecutive select instructions that share the same condition.
  6058. SmallVector<SelectInst *, 2> ASI;
  6059. ASI.push_back(SI);
  6060. for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
  6061. It != SI->getParent()->end(); ++It) {
  6062. SelectInst *I = dyn_cast<SelectInst>(&*It);
  6063. if (I && SI->getCondition() == I->getCondition()) {
  6064. ASI.push_back(I);
  6065. } else {
  6066. break;
  6067. }
  6068. }
  6069. SelectInst *LastSI = ASI.back();
  6070. // Increment the current iterator to skip all the rest of select instructions
  6071. // because they will be either "not lowered" or "all lowered" to branch.
  6072. CurInstIterator = std::next(LastSI->getIterator());
  6073. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  6074. // Can we convert the 'select' to CF ?
  6075. if (VectorCond || SI->getMetadata(LLVMContext::MD_unpredictable))
  6076. return false;
  6077. TargetLowering::SelectSupportKind SelectKind;
  6078. if (VectorCond)
  6079. SelectKind = TargetLowering::VectorMaskSelect;
  6080. else if (SI->getType()->isVectorTy())
  6081. SelectKind = TargetLowering::ScalarCondVectorVal;
  6082. else
  6083. SelectKind = TargetLowering::ScalarValSelect;
  6084. if (TLI->isSelectSupported(SelectKind) &&
  6085. (!isFormingBranchFromSelectProfitable(TTI, TLI, SI) || OptSize ||
  6086. llvm::shouldOptimizeForSize(SI->getParent(), PSI, BFI.get())))
  6087. return false;
  6088. // The DominatorTree needs to be rebuilt by any consumers after this
  6089. // transformation. We simply reset here rather than setting the ModifiedDT
  6090. // flag to avoid restarting the function walk in runOnFunction for each
  6091. // select optimized.
  6092. DT.reset();
  6093. // Transform a sequence like this:
  6094. // start:
  6095. // %cmp = cmp uge i32 %a, %b
  6096. // %sel = select i1 %cmp, i32 %c, i32 %d
  6097. //
  6098. // Into:
  6099. // start:
  6100. // %cmp = cmp uge i32 %a, %b
  6101. // %cmp.frozen = freeze %cmp
  6102. // br i1 %cmp.frozen, label %select.true, label %select.false
  6103. // select.true:
  6104. // br label %select.end
  6105. // select.false:
  6106. // br label %select.end
  6107. // select.end:
  6108. // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
  6109. //
  6110. // %cmp should be frozen, otherwise it may introduce undefined behavior.
  6111. // In addition, we may sink instructions that produce %c or %d from
  6112. // the entry block into the destination(s) of the new branch.
  6113. // If the true or false blocks do not contain a sunken instruction, that
  6114. // block and its branch may be optimized away. In that case, one side of the
  6115. // first branch will point directly to select.end, and the corresponding PHI
  6116. // predecessor block will be the start block.
  6117. // First, we split the block containing the select into 2 blocks.
  6118. BasicBlock *StartBlock = SI->getParent();
  6119. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
  6120. BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  6121. if (IsHugeFunc)
  6122. FreshBBs.insert(EndBlock);
  6123. BFI->setBlockFreq(EndBlock, BFI->getBlockFreq(StartBlock).getFrequency());
  6124. // Delete the unconditional branch that was just created by the split.
  6125. StartBlock->getTerminator()->eraseFromParent();
  6126. // These are the new basic blocks for the conditional branch.
  6127. // At least one will become an actual new basic block.
  6128. BasicBlock *TrueBlock = nullptr;
  6129. BasicBlock *FalseBlock = nullptr;
  6130. BranchInst *TrueBranch = nullptr;
  6131. BranchInst *FalseBranch = nullptr;
  6132. // Sink expensive instructions into the conditional blocks to avoid executing
  6133. // them speculatively.
  6134. for (SelectInst *SI : ASI) {
  6135. if (sinkSelectOperand(TTI, SI->getTrueValue())) {
  6136. if (TrueBlock == nullptr) {
  6137. TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
  6138. EndBlock->getParent(), EndBlock);
  6139. TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
  6140. if (IsHugeFunc)
  6141. FreshBBs.insert(TrueBlock);
  6142. TrueBranch->setDebugLoc(SI->getDebugLoc());
  6143. }
  6144. auto *TrueInst = cast<Instruction>(SI->getTrueValue());
  6145. TrueInst->moveBefore(TrueBranch);
  6146. }
  6147. if (sinkSelectOperand(TTI, SI->getFalseValue())) {
  6148. if (FalseBlock == nullptr) {
  6149. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
  6150. EndBlock->getParent(), EndBlock);
  6151. if (IsHugeFunc)
  6152. FreshBBs.insert(FalseBlock);
  6153. FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  6154. FalseBranch->setDebugLoc(SI->getDebugLoc());
  6155. }
  6156. auto *FalseInst = cast<Instruction>(SI->getFalseValue());
  6157. FalseInst->moveBefore(FalseBranch);
  6158. }
  6159. }
  6160. // If there was nothing to sink, then arbitrarily choose the 'false' side
  6161. // for a new input value to the PHI.
  6162. if (TrueBlock == FalseBlock) {
  6163. assert(TrueBlock == nullptr &&
  6164. "Unexpected basic block transform while optimizing select");
  6165. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
  6166. EndBlock->getParent(), EndBlock);
  6167. if (IsHugeFunc)
  6168. FreshBBs.insert(FalseBlock);
  6169. auto *FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  6170. FalseBranch->setDebugLoc(SI->getDebugLoc());
  6171. }
  6172. // Insert the real conditional branch based on the original condition.
  6173. // If we did not create a new block for one of the 'true' or 'false' paths
  6174. // of the condition, it means that side of the branch goes to the end block
  6175. // directly and the path originates from the start block from the point of
  6176. // view of the new PHI.
  6177. BasicBlock *TT, *FT;
  6178. if (TrueBlock == nullptr) {
  6179. TT = EndBlock;
  6180. FT = FalseBlock;
  6181. TrueBlock = StartBlock;
  6182. } else if (FalseBlock == nullptr) {
  6183. TT = TrueBlock;
  6184. FT = EndBlock;
  6185. FalseBlock = StartBlock;
  6186. } else {
  6187. TT = TrueBlock;
  6188. FT = FalseBlock;
  6189. }
  6190. IRBuilder<> IB(SI);
  6191. auto *CondFr = IB.CreateFreeze(SI->getCondition(), SI->getName() + ".frozen");
  6192. IB.CreateCondBr(CondFr, TT, FT, SI);
  6193. SmallPtrSet<const Instruction *, 2> INS;
  6194. INS.insert(ASI.begin(), ASI.end());
  6195. // Use reverse iterator because later select may use the value of the
  6196. // earlier select, and we need to propagate value through earlier select
  6197. // to get the PHI operand.
  6198. for (SelectInst *SI : llvm::reverse(ASI)) {
  6199. // The select itself is replaced with a PHI Node.
  6200. PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
  6201. PN->takeName(SI);
  6202. PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
  6203. PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
  6204. PN->setDebugLoc(SI->getDebugLoc());
  6205. replaceAllUsesWith(SI, PN, FreshBBs, IsHugeFunc);
  6206. SI->eraseFromParent();
  6207. INS.erase(SI);
  6208. ++NumSelectsExpanded;
  6209. }
  6210. // Instruct OptimizeBlock to skip to the next block.
  6211. CurInstIterator = StartBlock->end();
  6212. return true;
  6213. }
  6214. /// Some targets only accept certain types for splat inputs. For example a VDUP
  6215. /// in MVE takes a GPR (integer) register, and the instruction that incorporate
  6216. /// a VDUP (such as a VADD qd, qm, rm) also require a gpr register.
  6217. bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  6218. // Accept shuf(insertelem(undef/poison, val, 0), undef/poison, <0,0,..>) only
  6219. if (!match(SVI, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
  6220. m_Undef(), m_ZeroMask())))
  6221. return false;
  6222. Type *NewType = TLI->shouldConvertSplatType(SVI);
  6223. if (!NewType)
  6224. return false;
  6225. auto *SVIVecType = cast<FixedVectorType>(SVI->getType());
  6226. assert(!NewType->isVectorTy() && "Expected a scalar type!");
  6227. assert(NewType->getScalarSizeInBits() == SVIVecType->getScalarSizeInBits() &&
  6228. "Expected a type of the same size!");
  6229. auto *NewVecType =
  6230. FixedVectorType::get(NewType, SVIVecType->getNumElements());
  6231. // Create a bitcast (shuffle (insert (bitcast(..))))
  6232. IRBuilder<> Builder(SVI->getContext());
  6233. Builder.SetInsertPoint(SVI);
  6234. Value *BC1 = Builder.CreateBitCast(
  6235. cast<Instruction>(SVI->getOperand(0))->getOperand(1), NewType);
  6236. Value *Shuffle = Builder.CreateVectorSplat(NewVecType->getNumElements(), BC1);
  6237. Value *BC2 = Builder.CreateBitCast(Shuffle, SVIVecType);
  6238. replaceAllUsesWith(SVI, BC2, FreshBBs, IsHugeFunc);
  6239. RecursivelyDeleteTriviallyDeadInstructions(
  6240. SVI, TLInfo, nullptr,
  6241. [&](Value *V) { removeAllAssertingVHReferences(V); });
  6242. // Also hoist the bitcast up to its operand if it they are not in the same
  6243. // block.
  6244. if (auto *BCI = dyn_cast<Instruction>(BC1))
  6245. if (auto *Op = dyn_cast<Instruction>(BCI->getOperand(0)))
  6246. if (BCI->getParent() != Op->getParent() && !isa<PHINode>(Op) &&
  6247. !Op->isTerminator() && !Op->isEHPad())
  6248. BCI->moveAfter(Op);
  6249. return true;
  6250. }
  6251. bool CodeGenPrepare::tryToSinkFreeOperands(Instruction *I) {
  6252. // If the operands of I can be folded into a target instruction together with
  6253. // I, duplicate and sink them.
  6254. SmallVector<Use *, 4> OpsToSink;
  6255. if (!TLI->shouldSinkOperands(I, OpsToSink))
  6256. return false;
  6257. // OpsToSink can contain multiple uses in a use chain (e.g.
  6258. // (%u1 with %u1 = shufflevector), (%u2 with %u2 = zext %u1)). The dominating
  6259. // uses must come first, so we process the ops in reverse order so as to not
  6260. // create invalid IR.
  6261. BasicBlock *TargetBB = I->getParent();
  6262. bool Changed = false;
  6263. SmallVector<Use *, 4> ToReplace;
  6264. Instruction *InsertPoint = I;
  6265. DenseMap<const Instruction *, unsigned long> InstOrdering;
  6266. unsigned long InstNumber = 0;
  6267. for (const auto &I : *TargetBB)
  6268. InstOrdering[&I] = InstNumber++;
  6269. for (Use *U : reverse(OpsToSink)) {
  6270. auto *UI = cast<Instruction>(U->get());
  6271. if (isa<PHINode>(UI))
  6272. continue;
  6273. if (UI->getParent() == TargetBB) {
  6274. if (InstOrdering[UI] < InstOrdering[InsertPoint])
  6275. InsertPoint = UI;
  6276. continue;
  6277. }
  6278. ToReplace.push_back(U);
  6279. }
  6280. SetVector<Instruction *> MaybeDead;
  6281. DenseMap<Instruction *, Instruction *> NewInstructions;
  6282. for (Use *U : ToReplace) {
  6283. auto *UI = cast<Instruction>(U->get());
  6284. Instruction *NI = UI->clone();
  6285. if (IsHugeFunc) {
  6286. // Now we clone an instruction, its operands' defs may sink to this BB
  6287. // now. So we put the operands defs' BBs into FreshBBs to do optmization.
  6288. for (unsigned I = 0; I < NI->getNumOperands(); ++I) {
  6289. auto *OpDef = dyn_cast<Instruction>(NI->getOperand(I));
  6290. if (!OpDef)
  6291. continue;
  6292. FreshBBs.insert(OpDef->getParent());
  6293. }
  6294. }
  6295. NewInstructions[UI] = NI;
  6296. MaybeDead.insert(UI);
  6297. LLVM_DEBUG(dbgs() << "Sinking " << *UI << " to user " << *I << "\n");
  6298. NI->insertBefore(InsertPoint);
  6299. InsertPoint = NI;
  6300. InsertedInsts.insert(NI);
  6301. // Update the use for the new instruction, making sure that we update the
  6302. // sunk instruction uses, if it is part of a chain that has already been
  6303. // sunk.
  6304. Instruction *OldI = cast<Instruction>(U->getUser());
  6305. if (NewInstructions.count(OldI))
  6306. NewInstructions[OldI]->setOperand(U->getOperandNo(), NI);
  6307. else
  6308. U->set(NI);
  6309. Changed = true;
  6310. }
  6311. // Remove instructions that are dead after sinking.
  6312. for (auto *I : MaybeDead) {
  6313. if (!I->hasNUsesOrMore(1)) {
  6314. LLVM_DEBUG(dbgs() << "Removing dead instruction: " << *I << "\n");
  6315. I->eraseFromParent();
  6316. }
  6317. }
  6318. return Changed;
  6319. }
  6320. bool CodeGenPrepare::optimizeSwitchType(SwitchInst *SI) {
  6321. Value *Cond = SI->getCondition();
  6322. Type *OldType = Cond->getType();
  6323. LLVMContext &Context = Cond->getContext();
  6324. EVT OldVT = TLI->getValueType(*DL, OldType);
  6325. MVT RegType = TLI->getPreferredSwitchConditionType(Context, OldVT);
  6326. unsigned RegWidth = RegType.getSizeInBits();
  6327. if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
  6328. return false;
  6329. // If the register width is greater than the type width, expand the condition
  6330. // of the switch instruction and each case constant to the width of the
  6331. // register. By widening the type of the switch condition, subsequent
  6332. // comparisons (for case comparisons) will not need to be extended to the
  6333. // preferred register width, so we will potentially eliminate N-1 extends,
  6334. // where N is the number of cases in the switch.
  6335. auto *NewType = Type::getIntNTy(Context, RegWidth);
  6336. // Extend the switch condition and case constants using the target preferred
  6337. // extend unless the switch condition is a function argument with an extend
  6338. // attribute. In that case, we can avoid an unnecessary mask/extension by
  6339. // matching the argument extension instead.
  6340. Instruction::CastOps ExtType = Instruction::ZExt;
  6341. // Some targets prefer SExt over ZExt.
  6342. if (TLI->isSExtCheaperThanZExt(OldVT, RegType))
  6343. ExtType = Instruction::SExt;
  6344. if (auto *Arg = dyn_cast<Argument>(Cond)) {
  6345. if (Arg->hasSExtAttr())
  6346. ExtType = Instruction::SExt;
  6347. if (Arg->hasZExtAttr())
  6348. ExtType = Instruction::ZExt;
  6349. }
  6350. auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
  6351. ExtInst->insertBefore(SI);
  6352. ExtInst->setDebugLoc(SI->getDebugLoc());
  6353. SI->setCondition(ExtInst);
  6354. for (auto Case : SI->cases()) {
  6355. const APInt &NarrowConst = Case.getCaseValue()->getValue();
  6356. APInt WideConst = (ExtType == Instruction::ZExt)
  6357. ? NarrowConst.zext(RegWidth)
  6358. : NarrowConst.sext(RegWidth);
  6359. Case.setValue(ConstantInt::get(Context, WideConst));
  6360. }
  6361. return true;
  6362. }
  6363. bool CodeGenPrepare::optimizeSwitchPhiConstants(SwitchInst *SI) {
  6364. // The SCCP optimization tends to produce code like this:
  6365. // switch(x) { case 42: phi(42, ...) }
  6366. // Materializing the constant for the phi-argument needs instructions; So we
  6367. // change the code to:
  6368. // switch(x) { case 42: phi(x, ...) }
  6369. Value *Condition = SI->getCondition();
  6370. // Avoid endless loop in degenerate case.
  6371. if (isa<ConstantInt>(*Condition))
  6372. return false;
  6373. bool Changed = false;
  6374. BasicBlock *SwitchBB = SI->getParent();
  6375. Type *ConditionType = Condition->getType();
  6376. for (const SwitchInst::CaseHandle &Case : SI->cases()) {
  6377. ConstantInt *CaseValue = Case.getCaseValue();
  6378. BasicBlock *CaseBB = Case.getCaseSuccessor();
  6379. // Set to true if we previously checked that `CaseBB` is only reached by
  6380. // a single case from this switch.
  6381. bool CheckedForSinglePred = false;
  6382. for (PHINode &PHI : CaseBB->phis()) {
  6383. Type *PHIType = PHI.getType();
  6384. // If ZExt is free then we can also catch patterns like this:
  6385. // switch((i32)x) { case 42: phi((i64)42, ...); }
  6386. // and replace `(i64)42` with `zext i32 %x to i64`.
  6387. bool TryZExt =
  6388. PHIType->isIntegerTy() &&
  6389. PHIType->getIntegerBitWidth() > ConditionType->getIntegerBitWidth() &&
  6390. TLI->isZExtFree(ConditionType, PHIType);
  6391. if (PHIType == ConditionType || TryZExt) {
  6392. // Set to true to skip this case because of multiple preds.
  6393. bool SkipCase = false;
  6394. Value *Replacement = nullptr;
  6395. for (unsigned I = 0, E = PHI.getNumIncomingValues(); I != E; I++) {
  6396. Value *PHIValue = PHI.getIncomingValue(I);
  6397. if (PHIValue != CaseValue) {
  6398. if (!TryZExt)
  6399. continue;
  6400. ConstantInt *PHIValueInt = dyn_cast<ConstantInt>(PHIValue);
  6401. if (!PHIValueInt ||
  6402. PHIValueInt->getValue() !=
  6403. CaseValue->getValue().zext(PHIType->getIntegerBitWidth()))
  6404. continue;
  6405. }
  6406. if (PHI.getIncomingBlock(I) != SwitchBB)
  6407. continue;
  6408. // We cannot optimize if there are multiple case labels jumping to
  6409. // this block. This check may get expensive when there are many
  6410. // case labels so we test for it last.
  6411. if (!CheckedForSinglePred) {
  6412. CheckedForSinglePred = true;
  6413. if (SI->findCaseDest(CaseBB) == nullptr) {
  6414. SkipCase = true;
  6415. break;
  6416. }
  6417. }
  6418. if (Replacement == nullptr) {
  6419. if (PHIValue == CaseValue) {
  6420. Replacement = Condition;
  6421. } else {
  6422. IRBuilder<> Builder(SI);
  6423. Replacement = Builder.CreateZExt(Condition, PHIType);
  6424. }
  6425. }
  6426. PHI.setIncomingValue(I, Replacement);
  6427. Changed = true;
  6428. }
  6429. if (SkipCase)
  6430. break;
  6431. }
  6432. }
  6433. }
  6434. return Changed;
  6435. }
  6436. bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
  6437. bool Changed = optimizeSwitchType(SI);
  6438. Changed |= optimizeSwitchPhiConstants(SI);
  6439. return Changed;
  6440. }
  6441. namespace {
  6442. /// Helper class to promote a scalar operation to a vector one.
  6443. /// This class is used to move downward extractelement transition.
  6444. /// E.g.,
  6445. /// a = vector_op <2 x i32>
  6446. /// b = extractelement <2 x i32> a, i32 0
  6447. /// c = scalar_op b
  6448. /// store c
  6449. ///
  6450. /// =>
  6451. /// a = vector_op <2 x i32>
  6452. /// c = vector_op a (equivalent to scalar_op on the related lane)
  6453. /// * d = extractelement <2 x i32> c, i32 0
  6454. /// * store d
  6455. /// Assuming both extractelement and store can be combine, we get rid of the
  6456. /// transition.
  6457. class VectorPromoteHelper {
  6458. /// DataLayout associated with the current module.
  6459. const DataLayout &DL;
  6460. /// Used to perform some checks on the legality of vector operations.
  6461. const TargetLowering &TLI;
  6462. /// Used to estimated the cost of the promoted chain.
  6463. const TargetTransformInfo &TTI;
  6464. /// The transition being moved downwards.
  6465. Instruction *Transition;
  6466. /// The sequence of instructions to be promoted.
  6467. SmallVector<Instruction *, 4> InstsToBePromoted;
  6468. /// Cost of combining a store and an extract.
  6469. unsigned StoreExtractCombineCost;
  6470. /// Instruction that will be combined with the transition.
  6471. Instruction *CombineInst = nullptr;
  6472. /// The instruction that represents the current end of the transition.
  6473. /// Since we are faking the promotion until we reach the end of the chain
  6474. /// of computation, we need a way to get the current end of the transition.
  6475. Instruction *getEndOfTransition() const {
  6476. if (InstsToBePromoted.empty())
  6477. return Transition;
  6478. return InstsToBePromoted.back();
  6479. }
  6480. /// Return the index of the original value in the transition.
  6481. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  6482. /// c, is at index 0.
  6483. unsigned getTransitionOriginalValueIdx() const {
  6484. assert(isa<ExtractElementInst>(Transition) &&
  6485. "Other kind of transitions are not supported yet");
  6486. return 0;
  6487. }
  6488. /// Return the index of the index in the transition.
  6489. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  6490. /// is at index 1.
  6491. unsigned getTransitionIdx() const {
  6492. assert(isa<ExtractElementInst>(Transition) &&
  6493. "Other kind of transitions are not supported yet");
  6494. return 1;
  6495. }
  6496. /// Get the type of the transition.
  6497. /// This is the type of the original value.
  6498. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  6499. /// transition is <2 x i32>.
  6500. Type *getTransitionType() const {
  6501. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  6502. }
  6503. /// Promote \p ToBePromoted by moving \p Def downward through.
  6504. /// I.e., we have the following sequence:
  6505. /// Def = Transition <ty1> a to <ty2>
  6506. /// b = ToBePromoted <ty2> Def, ...
  6507. /// =>
  6508. /// b = ToBePromoted <ty1> a, ...
  6509. /// Def = Transition <ty1> ToBePromoted to <ty2>
  6510. void promoteImpl(Instruction *ToBePromoted);
  6511. /// Check whether or not it is profitable to promote all the
  6512. /// instructions enqueued to be promoted.
  6513. bool isProfitableToPromote() {
  6514. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  6515. unsigned Index = isa<ConstantInt>(ValIdx)
  6516. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  6517. : -1;
  6518. Type *PromotedType = getTransitionType();
  6519. StoreInst *ST = cast<StoreInst>(CombineInst);
  6520. unsigned AS = ST->getPointerAddressSpace();
  6521. // Check if this store is supported.
  6522. if (!TLI.allowsMisalignedMemoryAccesses(
  6523. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  6524. ST->getAlign())) {
  6525. // If this is not supported, there is no way we can combine
  6526. // the extract with the store.
  6527. return false;
  6528. }
  6529. // The scalar chain of computation has to pay for the transition
  6530. // scalar to vector.
  6531. // The vector chain has to account for the combining cost.
  6532. enum TargetTransformInfo::TargetCostKind CostKind =
  6533. TargetTransformInfo::TCK_RecipThroughput;
  6534. InstructionCost ScalarCost =
  6535. TTI.getVectorInstrCost(*Transition, PromotedType, CostKind, Index);
  6536. InstructionCost VectorCost = StoreExtractCombineCost;
  6537. for (const auto &Inst : InstsToBePromoted) {
  6538. // Compute the cost.
  6539. // By construction, all instructions being promoted are arithmetic ones.
  6540. // Moreover, one argument is a constant that can be viewed as a splat
  6541. // constant.
  6542. Value *Arg0 = Inst->getOperand(0);
  6543. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  6544. isa<ConstantFP>(Arg0);
  6545. TargetTransformInfo::OperandValueInfo Arg0Info, Arg1Info;
  6546. if (IsArg0Constant)
  6547. Arg0Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
  6548. else
  6549. Arg1Info.Kind = TargetTransformInfo::OK_UniformConstantValue;
  6550. ScalarCost += TTI.getArithmeticInstrCost(
  6551. Inst->getOpcode(), Inst->getType(), CostKind, Arg0Info, Arg1Info);
  6552. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  6553. CostKind, Arg0Info, Arg1Info);
  6554. }
  6555. LLVM_DEBUG(
  6556. dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  6557. << ScalarCost << "\nVector: " << VectorCost << '\n');
  6558. return ScalarCost > VectorCost;
  6559. }
  6560. /// Generate a constant vector with \p Val with the same
  6561. /// number of elements as the transition.
  6562. /// \p UseSplat defines whether or not \p Val should be replicated
  6563. /// across the whole vector.
  6564. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  6565. /// otherwise we generate a vector with as many undef as possible:
  6566. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  6567. /// used at the index of the extract.
  6568. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  6569. unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
  6570. if (!UseSplat) {
  6571. // If we cannot determine where the constant must be, we have to
  6572. // use a splat constant.
  6573. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  6574. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  6575. ExtractIdx = CstVal->getSExtValue();
  6576. else
  6577. UseSplat = true;
  6578. }
  6579. ElementCount EC = cast<VectorType>(getTransitionType())->getElementCount();
  6580. if (UseSplat)
  6581. return ConstantVector::getSplat(EC, Val);
  6582. if (!EC.isScalable()) {
  6583. SmallVector<Constant *, 4> ConstVec;
  6584. UndefValue *UndefVal = UndefValue::get(Val->getType());
  6585. for (unsigned Idx = 0; Idx != EC.getKnownMinValue(); ++Idx) {
  6586. if (Idx == ExtractIdx)
  6587. ConstVec.push_back(Val);
  6588. else
  6589. ConstVec.push_back(UndefVal);
  6590. }
  6591. return ConstantVector::get(ConstVec);
  6592. } else
  6593. llvm_unreachable(
  6594. "Generate scalable vector for non-splat is unimplemented");
  6595. }
  6596. /// Check if promoting to a vector type an operand at \p OperandIdx
  6597. /// in \p Use can trigger undefined behavior.
  6598. static bool canCauseUndefinedBehavior(const Instruction *Use,
  6599. unsigned OperandIdx) {
  6600. // This is not safe to introduce undef when the operand is on
  6601. // the right hand side of a division-like instruction.
  6602. if (OperandIdx != 1)
  6603. return false;
  6604. switch (Use->getOpcode()) {
  6605. default:
  6606. return false;
  6607. case Instruction::SDiv:
  6608. case Instruction::UDiv:
  6609. case Instruction::SRem:
  6610. case Instruction::URem:
  6611. return true;
  6612. case Instruction::FDiv:
  6613. case Instruction::FRem:
  6614. return !Use->hasNoNaNs();
  6615. }
  6616. llvm_unreachable(nullptr);
  6617. }
  6618. public:
  6619. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  6620. const TargetTransformInfo &TTI, Instruction *Transition,
  6621. unsigned CombineCost)
  6622. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  6623. StoreExtractCombineCost(CombineCost) {
  6624. assert(Transition && "Do not know how to promote null");
  6625. }
  6626. /// Check if we can promote \p ToBePromoted to \p Type.
  6627. bool canPromote(const Instruction *ToBePromoted) const {
  6628. // We could support CastInst too.
  6629. return isa<BinaryOperator>(ToBePromoted);
  6630. }
  6631. /// Check if it is profitable to promote \p ToBePromoted
  6632. /// by moving downward the transition through.
  6633. bool shouldPromote(const Instruction *ToBePromoted) const {
  6634. // Promote only if all the operands can be statically expanded.
  6635. // Indeed, we do not want to introduce any new kind of transitions.
  6636. for (const Use &U : ToBePromoted->operands()) {
  6637. const Value *Val = U.get();
  6638. if (Val == getEndOfTransition()) {
  6639. // If the use is a division and the transition is on the rhs,
  6640. // we cannot promote the operation, otherwise we may create a
  6641. // division by zero.
  6642. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  6643. return false;
  6644. continue;
  6645. }
  6646. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  6647. !isa<ConstantFP>(Val))
  6648. return false;
  6649. }
  6650. // Check that the resulting operation is legal.
  6651. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  6652. if (!ISDOpcode)
  6653. return false;
  6654. return StressStoreExtract ||
  6655. TLI.isOperationLegalOrCustom(
  6656. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  6657. }
  6658. /// Check whether or not \p Use can be combined
  6659. /// with the transition.
  6660. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  6661. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  6662. /// Record \p ToBePromoted as part of the chain to be promoted.
  6663. void enqueueForPromotion(Instruction *ToBePromoted) {
  6664. InstsToBePromoted.push_back(ToBePromoted);
  6665. }
  6666. /// Set the instruction that will be combined with the transition.
  6667. void recordCombineInstruction(Instruction *ToBeCombined) {
  6668. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  6669. CombineInst = ToBeCombined;
  6670. }
  6671. /// Promote all the instructions enqueued for promotion if it is
  6672. /// is profitable.
  6673. /// \return True if the promotion happened, false otherwise.
  6674. bool promote() {
  6675. // Check if there is something to promote.
  6676. // Right now, if we do not have anything to combine with,
  6677. // we assume the promotion is not profitable.
  6678. if (InstsToBePromoted.empty() || !CombineInst)
  6679. return false;
  6680. // Check cost.
  6681. if (!StressStoreExtract && !isProfitableToPromote())
  6682. return false;
  6683. // Promote.
  6684. for (auto &ToBePromoted : InstsToBePromoted)
  6685. promoteImpl(ToBePromoted);
  6686. InstsToBePromoted.clear();
  6687. return true;
  6688. }
  6689. };
  6690. } // end anonymous namespace
  6691. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  6692. // At this point, we know that all the operands of ToBePromoted but Def
  6693. // can be statically promoted.
  6694. // For Def, we need to use its parameter in ToBePromoted:
  6695. // b = ToBePromoted ty1 a
  6696. // Def = Transition ty1 b to ty2
  6697. // Move the transition down.
  6698. // 1. Replace all uses of the promoted operation by the transition.
  6699. // = ... b => = ... Def.
  6700. assert(ToBePromoted->getType() == Transition->getType() &&
  6701. "The type of the result of the transition does not match "
  6702. "the final type");
  6703. ToBePromoted->replaceAllUsesWith(Transition);
  6704. // 2. Update the type of the uses.
  6705. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  6706. Type *TransitionTy = getTransitionType();
  6707. ToBePromoted->mutateType(TransitionTy);
  6708. // 3. Update all the operands of the promoted operation with promoted
  6709. // operands.
  6710. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  6711. for (Use &U : ToBePromoted->operands()) {
  6712. Value *Val = U.get();
  6713. Value *NewVal = nullptr;
  6714. if (Val == Transition)
  6715. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  6716. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  6717. isa<ConstantFP>(Val)) {
  6718. // Use a splat constant if it is not safe to use undef.
  6719. NewVal = getConstantVector(
  6720. cast<Constant>(Val),
  6721. isa<UndefValue>(Val) ||
  6722. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  6723. } else
  6724. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  6725. "this?");
  6726. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  6727. }
  6728. Transition->moveAfter(ToBePromoted);
  6729. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  6730. }
  6731. /// Some targets can do store(extractelement) with one instruction.
  6732. /// Try to push the extractelement towards the stores when the target
  6733. /// has this feature and this is profitable.
  6734. bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
  6735. unsigned CombineCost = std::numeric_limits<unsigned>::max();
  6736. if (DisableStoreExtract ||
  6737. (!StressStoreExtract &&
  6738. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  6739. Inst->getOperand(1), CombineCost)))
  6740. return false;
  6741. // At this point we know that Inst is a vector to scalar transition.
  6742. // Try to move it down the def-use chain, until:
  6743. // - We can combine the transition with its single use
  6744. // => we got rid of the transition.
  6745. // - We escape the current basic block
  6746. // => we would need to check that we are moving it at a cheaper place and
  6747. // we do not do that for now.
  6748. BasicBlock *Parent = Inst->getParent();
  6749. LLVM_DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  6750. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  6751. // If the transition has more than one use, assume this is not going to be
  6752. // beneficial.
  6753. while (Inst->hasOneUse()) {
  6754. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  6755. LLVM_DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  6756. if (ToBePromoted->getParent() != Parent) {
  6757. LLVM_DEBUG(dbgs() << "Instruction to promote is in a different block ("
  6758. << ToBePromoted->getParent()->getName()
  6759. << ") than the transition (" << Parent->getName()
  6760. << ").\n");
  6761. return false;
  6762. }
  6763. if (VPH.canCombine(ToBePromoted)) {
  6764. LLVM_DEBUG(dbgs() << "Assume " << *Inst << '\n'
  6765. << "will be combined with: " << *ToBePromoted << '\n');
  6766. VPH.recordCombineInstruction(ToBePromoted);
  6767. bool Changed = VPH.promote();
  6768. NumStoreExtractExposed += Changed;
  6769. return Changed;
  6770. }
  6771. LLVM_DEBUG(dbgs() << "Try promoting.\n");
  6772. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  6773. return false;
  6774. LLVM_DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  6775. VPH.enqueueForPromotion(ToBePromoted);
  6776. Inst = ToBePromoted;
  6777. }
  6778. return false;
  6779. }
  6780. /// For the instruction sequence of store below, F and I values
  6781. /// are bundled together as an i64 value before being stored into memory.
  6782. /// Sometimes it is more efficient to generate separate stores for F and I,
  6783. /// which can remove the bitwise instructions or sink them to colder places.
  6784. ///
  6785. /// (store (or (zext (bitcast F to i32) to i64),
  6786. /// (shl (zext I to i64), 32)), addr) -->
  6787. /// (store F, addr) and (store I, addr+4)
  6788. ///
  6789. /// Similarly, splitting for other merged store can also be beneficial, like:
  6790. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  6791. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  6792. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  6793. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  6794. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  6795. ///
  6796. /// We allow each target to determine specifically which kind of splitting is
  6797. /// supported.
  6798. ///
  6799. /// The store patterns are commonly seen from the simple code snippet below
  6800. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  6801. /// void goo(const std::pair<int, float> &);
  6802. /// hoo() {
  6803. /// ...
  6804. /// goo(std::make_pair(tmp, ftmp));
  6805. /// ...
  6806. /// }
  6807. ///
  6808. /// Although we already have similar splitting in DAG Combine, we duplicate
  6809. /// it in CodeGenPrepare to catch the case in which pattern is across
  6810. /// multiple BBs. The logic in DAG Combine is kept to catch case generated
  6811. /// during code expansion.
  6812. static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
  6813. const TargetLowering &TLI) {
  6814. // Handle simple but common cases only.
  6815. Type *StoreType = SI.getValueOperand()->getType();
  6816. // The code below assumes shifting a value by <number of bits>,
  6817. // whereas scalable vectors would have to be shifted by
  6818. // <2log(vscale) + number of bits> in order to store the
  6819. // low/high parts. Bailing out for now.
  6820. if (isa<ScalableVectorType>(StoreType))
  6821. return false;
  6822. if (!DL.typeSizeEqualsStoreSize(StoreType) ||
  6823. DL.getTypeSizeInBits(StoreType) == 0)
  6824. return false;
  6825. unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
  6826. Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
  6827. if (!DL.typeSizeEqualsStoreSize(SplitStoreType))
  6828. return false;
  6829. // Don't split the store if it is volatile.
  6830. if (SI.isVolatile())
  6831. return false;
  6832. // Match the following patterns:
  6833. // (store (or (zext LValue to i64),
  6834. // (shl (zext HValue to i64), 32)), HalfValBitSize)
  6835. // or
  6836. // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
  6837. // (zext LValue to i64),
  6838. // Expect both operands of OR and the first operand of SHL have only
  6839. // one use.
  6840. Value *LValue, *HValue;
  6841. if (!match(SI.getValueOperand(),
  6842. m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
  6843. m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
  6844. m_SpecificInt(HalfValBitSize))))))
  6845. return false;
  6846. // Check LValue and HValue are int with size less or equal than 32.
  6847. if (!LValue->getType()->isIntegerTy() ||
  6848. DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
  6849. !HValue->getType()->isIntegerTy() ||
  6850. DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
  6851. return false;
  6852. // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
  6853. // as the input of target query.
  6854. auto *LBC = dyn_cast<BitCastInst>(LValue);
  6855. auto *HBC = dyn_cast<BitCastInst>(HValue);
  6856. EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
  6857. : EVT::getEVT(LValue->getType());
  6858. EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
  6859. : EVT::getEVT(HValue->getType());
  6860. if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  6861. return false;
  6862. // Start to split store.
  6863. IRBuilder<> Builder(SI.getContext());
  6864. Builder.SetInsertPoint(&SI);
  6865. // If LValue/HValue is a bitcast in another BB, create a new one in current
  6866. // BB so it may be merged with the splitted stores by dag combiner.
  6867. if (LBC && LBC->getParent() != SI.getParent())
  6868. LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
  6869. if (HBC && HBC->getParent() != SI.getParent())
  6870. HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
  6871. bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
  6872. auto CreateSplitStore = [&](Value *V, bool Upper) {
  6873. V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
  6874. Value *Addr = Builder.CreateBitCast(
  6875. SI.getOperand(1),
  6876. SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
  6877. Align Alignment = SI.getAlign();
  6878. const bool IsOffsetStore = (IsLE && Upper) || (!IsLE && !Upper);
  6879. if (IsOffsetStore) {
  6880. Addr = Builder.CreateGEP(
  6881. SplitStoreType, Addr,
  6882. ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
  6883. // When splitting the store in half, naturally one half will retain the
  6884. // alignment of the original wider store, regardless of whether it was
  6885. // over-aligned or not, while the other will require adjustment.
  6886. Alignment = commonAlignment(Alignment, HalfValBitSize / 8);
  6887. }
  6888. Builder.CreateAlignedStore(V, Addr, Alignment);
  6889. };
  6890. CreateSplitStore(LValue, false);
  6891. CreateSplitStore(HValue, true);
  6892. // Delete the old store.
  6893. SI.eraseFromParent();
  6894. return true;
  6895. }
  6896. // Return true if the GEP has two operands, the first operand is of a sequential
  6897. // type, and the second operand is a constant.
  6898. static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
  6899. gep_type_iterator I = gep_type_begin(*GEP);
  6900. return GEP->getNumOperands() == 2 && I.isSequential() &&
  6901. isa<ConstantInt>(GEP->getOperand(1));
  6902. }
  6903. // Try unmerging GEPs to reduce liveness interference (register pressure) across
  6904. // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
  6905. // reducing liveness interference across those edges benefits global register
  6906. // allocation. Currently handles only certain cases.
  6907. //
  6908. // For example, unmerge %GEPI and %UGEPI as below.
  6909. //
  6910. // ---------- BEFORE ----------
  6911. // SrcBlock:
  6912. // ...
  6913. // %GEPIOp = ...
  6914. // ...
  6915. // %GEPI = gep %GEPIOp, Idx
  6916. // ...
  6917. // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
  6918. // (* %GEPI is alive on the indirectbr edges due to other uses ahead)
  6919. // (* %GEPIOp is alive on the indirectbr edges only because of it's used by
  6920. // %UGEPI)
  6921. //
  6922. // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
  6923. // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
  6924. // ...
  6925. //
  6926. // DstBi:
  6927. // ...
  6928. // %UGEPI = gep %GEPIOp, UIdx
  6929. // ...
  6930. // ---------------------------
  6931. //
  6932. // ---------- AFTER ----------
  6933. // SrcBlock:
  6934. // ... (same as above)
  6935. // (* %GEPI is still alive on the indirectbr edges)
  6936. // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
  6937. // unmerging)
  6938. // ...
  6939. //
  6940. // DstBi:
  6941. // ...
  6942. // %UGEPI = gep %GEPI, (UIdx-Idx)
  6943. // ...
  6944. // ---------------------------
  6945. //
  6946. // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
  6947. // no longer alive on them.
  6948. //
  6949. // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
  6950. // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
  6951. // not to disable further simplications and optimizations as a result of GEP
  6952. // merging.
  6953. //
  6954. // Note this unmerging may increase the length of the data flow critical path
  6955. // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
  6956. // between the register pressure and the length of data-flow critical
  6957. // path. Restricting this to the uncommon IndirectBr case would minimize the
  6958. // impact of potentially longer critical path, if any, and the impact on compile
  6959. // time.
  6960. static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
  6961. const TargetTransformInfo *TTI) {
  6962. BasicBlock *SrcBlock = GEPI->getParent();
  6963. // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
  6964. // (non-IndirectBr) cases exit early here.
  6965. if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
  6966. return false;
  6967. // Check that GEPI is a simple gep with a single constant index.
  6968. if (!GEPSequentialConstIndexed(GEPI))
  6969. return false;
  6970. ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
  6971. // Check that GEPI is a cheap one.
  6972. if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType(),
  6973. TargetTransformInfo::TCK_SizeAndLatency) >
  6974. TargetTransformInfo::TCC_Basic)
  6975. return false;
  6976. Value *GEPIOp = GEPI->getOperand(0);
  6977. // Check that GEPIOp is an instruction that's also defined in SrcBlock.
  6978. if (!isa<Instruction>(GEPIOp))
  6979. return false;
  6980. auto *GEPIOpI = cast<Instruction>(GEPIOp);
  6981. if (GEPIOpI->getParent() != SrcBlock)
  6982. return false;
  6983. // Check that GEP is used outside the block, meaning it's alive on the
  6984. // IndirectBr edge(s).
  6985. if (llvm::none_of(GEPI->users(), [&](User *Usr) {
  6986. if (auto *I = dyn_cast<Instruction>(Usr)) {
  6987. if (I->getParent() != SrcBlock) {
  6988. return true;
  6989. }
  6990. }
  6991. return false;
  6992. }))
  6993. return false;
  6994. // The second elements of the GEP chains to be unmerged.
  6995. std::vector<GetElementPtrInst *> UGEPIs;
  6996. // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
  6997. // on IndirectBr edges.
  6998. for (User *Usr : GEPIOp->users()) {
  6999. if (Usr == GEPI)
  7000. continue;
  7001. // Check if Usr is an Instruction. If not, give up.
  7002. if (!isa<Instruction>(Usr))
  7003. return false;
  7004. auto *UI = cast<Instruction>(Usr);
  7005. // Check if Usr in the same block as GEPIOp, which is fine, skip.
  7006. if (UI->getParent() == SrcBlock)
  7007. continue;
  7008. // Check if Usr is a GEP. If not, give up.
  7009. if (!isa<GetElementPtrInst>(Usr))
  7010. return false;
  7011. auto *UGEPI = cast<GetElementPtrInst>(Usr);
  7012. // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
  7013. // the pointer operand to it. If so, record it in the vector. If not, give
  7014. // up.
  7015. if (!GEPSequentialConstIndexed(UGEPI))
  7016. return false;
  7017. if (UGEPI->getOperand(0) != GEPIOp)
  7018. return false;
  7019. if (GEPIIdx->getType() !=
  7020. cast<ConstantInt>(UGEPI->getOperand(1))->getType())
  7021. return false;
  7022. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  7023. if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType(),
  7024. TargetTransformInfo::TCK_SizeAndLatency) >
  7025. TargetTransformInfo::TCC_Basic)
  7026. return false;
  7027. UGEPIs.push_back(UGEPI);
  7028. }
  7029. if (UGEPIs.size() == 0)
  7030. return false;
  7031. // Check the materializing cost of (Uidx-Idx).
  7032. for (GetElementPtrInst *UGEPI : UGEPIs) {
  7033. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  7034. APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
  7035. InstructionCost ImmCost = TTI->getIntImmCost(
  7036. NewIdx, GEPIIdx->getType(), TargetTransformInfo::TCK_SizeAndLatency);
  7037. if (ImmCost > TargetTransformInfo::TCC_Basic)
  7038. return false;
  7039. }
  7040. // Now unmerge between GEPI and UGEPIs.
  7041. for (GetElementPtrInst *UGEPI : UGEPIs) {
  7042. UGEPI->setOperand(0, GEPI);
  7043. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  7044. Constant *NewUGEPIIdx = ConstantInt::get(
  7045. GEPIIdx->getType(), UGEPIIdx->getValue() - GEPIIdx->getValue());
  7046. UGEPI->setOperand(1, NewUGEPIIdx);
  7047. // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
  7048. // inbounds to avoid UB.
  7049. if (!GEPI->isInBounds()) {
  7050. UGEPI->setIsInBounds(false);
  7051. }
  7052. }
  7053. // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
  7054. // alive on IndirectBr edges).
  7055. assert(llvm::none_of(GEPIOp->users(),
  7056. [&](User *Usr) {
  7057. return cast<Instruction>(Usr)->getParent() != SrcBlock;
  7058. }) &&
  7059. "GEPIOp is used outside SrcBlock");
  7060. return true;
  7061. }
  7062. static bool optimizeBranch(BranchInst *Branch, const TargetLowering &TLI,
  7063. SmallSet<BasicBlock *, 32> &FreshBBs,
  7064. bool IsHugeFunc) {
  7065. // Try and convert
  7066. // %c = icmp ult %x, 8
  7067. // br %c, bla, blb
  7068. // %tc = lshr %x, 3
  7069. // to
  7070. // %tc = lshr %x, 3
  7071. // %c = icmp eq %tc, 0
  7072. // br %c, bla, blb
  7073. // Creating the cmp to zero can be better for the backend, especially if the
  7074. // lshr produces flags that can be used automatically.
  7075. if (!TLI.preferZeroCompareBranch() || !Branch->isConditional())
  7076. return false;
  7077. ICmpInst *Cmp = dyn_cast<ICmpInst>(Branch->getCondition());
  7078. if (!Cmp || !isa<ConstantInt>(Cmp->getOperand(1)) || !Cmp->hasOneUse())
  7079. return false;
  7080. Value *X = Cmp->getOperand(0);
  7081. APInt CmpC = cast<ConstantInt>(Cmp->getOperand(1))->getValue();
  7082. for (auto *U : X->users()) {
  7083. Instruction *UI = dyn_cast<Instruction>(U);
  7084. // A quick dominance check
  7085. if (!UI ||
  7086. (UI->getParent() != Branch->getParent() &&
  7087. UI->getParent() != Branch->getSuccessor(0) &&
  7088. UI->getParent() != Branch->getSuccessor(1)) ||
  7089. (UI->getParent() != Branch->getParent() &&
  7090. !UI->getParent()->getSinglePredecessor()))
  7091. continue;
  7092. if (CmpC.isPowerOf2() && Cmp->getPredicate() == ICmpInst::ICMP_ULT &&
  7093. match(UI, m_Shr(m_Specific(X), m_SpecificInt(CmpC.logBase2())))) {
  7094. IRBuilder<> Builder(Branch);
  7095. if (UI->getParent() != Branch->getParent())
  7096. UI->moveBefore(Branch);
  7097. Value *NewCmp = Builder.CreateCmp(ICmpInst::ICMP_EQ, UI,
  7098. ConstantInt::get(UI->getType(), 0));
  7099. LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
  7100. LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
  7101. replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
  7102. return true;
  7103. }
  7104. if (Cmp->isEquality() &&
  7105. (match(UI, m_Add(m_Specific(X), m_SpecificInt(-CmpC))) ||
  7106. match(UI, m_Sub(m_Specific(X), m_SpecificInt(CmpC))))) {
  7107. IRBuilder<> Builder(Branch);
  7108. if (UI->getParent() != Branch->getParent())
  7109. UI->moveBefore(Branch);
  7110. Value *NewCmp = Builder.CreateCmp(Cmp->getPredicate(), UI,
  7111. ConstantInt::get(UI->getType(), 0));
  7112. LLVM_DEBUG(dbgs() << "Converting " << *Cmp << "\n");
  7113. LLVM_DEBUG(dbgs() << " to compare on zero: " << *NewCmp << "\n");
  7114. replaceAllUsesWith(Cmp, NewCmp, FreshBBs, IsHugeFunc);
  7115. return true;
  7116. }
  7117. }
  7118. return false;
  7119. }
  7120. bool CodeGenPrepare::optimizeInst(Instruction *I, ModifyDT &ModifiedDT) {
  7121. // Bail out if we inserted the instruction to prevent optimizations from
  7122. // stepping on each other's toes.
  7123. if (InsertedInsts.count(I))
  7124. return false;
  7125. // TODO: Move into the switch on opcode below here.
  7126. if (PHINode *P = dyn_cast<PHINode>(I)) {
  7127. // It is possible for very late stage optimizations (such as SimplifyCFG)
  7128. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  7129. // trivial PHI, go ahead and zap it here.
  7130. if (Value *V = simplifyInstruction(P, {*DL, TLInfo})) {
  7131. LargeOffsetGEPMap.erase(P);
  7132. replaceAllUsesWith(P, V, FreshBBs, IsHugeFunc);
  7133. P->eraseFromParent();
  7134. ++NumPHIsElim;
  7135. return true;
  7136. }
  7137. return false;
  7138. }
  7139. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  7140. // If the source of the cast is a constant, then this should have
  7141. // already been constant folded. The only reason NOT to constant fold
  7142. // it is if something (e.g. LSR) was careful to place the constant
  7143. // evaluation in a block other than then one that uses it (e.g. to hoist
  7144. // the address of globals out of a loop). If this is the case, we don't
  7145. // want to forward-subst the cast.
  7146. if (isa<Constant>(CI->getOperand(0)))
  7147. return false;
  7148. if (OptimizeNoopCopyExpression(CI, *TLI, *DL))
  7149. return true;
  7150. if ((isa<UIToFPInst>(I) || isa<FPToUIInst>(I) || isa<TruncInst>(I)) &&
  7151. TLI->optimizeExtendOrTruncateConversion(I,
  7152. LI->getLoopFor(I->getParent())))
  7153. return true;
  7154. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  7155. /// Sink a zext or sext into its user blocks if the target type doesn't
  7156. /// fit in one register
  7157. if (TLI->getTypeAction(CI->getContext(),
  7158. TLI->getValueType(*DL, CI->getType())) ==
  7159. TargetLowering::TypeExpandInteger) {
  7160. return SinkCast(CI);
  7161. } else {
  7162. if (TLI->optimizeExtendOrTruncateConversion(
  7163. I, LI->getLoopFor(I->getParent())))
  7164. return true;
  7165. bool MadeChange = optimizeExt(I);
  7166. return MadeChange | optimizeExtUses(I);
  7167. }
  7168. }
  7169. return false;
  7170. }
  7171. if (auto *Cmp = dyn_cast<CmpInst>(I))
  7172. if (optimizeCmp(Cmp, ModifiedDT))
  7173. return true;
  7174. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  7175. LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  7176. bool Modified = optimizeLoadExt(LI);
  7177. unsigned AS = LI->getPointerAddressSpace();
  7178. Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  7179. return Modified;
  7180. }
  7181. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  7182. if (splitMergedValStore(*SI, *DL, *TLI))
  7183. return true;
  7184. SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  7185. unsigned AS = SI->getPointerAddressSpace();
  7186. return optimizeMemoryInst(I, SI->getOperand(1),
  7187. SI->getOperand(0)->getType(), AS);
  7188. }
  7189. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  7190. unsigned AS = RMW->getPointerAddressSpace();
  7191. return optimizeMemoryInst(I, RMW->getPointerOperand(), RMW->getType(), AS);
  7192. }
  7193. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
  7194. unsigned AS = CmpX->getPointerAddressSpace();
  7195. return optimizeMemoryInst(I, CmpX->getPointerOperand(),
  7196. CmpX->getCompareOperand()->getType(), AS);
  7197. }
  7198. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  7199. if (BinOp && BinOp->getOpcode() == Instruction::And && EnableAndCmpSinking &&
  7200. sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts))
  7201. return true;
  7202. // TODO: Move this into the switch on opcode - it handles shifts already.
  7203. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  7204. BinOp->getOpcode() == Instruction::LShr)) {
  7205. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  7206. if (CI && TLI->hasExtractBitsInsn())
  7207. if (OptimizeExtractBits(BinOp, CI, *TLI, *DL))
  7208. return true;
  7209. }
  7210. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  7211. if (GEPI->hasAllZeroIndices()) {
  7212. /// The GEP operand must be a pointer, so must its result -> BitCast
  7213. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  7214. GEPI->getName(), GEPI);
  7215. NC->setDebugLoc(GEPI->getDebugLoc());
  7216. replaceAllUsesWith(GEPI, NC, FreshBBs, IsHugeFunc);
  7217. GEPI->eraseFromParent();
  7218. ++NumGEPsElim;
  7219. optimizeInst(NC, ModifiedDT);
  7220. return true;
  7221. }
  7222. if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
  7223. return true;
  7224. }
  7225. return false;
  7226. }
  7227. if (FreezeInst *FI = dyn_cast<FreezeInst>(I)) {
  7228. // freeze(icmp a, const)) -> icmp (freeze a), const
  7229. // This helps generate efficient conditional jumps.
  7230. Instruction *CmpI = nullptr;
  7231. if (ICmpInst *II = dyn_cast<ICmpInst>(FI->getOperand(0)))
  7232. CmpI = II;
  7233. else if (FCmpInst *F = dyn_cast<FCmpInst>(FI->getOperand(0)))
  7234. CmpI = F->getFastMathFlags().none() ? F : nullptr;
  7235. if (CmpI && CmpI->hasOneUse()) {
  7236. auto Op0 = CmpI->getOperand(0), Op1 = CmpI->getOperand(1);
  7237. bool Const0 = isa<ConstantInt>(Op0) || isa<ConstantFP>(Op0) ||
  7238. isa<ConstantPointerNull>(Op0);
  7239. bool Const1 = isa<ConstantInt>(Op1) || isa<ConstantFP>(Op1) ||
  7240. isa<ConstantPointerNull>(Op1);
  7241. if (Const0 || Const1) {
  7242. if (!Const0 || !Const1) {
  7243. auto *F = new FreezeInst(Const0 ? Op1 : Op0, "", CmpI);
  7244. F->takeName(FI);
  7245. CmpI->setOperand(Const0 ? 1 : 0, F);
  7246. }
  7247. replaceAllUsesWith(FI, CmpI, FreshBBs, IsHugeFunc);
  7248. FI->eraseFromParent();
  7249. return true;
  7250. }
  7251. }
  7252. return false;
  7253. }
  7254. if (tryToSinkFreeOperands(I))
  7255. return true;
  7256. switch (I->getOpcode()) {
  7257. case Instruction::Shl:
  7258. case Instruction::LShr:
  7259. case Instruction::AShr:
  7260. return optimizeShiftInst(cast<BinaryOperator>(I));
  7261. case Instruction::Call:
  7262. return optimizeCallInst(cast<CallInst>(I), ModifiedDT);
  7263. case Instruction::Select:
  7264. return optimizeSelectInst(cast<SelectInst>(I));
  7265. case Instruction::ShuffleVector:
  7266. return optimizeShuffleVectorInst(cast<ShuffleVectorInst>(I));
  7267. case Instruction::Switch:
  7268. return optimizeSwitchInst(cast<SwitchInst>(I));
  7269. case Instruction::ExtractElement:
  7270. return optimizeExtractElementInst(cast<ExtractElementInst>(I));
  7271. case Instruction::Br:
  7272. return optimizeBranch(cast<BranchInst>(I), *TLI, FreshBBs, IsHugeFunc);
  7273. }
  7274. return false;
  7275. }
  7276. /// Given an OR instruction, check to see if this is a bitreverse
  7277. /// idiom. If so, insert the new intrinsic and return true.
  7278. bool CodeGenPrepare::makeBitReverse(Instruction &I) {
  7279. if (!I.getType()->isIntegerTy() ||
  7280. !TLI->isOperationLegalOrCustom(ISD::BITREVERSE,
  7281. TLI->getValueType(*DL, I.getType(), true)))
  7282. return false;
  7283. SmallVector<Instruction *, 4> Insts;
  7284. if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
  7285. return false;
  7286. Instruction *LastInst = Insts.back();
  7287. replaceAllUsesWith(&I, LastInst, FreshBBs, IsHugeFunc);
  7288. RecursivelyDeleteTriviallyDeadInstructions(
  7289. &I, TLInfo, nullptr,
  7290. [&](Value *V) { removeAllAssertingVHReferences(V); });
  7291. return true;
  7292. }
  7293. // In this pass we look for GEP and cast instructions that are used
  7294. // across basic blocks and rewrite them to improve basic-block-at-a-time
  7295. // selection.
  7296. bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, ModifyDT &ModifiedDT) {
  7297. SunkAddrs.clear();
  7298. bool MadeChange = false;
  7299. do {
  7300. CurInstIterator = BB.begin();
  7301. ModifiedDT = ModifyDT::NotModifyDT;
  7302. while (CurInstIterator != BB.end()) {
  7303. MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
  7304. if (ModifiedDT != ModifyDT::NotModifyDT) {
  7305. // For huge function we tend to quickly go though the inner optmization
  7306. // opportunities in the BB. So we go back to the BB head to re-optimize
  7307. // each instruction instead of go back to the function head.
  7308. if (IsHugeFunc) {
  7309. DT.reset();
  7310. getDT(*BB.getParent());
  7311. break;
  7312. } else {
  7313. return true;
  7314. }
  7315. }
  7316. }
  7317. } while (ModifiedDT == ModifyDT::ModifyInstDT);
  7318. bool MadeBitReverse = true;
  7319. while (MadeBitReverse) {
  7320. MadeBitReverse = false;
  7321. for (auto &I : reverse(BB)) {
  7322. if (makeBitReverse(I)) {
  7323. MadeBitReverse = MadeChange = true;
  7324. break;
  7325. }
  7326. }
  7327. }
  7328. MadeChange |= dupRetToEnableTailCallOpts(&BB, ModifiedDT);
  7329. return MadeChange;
  7330. }
  7331. // Some CGP optimizations may move or alter what's computed in a block. Check
  7332. // whether a dbg.value intrinsic could be pointed at a more appropriate operand.
  7333. bool CodeGenPrepare::fixupDbgValue(Instruction *I) {
  7334. assert(isa<DbgValueInst>(I));
  7335. DbgValueInst &DVI = *cast<DbgValueInst>(I);
  7336. // Does this dbg.value refer to a sunk address calculation?
  7337. bool AnyChange = false;
  7338. SmallDenseSet<Value *> LocationOps(DVI.location_ops().begin(),
  7339. DVI.location_ops().end());
  7340. for (Value *Location : LocationOps) {
  7341. WeakTrackingVH SunkAddrVH = SunkAddrs[Location];
  7342. Value *SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
  7343. if (SunkAddr) {
  7344. // Point dbg.value at locally computed address, which should give the best
  7345. // opportunity to be accurately lowered. This update may change the type
  7346. // of pointer being referred to; however this makes no difference to
  7347. // debugging information, and we can't generate bitcasts that may affect
  7348. // codegen.
  7349. DVI.replaceVariableLocationOp(Location, SunkAddr);
  7350. AnyChange = true;
  7351. }
  7352. }
  7353. return AnyChange;
  7354. }
  7355. // A llvm.dbg.value may be using a value before its definition, due to
  7356. // optimizations in this pass and others. Scan for such dbg.values, and rescue
  7357. // them by moving the dbg.value to immediately after the value definition.
  7358. // FIXME: Ideally this should never be necessary, and this has the potential
  7359. // to re-order dbg.value intrinsics.
  7360. bool CodeGenPrepare::placeDbgValues(Function &F) {
  7361. bool MadeChange = false;
  7362. DominatorTree DT(F);
  7363. for (BasicBlock &BB : F) {
  7364. for (Instruction &Insn : llvm::make_early_inc_range(BB)) {
  7365. DbgValueInst *DVI = dyn_cast<DbgValueInst>(&Insn);
  7366. if (!DVI)
  7367. continue;
  7368. SmallVector<Instruction *, 4> VIs;
  7369. for (Value *V : DVI->getValues())
  7370. if (Instruction *VI = dyn_cast_or_null<Instruction>(V))
  7371. VIs.push_back(VI);
  7372. // This DVI may depend on multiple instructions, complicating any
  7373. // potential sink. This block takes the defensive approach, opting to
  7374. // "undef" the DVI if it has more than one instruction and any of them do
  7375. // not dominate DVI.
  7376. for (Instruction *VI : VIs) {
  7377. if (VI->isTerminator())
  7378. continue;
  7379. // If VI is a phi in a block with an EHPad terminator, we can't insert
  7380. // after it.
  7381. if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
  7382. continue;
  7383. // If the defining instruction dominates the dbg.value, we do not need
  7384. // to move the dbg.value.
  7385. if (DT.dominates(VI, DVI))
  7386. continue;
  7387. // If we depend on multiple instructions and any of them doesn't
  7388. // dominate this DVI, we probably can't salvage it: moving it to
  7389. // after any of the instructions could cause us to lose the others.
  7390. if (VIs.size() > 1) {
  7391. LLVM_DEBUG(
  7392. dbgs()
  7393. << "Unable to find valid location for Debug Value, undefing:\n"
  7394. << *DVI);
  7395. DVI->setKillLocation();
  7396. break;
  7397. }
  7398. LLVM_DEBUG(dbgs() << "Moving Debug Value before :\n"
  7399. << *DVI << ' ' << *VI);
  7400. DVI->removeFromParent();
  7401. if (isa<PHINode>(VI))
  7402. DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
  7403. else
  7404. DVI->insertAfter(VI);
  7405. MadeChange = true;
  7406. ++NumDbgValueMoved;
  7407. }
  7408. }
  7409. }
  7410. return MadeChange;
  7411. }
  7412. // Group scattered pseudo probes in a block to favor SelectionDAG. Scattered
  7413. // probes can be chained dependencies of other regular DAG nodes and block DAG
  7414. // combine optimizations.
  7415. bool CodeGenPrepare::placePseudoProbes(Function &F) {
  7416. bool MadeChange = false;
  7417. for (auto &Block : F) {
  7418. // Move the rest probes to the beginning of the block.
  7419. auto FirstInst = Block.getFirstInsertionPt();
  7420. while (FirstInst != Block.end() && FirstInst->isDebugOrPseudoInst())
  7421. ++FirstInst;
  7422. BasicBlock::iterator I(FirstInst);
  7423. I++;
  7424. while (I != Block.end()) {
  7425. if (auto *II = dyn_cast<PseudoProbeInst>(I++)) {
  7426. II->moveBefore(&*FirstInst);
  7427. MadeChange = true;
  7428. }
  7429. }
  7430. }
  7431. return MadeChange;
  7432. }
  7433. /// Scale down both weights to fit into uint32_t.
  7434. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  7435. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  7436. uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
  7437. NewTrue = NewTrue / Scale;
  7438. NewFalse = NewFalse / Scale;
  7439. }
  7440. /// Some targets prefer to split a conditional branch like:
  7441. /// \code
  7442. /// %0 = icmp ne i32 %a, 0
  7443. /// %1 = icmp ne i32 %b, 0
  7444. /// %or.cond = or i1 %0, %1
  7445. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  7446. /// \endcode
  7447. /// into multiple branch instructions like:
  7448. /// \code
  7449. /// bb1:
  7450. /// %0 = icmp ne i32 %a, 0
  7451. /// br i1 %0, label %TrueBB, label %bb2
  7452. /// bb2:
  7453. /// %1 = icmp ne i32 %b, 0
  7454. /// br i1 %1, label %TrueBB, label %FalseBB
  7455. /// \endcode
  7456. /// This usually allows instruction selection to do even further optimizations
  7457. /// and combine the compare with the branch instruction. Currently this is
  7458. /// applied for targets which have "cheap" jump instructions.
  7459. ///
  7460. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  7461. ///
  7462. bool CodeGenPrepare::splitBranchCondition(Function &F, ModifyDT &ModifiedDT) {
  7463. if (!TM->Options.EnableFastISel || TLI->isJumpExpensive())
  7464. return false;
  7465. bool MadeChange = false;
  7466. for (auto &BB : F) {
  7467. // Does this BB end with the following?
  7468. // %cond1 = icmp|fcmp|binary instruction ...
  7469. // %cond2 = icmp|fcmp|binary instruction ...
  7470. // %cond.or = or|and i1 %cond1, cond2
  7471. // br i1 %cond.or label %dest1, label %dest2"
  7472. Instruction *LogicOp;
  7473. BasicBlock *TBB, *FBB;
  7474. if (!match(BB.getTerminator(),
  7475. m_Br(m_OneUse(m_Instruction(LogicOp)), TBB, FBB)))
  7476. continue;
  7477. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  7478. if (Br1->getMetadata(LLVMContext::MD_unpredictable))
  7479. continue;
  7480. // The merging of mostly empty BB can cause a degenerate branch.
  7481. if (TBB == FBB)
  7482. continue;
  7483. unsigned Opc;
  7484. Value *Cond1, *Cond2;
  7485. if (match(LogicOp,
  7486. m_LogicalAnd(m_OneUse(m_Value(Cond1)), m_OneUse(m_Value(Cond2)))))
  7487. Opc = Instruction::And;
  7488. else if (match(LogicOp, m_LogicalOr(m_OneUse(m_Value(Cond1)),
  7489. m_OneUse(m_Value(Cond2)))))
  7490. Opc = Instruction::Or;
  7491. else
  7492. continue;
  7493. auto IsGoodCond = [](Value *Cond) {
  7494. return match(
  7495. Cond,
  7496. m_CombineOr(m_Cmp(), m_CombineOr(m_LogicalAnd(m_Value(), m_Value()),
  7497. m_LogicalOr(m_Value(), m_Value()))));
  7498. };
  7499. if (!IsGoodCond(Cond1) || !IsGoodCond(Cond2))
  7500. continue;
  7501. LLVM_DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  7502. // Create a new BB.
  7503. auto *TmpBB =
  7504. BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
  7505. BB.getParent(), BB.getNextNode());
  7506. if (IsHugeFunc)
  7507. FreshBBs.insert(TmpBB);
  7508. // Update original basic block by using the first condition directly by the
  7509. // branch instruction and removing the no longer needed and/or instruction.
  7510. Br1->setCondition(Cond1);
  7511. LogicOp->eraseFromParent();
  7512. // Depending on the condition we have to either replace the true or the
  7513. // false successor of the original branch instruction.
  7514. if (Opc == Instruction::And)
  7515. Br1->setSuccessor(0, TmpBB);
  7516. else
  7517. Br1->setSuccessor(1, TmpBB);
  7518. // Fill in the new basic block.
  7519. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  7520. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  7521. I->removeFromParent();
  7522. I->insertBefore(Br2);
  7523. }
  7524. // Update PHI nodes in both successors. The original BB needs to be
  7525. // replaced in one successor's PHI nodes, because the branch comes now from
  7526. // the newly generated BB (NewBB). In the other successor we need to add one
  7527. // incoming edge to the PHI nodes, because both branch instructions target
  7528. // now the same successor. Depending on the original branch condition
  7529. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  7530. // we perform the correct update for the PHI nodes.
  7531. // This doesn't change the successor order of the just created branch
  7532. // instruction (or any other instruction).
  7533. if (Opc == Instruction::Or)
  7534. std::swap(TBB, FBB);
  7535. // Replace the old BB with the new BB.
  7536. TBB->replacePhiUsesWith(&BB, TmpBB);
  7537. // Add another incoming edge from the new BB.
  7538. for (PHINode &PN : FBB->phis()) {
  7539. auto *Val = PN.getIncomingValueForBlock(&BB);
  7540. PN.addIncoming(Val, TmpBB);
  7541. }
  7542. // Update the branch weights (from SelectionDAGBuilder::
  7543. // FindMergedConditions).
  7544. if (Opc == Instruction::Or) {
  7545. // Codegen X | Y as:
  7546. // BB1:
  7547. // jmp_if_X TBB
  7548. // jmp TmpBB
  7549. // TmpBB:
  7550. // jmp_if_Y TBB
  7551. // jmp FBB
  7552. //
  7553. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  7554. // The requirement is that
  7555. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  7556. // = TrueProb for original BB.
  7557. // Assuming the original weights are A and B, one choice is to set BB1's
  7558. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  7559. // assumes that
  7560. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  7561. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  7562. // TmpBB, but the math is more complicated.
  7563. uint64_t TrueWeight, FalseWeight;
  7564. if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
  7565. uint64_t NewTrueWeight = TrueWeight;
  7566. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  7567. scaleWeights(NewTrueWeight, NewFalseWeight);
  7568. Br1->setMetadata(LLVMContext::MD_prof,
  7569. MDBuilder(Br1->getContext())
  7570. .createBranchWeights(TrueWeight, FalseWeight));
  7571. NewTrueWeight = TrueWeight;
  7572. NewFalseWeight = 2 * FalseWeight;
  7573. scaleWeights(NewTrueWeight, NewFalseWeight);
  7574. Br2->setMetadata(LLVMContext::MD_prof,
  7575. MDBuilder(Br2->getContext())
  7576. .createBranchWeights(TrueWeight, FalseWeight));
  7577. }
  7578. } else {
  7579. // Codegen X & Y as:
  7580. // BB1:
  7581. // jmp_if_X TmpBB
  7582. // jmp FBB
  7583. // TmpBB:
  7584. // jmp_if_Y TBB
  7585. // jmp FBB
  7586. //
  7587. // This requires creation of TmpBB after CurBB.
  7588. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  7589. // The requirement is that
  7590. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  7591. // = FalseProb for original BB.
  7592. // Assuming the original weights are A and B, one choice is to set BB1's
  7593. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  7594. // assumes that
  7595. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  7596. uint64_t TrueWeight, FalseWeight;
  7597. if (extractBranchWeights(*Br1, TrueWeight, FalseWeight)) {
  7598. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  7599. uint64_t NewFalseWeight = FalseWeight;
  7600. scaleWeights(NewTrueWeight, NewFalseWeight);
  7601. Br1->setMetadata(LLVMContext::MD_prof,
  7602. MDBuilder(Br1->getContext())
  7603. .createBranchWeights(TrueWeight, FalseWeight));
  7604. NewTrueWeight = 2 * TrueWeight;
  7605. NewFalseWeight = FalseWeight;
  7606. scaleWeights(NewTrueWeight, NewFalseWeight);
  7607. Br2->setMetadata(LLVMContext::MD_prof,
  7608. MDBuilder(Br2->getContext())
  7609. .createBranchWeights(TrueWeight, FalseWeight));
  7610. }
  7611. }
  7612. ModifiedDT = ModifyDT::ModifyBBDT;
  7613. MadeChange = true;
  7614. LLVM_DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  7615. TmpBB->dump());
  7616. }
  7617. return MadeChange;
  7618. }