ScalarReplAggregatesHLSL.cpp 231 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206
  1. //===- ScalarReplAggregatesHLSL.cpp - Scalar Replacement of Aggregates ----===//
  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. //
  11. // Based on ScalarReplAggregates.cpp. The difference is HLSL version will keep
  12. // array so it can break up all structure.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/ADT/SetVector.h"
  16. #include "llvm/ADT/SmallVector.h"
  17. #include "llvm/ADT/Statistic.h"
  18. #include "llvm/Analysis/AssumptionCache.h"
  19. #include "llvm/Analysis/Loads.h"
  20. #include "llvm/Analysis/ValueTracking.h"
  21. #include "llvm/Analysis/PostDominators.h"
  22. #include "llvm/IR/CallSite.h"
  23. #include "llvm/IR/Constants.h"
  24. #include "llvm/IR/DIBuilder.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/DebugInfo.h"
  27. #include "llvm/IR/DerivedTypes.h"
  28. #include "llvm/IR/Dominators.h"
  29. #include "llvm/IR/Function.h"
  30. #include "llvm/IR/GetElementPtrTypeIterator.h"
  31. #include "llvm/IR/GlobalVariable.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/Instructions.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include "llvm/IR/LLVMContext.h"
  36. #include "llvm/IR/InstIterator.h"
  37. #include "llvm/IR/Module.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/Pass.h"
  40. #include "llvm/Support/Debug.h"
  41. #include "llvm/Support/ErrorHandling.h"
  42. #include "llvm/Support/MathExtras.h"
  43. #include "llvm/Support/raw_ostream.h"
  44. #include "llvm/Transforms/Scalar.h"
  45. #include "llvm/Transforms/Utils/Local.h"
  46. #include "llvm/Transforms/Utils/PromoteMemToReg.h"
  47. #include "llvm/Transforms/Utils/SSAUpdater.h"
  48. #include "llvm/Transforms/Utils/Local.h"
  49. #include "dxc/HLSL/HLOperations.h"
  50. #include "dxc/DXIL/DxilConstants.h"
  51. #include "dxc/HLSL/HLModule.h"
  52. #include "dxc/DXIL/DxilUtil.h"
  53. #include "dxc/DXIL/DxilModule.h"
  54. #include "dxc/HlslIntrinsicOp.h"
  55. #include "dxc/DXIL/DxilTypeSystem.h"
  56. #include "dxc/HLSL/HLMatrixLowerHelper.h"
  57. #include "dxc/HLSL/HLMatrixType.h"
  58. #include "dxc/DXIL/DxilOperations.h"
  59. #include "dxc/HLSL/HLLowerUDT.h"
  60. #include "dxc/HLSL/HLUtil.h"
  61. #include <deque>
  62. #include <unordered_map>
  63. #include <unordered_set>
  64. #include <queue>
  65. using namespace llvm;
  66. using namespace hlsl;
  67. #define DEBUG_TYPE "scalarreplhlsl"
  68. STATISTIC(NumReplaced, "Number of allocas broken up");
  69. STATISTIC(NumPromoted, "Number of allocas promoted");
  70. STATISTIC(NumAdjusted, "Number of scalar allocas adjusted to allow promotion");
  71. namespace {
  72. class SROA_Helper {
  73. public:
  74. // Split V into AllocaInsts with Builder and save the new AllocaInsts into Elts.
  75. // Then do SROA on V.
  76. static bool DoScalarReplacement(Value *V, std::vector<Value *> &Elts,
  77. Type *&BrokenUpTy, uint64_t &NumInstances,
  78. IRBuilder<> &Builder, bool bFlatVector,
  79. bool hasPrecise, DxilTypeSystem &typeSys,
  80. const DataLayout &DL,
  81. SmallVector<Value *, 32> &DeadInsts,
  82. DominatorTree *DT);
  83. static bool DoScalarReplacement(GlobalVariable *GV, std::vector<Value *> &Elts,
  84. IRBuilder<> &Builder, bool bFlatVector,
  85. bool hasPrecise, DxilTypeSystem &typeSys,
  86. const DataLayout &DL,
  87. SmallVector<Value *, 32> &DeadInsts,
  88. DominatorTree *DT);
  89. static unsigned GetEltAlign(unsigned ValueAlign, const DataLayout &DL,
  90. Type *EltTy, unsigned Offset);
  91. // Lower memcpy related to V.
  92. static bool LowerMemcpy(Value *V, DxilFieldAnnotation *annotation,
  93. DxilTypeSystem &typeSys, const DataLayout &DL,
  94. DominatorTree *DT, bool bAllowReplace);
  95. static void MarkEmptyStructUsers(Value *V,
  96. SmallVector<Value *, 32> &DeadInsts);
  97. static bool IsEmptyStructType(Type *Ty, DxilTypeSystem &typeSys);
  98. private:
  99. SROA_Helper(Value *V, ArrayRef<Value *> Elts,
  100. SmallVector<Value *, 32> &DeadInsts, DxilTypeSystem &ts,
  101. const DataLayout &dl, DominatorTree *dt)
  102. : OldVal(V), NewElts(Elts), DeadInsts(DeadInsts), typeSys(ts), DL(dl), DT(dt) {}
  103. void RewriteForScalarRepl(Value *V, IRBuilder<> &Builder);
  104. private:
  105. // Must be a pointer type val.
  106. Value * OldVal;
  107. // Flattened elements for OldVal.
  108. ArrayRef<Value*> NewElts;
  109. SmallVector<Value *, 32> &DeadInsts;
  110. DxilTypeSystem &typeSys;
  111. const DataLayout &DL;
  112. DominatorTree *DT;
  113. void RewriteForConstExpr(ConstantExpr *user, IRBuilder<> &Builder);
  114. void RewriteForGEP(GEPOperator *GEP, IRBuilder<> &Builder);
  115. void RewriteForAddrSpaceCast(Value *user, IRBuilder<> &Builder);
  116. void RewriteForLoad(LoadInst *loadInst);
  117. void RewriteForStore(StoreInst *storeInst);
  118. void RewriteMemIntrin(MemIntrinsic *MI, Value *OldV);
  119. void RewriteCall(CallInst *CI);
  120. void RewriteBitCast(BitCastInst *BCI);
  121. void RewriteCallArg(CallInst *CI, unsigned ArgIdx, bool bIn, bool bOut);
  122. };
  123. struct SROA_HLSL : public FunctionPass {
  124. SROA_HLSL(bool Promote, int T, bool hasDT, char &ID, int ST, int AT, int SLT)
  125. : FunctionPass(ID), HasDomTree(hasDT), RunPromotion(Promote) {
  126. if (AT == -1)
  127. ArrayElementThreshold = 8;
  128. else
  129. ArrayElementThreshold = AT;
  130. if (SLT == -1)
  131. // Do not limit the scalar integer load size if no threshold is given.
  132. ScalarLoadThreshold = -1;
  133. else
  134. ScalarLoadThreshold = SLT;
  135. }
  136. bool runOnFunction(Function &F) override;
  137. bool performScalarRepl(Function &F, DxilTypeSystem &typeSys);
  138. bool markPrecise(Function &F);
  139. private:
  140. bool HasDomTree;
  141. bool RunPromotion;
  142. /// DeadInsts - Keep track of instructions we have made dead, so that
  143. /// we can remove them after we are done working.
  144. SmallVector<Value *, 32> DeadInsts;
  145. /// AllocaInfo - When analyzing uses of an alloca instruction, this captures
  146. /// information about the uses. All these fields are initialized to false
  147. /// and set to true when something is learned.
  148. struct AllocaInfo {
  149. /// The alloca to promote.
  150. AllocaInst *AI;
  151. /// CheckedPHIs - This is a set of verified PHI nodes, to prevent infinite
  152. /// looping and avoid redundant work.
  153. SmallPtrSet<PHINode *, 8> CheckedPHIs;
  154. /// isUnsafe - This is set to true if the alloca cannot be SROA'd.
  155. bool isUnsafe : 1;
  156. /// isMemCpySrc - This is true if this aggregate is memcpy'd from.
  157. bool isMemCpySrc : 1;
  158. /// isMemCpyDst - This is true if this aggregate is memcpy'd into.
  159. bool isMemCpyDst : 1;
  160. /// hasSubelementAccess - This is true if a subelement of the alloca is
  161. /// ever accessed, or false if the alloca is only accessed with mem
  162. /// intrinsics or load/store that only access the entire alloca at once.
  163. bool hasSubelementAccess : 1;
  164. /// hasALoadOrStore - This is true if there are any loads or stores to it.
  165. /// The alloca may just be accessed with memcpy, for example, which would
  166. /// not set this.
  167. bool hasALoadOrStore : 1;
  168. /// hasArrayIndexing - This is true if there are any dynamic array
  169. /// indexing to it.
  170. bool hasArrayIndexing : 1;
  171. /// hasVectorIndexing - This is true if there are any dynamic vector
  172. /// indexing to it.
  173. bool hasVectorIndexing : 1;
  174. explicit AllocaInfo(AllocaInst *ai)
  175. : AI(ai), isUnsafe(false), isMemCpySrc(false), isMemCpyDst(false),
  176. hasSubelementAccess(false), hasALoadOrStore(false),
  177. hasArrayIndexing(false), hasVectorIndexing(false) {}
  178. };
  179. /// ArrayElementThreshold - The maximum number of elements an array can
  180. /// have to be considered for SROA.
  181. unsigned ArrayElementThreshold;
  182. /// ScalarLoadThreshold - The maximum size in bits of scalars to load when
  183. /// converting to scalar
  184. unsigned ScalarLoadThreshold;
  185. void MarkUnsafe(AllocaInfo &I, Instruction *User) {
  186. I.isUnsafe = true;
  187. DEBUG(dbgs() << " Transformation preventing inst: " << *User << '\n');
  188. }
  189. bool isSafeAllocaToScalarRepl(AllocaInst *AI);
  190. void isSafeForScalarRepl(Instruction *I, uint64_t Offset, AllocaInfo &Info);
  191. void isSafePHISelectUseForScalarRepl(Instruction *User, uint64_t Offset,
  192. AllocaInfo &Info);
  193. void isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset, AllocaInfo &Info);
  194. void isSafeMemAccess(uint64_t Offset, uint64_t MemSize, Type *MemOpType,
  195. bool isStore, AllocaInfo &Info, Instruction *TheAccess,
  196. bool AllowWholeAccess);
  197. bool TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
  198. const DataLayout &DL);
  199. void DeleteDeadInstructions();
  200. bool ShouldAttemptScalarRepl(AllocaInst *AI);
  201. };
  202. // SROA_DT_HLSL - SROA that uses DominatorTree.
  203. struct SROA_DT_HLSL : public SROA_HLSL {
  204. static char ID;
  205. public:
  206. SROA_DT_HLSL(bool Promote = false, int T = -1, int ST = -1, int AT = -1, int SLT = -1)
  207. : SROA_HLSL(Promote, T, true, ID, ST, AT, SLT) {
  208. initializeSROA_DTPass(*PassRegistry::getPassRegistry());
  209. }
  210. // getAnalysisUsage - This pass does not require any passes, but we know it
  211. // will not alter the CFG, so say so.
  212. void getAnalysisUsage(AnalysisUsage &AU) const override {
  213. AU.addRequired<AssumptionCacheTracker>();
  214. AU.addRequired<DominatorTreeWrapperPass>();
  215. AU.setPreservesCFG();
  216. }
  217. };
  218. // SROA_SSAUp - SROA that uses SSAUpdater.
  219. struct SROA_SSAUp_HLSL : public SROA_HLSL {
  220. static char ID;
  221. public:
  222. SROA_SSAUp_HLSL(bool Promote = false, int T = -1, int ST = -1, int AT = -1, int SLT = -1)
  223. : SROA_HLSL(Promote, T, false, ID, ST, AT, SLT) {
  224. initializeSROA_SSAUpPass(*PassRegistry::getPassRegistry());
  225. }
  226. // getAnalysisUsage - This pass does not require any passes, but we know it
  227. // will not alter the CFG, so say so.
  228. void getAnalysisUsage(AnalysisUsage &AU) const override {
  229. AU.addRequired<AssumptionCacheTracker>();
  230. AU.setPreservesCFG();
  231. }
  232. };
  233. // Simple struct to split memcpy into ld/st
  234. struct MemcpySplitter {
  235. llvm::LLVMContext &m_context;
  236. DxilTypeSystem &m_typeSys;
  237. public:
  238. MemcpySplitter(llvm::LLVMContext &context, DxilTypeSystem &typeSys)
  239. : m_context(context), m_typeSys(typeSys) {}
  240. void Split(llvm::Function &F);
  241. static void PatchMemCpyWithZeroIdxGEP(Module &M);
  242. static void PatchMemCpyWithZeroIdxGEP(MemCpyInst *MI, const DataLayout &DL);
  243. static void SplitMemCpy(MemCpyInst *MI, const DataLayout &DL,
  244. DxilFieldAnnotation *fieldAnnotation,
  245. DxilTypeSystem &typeSys,
  246. const bool bEltMemCpy = true);
  247. };
  248. }
  249. char SROA_DT_HLSL::ID = 0;
  250. char SROA_SSAUp_HLSL::ID = 0;
  251. INITIALIZE_PASS_BEGIN(SROA_DT_HLSL, "scalarreplhlsl",
  252. "Scalar Replacement of Aggregates HLSL (DT)", false,
  253. false)
  254. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  255. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  256. INITIALIZE_PASS_END(SROA_DT_HLSL, "scalarreplhlsl",
  257. "Scalar Replacement of Aggregates HLSL (DT)", false, false)
  258. INITIALIZE_PASS_BEGIN(SROA_SSAUp_HLSL, "scalarreplhlsl-ssa",
  259. "Scalar Replacement of Aggregates HLSL (SSAUp)", false,
  260. false)
  261. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  262. INITIALIZE_PASS_END(SROA_SSAUp_HLSL, "scalarreplhlsl-ssa",
  263. "Scalar Replacement of Aggregates HLSL (SSAUp)", false,
  264. false)
  265. // Public interface to the ScalarReplAggregates pass
  266. FunctionPass *llvm::createScalarReplAggregatesHLSLPass(bool UseDomTree, bool Promote) {
  267. if (UseDomTree)
  268. return new SROA_DT_HLSL(Promote);
  269. return new SROA_SSAUp_HLSL(Promote);
  270. }
  271. //===----------------------------------------------------------------------===//
  272. // SRoA Driver
  273. //===----------------------------------------------------------------------===//
  274. bool SROA_HLSL::runOnFunction(Function &F) {
  275. Module *M = F.getParent();
  276. HLModule &HLM = M->GetOrCreateHLModule();
  277. DxilTypeSystem &typeSys = HLM.GetTypeSystem();
  278. // Establish debug metadata layout name in the context in advance so the name
  279. // is serialized in both debug and non-debug compilations.
  280. (void)M->getContext().getMDKindID(DxilMDHelper::kDxilVariableDebugLayoutMDName);
  281. bool Changed = performScalarRepl(F, typeSys);
  282. // change rest memcpy into ld/st.
  283. MemcpySplitter splitter(F.getContext(), typeSys);
  284. splitter.Split(F);
  285. Changed |= markPrecise(F);
  286. return Changed;
  287. }
  288. namespace {
  289. class AllocaPromoter : public LoadAndStorePromoter {
  290. AllocaInst *AI;
  291. DIBuilder *DIB;
  292. SmallVector<DbgDeclareInst *, 4> DDIs;
  293. SmallVector<DbgValueInst *, 4> DVIs;
  294. public:
  295. AllocaPromoter(ArrayRef<Instruction *> Insts, SSAUpdater &S, DIBuilder *DB)
  296. : LoadAndStorePromoter(Insts, S), AI(nullptr), DIB(DB) {}
  297. void run(AllocaInst *AI, const SmallVectorImpl<Instruction *> &Insts) {
  298. // Remember which alloca we're promoting (for isInstInList).
  299. this->AI = AI;
  300. if (auto *L = LocalAsMetadata::getIfExists(AI)) {
  301. if (auto *DINode = MetadataAsValue::getIfExists(AI->getContext(), L)) {
  302. for (User *U : DINode->users())
  303. if (DbgDeclareInst *DDI = dyn_cast<DbgDeclareInst>(U))
  304. DDIs.push_back(DDI);
  305. else if (DbgValueInst *DVI = dyn_cast<DbgValueInst>(U))
  306. DVIs.push_back(DVI);
  307. }
  308. }
  309. LoadAndStorePromoter::run(Insts);
  310. AI->eraseFromParent();
  311. for (SmallVectorImpl<DbgDeclareInst *>::iterator I = DDIs.begin(),
  312. E = DDIs.end();
  313. I != E; ++I) {
  314. DbgDeclareInst *DDI = *I;
  315. DDI->eraseFromParent();
  316. }
  317. for (SmallVectorImpl<DbgValueInst *>::iterator I = DVIs.begin(),
  318. E = DVIs.end();
  319. I != E; ++I) {
  320. DbgValueInst *DVI = *I;
  321. DVI->eraseFromParent();
  322. }
  323. }
  324. bool
  325. isInstInList(Instruction *I,
  326. const SmallVectorImpl<Instruction *> &Insts) const override {
  327. if (LoadInst *LI = dyn_cast<LoadInst>(I))
  328. return LI->getOperand(0) == AI;
  329. return cast<StoreInst>(I)->getPointerOperand() == AI;
  330. }
  331. void updateDebugInfo(Instruction *Inst) const override {
  332. for (SmallVectorImpl<DbgDeclareInst *>::const_iterator I = DDIs.begin(),
  333. E = DDIs.end();
  334. I != E; ++I) {
  335. DbgDeclareInst *DDI = *I;
  336. if (StoreInst *SI = dyn_cast<StoreInst>(Inst))
  337. ConvertDebugDeclareToDebugValue(DDI, SI, *DIB);
  338. else if (LoadInst *LI = dyn_cast<LoadInst>(Inst))
  339. ConvertDebugDeclareToDebugValue(DDI, LI, *DIB);
  340. }
  341. for (SmallVectorImpl<DbgValueInst *>::const_iterator I = DVIs.begin(),
  342. E = DVIs.end();
  343. I != E; ++I) {
  344. DbgValueInst *DVI = *I;
  345. Value *Arg = nullptr;
  346. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  347. // If an argument is zero extended then use argument directly. The ZExt
  348. // may be zapped by an optimization pass in future.
  349. if (ZExtInst *ZExt = dyn_cast<ZExtInst>(SI->getOperand(0)))
  350. Arg = dyn_cast<Argument>(ZExt->getOperand(0));
  351. if (SExtInst *SExt = dyn_cast<SExtInst>(SI->getOperand(0)))
  352. Arg = dyn_cast<Argument>(SExt->getOperand(0));
  353. if (!Arg)
  354. Arg = SI->getOperand(0);
  355. } else if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  356. Arg = LI->getOperand(0);
  357. } else {
  358. continue;
  359. }
  360. DIB->insertDbgValueIntrinsic(Arg, 0, DVI->getVariable(),
  361. DVI->getExpression(), DVI->getDebugLoc(),
  362. Inst);
  363. }
  364. }
  365. };
  366. } // end anon namespace
  367. /// isSafeSelectToSpeculate - Select instructions that use an alloca and are
  368. /// subsequently loaded can be rewritten to load both input pointers and then
  369. /// select between the result, allowing the load of the alloca to be promoted.
  370. /// From this:
  371. /// %P2 = select i1 %cond, i32* %Alloca, i32* %Other
  372. /// %V = load i32* %P2
  373. /// to:
  374. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  375. /// %V2 = load i32* %Other
  376. /// %V = select i1 %cond, i32 %V1, i32 %V2
  377. ///
  378. /// We can do this to a select if its only uses are loads and if the operand to
  379. /// the select can be loaded unconditionally.
  380. static bool isSafeSelectToSpeculate(SelectInst *SI) {
  381. const DataLayout &DL = SI->getModule()->getDataLayout();
  382. bool TDerefable = isDereferenceablePointer(SI->getTrueValue(), DL);
  383. bool FDerefable = isDereferenceablePointer(SI->getFalseValue(), DL);
  384. for (User *U : SI->users()) {
  385. LoadInst *LI = dyn_cast<LoadInst>(U);
  386. if (!LI || !LI->isSimple())
  387. return false;
  388. // Both operands to the select need to be dereferencable, either absolutely
  389. // (e.g. allocas) or at this point because we can see other accesses to it.
  390. if (!TDerefable &&
  391. !isSafeToLoadUnconditionally(SI->getTrueValue(), LI,
  392. LI->getAlignment()))
  393. return false;
  394. if (!FDerefable &&
  395. !isSafeToLoadUnconditionally(SI->getFalseValue(), LI,
  396. LI->getAlignment()))
  397. return false;
  398. }
  399. return true;
  400. }
  401. /// isSafePHIToSpeculate - PHI instructions that use an alloca and are
  402. /// subsequently loaded can be rewritten to load both input pointers in the pred
  403. /// blocks and then PHI the results, allowing the load of the alloca to be
  404. /// promoted.
  405. /// From this:
  406. /// %P2 = phi [i32* %Alloca, i32* %Other]
  407. /// %V = load i32* %P2
  408. /// to:
  409. /// %V1 = load i32* %Alloca -> will be mem2reg'd
  410. /// ...
  411. /// %V2 = load i32* %Other
  412. /// ...
  413. /// %V = phi [i32 %V1, i32 %V2]
  414. ///
  415. /// We can do this to a select if its only uses are loads and if the operand to
  416. /// the select can be loaded unconditionally.
  417. static bool isSafePHIToSpeculate(PHINode *PN) {
  418. // For now, we can only do this promotion if the load is in the same block as
  419. // the PHI, and if there are no stores between the phi and load.
  420. // TODO: Allow recursive phi users.
  421. // TODO: Allow stores.
  422. BasicBlock *BB = PN->getParent();
  423. unsigned MaxAlign = 0;
  424. for (User *U : PN->users()) {
  425. LoadInst *LI = dyn_cast<LoadInst>(U);
  426. if (!LI || !LI->isSimple())
  427. return false;
  428. // For now we only allow loads in the same block as the PHI. This is a
  429. // common case that happens when instcombine merges two loads through a PHI.
  430. if (LI->getParent() != BB)
  431. return false;
  432. // Ensure that there are no instructions between the PHI and the load that
  433. // could store.
  434. for (BasicBlock::iterator BBI = PN; &*BBI != LI; ++BBI)
  435. if (BBI->mayWriteToMemory())
  436. return false;
  437. MaxAlign = std::max(MaxAlign, LI->getAlignment());
  438. }
  439. const DataLayout &DL = PN->getModule()->getDataLayout();
  440. // Okay, we know that we have one or more loads in the same block as the PHI.
  441. // We can transform this if it is safe to push the loads into the predecessor
  442. // blocks. The only thing to watch out for is that we can't put a possibly
  443. // trapping load in the predecessor if it is a critical edge.
  444. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  445. BasicBlock *Pred = PN->getIncomingBlock(i);
  446. Value *InVal = PN->getIncomingValue(i);
  447. // If the terminator of the predecessor has side-effects (an invoke),
  448. // there is no safe place to put a load in the predecessor.
  449. if (Pred->getTerminator()->mayHaveSideEffects())
  450. return false;
  451. // If the value is produced by the terminator of the predecessor
  452. // (an invoke), there is no valid place to put a load in the predecessor.
  453. if (Pred->getTerminator() == InVal)
  454. return false;
  455. // If the predecessor has a single successor, then the edge isn't critical.
  456. if (Pred->getTerminator()->getNumSuccessors() == 1)
  457. continue;
  458. // If this pointer is always safe to load, or if we can prove that there is
  459. // already a load in the block, then we can move the load to the pred block.
  460. if (isDereferenceablePointer(InVal, DL) ||
  461. isSafeToLoadUnconditionally(InVal, Pred->getTerminator(), MaxAlign))
  462. continue;
  463. return false;
  464. }
  465. return true;
  466. }
  467. /// tryToMakeAllocaBePromotable - This returns true if the alloca only has
  468. /// direct (non-volatile) loads and stores to it. If the alloca is close but
  469. /// not quite there, this will transform the code to allow promotion. As such,
  470. /// it is a non-pure predicate.
  471. static bool tryToMakeAllocaBePromotable(AllocaInst *AI, const DataLayout &DL) {
  472. SetVector<Instruction *, SmallVector<Instruction *, 4>,
  473. SmallPtrSet<Instruction *, 4>>
  474. InstsToRewrite;
  475. for (User *U : AI->users()) {
  476. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  477. if (!LI->isSimple())
  478. return false;
  479. continue;
  480. }
  481. if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  482. if (SI->getOperand(0) == AI || !SI->isSimple())
  483. return false; // Don't allow a store OF the AI, only INTO the AI.
  484. continue;
  485. }
  486. if (SelectInst *SI = dyn_cast<SelectInst>(U)) {
  487. // If the condition being selected on is a constant, fold the select, yes
  488. // this does (rarely) happen early on.
  489. if (ConstantInt *CI = dyn_cast<ConstantInt>(SI->getCondition())) {
  490. Value *Result = SI->getOperand(1 + CI->isZero());
  491. SI->replaceAllUsesWith(Result);
  492. SI->eraseFromParent();
  493. // This is very rare and we just scrambled the use list of AI, start
  494. // over completely.
  495. return tryToMakeAllocaBePromotable(AI, DL);
  496. }
  497. // If it is safe to turn "load (select c, AI, ptr)" into a select of two
  498. // loads, then we can transform this by rewriting the select.
  499. if (!isSafeSelectToSpeculate(SI))
  500. return false;
  501. InstsToRewrite.insert(SI);
  502. continue;
  503. }
  504. if (PHINode *PN = dyn_cast<PHINode>(U)) {
  505. if (PN->use_empty()) { // Dead PHIs can be stripped.
  506. InstsToRewrite.insert(PN);
  507. continue;
  508. }
  509. // If it is safe to turn "load (phi [AI, ptr, ...])" into a PHI of loads
  510. // in the pred blocks, then we can transform this by rewriting the PHI.
  511. if (!isSafePHIToSpeculate(PN))
  512. return false;
  513. InstsToRewrite.insert(PN);
  514. continue;
  515. }
  516. if (BitCastInst *BCI = dyn_cast<BitCastInst>(U)) {
  517. if (onlyUsedByLifetimeMarkers(BCI)) {
  518. InstsToRewrite.insert(BCI);
  519. continue;
  520. }
  521. }
  522. return false;
  523. }
  524. // If there are no instructions to rewrite, then all uses are load/stores and
  525. // we're done!
  526. if (InstsToRewrite.empty())
  527. return true;
  528. // If we have instructions that need to be rewritten for this to be promotable
  529. // take care of it now.
  530. for (unsigned i = 0, e = InstsToRewrite.size(); i != e; ++i) {
  531. if (BitCastInst *BCI = dyn_cast<BitCastInst>(InstsToRewrite[i])) {
  532. // This could only be a bitcast used by nothing but lifetime intrinsics.
  533. for (BitCastInst::user_iterator I = BCI->user_begin(),
  534. E = BCI->user_end();
  535. I != E;)
  536. cast<Instruction>(*I++)->eraseFromParent();
  537. BCI->eraseFromParent();
  538. continue;
  539. }
  540. if (SelectInst *SI = dyn_cast<SelectInst>(InstsToRewrite[i])) {
  541. // Selects in InstsToRewrite only have load uses. Rewrite each as two
  542. // loads with a new select.
  543. while (!SI->use_empty()) {
  544. LoadInst *LI = cast<LoadInst>(SI->user_back());
  545. IRBuilder<> Builder(LI);
  546. LoadInst *TrueLoad =
  547. Builder.CreateLoad(SI->getTrueValue(), LI->getName() + ".t");
  548. LoadInst *FalseLoad =
  549. Builder.CreateLoad(SI->getFalseValue(), LI->getName() + ".f");
  550. // Transfer alignment and AA info if present.
  551. TrueLoad->setAlignment(LI->getAlignment());
  552. FalseLoad->setAlignment(LI->getAlignment());
  553. AAMDNodes Tags;
  554. LI->getAAMetadata(Tags);
  555. if (Tags) {
  556. TrueLoad->setAAMetadata(Tags);
  557. FalseLoad->setAAMetadata(Tags);
  558. }
  559. Value *V =
  560. Builder.CreateSelect(SI->getCondition(), TrueLoad, FalseLoad);
  561. V->takeName(LI);
  562. LI->replaceAllUsesWith(V);
  563. LI->eraseFromParent();
  564. }
  565. // Now that all the loads are gone, the select is gone too.
  566. SI->eraseFromParent();
  567. continue;
  568. }
  569. // Otherwise, we have a PHI node which allows us to push the loads into the
  570. // predecessors.
  571. PHINode *PN = cast<PHINode>(InstsToRewrite[i]);
  572. if (PN->use_empty()) {
  573. PN->eraseFromParent();
  574. continue;
  575. }
  576. Type *LoadTy = cast<PointerType>(PN->getType())->getElementType();
  577. PHINode *NewPN = PHINode::Create(LoadTy, PN->getNumIncomingValues(),
  578. PN->getName() + ".ld", PN);
  579. // Get the AA tags and alignment to use from one of the loads. It doesn't
  580. // matter which one we get and if any differ, it doesn't matter.
  581. LoadInst *SomeLoad = cast<LoadInst>(PN->user_back());
  582. AAMDNodes AATags;
  583. SomeLoad->getAAMetadata(AATags);
  584. unsigned Align = SomeLoad->getAlignment();
  585. // Rewrite all loads of the PN to use the new PHI.
  586. while (!PN->use_empty()) {
  587. LoadInst *LI = cast<LoadInst>(PN->user_back());
  588. LI->replaceAllUsesWith(NewPN);
  589. LI->eraseFromParent();
  590. }
  591. // Inject loads into all of the pred blocks. Keep track of which blocks we
  592. // insert them into in case we have multiple edges from the same block.
  593. DenseMap<BasicBlock *, LoadInst *> InsertedLoads;
  594. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
  595. BasicBlock *Pred = PN->getIncomingBlock(i);
  596. LoadInst *&Load = InsertedLoads[Pred];
  597. if (!Load) {
  598. Load = new LoadInst(PN->getIncomingValue(i),
  599. PN->getName() + "." + Pred->getName(),
  600. Pred->getTerminator());
  601. Load->setAlignment(Align);
  602. if (AATags)
  603. Load->setAAMetadata(AATags);
  604. }
  605. NewPN->addIncoming(Load, Pred);
  606. }
  607. PN->eraseFromParent();
  608. }
  609. ++NumAdjusted;
  610. return true;
  611. }
  612. /// ShouldAttemptScalarRepl - Decide if an alloca is a good candidate for
  613. /// SROA. It must be a struct or array type with a small number of elements.
  614. bool SROA_HLSL::ShouldAttemptScalarRepl(AllocaInst *AI) {
  615. Type *T = AI->getAllocatedType();
  616. // promote every struct.
  617. if (dyn_cast<StructType>(T))
  618. return true;
  619. // promote every array.
  620. if (dyn_cast<ArrayType>(T))
  621. return true;
  622. return false;
  623. }
  624. static unsigned getNestedLevelInStruct(const Type *ty) {
  625. unsigned lvl = 0;
  626. while (ty->isStructTy()) {
  627. if (ty->getStructNumElements() != 1)
  628. break;
  629. ty = ty->getStructElementType(0);
  630. lvl++;
  631. }
  632. return lvl;
  633. }
  634. // After SROA'ing a given value into a series of elements,
  635. // creates the debug info for the storage of the individual elements.
  636. static void addDebugInfoForElements(Value *ParentVal,
  637. Type *BrokenUpTy, uint64_t NumInstances,
  638. ArrayRef<Value*> Elems, const DataLayout &DatLayout,
  639. DIBuilder *DbgBuilder) {
  640. // Extract the data we need from the parent value,
  641. // depending on whether it is an alloca, argument or global variable.
  642. Type *ParentTy;
  643. unsigned ParentBitPieceOffset = 0;
  644. std::vector<DxilDIArrayDim> DIArrayDims;
  645. DIVariable *ParentDbgVariable;
  646. DIExpression *ParentDbgExpr;
  647. DILocation *ParentDbgLocation;
  648. Instruction *DbgDeclareInsertPt = nullptr;
  649. if (isa<GlobalVariable>(ParentVal)) {
  650. llvm_unreachable("Not implemented: sroa debug info propagation for global vars.");
  651. }
  652. else {
  653. if (AllocaInst *ParentAlloca = dyn_cast<AllocaInst>(ParentVal))
  654. ParentTy = ParentAlloca->getAllocatedType();
  655. else
  656. ParentTy = cast<Argument>(ParentVal)->getType();
  657. DbgDeclareInst *ParentDbgDeclare = llvm::FindAllocaDbgDeclare(ParentVal);
  658. if (ParentDbgDeclare == nullptr) return;
  659. // Get the bit piece offset
  660. if ((ParentDbgExpr = ParentDbgDeclare->getExpression())) {
  661. if (ParentDbgExpr->isBitPiece()) {
  662. ParentBitPieceOffset = ParentDbgExpr->getBitPieceOffset();
  663. }
  664. }
  665. ParentDbgVariable = ParentDbgDeclare->getVariable();
  666. ParentDbgLocation = ParentDbgDeclare->getDebugLoc();
  667. DbgDeclareInsertPt = ParentDbgDeclare;
  668. // Read the extra layout metadata, if any
  669. unsigned ParentBitPieceOffsetFromMD = 0;
  670. if (DxilMDHelper::GetVariableDebugLayout(ParentDbgDeclare, ParentBitPieceOffsetFromMD, DIArrayDims)) {
  671. // The offset is redundant for local variables and only necessary for global variables.
  672. DXASSERT(ParentBitPieceOffsetFromMD == ParentBitPieceOffset,
  673. "Bit piece offset mismatch between llvm.dbg.declare and DXIL metadata.");
  674. }
  675. }
  676. // If the type that was broken up is nested in arrays,
  677. // then each element will also be an array,
  678. // but the continuity between successive elements of the original aggregate
  679. // will have been broken, such that we must store the stride to rebuild it.
  680. // For example: [2 x {i32, float}] => [2 x i32], [2 x float], each with stride 64 bits
  681. if (NumInstances > 1 && Elems.size() > 1) {
  682. // Existing dimensions already account for part of the stride
  683. uint64_t NewDimNumElements = NumInstances;
  684. for (const DxilDIArrayDim& ArrayDim : DIArrayDims) {
  685. DXASSERT(NewDimNumElements % ArrayDim.NumElements == 0,
  686. "Debug array stride is inconsistent with the number of elements.");
  687. NewDimNumElements /= ArrayDim.NumElements;
  688. }
  689. // Add a stride dimension
  690. DxilDIArrayDim NewDIArrayDim = {};
  691. NewDIArrayDim.StrideInBits = (unsigned)DatLayout.getTypeAllocSizeInBits(BrokenUpTy);
  692. NewDIArrayDim.NumElements = (unsigned)NewDimNumElements;
  693. DIArrayDims.emplace_back(NewDIArrayDim);
  694. }
  695. else {
  696. DIArrayDims.clear();
  697. }
  698. // Create the debug info for each element
  699. for (unsigned ElemIdx = 0; ElemIdx < Elems.size(); ++ElemIdx) {
  700. // Figure out the offset of the element in the broken up type
  701. unsigned ElemBitPieceOffset = ParentBitPieceOffset;
  702. if (StructType *ParentStructTy = dyn_cast<StructType>(BrokenUpTy)) {
  703. DXASSERT_NOMSG(Elems.size() == ParentStructTy->getNumElements());
  704. ElemBitPieceOffset += (unsigned)DatLayout.getStructLayout(ParentStructTy)->getElementOffsetInBits(ElemIdx);
  705. }
  706. else if (VectorType *ParentVecTy = dyn_cast<VectorType>(BrokenUpTy)) {
  707. DXASSERT_NOMSG(Elems.size() == ParentVecTy->getNumElements());
  708. ElemBitPieceOffset += (unsigned)DatLayout.getTypeStoreSizeInBits(ParentVecTy->getElementType()) * ElemIdx;
  709. }
  710. else if (ArrayType *ParentArrayTy = dyn_cast<ArrayType>(BrokenUpTy)) {
  711. DXASSERT_NOMSG(Elems.size() == ParentArrayTy->getNumElements());
  712. ElemBitPieceOffset += (unsigned)DatLayout.getTypeStoreSizeInBits(ParentArrayTy->getElementType()) * ElemIdx;
  713. }
  714. // The bit_piece can only represent the leading contiguous bytes.
  715. // If strides are involved, we'll need additional metadata.
  716. Type *ElemTy = Elems[ElemIdx]->getType()->getPointerElementType();
  717. unsigned ElemBitPieceSize = (unsigned)DatLayout.getTypeAllocSizeInBits(ElemTy);
  718. for (const DxilDIArrayDim& ArrayDim : DIArrayDims)
  719. ElemBitPieceSize /= ArrayDim.NumElements;
  720. if (AllocaInst *ElemAlloca = dyn_cast<AllocaInst>(Elems[ElemIdx])) {
  721. // Local variables get an @llvm.dbg.declare plus optional metadata for layout stride information.
  722. DIExpression *ElemDbgExpr = nullptr;
  723. if (ElemBitPieceOffset == 0 && DatLayout.getTypeAllocSizeInBits(ParentTy) == ElemBitPieceSize) {
  724. ElemDbgExpr = DbgBuilder->createExpression();
  725. }
  726. else {
  727. ElemDbgExpr = DbgBuilder->createBitPieceExpression(ElemBitPieceOffset, ElemBitPieceSize);
  728. }
  729. DXASSERT_NOMSG(DbgBuilder != nullptr);
  730. DbgDeclareInst *EltDDI = cast<DbgDeclareInst>(DbgBuilder->insertDeclare(
  731. ElemAlloca, cast<DILocalVariable>(ParentDbgVariable), ElemDbgExpr, ParentDbgLocation, DbgDeclareInsertPt));
  732. if (!DIArrayDims.empty()) DxilMDHelper::SetVariableDebugLayout(EltDDI, ElemBitPieceOffset, DIArrayDims);
  733. }
  734. else {
  735. llvm_unreachable("Non-AllocaInst SROA'd elements.");
  736. }
  737. }
  738. }
  739. /// Returns first GEP index that indexes a struct member, or 0 otherwise.
  740. /// Ignores initial ptr index.
  741. static unsigned FindFirstStructMemberIdxInGEP(GEPOperator *GEP) {
  742. StructType *ST = dyn_cast<StructType>(
  743. GEP->getPointerOperandType()->getPointerElementType());
  744. int index = 1;
  745. for (auto it = gep_type_begin(GEP), E = gep_type_end(GEP); it != E;
  746. ++it, ++index) {
  747. if (ST) {
  748. DXASSERT(!HLMatrixType::isa(ST) && !dxilutil::IsHLSLObjectType(ST),
  749. "otherwise, indexing into hlsl object");
  750. return index;
  751. }
  752. ST = dyn_cast<StructType>(it->getPointerElementType());
  753. }
  754. return 0;
  755. }
  756. /// Return true when ptr should not be SROA'd or copied, but used directly
  757. /// by a function in its lowered form. Also collect uses for translation.
  758. /// What is meant by directly here:
  759. /// Possibly accessed through GEP array index or address space cast, but
  760. /// not under another struct member (always allow SROA of outer struct).
  761. typedef SmallMapVector<CallInst*, unsigned, 4> FunctionUseMap;
  762. static unsigned IsPtrUsedByLoweredFn(
  763. Value *V, FunctionUseMap &CollectedUses) {
  764. bool bFound = false;
  765. for (Use &U : V->uses()) {
  766. User *user = U.getUser();
  767. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  768. unsigned foundIdx = (unsigned)-1;
  769. Function *F = CI->getCalledFunction();
  770. Type *Ty = V->getType();
  771. if (F->isDeclaration() && !F->isIntrinsic() &&
  772. Ty->isPointerTy()) {
  773. HLOpcodeGroup group = hlsl::GetHLOpcodeGroupByName(F);
  774. if (group == HLOpcodeGroup::HLIntrinsic) {
  775. unsigned opIdx = U.getOperandNo();
  776. switch ((IntrinsicOp)hlsl::GetHLOpcode(CI)) {
  777. // TODO: Lower these as well, along with function parameter types
  778. //case IntrinsicOp::IOP_TraceRay:
  779. // if (opIdx != HLOperandIndex::kTraceRayPayLoadOpIdx)
  780. // continue;
  781. // break;
  782. //case IntrinsicOp::IOP_ReportHit:
  783. // if (opIdx != HLOperandIndex::kReportIntersectionAttributeOpIdx)
  784. // continue;
  785. // break;
  786. //case IntrinsicOp::IOP_CallShader:
  787. // if (opIdx != HLOperandIndex::kCallShaderPayloadOpIdx)
  788. // continue;
  789. // break;
  790. case IntrinsicOp::IOP_DispatchMesh:
  791. if (opIdx != HLOperandIndex::kDispatchMeshOpPayload)
  792. continue;
  793. break;
  794. default:
  795. continue;
  796. }
  797. foundIdx = opIdx;
  798. // TODO: Lower these as well, along with function parameter types
  799. //} else if (group == HLOpcodeGroup::NotHL) {
  800. // foundIdx = U.getOperandNo();
  801. }
  802. }
  803. if (foundIdx != (unsigned)-1) {
  804. bFound = true;
  805. auto insRes = CollectedUses.insert(std::make_pair(CI, foundIdx));
  806. DXASSERT_LOCALVAR(insRes, insRes.second,
  807. "otherwise, multiple uses in single call");
  808. }
  809. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {
  810. // Not what we are looking for if GEP result is not [array of] struct.
  811. // If use is under struct member, we can still SROA the outer struct.
  812. if (!dxilutil::StripArrayTypes(GEP->getType()->getPointerElementType())
  813. ->isStructTy() ||
  814. FindFirstStructMemberIdxInGEP(cast<GEPOperator>(GEP)))
  815. continue;
  816. if (IsPtrUsedByLoweredFn(user, CollectedUses))
  817. bFound = true;
  818. } else if (AddrSpaceCastInst *AC = dyn_cast<AddrSpaceCastInst>(user)) {
  819. if (IsPtrUsedByLoweredFn(user, CollectedUses))
  820. bFound = true;
  821. } else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(user)) {
  822. unsigned opcode = CE->getOpcode();
  823. if (opcode == Instruction::AddrSpaceCast || opcode == Instruction::GetElementPtr)
  824. if (IsPtrUsedByLoweredFn(user, CollectedUses))
  825. bFound = true;
  826. }
  827. }
  828. return bFound;
  829. }
  830. /// Rewrite call to natively use an argument with addrspace cast/bitcast
  831. static CallInst *RewriteIntrinsicCallForCastedArg(CallInst *CI, unsigned argIdx) {
  832. Function *F = CI->getCalledFunction();
  833. HLOpcodeGroup group = GetHLOpcodeGroupByName(F);
  834. DXASSERT_NOMSG(group == HLOpcodeGroup::HLIntrinsic);
  835. unsigned opcode = GetHLOpcode(CI);
  836. SmallVector<Type *, 8> newArgTypes(CI->getFunctionType()->param_begin(),
  837. CI->getFunctionType()->param_end());
  838. SmallVector<Value *, 8> newArgs(CI->arg_operands());
  839. Value *newArg = CI->getOperand(argIdx)->stripPointerCasts();
  840. newArgTypes[argIdx] = newArg->getType();
  841. newArgs[argIdx] = newArg;
  842. FunctionType *newFuncTy = FunctionType::get(CI->getType(), newArgTypes, false);
  843. Function *newF = GetOrCreateHLFunction(*F->getParent(), newFuncTy, group, opcode,
  844. F->getAttributes().getFnAttributes());
  845. IRBuilder<> Builder(CI);
  846. return Builder.CreateCall(newF, newArgs);
  847. }
  848. /// Translate pointer for cases where intrinsics use UDT pointers directly
  849. /// Return existing or new ptr if needs preserving,
  850. /// otherwise nullptr to proceed with existing checks and SROA.
  851. static Value *TranslatePtrIfUsedByLoweredFn(
  852. Value *Ptr, DxilTypeSystem &TypeSys) {
  853. if (!Ptr->getType()->isPointerTy())
  854. return nullptr;
  855. Type *Ty = Ptr->getType()->getPointerElementType();
  856. SmallVector<unsigned, 4> outerToInnerLengths;
  857. Ty = dxilutil::StripArrayTypes(Ty, &outerToInnerLengths);
  858. if (!Ty->isStructTy())
  859. return nullptr;
  860. if (HLMatrixType::isa(Ty) || dxilutil::IsHLSLObjectType(Ty))
  861. return nullptr;
  862. unsigned AddrSpace = Ptr->getType()->getPointerAddressSpace();
  863. FunctionUseMap FunctionUses;
  864. if (!IsPtrUsedByLoweredFn(Ptr, FunctionUses))
  865. return nullptr;
  866. // Translate vectors to arrays in type, but don't SROA
  867. Type *NewTy = GetLoweredUDT(cast<StructType>(Ty), &TypeSys);
  868. // No work to do here, but prevent SROA.
  869. if (Ty == NewTy && AddrSpace != DXIL::kTGSMAddrSpace)
  870. return Ptr;
  871. // If type changed, replace value, otherwise casting may still
  872. // require a rewrite of the calls.
  873. Value *NewPtr = Ptr;
  874. if (Ty != NewTy) {
  875. NewTy = dxilutil::WrapInArrayTypes(NewTy, outerToInnerLengths);
  876. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Ptr)) {
  877. Module &M = *GV->getParent();
  878. // Rewrite init expression for arrays instead of vectors
  879. Constant *Init = GV->hasInitializer() ?
  880. GV->getInitializer() : UndefValue::get(Ptr->getType());
  881. Constant *NewInit = TranslateInitForLoweredUDT(
  882. Init, NewTy, &TypeSys);
  883. // Replace with new GV, and rewrite vector load/store users
  884. GlobalVariable *NewGV = new GlobalVariable(
  885. M, NewTy, GV->isConstant(), GV->getLinkage(),
  886. NewInit, GV->getName(), /*InsertBefore*/ GV,
  887. GV->getThreadLocalMode(), AddrSpace);
  888. NewPtr = NewGV;
  889. } else if (AllocaInst *AI = dyn_cast<AllocaInst>(Ptr)) {
  890. IRBuilder<> Builder(AI);
  891. AllocaInst * NewAI = Builder.CreateAlloca(NewTy, nullptr, AI->getName());
  892. NewPtr = NewAI;
  893. } else {
  894. DXASSERT(false, "Ptr must be global or alloca");
  895. }
  896. // This will rewrite vector load/store users
  897. // and insert bitcasts for CallInst users
  898. ReplaceUsesForLoweredUDT(Ptr, NewPtr);
  899. }
  900. // Rewrite the HLIntrinsic calls
  901. for (auto it : FunctionUses) {
  902. CallInst *CI = it.first;
  903. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  904. if (group == HLOpcodeGroup::NotHL)
  905. continue;
  906. CallInst *newCI = RewriteIntrinsicCallForCastedArg(CI, it.second);
  907. CI->replaceAllUsesWith(newCI);
  908. CI->eraseFromParent();
  909. }
  910. return NewPtr;
  911. }
  912. // performScalarRepl - This algorithm is a simple worklist driven algorithm,
  913. // which runs on all of the alloca instructions in the entry block, removing
  914. // them if they are only used by getelementptr instructions.
  915. //
  916. bool SROA_HLSL::performScalarRepl(Function &F, DxilTypeSystem &typeSys) {
  917. std::vector<AllocaInst *> AllocaList;
  918. const DataLayout &DL = F.getParent()->getDataLayout();
  919. // Make sure big alloca split first.
  920. // This will simplify memcpy check between part of big alloca and small
  921. // alloca. Big alloca will be split to smaller piece first, when process the
  922. // alloca, it will be alloca flattened from big alloca instead of a GEP of big
  923. // alloca.
  924. auto size_cmp = [&DL](const AllocaInst *a0, const AllocaInst *a1) -> bool {
  925. Type* a0ty = a0->getAllocatedType();
  926. Type* a1ty = a1->getAllocatedType();
  927. bool isUnitSzStruct0 = a0ty->isStructTy() && a0ty->getStructNumElements() == 1;
  928. bool isUnitSzStruct1 = a1ty->isStructTy() && a1ty->getStructNumElements() == 1;
  929. auto sz0 = DL.getTypeAllocSize(a0ty);
  930. auto sz1 = DL.getTypeAllocSize(a1ty);
  931. if (sz0 == sz1 && (isUnitSzStruct0 || isUnitSzStruct1))
  932. return getNestedLevelInStruct(a0ty) < getNestedLevelInStruct(a1ty);
  933. return sz0 < sz1;
  934. };
  935. std::priority_queue<AllocaInst *, std::vector<AllocaInst *>,
  936. std::function<bool(AllocaInst *, AllocaInst *)>>
  937. WorkList(size_cmp);
  938. // Scan the entry basic block, adding allocas to the worklist.
  939. BasicBlock &BB = F.getEntryBlock();
  940. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
  941. if (AllocaInst *A = dyn_cast<AllocaInst>(I)) {
  942. if (!A->user_empty()) {
  943. WorkList.push(A);
  944. // merge GEP use for the allocs
  945. HLModule::MergeGepUse(A);
  946. }
  947. }
  948. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  949. // Process the worklist
  950. bool Changed = false;
  951. while (!WorkList.empty()) {
  952. AllocaInst *AI = WorkList.top();
  953. WorkList.pop();
  954. // Handle dead allocas trivially. These can be formed by SROA'ing arrays
  955. // with unused elements.
  956. if (AI->use_empty()) {
  957. AI->eraseFromParent();
  958. Changed = true;
  959. continue;
  960. }
  961. const bool bAllowReplace = true;
  962. DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  963. if (SROA_Helper::LowerMemcpy(AI, /*annotation*/ nullptr, typeSys, DL,
  964. DT, bAllowReplace)) {
  965. Changed = true;
  966. continue;
  967. }
  968. // If this alloca is impossible for us to promote, reject it early.
  969. if (AI->isArrayAllocation() || !AI->getAllocatedType()->isSized())
  970. continue;
  971. // Check to see if we can perform the core SROA transformation. We cannot
  972. // transform the allocation instruction if it is an array allocation
  973. // (allocations OF arrays are ok though), and an allocation of a scalar
  974. // value cannot be decomposed at all.
  975. uint64_t AllocaSize = DL.getTypeAllocSize(AI->getAllocatedType());
  976. // Do not promote [0 x %struct].
  977. if (AllocaSize == 0)
  978. continue;
  979. Type *Ty = AI->getAllocatedType();
  980. // Skip empty struct type.
  981. if (SROA_Helper::IsEmptyStructType(Ty, typeSys)) {
  982. SROA_Helper::MarkEmptyStructUsers(AI, DeadInsts);
  983. DeleteDeadInstructions();
  984. continue;
  985. }
  986. if (Value *NewV = TranslatePtrIfUsedByLoweredFn(AI, typeSys)) {
  987. if (NewV != AI) {
  988. DXASSERT(AI->getNumUses() == 0, "must have zero users.");
  989. AI->eraseFromParent();
  990. Changed = true;
  991. }
  992. continue;
  993. }
  994. // If the alloca looks like a good candidate for scalar replacement, and
  995. // if
  996. // all its users can be transformed, then split up the aggregate into its
  997. // separate elements.
  998. if (ShouldAttemptScalarRepl(AI) && isSafeAllocaToScalarRepl(AI)) {
  999. std::vector<Value *> Elts;
  1000. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(AI));
  1001. bool hasPrecise = HLModule::HasPreciseAttributeWithMetadata(AI);
  1002. Type *BrokenUpTy = nullptr;
  1003. uint64_t NumInstances = 1;
  1004. DominatorTree *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1005. bool SROAed = SROA_Helper::DoScalarReplacement(
  1006. AI, Elts, BrokenUpTy, NumInstances, Builder,
  1007. /*bFlatVector*/ true, hasPrecise, typeSys, DL, DeadInsts, DT);
  1008. if (SROAed) {
  1009. Type *Ty = AI->getAllocatedType();
  1010. // Skip empty struct parameters.
  1011. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1012. if (!HLMatrixType::isa(Ty)) {
  1013. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  1014. if (SA && SA->IsEmptyStruct()) {
  1015. for (User *U : AI->users()) {
  1016. if (StoreInst *SI = dyn_cast<StoreInst>(U))
  1017. DeadInsts.emplace_back(SI);
  1018. }
  1019. DeleteDeadInstructions();
  1020. AI->replaceAllUsesWith(UndefValue::get(AI->getType()));
  1021. AI->eraseFromParent();
  1022. continue;
  1023. }
  1024. }
  1025. }
  1026. addDebugInfoForElements(AI, BrokenUpTy, NumInstances, Elts, DL, &DIB);
  1027. // Push Elts into workList.
  1028. for (unsigned EltIdx = 0; EltIdx < Elts.size(); ++EltIdx) {
  1029. AllocaInst *EltAlloca = cast<AllocaInst>(Elts[EltIdx]);
  1030. WorkList.push(EltAlloca);
  1031. }
  1032. // Now erase any instructions that were made dead while rewriting the
  1033. // alloca.
  1034. DeleteDeadInstructions();
  1035. ++NumReplaced;
  1036. DXASSERT(AI->getNumUses() == 0, "must have zero users.");
  1037. AI->eraseFromParent();
  1038. Changed = true;
  1039. continue;
  1040. }
  1041. }
  1042. }
  1043. return Changed;
  1044. }
  1045. // markPrecise - To save the precise attribute on alloca inst which might be removed by promote,
  1046. // mark precise attribute with function call on alloca inst stores.
  1047. bool SROA_HLSL::markPrecise(Function &F) {
  1048. bool Changed = false;
  1049. BasicBlock &BB = F.getEntryBlock();
  1050. for (BasicBlock::iterator I = BB.begin(), E = BB.end(); I != E; ++I)
  1051. if (AllocaInst *A = dyn_cast<AllocaInst>(I)) {
  1052. // TODO: Only do this on basic types.
  1053. if (HLModule::HasPreciseAttributeWithMetadata(A)) {
  1054. HLModule::MarkPreciseAttributeOnPtrWithFunctionCall(A,
  1055. *(F.getParent()));
  1056. Changed = true;
  1057. }
  1058. }
  1059. return Changed;
  1060. }
  1061. /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
  1062. /// recursively including all their operands that become trivially dead.
  1063. void SROA_HLSL::DeleteDeadInstructions() {
  1064. while (!DeadInsts.empty()) {
  1065. Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
  1066. for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
  1067. if (Instruction *U = dyn_cast<Instruction>(*OI)) {
  1068. // Zero out the operand and see if it becomes trivially dead.
  1069. // (But, don't add allocas to the dead instruction list -- they are
  1070. // already on the worklist and will be deleted separately.)
  1071. *OI = nullptr;
  1072. if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
  1073. DeadInsts.push_back(U);
  1074. }
  1075. I->eraseFromParent();
  1076. }
  1077. }
  1078. /// isSafeForScalarRepl - Check if instruction I is a safe use with regard to
  1079. /// performing scalar replacement of alloca AI. The results are flagged in
  1080. /// the Info parameter. Offset indicates the position within AI that is
  1081. /// referenced by this instruction.
  1082. void SROA_HLSL::isSafeForScalarRepl(Instruction *I, uint64_t Offset,
  1083. AllocaInfo &Info) {
  1084. if (I->getType()->isPointerTy()) {
  1085. // Don't check object pointers.
  1086. if (dxilutil::IsHLSLObjectType(I->getType()->getPointerElementType()))
  1087. return;
  1088. }
  1089. const DataLayout &DL = I->getModule()->getDataLayout();
  1090. for (Use &U : I->uses()) {
  1091. Instruction *User = cast<Instruction>(U.getUser());
  1092. if (BitCastInst *BC = dyn_cast<BitCastInst>(User)) {
  1093. isSafeForScalarRepl(BC, Offset, Info);
  1094. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(User)) {
  1095. uint64_t GEPOffset = Offset;
  1096. isSafeGEP(GEPI, GEPOffset, Info);
  1097. if (!Info.isUnsafe)
  1098. isSafeForScalarRepl(GEPI, GEPOffset, Info);
  1099. } else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User)) {
  1100. ConstantInt *Length = dyn_cast<ConstantInt>(MI->getLength());
  1101. if (!Length || Length->isNegative())
  1102. return MarkUnsafe(Info, User);
  1103. isSafeMemAccess(Offset, Length->getZExtValue(), nullptr,
  1104. U.getOperandNo() == 0, Info, MI,
  1105. true /*AllowWholeAccess*/);
  1106. } else if (LoadInst *LI = dyn_cast<LoadInst>(User)) {
  1107. if (!LI->isSimple())
  1108. return MarkUnsafe(Info, User);
  1109. Type *LIType = LI->getType();
  1110. isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
  1111. LI, true /*AllowWholeAccess*/);
  1112. Info.hasALoadOrStore = true;
  1113. } else if (StoreInst *SI = dyn_cast<StoreInst>(User)) {
  1114. // Store is ok if storing INTO the pointer, not storing the pointer
  1115. if (!SI->isSimple() || SI->getOperand(0) == I)
  1116. return MarkUnsafe(Info, User);
  1117. Type *SIType = SI->getOperand(0)->getType();
  1118. isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
  1119. SI, true /*AllowWholeAccess*/);
  1120. Info.hasALoadOrStore = true;
  1121. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(User)) {
  1122. if (II->getIntrinsicID() != Intrinsic::lifetime_start &&
  1123. II->getIntrinsicID() != Intrinsic::lifetime_end)
  1124. return MarkUnsafe(Info, User);
  1125. } else if (isa<PHINode>(User) || isa<SelectInst>(User)) {
  1126. isSafePHISelectUseForScalarRepl(User, Offset, Info);
  1127. } else if (CallInst *CI = dyn_cast<CallInst>(User)) {
  1128. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  1129. // Most HL functions are safe for scalar repl.
  1130. if (HLOpcodeGroup::NotHL == group)
  1131. return MarkUnsafe(Info, User);
  1132. else if (HLOpcodeGroup::HLIntrinsic == group) {
  1133. // TODO: should we check HL parameter type for UDT overload instead of basing on IOP?
  1134. IntrinsicOp opcode = static_cast<IntrinsicOp>(GetHLOpcode(CI));
  1135. if (IntrinsicOp::IOP_TraceRay == opcode ||
  1136. IntrinsicOp::IOP_ReportHit == opcode ||
  1137. IntrinsicOp::IOP_CallShader == opcode) {
  1138. return MarkUnsafe(Info, User);
  1139. }
  1140. }
  1141. } else {
  1142. return MarkUnsafe(Info, User);
  1143. }
  1144. if (Info.isUnsafe)
  1145. return;
  1146. }
  1147. }
  1148. /// isSafePHIUseForScalarRepl - If we see a PHI node or select using a pointer
  1149. /// derived from the alloca, we can often still split the alloca into elements.
  1150. /// This is useful if we have a large alloca where one element is phi'd
  1151. /// together somewhere: we can SRoA and promote all the other elements even if
  1152. /// we end up not being able to promote this one.
  1153. ///
  1154. /// All we require is that the uses of the PHI do not index into other parts of
  1155. /// the alloca. The most important use case for this is single load and stores
  1156. /// that are PHI'd together, which can happen due to code sinking.
  1157. void SROA_HLSL::isSafePHISelectUseForScalarRepl(Instruction *I, uint64_t Offset,
  1158. AllocaInfo &Info) {
  1159. // If we've already checked this PHI, don't do it again.
  1160. if (PHINode *PN = dyn_cast<PHINode>(I))
  1161. if (!Info.CheckedPHIs.insert(PN).second)
  1162. return;
  1163. const DataLayout &DL = I->getModule()->getDataLayout();
  1164. for (User *U : I->users()) {
  1165. Instruction *UI = cast<Instruction>(U);
  1166. if (BitCastInst *BC = dyn_cast<BitCastInst>(UI)) {
  1167. isSafePHISelectUseForScalarRepl(BC, Offset, Info);
  1168. } else if (GetElementPtrInst *GEPI = dyn_cast<GetElementPtrInst>(UI)) {
  1169. // Only allow "bitcast" GEPs for simplicity. We could generalize this,
  1170. // but would have to prove that we're staying inside of an element being
  1171. // promoted.
  1172. if (!GEPI->hasAllZeroIndices())
  1173. return MarkUnsafe(Info, UI);
  1174. isSafePHISelectUseForScalarRepl(GEPI, Offset, Info);
  1175. } else if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  1176. if (!LI->isSimple())
  1177. return MarkUnsafe(Info, UI);
  1178. Type *LIType = LI->getType();
  1179. isSafeMemAccess(Offset, DL.getTypeAllocSize(LIType), LIType, false, Info,
  1180. LI, false /*AllowWholeAccess*/);
  1181. Info.hasALoadOrStore = true;
  1182. } else if (StoreInst *SI = dyn_cast<StoreInst>(UI)) {
  1183. // Store is ok if storing INTO the pointer, not storing the pointer
  1184. if (!SI->isSimple() || SI->getOperand(0) == I)
  1185. return MarkUnsafe(Info, UI);
  1186. Type *SIType = SI->getOperand(0)->getType();
  1187. isSafeMemAccess(Offset, DL.getTypeAllocSize(SIType), SIType, true, Info,
  1188. SI, false /*AllowWholeAccess*/);
  1189. Info.hasALoadOrStore = true;
  1190. } else if (isa<PHINode>(UI) || isa<SelectInst>(UI)) {
  1191. isSafePHISelectUseForScalarRepl(UI, Offset, Info);
  1192. } else {
  1193. return MarkUnsafe(Info, UI);
  1194. }
  1195. if (Info.isUnsafe)
  1196. return;
  1197. }
  1198. }
  1199. /// isSafeGEP - Check if a GEP instruction can be handled for scalar
  1200. /// replacement. It is safe when all the indices are constant, in-bounds
  1201. /// references, and when the resulting offset corresponds to an element within
  1202. /// the alloca type. The results are flagged in the Info parameter. Upon
  1203. /// return, Offset is adjusted as specified by the GEP indices.
  1204. void SROA_HLSL::isSafeGEP(GetElementPtrInst *GEPI, uint64_t &Offset,
  1205. AllocaInfo &Info) {
  1206. gep_type_iterator GEPIt = gep_type_begin(GEPI), E = gep_type_end(GEPI);
  1207. if (GEPIt == E)
  1208. return;
  1209. bool NonConstant = false;
  1210. unsigned NonConstantIdxSize = 0;
  1211. // Compute the offset due to this GEP and check if the alloca has a
  1212. // component element at that offset.
  1213. SmallVector<Value *, 8> Indices(GEPI->op_begin() + 1, GEPI->op_end());
  1214. auto indicesIt = Indices.begin();
  1215. // Walk through the GEP type indices, checking the types that this indexes
  1216. // into.
  1217. uint32_t arraySize = 0;
  1218. bool isArrayIndexing = false;
  1219. for (;GEPIt != E; ++GEPIt) {
  1220. Type *Ty = *GEPIt;
  1221. if (Ty->isStructTy() && !HLMatrixType::isa(Ty)) {
  1222. // Don't go inside struct when mark hasArrayIndexing and hasVectorIndexing.
  1223. // The following level won't affect scalar repl on the struct.
  1224. break;
  1225. }
  1226. if (GEPIt->isArrayTy()) {
  1227. arraySize = GEPIt->getArrayNumElements();
  1228. isArrayIndexing = true;
  1229. }
  1230. if (GEPIt->isVectorTy()) {
  1231. arraySize = GEPIt->getVectorNumElements();
  1232. isArrayIndexing = false;
  1233. }
  1234. // Allow dynamic indexing
  1235. ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
  1236. if (!IdxVal) {
  1237. // for dynamic index, use array size - 1 to check the offset
  1238. *indicesIt = Constant::getIntegerValue(
  1239. Type::getInt32Ty(GEPI->getContext()), APInt(32, arraySize - 1));
  1240. if (isArrayIndexing)
  1241. Info.hasArrayIndexing = true;
  1242. else
  1243. Info.hasVectorIndexing = true;
  1244. NonConstant = true;
  1245. }
  1246. indicesIt++;
  1247. }
  1248. // Continue iterate only for the NonConstant.
  1249. for (;GEPIt != E; ++GEPIt) {
  1250. Type *Ty = *GEPIt;
  1251. if (Ty->isArrayTy()) {
  1252. arraySize = GEPIt->getArrayNumElements();
  1253. }
  1254. if (Ty->isVectorTy()) {
  1255. arraySize = GEPIt->getVectorNumElements();
  1256. }
  1257. // Allow dynamic indexing
  1258. ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
  1259. if (!IdxVal) {
  1260. // for dynamic index, use array size - 1 to check the offset
  1261. *indicesIt = Constant::getIntegerValue(
  1262. Type::getInt32Ty(GEPI->getContext()), APInt(32, arraySize - 1));
  1263. NonConstant = true;
  1264. }
  1265. indicesIt++;
  1266. }
  1267. // If this GEP is non-constant then the last operand must have been a
  1268. // dynamic index into a vector. Pop this now as it has no impact on the
  1269. // constant part of the offset.
  1270. if (NonConstant)
  1271. Indices.pop_back();
  1272. const DataLayout &DL = GEPI->getModule()->getDataLayout();
  1273. Offset += DL.getIndexedOffset(GEPI->getPointerOperandType(), Indices);
  1274. if (!TypeHasComponent(Info.AI->getAllocatedType(), Offset, NonConstantIdxSize,
  1275. DL))
  1276. MarkUnsafe(Info, GEPI);
  1277. }
  1278. /// isHomogeneousAggregate - Check if type T is a struct or array containing
  1279. /// elements of the same type (which is always true for arrays). If so,
  1280. /// return true with NumElts and EltTy set to the number of elements and the
  1281. /// element type, respectively.
  1282. static bool isHomogeneousAggregate(Type *T, unsigned &NumElts, Type *&EltTy) {
  1283. if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
  1284. NumElts = AT->getNumElements();
  1285. EltTy = (NumElts == 0 ? nullptr : AT->getElementType());
  1286. return true;
  1287. }
  1288. if (StructType *ST = dyn_cast<StructType>(T)) {
  1289. NumElts = ST->getNumContainedTypes();
  1290. EltTy = (NumElts == 0 ? nullptr : ST->getContainedType(0));
  1291. for (unsigned n = 1; n < NumElts; ++n) {
  1292. if (ST->getContainedType(n) != EltTy)
  1293. return false;
  1294. }
  1295. return true;
  1296. }
  1297. return false;
  1298. }
  1299. /// isCompatibleAggregate - Check if T1 and T2 are either the same type or are
  1300. /// "homogeneous" aggregates with the same element type and number of elements.
  1301. static bool isCompatibleAggregate(Type *T1, Type *T2) {
  1302. if (T1 == T2)
  1303. return true;
  1304. unsigned NumElts1, NumElts2;
  1305. Type *EltTy1, *EltTy2;
  1306. if (isHomogeneousAggregate(T1, NumElts1, EltTy1) &&
  1307. isHomogeneousAggregate(T2, NumElts2, EltTy2) && NumElts1 == NumElts2 &&
  1308. EltTy1 == EltTy2)
  1309. return true;
  1310. return false;
  1311. }
  1312. /// isSafeMemAccess - Check if a load/store/memcpy operates on the entire AI
  1313. /// alloca or has an offset and size that corresponds to a component element
  1314. /// within it. The offset checked here may have been formed from a GEP with a
  1315. /// pointer bitcasted to a different type.
  1316. ///
  1317. /// If AllowWholeAccess is true, then this allows uses of the entire alloca as a
  1318. /// unit. If false, it only allows accesses known to be in a single element.
  1319. void SROA_HLSL::isSafeMemAccess(uint64_t Offset, uint64_t MemSize,
  1320. Type *MemOpType, bool isStore, AllocaInfo &Info,
  1321. Instruction *TheAccess, bool AllowWholeAccess) {
  1322. // What hlsl cares is Info.hasVectorIndexing.
  1323. // Do nothing here.
  1324. }
  1325. /// TypeHasComponent - Return true if T has a component type with the
  1326. /// specified offset and size. If Size is zero, do not check the size.
  1327. bool SROA_HLSL::TypeHasComponent(Type *T, uint64_t Offset, uint64_t Size,
  1328. const DataLayout &DL) {
  1329. Type *EltTy;
  1330. uint64_t EltSize;
  1331. if (StructType *ST = dyn_cast<StructType>(T)) {
  1332. const StructLayout *Layout = DL.getStructLayout(ST);
  1333. unsigned EltIdx = Layout->getElementContainingOffset(Offset);
  1334. EltTy = ST->getContainedType(EltIdx);
  1335. EltSize = DL.getTypeAllocSize(EltTy);
  1336. Offset -= Layout->getElementOffset(EltIdx);
  1337. } else if (ArrayType *AT = dyn_cast<ArrayType>(T)) {
  1338. EltTy = AT->getElementType();
  1339. EltSize = DL.getTypeAllocSize(EltTy);
  1340. if (Offset >= AT->getNumElements() * EltSize)
  1341. return false;
  1342. Offset %= EltSize;
  1343. } else if (VectorType *VT = dyn_cast<VectorType>(T)) {
  1344. EltTy = VT->getElementType();
  1345. EltSize = DL.getTypeAllocSize(EltTy);
  1346. if (Offset >= VT->getNumElements() * EltSize)
  1347. return false;
  1348. Offset %= EltSize;
  1349. } else {
  1350. return false;
  1351. }
  1352. if (Offset == 0 && (Size == 0 || EltSize == Size))
  1353. return true;
  1354. // Check if the component spans multiple elements.
  1355. if (Offset + Size > EltSize)
  1356. return false;
  1357. return TypeHasComponent(EltTy, Offset, Size, DL);
  1358. }
  1359. /// LoadVectorArray - Load vector array like [2 x <4 x float>] from
  1360. /// arrays like 4 [2 x float] or struct array like
  1361. /// [2 x { <4 x float>, < 4 x uint> }]
  1362. /// from arrays like [ 2 x <4 x float> ], [ 2 x <4 x uint> ].
  1363. static Value *LoadVectorOrStructArray(ArrayType *AT, ArrayRef<Value *> NewElts,
  1364. SmallVector<Value *, 8> &idxList,
  1365. IRBuilder<> &Builder) {
  1366. Type *EltTy = AT->getElementType();
  1367. Value *retVal = llvm::UndefValue::get(AT);
  1368. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  1369. uint32_t arraySize = AT->getNumElements();
  1370. for (uint32_t i = 0; i < arraySize; i++) {
  1371. Constant *idx = ConstantInt::get(i32Ty, i);
  1372. idxList.emplace_back(idx);
  1373. if (ArrayType *EltAT = dyn_cast<ArrayType>(EltTy)) {
  1374. Value *EltVal = LoadVectorOrStructArray(EltAT, NewElts, idxList, Builder);
  1375. retVal = Builder.CreateInsertValue(retVal, EltVal, i);
  1376. } else {
  1377. assert((EltTy->isVectorTy() ||
  1378. EltTy->isStructTy()) && "must be a vector or struct type");
  1379. bool isVectorTy = EltTy->isVectorTy();
  1380. Value *retVec = llvm::UndefValue::get(EltTy);
  1381. if (isVectorTy) {
  1382. for (uint32_t c = 0; c < EltTy->getVectorNumElements(); c++) {
  1383. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1384. Value *elt = Builder.CreateLoad(GEP);
  1385. retVec = Builder.CreateInsertElement(retVec, elt, c);
  1386. }
  1387. } else {
  1388. for (uint32_t c = 0; c < EltTy->getStructNumElements(); c++) {
  1389. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1390. Value *elt = Builder.CreateLoad(GEP);
  1391. retVec = Builder.CreateInsertValue(retVec, elt, c);
  1392. }
  1393. }
  1394. retVal = Builder.CreateInsertValue(retVal, retVec, i);
  1395. }
  1396. idxList.pop_back();
  1397. }
  1398. return retVal;
  1399. }
  1400. /// LoadVectorArray - Store vector array like [2 x <4 x float>] to
  1401. /// arrays like 4 [2 x float] or struct array like
  1402. /// [2 x { <4 x float>, < 4 x uint> }]
  1403. /// from arrays like [ 2 x <4 x float> ], [ 2 x <4 x uint> ].
  1404. static void StoreVectorOrStructArray(ArrayType *AT, Value *val,
  1405. ArrayRef<Value *> NewElts,
  1406. SmallVector<Value *, 8> &idxList,
  1407. IRBuilder<> &Builder) {
  1408. Type *EltTy = AT->getElementType();
  1409. Type *i32Ty = Type::getInt32Ty(EltTy->getContext());
  1410. uint32_t arraySize = AT->getNumElements();
  1411. for (uint32_t i = 0; i < arraySize; i++) {
  1412. Value *elt = Builder.CreateExtractValue(val, i);
  1413. Constant *idx = ConstantInt::get(i32Ty, i);
  1414. idxList.emplace_back(idx);
  1415. if (ArrayType *EltAT = dyn_cast<ArrayType>(EltTy)) {
  1416. StoreVectorOrStructArray(EltAT, elt, NewElts, idxList, Builder);
  1417. } else {
  1418. assert((EltTy->isVectorTy() ||
  1419. EltTy->isStructTy()) && "must be a vector or struct type");
  1420. bool isVectorTy = EltTy->isVectorTy();
  1421. if (isVectorTy) {
  1422. for (uint32_t c = 0; c < EltTy->getVectorNumElements(); c++) {
  1423. Value *component = Builder.CreateExtractElement(elt, c);
  1424. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1425. Builder.CreateStore(component, GEP);
  1426. }
  1427. } else {
  1428. for (uint32_t c = 0; c < EltTy->getStructNumElements(); c++) {
  1429. Value *field = Builder.CreateExtractValue(elt, c);
  1430. Value *GEP = Builder.CreateInBoundsGEP(NewElts[c], idxList);
  1431. Builder.CreateStore(field, GEP);
  1432. }
  1433. }
  1434. }
  1435. idxList.pop_back();
  1436. }
  1437. }
  1438. /// HasPadding - Return true if the specified type has any structure or
  1439. /// alignment padding in between the elements that would be split apart
  1440. /// by SROA; return false otherwise.
  1441. static bool HasPadding(Type *Ty, const DataLayout &DL) {
  1442. if (ArrayType *ATy = dyn_cast<ArrayType>(Ty)) {
  1443. Ty = ATy->getElementType();
  1444. return DL.getTypeSizeInBits(Ty) != DL.getTypeAllocSizeInBits(Ty);
  1445. }
  1446. // SROA currently handles only Arrays and Structs.
  1447. StructType *STy = cast<StructType>(Ty);
  1448. const StructLayout *SL = DL.getStructLayout(STy);
  1449. unsigned PrevFieldBitOffset = 0;
  1450. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1451. unsigned FieldBitOffset = SL->getElementOffsetInBits(i);
  1452. // Check to see if there is any padding between this element and the
  1453. // previous one.
  1454. if (i) {
  1455. unsigned PrevFieldEnd =
  1456. PrevFieldBitOffset + DL.getTypeSizeInBits(STy->getElementType(i - 1));
  1457. if (PrevFieldEnd < FieldBitOffset)
  1458. return true;
  1459. }
  1460. PrevFieldBitOffset = FieldBitOffset;
  1461. }
  1462. // Check for tail padding.
  1463. if (unsigned EltCount = STy->getNumElements()) {
  1464. unsigned PrevFieldEnd =
  1465. PrevFieldBitOffset +
  1466. DL.getTypeSizeInBits(STy->getElementType(EltCount - 1));
  1467. if (PrevFieldEnd < SL->getSizeInBits())
  1468. return true;
  1469. }
  1470. return false;
  1471. }
  1472. /// isSafeStructAllocaToScalarRepl - Check to see if the specified allocation of
  1473. /// an aggregate can be broken down into elements. Return 0 if not, 3 if safe,
  1474. /// or 1 if safe after canonicalization has been performed.
  1475. bool SROA_HLSL::isSafeAllocaToScalarRepl(AllocaInst *AI) {
  1476. // Loop over the use list of the alloca. We can only transform it if all of
  1477. // the users are safe to transform.
  1478. AllocaInfo Info(AI);
  1479. isSafeForScalarRepl(AI, 0, Info);
  1480. if (Info.isUnsafe) {
  1481. DEBUG(dbgs() << "Cannot transform: " << *AI << '\n');
  1482. return false;
  1483. }
  1484. // vector indexing need translate vector into array
  1485. if (Info.hasVectorIndexing)
  1486. return false;
  1487. const DataLayout &DL = AI->getModule()->getDataLayout();
  1488. // Okay, we know all the users are promotable. If the aggregate is a memcpy
  1489. // source and destination, we have to be careful. In particular, the memcpy
  1490. // could be moving around elements that live in structure padding of the LLVM
  1491. // types, but may actually be used. In these cases, we refuse to promote the
  1492. // struct.
  1493. if (Info.isMemCpySrc && Info.isMemCpyDst &&
  1494. HasPadding(AI->getAllocatedType(), DL))
  1495. return false;
  1496. return true;
  1497. }
  1498. // Copy data from srcPtr to destPtr.
  1499. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  1500. llvm::SmallVector<llvm::Value *, 16> &idxList,
  1501. IRBuilder<> &Builder) {
  1502. if (idxList.size() > 1) {
  1503. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  1504. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  1505. }
  1506. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  1507. Builder.CreateStore(ld, DestPtr);
  1508. }
  1509. // Copy srcVal to destPtr.
  1510. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  1511. llvm::SmallVector<llvm::Value *, 16> &idxList,
  1512. IRBuilder<> &Builder) {
  1513. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  1514. Value *Val = SrcVal;
  1515. // Skip beginning pointer type.
  1516. for (unsigned i = 1; i < idxList.size(); i++) {
  1517. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  1518. Type *Ty = Val->getType();
  1519. if (Ty->isAggregateType()) {
  1520. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  1521. }
  1522. }
  1523. Builder.CreateStore(Val, DestGEP);
  1524. }
  1525. static void SimpleCopy(Value *Dest, Value *Src,
  1526. llvm::SmallVector<llvm::Value *, 16> &idxList,
  1527. IRBuilder<> &Builder) {
  1528. if (Src->getType()->isPointerTy())
  1529. SimplePtrCopy(Dest, Src, idxList, Builder);
  1530. else
  1531. SimpleValCopy(Dest, Src, idxList, Builder);
  1532. }
  1533. static Value *CreateMergedGEP(Value *Ptr, SmallVector<Value *, 16> &idxList,
  1534. IRBuilder<> &Builder) {
  1535. if (GEPOperator *GEPPtr = dyn_cast<GEPOperator>(Ptr)) {
  1536. SmallVector<Value *, 2> IdxList(GEPPtr->idx_begin(), GEPPtr->idx_end());
  1537. // skip idxLIst.begin() because it is included in GEPPtr idx.
  1538. IdxList.append(idxList.begin() + 1, idxList.end());
  1539. return Builder.CreateInBoundsGEP(GEPPtr->getPointerOperand(), IdxList);
  1540. } else {
  1541. return Builder.CreateInBoundsGEP(Ptr, idxList);
  1542. }
  1543. }
  1544. static void EltMemCpy(Type *Ty, Value *Dest, Value *Src,
  1545. SmallVector<Value *, 16> &idxList, IRBuilder<> &Builder,
  1546. const DataLayout &DL) {
  1547. Value *DestGEP = CreateMergedGEP(Dest, idxList, Builder);
  1548. Value *SrcGEP = CreateMergedGEP(Src, idxList, Builder);
  1549. unsigned size = DL.getTypeAllocSize(Ty);
  1550. Builder.CreateMemCpy(DestGEP, SrcGEP, size, /* Align */ 1);
  1551. }
  1552. static bool IsMemCpyTy(Type *Ty, DxilTypeSystem &typeSys) {
  1553. if (!Ty->isAggregateType())
  1554. return false;
  1555. if (HLMatrixType::isa(Ty))
  1556. return false;
  1557. if (dxilutil::IsHLSLObjectType(Ty))
  1558. return false;
  1559. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1560. DxilStructAnnotation *STA = typeSys.GetStructAnnotation(ST);
  1561. DXASSERT(STA, "require annotation here");
  1562. if (STA->IsEmptyStruct())
  1563. return false;
  1564. // Skip 1 element struct which the element is basic type.
  1565. // Because create memcpy will create gep on the struct, memcpy the basic
  1566. // type only.
  1567. if (ST->getNumElements() == 1)
  1568. return IsMemCpyTy(ST->getElementType(0), typeSys);
  1569. }
  1570. return true;
  1571. }
  1572. // Split copy into ld/st.
  1573. static void SplitCpy(Type *Ty, Value *Dest, Value *Src,
  1574. SmallVector<Value *, 16> &idxList, IRBuilder<> &Builder,
  1575. const DataLayout &DL, DxilTypeSystem &typeSys,
  1576. const DxilFieldAnnotation *fieldAnnotation, const bool bEltMemCpy = true) {
  1577. if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
  1578. Constant *idx = Constant::getIntegerValue(
  1579. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  1580. idxList.emplace_back(idx);
  1581. SplitCpy(PT->getElementType(), Dest, Src, idxList, Builder, DL, typeSys,
  1582. fieldAnnotation, bEltMemCpy);
  1583. idxList.pop_back();
  1584. } else if (HLMatrixType::isa(Ty)) {
  1585. // If no fieldAnnotation, use row major as default.
  1586. // Only load then store immediately should be fine.
  1587. bool bRowMajor = true;
  1588. if (fieldAnnotation) {
  1589. DXASSERT(fieldAnnotation->HasMatrixAnnotation(),
  1590. "must has matrix annotation");
  1591. bRowMajor = fieldAnnotation->GetMatrixAnnotation().Orientation ==
  1592. MatrixOrientation::RowMajor;
  1593. }
  1594. Module *M = Builder.GetInsertPoint()->getModule();
  1595. Value *DestMatPtr;
  1596. Value *SrcMatPtr;
  1597. if (idxList.size() == 1 && idxList[0] == ConstantInt::get(
  1598. IntegerType::get(Ty->getContext(), 32), APInt(32, 0))) {
  1599. // Avoid creating GEP(0)
  1600. DestMatPtr = Dest;
  1601. SrcMatPtr = Src;
  1602. }
  1603. else {
  1604. DestMatPtr = Builder.CreateInBoundsGEP(Dest, idxList);
  1605. SrcMatPtr = Builder.CreateInBoundsGEP(Src, idxList);
  1606. }
  1607. HLMatLoadStoreOpcode loadOp = bRowMajor
  1608. ? HLMatLoadStoreOpcode::RowMatLoad : HLMatLoadStoreOpcode::ColMatLoad;
  1609. HLMatLoadStoreOpcode storeOp = bRowMajor
  1610. ? HLMatLoadStoreOpcode::RowMatStore : HLMatLoadStoreOpcode::ColMatStore;
  1611. Value *Load = HLModule::EmitHLOperationCall(
  1612. Builder, HLOpcodeGroup::HLMatLoadStore, static_cast<unsigned>(loadOp),
  1613. Ty, { SrcMatPtr }, *M);
  1614. HLModule::EmitHLOperationCall(
  1615. Builder, HLOpcodeGroup::HLMatLoadStore, static_cast<unsigned>(storeOp),
  1616. Ty, { DestMatPtr, Load }, *M);
  1617. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1618. if (dxilutil::IsHLSLObjectType(ST)) {
  1619. // Avoid split HLSL object.
  1620. SimpleCopy(Dest, Src, idxList, Builder);
  1621. return;
  1622. }
  1623. // Built-in structs have no type annotation
  1624. DxilStructAnnotation *STA = typeSys.GetStructAnnotation(ST);
  1625. if (STA && STA->IsEmptyStruct())
  1626. return;
  1627. for (uint32_t i = 0; i < ST->getNumElements(); i++) {
  1628. llvm::Type *ET = ST->getElementType(i);
  1629. Constant *idx = llvm::Constant::getIntegerValue(
  1630. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  1631. idxList.emplace_back(idx);
  1632. if (bEltMemCpy && IsMemCpyTy(ET, typeSys)) {
  1633. EltMemCpy(ET, Dest, Src, idxList, Builder, DL);
  1634. } else {
  1635. DxilFieldAnnotation *EltAnnotation = STA ? &STA->GetFieldAnnotation(i) : nullptr;
  1636. SplitCpy(ET, Dest, Src, idxList, Builder, DL, typeSys, EltAnnotation,
  1637. bEltMemCpy);
  1638. }
  1639. idxList.pop_back();
  1640. }
  1641. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  1642. Type *ET = AT->getElementType();
  1643. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  1644. Constant *idx = Constant::getIntegerValue(
  1645. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  1646. idxList.emplace_back(idx);
  1647. if (bEltMemCpy && IsMemCpyTy(ET, typeSys)) {
  1648. EltMemCpy(ET, Dest, Src, idxList, Builder, DL);
  1649. } else {
  1650. SplitCpy(ET, Dest, Src, idxList, Builder, DL, typeSys, fieldAnnotation,
  1651. bEltMemCpy);
  1652. }
  1653. idxList.pop_back();
  1654. }
  1655. } else {
  1656. SimpleCopy(Dest, Src, idxList, Builder);
  1657. }
  1658. }
  1659. // Given a pointer to a value, produces a list of pointers to
  1660. // all scalar elements of that value and their field annotations, at any nesting level.
  1661. static void SplitPtr(Value *Ptr, // The root value pointer
  1662. SmallVectorImpl<Value *> &IdxList, // GEP indices stack during recursion
  1663. Type *Ty, // Type at the current GEP indirection level
  1664. const DxilFieldAnnotation &Annotation, // Annotation at the current GEP indirection level
  1665. SmallVectorImpl<Value *> &EltPtrList, // Accumulates pointers to each element found
  1666. SmallVectorImpl<const DxilFieldAnnotation*> &EltAnnotationList, // Accumulates field annotations for each element found
  1667. DxilTypeSystem &TypeSys,
  1668. IRBuilder<> &Builder) {
  1669. if (PointerType *PT = dyn_cast<PointerType>(Ty)) {
  1670. Constant *idx = Constant::getIntegerValue(
  1671. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  1672. IdxList.emplace_back(idx);
  1673. SplitPtr(Ptr, IdxList, PT->getElementType(), Annotation,
  1674. EltPtrList, EltAnnotationList, TypeSys, Builder);
  1675. IdxList.pop_back();
  1676. return;
  1677. }
  1678. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1679. if (!HLMatrixType::isa(Ty) && !dxilutil::IsHLSLObjectType(ST)) {
  1680. const DxilStructAnnotation* SA = TypeSys.GetStructAnnotation(ST);
  1681. for (uint32_t i = 0; i < ST->getNumElements(); i++) {
  1682. llvm::Type *EltTy = ST->getElementType(i);
  1683. Constant *idx = llvm::Constant::getIntegerValue(
  1684. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  1685. IdxList.emplace_back(idx);
  1686. SplitPtr(Ptr, IdxList, EltTy, SA->GetFieldAnnotation(i),
  1687. EltPtrList, EltAnnotationList, TypeSys, Builder);
  1688. IdxList.pop_back();
  1689. }
  1690. return;
  1691. }
  1692. }
  1693. if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  1694. if (AT->getArrayNumElements() == 0) {
  1695. // Skip cases like [0 x %struct], nothing to copy
  1696. return;
  1697. }
  1698. Type *ElTy = AT->getElementType();
  1699. SmallVector<ArrayType *, 4> nestArrayTys;
  1700. nestArrayTys.emplace_back(AT);
  1701. // support multi level of array
  1702. while (ElTy->isArrayTy()) {
  1703. ArrayType *ElAT = cast<ArrayType>(ElTy);
  1704. nestArrayTys.emplace_back(ElAT);
  1705. ElTy = ElAT->getElementType();
  1706. }
  1707. if (ElTy->isStructTy() && !HLMatrixType::isa(ElTy)) {
  1708. DXASSERT(0, "Not support array of struct when split pointers.");
  1709. return;
  1710. }
  1711. }
  1712. // Return a pointer to the current element and its annotation
  1713. Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  1714. EltPtrList.emplace_back(GEP);
  1715. EltAnnotationList.emplace_back(&Annotation);
  1716. }
  1717. // Support case when bitcast (gep ptr, 0,0) is transformed into bitcast ptr.
  1718. static unsigned MatchSizeByCheckElementType(Type *Ty, const DataLayout &DL, unsigned size, unsigned level) {
  1719. unsigned ptrSize = DL.getTypeAllocSize(Ty);
  1720. // Size match, return current level.
  1721. if (ptrSize == size) {
  1722. // Do not go deeper for matrix or object.
  1723. if (HLMatrixType::isa(Ty) || dxilutil::IsHLSLObjectType(Ty))
  1724. return level;
  1725. // For struct, go deeper if size not change.
  1726. // This will leave memcpy to deeper level when flatten.
  1727. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1728. if (ST->getNumElements() == 1) {
  1729. return MatchSizeByCheckElementType(ST->getElementType(0), DL, size, level+1);
  1730. }
  1731. }
  1732. // Don't do this for array.
  1733. // Array will be flattened as struct of array.
  1734. return level;
  1735. }
  1736. // Add ZeroIdx cannot make ptrSize bigger.
  1737. if (ptrSize < size)
  1738. return 0;
  1739. // ptrSize > size.
  1740. // Try to use element type to make size match.
  1741. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  1742. return MatchSizeByCheckElementType(ST->getElementType(0), DL, size, level+1);
  1743. } else if (ArrayType *AT = dyn_cast<ArrayType>(Ty)) {
  1744. return MatchSizeByCheckElementType(AT->getElementType(), DL, size, level+1);
  1745. } else {
  1746. return 0;
  1747. }
  1748. }
  1749. static void PatchZeroIdxGEP(Value *Ptr, Value *RawPtr, MemCpyInst *MI,
  1750. unsigned level, IRBuilder<> &Builder) {
  1751. Value *zeroIdx = Builder.getInt32(0);
  1752. Value *GEP = nullptr;
  1753. if (GEPOperator *GEPPtr = dyn_cast<GEPOperator>(Ptr)) {
  1754. SmallVector<Value *, 2> IdxList(GEPPtr->idx_begin(), GEPPtr->idx_end());
  1755. // level not + 1 because it is included in GEPPtr idx.
  1756. IdxList.append(level, zeroIdx);
  1757. GEP = Builder.CreateInBoundsGEP(GEPPtr->getPointerOperand(), IdxList);
  1758. } else {
  1759. SmallVector<Value *, 2> IdxList(level + 1, zeroIdx);
  1760. GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  1761. }
  1762. // Use BitCastInst::Create to prevent idxList from being optimized.
  1763. CastInst *Cast =
  1764. BitCastInst::Create(Instruction::BitCast, GEP, RawPtr->getType());
  1765. Builder.Insert(Cast);
  1766. MI->replaceUsesOfWith(RawPtr, Cast);
  1767. // Remove RawPtr if possible.
  1768. if (RawPtr->user_empty()) {
  1769. if (Instruction *I = dyn_cast<Instruction>(RawPtr)) {
  1770. I->eraseFromParent();
  1771. }
  1772. }
  1773. }
  1774. void MemcpySplitter::PatchMemCpyWithZeroIdxGEP(MemCpyInst *MI,
  1775. const DataLayout &DL) {
  1776. Value *Dest = MI->getRawDest();
  1777. Value *Src = MI->getRawSource();
  1778. // Only remove one level bitcast generated from inline.
  1779. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Dest))
  1780. Dest = BC->getOperand(0);
  1781. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Src))
  1782. Src = BC->getOperand(0);
  1783. IRBuilder<> Builder(MI);
  1784. ConstantInt *zero = Builder.getInt32(0);
  1785. Type *DestTy = Dest->getType()->getPointerElementType();
  1786. Type *SrcTy = Src->getType()->getPointerElementType();
  1787. // Support case when bitcast (gep ptr, 0,0) is transformed into
  1788. // bitcast ptr.
  1789. // Also replace (gep ptr, 0) with ptr.
  1790. ConstantInt *Length = cast<ConstantInt>(MI->getLength());
  1791. unsigned size = Length->getLimitedValue();
  1792. if (unsigned level = MatchSizeByCheckElementType(DestTy, DL, size, 0)) {
  1793. PatchZeroIdxGEP(Dest, MI->getRawDest(), MI, level, Builder);
  1794. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(Dest)) {
  1795. if (GEP->getNumIndices() == 1) {
  1796. Value *idx = *GEP->idx_begin();
  1797. if (idx == zero) {
  1798. GEP->replaceAllUsesWith(GEP->getPointerOperand());
  1799. }
  1800. }
  1801. }
  1802. if (unsigned level = MatchSizeByCheckElementType(SrcTy, DL, size, 0)) {
  1803. PatchZeroIdxGEP(Src, MI->getRawSource(), MI, level, Builder);
  1804. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
  1805. if (GEP->getNumIndices() == 1) {
  1806. Value *idx = *GEP->idx_begin();
  1807. if (idx == zero) {
  1808. GEP->replaceAllUsesWith(GEP->getPointerOperand());
  1809. }
  1810. }
  1811. }
  1812. }
  1813. void MemcpySplitter::PatchMemCpyWithZeroIdxGEP(Module &M) {
  1814. const DataLayout &DL = M.getDataLayout();
  1815. for (Function &F : M.functions()) {
  1816. for (Function::iterator BB = F.begin(), BBE = F.end(); BB != BBE; ++BB) {
  1817. for (BasicBlock::iterator BI = BB->begin(), BE = BB->end(); BI != BE;) {
  1818. // Avoid invalidating the iterator.
  1819. Instruction *I = BI++;
  1820. if (MemCpyInst *MI = dyn_cast<MemCpyInst>(I)) {
  1821. PatchMemCpyWithZeroIdxGEP(MI, DL);
  1822. }
  1823. }
  1824. }
  1825. }
  1826. }
  1827. static void DeleteMemcpy(MemCpyInst *MI) {
  1828. Value *Op0 = MI->getOperand(0);
  1829. Value *Op1 = MI->getOperand(1);
  1830. // delete memcpy
  1831. MI->eraseFromParent();
  1832. if (Instruction *op0 = dyn_cast<Instruction>(Op0)) {
  1833. if (op0->user_empty())
  1834. op0->eraseFromParent();
  1835. }
  1836. if (Instruction *op1 = dyn_cast<Instruction>(Op1)) {
  1837. if (op1->user_empty())
  1838. op1->eraseFromParent();
  1839. }
  1840. }
  1841. // If user is function call, return param annotation to get matrix major.
  1842. static DxilFieldAnnotation *FindAnnotationFromMatUser(Value *Mat,
  1843. DxilTypeSystem &typeSys) {
  1844. for (User *U : Mat->users()) {
  1845. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  1846. Function *F = CI->getCalledFunction();
  1847. if (DxilFunctionAnnotation *Anno = typeSys.GetFunctionAnnotation(F)) {
  1848. for (unsigned i = 0; i < CI->getNumArgOperands(); i++) {
  1849. if (CI->getArgOperand(i) == Mat) {
  1850. return &Anno->GetParameterAnnotation(i);
  1851. }
  1852. }
  1853. }
  1854. }
  1855. }
  1856. return nullptr;
  1857. }
  1858. void MemcpySplitter::SplitMemCpy(MemCpyInst *MI, const DataLayout &DL,
  1859. DxilFieldAnnotation *fieldAnnotation,
  1860. DxilTypeSystem &typeSys, const bool bEltMemCpy) {
  1861. Value *Dest = MI->getRawDest();
  1862. Value *Src = MI->getRawSource();
  1863. // Only remove one level bitcast generated from inline.
  1864. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Dest))
  1865. Dest = BC->getOperand(0);
  1866. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Src))
  1867. Src = BC->getOperand(0);
  1868. if (Dest == Src) {
  1869. // delete self copy.
  1870. DeleteMemcpy(MI);
  1871. return;
  1872. }
  1873. IRBuilder<> Builder(MI);
  1874. Type *DestTy = Dest->getType()->getPointerElementType();
  1875. Type *SrcTy = Src->getType()->getPointerElementType();
  1876. // Allow copy between different address space.
  1877. if (DestTy != SrcTy) {
  1878. return;
  1879. }
  1880. // Try to find fieldAnnotation from user of Dest/Src.
  1881. if (!fieldAnnotation) {
  1882. Type *EltTy = dxilutil::GetArrayEltTy(DestTy);
  1883. if (HLMatrixType::isa(EltTy)) {
  1884. fieldAnnotation = FindAnnotationFromMatUser(Dest, typeSys);
  1885. }
  1886. }
  1887. llvm::SmallVector<llvm::Value *, 16> idxList;
  1888. // split
  1889. // Matrix is treated as scalar type, will not use memcpy.
  1890. // So use nullptr for fieldAnnotation should be safe here.
  1891. SplitCpy(Dest->getType(), Dest, Src, idxList, Builder, DL, typeSys,
  1892. fieldAnnotation, bEltMemCpy);
  1893. // delete memcpy
  1894. DeleteMemcpy(MI);
  1895. }
  1896. void MemcpySplitter::Split(llvm::Function &F) {
  1897. const DataLayout &DL = F.getParent()->getDataLayout();
  1898. SmallVector<Function *, 2> memcpys;
  1899. for (Function &Fn : F.getParent()->functions()) {
  1900. if (Fn.getIntrinsicID() == Intrinsic::memcpy) {
  1901. memcpys.emplace_back(&Fn);
  1902. }
  1903. }
  1904. for (Function *memcpy : memcpys) {
  1905. for (auto U = memcpy->user_begin(); U != memcpy->user_end();) {
  1906. MemCpyInst *MI = cast<MemCpyInst>(*(U++));
  1907. if (MI->getParent()->getParent() != &F)
  1908. continue;
  1909. // Matrix is treated as scalar type, will not use memcpy.
  1910. // So use nullptr for fieldAnnotation should be safe here.
  1911. SplitMemCpy(MI, DL, /*fieldAnnotation*/ nullptr, m_typeSys,
  1912. /*bEltMemCpy*/ false);
  1913. }
  1914. }
  1915. }
  1916. //===----------------------------------------------------------------------===//
  1917. // SRoA Helper
  1918. //===----------------------------------------------------------------------===//
  1919. /// RewriteGEP - Rewrite the GEP to be relative to new element when can find a
  1920. /// new element which is struct field. If cannot find, create new element GEPs
  1921. /// and try to rewrite GEP with new GEPS.
  1922. void SROA_Helper::RewriteForGEP(GEPOperator *GEP, IRBuilder<> &Builder) {
  1923. assert(OldVal == GEP->getPointerOperand() && "");
  1924. Value *NewPointer = nullptr;
  1925. SmallVector<Value *, 8> NewArgs;
  1926. gep_type_iterator GEPIt = gep_type_begin(GEP), E = gep_type_end(GEP);
  1927. for (; GEPIt != E; ++GEPIt) {
  1928. if (GEPIt->isStructTy()) {
  1929. // must be const
  1930. ConstantInt *IdxVal = dyn_cast<ConstantInt>(GEPIt.getOperand());
  1931. assert(IdxVal->getLimitedValue() < NewElts.size() && "");
  1932. NewPointer = NewElts[IdxVal->getLimitedValue()];
  1933. // The idx is used for NewPointer, not part of newGEP idx,
  1934. GEPIt++;
  1935. break;
  1936. } else if (GEPIt->isArrayTy()) {
  1937. // Add array idx.
  1938. NewArgs.push_back(GEPIt.getOperand());
  1939. } else if (GEPIt->isPointerTy()) {
  1940. // Add pointer idx.
  1941. NewArgs.push_back(GEPIt.getOperand());
  1942. } else if (GEPIt->isVectorTy()) {
  1943. // Add vector idx.
  1944. NewArgs.push_back(GEPIt.getOperand());
  1945. } else {
  1946. llvm_unreachable("should break from structTy");
  1947. }
  1948. }
  1949. if (NewPointer) {
  1950. // Struct split.
  1951. // Add rest of idx.
  1952. for (; GEPIt != E; ++GEPIt) {
  1953. NewArgs.push_back(GEPIt.getOperand());
  1954. }
  1955. // If only 1 level struct, just use the new pointer.
  1956. Value *NewGEP = NewPointer;
  1957. if (NewArgs.size() > 1) {
  1958. NewGEP = Builder.CreateInBoundsGEP(NewPointer, NewArgs);
  1959. NewGEP->takeName(GEP);
  1960. }
  1961. assert(NewGEP->getType() == GEP->getType() && "type mismatch");
  1962. GEP->replaceAllUsesWith(NewGEP);
  1963. } else {
  1964. // End at array of basic type.
  1965. Type *Ty = GEP->getType()->getPointerElementType();
  1966. if (Ty->isVectorTy() ||
  1967. (Ty->isStructTy() && !dxilutil::IsHLSLObjectType(Ty)) ||
  1968. Ty->isArrayTy()) {
  1969. SmallVector<Value *, 8> NewArgs;
  1970. NewArgs.append(GEP->idx_begin(), GEP->idx_end());
  1971. SmallVector<Value *, 8> NewGEPs;
  1972. // create new geps
  1973. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  1974. Value *NewGEP = Builder.CreateGEP(nullptr, NewElts[i], NewArgs);
  1975. NewGEPs.emplace_back(NewGEP);
  1976. }
  1977. const bool bAllowReplace = isa<AllocaInst>(OldVal);
  1978. if (!SROA_Helper::LowerMemcpy(GEP, /*annoation*/ nullptr, typeSys, DL, DT, bAllowReplace)) {
  1979. SROA_Helper helper(GEP, NewGEPs, DeadInsts, typeSys, DL, DT);
  1980. helper.RewriteForScalarRepl(GEP, Builder);
  1981. for (Value *NewGEP : NewGEPs) {
  1982. if (NewGEP->user_empty() && isa<Instruction>(NewGEP)) {
  1983. // Delete unused newGEP.
  1984. cast<Instruction>(NewGEP)->eraseFromParent();
  1985. }
  1986. }
  1987. }
  1988. } else {
  1989. Value *vecIdx = NewArgs.back();
  1990. if (ConstantInt *immVecIdx = dyn_cast<ConstantInt>(vecIdx)) {
  1991. // Replace vecArray[arrayIdx][immVecIdx]
  1992. // with scalarArray_immVecIdx[arrayIdx]
  1993. // Pop the vecIdx.
  1994. NewArgs.pop_back();
  1995. Value *NewGEP = NewElts[immVecIdx->getLimitedValue()];
  1996. if (NewArgs.size() > 1) {
  1997. NewGEP = Builder.CreateInBoundsGEP(NewGEP, NewArgs);
  1998. NewGEP->takeName(GEP);
  1999. }
  2000. assert(NewGEP->getType() == GEP->getType() && "type mismatch");
  2001. GEP->replaceAllUsesWith(NewGEP);
  2002. } else {
  2003. // dynamic vector indexing.
  2004. assert(0 && "should not reach here");
  2005. }
  2006. }
  2007. }
  2008. // Remove the use so that the caller can keep iterating over its other users
  2009. DXASSERT(GEP->user_empty(), "All uses of the GEP should have been eliminated");
  2010. if (isa<Instruction>(GEP)) {
  2011. GEP->setOperand(GEP->getPointerOperandIndex(), UndefValue::get(GEP->getPointerOperand()->getType()));
  2012. DeadInsts.push_back(GEP);
  2013. }
  2014. else {
  2015. cast<Constant>(GEP)->destroyConstant();
  2016. }
  2017. }
  2018. /// isVectorOrStructArray - Check if T is array of vector or struct.
  2019. static bool isVectorOrStructArray(Type *T) {
  2020. if (!T->isArrayTy())
  2021. return false;
  2022. T = dxilutil::GetArrayEltTy(T);
  2023. return T->isStructTy() || T->isVectorTy();
  2024. }
  2025. static void SimplifyStructValUsage(Value *StructVal, std::vector<Value *> Elts,
  2026. SmallVectorImpl<Value *> &DeadInsts) {
  2027. for (User *user : StructVal->users()) {
  2028. if (ExtractValueInst *Extract = dyn_cast<ExtractValueInst>(user)) {
  2029. DXASSERT(Extract->getNumIndices() == 1, "only support 1 index case");
  2030. unsigned index = Extract->getIndices()[0];
  2031. Value *Elt = Elts[index];
  2032. Extract->replaceAllUsesWith(Elt);
  2033. DeadInsts.emplace_back(Extract);
  2034. } else if (InsertValueInst *Insert = dyn_cast<InsertValueInst>(user)) {
  2035. DXASSERT(Insert->getNumIndices() == 1, "only support 1 index case");
  2036. unsigned index = Insert->getIndices()[0];
  2037. if (Insert->getAggregateOperand() == StructVal) {
  2038. // Update field.
  2039. std::vector<Value *> NewElts = Elts;
  2040. NewElts[index] = Insert->getInsertedValueOperand();
  2041. SimplifyStructValUsage(Insert, NewElts, DeadInsts);
  2042. } else {
  2043. // Insert to another bigger struct.
  2044. IRBuilder<> Builder(Insert);
  2045. Value *TmpStructVal = UndefValue::get(StructVal->getType());
  2046. for (unsigned i = 0; i < Elts.size(); i++) {
  2047. TmpStructVal =
  2048. Builder.CreateInsertValue(TmpStructVal, Elts[i], {i});
  2049. }
  2050. Insert->replaceUsesOfWith(StructVal, TmpStructVal);
  2051. }
  2052. }
  2053. }
  2054. }
  2055. /// RewriteForLoad - Replace OldVal with flattened NewElts in LoadInst.
  2056. void SROA_Helper::RewriteForLoad(LoadInst *LI) {
  2057. Type *LIType = LI->getType();
  2058. Type *ValTy = OldVal->getType()->getPointerElementType();
  2059. IRBuilder<> Builder(LI);
  2060. if (LIType->isVectorTy()) {
  2061. // Replace:
  2062. // %res = load { 2 x i32 }* %alloc
  2063. // with:
  2064. // %load.0 = load i32* %alloc.0
  2065. // %insert.0 insertvalue { 2 x i32 } zeroinitializer, i32 %load.0, 0
  2066. // %load.1 = load i32* %alloc.1
  2067. // %insert = insertvalue { 2 x i32 } %insert.0, i32 %load.1, 1
  2068. Value *Insert = UndefValue::get(LIType);
  2069. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2070. Value *Load = Builder.CreateLoad(NewElts[i], "load");
  2071. Insert = Builder.CreateInsertElement(Insert, Load, i, "insert");
  2072. }
  2073. LI->replaceAllUsesWith(Insert);
  2074. } else if (isCompatibleAggregate(LIType, ValTy)) {
  2075. if (isVectorOrStructArray(LIType)) {
  2076. // Replace:
  2077. // %res = load [2 x <2 x float>] * %alloc
  2078. // with:
  2079. // %load.0 = load [4 x float]* %alloc.0
  2080. // %insert.0 insertvalue [4 x float] zeroinitializer,i32 %load.0,0
  2081. // %load.1 = load [4 x float]* %alloc.1
  2082. // %insert = insertvalue [4 x float] %insert.0, i32 %load.1, 1
  2083. // ...
  2084. Type *i32Ty = Type::getInt32Ty(LIType->getContext());
  2085. Value *zero = ConstantInt::get(i32Ty, 0);
  2086. SmallVector<Value *, 8> idxList;
  2087. idxList.emplace_back(zero);
  2088. Value *newLd =
  2089. LoadVectorOrStructArray(cast<ArrayType>(LIType), NewElts, idxList, Builder);
  2090. LI->replaceAllUsesWith(newLd);
  2091. } else {
  2092. // Replace:
  2093. // %res = load { i32, i32 }* %alloc
  2094. // with:
  2095. // %load.0 = load i32* %alloc.0
  2096. // %insert.0 insertvalue { i32, i32 } zeroinitializer, i32 %load.0,
  2097. // 0
  2098. // %load.1 = load i32* %alloc.1
  2099. // %insert = insertvalue { i32, i32 } %insert.0, i32 %load.1, 1
  2100. // (Also works for arrays instead of structs)
  2101. Module *M = LI->getModule();
  2102. Value *Insert = UndefValue::get(LIType);
  2103. std::vector<Value *> LdElts(NewElts.size());
  2104. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2105. Value *Ptr = NewElts[i];
  2106. Type *Ty = Ptr->getType()->getPointerElementType();
  2107. Value *Load = nullptr;
  2108. if (!HLMatrixType::isa(Ty))
  2109. Load = Builder.CreateLoad(Ptr, "load");
  2110. else {
  2111. // Generate Matrix Load.
  2112. Load = HLModule::EmitHLOperationCall(
  2113. Builder, HLOpcodeGroup::HLMatLoadStore,
  2114. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad), Ty,
  2115. {Ptr}, *M);
  2116. }
  2117. LdElts[i] = Load;
  2118. Insert = Builder.CreateInsertValue(Insert, Load, i, "insert");
  2119. }
  2120. LI->replaceAllUsesWith(Insert);
  2121. if (LIType->isStructTy()) {
  2122. SimplifyStructValUsage(Insert, LdElts, DeadInsts);
  2123. }
  2124. }
  2125. } else {
  2126. llvm_unreachable("other type don't need rewrite");
  2127. }
  2128. // Remove the use so that the caller can keep iterating over its other users
  2129. LI->setOperand(LI->getPointerOperandIndex(), UndefValue::get(LI->getPointerOperand()->getType()));
  2130. DeadInsts.push_back(LI);
  2131. }
  2132. /// RewriteForStore - Replace OldVal with flattened NewElts in StoreInst.
  2133. void SROA_Helper::RewriteForStore(StoreInst *SI) {
  2134. Value *Val = SI->getOperand(0);
  2135. Type *SIType = Val->getType();
  2136. IRBuilder<> Builder(SI);
  2137. Type *ValTy = OldVal->getType()->getPointerElementType();
  2138. if (SIType->isVectorTy()) {
  2139. // Replace:
  2140. // store <2 x float> %val, <2 x float>* %alloc
  2141. // with:
  2142. // %val.0 = extractelement { 2 x float } %val, 0
  2143. // store i32 %val.0, i32* %alloc.0
  2144. // %val.1 = extractelement { 2 x float } %val, 1
  2145. // store i32 %val.1, i32* %alloc.1
  2146. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2147. Value *Extract = Builder.CreateExtractElement(Val, i, Val->getName());
  2148. Builder.CreateStore(Extract, NewElts[i]);
  2149. }
  2150. } else if (isCompatibleAggregate(SIType, ValTy)) {
  2151. if (isVectorOrStructArray(SIType)) {
  2152. // Replace:
  2153. // store [2 x <2 x i32>] %val, [2 x <2 x i32>]* %alloc, align 16
  2154. // with:
  2155. // %val.0 = extractvalue [2 x <2 x i32>] %val, 0
  2156. // %all0c.0.0 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.0,
  2157. // i32 0, i32 0
  2158. // %val.0.0 = extractelement <2 x i32> %243, i64 0
  2159. // store i32 %val.0.0, i32* %all0c.0.0
  2160. // %alloc.1.0 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.1,
  2161. // i32 0, i32 0
  2162. // %val.0.1 = extractelement <2 x i32> %243, i64 1
  2163. // store i32 %val.0.1, i32* %alloc.1.0
  2164. // %val.1 = extractvalue [2 x <2 x i32>] %val, 1
  2165. // %alloc.0.0 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.0,
  2166. // i32 0, i32 1
  2167. // %val.1.0 = extractelement <2 x i32> %248, i64 0
  2168. // store i32 %val.1.0, i32* %alloc.0.0
  2169. // %all0c.1.1 = getelementptr inbounds [2 x i32], [2 x i32]* %alloc.1,
  2170. // i32 0, i32 1
  2171. // %val.1.1 = extractelement <2 x i32> %248, i64 1
  2172. // store i32 %val.1.1, i32* %all0c.1.1
  2173. ArrayType *AT = cast<ArrayType>(SIType);
  2174. Type *i32Ty = Type::getInt32Ty(SIType->getContext());
  2175. Value *zero = ConstantInt::get(i32Ty, 0);
  2176. SmallVector<Value *, 8> idxList;
  2177. idxList.emplace_back(zero);
  2178. StoreVectorOrStructArray(AT, Val, NewElts, idxList, Builder);
  2179. } else {
  2180. // Replace:
  2181. // store { i32, i32 } %val, { i32, i32 }* %alloc
  2182. // with:
  2183. // %val.0 = extractvalue { i32, i32 } %val, 0
  2184. // store i32 %val.0, i32* %alloc.0
  2185. // %val.1 = extractvalue { i32, i32 } %val, 1
  2186. // store i32 %val.1, i32* %alloc.1
  2187. // (Also works for arrays instead of structs)
  2188. Module *M = SI->getModule();
  2189. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2190. Value *Extract = Builder.CreateExtractValue(Val, i, Val->getName());
  2191. if (!HLMatrixType::isa(Extract->getType())) {
  2192. Builder.CreateStore(Extract, NewElts[i]);
  2193. } else {
  2194. // Generate Matrix Store.
  2195. HLModule::EmitHLOperationCall(
  2196. Builder, HLOpcodeGroup::HLMatLoadStore,
  2197. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore),
  2198. Extract->getType(), {NewElts[i], Extract}, *M);
  2199. }
  2200. }
  2201. }
  2202. } else {
  2203. llvm_unreachable("other type don't need rewrite");
  2204. }
  2205. // Remove the use so that the caller can keep iterating over its other users
  2206. SI->setOperand(SI->getPointerOperandIndex(), UndefValue::get(SI->getPointerOperand()->getType()));
  2207. DeadInsts.push_back(SI);
  2208. }
  2209. /// RewriteMemIntrin - MI is a memcpy/memset/memmove from or to AI.
  2210. /// Rewrite it to copy or set the elements of the scalarized memory.
  2211. void SROA_Helper::RewriteMemIntrin(MemIntrinsic *MI, Value *OldV) {
  2212. // If this is a memcpy/memmove, construct the other pointer as the
  2213. // appropriate type. The "Other" pointer is the pointer that goes to memory
  2214. // that doesn't have anything to do with the alloca that we are promoting. For
  2215. // memset, this Value* stays null.
  2216. Value *OtherPtr = nullptr;
  2217. unsigned MemAlignment = MI->getAlignment();
  2218. if (MemTransferInst *MTI = dyn_cast<MemTransferInst>(MI)) { // memmove/memcopy
  2219. if (OldV == MTI->getRawDest())
  2220. OtherPtr = MTI->getRawSource();
  2221. else {
  2222. assert(OldV == MTI->getRawSource());
  2223. OtherPtr = MTI->getRawDest();
  2224. }
  2225. }
  2226. // If there is an other pointer, we want to convert it to the same pointer
  2227. // type as AI has, so we can GEP through it safely.
  2228. if (OtherPtr) {
  2229. unsigned AddrSpace =
  2230. cast<PointerType>(OtherPtr->getType())->getAddressSpace();
  2231. // Remove bitcasts and all-zero GEPs from OtherPtr. This is an
  2232. // optimization, but it's also required to detect the corner case where
  2233. // both pointer operands are referencing the same memory, and where
  2234. // OtherPtr may be a bitcast or GEP that currently being rewritten. (This
  2235. // function is only called for mem intrinsics that access the whole
  2236. // aggregate, so non-zero GEPs are not an issue here.)
  2237. OtherPtr = OtherPtr->stripPointerCasts();
  2238. // Copying the alloca to itself is a no-op: just delete it.
  2239. if (OtherPtr == OldVal || OtherPtr == NewElts[0]) {
  2240. // This code will run twice for a no-op memcpy -- once for each operand.
  2241. // Put only one reference to MI on the DeadInsts list.
  2242. for (SmallVectorImpl<Value *>::const_iterator I = DeadInsts.begin(),
  2243. E = DeadInsts.end();
  2244. I != E; ++I)
  2245. if (*I == MI)
  2246. return;
  2247. // Remove the uses so that the caller can keep iterating over its other users
  2248. MI->setOperand(0, UndefValue::get(MI->getOperand(0)->getType()));
  2249. MI->setOperand(1, UndefValue::get(MI->getOperand(1)->getType()));
  2250. DeadInsts.push_back(MI);
  2251. return;
  2252. }
  2253. // If the pointer is not the right type, insert a bitcast to the right
  2254. // type.
  2255. Type *NewTy =
  2256. PointerType::get(OldVal->getType()->getPointerElementType(), AddrSpace);
  2257. if (OtherPtr->getType() != NewTy)
  2258. OtherPtr = new BitCastInst(OtherPtr, NewTy, OtherPtr->getName(), MI);
  2259. }
  2260. // Process each element of the aggregate.
  2261. bool SROADest = MI->getRawDest() == OldV;
  2262. Constant *Zero = Constant::getNullValue(Type::getInt32Ty(MI->getContext()));
  2263. const DataLayout &DL = MI->getModule()->getDataLayout();
  2264. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2265. // If this is a memcpy/memmove, emit a GEP of the other element address.
  2266. Value *OtherElt = nullptr;
  2267. unsigned OtherEltAlign = MemAlignment;
  2268. if (OtherPtr) {
  2269. Value *Idx[2] = {Zero,
  2270. ConstantInt::get(Type::getInt32Ty(MI->getContext()), i)};
  2271. OtherElt = GetElementPtrInst::CreateInBounds(
  2272. OtherPtr, Idx, OtherPtr->getName() + "." + Twine(i), MI);
  2273. uint64_t EltOffset;
  2274. PointerType *OtherPtrTy = cast<PointerType>(OtherPtr->getType());
  2275. Type *OtherTy = OtherPtrTy->getElementType();
  2276. if (StructType *ST = dyn_cast<StructType>(OtherTy)) {
  2277. EltOffset = DL.getStructLayout(ST)->getElementOffset(i);
  2278. } else {
  2279. Type *EltTy = cast<SequentialType>(OtherTy)->getElementType();
  2280. EltOffset = DL.getTypeAllocSize(EltTy) * i;
  2281. }
  2282. // The alignment of the other pointer is the guaranteed alignment of the
  2283. // element, which is affected by both the known alignment of the whole
  2284. // mem intrinsic and the alignment of the element. If the alignment of
  2285. // the memcpy (f.e.) is 32 but the element is at a 4-byte offset, then the
  2286. // known alignment is just 4 bytes.
  2287. OtherEltAlign = (unsigned)MinAlign(OtherEltAlign, EltOffset);
  2288. }
  2289. Value *EltPtr = NewElts[i];
  2290. Type *EltTy = cast<PointerType>(EltPtr->getType())->getElementType();
  2291. // If we got down to a scalar, insert a load or store as appropriate.
  2292. if (EltTy->isSingleValueType()) {
  2293. if (isa<MemTransferInst>(MI)) {
  2294. if (SROADest) {
  2295. // From Other to Alloca.
  2296. Value *Elt = new LoadInst(OtherElt, "tmp", false, OtherEltAlign, MI);
  2297. new StoreInst(Elt, EltPtr, MI);
  2298. } else {
  2299. // From Alloca to Other.
  2300. Value *Elt = new LoadInst(EltPtr, "tmp", MI);
  2301. new StoreInst(Elt, OtherElt, false, OtherEltAlign, MI);
  2302. }
  2303. continue;
  2304. }
  2305. assert(isa<MemSetInst>(MI));
  2306. // If the stored element is zero (common case), just store a null
  2307. // constant.
  2308. Constant *StoreVal;
  2309. if (ConstantInt *CI = dyn_cast<ConstantInt>(MI->getArgOperand(1))) {
  2310. if (CI->isZero()) {
  2311. StoreVal = Constant::getNullValue(EltTy); // 0.0, null, 0, <0,0>
  2312. } else {
  2313. // If EltTy is a vector type, get the element type.
  2314. Type *ValTy = EltTy->getScalarType();
  2315. // Construct an integer with the right value.
  2316. unsigned EltSize = DL.getTypeSizeInBits(ValTy);
  2317. APInt OneVal(EltSize, CI->getZExtValue());
  2318. APInt TotalVal(OneVal);
  2319. // Set each byte.
  2320. for (unsigned i = 0; 8 * i < EltSize; ++i) {
  2321. TotalVal = TotalVal.shl(8);
  2322. TotalVal |= OneVal;
  2323. }
  2324. // Convert the integer value to the appropriate type.
  2325. StoreVal = ConstantInt::get(CI->getContext(), TotalVal);
  2326. if (ValTy->isPointerTy())
  2327. StoreVal = ConstantExpr::getIntToPtr(StoreVal, ValTy);
  2328. else if (ValTy->isFloatingPointTy())
  2329. StoreVal = ConstantExpr::getBitCast(StoreVal, ValTy);
  2330. assert(StoreVal->getType() == ValTy && "Type mismatch!");
  2331. // If the requested value was a vector constant, create it.
  2332. if (EltTy->isVectorTy()) {
  2333. unsigned NumElts = cast<VectorType>(EltTy)->getNumElements();
  2334. StoreVal = ConstantVector::getSplat(NumElts, StoreVal);
  2335. }
  2336. }
  2337. new StoreInst(StoreVal, EltPtr, MI);
  2338. continue;
  2339. }
  2340. // Otherwise, if we're storing a byte variable, use a memset call for
  2341. // this element.
  2342. }
  2343. unsigned EltSize = DL.getTypeAllocSize(EltTy);
  2344. if (!EltSize)
  2345. continue;
  2346. IRBuilder<> Builder(MI);
  2347. // Finally, insert the meminst for this element.
  2348. if (isa<MemSetInst>(MI)) {
  2349. Builder.CreateMemSet(EltPtr, MI->getArgOperand(1), EltSize,
  2350. MI->isVolatile());
  2351. } else {
  2352. assert(isa<MemTransferInst>(MI));
  2353. Value *Dst = SROADest ? EltPtr : OtherElt; // Dest ptr
  2354. Value *Src = SROADest ? OtherElt : EltPtr; // Src ptr
  2355. if (isa<MemCpyInst>(MI))
  2356. Builder.CreateMemCpy(Dst, Src, EltSize, OtherEltAlign,
  2357. MI->isVolatile());
  2358. else
  2359. Builder.CreateMemMove(Dst, Src, EltSize, OtherEltAlign,
  2360. MI->isVolatile());
  2361. }
  2362. }
  2363. // Remove the use so that the caller can keep iterating over its other users
  2364. MI->setOperand(0, UndefValue::get(MI->getOperand(0)->getType()));
  2365. if (isa<MemTransferInst>(MI))
  2366. MI->setOperand(1, UndefValue::get(MI->getOperand(1)->getType()));
  2367. DeadInsts.push_back(MI);
  2368. }
  2369. void SROA_Helper::RewriteBitCast(BitCastInst *BCI) {
  2370. // Unused bitcast may be leftover from temporary memcpy
  2371. if (BCI->use_empty()) {
  2372. BCI->eraseFromParent();
  2373. return;
  2374. }
  2375. Type *DstTy = BCI->getType();
  2376. Value *Val = BCI->getOperand(0);
  2377. Type *SrcTy = Val->getType();
  2378. if (!DstTy->isPointerTy()) {
  2379. assert(0 && "Type mismatch.");
  2380. return;
  2381. }
  2382. if (!SrcTy->isPointerTy()) {
  2383. assert(0 && "Type mismatch.");
  2384. return;
  2385. }
  2386. DstTy = DstTy->getPointerElementType();
  2387. SrcTy = SrcTy->getPointerElementType();
  2388. if (!DstTy->isStructTy()) {
  2389. assert(0 && "Type mismatch.");
  2390. return;
  2391. }
  2392. if (!SrcTy->isStructTy()) {
  2393. assert(0 && "Type mismatch.");
  2394. return;
  2395. }
  2396. // Only support bitcast to parent struct type.
  2397. StructType *DstST = cast<StructType>(DstTy);
  2398. StructType *SrcST = cast<StructType>(SrcTy);
  2399. bool bTypeMatch = false;
  2400. unsigned level = 0;
  2401. while (SrcST) {
  2402. level++;
  2403. Type *EltTy = SrcST->getElementType(0);
  2404. if (EltTy == DstST) {
  2405. bTypeMatch = true;
  2406. break;
  2407. }
  2408. SrcST = dyn_cast<StructType>(EltTy);
  2409. }
  2410. if (!bTypeMatch) {
  2411. // If the layouts match, just replace the type
  2412. SrcST = cast<StructType>(SrcTy);
  2413. if (SrcST->isLayoutIdentical(DstST)) {
  2414. BCI->mutateType(Val->getType());
  2415. BCI->replaceAllUsesWith(Val);
  2416. BCI->eraseFromParent();
  2417. return;
  2418. }
  2419. assert(0 && "Type mismatch.");
  2420. return;
  2421. }
  2422. std::vector<Value*> idxList(level+1);
  2423. ConstantInt *zeroIdx = ConstantInt::get(Type::getInt32Ty(Val->getContext()), 0);
  2424. for (unsigned i=0;i<(level+1);i++)
  2425. idxList[i] = zeroIdx;
  2426. IRBuilder<> Builder(BCI);
  2427. Instruction *GEP = cast<Instruction>(Builder.CreateInBoundsGEP(Val, idxList));
  2428. BCI->replaceAllUsesWith(GEP);
  2429. BCI->eraseFromParent();
  2430. IRBuilder<> GEPBuilder(GEP);
  2431. RewriteForGEP(cast<GEPOperator>(GEP), GEPBuilder);
  2432. }
  2433. /// RewriteCallArg - For Functions which don't flat,
  2434. /// replace OldVal with alloca and
  2435. /// copy in copy out data between alloca and flattened NewElts
  2436. /// in CallInst.
  2437. void SROA_Helper::RewriteCallArg(CallInst *CI, unsigned ArgIdx, bool bIn,
  2438. bool bOut) {
  2439. Function *F = CI->getParent()->getParent();
  2440. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  2441. const DataLayout &DL = F->getParent()->getDataLayout();
  2442. Value *userTyV = CI->getArgOperand(ArgIdx);
  2443. PointerType *userTy = cast<PointerType>(userTyV->getType());
  2444. Type *userTyElt = userTy->getElementType();
  2445. Value *Alloca = AllocaBuilder.CreateAlloca(userTyElt);
  2446. IRBuilder<> Builder(CI);
  2447. if (bIn) {
  2448. MemCpyInst *cpy = cast<MemCpyInst>(Builder.CreateMemCpy(
  2449. Alloca, userTyV, DL.getTypeAllocSize(userTyElt), false));
  2450. RewriteMemIntrin(cpy, cpy->getRawSource());
  2451. }
  2452. CI->setArgOperand(ArgIdx, Alloca);
  2453. if (bOut) {
  2454. Builder.SetInsertPoint(CI->getNextNode());
  2455. MemCpyInst *cpy = cast<MemCpyInst>(Builder.CreateMemCpy(
  2456. userTyV, Alloca, DL.getTypeAllocSize(userTyElt), false));
  2457. RewriteMemIntrin(cpy, cpy->getRawSource());
  2458. }
  2459. }
  2460. // Flatten matching OldVal arg to NewElts, optionally loading values (loadElts).
  2461. // Does not replace or clean up old CallInst.
  2462. static CallInst *CreateFlattenedHLIntrinsicCall(
  2463. CallInst *CI, Value* OldVal, ArrayRef<Value*> NewElts, bool loadElts) {
  2464. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  2465. Function *F = CI->getCalledFunction();
  2466. DXASSERT_NOMSG(group == HLOpcodeGroup::HLIntrinsic);
  2467. unsigned opcode = GetHLOpcode(CI);
  2468. IRBuilder<> Builder(CI);
  2469. SmallVector<Value *, 4> flatArgs;
  2470. for (Value *arg : CI->arg_operands()) {
  2471. if (arg == OldVal) {
  2472. for (Value *Elt : NewElts) {
  2473. if (loadElts && Elt->getType()->isPointerTy())
  2474. Elt = Builder.CreateLoad(Elt);
  2475. flatArgs.emplace_back(Elt);
  2476. }
  2477. } else
  2478. flatArgs.emplace_back(arg);
  2479. }
  2480. SmallVector<Type *, 4> flatParamTys;
  2481. for (Value *arg : flatArgs)
  2482. flatParamTys.emplace_back(arg->getType());
  2483. FunctionType *flatFuncTy =
  2484. FunctionType::get(CI->getType(), flatParamTys, false);
  2485. Function *flatF =
  2486. GetOrCreateHLFunction(*F->getParent(), flatFuncTy, group, opcode,
  2487. F->getAttributes().getFnAttributes());
  2488. return Builder.CreateCall(flatF, flatArgs);
  2489. }
  2490. static CallInst *RewriteWithFlattenedHLIntrinsicCall(
  2491. CallInst *CI, Value* OldVal, ArrayRef<Value*> NewElts, bool loadElts) {
  2492. CallInst *flatCI = CreateFlattenedHLIntrinsicCall(
  2493. CI, OldVal, NewElts, /*loadElts*/loadElts);
  2494. CI->replaceAllUsesWith(flatCI);
  2495. // Clear CI operands so we don't try to translate old call again
  2496. for (auto& opit : CI->operands())
  2497. opit.set(UndefValue::get(opit->getType()));
  2498. return flatCI;
  2499. }
  2500. /// RewriteCall - Replace OldVal with flattened NewElts in CallInst.
  2501. void SROA_Helper::RewriteCall(CallInst *CI) {
  2502. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  2503. if (group != HLOpcodeGroup::NotHL) {
  2504. unsigned opcode = GetHLOpcode(CI);
  2505. if (group == HLOpcodeGroup::HLIntrinsic) {
  2506. IntrinsicOp IOP = static_cast<IntrinsicOp>(opcode);
  2507. switch (IOP) {
  2508. case IntrinsicOp::MOP_Append: {
  2509. // Buffer Append already expand in code gen.
  2510. // Must be OutputStream Append here.
  2511. // Every Elt has a pointer type.
  2512. // For Append, this is desired, so don't load.
  2513. RewriteWithFlattenedHLIntrinsicCall(CI, OldVal, NewElts, /*loadElts*/false);
  2514. DeadInsts.push_back(CI);
  2515. } break;
  2516. case IntrinsicOp::IOP_TraceRay: {
  2517. if (OldVal ==
  2518. CI->getArgOperand(HLOperandIndex::kTraceRayRayDescOpIdx)) {
  2519. RewriteCallArg(CI, HLOperandIndex::kTraceRayRayDescOpIdx,
  2520. /*bIn*/ true, /*bOut*/ false);
  2521. } else {
  2522. DXASSERT(OldVal ==
  2523. CI->getArgOperand(HLOperandIndex::kTraceRayPayLoadOpIdx),
  2524. "else invalid TraceRay");
  2525. RewriteCallArg(CI, HLOperandIndex::kTraceRayPayLoadOpIdx,
  2526. /*bIn*/ true, /*bOut*/ true);
  2527. }
  2528. } break;
  2529. case IntrinsicOp::IOP_ReportHit: {
  2530. RewriteCallArg(CI, HLOperandIndex::kReportIntersectionAttributeOpIdx,
  2531. /*bIn*/ true, /*bOut*/ false);
  2532. } break;
  2533. case IntrinsicOp::IOP_CallShader: {
  2534. RewriteCallArg(CI, HLOperandIndex::kCallShaderPayloadOpIdx,
  2535. /*bIn*/ true, /*bOut*/ true);
  2536. } break;
  2537. case IntrinsicOp::MOP_TraceRayInline: {
  2538. if (OldVal ==
  2539. CI->getArgOperand(HLOperandIndex::kTraceRayInlineRayDescOpIdx)) {
  2540. RewriteWithFlattenedHLIntrinsicCall(CI, OldVal, NewElts, /*loadElts*/true);
  2541. DeadInsts.push_back(CI);
  2542. break;
  2543. }
  2544. }
  2545. __fallthrough;
  2546. default:
  2547. // RayQuery this pointer replacement.
  2548. if (OldVal->getType()->isPointerTy() &&
  2549. CI->getNumArgOperands() >= HLOperandIndex::kHandleOpIdx &&
  2550. OldVal == CI->getArgOperand(HLOperandIndex::kHandleOpIdx) &&
  2551. dxilutil::IsHLSLRayQueryType(
  2552. OldVal->getType()->getPointerElementType())) {
  2553. // For RayQuery methods, we want to replace the RayQuery this pointer
  2554. // with a load and use of the underlying handle value.
  2555. // This will allow elimination of RayQuery types earlier.
  2556. RewriteWithFlattenedHLIntrinsicCall(CI, OldVal, NewElts, /*loadElts*/true);
  2557. DeadInsts.push_back(CI);
  2558. break;
  2559. }
  2560. DXASSERT(0, "cannot flatten hlsl intrinsic.");
  2561. }
  2562. }
  2563. // TODO: check other high level dx operations if need to.
  2564. } else {
  2565. DXASSERT(0, "should done at inline");
  2566. }
  2567. }
  2568. /// RewriteForAddrSpaceCast - Rewrite the AddrSpaceCast, either ConstExpr or Inst.
  2569. void SROA_Helper::RewriteForAddrSpaceCast(Value *CE,
  2570. IRBuilder<> &Builder) {
  2571. SmallVector<Value *, 8> NewCasts;
  2572. // create new AddrSpaceCast.
  2573. for (unsigned i = 0, e = NewElts.size(); i != e; ++i) {
  2574. Value *NewCast = Builder.CreateAddrSpaceCast(
  2575. NewElts[i],
  2576. PointerType::get(NewElts[i]->getType()->getPointerElementType(),
  2577. CE->getType()->getPointerAddressSpace()));
  2578. NewCasts.emplace_back(NewCast);
  2579. }
  2580. SROA_Helper helper(CE, NewCasts, DeadInsts, typeSys, DL, DT);
  2581. helper.RewriteForScalarRepl(CE, Builder);
  2582. // Remove the use so that the caller can keep iterating over its other users
  2583. DXASSERT(CE->user_empty(), "All uses of the addrspacecast should have been eliminated");
  2584. if (Instruction *I = dyn_cast<Instruction>(CE))
  2585. I->eraseFromParent();
  2586. else
  2587. cast<Constant>(CE)->destroyConstant();
  2588. }
  2589. /// RewriteForConstExpr - Rewrite the GEP which is ConstantExpr.
  2590. void SROA_Helper::RewriteForConstExpr(ConstantExpr *CE, IRBuilder<> &Builder) {
  2591. if (GEPOperator *GEP = dyn_cast<GEPOperator>(CE)) {
  2592. if (OldVal == GEP->getPointerOperand()) {
  2593. // Flatten GEP.
  2594. RewriteForGEP(GEP, Builder);
  2595. return;
  2596. }
  2597. }
  2598. if (CE->getOpcode() == Instruction::AddrSpaceCast) {
  2599. if (OldVal == CE->getOperand(0)) {
  2600. // Flatten AddrSpaceCast.
  2601. RewriteForAddrSpaceCast(CE, Builder);
  2602. return;
  2603. }
  2604. }
  2605. for (Value::use_iterator UI = CE->use_begin(), E = CE->use_end(); UI != E;) {
  2606. Use &TheUse = *UI++;
  2607. if (Instruction *I = dyn_cast<Instruction>(TheUse.getUser())) {
  2608. IRBuilder<> tmpBuilder(I);
  2609. // Replace CE with constInst.
  2610. Instruction *tmpInst = CE->getAsInstruction();
  2611. tmpBuilder.Insert(tmpInst);
  2612. TheUse.set(tmpInst);
  2613. }
  2614. else {
  2615. RewriteForConstExpr(cast<ConstantExpr>(TheUse.getUser()), Builder);
  2616. }
  2617. }
  2618. // Remove the use so that the caller can keep iterating over its other users
  2619. DXASSERT(CE->user_empty(), "All uses of the constantexpr should have been eliminated");
  2620. CE->destroyConstant();
  2621. }
  2622. /// RewriteForScalarRepl - OldVal is being split into NewElts, so rewrite
  2623. /// users of V, which references it, to use the separate elements.
  2624. void SROA_Helper::RewriteForScalarRepl(Value *V, IRBuilder<> &Builder) {
  2625. // Don't iterate upon the uses explicitly because we'll be removing them,
  2626. // and potentially adding new ones (if expanding memcpys) during the iteration.
  2627. Use* PrevUse = nullptr;
  2628. while (!V->use_empty()) {
  2629. Use &TheUse = *V->use_begin();
  2630. DXASSERT_LOCALVAR(PrevUse, &TheUse != PrevUse,
  2631. "Infinite loop while SROA'ing value, use isn't getting eliminated.");
  2632. PrevUse = &TheUse;
  2633. // Each of these must either call ->eraseFromParent()
  2634. // or null out the use of V so that we make progress.
  2635. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(TheUse.getUser())) {
  2636. RewriteForConstExpr(CE, Builder);
  2637. }
  2638. else {
  2639. Instruction *User = cast<Instruction>(TheUse.getUser());
  2640. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(User)) {
  2641. IRBuilder<> Builder(GEP);
  2642. RewriteForGEP(cast<GEPOperator>(GEP), Builder);
  2643. } else if (LoadInst *ldInst = dyn_cast<LoadInst>(User))
  2644. RewriteForLoad(ldInst);
  2645. else if (StoreInst *stInst = dyn_cast<StoreInst>(User))
  2646. RewriteForStore(stInst);
  2647. else if (MemIntrinsic *MI = dyn_cast<MemIntrinsic>(User))
  2648. RewriteMemIntrin(MI, V);
  2649. else if (CallInst *CI = dyn_cast<CallInst>(User))
  2650. RewriteCall(CI);
  2651. else if (BitCastInst *BCI = dyn_cast<BitCastInst>(User))
  2652. RewriteBitCast(BCI);
  2653. else if (AddrSpaceCastInst *CI = dyn_cast<AddrSpaceCastInst>(User)) {
  2654. RewriteForAddrSpaceCast(CI, Builder);
  2655. } else {
  2656. assert(0 && "not support.");
  2657. }
  2658. }
  2659. }
  2660. }
  2661. static ArrayType *CreateNestArrayTy(Type *FinalEltTy,
  2662. ArrayRef<ArrayType *> nestArrayTys) {
  2663. Type *newAT = FinalEltTy;
  2664. for (auto ArrayTy = nestArrayTys.rbegin(), E=nestArrayTys.rend(); ArrayTy != E;
  2665. ++ArrayTy)
  2666. newAT = ArrayType::get(newAT, (*ArrayTy)->getNumElements());
  2667. return cast<ArrayType>(newAT);
  2668. }
  2669. /// DoScalarReplacement - Split V into AllocaInsts with Builder and save the new AllocaInsts into Elts.
  2670. /// Then do SROA on V.
  2671. bool SROA_Helper::DoScalarReplacement(Value *V, std::vector<Value *> &Elts,
  2672. Type *&BrokenUpTy, uint64_t &NumInstances,
  2673. IRBuilder<> &Builder, bool bFlatVector,
  2674. bool hasPrecise, DxilTypeSystem &typeSys,
  2675. const DataLayout &DL,
  2676. SmallVector<Value *, 32> &DeadInsts,
  2677. DominatorTree *DT) {
  2678. DEBUG(dbgs() << "Found inst to SROA: " << *V << '\n');
  2679. Type *Ty = V->getType();
  2680. // Skip none pointer types.
  2681. if (!Ty->isPointerTy())
  2682. return false;
  2683. Ty = Ty->getPointerElementType();
  2684. // Skip none aggregate types.
  2685. if (!Ty->isAggregateType())
  2686. return false;
  2687. // Skip matrix types.
  2688. if (HLMatrixType::isa(Ty))
  2689. return false;
  2690. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
  2691. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2692. // Skip HLSL object types and RayQuery.
  2693. if (dxilutil::IsHLSLObjectType(ST)) {
  2694. return false;
  2695. }
  2696. BrokenUpTy = ST;
  2697. NumInstances = 1;
  2698. unsigned numTypes = ST->getNumContainedTypes();
  2699. Elts.reserve(numTypes);
  2700. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  2701. // Skip empty struct.
  2702. if (SA && SA->IsEmptyStruct())
  2703. return true;
  2704. for (int i = 0, e = numTypes; i != e; ++i) {
  2705. AllocaInst *NA = AllocaBuilder.CreateAlloca(ST->getContainedType(i), nullptr, V->getName() + "." + Twine(i));
  2706. bool markPrecise = hasPrecise;
  2707. if (SA) {
  2708. DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  2709. markPrecise |= FA.IsPrecise();
  2710. }
  2711. if (markPrecise)
  2712. HLModule::MarkPreciseAttributeWithMetadata(NA);
  2713. Elts.push_back(NA);
  2714. }
  2715. } else {
  2716. ArrayType *AT = cast<ArrayType>(Ty);
  2717. if (AT->getNumContainedTypes() == 0) {
  2718. // Skip case like [0 x %struct].
  2719. return false;
  2720. }
  2721. Type *ElTy = AT->getElementType();
  2722. SmallVector<ArrayType *, 4> nestArrayTys;
  2723. nestArrayTys.emplace_back(AT);
  2724. NumInstances = AT->getNumElements();
  2725. // support multi level of array
  2726. while (ElTy->isArrayTy()) {
  2727. ArrayType *ElAT = cast<ArrayType>(ElTy);
  2728. nestArrayTys.emplace_back(ElAT);
  2729. NumInstances *= ElAT->getNumElements();
  2730. ElTy = ElAT->getElementType();
  2731. }
  2732. BrokenUpTy = ElTy;
  2733. if (ElTy->isStructTy() &&
  2734. // Skip Matrix type.
  2735. !HLMatrixType::isa(ElTy)) {
  2736. if (!dxilutil::IsHLSLObjectType(ElTy)) {
  2737. // for array of struct
  2738. // split into arrays of struct elements
  2739. StructType *ElST = cast<StructType>(ElTy);
  2740. unsigned numTypes = ElST->getNumContainedTypes();
  2741. Elts.reserve(numTypes);
  2742. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ElST);
  2743. // Skip empty struct.
  2744. if (SA && SA->IsEmptyStruct())
  2745. return true;
  2746. for (int i = 0, e = numTypes; i != e; ++i) {
  2747. AllocaInst *NA = AllocaBuilder.CreateAlloca(
  2748. CreateNestArrayTy(ElST->getContainedType(i), nestArrayTys),
  2749. nullptr, V->getName() + "." + Twine(i));
  2750. bool markPrecise = hasPrecise;
  2751. if (SA) {
  2752. DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  2753. markPrecise |= FA.IsPrecise();
  2754. }
  2755. if (markPrecise)
  2756. HLModule::MarkPreciseAttributeWithMetadata(NA);
  2757. Elts.push_back(NA);
  2758. }
  2759. } else {
  2760. // For local resource array which not dynamic indexing,
  2761. // split it.
  2762. if (dxilutil::HasDynamicIndexing(V) ||
  2763. // Only support 1 dim split.
  2764. nestArrayTys.size() > 1)
  2765. return false;
  2766. BrokenUpTy = AT;
  2767. NumInstances = 1;
  2768. for (int i = 0, e = AT->getNumElements(); i != e; ++i) {
  2769. AllocaInst *NA = AllocaBuilder.CreateAlloca(ElTy, nullptr,
  2770. V->getName() + "." + Twine(i));
  2771. Elts.push_back(NA);
  2772. }
  2773. }
  2774. } else if (ElTy->isVectorTy()) {
  2775. // Skip vector if required.
  2776. if (!bFlatVector)
  2777. return false;
  2778. // for array of vector
  2779. // split into arrays of scalar
  2780. VectorType *ElVT = cast<VectorType>(ElTy);
  2781. BrokenUpTy = ElVT;
  2782. Elts.reserve(ElVT->getNumElements());
  2783. ArrayType *scalarArrayTy = CreateNestArrayTy(ElVT->getElementType(), nestArrayTys);
  2784. for (int i = 0, e = ElVT->getNumElements(); i != e; ++i) {
  2785. AllocaInst *NA = AllocaBuilder.CreateAlloca(scalarArrayTy, nullptr,
  2786. V->getName() + "." + Twine(i));
  2787. if (hasPrecise)
  2788. HLModule::MarkPreciseAttributeWithMetadata(NA);
  2789. Elts.push_back(NA);
  2790. }
  2791. } else
  2792. // Skip array of basic types.
  2793. return false;
  2794. }
  2795. // Now that we have created the new alloca instructions, rewrite all the
  2796. // uses of the old alloca.
  2797. SROA_Helper helper(V, Elts, DeadInsts, typeSys, DL, DT);
  2798. helper.RewriteForScalarRepl(V, Builder);
  2799. return true;
  2800. }
  2801. static Constant *GetEltInit(Type *Ty, Constant *Init, unsigned idx,
  2802. Type *EltTy) {
  2803. if (isa<UndefValue>(Init))
  2804. return UndefValue::get(EltTy);
  2805. if (dyn_cast<StructType>(Ty)) {
  2806. return Init->getAggregateElement(idx);
  2807. } else if (dyn_cast<VectorType>(Ty)) {
  2808. return Init->getAggregateElement(idx);
  2809. } else {
  2810. ArrayType *AT = cast<ArrayType>(Ty);
  2811. ArrayType *EltArrayTy = cast<ArrayType>(EltTy);
  2812. std::vector<Constant *> Elts;
  2813. if (!AT->getElementType()->isArrayTy()) {
  2814. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  2815. // Get Array[i]
  2816. Constant *InitArrayElt = Init->getAggregateElement(i);
  2817. // Get Array[i].idx
  2818. InitArrayElt = InitArrayElt->getAggregateElement(idx);
  2819. Elts.emplace_back(InitArrayElt);
  2820. }
  2821. return ConstantArray::get(EltArrayTy, Elts);
  2822. } else {
  2823. Type *EltTy = AT->getElementType();
  2824. ArrayType *NestEltArrayTy = cast<ArrayType>(EltArrayTy->getElementType());
  2825. // Nested array.
  2826. for (unsigned i = 0; i < AT->getNumElements(); i++) {
  2827. // Get Array[i]
  2828. Constant *InitArrayElt = Init->getAggregateElement(i);
  2829. // Get Array[i].idx
  2830. InitArrayElt = GetEltInit(EltTy, InitArrayElt, idx, NestEltArrayTy);
  2831. Elts.emplace_back(InitArrayElt);
  2832. }
  2833. return ConstantArray::get(EltArrayTy, Elts);
  2834. }
  2835. }
  2836. }
  2837. unsigned SROA_Helper::GetEltAlign(unsigned ValueAlign, const DataLayout &DL,
  2838. Type *EltTy, unsigned Offset) {
  2839. unsigned Alignment = ValueAlign;
  2840. if (ValueAlign == 0) {
  2841. // The minimum alignment which users can rely on when the explicit
  2842. // alignment is omitted or zero is that required by the ABI for this
  2843. // type.
  2844. Alignment = DL.getABITypeAlignment(EltTy);
  2845. }
  2846. return MinAlign(Alignment, Offset);
  2847. }
  2848. /// DoScalarReplacement - Split V into AllocaInsts with Builder and save the new AllocaInsts into Elts.
  2849. /// Then do SROA on V.
  2850. bool SROA_Helper::DoScalarReplacement(GlobalVariable *GV,
  2851. std::vector<Value *> &Elts,
  2852. IRBuilder<> &Builder, bool bFlatVector,
  2853. bool hasPrecise, DxilTypeSystem &typeSys,
  2854. const DataLayout &DL,
  2855. SmallVector<Value *, 32> &DeadInsts,
  2856. DominatorTree *DT) {
  2857. DEBUG(dbgs() << "Found inst to SROA: " << *GV << '\n');
  2858. Type *Ty = GV->getType();
  2859. // Skip none pointer types.
  2860. if (!Ty->isPointerTy())
  2861. return false;
  2862. Ty = Ty->getPointerElementType();
  2863. // Skip none aggregate types.
  2864. if (!Ty->isAggregateType() && !bFlatVector)
  2865. return false;
  2866. // Skip basic types.
  2867. if (Ty->isSingleValueType() && !Ty->isVectorTy())
  2868. return false;
  2869. // Skip matrix types.
  2870. if (HLMatrixType::isa(Ty))
  2871. return false;
  2872. Module *M = GV->getParent();
  2873. Constant *Init = GV->hasInitializer() ? GV->getInitializer() : UndefValue::get(Ty);
  2874. bool isConst = GV->isConstant();
  2875. GlobalVariable::ThreadLocalMode TLMode = GV->getThreadLocalMode();
  2876. unsigned AddressSpace = GV->getType()->getAddressSpace();
  2877. GlobalValue::LinkageTypes linkage = GV->getLinkage();
  2878. const unsigned Alignment = GV->getAlignment();
  2879. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  2880. // Skip HLSL object types.
  2881. if (dxilutil::IsHLSLObjectType(ST))
  2882. return false;
  2883. unsigned numTypes = ST->getNumContainedTypes();
  2884. Elts.reserve(numTypes);
  2885. unsigned Offset = 0;
  2886. //DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  2887. for (int i = 0, e = numTypes; i != e; ++i) {
  2888. Type *EltTy = ST->getElementType(i);
  2889. Constant *EltInit = GetEltInit(Ty, Init, i, EltTy);
  2890. GlobalVariable *EltGV = new llvm::GlobalVariable(
  2891. *M, ST->getContainedType(i), /*IsConstant*/ isConst, linkage,
  2892. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  2893. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  2894. EltGV->setAlignment(GetEltAlign(Alignment, DL, EltTy, Offset));
  2895. Offset += DL.getTypeAllocSize(EltTy);
  2896. //DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  2897. // TODO: set precise.
  2898. // if (hasPrecise || FA.IsPrecise())
  2899. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  2900. Elts.push_back(EltGV);
  2901. }
  2902. } else if (VectorType *VT = dyn_cast<VectorType>(Ty)) {
  2903. // TODO: support dynamic indexing on vector by change it to array.
  2904. unsigned numElts = VT->getNumElements();
  2905. Elts.reserve(numElts);
  2906. Type *EltTy = VT->getElementType();
  2907. unsigned Offset = 0;
  2908. //DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  2909. for (int i = 0, e = numElts; i != e; ++i) {
  2910. Constant *EltInit = GetEltInit(Ty, Init, i, EltTy);
  2911. GlobalVariable *EltGV = new llvm::GlobalVariable(
  2912. *M, EltTy, /*IsConstant*/ isConst, linkage,
  2913. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  2914. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  2915. EltGV->setAlignment(GetEltAlign(Alignment, DL, EltTy, Offset));
  2916. Offset += DL.getTypeAllocSize(EltTy);
  2917. //DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  2918. // TODO: set precise.
  2919. // if (hasPrecise || FA.IsPrecise())
  2920. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  2921. Elts.push_back(EltGV);
  2922. }
  2923. } else {
  2924. ArrayType *AT = cast<ArrayType>(Ty);
  2925. if (AT->getNumContainedTypes() == 0) {
  2926. // Skip case like [0 x %struct].
  2927. return false;
  2928. }
  2929. Type *ElTy = AT->getElementType();
  2930. SmallVector<ArrayType *, 4> nestArrayTys;
  2931. nestArrayTys.emplace_back(AT);
  2932. // support multi level of array
  2933. while (ElTy->isArrayTy()) {
  2934. ArrayType *ElAT = cast<ArrayType>(ElTy);
  2935. nestArrayTys.emplace_back(ElAT);
  2936. ElTy = ElAT->getElementType();
  2937. }
  2938. if (ElTy->isStructTy() &&
  2939. // Skip Matrix and Resource type.
  2940. !HLMatrixType::isa(ElTy) &&
  2941. !dxilutil::IsHLSLResourceType(ElTy)) {
  2942. // for array of struct
  2943. // split into arrays of struct elements
  2944. StructType *ElST = cast<StructType>(ElTy);
  2945. unsigned numTypes = ElST->getNumContainedTypes();
  2946. Elts.reserve(numTypes);
  2947. unsigned Offset = 0;
  2948. //DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ElST);
  2949. for (int i = 0, e = numTypes; i != e; ++i) {
  2950. Type *EltTy =
  2951. CreateNestArrayTy(ElST->getContainedType(i), nestArrayTys);
  2952. Constant *EltInit = GetEltInit(Ty, Init, i, EltTy);
  2953. GlobalVariable *EltGV = new llvm::GlobalVariable(
  2954. *M, EltTy, /*IsConstant*/ isConst, linkage,
  2955. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  2956. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  2957. EltGV->setAlignment(GetEltAlign(Alignment, DL, EltTy, Offset));
  2958. Offset += DL.getTypeAllocSize(EltTy);
  2959. //DxilFieldAnnotation &FA = SA->GetFieldAnnotation(i);
  2960. // TODO: set precise.
  2961. // if (hasPrecise || FA.IsPrecise())
  2962. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  2963. Elts.push_back(EltGV);
  2964. }
  2965. } else if (ElTy->isVectorTy()) {
  2966. // Skip vector if required.
  2967. if (!bFlatVector)
  2968. return false;
  2969. // for array of vector
  2970. // split into arrays of scalar
  2971. VectorType *ElVT = cast<VectorType>(ElTy);
  2972. Elts.reserve(ElVT->getNumElements());
  2973. ArrayType *scalarArrayTy =
  2974. CreateNestArrayTy(ElVT->getElementType(), nestArrayTys);
  2975. unsigned Offset = 0;
  2976. for (int i = 0, e = ElVT->getNumElements(); i != e; ++i) {
  2977. Constant *EltInit = GetEltInit(Ty, Init, i, scalarArrayTy);
  2978. GlobalVariable *EltGV = new llvm::GlobalVariable(
  2979. *M, scalarArrayTy, /*IsConstant*/ isConst, linkage,
  2980. /*InitVal*/ EltInit, GV->getName() + "." + Twine(i),
  2981. /*InsertBefore*/ nullptr, TLMode, AddressSpace);
  2982. // TODO: set precise.
  2983. // if (hasPrecise)
  2984. // HLModule::MarkPreciseAttributeWithMetadata(NA);
  2985. EltGV->setAlignment(GetEltAlign(Alignment, DL, scalarArrayTy, Offset));
  2986. Offset += DL.getTypeAllocSize(scalarArrayTy);
  2987. Elts.push_back(EltGV);
  2988. }
  2989. } else
  2990. // Skip array of basic types.
  2991. return false;
  2992. }
  2993. // Now that we have created the new alloca instructions, rewrite all the
  2994. // uses of the old alloca.
  2995. SROA_Helper helper(GV, Elts, DeadInsts, typeSys, DL, DT);
  2996. helper.RewriteForScalarRepl(GV, Builder);
  2997. return true;
  2998. }
  2999. static void ReplaceConstantWithInst(Constant *C, Value *V, IRBuilder<> &Builder) {
  3000. for (auto it = C->user_begin(); it != C->user_end(); ) {
  3001. User *U = *(it++);
  3002. if (Instruction *I = dyn_cast<Instruction>(U)) {
  3003. I->replaceUsesOfWith(C, V);
  3004. } else {
  3005. // Skip unused ConstantExpr.
  3006. if (U->user_empty())
  3007. continue;
  3008. ConstantExpr *CE = cast<ConstantExpr>(U);
  3009. Instruction *Inst = CE->getAsInstruction();
  3010. Builder.Insert(Inst);
  3011. Inst->replaceUsesOfWith(C, V);
  3012. ReplaceConstantWithInst(CE, Inst, Builder);
  3013. }
  3014. }
  3015. C->removeDeadConstantUsers();
  3016. }
  3017. static void ReplaceUnboundedArrayUses(Value *V, Value *Src) {
  3018. for (auto it = V->user_begin(); it != V->user_end(); ) {
  3019. User *U = *(it++);
  3020. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  3021. SmallVector<Value *, 4> idxList(GEP->idx_begin(), GEP->idx_end());
  3022. // Must set the insert point to the GEP itself (instead of the memcpy),
  3023. // because the indices might not dominate the memcpy.
  3024. IRBuilder<> Builder(GEP);
  3025. Value *NewGEP = Builder.CreateGEP(Src, idxList);
  3026. GEP->replaceAllUsesWith(NewGEP);
  3027. } else if (BitCastInst *BC = dyn_cast<BitCastInst>(U)) {
  3028. BC->setOperand(0, Src);
  3029. } else {
  3030. DXASSERT(false, "otherwise unbounded array used in unexpected instruction");
  3031. }
  3032. }
  3033. }
  3034. static bool IsUnboundedArrayMemcpy(Type *destTy, Type *srcTy) {
  3035. return (destTy->isArrayTy() && srcTy->isArrayTy()) &&
  3036. (destTy->getArrayNumElements() == 0 || srcTy->getArrayNumElements() == 0);
  3037. }
  3038. static bool ArePointersToStructsOfIdenticalLayouts(Type *DstTy, Type *SrcTy) {
  3039. if (!SrcTy->isPointerTy() || !DstTy->isPointerTy())
  3040. return false;
  3041. DstTy = DstTy->getPointerElementType();
  3042. SrcTy = SrcTy->getPointerElementType();
  3043. if (!SrcTy->isStructTy() || !DstTy->isStructTy())
  3044. return false;
  3045. StructType *DstST = cast<StructType>(DstTy);
  3046. StructType *SrcST = cast<StructType>(SrcTy);
  3047. return SrcST->isLayoutIdentical(DstST);
  3048. }
  3049. static std::vector<Value *> GetConstValueIdxList(IRBuilder<> &builder,
  3050. std::vector<unsigned> idxlist) {
  3051. std::vector<Value *> idxConstList;
  3052. for (unsigned idx : idxlist) {
  3053. idxConstList.push_back(ConstantInt::get(builder.getInt32Ty(), idx));
  3054. }
  3055. return idxConstList;
  3056. }
  3057. static void CopyElementsOfStructsWithIdenticalLayout(
  3058. IRBuilder<> &builder, Value *destPtr, Value *srcPtr, Type *ty,
  3059. std::vector<unsigned>& idxlist) {
  3060. if (ty->isStructTy()) {
  3061. for (unsigned i = 0; i < ty->getStructNumElements(); i++) {
  3062. idxlist.push_back(i);
  3063. CopyElementsOfStructsWithIdenticalLayout(
  3064. builder, destPtr, srcPtr, ty->getStructElementType(i), idxlist);
  3065. idxlist.pop_back();
  3066. }
  3067. }
  3068. else if (ty->isArrayTy()) {
  3069. for (unsigned i = 0; i < ty->getArrayNumElements(); i++) {
  3070. idxlist.push_back(i);
  3071. CopyElementsOfStructsWithIdenticalLayout(
  3072. builder, destPtr, srcPtr, ty->getArrayElementType(), idxlist);
  3073. idxlist.pop_back();
  3074. }
  3075. }
  3076. else if (ty->isIntegerTy() || ty->isFloatTy() || ty->isDoubleTy() ||
  3077. ty->isHalfTy() || ty->isVectorTy()) {
  3078. Value *srcGEP =
  3079. builder.CreateInBoundsGEP(srcPtr, GetConstValueIdxList(builder, idxlist));
  3080. Value *destGEP =
  3081. builder.CreateInBoundsGEP(destPtr, GetConstValueIdxList(builder, idxlist));
  3082. LoadInst *LI = builder.CreateLoad(srcGEP);
  3083. builder.CreateStore(LI, destGEP);
  3084. }
  3085. else {
  3086. DXASSERT(0, "encountered unsupported type when copying elements of identical structs.");
  3087. }
  3088. }
  3089. static bool DominateAllUsers(Instruction *I, Value *V, DominatorTree *DT);
  3090. static bool ReplaceMemcpy(Value *V, Value *Src, MemCpyInst *MC,
  3091. DxilFieldAnnotation *annotation, DxilTypeSystem &typeSys,
  3092. const DataLayout &DL, DominatorTree *DT) {
  3093. // If the only user of the src and dst is the memcpy,
  3094. // this memcpy was probably produced by splitting another.
  3095. // Regardless, the goal here is to replace, not remove the memcpy
  3096. // we won't have enough information to determine if we can do that before mem2reg
  3097. if (V != Src && V->hasOneUse() && Src->hasOneUse())
  3098. return false;
  3099. // If the memcpy doesn't dominate all its users,
  3100. // full replacement isn't possible without complicated PHI insertion
  3101. // This will likely replace with ld/st which will be replaced in mem2reg
  3102. if (Instruction *SrcI = dyn_cast<Instruction>(Src))
  3103. if (!DominateAllUsers(SrcI, V, DT))
  3104. return false;
  3105. Type *TyV = V->getType()->getPointerElementType();
  3106. Type *TySrc = Src->getType()->getPointerElementType();
  3107. if (Constant *C = dyn_cast<Constant>(V)) {
  3108. if (TyV == TySrc) {
  3109. if (isa<Constant>(Src)) {
  3110. V->replaceAllUsesWith(Src);
  3111. } else {
  3112. // Replace Constant with a non-Constant.
  3113. IRBuilder<> Builder(MC);
  3114. ReplaceConstantWithInst(C, Src, Builder);
  3115. }
  3116. } else {
  3117. IRBuilder<> Builder(MC);
  3118. Src = Builder.CreateBitCast(Src, V->getType());
  3119. ReplaceConstantWithInst(C, Src, Builder);
  3120. }
  3121. } else {
  3122. if (TyV == TySrc) {
  3123. if (V != Src)
  3124. V->replaceAllUsesWith(Src);
  3125. } else if (!IsUnboundedArrayMemcpy(TyV, TySrc)) {
  3126. Value* DestVal = MC->getRawDest();
  3127. Value* SrcVal = MC->getRawSource();
  3128. if (!isa<BitCastInst>(SrcVal) || !isa<BitCastInst>(DestVal)) {
  3129. DXASSERT(0, "Encountered unexpected instruction sequence");
  3130. return false;
  3131. }
  3132. BitCastInst *DestBCI = cast<BitCastInst>(DestVal);
  3133. BitCastInst *SrcBCI = cast<BitCastInst>(SrcVal);
  3134. Type* DstTy = DestBCI->getSrcTy();
  3135. Type *SrcTy = SrcBCI->getSrcTy();
  3136. if (ArePointersToStructsOfIdenticalLayouts(DstTy, SrcTy)) {
  3137. const DataLayout &DL = SrcBCI->getModule()->getDataLayout();
  3138. unsigned SrcSize = DL.getTypeAllocSize(
  3139. SrcBCI->getOperand(0)->getType()->getPointerElementType());
  3140. unsigned MemcpySize = cast<ConstantInt>(MC->getLength())->getZExtValue();
  3141. if (SrcSize != MemcpySize) {
  3142. DXASSERT(0, "Cannot handle partial memcpy");
  3143. return false;
  3144. }
  3145. if (DestBCI->hasOneUse() && SrcBCI->hasOneUse()) {
  3146. IRBuilder<> Builder(MC);
  3147. StructType *srcStTy = cast<StructType>(
  3148. SrcBCI->getOperand(0)->getType()->getPointerElementType());
  3149. std::vector<unsigned> idxlist = {0};
  3150. CopyElementsOfStructsWithIdenticalLayout(
  3151. Builder, DestBCI->getOperand(0), SrcBCI->getOperand(0), srcStTy,
  3152. idxlist);
  3153. }
  3154. } else {
  3155. if (DstTy == SrcTy) {
  3156. Value *DstPtr = DestBCI->getOperand(0);
  3157. Value *SrcPtr = SrcBCI->getOperand(0);
  3158. if (isa<GEPOperator>(DstPtr) || isa<GEPOperator>(SrcPtr)) {
  3159. MemcpySplitter::SplitMemCpy(MC, DL, annotation, typeSys);
  3160. return true;
  3161. } else {
  3162. DstPtr->replaceAllUsesWith(SrcPtr);
  3163. }
  3164. } else {
  3165. DXASSERT(0, "Can't handle structs of different layouts");
  3166. return false;
  3167. }
  3168. }
  3169. } else {
  3170. DXASSERT(IsUnboundedArrayMemcpy(TyV, TySrc), "otherwise mismatched types in memcpy are not unbounded array");
  3171. ReplaceUnboundedArrayUses(V, Src);
  3172. }
  3173. }
  3174. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(Src)) {
  3175. // For const GV, if has stored, mark as non-constant.
  3176. if (GV->isConstant()) {
  3177. hlutil::PointerStatus PS(GV, 0, /*bLdStOnly*/ true);
  3178. PS.analyze(typeSys, /*bStructElt*/ false);
  3179. if (PS.HasStored())
  3180. GV->setConstant(false);
  3181. }
  3182. }
  3183. Value *RawDest = MC->getOperand(0);
  3184. Value *RawSrc = MC->getOperand(1);
  3185. MC->eraseFromParent();
  3186. if (Instruction *I = dyn_cast<Instruction>(RawDest)) {
  3187. if (I->user_empty())
  3188. I->eraseFromParent();
  3189. }
  3190. if (Instruction *I = dyn_cast<Instruction>(RawSrc)) {
  3191. if (I->user_empty())
  3192. I->eraseFromParent();
  3193. }
  3194. return true;
  3195. }
  3196. static bool ReplaceUseOfZeroInitEntry(Instruction *I, Value *V) {
  3197. BasicBlock *BB = I->getParent();
  3198. Function *F = I->getParent()->getParent();
  3199. for (auto U = V->user_begin(); U != V->user_end(); ) {
  3200. Instruction *UI = dyn_cast<Instruction>(*(U++));
  3201. if (!UI)
  3202. continue;
  3203. if (UI->getParent()->getParent() != F)
  3204. continue;
  3205. if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
  3206. if (!ReplaceUseOfZeroInitEntry(I, UI))
  3207. return false;
  3208. else
  3209. continue;
  3210. }
  3211. if (BB != UI->getParent() || UI == I)
  3212. continue;
  3213. // I is the last inst in the block after split.
  3214. // Any inst in current block is before I.
  3215. if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  3216. LI->replaceAllUsesWith(ConstantAggregateZero::get(LI->getType()));
  3217. LI->eraseFromParent();
  3218. continue;
  3219. }
  3220. return false;
  3221. }
  3222. return true;
  3223. }
  3224. static bool ReplaceUseOfZeroInitPostDom(Instruction *I, Value *V,
  3225. PostDominatorTree &PDT) {
  3226. BasicBlock *BB = I->getParent();
  3227. Function *F = I->getParent()->getParent();
  3228. for (auto U = V->user_begin(); U != V->user_end(); ) {
  3229. Instruction *UI = dyn_cast<Instruction>(*(U++));
  3230. if (!UI)
  3231. continue;
  3232. if (UI->getParent()->getParent() != F)
  3233. continue;
  3234. if (!PDT.dominates(BB, UI->getParent()))
  3235. return false;
  3236. if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
  3237. if (!ReplaceUseOfZeroInitPostDom(I, UI, PDT))
  3238. return false;
  3239. else
  3240. continue;
  3241. }
  3242. if (BB != UI->getParent() || UI == I)
  3243. continue;
  3244. // I is the last inst in the block after split.
  3245. // Any inst in current block is before I.
  3246. if (LoadInst *LI = dyn_cast<LoadInst>(UI)) {
  3247. LI->replaceAllUsesWith(ConstantAggregateZero::get(LI->getType()));
  3248. LI->eraseFromParent();
  3249. continue;
  3250. }
  3251. return false;
  3252. }
  3253. return true;
  3254. }
  3255. // When zero initialized GV has only one define, all uses before the def should
  3256. // use zero.
  3257. static bool ReplaceUseOfZeroInitBeforeDef(Instruction *I, GlobalVariable *GV) {
  3258. BasicBlock *BB = I->getParent();
  3259. Function *F = I->getParent()->getParent();
  3260. // Make sure I is the last inst for BB.
  3261. if (I != BB->getTerminator())
  3262. BB->splitBasicBlock(I->getNextNode());
  3263. if (&F->getEntryBlock() == I->getParent()) {
  3264. return ReplaceUseOfZeroInitEntry(I, GV);
  3265. } else {
  3266. // Post dominator tree.
  3267. PostDominatorTree PDT;
  3268. PDT.runOnFunction(*F);
  3269. return ReplaceUseOfZeroInitPostDom(I, GV, PDT);
  3270. }
  3271. }
  3272. static bool DominateAllUsersDom(Instruction *I, Value *V, DominatorTree *DT) {
  3273. BasicBlock *BB = I->getParent();
  3274. for (auto U = V->user_begin(); U != V->user_end(); ) {
  3275. Instruction *UI = dyn_cast<Instruction>(*(U++));
  3276. if (!UI)
  3277. continue;
  3278. assert (UI->getParent()->getParent() == I->getParent()->getParent());
  3279. if (!DT->dominates(BB, UI->getParent()))
  3280. return false;
  3281. if (isa<GetElementPtrInst>(UI) || isa<BitCastInst>(UI)) {
  3282. if (!DominateAllUsersDom(I, UI, DT))
  3283. return false;
  3284. }
  3285. }
  3286. return true;
  3287. }
  3288. // Determine if `I` dominates all the users of `V`
  3289. static bool DominateAllUsers(Instruction *I, Value *V, DominatorTree *DT) {
  3290. Function *F = I->getParent()->getParent();
  3291. // The Entry Block dominates everything, trivially true
  3292. if (&F->getEntryBlock() == I->getParent())
  3293. return true;
  3294. return DominateAllUsersDom(I, V, DT);
  3295. }
  3296. bool SROA_Helper::LowerMemcpy(Value *V, DxilFieldAnnotation *annotation,
  3297. DxilTypeSystem &typeSys, const DataLayout &DL,
  3298. DominatorTree *DT, bool bAllowReplace) {
  3299. Type *Ty = V->getType();
  3300. if (!Ty->isPointerTy()) {
  3301. return false;
  3302. }
  3303. // Get access status and collect memcpy uses.
  3304. // if MemcpyOnce, replace with dest with src if dest is not out param.
  3305. // else flat memcpy.
  3306. unsigned size = DL.getTypeAllocSize(Ty->getPointerElementType());
  3307. hlutil::PointerStatus PS(V, size, /*bLdStOnly*/ false);
  3308. const bool bStructElt = false;
  3309. PS.analyze(typeSys, bStructElt);
  3310. if (GlobalVariable *GV = dyn_cast<GlobalVariable>(V)) {
  3311. if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
  3312. if (PS.storedType == hlutil::PointerStatus::StoredType::NotStored) {
  3313. PS.storedType = hlutil::PointerStatus::StoredType::InitializerStored;
  3314. } else if (PS.storedType ==
  3315. hlutil::PointerStatus::StoredType::MemcopyDestOnce) {
  3316. // For single mem store, if the store does not dominate all users.
  3317. // Mark it as Stored.
  3318. // In cases like:
  3319. // struct A { float4 x[25]; };
  3320. // A a;
  3321. // static A a2;
  3322. // void set(A aa) { aa = a; }
  3323. // call set inside entry function then use a2.
  3324. if (isa<ConstantAggregateZero>(GV->getInitializer())) {
  3325. Instruction * Memcpy = PS.StoringMemcpy;
  3326. if (!ReplaceUseOfZeroInitBeforeDef(Memcpy, GV)) {
  3327. PS.storedType = hlutil::PointerStatus::StoredType::Stored;
  3328. }
  3329. }
  3330. } else {
  3331. PS.storedType = hlutil::PointerStatus::StoredType::Stored;
  3332. }
  3333. }
  3334. }
  3335. if (bAllowReplace && !PS.HasMultipleAccessingFunctions) {
  3336. if (PS.storedType == hlutil::PointerStatus::StoredType::MemcopyDestOnce &&
  3337. // Skip argument for input argument has input value, it is not dest once anymore.
  3338. !isa<Argument>(V)) {
  3339. // Replace with src of memcpy.
  3340. MemCpyInst *MC = PS.StoringMemcpy;
  3341. if (MC->getSourceAddressSpace() == MC->getDestAddressSpace()) {
  3342. Value *Src = MC->getOperand(1);
  3343. // Only remove one level bitcast generated from inline.
  3344. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Src))
  3345. Src = BC->getOperand(0);
  3346. if (GEPOperator *GEP = dyn_cast<GEPOperator>(Src)) {
  3347. // For GEP, the ptr could have other GEP read/write.
  3348. // Only scan one GEP is not enough.
  3349. Value *Ptr = GEP->getPointerOperand();
  3350. while (GEPOperator *NestedGEP = dyn_cast<GEPOperator>(Ptr))
  3351. Ptr = NestedGEP->getPointerOperand();
  3352. if (CallInst *PtrCI = dyn_cast<CallInst>(Ptr)) {
  3353. hlsl::HLOpcodeGroup group =
  3354. hlsl::GetHLOpcodeGroup(PtrCI->getCalledFunction());
  3355. if (group == HLOpcodeGroup::HLSubscript) {
  3356. HLSubscriptOpcode opcode =
  3357. static_cast<HLSubscriptOpcode>(hlsl::GetHLOpcode(PtrCI));
  3358. if (opcode == HLSubscriptOpcode::CBufferSubscript) {
  3359. // Ptr from CBuffer is safe.
  3360. if (ReplaceMemcpy(V, Src, MC, annotation, typeSys, DL, DT))
  3361. return true;
  3362. }
  3363. }
  3364. }
  3365. } else if (!isa<CallInst>(Src)) {
  3366. // Resource ptr should not be replaced.
  3367. // Need to make sure src not updated after current memcpy.
  3368. // Check Src only have 1 store now.
  3369. hlutil::PointerStatus SrcPS(Src, size, /*bLdStOnly*/ false);
  3370. SrcPS.analyze(typeSys, bStructElt);
  3371. if (SrcPS.storedType != hlutil::PointerStatus::StoredType::Stored) {
  3372. if (ReplaceMemcpy(V, Src, MC, annotation, typeSys, DL, DT))
  3373. return true;
  3374. }
  3375. }
  3376. }
  3377. } else if (PS.loadedType ==
  3378. hlutil::PointerStatus::LoadedType::MemcopySrcOnce) {
  3379. // Replace dst of memcpy.
  3380. MemCpyInst *MC = PS.LoadingMemcpy;
  3381. if (MC->getSourceAddressSpace() == MC->getDestAddressSpace()) {
  3382. Value *Dest = MC->getOperand(0);
  3383. // Only remove one level bitcast generated from inline.
  3384. if (BitCastOperator *BC = dyn_cast<BitCastOperator>(Dest))
  3385. Dest = BC->getOperand(0);
  3386. // For GEP, the ptr could have other GEP read/write.
  3387. // Only scan one GEP is not enough.
  3388. // And resource ptr should not be replaced.
  3389. if (!isa<GEPOperator>(Dest) && !isa<CallInst>(Dest) &&
  3390. !isa<BitCastOperator>(Dest)) {
  3391. // Need to make sure Dest not updated after current memcpy.
  3392. // Check Dest only have 1 store now.
  3393. hlutil::PointerStatus DestPS(Dest, size, /*bLdStOnly*/ false);
  3394. DestPS.analyze(typeSys, bStructElt);
  3395. if (DestPS.storedType != hlutil::PointerStatus::StoredType::Stored) {
  3396. if (ReplaceMemcpy(Dest, V, MC, annotation, typeSys, DL, DT)) {
  3397. // V still needs to be flattened.
  3398. // Lower memcpy come from Dest.
  3399. return LowerMemcpy(V, annotation, typeSys, DL, DT, bAllowReplace);
  3400. }
  3401. }
  3402. }
  3403. }
  3404. }
  3405. }
  3406. for (MemCpyInst *MC : PS.memcpySet) {
  3407. MemcpySplitter::SplitMemCpy(MC, DL, annotation, typeSys);
  3408. }
  3409. return false;
  3410. }
  3411. /// MarkEmptyStructUsers - Add instruction related to Empty struct to DeadInsts.
  3412. void SROA_Helper::MarkEmptyStructUsers(Value *V, SmallVector<Value *, 32> &DeadInsts) {
  3413. UndefValue *undef = UndefValue::get(V->getType());
  3414. for (auto itU = V->user_begin(), E = V->user_end(); itU != E;) {
  3415. Value *U = *(itU++);
  3416. // Kill memcpy, set operands to undef for call and ret, and recurse
  3417. if (MemCpyInst *MC = dyn_cast<MemCpyInst>(U)) {
  3418. DeadInsts.emplace_back(MC);
  3419. } else if (CallInst *CI = dyn_cast<CallInst>(U)) {
  3420. for (auto &operand : CI->operands()) {
  3421. if (operand == V)
  3422. operand.set(undef);
  3423. }
  3424. } else if (ReturnInst *Ret = dyn_cast<ReturnInst>(U)) {
  3425. Ret->setOperand(0, undef);
  3426. } else if (isa<Constant>(U) || isa<GetElementPtrInst>(U) ||
  3427. isa<BitCastInst>(U) || isa<LoadInst>(U) || isa<StoreInst>(U)) {
  3428. // Recurse users
  3429. MarkEmptyStructUsers(U, DeadInsts);
  3430. } else {
  3431. DXASSERT(false, "otherwise, recursing unexpected empty struct user");
  3432. }
  3433. }
  3434. if (Instruction *I = dyn_cast<Instruction>(V)) {
  3435. // Only need to add no use inst here.
  3436. // DeleteDeadInst will delete everything.
  3437. if (I->user_empty())
  3438. DeadInsts.emplace_back(I);
  3439. }
  3440. }
  3441. bool SROA_Helper::IsEmptyStructType(Type *Ty, DxilTypeSystem &typeSys) {
  3442. if (isa<ArrayType>(Ty))
  3443. Ty = Ty->getArrayElementType();
  3444. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  3445. if (!HLMatrixType::isa(Ty)) {
  3446. DxilStructAnnotation *SA = typeSys.GetStructAnnotation(ST);
  3447. if (SA && SA->IsEmptyStruct())
  3448. return true;
  3449. }
  3450. }
  3451. return false;
  3452. }
  3453. //===----------------------------------------------------------------------===//
  3454. // SROA on function parameters.
  3455. //===----------------------------------------------------------------------===//
  3456. static void LegalizeDxilInputOutputs(Function *F,
  3457. DxilFunctionAnnotation *EntryAnnotation,
  3458. const DataLayout &DL,
  3459. DxilTypeSystem &typeSys);
  3460. static void InjectReturnAfterNoReturnPreserveOutput(HLModule &HLM);
  3461. namespace {
  3462. class SROA_Parameter_HLSL : public ModulePass {
  3463. HLModule *m_pHLModule;
  3464. public:
  3465. static char ID; // Pass identification, replacement for typeid
  3466. explicit SROA_Parameter_HLSL() : ModulePass(ID) {}
  3467. const char *getPassName() const override { return "SROA Parameter HLSL"; }
  3468. static void RewriteBitcastWithIdenticalStructs(Function *F);
  3469. static void RewriteBitcastWithIdenticalStructs(BitCastInst *BCI);
  3470. bool runOnModule(Module &M) override {
  3471. // Patch memcpy to cover case bitcast (gep ptr, 0,0) is transformed into
  3472. // bitcast ptr.
  3473. MemcpySplitter::PatchMemCpyWithZeroIdxGEP(M);
  3474. m_pHLModule = &M.GetOrCreateHLModule();
  3475. const DataLayout &DL = M.getDataLayout();
  3476. // Load up debug information, to cross-reference values and the instructions
  3477. // used to load them.
  3478. m_HasDbgInfo = getDebugMetadataVersionFromModule(M) != 0;
  3479. InjectReturnAfterNoReturnPreserveOutput(*m_pHLModule);
  3480. std::deque<Function *> WorkList;
  3481. std::vector<Function *> DeadHLFunctions;
  3482. for (Function &F : M.functions()) {
  3483. HLOpcodeGroup group = GetHLOpcodeGroup(&F);
  3484. // Skip HL operations.
  3485. if (group != HLOpcodeGroup::NotHL ||
  3486. group == HLOpcodeGroup::HLExtIntrinsic) {
  3487. if (F.user_empty())
  3488. DeadHLFunctions.emplace_back(&F);
  3489. continue;
  3490. }
  3491. if (F.isDeclaration()) {
  3492. // Skip llvm intrinsic.
  3493. if (F.isIntrinsic())
  3494. continue;
  3495. // Skip unused external function.
  3496. if (F.user_empty())
  3497. continue;
  3498. }
  3499. // Skip void(void) functions.
  3500. if (F.getReturnType()->isVoidTy() && F.arg_size() == 0)
  3501. continue;
  3502. // Skip library function, except to LegalizeDxilInputOutputs
  3503. if (&F != m_pHLModule->GetEntryFunction() &&
  3504. !m_pHLModule->IsEntryThatUsesSignatures(&F)) {
  3505. if (!F.isDeclaration())
  3506. LegalizeDxilInputOutputs(&F, m_pHLModule->GetFunctionAnnotation(&F),
  3507. DL, m_pHLModule->GetTypeSystem());
  3508. continue;
  3509. }
  3510. WorkList.emplace_back(&F);
  3511. }
  3512. // Remove dead hl functions here.
  3513. // This is for hl functions which has body and always inline.
  3514. for (Function *F : DeadHLFunctions) {
  3515. F->eraseFromParent();
  3516. }
  3517. // Preprocess aggregate function param used as function call arg.
  3518. for (Function *F : WorkList) {
  3519. preprocessArgUsedInCall(F);
  3520. }
  3521. // Process the worklist
  3522. while (!WorkList.empty()) {
  3523. Function *F = WorkList.front();
  3524. WorkList.pop_front();
  3525. RewriteBitcastWithIdenticalStructs(F);
  3526. createFlattenedFunction(F);
  3527. }
  3528. // Replace functions with flattened version when we flat all the functions.
  3529. for (auto Iter : funcMap)
  3530. replaceCall(Iter.first, Iter.second);
  3531. // Update patch constant function.
  3532. for (Function &F : M.functions()) {
  3533. if (F.isDeclaration())
  3534. continue;
  3535. if (!m_pHLModule->HasDxilFunctionProps(&F))
  3536. continue;
  3537. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(&F);
  3538. if (funcProps.shaderKind == DXIL::ShaderKind::Hull) {
  3539. Function *oldPatchConstantFunc =
  3540. funcProps.ShaderProps.HS.patchConstantFunc;
  3541. if (funcMap.count(oldPatchConstantFunc))
  3542. m_pHLModule->SetPatchConstantFunctionForHS(&F, funcMap[oldPatchConstantFunc]);
  3543. }
  3544. }
  3545. // Remove flattened functions.
  3546. for (auto Iter : funcMap) {
  3547. Function *F = Iter.first;
  3548. Function *flatF = Iter.second;
  3549. flatF->takeName(F);
  3550. F->eraseFromParent();
  3551. }
  3552. // Flatten internal global.
  3553. std::vector<GlobalVariable *> staticGVs;
  3554. for (GlobalVariable &GV : M.globals()) {
  3555. if (dxilutil::IsStaticGlobal(&GV) ||
  3556. dxilutil::IsSharedMemoryGlobal(&GV)) {
  3557. staticGVs.emplace_back(&GV);
  3558. } else {
  3559. // merge GEP use for global.
  3560. HLModule::MergeGepUse(&GV);
  3561. }
  3562. }
  3563. for (GlobalVariable *GV : staticGVs)
  3564. flattenGlobal(GV);
  3565. // Remove unused internal global.
  3566. staticGVs.clear();
  3567. for (GlobalVariable &GV : M.globals()) {
  3568. if (dxilutil::IsStaticGlobal(&GV) ||
  3569. dxilutil::IsSharedMemoryGlobal(&GV)) {
  3570. staticGVs.emplace_back(&GV);
  3571. }
  3572. }
  3573. for (GlobalVariable *GV : staticGVs) {
  3574. bool onlyStoreUse = true;
  3575. for (User *user : GV->users()) {
  3576. if (isa<StoreInst>(user))
  3577. continue;
  3578. if (isa<ConstantExpr>(user) && user->user_empty())
  3579. continue;
  3580. // Check matrix store.
  3581. if (HLMatrixType::isa(
  3582. GV->getType()->getPointerElementType())) {
  3583. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  3584. if (GetHLOpcodeGroupByName(CI->getCalledFunction()) ==
  3585. HLOpcodeGroup::HLMatLoadStore) {
  3586. HLMatLoadStoreOpcode opcode =
  3587. static_cast<HLMatLoadStoreOpcode>(GetHLOpcode(CI));
  3588. if (opcode == HLMatLoadStoreOpcode::ColMatStore ||
  3589. opcode == HLMatLoadStoreOpcode::RowMatStore)
  3590. continue;
  3591. }
  3592. }
  3593. }
  3594. onlyStoreUse = false;
  3595. break;
  3596. }
  3597. if (onlyStoreUse) {
  3598. for (auto UserIt = GV->user_begin(); UserIt != GV->user_end();) {
  3599. Value *User = *(UserIt++);
  3600. if (Instruction *I = dyn_cast<Instruction>(User)) {
  3601. I->eraseFromParent();
  3602. }
  3603. else {
  3604. ConstantExpr *CE = cast<ConstantExpr>(User);
  3605. CE->dropAllReferences();
  3606. }
  3607. }
  3608. GV->eraseFromParent();
  3609. }
  3610. }
  3611. return true;
  3612. }
  3613. private:
  3614. void DeleteDeadInstructions();
  3615. void preprocessArgUsedInCall(Function *F);
  3616. void moveFunctionBody(Function *F, Function *flatF);
  3617. void replaceCall(Function *F, Function *flatF);
  3618. void createFlattenedFunction(Function *F);
  3619. void
  3620. flattenArgument(Function *F, Value *Arg, bool bForParam,
  3621. DxilParameterAnnotation &paramAnnotation,
  3622. std::vector<Value *> &FlatParamList,
  3623. std::vector<DxilParameterAnnotation> &FlatRetAnnotationList,
  3624. BasicBlock *EntryBlock, DbgDeclareInst *DDI);
  3625. Value *castResourceArgIfRequired(Value *V, Type *Ty, bool bOut,
  3626. DxilParamInputQual inputQual,
  3627. IRBuilder<> &Builder);
  3628. Value *castArgumentIfRequired(Value *V, Type *Ty, bool bOut,
  3629. DxilParamInputQual inputQual,
  3630. DxilFieldAnnotation &annotation,
  3631. IRBuilder<> &Builder,
  3632. DxilTypeSystem &TypeSys);
  3633. // Replace use of parameter which changed type when flatten.
  3634. // Also add information to Arg if required.
  3635. void replaceCastParameter(Value *NewParam, Value *OldParam, Function &F,
  3636. Argument *Arg, const DxilParamInputQual inputQual,
  3637. IRBuilder<> &Builder);
  3638. void allocateSemanticIndex(
  3639. std::vector<DxilParameterAnnotation> &FlatAnnotationList,
  3640. unsigned startArgIndex, llvm::StringMap<Type *> &semanticTypeMap);
  3641. bool hasDynamicVectorIndexing(Value *V);
  3642. void flattenGlobal(GlobalVariable *GV);
  3643. //static std::vector<Value*> GetConstValueIdxList(IRBuilder<>& builder, std::vector<unsigned> idxlist);
  3644. /// DeadInsts - Keep track of instructions we have made dead, so that
  3645. /// we can remove them after we are done working.
  3646. SmallVector<Value *, 32> DeadInsts;
  3647. // Map from orginal function to the flatten version.
  3648. MapVector<Function *, Function *> funcMap; // Need deterministic order of iteration
  3649. // Map from original arg/param to flatten cast version.
  3650. std::unordered_map<Value *, std::pair<Value*, DxilParamInputQual>> castParamMap;
  3651. // Map form first element of a vector the list of all elements of the vector.
  3652. std::unordered_map<Value *, SmallVector<Value*, 4> > vectorEltsMap;
  3653. // Set for row major matrix parameter.
  3654. std::unordered_set<Value *> castRowMajorParamMap;
  3655. bool m_HasDbgInfo;
  3656. };
  3657. // When replacing aggregates by its scalar elements,
  3658. // the first element will preserve the original semantic,
  3659. // and the subsequent ones will temporarily use this value.
  3660. // We then run a pass to fix the semantics and properly renumber them
  3661. // once the aggregate has been fully expanded.
  3662. //
  3663. // For example:
  3664. // struct Foo { float a; float b; };
  3665. // void main(Foo foo : TEXCOORD0, float bar : TEXCOORD0)
  3666. //
  3667. // Will be expanded to
  3668. // void main(float a : TEXCOORD0, float b : *, float bar : TEXCOORD0)
  3669. //
  3670. // And then fixed up to
  3671. // void main(float a : TEXCOORD0, float b : TEXCOORD1, float bar : TEXCOORD0)
  3672. //
  3673. // (which will later on fail validation due to duplicate semantics).
  3674. constexpr const char *ContinuedPseudoSemantic = "*";
  3675. }
  3676. char SROA_Parameter_HLSL::ID = 0;
  3677. INITIALIZE_PASS(SROA_Parameter_HLSL, "scalarrepl-param-hlsl",
  3678. "Scalar Replacement of Aggregates HLSL (parameters)", false,
  3679. false)
  3680. void SROA_Parameter_HLSL::RewriteBitcastWithIdenticalStructs(Function *F) {
  3681. if (F->isDeclaration())
  3682. return;
  3683. // Gather list of bitcast involving src and dest structs with identical layout
  3684. std::vector<BitCastInst*> worklist;
  3685. for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
  3686. if (BitCastInst *BCI = dyn_cast<BitCastInst>(&*I)) {
  3687. Type *DstTy = BCI->getDestTy();
  3688. Type *SrcTy = BCI->getSrcTy();
  3689. if(ArePointersToStructsOfIdenticalLayouts(DstTy, SrcTy))
  3690. worklist.push_back(BCI);
  3691. }
  3692. }
  3693. // Replace bitcast involving src and dest structs with identical layout
  3694. while (!worklist.empty()) {
  3695. BitCastInst *BCI = worklist.back();
  3696. worklist.pop_back();
  3697. RewriteBitcastWithIdenticalStructs(BCI);
  3698. }
  3699. }
  3700. void SROA_Parameter_HLSL::RewriteBitcastWithIdenticalStructs(BitCastInst *BCI) {
  3701. StructType *srcStTy = cast<StructType>(BCI->getSrcTy()->getPointerElementType());
  3702. StructType *destStTy = cast<StructType>(BCI->getDestTy()->getPointerElementType());
  3703. Value* srcPtr = BCI->getOperand(0);
  3704. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(BCI->getParent()->getParent()));
  3705. AllocaInst *destPtr = AllocaBuilder.CreateAlloca(destStTy);
  3706. IRBuilder<> InstBuilder(BCI);
  3707. std::vector<unsigned> idxlist = { 0 };
  3708. CopyElementsOfStructsWithIdenticalLayout(InstBuilder, destPtr, srcPtr, srcStTy, idxlist);
  3709. BCI->replaceAllUsesWith(destPtr);
  3710. BCI->eraseFromParent();
  3711. }
  3712. /// DeleteDeadInstructions - Erase instructions on the DeadInstrs list,
  3713. /// recursively including all their operands that become trivially dead.
  3714. void SROA_Parameter_HLSL::DeleteDeadInstructions() {
  3715. while (!DeadInsts.empty()) {
  3716. Instruction *I = cast<Instruction>(DeadInsts.pop_back_val());
  3717. for (User::op_iterator OI = I->op_begin(), E = I->op_end(); OI != E; ++OI)
  3718. if (Instruction *U = dyn_cast<Instruction>(*OI)) {
  3719. // Zero out the operand and see if it becomes trivially dead.
  3720. // (But, don't add allocas to the dead instruction list -- they are
  3721. // already on the worklist and will be deleted separately.)
  3722. *OI = nullptr;
  3723. if (isInstructionTriviallyDead(U) && !isa<AllocaInst>(U))
  3724. DeadInsts.push_back(U);
  3725. }
  3726. I->eraseFromParent();
  3727. }
  3728. }
  3729. bool SROA_Parameter_HLSL::hasDynamicVectorIndexing(Value *V) {
  3730. for (User *U : V->users()) {
  3731. if (!U->getType()->isPointerTy())
  3732. continue;
  3733. if (dyn_cast<GEPOperator>(U)) {
  3734. gep_type_iterator GEPIt = gep_type_begin(U), E = gep_type_end(U);
  3735. for (; GEPIt != E; ++GEPIt) {
  3736. if (isa<VectorType>(*GEPIt)) {
  3737. Value *VecIdx = GEPIt.getOperand();
  3738. if (!isa<ConstantInt>(VecIdx))
  3739. return true;
  3740. }
  3741. }
  3742. }
  3743. }
  3744. return false;
  3745. }
  3746. void SROA_Parameter_HLSL::flattenGlobal(GlobalVariable *GV) {
  3747. Type *Ty = GV->getType()->getPointerElementType();
  3748. // Skip basic types.
  3749. if (!Ty->isAggregateType() && !Ty->isVectorTy())
  3750. return;
  3751. std::deque<Value *> WorkList;
  3752. WorkList.push_back(GV);
  3753. // merge GEP use for global.
  3754. HLModule::MergeGepUse(GV);
  3755. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  3756. // Only used to create ConstantExpr.
  3757. IRBuilder<> Builder(m_pHLModule->GetCtx());
  3758. std::vector<Instruction*> deadAllocas;
  3759. const DataLayout &DL = GV->getParent()->getDataLayout();
  3760. unsigned debugOffset = 0;
  3761. std::unordered_map<Value*, StringRef> EltNameMap;
  3762. // Process the worklist
  3763. while (!WorkList.empty()) {
  3764. GlobalVariable *EltGV = cast<GlobalVariable>(WorkList.front());
  3765. WorkList.pop_front();
  3766. const bool bAllowReplace = true;
  3767. // Globals don't need DomTree here because they take another path
  3768. if (SROA_Helper::LowerMemcpy(EltGV, /*annoation*/ nullptr, dxilTypeSys, DL,
  3769. nullptr /*DT */, bAllowReplace)) {
  3770. continue;
  3771. }
  3772. // Flat Global vector if no dynamic vector indexing.
  3773. bool bFlatVector = !hasDynamicVectorIndexing(EltGV);
  3774. // Disable scalarization of groupshared/const_static vector arrays
  3775. if ((GV->getType()->getAddressSpace() == DXIL::kTGSMAddrSpace ||
  3776. (GV->isConstant() && GV->hasInitializer() &&
  3777. GV->getLinkage() == GlobalValue::LinkageTypes::InternalLinkage)) &&
  3778. Ty->isArrayTy())
  3779. bFlatVector = false;
  3780. std::vector<Value *> Elts;
  3781. bool SROAed = false;
  3782. if (GlobalVariable *NewEltGV = dyn_cast_or_null<GlobalVariable>(
  3783. TranslatePtrIfUsedByLoweredFn(EltGV, dxilTypeSys))) {
  3784. if (GV != EltGV) {
  3785. EltGV->removeDeadConstantUsers();
  3786. EltGV->eraseFromParent();
  3787. }
  3788. EltGV = NewEltGV;
  3789. } else {
  3790. // Globals don't need DomTree
  3791. SROAed = SROA_Helper::DoScalarReplacement(
  3792. EltGV, Elts, Builder, bFlatVector,
  3793. // TODO: set precise.
  3794. /*hasPrecise*/ false, dxilTypeSys, DL, DeadInsts, /*DT*/ nullptr);
  3795. }
  3796. if (SROAed) {
  3797. // Push Elts into workList.
  3798. // Use rbegin to make sure the order not change.
  3799. for (auto iter = Elts.rbegin(); iter != Elts.rend(); iter++) {
  3800. WorkList.push_front(*iter);
  3801. if (m_HasDbgInfo) {
  3802. StringRef EltName = (*iter)->getName().ltrim(GV->getName());
  3803. EltNameMap[*iter] = EltName;
  3804. }
  3805. }
  3806. EltGV->removeDeadConstantUsers();
  3807. // Now erase any instructions that were made dead while rewriting the
  3808. // alloca.
  3809. DeleteDeadInstructions();
  3810. ++NumReplaced;
  3811. } else {
  3812. // Add debug info for flattened globals.
  3813. if (m_HasDbgInfo && GV != EltGV) {
  3814. DebugInfoFinder &Finder = m_pHLModule->GetOrCreateDebugInfoFinder();
  3815. Type *Ty = EltGV->getType()->getElementType();
  3816. unsigned size = DL.getTypeAllocSizeInBits(Ty);
  3817. unsigned align = DL.getPrefTypeAlignment(Ty);
  3818. HLModule::CreateElementGlobalVariableDebugInfo(
  3819. GV, Finder, EltGV, size, align, debugOffset,
  3820. EltNameMap[EltGV]);
  3821. debugOffset += size;
  3822. }
  3823. }
  3824. }
  3825. DeleteDeadInstructions();
  3826. if (GV->user_empty()) {
  3827. GV->removeDeadConstantUsers();
  3828. GV->eraseFromParent();
  3829. }
  3830. }
  3831. static DxilFieldAnnotation &GetEltAnnotation(Type *Ty, unsigned idx, DxilFieldAnnotation &annotation, DxilTypeSystem &dxilTypeSys) {
  3832. while (Ty->isArrayTy())
  3833. Ty = Ty->getArrayElementType();
  3834. if (StructType *ST = dyn_cast<StructType>(Ty)) {
  3835. if (HLMatrixType::isa(Ty))
  3836. return annotation;
  3837. DxilStructAnnotation *SA = dxilTypeSys.GetStructAnnotation(ST);
  3838. if (SA) {
  3839. DxilFieldAnnotation &FA = SA->GetFieldAnnotation(idx);
  3840. return FA;
  3841. }
  3842. }
  3843. return annotation;
  3844. }
  3845. // Note: Semantic index allocation.
  3846. // Semantic index is allocated base on linear layout.
  3847. // For following code
  3848. /*
  3849. struct S {
  3850. float4 m;
  3851. float4 m2;
  3852. };
  3853. S s[2] : semantic;
  3854. struct S2 {
  3855. float4 m[2];
  3856. float4 m2[2];
  3857. };
  3858. S2 s2 : semantic;
  3859. */
  3860. // The semantic index is like this:
  3861. // s[0].m : semantic0
  3862. // s[0].m2 : semantic1
  3863. // s[1].m : semantic2
  3864. // s[1].m2 : semantic3
  3865. // s2.m[0] : semantic0
  3866. // s2.m[1] : semantic1
  3867. // s2.m2[0] : semantic2
  3868. // s2.m2[1] : semantic3
  3869. // But when flatten argument, the result is like this:
  3870. // float4 s_m[2], float4 s_m2[2].
  3871. // float4 s2_m[2], float4 s2_m2[2].
  3872. // To do the allocation, need to map from each element to its flattened argument.
  3873. // Say arg index of float4 s_m[2] is 0, float4 s_m2[2] is 1.
  3874. // Need to get 0 from s[0].m and s[1].m, get 1 from s[0].m2 and s[1].m2.
  3875. // Allocate the argments with same semantic string from type where the
  3876. // semantic starts( S2 for s2.m[2] and s2.m2[2]).
  3877. // Iterate each elements of the type, save the semantic index and update it.
  3878. // The map from element to the arg ( s[0].m2 -> s.m2[2]) is done by argIdx.
  3879. // ArgIdx only inc by 1 when finish a struct field.
  3880. static unsigned AllocateSemanticIndex(
  3881. Type *Ty, unsigned &semIndex, unsigned argIdx, unsigned endArgIdx,
  3882. std::vector<DxilParameterAnnotation> &FlatAnnotationList) {
  3883. if (Ty->isPointerTy()) {
  3884. return AllocateSemanticIndex(Ty->getPointerElementType(), semIndex, argIdx,
  3885. endArgIdx, FlatAnnotationList);
  3886. } else if (Ty->isArrayTy()) {
  3887. unsigned arraySize = Ty->getArrayNumElements();
  3888. unsigned updatedArgIdx = argIdx;
  3889. Type *EltTy = Ty->getArrayElementType();
  3890. for (unsigned i = 0; i < arraySize; i++) {
  3891. updatedArgIdx = AllocateSemanticIndex(EltTy, semIndex, argIdx, endArgIdx,
  3892. FlatAnnotationList);
  3893. }
  3894. return updatedArgIdx;
  3895. } else if (Ty->isStructTy() && !HLMatrixType::isa(Ty)) {
  3896. unsigned fieldsCount = Ty->getStructNumElements();
  3897. for (unsigned i = 0; i < fieldsCount; i++) {
  3898. Type *EltTy = Ty->getStructElementType(i);
  3899. argIdx = AllocateSemanticIndex(EltTy, semIndex, argIdx, endArgIdx,
  3900. FlatAnnotationList);
  3901. if (!(EltTy->isStructTy() && !HLMatrixType::isa(EltTy))) {
  3902. // Update argIdx only when it is a leaf node.
  3903. argIdx++;
  3904. }
  3905. }
  3906. return argIdx;
  3907. } else {
  3908. DXASSERT(argIdx < endArgIdx, "arg index out of bound");
  3909. DxilParameterAnnotation &paramAnnotation = FlatAnnotationList[argIdx];
  3910. // Get element size.
  3911. unsigned rows = 1;
  3912. if (paramAnnotation.HasMatrixAnnotation()) {
  3913. const DxilMatrixAnnotation &matrix =
  3914. paramAnnotation.GetMatrixAnnotation();
  3915. if (matrix.Orientation == MatrixOrientation::RowMajor) {
  3916. rows = matrix.Rows;
  3917. } else {
  3918. DXASSERT_NOMSG(matrix.Orientation == MatrixOrientation::ColumnMajor);
  3919. rows = matrix.Cols;
  3920. }
  3921. }
  3922. // Save semIndex.
  3923. for (unsigned i = 0; i < rows; i++)
  3924. paramAnnotation.AppendSemanticIndex(semIndex + i);
  3925. // Update semIndex.
  3926. semIndex += rows;
  3927. return argIdx;
  3928. }
  3929. }
  3930. void SROA_Parameter_HLSL::allocateSemanticIndex(
  3931. std::vector<DxilParameterAnnotation> &FlatAnnotationList,
  3932. unsigned startArgIndex, llvm::StringMap<Type *> &semanticTypeMap) {
  3933. unsigned endArgIndex = FlatAnnotationList.size();
  3934. // Allocate semantic index.
  3935. for (unsigned i = startArgIndex; i < endArgIndex; ++i) {
  3936. // Group by semantic names.
  3937. DxilParameterAnnotation &flatParamAnnotation = FlatAnnotationList[i];
  3938. const std::string &semantic = flatParamAnnotation.GetSemanticString();
  3939. // If semantic is undefined, an error will be emitted elsewhere. For now,
  3940. // we should avoid asserting.
  3941. if (semantic.empty())
  3942. continue;
  3943. StringRef baseSemName; // The 'FOO' in 'FOO1'.
  3944. uint32_t semIndex; // The '1' in 'FOO1'
  3945. // Split semName and index.
  3946. Semantic::DecomposeNameAndIndex(semantic, &baseSemName, &semIndex);
  3947. unsigned semGroupEnd = i + 1;
  3948. while (semGroupEnd < endArgIndex &&
  3949. FlatAnnotationList[semGroupEnd].GetSemanticString() == ContinuedPseudoSemantic) {
  3950. FlatAnnotationList[semGroupEnd].SetSemanticString(baseSemName);
  3951. ++semGroupEnd;
  3952. }
  3953. DXASSERT(semanticTypeMap.count(semantic) > 0, "Must has semantic type");
  3954. Type *semanticTy = semanticTypeMap[semantic];
  3955. AllocateSemanticIndex(semanticTy, semIndex, /*argIdx*/ i,
  3956. /*endArgIdx*/ semGroupEnd, FlatAnnotationList);
  3957. // Update i.
  3958. i = semGroupEnd - 1;
  3959. }
  3960. }
  3961. //
  3962. // Cast parameters.
  3963. //
  3964. static void CopyHandleToResourcePtr(Value *Handle, Value *ResPtr, HLModule &HLM,
  3965. IRBuilder<> &Builder) {
  3966. // Cast it to resource.
  3967. Type *ResTy = ResPtr->getType()->getPointerElementType();
  3968. Value *Res = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  3969. (unsigned)HLCastOpcode::HandleToResCast,
  3970. ResTy, {Handle}, *HLM.GetModule());
  3971. // Store casted resource to OldArg.
  3972. Builder.CreateStore(Res, ResPtr);
  3973. }
  3974. static void CopyHandlePtrToResourcePtr(Value *HandlePtr, Value *ResPtr,
  3975. HLModule &HLM, IRBuilder<> &Builder) {
  3976. // Load the handle.
  3977. Value *Handle = Builder.CreateLoad(HandlePtr);
  3978. CopyHandleToResourcePtr(Handle, ResPtr, HLM, Builder);
  3979. }
  3980. static Value *CastResourcePtrToHandle(Value *Res, Type *HandleTy, HLModule &HLM,
  3981. IRBuilder<> &Builder) {
  3982. // Load OldArg.
  3983. Value *LdRes = Builder.CreateLoad(Res);
  3984. Value *Handle = HLM.EmitHLOperationCall(
  3985. Builder, HLOpcodeGroup::HLCreateHandle,
  3986. /*opcode*/ 0, HandleTy, {LdRes}, *HLM.GetModule());
  3987. return Handle;
  3988. }
  3989. static void CopyResourcePtrToHandlePtr(Value *Res, Value *HandlePtr,
  3990. HLModule &HLM, IRBuilder<> &Builder) {
  3991. Type *HandleTy = HandlePtr->getType()->getPointerElementType();
  3992. Value *Handle = CastResourcePtrToHandle(Res, HandleTy, HLM, Builder);
  3993. Builder.CreateStore(Handle, HandlePtr);
  3994. }
  3995. static void CopyVectorPtrToEltsPtr(Value *VecPtr, ArrayRef<Value *> elts,
  3996. unsigned vecSize, IRBuilder<> &Builder) {
  3997. Value *Vec = Builder.CreateLoad(VecPtr);
  3998. for (unsigned i = 0; i < vecSize; i++) {
  3999. Value *Elt = Builder.CreateExtractElement(Vec, i);
  4000. Builder.CreateStore(Elt, elts[i]);
  4001. }
  4002. }
  4003. static void CopyEltsPtrToVectorPtr(ArrayRef<Value *> elts, Value *VecPtr,
  4004. Type *VecTy, unsigned vecSize,
  4005. IRBuilder<> &Builder) {
  4006. Value *Vec = UndefValue::get(VecTy);
  4007. for (unsigned i = 0; i < vecSize; i++) {
  4008. Value *Elt = Builder.CreateLoad(elts[i]);
  4009. Vec = Builder.CreateInsertElement(Vec, Elt, i);
  4010. }
  4011. Builder.CreateStore(Vec, VecPtr);
  4012. }
  4013. static void CopyMatToArrayPtr(Value *Mat, Value *ArrayPtr,
  4014. unsigned arrayBaseIdx, HLModule &HLM,
  4015. IRBuilder<> &Builder, bool bRowMajor) {
  4016. // Mat val is row major.
  4017. HLMatrixType MatTy = HLMatrixType::cast(Mat->getType());
  4018. Type *VecTy = MatTy.getLoweredVectorTypeForReg();
  4019. Value *Vec =
  4020. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  4021. (unsigned)HLCastOpcode::RowMatrixToVecCast, VecTy,
  4022. {Mat}, *HLM.GetModule());
  4023. Value *zero = Builder.getInt32(0);
  4024. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  4025. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  4026. unsigned matIdx = MatTy.getColumnMajorIndex(r, c);
  4027. Value *Elt = Builder.CreateExtractElement(Vec, matIdx);
  4028. Value *Ptr = Builder.CreateInBoundsGEP(
  4029. ArrayPtr, {zero, Builder.getInt32(arrayBaseIdx + matIdx)});
  4030. Builder.CreateStore(Elt, Ptr);
  4031. }
  4032. }
  4033. }
  4034. static void CopyMatPtrToArrayPtr(Value *MatPtr, Value *ArrayPtr,
  4035. unsigned arrayBaseIdx, HLModule &HLM,
  4036. IRBuilder<> &Builder, bool bRowMajor) {
  4037. Type *Ty = MatPtr->getType()->getPointerElementType();
  4038. Value *Mat = nullptr;
  4039. if (bRowMajor) {
  4040. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4041. (unsigned)HLMatLoadStoreOpcode::RowMatLoad,
  4042. Ty, {MatPtr}, *HLM.GetModule());
  4043. } else {
  4044. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4045. (unsigned)HLMatLoadStoreOpcode::ColMatLoad,
  4046. Ty, {MatPtr}, *HLM.GetModule());
  4047. // Matrix value should be row major.
  4048. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  4049. (unsigned)HLCastOpcode::ColMatrixToRowMatrix,
  4050. Ty, {Mat}, *HLM.GetModule());
  4051. }
  4052. CopyMatToArrayPtr(Mat, ArrayPtr, arrayBaseIdx, HLM, Builder, bRowMajor);
  4053. }
  4054. static Value *LoadArrayPtrToMat(Value *ArrayPtr, unsigned arrayBaseIdx,
  4055. Type *Ty, HLModule &HLM, IRBuilder<> &Builder,
  4056. bool bRowMajor) {
  4057. HLMatrixType MatTy = HLMatrixType::cast(Ty);
  4058. // HLInit operands are in row major.
  4059. SmallVector<Value *, 16> Elts;
  4060. Value *zero = Builder.getInt32(0);
  4061. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  4062. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  4063. unsigned matIdx = bRowMajor
  4064. ? MatTy.getRowMajorIndex(r, c)
  4065. : MatTy.getColumnMajorIndex(r, c);
  4066. Value *Ptr = Builder.CreateInBoundsGEP(
  4067. ArrayPtr, {zero, Builder.getInt32(arrayBaseIdx + matIdx)});
  4068. Value *Elt = Builder.CreateLoad(Ptr);
  4069. Elts.emplace_back(Elt);
  4070. }
  4071. }
  4072. return HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLInit,
  4073. /*opcode*/ 0, Ty, {Elts}, *HLM.GetModule());
  4074. }
  4075. static void CopyArrayPtrToMatPtr(Value *ArrayPtr, unsigned arrayBaseIdx,
  4076. Value *MatPtr, HLModule &HLM,
  4077. IRBuilder<> &Builder, bool bRowMajor) {
  4078. Type *Ty = MatPtr->getType()->getPointerElementType();
  4079. Value *Mat =
  4080. LoadArrayPtrToMat(ArrayPtr, arrayBaseIdx, Ty, HLM, Builder, bRowMajor);
  4081. if (bRowMajor) {
  4082. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4083. (unsigned)HLMatLoadStoreOpcode::RowMatStore, Ty,
  4084. {MatPtr, Mat}, *HLM.GetModule());
  4085. } else {
  4086. // Mat is row major.
  4087. // Cast it to col major before store.
  4088. Mat = HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLCast,
  4089. (unsigned)HLCastOpcode::RowMatrixToColMatrix,
  4090. Ty, {Mat}, *HLM.GetModule());
  4091. HLM.EmitHLOperationCall(Builder, HLOpcodeGroup::HLMatLoadStore,
  4092. (unsigned)HLMatLoadStoreOpcode::ColMatStore, Ty,
  4093. {MatPtr, Mat}, *HLM.GetModule());
  4094. }
  4095. }
  4096. using CopyFunctionTy = void(Value *FromPtr, Value *ToPtr, HLModule &HLM,
  4097. Type *HandleTy, IRBuilder<> &Builder,
  4098. bool bRowMajor);
  4099. static void
  4100. CastCopyArrayMultiDimTo1Dim(Value *FromArray, Value *ToArray, Type *CurFromTy,
  4101. std::vector<Value *> &idxList, unsigned calcIdx,
  4102. Type *HandleTy, HLModule &HLM, IRBuilder<> &Builder,
  4103. CopyFunctionTy CastCopyFn, bool bRowMajor) {
  4104. if (CurFromTy->isVectorTy()) {
  4105. // Copy vector to array.
  4106. Value *FromPtr = Builder.CreateInBoundsGEP(FromArray, idxList);
  4107. Value *V = Builder.CreateLoad(FromPtr);
  4108. unsigned vecSize = CurFromTy->getVectorNumElements();
  4109. Value *zeroIdx = Builder.getInt32(0);
  4110. for (unsigned i = 0; i < vecSize; i++) {
  4111. Value *ToPtr = Builder.CreateInBoundsGEP(
  4112. ToArray, {zeroIdx, Builder.getInt32(calcIdx++)});
  4113. Value *Elt = Builder.CreateExtractElement(V, i);
  4114. Builder.CreateStore(Elt, ToPtr);
  4115. }
  4116. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(CurFromTy)) {
  4117. // Copy matrix to array.
  4118. // Calculate the offset.
  4119. unsigned offset = calcIdx * MatTy.getNumElements();
  4120. Value *FromPtr = Builder.CreateInBoundsGEP(FromArray, idxList);
  4121. CopyMatPtrToArrayPtr(FromPtr, ToArray, offset, HLM, Builder, bRowMajor);
  4122. } else if (!CurFromTy->isArrayTy()) {
  4123. Value *FromPtr = Builder.CreateInBoundsGEP(FromArray, idxList);
  4124. Value *ToPtr = Builder.CreateInBoundsGEP(
  4125. ToArray, {Builder.getInt32(0), Builder.getInt32(calcIdx)});
  4126. CastCopyFn(FromPtr, ToPtr, HLM, HandleTy, Builder, bRowMajor);
  4127. } else {
  4128. unsigned size = CurFromTy->getArrayNumElements();
  4129. Type *FromEltTy = CurFromTy->getArrayElementType();
  4130. for (unsigned i = 0; i < size; i++) {
  4131. idxList.push_back(Builder.getInt32(i));
  4132. unsigned idx = calcIdx * size + i;
  4133. CastCopyArrayMultiDimTo1Dim(FromArray, ToArray, FromEltTy, idxList, idx,
  4134. HandleTy, HLM, Builder, CastCopyFn,
  4135. bRowMajor);
  4136. idxList.pop_back();
  4137. }
  4138. }
  4139. }
  4140. static void
  4141. CastCopyArray1DimToMultiDim(Value *FromArray, Value *ToArray, Type *CurToTy,
  4142. std::vector<Value *> &idxList, unsigned calcIdx,
  4143. Type *HandleTy, HLModule &HLM, IRBuilder<> &Builder,
  4144. CopyFunctionTy CastCopyFn, bool bRowMajor) {
  4145. if (CurToTy->isVectorTy()) {
  4146. // Copy array to vector.
  4147. Value *V = UndefValue::get(CurToTy);
  4148. unsigned vecSize = CurToTy->getVectorNumElements();
  4149. // Calculate the offset.
  4150. unsigned offset = calcIdx * vecSize;
  4151. Value *zeroIdx = Builder.getInt32(0);
  4152. Value *ToPtr = Builder.CreateInBoundsGEP(ToArray, idxList);
  4153. for (unsigned i = 0; i < vecSize; i++) {
  4154. Value *FromPtr = Builder.CreateInBoundsGEP(
  4155. FromArray, {zeroIdx, Builder.getInt32(offset++)});
  4156. Value *Elt = Builder.CreateLoad(FromPtr);
  4157. V = Builder.CreateInsertElement(V, Elt, i);
  4158. }
  4159. Builder.CreateStore(V, ToPtr);
  4160. } else if (HLMatrixType MatTy = HLMatrixType::cast(CurToTy)) {
  4161. // Copy array to matrix.
  4162. // Calculate the offset.
  4163. unsigned offset = calcIdx * MatTy.getNumElements();
  4164. Value *ToPtr = Builder.CreateInBoundsGEP(ToArray, idxList);
  4165. CopyArrayPtrToMatPtr(FromArray, offset, ToPtr, HLM, Builder, bRowMajor);
  4166. } else if (!CurToTy->isArrayTy()) {
  4167. Value *FromPtr = Builder.CreateInBoundsGEP(
  4168. FromArray, {Builder.getInt32(0), Builder.getInt32(calcIdx)});
  4169. Value *ToPtr = Builder.CreateInBoundsGEP(ToArray, idxList);
  4170. CastCopyFn(FromPtr, ToPtr, HLM, HandleTy, Builder, bRowMajor);
  4171. } else {
  4172. unsigned size = CurToTy->getArrayNumElements();
  4173. Type *ToEltTy = CurToTy->getArrayElementType();
  4174. for (unsigned i = 0; i < size; i++) {
  4175. idxList.push_back(Builder.getInt32(i));
  4176. unsigned idx = calcIdx * size + i;
  4177. CastCopyArray1DimToMultiDim(FromArray, ToArray, ToEltTy, idxList, idx,
  4178. HandleTy, HLM, Builder, CastCopyFn,
  4179. bRowMajor);
  4180. idxList.pop_back();
  4181. }
  4182. }
  4183. }
  4184. static void CastCopyOldPtrToNewPtr(Value *OldPtr, Value *NewPtr, HLModule &HLM,
  4185. Type *HandleTy, IRBuilder<> &Builder,
  4186. bool bRowMajor) {
  4187. Type *NewTy = NewPtr->getType()->getPointerElementType();
  4188. Type *OldTy = OldPtr->getType()->getPointerElementType();
  4189. if (NewTy == HandleTy) {
  4190. CopyResourcePtrToHandlePtr(OldPtr, NewPtr, HLM, Builder);
  4191. } else if (OldTy->isVectorTy()) {
  4192. // Copy vector to array.
  4193. Value *V = Builder.CreateLoad(OldPtr);
  4194. unsigned vecSize = OldTy->getVectorNumElements();
  4195. Value *zeroIdx = Builder.getInt32(0);
  4196. for (unsigned i = 0; i < vecSize; i++) {
  4197. Value *EltPtr = Builder.CreateGEP(NewPtr, {zeroIdx, Builder.getInt32(i)});
  4198. Value *Elt = Builder.CreateExtractElement(V, i);
  4199. Builder.CreateStore(Elt, EltPtr);
  4200. }
  4201. } else if (HLMatrixType::isa(OldTy)) {
  4202. CopyMatPtrToArrayPtr(OldPtr, NewPtr, /*arrayBaseIdx*/ 0, HLM, Builder,
  4203. bRowMajor);
  4204. } else if (OldTy->isArrayTy()) {
  4205. std::vector<Value *> idxList;
  4206. idxList.emplace_back(Builder.getInt32(0));
  4207. CastCopyArrayMultiDimTo1Dim(OldPtr, NewPtr, OldTy, idxList, /*calcIdx*/ 0,
  4208. HandleTy, HLM, Builder, CastCopyOldPtrToNewPtr,
  4209. bRowMajor);
  4210. }
  4211. }
  4212. static void CastCopyNewPtrToOldPtr(Value *NewPtr, Value *OldPtr, HLModule &HLM,
  4213. Type *HandleTy, IRBuilder<> &Builder,
  4214. bool bRowMajor) {
  4215. Type *NewTy = NewPtr->getType()->getPointerElementType();
  4216. Type *OldTy = OldPtr->getType()->getPointerElementType();
  4217. if (NewTy == HandleTy) {
  4218. CopyHandlePtrToResourcePtr(NewPtr, OldPtr, HLM, Builder);
  4219. } else if (OldTy->isVectorTy()) {
  4220. // Copy array to vector.
  4221. Value *V = UndefValue::get(OldTy);
  4222. unsigned vecSize = OldTy->getVectorNumElements();
  4223. Value *zeroIdx = Builder.getInt32(0);
  4224. for (unsigned i = 0; i < vecSize; i++) {
  4225. Value *EltPtr = Builder.CreateGEP(NewPtr, {zeroIdx, Builder.getInt32(i)});
  4226. Value *Elt = Builder.CreateLoad(EltPtr);
  4227. V = Builder.CreateInsertElement(V, Elt, i);
  4228. }
  4229. Builder.CreateStore(V, OldPtr);
  4230. } else if (HLMatrixType::isa(OldTy)) {
  4231. CopyArrayPtrToMatPtr(NewPtr, /*arrayBaseIdx*/ 0, OldPtr, HLM, Builder,
  4232. bRowMajor);
  4233. } else if (OldTy->isArrayTy()) {
  4234. std::vector<Value *> idxList;
  4235. idxList.emplace_back(Builder.getInt32(0));
  4236. CastCopyArray1DimToMultiDim(NewPtr, OldPtr, OldTy, idxList, /*calcIdx*/ 0,
  4237. HandleTy, HLM, Builder, CastCopyNewPtrToOldPtr,
  4238. bRowMajor);
  4239. }
  4240. }
  4241. void SROA_Parameter_HLSL::replaceCastParameter(
  4242. Value *NewParam, Value *OldParam, Function &F, Argument *Arg,
  4243. const DxilParamInputQual inputQual, IRBuilder<> &Builder) {
  4244. Type *HandleTy = m_pHLModule->GetOP()->GetHandleType();
  4245. Type *NewTy = NewParam->getType();
  4246. Type *OldTy = OldParam->getType();
  4247. bool bIn = inputQual == DxilParamInputQual::Inout ||
  4248. inputQual == DxilParamInputQual::In;
  4249. bool bOut = inputQual == DxilParamInputQual::Inout ||
  4250. inputQual == DxilParamInputQual::Out;
  4251. // Make sure InsertPoint after OldParam inst.
  4252. if (Instruction *I = dyn_cast<Instruction>(OldParam)) {
  4253. Builder.SetInsertPoint(I->getNextNode());
  4254. }
  4255. if (DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(OldParam)) {
  4256. // Add debug info to new param.
  4257. DIBuilder DIB(*F.getParent(), /*AllowUnresolved*/ false);
  4258. DIExpression *DDIExp = DDI->getExpression();
  4259. DIB.insertDeclare(NewParam, DDI->getVariable(), DDIExp, DDI->getDebugLoc(),
  4260. Builder.GetInsertPoint());
  4261. }
  4262. if (isa<Argument>(OldParam) && OldTy->isPointerTy()) {
  4263. // OldParam will be removed with Old function.
  4264. // Create alloca to replace it.
  4265. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(&F));
  4266. Value *AllocParam = AllocaBuilder.CreateAlloca(OldTy->getPointerElementType());
  4267. OldParam->replaceAllUsesWith(AllocParam);
  4268. OldParam = AllocParam;
  4269. }
  4270. if (NewTy == HandleTy) {
  4271. CopyHandleToResourcePtr(NewParam, OldParam, *m_pHLModule, Builder);
  4272. } else if (vectorEltsMap.count(NewParam)) {
  4273. // Vector is flattened to scalars.
  4274. Type *VecTy = OldTy;
  4275. if (VecTy->isPointerTy())
  4276. VecTy = VecTy->getPointerElementType();
  4277. // Flattened vector.
  4278. SmallVector<Value *, 4> &elts = vectorEltsMap[NewParam];
  4279. unsigned vecSize = elts.size();
  4280. if (NewTy->isPointerTy()) {
  4281. if (bIn) {
  4282. // Copy NewParam to OldParam at entry.
  4283. CopyEltsPtrToVectorPtr(elts, OldParam, VecTy, vecSize, Builder);
  4284. }
  4285. // bOut must be true here.
  4286. // Store the OldParam to NewParam before every return.
  4287. for (auto &BB : F.getBasicBlockList()) {
  4288. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  4289. IRBuilder<> RetBuilder(RI);
  4290. CopyVectorPtrToEltsPtr(OldParam, elts, vecSize, RetBuilder);
  4291. }
  4292. }
  4293. } else {
  4294. // Must be in parameter.
  4295. // Copy NewParam to OldParam at entry.
  4296. Value *Vec = UndefValue::get(VecTy);
  4297. for (unsigned i = 0; i < vecSize; i++) {
  4298. Vec = Builder.CreateInsertElement(Vec, elts[i], i);
  4299. }
  4300. if (OldTy->isPointerTy()) {
  4301. Builder.CreateStore(Vec, OldParam);
  4302. } else {
  4303. OldParam->replaceAllUsesWith(Vec);
  4304. }
  4305. }
  4306. // Don't need elts anymore.
  4307. vectorEltsMap.erase(NewParam);
  4308. } else if (!NewTy->isPointerTy()) {
  4309. // Ptr param is cast to non-ptr param.
  4310. // Must be in param.
  4311. // Store NewParam to OldParam at entry.
  4312. Builder.CreateStore(NewParam, OldParam);
  4313. } else if (HLMatrixType::isa(OldTy)) {
  4314. bool bRowMajor = castRowMajorParamMap.count(NewParam);
  4315. Value *Mat = LoadArrayPtrToMat(NewParam, /*arrayBaseIdx*/ 0, OldTy,
  4316. *m_pHLModule, Builder, bRowMajor);
  4317. OldParam->replaceAllUsesWith(Mat);
  4318. } else {
  4319. bool bRowMajor = castRowMajorParamMap.count(NewParam);
  4320. // NewTy is pointer type.
  4321. if (bIn) {
  4322. // Copy NewParam to OldParam at entry.
  4323. CastCopyNewPtrToOldPtr(NewParam, OldParam, *m_pHLModule, HandleTy,
  4324. Builder, bRowMajor);
  4325. }
  4326. if (bOut) {
  4327. // Store the OldParam to NewParam before every return.
  4328. for (auto &BB : F.getBasicBlockList()) {
  4329. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  4330. IRBuilder<> RetBuilder(RI);
  4331. CastCopyOldPtrToNewPtr(OldParam, NewParam, *m_pHLModule, HandleTy,
  4332. RetBuilder, bRowMajor);
  4333. }
  4334. }
  4335. }
  4336. }
  4337. }
  4338. Value *SROA_Parameter_HLSL::castResourceArgIfRequired(
  4339. Value *V, Type *Ty, bool bOut,
  4340. DxilParamInputQual inputQual,
  4341. IRBuilder<> &Builder) {
  4342. Type *HandleTy = m_pHLModule->GetOP()->GetHandleType();
  4343. Module &M = *m_pHLModule->GetModule();
  4344. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
  4345. // Lower resource type to handle ty.
  4346. if (dxilutil::IsHLSLResourceType(Ty)) {
  4347. Value *Res = V;
  4348. if (!bOut) {
  4349. Value *LdRes = Builder.CreateLoad(Res);
  4350. V = m_pHLModule->EmitHLOperationCall(Builder,
  4351. HLOpcodeGroup::HLCreateHandle,
  4352. /*opcode*/ 0, HandleTy, { LdRes }, M);
  4353. }
  4354. else {
  4355. V = AllocaBuilder.CreateAlloca(HandleTy);
  4356. }
  4357. castParamMap[V] = std::make_pair(Res, inputQual);
  4358. }
  4359. else if (Ty->isArrayTy()) {
  4360. unsigned arraySize = 1;
  4361. Type *AT = Ty;
  4362. while (AT->isArrayTy()) {
  4363. arraySize *= AT->getArrayNumElements();
  4364. AT = AT->getArrayElementType();
  4365. }
  4366. if (dxilutil::IsHLSLResourceType(AT)) {
  4367. Value *Res = V;
  4368. Type *Ty = ArrayType::get(HandleTy, arraySize);
  4369. V = AllocaBuilder.CreateAlloca(Ty);
  4370. castParamMap[V] = std::make_pair(Res, inputQual);
  4371. }
  4372. }
  4373. return V;
  4374. }
  4375. Value *SROA_Parameter_HLSL::castArgumentIfRequired(
  4376. Value *V, Type *Ty, bool bOut,
  4377. DxilParamInputQual inputQual, DxilFieldAnnotation &annotation,
  4378. IRBuilder<> &Builder,
  4379. DxilTypeSystem &TypeSys) {
  4380. Module &M = *m_pHLModule->GetModule();
  4381. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(Builder.GetInsertPoint()));
  4382. if (inputQual == DxilParamInputQual::InPayload) {
  4383. DXASSERT_NOMSG(isa<StructType>(Ty));
  4384. // Lower payload type here
  4385. StructType *LoweredTy = GetLoweredUDT(cast<StructType>(Ty), &TypeSys);
  4386. if (LoweredTy != Ty) {
  4387. Value *Ptr = AllocaBuilder.CreateAlloca(LoweredTy);
  4388. ReplaceUsesForLoweredUDT(V, Ptr);
  4389. castParamMap[V] = std::make_pair(Ptr, inputQual);
  4390. V = Ptr;
  4391. }
  4392. return V;
  4393. }
  4394. // Remove pointer for vector/scalar which is not out.
  4395. if (V->getType()->isPointerTy() && !Ty->isAggregateType() && !bOut) {
  4396. Value *Ptr = AllocaBuilder.CreateAlloca(Ty);
  4397. V->replaceAllUsesWith(Ptr);
  4398. // Create load here to make correct type.
  4399. // The Ptr will be store with correct value in replaceCastParameter.
  4400. if (Ptr->hasOneUse()) {
  4401. // Load after existing user for call arg replace.
  4402. // If not, call arg will load undef.
  4403. // This will not hurt parameter, new load is only after first load.
  4404. // It still before all the load users.
  4405. Instruction *User = cast<Instruction>(*(Ptr->user_begin()));
  4406. IRBuilder<> CallBuilder(User->getNextNode());
  4407. V = CallBuilder.CreateLoad(Ptr);
  4408. } else {
  4409. V = Builder.CreateLoad(Ptr);
  4410. }
  4411. castParamMap[V] = std::make_pair(Ptr, inputQual);
  4412. }
  4413. V = castResourceArgIfRequired(V, Ty, bOut, inputQual, Builder);
  4414. // Entry function matrix value parameter has major.
  4415. // Make sure its user use row major matrix value.
  4416. bool updateToColMajor = annotation.HasMatrixAnnotation() &&
  4417. annotation.GetMatrixAnnotation().Orientation ==
  4418. MatrixOrientation::ColumnMajor;
  4419. if (updateToColMajor) {
  4420. if (V->getType()->isPointerTy()) {
  4421. for (User *user : V->users()) {
  4422. CallInst *CI = dyn_cast<CallInst>(user);
  4423. if (!CI)
  4424. continue;
  4425. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4426. if (group != HLOpcodeGroup::HLMatLoadStore)
  4427. continue;
  4428. HLMatLoadStoreOpcode opcode =
  4429. static_cast<HLMatLoadStoreOpcode>(GetHLOpcode(CI));
  4430. Type *opcodeTy = Builder.getInt32Ty();
  4431. switch (opcode) {
  4432. case HLMatLoadStoreOpcode::RowMatLoad: {
  4433. // Update matrix function opcode to col major version.
  4434. Value *rowOpArg = ConstantInt::get(
  4435. opcodeTy,
  4436. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad));
  4437. CI->setOperand(HLOperandIndex::kOpcodeIdx, rowOpArg);
  4438. // Cast it to row major.
  4439. CallInst *RowMat = HLModule::EmitHLOperationCall(
  4440. Builder, HLOpcodeGroup::HLCast,
  4441. (unsigned)HLCastOpcode::ColMatrixToRowMatrix, Ty, {CI}, M);
  4442. CI->replaceAllUsesWith(RowMat);
  4443. // Set arg to CI again.
  4444. RowMat->setArgOperand(HLOperandIndex::kUnaryOpSrc0Idx, CI);
  4445. } break;
  4446. case HLMatLoadStoreOpcode::RowMatStore:
  4447. // Update matrix function opcode to col major version.
  4448. Value *rowOpArg = ConstantInt::get(
  4449. opcodeTy,
  4450. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore));
  4451. CI->setOperand(HLOperandIndex::kOpcodeIdx, rowOpArg);
  4452. Value *Mat = CI->getArgOperand(HLOperandIndex::kMatStoreValOpIdx);
  4453. // Cast it to col major.
  4454. CallInst *RowMat = HLModule::EmitHLOperationCall(
  4455. Builder, HLOpcodeGroup::HLCast,
  4456. (unsigned)HLCastOpcode::RowMatrixToColMatrix, Ty, {Mat}, M);
  4457. CI->setArgOperand(HLOperandIndex::kMatStoreValOpIdx, RowMat);
  4458. break;
  4459. }
  4460. }
  4461. } else {
  4462. CallInst *RowMat = HLModule::EmitHLOperationCall(
  4463. Builder, HLOpcodeGroup::HLCast,
  4464. (unsigned)HLCastOpcode::ColMatrixToRowMatrix, Ty, {V}, M);
  4465. V->replaceAllUsesWith(RowMat);
  4466. // Set arg to V again.
  4467. RowMat->setArgOperand(HLOperandIndex::kUnaryOpSrc0Idx, V);
  4468. }
  4469. }
  4470. return V;
  4471. }
  4472. struct AnnotatedValue {
  4473. llvm::Value *Value;
  4474. DxilFieldAnnotation Annotation;
  4475. };
  4476. void SROA_Parameter_HLSL::flattenArgument(
  4477. Function *F, Value *Arg, bool bForParam,
  4478. DxilParameterAnnotation &paramAnnotation,
  4479. std::vector<Value *> &FlatParamList,
  4480. std::vector<DxilParameterAnnotation> &FlatAnnotationList,
  4481. BasicBlock *EntryBlock, DbgDeclareInst *DDI) {
  4482. std::deque<AnnotatedValue> WorkList;
  4483. WorkList.push_back({ Arg, paramAnnotation });
  4484. unsigned startArgIndex = FlatAnnotationList.size();
  4485. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  4486. const std::string &semantic = paramAnnotation.GetSemanticString();
  4487. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  4488. bool bOut = inputQual == DxilParamInputQual::Out ||
  4489. inputQual == DxilParamInputQual::Inout ||
  4490. inputQual == DxilParamInputQual::OutStream0 ||
  4491. inputQual == DxilParamInputQual::OutStream1 ||
  4492. inputQual == DxilParamInputQual::OutStream2 ||
  4493. inputQual == DxilParamInputQual::OutStream3;
  4494. // Map from semantic string to type.
  4495. llvm::StringMap<Type *> semanticTypeMap;
  4496. // Original semantic type.
  4497. if (!semantic.empty()) {
  4498. // Unwrap top-level array if primitive
  4499. if (inputQual == DxilParamInputQual::InputPatch ||
  4500. inputQual == DxilParamInputQual::OutputPatch ||
  4501. inputQual == DxilParamInputQual::InputPrimitive) {
  4502. Type *Ty = Arg->getType();
  4503. if (Ty->isPointerTy())
  4504. Ty = Ty->getPointerElementType();
  4505. if (Ty->isArrayTy())
  4506. semanticTypeMap[semantic] = Ty->getArrayElementType();
  4507. } else {
  4508. semanticTypeMap[semantic] = Arg->getType();
  4509. }
  4510. }
  4511. std::vector<Instruction*> deadAllocas;
  4512. DIBuilder DIB(*F->getParent(), /*AllowUnresolved*/ false);
  4513. unsigned debugOffset = 0;
  4514. const DataLayout &DL = F->getParent()->getDataLayout();
  4515. // Process the worklist
  4516. while (!WorkList.empty()) {
  4517. AnnotatedValue AV = WorkList.front();
  4518. WorkList.pop_front();
  4519. // Do not skip unused parameter.
  4520. Value *V = AV.Value;
  4521. DxilFieldAnnotation &annotation = AV.Annotation;
  4522. // We can never replace memcpy for arguments because they have an implicit
  4523. // first memcpy that happens from argument passing, and pointer analysis
  4524. // will not reveal that, especially if we've done a first SROA pass on V.
  4525. // No DomTree needed for that reason
  4526. const bool bAllowReplace = false;
  4527. SROA_Helper::LowerMemcpy(V, &annotation, dxilTypeSys, DL, nullptr /*DT */, bAllowReplace);
  4528. // Now is safe to create the IRBuilders.
  4529. // If we create it before LowerMemcpy, the insertion pointer instruction may get deleted
  4530. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(EntryBlock));
  4531. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(EntryBlock));
  4532. std::vector<Value *> Elts;
  4533. // Not flat vector for entry function currently.
  4534. bool SROAed = false;
  4535. Type *BrokenUpTy = nullptr;
  4536. uint64_t NumInstances = 1;
  4537. if (inputQual != DxilParamInputQual::InPayload) {
  4538. // DomTree isn't used by arguments
  4539. SROAed = SROA_Helper::DoScalarReplacement(
  4540. V, Elts, BrokenUpTy, NumInstances, Builder,
  4541. /*bFlatVector*/ false, annotation.IsPrecise(),
  4542. dxilTypeSys, DL, DeadInsts, /*DT*/ nullptr);
  4543. }
  4544. if (SROAed) {
  4545. Type *Ty = V->getType()->getPointerElementType();
  4546. // Skip empty struct parameters.
  4547. if (SROA_Helper::IsEmptyStructType(Ty, dxilTypeSys)) {
  4548. SROA_Helper::MarkEmptyStructUsers(V, DeadInsts);
  4549. DeleteDeadInstructions();
  4550. continue;
  4551. }
  4552. bool precise = annotation.IsPrecise();
  4553. const std::string &semantic = annotation.GetSemanticString();
  4554. hlsl::InterpolationMode interpMode = annotation.GetInterpolationMode();
  4555. // Push Elts into workList from right to left to preserve the order.
  4556. for (unsigned ri=0;ri<Elts.size();ri++) {
  4557. unsigned i = Elts.size() - ri - 1;
  4558. DxilFieldAnnotation EltAnnotation = GetEltAnnotation(Ty, i, annotation, dxilTypeSys);
  4559. const std::string &eltSem = EltAnnotation.GetSemanticString();
  4560. if (!semantic.empty()) {
  4561. if (!eltSem.empty()) {
  4562. // It doesn't look like we can provide source location information from here
  4563. F->getContext().emitWarning(
  4564. Twine("semantic '") + eltSem + "' on field overridden by function or enclosing type");
  4565. }
  4566. // Inherit semantic from parent, but only preserve it for the first element.
  4567. // Subsequent elements are noted with a special value that gets resolved
  4568. // once the argument is completely flattened.
  4569. EltAnnotation.SetSemanticString(i == 0 ? semantic : ContinuedPseudoSemantic);
  4570. } else if (!eltSem.empty() &&
  4571. semanticTypeMap.count(eltSem) == 0) {
  4572. Type *EltTy = dxilutil::GetArrayEltTy(Ty);
  4573. DXASSERT(EltTy->isStructTy(), "must be a struct type to has semantic.");
  4574. semanticTypeMap[eltSem] = EltTy->getStructElementType(i);
  4575. }
  4576. if (precise)
  4577. EltAnnotation.SetPrecise();
  4578. if (EltAnnotation.GetInterpolationMode().GetKind() == DXIL::InterpolationMode::Undefined)
  4579. EltAnnotation.SetInterpolationMode(interpMode);
  4580. WorkList.push_front({ Elts[i], EltAnnotation });
  4581. }
  4582. ++NumReplaced;
  4583. if (Instruction *I = dyn_cast<Instruction>(V))
  4584. deadAllocas.emplace_back(I);
  4585. } else {
  4586. Type *Ty = V->getType();
  4587. if (Ty->isPointerTy())
  4588. Ty = Ty->getPointerElementType();
  4589. // Flatten array of SV_Target.
  4590. StringRef semanticStr = annotation.GetSemanticString();
  4591. if (semanticStr.upper().find("SV_TARGET") == 0 &&
  4592. Ty->isArrayTy()) {
  4593. Type *Ty = cast<ArrayType>(V->getType()->getPointerElementType());
  4594. StringRef targetStr;
  4595. unsigned targetIndex;
  4596. Semantic::DecomposeNameAndIndex(semanticStr, &targetStr, &targetIndex);
  4597. // Replace target parameter with local target.
  4598. AllocaInst *localTarget = AllocaBuilder.CreateAlloca(Ty);
  4599. V->replaceAllUsesWith(localTarget);
  4600. unsigned arraySize = 1;
  4601. std::vector<unsigned> arraySizeList;
  4602. while (Ty->isArrayTy()) {
  4603. unsigned size = Ty->getArrayNumElements();
  4604. arraySizeList.emplace_back(size);
  4605. arraySize *= size;
  4606. Ty = Ty->getArrayElementType();
  4607. }
  4608. unsigned arrayLevel = arraySizeList.size();
  4609. std::vector<unsigned> arrayIdxList(arrayLevel, 0);
  4610. // Create flattened target.
  4611. DxilFieldAnnotation EltAnnotation = annotation;
  4612. for (unsigned i=0;i<arraySize;i++) {
  4613. Value *Elt = AllocaBuilder.CreateAlloca(Ty);
  4614. EltAnnotation.SetSemanticString(targetStr.str()+std::to_string(targetIndex+i));
  4615. // Add semantic type.
  4616. semanticTypeMap[EltAnnotation.GetSemanticString()] = Ty;
  4617. WorkList.push_front({ Elt, EltAnnotation });
  4618. // Copy local target to flattened target.
  4619. std::vector<Value*> idxList(arrayLevel+1);
  4620. idxList[0] = Builder.getInt32(0);
  4621. for (unsigned idx=0;idx<arrayLevel; idx++) {
  4622. idxList[idx+1] = Builder.getInt32(arrayIdxList[idx]);
  4623. }
  4624. if (bForParam) {
  4625. // If Argument, copy before each return.
  4626. for (auto &BB : F->getBasicBlockList()) {
  4627. TerminatorInst *TI = BB.getTerminator();
  4628. if (isa<ReturnInst>(TI)) {
  4629. IRBuilder<> RetBuilder(TI);
  4630. Value *Ptr = RetBuilder.CreateGEP(localTarget, idxList);
  4631. Value *V = RetBuilder.CreateLoad(Ptr);
  4632. RetBuilder.CreateStore(V, Elt);
  4633. }
  4634. }
  4635. } else {
  4636. // Else, copy with Builder.
  4637. Value *Ptr = Builder.CreateGEP(localTarget, idxList);
  4638. Value *V = Builder.CreateLoad(Ptr);
  4639. Builder.CreateStore(V, Elt);
  4640. }
  4641. // Update arrayIdxList.
  4642. for (unsigned idx=arrayLevel;idx>0;idx--) {
  4643. arrayIdxList[idx-1]++;
  4644. if (arrayIdxList[idx-1] < arraySizeList[idx-1])
  4645. break;
  4646. arrayIdxList[idx-1] = 0;
  4647. }
  4648. }
  4649. continue;
  4650. }
  4651. // Cast vector/matrix/resource parameter.
  4652. V = castArgumentIfRequired(V, Ty, bOut, inputQual,
  4653. annotation, Builder, dxilTypeSys);
  4654. // Cannot SROA, save it to final parameter list.
  4655. FlatParamList.emplace_back(V);
  4656. // Create ParamAnnotation for V.
  4657. FlatAnnotationList.emplace_back(DxilParameterAnnotation());
  4658. DxilParameterAnnotation &flatParamAnnotation = FlatAnnotationList.back();
  4659. flatParamAnnotation.SetParamInputQual(paramAnnotation.GetParamInputQual());
  4660. flatParamAnnotation.SetInterpolationMode(annotation.GetInterpolationMode());
  4661. flatParamAnnotation.SetSemanticString(annotation.GetSemanticString());
  4662. flatParamAnnotation.SetCompType(annotation.GetCompType().GetKind());
  4663. flatParamAnnotation.SetMatrixAnnotation(annotation.GetMatrixAnnotation());
  4664. flatParamAnnotation.SetPrecise(annotation.IsPrecise());
  4665. flatParamAnnotation.SetResourceAttribute(annotation.GetResourceAttribute());
  4666. // Add debug info.
  4667. if (DDI && V != Arg) {
  4668. Value *TmpV = V;
  4669. // If V is casted, add debug into to original V.
  4670. if (castParamMap.count(V)) {
  4671. TmpV = castParamMap[V].first;
  4672. // One more level for ptr of input vector.
  4673. // It cast from ptr to non-ptr then cast to scalars.
  4674. if (castParamMap.count(TmpV)) {
  4675. TmpV = castParamMap[TmpV].first;
  4676. }
  4677. }
  4678. Type *Ty = TmpV->getType();
  4679. if (Ty->isPointerTy())
  4680. Ty = Ty->getPointerElementType();
  4681. unsigned size = DL.getTypeAllocSize(Ty);
  4682. #if 0 // HLSL Change
  4683. DIExpression *DDIExp = DIB.createBitPieceExpression(debugOffset, size);
  4684. #else // HLSL Change
  4685. Type *argTy = Arg->getType();
  4686. if (argTy->isPointerTy())
  4687. argTy = argTy->getPointerElementType();
  4688. DIExpression *DDIExp = nullptr;
  4689. if (debugOffset == 0 && DL.getTypeAllocSize(argTy) == size) {
  4690. DDIExp = DIB.createExpression();
  4691. }
  4692. else {
  4693. DDIExp = DIB.createBitPieceExpression(debugOffset * 8, size * 8);
  4694. }
  4695. #endif // HLSL Change
  4696. debugOffset += size;
  4697. DIB.insertDeclare(TmpV, DDI->getVariable(), DDIExp, DDI->getDebugLoc(),
  4698. Builder.GetInsertPoint());
  4699. }
  4700. // Flatten stream out.
  4701. if (HLModule::IsStreamOutputPtrType(V->getType())) {
  4702. // For stream output objects.
  4703. // Create a value as output value.
  4704. Type *outputType = V->getType()->getPointerElementType()->getStructElementType(0);
  4705. Value *outputVal = AllocaBuilder.CreateAlloca(outputType);
  4706. // For each stream.Append(data)
  4707. // transform into
  4708. // d = load data
  4709. // store outputVal, d
  4710. // stream.Append(outputVal)
  4711. for (User *user : V->users()) {
  4712. if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4713. unsigned opcode = GetHLOpcode(CI);
  4714. if (opcode == static_cast<unsigned>(IntrinsicOp::MOP_Append)) {
  4715. // At this point, the stream append data argument might or not have been SROA'd
  4716. Value *firstDataPtr = CI->getArgOperand(HLOperandIndex::kStreamAppendDataOpIndex);
  4717. DXASSERT(firstDataPtr->getType()->isPointerTy(), "Append value must be a pointer.");
  4718. if (firstDataPtr->getType()->getPointerElementType() == outputType) {
  4719. // The data has not been SROA'd
  4720. DXASSERT(CI->getNumArgOperands() == (HLOperandIndex::kStreamAppendDataOpIndex + 1),
  4721. "Unexpected number of arguments for non-SROA'd StreamOutput.Append");
  4722. IRBuilder<> Builder(CI);
  4723. llvm::SmallVector<llvm::Value *, 16> idxList;
  4724. SplitCpy(firstDataPtr->getType(), outputVal, firstDataPtr, idxList, Builder, DL,
  4725. dxilTypeSys, &flatParamAnnotation);
  4726. CI->setArgOperand(HLOperandIndex::kStreamAppendDataOpIndex, outputVal);
  4727. }
  4728. else {
  4729. // Append has been SROA'd, we might be operating on multiple values
  4730. // with types differing from the stream output type.
  4731. // Flatten store outputVal.
  4732. // Must be struct to be flatten.
  4733. IRBuilder<> Builder(CI);
  4734. llvm::SmallVector<llvm::Value *, 16> IdxList;
  4735. llvm::SmallVector<llvm::Value *, 16> EltPtrList;
  4736. llvm::SmallVector<const DxilFieldAnnotation*, 16> EltAnnotationList;
  4737. // split
  4738. SplitPtr(outputVal, IdxList, outputVal->getType(), flatParamAnnotation,
  4739. EltPtrList, EltAnnotationList, dxilTypeSys, Builder);
  4740. unsigned eltCount = CI->getNumArgOperands()-2;
  4741. DXASSERT_LOCALVAR(eltCount, eltCount == EltPtrList.size(), "invalid element count");
  4742. for (unsigned i = HLOperandIndex::kStreamAppendDataOpIndex; i < CI->getNumArgOperands(); i++) {
  4743. Value *DataPtr = CI->getArgOperand(i);
  4744. Value *EltPtr = EltPtrList[i - HLOperandIndex::kStreamAppendDataOpIndex];
  4745. const DxilFieldAnnotation *EltAnnotation = EltAnnotationList[i - HLOperandIndex::kStreamAppendDataOpIndex];
  4746. llvm::SmallVector<llvm::Value *, 16> IdxList;
  4747. SplitCpy(DataPtr->getType(), EltPtr, DataPtr, IdxList,
  4748. Builder, DL, dxilTypeSys, EltAnnotation);
  4749. CI->setArgOperand(i, EltPtr);
  4750. }
  4751. }
  4752. }
  4753. }
  4754. }
  4755. // Then split output value to generate ParamQual.
  4756. WorkList.push_front({ outputVal, annotation });
  4757. }
  4758. }
  4759. }
  4760. // Now erase any instructions that were made dead while rewriting the
  4761. // alloca.
  4762. DeleteDeadInstructions();
  4763. // Erase dead allocas after all uses deleted.
  4764. for (Instruction *I : deadAllocas)
  4765. I->eraseFromParent();
  4766. unsigned endArgIndex = FlatAnnotationList.size();
  4767. if (bForParam && startArgIndex < endArgIndex) {
  4768. DxilParamInputQual inputQual = paramAnnotation.GetParamInputQual();
  4769. if (inputQual == DxilParamInputQual::OutStream0 ||
  4770. inputQual == DxilParamInputQual::OutStream1 ||
  4771. inputQual == DxilParamInputQual::OutStream2 ||
  4772. inputQual == DxilParamInputQual::OutStream3)
  4773. startArgIndex++;
  4774. DxilParameterAnnotation &flatParamAnnotation =
  4775. FlatAnnotationList[startArgIndex];
  4776. const std::string &semantic = flatParamAnnotation.GetSemanticString();
  4777. if (!semantic.empty())
  4778. allocateSemanticIndex(FlatAnnotationList, startArgIndex,
  4779. semanticTypeMap);
  4780. }
  4781. }
  4782. static bool IsUsedAsCallArg(Value *V) {
  4783. for (User *U : V->users()) {
  4784. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  4785. Function *CalledF = CI->getCalledFunction();
  4786. HLOpcodeGroup group = GetHLOpcodeGroup(CalledF);
  4787. // Skip HL operations.
  4788. if (group != HLOpcodeGroup::NotHL ||
  4789. group == HLOpcodeGroup::HLExtIntrinsic) {
  4790. continue;
  4791. }
  4792. // Skip llvm intrinsic.
  4793. if (CalledF->isIntrinsic())
  4794. continue;
  4795. return true;
  4796. }
  4797. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(U)) {
  4798. if (IsUsedAsCallArg(GEP))
  4799. return true;
  4800. }
  4801. }
  4802. return false;
  4803. }
  4804. // For function parameter which used in function call and need to be flattened.
  4805. // Replace with tmp alloca.
  4806. void SROA_Parameter_HLSL::preprocessArgUsedInCall(Function *F) {
  4807. if (F->isDeclaration())
  4808. return;
  4809. const DataLayout &DL = m_pHLModule->GetModule()->getDataLayout();
  4810. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  4811. DxilFunctionAnnotation *pFuncAnnot = typeSys.GetFunctionAnnotation(F);
  4812. DXASSERT(pFuncAnnot, "else invalid function");
  4813. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  4814. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(F));
  4815. SmallVector<ReturnInst*, 2> retList;
  4816. for (BasicBlock &bb : F->getBasicBlockList()) {
  4817. if (ReturnInst *RI = dyn_cast<ReturnInst>(bb.getTerminator())) {
  4818. retList.emplace_back(RI);
  4819. }
  4820. }
  4821. for (Argument &arg : F->args()) {
  4822. Type *Ty = arg.getType();
  4823. // Only check pointer types.
  4824. if (!Ty->isPointerTy())
  4825. continue;
  4826. Ty = Ty->getPointerElementType();
  4827. // Skip scalar types.
  4828. if (!Ty->isAggregateType() &&
  4829. Ty->getScalarType() == Ty)
  4830. continue;
  4831. bool bUsedInCall = IsUsedAsCallArg(&arg);
  4832. if (bUsedInCall) {
  4833. // Create tmp.
  4834. Value *TmpArg = AllocaBuilder.CreateAlloca(Ty);
  4835. // Replace arg with tmp.
  4836. arg.replaceAllUsesWith(TmpArg);
  4837. DxilParameterAnnotation &paramAnnot = pFuncAnnot->GetParameterAnnotation(arg.getArgNo());
  4838. DxilParamInputQual inputQual = paramAnnot.GetParamInputQual();
  4839. unsigned size = DL.getTypeAllocSize(Ty);
  4840. // Copy between arg and tmp.
  4841. if (inputQual == DxilParamInputQual::In ||
  4842. inputQual == DxilParamInputQual::Inout) {
  4843. // copy arg to tmp.
  4844. CallInst *argToTmp = Builder.CreateMemCpy(TmpArg, &arg, size, 0);
  4845. // Split the memcpy.
  4846. MemcpySplitter::SplitMemCpy(cast<MemCpyInst>(argToTmp), DL, nullptr,
  4847. typeSys);
  4848. }
  4849. if (inputQual == DxilParamInputQual::Out ||
  4850. inputQual == DxilParamInputQual::Inout) {
  4851. for (ReturnInst *RI : retList) {
  4852. IRBuilder<> RetBuilder(RI);
  4853. // copy tmp to arg.
  4854. CallInst *tmpToArg =
  4855. RetBuilder.CreateMemCpy(&arg, TmpArg, size, 0);
  4856. // Split the memcpy.
  4857. MemcpySplitter::SplitMemCpy(cast<MemCpyInst>(tmpToArg), DL, nullptr,
  4858. typeSys);
  4859. }
  4860. }
  4861. // TODO: support other DxilParamInputQual.
  4862. }
  4863. }
  4864. }
  4865. /// moveFunctionBlocks - Move body of F to flatF.
  4866. void SROA_Parameter_HLSL::moveFunctionBody(Function *F, Function *flatF) {
  4867. bool updateRetType = F->getReturnType() != flatF->getReturnType();
  4868. // Splice the body of the old function right into the new function.
  4869. flatF->getBasicBlockList().splice(flatF->begin(), F->getBasicBlockList());
  4870. // Update Block uses.
  4871. if (updateRetType) {
  4872. for (BasicBlock &BB : flatF->getBasicBlockList()) {
  4873. if (updateRetType) {
  4874. // Replace ret with ret void.
  4875. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  4876. // Create store for return.
  4877. IRBuilder<> Builder(RI);
  4878. Builder.CreateRetVoid();
  4879. RI->eraseFromParent();
  4880. }
  4881. }
  4882. }
  4883. }
  4884. }
  4885. static void SplitArrayCopy(Value *V, const DataLayout &DL,
  4886. DxilTypeSystem &typeSys,
  4887. DxilFieldAnnotation *fieldAnnotation) {
  4888. for (auto U = V->user_begin(); U != V->user_end();) {
  4889. User *user = *(U++);
  4890. if (StoreInst *ST = dyn_cast<StoreInst>(user)) {
  4891. Value *ptr = ST->getPointerOperand();
  4892. Value *val = ST->getValueOperand();
  4893. IRBuilder<> Builder(ST);
  4894. SmallVector<Value *, 16> idxList;
  4895. SplitCpy(ptr->getType(), ptr, val, idxList, Builder, DL, typeSys,
  4896. fieldAnnotation);
  4897. ST->eraseFromParent();
  4898. }
  4899. }
  4900. }
  4901. static void CheckArgUsage(Value *V, bool &bLoad, bool &bStore) {
  4902. if (bLoad && bStore)
  4903. return;
  4904. for (User *user : V->users()) {
  4905. if (dyn_cast<LoadInst>(user)) {
  4906. bLoad = true;
  4907. } else if (dyn_cast<StoreInst>(user)) {
  4908. bStore = true;
  4909. } else if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(user)) {
  4910. CheckArgUsage(GEP, bLoad, bStore);
  4911. } else if (CallInst *CI = dyn_cast<CallInst>(user)) {
  4912. if (CI->getType()->isPointerTy())
  4913. CheckArgUsage(CI, bLoad, bStore);
  4914. else {
  4915. HLOpcodeGroup group = GetHLOpcodeGroupByName(CI->getCalledFunction());
  4916. if (group == HLOpcodeGroup::HLMatLoadStore) {
  4917. HLMatLoadStoreOpcode opcode =
  4918. static_cast<HLMatLoadStoreOpcode>(GetHLOpcode(CI));
  4919. switch (opcode) {
  4920. case HLMatLoadStoreOpcode::ColMatLoad:
  4921. case HLMatLoadStoreOpcode::RowMatLoad:
  4922. bLoad = true;
  4923. break;
  4924. case HLMatLoadStoreOpcode::ColMatStore:
  4925. case HLMatLoadStoreOpcode::RowMatStore:
  4926. bStore = true;
  4927. break;
  4928. }
  4929. }
  4930. }
  4931. }
  4932. }
  4933. }
  4934. // AcceptHitAndEndSearch and IgnoreHit both will not return, but require
  4935. // outputs to have been written before the call. Do this by:
  4936. // - inject a return immediately after the call if not there already
  4937. // - LegalizeDxilInputOutputs will inject writes from temp alloca to
  4938. // outputs before each return.
  4939. // - in HLOperationLower, after lowering the intrinsic, move the intrinsic
  4940. // to just before the return.
  4941. static void InjectReturnAfterNoReturnPreserveOutput(HLModule &HLM) {
  4942. for (Function &F : HLM.GetModule()->functions()) {
  4943. if (GetHLOpcodeGroup(&F) == HLOpcodeGroup::HLIntrinsic) {
  4944. for (auto U : F.users()) {
  4945. if (CallInst *CI = dyn_cast<CallInst>(U)) {
  4946. unsigned OpCode = GetHLOpcode(CI);
  4947. if (OpCode == (unsigned)IntrinsicOp::IOP_AcceptHitAndEndSearch ||
  4948. OpCode == (unsigned)IntrinsicOp::IOP_IgnoreHit) {
  4949. Instruction *pNextI = CI->getNextNode();
  4950. // Skip if already has a return immediatly following call
  4951. if (isa<ReturnInst>(pNextI))
  4952. continue;
  4953. // split block and add return:
  4954. BasicBlock *BB = CI->getParent();
  4955. BB->splitBasicBlock(pNextI);
  4956. TerminatorInst *Term = BB->getTerminator();
  4957. Term->eraseFromParent();
  4958. IRBuilder<> Builder(BB);
  4959. llvm::Type *RetTy = CI->getParent()->getParent()->getReturnType();
  4960. if (RetTy->isVoidTy())
  4961. Builder.CreateRetVoid();
  4962. else
  4963. Builder.CreateRet(UndefValue::get(RetTy));
  4964. }
  4965. }
  4966. }
  4967. }
  4968. }
  4969. }
  4970. // Support store to input and load from output.
  4971. static void LegalizeDxilInputOutputs(Function *F,
  4972. DxilFunctionAnnotation *EntryAnnotation,
  4973. const DataLayout &DL,
  4974. DxilTypeSystem &typeSys) {
  4975. BasicBlock &EntryBlk = F->getEntryBlock();
  4976. Module *M = F->getParent();
  4977. // Map from output to the temp created for it.
  4978. MapVector<Argument *, Value*> outputTempMap; // Need deterministic order of iteration
  4979. for (Argument &arg : F->args()) {
  4980. Type *Ty = arg.getType();
  4981. DxilParameterAnnotation &paramAnnotation = EntryAnnotation->GetParameterAnnotation(arg.getArgNo());
  4982. DxilParamInputQual qual = paramAnnotation.GetParamInputQual();
  4983. bool isColMajor = false;
  4984. // Skip arg which is not a pointer.
  4985. if (!Ty->isPointerTy()) {
  4986. if (HLMatrixType::isa(Ty)) {
  4987. // Replace matrix arg with cast to vec. It will be lowered in
  4988. // DxilGenerationPass.
  4989. isColMajor = paramAnnotation.GetMatrixAnnotation().Orientation ==
  4990. MatrixOrientation::ColumnMajor;
  4991. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(F));
  4992. HLCastOpcode opcode = isColMajor ? HLCastOpcode::ColMatrixToVecCast
  4993. : HLCastOpcode::RowMatrixToVecCast;
  4994. Value *undefVal = UndefValue::get(Ty);
  4995. Value *Cast = HLModule::EmitHLOperationCall(
  4996. Builder, HLOpcodeGroup::HLCast, static_cast<unsigned>(opcode), Ty,
  4997. {undefVal}, *M);
  4998. arg.replaceAllUsesWith(Cast);
  4999. // Set arg as the operand.
  5000. CallInst *CI = cast<CallInst>(Cast);
  5001. CI->setArgOperand(HLOperandIndex::kUnaryOpSrc0Idx, &arg);
  5002. }
  5003. continue;
  5004. }
  5005. Ty = Ty->getPointerElementType();
  5006. bool bLoad = false;
  5007. bool bStore = false;
  5008. CheckArgUsage(&arg, bLoad, bStore);
  5009. bool bStoreInputToTemp = false;
  5010. bool bLoadOutputFromTemp = false;
  5011. if (qual == DxilParamInputQual::In && bStore) {
  5012. bStoreInputToTemp = true;
  5013. } else if (qual == DxilParamInputQual::Out && bLoad) {
  5014. bLoadOutputFromTemp = true;
  5015. } else if (bLoad && bStore) {
  5016. switch (qual) {
  5017. case DxilParamInputQual::InPayload:
  5018. case DxilParamInputQual::InputPrimitive:
  5019. case DxilParamInputQual::InputPatch:
  5020. case DxilParamInputQual::OutputPatch: {
  5021. bStoreInputToTemp = true;
  5022. } break;
  5023. case DxilParamInputQual::Inout:
  5024. break;
  5025. default:
  5026. DXASSERT(0, "invalid input qual here");
  5027. }
  5028. } else if (qual == DxilParamInputQual::Inout) {
  5029. // Only replace inout when (bLoad && bStore) == false.
  5030. bLoadOutputFromTemp = true;
  5031. bStoreInputToTemp = true;
  5032. }
  5033. if (HLMatrixType::isa(Ty)) {
  5034. if (qual == DxilParamInputQual::In)
  5035. bStoreInputToTemp = bLoad;
  5036. else if (qual == DxilParamInputQual::Out)
  5037. bLoadOutputFromTemp = bStore;
  5038. else if (qual == DxilParamInputQual::Inout) {
  5039. bStoreInputToTemp = true;
  5040. bLoadOutputFromTemp = true;
  5041. }
  5042. }
  5043. if (bStoreInputToTemp || bLoadOutputFromTemp) {
  5044. IRBuilder<> AllocaBuilder(EntryBlk.getFirstInsertionPt());
  5045. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(&EntryBlk));
  5046. AllocaInst *temp = AllocaBuilder.CreateAlloca(Ty);
  5047. // Replace all uses with temp.
  5048. arg.replaceAllUsesWith(temp);
  5049. // Copy input to temp.
  5050. if (bStoreInputToTemp) {
  5051. llvm::SmallVector<llvm::Value *, 16> idxList;
  5052. // split copy.
  5053. SplitCpy(temp->getType(), temp, &arg, idxList, Builder, DL, typeSys,
  5054. &paramAnnotation);
  5055. }
  5056. // Generate store output, temp later.
  5057. if (bLoadOutputFromTemp) {
  5058. outputTempMap[&arg] = temp;
  5059. }
  5060. }
  5061. }
  5062. for (BasicBlock &BB : F->getBasicBlockList()) {
  5063. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  5064. IRBuilder<> Builder(RI);
  5065. // Copy temp to output.
  5066. for (auto It : outputTempMap) {
  5067. Argument *output = It.first;
  5068. Value *temp = It.second;
  5069. llvm::SmallVector<llvm::Value *, 16> idxList;
  5070. DxilParameterAnnotation &paramAnnotation =
  5071. EntryAnnotation->GetParameterAnnotation(output->getArgNo());
  5072. auto Iter = Builder.GetInsertPoint();
  5073. if (RI != BB.begin())
  5074. Iter--;
  5075. // split copy.
  5076. SplitCpy(output->getType(), output, temp, idxList, Builder, DL, typeSys,
  5077. &paramAnnotation);
  5078. }
  5079. // Clone the return.
  5080. Builder.CreateRet(RI->getReturnValue());
  5081. RI->eraseFromParent();
  5082. }
  5083. }
  5084. }
  5085. void SROA_Parameter_HLSL::createFlattenedFunction(Function *F) {
  5086. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  5087. DXASSERT(F == m_pHLModule->GetEntryFunction() ||
  5088. m_pHLModule->IsEntryThatUsesSignatures(F),
  5089. "otherwise, createFlattenedFunction called on library function "
  5090. "that should not be flattened.");
  5091. const DataLayout &DL = m_pHLModule->GetModule()->getDataLayout();
  5092. // Skip void (void) function.
  5093. if (F->getReturnType()->isVoidTy() && F->getArgumentList().empty()) {
  5094. return;
  5095. }
  5096. // Clear maps for cast.
  5097. castParamMap.clear();
  5098. vectorEltsMap.clear();
  5099. DxilFunctionAnnotation *funcAnnotation = m_pHLModule->GetFunctionAnnotation(F);
  5100. DXASSERT(funcAnnotation, "must find annotation for function");
  5101. std::deque<Value *> WorkList;
  5102. LLVMContext &Ctx = m_pHLModule->GetCtx();
  5103. std::unique_ptr<BasicBlock> TmpBlockForFuncDecl;
  5104. BasicBlock *EntryBlock;
  5105. if (F->isDeclaration()) {
  5106. // We still want to SROA the parameters, so creaty a dummy
  5107. // function body block to avoid special cases.
  5108. TmpBlockForFuncDecl.reset(BasicBlock::Create(Ctx));
  5109. // Create return as terminator.
  5110. IRBuilder<> RetBuilder(TmpBlockForFuncDecl.get());
  5111. RetBuilder.CreateRetVoid();
  5112. EntryBlock = TmpBlockForFuncDecl.get();
  5113. } else {
  5114. EntryBlock = &F->getEntryBlock();
  5115. }
  5116. std::vector<Value *> FlatParamList;
  5117. std::vector<DxilParameterAnnotation> FlatParamAnnotationList;
  5118. std::vector<int> FlatParamOriArgNoList;
  5119. const bool bForParamTrue = true;
  5120. // Add all argument to worklist.
  5121. for (Argument &Arg : F->args()) {
  5122. // merge GEP use for arg.
  5123. HLModule::MergeGepUse(&Arg);
  5124. unsigned prevFlatParamCount = FlatParamList.size();
  5125. DxilParameterAnnotation &paramAnnotation =
  5126. funcAnnotation->GetParameterAnnotation(Arg.getArgNo());
  5127. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(&Arg);
  5128. flattenArgument(F, &Arg, bForParamTrue, paramAnnotation, FlatParamList,
  5129. FlatParamAnnotationList, EntryBlock, DDI);
  5130. unsigned newFlatParamCount = FlatParamList.size() - prevFlatParamCount;
  5131. for (unsigned i = 0; i < newFlatParamCount; i++) {
  5132. FlatParamOriArgNoList.emplace_back(Arg.getArgNo());
  5133. }
  5134. }
  5135. Type *retType = F->getReturnType();
  5136. std::vector<Value *> FlatRetList;
  5137. std::vector<DxilParameterAnnotation> FlatRetAnnotationList;
  5138. // Split and change to out parameter.
  5139. if (!retType->isVoidTy()) {
  5140. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(EntryBlock));
  5141. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(EntryBlock));
  5142. Value *retValAddr = AllocaBuilder.CreateAlloca(retType);
  5143. DxilParameterAnnotation &retAnnotation =
  5144. funcAnnotation->GetRetTypeAnnotation();
  5145. Module &M = *m_pHLModule->GetModule();
  5146. Type *voidTy = Type::getVoidTy(m_pHLModule->GetCtx());
  5147. #if 0 // We don't really want this to show up in debug info.
  5148. // Create DbgDecl for the ret value.
  5149. if (DISubprogram *funcDI = getDISubprogram(F)) {
  5150. DITypeRef RetDITyRef = funcDI->getType()->getTypeArray()[0];
  5151. DITypeIdentifierMap EmptyMap;
  5152. DIType * RetDIType = RetDITyRef.resolve(EmptyMap);
  5153. DIBuilder DIB(*F->getParent(), /*AllowUnresolved*/ false);
  5154. DILocalVariable *RetVar = DIB.createLocalVariable(llvm::dwarf::Tag::DW_TAG_arg_variable, funcDI, F->getName().str() + ".Ret", funcDI->getFile(),
  5155. funcDI->getLine(), RetDIType);
  5156. DIExpression *Expr = DIB.createExpression();
  5157. // TODO: how to get col?
  5158. DILocation *DL = DILocation::get(F->getContext(), funcDI->getLine(), 0, funcDI);
  5159. DIB.insertDeclare(retValAddr, RetVar, Expr, DL, Builder.GetInsertPoint());
  5160. }
  5161. #endif
  5162. for (BasicBlock &BB : F->getBasicBlockList()) {
  5163. if (ReturnInst *RI = dyn_cast<ReturnInst>(BB.getTerminator())) {
  5164. // Create store for return.
  5165. IRBuilder<> RetBuilder(RI);
  5166. if (!retAnnotation.HasMatrixAnnotation()) {
  5167. RetBuilder.CreateStore(RI->getReturnValue(), retValAddr);
  5168. } else {
  5169. bool isRowMajor = retAnnotation.GetMatrixAnnotation().Orientation ==
  5170. MatrixOrientation::RowMajor;
  5171. Value *RetVal = RI->getReturnValue();
  5172. if (!isRowMajor) {
  5173. // Matrix value is row major. ColMatStore require col major.
  5174. // Cast before store.
  5175. RetVal = HLModule::EmitHLOperationCall(
  5176. RetBuilder, HLOpcodeGroup::HLCast,
  5177. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  5178. RetVal->getType(), {RetVal}, M);
  5179. }
  5180. unsigned opcode = static_cast<unsigned>(
  5181. isRowMajor ? HLMatLoadStoreOpcode::RowMatStore
  5182. : HLMatLoadStoreOpcode::ColMatStore);
  5183. HLModule::EmitHLOperationCall(RetBuilder,
  5184. HLOpcodeGroup::HLMatLoadStore, opcode,
  5185. voidTy, {retValAddr, RetVal}, M);
  5186. }
  5187. }
  5188. }
  5189. // Create a fake store to keep retValAddr so it can be flattened.
  5190. if (retValAddr->user_empty()) {
  5191. Builder.CreateStore(UndefValue::get(retType), retValAddr);
  5192. }
  5193. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(retValAddr);
  5194. flattenArgument(F, retValAddr, bForParamTrue,
  5195. funcAnnotation->GetRetTypeAnnotation(), FlatRetList,
  5196. FlatRetAnnotationList, EntryBlock, DDI);
  5197. const int kRetArgNo = -1;
  5198. for (unsigned i = 0; i < FlatRetList.size(); i++) {
  5199. FlatParamOriArgNoList.insert(FlatParamOriArgNoList.begin(), kRetArgNo);
  5200. }
  5201. }
  5202. // Always change return type as parameter.
  5203. // By doing this, no need to check return when generate storeOutput.
  5204. if (FlatRetList.size() ||
  5205. // For empty struct return type.
  5206. !retType->isVoidTy()) {
  5207. // Return value is flattened.
  5208. // Change return value into out parameter.
  5209. retType = Type::getVoidTy(retType->getContext());
  5210. // Merge return data info param data.
  5211. FlatParamList.insert(FlatParamList.begin(), FlatRetList.begin(), FlatRetList.end());
  5212. FlatParamAnnotationList.insert(FlatParamAnnotationList.begin(),
  5213. FlatRetAnnotationList.begin(),
  5214. FlatRetAnnotationList.end());
  5215. }
  5216. std::vector<Type *> FinalTypeList;
  5217. for (Value * arg : FlatParamList) {
  5218. FinalTypeList.emplace_back(arg->getType());
  5219. }
  5220. unsigned extraParamSize = 0;
  5221. if (m_pHLModule->HasDxilFunctionProps(F)) {
  5222. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  5223. if (funcProps.shaderKind == ShaderModel::Kind::Vertex) {
  5224. auto &VS = funcProps.ShaderProps.VS;
  5225. Type *outFloatTy = Type::getFloatPtrTy(F->getContext());
  5226. // Add out float parameter for each clip plane.
  5227. unsigned i=0;
  5228. for (; i < DXIL::kNumClipPlanes; i++) {
  5229. if (!VS.clipPlanes[i])
  5230. break;
  5231. FinalTypeList.emplace_back(outFloatTy);
  5232. }
  5233. extraParamSize = i;
  5234. }
  5235. }
  5236. FunctionType *flatFuncTy = FunctionType::get(retType, FinalTypeList, false);
  5237. // Return if nothing changed.
  5238. if (flatFuncTy == F->getFunctionType()) {
  5239. // Copy semantic allocation.
  5240. if (!FlatParamAnnotationList.empty()) {
  5241. if (!FlatParamAnnotationList[0].GetSemanticString().empty()) {
  5242. for (unsigned i = 0; i < FlatParamAnnotationList.size(); i++) {
  5243. DxilParameterAnnotation &paramAnnotation = funcAnnotation->GetParameterAnnotation(i);
  5244. DxilParameterAnnotation &flatParamAnnotation = FlatParamAnnotationList[i];
  5245. paramAnnotation.SetSemanticIndexVec(flatParamAnnotation.GetSemanticIndexVec());
  5246. paramAnnotation.SetSemanticString(flatParamAnnotation.GetSemanticString());
  5247. }
  5248. }
  5249. }
  5250. if (!F->isDeclaration()) {
  5251. // Support store to input and load from output.
  5252. LegalizeDxilInputOutputs(F, funcAnnotation, DL, typeSys);
  5253. }
  5254. return;
  5255. }
  5256. std::string flatName = F->getName().str() + ".flat";
  5257. DXASSERT(nullptr == F->getParent()->getFunction(flatName),
  5258. "else overwriting existing function");
  5259. Function *flatF =
  5260. cast<Function>(F->getParent()->getOrInsertFunction(flatName, flatFuncTy));
  5261. funcMap[F] = flatF;
  5262. // Update function debug info.
  5263. if (DISubprogram *funcDI = getDISubprogram(F))
  5264. funcDI->replaceFunction(flatF);
  5265. // Create FunctionAnnotation for flatF.
  5266. DxilFunctionAnnotation *flatFuncAnnotation = m_pHLModule->AddFunctionAnnotation(flatF);
  5267. // Don't need to set Ret Info, flatF always return void now.
  5268. // Param Info
  5269. for (unsigned ArgNo = 0; ArgNo < FlatParamAnnotationList.size(); ++ArgNo) {
  5270. DxilParameterAnnotation &paramAnnotation = flatFuncAnnotation->GetParameterAnnotation(ArgNo);
  5271. paramAnnotation = FlatParamAnnotationList[ArgNo];
  5272. }
  5273. // Function Attr and Parameter Attr.
  5274. // Remove sret first.
  5275. if (F->hasStructRetAttr())
  5276. F->removeFnAttr(Attribute::StructRet);
  5277. for (Argument &arg : F->args()) {
  5278. if (arg.hasStructRetAttr()) {
  5279. Attribute::AttrKind SRet [] = {Attribute::StructRet};
  5280. AttributeSet SRetAS = AttributeSet::get(Ctx, arg.getArgNo() + 1, SRet);
  5281. arg.removeAttr(SRetAS);
  5282. }
  5283. }
  5284. AttributeSet AS = F->getAttributes();
  5285. AttrBuilder FnAttrs(AS.getFnAttributes(), AttributeSet::FunctionIndex);
  5286. AttributeSet flatAS;
  5287. flatAS = flatAS.addAttributes(
  5288. Ctx, AttributeSet::FunctionIndex,
  5289. AttributeSet::get(Ctx, AttributeSet::FunctionIndex, FnAttrs));
  5290. if (!F->isDeclaration()) {
  5291. // Only set Param attribute for function has a body.
  5292. for (unsigned ArgNo = 0; ArgNo < FlatParamAnnotationList.size(); ++ArgNo) {
  5293. unsigned oriArgNo = FlatParamOriArgNoList[ArgNo] + 1;
  5294. AttrBuilder paramAttr(AS, oriArgNo);
  5295. if (oriArgNo == AttributeSet::ReturnIndex)
  5296. paramAttr.addAttribute(Attribute::AttrKind::NoAlias);
  5297. flatAS = flatAS.addAttributes(
  5298. Ctx, ArgNo + 1, AttributeSet::get(Ctx, ArgNo + 1, paramAttr));
  5299. }
  5300. }
  5301. flatF->setAttributes(flatAS);
  5302. DXASSERT_LOCALVAR(extraParamSize, flatF->arg_size() == (extraParamSize + FlatParamAnnotationList.size()), "parameter count mismatch");
  5303. // ShaderProps.
  5304. if (m_pHLModule->HasDxilFunctionProps(F)) {
  5305. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  5306. std::unique_ptr<DxilFunctionProps> flatFuncProps = llvm::make_unique<DxilFunctionProps>();
  5307. flatFuncProps->shaderKind = funcProps.shaderKind;
  5308. flatFuncProps->ShaderProps = funcProps.ShaderProps;
  5309. m_pHLModule->AddDxilFunctionProps(flatF, flatFuncProps);
  5310. if (funcProps.shaderKind == ShaderModel::Kind::Vertex) {
  5311. auto &VS = funcProps.ShaderProps.VS;
  5312. unsigned clipArgIndex = FlatParamAnnotationList.size();
  5313. // Add out float SV_ClipDistance for each clip plane.
  5314. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  5315. if (!VS.clipPlanes[i])
  5316. break;
  5317. DxilParameterAnnotation &paramAnnotation =
  5318. flatFuncAnnotation->GetParameterAnnotation(clipArgIndex+i);
  5319. paramAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  5320. Twine semName = Twine("SV_ClipDistance") + Twine(i);
  5321. paramAnnotation.SetSemanticString(semName.str());
  5322. paramAnnotation.SetCompType(DXIL::ComponentType::F32);
  5323. paramAnnotation.AppendSemanticIndex(i);
  5324. }
  5325. }
  5326. }
  5327. if (!F->isDeclaration()) {
  5328. // Move function body into flatF.
  5329. moveFunctionBody(F, flatF);
  5330. // Replace old parameters with flatF Arguments.
  5331. auto argIter = flatF->arg_begin();
  5332. auto flatArgIter = FlatParamList.begin();
  5333. LLVMContext &Context = F->getContext();
  5334. // Parameter cast come from begining of entry block.
  5335. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(flatF));
  5336. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(flatF));
  5337. while (argIter != flatF->arg_end()) {
  5338. Argument *Arg = argIter++;
  5339. if (flatArgIter == FlatParamList.end()) {
  5340. DXASSERT(extraParamSize > 0, "parameter count mismatch");
  5341. break;
  5342. }
  5343. Value *flatArg = *(flatArgIter++);
  5344. if (castParamMap.count(flatArg)) {
  5345. replaceCastParameter(flatArg, castParamMap[flatArg].first, *flatF, Arg,
  5346. castParamMap[flatArg].second, Builder);
  5347. }
  5348. // Update arg debug info.
  5349. DbgDeclareInst *DDI = llvm::FindAllocaDbgDeclare(flatArg);
  5350. if (DDI) {
  5351. if (!flatArg->getType()->isPointerTy()) {
  5352. // Create alloca to hold the debug info.
  5353. Value *allocaArg = nullptr;
  5354. if (flatArg->hasOneUse() && isa<StoreInst>(*flatArg->user_begin())) {
  5355. StoreInst *SI = cast<StoreInst>(*flatArg->user_begin());
  5356. allocaArg = SI->getPointerOperand();
  5357. } else {
  5358. allocaArg = AllocaBuilder.CreateAlloca(flatArg->getType());
  5359. StoreInst *initArg = Builder.CreateStore(flatArg, allocaArg);
  5360. Value *ldArg = Builder.CreateLoad(allocaArg);
  5361. flatArg->replaceAllUsesWith(ldArg);
  5362. initArg->setOperand(0, flatArg);
  5363. }
  5364. Value *VMD = MetadataAsValue::get(Context, ValueAsMetadata::get(allocaArg));
  5365. DDI->setArgOperand(0, VMD);
  5366. } else {
  5367. Value *VMD = MetadataAsValue::get(Context, ValueAsMetadata::get(Arg));
  5368. DDI->setArgOperand(0, VMD);
  5369. }
  5370. }
  5371. flatArg->replaceAllUsesWith(Arg);
  5372. if (isa<Instruction>(flatArg))
  5373. DeadInsts.emplace_back(flatArg);
  5374. HLModule::MergeGepUse(Arg);
  5375. // Flatten store of array parameter.
  5376. if (Arg->getType()->isPointerTy()) {
  5377. Type *Ty = Arg->getType()->getPointerElementType();
  5378. if (Ty->isArrayTy())
  5379. SplitArrayCopy(
  5380. Arg, DL, typeSys,
  5381. &flatFuncAnnotation->GetParameterAnnotation(Arg->getArgNo()));
  5382. }
  5383. }
  5384. // Support store to input and load from output.
  5385. LegalizeDxilInputOutputs(flatF, flatFuncAnnotation, DL, typeSys);
  5386. }
  5387. }
  5388. void SROA_Parameter_HLSL::replaceCall(Function *F, Function *flatF) {
  5389. // Update entry function.
  5390. if (F == m_pHLModule->GetEntryFunction()) {
  5391. m_pHLModule->SetEntryFunction(flatF);
  5392. }
  5393. DXASSERT(F->user_empty(), "otherwise we flattened a library function.");
  5394. }
  5395. // Public interface to the SROA_Parameter_HLSL pass
  5396. ModulePass *llvm::createSROA_Parameter_HLSL() {
  5397. return new SROA_Parameter_HLSL();
  5398. }
  5399. //===----------------------------------------------------------------------===//
  5400. // Lower static global into Alloca.
  5401. //===----------------------------------------------------------------------===//
  5402. namespace {
  5403. class LowerStaticGlobalIntoAlloca : public ModulePass {
  5404. HLModule *m_pHLModule;
  5405. DebugInfoFinder m_DbgFinder;
  5406. public:
  5407. static char ID; // Pass identification, replacement for typeid
  5408. explicit LowerStaticGlobalIntoAlloca() : ModulePass(ID) {}
  5409. const char *getPassName() const override { return "Lower static global into Alloca"; }
  5410. bool runOnModule(Module &M) override {
  5411. m_pHLModule = &M.GetOrCreateHLModule();
  5412. m_DbgFinder.processModule(M);
  5413. // Lower static global into allocas.
  5414. std::vector<GlobalVariable *> staticGVs;
  5415. for (GlobalVariable &GV : M.globals()) {
  5416. // only for non-constant static globals
  5417. if (!dxilutil::IsStaticGlobal(&GV) || GV.isConstant())
  5418. continue;
  5419. Type *EltTy = GV.getType()->getElementType();
  5420. if (!EltTy->isAggregateType()) {
  5421. staticGVs.emplace_back(&GV);
  5422. } else {
  5423. // Lower static [array of] resources
  5424. if (dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(EltTy))) {
  5425. staticGVs.emplace_back(&GV);
  5426. }
  5427. }
  5428. }
  5429. bool bUpdated = false;
  5430. const DataLayout &DL = M.getDataLayout();
  5431. for (GlobalVariable *GV : staticGVs) {
  5432. bUpdated |= lowerStaticGlobalIntoAlloca(GV, DL);
  5433. }
  5434. return bUpdated;
  5435. }
  5436. private:
  5437. bool lowerStaticGlobalIntoAlloca(GlobalVariable *GV, const DataLayout &DL);
  5438. };
  5439. }
  5440. // Go through the base type chain of TyA and see if
  5441. // we eventually get to TyB
  5442. //
  5443. // Note: Not necessarily about inheritance. Could be
  5444. // typedef, const type, ref type, MEMBER type (TyA
  5445. // being a member of TyB).
  5446. //
  5447. static bool IsDerivedTypeOf(DIType *TyA, DIType *TyB) {
  5448. DITypeIdentifierMap EmptyMap;
  5449. while (TyA) {
  5450. if (DIDerivedType *Derived = dyn_cast<DIDerivedType>(TyA)) {
  5451. if (Derived->getBaseType() == TyB)
  5452. return true;
  5453. else
  5454. TyA = Derived->getBaseType().resolve(EmptyMap);
  5455. }
  5456. else {
  5457. break;
  5458. }
  5459. }
  5460. return false;
  5461. }
  5462. // See if 'DGV' a member type of some other variable, and return that variable
  5463. // and the offset and size DGV is into it.
  5464. //
  5465. // If DGV is not a member, just return nullptr.
  5466. //
  5467. static DIGlobalVariable *FindGlobalVariableFragment(const DebugInfoFinder &DbgFinder, DIGlobalVariable *DGV, unsigned *Out_OffsetInBits, unsigned *Out_SizeInBits) {
  5468. DITypeIdentifierMap EmptyMap;
  5469. StringRef FullName = DGV->getName();
  5470. size_t FirstDot = FullName.find_first_of('.');
  5471. if (FirstDot == StringRef::npos)
  5472. return nullptr;
  5473. StringRef BaseName = FullName.substr(0, FirstDot);
  5474. assert(BaseName.size());
  5475. DIType *Ty = DGV->getType().resolve(EmptyMap);
  5476. assert(isa<DIDerivedType>(Ty) && Ty->getTag() == dwarf::DW_TAG_member);
  5477. DIGlobalVariable *FinalResult = nullptr;
  5478. for (DIGlobalVariable *DGV_It : DbgFinder.global_variables()) {
  5479. if (DGV_It->getName() == BaseName &&
  5480. IsDerivedTypeOf(Ty, DGV_It->getType().resolve(EmptyMap)))
  5481. {
  5482. FinalResult = DGV_It;
  5483. break;
  5484. }
  5485. }
  5486. if (FinalResult) {
  5487. *Out_OffsetInBits = Ty->getOffsetInBits();
  5488. *Out_SizeInBits = Ty->getSizeInBits();
  5489. }
  5490. return FinalResult;
  5491. }
  5492. // Create a fake local variable for the GlobalVariable GV that has just been
  5493. // lowered to local Alloca.
  5494. //
  5495. static
  5496. void PatchDebugInfo(DebugInfoFinder &DbgFinder, Function *F, GlobalVariable *GV, AllocaInst *AI) {
  5497. if (!DbgFinder.compile_unit_count())
  5498. return;
  5499. // Find the subprogram for function
  5500. DISubprogram *Subprogram = nullptr;
  5501. for (DISubprogram *SP : DbgFinder.subprograms()) {
  5502. if (SP->getFunction() == F) {
  5503. Subprogram = SP;
  5504. break;
  5505. }
  5506. }
  5507. DIGlobalVariable *DGV = dxilutil::FindGlobalVariableDebugInfo(GV, DbgFinder);
  5508. if (!DGV)
  5509. return;
  5510. DITypeIdentifierMap EmptyMap;
  5511. DIBuilder DIB(*GV->getParent());
  5512. DIScope *Scope = Subprogram;
  5513. DebugLoc Loc = DebugLoc::get(0, 0, Scope);
  5514. // If the variable is a member of another variable, find the offset and size
  5515. bool IsFragment = false;
  5516. unsigned OffsetInBits = 0,
  5517. SizeInBits = 0;
  5518. if (DIGlobalVariable *UnsplitDGV = FindGlobalVariableFragment(DbgFinder, DGV, &OffsetInBits, &SizeInBits)) {
  5519. DGV = UnsplitDGV;
  5520. IsFragment = true;
  5521. }
  5522. std::string Name = "global.";
  5523. Name += DGV->getName();
  5524. // Using arg_variable instead of auto_variable because arg variables can use
  5525. // Subprogram as its scope, so we don't have to make one up for it.
  5526. llvm::dwarf::Tag Tag = llvm::dwarf::Tag::DW_TAG_arg_variable;
  5527. DIType *Ty = DGV->getType().resolve(EmptyMap);
  5528. DXASSERT(Ty->getTag() != dwarf::DW_TAG_member, "Member type is not allowed for variables.");
  5529. DILocalVariable *ConvertedLocalVar =
  5530. DIB.createLocalVariable(Tag, Scope,
  5531. Name, DGV->getFile(), DGV->getLine(), Ty);
  5532. DIExpression *Expr = nullptr;
  5533. if (IsFragment) {
  5534. Expr = DIB.createBitPieceExpression(OffsetInBits, SizeInBits);
  5535. }
  5536. else {
  5537. Expr = DIB.createExpression(ArrayRef<int64_t>());
  5538. }
  5539. DIB.insertDeclare(AI, ConvertedLocalVar, Expr, Loc, AI->getNextNode());
  5540. }
  5541. bool LowerStaticGlobalIntoAlloca::lowerStaticGlobalIntoAlloca(GlobalVariable *GV, const DataLayout &DL) {
  5542. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  5543. unsigned size = DL.getTypeAllocSize(GV->getType()->getElementType());
  5544. hlutil::PointerStatus PS(GV, size, /*bLdStOnly*/ false);
  5545. GV->removeDeadConstantUsers();
  5546. PS.analyze(typeSys, /*bStructElt*/ false);
  5547. bool NotStored = !PS.HasStored();
  5548. // Make sure GV only used in one function.
  5549. // Skip GV which don't have store.
  5550. if (PS.HasMultipleAccessingFunctions || NotStored)
  5551. return false;
  5552. Function *F = const_cast<Function*>(PS.AccessingFunction);
  5553. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  5554. AllocaInst *AI = AllocaBuilder.CreateAlloca(GV->getType()->getElementType());
  5555. IRBuilder<> Builder(dxilutil::FirstNonAllocaInsertionPt(F));
  5556. // Store initializer is exist.
  5557. if (GV->hasInitializer() && !isa<UndefValue>(GV->getInitializer())) {
  5558. Builder.CreateStore(GV->getInitializer(), GV);
  5559. }
  5560. ReplaceConstantWithInst(GV, AI, Builder);
  5561. PatchDebugInfo(m_DbgFinder, F, GV, AI);
  5562. GV->eraseFromParent();
  5563. return true;
  5564. }
  5565. char LowerStaticGlobalIntoAlloca::ID = 0;
  5566. INITIALIZE_PASS(LowerStaticGlobalIntoAlloca, "static-global-to-alloca",
  5567. "Lower static global into Alloca", false,
  5568. false)
  5569. // Public interface to the LowerStaticGlobalIntoAlloca pass
  5570. ModulePass *llvm::createLowerStaticGlobalIntoAlloca() {
  5571. return new LowerStaticGlobalIntoAlloca();
  5572. }