CodeGenPrepare.cpp 246 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620
  1. //===- CodeGenPrepare.cpp - Prepare a function for code generation --------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass munges the code in the input function to better prepare it for
  11. // SelectionDAG-based code generation. This works around limitations in it's
  12. // basic-block-at-a-time approach. It should eventually be removed.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/APInt.h"
  16. #include "llvm/ADT/ArrayRef.h"
  17. #include "llvm/ADT/DenseMap.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/ConstantFolding.h"
  26. #include "llvm/Analysis/InstructionSimplify.h"
  27. #include "llvm/Analysis/LoopInfo.h"
  28. #include "llvm/Analysis/MemoryBuiltins.h"
  29. #include "llvm/Analysis/ProfileSummaryInfo.h"
  30. #include "llvm/Analysis/TargetLibraryInfo.h"
  31. #include "llvm/Analysis/TargetTransformInfo.h"
  32. #include "llvm/Analysis/Utils/Local.h"
  33. #include "llvm/Analysis/ValueTracking.h"
  34. #include "llvm/CodeGen/Analysis.h"
  35. #include "llvm/CodeGen/ISDOpcodes.h"
  36. #include "llvm/CodeGen/SelectionDAGNodes.h"
  37. #include "llvm/CodeGen/TargetLowering.h"
  38. #include "llvm/CodeGen/TargetPassConfig.h"
  39. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  40. #include "llvm/CodeGen/ValueTypes.h"
  41. #include "llvm/Config/llvm-config.h"
  42. #include "llvm/IR/Argument.h"
  43. #include "llvm/IR/Attributes.h"
  44. #include "llvm/IR/BasicBlock.h"
  45. #include "llvm/IR/CallSite.h"
  46. #include "llvm/IR/Constant.h"
  47. #include "llvm/IR/Constants.h"
  48. #include "llvm/IR/DataLayout.h"
  49. #include "llvm/IR/DerivedTypes.h"
  50. #include "llvm/IR/Dominators.h"
  51. #include "llvm/IR/Function.h"
  52. #include "llvm/IR/GetElementPtrTypeIterator.h"
  53. #include "llvm/IR/GlobalValue.h"
  54. #include "llvm/IR/GlobalVariable.h"
  55. #include "llvm/IR/IRBuilder.h"
  56. #include "llvm/IR/InlineAsm.h"
  57. #include "llvm/IR/InstrTypes.h"
  58. #include "llvm/IR/Instruction.h"
  59. #include "llvm/IR/Instructions.h"
  60. #include "llvm/IR/IntrinsicInst.h"
  61. #include "llvm/IR/Intrinsics.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/Statepoint.h"
  68. #include "llvm/IR/Type.h"
  69. #include "llvm/IR/Use.h"
  70. #include "llvm/IR/User.h"
  71. #include "llvm/IR/Value.h"
  72. #include "llvm/IR/ValueHandle.h"
  73. #include "llvm/IR/ValueMap.h"
  74. #include "llvm/Pass.h"
  75. #include "llvm/Support/BlockFrequency.h"
  76. #include "llvm/Support/BranchProbability.h"
  77. #include "llvm/Support/Casting.h"
  78. #include "llvm/Support/CommandLine.h"
  79. #include "llvm/Support/Compiler.h"
  80. #include "llvm/Support/Debug.h"
  81. #include "llvm/Support/ErrorHandling.h"
  82. #include "llvm/Support/MachineValueType.h"
  83. #include "llvm/Support/MathExtras.h"
  84. #include "llvm/Support/raw_ostream.h"
  85. #include "llvm/Target/TargetMachine.h"
  86. #include "llvm/Target/TargetOptions.h"
  87. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  88. #include "llvm/Transforms/Utils/BypassSlowDivision.h"
  89. #include "llvm/Transforms/Utils/SimplifyLibCalls.h"
  90. #include <algorithm>
  91. #include <cassert>
  92. #include <cstdint>
  93. #include <iterator>
  94. #include <limits>
  95. #include <memory>
  96. #include <utility>
  97. #include <vector>
  98. using namespace llvm;
  99. using namespace llvm::PatternMatch;
  100. #define DEBUG_TYPE "codegenprepare"
  101. STATISTIC(NumBlocksElim, "Number of blocks eliminated");
  102. STATISTIC(NumPHIsElim, "Number of trivial PHIs eliminated");
  103. STATISTIC(NumGEPsElim, "Number of GEPs converted to casts");
  104. STATISTIC(NumCmpUses, "Number of uses of Cmp expressions replaced with uses of "
  105. "sunken Cmps");
  106. STATISTIC(NumCastUses, "Number of uses of Cast expressions replaced with uses "
  107. "of sunken Casts");
  108. STATISTIC(NumMemoryInsts, "Number of memory instructions whose address "
  109. "computations were sunk");
  110. STATISTIC(NumMemoryInstsPhiCreated,
  111. "Number of phis created when address "
  112. "computations were sunk to memory instructions");
  113. STATISTIC(NumMemoryInstsSelectCreated,
  114. "Number of select created when address "
  115. "computations were sunk to memory instructions");
  116. STATISTIC(NumExtsMoved, "Number of [s|z]ext instructions combined with loads");
  117. STATISTIC(NumExtUses, "Number of uses of [s|z]ext instructions optimized");
  118. STATISTIC(NumAndsAdded,
  119. "Number of and mask instructions added to form ext loads");
  120. STATISTIC(NumAndUses, "Number of uses of and mask instructions optimized");
  121. STATISTIC(NumRetsDup, "Number of return instructions duplicated");
  122. STATISTIC(NumDbgValueMoved, "Number of debug value instructions moved");
  123. STATISTIC(NumSelectsExpanded, "Number of selects turned into branches");
  124. STATISTIC(NumStoreExtractExposed, "Number of store(extractelement) exposed");
  125. static cl::opt<bool> DisableBranchOpts(
  126. "disable-cgp-branch-opts", cl::Hidden, cl::init(false),
  127. cl::desc("Disable branch optimizations in CodeGenPrepare"));
  128. static cl::opt<bool>
  129. DisableGCOpts("disable-cgp-gc-opts", cl::Hidden, cl::init(false),
  130. cl::desc("Disable GC optimizations in CodeGenPrepare"));
  131. static cl::opt<bool> DisableSelectToBranch(
  132. "disable-cgp-select2branch", cl::Hidden, cl::init(false),
  133. cl::desc("Disable select to branch conversion."));
  134. static cl::opt<bool> AddrSinkUsingGEPs(
  135. "addr-sink-using-gep", cl::Hidden, cl::init(true),
  136. cl::desc("Address sinking in CGP using GEPs."));
  137. static cl::opt<bool> EnableAndCmpSinking(
  138. "enable-andcmp-sinking", cl::Hidden, cl::init(true),
  139. cl::desc("Enable sinkinig and/cmp into branches."));
  140. static cl::opt<bool> DisableStoreExtract(
  141. "disable-cgp-store-extract", cl::Hidden, cl::init(false),
  142. cl::desc("Disable store(extract) optimizations in CodeGenPrepare"));
  143. static cl::opt<bool> StressStoreExtract(
  144. "stress-cgp-store-extract", cl::Hidden, cl::init(false),
  145. cl::desc("Stress test store(extract) optimizations in CodeGenPrepare"));
  146. static cl::opt<bool> DisableExtLdPromotion(
  147. "disable-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  148. cl::desc("Disable ext(promotable(ld)) -> promoted(ext(ld)) optimization in "
  149. "CodeGenPrepare"));
  150. static cl::opt<bool> StressExtLdPromotion(
  151. "stress-cgp-ext-ld-promotion", cl::Hidden, cl::init(false),
  152. cl::desc("Stress test ext(promotable(ld)) -> promoted(ext(ld)) "
  153. "optimization in CodeGenPrepare"));
  154. static cl::opt<bool> DisablePreheaderProtect(
  155. "disable-preheader-prot", cl::Hidden, cl::init(false),
  156. cl::desc("Disable protection against removing loop preheaders"));
  157. static cl::opt<bool> ProfileGuidedSectionPrefix(
  158. "profile-guided-section-prefix", cl::Hidden, cl::init(true), cl::ZeroOrMore,
  159. cl::desc("Use profile info to add section prefix for hot/cold functions"));
  160. static cl::opt<unsigned> FreqRatioToSkipMerge(
  161. "cgp-freq-ratio-to-skip-merge", cl::Hidden, cl::init(2),
  162. cl::desc("Skip merging empty blocks if (frequency of empty block) / "
  163. "(frequency of destination block) is greater than this ratio"));
  164. static cl::opt<bool> ForceSplitStore(
  165. "force-split-store", cl::Hidden, cl::init(false),
  166. cl::desc("Force store splitting no matter what the target query says."));
  167. static cl::opt<bool>
  168. EnableTypePromotionMerge("cgp-type-promotion-merge", cl::Hidden,
  169. cl::desc("Enable merging of redundant sexts when one is dominating"
  170. " the other."), cl::init(true));
  171. static cl::opt<bool> DisableComplexAddrModes(
  172. "disable-complex-addr-modes", cl::Hidden, cl::init(false),
  173. cl::desc("Disables combining addressing modes with different parts "
  174. "in optimizeMemoryInst."));
  175. static cl::opt<bool>
  176. AddrSinkNewPhis("addr-sink-new-phis", cl::Hidden, cl::init(false),
  177. cl::desc("Allow creation of Phis in Address sinking."));
  178. static cl::opt<bool>
  179. AddrSinkNewSelects("addr-sink-new-select", cl::Hidden, cl::init(true),
  180. cl::desc("Allow creation of selects in Address sinking."));
  181. static cl::opt<bool> AddrSinkCombineBaseReg(
  182. "addr-sink-combine-base-reg", cl::Hidden, cl::init(true),
  183. cl::desc("Allow combining of BaseReg field in Address sinking."));
  184. static cl::opt<bool> AddrSinkCombineBaseGV(
  185. "addr-sink-combine-base-gv", cl::Hidden, cl::init(true),
  186. cl::desc("Allow combining of BaseGV field in Address sinking."));
  187. static cl::opt<bool> AddrSinkCombineBaseOffs(
  188. "addr-sink-combine-base-offs", cl::Hidden, cl::init(true),
  189. cl::desc("Allow combining of BaseOffs field in Address sinking."));
  190. static cl::opt<bool> AddrSinkCombineScaledReg(
  191. "addr-sink-combine-scaled-reg", cl::Hidden, cl::init(true),
  192. cl::desc("Allow combining of ScaledReg field in Address sinking."));
  193. namespace {
  194. using SetOfInstrs = SmallPtrSet<Instruction *, 16>;
  195. using TypeIsSExt = PointerIntPair<Type *, 1, bool>;
  196. using InstrToOrigTy = DenseMap<Instruction *, TypeIsSExt>;
  197. using SExts = SmallVector<Instruction *, 16>;
  198. using ValueToSExts = DenseMap<Value *, SExts>;
  199. class TypePromotionTransaction;
  200. class CodeGenPrepare : public FunctionPass {
  201. const TargetMachine *TM = nullptr;
  202. const TargetSubtargetInfo *SubtargetInfo;
  203. const TargetLowering *TLI = nullptr;
  204. const TargetRegisterInfo *TRI;
  205. const TargetTransformInfo *TTI = nullptr;
  206. const TargetLibraryInfo *TLInfo;
  207. const LoopInfo *LI;
  208. std::unique_ptr<BlockFrequencyInfo> BFI;
  209. std::unique_ptr<BranchProbabilityInfo> BPI;
  210. /// As we scan instructions optimizing them, this is the next instruction
  211. /// to optimize. Transforms that can invalidate this should update it.
  212. BasicBlock::iterator CurInstIterator;
  213. /// Keeps track of non-local addresses that have been sunk into a block.
  214. /// This allows us to avoid inserting duplicate code for blocks with
  215. /// multiple load/stores of the same address. The usage of WeakTrackingVH
  216. /// enables SunkAddrs to be treated as a cache whose entries can be
  217. /// invalidated if a sunken address computation has been erased.
  218. ValueMap<Value*, WeakTrackingVH> SunkAddrs;
  219. /// Keeps track of all instructions inserted for the current function.
  220. SetOfInstrs InsertedInsts;
  221. /// Keeps track of the type of the related instruction before their
  222. /// promotion for the current function.
  223. InstrToOrigTy PromotedInsts;
  224. /// Keep track of instructions removed during promotion.
  225. SetOfInstrs RemovedInsts;
  226. /// Keep track of sext chains based on their initial value.
  227. DenseMap<Value *, Instruction *> SeenChainsForSExt;
  228. /// Keep track of SExt promoted.
  229. ValueToSExts ValToSExtendedUses;
  230. /// True if CFG is modified in any way.
  231. bool ModifiedDT;
  232. /// True if optimizing for size.
  233. bool OptSize;
  234. /// DataLayout for the Function being processed.
  235. const DataLayout *DL = nullptr;
  236. public:
  237. static char ID; // Pass identification, replacement for typeid
  238. CodeGenPrepare() : FunctionPass(ID) {
  239. initializeCodeGenPreparePass(*PassRegistry::getPassRegistry());
  240. }
  241. bool runOnFunction(Function &F) override;
  242. StringRef getPassName() const override { return "CodeGen Prepare"; }
  243. void getAnalysisUsage(AnalysisUsage &AU) const override {
  244. // FIXME: When we can selectively preserve passes, preserve the domtree.
  245. AU.addRequired<ProfileSummaryInfoWrapperPass>();
  246. AU.addRequired<TargetLibraryInfoWrapperPass>();
  247. AU.addRequired<TargetTransformInfoWrapperPass>();
  248. AU.addRequired<LoopInfoWrapperPass>();
  249. }
  250. private:
  251. bool eliminateFallThrough(Function &F);
  252. bool eliminateMostlyEmptyBlocks(Function &F);
  253. BasicBlock *findDestBlockOfMergeableEmptyBlock(BasicBlock *BB);
  254. bool canMergeBlocks(const BasicBlock *BB, const BasicBlock *DestBB) const;
  255. void eliminateMostlyEmptyBlock(BasicBlock *BB);
  256. bool isMergingEmptyBlockProfitable(BasicBlock *BB, BasicBlock *DestBB,
  257. bool isPreheader);
  258. bool optimizeBlock(BasicBlock &BB, bool &ModifiedDT);
  259. bool optimizeInst(Instruction *I, bool &ModifiedDT);
  260. bool optimizeMemoryInst(Instruction *I, Value *Addr,
  261. Type *AccessTy, unsigned AS);
  262. bool optimizeInlineAsmInst(CallInst *CS);
  263. bool optimizeCallInst(CallInst *CI, bool &ModifiedDT);
  264. bool optimizeExt(Instruction *&I);
  265. bool optimizeExtUses(Instruction *I);
  266. bool optimizeLoadExt(LoadInst *I);
  267. bool optimizeSelectInst(SelectInst *SI);
  268. bool optimizeShuffleVectorInst(ShuffleVectorInst *SI);
  269. bool optimizeSwitchInst(SwitchInst *CI);
  270. bool optimizeExtractElementInst(Instruction *Inst);
  271. bool dupRetToEnableTailCallOpts(BasicBlock *BB);
  272. bool placeDbgValues(Function &F);
  273. bool canFormExtLd(const SmallVectorImpl<Instruction *> &MovedExts,
  274. LoadInst *&LI, Instruction *&Inst, bool HasPromoted);
  275. bool tryToPromoteExts(TypePromotionTransaction &TPT,
  276. const SmallVectorImpl<Instruction *> &Exts,
  277. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  278. unsigned CreatedInstsCost = 0);
  279. bool mergeSExts(Function &F);
  280. bool performAddressTypePromotion(
  281. Instruction *&Inst,
  282. bool AllowPromotionWithoutCommonHeader,
  283. bool HasPromoted, TypePromotionTransaction &TPT,
  284. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts);
  285. bool splitBranchCondition(Function &F);
  286. bool simplifyOffsetableRelocate(Instruction &I);
  287. };
  288. } // end anonymous namespace
  289. char CodeGenPrepare::ID = 0;
  290. INITIALIZE_PASS_BEGIN(CodeGenPrepare, DEBUG_TYPE,
  291. "Optimize for code generation", false, false)
  292. INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
  293. INITIALIZE_PASS_END(CodeGenPrepare, DEBUG_TYPE,
  294. "Optimize for code generation", false, false)
  295. FunctionPass *llvm::createCodeGenPreparePass() { return new CodeGenPrepare(); }
  296. bool CodeGenPrepare::runOnFunction(Function &F) {
  297. if (skipFunction(F))
  298. return false;
  299. DL = &F.getParent()->getDataLayout();
  300. bool EverMadeChange = false;
  301. // Clear per function information.
  302. InsertedInsts.clear();
  303. PromotedInsts.clear();
  304. ModifiedDT = false;
  305. if (auto *TPC = getAnalysisIfAvailable<TargetPassConfig>()) {
  306. TM = &TPC->getTM<TargetMachine>();
  307. SubtargetInfo = TM->getSubtargetImpl(F);
  308. TLI = SubtargetInfo->getTargetLowering();
  309. TRI = SubtargetInfo->getRegisterInfo();
  310. }
  311. TLInfo = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
  312. TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  313. LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  314. BPI.reset(new BranchProbabilityInfo(F, *LI));
  315. BFI.reset(new BlockFrequencyInfo(F, *BPI, *LI));
  316. OptSize = F.optForSize();
  317. ProfileSummaryInfo *PSI =
  318. getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
  319. if (ProfileGuidedSectionPrefix) {
  320. if (PSI->isFunctionHotInCallGraph(&F, *BFI))
  321. F.setSectionPrefix(".hot");
  322. else if (PSI->isFunctionColdInCallGraph(&F, *BFI))
  323. F.setSectionPrefix(".unlikely");
  324. }
  325. /// This optimization identifies DIV instructions that can be
  326. /// profitably bypassed and carried out with a shorter, faster divide.
  327. if (!OptSize && !PSI->hasHugeWorkingSetSize() && TLI &&
  328. TLI->isSlowDivBypassed()) {
  329. const DenseMap<unsigned int, unsigned int> &BypassWidths =
  330. TLI->getBypassSlowDivWidths();
  331. BasicBlock* BB = &*F.begin();
  332. while (BB != nullptr) {
  333. // bypassSlowDivision may create new BBs, but we don't want to reapply the
  334. // optimization to those blocks.
  335. BasicBlock* Next = BB->getNextNode();
  336. EverMadeChange |= bypassSlowDivision(BB, BypassWidths);
  337. BB = Next;
  338. }
  339. }
  340. // Eliminate blocks that contain only PHI nodes and an
  341. // unconditional branch.
  342. EverMadeChange |= eliminateMostlyEmptyBlocks(F);
  343. // llvm.dbg.value is far away from the value then iSel may not be able
  344. // handle it properly. iSel will drop llvm.dbg.value if it can not
  345. // find a node corresponding to the value.
  346. EverMadeChange |= placeDbgValues(F);
  347. if (!DisableBranchOpts)
  348. EverMadeChange |= splitBranchCondition(F);
  349. // Split some critical edges where one of the sources is an indirect branch,
  350. // to help generate sane code for PHIs involving such edges.
  351. EverMadeChange |= SplitIndirectBrCriticalEdges(F);
  352. bool MadeChange = true;
  353. while (MadeChange) {
  354. MadeChange = false;
  355. SeenChainsForSExt.clear();
  356. ValToSExtendedUses.clear();
  357. RemovedInsts.clear();
  358. for (Function::iterator I = F.begin(); I != F.end(); ) {
  359. BasicBlock *BB = &*I++;
  360. bool ModifiedDTOnIteration = false;
  361. MadeChange |= optimizeBlock(*BB, ModifiedDTOnIteration);
  362. // Restart BB iteration if the dominator tree of the Function was changed
  363. if (ModifiedDTOnIteration)
  364. break;
  365. }
  366. if (EnableTypePromotionMerge && !ValToSExtendedUses.empty())
  367. MadeChange |= mergeSExts(F);
  368. // Really free removed instructions during promotion.
  369. for (Instruction *I : RemovedInsts)
  370. I->deleteValue();
  371. EverMadeChange |= MadeChange;
  372. }
  373. SunkAddrs.clear();
  374. if (!DisableBranchOpts) {
  375. MadeChange = false;
  376. SmallPtrSet<BasicBlock*, 8> WorkList;
  377. for (BasicBlock &BB : F) {
  378. SmallVector<BasicBlock *, 2> Successors(succ_begin(&BB), succ_end(&BB));
  379. MadeChange |= ConstantFoldTerminator(&BB, true);
  380. if (!MadeChange) continue;
  381. for (SmallVectorImpl<BasicBlock*>::iterator
  382. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  383. if (pred_begin(*II) == pred_end(*II))
  384. WorkList.insert(*II);
  385. }
  386. // Delete the dead blocks and any of their dead successors.
  387. MadeChange |= !WorkList.empty();
  388. while (!WorkList.empty()) {
  389. BasicBlock *BB = *WorkList.begin();
  390. WorkList.erase(BB);
  391. SmallVector<BasicBlock*, 2> Successors(succ_begin(BB), succ_end(BB));
  392. DeleteDeadBlock(BB);
  393. for (SmallVectorImpl<BasicBlock*>::iterator
  394. II = Successors.begin(), IE = Successors.end(); II != IE; ++II)
  395. if (pred_begin(*II) == pred_end(*II))
  396. WorkList.insert(*II);
  397. }
  398. // Merge pairs of basic blocks with unconditional branches, connected by
  399. // a single edge.
  400. if (EverMadeChange || MadeChange)
  401. MadeChange |= eliminateFallThrough(F);
  402. EverMadeChange |= MadeChange;
  403. }
  404. if (!DisableGCOpts) {
  405. SmallVector<Instruction *, 2> Statepoints;
  406. for (BasicBlock &BB : F)
  407. for (Instruction &I : BB)
  408. if (isStatepoint(I))
  409. Statepoints.push_back(&I);
  410. for (auto &I : Statepoints)
  411. EverMadeChange |= simplifyOffsetableRelocate(*I);
  412. }
  413. return EverMadeChange;
  414. }
  415. /// Merge basic blocks which are connected by a single edge, where one of the
  416. /// basic blocks has a single successor pointing to the other basic block,
  417. /// which has a single predecessor.
  418. bool CodeGenPrepare::eliminateFallThrough(Function &F) {
  419. bool Changed = false;
  420. // Scan all of the blocks in the function, except for the entry block.
  421. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  422. BasicBlock *BB = &*I++;
  423. // If the destination block has a single pred, then this is a trivial
  424. // edge, just collapse it.
  425. BasicBlock *SinglePred = BB->getSinglePredecessor();
  426. // Don't merge if BB's address is taken.
  427. if (!SinglePred || SinglePred == BB || BB->hasAddressTaken()) continue;
  428. BranchInst *Term = dyn_cast<BranchInst>(SinglePred->getTerminator());
  429. if (Term && !Term->isConditional()) {
  430. Changed = true;
  431. DEBUG(dbgs() << "To merge:\n"<< *SinglePred << "\n\n\n");
  432. // Remember if SinglePred was the entry block of the function.
  433. // If so, we will need to move BB back to the entry position.
  434. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  435. MergeBasicBlockIntoOnlyPred(BB, nullptr);
  436. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  437. BB->moveBefore(&BB->getParent()->getEntryBlock());
  438. // We have erased a block. Update the iterator.
  439. I = BB->getIterator();
  440. }
  441. }
  442. return Changed;
  443. }
  444. /// Find a destination block from BB if BB is mergeable empty block.
  445. BasicBlock *CodeGenPrepare::findDestBlockOfMergeableEmptyBlock(BasicBlock *BB) {
  446. // If this block doesn't end with an uncond branch, ignore it.
  447. BranchInst *BI = dyn_cast<BranchInst>(BB->getTerminator());
  448. if (!BI || !BI->isUnconditional())
  449. return nullptr;
  450. // If the instruction before the branch (skipping debug info) isn't a phi
  451. // node, then other stuff is happening here.
  452. BasicBlock::iterator BBI = BI->getIterator();
  453. if (BBI != BB->begin()) {
  454. --BBI;
  455. while (isa<DbgInfoIntrinsic>(BBI)) {
  456. if (BBI == BB->begin())
  457. break;
  458. --BBI;
  459. }
  460. if (!isa<DbgInfoIntrinsic>(BBI) && !isa<PHINode>(BBI))
  461. return nullptr;
  462. }
  463. // Do not break infinite loops.
  464. BasicBlock *DestBB = BI->getSuccessor(0);
  465. if (DestBB == BB)
  466. return nullptr;
  467. if (!canMergeBlocks(BB, DestBB))
  468. DestBB = nullptr;
  469. return DestBB;
  470. }
  471. /// Eliminate blocks that contain only PHI nodes, debug info directives, and an
  472. /// unconditional branch. Passes before isel (e.g. LSR/loopsimplify) often split
  473. /// edges in ways that are non-optimal for isel. Start by eliminating these
  474. /// blocks so we can split them the way we want them.
  475. bool CodeGenPrepare::eliminateMostlyEmptyBlocks(Function &F) {
  476. SmallPtrSet<BasicBlock *, 16> Preheaders;
  477. SmallVector<Loop *, 16> LoopList(LI->begin(), LI->end());
  478. while (!LoopList.empty()) {
  479. Loop *L = LoopList.pop_back_val();
  480. LoopList.insert(LoopList.end(), L->begin(), L->end());
  481. if (BasicBlock *Preheader = L->getLoopPreheader())
  482. Preheaders.insert(Preheader);
  483. }
  484. bool MadeChange = false;
  485. // Note that this intentionally skips the entry block.
  486. for (Function::iterator I = std::next(F.begin()), E = F.end(); I != E;) {
  487. BasicBlock *BB = &*I++;
  488. BasicBlock *DestBB = findDestBlockOfMergeableEmptyBlock(BB);
  489. if (!DestBB ||
  490. !isMergingEmptyBlockProfitable(BB, DestBB, Preheaders.count(BB)))
  491. continue;
  492. eliminateMostlyEmptyBlock(BB);
  493. MadeChange = true;
  494. }
  495. return MadeChange;
  496. }
  497. bool CodeGenPrepare::isMergingEmptyBlockProfitable(BasicBlock *BB,
  498. BasicBlock *DestBB,
  499. bool isPreheader) {
  500. // Do not delete loop preheaders if doing so would create a critical edge.
  501. // Loop preheaders can be good locations to spill registers. If the
  502. // preheader is deleted and we create a critical edge, registers may be
  503. // spilled in the loop body instead.
  504. if (!DisablePreheaderProtect && isPreheader &&
  505. !(BB->getSinglePredecessor() &&
  506. BB->getSinglePredecessor()->getSingleSuccessor()))
  507. return false;
  508. // Try to skip merging if the unique predecessor of BB is terminated by a
  509. // switch or indirect branch instruction, and BB is used as an incoming block
  510. // of PHIs in DestBB. In such case, merging BB and DestBB would cause ISel to
  511. // add COPY instructions in the predecessor of BB instead of BB (if it is not
  512. // merged). Note that the critical edge created by merging such blocks wont be
  513. // split in MachineSink because the jump table is not analyzable. By keeping
  514. // such empty block (BB), ISel will place COPY instructions in BB, not in the
  515. // predecessor of BB.
  516. BasicBlock *Pred = BB->getUniquePredecessor();
  517. if (!Pred ||
  518. !(isa<SwitchInst>(Pred->getTerminator()) ||
  519. isa<IndirectBrInst>(Pred->getTerminator())))
  520. return true;
  521. if (BB->getTerminator() != BB->getFirstNonPHI())
  522. return true;
  523. // We use a simple cost heuristic which determine skipping merging is
  524. // profitable if the cost of skipping merging is less than the cost of
  525. // merging : Cost(skipping merging) < Cost(merging BB), where the
  526. // Cost(skipping merging) is Freq(BB) * (Cost(Copy) + Cost(Branch)), and
  527. // the Cost(merging BB) is Freq(Pred) * Cost(Copy).
  528. // Assuming Cost(Copy) == Cost(Branch), we could simplify it to :
  529. // Freq(Pred) / Freq(BB) > 2.
  530. // Note that if there are multiple empty blocks sharing the same incoming
  531. // value for the PHIs in the DestBB, we consider them together. In such
  532. // case, Cost(merging BB) will be the sum of their frequencies.
  533. if (!isa<PHINode>(DestBB->begin()))
  534. return true;
  535. SmallPtrSet<BasicBlock *, 16> SameIncomingValueBBs;
  536. // Find all other incoming blocks from which incoming values of all PHIs in
  537. // DestBB are the same as the ones from BB.
  538. for (pred_iterator PI = pred_begin(DestBB), E = pred_end(DestBB); PI != E;
  539. ++PI) {
  540. BasicBlock *DestBBPred = *PI;
  541. if (DestBBPred == BB)
  542. continue;
  543. if (llvm::all_of(DestBB->phis(), [&](const PHINode &DestPN) {
  544. return DestPN.getIncomingValueForBlock(BB) ==
  545. DestPN.getIncomingValueForBlock(DestBBPred);
  546. }))
  547. SameIncomingValueBBs.insert(DestBBPred);
  548. }
  549. // See if all BB's incoming values are same as the value from Pred. In this
  550. // case, no reason to skip merging because COPYs are expected to be place in
  551. // Pred already.
  552. if (SameIncomingValueBBs.count(Pred))
  553. return true;
  554. BlockFrequency PredFreq = BFI->getBlockFreq(Pred);
  555. BlockFrequency BBFreq = BFI->getBlockFreq(BB);
  556. for (auto SameValueBB : SameIncomingValueBBs)
  557. if (SameValueBB->getUniquePredecessor() == Pred &&
  558. DestBB == findDestBlockOfMergeableEmptyBlock(SameValueBB))
  559. BBFreq += BFI->getBlockFreq(SameValueBB);
  560. return PredFreq.getFrequency() <=
  561. BBFreq.getFrequency() * FreqRatioToSkipMerge;
  562. }
  563. /// Return true if we can merge BB into DestBB if there is a single
  564. /// unconditional branch between them, and BB contains no other non-phi
  565. /// instructions.
  566. bool CodeGenPrepare::canMergeBlocks(const BasicBlock *BB,
  567. const BasicBlock *DestBB) const {
  568. // We only want to eliminate blocks whose phi nodes are used by phi nodes in
  569. // the successor. If there are more complex condition (e.g. preheaders),
  570. // don't mess around with them.
  571. for (const PHINode &PN : BB->phis()) {
  572. for (const User *U : PN.users()) {
  573. const Instruction *UI = cast<Instruction>(U);
  574. if (UI->getParent() != DestBB || !isa<PHINode>(UI))
  575. return false;
  576. // If User is inside DestBB block and it is a PHINode then check
  577. // incoming value. If incoming value is not from BB then this is
  578. // a complex condition (e.g. preheaders) we want to avoid here.
  579. if (UI->getParent() == DestBB) {
  580. if (const PHINode *UPN = dyn_cast<PHINode>(UI))
  581. for (unsigned I = 0, E = UPN->getNumIncomingValues(); I != E; ++I) {
  582. Instruction *Insn = dyn_cast<Instruction>(UPN->getIncomingValue(I));
  583. if (Insn && Insn->getParent() == BB &&
  584. Insn->getParent() != UPN->getIncomingBlock(I))
  585. return false;
  586. }
  587. }
  588. }
  589. }
  590. // If BB and DestBB contain any common predecessors, then the phi nodes in BB
  591. // and DestBB may have conflicting incoming values for the block. If so, we
  592. // can't merge the block.
  593. const PHINode *DestBBPN = dyn_cast<PHINode>(DestBB->begin());
  594. if (!DestBBPN) return true; // no conflict.
  595. // Collect the preds of BB.
  596. SmallPtrSet<const BasicBlock*, 16> BBPreds;
  597. if (const PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  598. // It is faster to get preds from a PHI than with pred_iterator.
  599. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  600. BBPreds.insert(BBPN->getIncomingBlock(i));
  601. } else {
  602. BBPreds.insert(pred_begin(BB), pred_end(BB));
  603. }
  604. // Walk the preds of DestBB.
  605. for (unsigned i = 0, e = DestBBPN->getNumIncomingValues(); i != e; ++i) {
  606. BasicBlock *Pred = DestBBPN->getIncomingBlock(i);
  607. if (BBPreds.count(Pred)) { // Common predecessor?
  608. for (const PHINode &PN : DestBB->phis()) {
  609. const Value *V1 = PN.getIncomingValueForBlock(Pred);
  610. const Value *V2 = PN.getIncomingValueForBlock(BB);
  611. // If V2 is a phi node in BB, look up what the mapped value will be.
  612. if (const PHINode *V2PN = dyn_cast<PHINode>(V2))
  613. if (V2PN->getParent() == BB)
  614. V2 = V2PN->getIncomingValueForBlock(Pred);
  615. // If there is a conflict, bail out.
  616. if (V1 != V2) return false;
  617. }
  618. }
  619. }
  620. return true;
  621. }
  622. /// Eliminate a basic block that has only phi's and an unconditional branch in
  623. /// it.
  624. void CodeGenPrepare::eliminateMostlyEmptyBlock(BasicBlock *BB) {
  625. BranchInst *BI = cast<BranchInst>(BB->getTerminator());
  626. BasicBlock *DestBB = BI->getSuccessor(0);
  627. DEBUG(dbgs() << "MERGING MOSTLY EMPTY BLOCKS - BEFORE:\n" << *BB << *DestBB);
  628. // If the destination block has a single pred, then this is a trivial edge,
  629. // just collapse it.
  630. if (BasicBlock *SinglePred = DestBB->getSinglePredecessor()) {
  631. if (SinglePred != DestBB) {
  632. // Remember if SinglePred was the entry block of the function. If so, we
  633. // will need to move BB back to the entry position.
  634. bool isEntry = SinglePred == &SinglePred->getParent()->getEntryBlock();
  635. MergeBasicBlockIntoOnlyPred(DestBB, nullptr);
  636. if (isEntry && BB != &BB->getParent()->getEntryBlock())
  637. BB->moveBefore(&BB->getParent()->getEntryBlock());
  638. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  639. return;
  640. }
  641. }
  642. // Otherwise, we have multiple predecessors of BB. Update the PHIs in DestBB
  643. // to handle the new incoming edges it is about to have.
  644. for (PHINode &PN : DestBB->phis()) {
  645. // Remove the incoming value for BB, and remember it.
  646. Value *InVal = PN.removeIncomingValue(BB, false);
  647. // Two options: either the InVal is a phi node defined in BB or it is some
  648. // value that dominates BB.
  649. PHINode *InValPhi = dyn_cast<PHINode>(InVal);
  650. if (InValPhi && InValPhi->getParent() == BB) {
  651. // Add all of the input values of the input PHI as inputs of this phi.
  652. for (unsigned i = 0, e = InValPhi->getNumIncomingValues(); i != e; ++i)
  653. PN.addIncoming(InValPhi->getIncomingValue(i),
  654. InValPhi->getIncomingBlock(i));
  655. } else {
  656. // Otherwise, add one instance of the dominating value for each edge that
  657. // we will be adding.
  658. if (PHINode *BBPN = dyn_cast<PHINode>(BB->begin())) {
  659. for (unsigned i = 0, e = BBPN->getNumIncomingValues(); i != e; ++i)
  660. PN.addIncoming(InVal, BBPN->getIncomingBlock(i));
  661. } else {
  662. for (pred_iterator PI = pred_begin(BB), E = pred_end(BB); PI != E; ++PI)
  663. PN.addIncoming(InVal, *PI);
  664. }
  665. }
  666. }
  667. // The PHIs are now updated, change everything that refers to BB to use
  668. // DestBB and remove BB.
  669. BB->replaceAllUsesWith(DestBB);
  670. BB->eraseFromParent();
  671. ++NumBlocksElim;
  672. DEBUG(dbgs() << "AFTER:\n" << *DestBB << "\n\n\n");
  673. }
  674. // Computes a map of base pointer relocation instructions to corresponding
  675. // derived pointer relocation instructions given a vector of all relocate calls
  676. static void computeBaseDerivedRelocateMap(
  677. const SmallVectorImpl<GCRelocateInst *> &AllRelocateCalls,
  678. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>>
  679. &RelocateInstMap) {
  680. // Collect information in two maps: one primarily for locating the base object
  681. // while filling the second map; the second map is the final structure holding
  682. // a mapping between Base and corresponding Derived relocate calls
  683. DenseMap<std::pair<unsigned, unsigned>, GCRelocateInst *> RelocateIdxMap;
  684. for (auto *ThisRelocate : AllRelocateCalls) {
  685. auto K = std::make_pair(ThisRelocate->getBasePtrIndex(),
  686. ThisRelocate->getDerivedPtrIndex());
  687. RelocateIdxMap.insert(std::make_pair(K, ThisRelocate));
  688. }
  689. for (auto &Item : RelocateIdxMap) {
  690. std::pair<unsigned, unsigned> Key = Item.first;
  691. if (Key.first == Key.second)
  692. // Base relocation: nothing to insert
  693. continue;
  694. GCRelocateInst *I = Item.second;
  695. auto BaseKey = std::make_pair(Key.first, Key.first);
  696. // We're iterating over RelocateIdxMap so we cannot modify it.
  697. auto MaybeBase = RelocateIdxMap.find(BaseKey);
  698. if (MaybeBase == RelocateIdxMap.end())
  699. // TODO: We might want to insert a new base object relocate and gep off
  700. // that, if there are enough derived object relocates.
  701. continue;
  702. RelocateInstMap[MaybeBase->second].push_back(I);
  703. }
  704. }
  705. // Accepts a GEP and extracts the operands into a vector provided they're all
  706. // small integer constants
  707. static bool getGEPSmallConstantIntOffsetV(GetElementPtrInst *GEP,
  708. SmallVectorImpl<Value *> &OffsetV) {
  709. for (unsigned i = 1; i < GEP->getNumOperands(); i++) {
  710. // Only accept small constant integer operands
  711. auto Op = dyn_cast<ConstantInt>(GEP->getOperand(i));
  712. if (!Op || Op->getZExtValue() > 20)
  713. return false;
  714. }
  715. for (unsigned i = 1; i < GEP->getNumOperands(); i++)
  716. OffsetV.push_back(GEP->getOperand(i));
  717. return true;
  718. }
  719. // Takes a RelocatedBase (base pointer relocation instruction) and Targets to
  720. // replace, computes a replacement, and affects it.
  721. static bool
  722. simplifyRelocatesOffABase(GCRelocateInst *RelocatedBase,
  723. const SmallVectorImpl<GCRelocateInst *> &Targets) {
  724. bool MadeChange = false;
  725. // We must ensure the relocation of derived pointer is defined after
  726. // relocation of base pointer. If we find a relocation corresponding to base
  727. // defined earlier than relocation of base then we move relocation of base
  728. // right before found relocation. We consider only relocation in the same
  729. // basic block as relocation of base. Relocations from other basic block will
  730. // be skipped by optimization and we do not care about them.
  731. for (auto R = RelocatedBase->getParent()->getFirstInsertionPt();
  732. &*R != RelocatedBase; ++R)
  733. if (auto RI = dyn_cast<GCRelocateInst>(R))
  734. if (RI->getStatepoint() == RelocatedBase->getStatepoint())
  735. if (RI->getBasePtrIndex() == RelocatedBase->getBasePtrIndex()) {
  736. RelocatedBase->moveBefore(RI);
  737. break;
  738. }
  739. for (GCRelocateInst *ToReplace : Targets) {
  740. assert(ToReplace->getBasePtrIndex() == RelocatedBase->getBasePtrIndex() &&
  741. "Not relocating a derived object of the original base object");
  742. if (ToReplace->getBasePtrIndex() == ToReplace->getDerivedPtrIndex()) {
  743. // A duplicate relocate call. TODO: coalesce duplicates.
  744. continue;
  745. }
  746. if (RelocatedBase->getParent() != ToReplace->getParent()) {
  747. // Base and derived relocates are in different basic blocks.
  748. // In this case transform is only valid when base dominates derived
  749. // relocate. However it would be too expensive to check dominance
  750. // for each such relocate, so we skip the whole transformation.
  751. continue;
  752. }
  753. Value *Base = ToReplace->getBasePtr();
  754. auto Derived = dyn_cast<GetElementPtrInst>(ToReplace->getDerivedPtr());
  755. if (!Derived || Derived->getPointerOperand() != Base)
  756. continue;
  757. SmallVector<Value *, 2> OffsetV;
  758. if (!getGEPSmallConstantIntOffsetV(Derived, OffsetV))
  759. continue;
  760. // Create a Builder and replace the target callsite with a gep
  761. assert(RelocatedBase->getNextNode() &&
  762. "Should always have one since it's not a terminator");
  763. // Insert after RelocatedBase
  764. IRBuilder<> Builder(RelocatedBase->getNextNode());
  765. Builder.SetCurrentDebugLocation(ToReplace->getDebugLoc());
  766. // If gc_relocate does not match the actual type, cast it to the right type.
  767. // In theory, there must be a bitcast after gc_relocate if the type does not
  768. // match, and we should reuse it to get the derived pointer. But it could be
  769. // cases like this:
  770. // bb1:
  771. // ...
  772. // %g1 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  773. // br label %merge
  774. //
  775. // bb2:
  776. // ...
  777. // %g2 = call coldcc i8 addrspace(1)* @llvm.experimental.gc.relocate.p1i8(...)
  778. // br label %merge
  779. //
  780. // merge:
  781. // %p1 = phi i8 addrspace(1)* [ %g1, %bb1 ], [ %g2, %bb2 ]
  782. // %cast = bitcast i8 addrspace(1)* %p1 in to i32 addrspace(1)*
  783. //
  784. // In this case, we can not find the bitcast any more. So we insert a new bitcast
  785. // no matter there is already one or not. In this way, we can handle all cases, and
  786. // the extra bitcast should be optimized away in later passes.
  787. Value *ActualRelocatedBase = RelocatedBase;
  788. if (RelocatedBase->getType() != Base->getType()) {
  789. ActualRelocatedBase =
  790. Builder.CreateBitCast(RelocatedBase, Base->getType());
  791. }
  792. Value *Replacement = Builder.CreateGEP(
  793. Derived->getSourceElementType(), ActualRelocatedBase, makeArrayRef(OffsetV));
  794. Replacement->takeName(ToReplace);
  795. // If the newly generated derived pointer's type does not match the original derived
  796. // pointer's type, cast the new derived pointer to match it. Same reasoning as above.
  797. Value *ActualReplacement = Replacement;
  798. if (Replacement->getType() != ToReplace->getType()) {
  799. ActualReplacement =
  800. Builder.CreateBitCast(Replacement, ToReplace->getType());
  801. }
  802. ToReplace->replaceAllUsesWith(ActualReplacement);
  803. ToReplace->eraseFromParent();
  804. MadeChange = true;
  805. }
  806. return MadeChange;
  807. }
  808. // Turns this:
  809. //
  810. // %base = ...
  811. // %ptr = gep %base + 15
  812. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  813. // %base' = relocate(%tok, i32 4, i32 4)
  814. // %ptr' = relocate(%tok, i32 4, i32 5)
  815. // %val = load %ptr'
  816. //
  817. // into this:
  818. //
  819. // %base = ...
  820. // %ptr = gep %base + 15
  821. // %tok = statepoint (%fun, i32 0, i32 0, i32 0, %base, %ptr)
  822. // %base' = gc.relocate(%tok, i32 4, i32 4)
  823. // %ptr' = gep %base' + 15
  824. // %val = load %ptr'
  825. bool CodeGenPrepare::simplifyOffsetableRelocate(Instruction &I) {
  826. bool MadeChange = false;
  827. SmallVector<GCRelocateInst *, 2> AllRelocateCalls;
  828. for (auto *U : I.users())
  829. if (GCRelocateInst *Relocate = dyn_cast<GCRelocateInst>(U))
  830. // Collect all the relocate calls associated with a statepoint
  831. AllRelocateCalls.push_back(Relocate);
  832. // We need atleast one base pointer relocation + one derived pointer
  833. // relocation to mangle
  834. if (AllRelocateCalls.size() < 2)
  835. return false;
  836. // RelocateInstMap is a mapping from the base relocate instruction to the
  837. // corresponding derived relocate instructions
  838. DenseMap<GCRelocateInst *, SmallVector<GCRelocateInst *, 2>> RelocateInstMap;
  839. computeBaseDerivedRelocateMap(AllRelocateCalls, RelocateInstMap);
  840. if (RelocateInstMap.empty())
  841. return false;
  842. for (auto &Item : RelocateInstMap)
  843. // Item.first is the RelocatedBase to offset against
  844. // Item.second is the vector of Targets to replace
  845. MadeChange = simplifyRelocatesOffABase(Item.first, Item.second);
  846. return MadeChange;
  847. }
  848. /// SinkCast - Sink the specified cast instruction into its user blocks
  849. static bool SinkCast(CastInst *CI) {
  850. BasicBlock *DefBB = CI->getParent();
  851. /// InsertedCasts - Only insert a cast in each block once.
  852. DenseMap<BasicBlock*, CastInst*> InsertedCasts;
  853. bool MadeChange = false;
  854. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  855. UI != E; ) {
  856. Use &TheUse = UI.getUse();
  857. Instruction *User = cast<Instruction>(*UI);
  858. // Figure out which BB this cast is used in. For PHI's this is the
  859. // appropriate predecessor block.
  860. BasicBlock *UserBB = User->getParent();
  861. if (PHINode *PN = dyn_cast<PHINode>(User)) {
  862. UserBB = PN->getIncomingBlock(TheUse);
  863. }
  864. // Preincrement use iterator so we don't invalidate it.
  865. ++UI;
  866. // The first insertion point of a block containing an EH pad is after the
  867. // pad. If the pad is the user, we cannot sink the cast past the pad.
  868. if (User->isEHPad())
  869. continue;
  870. // If the block selected to receive the cast is an EH pad that does not
  871. // allow non-PHI instructions before the terminator, we can't sink the
  872. // cast.
  873. if (UserBB->getTerminator()->isEHPad())
  874. continue;
  875. // If this user is in the same block as the cast, don't change the cast.
  876. if (UserBB == DefBB) continue;
  877. // If we have already inserted a cast into this block, use it.
  878. CastInst *&InsertedCast = InsertedCasts[UserBB];
  879. if (!InsertedCast) {
  880. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  881. assert(InsertPt != UserBB->end());
  882. InsertedCast = CastInst::Create(CI->getOpcode(), CI->getOperand(0),
  883. CI->getType(), "", &*InsertPt);
  884. }
  885. // Replace a use of the cast with a use of the new cast.
  886. TheUse = InsertedCast;
  887. MadeChange = true;
  888. ++NumCastUses;
  889. }
  890. // If we removed all uses, nuke the cast.
  891. if (CI->use_empty()) {
  892. salvageDebugInfo(*CI);
  893. CI->eraseFromParent();
  894. MadeChange = true;
  895. }
  896. return MadeChange;
  897. }
  898. /// If the specified cast instruction is a noop copy (e.g. it's casting from
  899. /// one pointer type to another, i32->i8 on PPC), sink it into user blocks to
  900. /// reduce the number of virtual registers that must be created and coalesced.
  901. ///
  902. /// Return true if any changes are made.
  903. static bool OptimizeNoopCopyExpression(CastInst *CI, const TargetLowering &TLI,
  904. const DataLayout &DL) {
  905. // Sink only "cheap" (or nop) address-space casts. This is a weaker condition
  906. // than sinking only nop casts, but is helpful on some platforms.
  907. if (auto *ASC = dyn_cast<AddrSpaceCastInst>(CI)) {
  908. if (!TLI.isCheapAddrSpaceCast(ASC->getSrcAddressSpace(),
  909. ASC->getDestAddressSpace()))
  910. return false;
  911. }
  912. // If this is a noop copy,
  913. EVT SrcVT = TLI.getValueType(DL, CI->getOperand(0)->getType());
  914. EVT DstVT = TLI.getValueType(DL, CI->getType());
  915. // This is an fp<->int conversion?
  916. if (SrcVT.isInteger() != DstVT.isInteger())
  917. return false;
  918. // If this is an extension, it will be a zero or sign extension, which
  919. // isn't a noop.
  920. if (SrcVT.bitsLT(DstVT)) return false;
  921. // If these values will be promoted, find out what they will be promoted
  922. // to. This helps us consider truncates on PPC as noop copies when they
  923. // are.
  924. if (TLI.getTypeAction(CI->getContext(), SrcVT) ==
  925. TargetLowering::TypePromoteInteger)
  926. SrcVT = TLI.getTypeToTransformTo(CI->getContext(), SrcVT);
  927. if (TLI.getTypeAction(CI->getContext(), DstVT) ==
  928. TargetLowering::TypePromoteInteger)
  929. DstVT = TLI.getTypeToTransformTo(CI->getContext(), DstVT);
  930. // If, after promotion, these are the same types, this is a noop copy.
  931. if (SrcVT != DstVT)
  932. return false;
  933. return SinkCast(CI);
  934. }
  935. /// Try to combine CI into a call to the llvm.uadd.with.overflow intrinsic if
  936. /// possible.
  937. ///
  938. /// Return true if any changes were made.
  939. static bool CombineUAddWithOverflow(CmpInst *CI) {
  940. Value *A, *B;
  941. Instruction *AddI;
  942. if (!match(CI,
  943. m_UAddWithOverflow(m_Value(A), m_Value(B), m_Instruction(AddI))))
  944. return false;
  945. Type *Ty = AddI->getType();
  946. if (!isa<IntegerType>(Ty))
  947. return false;
  948. // We don't want to move around uses of condition values this late, so we we
  949. // check if it is legal to create the call to the intrinsic in the basic
  950. // block containing the icmp:
  951. if (AddI->getParent() != CI->getParent() && !AddI->hasOneUse())
  952. return false;
  953. #ifndef NDEBUG
  954. // Someday m_UAddWithOverflow may get smarter, but this is a safe assumption
  955. // for now:
  956. if (AddI->hasOneUse())
  957. assert(*AddI->user_begin() == CI && "expected!");
  958. #endif
  959. Module *M = CI->getModule();
  960. Value *F = Intrinsic::getDeclaration(M, Intrinsic::uadd_with_overflow, Ty);
  961. auto *InsertPt = AddI->hasOneUse() ? CI : AddI;
  962. auto *UAddWithOverflow =
  963. CallInst::Create(F, {A, B}, "uadd.overflow", InsertPt);
  964. auto *UAdd = ExtractValueInst::Create(UAddWithOverflow, 0, "uadd", InsertPt);
  965. auto *Overflow =
  966. ExtractValueInst::Create(UAddWithOverflow, 1, "overflow", InsertPt);
  967. CI->replaceAllUsesWith(Overflow);
  968. AddI->replaceAllUsesWith(UAdd);
  969. CI->eraseFromParent();
  970. AddI->eraseFromParent();
  971. return true;
  972. }
  973. /// Sink the given CmpInst into user blocks to reduce the number of virtual
  974. /// registers that must be created and coalesced. This is a clear win except on
  975. /// targets with multiple condition code registers (PowerPC), where it might
  976. /// lose; some adjustment may be wanted there.
  977. ///
  978. /// Return true if any changes are made.
  979. static bool SinkCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
  980. BasicBlock *DefBB = CI->getParent();
  981. // Avoid sinking soft-FP comparisons, since this can move them into a loop.
  982. if (TLI && TLI->useSoftFloat() && isa<FCmpInst>(CI))
  983. return false;
  984. // Only insert a cmp in each block once.
  985. DenseMap<BasicBlock*, CmpInst*> InsertedCmps;
  986. bool MadeChange = false;
  987. for (Value::user_iterator UI = CI->user_begin(), E = CI->user_end();
  988. UI != E; ) {
  989. Use &TheUse = UI.getUse();
  990. Instruction *User = cast<Instruction>(*UI);
  991. // Preincrement use iterator so we don't invalidate it.
  992. ++UI;
  993. // Don't bother for PHI nodes.
  994. if (isa<PHINode>(User))
  995. continue;
  996. // Figure out which BB this cmp is used in.
  997. BasicBlock *UserBB = User->getParent();
  998. // If this user is in the same block as the cmp, don't change the cmp.
  999. if (UserBB == DefBB) continue;
  1000. // If we have already inserted a cmp into this block, use it.
  1001. CmpInst *&InsertedCmp = InsertedCmps[UserBB];
  1002. if (!InsertedCmp) {
  1003. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1004. assert(InsertPt != UserBB->end());
  1005. InsertedCmp =
  1006. CmpInst::Create(CI->getOpcode(), CI->getPredicate(),
  1007. CI->getOperand(0), CI->getOperand(1), "", &*InsertPt);
  1008. // Propagate the debug info.
  1009. InsertedCmp->setDebugLoc(CI->getDebugLoc());
  1010. }
  1011. // Replace a use of the cmp with a use of the new cmp.
  1012. TheUse = InsertedCmp;
  1013. MadeChange = true;
  1014. ++NumCmpUses;
  1015. }
  1016. // If we removed all uses, nuke the cmp.
  1017. if (CI->use_empty()) {
  1018. CI->eraseFromParent();
  1019. MadeChange = true;
  1020. }
  1021. return MadeChange;
  1022. }
  1023. static bool OptimizeCmpExpression(CmpInst *CI, const TargetLowering *TLI) {
  1024. if (SinkCmpExpression(CI, TLI))
  1025. return true;
  1026. if (CombineUAddWithOverflow(CI))
  1027. return true;
  1028. return false;
  1029. }
  1030. /// Duplicate and sink the given 'and' instruction into user blocks where it is
  1031. /// used in a compare to allow isel to generate better code for targets where
  1032. /// this operation can be combined.
  1033. ///
  1034. /// Return true if any changes are made.
  1035. static bool sinkAndCmp0Expression(Instruction *AndI,
  1036. const TargetLowering &TLI,
  1037. SetOfInstrs &InsertedInsts) {
  1038. // Double-check that we're not trying to optimize an instruction that was
  1039. // already optimized by some other part of this pass.
  1040. assert(!InsertedInsts.count(AndI) &&
  1041. "Attempting to optimize already optimized and instruction");
  1042. (void) InsertedInsts;
  1043. // Nothing to do for single use in same basic block.
  1044. if (AndI->hasOneUse() &&
  1045. AndI->getParent() == cast<Instruction>(*AndI->user_begin())->getParent())
  1046. return false;
  1047. // Try to avoid cases where sinking/duplicating is likely to increase register
  1048. // pressure.
  1049. if (!isa<ConstantInt>(AndI->getOperand(0)) &&
  1050. !isa<ConstantInt>(AndI->getOperand(1)) &&
  1051. AndI->getOperand(0)->hasOneUse() && AndI->getOperand(1)->hasOneUse())
  1052. return false;
  1053. for (auto *U : AndI->users()) {
  1054. Instruction *User = cast<Instruction>(U);
  1055. // Only sink for and mask feeding icmp with 0.
  1056. if (!isa<ICmpInst>(User))
  1057. return false;
  1058. auto *CmpC = dyn_cast<ConstantInt>(User->getOperand(1));
  1059. if (!CmpC || !CmpC->isZero())
  1060. return false;
  1061. }
  1062. if (!TLI.isMaskAndCmp0FoldingBeneficial(*AndI))
  1063. return false;
  1064. DEBUG(dbgs() << "found 'and' feeding only icmp 0;\n");
  1065. DEBUG(AndI->getParent()->dump());
  1066. // Push the 'and' into the same block as the icmp 0. There should only be
  1067. // one (icmp (and, 0)) in each block, since CSE/GVN should have removed any
  1068. // others, so we don't need to keep track of which BBs we insert into.
  1069. for (Value::user_iterator UI = AndI->user_begin(), E = AndI->user_end();
  1070. UI != E; ) {
  1071. Use &TheUse = UI.getUse();
  1072. Instruction *User = cast<Instruction>(*UI);
  1073. // Preincrement use iterator so we don't invalidate it.
  1074. ++UI;
  1075. DEBUG(dbgs() << "sinking 'and' use: " << *User << "\n");
  1076. // Keep the 'and' in the same place if the use is already in the same block.
  1077. Instruction *InsertPt =
  1078. User->getParent() == AndI->getParent() ? AndI : User;
  1079. Instruction *InsertedAnd =
  1080. BinaryOperator::Create(Instruction::And, AndI->getOperand(0),
  1081. AndI->getOperand(1), "", InsertPt);
  1082. // Propagate the debug info.
  1083. InsertedAnd->setDebugLoc(AndI->getDebugLoc());
  1084. // Replace a use of the 'and' with a use of the new 'and'.
  1085. TheUse = InsertedAnd;
  1086. ++NumAndUses;
  1087. DEBUG(User->getParent()->dump());
  1088. }
  1089. // We removed all uses, nuke the and.
  1090. AndI->eraseFromParent();
  1091. return true;
  1092. }
  1093. /// Check if the candidates could be combined with a shift instruction, which
  1094. /// includes:
  1095. /// 1. Truncate instruction
  1096. /// 2. And instruction and the imm is a mask of the low bits:
  1097. /// imm & (imm+1) == 0
  1098. static bool isExtractBitsCandidateUse(Instruction *User) {
  1099. if (!isa<TruncInst>(User)) {
  1100. if (User->getOpcode() != Instruction::And ||
  1101. !isa<ConstantInt>(User->getOperand(1)))
  1102. return false;
  1103. const APInt &Cimm = cast<ConstantInt>(User->getOperand(1))->getValue();
  1104. if ((Cimm & (Cimm + 1)).getBoolValue())
  1105. return false;
  1106. }
  1107. return true;
  1108. }
  1109. /// Sink both shift and truncate instruction to the use of truncate's BB.
  1110. static bool
  1111. SinkShiftAndTruncate(BinaryOperator *ShiftI, Instruction *User, ConstantInt *CI,
  1112. DenseMap<BasicBlock *, BinaryOperator *> &InsertedShifts,
  1113. const TargetLowering &TLI, const DataLayout &DL) {
  1114. BasicBlock *UserBB = User->getParent();
  1115. DenseMap<BasicBlock *, CastInst *> InsertedTruncs;
  1116. TruncInst *TruncI = dyn_cast<TruncInst>(User);
  1117. bool MadeChange = false;
  1118. for (Value::user_iterator TruncUI = TruncI->user_begin(),
  1119. TruncE = TruncI->user_end();
  1120. TruncUI != TruncE;) {
  1121. Use &TruncTheUse = TruncUI.getUse();
  1122. Instruction *TruncUser = cast<Instruction>(*TruncUI);
  1123. // Preincrement use iterator so we don't invalidate it.
  1124. ++TruncUI;
  1125. int ISDOpcode = TLI.InstructionOpcodeToISD(TruncUser->getOpcode());
  1126. if (!ISDOpcode)
  1127. continue;
  1128. // If the use is actually a legal node, there will not be an
  1129. // implicit truncate.
  1130. // FIXME: always querying the result type is just an
  1131. // approximation; some nodes' legality is determined by the
  1132. // operand or other means. There's no good way to find out though.
  1133. if (TLI.isOperationLegalOrCustom(
  1134. ISDOpcode, TLI.getValueType(DL, TruncUser->getType(), true)))
  1135. continue;
  1136. // Don't bother for PHI nodes.
  1137. if (isa<PHINode>(TruncUser))
  1138. continue;
  1139. BasicBlock *TruncUserBB = TruncUser->getParent();
  1140. if (UserBB == TruncUserBB)
  1141. continue;
  1142. BinaryOperator *&InsertedShift = InsertedShifts[TruncUserBB];
  1143. CastInst *&InsertedTrunc = InsertedTruncs[TruncUserBB];
  1144. if (!InsertedShift && !InsertedTrunc) {
  1145. BasicBlock::iterator InsertPt = TruncUserBB->getFirstInsertionPt();
  1146. assert(InsertPt != TruncUserBB->end());
  1147. // Sink the shift
  1148. if (ShiftI->getOpcode() == Instruction::AShr)
  1149. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1150. "", &*InsertPt);
  1151. else
  1152. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1153. "", &*InsertPt);
  1154. // Sink the trunc
  1155. BasicBlock::iterator TruncInsertPt = TruncUserBB->getFirstInsertionPt();
  1156. TruncInsertPt++;
  1157. assert(TruncInsertPt != TruncUserBB->end());
  1158. InsertedTrunc = CastInst::Create(TruncI->getOpcode(), InsertedShift,
  1159. TruncI->getType(), "", &*TruncInsertPt);
  1160. MadeChange = true;
  1161. TruncTheUse = InsertedTrunc;
  1162. }
  1163. }
  1164. return MadeChange;
  1165. }
  1166. /// Sink the shift *right* instruction into user blocks if the uses could
  1167. /// potentially be combined with this shift instruction and generate BitExtract
  1168. /// instruction. It will only be applied if the architecture supports BitExtract
  1169. /// instruction. Here is an example:
  1170. /// BB1:
  1171. /// %x.extract.shift = lshr i64 %arg1, 32
  1172. /// BB2:
  1173. /// %x.extract.trunc = trunc i64 %x.extract.shift to i16
  1174. /// ==>
  1175. ///
  1176. /// BB2:
  1177. /// %x.extract.shift.1 = lshr i64 %arg1, 32
  1178. /// %x.extract.trunc = trunc i64 %x.extract.shift.1 to i16
  1179. ///
  1180. /// CodeGen will recoginze the pattern in BB2 and generate BitExtract
  1181. /// instruction.
  1182. /// Return true if any changes are made.
  1183. static bool OptimizeExtractBits(BinaryOperator *ShiftI, ConstantInt *CI,
  1184. const TargetLowering &TLI,
  1185. const DataLayout &DL) {
  1186. BasicBlock *DefBB = ShiftI->getParent();
  1187. /// Only insert instructions in each block once.
  1188. DenseMap<BasicBlock *, BinaryOperator *> InsertedShifts;
  1189. bool shiftIsLegal = TLI.isTypeLegal(TLI.getValueType(DL, ShiftI->getType()));
  1190. bool MadeChange = false;
  1191. for (Value::user_iterator UI = ShiftI->user_begin(), E = ShiftI->user_end();
  1192. UI != E;) {
  1193. Use &TheUse = UI.getUse();
  1194. Instruction *User = cast<Instruction>(*UI);
  1195. // Preincrement use iterator so we don't invalidate it.
  1196. ++UI;
  1197. // Don't bother for PHI nodes.
  1198. if (isa<PHINode>(User))
  1199. continue;
  1200. if (!isExtractBitsCandidateUse(User))
  1201. continue;
  1202. BasicBlock *UserBB = User->getParent();
  1203. if (UserBB == DefBB) {
  1204. // If the shift and truncate instruction are in the same BB. The use of
  1205. // the truncate(TruncUse) may still introduce another truncate if not
  1206. // legal. In this case, we would like to sink both shift and truncate
  1207. // instruction to the BB of TruncUse.
  1208. // for example:
  1209. // BB1:
  1210. // i64 shift.result = lshr i64 opnd, imm
  1211. // trunc.result = trunc shift.result to i16
  1212. //
  1213. // BB2:
  1214. // ----> We will have an implicit truncate here if the architecture does
  1215. // not have i16 compare.
  1216. // cmp i16 trunc.result, opnd2
  1217. //
  1218. if (isa<TruncInst>(User) && shiftIsLegal
  1219. // If the type of the truncate is legal, no trucate will be
  1220. // introduced in other basic blocks.
  1221. &&
  1222. (!TLI.isTypeLegal(TLI.getValueType(DL, User->getType()))))
  1223. MadeChange =
  1224. SinkShiftAndTruncate(ShiftI, User, CI, InsertedShifts, TLI, DL);
  1225. continue;
  1226. }
  1227. // If we have already inserted a shift into this block, use it.
  1228. BinaryOperator *&InsertedShift = InsertedShifts[UserBB];
  1229. if (!InsertedShift) {
  1230. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  1231. assert(InsertPt != UserBB->end());
  1232. if (ShiftI->getOpcode() == Instruction::AShr)
  1233. InsertedShift = BinaryOperator::CreateAShr(ShiftI->getOperand(0), CI,
  1234. "", &*InsertPt);
  1235. else
  1236. InsertedShift = BinaryOperator::CreateLShr(ShiftI->getOperand(0), CI,
  1237. "", &*InsertPt);
  1238. MadeChange = true;
  1239. }
  1240. // Replace a use of the shift with a use of the new shift.
  1241. TheUse = InsertedShift;
  1242. }
  1243. // If we removed all uses, nuke the shift.
  1244. if (ShiftI->use_empty())
  1245. ShiftI->eraseFromParent();
  1246. return MadeChange;
  1247. }
  1248. /// If counting leading or trailing zeros is an expensive operation and a zero
  1249. /// input is defined, add a check for zero to avoid calling the intrinsic.
  1250. ///
  1251. /// We want to transform:
  1252. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 false)
  1253. ///
  1254. /// into:
  1255. /// entry:
  1256. /// %cmpz = icmp eq i64 %A, 0
  1257. /// br i1 %cmpz, label %cond.end, label %cond.false
  1258. /// cond.false:
  1259. /// %z = call i64 @llvm.cttz.i64(i64 %A, i1 true)
  1260. /// br label %cond.end
  1261. /// cond.end:
  1262. /// %ctz = phi i64 [ 64, %entry ], [ %z, %cond.false ]
  1263. ///
  1264. /// If the transform is performed, return true and set ModifiedDT to true.
  1265. static bool despeculateCountZeros(IntrinsicInst *CountZeros,
  1266. const TargetLowering *TLI,
  1267. const DataLayout *DL,
  1268. bool &ModifiedDT) {
  1269. if (!TLI || !DL)
  1270. return false;
  1271. // If a zero input is undefined, it doesn't make sense to despeculate that.
  1272. if (match(CountZeros->getOperand(1), m_One()))
  1273. return false;
  1274. // If it's cheap to speculate, there's nothing to do.
  1275. auto IntrinsicID = CountZeros->getIntrinsicID();
  1276. if ((IntrinsicID == Intrinsic::cttz && TLI->isCheapToSpeculateCttz()) ||
  1277. (IntrinsicID == Intrinsic::ctlz && TLI->isCheapToSpeculateCtlz()))
  1278. return false;
  1279. // Only handle legal scalar cases. Anything else requires too much work.
  1280. Type *Ty = CountZeros->getType();
  1281. unsigned SizeInBits = Ty->getPrimitiveSizeInBits();
  1282. if (Ty->isVectorTy() || SizeInBits > DL->getLargestLegalIntTypeSizeInBits())
  1283. return false;
  1284. // The intrinsic will be sunk behind a compare against zero and branch.
  1285. BasicBlock *StartBlock = CountZeros->getParent();
  1286. BasicBlock *CallBlock = StartBlock->splitBasicBlock(CountZeros, "cond.false");
  1287. // Create another block after the count zero intrinsic. A PHI will be added
  1288. // in this block to select the result of the intrinsic or the bit-width
  1289. // constant if the input to the intrinsic is zero.
  1290. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(CountZeros));
  1291. BasicBlock *EndBlock = CallBlock->splitBasicBlock(SplitPt, "cond.end");
  1292. // Set up a builder to create a compare, conditional branch, and PHI.
  1293. IRBuilder<> Builder(CountZeros->getContext());
  1294. Builder.SetInsertPoint(StartBlock->getTerminator());
  1295. Builder.SetCurrentDebugLocation(CountZeros->getDebugLoc());
  1296. // Replace the unconditional branch that was created by the first split with
  1297. // a compare against zero and a conditional branch.
  1298. Value *Zero = Constant::getNullValue(Ty);
  1299. Value *Cmp = Builder.CreateICmpEQ(CountZeros->getOperand(0), Zero, "cmpz");
  1300. Builder.CreateCondBr(Cmp, EndBlock, CallBlock);
  1301. StartBlock->getTerminator()->eraseFromParent();
  1302. // Create a PHI in the end block to select either the output of the intrinsic
  1303. // or the bit width of the operand.
  1304. Builder.SetInsertPoint(&EndBlock->front());
  1305. PHINode *PN = Builder.CreatePHI(Ty, 2, "ctz");
  1306. CountZeros->replaceAllUsesWith(PN);
  1307. Value *BitWidth = Builder.getInt(APInt(SizeInBits, SizeInBits));
  1308. PN->addIncoming(BitWidth, StartBlock);
  1309. PN->addIncoming(CountZeros, CallBlock);
  1310. // We are explicitly handling the zero case, so we can set the intrinsic's
  1311. // undefined zero argument to 'true'. This will also prevent reprocessing the
  1312. // intrinsic; we only despeculate when a zero input is defined.
  1313. CountZeros->setArgOperand(1, Builder.getTrue());
  1314. ModifiedDT = true;
  1315. return true;
  1316. }
  1317. bool CodeGenPrepare::optimizeCallInst(CallInst *CI, bool &ModifiedDT) {
  1318. BasicBlock *BB = CI->getParent();
  1319. // Lower inline assembly if we can.
  1320. // If we found an inline asm expession, and if the target knows how to
  1321. // lower it to normal LLVM code, do so now.
  1322. if (TLI && isa<InlineAsm>(CI->getCalledValue())) {
  1323. if (TLI->ExpandInlineAsm(CI)) {
  1324. // Avoid invalidating the iterator.
  1325. CurInstIterator = BB->begin();
  1326. // Avoid processing instructions out of order, which could cause
  1327. // reuse before a value is defined.
  1328. SunkAddrs.clear();
  1329. return true;
  1330. }
  1331. // Sink address computing for memory operands into the block.
  1332. if (optimizeInlineAsmInst(CI))
  1333. return true;
  1334. }
  1335. // Align the pointer arguments to this call if the target thinks it's a good
  1336. // idea
  1337. unsigned MinSize, PrefAlign;
  1338. if (TLI && TLI->shouldAlignPointerArgs(CI, MinSize, PrefAlign)) {
  1339. for (auto &Arg : CI->arg_operands()) {
  1340. // We want to align both objects whose address is used directly and
  1341. // objects whose address is used in casts and GEPs, though it only makes
  1342. // sense for GEPs if the offset is a multiple of the desired alignment and
  1343. // if size - offset meets the size threshold.
  1344. if (!Arg->getType()->isPointerTy())
  1345. continue;
  1346. APInt Offset(DL->getIndexSizeInBits(
  1347. cast<PointerType>(Arg->getType())->getAddressSpace()),
  1348. 0);
  1349. Value *Val = Arg->stripAndAccumulateInBoundsConstantOffsets(*DL, Offset);
  1350. uint64_t Offset2 = Offset.getLimitedValue();
  1351. if ((Offset2 & (PrefAlign-1)) != 0)
  1352. continue;
  1353. AllocaInst *AI;
  1354. if ((AI = dyn_cast<AllocaInst>(Val)) && AI->getAlignment() < PrefAlign &&
  1355. DL->getTypeAllocSize(AI->getAllocatedType()) >= MinSize + Offset2)
  1356. AI->setAlignment(PrefAlign);
  1357. // Global variables can only be aligned if they are defined in this
  1358. // object (i.e. they are uniquely initialized in this object), and
  1359. // over-aligning global variables that have an explicit section is
  1360. // forbidden.
  1361. GlobalVariable *GV;
  1362. if ((GV = dyn_cast<GlobalVariable>(Val)) && GV->canIncreaseAlignment() &&
  1363. GV->getPointerAlignment(*DL) < PrefAlign &&
  1364. DL->getTypeAllocSize(GV->getValueType()) >=
  1365. MinSize + Offset2)
  1366. GV->setAlignment(PrefAlign);
  1367. }
  1368. // If this is a memcpy (or similar) then we may be able to improve the
  1369. // alignment
  1370. if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(CI)) {
  1371. unsigned DestAlign = getKnownAlignment(MI->getDest(), *DL);
  1372. if (DestAlign > MI->getDestAlignment())
  1373. MI->setDestAlignment(DestAlign);
  1374. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) {
  1375. unsigned SrcAlign = getKnownAlignment(MTI->getSource(), *DL);
  1376. if (SrcAlign > MTI->getSourceAlignment())
  1377. MTI->setSourceAlignment(SrcAlign);
  1378. }
  1379. }
  1380. }
  1381. // If we have a cold call site, try to sink addressing computation into the
  1382. // cold block. This interacts with our handling for loads and stores to
  1383. // ensure that we can fold all uses of a potential addressing computation
  1384. // into their uses. TODO: generalize this to work over profiling data
  1385. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  1386. for (auto &Arg : CI->arg_operands()) {
  1387. if (!Arg->getType()->isPointerTy())
  1388. continue;
  1389. unsigned AS = Arg->getType()->getPointerAddressSpace();
  1390. return optimizeMemoryInst(CI, Arg, Arg->getType(), AS);
  1391. }
  1392. IntrinsicInst *II = dyn_cast<IntrinsicInst>(CI);
  1393. if (II) {
  1394. switch (II->getIntrinsicID()) {
  1395. default: break;
  1396. case Intrinsic::objectsize: {
  1397. // Lower all uses of llvm.objectsize.*
  1398. ConstantInt *RetVal =
  1399. lowerObjectSizeCall(II, *DL, TLInfo, /*MustSucceed=*/true);
  1400. // Substituting this can cause recursive simplifications, which can
  1401. // invalidate our iterator. Use a WeakTrackingVH to hold onto it in case
  1402. // this
  1403. // happens.
  1404. Value *CurValue = &*CurInstIterator;
  1405. WeakTrackingVH IterHandle(CurValue);
  1406. replaceAndRecursivelySimplify(CI, RetVal, TLInfo, nullptr);
  1407. // If the iterator instruction was recursively deleted, start over at the
  1408. // start of the block.
  1409. if (IterHandle != CurValue) {
  1410. CurInstIterator = BB->begin();
  1411. SunkAddrs.clear();
  1412. }
  1413. return true;
  1414. }
  1415. case Intrinsic::aarch64_stlxr:
  1416. case Intrinsic::aarch64_stxr: {
  1417. ZExtInst *ExtVal = dyn_cast<ZExtInst>(CI->getArgOperand(0));
  1418. if (!ExtVal || !ExtVal->hasOneUse() ||
  1419. ExtVal->getParent() == CI->getParent())
  1420. return false;
  1421. // Sink a zext feeding stlxr/stxr before it, so it can be folded into it.
  1422. ExtVal->moveBefore(CI);
  1423. // Mark this instruction as "inserted by CGP", so that other
  1424. // optimizations don't touch it.
  1425. InsertedInsts.insert(ExtVal);
  1426. return true;
  1427. }
  1428. case Intrinsic::invariant_group_barrier:
  1429. II->replaceAllUsesWith(II->getArgOperand(0));
  1430. II->eraseFromParent();
  1431. return true;
  1432. case Intrinsic::cttz:
  1433. case Intrinsic::ctlz:
  1434. // If counting zeros is expensive, try to avoid it.
  1435. return despeculateCountZeros(II, TLI, DL, ModifiedDT);
  1436. }
  1437. if (TLI) {
  1438. SmallVector<Value*, 2> PtrOps;
  1439. Type *AccessTy;
  1440. if (TLI->getAddrModeArguments(II, PtrOps, AccessTy))
  1441. while (!PtrOps.empty()) {
  1442. Value *PtrVal = PtrOps.pop_back_val();
  1443. unsigned AS = PtrVal->getType()->getPointerAddressSpace();
  1444. if (optimizeMemoryInst(II, PtrVal, AccessTy, AS))
  1445. return true;
  1446. }
  1447. }
  1448. }
  1449. // From here on out we're working with named functions.
  1450. if (!CI->getCalledFunction()) return false;
  1451. // Lower all default uses of _chk calls. This is very similar
  1452. // to what InstCombineCalls does, but here we are only lowering calls
  1453. // to fortified library functions (e.g. __memcpy_chk) that have the default
  1454. // "don't know" as the objectsize. Anything else should be left alone.
  1455. FortifiedLibCallSimplifier Simplifier(TLInfo, true);
  1456. if (Value *V = Simplifier.optimizeCall(CI)) {
  1457. CI->replaceAllUsesWith(V);
  1458. CI->eraseFromParent();
  1459. return true;
  1460. }
  1461. return false;
  1462. }
  1463. /// Look for opportunities to duplicate return instructions to the predecessor
  1464. /// to enable tail call optimizations. The case it is currently looking for is:
  1465. /// @code
  1466. /// bb0:
  1467. /// %tmp0 = tail call i32 @f0()
  1468. /// br label %return
  1469. /// bb1:
  1470. /// %tmp1 = tail call i32 @f1()
  1471. /// br label %return
  1472. /// bb2:
  1473. /// %tmp2 = tail call i32 @f2()
  1474. /// br label %return
  1475. /// return:
  1476. /// %retval = phi i32 [ %tmp0, %bb0 ], [ %tmp1, %bb1 ], [ %tmp2, %bb2 ]
  1477. /// ret i32 %retval
  1478. /// @endcode
  1479. ///
  1480. /// =>
  1481. ///
  1482. /// @code
  1483. /// bb0:
  1484. /// %tmp0 = tail call i32 @f0()
  1485. /// ret i32 %tmp0
  1486. /// bb1:
  1487. /// %tmp1 = tail call i32 @f1()
  1488. /// ret i32 %tmp1
  1489. /// bb2:
  1490. /// %tmp2 = tail call i32 @f2()
  1491. /// ret i32 %tmp2
  1492. /// @endcode
  1493. bool CodeGenPrepare::dupRetToEnableTailCallOpts(BasicBlock *BB) {
  1494. if (!TLI)
  1495. return false;
  1496. ReturnInst *RetI = dyn_cast<ReturnInst>(BB->getTerminator());
  1497. if (!RetI)
  1498. return false;
  1499. PHINode *PN = nullptr;
  1500. BitCastInst *BCI = nullptr;
  1501. Value *V = RetI->getReturnValue();
  1502. if (V) {
  1503. BCI = dyn_cast<BitCastInst>(V);
  1504. if (BCI)
  1505. V = BCI->getOperand(0);
  1506. PN = dyn_cast<PHINode>(V);
  1507. if (!PN)
  1508. return false;
  1509. }
  1510. if (PN && PN->getParent() != BB)
  1511. return false;
  1512. // Make sure there are no instructions between the PHI and return, or that the
  1513. // return is the first instruction in the block.
  1514. if (PN) {
  1515. BasicBlock::iterator BI = BB->begin();
  1516. do { ++BI; } while (isa<DbgInfoIntrinsic>(BI));
  1517. if (&*BI == BCI)
  1518. // Also skip over the bitcast.
  1519. ++BI;
  1520. if (&*BI != RetI)
  1521. return false;
  1522. } else {
  1523. BasicBlock::iterator BI = BB->begin();
  1524. while (isa<DbgInfoIntrinsic>(BI)) ++BI;
  1525. if (&*BI != RetI)
  1526. return false;
  1527. }
  1528. /// Only dup the ReturnInst if the CallInst is likely to be emitted as a tail
  1529. /// call.
  1530. const Function *F = BB->getParent();
  1531. SmallVector<CallInst*, 4> TailCalls;
  1532. if (PN) {
  1533. for (unsigned I = 0, E = PN->getNumIncomingValues(); I != E; ++I) {
  1534. CallInst *CI = dyn_cast<CallInst>(PN->getIncomingValue(I));
  1535. // Make sure the phi value is indeed produced by the tail call.
  1536. if (CI && CI->hasOneUse() && CI->getParent() == PN->getIncomingBlock(I) &&
  1537. TLI->mayBeEmittedAsTailCall(CI) &&
  1538. attributesPermitTailCall(F, CI, RetI, *TLI))
  1539. TailCalls.push_back(CI);
  1540. }
  1541. } else {
  1542. SmallPtrSet<BasicBlock*, 4> VisitedBBs;
  1543. for (pred_iterator PI = pred_begin(BB), PE = pred_end(BB); PI != PE; ++PI) {
  1544. if (!VisitedBBs.insert(*PI).second)
  1545. continue;
  1546. BasicBlock::InstListType &InstList = (*PI)->getInstList();
  1547. BasicBlock::InstListType::reverse_iterator RI = InstList.rbegin();
  1548. BasicBlock::InstListType::reverse_iterator RE = InstList.rend();
  1549. do { ++RI; } while (RI != RE && isa<DbgInfoIntrinsic>(&*RI));
  1550. if (RI == RE)
  1551. continue;
  1552. CallInst *CI = dyn_cast<CallInst>(&*RI);
  1553. if (CI && CI->use_empty() && TLI->mayBeEmittedAsTailCall(CI) &&
  1554. attributesPermitTailCall(F, CI, RetI, *TLI))
  1555. TailCalls.push_back(CI);
  1556. }
  1557. }
  1558. bool Changed = false;
  1559. for (unsigned i = 0, e = TailCalls.size(); i != e; ++i) {
  1560. CallInst *CI = TailCalls[i];
  1561. CallSite CS(CI);
  1562. // Conservatively require the attributes of the call to match those of the
  1563. // return. Ignore noalias because it doesn't affect the call sequence.
  1564. AttributeList CalleeAttrs = CS.getAttributes();
  1565. if (AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
  1566. .removeAttribute(Attribute::NoAlias) !=
  1567. AttrBuilder(CalleeAttrs, AttributeList::ReturnIndex)
  1568. .removeAttribute(Attribute::NoAlias))
  1569. continue;
  1570. // Make sure the call instruction is followed by an unconditional branch to
  1571. // the return block.
  1572. BasicBlock *CallBB = CI->getParent();
  1573. BranchInst *BI = dyn_cast<BranchInst>(CallBB->getTerminator());
  1574. if (!BI || !BI->isUnconditional() || BI->getSuccessor(0) != BB)
  1575. continue;
  1576. // Duplicate the return into CallBB.
  1577. (void)FoldReturnIntoUncondBranch(RetI, BB, CallBB);
  1578. ModifiedDT = Changed = true;
  1579. ++NumRetsDup;
  1580. }
  1581. // If we eliminated all predecessors of the block, delete the block now.
  1582. if (Changed && !BB->hasAddressTaken() && pred_begin(BB) == pred_end(BB))
  1583. BB->eraseFromParent();
  1584. return Changed;
  1585. }
  1586. //===----------------------------------------------------------------------===//
  1587. // Memory Optimization
  1588. //===----------------------------------------------------------------------===//
  1589. namespace {
  1590. /// This is an extended version of TargetLowering::AddrMode
  1591. /// which holds actual Value*'s for register values.
  1592. struct ExtAddrMode : public TargetLowering::AddrMode {
  1593. Value *BaseReg = nullptr;
  1594. Value *ScaledReg = nullptr;
  1595. Value *OriginalValue = nullptr;
  1596. enum FieldName {
  1597. NoField = 0x00,
  1598. BaseRegField = 0x01,
  1599. BaseGVField = 0x02,
  1600. BaseOffsField = 0x04,
  1601. ScaledRegField = 0x08,
  1602. ScaleField = 0x10,
  1603. MultipleFields = 0xff
  1604. };
  1605. ExtAddrMode() = default;
  1606. void print(raw_ostream &OS) const;
  1607. void dump() const;
  1608. FieldName compare(const ExtAddrMode &other) {
  1609. // First check that the types are the same on each field, as differing types
  1610. // is something we can't cope with later on.
  1611. if (BaseReg && other.BaseReg &&
  1612. BaseReg->getType() != other.BaseReg->getType())
  1613. return MultipleFields;
  1614. if (BaseGV && other.BaseGV &&
  1615. BaseGV->getType() != other.BaseGV->getType())
  1616. return MultipleFields;
  1617. if (ScaledReg && other.ScaledReg &&
  1618. ScaledReg->getType() != other.ScaledReg->getType())
  1619. return MultipleFields;
  1620. // Check each field to see if it differs.
  1621. unsigned Result = NoField;
  1622. if (BaseReg != other.BaseReg)
  1623. Result |= BaseRegField;
  1624. if (BaseGV != other.BaseGV)
  1625. Result |= BaseGVField;
  1626. if (BaseOffs != other.BaseOffs)
  1627. Result |= BaseOffsField;
  1628. if (ScaledReg != other.ScaledReg)
  1629. Result |= ScaledRegField;
  1630. // Don't count 0 as being a different scale, because that actually means
  1631. // unscaled (which will already be counted by having no ScaledReg).
  1632. if (Scale && other.Scale && Scale != other.Scale)
  1633. Result |= ScaleField;
  1634. if (countPopulation(Result) > 1)
  1635. return MultipleFields;
  1636. else
  1637. return static_cast<FieldName>(Result);
  1638. }
  1639. // An AddrMode is trivial if it involves no calculation i.e. it is just a base
  1640. // with no offset.
  1641. bool isTrivial() {
  1642. // An AddrMode is (BaseGV + BaseReg + BaseOffs + ScaleReg * Scale) so it is
  1643. // trivial if at most one of these terms is nonzero, except that BaseGV and
  1644. // BaseReg both being zero actually means a null pointer value, which we
  1645. // consider to be 'non-zero' here.
  1646. return !BaseOffs && !Scale && !(BaseGV && BaseReg);
  1647. }
  1648. Value *GetFieldAsValue(FieldName Field, Type *IntPtrTy) {
  1649. switch (Field) {
  1650. default:
  1651. return nullptr;
  1652. case BaseRegField:
  1653. return BaseReg;
  1654. case BaseGVField:
  1655. return BaseGV;
  1656. case ScaledRegField:
  1657. return ScaledReg;
  1658. case BaseOffsField:
  1659. return ConstantInt::get(IntPtrTy, BaseOffs);
  1660. }
  1661. }
  1662. void SetCombinedField(FieldName Field, Value *V,
  1663. const SmallVectorImpl<ExtAddrMode> &AddrModes) {
  1664. switch (Field) {
  1665. default:
  1666. llvm_unreachable("Unhandled fields are expected to be rejected earlier");
  1667. break;
  1668. case ExtAddrMode::BaseRegField:
  1669. BaseReg = V;
  1670. break;
  1671. case ExtAddrMode::BaseGVField:
  1672. // A combined BaseGV is an Instruction, not a GlobalValue, so it goes
  1673. // in the BaseReg field.
  1674. assert(BaseReg == nullptr);
  1675. BaseReg = V;
  1676. BaseGV = nullptr;
  1677. break;
  1678. case ExtAddrMode::ScaledRegField:
  1679. ScaledReg = V;
  1680. // If we have a mix of scaled and unscaled addrmodes then we want scale
  1681. // to be the scale and not zero.
  1682. if (!Scale)
  1683. for (const ExtAddrMode &AM : AddrModes)
  1684. if (AM.Scale) {
  1685. Scale = AM.Scale;
  1686. break;
  1687. }
  1688. break;
  1689. case ExtAddrMode::BaseOffsField:
  1690. // The offset is no longer a constant, so it goes in ScaledReg with a
  1691. // scale of 1.
  1692. assert(ScaledReg == nullptr);
  1693. ScaledReg = V;
  1694. Scale = 1;
  1695. BaseOffs = 0;
  1696. break;
  1697. }
  1698. }
  1699. };
  1700. } // end anonymous namespace
  1701. #ifndef NDEBUG
  1702. static inline raw_ostream &operator<<(raw_ostream &OS, const ExtAddrMode &AM) {
  1703. AM.print(OS);
  1704. return OS;
  1705. }
  1706. #endif
  1707. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1708. void ExtAddrMode::print(raw_ostream &OS) const {
  1709. bool NeedPlus = false;
  1710. OS << "[";
  1711. if (BaseGV) {
  1712. OS << (NeedPlus ? " + " : "")
  1713. << "GV:";
  1714. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  1715. NeedPlus = true;
  1716. }
  1717. if (BaseOffs) {
  1718. OS << (NeedPlus ? " + " : "")
  1719. << BaseOffs;
  1720. NeedPlus = true;
  1721. }
  1722. if (BaseReg) {
  1723. OS << (NeedPlus ? " + " : "")
  1724. << "Base:";
  1725. BaseReg->printAsOperand(OS, /*PrintType=*/false);
  1726. NeedPlus = true;
  1727. }
  1728. if (Scale) {
  1729. OS << (NeedPlus ? " + " : "")
  1730. << Scale << "*";
  1731. ScaledReg->printAsOperand(OS, /*PrintType=*/false);
  1732. }
  1733. OS << ']';
  1734. }
  1735. LLVM_DUMP_METHOD void ExtAddrMode::dump() const {
  1736. print(dbgs());
  1737. dbgs() << '\n';
  1738. }
  1739. #endif
  1740. namespace {
  1741. /// \brief This class provides transaction based operation on the IR.
  1742. /// Every change made through this class is recorded in the internal state and
  1743. /// can be undone (rollback) until commit is called.
  1744. class TypePromotionTransaction {
  1745. /// \brief This represents the common interface of the individual transaction.
  1746. /// Each class implements the logic for doing one specific modification on
  1747. /// the IR via the TypePromotionTransaction.
  1748. class TypePromotionAction {
  1749. protected:
  1750. /// The Instruction modified.
  1751. Instruction *Inst;
  1752. public:
  1753. /// \brief Constructor of the action.
  1754. /// The constructor performs the related action on the IR.
  1755. TypePromotionAction(Instruction *Inst) : Inst(Inst) {}
  1756. virtual ~TypePromotionAction() = default;
  1757. /// \brief Undo the modification done by this action.
  1758. /// When this method is called, the IR must be in the same state as it was
  1759. /// before this action was applied.
  1760. /// \pre Undoing the action works if and only if the IR is in the exact same
  1761. /// state as it was directly after this action was applied.
  1762. virtual void undo() = 0;
  1763. /// \brief Advocate every change made by this action.
  1764. /// When the results on the IR of the action are to be kept, it is important
  1765. /// to call this function, otherwise hidden information may be kept forever.
  1766. virtual void commit() {
  1767. // Nothing to be done, this action is not doing anything.
  1768. }
  1769. };
  1770. /// \brief Utility to remember the position of an instruction.
  1771. class InsertionHandler {
  1772. /// Position of an instruction.
  1773. /// Either an instruction:
  1774. /// - Is the first in a basic block: BB is used.
  1775. /// - Has a previous instructon: PrevInst is used.
  1776. union {
  1777. Instruction *PrevInst;
  1778. BasicBlock *BB;
  1779. } Point;
  1780. /// Remember whether or not the instruction had a previous instruction.
  1781. bool HasPrevInstruction;
  1782. public:
  1783. /// \brief Record the position of \p Inst.
  1784. InsertionHandler(Instruction *Inst) {
  1785. BasicBlock::iterator It = Inst->getIterator();
  1786. HasPrevInstruction = (It != (Inst->getParent()->begin()));
  1787. if (HasPrevInstruction)
  1788. Point.PrevInst = &*--It;
  1789. else
  1790. Point.BB = Inst->getParent();
  1791. }
  1792. /// \brief Insert \p Inst at the recorded position.
  1793. void insert(Instruction *Inst) {
  1794. if (HasPrevInstruction) {
  1795. if (Inst->getParent())
  1796. Inst->removeFromParent();
  1797. Inst->insertAfter(Point.PrevInst);
  1798. } else {
  1799. Instruction *Position = &*Point.BB->getFirstInsertionPt();
  1800. if (Inst->getParent())
  1801. Inst->moveBefore(Position);
  1802. else
  1803. Inst->insertBefore(Position);
  1804. }
  1805. }
  1806. };
  1807. /// \brief Move an instruction before another.
  1808. class InstructionMoveBefore : public TypePromotionAction {
  1809. /// Original position of the instruction.
  1810. InsertionHandler Position;
  1811. public:
  1812. /// \brief Move \p Inst before \p Before.
  1813. InstructionMoveBefore(Instruction *Inst, Instruction *Before)
  1814. : TypePromotionAction(Inst), Position(Inst) {
  1815. DEBUG(dbgs() << "Do: move: " << *Inst << "\nbefore: " << *Before << "\n");
  1816. Inst->moveBefore(Before);
  1817. }
  1818. /// \brief Move the instruction back to its original position.
  1819. void undo() override {
  1820. DEBUG(dbgs() << "Undo: moveBefore: " << *Inst << "\n");
  1821. Position.insert(Inst);
  1822. }
  1823. };
  1824. /// \brief Set the operand of an instruction with a new value.
  1825. class OperandSetter : public TypePromotionAction {
  1826. /// Original operand of the instruction.
  1827. Value *Origin;
  1828. /// Index of the modified instruction.
  1829. unsigned Idx;
  1830. public:
  1831. /// \brief Set \p Idx operand of \p Inst with \p NewVal.
  1832. OperandSetter(Instruction *Inst, unsigned Idx, Value *NewVal)
  1833. : TypePromotionAction(Inst), Idx(Idx) {
  1834. DEBUG(dbgs() << "Do: setOperand: " << Idx << "\n"
  1835. << "for:" << *Inst << "\n"
  1836. << "with:" << *NewVal << "\n");
  1837. Origin = Inst->getOperand(Idx);
  1838. Inst->setOperand(Idx, NewVal);
  1839. }
  1840. /// \brief Restore the original value of the instruction.
  1841. void undo() override {
  1842. DEBUG(dbgs() << "Undo: setOperand:" << Idx << "\n"
  1843. << "for: " << *Inst << "\n"
  1844. << "with: " << *Origin << "\n");
  1845. Inst->setOperand(Idx, Origin);
  1846. }
  1847. };
  1848. /// \brief Hide the operands of an instruction.
  1849. /// Do as if this instruction was not using any of its operands.
  1850. class OperandsHider : public TypePromotionAction {
  1851. /// The list of original operands.
  1852. SmallVector<Value *, 4> OriginalValues;
  1853. public:
  1854. /// \brief Remove \p Inst from the uses of the operands of \p Inst.
  1855. OperandsHider(Instruction *Inst) : TypePromotionAction(Inst) {
  1856. DEBUG(dbgs() << "Do: OperandsHider: " << *Inst << "\n");
  1857. unsigned NumOpnds = Inst->getNumOperands();
  1858. OriginalValues.reserve(NumOpnds);
  1859. for (unsigned It = 0; It < NumOpnds; ++It) {
  1860. // Save the current operand.
  1861. Value *Val = Inst->getOperand(It);
  1862. OriginalValues.push_back(Val);
  1863. // Set a dummy one.
  1864. // We could use OperandSetter here, but that would imply an overhead
  1865. // that we are not willing to pay.
  1866. Inst->setOperand(It, UndefValue::get(Val->getType()));
  1867. }
  1868. }
  1869. /// \brief Restore the original list of uses.
  1870. void undo() override {
  1871. DEBUG(dbgs() << "Undo: OperandsHider: " << *Inst << "\n");
  1872. for (unsigned It = 0, EndIt = OriginalValues.size(); It != EndIt; ++It)
  1873. Inst->setOperand(It, OriginalValues[It]);
  1874. }
  1875. };
  1876. /// \brief Build a truncate instruction.
  1877. class TruncBuilder : public TypePromotionAction {
  1878. Value *Val;
  1879. public:
  1880. /// \brief Build a truncate instruction of \p Opnd producing a \p Ty
  1881. /// result.
  1882. /// trunc Opnd to Ty.
  1883. TruncBuilder(Instruction *Opnd, Type *Ty) : TypePromotionAction(Opnd) {
  1884. IRBuilder<> Builder(Opnd);
  1885. Val = Builder.CreateTrunc(Opnd, Ty, "promoted");
  1886. DEBUG(dbgs() << "Do: TruncBuilder: " << *Val << "\n");
  1887. }
  1888. /// \brief Get the built value.
  1889. Value *getBuiltValue() { return Val; }
  1890. /// \brief Remove the built instruction.
  1891. void undo() override {
  1892. DEBUG(dbgs() << "Undo: TruncBuilder: " << *Val << "\n");
  1893. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1894. IVal->eraseFromParent();
  1895. }
  1896. };
  1897. /// \brief Build a sign extension instruction.
  1898. class SExtBuilder : public TypePromotionAction {
  1899. Value *Val;
  1900. public:
  1901. /// \brief Build a sign extension instruction of \p Opnd producing a \p Ty
  1902. /// result.
  1903. /// sext Opnd to Ty.
  1904. SExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1905. : TypePromotionAction(InsertPt) {
  1906. IRBuilder<> Builder(InsertPt);
  1907. Val = Builder.CreateSExt(Opnd, Ty, "promoted");
  1908. DEBUG(dbgs() << "Do: SExtBuilder: " << *Val << "\n");
  1909. }
  1910. /// \brief Get the built value.
  1911. Value *getBuiltValue() { return Val; }
  1912. /// \brief Remove the built instruction.
  1913. void undo() override {
  1914. DEBUG(dbgs() << "Undo: SExtBuilder: " << *Val << "\n");
  1915. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1916. IVal->eraseFromParent();
  1917. }
  1918. };
  1919. /// \brief Build a zero extension instruction.
  1920. class ZExtBuilder : public TypePromotionAction {
  1921. Value *Val;
  1922. public:
  1923. /// \brief Build a zero extension instruction of \p Opnd producing a \p Ty
  1924. /// result.
  1925. /// zext Opnd to Ty.
  1926. ZExtBuilder(Instruction *InsertPt, Value *Opnd, Type *Ty)
  1927. : TypePromotionAction(InsertPt) {
  1928. IRBuilder<> Builder(InsertPt);
  1929. Val = Builder.CreateZExt(Opnd, Ty, "promoted");
  1930. DEBUG(dbgs() << "Do: ZExtBuilder: " << *Val << "\n");
  1931. }
  1932. /// \brief Get the built value.
  1933. Value *getBuiltValue() { return Val; }
  1934. /// \brief Remove the built instruction.
  1935. void undo() override {
  1936. DEBUG(dbgs() << "Undo: ZExtBuilder: " << *Val << "\n");
  1937. if (Instruction *IVal = dyn_cast<Instruction>(Val))
  1938. IVal->eraseFromParent();
  1939. }
  1940. };
  1941. /// \brief Mutate an instruction to another type.
  1942. class TypeMutator : public TypePromotionAction {
  1943. /// Record the original type.
  1944. Type *OrigTy;
  1945. public:
  1946. /// \brief Mutate the type of \p Inst into \p NewTy.
  1947. TypeMutator(Instruction *Inst, Type *NewTy)
  1948. : TypePromotionAction(Inst), OrigTy(Inst->getType()) {
  1949. DEBUG(dbgs() << "Do: MutateType: " << *Inst << " with " << *NewTy
  1950. << "\n");
  1951. Inst->mutateType(NewTy);
  1952. }
  1953. /// \brief Mutate the instruction back to its original type.
  1954. void undo() override {
  1955. DEBUG(dbgs() << "Undo: MutateType: " << *Inst << " with " << *OrigTy
  1956. << "\n");
  1957. Inst->mutateType(OrigTy);
  1958. }
  1959. };
  1960. /// \brief Replace the uses of an instruction by another instruction.
  1961. class UsesReplacer : public TypePromotionAction {
  1962. /// Helper structure to keep track of the replaced uses.
  1963. struct InstructionAndIdx {
  1964. /// The instruction using the instruction.
  1965. Instruction *Inst;
  1966. /// The index where this instruction is used for Inst.
  1967. unsigned Idx;
  1968. InstructionAndIdx(Instruction *Inst, unsigned Idx)
  1969. : Inst(Inst), Idx(Idx) {}
  1970. };
  1971. /// Keep track of the original uses (pair Instruction, Index).
  1972. SmallVector<InstructionAndIdx, 4> OriginalUses;
  1973. using use_iterator = SmallVectorImpl<InstructionAndIdx>::iterator;
  1974. public:
  1975. /// \brief Replace all the use of \p Inst by \p New.
  1976. UsesReplacer(Instruction *Inst, Value *New) : TypePromotionAction(Inst) {
  1977. DEBUG(dbgs() << "Do: UsersReplacer: " << *Inst << " with " << *New
  1978. << "\n");
  1979. // Record the original uses.
  1980. for (Use &U : Inst->uses()) {
  1981. Instruction *UserI = cast<Instruction>(U.getUser());
  1982. OriginalUses.push_back(InstructionAndIdx(UserI, U.getOperandNo()));
  1983. }
  1984. // Now, we can replace the uses.
  1985. Inst->replaceAllUsesWith(New);
  1986. }
  1987. /// \brief Reassign the original uses of Inst to Inst.
  1988. void undo() override {
  1989. DEBUG(dbgs() << "Undo: UsersReplacer: " << *Inst << "\n");
  1990. for (use_iterator UseIt = OriginalUses.begin(),
  1991. EndIt = OriginalUses.end();
  1992. UseIt != EndIt; ++UseIt) {
  1993. UseIt->Inst->setOperand(UseIt->Idx, Inst);
  1994. }
  1995. }
  1996. };
  1997. /// \brief Remove an instruction from the IR.
  1998. class InstructionRemover : public TypePromotionAction {
  1999. /// Original position of the instruction.
  2000. InsertionHandler Inserter;
  2001. /// Helper structure to hide all the link to the instruction. In other
  2002. /// words, this helps to do as if the instruction was removed.
  2003. OperandsHider Hider;
  2004. /// Keep track of the uses replaced, if any.
  2005. UsesReplacer *Replacer = nullptr;
  2006. /// Keep track of instructions removed.
  2007. SetOfInstrs &RemovedInsts;
  2008. public:
  2009. /// \brief Remove all reference of \p Inst and optinally replace all its
  2010. /// uses with New.
  2011. /// \p RemovedInsts Keep track of the instructions removed by this Action.
  2012. /// \pre If !Inst->use_empty(), then New != nullptr
  2013. InstructionRemover(Instruction *Inst, SetOfInstrs &RemovedInsts,
  2014. Value *New = nullptr)
  2015. : TypePromotionAction(Inst), Inserter(Inst), Hider(Inst),
  2016. RemovedInsts(RemovedInsts) {
  2017. if (New)
  2018. Replacer = new UsesReplacer(Inst, New);
  2019. DEBUG(dbgs() << "Do: InstructionRemover: " << *Inst << "\n");
  2020. RemovedInsts.insert(Inst);
  2021. /// The instructions removed here will be freed after completing
  2022. /// optimizeBlock() for all blocks as we need to keep track of the
  2023. /// removed instructions during promotion.
  2024. Inst->removeFromParent();
  2025. }
  2026. ~InstructionRemover() override { delete Replacer; }
  2027. /// \brief Resurrect the instruction and reassign it to the proper uses if
  2028. /// new value was provided when build this action.
  2029. void undo() override {
  2030. DEBUG(dbgs() << "Undo: InstructionRemover: " << *Inst << "\n");
  2031. Inserter.insert(Inst);
  2032. if (Replacer)
  2033. Replacer->undo();
  2034. Hider.undo();
  2035. RemovedInsts.erase(Inst);
  2036. }
  2037. };
  2038. public:
  2039. /// Restoration point.
  2040. /// The restoration point is a pointer to an action instead of an iterator
  2041. /// because the iterator may be invalidated but not the pointer.
  2042. using ConstRestorationPt = const TypePromotionAction *;
  2043. TypePromotionTransaction(SetOfInstrs &RemovedInsts)
  2044. : RemovedInsts(RemovedInsts) {}
  2045. /// Advocate every changes made in that transaction.
  2046. void commit();
  2047. /// Undo all the changes made after the given point.
  2048. void rollback(ConstRestorationPt Point);
  2049. /// Get the current restoration point.
  2050. ConstRestorationPt getRestorationPoint() const;
  2051. /// \name API for IR modification with state keeping to support rollback.
  2052. /// @{
  2053. /// Same as Instruction::setOperand.
  2054. void setOperand(Instruction *Inst, unsigned Idx, Value *NewVal);
  2055. /// Same as Instruction::eraseFromParent.
  2056. void eraseInstruction(Instruction *Inst, Value *NewVal = nullptr);
  2057. /// Same as Value::replaceAllUsesWith.
  2058. void replaceAllUsesWith(Instruction *Inst, Value *New);
  2059. /// Same as Value::mutateType.
  2060. void mutateType(Instruction *Inst, Type *NewTy);
  2061. /// Same as IRBuilder::createTrunc.
  2062. Value *createTrunc(Instruction *Opnd, Type *Ty);
  2063. /// Same as IRBuilder::createSExt.
  2064. Value *createSExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2065. /// Same as IRBuilder::createZExt.
  2066. Value *createZExt(Instruction *Inst, Value *Opnd, Type *Ty);
  2067. /// Same as Instruction::moveBefore.
  2068. void moveBefore(Instruction *Inst, Instruction *Before);
  2069. /// @}
  2070. private:
  2071. /// The ordered list of actions made so far.
  2072. SmallVector<std::unique_ptr<TypePromotionAction>, 16> Actions;
  2073. using CommitPt = SmallVectorImpl<std::unique_ptr<TypePromotionAction>>::iterator;
  2074. SetOfInstrs &RemovedInsts;
  2075. };
  2076. } // end anonymous namespace
  2077. void TypePromotionTransaction::setOperand(Instruction *Inst, unsigned Idx,
  2078. Value *NewVal) {
  2079. Actions.push_back(llvm::make_unique<TypePromotionTransaction::OperandSetter>(
  2080. Inst, Idx, NewVal));
  2081. }
  2082. void TypePromotionTransaction::eraseInstruction(Instruction *Inst,
  2083. Value *NewVal) {
  2084. Actions.push_back(
  2085. llvm::make_unique<TypePromotionTransaction::InstructionRemover>(
  2086. Inst, RemovedInsts, NewVal));
  2087. }
  2088. void TypePromotionTransaction::replaceAllUsesWith(Instruction *Inst,
  2089. Value *New) {
  2090. Actions.push_back(
  2091. llvm::make_unique<TypePromotionTransaction::UsesReplacer>(Inst, New));
  2092. }
  2093. void TypePromotionTransaction::mutateType(Instruction *Inst, Type *NewTy) {
  2094. Actions.push_back(
  2095. llvm::make_unique<TypePromotionTransaction::TypeMutator>(Inst, NewTy));
  2096. }
  2097. Value *TypePromotionTransaction::createTrunc(Instruction *Opnd,
  2098. Type *Ty) {
  2099. std::unique_ptr<TruncBuilder> Ptr(new TruncBuilder(Opnd, Ty));
  2100. Value *Val = Ptr->getBuiltValue();
  2101. Actions.push_back(std::move(Ptr));
  2102. return Val;
  2103. }
  2104. Value *TypePromotionTransaction::createSExt(Instruction *Inst,
  2105. Value *Opnd, Type *Ty) {
  2106. std::unique_ptr<SExtBuilder> Ptr(new SExtBuilder(Inst, Opnd, Ty));
  2107. Value *Val = Ptr->getBuiltValue();
  2108. Actions.push_back(std::move(Ptr));
  2109. return Val;
  2110. }
  2111. Value *TypePromotionTransaction::createZExt(Instruction *Inst,
  2112. Value *Opnd, Type *Ty) {
  2113. std::unique_ptr<ZExtBuilder> Ptr(new ZExtBuilder(Inst, Opnd, Ty));
  2114. Value *Val = Ptr->getBuiltValue();
  2115. Actions.push_back(std::move(Ptr));
  2116. return Val;
  2117. }
  2118. void TypePromotionTransaction::moveBefore(Instruction *Inst,
  2119. Instruction *Before) {
  2120. Actions.push_back(
  2121. llvm::make_unique<TypePromotionTransaction::InstructionMoveBefore>(
  2122. Inst, Before));
  2123. }
  2124. TypePromotionTransaction::ConstRestorationPt
  2125. TypePromotionTransaction::getRestorationPoint() const {
  2126. return !Actions.empty() ? Actions.back().get() : nullptr;
  2127. }
  2128. void TypePromotionTransaction::commit() {
  2129. for (CommitPt It = Actions.begin(), EndIt = Actions.end(); It != EndIt;
  2130. ++It)
  2131. (*It)->commit();
  2132. Actions.clear();
  2133. }
  2134. void TypePromotionTransaction::rollback(
  2135. TypePromotionTransaction::ConstRestorationPt Point) {
  2136. while (!Actions.empty() && Point != Actions.back().get()) {
  2137. std::unique_ptr<TypePromotionAction> Curr = Actions.pop_back_val();
  2138. Curr->undo();
  2139. }
  2140. }
  2141. namespace {
  2142. /// \brief A helper class for matching addressing modes.
  2143. ///
  2144. /// This encapsulates the logic for matching the target-legal addressing modes.
  2145. class AddressingModeMatcher {
  2146. SmallVectorImpl<Instruction*> &AddrModeInsts;
  2147. const TargetLowering &TLI;
  2148. const TargetRegisterInfo &TRI;
  2149. const DataLayout &DL;
  2150. /// AccessTy/MemoryInst - This is the type for the access (e.g. double) and
  2151. /// the memory instruction that we're computing this address for.
  2152. Type *AccessTy;
  2153. unsigned AddrSpace;
  2154. Instruction *MemoryInst;
  2155. /// This is the addressing mode that we're building up. This is
  2156. /// part of the return value of this addressing mode matching stuff.
  2157. ExtAddrMode &AddrMode;
  2158. /// The instructions inserted by other CodeGenPrepare optimizations.
  2159. const SetOfInstrs &InsertedInsts;
  2160. /// A map from the instructions to their type before promotion.
  2161. InstrToOrigTy &PromotedInsts;
  2162. /// The ongoing transaction where every action should be registered.
  2163. TypePromotionTransaction &TPT;
  2164. /// This is set to true when we should not do profitability checks.
  2165. /// When true, IsProfitableToFoldIntoAddressingMode always returns true.
  2166. bool IgnoreProfitability;
  2167. AddressingModeMatcher(SmallVectorImpl<Instruction *> &AMI,
  2168. const TargetLowering &TLI,
  2169. const TargetRegisterInfo &TRI,
  2170. Type *AT, unsigned AS,
  2171. Instruction *MI, ExtAddrMode &AM,
  2172. const SetOfInstrs &InsertedInsts,
  2173. InstrToOrigTy &PromotedInsts,
  2174. TypePromotionTransaction &TPT)
  2175. : AddrModeInsts(AMI), TLI(TLI), TRI(TRI),
  2176. DL(MI->getModule()->getDataLayout()), AccessTy(AT), AddrSpace(AS),
  2177. MemoryInst(MI), AddrMode(AM), InsertedInsts(InsertedInsts),
  2178. PromotedInsts(PromotedInsts), TPT(TPT) {
  2179. IgnoreProfitability = false;
  2180. }
  2181. public:
  2182. /// Find the maximal addressing mode that a load/store of V can fold,
  2183. /// give an access type of AccessTy. This returns a list of involved
  2184. /// instructions in AddrModeInsts.
  2185. /// \p InsertedInsts The instructions inserted by other CodeGenPrepare
  2186. /// optimizations.
  2187. /// \p PromotedInsts maps the instructions to their type before promotion.
  2188. /// \p The ongoing transaction where every action should be registered.
  2189. static ExtAddrMode Match(Value *V, Type *AccessTy, unsigned AS,
  2190. Instruction *MemoryInst,
  2191. SmallVectorImpl<Instruction*> &AddrModeInsts,
  2192. const TargetLowering &TLI,
  2193. const TargetRegisterInfo &TRI,
  2194. const SetOfInstrs &InsertedInsts,
  2195. InstrToOrigTy &PromotedInsts,
  2196. TypePromotionTransaction &TPT) {
  2197. ExtAddrMode Result;
  2198. bool Success = AddressingModeMatcher(AddrModeInsts, TLI, TRI,
  2199. AccessTy, AS,
  2200. MemoryInst, Result, InsertedInsts,
  2201. PromotedInsts, TPT).matchAddr(V, 0);
  2202. (void)Success; assert(Success && "Couldn't select *anything*?");
  2203. return Result;
  2204. }
  2205. private:
  2206. bool matchScaledValue(Value *ScaleReg, int64_t Scale, unsigned Depth);
  2207. bool matchAddr(Value *V, unsigned Depth);
  2208. bool matchOperationAddr(User *Operation, unsigned Opcode, unsigned Depth,
  2209. bool *MovedAway = nullptr);
  2210. bool isProfitableToFoldIntoAddressingMode(Instruction *I,
  2211. ExtAddrMode &AMBefore,
  2212. ExtAddrMode &AMAfter);
  2213. bool valueAlreadyLiveAtInst(Value *Val, Value *KnownLive1, Value *KnownLive2);
  2214. bool isPromotionProfitable(unsigned NewCost, unsigned OldCost,
  2215. Value *PromotedOperand) const;
  2216. };
  2217. /// \brief Keep track of simplification of Phi nodes.
  2218. /// Accept the set of all phi nodes and erase phi node from this set
  2219. /// if it is simplified.
  2220. class SimplificationTracker {
  2221. DenseMap<Value *, Value *> Storage;
  2222. const SimplifyQuery &SQ;
  2223. // Tracks newly created Phi nodes. We use a SetVector to get deterministic
  2224. // order when iterating over the set in MatchPhiSet.
  2225. SmallSetVector<PHINode *, 32> AllPhiNodes;
  2226. // Tracks newly created Select nodes.
  2227. SmallPtrSet<SelectInst *, 32> AllSelectNodes;
  2228. public:
  2229. SimplificationTracker(const SimplifyQuery &sq)
  2230. : SQ(sq) {}
  2231. Value *Get(Value *V) {
  2232. do {
  2233. auto SV = Storage.find(V);
  2234. if (SV == Storage.end())
  2235. return V;
  2236. V = SV->second;
  2237. } while (true);
  2238. }
  2239. Value *Simplify(Value *Val) {
  2240. SmallVector<Value *, 32> WorkList;
  2241. SmallPtrSet<Value *, 32> Visited;
  2242. WorkList.push_back(Val);
  2243. while (!WorkList.empty()) {
  2244. auto P = WorkList.pop_back_val();
  2245. if (!Visited.insert(P).second)
  2246. continue;
  2247. if (auto *PI = dyn_cast<Instruction>(P))
  2248. if (Value *V = SimplifyInstruction(cast<Instruction>(PI), SQ)) {
  2249. for (auto *U : PI->users())
  2250. WorkList.push_back(cast<Value>(U));
  2251. Put(PI, V);
  2252. PI->replaceAllUsesWith(V);
  2253. if (auto *PHI = dyn_cast<PHINode>(PI))
  2254. AllPhiNodes.remove(PHI);
  2255. if (auto *Select = dyn_cast<SelectInst>(PI))
  2256. AllSelectNodes.erase(Select);
  2257. PI->eraseFromParent();
  2258. }
  2259. }
  2260. return Get(Val);
  2261. }
  2262. void Put(Value *From, Value *To) {
  2263. Storage.insert({ From, To });
  2264. }
  2265. void ReplacePhi(PHINode *From, PHINode *To) {
  2266. Value* OldReplacement = Get(From);
  2267. while (OldReplacement != From) {
  2268. From = To;
  2269. To = dyn_cast<PHINode>(OldReplacement);
  2270. OldReplacement = Get(From);
  2271. }
  2272. assert(Get(To) == To && "Replacement PHI node is already replaced.");
  2273. Put(From, To);
  2274. From->replaceAllUsesWith(To);
  2275. AllPhiNodes.remove(From);
  2276. From->eraseFromParent();
  2277. }
  2278. SmallSetVector<PHINode *, 32>& newPhiNodes() { return AllPhiNodes; }
  2279. void insertNewPhi(PHINode *PN) { AllPhiNodes.insert(PN); }
  2280. void insertNewSelect(SelectInst *SI) { AllSelectNodes.insert(SI); }
  2281. unsigned countNewPhiNodes() const { return AllPhiNodes.size(); }
  2282. unsigned countNewSelectNodes() const { return AllSelectNodes.size(); }
  2283. void destroyNewNodes(Type *CommonType) {
  2284. // For safe erasing, replace the uses with dummy value first.
  2285. auto Dummy = UndefValue::get(CommonType);
  2286. for (auto I : AllPhiNodes) {
  2287. I->replaceAllUsesWith(Dummy);
  2288. I->eraseFromParent();
  2289. }
  2290. AllPhiNodes.clear();
  2291. for (auto I : AllSelectNodes) {
  2292. I->replaceAllUsesWith(Dummy);
  2293. I->eraseFromParent();
  2294. }
  2295. AllSelectNodes.clear();
  2296. }
  2297. };
  2298. /// \brief A helper class for combining addressing modes.
  2299. class AddressingModeCombiner {
  2300. typedef std::pair<Value *, BasicBlock *> ValueInBB;
  2301. typedef DenseMap<ValueInBB, Value *> FoldAddrToValueMapping;
  2302. typedef std::pair<PHINode *, PHINode *> PHIPair;
  2303. private:
  2304. /// The addressing modes we've collected.
  2305. SmallVector<ExtAddrMode, 16> AddrModes;
  2306. /// The field in which the AddrModes differ, when we have more than one.
  2307. ExtAddrMode::FieldName DifferentField = ExtAddrMode::NoField;
  2308. /// Are the AddrModes that we have all just equal to their original values?
  2309. bool AllAddrModesTrivial = true;
  2310. /// Common Type for all different fields in addressing modes.
  2311. Type *CommonType;
  2312. /// SimplifyQuery for simplifyInstruction utility.
  2313. const SimplifyQuery &SQ;
  2314. /// Original Address.
  2315. ValueInBB Original;
  2316. public:
  2317. AddressingModeCombiner(const SimplifyQuery &_SQ, ValueInBB OriginalValue)
  2318. : CommonType(nullptr), SQ(_SQ), Original(OriginalValue) {}
  2319. /// \brief Get the combined AddrMode
  2320. const ExtAddrMode &getAddrMode() const {
  2321. return AddrModes[0];
  2322. }
  2323. /// \brief Add a new AddrMode if it's compatible with the AddrModes we already
  2324. /// have.
  2325. /// \return True iff we succeeded in doing so.
  2326. bool addNewAddrMode(ExtAddrMode &NewAddrMode) {
  2327. // Take note of if we have any non-trivial AddrModes, as we need to detect
  2328. // when all AddrModes are trivial as then we would introduce a phi or select
  2329. // which just duplicates what's already there.
  2330. AllAddrModesTrivial = AllAddrModesTrivial && NewAddrMode.isTrivial();
  2331. // If this is the first addrmode then everything is fine.
  2332. if (AddrModes.empty()) {
  2333. AddrModes.emplace_back(NewAddrMode);
  2334. return true;
  2335. }
  2336. // Figure out how different this is from the other address modes, which we
  2337. // can do just by comparing against the first one given that we only care
  2338. // about the cumulative difference.
  2339. ExtAddrMode::FieldName ThisDifferentField =
  2340. AddrModes[0].compare(NewAddrMode);
  2341. if (DifferentField == ExtAddrMode::NoField)
  2342. DifferentField = ThisDifferentField;
  2343. else if (DifferentField != ThisDifferentField)
  2344. DifferentField = ExtAddrMode::MultipleFields;
  2345. // If NewAddrMode differs in more than one dimension we cannot handle it.
  2346. bool CanHandle = DifferentField != ExtAddrMode::MultipleFields;
  2347. // If Scale Field is different then we reject.
  2348. CanHandle = CanHandle && DifferentField != ExtAddrMode::ScaleField;
  2349. // We also must reject the case when base offset is different and
  2350. // scale reg is not null, we cannot handle this case due to merge of
  2351. // different offsets will be used as ScaleReg.
  2352. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseOffsField ||
  2353. !NewAddrMode.ScaledReg);
  2354. // We also must reject the case when GV is different and BaseReg installed
  2355. // due to we want to use base reg as a merge of GV values.
  2356. CanHandle = CanHandle && (DifferentField != ExtAddrMode::BaseGVField ||
  2357. !NewAddrMode.HasBaseReg);
  2358. // Even if NewAddMode is the same we still need to collect it due to
  2359. // original value is different. And later we will need all original values
  2360. // as anchors during finding the common Phi node.
  2361. if (CanHandle)
  2362. AddrModes.emplace_back(NewAddrMode);
  2363. else
  2364. AddrModes.clear();
  2365. return CanHandle;
  2366. }
  2367. /// \brief Combine the addressing modes we've collected into a single
  2368. /// addressing mode.
  2369. /// \return True iff we successfully combined them or we only had one so
  2370. /// didn't need to combine them anyway.
  2371. bool combineAddrModes() {
  2372. // If we have no AddrModes then they can't be combined.
  2373. if (AddrModes.size() == 0)
  2374. return false;
  2375. // A single AddrMode can trivially be combined.
  2376. if (AddrModes.size() == 1 || DifferentField == ExtAddrMode::NoField)
  2377. return true;
  2378. // If the AddrModes we collected are all just equal to the value they are
  2379. // derived from then combining them wouldn't do anything useful.
  2380. if (AllAddrModesTrivial)
  2381. return false;
  2382. if (!addrModeCombiningAllowed())
  2383. return false;
  2384. // Build a map between <original value, basic block where we saw it> to
  2385. // value of base register.
  2386. // Bail out if there is no common type.
  2387. FoldAddrToValueMapping Map;
  2388. if (!initializeMap(Map))
  2389. return false;
  2390. Value *CommonValue = findCommon(Map);
  2391. if (CommonValue)
  2392. AddrModes[0].SetCombinedField(DifferentField, CommonValue, AddrModes);
  2393. return CommonValue != nullptr;
  2394. }
  2395. private:
  2396. /// \brief Initialize Map with anchor values. For address seen in some BB
  2397. /// we set the value of different field saw in this address.
  2398. /// If address is not an instruction than basic block is set to null.
  2399. /// At the same time we find a common type for different field we will
  2400. /// use to create new Phi/Select nodes. Keep it in CommonType field.
  2401. /// Return false if there is no common type found.
  2402. bool initializeMap(FoldAddrToValueMapping &Map) {
  2403. // Keep track of keys where the value is null. We will need to replace it
  2404. // with constant null when we know the common type.
  2405. SmallVector<ValueInBB, 2> NullValue;
  2406. Type *IntPtrTy = SQ.DL.getIntPtrType(AddrModes[0].OriginalValue->getType());
  2407. for (auto &AM : AddrModes) {
  2408. BasicBlock *BB = nullptr;
  2409. if (Instruction *I = dyn_cast<Instruction>(AM.OriginalValue))
  2410. BB = I->getParent();
  2411. Value *DV = AM.GetFieldAsValue(DifferentField, IntPtrTy);
  2412. if (DV) {
  2413. auto *Type = DV->getType();
  2414. if (CommonType && CommonType != Type)
  2415. return false;
  2416. CommonType = Type;
  2417. Map[{ AM.OriginalValue, BB }] = DV;
  2418. } else {
  2419. NullValue.push_back({ AM.OriginalValue, BB });
  2420. }
  2421. }
  2422. assert(CommonType && "At least one non-null value must be!");
  2423. for (auto VIBB : NullValue)
  2424. Map[VIBB] = Constant::getNullValue(CommonType);
  2425. return true;
  2426. }
  2427. /// \brief We have mapping between value A and basic block where value A
  2428. /// seen to other value B where B was a field in addressing mode represented
  2429. /// by A. Also we have an original value C representin an address in some
  2430. /// basic block. Traversing from C through phi and selects we ended up with
  2431. /// A's in a map. This utility function tries to find a value V which is a
  2432. /// field in addressing mode C and traversing through phi nodes and selects
  2433. /// we will end up in corresponded values B in a map.
  2434. /// The utility will create a new Phi/Selects if needed.
  2435. // The simple example looks as follows:
  2436. // BB1:
  2437. // p1 = b1 + 40
  2438. // br cond BB2, BB3
  2439. // BB2:
  2440. // p2 = b2 + 40
  2441. // br BB3
  2442. // BB3:
  2443. // p = phi [p1, BB1], [p2, BB2]
  2444. // v = load p
  2445. // Map is
  2446. // <p1, BB1> -> b1
  2447. // <p2, BB2> -> b2
  2448. // Request is
  2449. // <p, BB3> -> ?
  2450. // The function tries to find or build phi [b1, BB1], [b2, BB2] in BB3
  2451. Value *findCommon(FoldAddrToValueMapping &Map) {
  2452. // Tracks the simplification of newly created phi nodes. The reason we use
  2453. // this mapping is because we will add new created Phi nodes in AddrToBase.
  2454. // Simplification of Phi nodes is recursive, so some Phi node may
  2455. // be simplified after we added it to AddrToBase.
  2456. // Using this mapping we can find the current value in AddrToBase.
  2457. SimplificationTracker ST(SQ);
  2458. // First step, DFS to create PHI nodes for all intermediate blocks.
  2459. // Also fill traverse order for the second step.
  2460. SmallVector<ValueInBB, 32> TraverseOrder;
  2461. InsertPlaceholders(Map, TraverseOrder, ST);
  2462. // Second Step, fill new nodes by merged values and simplify if possible.
  2463. FillPlaceholders(Map, TraverseOrder, ST);
  2464. if (!AddrSinkNewSelects && ST.countNewSelectNodes() > 0) {
  2465. ST.destroyNewNodes(CommonType);
  2466. return nullptr;
  2467. }
  2468. // Now we'd like to match New Phi nodes to existed ones.
  2469. unsigned PhiNotMatchedCount = 0;
  2470. if (!MatchPhiSet(ST, AddrSinkNewPhis, PhiNotMatchedCount)) {
  2471. ST.destroyNewNodes(CommonType);
  2472. return nullptr;
  2473. }
  2474. auto *Result = ST.Get(Map.find(Original)->second);
  2475. if (Result) {
  2476. NumMemoryInstsPhiCreated += ST.countNewPhiNodes() + PhiNotMatchedCount;
  2477. NumMemoryInstsSelectCreated += ST.countNewSelectNodes();
  2478. }
  2479. return Result;
  2480. }
  2481. /// \brief Try to match PHI node to Candidate.
  2482. /// Matcher tracks the matched Phi nodes.
  2483. bool MatchPhiNode(PHINode *PHI, PHINode *Candidate,
  2484. SmallSetVector<PHIPair, 8> &Matcher,
  2485. SmallSetVector<PHINode *, 32> &PhiNodesToMatch) {
  2486. SmallVector<PHIPair, 8> WorkList;
  2487. Matcher.insert({ PHI, Candidate });
  2488. WorkList.push_back({ PHI, Candidate });
  2489. SmallSet<PHIPair, 8> Visited;
  2490. while (!WorkList.empty()) {
  2491. auto Item = WorkList.pop_back_val();
  2492. if (!Visited.insert(Item).second)
  2493. continue;
  2494. // We iterate over all incoming values to Phi to compare them.
  2495. // If values are different and both of them Phi and the first one is a
  2496. // Phi we added (subject to match) and both of them is in the same basic
  2497. // block then we can match our pair if values match. So we state that
  2498. // these values match and add it to work list to verify that.
  2499. for (auto B : Item.first->blocks()) {
  2500. Value *FirstValue = Item.first->getIncomingValueForBlock(B);
  2501. Value *SecondValue = Item.second->getIncomingValueForBlock(B);
  2502. if (FirstValue == SecondValue)
  2503. continue;
  2504. PHINode *FirstPhi = dyn_cast<PHINode>(FirstValue);
  2505. PHINode *SecondPhi = dyn_cast<PHINode>(SecondValue);
  2506. // One of them is not Phi or
  2507. // The first one is not Phi node from the set we'd like to match or
  2508. // Phi nodes from different basic blocks then
  2509. // we will not be able to match.
  2510. if (!FirstPhi || !SecondPhi || !PhiNodesToMatch.count(FirstPhi) ||
  2511. FirstPhi->getParent() != SecondPhi->getParent())
  2512. return false;
  2513. // If we already matched them then continue.
  2514. if (Matcher.count({ FirstPhi, SecondPhi }))
  2515. continue;
  2516. // So the values are different and does not match. So we need them to
  2517. // match.
  2518. Matcher.insert({ FirstPhi, SecondPhi });
  2519. // But me must check it.
  2520. WorkList.push_back({ FirstPhi, SecondPhi });
  2521. }
  2522. }
  2523. return true;
  2524. }
  2525. /// \brief For the given set of PHI nodes (in the SimplificationTracker) try
  2526. /// to find their equivalents.
  2527. /// Returns false if this matching fails and creation of new Phi is disabled.
  2528. bool MatchPhiSet(SimplificationTracker &ST, bool AllowNewPhiNodes,
  2529. unsigned &PhiNotMatchedCount) {
  2530. // Use a SetVector for Matched to make sure we do replacements (ReplacePhi)
  2531. // in a deterministic order below.
  2532. SmallSetVector<PHIPair, 8> Matched;
  2533. SmallPtrSet<PHINode *, 8> WillNotMatch;
  2534. SmallSetVector<PHINode *, 32> &PhiNodesToMatch = ST.newPhiNodes();
  2535. while (PhiNodesToMatch.size()) {
  2536. PHINode *PHI = *PhiNodesToMatch.begin();
  2537. // Add us, if no Phi nodes in the basic block we do not match.
  2538. WillNotMatch.clear();
  2539. WillNotMatch.insert(PHI);
  2540. // Traverse all Phis until we found equivalent or fail to do that.
  2541. bool IsMatched = false;
  2542. for (auto &P : PHI->getParent()->phis()) {
  2543. if (&P == PHI)
  2544. continue;
  2545. if ((IsMatched = MatchPhiNode(PHI, &P, Matched, PhiNodesToMatch)))
  2546. break;
  2547. // If it does not match, collect all Phi nodes from matcher.
  2548. // if we end up with no match, them all these Phi nodes will not match
  2549. // later.
  2550. for (auto M : Matched)
  2551. WillNotMatch.insert(M.first);
  2552. Matched.clear();
  2553. }
  2554. if (IsMatched) {
  2555. // Replace all matched values and erase them.
  2556. for (auto MV : Matched)
  2557. ST.ReplacePhi(MV.first, MV.second);
  2558. Matched.clear();
  2559. continue;
  2560. }
  2561. // If we are not allowed to create new nodes then bail out.
  2562. if (!AllowNewPhiNodes)
  2563. return false;
  2564. // Just remove all seen values in matcher. They will not match anything.
  2565. PhiNotMatchedCount += WillNotMatch.size();
  2566. for (auto *P : WillNotMatch)
  2567. PhiNodesToMatch.remove(P);
  2568. }
  2569. return true;
  2570. }
  2571. /// \brief Fill the placeholder with values from predecessors and simplify it.
  2572. void FillPlaceholders(FoldAddrToValueMapping &Map,
  2573. SmallVectorImpl<ValueInBB> &TraverseOrder,
  2574. SimplificationTracker &ST) {
  2575. while (!TraverseOrder.empty()) {
  2576. auto Current = TraverseOrder.pop_back_val();
  2577. assert(Map.find(Current) != Map.end() && "No node to fill!!!");
  2578. Value *CurrentValue = Current.first;
  2579. BasicBlock *CurrentBlock = Current.second;
  2580. Value *V = Map[Current];
  2581. if (SelectInst *Select = dyn_cast<SelectInst>(V)) {
  2582. // CurrentValue also must be Select.
  2583. auto *CurrentSelect = cast<SelectInst>(CurrentValue);
  2584. auto *TrueValue = CurrentSelect->getTrueValue();
  2585. ValueInBB TrueItem = { TrueValue, isa<Instruction>(TrueValue)
  2586. ? CurrentBlock
  2587. : nullptr };
  2588. assert(Map.find(TrueItem) != Map.end() && "No True Value!");
  2589. Select->setTrueValue(ST.Get(Map[TrueItem]));
  2590. auto *FalseValue = CurrentSelect->getFalseValue();
  2591. ValueInBB FalseItem = { FalseValue, isa<Instruction>(FalseValue)
  2592. ? CurrentBlock
  2593. : nullptr };
  2594. assert(Map.find(FalseItem) != Map.end() && "No False Value!");
  2595. Select->setFalseValue(ST.Get(Map[FalseItem]));
  2596. } else {
  2597. // Must be a Phi node then.
  2598. PHINode *PHI = cast<PHINode>(V);
  2599. // Fill the Phi node with values from predecessors.
  2600. bool IsDefinedInThisBB =
  2601. cast<Instruction>(CurrentValue)->getParent() == CurrentBlock;
  2602. auto *CurrentPhi = dyn_cast<PHINode>(CurrentValue);
  2603. for (auto B : predecessors(CurrentBlock)) {
  2604. Value *PV = IsDefinedInThisBB
  2605. ? CurrentPhi->getIncomingValueForBlock(B)
  2606. : CurrentValue;
  2607. ValueInBB item = { PV, isa<Instruction>(PV) ? B : nullptr };
  2608. assert(Map.find(item) != Map.end() && "No predecessor Value!");
  2609. PHI->addIncoming(ST.Get(Map[item]), B);
  2610. }
  2611. }
  2612. // Simplify if possible.
  2613. Map[Current] = ST.Simplify(V);
  2614. }
  2615. }
  2616. /// Starting from value recursively iterates over predecessors up to known
  2617. /// ending values represented in a map. For each traversed block inserts
  2618. /// a placeholder Phi or Select.
  2619. /// Reports all new created Phi/Select nodes by adding them to set.
  2620. /// Also reports and order in what basic blocks have been traversed.
  2621. void InsertPlaceholders(FoldAddrToValueMapping &Map,
  2622. SmallVectorImpl<ValueInBB> &TraverseOrder,
  2623. SimplificationTracker &ST) {
  2624. SmallVector<ValueInBB, 32> Worklist;
  2625. assert((isa<PHINode>(Original.first) || isa<SelectInst>(Original.first)) &&
  2626. "Address must be a Phi or Select node");
  2627. auto *Dummy = UndefValue::get(CommonType);
  2628. Worklist.push_back(Original);
  2629. while (!Worklist.empty()) {
  2630. auto Current = Worklist.pop_back_val();
  2631. // If value is not an instruction it is something global, constant,
  2632. // parameter and we can say that this value is observable in any block.
  2633. // Set block to null to denote it.
  2634. // Also please take into account that it is how we build anchors.
  2635. if (!isa<Instruction>(Current.first))
  2636. Current.second = nullptr;
  2637. // if it is already visited or it is an ending value then skip it.
  2638. if (Map.find(Current) != Map.end())
  2639. continue;
  2640. TraverseOrder.push_back(Current);
  2641. Value *CurrentValue = Current.first;
  2642. BasicBlock *CurrentBlock = Current.second;
  2643. // CurrentValue must be a Phi node or select. All others must be covered
  2644. // by anchors.
  2645. Instruction *CurrentI = cast<Instruction>(CurrentValue);
  2646. bool IsDefinedInThisBB = CurrentI->getParent() == CurrentBlock;
  2647. unsigned PredCount =
  2648. std::distance(pred_begin(CurrentBlock), pred_end(CurrentBlock));
  2649. // if Current Value is not defined in this basic block we are interested
  2650. // in values in predecessors.
  2651. if (!IsDefinedInThisBB) {
  2652. assert(PredCount && "Unreachable block?!");
  2653. PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
  2654. &CurrentBlock->front());
  2655. Map[Current] = PHI;
  2656. ST.insertNewPhi(PHI);
  2657. // Add all predecessors in work list.
  2658. for (auto B : predecessors(CurrentBlock))
  2659. Worklist.push_back({ CurrentValue, B });
  2660. continue;
  2661. }
  2662. // Value is defined in this basic block.
  2663. if (SelectInst *OrigSelect = dyn_cast<SelectInst>(CurrentI)) {
  2664. // Is it OK to get metadata from OrigSelect?!
  2665. // Create a Select placeholder with dummy value.
  2666. SelectInst *Select =
  2667. SelectInst::Create(OrigSelect->getCondition(), Dummy, Dummy,
  2668. OrigSelect->getName(), OrigSelect, OrigSelect);
  2669. Map[Current] = Select;
  2670. ST.insertNewSelect(Select);
  2671. // We are interested in True and False value in this basic block.
  2672. Worklist.push_back({ OrigSelect->getTrueValue(), CurrentBlock });
  2673. Worklist.push_back({ OrigSelect->getFalseValue(), CurrentBlock });
  2674. } else {
  2675. // It must be a Phi node then.
  2676. auto *CurrentPhi = cast<PHINode>(CurrentI);
  2677. // Create new Phi node for merge of bases.
  2678. assert(PredCount && "Unreachable block?!");
  2679. PHINode *PHI = PHINode::Create(CommonType, PredCount, "sunk_phi",
  2680. &CurrentBlock->front());
  2681. Map[Current] = PHI;
  2682. ST.insertNewPhi(PHI);
  2683. // Add all predecessors in work list.
  2684. for (auto B : predecessors(CurrentBlock))
  2685. Worklist.push_back({ CurrentPhi->getIncomingValueForBlock(B), B });
  2686. }
  2687. }
  2688. }
  2689. bool addrModeCombiningAllowed() {
  2690. if (DisableComplexAddrModes)
  2691. return false;
  2692. switch (DifferentField) {
  2693. default:
  2694. return false;
  2695. case ExtAddrMode::BaseRegField:
  2696. return AddrSinkCombineBaseReg;
  2697. case ExtAddrMode::BaseGVField:
  2698. return AddrSinkCombineBaseGV;
  2699. case ExtAddrMode::BaseOffsField:
  2700. return AddrSinkCombineBaseOffs;
  2701. case ExtAddrMode::ScaledRegField:
  2702. return AddrSinkCombineScaledReg;
  2703. }
  2704. }
  2705. };
  2706. } // end anonymous namespace
  2707. /// Try adding ScaleReg*Scale to the current addressing mode.
  2708. /// Return true and update AddrMode if this addr mode is legal for the target,
  2709. /// false if not.
  2710. bool AddressingModeMatcher::matchScaledValue(Value *ScaleReg, int64_t Scale,
  2711. unsigned Depth) {
  2712. // If Scale is 1, then this is the same as adding ScaleReg to the addressing
  2713. // mode. Just process that directly.
  2714. if (Scale == 1)
  2715. return matchAddr(ScaleReg, Depth);
  2716. // If the scale is 0, it takes nothing to add this.
  2717. if (Scale == 0)
  2718. return true;
  2719. // If we already have a scale of this value, we can add to it, otherwise, we
  2720. // need an available scale field.
  2721. if (AddrMode.Scale != 0 && AddrMode.ScaledReg != ScaleReg)
  2722. return false;
  2723. ExtAddrMode TestAddrMode = AddrMode;
  2724. // Add scale to turn X*4+X*3 -> X*7. This could also do things like
  2725. // [A+B + A*7] -> [B+A*8].
  2726. TestAddrMode.Scale += Scale;
  2727. TestAddrMode.ScaledReg = ScaleReg;
  2728. // If the new address isn't legal, bail out.
  2729. if (!TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace))
  2730. return false;
  2731. // It was legal, so commit it.
  2732. AddrMode = TestAddrMode;
  2733. // Okay, we decided that we can add ScaleReg+Scale to AddrMode. Check now
  2734. // to see if ScaleReg is actually X+C. If so, we can turn this into adding
  2735. // X*Scale + C*Scale to addr mode.
  2736. ConstantInt *CI = nullptr; Value *AddLHS = nullptr;
  2737. if (isa<Instruction>(ScaleReg) && // not a constant expr.
  2738. match(ScaleReg, m_Add(m_Value(AddLHS), m_ConstantInt(CI)))) {
  2739. TestAddrMode.ScaledReg = AddLHS;
  2740. TestAddrMode.BaseOffs += CI->getSExtValue()*TestAddrMode.Scale;
  2741. // If this addressing mode is legal, commit it and remember that we folded
  2742. // this instruction.
  2743. if (TLI.isLegalAddressingMode(DL, TestAddrMode, AccessTy, AddrSpace)) {
  2744. AddrModeInsts.push_back(cast<Instruction>(ScaleReg));
  2745. AddrMode = TestAddrMode;
  2746. return true;
  2747. }
  2748. }
  2749. // Otherwise, not (x+c)*scale, just return what we have.
  2750. return true;
  2751. }
  2752. /// This is a little filter, which returns true if an addressing computation
  2753. /// involving I might be folded into a load/store accessing it.
  2754. /// This doesn't need to be perfect, but needs to accept at least
  2755. /// the set of instructions that MatchOperationAddr can.
  2756. static bool MightBeFoldableInst(Instruction *I) {
  2757. switch (I->getOpcode()) {
  2758. case Instruction::BitCast:
  2759. case Instruction::AddrSpaceCast:
  2760. // Don't touch identity bitcasts.
  2761. if (I->getType() == I->getOperand(0)->getType())
  2762. return false;
  2763. return I->getType()->isPointerTy() || I->getType()->isIntegerTy();
  2764. case Instruction::PtrToInt:
  2765. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  2766. return true;
  2767. case Instruction::IntToPtr:
  2768. // We know the input is intptr_t, so this is foldable.
  2769. return true;
  2770. case Instruction::Add:
  2771. return true;
  2772. case Instruction::Mul:
  2773. case Instruction::Shl:
  2774. // Can only handle X*C and X << C.
  2775. return isa<ConstantInt>(I->getOperand(1));
  2776. case Instruction::GetElementPtr:
  2777. return true;
  2778. default:
  2779. return false;
  2780. }
  2781. }
  2782. /// \brief Check whether or not \p Val is a legal instruction for \p TLI.
  2783. /// \note \p Val is assumed to be the product of some type promotion.
  2784. /// Therefore if \p Val has an undefined state in \p TLI, this is assumed
  2785. /// to be legal, as the non-promoted value would have had the same state.
  2786. static bool isPromotedInstructionLegal(const TargetLowering &TLI,
  2787. const DataLayout &DL, Value *Val) {
  2788. Instruction *PromotedInst = dyn_cast<Instruction>(Val);
  2789. if (!PromotedInst)
  2790. return false;
  2791. int ISDOpcode = TLI.InstructionOpcodeToISD(PromotedInst->getOpcode());
  2792. // If the ISDOpcode is undefined, it was undefined before the promotion.
  2793. if (!ISDOpcode)
  2794. return true;
  2795. // Otherwise, check if the promoted instruction is legal or not.
  2796. return TLI.isOperationLegalOrCustom(
  2797. ISDOpcode, TLI.getValueType(DL, PromotedInst->getType()));
  2798. }
  2799. namespace {
  2800. /// \brief Hepler class to perform type promotion.
  2801. class TypePromotionHelper {
  2802. /// \brief Utility function to check whether or not a sign or zero extension
  2803. /// of \p Inst with \p ConsideredExtType can be moved through \p Inst by
  2804. /// either using the operands of \p Inst or promoting \p Inst.
  2805. /// The type of the extension is defined by \p IsSExt.
  2806. /// In other words, check if:
  2807. /// ext (Ty Inst opnd1 opnd2 ... opndN) to ConsideredExtType.
  2808. /// #1 Promotion applies:
  2809. /// ConsideredExtType Inst (ext opnd1 to ConsideredExtType, ...).
  2810. /// #2 Operand reuses:
  2811. /// ext opnd1 to ConsideredExtType.
  2812. /// \p PromotedInsts maps the instructions to their type before promotion.
  2813. static bool canGetThrough(const Instruction *Inst, Type *ConsideredExtType,
  2814. const InstrToOrigTy &PromotedInsts, bool IsSExt);
  2815. /// \brief Utility function to determine if \p OpIdx should be promoted when
  2816. /// promoting \p Inst.
  2817. static bool shouldExtOperand(const Instruction *Inst, int OpIdx) {
  2818. return !(isa<SelectInst>(Inst) && OpIdx == 0);
  2819. }
  2820. /// \brief Utility function to promote the operand of \p Ext when this
  2821. /// operand is a promotable trunc or sext or zext.
  2822. /// \p PromotedInsts maps the instructions to their type before promotion.
  2823. /// \p CreatedInstsCost[out] contains the cost of all instructions
  2824. /// created to promote the operand of Ext.
  2825. /// Newly added extensions are inserted in \p Exts.
  2826. /// Newly added truncates are inserted in \p Truncs.
  2827. /// Should never be called directly.
  2828. /// \return The promoted value which is used instead of Ext.
  2829. static Value *promoteOperandForTruncAndAnyExt(
  2830. Instruction *Ext, TypePromotionTransaction &TPT,
  2831. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2832. SmallVectorImpl<Instruction *> *Exts,
  2833. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI);
  2834. /// \brief Utility function to promote the operand of \p Ext when this
  2835. /// operand is promotable and is not a supported trunc or sext.
  2836. /// \p PromotedInsts maps the instructions to their type before promotion.
  2837. /// \p CreatedInstsCost[out] contains the cost of all the instructions
  2838. /// created to promote the operand of Ext.
  2839. /// Newly added extensions are inserted in \p Exts.
  2840. /// Newly added truncates are inserted in \p Truncs.
  2841. /// Should never be called directly.
  2842. /// \return The promoted value which is used instead of Ext.
  2843. static Value *promoteOperandForOther(Instruction *Ext,
  2844. TypePromotionTransaction &TPT,
  2845. InstrToOrigTy &PromotedInsts,
  2846. unsigned &CreatedInstsCost,
  2847. SmallVectorImpl<Instruction *> *Exts,
  2848. SmallVectorImpl<Instruction *> *Truncs,
  2849. const TargetLowering &TLI, bool IsSExt);
  2850. /// \see promoteOperandForOther.
  2851. static Value *signExtendOperandForOther(
  2852. Instruction *Ext, TypePromotionTransaction &TPT,
  2853. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2854. SmallVectorImpl<Instruction *> *Exts,
  2855. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2856. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2857. Exts, Truncs, TLI, true);
  2858. }
  2859. /// \see promoteOperandForOther.
  2860. static Value *zeroExtendOperandForOther(
  2861. Instruction *Ext, TypePromotionTransaction &TPT,
  2862. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2863. SmallVectorImpl<Instruction *> *Exts,
  2864. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2865. return promoteOperandForOther(Ext, TPT, PromotedInsts, CreatedInstsCost,
  2866. Exts, Truncs, TLI, false);
  2867. }
  2868. public:
  2869. /// Type for the utility function that promotes the operand of Ext.
  2870. using Action = Value *(*)(Instruction *Ext, TypePromotionTransaction &TPT,
  2871. InstrToOrigTy &PromotedInsts,
  2872. unsigned &CreatedInstsCost,
  2873. SmallVectorImpl<Instruction *> *Exts,
  2874. SmallVectorImpl<Instruction *> *Truncs,
  2875. const TargetLowering &TLI);
  2876. /// \brief Given a sign/zero extend instruction \p Ext, return the approriate
  2877. /// action to promote the operand of \p Ext instead of using Ext.
  2878. /// \return NULL if no promotable action is possible with the current
  2879. /// sign extension.
  2880. /// \p InsertedInsts keeps track of all the instructions inserted by the
  2881. /// other CodeGenPrepare optimizations. This information is important
  2882. /// because we do not want to promote these instructions as CodeGenPrepare
  2883. /// will reinsert them later. Thus creating an infinite loop: create/remove.
  2884. /// \p PromotedInsts maps the instructions to their type before promotion.
  2885. static Action getAction(Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2886. const TargetLowering &TLI,
  2887. const InstrToOrigTy &PromotedInsts);
  2888. };
  2889. } // end anonymous namespace
  2890. bool TypePromotionHelper::canGetThrough(const Instruction *Inst,
  2891. Type *ConsideredExtType,
  2892. const InstrToOrigTy &PromotedInsts,
  2893. bool IsSExt) {
  2894. // The promotion helper does not know how to deal with vector types yet.
  2895. // To be able to fix that, we would need to fix the places where we
  2896. // statically extend, e.g., constants and such.
  2897. if (Inst->getType()->isVectorTy())
  2898. return false;
  2899. // We can always get through zext.
  2900. if (isa<ZExtInst>(Inst))
  2901. return true;
  2902. // sext(sext) is ok too.
  2903. if (IsSExt && isa<SExtInst>(Inst))
  2904. return true;
  2905. // We can get through binary operator, if it is legal. In other words, the
  2906. // binary operator must have a nuw or nsw flag.
  2907. const BinaryOperator *BinOp = dyn_cast<BinaryOperator>(Inst);
  2908. if (BinOp && isa<OverflowingBinaryOperator>(BinOp) &&
  2909. ((!IsSExt && BinOp->hasNoUnsignedWrap()) ||
  2910. (IsSExt && BinOp->hasNoSignedWrap())))
  2911. return true;
  2912. // Check if we can do the following simplification.
  2913. // ext(trunc(opnd)) --> ext(opnd)
  2914. if (!isa<TruncInst>(Inst))
  2915. return false;
  2916. Value *OpndVal = Inst->getOperand(0);
  2917. // Check if we can use this operand in the extension.
  2918. // If the type is larger than the result type of the extension, we cannot.
  2919. if (!OpndVal->getType()->isIntegerTy() ||
  2920. OpndVal->getType()->getIntegerBitWidth() >
  2921. ConsideredExtType->getIntegerBitWidth())
  2922. return false;
  2923. // If the operand of the truncate is not an instruction, we will not have
  2924. // any information on the dropped bits.
  2925. // (Actually we could for constant but it is not worth the extra logic).
  2926. Instruction *Opnd = dyn_cast<Instruction>(OpndVal);
  2927. if (!Opnd)
  2928. return false;
  2929. // Check if the source of the type is narrow enough.
  2930. // I.e., check that trunc just drops extended bits of the same kind of
  2931. // the extension.
  2932. // #1 get the type of the operand and check the kind of the extended bits.
  2933. const Type *OpndType;
  2934. InstrToOrigTy::const_iterator It = PromotedInsts.find(Opnd);
  2935. if (It != PromotedInsts.end() && It->second.getInt() == IsSExt)
  2936. OpndType = It->second.getPointer();
  2937. else if ((IsSExt && isa<SExtInst>(Opnd)) || (!IsSExt && isa<ZExtInst>(Opnd)))
  2938. OpndType = Opnd->getOperand(0)->getType();
  2939. else
  2940. return false;
  2941. // #2 check that the truncate just drops extended bits.
  2942. return Inst->getType()->getIntegerBitWidth() >=
  2943. OpndType->getIntegerBitWidth();
  2944. }
  2945. TypePromotionHelper::Action TypePromotionHelper::getAction(
  2946. Instruction *Ext, const SetOfInstrs &InsertedInsts,
  2947. const TargetLowering &TLI, const InstrToOrigTy &PromotedInsts) {
  2948. assert((isa<SExtInst>(Ext) || isa<ZExtInst>(Ext)) &&
  2949. "Unexpected instruction type");
  2950. Instruction *ExtOpnd = dyn_cast<Instruction>(Ext->getOperand(0));
  2951. Type *ExtTy = Ext->getType();
  2952. bool IsSExt = isa<SExtInst>(Ext);
  2953. // If the operand of the extension is not an instruction, we cannot
  2954. // get through.
  2955. // If it, check we can get through.
  2956. if (!ExtOpnd || !canGetThrough(ExtOpnd, ExtTy, PromotedInsts, IsSExt))
  2957. return nullptr;
  2958. // Do not promote if the operand has been added by codegenprepare.
  2959. // Otherwise, it means we are undoing an optimization that is likely to be
  2960. // redone, thus causing potential infinite loop.
  2961. if (isa<TruncInst>(ExtOpnd) && InsertedInsts.count(ExtOpnd))
  2962. return nullptr;
  2963. // SExt or Trunc instructions.
  2964. // Return the related handler.
  2965. if (isa<SExtInst>(ExtOpnd) || isa<TruncInst>(ExtOpnd) ||
  2966. isa<ZExtInst>(ExtOpnd))
  2967. return promoteOperandForTruncAndAnyExt;
  2968. // Regular instruction.
  2969. // Abort early if we will have to insert non-free instructions.
  2970. if (!ExtOpnd->hasOneUse() && !TLI.isTruncateFree(ExtTy, ExtOpnd->getType()))
  2971. return nullptr;
  2972. return IsSExt ? signExtendOperandForOther : zeroExtendOperandForOther;
  2973. }
  2974. Value *TypePromotionHelper::promoteOperandForTruncAndAnyExt(
  2975. Instruction *SExt, TypePromotionTransaction &TPT,
  2976. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  2977. SmallVectorImpl<Instruction *> *Exts,
  2978. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI) {
  2979. // By construction, the operand of SExt is an instruction. Otherwise we cannot
  2980. // get through it and this method should not be called.
  2981. Instruction *SExtOpnd = cast<Instruction>(SExt->getOperand(0));
  2982. Value *ExtVal = SExt;
  2983. bool HasMergedNonFreeExt = false;
  2984. if (isa<ZExtInst>(SExtOpnd)) {
  2985. // Replace s|zext(zext(opnd))
  2986. // => zext(opnd).
  2987. HasMergedNonFreeExt = !TLI.isExtFree(SExtOpnd);
  2988. Value *ZExt =
  2989. TPT.createZExt(SExt, SExtOpnd->getOperand(0), SExt->getType());
  2990. TPT.replaceAllUsesWith(SExt, ZExt);
  2991. TPT.eraseInstruction(SExt);
  2992. ExtVal = ZExt;
  2993. } else {
  2994. // Replace z|sext(trunc(opnd)) or sext(sext(opnd))
  2995. // => z|sext(opnd).
  2996. TPT.setOperand(SExt, 0, SExtOpnd->getOperand(0));
  2997. }
  2998. CreatedInstsCost = 0;
  2999. // Remove dead code.
  3000. if (SExtOpnd->use_empty())
  3001. TPT.eraseInstruction(SExtOpnd);
  3002. // Check if the extension is still needed.
  3003. Instruction *ExtInst = dyn_cast<Instruction>(ExtVal);
  3004. if (!ExtInst || ExtInst->getType() != ExtInst->getOperand(0)->getType()) {
  3005. if (ExtInst) {
  3006. if (Exts)
  3007. Exts->push_back(ExtInst);
  3008. CreatedInstsCost = !TLI.isExtFree(ExtInst) && !HasMergedNonFreeExt;
  3009. }
  3010. return ExtVal;
  3011. }
  3012. // At this point we have: ext ty opnd to ty.
  3013. // Reassign the uses of ExtInst to the opnd and remove ExtInst.
  3014. Value *NextVal = ExtInst->getOperand(0);
  3015. TPT.eraseInstruction(ExtInst, NextVal);
  3016. return NextVal;
  3017. }
  3018. Value *TypePromotionHelper::promoteOperandForOther(
  3019. Instruction *Ext, TypePromotionTransaction &TPT,
  3020. InstrToOrigTy &PromotedInsts, unsigned &CreatedInstsCost,
  3021. SmallVectorImpl<Instruction *> *Exts,
  3022. SmallVectorImpl<Instruction *> *Truncs, const TargetLowering &TLI,
  3023. bool IsSExt) {
  3024. // By construction, the operand of Ext is an instruction. Otherwise we cannot
  3025. // get through it and this method should not be called.
  3026. Instruction *ExtOpnd = cast<Instruction>(Ext->getOperand(0));
  3027. CreatedInstsCost = 0;
  3028. if (!ExtOpnd->hasOneUse()) {
  3029. // ExtOpnd will be promoted.
  3030. // All its uses, but Ext, will need to use a truncated value of the
  3031. // promoted version.
  3032. // Create the truncate now.
  3033. Value *Trunc = TPT.createTrunc(Ext, ExtOpnd->getType());
  3034. if (Instruction *ITrunc = dyn_cast<Instruction>(Trunc)) {
  3035. // Insert it just after the definition.
  3036. ITrunc->moveAfter(ExtOpnd);
  3037. if (Truncs)
  3038. Truncs->push_back(ITrunc);
  3039. }
  3040. TPT.replaceAllUsesWith(ExtOpnd, Trunc);
  3041. // Restore the operand of Ext (which has been replaced by the previous call
  3042. // to replaceAllUsesWith) to avoid creating a cycle trunc <-> sext.
  3043. TPT.setOperand(Ext, 0, ExtOpnd);
  3044. }
  3045. // Get through the Instruction:
  3046. // 1. Update its type.
  3047. // 2. Replace the uses of Ext by Inst.
  3048. // 3. Extend each operand that needs to be extended.
  3049. // Remember the original type of the instruction before promotion.
  3050. // This is useful to know that the high bits are sign extended bits.
  3051. PromotedInsts.insert(std::pair<Instruction *, TypeIsSExt>(
  3052. ExtOpnd, TypeIsSExt(ExtOpnd->getType(), IsSExt)));
  3053. // Step #1.
  3054. TPT.mutateType(ExtOpnd, Ext->getType());
  3055. // Step #2.
  3056. TPT.replaceAllUsesWith(Ext, ExtOpnd);
  3057. // Step #3.
  3058. Instruction *ExtForOpnd = Ext;
  3059. DEBUG(dbgs() << "Propagate Ext to operands\n");
  3060. for (int OpIdx = 0, EndOpIdx = ExtOpnd->getNumOperands(); OpIdx != EndOpIdx;
  3061. ++OpIdx) {
  3062. DEBUG(dbgs() << "Operand:\n" << *(ExtOpnd->getOperand(OpIdx)) << '\n');
  3063. if (ExtOpnd->getOperand(OpIdx)->getType() == Ext->getType() ||
  3064. !shouldExtOperand(ExtOpnd, OpIdx)) {
  3065. DEBUG(dbgs() << "No need to propagate\n");
  3066. continue;
  3067. }
  3068. // Check if we can statically extend the operand.
  3069. Value *Opnd = ExtOpnd->getOperand(OpIdx);
  3070. if (const ConstantInt *Cst = dyn_cast<ConstantInt>(Opnd)) {
  3071. DEBUG(dbgs() << "Statically extend\n");
  3072. unsigned BitWidth = Ext->getType()->getIntegerBitWidth();
  3073. APInt CstVal = IsSExt ? Cst->getValue().sext(BitWidth)
  3074. : Cst->getValue().zext(BitWidth);
  3075. TPT.setOperand(ExtOpnd, OpIdx, ConstantInt::get(Ext->getType(), CstVal));
  3076. continue;
  3077. }
  3078. // UndefValue are typed, so we have to statically sign extend them.
  3079. if (isa<UndefValue>(Opnd)) {
  3080. DEBUG(dbgs() << "Statically extend\n");
  3081. TPT.setOperand(ExtOpnd, OpIdx, UndefValue::get(Ext->getType()));
  3082. continue;
  3083. }
  3084. // Otherwise we have to explicity sign extend the operand.
  3085. // Check if Ext was reused to extend an operand.
  3086. if (!ExtForOpnd) {
  3087. // If yes, create a new one.
  3088. DEBUG(dbgs() << "More operands to ext\n");
  3089. Value *ValForExtOpnd = IsSExt ? TPT.createSExt(Ext, Opnd, Ext->getType())
  3090. : TPT.createZExt(Ext, Opnd, Ext->getType());
  3091. if (!isa<Instruction>(ValForExtOpnd)) {
  3092. TPT.setOperand(ExtOpnd, OpIdx, ValForExtOpnd);
  3093. continue;
  3094. }
  3095. ExtForOpnd = cast<Instruction>(ValForExtOpnd);
  3096. }
  3097. if (Exts)
  3098. Exts->push_back(ExtForOpnd);
  3099. TPT.setOperand(ExtForOpnd, 0, Opnd);
  3100. // Move the sign extension before the insertion point.
  3101. TPT.moveBefore(ExtForOpnd, ExtOpnd);
  3102. TPT.setOperand(ExtOpnd, OpIdx, ExtForOpnd);
  3103. CreatedInstsCost += !TLI.isExtFree(ExtForOpnd);
  3104. // If more sext are required, new instructions will have to be created.
  3105. ExtForOpnd = nullptr;
  3106. }
  3107. if (ExtForOpnd == Ext) {
  3108. DEBUG(dbgs() << "Extension is useless now\n");
  3109. TPT.eraseInstruction(Ext);
  3110. }
  3111. return ExtOpnd;
  3112. }
  3113. /// Check whether or not promoting an instruction to a wider type is profitable.
  3114. /// \p NewCost gives the cost of extension instructions created by the
  3115. /// promotion.
  3116. /// \p OldCost gives the cost of extension instructions before the promotion
  3117. /// plus the number of instructions that have been
  3118. /// matched in the addressing mode the promotion.
  3119. /// \p PromotedOperand is the value that has been promoted.
  3120. /// \return True if the promotion is profitable, false otherwise.
  3121. bool AddressingModeMatcher::isPromotionProfitable(
  3122. unsigned NewCost, unsigned OldCost, Value *PromotedOperand) const {
  3123. DEBUG(dbgs() << "OldCost: " << OldCost << "\tNewCost: " << NewCost << '\n');
  3124. // The cost of the new extensions is greater than the cost of the
  3125. // old extension plus what we folded.
  3126. // This is not profitable.
  3127. if (NewCost > OldCost)
  3128. return false;
  3129. if (NewCost < OldCost)
  3130. return true;
  3131. // The promotion is neutral but it may help folding the sign extension in
  3132. // loads for instance.
  3133. // Check that we did not create an illegal instruction.
  3134. return isPromotedInstructionLegal(TLI, DL, PromotedOperand);
  3135. }
  3136. /// Given an instruction or constant expr, see if we can fold the operation
  3137. /// into the addressing mode. If so, update the addressing mode and return
  3138. /// true, otherwise return false without modifying AddrMode.
  3139. /// If \p MovedAway is not NULL, it contains the information of whether or
  3140. /// not AddrInst has to be folded into the addressing mode on success.
  3141. /// If \p MovedAway == true, \p AddrInst will not be part of the addressing
  3142. /// because it has been moved away.
  3143. /// Thus AddrInst must not be added in the matched instructions.
  3144. /// This state can happen when AddrInst is a sext, since it may be moved away.
  3145. /// Therefore, AddrInst may not be valid when MovedAway is true and it must
  3146. /// not be referenced anymore.
  3147. bool AddressingModeMatcher::matchOperationAddr(User *AddrInst, unsigned Opcode,
  3148. unsigned Depth,
  3149. bool *MovedAway) {
  3150. // Avoid exponential behavior on extremely deep expression trees.
  3151. if (Depth >= 5) return false;
  3152. // By default, all matched instructions stay in place.
  3153. if (MovedAway)
  3154. *MovedAway = false;
  3155. switch (Opcode) {
  3156. case Instruction::PtrToInt:
  3157. // PtrToInt is always a noop, as we know that the int type is pointer sized.
  3158. return matchAddr(AddrInst->getOperand(0), Depth);
  3159. case Instruction::IntToPtr: {
  3160. auto AS = AddrInst->getType()->getPointerAddressSpace();
  3161. auto PtrTy = MVT::getIntegerVT(DL.getPointerSizeInBits(AS));
  3162. // This inttoptr is a no-op if the integer type is pointer sized.
  3163. if (TLI.getValueType(DL, AddrInst->getOperand(0)->getType()) == PtrTy)
  3164. return matchAddr(AddrInst->getOperand(0), Depth);
  3165. return false;
  3166. }
  3167. case Instruction::BitCast:
  3168. // BitCast is always a noop, and we can handle it as long as it is
  3169. // int->int or pointer->pointer (we don't want int<->fp or something).
  3170. if ((AddrInst->getOperand(0)->getType()->isPointerTy() ||
  3171. AddrInst->getOperand(0)->getType()->isIntegerTy()) &&
  3172. // Don't touch identity bitcasts. These were probably put here by LSR,
  3173. // and we don't want to mess around with them. Assume it knows what it
  3174. // is doing.
  3175. AddrInst->getOperand(0)->getType() != AddrInst->getType())
  3176. return matchAddr(AddrInst->getOperand(0), Depth);
  3177. return false;
  3178. case Instruction::AddrSpaceCast: {
  3179. unsigned SrcAS
  3180. = AddrInst->getOperand(0)->getType()->getPointerAddressSpace();
  3181. unsigned DestAS = AddrInst->getType()->getPointerAddressSpace();
  3182. if (TLI.isNoopAddrSpaceCast(SrcAS, DestAS))
  3183. return matchAddr(AddrInst->getOperand(0), Depth);
  3184. return false;
  3185. }
  3186. case Instruction::Add: {
  3187. // Check to see if we can merge in the RHS then the LHS. If so, we win.
  3188. ExtAddrMode BackupAddrMode = AddrMode;
  3189. unsigned OldSize = AddrModeInsts.size();
  3190. // Start a transaction at this point.
  3191. // The LHS may match but not the RHS.
  3192. // Therefore, we need a higher level restoration point to undo partially
  3193. // matched operation.
  3194. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3195. TPT.getRestorationPoint();
  3196. if (matchAddr(AddrInst->getOperand(1), Depth+1) &&
  3197. matchAddr(AddrInst->getOperand(0), Depth+1))
  3198. return true;
  3199. // Restore the old addr mode info.
  3200. AddrMode = BackupAddrMode;
  3201. AddrModeInsts.resize(OldSize);
  3202. TPT.rollback(LastKnownGood);
  3203. // Otherwise this was over-aggressive. Try merging in the LHS then the RHS.
  3204. if (matchAddr(AddrInst->getOperand(0), Depth+1) &&
  3205. matchAddr(AddrInst->getOperand(1), Depth+1))
  3206. return true;
  3207. // Otherwise we definitely can't merge the ADD in.
  3208. AddrMode = BackupAddrMode;
  3209. AddrModeInsts.resize(OldSize);
  3210. TPT.rollback(LastKnownGood);
  3211. break;
  3212. }
  3213. //case Instruction::Or:
  3214. // TODO: We can handle "Or Val, Imm" iff this OR is equivalent to an ADD.
  3215. //break;
  3216. case Instruction::Mul:
  3217. case Instruction::Shl: {
  3218. // Can only handle X*C and X << C.
  3219. ConstantInt *RHS = dyn_cast<ConstantInt>(AddrInst->getOperand(1));
  3220. if (!RHS || RHS->getBitWidth() > 64)
  3221. return false;
  3222. int64_t Scale = RHS->getSExtValue();
  3223. if (Opcode == Instruction::Shl)
  3224. Scale = 1LL << Scale;
  3225. return matchScaledValue(AddrInst->getOperand(0), Scale, Depth);
  3226. }
  3227. case Instruction::GetElementPtr: {
  3228. // Scan the GEP. We check it if it contains constant offsets and at most
  3229. // one variable offset.
  3230. int VariableOperand = -1;
  3231. unsigned VariableScale = 0;
  3232. int64_t ConstantOffset = 0;
  3233. gep_type_iterator GTI = gep_type_begin(AddrInst);
  3234. for (unsigned i = 1, e = AddrInst->getNumOperands(); i != e; ++i, ++GTI) {
  3235. if (StructType *STy = GTI.getStructTypeOrNull()) {
  3236. const StructLayout *SL = DL.getStructLayout(STy);
  3237. unsigned Idx =
  3238. cast<ConstantInt>(AddrInst->getOperand(i))->getZExtValue();
  3239. ConstantOffset += SL->getElementOffset(Idx);
  3240. } else {
  3241. uint64_t TypeSize = DL.getTypeAllocSize(GTI.getIndexedType());
  3242. if (ConstantInt *CI = dyn_cast<ConstantInt>(AddrInst->getOperand(i))) {
  3243. ConstantOffset += CI->getSExtValue() * TypeSize;
  3244. } else if (TypeSize) { // Scales of zero don't do anything.
  3245. // We only allow one variable index at the moment.
  3246. if (VariableOperand != -1)
  3247. return false;
  3248. // Remember the variable index.
  3249. VariableOperand = i;
  3250. VariableScale = TypeSize;
  3251. }
  3252. }
  3253. }
  3254. // A common case is for the GEP to only do a constant offset. In this case,
  3255. // just add it to the disp field and check validity.
  3256. if (VariableOperand == -1) {
  3257. AddrMode.BaseOffs += ConstantOffset;
  3258. if (ConstantOffset == 0 ||
  3259. TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace)) {
  3260. // Check to see if we can fold the base pointer in too.
  3261. if (matchAddr(AddrInst->getOperand(0), Depth+1))
  3262. return true;
  3263. }
  3264. AddrMode.BaseOffs -= ConstantOffset;
  3265. return false;
  3266. }
  3267. // Save the valid addressing mode in case we can't match.
  3268. ExtAddrMode BackupAddrMode = AddrMode;
  3269. unsigned OldSize = AddrModeInsts.size();
  3270. // See if the scale and offset amount is valid for this target.
  3271. AddrMode.BaseOffs += ConstantOffset;
  3272. // Match the base operand of the GEP.
  3273. if (!matchAddr(AddrInst->getOperand(0), Depth+1)) {
  3274. // If it couldn't be matched, just stuff the value in a register.
  3275. if (AddrMode.HasBaseReg) {
  3276. AddrMode = BackupAddrMode;
  3277. AddrModeInsts.resize(OldSize);
  3278. return false;
  3279. }
  3280. AddrMode.HasBaseReg = true;
  3281. AddrMode.BaseReg = AddrInst->getOperand(0);
  3282. }
  3283. // Match the remaining variable portion of the GEP.
  3284. if (!matchScaledValue(AddrInst->getOperand(VariableOperand), VariableScale,
  3285. Depth)) {
  3286. // If it couldn't be matched, try stuffing the base into a register
  3287. // instead of matching it, and retrying the match of the scale.
  3288. AddrMode = BackupAddrMode;
  3289. AddrModeInsts.resize(OldSize);
  3290. if (AddrMode.HasBaseReg)
  3291. return false;
  3292. AddrMode.HasBaseReg = true;
  3293. AddrMode.BaseReg = AddrInst->getOperand(0);
  3294. AddrMode.BaseOffs += ConstantOffset;
  3295. if (!matchScaledValue(AddrInst->getOperand(VariableOperand),
  3296. VariableScale, Depth)) {
  3297. // If even that didn't work, bail.
  3298. AddrMode = BackupAddrMode;
  3299. AddrModeInsts.resize(OldSize);
  3300. return false;
  3301. }
  3302. }
  3303. return true;
  3304. }
  3305. case Instruction::SExt:
  3306. case Instruction::ZExt: {
  3307. Instruction *Ext = dyn_cast<Instruction>(AddrInst);
  3308. if (!Ext)
  3309. return false;
  3310. // Try to move this ext out of the way of the addressing mode.
  3311. // Ask for a method for doing so.
  3312. TypePromotionHelper::Action TPH =
  3313. TypePromotionHelper::getAction(Ext, InsertedInsts, TLI, PromotedInsts);
  3314. if (!TPH)
  3315. return false;
  3316. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3317. TPT.getRestorationPoint();
  3318. unsigned CreatedInstsCost = 0;
  3319. unsigned ExtCost = !TLI.isExtFree(Ext);
  3320. Value *PromotedOperand =
  3321. TPH(Ext, TPT, PromotedInsts, CreatedInstsCost, nullptr, nullptr, TLI);
  3322. // SExt has been moved away.
  3323. // Thus either it will be rematched later in the recursive calls or it is
  3324. // gone. Anyway, we must not fold it into the addressing mode at this point.
  3325. // E.g.,
  3326. // op = add opnd, 1
  3327. // idx = ext op
  3328. // addr = gep base, idx
  3329. // is now:
  3330. // promotedOpnd = ext opnd <- no match here
  3331. // op = promoted_add promotedOpnd, 1 <- match (later in recursive calls)
  3332. // addr = gep base, op <- match
  3333. if (MovedAway)
  3334. *MovedAway = true;
  3335. assert(PromotedOperand &&
  3336. "TypePromotionHelper should have filtered out those cases");
  3337. ExtAddrMode BackupAddrMode = AddrMode;
  3338. unsigned OldSize = AddrModeInsts.size();
  3339. if (!matchAddr(PromotedOperand, Depth) ||
  3340. // The total of the new cost is equal to the cost of the created
  3341. // instructions.
  3342. // The total of the old cost is equal to the cost of the extension plus
  3343. // what we have saved in the addressing mode.
  3344. !isPromotionProfitable(CreatedInstsCost,
  3345. ExtCost + (AddrModeInsts.size() - OldSize),
  3346. PromotedOperand)) {
  3347. AddrMode = BackupAddrMode;
  3348. AddrModeInsts.resize(OldSize);
  3349. DEBUG(dbgs() << "Sign extension does not pay off: rollback\n");
  3350. TPT.rollback(LastKnownGood);
  3351. return false;
  3352. }
  3353. return true;
  3354. }
  3355. }
  3356. return false;
  3357. }
  3358. /// If we can, try to add the value of 'Addr' into the current addressing mode.
  3359. /// If Addr can't be added to AddrMode this returns false and leaves AddrMode
  3360. /// unmodified. This assumes that Addr is either a pointer type or intptr_t
  3361. /// for the target.
  3362. ///
  3363. bool AddressingModeMatcher::matchAddr(Value *Addr, unsigned Depth) {
  3364. // Start a transaction at this point that we will rollback if the matching
  3365. // fails.
  3366. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3367. TPT.getRestorationPoint();
  3368. if (ConstantInt *CI = dyn_cast<ConstantInt>(Addr)) {
  3369. // Fold in immediates if legal for the target.
  3370. AddrMode.BaseOffs += CI->getSExtValue();
  3371. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3372. return true;
  3373. AddrMode.BaseOffs -= CI->getSExtValue();
  3374. } else if (GlobalValue *GV = dyn_cast<GlobalValue>(Addr)) {
  3375. // If this is a global variable, try to fold it into the addressing mode.
  3376. if (!AddrMode.BaseGV) {
  3377. AddrMode.BaseGV = GV;
  3378. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3379. return true;
  3380. AddrMode.BaseGV = nullptr;
  3381. }
  3382. } else if (Instruction *I = dyn_cast<Instruction>(Addr)) {
  3383. ExtAddrMode BackupAddrMode = AddrMode;
  3384. unsigned OldSize = AddrModeInsts.size();
  3385. // Check to see if it is possible to fold this operation.
  3386. bool MovedAway = false;
  3387. if (matchOperationAddr(I, I->getOpcode(), Depth, &MovedAway)) {
  3388. // This instruction may have been moved away. If so, there is nothing
  3389. // to check here.
  3390. if (MovedAway)
  3391. return true;
  3392. // Okay, it's possible to fold this. Check to see if it is actually
  3393. // *profitable* to do so. We use a simple cost model to avoid increasing
  3394. // register pressure too much.
  3395. if (I->hasOneUse() ||
  3396. isProfitableToFoldIntoAddressingMode(I, BackupAddrMode, AddrMode)) {
  3397. AddrModeInsts.push_back(I);
  3398. return true;
  3399. }
  3400. // It isn't profitable to do this, roll back.
  3401. //cerr << "NOT FOLDING: " << *I;
  3402. AddrMode = BackupAddrMode;
  3403. AddrModeInsts.resize(OldSize);
  3404. TPT.rollback(LastKnownGood);
  3405. }
  3406. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Addr)) {
  3407. if (matchOperationAddr(CE, CE->getOpcode(), Depth))
  3408. return true;
  3409. TPT.rollback(LastKnownGood);
  3410. } else if (isa<ConstantPointerNull>(Addr)) {
  3411. // Null pointer gets folded without affecting the addressing mode.
  3412. return true;
  3413. }
  3414. // Worse case, the target should support [reg] addressing modes. :)
  3415. if (!AddrMode.HasBaseReg) {
  3416. AddrMode.HasBaseReg = true;
  3417. AddrMode.BaseReg = Addr;
  3418. // Still check for legality in case the target supports [imm] but not [i+r].
  3419. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3420. return true;
  3421. AddrMode.HasBaseReg = false;
  3422. AddrMode.BaseReg = nullptr;
  3423. }
  3424. // If the base register is already taken, see if we can do [r+r].
  3425. if (AddrMode.Scale == 0) {
  3426. AddrMode.Scale = 1;
  3427. AddrMode.ScaledReg = Addr;
  3428. if (TLI.isLegalAddressingMode(DL, AddrMode, AccessTy, AddrSpace))
  3429. return true;
  3430. AddrMode.Scale = 0;
  3431. AddrMode.ScaledReg = nullptr;
  3432. }
  3433. // Couldn't match.
  3434. TPT.rollback(LastKnownGood);
  3435. return false;
  3436. }
  3437. /// Check to see if all uses of OpVal by the specified inline asm call are due
  3438. /// to memory operands. If so, return true, otherwise return false.
  3439. static bool IsOperandAMemoryOperand(CallInst *CI, InlineAsm *IA, Value *OpVal,
  3440. const TargetLowering &TLI,
  3441. const TargetRegisterInfo &TRI) {
  3442. const Function *F = CI->getFunction();
  3443. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3444. TLI.ParseConstraints(F->getParent()->getDataLayout(), &TRI,
  3445. ImmutableCallSite(CI));
  3446. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3447. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3448. // Compute the constraint code and ConstraintType to use.
  3449. TLI.ComputeConstraintToUse(OpInfo, SDValue());
  3450. // If this asm operand is our Value*, and if it isn't an indirect memory
  3451. // operand, we can't fold it!
  3452. if (OpInfo.CallOperandVal == OpVal &&
  3453. (OpInfo.ConstraintType != TargetLowering::C_Memory ||
  3454. !OpInfo.isIndirect))
  3455. return false;
  3456. }
  3457. return true;
  3458. }
  3459. // Max number of memory uses to look at before aborting the search to conserve
  3460. // compile time.
  3461. static constexpr int MaxMemoryUsesToScan = 20;
  3462. /// Recursively walk all the uses of I until we find a memory use.
  3463. /// If we find an obviously non-foldable instruction, return true.
  3464. /// Add the ultimately found memory instructions to MemoryUses.
  3465. static bool FindAllMemoryUses(
  3466. Instruction *I,
  3467. SmallVectorImpl<std::pair<Instruction *, unsigned>> &MemoryUses,
  3468. SmallPtrSetImpl<Instruction *> &ConsideredInsts, const TargetLowering &TLI,
  3469. const TargetRegisterInfo &TRI, int SeenInsts = 0) {
  3470. // If we already considered this instruction, we're done.
  3471. if (!ConsideredInsts.insert(I).second)
  3472. return false;
  3473. // If this is an obviously unfoldable instruction, bail out.
  3474. if (!MightBeFoldableInst(I))
  3475. return true;
  3476. const bool OptSize = I->getFunction()->optForSize();
  3477. // Loop over all the uses, recursively processing them.
  3478. for (Use &U : I->uses()) {
  3479. // Conservatively return true if we're seeing a large number or a deep chain
  3480. // of users. This avoids excessive compilation times in pathological cases.
  3481. if (SeenInsts++ >= MaxMemoryUsesToScan)
  3482. return true;
  3483. Instruction *UserI = cast<Instruction>(U.getUser());
  3484. if (LoadInst *LI = dyn_cast<LoadInst>(UserI)) {
  3485. MemoryUses.push_back(std::make_pair(LI, U.getOperandNo()));
  3486. continue;
  3487. }
  3488. if (StoreInst *SI = dyn_cast<StoreInst>(UserI)) {
  3489. unsigned opNo = U.getOperandNo();
  3490. if (opNo != StoreInst::getPointerOperandIndex())
  3491. return true; // Storing addr, not into addr.
  3492. MemoryUses.push_back(std::make_pair(SI, opNo));
  3493. continue;
  3494. }
  3495. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(UserI)) {
  3496. unsigned opNo = U.getOperandNo();
  3497. if (opNo != AtomicRMWInst::getPointerOperandIndex())
  3498. return true; // Storing addr, not into addr.
  3499. MemoryUses.push_back(std::make_pair(RMW, opNo));
  3500. continue;
  3501. }
  3502. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(UserI)) {
  3503. unsigned opNo = U.getOperandNo();
  3504. if (opNo != AtomicCmpXchgInst::getPointerOperandIndex())
  3505. return true; // Storing addr, not into addr.
  3506. MemoryUses.push_back(std::make_pair(CmpX, opNo));
  3507. continue;
  3508. }
  3509. if (CallInst *CI = dyn_cast<CallInst>(UserI)) {
  3510. // If this is a cold call, we can sink the addressing calculation into
  3511. // the cold path. See optimizeCallInst
  3512. if (!OptSize && CI->hasFnAttr(Attribute::Cold))
  3513. continue;
  3514. InlineAsm *IA = dyn_cast<InlineAsm>(CI->getCalledValue());
  3515. if (!IA) return true;
  3516. // If this is a memory operand, we're cool, otherwise bail out.
  3517. if (!IsOperandAMemoryOperand(CI, IA, I, TLI, TRI))
  3518. return true;
  3519. continue;
  3520. }
  3521. if (FindAllMemoryUses(UserI, MemoryUses, ConsideredInsts, TLI, TRI,
  3522. SeenInsts))
  3523. return true;
  3524. }
  3525. return false;
  3526. }
  3527. /// Return true if Val is already known to be live at the use site that we're
  3528. /// folding it into. If so, there is no cost to include it in the addressing
  3529. /// mode. KnownLive1 and KnownLive2 are two values that we know are live at the
  3530. /// instruction already.
  3531. bool AddressingModeMatcher::valueAlreadyLiveAtInst(Value *Val,Value *KnownLive1,
  3532. Value *KnownLive2) {
  3533. // If Val is either of the known-live values, we know it is live!
  3534. if (Val == nullptr || Val == KnownLive1 || Val == KnownLive2)
  3535. return true;
  3536. // All values other than instructions and arguments (e.g. constants) are live.
  3537. if (!isa<Instruction>(Val) && !isa<Argument>(Val)) return true;
  3538. // If Val is a constant sized alloca in the entry block, it is live, this is
  3539. // true because it is just a reference to the stack/frame pointer, which is
  3540. // live for the whole function.
  3541. if (AllocaInst *AI = dyn_cast<AllocaInst>(Val))
  3542. if (AI->isStaticAlloca())
  3543. return true;
  3544. // Check to see if this value is already used in the memory instruction's
  3545. // block. If so, it's already live into the block at the very least, so we
  3546. // can reasonably fold it.
  3547. return Val->isUsedInBasicBlock(MemoryInst->getParent());
  3548. }
  3549. /// It is possible for the addressing mode of the machine to fold the specified
  3550. /// instruction into a load or store that ultimately uses it.
  3551. /// However, the specified instruction has multiple uses.
  3552. /// Given this, it may actually increase register pressure to fold it
  3553. /// into the load. For example, consider this code:
  3554. ///
  3555. /// X = ...
  3556. /// Y = X+1
  3557. /// use(Y) -> nonload/store
  3558. /// Z = Y+1
  3559. /// load Z
  3560. ///
  3561. /// In this case, Y has multiple uses, and can be folded into the load of Z
  3562. /// (yielding load [X+2]). However, doing this will cause both "X" and "X+1" to
  3563. /// be live at the use(Y) line. If we don't fold Y into load Z, we use one
  3564. /// fewer register. Since Y can't be folded into "use(Y)" we don't increase the
  3565. /// number of computations either.
  3566. ///
  3567. /// Note that this (like most of CodeGenPrepare) is just a rough heuristic. If
  3568. /// X was live across 'load Z' for other reasons, we actually *would* want to
  3569. /// fold the addressing mode in the Z case. This would make Y die earlier.
  3570. bool AddressingModeMatcher::
  3571. isProfitableToFoldIntoAddressingMode(Instruction *I, ExtAddrMode &AMBefore,
  3572. ExtAddrMode &AMAfter) {
  3573. if (IgnoreProfitability) return true;
  3574. // AMBefore is the addressing mode before this instruction was folded into it,
  3575. // and AMAfter is the addressing mode after the instruction was folded. Get
  3576. // the set of registers referenced by AMAfter and subtract out those
  3577. // referenced by AMBefore: this is the set of values which folding in this
  3578. // address extends the lifetime of.
  3579. //
  3580. // Note that there are only two potential values being referenced here,
  3581. // BaseReg and ScaleReg (global addresses are always available, as are any
  3582. // folded immediates).
  3583. Value *BaseReg = AMAfter.BaseReg, *ScaledReg = AMAfter.ScaledReg;
  3584. // If the BaseReg or ScaledReg was referenced by the previous addrmode, their
  3585. // lifetime wasn't extended by adding this instruction.
  3586. if (valueAlreadyLiveAtInst(BaseReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3587. BaseReg = nullptr;
  3588. if (valueAlreadyLiveAtInst(ScaledReg, AMBefore.BaseReg, AMBefore.ScaledReg))
  3589. ScaledReg = nullptr;
  3590. // If folding this instruction (and it's subexprs) didn't extend any live
  3591. // ranges, we're ok with it.
  3592. if (!BaseReg && !ScaledReg)
  3593. return true;
  3594. // If all uses of this instruction can have the address mode sunk into them,
  3595. // we can remove the addressing mode and effectively trade one live register
  3596. // for another (at worst.) In this context, folding an addressing mode into
  3597. // the use is just a particularly nice way of sinking it.
  3598. SmallVector<std::pair<Instruction*,unsigned>, 16> MemoryUses;
  3599. SmallPtrSet<Instruction*, 16> ConsideredInsts;
  3600. if (FindAllMemoryUses(I, MemoryUses, ConsideredInsts, TLI, TRI))
  3601. return false; // Has a non-memory, non-foldable use!
  3602. // Now that we know that all uses of this instruction are part of a chain of
  3603. // computation involving only operations that could theoretically be folded
  3604. // into a memory use, loop over each of these memory operation uses and see
  3605. // if they could *actually* fold the instruction. The assumption is that
  3606. // addressing modes are cheap and that duplicating the computation involved
  3607. // many times is worthwhile, even on a fastpath. For sinking candidates
  3608. // (i.e. cold call sites), this serves as a way to prevent excessive code
  3609. // growth since most architectures have some reasonable small and fast way to
  3610. // compute an effective address. (i.e LEA on x86)
  3611. SmallVector<Instruction*, 32> MatchedAddrModeInsts;
  3612. for (unsigned i = 0, e = MemoryUses.size(); i != e; ++i) {
  3613. Instruction *User = MemoryUses[i].first;
  3614. unsigned OpNo = MemoryUses[i].second;
  3615. // Get the access type of this use. If the use isn't a pointer, we don't
  3616. // know what it accesses.
  3617. Value *Address = User->getOperand(OpNo);
  3618. PointerType *AddrTy = dyn_cast<PointerType>(Address->getType());
  3619. if (!AddrTy)
  3620. return false;
  3621. Type *AddressAccessTy = AddrTy->getElementType();
  3622. unsigned AS = AddrTy->getAddressSpace();
  3623. // Do a match against the root of this address, ignoring profitability. This
  3624. // will tell us if the addressing mode for the memory operation will
  3625. // *actually* cover the shared instruction.
  3626. ExtAddrMode Result;
  3627. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3628. TPT.getRestorationPoint();
  3629. AddressingModeMatcher Matcher(MatchedAddrModeInsts, TLI, TRI,
  3630. AddressAccessTy, AS,
  3631. MemoryInst, Result, InsertedInsts,
  3632. PromotedInsts, TPT);
  3633. Matcher.IgnoreProfitability = true;
  3634. bool Success = Matcher.matchAddr(Address, 0);
  3635. (void)Success; assert(Success && "Couldn't select *anything*?");
  3636. // The match was to check the profitability, the changes made are not
  3637. // part of the original matcher. Therefore, they should be dropped
  3638. // otherwise the original matcher will not present the right state.
  3639. TPT.rollback(LastKnownGood);
  3640. // If the match didn't cover I, then it won't be shared by it.
  3641. if (!is_contained(MatchedAddrModeInsts, I))
  3642. return false;
  3643. MatchedAddrModeInsts.clear();
  3644. }
  3645. return true;
  3646. }
  3647. /// Return true if the specified values are defined in a
  3648. /// different basic block than BB.
  3649. static bool IsNonLocalValue(Value *V, BasicBlock *BB) {
  3650. if (Instruction *I = dyn_cast<Instruction>(V))
  3651. return I->getParent() != BB;
  3652. return false;
  3653. }
  3654. /// Sink addressing mode computation immediate before MemoryInst if doing so
  3655. /// can be done without increasing register pressure. The need for the
  3656. /// register pressure constraint means this can end up being an all or nothing
  3657. /// decision for all uses of the same addressing computation.
  3658. ///
  3659. /// Load and Store Instructions often have addressing modes that can do
  3660. /// significant amounts of computation. As such, instruction selection will try
  3661. /// to get the load or store to do as much computation as possible for the
  3662. /// program. The problem is that isel can only see within a single block. As
  3663. /// such, we sink as much legal addressing mode work into the block as possible.
  3664. ///
  3665. /// This method is used to optimize both load/store and inline asms with memory
  3666. /// operands. It's also used to sink addressing computations feeding into cold
  3667. /// call sites into their (cold) basic block.
  3668. ///
  3669. /// The motivation for handling sinking into cold blocks is that doing so can
  3670. /// both enable other address mode sinking (by satisfying the register pressure
  3671. /// constraint above), and reduce register pressure globally (by removing the
  3672. /// addressing mode computation from the fast path entirely.).
  3673. bool CodeGenPrepare::optimizeMemoryInst(Instruction *MemoryInst, Value *Addr,
  3674. Type *AccessTy, unsigned AddrSpace) {
  3675. Value *Repl = Addr;
  3676. // Try to collapse single-value PHI nodes. This is necessary to undo
  3677. // unprofitable PRE transformations.
  3678. SmallVector<Value*, 8> worklist;
  3679. SmallPtrSet<Value*, 16> Visited;
  3680. worklist.push_back(Addr);
  3681. // Use a worklist to iteratively look through PHI and select nodes, and
  3682. // ensure that the addressing mode obtained from the non-PHI/select roots of
  3683. // the graph are compatible.
  3684. bool PhiOrSelectSeen = false;
  3685. SmallVector<Instruction*, 16> AddrModeInsts;
  3686. const SimplifyQuery SQ(*DL, TLInfo);
  3687. AddressingModeCombiner AddrModes(SQ, { Addr, MemoryInst->getParent() });
  3688. TypePromotionTransaction TPT(RemovedInsts);
  3689. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  3690. TPT.getRestorationPoint();
  3691. while (!worklist.empty()) {
  3692. Value *V = worklist.back();
  3693. worklist.pop_back();
  3694. // We allow traversing cyclic Phi nodes.
  3695. // In case of success after this loop we ensure that traversing through
  3696. // Phi nodes ends up with all cases to compute address of the form
  3697. // BaseGV + Base + Scale * Index + Offset
  3698. // where Scale and Offset are constans and BaseGV, Base and Index
  3699. // are exactly the same Values in all cases.
  3700. // It means that BaseGV, Scale and Offset dominate our memory instruction
  3701. // and have the same value as they had in address computation represented
  3702. // as Phi. So we can safely sink address computation to memory instruction.
  3703. if (!Visited.insert(V).second)
  3704. continue;
  3705. // For a PHI node, push all of its incoming values.
  3706. if (PHINode *P = dyn_cast<PHINode>(V)) {
  3707. for (Value *IncValue : P->incoming_values())
  3708. worklist.push_back(IncValue);
  3709. PhiOrSelectSeen = true;
  3710. continue;
  3711. }
  3712. // Similar for select.
  3713. if (SelectInst *SI = dyn_cast<SelectInst>(V)) {
  3714. worklist.push_back(SI->getFalseValue());
  3715. worklist.push_back(SI->getTrueValue());
  3716. PhiOrSelectSeen = true;
  3717. continue;
  3718. }
  3719. // For non-PHIs, determine the addressing mode being computed. Note that
  3720. // the result may differ depending on what other uses our candidate
  3721. // addressing instructions might have.
  3722. AddrModeInsts.clear();
  3723. ExtAddrMode NewAddrMode = AddressingModeMatcher::Match(
  3724. V, AccessTy, AddrSpace, MemoryInst, AddrModeInsts, *TLI, *TRI,
  3725. InsertedInsts, PromotedInsts, TPT);
  3726. NewAddrMode.OriginalValue = V;
  3727. if (!AddrModes.addNewAddrMode(NewAddrMode))
  3728. break;
  3729. }
  3730. // Try to combine the AddrModes we've collected. If we couldn't collect any,
  3731. // or we have multiple but either couldn't combine them or combining them
  3732. // wouldn't do anything useful, bail out now.
  3733. if (!AddrModes.combineAddrModes()) {
  3734. TPT.rollback(LastKnownGood);
  3735. return false;
  3736. }
  3737. TPT.commit();
  3738. // Get the combined AddrMode (or the only AddrMode, if we only had one).
  3739. ExtAddrMode AddrMode = AddrModes.getAddrMode();
  3740. // If all the instructions matched are already in this BB, don't do anything.
  3741. // If we saw a Phi node then it is not local definitely, and if we saw a select
  3742. // then we want to push the address calculation past it even if it's already
  3743. // in this BB.
  3744. if (!PhiOrSelectSeen && none_of(AddrModeInsts, [&](Value *V) {
  3745. return IsNonLocalValue(V, MemoryInst->getParent());
  3746. })) {
  3747. DEBUG(dbgs() << "CGP: Found local addrmode: " << AddrMode << "\n");
  3748. return false;
  3749. }
  3750. // Insert this computation right after this user. Since our caller is
  3751. // scanning from the top of the BB to the bottom, reuse of the expr are
  3752. // guaranteed to happen later.
  3753. IRBuilder<> Builder(MemoryInst);
  3754. // Now that we determined the addressing expression we want to use and know
  3755. // that we have to sink it into this block. Check to see if we have already
  3756. // done this for some other load/store instr in this block. If so, reuse
  3757. // the computation. Before attempting reuse, check if the address is valid
  3758. // as it may have been erased.
  3759. WeakTrackingVH SunkAddrVH = SunkAddrs[Addr];
  3760. Value * SunkAddr = SunkAddrVH.pointsToAliveValue() ? SunkAddrVH : nullptr;
  3761. if (SunkAddr) {
  3762. DEBUG(dbgs() << "CGP: Reusing nonlocal addrmode: " << AddrMode << " for "
  3763. << *MemoryInst << "\n");
  3764. if (SunkAddr->getType() != Addr->getType())
  3765. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  3766. } else if (AddrSinkUsingGEPs ||
  3767. (!AddrSinkUsingGEPs.getNumOccurrences() && TM && TTI->useAA())) {
  3768. // By default, we use the GEP-based method when AA is used later. This
  3769. // prevents new inttoptr/ptrtoint pairs from degrading AA capabilities.
  3770. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  3771. << *MemoryInst << "\n");
  3772. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  3773. Value *ResultPtr = nullptr, *ResultIndex = nullptr;
  3774. // First, find the pointer.
  3775. if (AddrMode.BaseReg && AddrMode.BaseReg->getType()->isPointerTy()) {
  3776. ResultPtr = AddrMode.BaseReg;
  3777. AddrMode.BaseReg = nullptr;
  3778. }
  3779. if (AddrMode.Scale && AddrMode.ScaledReg->getType()->isPointerTy()) {
  3780. // We can't add more than one pointer together, nor can we scale a
  3781. // pointer (both of which seem meaningless).
  3782. if (ResultPtr || AddrMode.Scale != 1)
  3783. return false;
  3784. ResultPtr = AddrMode.ScaledReg;
  3785. AddrMode.Scale = 0;
  3786. }
  3787. // It is only safe to sign extend the BaseReg if we know that the math
  3788. // required to create it did not overflow before we extend it. Since
  3789. // the original IR value was tossed in favor of a constant back when
  3790. // the AddrMode was created we need to bail out gracefully if widths
  3791. // do not match instead of extending it.
  3792. //
  3793. // (See below for code to add the scale.)
  3794. if (AddrMode.Scale) {
  3795. Type *ScaledRegTy = AddrMode.ScaledReg->getType();
  3796. if (cast<IntegerType>(IntPtrTy)->getBitWidth() >
  3797. cast<IntegerType>(ScaledRegTy)->getBitWidth())
  3798. return false;
  3799. }
  3800. if (AddrMode.BaseGV) {
  3801. if (ResultPtr)
  3802. return false;
  3803. ResultPtr = AddrMode.BaseGV;
  3804. }
  3805. // If the real base value actually came from an inttoptr, then the matcher
  3806. // will look through it and provide only the integer value. In that case,
  3807. // use it here.
  3808. if (!DL->isNonIntegralPointerType(Addr->getType())) {
  3809. if (!ResultPtr && AddrMode.BaseReg) {
  3810. ResultPtr = Builder.CreateIntToPtr(AddrMode.BaseReg, Addr->getType(),
  3811. "sunkaddr");
  3812. AddrMode.BaseReg = nullptr;
  3813. } else if (!ResultPtr && AddrMode.Scale == 1) {
  3814. ResultPtr = Builder.CreateIntToPtr(AddrMode.ScaledReg, Addr->getType(),
  3815. "sunkaddr");
  3816. AddrMode.Scale = 0;
  3817. }
  3818. }
  3819. if (!ResultPtr &&
  3820. !AddrMode.BaseReg && !AddrMode.Scale && !AddrMode.BaseOffs) {
  3821. SunkAddr = Constant::getNullValue(Addr->getType());
  3822. } else if (!ResultPtr) {
  3823. return false;
  3824. } else {
  3825. Type *I8PtrTy =
  3826. Builder.getInt8PtrTy(Addr->getType()->getPointerAddressSpace());
  3827. Type *I8Ty = Builder.getInt8Ty();
  3828. // Start with the base register. Do this first so that subsequent address
  3829. // matching finds it last, which will prevent it from trying to match it
  3830. // as the scaled value in case it happens to be a mul. That would be
  3831. // problematic if we've sunk a different mul for the scale, because then
  3832. // we'd end up sinking both muls.
  3833. if (AddrMode.BaseReg) {
  3834. Value *V = AddrMode.BaseReg;
  3835. if (V->getType() != IntPtrTy)
  3836. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  3837. ResultIndex = V;
  3838. }
  3839. // Add the scale value.
  3840. if (AddrMode.Scale) {
  3841. Value *V = AddrMode.ScaledReg;
  3842. if (V->getType() == IntPtrTy) {
  3843. // done.
  3844. } else {
  3845. assert(cast<IntegerType>(IntPtrTy)->getBitWidth() <
  3846. cast<IntegerType>(V->getType())->getBitWidth() &&
  3847. "We can't transform if ScaledReg is too narrow");
  3848. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  3849. }
  3850. if (AddrMode.Scale != 1)
  3851. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3852. "sunkaddr");
  3853. if (ResultIndex)
  3854. ResultIndex = Builder.CreateAdd(ResultIndex, V, "sunkaddr");
  3855. else
  3856. ResultIndex = V;
  3857. }
  3858. // Add in the Base Offset if present.
  3859. if (AddrMode.BaseOffs) {
  3860. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3861. if (ResultIndex) {
  3862. // We need to add this separately from the scale above to help with
  3863. // SDAG consecutive load/store merging.
  3864. if (ResultPtr->getType() != I8PtrTy)
  3865. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  3866. ResultPtr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3867. }
  3868. ResultIndex = V;
  3869. }
  3870. if (!ResultIndex) {
  3871. SunkAddr = ResultPtr;
  3872. } else {
  3873. if (ResultPtr->getType() != I8PtrTy)
  3874. ResultPtr = Builder.CreatePointerCast(ResultPtr, I8PtrTy);
  3875. SunkAddr = Builder.CreateGEP(I8Ty, ResultPtr, ResultIndex, "sunkaddr");
  3876. }
  3877. if (SunkAddr->getType() != Addr->getType())
  3878. SunkAddr = Builder.CreatePointerCast(SunkAddr, Addr->getType());
  3879. }
  3880. } else {
  3881. // We'd require a ptrtoint/inttoptr down the line, which we can't do for
  3882. // non-integral pointers, so in that case bail out now.
  3883. Type *BaseTy = AddrMode.BaseReg ? AddrMode.BaseReg->getType() : nullptr;
  3884. Type *ScaleTy = AddrMode.Scale ? AddrMode.ScaledReg->getType() : nullptr;
  3885. PointerType *BasePtrTy = dyn_cast_or_null<PointerType>(BaseTy);
  3886. PointerType *ScalePtrTy = dyn_cast_or_null<PointerType>(ScaleTy);
  3887. if (DL->isNonIntegralPointerType(Addr->getType()) ||
  3888. (BasePtrTy && DL->isNonIntegralPointerType(BasePtrTy)) ||
  3889. (ScalePtrTy && DL->isNonIntegralPointerType(ScalePtrTy)) ||
  3890. (AddrMode.BaseGV &&
  3891. DL->isNonIntegralPointerType(AddrMode.BaseGV->getType())))
  3892. return false;
  3893. DEBUG(dbgs() << "CGP: SINKING nonlocal addrmode: " << AddrMode << " for "
  3894. << *MemoryInst << "\n");
  3895. Type *IntPtrTy = DL->getIntPtrType(Addr->getType());
  3896. Value *Result = nullptr;
  3897. // Start with the base register. Do this first so that subsequent address
  3898. // matching finds it last, which will prevent it from trying to match it
  3899. // as the scaled value in case it happens to be a mul. That would be
  3900. // problematic if we've sunk a different mul for the scale, because then
  3901. // we'd end up sinking both muls.
  3902. if (AddrMode.BaseReg) {
  3903. Value *V = AddrMode.BaseReg;
  3904. if (V->getType()->isPointerTy())
  3905. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3906. if (V->getType() != IntPtrTy)
  3907. V = Builder.CreateIntCast(V, IntPtrTy, /*isSigned=*/true, "sunkaddr");
  3908. Result = V;
  3909. }
  3910. // Add the scale value.
  3911. if (AddrMode.Scale) {
  3912. Value *V = AddrMode.ScaledReg;
  3913. if (V->getType() == IntPtrTy) {
  3914. // done.
  3915. } else if (V->getType()->isPointerTy()) {
  3916. V = Builder.CreatePtrToInt(V, IntPtrTy, "sunkaddr");
  3917. } else if (cast<IntegerType>(IntPtrTy)->getBitWidth() <
  3918. cast<IntegerType>(V->getType())->getBitWidth()) {
  3919. V = Builder.CreateTrunc(V, IntPtrTy, "sunkaddr");
  3920. } else {
  3921. // It is only safe to sign extend the BaseReg if we know that the math
  3922. // required to create it did not overflow before we extend it. Since
  3923. // the original IR value was tossed in favor of a constant back when
  3924. // the AddrMode was created we need to bail out gracefully if widths
  3925. // do not match instead of extending it.
  3926. Instruction *I = dyn_cast_or_null<Instruction>(Result);
  3927. if (I && (Result != AddrMode.BaseReg))
  3928. I->eraseFromParent();
  3929. return false;
  3930. }
  3931. if (AddrMode.Scale != 1)
  3932. V = Builder.CreateMul(V, ConstantInt::get(IntPtrTy, AddrMode.Scale),
  3933. "sunkaddr");
  3934. if (Result)
  3935. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3936. else
  3937. Result = V;
  3938. }
  3939. // Add in the BaseGV if present.
  3940. if (AddrMode.BaseGV) {
  3941. Value *V = Builder.CreatePtrToInt(AddrMode.BaseGV, IntPtrTy, "sunkaddr");
  3942. if (Result)
  3943. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3944. else
  3945. Result = V;
  3946. }
  3947. // Add in the Base Offset if present.
  3948. if (AddrMode.BaseOffs) {
  3949. Value *V = ConstantInt::get(IntPtrTy, AddrMode.BaseOffs);
  3950. if (Result)
  3951. Result = Builder.CreateAdd(Result, V, "sunkaddr");
  3952. else
  3953. Result = V;
  3954. }
  3955. if (!Result)
  3956. SunkAddr = Constant::getNullValue(Addr->getType());
  3957. else
  3958. SunkAddr = Builder.CreateIntToPtr(Result, Addr->getType(), "sunkaddr");
  3959. }
  3960. MemoryInst->replaceUsesOfWith(Repl, SunkAddr);
  3961. // Store the newly computed address into the cache. In the case we reused a
  3962. // value, this should be idempotent.
  3963. SunkAddrs[Addr] = WeakTrackingVH(SunkAddr);
  3964. // If we have no uses, recursively delete the value and all dead instructions
  3965. // using it.
  3966. if (Repl->use_empty()) {
  3967. // This can cause recursive deletion, which can invalidate our iterator.
  3968. // Use a WeakTrackingVH to hold onto it in case this happens.
  3969. Value *CurValue = &*CurInstIterator;
  3970. WeakTrackingVH IterHandle(CurValue);
  3971. BasicBlock *BB = CurInstIterator->getParent();
  3972. RecursivelyDeleteTriviallyDeadInstructions(Repl, TLInfo);
  3973. if (IterHandle != CurValue) {
  3974. // If the iterator instruction was recursively deleted, start over at the
  3975. // start of the block.
  3976. CurInstIterator = BB->begin();
  3977. SunkAddrs.clear();
  3978. }
  3979. }
  3980. ++NumMemoryInsts;
  3981. return true;
  3982. }
  3983. /// If there are any memory operands, use OptimizeMemoryInst to sink their
  3984. /// address computing into the block when possible / profitable.
  3985. bool CodeGenPrepare::optimizeInlineAsmInst(CallInst *CS) {
  3986. bool MadeChange = false;
  3987. const TargetRegisterInfo *TRI =
  3988. TM->getSubtargetImpl(*CS->getFunction())->getRegisterInfo();
  3989. TargetLowering::AsmOperandInfoVector TargetConstraints =
  3990. TLI->ParseConstraints(*DL, TRI, CS);
  3991. unsigned ArgNo = 0;
  3992. for (unsigned i = 0, e = TargetConstraints.size(); i != e; ++i) {
  3993. TargetLowering::AsmOperandInfo &OpInfo = TargetConstraints[i];
  3994. // Compute the constraint code and ConstraintType to use.
  3995. TLI->ComputeConstraintToUse(OpInfo, SDValue());
  3996. if (OpInfo.ConstraintType == TargetLowering::C_Memory &&
  3997. OpInfo.isIndirect) {
  3998. Value *OpVal = CS->getArgOperand(ArgNo++);
  3999. MadeChange |= optimizeMemoryInst(CS, OpVal, OpVal->getType(), ~0u);
  4000. } else if (OpInfo.Type == InlineAsm::isInput)
  4001. ArgNo++;
  4002. }
  4003. return MadeChange;
  4004. }
  4005. /// \brief Check if all the uses of \p Val are equivalent (or free) zero or
  4006. /// sign extensions.
  4007. static bool hasSameExtUse(Value *Val, const TargetLowering &TLI) {
  4008. assert(!Val->use_empty() && "Input must have at least one use");
  4009. const Instruction *FirstUser = cast<Instruction>(*Val->user_begin());
  4010. bool IsSExt = isa<SExtInst>(FirstUser);
  4011. Type *ExtTy = FirstUser->getType();
  4012. for (const User *U : Val->users()) {
  4013. const Instruction *UI = cast<Instruction>(U);
  4014. if ((IsSExt && !isa<SExtInst>(UI)) || (!IsSExt && !isa<ZExtInst>(UI)))
  4015. return false;
  4016. Type *CurTy = UI->getType();
  4017. // Same input and output types: Same instruction after CSE.
  4018. if (CurTy == ExtTy)
  4019. continue;
  4020. // If IsSExt is true, we are in this situation:
  4021. // a = Val
  4022. // b = sext ty1 a to ty2
  4023. // c = sext ty1 a to ty3
  4024. // Assuming ty2 is shorter than ty3, this could be turned into:
  4025. // a = Val
  4026. // b = sext ty1 a to ty2
  4027. // c = sext ty2 b to ty3
  4028. // However, the last sext is not free.
  4029. if (IsSExt)
  4030. return false;
  4031. // This is a ZExt, maybe this is free to extend from one type to another.
  4032. // In that case, we would not account for a different use.
  4033. Type *NarrowTy;
  4034. Type *LargeTy;
  4035. if (ExtTy->getScalarType()->getIntegerBitWidth() >
  4036. CurTy->getScalarType()->getIntegerBitWidth()) {
  4037. NarrowTy = CurTy;
  4038. LargeTy = ExtTy;
  4039. } else {
  4040. NarrowTy = ExtTy;
  4041. LargeTy = CurTy;
  4042. }
  4043. if (!TLI.isZExtFree(NarrowTy, LargeTy))
  4044. return false;
  4045. }
  4046. // All uses are the same or can be derived from one another for free.
  4047. return true;
  4048. }
  4049. /// \brief Try to speculatively promote extensions in \p Exts and continue
  4050. /// promoting through newly promoted operands recursively as far as doing so is
  4051. /// profitable. Save extensions profitably moved up, in \p ProfitablyMovedExts.
  4052. /// When some promotion happened, \p TPT contains the proper state to revert
  4053. /// them.
  4054. ///
  4055. /// \return true if some promotion happened, false otherwise.
  4056. bool CodeGenPrepare::tryToPromoteExts(
  4057. TypePromotionTransaction &TPT, const SmallVectorImpl<Instruction *> &Exts,
  4058. SmallVectorImpl<Instruction *> &ProfitablyMovedExts,
  4059. unsigned CreatedInstsCost) {
  4060. bool Promoted = false;
  4061. // Iterate over all the extensions to try to promote them.
  4062. for (auto I : Exts) {
  4063. // Early check if we directly have ext(load).
  4064. if (isa<LoadInst>(I->getOperand(0))) {
  4065. ProfitablyMovedExts.push_back(I);
  4066. continue;
  4067. }
  4068. // Check whether or not we want to do any promotion. The reason we have
  4069. // this check inside the for loop is to catch the case where an extension
  4070. // is directly fed by a load because in such case the extension can be moved
  4071. // up without any promotion on its operands.
  4072. if (!TLI || !TLI->enableExtLdPromotion() || DisableExtLdPromotion)
  4073. return false;
  4074. // Get the action to perform the promotion.
  4075. TypePromotionHelper::Action TPH =
  4076. TypePromotionHelper::getAction(I, InsertedInsts, *TLI, PromotedInsts);
  4077. // Check if we can promote.
  4078. if (!TPH) {
  4079. // Save the current extension as we cannot move up through its operand.
  4080. ProfitablyMovedExts.push_back(I);
  4081. continue;
  4082. }
  4083. // Save the current state.
  4084. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4085. TPT.getRestorationPoint();
  4086. SmallVector<Instruction *, 4> NewExts;
  4087. unsigned NewCreatedInstsCost = 0;
  4088. unsigned ExtCost = !TLI->isExtFree(I);
  4089. // Promote.
  4090. Value *PromotedVal = TPH(I, TPT, PromotedInsts, NewCreatedInstsCost,
  4091. &NewExts, nullptr, *TLI);
  4092. assert(PromotedVal &&
  4093. "TypePromotionHelper should have filtered out those cases");
  4094. // We would be able to merge only one extension in a load.
  4095. // Therefore, if we have more than 1 new extension we heuristically
  4096. // cut this search path, because it means we degrade the code quality.
  4097. // With exactly 2, the transformation is neutral, because we will merge
  4098. // one extension but leave one. However, we optimistically keep going,
  4099. // because the new extension may be removed too.
  4100. long long TotalCreatedInstsCost = CreatedInstsCost + NewCreatedInstsCost;
  4101. // FIXME: It would be possible to propagate a negative value instead of
  4102. // conservatively ceiling it to 0.
  4103. TotalCreatedInstsCost =
  4104. std::max((long long)0, (TotalCreatedInstsCost - ExtCost));
  4105. if (!StressExtLdPromotion &&
  4106. (TotalCreatedInstsCost > 1 ||
  4107. !isPromotedInstructionLegal(*TLI, *DL, PromotedVal))) {
  4108. // This promotion is not profitable, rollback to the previous state, and
  4109. // save the current extension in ProfitablyMovedExts as the latest
  4110. // speculative promotion turned out to be unprofitable.
  4111. TPT.rollback(LastKnownGood);
  4112. ProfitablyMovedExts.push_back(I);
  4113. continue;
  4114. }
  4115. // Continue promoting NewExts as far as doing so is profitable.
  4116. SmallVector<Instruction *, 2> NewlyMovedExts;
  4117. (void)tryToPromoteExts(TPT, NewExts, NewlyMovedExts, TotalCreatedInstsCost);
  4118. bool NewPromoted = false;
  4119. for (auto ExtInst : NewlyMovedExts) {
  4120. Instruction *MovedExt = cast<Instruction>(ExtInst);
  4121. Value *ExtOperand = MovedExt->getOperand(0);
  4122. // If we have reached to a load, we need this extra profitability check
  4123. // as it could potentially be merged into an ext(load).
  4124. if (isa<LoadInst>(ExtOperand) &&
  4125. !(StressExtLdPromotion || NewCreatedInstsCost <= ExtCost ||
  4126. (ExtOperand->hasOneUse() || hasSameExtUse(ExtOperand, *TLI))))
  4127. continue;
  4128. ProfitablyMovedExts.push_back(MovedExt);
  4129. NewPromoted = true;
  4130. }
  4131. // If none of speculative promotions for NewExts is profitable, rollback
  4132. // and save the current extension (I) as the last profitable extension.
  4133. if (!NewPromoted) {
  4134. TPT.rollback(LastKnownGood);
  4135. ProfitablyMovedExts.push_back(I);
  4136. continue;
  4137. }
  4138. // The promotion is profitable.
  4139. Promoted = true;
  4140. }
  4141. return Promoted;
  4142. }
  4143. /// Merging redundant sexts when one is dominating the other.
  4144. bool CodeGenPrepare::mergeSExts(Function &F) {
  4145. DominatorTree DT(F);
  4146. bool Changed = false;
  4147. for (auto &Entry : ValToSExtendedUses) {
  4148. SExts &Insts = Entry.second;
  4149. SExts CurPts;
  4150. for (Instruction *Inst : Insts) {
  4151. if (RemovedInsts.count(Inst) || !isa<SExtInst>(Inst) ||
  4152. Inst->getOperand(0) != Entry.first)
  4153. continue;
  4154. bool inserted = false;
  4155. for (auto &Pt : CurPts) {
  4156. if (DT.dominates(Inst, Pt)) {
  4157. Pt->replaceAllUsesWith(Inst);
  4158. RemovedInsts.insert(Pt);
  4159. Pt->removeFromParent();
  4160. Pt = Inst;
  4161. inserted = true;
  4162. Changed = true;
  4163. break;
  4164. }
  4165. if (!DT.dominates(Pt, Inst))
  4166. // Give up if we need to merge in a common dominator as the
  4167. // expermients show it is not profitable.
  4168. continue;
  4169. Inst->replaceAllUsesWith(Pt);
  4170. RemovedInsts.insert(Inst);
  4171. Inst->removeFromParent();
  4172. inserted = true;
  4173. Changed = true;
  4174. break;
  4175. }
  4176. if (!inserted)
  4177. CurPts.push_back(Inst);
  4178. }
  4179. }
  4180. return Changed;
  4181. }
  4182. /// Return true, if an ext(load) can be formed from an extension in
  4183. /// \p MovedExts.
  4184. bool CodeGenPrepare::canFormExtLd(
  4185. const SmallVectorImpl<Instruction *> &MovedExts, LoadInst *&LI,
  4186. Instruction *&Inst, bool HasPromoted) {
  4187. for (auto *MovedExtInst : MovedExts) {
  4188. if (isa<LoadInst>(MovedExtInst->getOperand(0))) {
  4189. LI = cast<LoadInst>(MovedExtInst->getOperand(0));
  4190. Inst = MovedExtInst;
  4191. break;
  4192. }
  4193. }
  4194. if (!LI)
  4195. return false;
  4196. // If they're already in the same block, there's nothing to do.
  4197. // Make the cheap checks first if we did not promote.
  4198. // If we promoted, we need to check if it is indeed profitable.
  4199. if (!HasPromoted && LI->getParent() == Inst->getParent())
  4200. return false;
  4201. return TLI->isExtLoad(LI, Inst, *DL);
  4202. }
  4203. /// Move a zext or sext fed by a load into the same basic block as the load,
  4204. /// unless conditions are unfavorable. This allows SelectionDAG to fold the
  4205. /// extend into the load.
  4206. ///
  4207. /// E.g.,
  4208. /// \code
  4209. /// %ld = load i32* %addr
  4210. /// %add = add nuw i32 %ld, 4
  4211. /// %zext = zext i32 %add to i64
  4212. // \endcode
  4213. /// =>
  4214. /// \code
  4215. /// %ld = load i32* %addr
  4216. /// %zext = zext i32 %ld to i64
  4217. /// %add = add nuw i64 %zext, 4
  4218. /// \encode
  4219. /// Note that the promotion in %add to i64 is done in tryToPromoteExts(), which
  4220. /// allow us to match zext(load i32*) to i64.
  4221. ///
  4222. /// Also, try to promote the computations used to obtain a sign extended
  4223. /// value used into memory accesses.
  4224. /// E.g.,
  4225. /// \code
  4226. /// a = add nsw i32 b, 3
  4227. /// d = sext i32 a to i64
  4228. /// e = getelementptr ..., i64 d
  4229. /// \endcode
  4230. /// =>
  4231. /// \code
  4232. /// f = sext i32 b to i64
  4233. /// a = add nsw i64 f, 3
  4234. /// e = getelementptr ..., i64 a
  4235. /// \endcode
  4236. ///
  4237. /// \p Inst[in/out] the extension may be modified during the process if some
  4238. /// promotions apply.
  4239. bool CodeGenPrepare::optimizeExt(Instruction *&Inst) {
  4240. // ExtLoad formation and address type promotion infrastructure requires TLI to
  4241. // be effective.
  4242. if (!TLI)
  4243. return false;
  4244. bool AllowPromotionWithoutCommonHeader = false;
  4245. /// See if it is an interesting sext operations for the address type
  4246. /// promotion before trying to promote it, e.g., the ones with the right
  4247. /// type and used in memory accesses.
  4248. bool ATPConsiderable = TTI->shouldConsiderAddressTypePromotion(
  4249. *Inst, AllowPromotionWithoutCommonHeader);
  4250. TypePromotionTransaction TPT(RemovedInsts);
  4251. TypePromotionTransaction::ConstRestorationPt LastKnownGood =
  4252. TPT.getRestorationPoint();
  4253. SmallVector<Instruction *, 1> Exts;
  4254. SmallVector<Instruction *, 2> SpeculativelyMovedExts;
  4255. Exts.push_back(Inst);
  4256. bool HasPromoted = tryToPromoteExts(TPT, Exts, SpeculativelyMovedExts);
  4257. // Look for a load being extended.
  4258. LoadInst *LI = nullptr;
  4259. Instruction *ExtFedByLoad;
  4260. // Try to promote a chain of computation if it allows to form an extended
  4261. // load.
  4262. if (canFormExtLd(SpeculativelyMovedExts, LI, ExtFedByLoad, HasPromoted)) {
  4263. assert(LI && ExtFedByLoad && "Expect a valid load and extension");
  4264. TPT.commit();
  4265. // Move the extend into the same block as the load
  4266. ExtFedByLoad->moveAfter(LI);
  4267. // CGP does not check if the zext would be speculatively executed when moved
  4268. // to the same basic block as the load. Preserving its original location
  4269. // would pessimize the debugging experience, as well as negatively impact
  4270. // the quality of sample pgo. We don't want to use "line 0" as that has a
  4271. // size cost in the line-table section and logically the zext can be seen as
  4272. // part of the load. Therefore we conservatively reuse the same debug
  4273. // location for the load and the zext.
  4274. ExtFedByLoad->setDebugLoc(LI->getDebugLoc());
  4275. ++NumExtsMoved;
  4276. Inst = ExtFedByLoad;
  4277. return true;
  4278. }
  4279. // Continue promoting SExts if known as considerable depending on targets.
  4280. if (ATPConsiderable &&
  4281. performAddressTypePromotion(Inst, AllowPromotionWithoutCommonHeader,
  4282. HasPromoted, TPT, SpeculativelyMovedExts))
  4283. return true;
  4284. TPT.rollback(LastKnownGood);
  4285. return false;
  4286. }
  4287. // Perform address type promotion if doing so is profitable.
  4288. // If AllowPromotionWithoutCommonHeader == false, we should find other sext
  4289. // instructions that sign extended the same initial value. However, if
  4290. // AllowPromotionWithoutCommonHeader == true, we expect promoting the
  4291. // extension is just profitable.
  4292. bool CodeGenPrepare::performAddressTypePromotion(
  4293. Instruction *&Inst, bool AllowPromotionWithoutCommonHeader,
  4294. bool HasPromoted, TypePromotionTransaction &TPT,
  4295. SmallVectorImpl<Instruction *> &SpeculativelyMovedExts) {
  4296. bool Promoted = false;
  4297. SmallPtrSet<Instruction *, 1> UnhandledExts;
  4298. bool AllSeenFirst = true;
  4299. for (auto I : SpeculativelyMovedExts) {
  4300. Value *HeadOfChain = I->getOperand(0);
  4301. DenseMap<Value *, Instruction *>::iterator AlreadySeen =
  4302. SeenChainsForSExt.find(HeadOfChain);
  4303. // If there is an unhandled SExt which has the same header, try to promote
  4304. // it as well.
  4305. if (AlreadySeen != SeenChainsForSExt.end()) {
  4306. if (AlreadySeen->second != nullptr)
  4307. UnhandledExts.insert(AlreadySeen->second);
  4308. AllSeenFirst = false;
  4309. }
  4310. }
  4311. if (!AllSeenFirst || (AllowPromotionWithoutCommonHeader &&
  4312. SpeculativelyMovedExts.size() == 1)) {
  4313. TPT.commit();
  4314. if (HasPromoted)
  4315. Promoted = true;
  4316. for (auto I : SpeculativelyMovedExts) {
  4317. Value *HeadOfChain = I->getOperand(0);
  4318. SeenChainsForSExt[HeadOfChain] = nullptr;
  4319. ValToSExtendedUses[HeadOfChain].push_back(I);
  4320. }
  4321. // Update Inst as promotion happen.
  4322. Inst = SpeculativelyMovedExts.pop_back_val();
  4323. } else {
  4324. // This is the first chain visited from the header, keep the current chain
  4325. // as unhandled. Defer to promote this until we encounter another SExt
  4326. // chain derived from the same header.
  4327. for (auto I : SpeculativelyMovedExts) {
  4328. Value *HeadOfChain = I->getOperand(0);
  4329. SeenChainsForSExt[HeadOfChain] = Inst;
  4330. }
  4331. return false;
  4332. }
  4333. if (!AllSeenFirst && !UnhandledExts.empty())
  4334. for (auto VisitedSExt : UnhandledExts) {
  4335. if (RemovedInsts.count(VisitedSExt))
  4336. continue;
  4337. TypePromotionTransaction TPT(RemovedInsts);
  4338. SmallVector<Instruction *, 1> Exts;
  4339. SmallVector<Instruction *, 2> Chains;
  4340. Exts.push_back(VisitedSExt);
  4341. bool HasPromoted = tryToPromoteExts(TPT, Exts, Chains);
  4342. TPT.commit();
  4343. if (HasPromoted)
  4344. Promoted = true;
  4345. for (auto I : Chains) {
  4346. Value *HeadOfChain = I->getOperand(0);
  4347. // Mark this as handled.
  4348. SeenChainsForSExt[HeadOfChain] = nullptr;
  4349. ValToSExtendedUses[HeadOfChain].push_back(I);
  4350. }
  4351. }
  4352. return Promoted;
  4353. }
  4354. bool CodeGenPrepare::optimizeExtUses(Instruction *I) {
  4355. BasicBlock *DefBB = I->getParent();
  4356. // If the result of a {s|z}ext and its source are both live out, rewrite all
  4357. // other uses of the source with result of extension.
  4358. Value *Src = I->getOperand(0);
  4359. if (Src->hasOneUse())
  4360. return false;
  4361. // Only do this xform if truncating is free.
  4362. if (TLI && !TLI->isTruncateFree(I->getType(), Src->getType()))
  4363. return false;
  4364. // Only safe to perform the optimization if the source is also defined in
  4365. // this block.
  4366. if (!isa<Instruction>(Src) || DefBB != cast<Instruction>(Src)->getParent())
  4367. return false;
  4368. bool DefIsLiveOut = false;
  4369. for (User *U : I->users()) {
  4370. Instruction *UI = cast<Instruction>(U);
  4371. // Figure out which BB this ext is used in.
  4372. BasicBlock *UserBB = UI->getParent();
  4373. if (UserBB == DefBB) continue;
  4374. DefIsLiveOut = true;
  4375. break;
  4376. }
  4377. if (!DefIsLiveOut)
  4378. return false;
  4379. // Make sure none of the uses are PHI nodes.
  4380. for (User *U : Src->users()) {
  4381. Instruction *UI = cast<Instruction>(U);
  4382. BasicBlock *UserBB = UI->getParent();
  4383. if (UserBB == DefBB) continue;
  4384. // Be conservative. We don't want this xform to end up introducing
  4385. // reloads just before load / store instructions.
  4386. if (isa<PHINode>(UI) || isa<LoadInst>(UI) || isa<StoreInst>(UI))
  4387. return false;
  4388. }
  4389. // InsertedTruncs - Only insert one trunc in each block once.
  4390. DenseMap<BasicBlock*, Instruction*> InsertedTruncs;
  4391. bool MadeChange = false;
  4392. for (Use &U : Src->uses()) {
  4393. Instruction *User = cast<Instruction>(U.getUser());
  4394. // Figure out which BB this ext is used in.
  4395. BasicBlock *UserBB = User->getParent();
  4396. if (UserBB == DefBB) continue;
  4397. // Both src and def are live in this block. Rewrite the use.
  4398. Instruction *&InsertedTrunc = InsertedTruncs[UserBB];
  4399. if (!InsertedTrunc) {
  4400. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  4401. assert(InsertPt != UserBB->end());
  4402. InsertedTrunc = new TruncInst(I, Src->getType(), "", &*InsertPt);
  4403. InsertedInsts.insert(InsertedTrunc);
  4404. }
  4405. // Replace a use of the {s|z}ext source with a use of the result.
  4406. U = InsertedTrunc;
  4407. ++NumExtUses;
  4408. MadeChange = true;
  4409. }
  4410. return MadeChange;
  4411. }
  4412. // Find loads whose uses only use some of the loaded value's bits. Add an "and"
  4413. // just after the load if the target can fold this into one extload instruction,
  4414. // with the hope of eliminating some of the other later "and" instructions using
  4415. // the loaded value. "and"s that are made trivially redundant by the insertion
  4416. // of the new "and" are removed by this function, while others (e.g. those whose
  4417. // path from the load goes through a phi) are left for isel to potentially
  4418. // remove.
  4419. //
  4420. // For example:
  4421. //
  4422. // b0:
  4423. // x = load i32
  4424. // ...
  4425. // b1:
  4426. // y = and x, 0xff
  4427. // z = use y
  4428. //
  4429. // becomes:
  4430. //
  4431. // b0:
  4432. // x = load i32
  4433. // x' = and x, 0xff
  4434. // ...
  4435. // b1:
  4436. // z = use x'
  4437. //
  4438. // whereas:
  4439. //
  4440. // b0:
  4441. // x1 = load i32
  4442. // ...
  4443. // b1:
  4444. // x2 = load i32
  4445. // ...
  4446. // b2:
  4447. // x = phi x1, x2
  4448. // y = and x, 0xff
  4449. //
  4450. // becomes (after a call to optimizeLoadExt for each load):
  4451. //
  4452. // b0:
  4453. // x1 = load i32
  4454. // x1' = and x1, 0xff
  4455. // ...
  4456. // b1:
  4457. // x2 = load i32
  4458. // x2' = and x2, 0xff
  4459. // ...
  4460. // b2:
  4461. // x = phi x1', x2'
  4462. // y = and x, 0xff
  4463. bool CodeGenPrepare::optimizeLoadExt(LoadInst *Load) {
  4464. if (!Load->isSimple() ||
  4465. !(Load->getType()->isIntegerTy() || Load->getType()->isPointerTy()))
  4466. return false;
  4467. // Skip loads we've already transformed.
  4468. if (Load->hasOneUse() &&
  4469. InsertedInsts.count(cast<Instruction>(*Load->user_begin())))
  4470. return false;
  4471. // Look at all uses of Load, looking through phis, to determine how many bits
  4472. // of the loaded value are needed.
  4473. SmallVector<Instruction *, 8> WorkList;
  4474. SmallPtrSet<Instruction *, 16> Visited;
  4475. SmallVector<Instruction *, 8> AndsToMaybeRemove;
  4476. for (auto *U : Load->users())
  4477. WorkList.push_back(cast<Instruction>(U));
  4478. EVT LoadResultVT = TLI->getValueType(*DL, Load->getType());
  4479. unsigned BitWidth = LoadResultVT.getSizeInBits();
  4480. APInt DemandBits(BitWidth, 0);
  4481. APInt WidestAndBits(BitWidth, 0);
  4482. while (!WorkList.empty()) {
  4483. Instruction *I = WorkList.back();
  4484. WorkList.pop_back();
  4485. // Break use-def graph loops.
  4486. if (!Visited.insert(I).second)
  4487. continue;
  4488. // For a PHI node, push all of its users.
  4489. if (auto *Phi = dyn_cast<PHINode>(I)) {
  4490. for (auto *U : Phi->users())
  4491. WorkList.push_back(cast<Instruction>(U));
  4492. continue;
  4493. }
  4494. switch (I->getOpcode()) {
  4495. case Instruction::And: {
  4496. auto *AndC = dyn_cast<ConstantInt>(I->getOperand(1));
  4497. if (!AndC)
  4498. return false;
  4499. APInt AndBits = AndC->getValue();
  4500. DemandBits |= AndBits;
  4501. // Keep track of the widest and mask we see.
  4502. if (AndBits.ugt(WidestAndBits))
  4503. WidestAndBits = AndBits;
  4504. if (AndBits == WidestAndBits && I->getOperand(0) == Load)
  4505. AndsToMaybeRemove.push_back(I);
  4506. break;
  4507. }
  4508. case Instruction::Shl: {
  4509. auto *ShlC = dyn_cast<ConstantInt>(I->getOperand(1));
  4510. if (!ShlC)
  4511. return false;
  4512. uint64_t ShiftAmt = ShlC->getLimitedValue(BitWidth - 1);
  4513. DemandBits.setLowBits(BitWidth - ShiftAmt);
  4514. break;
  4515. }
  4516. case Instruction::Trunc: {
  4517. EVT TruncVT = TLI->getValueType(*DL, I->getType());
  4518. unsigned TruncBitWidth = TruncVT.getSizeInBits();
  4519. DemandBits.setLowBits(TruncBitWidth);
  4520. break;
  4521. }
  4522. default:
  4523. return false;
  4524. }
  4525. }
  4526. uint32_t ActiveBits = DemandBits.getActiveBits();
  4527. // Avoid hoisting (and (load x) 1) since it is unlikely to be folded by the
  4528. // target even if isLoadExtLegal says an i1 EXTLOAD is valid. For example,
  4529. // for the AArch64 target isLoadExtLegal(ZEXTLOAD, i32, i1) returns true, but
  4530. // (and (load x) 1) is not matched as a single instruction, rather as a LDR
  4531. // followed by an AND.
  4532. // TODO: Look into removing this restriction by fixing backends to either
  4533. // return false for isLoadExtLegal for i1 or have them select this pattern to
  4534. // a single instruction.
  4535. //
  4536. // Also avoid hoisting if we didn't see any ands with the exact DemandBits
  4537. // mask, since these are the only ands that will be removed by isel.
  4538. if (ActiveBits <= 1 || !DemandBits.isMask(ActiveBits) ||
  4539. WidestAndBits != DemandBits)
  4540. return false;
  4541. LLVMContext &Ctx = Load->getType()->getContext();
  4542. Type *TruncTy = Type::getIntNTy(Ctx, ActiveBits);
  4543. EVT TruncVT = TLI->getValueType(*DL, TruncTy);
  4544. // Reject cases that won't be matched as extloads.
  4545. if (!LoadResultVT.bitsGT(TruncVT) || !TruncVT.isRound() ||
  4546. !TLI->isLoadExtLegal(ISD::ZEXTLOAD, LoadResultVT, TruncVT))
  4547. return false;
  4548. IRBuilder<> Builder(Load->getNextNode());
  4549. auto *NewAnd = dyn_cast<Instruction>(
  4550. Builder.CreateAnd(Load, ConstantInt::get(Ctx, DemandBits)));
  4551. // Mark this instruction as "inserted by CGP", so that other
  4552. // optimizations don't touch it.
  4553. InsertedInsts.insert(NewAnd);
  4554. // Replace all uses of load with new and (except for the use of load in the
  4555. // new and itself).
  4556. Load->replaceAllUsesWith(NewAnd);
  4557. NewAnd->setOperand(0, Load);
  4558. // Remove any and instructions that are now redundant.
  4559. for (auto *And : AndsToMaybeRemove)
  4560. // Check that the and mask is the same as the one we decided to put on the
  4561. // new and.
  4562. if (cast<ConstantInt>(And->getOperand(1))->getValue() == DemandBits) {
  4563. And->replaceAllUsesWith(NewAnd);
  4564. if (&*CurInstIterator == And)
  4565. CurInstIterator = std::next(And->getIterator());
  4566. And->eraseFromParent();
  4567. ++NumAndUses;
  4568. }
  4569. ++NumAndsAdded;
  4570. return true;
  4571. }
  4572. /// Check if V (an operand of a select instruction) is an expensive instruction
  4573. /// that is only used once.
  4574. static bool sinkSelectOperand(const TargetTransformInfo *TTI, Value *V) {
  4575. auto *I = dyn_cast<Instruction>(V);
  4576. // If it's safe to speculatively execute, then it should not have side
  4577. // effects; therefore, it's safe to sink and possibly *not* execute.
  4578. return I && I->hasOneUse() && isSafeToSpeculativelyExecute(I) &&
  4579. TTI->getUserCost(I) >= TargetTransformInfo::TCC_Expensive;
  4580. }
  4581. /// Returns true if a SelectInst should be turned into an explicit branch.
  4582. static bool isFormingBranchFromSelectProfitable(const TargetTransformInfo *TTI,
  4583. const TargetLowering *TLI,
  4584. SelectInst *SI) {
  4585. // If even a predictable select is cheap, then a branch can't be cheaper.
  4586. if (!TLI->isPredictableSelectExpensive())
  4587. return false;
  4588. // FIXME: This should use the same heuristics as IfConversion to determine
  4589. // whether a select is better represented as a branch.
  4590. // If metadata tells us that the select condition is obviously predictable,
  4591. // then we want to replace the select with a branch.
  4592. uint64_t TrueWeight, FalseWeight;
  4593. if (SI->extractProfMetadata(TrueWeight, FalseWeight)) {
  4594. uint64_t Max = std::max(TrueWeight, FalseWeight);
  4595. uint64_t Sum = TrueWeight + FalseWeight;
  4596. if (Sum != 0) {
  4597. auto Probability = BranchProbability::getBranchProbability(Max, Sum);
  4598. if (Probability > TLI->getPredictableBranchThreshold())
  4599. return true;
  4600. }
  4601. }
  4602. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  4603. // If a branch is predictable, an out-of-order CPU can avoid blocking on its
  4604. // comparison condition. If the compare has more than one use, there's
  4605. // probably another cmov or setcc around, so it's not worth emitting a branch.
  4606. if (!Cmp || !Cmp->hasOneUse())
  4607. return false;
  4608. // If either operand of the select is expensive and only needed on one side
  4609. // of the select, we should form a branch.
  4610. if (sinkSelectOperand(TTI, SI->getTrueValue()) ||
  4611. sinkSelectOperand(TTI, SI->getFalseValue()))
  4612. return true;
  4613. return false;
  4614. }
  4615. /// If \p isTrue is true, return the true value of \p SI, otherwise return
  4616. /// false value of \p SI. If the true/false value of \p SI is defined by any
  4617. /// select instructions in \p Selects, look through the defining select
  4618. /// instruction until the true/false value is not defined in \p Selects.
  4619. static Value *getTrueOrFalseValue(
  4620. SelectInst *SI, bool isTrue,
  4621. const SmallPtrSet<const Instruction *, 2> &Selects) {
  4622. Value *V;
  4623. for (SelectInst *DefSI = SI; DefSI != nullptr && Selects.count(DefSI);
  4624. DefSI = dyn_cast<SelectInst>(V)) {
  4625. assert(DefSI->getCondition() == SI->getCondition() &&
  4626. "The condition of DefSI does not match with SI");
  4627. V = (isTrue ? DefSI->getTrueValue() : DefSI->getFalseValue());
  4628. }
  4629. return V;
  4630. }
  4631. /// If we have a SelectInst that will likely profit from branch prediction,
  4632. /// turn it into a branch.
  4633. bool CodeGenPrepare::optimizeSelectInst(SelectInst *SI) {
  4634. // Find all consecutive select instructions that share the same condition.
  4635. SmallVector<SelectInst *, 2> ASI;
  4636. ASI.push_back(SI);
  4637. for (BasicBlock::iterator It = ++BasicBlock::iterator(SI);
  4638. It != SI->getParent()->end(); ++It) {
  4639. SelectInst *I = dyn_cast<SelectInst>(&*It);
  4640. if (I && SI->getCondition() == I->getCondition()) {
  4641. ASI.push_back(I);
  4642. } else {
  4643. break;
  4644. }
  4645. }
  4646. SelectInst *LastSI = ASI.back();
  4647. // Increment the current iterator to skip all the rest of select instructions
  4648. // because they will be either "not lowered" or "all lowered" to branch.
  4649. CurInstIterator = std::next(LastSI->getIterator());
  4650. bool VectorCond = !SI->getCondition()->getType()->isIntegerTy(1);
  4651. // Can we convert the 'select' to CF ?
  4652. if (DisableSelectToBranch || OptSize || !TLI || VectorCond ||
  4653. SI->getMetadata(LLVMContext::MD_unpredictable))
  4654. return false;
  4655. TargetLowering::SelectSupportKind SelectKind;
  4656. if (VectorCond)
  4657. SelectKind = TargetLowering::VectorMaskSelect;
  4658. else if (SI->getType()->isVectorTy())
  4659. SelectKind = TargetLowering::ScalarCondVectorVal;
  4660. else
  4661. SelectKind = TargetLowering::ScalarValSelect;
  4662. if (TLI->isSelectSupported(SelectKind) &&
  4663. !isFormingBranchFromSelectProfitable(TTI, TLI, SI))
  4664. return false;
  4665. ModifiedDT = true;
  4666. // Transform a sequence like this:
  4667. // start:
  4668. // %cmp = cmp uge i32 %a, %b
  4669. // %sel = select i1 %cmp, i32 %c, i32 %d
  4670. //
  4671. // Into:
  4672. // start:
  4673. // %cmp = cmp uge i32 %a, %b
  4674. // br i1 %cmp, label %select.true, label %select.false
  4675. // select.true:
  4676. // br label %select.end
  4677. // select.false:
  4678. // br label %select.end
  4679. // select.end:
  4680. // %sel = phi i32 [ %c, %select.true ], [ %d, %select.false ]
  4681. //
  4682. // In addition, we may sink instructions that produce %c or %d from
  4683. // the entry block into the destination(s) of the new branch.
  4684. // If the true or false blocks do not contain a sunken instruction, that
  4685. // block and its branch may be optimized away. In that case, one side of the
  4686. // first branch will point directly to select.end, and the corresponding PHI
  4687. // predecessor block will be the start block.
  4688. // First, we split the block containing the select into 2 blocks.
  4689. BasicBlock *StartBlock = SI->getParent();
  4690. BasicBlock::iterator SplitPt = ++(BasicBlock::iterator(LastSI));
  4691. BasicBlock *EndBlock = StartBlock->splitBasicBlock(SplitPt, "select.end");
  4692. // Delete the unconditional branch that was just created by the split.
  4693. StartBlock->getTerminator()->eraseFromParent();
  4694. // These are the new basic blocks for the conditional branch.
  4695. // At least one will become an actual new basic block.
  4696. BasicBlock *TrueBlock = nullptr;
  4697. BasicBlock *FalseBlock = nullptr;
  4698. BranchInst *TrueBranch = nullptr;
  4699. BranchInst *FalseBranch = nullptr;
  4700. // Sink expensive instructions into the conditional blocks to avoid executing
  4701. // them speculatively.
  4702. for (SelectInst *SI : ASI) {
  4703. if (sinkSelectOperand(TTI, SI->getTrueValue())) {
  4704. if (TrueBlock == nullptr) {
  4705. TrueBlock = BasicBlock::Create(SI->getContext(), "select.true.sink",
  4706. EndBlock->getParent(), EndBlock);
  4707. TrueBranch = BranchInst::Create(EndBlock, TrueBlock);
  4708. }
  4709. auto *TrueInst = cast<Instruction>(SI->getTrueValue());
  4710. TrueInst->moveBefore(TrueBranch);
  4711. }
  4712. if (sinkSelectOperand(TTI, SI->getFalseValue())) {
  4713. if (FalseBlock == nullptr) {
  4714. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false.sink",
  4715. EndBlock->getParent(), EndBlock);
  4716. FalseBranch = BranchInst::Create(EndBlock, FalseBlock);
  4717. }
  4718. auto *FalseInst = cast<Instruction>(SI->getFalseValue());
  4719. FalseInst->moveBefore(FalseBranch);
  4720. }
  4721. }
  4722. // If there was nothing to sink, then arbitrarily choose the 'false' side
  4723. // for a new input value to the PHI.
  4724. if (TrueBlock == FalseBlock) {
  4725. assert(TrueBlock == nullptr &&
  4726. "Unexpected basic block transform while optimizing select");
  4727. FalseBlock = BasicBlock::Create(SI->getContext(), "select.false",
  4728. EndBlock->getParent(), EndBlock);
  4729. BranchInst::Create(EndBlock, FalseBlock);
  4730. }
  4731. // Insert the real conditional branch based on the original condition.
  4732. // If we did not create a new block for one of the 'true' or 'false' paths
  4733. // of the condition, it means that side of the branch goes to the end block
  4734. // directly and the path originates from the start block from the point of
  4735. // view of the new PHI.
  4736. BasicBlock *TT, *FT;
  4737. if (TrueBlock == nullptr) {
  4738. TT = EndBlock;
  4739. FT = FalseBlock;
  4740. TrueBlock = StartBlock;
  4741. } else if (FalseBlock == nullptr) {
  4742. TT = TrueBlock;
  4743. FT = EndBlock;
  4744. FalseBlock = StartBlock;
  4745. } else {
  4746. TT = TrueBlock;
  4747. FT = FalseBlock;
  4748. }
  4749. IRBuilder<>(SI).CreateCondBr(SI->getCondition(), TT, FT, SI);
  4750. SmallPtrSet<const Instruction *, 2> INS;
  4751. INS.insert(ASI.begin(), ASI.end());
  4752. // Use reverse iterator because later select may use the value of the
  4753. // earlier select, and we need to propagate value through earlier select
  4754. // to get the PHI operand.
  4755. for (auto It = ASI.rbegin(); It != ASI.rend(); ++It) {
  4756. SelectInst *SI = *It;
  4757. // The select itself is replaced with a PHI Node.
  4758. PHINode *PN = PHINode::Create(SI->getType(), 2, "", &EndBlock->front());
  4759. PN->takeName(SI);
  4760. PN->addIncoming(getTrueOrFalseValue(SI, true, INS), TrueBlock);
  4761. PN->addIncoming(getTrueOrFalseValue(SI, false, INS), FalseBlock);
  4762. SI->replaceAllUsesWith(PN);
  4763. SI->eraseFromParent();
  4764. INS.erase(SI);
  4765. ++NumSelectsExpanded;
  4766. }
  4767. // Instruct OptimizeBlock to skip to the next block.
  4768. CurInstIterator = StartBlock->end();
  4769. return true;
  4770. }
  4771. static bool isBroadcastShuffle(ShuffleVectorInst *SVI) {
  4772. SmallVector<int, 16> Mask(SVI->getShuffleMask());
  4773. int SplatElem = -1;
  4774. for (unsigned i = 0; i < Mask.size(); ++i) {
  4775. if (SplatElem != -1 && Mask[i] != -1 && Mask[i] != SplatElem)
  4776. return false;
  4777. SplatElem = Mask[i];
  4778. }
  4779. return true;
  4780. }
  4781. /// Some targets have expensive vector shifts if the lanes aren't all the same
  4782. /// (e.g. x86 only introduced "vpsllvd" and friends with AVX2). In these cases
  4783. /// it's often worth sinking a shufflevector splat down to its use so that
  4784. /// codegen can spot all lanes are identical.
  4785. bool CodeGenPrepare::optimizeShuffleVectorInst(ShuffleVectorInst *SVI) {
  4786. BasicBlock *DefBB = SVI->getParent();
  4787. // Only do this xform if variable vector shifts are particularly expensive.
  4788. if (!TLI || !TLI->isVectorShiftByScalarCheap(SVI->getType()))
  4789. return false;
  4790. // We only expect better codegen by sinking a shuffle if we can recognise a
  4791. // constant splat.
  4792. if (!isBroadcastShuffle(SVI))
  4793. return false;
  4794. // InsertedShuffles - Only insert a shuffle in each block once.
  4795. DenseMap<BasicBlock*, Instruction*> InsertedShuffles;
  4796. bool MadeChange = false;
  4797. for (User *U : SVI->users()) {
  4798. Instruction *UI = cast<Instruction>(U);
  4799. // Figure out which BB this ext is used in.
  4800. BasicBlock *UserBB = UI->getParent();
  4801. if (UserBB == DefBB) continue;
  4802. // For now only apply this when the splat is used by a shift instruction.
  4803. if (!UI->isShift()) continue;
  4804. // Everything checks out, sink the shuffle if the user's block doesn't
  4805. // already have a copy.
  4806. Instruction *&InsertedShuffle = InsertedShuffles[UserBB];
  4807. if (!InsertedShuffle) {
  4808. BasicBlock::iterator InsertPt = UserBB->getFirstInsertionPt();
  4809. assert(InsertPt != UserBB->end());
  4810. InsertedShuffle =
  4811. new ShuffleVectorInst(SVI->getOperand(0), SVI->getOperand(1),
  4812. SVI->getOperand(2), "", &*InsertPt);
  4813. }
  4814. UI->replaceUsesOfWith(SVI, InsertedShuffle);
  4815. MadeChange = true;
  4816. }
  4817. // If we removed all uses, nuke the shuffle.
  4818. if (SVI->use_empty()) {
  4819. SVI->eraseFromParent();
  4820. MadeChange = true;
  4821. }
  4822. return MadeChange;
  4823. }
  4824. bool CodeGenPrepare::optimizeSwitchInst(SwitchInst *SI) {
  4825. if (!TLI || !DL)
  4826. return false;
  4827. Value *Cond = SI->getCondition();
  4828. Type *OldType = Cond->getType();
  4829. LLVMContext &Context = Cond->getContext();
  4830. MVT RegType = TLI->getRegisterType(Context, TLI->getValueType(*DL, OldType));
  4831. unsigned RegWidth = RegType.getSizeInBits();
  4832. if (RegWidth <= cast<IntegerType>(OldType)->getBitWidth())
  4833. return false;
  4834. // If the register width is greater than the type width, expand the condition
  4835. // of the switch instruction and each case constant to the width of the
  4836. // register. By widening the type of the switch condition, subsequent
  4837. // comparisons (for case comparisons) will not need to be extended to the
  4838. // preferred register width, so we will potentially eliminate N-1 extends,
  4839. // where N is the number of cases in the switch.
  4840. auto *NewType = Type::getIntNTy(Context, RegWidth);
  4841. // Zero-extend the switch condition and case constants unless the switch
  4842. // condition is a function argument that is already being sign-extended.
  4843. // In that case, we can avoid an unnecessary mask/extension by sign-extending
  4844. // everything instead.
  4845. Instruction::CastOps ExtType = Instruction::ZExt;
  4846. if (auto *Arg = dyn_cast<Argument>(Cond))
  4847. if (Arg->hasSExtAttr())
  4848. ExtType = Instruction::SExt;
  4849. auto *ExtInst = CastInst::Create(ExtType, Cond, NewType);
  4850. ExtInst->insertBefore(SI);
  4851. SI->setCondition(ExtInst);
  4852. for (auto Case : SI->cases()) {
  4853. APInt NarrowConst = Case.getCaseValue()->getValue();
  4854. APInt WideConst = (ExtType == Instruction::ZExt) ?
  4855. NarrowConst.zext(RegWidth) : NarrowConst.sext(RegWidth);
  4856. Case.setValue(ConstantInt::get(Context, WideConst));
  4857. }
  4858. return true;
  4859. }
  4860. namespace {
  4861. /// \brief Helper class to promote a scalar operation to a vector one.
  4862. /// This class is used to move downward extractelement transition.
  4863. /// E.g.,
  4864. /// a = vector_op <2 x i32>
  4865. /// b = extractelement <2 x i32> a, i32 0
  4866. /// c = scalar_op b
  4867. /// store c
  4868. ///
  4869. /// =>
  4870. /// a = vector_op <2 x i32>
  4871. /// c = vector_op a (equivalent to scalar_op on the related lane)
  4872. /// * d = extractelement <2 x i32> c, i32 0
  4873. /// * store d
  4874. /// Assuming both extractelement and store can be combine, we get rid of the
  4875. /// transition.
  4876. class VectorPromoteHelper {
  4877. /// DataLayout associated with the current module.
  4878. const DataLayout &DL;
  4879. /// Used to perform some checks on the legality of vector operations.
  4880. const TargetLowering &TLI;
  4881. /// Used to estimated the cost of the promoted chain.
  4882. const TargetTransformInfo &TTI;
  4883. /// The transition being moved downwards.
  4884. Instruction *Transition;
  4885. /// The sequence of instructions to be promoted.
  4886. SmallVector<Instruction *, 4> InstsToBePromoted;
  4887. /// Cost of combining a store and an extract.
  4888. unsigned StoreExtractCombineCost;
  4889. /// Instruction that will be combined with the transition.
  4890. Instruction *CombineInst = nullptr;
  4891. /// \brief The instruction that represents the current end of the transition.
  4892. /// Since we are faking the promotion until we reach the end of the chain
  4893. /// of computation, we need a way to get the current end of the transition.
  4894. Instruction *getEndOfTransition() const {
  4895. if (InstsToBePromoted.empty())
  4896. return Transition;
  4897. return InstsToBePromoted.back();
  4898. }
  4899. /// \brief Return the index of the original value in the transition.
  4900. /// E.g., for "extractelement <2 x i32> c, i32 1" the original value,
  4901. /// c, is at index 0.
  4902. unsigned getTransitionOriginalValueIdx() const {
  4903. assert(isa<ExtractElementInst>(Transition) &&
  4904. "Other kind of transitions are not supported yet");
  4905. return 0;
  4906. }
  4907. /// \brief Return the index of the index in the transition.
  4908. /// E.g., for "extractelement <2 x i32> c, i32 0" the index
  4909. /// is at index 1.
  4910. unsigned getTransitionIdx() const {
  4911. assert(isa<ExtractElementInst>(Transition) &&
  4912. "Other kind of transitions are not supported yet");
  4913. return 1;
  4914. }
  4915. /// \brief Get the type of the transition.
  4916. /// This is the type of the original value.
  4917. /// E.g., for "extractelement <2 x i32> c, i32 1" the type of the
  4918. /// transition is <2 x i32>.
  4919. Type *getTransitionType() const {
  4920. return Transition->getOperand(getTransitionOriginalValueIdx())->getType();
  4921. }
  4922. /// \brief Promote \p ToBePromoted by moving \p Def downward through.
  4923. /// I.e., we have the following sequence:
  4924. /// Def = Transition <ty1> a to <ty2>
  4925. /// b = ToBePromoted <ty2> Def, ...
  4926. /// =>
  4927. /// b = ToBePromoted <ty1> a, ...
  4928. /// Def = Transition <ty1> ToBePromoted to <ty2>
  4929. void promoteImpl(Instruction *ToBePromoted);
  4930. /// \brief Check whether or not it is profitable to promote all the
  4931. /// instructions enqueued to be promoted.
  4932. bool isProfitableToPromote() {
  4933. Value *ValIdx = Transition->getOperand(getTransitionOriginalValueIdx());
  4934. unsigned Index = isa<ConstantInt>(ValIdx)
  4935. ? cast<ConstantInt>(ValIdx)->getZExtValue()
  4936. : -1;
  4937. Type *PromotedType = getTransitionType();
  4938. StoreInst *ST = cast<StoreInst>(CombineInst);
  4939. unsigned AS = ST->getPointerAddressSpace();
  4940. unsigned Align = ST->getAlignment();
  4941. // Check if this store is supported.
  4942. if (!TLI.allowsMisalignedMemoryAccesses(
  4943. TLI.getValueType(DL, ST->getValueOperand()->getType()), AS,
  4944. Align)) {
  4945. // If this is not supported, there is no way we can combine
  4946. // the extract with the store.
  4947. return false;
  4948. }
  4949. // The scalar chain of computation has to pay for the transition
  4950. // scalar to vector.
  4951. // The vector chain has to account for the combining cost.
  4952. uint64_t ScalarCost =
  4953. TTI.getVectorInstrCost(Transition->getOpcode(), PromotedType, Index);
  4954. uint64_t VectorCost = StoreExtractCombineCost;
  4955. for (const auto &Inst : InstsToBePromoted) {
  4956. // Compute the cost.
  4957. // By construction, all instructions being promoted are arithmetic ones.
  4958. // Moreover, one argument is a constant that can be viewed as a splat
  4959. // constant.
  4960. Value *Arg0 = Inst->getOperand(0);
  4961. bool IsArg0Constant = isa<UndefValue>(Arg0) || isa<ConstantInt>(Arg0) ||
  4962. isa<ConstantFP>(Arg0);
  4963. TargetTransformInfo::OperandValueKind Arg0OVK =
  4964. IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  4965. : TargetTransformInfo::OK_AnyValue;
  4966. TargetTransformInfo::OperandValueKind Arg1OVK =
  4967. !IsArg0Constant ? TargetTransformInfo::OK_UniformConstantValue
  4968. : TargetTransformInfo::OK_AnyValue;
  4969. ScalarCost += TTI.getArithmeticInstrCost(
  4970. Inst->getOpcode(), Inst->getType(), Arg0OVK, Arg1OVK);
  4971. VectorCost += TTI.getArithmeticInstrCost(Inst->getOpcode(), PromotedType,
  4972. Arg0OVK, Arg1OVK);
  4973. }
  4974. DEBUG(dbgs() << "Estimated cost of computation to be promoted:\nScalar: "
  4975. << ScalarCost << "\nVector: " << VectorCost << '\n');
  4976. return ScalarCost > VectorCost;
  4977. }
  4978. /// \brief Generate a constant vector with \p Val with the same
  4979. /// number of elements as the transition.
  4980. /// \p UseSplat defines whether or not \p Val should be replicated
  4981. /// across the whole vector.
  4982. /// In other words, if UseSplat == true, we generate <Val, Val, ..., Val>,
  4983. /// otherwise we generate a vector with as many undef as possible:
  4984. /// <undef, ..., undef, Val, undef, ..., undef> where \p Val is only
  4985. /// used at the index of the extract.
  4986. Value *getConstantVector(Constant *Val, bool UseSplat) const {
  4987. unsigned ExtractIdx = std::numeric_limits<unsigned>::max();
  4988. if (!UseSplat) {
  4989. // If we cannot determine where the constant must be, we have to
  4990. // use a splat constant.
  4991. Value *ValExtractIdx = Transition->getOperand(getTransitionIdx());
  4992. if (ConstantInt *CstVal = dyn_cast<ConstantInt>(ValExtractIdx))
  4993. ExtractIdx = CstVal->getSExtValue();
  4994. else
  4995. UseSplat = true;
  4996. }
  4997. unsigned End = getTransitionType()->getVectorNumElements();
  4998. if (UseSplat)
  4999. return ConstantVector::getSplat(End, Val);
  5000. SmallVector<Constant *, 4> ConstVec;
  5001. UndefValue *UndefVal = UndefValue::get(Val->getType());
  5002. for (unsigned Idx = 0; Idx != End; ++Idx) {
  5003. if (Idx == ExtractIdx)
  5004. ConstVec.push_back(Val);
  5005. else
  5006. ConstVec.push_back(UndefVal);
  5007. }
  5008. return ConstantVector::get(ConstVec);
  5009. }
  5010. /// \brief Check if promoting to a vector type an operand at \p OperandIdx
  5011. /// in \p Use can trigger undefined behavior.
  5012. static bool canCauseUndefinedBehavior(const Instruction *Use,
  5013. unsigned OperandIdx) {
  5014. // This is not safe to introduce undef when the operand is on
  5015. // the right hand side of a division-like instruction.
  5016. if (OperandIdx != 1)
  5017. return false;
  5018. switch (Use->getOpcode()) {
  5019. default:
  5020. return false;
  5021. case Instruction::SDiv:
  5022. case Instruction::UDiv:
  5023. case Instruction::SRem:
  5024. case Instruction::URem:
  5025. return true;
  5026. case Instruction::FDiv:
  5027. case Instruction::FRem:
  5028. return !Use->hasNoNaNs();
  5029. }
  5030. llvm_unreachable(nullptr);
  5031. }
  5032. public:
  5033. VectorPromoteHelper(const DataLayout &DL, const TargetLowering &TLI,
  5034. const TargetTransformInfo &TTI, Instruction *Transition,
  5035. unsigned CombineCost)
  5036. : DL(DL), TLI(TLI), TTI(TTI), Transition(Transition),
  5037. StoreExtractCombineCost(CombineCost) {
  5038. assert(Transition && "Do not know how to promote null");
  5039. }
  5040. /// \brief Check if we can promote \p ToBePromoted to \p Type.
  5041. bool canPromote(const Instruction *ToBePromoted) const {
  5042. // We could support CastInst too.
  5043. return isa<BinaryOperator>(ToBePromoted);
  5044. }
  5045. /// \brief Check if it is profitable to promote \p ToBePromoted
  5046. /// by moving downward the transition through.
  5047. bool shouldPromote(const Instruction *ToBePromoted) const {
  5048. // Promote only if all the operands can be statically expanded.
  5049. // Indeed, we do not want to introduce any new kind of transitions.
  5050. for (const Use &U : ToBePromoted->operands()) {
  5051. const Value *Val = U.get();
  5052. if (Val == getEndOfTransition()) {
  5053. // If the use is a division and the transition is on the rhs,
  5054. // we cannot promote the operation, otherwise we may create a
  5055. // division by zero.
  5056. if (canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()))
  5057. return false;
  5058. continue;
  5059. }
  5060. if (!isa<ConstantInt>(Val) && !isa<UndefValue>(Val) &&
  5061. !isa<ConstantFP>(Val))
  5062. return false;
  5063. }
  5064. // Check that the resulting operation is legal.
  5065. int ISDOpcode = TLI.InstructionOpcodeToISD(ToBePromoted->getOpcode());
  5066. if (!ISDOpcode)
  5067. return false;
  5068. return StressStoreExtract ||
  5069. TLI.isOperationLegalOrCustom(
  5070. ISDOpcode, TLI.getValueType(DL, getTransitionType(), true));
  5071. }
  5072. /// \brief Check whether or not \p Use can be combined
  5073. /// with the transition.
  5074. /// I.e., is it possible to do Use(Transition) => AnotherUse?
  5075. bool canCombine(const Instruction *Use) { return isa<StoreInst>(Use); }
  5076. /// \brief Record \p ToBePromoted as part of the chain to be promoted.
  5077. void enqueueForPromotion(Instruction *ToBePromoted) {
  5078. InstsToBePromoted.push_back(ToBePromoted);
  5079. }
  5080. /// \brief Set the instruction that will be combined with the transition.
  5081. void recordCombineInstruction(Instruction *ToBeCombined) {
  5082. assert(canCombine(ToBeCombined) && "Unsupported instruction to combine");
  5083. CombineInst = ToBeCombined;
  5084. }
  5085. /// \brief Promote all the instructions enqueued for promotion if it is
  5086. /// is profitable.
  5087. /// \return True if the promotion happened, false otherwise.
  5088. bool promote() {
  5089. // Check if there is something to promote.
  5090. // Right now, if we do not have anything to combine with,
  5091. // we assume the promotion is not profitable.
  5092. if (InstsToBePromoted.empty() || !CombineInst)
  5093. return false;
  5094. // Check cost.
  5095. if (!StressStoreExtract && !isProfitableToPromote())
  5096. return false;
  5097. // Promote.
  5098. for (auto &ToBePromoted : InstsToBePromoted)
  5099. promoteImpl(ToBePromoted);
  5100. InstsToBePromoted.clear();
  5101. return true;
  5102. }
  5103. };
  5104. } // end anonymous namespace
  5105. void VectorPromoteHelper::promoteImpl(Instruction *ToBePromoted) {
  5106. // At this point, we know that all the operands of ToBePromoted but Def
  5107. // can be statically promoted.
  5108. // For Def, we need to use its parameter in ToBePromoted:
  5109. // b = ToBePromoted ty1 a
  5110. // Def = Transition ty1 b to ty2
  5111. // Move the transition down.
  5112. // 1. Replace all uses of the promoted operation by the transition.
  5113. // = ... b => = ... Def.
  5114. assert(ToBePromoted->getType() == Transition->getType() &&
  5115. "The type of the result of the transition does not match "
  5116. "the final type");
  5117. ToBePromoted->replaceAllUsesWith(Transition);
  5118. // 2. Update the type of the uses.
  5119. // b = ToBePromoted ty2 Def => b = ToBePromoted ty1 Def.
  5120. Type *TransitionTy = getTransitionType();
  5121. ToBePromoted->mutateType(TransitionTy);
  5122. // 3. Update all the operands of the promoted operation with promoted
  5123. // operands.
  5124. // b = ToBePromoted ty1 Def => b = ToBePromoted ty1 a.
  5125. for (Use &U : ToBePromoted->operands()) {
  5126. Value *Val = U.get();
  5127. Value *NewVal = nullptr;
  5128. if (Val == Transition)
  5129. NewVal = Transition->getOperand(getTransitionOriginalValueIdx());
  5130. else if (isa<UndefValue>(Val) || isa<ConstantInt>(Val) ||
  5131. isa<ConstantFP>(Val)) {
  5132. // Use a splat constant if it is not safe to use undef.
  5133. NewVal = getConstantVector(
  5134. cast<Constant>(Val),
  5135. isa<UndefValue>(Val) ||
  5136. canCauseUndefinedBehavior(ToBePromoted, U.getOperandNo()));
  5137. } else
  5138. llvm_unreachable("Did you modified shouldPromote and forgot to update "
  5139. "this?");
  5140. ToBePromoted->setOperand(U.getOperandNo(), NewVal);
  5141. }
  5142. Transition->moveAfter(ToBePromoted);
  5143. Transition->setOperand(getTransitionOriginalValueIdx(), ToBePromoted);
  5144. }
  5145. /// Some targets can do store(extractelement) with one instruction.
  5146. /// Try to push the extractelement towards the stores when the target
  5147. /// has this feature and this is profitable.
  5148. bool CodeGenPrepare::optimizeExtractElementInst(Instruction *Inst) {
  5149. unsigned CombineCost = std::numeric_limits<unsigned>::max();
  5150. if (DisableStoreExtract || !TLI ||
  5151. (!StressStoreExtract &&
  5152. !TLI->canCombineStoreAndExtract(Inst->getOperand(0)->getType(),
  5153. Inst->getOperand(1), CombineCost)))
  5154. return false;
  5155. // At this point we know that Inst is a vector to scalar transition.
  5156. // Try to move it down the def-use chain, until:
  5157. // - We can combine the transition with its single use
  5158. // => we got rid of the transition.
  5159. // - We escape the current basic block
  5160. // => we would need to check that we are moving it at a cheaper place and
  5161. // we do not do that for now.
  5162. BasicBlock *Parent = Inst->getParent();
  5163. DEBUG(dbgs() << "Found an interesting transition: " << *Inst << '\n');
  5164. VectorPromoteHelper VPH(*DL, *TLI, *TTI, Inst, CombineCost);
  5165. // If the transition has more than one use, assume this is not going to be
  5166. // beneficial.
  5167. while (Inst->hasOneUse()) {
  5168. Instruction *ToBePromoted = cast<Instruction>(*Inst->user_begin());
  5169. DEBUG(dbgs() << "Use: " << *ToBePromoted << '\n');
  5170. if (ToBePromoted->getParent() != Parent) {
  5171. DEBUG(dbgs() << "Instruction to promote is in a different block ("
  5172. << ToBePromoted->getParent()->getName()
  5173. << ") than the transition (" << Parent->getName() << ").\n");
  5174. return false;
  5175. }
  5176. if (VPH.canCombine(ToBePromoted)) {
  5177. DEBUG(dbgs() << "Assume " << *Inst << '\n'
  5178. << "will be combined with: " << *ToBePromoted << '\n');
  5179. VPH.recordCombineInstruction(ToBePromoted);
  5180. bool Changed = VPH.promote();
  5181. NumStoreExtractExposed += Changed;
  5182. return Changed;
  5183. }
  5184. DEBUG(dbgs() << "Try promoting.\n");
  5185. if (!VPH.canPromote(ToBePromoted) || !VPH.shouldPromote(ToBePromoted))
  5186. return false;
  5187. DEBUG(dbgs() << "Promoting is possible... Enqueue for promotion!\n");
  5188. VPH.enqueueForPromotion(ToBePromoted);
  5189. Inst = ToBePromoted;
  5190. }
  5191. return false;
  5192. }
  5193. /// For the instruction sequence of store below, F and I values
  5194. /// are bundled together as an i64 value before being stored into memory.
  5195. /// Sometimes it is more efficent to generate separate stores for F and I,
  5196. /// which can remove the bitwise instructions or sink them to colder places.
  5197. ///
  5198. /// (store (or (zext (bitcast F to i32) to i64),
  5199. /// (shl (zext I to i64), 32)), addr) -->
  5200. /// (store F, addr) and (store I, addr+4)
  5201. ///
  5202. /// Similarly, splitting for other merged store can also be beneficial, like:
  5203. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  5204. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  5205. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  5206. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  5207. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  5208. ///
  5209. /// We allow each target to determine specifically which kind of splitting is
  5210. /// supported.
  5211. ///
  5212. /// The store patterns are commonly seen from the simple code snippet below
  5213. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  5214. /// void goo(const std::pair<int, float> &);
  5215. /// hoo() {
  5216. /// ...
  5217. /// goo(std::make_pair(tmp, ftmp));
  5218. /// ...
  5219. /// }
  5220. ///
  5221. /// Although we already have similar splitting in DAG Combine, we duplicate
  5222. /// it in CodeGenPrepare to catch the case in which pattern is across
  5223. /// multiple BBs. The logic in DAG Combine is kept to catch case generated
  5224. /// during code expansion.
  5225. static bool splitMergedValStore(StoreInst &SI, const DataLayout &DL,
  5226. const TargetLowering &TLI) {
  5227. // Handle simple but common cases only.
  5228. Type *StoreType = SI.getValueOperand()->getType();
  5229. if (DL.getTypeStoreSizeInBits(StoreType) != DL.getTypeSizeInBits(StoreType) ||
  5230. DL.getTypeSizeInBits(StoreType) == 0)
  5231. return false;
  5232. unsigned HalfValBitSize = DL.getTypeSizeInBits(StoreType) / 2;
  5233. Type *SplitStoreType = Type::getIntNTy(SI.getContext(), HalfValBitSize);
  5234. if (DL.getTypeStoreSizeInBits(SplitStoreType) !=
  5235. DL.getTypeSizeInBits(SplitStoreType))
  5236. return false;
  5237. // Match the following patterns:
  5238. // (store (or (zext LValue to i64),
  5239. // (shl (zext HValue to i64), 32)), HalfValBitSize)
  5240. // or
  5241. // (store (or (shl (zext HValue to i64), 32)), HalfValBitSize)
  5242. // (zext LValue to i64),
  5243. // Expect both operands of OR and the first operand of SHL have only
  5244. // one use.
  5245. Value *LValue, *HValue;
  5246. if (!match(SI.getValueOperand(),
  5247. m_c_Or(m_OneUse(m_ZExt(m_Value(LValue))),
  5248. m_OneUse(m_Shl(m_OneUse(m_ZExt(m_Value(HValue))),
  5249. m_SpecificInt(HalfValBitSize))))))
  5250. return false;
  5251. // Check LValue and HValue are int with size less or equal than 32.
  5252. if (!LValue->getType()->isIntegerTy() ||
  5253. DL.getTypeSizeInBits(LValue->getType()) > HalfValBitSize ||
  5254. !HValue->getType()->isIntegerTy() ||
  5255. DL.getTypeSizeInBits(HValue->getType()) > HalfValBitSize)
  5256. return false;
  5257. // If LValue/HValue is a bitcast instruction, use the EVT before bitcast
  5258. // as the input of target query.
  5259. auto *LBC = dyn_cast<BitCastInst>(LValue);
  5260. auto *HBC = dyn_cast<BitCastInst>(HValue);
  5261. EVT LowTy = LBC ? EVT::getEVT(LBC->getOperand(0)->getType())
  5262. : EVT::getEVT(LValue->getType());
  5263. EVT HighTy = HBC ? EVT::getEVT(HBC->getOperand(0)->getType())
  5264. : EVT::getEVT(HValue->getType());
  5265. if (!ForceSplitStore && !TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  5266. return false;
  5267. // Start to split store.
  5268. IRBuilder<> Builder(SI.getContext());
  5269. Builder.SetInsertPoint(&SI);
  5270. // If LValue/HValue is a bitcast in another BB, create a new one in current
  5271. // BB so it may be merged with the splitted stores by dag combiner.
  5272. if (LBC && LBC->getParent() != SI.getParent())
  5273. LValue = Builder.CreateBitCast(LBC->getOperand(0), LBC->getType());
  5274. if (HBC && HBC->getParent() != SI.getParent())
  5275. HValue = Builder.CreateBitCast(HBC->getOperand(0), HBC->getType());
  5276. bool IsLE = SI.getModule()->getDataLayout().isLittleEndian();
  5277. auto CreateSplitStore = [&](Value *V, bool Upper) {
  5278. V = Builder.CreateZExtOrBitCast(V, SplitStoreType);
  5279. Value *Addr = Builder.CreateBitCast(
  5280. SI.getOperand(1),
  5281. SplitStoreType->getPointerTo(SI.getPointerAddressSpace()));
  5282. if ((IsLE && Upper) || (!IsLE && !Upper))
  5283. Addr = Builder.CreateGEP(
  5284. SplitStoreType, Addr,
  5285. ConstantInt::get(Type::getInt32Ty(SI.getContext()), 1));
  5286. Builder.CreateAlignedStore(
  5287. V, Addr, Upper ? SI.getAlignment() / 2 : SI.getAlignment());
  5288. };
  5289. CreateSplitStore(LValue, false);
  5290. CreateSplitStore(HValue, true);
  5291. // Delete the old store.
  5292. SI.eraseFromParent();
  5293. return true;
  5294. }
  5295. // Return true if the GEP has two operands, the first operand is of a sequential
  5296. // type, and the second operand is a constant.
  5297. static bool GEPSequentialConstIndexed(GetElementPtrInst *GEP) {
  5298. gep_type_iterator I = gep_type_begin(*GEP);
  5299. return GEP->getNumOperands() == 2 &&
  5300. I.isSequential() &&
  5301. isa<ConstantInt>(GEP->getOperand(1));
  5302. }
  5303. // Try unmerging GEPs to reduce liveness interference (register pressure) across
  5304. // IndirectBr edges. Since IndirectBr edges tend to touch on many blocks,
  5305. // reducing liveness interference across those edges benefits global register
  5306. // allocation. Currently handles only certain cases.
  5307. //
  5308. // For example, unmerge %GEPI and %UGEPI as below.
  5309. //
  5310. // ---------- BEFORE ----------
  5311. // SrcBlock:
  5312. // ...
  5313. // %GEPIOp = ...
  5314. // ...
  5315. // %GEPI = gep %GEPIOp, Idx
  5316. // ...
  5317. // indirectbr ... [ label %DstB0, label %DstB1, ... label %DstBi ... ]
  5318. // (* %GEPI is alive on the indirectbr edges due to other uses ahead)
  5319. // (* %GEPIOp is alive on the indirectbr edges only because of it's used by
  5320. // %UGEPI)
  5321. //
  5322. // DstB0: ... (there may be a gep similar to %UGEPI to be unmerged)
  5323. // DstB1: ... (there may be a gep similar to %UGEPI to be unmerged)
  5324. // ...
  5325. //
  5326. // DstBi:
  5327. // ...
  5328. // %UGEPI = gep %GEPIOp, UIdx
  5329. // ...
  5330. // ---------------------------
  5331. //
  5332. // ---------- AFTER ----------
  5333. // SrcBlock:
  5334. // ... (same as above)
  5335. // (* %GEPI is still alive on the indirectbr edges)
  5336. // (* %GEPIOp is no longer alive on the indirectbr edges as a result of the
  5337. // unmerging)
  5338. // ...
  5339. //
  5340. // DstBi:
  5341. // ...
  5342. // %UGEPI = gep %GEPI, (UIdx-Idx)
  5343. // ...
  5344. // ---------------------------
  5345. //
  5346. // The register pressure on the IndirectBr edges is reduced because %GEPIOp is
  5347. // no longer alive on them.
  5348. //
  5349. // We try to unmerge GEPs here in CodGenPrepare, as opposed to limiting merging
  5350. // of GEPs in the first place in InstCombiner::visitGetElementPtrInst() so as
  5351. // not to disable further simplications and optimizations as a result of GEP
  5352. // merging.
  5353. //
  5354. // Note this unmerging may increase the length of the data flow critical path
  5355. // (the path from %GEPIOp to %UGEPI would go through %GEPI), which is a tradeoff
  5356. // between the register pressure and the length of data-flow critical
  5357. // path. Restricting this to the uncommon IndirectBr case would minimize the
  5358. // impact of potentially longer critical path, if any, and the impact on compile
  5359. // time.
  5360. static bool tryUnmergingGEPsAcrossIndirectBr(GetElementPtrInst *GEPI,
  5361. const TargetTransformInfo *TTI) {
  5362. BasicBlock *SrcBlock = GEPI->getParent();
  5363. // Check that SrcBlock ends with an IndirectBr. If not, give up. The common
  5364. // (non-IndirectBr) cases exit early here.
  5365. if (!isa<IndirectBrInst>(SrcBlock->getTerminator()))
  5366. return false;
  5367. // Check that GEPI is a simple gep with a single constant index.
  5368. if (!GEPSequentialConstIndexed(GEPI))
  5369. return false;
  5370. ConstantInt *GEPIIdx = cast<ConstantInt>(GEPI->getOperand(1));
  5371. // Check that GEPI is a cheap one.
  5372. if (TTI->getIntImmCost(GEPIIdx->getValue(), GEPIIdx->getType())
  5373. > TargetTransformInfo::TCC_Basic)
  5374. return false;
  5375. Value *GEPIOp = GEPI->getOperand(0);
  5376. // Check that GEPIOp is an instruction that's also defined in SrcBlock.
  5377. if (!isa<Instruction>(GEPIOp))
  5378. return false;
  5379. auto *GEPIOpI = cast<Instruction>(GEPIOp);
  5380. if (GEPIOpI->getParent() != SrcBlock)
  5381. return false;
  5382. // Check that GEP is used outside the block, meaning it's alive on the
  5383. // IndirectBr edge(s).
  5384. if (find_if(GEPI->users(), [&](User *Usr) {
  5385. if (auto *I = dyn_cast<Instruction>(Usr)) {
  5386. if (I->getParent() != SrcBlock) {
  5387. return true;
  5388. }
  5389. }
  5390. return false;
  5391. }) == GEPI->users().end())
  5392. return false;
  5393. // The second elements of the GEP chains to be unmerged.
  5394. std::vector<GetElementPtrInst *> UGEPIs;
  5395. // Check each user of GEPIOp to check if unmerging would make GEPIOp not alive
  5396. // on IndirectBr edges.
  5397. for (User *Usr : GEPIOp->users()) {
  5398. if (Usr == GEPI) continue;
  5399. // Check if Usr is an Instruction. If not, give up.
  5400. if (!isa<Instruction>(Usr))
  5401. return false;
  5402. auto *UI = cast<Instruction>(Usr);
  5403. // Check if Usr in the same block as GEPIOp, which is fine, skip.
  5404. if (UI->getParent() == SrcBlock)
  5405. continue;
  5406. // Check if Usr is a GEP. If not, give up.
  5407. if (!isa<GetElementPtrInst>(Usr))
  5408. return false;
  5409. auto *UGEPI = cast<GetElementPtrInst>(Usr);
  5410. // Check if UGEPI is a simple gep with a single constant index and GEPIOp is
  5411. // the pointer operand to it. If so, record it in the vector. If not, give
  5412. // up.
  5413. if (!GEPSequentialConstIndexed(UGEPI))
  5414. return false;
  5415. if (UGEPI->getOperand(0) != GEPIOp)
  5416. return false;
  5417. if (GEPIIdx->getType() !=
  5418. cast<ConstantInt>(UGEPI->getOperand(1))->getType())
  5419. return false;
  5420. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  5421. if (TTI->getIntImmCost(UGEPIIdx->getValue(), UGEPIIdx->getType())
  5422. > TargetTransformInfo::TCC_Basic)
  5423. return false;
  5424. UGEPIs.push_back(UGEPI);
  5425. }
  5426. if (UGEPIs.size() == 0)
  5427. return false;
  5428. // Check the materializing cost of (Uidx-Idx).
  5429. for (GetElementPtrInst *UGEPI : UGEPIs) {
  5430. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  5431. APInt NewIdx = UGEPIIdx->getValue() - GEPIIdx->getValue();
  5432. unsigned ImmCost = TTI->getIntImmCost(NewIdx, GEPIIdx->getType());
  5433. if (ImmCost > TargetTransformInfo::TCC_Basic)
  5434. return false;
  5435. }
  5436. // Now unmerge between GEPI and UGEPIs.
  5437. for (GetElementPtrInst *UGEPI : UGEPIs) {
  5438. UGEPI->setOperand(0, GEPI);
  5439. ConstantInt *UGEPIIdx = cast<ConstantInt>(UGEPI->getOperand(1));
  5440. Constant *NewUGEPIIdx =
  5441. ConstantInt::get(GEPIIdx->getType(),
  5442. UGEPIIdx->getValue() - GEPIIdx->getValue());
  5443. UGEPI->setOperand(1, NewUGEPIIdx);
  5444. // If GEPI is not inbounds but UGEPI is inbounds, change UGEPI to not
  5445. // inbounds to avoid UB.
  5446. if (!GEPI->isInBounds()) {
  5447. UGEPI->setIsInBounds(false);
  5448. }
  5449. }
  5450. // After unmerging, verify that GEPIOp is actually only used in SrcBlock (not
  5451. // alive on IndirectBr edges).
  5452. assert(find_if(GEPIOp->users(), [&](User *Usr) {
  5453. return cast<Instruction>(Usr)->getParent() != SrcBlock;
  5454. }) == GEPIOp->users().end() && "GEPIOp is used outside SrcBlock");
  5455. return true;
  5456. }
  5457. bool CodeGenPrepare::optimizeInst(Instruction *I, bool &ModifiedDT) {
  5458. // Bail out if we inserted the instruction to prevent optimizations from
  5459. // stepping on each other's toes.
  5460. if (InsertedInsts.count(I))
  5461. return false;
  5462. if (PHINode *P = dyn_cast<PHINode>(I)) {
  5463. // It is possible for very late stage optimizations (such as SimplifyCFG)
  5464. // to introduce PHI nodes too late to be cleaned up. If we detect such a
  5465. // trivial PHI, go ahead and zap it here.
  5466. if (Value *V = SimplifyInstruction(P, {*DL, TLInfo})) {
  5467. P->replaceAllUsesWith(V);
  5468. P->eraseFromParent();
  5469. ++NumPHIsElim;
  5470. return true;
  5471. }
  5472. return false;
  5473. }
  5474. if (CastInst *CI = dyn_cast<CastInst>(I)) {
  5475. // If the source of the cast is a constant, then this should have
  5476. // already been constant folded. The only reason NOT to constant fold
  5477. // it is if something (e.g. LSR) was careful to place the constant
  5478. // evaluation in a block other than then one that uses it (e.g. to hoist
  5479. // the address of globals out of a loop). If this is the case, we don't
  5480. // want to forward-subst the cast.
  5481. if (isa<Constant>(CI->getOperand(0)))
  5482. return false;
  5483. if (TLI && OptimizeNoopCopyExpression(CI, *TLI, *DL))
  5484. return true;
  5485. if (isa<ZExtInst>(I) || isa<SExtInst>(I)) {
  5486. /// Sink a zext or sext into its user blocks if the target type doesn't
  5487. /// fit in one register
  5488. if (TLI &&
  5489. TLI->getTypeAction(CI->getContext(),
  5490. TLI->getValueType(*DL, CI->getType())) ==
  5491. TargetLowering::TypeExpandInteger) {
  5492. return SinkCast(CI);
  5493. } else {
  5494. bool MadeChange = optimizeExt(I);
  5495. return MadeChange | optimizeExtUses(I);
  5496. }
  5497. }
  5498. return false;
  5499. }
  5500. if (CmpInst *CI = dyn_cast<CmpInst>(I))
  5501. if (!TLI || !TLI->hasMultipleConditionRegisters())
  5502. return OptimizeCmpExpression(CI, TLI);
  5503. if (LoadInst *LI = dyn_cast<LoadInst>(I)) {
  5504. LI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  5505. if (TLI) {
  5506. bool Modified = optimizeLoadExt(LI);
  5507. unsigned AS = LI->getPointerAddressSpace();
  5508. Modified |= optimizeMemoryInst(I, I->getOperand(0), LI->getType(), AS);
  5509. return Modified;
  5510. }
  5511. return false;
  5512. }
  5513. if (StoreInst *SI = dyn_cast<StoreInst>(I)) {
  5514. if (TLI && splitMergedValStore(*SI, *DL, *TLI))
  5515. return true;
  5516. SI->setMetadata(LLVMContext::MD_invariant_group, nullptr);
  5517. if (TLI) {
  5518. unsigned AS = SI->getPointerAddressSpace();
  5519. return optimizeMemoryInst(I, SI->getOperand(1),
  5520. SI->getOperand(0)->getType(), AS);
  5521. }
  5522. return false;
  5523. }
  5524. if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(I)) {
  5525. unsigned AS = RMW->getPointerAddressSpace();
  5526. return optimizeMemoryInst(I, RMW->getPointerOperand(),
  5527. RMW->getType(), AS);
  5528. }
  5529. if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(I)) {
  5530. unsigned AS = CmpX->getPointerAddressSpace();
  5531. return optimizeMemoryInst(I, CmpX->getPointerOperand(),
  5532. CmpX->getCompareOperand()->getType(), AS);
  5533. }
  5534. BinaryOperator *BinOp = dyn_cast<BinaryOperator>(I);
  5535. if (BinOp && (BinOp->getOpcode() == Instruction::And) &&
  5536. EnableAndCmpSinking && TLI)
  5537. return sinkAndCmp0Expression(BinOp, *TLI, InsertedInsts);
  5538. if (BinOp && (BinOp->getOpcode() == Instruction::AShr ||
  5539. BinOp->getOpcode() == Instruction::LShr)) {
  5540. ConstantInt *CI = dyn_cast<ConstantInt>(BinOp->getOperand(1));
  5541. if (TLI && CI && TLI->hasExtractBitsInsn())
  5542. return OptimizeExtractBits(BinOp, CI, *TLI, *DL);
  5543. return false;
  5544. }
  5545. if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(I)) {
  5546. if (GEPI->hasAllZeroIndices()) {
  5547. /// The GEP operand must be a pointer, so must its result -> BitCast
  5548. Instruction *NC = new BitCastInst(GEPI->getOperand(0), GEPI->getType(),
  5549. GEPI->getName(), GEPI);
  5550. GEPI->replaceAllUsesWith(NC);
  5551. GEPI->eraseFromParent();
  5552. ++NumGEPsElim;
  5553. optimizeInst(NC, ModifiedDT);
  5554. return true;
  5555. }
  5556. if (tryUnmergingGEPsAcrossIndirectBr(GEPI, TTI)) {
  5557. return true;
  5558. }
  5559. return false;
  5560. }
  5561. if (CallInst *CI = dyn_cast<CallInst>(I))
  5562. return optimizeCallInst(CI, ModifiedDT);
  5563. if (SelectInst *SI = dyn_cast<SelectInst>(I))
  5564. return optimizeSelectInst(SI);
  5565. if (ShuffleVectorInst *SVI = dyn_cast<ShuffleVectorInst>(I))
  5566. return optimizeShuffleVectorInst(SVI);
  5567. if (auto *Switch = dyn_cast<SwitchInst>(I))
  5568. return optimizeSwitchInst(Switch);
  5569. if (isa<ExtractElementInst>(I))
  5570. return optimizeExtractElementInst(I);
  5571. return false;
  5572. }
  5573. /// Given an OR instruction, check to see if this is a bitreverse
  5574. /// idiom. If so, insert the new intrinsic and return true.
  5575. static bool makeBitReverse(Instruction &I, const DataLayout &DL,
  5576. const TargetLowering &TLI) {
  5577. if (!I.getType()->isIntegerTy() ||
  5578. !TLI.isOperationLegalOrCustom(ISD::BITREVERSE,
  5579. TLI.getValueType(DL, I.getType(), true)))
  5580. return false;
  5581. SmallVector<Instruction*, 4> Insts;
  5582. if (!recognizeBSwapOrBitReverseIdiom(&I, false, true, Insts))
  5583. return false;
  5584. Instruction *LastInst = Insts.back();
  5585. I.replaceAllUsesWith(LastInst);
  5586. RecursivelyDeleteTriviallyDeadInstructions(&I);
  5587. return true;
  5588. }
  5589. // In this pass we look for GEP and cast instructions that are used
  5590. // across basic blocks and rewrite them to improve basic-block-at-a-time
  5591. // selection.
  5592. bool CodeGenPrepare::optimizeBlock(BasicBlock &BB, bool &ModifiedDT) {
  5593. SunkAddrs.clear();
  5594. bool MadeChange = false;
  5595. CurInstIterator = BB.begin();
  5596. while (CurInstIterator != BB.end()) {
  5597. MadeChange |= optimizeInst(&*CurInstIterator++, ModifiedDT);
  5598. if (ModifiedDT)
  5599. return true;
  5600. }
  5601. bool MadeBitReverse = true;
  5602. while (TLI && MadeBitReverse) {
  5603. MadeBitReverse = false;
  5604. for (auto &I : reverse(BB)) {
  5605. if (makeBitReverse(I, *DL, *TLI)) {
  5606. MadeBitReverse = MadeChange = true;
  5607. ModifiedDT = true;
  5608. break;
  5609. }
  5610. }
  5611. }
  5612. MadeChange |= dupRetToEnableTailCallOpts(&BB);
  5613. return MadeChange;
  5614. }
  5615. // llvm.dbg.value is far away from the value then iSel may not be able
  5616. // handle it properly. iSel will drop llvm.dbg.value if it can not
  5617. // find a node corresponding to the value.
  5618. bool CodeGenPrepare::placeDbgValues(Function &F) {
  5619. bool MadeChange = false;
  5620. for (BasicBlock &BB : F) {
  5621. Instruction *PrevNonDbgInst = nullptr;
  5622. for (BasicBlock::iterator BI = BB.begin(), BE = BB.end(); BI != BE;) {
  5623. Instruction *Insn = &*BI++;
  5624. DbgValueInst *DVI = dyn_cast<DbgValueInst>(Insn);
  5625. // Leave dbg.values that refer to an alloca alone. These
  5626. // intrinsics describe the address of a variable (= the alloca)
  5627. // being taken. They should not be moved next to the alloca
  5628. // (and to the beginning of the scope), but rather stay close to
  5629. // where said address is used.
  5630. if (!DVI || (DVI->getValue() && isa<AllocaInst>(DVI->getValue()))) {
  5631. PrevNonDbgInst = Insn;
  5632. continue;
  5633. }
  5634. Instruction *VI = dyn_cast_or_null<Instruction>(DVI->getValue());
  5635. if (VI && VI != PrevNonDbgInst && !VI->isTerminator()) {
  5636. // If VI is a phi in a block with an EHPad terminator, we can't insert
  5637. // after it.
  5638. if (isa<PHINode>(VI) && VI->getParent()->getTerminator()->isEHPad())
  5639. continue;
  5640. DEBUG(dbgs() << "Moving Debug Value before :\n" << *DVI << ' ' << *VI);
  5641. DVI->removeFromParent();
  5642. if (isa<PHINode>(VI))
  5643. DVI->insertBefore(&*VI->getParent()->getFirstInsertionPt());
  5644. else
  5645. DVI->insertAfter(VI);
  5646. MadeChange = true;
  5647. ++NumDbgValueMoved;
  5648. }
  5649. }
  5650. }
  5651. return MadeChange;
  5652. }
  5653. /// \brief Scale down both weights to fit into uint32_t.
  5654. static void scaleWeights(uint64_t &NewTrue, uint64_t &NewFalse) {
  5655. uint64_t NewMax = (NewTrue > NewFalse) ? NewTrue : NewFalse;
  5656. uint32_t Scale = (NewMax / std::numeric_limits<uint32_t>::max()) + 1;
  5657. NewTrue = NewTrue / Scale;
  5658. NewFalse = NewFalse / Scale;
  5659. }
  5660. /// \brief Some targets prefer to split a conditional branch like:
  5661. /// \code
  5662. /// %0 = icmp ne i32 %a, 0
  5663. /// %1 = icmp ne i32 %b, 0
  5664. /// %or.cond = or i1 %0, %1
  5665. /// br i1 %or.cond, label %TrueBB, label %FalseBB
  5666. /// \endcode
  5667. /// into multiple branch instructions like:
  5668. /// \code
  5669. /// bb1:
  5670. /// %0 = icmp ne i32 %a, 0
  5671. /// br i1 %0, label %TrueBB, label %bb2
  5672. /// bb2:
  5673. /// %1 = icmp ne i32 %b, 0
  5674. /// br i1 %1, label %TrueBB, label %FalseBB
  5675. /// \endcode
  5676. /// This usually allows instruction selection to do even further optimizations
  5677. /// and combine the compare with the branch instruction. Currently this is
  5678. /// applied for targets which have "cheap" jump instructions.
  5679. ///
  5680. /// FIXME: Remove the (equivalent?) implementation in SelectionDAG.
  5681. ///
  5682. bool CodeGenPrepare::splitBranchCondition(Function &F) {
  5683. if (!TM || !TM->Options.EnableFastISel || !TLI || TLI->isJumpExpensive())
  5684. return false;
  5685. bool MadeChange = false;
  5686. for (auto &BB : F) {
  5687. // Does this BB end with the following?
  5688. // %cond1 = icmp|fcmp|binary instruction ...
  5689. // %cond2 = icmp|fcmp|binary instruction ...
  5690. // %cond.or = or|and i1 %cond1, cond2
  5691. // br i1 %cond.or label %dest1, label %dest2"
  5692. BinaryOperator *LogicOp;
  5693. BasicBlock *TBB, *FBB;
  5694. if (!match(BB.getTerminator(), m_Br(m_OneUse(m_BinOp(LogicOp)), TBB, FBB)))
  5695. continue;
  5696. auto *Br1 = cast<BranchInst>(BB.getTerminator());
  5697. if (Br1->getMetadata(LLVMContext::MD_unpredictable))
  5698. continue;
  5699. unsigned Opc;
  5700. Value *Cond1, *Cond2;
  5701. if (match(LogicOp, m_And(m_OneUse(m_Value(Cond1)),
  5702. m_OneUse(m_Value(Cond2)))))
  5703. Opc = Instruction::And;
  5704. else if (match(LogicOp, m_Or(m_OneUse(m_Value(Cond1)),
  5705. m_OneUse(m_Value(Cond2)))))
  5706. Opc = Instruction::Or;
  5707. else
  5708. continue;
  5709. if (!match(Cond1, m_CombineOr(m_Cmp(), m_BinOp())) ||
  5710. !match(Cond2, m_CombineOr(m_Cmp(), m_BinOp())) )
  5711. continue;
  5712. DEBUG(dbgs() << "Before branch condition splitting\n"; BB.dump());
  5713. // Create a new BB.
  5714. auto TmpBB =
  5715. BasicBlock::Create(BB.getContext(), BB.getName() + ".cond.split",
  5716. BB.getParent(), BB.getNextNode());
  5717. // Update original basic block by using the first condition directly by the
  5718. // branch instruction and removing the no longer needed and/or instruction.
  5719. Br1->setCondition(Cond1);
  5720. LogicOp->eraseFromParent();
  5721. // Depending on the conditon we have to either replace the true or the false
  5722. // successor of the original branch instruction.
  5723. if (Opc == Instruction::And)
  5724. Br1->setSuccessor(0, TmpBB);
  5725. else
  5726. Br1->setSuccessor(1, TmpBB);
  5727. // Fill in the new basic block.
  5728. auto *Br2 = IRBuilder<>(TmpBB).CreateCondBr(Cond2, TBB, FBB);
  5729. if (auto *I = dyn_cast<Instruction>(Cond2)) {
  5730. I->removeFromParent();
  5731. I->insertBefore(Br2);
  5732. }
  5733. // Update PHI nodes in both successors. The original BB needs to be
  5734. // replaced in one successor's PHI nodes, because the branch comes now from
  5735. // the newly generated BB (NewBB). In the other successor we need to add one
  5736. // incoming edge to the PHI nodes, because both branch instructions target
  5737. // now the same successor. Depending on the original branch condition
  5738. // (and/or) we have to swap the successors (TrueDest, FalseDest), so that
  5739. // we perform the correct update for the PHI nodes.
  5740. // This doesn't change the successor order of the just created branch
  5741. // instruction (or any other instruction).
  5742. if (Opc == Instruction::Or)
  5743. std::swap(TBB, FBB);
  5744. // Replace the old BB with the new BB.
  5745. for (PHINode &PN : TBB->phis()) {
  5746. int i;
  5747. while ((i = PN.getBasicBlockIndex(&BB)) >= 0)
  5748. PN.setIncomingBlock(i, TmpBB);
  5749. }
  5750. // Add another incoming edge form the new BB.
  5751. for (PHINode &PN : FBB->phis()) {
  5752. auto *Val = PN.getIncomingValueForBlock(&BB);
  5753. PN.addIncoming(Val, TmpBB);
  5754. }
  5755. // Update the branch weights (from SelectionDAGBuilder::
  5756. // FindMergedConditions).
  5757. if (Opc == Instruction::Or) {
  5758. // Codegen X | Y as:
  5759. // BB1:
  5760. // jmp_if_X TBB
  5761. // jmp TmpBB
  5762. // TmpBB:
  5763. // jmp_if_Y TBB
  5764. // jmp FBB
  5765. //
  5766. // We have flexibility in setting Prob for BB1 and Prob for NewBB.
  5767. // The requirement is that
  5768. // TrueProb for BB1 + (FalseProb for BB1 * TrueProb for TmpBB)
  5769. // = TrueProb for orignal BB.
  5770. // Assuming the orignal weights are A and B, one choice is to set BB1's
  5771. // weights to A and A+2B, and set TmpBB's weights to A and 2B. This choice
  5772. // assumes that
  5773. // TrueProb for BB1 == FalseProb for BB1 * TrueProb for TmpBB.
  5774. // Another choice is to assume TrueProb for BB1 equals to TrueProb for
  5775. // TmpBB, but the math is more complicated.
  5776. uint64_t TrueWeight, FalseWeight;
  5777. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  5778. uint64_t NewTrueWeight = TrueWeight;
  5779. uint64_t NewFalseWeight = TrueWeight + 2 * FalseWeight;
  5780. scaleWeights(NewTrueWeight, NewFalseWeight);
  5781. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  5782. .createBranchWeights(TrueWeight, FalseWeight));
  5783. NewTrueWeight = TrueWeight;
  5784. NewFalseWeight = 2 * FalseWeight;
  5785. scaleWeights(NewTrueWeight, NewFalseWeight);
  5786. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  5787. .createBranchWeights(TrueWeight, FalseWeight));
  5788. }
  5789. } else {
  5790. // Codegen X & Y as:
  5791. // BB1:
  5792. // jmp_if_X TmpBB
  5793. // jmp FBB
  5794. // TmpBB:
  5795. // jmp_if_Y TBB
  5796. // jmp FBB
  5797. //
  5798. // This requires creation of TmpBB after CurBB.
  5799. // We have flexibility in setting Prob for BB1 and Prob for TmpBB.
  5800. // The requirement is that
  5801. // FalseProb for BB1 + (TrueProb for BB1 * FalseProb for TmpBB)
  5802. // = FalseProb for orignal BB.
  5803. // Assuming the orignal weights are A and B, one choice is to set BB1's
  5804. // weights to 2A+B and B, and set TmpBB's weights to 2A and B. This choice
  5805. // assumes that
  5806. // FalseProb for BB1 == TrueProb for BB1 * FalseProb for TmpBB.
  5807. uint64_t TrueWeight, FalseWeight;
  5808. if (Br1->extractProfMetadata(TrueWeight, FalseWeight)) {
  5809. uint64_t NewTrueWeight = 2 * TrueWeight + FalseWeight;
  5810. uint64_t NewFalseWeight = FalseWeight;
  5811. scaleWeights(NewTrueWeight, NewFalseWeight);
  5812. Br1->setMetadata(LLVMContext::MD_prof, MDBuilder(Br1->getContext())
  5813. .createBranchWeights(TrueWeight, FalseWeight));
  5814. NewTrueWeight = 2 * TrueWeight;
  5815. NewFalseWeight = FalseWeight;
  5816. scaleWeights(NewTrueWeight, NewFalseWeight);
  5817. Br2->setMetadata(LLVMContext::MD_prof, MDBuilder(Br2->getContext())
  5818. .createBranchWeights(TrueWeight, FalseWeight));
  5819. }
  5820. }
  5821. // Note: No point in getting fancy here, since the DT info is never
  5822. // available to CodeGenPrepare.
  5823. ModifiedDT = true;
  5824. MadeChange = true;
  5825. DEBUG(dbgs() << "After branch condition splitting\n"; BB.dump();
  5826. TmpBB->dump());
  5827. }
  5828. return MadeChange;
  5829. }