ScalarReplAggregatesHLSL.cpp 259 KB

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