CGHLSLMS.cpp 272 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265
  1. //===----- CGHLSLMS.cpp - Interface to HLSL Runtime ----------------===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // CGHLSLMS.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This provides a class for HLSL code generation. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "CGHLSLRuntime.h"
  13. #include "CodeGenFunction.h"
  14. #include "CodeGenModule.h"
  15. #include "CGRecordLayout.h"
  16. #include "dxc/HlslIntrinsicOp.h"
  17. #include "dxc/HLSL/HLMatrixType.h"
  18. #include "dxc/HLSL/HLModule.h"
  19. #include "dxc/DXIL/DxilUtil.h"
  20. #include "dxc/HLSL/HLOperations.h"
  21. #include "dxc/DXIL/DxilOperations.h"
  22. #include "dxc/DXIL/DxilTypeSystem.h"
  23. #include "clang/AST/DeclTemplate.h"
  24. #include "clang/AST/HlslTypes.h"
  25. #include "clang/Frontend/CodeGenOptions.h"
  26. #include "clang/Lex/HLSLMacroExpander.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/StringSwitch.h"
  29. #include "llvm/ADT/SmallPtrSet.h"
  30. #include "llvm/ADT/StringSet.h"
  31. #include "llvm/IR/Constants.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/GetElementPtrTypeIterator.h"
  34. #include "llvm/Transforms/Utils/Cloning.h"
  35. #include "llvm/IR/InstIterator.h"
  36. #include <memory>
  37. #include <unordered_map>
  38. #include <unordered_set>
  39. #include <set>
  40. #include "dxc/DxilRootSignature/DxilRootSignature.h"
  41. #include "dxc/DXIL/DxilCBuffer.h"
  42. #include "clang/Parse/ParseHLSL.h" // root sig would be in Parser if part of lang
  43. #include "dxc/Support/WinIncludes.h" // stream support
  44. #include "dxc/dxcapi.h" // stream support
  45. #include "dxc/HLSL/HLSLExtensionsCodegenHelper.h"
  46. #include "dxc/HLSL/DxilGenerationPass.h" // support pause/resume passes
  47. #include "dxc/HLSL/DxilExportMap.h"
  48. using namespace clang;
  49. using namespace CodeGen;
  50. using namespace hlsl;
  51. using namespace llvm;
  52. using std::unique_ptr;
  53. static const bool KeepUndefinedTrue = true; // Keep interpolation mode undefined if not set explicitly.
  54. namespace {
  55. /// Use this class to represent HLSL cbuffer in high-level DXIL.
  56. class HLCBuffer : public DxilCBuffer {
  57. public:
  58. HLCBuffer() = default;
  59. virtual ~HLCBuffer() = default;
  60. void AddConst(std::unique_ptr<DxilResourceBase> &pItem);
  61. std::vector<std::unique_ptr<DxilResourceBase>> &GetConstants();
  62. private:
  63. std::vector<std::unique_ptr<DxilResourceBase>> constants; // constants inside const buffer
  64. };
  65. //------------------------------------------------------------------------------
  66. //
  67. // HLCBuffer methods.
  68. //
  69. void HLCBuffer::AddConst(std::unique_ptr<DxilResourceBase> &pItem) {
  70. pItem->SetID(constants.size());
  71. constants.push_back(std::move(pItem));
  72. }
  73. std::vector<std::unique_ptr<DxilResourceBase>> &HLCBuffer::GetConstants() {
  74. return constants;
  75. }
  76. class CGMSHLSLRuntime : public CGHLSLRuntime {
  77. private:
  78. /// Convenience reference to LLVM Context
  79. llvm::LLVMContext &Context;
  80. /// Convenience reference to the current module
  81. llvm::Module &TheModule;
  82. HLModule *m_pHLModule;
  83. llvm::Type *CBufferType;
  84. uint32_t globalCBIndex;
  85. // TODO: make sure how minprec works
  86. llvm::DataLayout dataLayout;
  87. // decl map to constant id for program
  88. llvm::DenseMap<HLSLBufferDecl *, uint32_t> constantBufMap;
  89. // Map for resource type to resource metadata value.
  90. std::unordered_map<llvm::Type *, MDNode*> resMetadataMap;
  91. bool m_bDebugInfo;
  92. bool m_bIsLib;
  93. // For library, m_ExportMap maps from internal name to zero or more renames
  94. dxilutil::ExportMap m_ExportMap;
  95. HLCBuffer &GetGlobalCBuffer() {
  96. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(globalCBIndex)));
  97. }
  98. void AddConstant(VarDecl *constDecl, HLCBuffer &CB);
  99. uint32_t AddSampler(VarDecl *samplerDecl);
  100. uint32_t AddUAVSRV(VarDecl *decl, hlsl::DxilResourceBase::Class resClass);
  101. bool SetUAVSRV(SourceLocation loc, hlsl::DxilResourceBase::Class resClass,
  102. DxilResource *hlslRes, const RecordDecl *RD);
  103. uint32_t AddCBuffer(HLSLBufferDecl *D);
  104. hlsl::DxilResourceBase::Class TypeToClass(clang::QualType Ty);
  105. void CreateSubobject(DXIL::SubobjectKind kind, const StringRef name, clang::Expr **args,
  106. unsigned int argCount, DXIL::HitGroupType hgType = (DXIL::HitGroupType)(-1));
  107. bool GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty = false);
  108. bool GetAsConstantUInt32(clang::Expr *expr, uint32_t *value);
  109. std::vector<StringRef> ParseSubobjectExportsAssociations(StringRef exports);
  110. // Save the entryFunc so don't need to find it with original name.
  111. struct EntryFunctionInfo {
  112. clang::SourceLocation SL = clang::SourceLocation();
  113. llvm::Function *Func = nullptr;
  114. };
  115. EntryFunctionInfo Entry;
  116. // Map to save patch constant functions
  117. struct PatchConstantInfo {
  118. clang::SourceLocation SL = clang::SourceLocation();
  119. llvm::Function *Func = nullptr;
  120. std::uint32_t NumOverloads = 0;
  121. };
  122. StringMap<PatchConstantInfo> patchConstantFunctionMap;
  123. std::unordered_map<Function *, std::unique_ptr<DxilFunctionProps>>
  124. patchConstantFunctionPropsMap;
  125. bool IsPatchConstantFunction(const Function *F);
  126. std::unordered_map<Function *, const clang::HLSLPatchConstantFuncAttr *>
  127. HSEntryPatchConstantFuncAttr;
  128. // Map to save entry functions.
  129. StringMap<EntryFunctionInfo> entryFunctionMap;
  130. // Map to save static global init exp.
  131. std::unordered_map<Expr *, GlobalVariable *> staticConstGlobalInitMap;
  132. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  133. staticConstGlobalInitListMap;
  134. std::unordered_map<GlobalVariable *, Function *> staticConstGlobalCtorMap;
  135. // List for functions with clip plane.
  136. std::vector<Function *> clipPlaneFuncList;
  137. std::unordered_map<Value *, DebugLoc> debugInfoMap;
  138. DxilRootSignatureVersion rootSigVer;
  139. Value *EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr, QualType Ty);
  140. void EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val, Value *DestPtr,
  141. QualType Ty);
  142. // Flatten the val into scalar val and push into elts and eltTys.
  143. void FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  144. SmallVector<QualType, 4> &eltTys, QualType Ty,
  145. Value *val);
  146. // Push every value on InitListExpr into EltValList and EltTyList.
  147. void ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  148. SmallVector<Value *, 4> &EltValList,
  149. SmallVector<QualType, 4> &EltTyList);
  150. void FlattenAggregatePtrToGepList(CodeGenFunction &CGF, Value *Ptr,
  151. SmallVector<Value *, 4> &idxList,
  152. clang::QualType Type, llvm::Type *Ty,
  153. SmallVector<Value *, 4> &GepList,
  154. SmallVector<QualType, 4> &EltTyList);
  155. void LoadElements(CodeGenFunction &CGF,
  156. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  157. SmallVector<Value *, 4> &Vals);
  158. void ConvertAndStoreElements(CodeGenFunction &CGF,
  159. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  160. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys);
  161. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  162. llvm::Value *DestPtr,
  163. SmallVector<Value *, 4> &idxList,
  164. clang::QualType SrcType,
  165. clang::QualType DestType,
  166. llvm::Type *Ty);
  167. void EmitHLSLSplat(CodeGenFunction &CGF, Value *SrcVal,
  168. llvm::Value *DestPtr,
  169. SmallVector<Value *, 4> &idxList,
  170. QualType Type, QualType SrcType,
  171. llvm::Type *Ty);
  172. void EmitHLSLRootSignature(CodeGenFunction &CGF, HLSLRootSignatureAttr *RSA,
  173. llvm::Function *Fn) override;
  174. void CheckParameterAnnotation(SourceLocation SLoc,
  175. const DxilParameterAnnotation &paramInfo,
  176. bool isPatchConstantFunction);
  177. void CheckParameterAnnotation(SourceLocation SLoc,
  178. DxilParamInputQual paramQual,
  179. llvm::StringRef semFullName,
  180. bool isPatchConstantFunction);
  181. void RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo,
  182. bool isPatchConstantFunction);
  183. void SetEntryFunction();
  184. SourceLocation SetSemantic(const NamedDecl *decl,
  185. DxilParameterAnnotation &paramInfo);
  186. hlsl::InterpolationMode GetInterpMode(const Decl *decl, CompType compType,
  187. bool bKeepUndefined);
  188. hlsl::CompType GetCompType(const BuiltinType *BT);
  189. // save intrinsic opcode
  190. std::vector<std::pair<Function *, unsigned>> m_IntrinsicMap;
  191. void AddHLSLIntrinsicOpcodeToFunction(Function *, unsigned opcode);
  192. // Type annotation related.
  193. unsigned ConstructStructAnnotation(DxilStructAnnotation *annotation,
  194. const RecordDecl *RD,
  195. DxilTypeSystem &dxilTypeSys);
  196. unsigned AddTypeAnnotation(QualType Ty, DxilTypeSystem &dxilTypeSys,
  197. unsigned &arrayEltSize);
  198. MDNode *GetOrAddResTypeMD(QualType resTy);
  199. void ConstructFieldAttributedAnnotation(DxilFieldAnnotation &fieldAnnotation,
  200. QualType fieldTy,
  201. bool bDefaultRowMajor);
  202. std::unordered_map<Constant*, DxilFieldAnnotation> m_ConstVarAnnotationMap;
  203. public:
  204. CGMSHLSLRuntime(CodeGenModule &CGM);
  205. /// Add resouce to the program
  206. void addResource(Decl *D) override;
  207. void SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc);
  208. void SetPatchConstantFunctionWithAttr(
  209. const EntryFunctionInfo &EntryFunc,
  210. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr);
  211. void addSubobject(Decl *D) override;
  212. void FinishCodeGen() override;
  213. bool IsTrivalInitListExpr(CodeGenFunction &CGF, InitListExpr *E) override;
  214. Value *EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E, Value *DestPtr) override;
  215. Constant *EmitHLSLConstInitListExpr(CodeGenModule &CGM, InitListExpr *E) override;
  216. RValue EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF, const FunctionDecl *FD,
  217. const CallExpr *E,
  218. ReturnValueSlot ReturnValue) override;
  219. void EmitHLSLOutParamConversionInit(
  220. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  221. llvm::SmallVector<LValue, 8> &castArgList,
  222. llvm::SmallVector<const Stmt *, 8> &argList,
  223. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap)
  224. override;
  225. void EmitHLSLOutParamConversionCopyBack(
  226. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) override;
  227. Value *EmitHLSLMatrixOperationCall(CodeGenFunction &CGF, const clang::Expr *E,
  228. llvm::Type *RetType,
  229. ArrayRef<Value *> paramList) override;
  230. void EmitHLSLDiscard(CodeGenFunction &CGF) override;
  231. Value *EmitHLSLMatrixSubscript(CodeGenFunction &CGF, llvm::Type *RetType,
  232. Value *Ptr, Value *Idx, QualType Ty) override;
  233. Value *EmitHLSLMatrixElement(CodeGenFunction &CGF, llvm::Type *RetType,
  234. ArrayRef<Value *> paramList,
  235. QualType Ty) override;
  236. Value *EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  237. QualType Ty) override;
  238. void EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val, Value *DestPtr,
  239. QualType Ty) override;
  240. void EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  241. llvm::Value *DestPtr,
  242. clang::QualType Ty) override;
  243. void EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *Val,
  244. llvm::Value *DestPtr,
  245. clang::QualType Ty) override;
  246. void EmitHLSLFlatConversion(CodeGenFunction &CGF, Value *Val,
  247. Value *DestPtr,
  248. QualType Ty,
  249. QualType SrcTy) override;
  250. Value *EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src, QualType SrcType,
  251. QualType DstType) override;
  252. void EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  253. clang::QualType SrcTy,
  254. llvm::Value *DestPtr,
  255. clang::QualType DestTy) override;
  256. void AddHLSLFunctionInfo(llvm::Function *, const FunctionDecl *FD) override;
  257. void EmitHLSLFunctionProlog(llvm::Function *, const FunctionDecl *FD) override;
  258. void AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  259. llvm::TerminatorInst *TI,
  260. ArrayRef<const Attr *> Attrs) override;
  261. void FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) override;
  262. /// Get or add constant to the program
  263. HLCBuffer &GetOrCreateCBuffer(HLSLBufferDecl *D);
  264. };
  265. }
  266. void clang::CompileRootSignature(
  267. StringRef rootSigStr, DiagnosticsEngine &Diags, SourceLocation SLoc,
  268. hlsl::DxilRootSignatureVersion rootSigVer,
  269. hlsl::DxilRootSignatureCompilationFlags flags,
  270. hlsl::RootSignatureHandle *pRootSigHandle) {
  271. std::string OSStr;
  272. llvm::raw_string_ostream OS(OSStr);
  273. hlsl::DxilVersionedRootSignatureDesc *D = nullptr;
  274. if (ParseHLSLRootSignature(rootSigStr.data(), rootSigStr.size(), rootSigVer,
  275. flags, &D, SLoc, Diags)) {
  276. CComPtr<IDxcBlob> pSignature;
  277. CComPtr<IDxcBlobEncoding> pErrors;
  278. hlsl::SerializeRootSignature(D, &pSignature, &pErrors, false);
  279. if (pSignature == nullptr) {
  280. assert(pErrors != nullptr && "else serialize failed with no msg");
  281. ReportHLSLRootSigError(Diags, SLoc, (char *)pErrors->GetBufferPointer(),
  282. pErrors->GetBufferSize());
  283. hlsl::DeleteRootSignature(D);
  284. } else {
  285. pRootSigHandle->Assign(D, pSignature);
  286. }
  287. }
  288. }
  289. //------------------------------------------------------------------------------
  290. //
  291. // CGMSHLSLRuntime methods.
  292. //
  293. CGMSHLSLRuntime::CGMSHLSLRuntime(CodeGenModule &CGM)
  294. : CGHLSLRuntime(CGM), Context(CGM.getLLVMContext()),
  295. TheModule(CGM.getModule()),
  296. CBufferType(
  297. llvm::StructType::create(TheModule.getContext(), "ConstantBuffer")),
  298. dataLayout(CGM.getLangOpts().UseMinPrecision
  299. ? hlsl::DXIL::kLegacyLayoutString
  300. : hlsl::DXIL::kNewLayoutString), Entry() {
  301. const hlsl::ShaderModel *SM =
  302. hlsl::ShaderModel::GetByName(CGM.getCodeGenOpts().HLSLProfile.c_str());
  303. // Only accept valid, 6.0 shader model.
  304. if (!SM->IsValid() || SM->GetMajor() != 6) {
  305. DiagnosticsEngine &Diags = CGM.getDiags();
  306. unsigned DiagID =
  307. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid profile %0");
  308. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLProfile;
  309. return;
  310. }
  311. m_bIsLib = SM->IsLib();
  312. // TODO: add AllResourceBound.
  313. if (CGM.getCodeGenOpts().HLSLAvoidControlFlow && !CGM.getCodeGenOpts().HLSLAllResourcesBound) {
  314. if (SM->IsSM51Plus()) {
  315. DiagnosticsEngine &Diags = CGM.getDiags();
  316. unsigned DiagID =
  317. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  318. "Gfa option cannot be used in SM_5_1+ unless "
  319. "all_resources_bound flag is specified");
  320. Diags.Report(DiagID);
  321. }
  322. }
  323. // Create HLModule.
  324. const bool skipInit = true;
  325. m_pHLModule = &TheModule.GetOrCreateHLModule(skipInit);
  326. // Set Option.
  327. HLOptions opts;
  328. opts.bIEEEStrict = CGM.getCodeGenOpts().UnsafeFPMath;
  329. opts.bDefaultRowMajor = CGM.getCodeGenOpts().HLSLDefaultRowMajor;
  330. opts.bDisableOptimizations = CGM.getCodeGenOpts().DisableLLVMOpts;
  331. opts.bLegacyCBufferLoad = !CGM.getCodeGenOpts().HLSLNotUseLegacyCBufLoad;
  332. opts.bAllResourcesBound = CGM.getCodeGenOpts().HLSLAllResourcesBound;
  333. opts.PackingStrategy = CGM.getCodeGenOpts().HLSLSignaturePackingStrategy;
  334. opts.bLegacyResourceReservation = CGM.getCodeGenOpts().HLSLLegacyResourceReservation;
  335. opts.bUseMinPrecision = CGM.getLangOpts().UseMinPrecision;
  336. opts.bDX9CompatMode = CGM.getLangOpts().EnableDX9CompatMode;
  337. opts.bFXCCompatMode = CGM.getLangOpts().EnableFXCCompatMode;
  338. m_pHLModule->SetHLOptions(opts);
  339. m_pHLModule->GetOP()->SetMinPrecision(opts.bUseMinPrecision);
  340. m_pHLModule->GetTypeSystem().SetMinPrecision(opts.bUseMinPrecision);
  341. m_pHLModule->SetAutoBindingSpace(CGM.getCodeGenOpts().HLSLDefaultSpace);
  342. m_pHLModule->SetValidatorVersion(CGM.getCodeGenOpts().HLSLValidatorMajorVer, CGM.getCodeGenOpts().HLSLValidatorMinorVer);
  343. m_bDebugInfo = CGM.getCodeGenOpts().getDebugInfo() == CodeGenOptions::FullDebugInfo;
  344. // set profile
  345. m_pHLModule->SetShaderModel(SM);
  346. // set entry name
  347. if (!SM->IsLib())
  348. m_pHLModule->SetEntryFunctionName(CGM.getCodeGenOpts().HLSLEntryFunction);
  349. // set root signature version.
  350. if (CGM.getLangOpts().RootSigMinor == 0) {
  351. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_0;
  352. }
  353. else {
  354. DXASSERT(CGM.getLangOpts().RootSigMinor == 1,
  355. "else CGMSHLSLRuntime Constructor needs to be updated");
  356. rootSigVer = hlsl::DxilRootSignatureVersion::Version_1_1;
  357. }
  358. DXASSERT(CGM.getLangOpts().RootSigMajor == 1,
  359. "else CGMSHLSLRuntime Constructor needs to be updated");
  360. // add globalCB
  361. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  362. std::string globalCBName = "$Globals";
  363. CB->SetGlobalSymbol(nullptr);
  364. CB->SetGlobalName(globalCBName);
  365. globalCBIndex = m_pHLModule->GetCBuffers().size();
  366. CB->SetID(globalCBIndex);
  367. CB->SetRangeSize(1);
  368. CB->SetLowerBound(UINT_MAX);
  369. DXVERIFY_NOMSG(globalCBIndex == m_pHLModule->AddCBuffer(std::move(CB)));
  370. // set Float Denorm Mode
  371. m_pHLModule->SetFloat32DenormMode(CGM.getCodeGenOpts().HLSLFloat32DenormMode);
  372. // set DefaultLinkage
  373. m_pHLModule->SetDefaultLinkage(CGM.getCodeGenOpts().DefaultLinkage);
  374. // Fill in m_ExportMap, which maps from internal name to zero or more renames
  375. m_ExportMap.clear();
  376. std::string errors;
  377. llvm::raw_string_ostream os(errors);
  378. if (!m_ExportMap.ParseExports(CGM.getCodeGenOpts().HLSLLibraryExports, os)) {
  379. DiagnosticsEngine &Diags = CGM.getDiags();
  380. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "Error parsing -exports options: %0");
  381. Diags.Report(DiagID) << os.str();
  382. }
  383. }
  384. void CGMSHLSLRuntime::AddHLSLIntrinsicOpcodeToFunction(Function *F,
  385. unsigned opcode) {
  386. m_IntrinsicMap.emplace_back(F,opcode);
  387. }
  388. void CGMSHLSLRuntime::CheckParameterAnnotation(
  389. SourceLocation SLoc, const DxilParameterAnnotation &paramInfo,
  390. bool isPatchConstantFunction) {
  391. if (!paramInfo.HasSemanticString()) {
  392. return;
  393. }
  394. llvm::StringRef semFullName = paramInfo.GetSemanticStringRef();
  395. DxilParamInputQual paramQual = paramInfo.GetParamInputQual();
  396. if (paramQual == DxilParamInputQual::Inout) {
  397. CheckParameterAnnotation(SLoc, DxilParamInputQual::In, semFullName, isPatchConstantFunction);
  398. CheckParameterAnnotation(SLoc, DxilParamInputQual::Out, semFullName, isPatchConstantFunction);
  399. return;
  400. }
  401. CheckParameterAnnotation(SLoc, paramQual, semFullName, isPatchConstantFunction);
  402. }
  403. void CGMSHLSLRuntime::CheckParameterAnnotation(
  404. SourceLocation SLoc, DxilParamInputQual paramQual, llvm::StringRef semFullName,
  405. bool isPatchConstantFunction) {
  406. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  407. DXIL::SigPointKind sigPoint = SigPointFromInputQual(
  408. paramQual, SM->GetKind(), isPatchConstantFunction);
  409. llvm::StringRef semName;
  410. unsigned semIndex;
  411. Semantic::DecomposeNameAndIndex(semFullName, &semName, &semIndex);
  412. const Semantic *pSemantic =
  413. Semantic::GetByName(semName, sigPoint, SM->GetMajor(), SM->GetMinor());
  414. if (pSemantic->IsInvalid()) {
  415. DiagnosticsEngine &Diags = CGM.getDiags();
  416. unsigned DiagID =
  417. Diags.getCustomDiagID(DiagnosticsEngine::Error, "invalid semantic '%0' for %1 %2.%3");
  418. Diags.Report(SLoc, DiagID) << semName << SM->GetKindName() << SM->GetMajor() << SM->GetMinor();
  419. }
  420. }
  421. SourceLocation
  422. CGMSHLSLRuntime::SetSemantic(const NamedDecl *decl,
  423. DxilParameterAnnotation &paramInfo) {
  424. for (const hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  425. if (it->getKind() == hlsl::UnusualAnnotation::UA_SemanticDecl) {
  426. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  427. paramInfo.SetSemanticString(sd->SemanticName);
  428. return it->Loc;
  429. }
  430. }
  431. return SourceLocation();
  432. }
  433. static DXIL::TessellatorDomain StringToDomain(StringRef domain) {
  434. if (domain == "isoline")
  435. return DXIL::TessellatorDomain::IsoLine;
  436. if (domain == "tri")
  437. return DXIL::TessellatorDomain::Tri;
  438. if (domain == "quad")
  439. return DXIL::TessellatorDomain::Quad;
  440. return DXIL::TessellatorDomain::Undefined;
  441. }
  442. static DXIL::TessellatorPartitioning StringToPartitioning(StringRef partition) {
  443. if (partition == "integer")
  444. return DXIL::TessellatorPartitioning::Integer;
  445. if (partition == "pow2")
  446. return DXIL::TessellatorPartitioning::Pow2;
  447. if (partition == "fractional_even")
  448. return DXIL::TessellatorPartitioning::FractionalEven;
  449. if (partition == "fractional_odd")
  450. return DXIL::TessellatorPartitioning::FractionalOdd;
  451. return DXIL::TessellatorPartitioning::Undefined;
  452. }
  453. static DXIL::TessellatorOutputPrimitive
  454. StringToTessOutputPrimitive(StringRef primitive) {
  455. if (primitive == "point")
  456. return DXIL::TessellatorOutputPrimitive::Point;
  457. if (primitive == "line")
  458. return DXIL::TessellatorOutputPrimitive::Line;
  459. if (primitive == "triangle_cw")
  460. return DXIL::TessellatorOutputPrimitive::TriangleCW;
  461. if (primitive == "triangle_ccw")
  462. return DXIL::TessellatorOutputPrimitive::TriangleCCW;
  463. return DXIL::TessellatorOutputPrimitive::Undefined;
  464. }
  465. static unsigned RoundToAlign(unsigned num, unsigned mod) {
  466. // round num to next highest mod
  467. if (mod != 0)
  468. return mod * ((num + mod - 1) / mod);
  469. return num;
  470. }
  471. // Align cbuffer offset in legacy mode (16 bytes per row).
  472. static unsigned AlignBufferOffsetInLegacy(unsigned offset, unsigned size,
  473. unsigned scalarSizeInBytes,
  474. bool bNeedNewRow) {
  475. if (unsigned remainder = (offset & 0xf)) {
  476. // Start from new row
  477. if (remainder + size > 16 || bNeedNewRow) {
  478. return offset + 16 - remainder;
  479. }
  480. // If not, naturally align data
  481. return RoundToAlign(offset, scalarSizeInBytes);
  482. }
  483. return offset;
  484. }
  485. static unsigned AlignBaseOffset(unsigned baseOffset, unsigned size,
  486. QualType Ty, bool bDefaultRowMajor) {
  487. bool needNewAlign = Ty->isArrayType();
  488. if (IsHLSLMatType(Ty)) {
  489. bool bRowMajor = false;
  490. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  491. bRowMajor = bDefaultRowMajor;
  492. unsigned row, col;
  493. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  494. needNewAlign |= !bRowMajor && col > 1;
  495. needNewAlign |= bRowMajor && row > 1;
  496. }
  497. unsigned scalarSizeInBytes = 4;
  498. const clang::BuiltinType *BT = Ty->getAs<clang::BuiltinType>();
  499. if (hlsl::IsHLSLVecMatType(Ty)) {
  500. BT = hlsl::GetElementTypeOrType(Ty)->getAs<clang::BuiltinType>();
  501. }
  502. if (BT) {
  503. if (BT->getKind() == clang::BuiltinType::Kind::Double ||
  504. BT->getKind() == clang::BuiltinType::Kind::LongLong)
  505. scalarSizeInBytes = 8;
  506. else if (BT->getKind() == clang::BuiltinType::Kind::Half ||
  507. BT->getKind() == clang::BuiltinType::Kind::Short ||
  508. BT->getKind() == clang::BuiltinType::Kind::UShort)
  509. scalarSizeInBytes = 2;
  510. }
  511. return AlignBufferOffsetInLegacy(baseOffset, size, scalarSizeInBytes, needNewAlign);
  512. }
  513. static unsigned AlignBaseOffset(QualType Ty, unsigned baseOffset,
  514. bool bDefaultRowMajor,
  515. CodeGen::CodeGenModule &CGM,
  516. llvm::DataLayout &layout) {
  517. QualType paramTy = Ty.getCanonicalType();
  518. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  519. paramTy = RefType->getPointeeType();
  520. // Get size.
  521. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  522. unsigned size = layout.getTypeAllocSize(Type);
  523. return AlignBaseOffset(baseOffset, size, paramTy, bDefaultRowMajor);
  524. }
  525. static unsigned GetMatrixSizeInCB(QualType Ty, bool defaultRowMajor,
  526. bool b64Bit) {
  527. bool bRowMajor;
  528. if (!hlsl::HasHLSLMatOrientation(Ty, &bRowMajor))
  529. bRowMajor = defaultRowMajor;
  530. unsigned row, col;
  531. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  532. unsigned EltSize = b64Bit ? 8 : 4;
  533. // Align to 4 * 4bytes.
  534. unsigned alignment = 4 * 4;
  535. if (bRowMajor) {
  536. unsigned rowSize = EltSize * col;
  537. // 3x64bit or 4x64bit align to 32 bytes.
  538. if (rowSize > alignment)
  539. alignment <<= 1;
  540. return alignment * (row - 1) + col * EltSize;
  541. } else {
  542. unsigned rowSize = EltSize * row;
  543. // 3x64bit or 4x64bit align to 32 bytes.
  544. if (rowSize > alignment)
  545. alignment <<= 1;
  546. return alignment * (col - 1) + row * EltSize;
  547. }
  548. }
  549. static CompType::Kind BuiltinTyToCompTy(const BuiltinType *BTy, bool bSNorm,
  550. bool bUNorm) {
  551. CompType::Kind kind = CompType::Kind::Invalid;
  552. switch (BTy->getKind()) {
  553. case BuiltinType::UInt:
  554. kind = CompType::Kind::U32;
  555. break;
  556. case BuiltinType::Min16UInt: // HLSL Change
  557. case BuiltinType::UShort:
  558. kind = CompType::Kind::U16;
  559. break;
  560. case BuiltinType::ULongLong:
  561. kind = CompType::Kind::U64;
  562. break;
  563. case BuiltinType::Int:
  564. kind = CompType::Kind::I32;
  565. break;
  566. // HLSL Changes begin
  567. case BuiltinType::Min12Int:
  568. case BuiltinType::Min16Int:
  569. // HLSL Changes end
  570. case BuiltinType::Short:
  571. kind = CompType::Kind::I16;
  572. break;
  573. case BuiltinType::LongLong:
  574. kind = CompType::Kind::I64;
  575. break;
  576. // HLSL Changes begin
  577. case BuiltinType::Min10Float:
  578. case BuiltinType::Min16Float:
  579. // HLSL Changes end
  580. case BuiltinType::Half:
  581. if (bSNorm)
  582. kind = CompType::Kind::SNormF16;
  583. else if (bUNorm)
  584. kind = CompType::Kind::UNormF16;
  585. else
  586. kind = CompType::Kind::F16;
  587. break;
  588. case BuiltinType::HalfFloat: // HLSL Change
  589. case BuiltinType::Float:
  590. if (bSNorm)
  591. kind = CompType::Kind::SNormF32;
  592. else if (bUNorm)
  593. kind = CompType::Kind::UNormF32;
  594. else
  595. kind = CompType::Kind::F32;
  596. break;
  597. case BuiltinType::Double:
  598. if (bSNorm)
  599. kind = CompType::Kind::SNormF64;
  600. else if (bUNorm)
  601. kind = CompType::Kind::UNormF64;
  602. else
  603. kind = CompType::Kind::F64;
  604. break;
  605. case BuiltinType::Bool:
  606. kind = CompType::Kind::I1;
  607. break;
  608. default:
  609. // Other types not used by HLSL.
  610. break;
  611. }
  612. return kind;
  613. }
  614. static DxilSampler::SamplerKind KeywordToSamplerKind(llvm::StringRef keyword) {
  615. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  616. // compare)
  617. return llvm::StringSwitch<DxilSampler::SamplerKind>(keyword)
  618. .Case("SamplerState", DxilSampler::SamplerKind::Default)
  619. .Case("SamplerComparisonState", DxilSampler::SamplerKind::Comparison)
  620. .Default(DxilSampler::SamplerKind::Invalid);
  621. }
  622. MDNode *CGMSHLSLRuntime::GetOrAddResTypeMD(QualType resTy) {
  623. const RecordType *RT = resTy->getAs<RecordType>();
  624. if (!RT)
  625. return nullptr;
  626. RecordDecl *RD = RT->getDecl();
  627. SourceLocation loc = RD->getLocation();
  628. hlsl::DxilResourceBase::Class resClass = TypeToClass(resTy);
  629. llvm::Type *Ty = CGM.getTypes().ConvertType(resTy);
  630. auto it = resMetadataMap.find(Ty);
  631. if (it != resMetadataMap.end())
  632. return it->second;
  633. // Save resource type metadata.
  634. switch (resClass) {
  635. case DXIL::ResourceClass::UAV: {
  636. DxilResource UAV;
  637. // TODO: save globalcoherent to variable in EmitHLSLBuiltinCallExpr.
  638. SetUAVSRV(loc, resClass, &UAV, RD);
  639. // Set global symbol to save type.
  640. UAV.SetGlobalSymbol(UndefValue::get(Ty));
  641. MDNode *MD = m_pHLModule->DxilUAVToMDNode(UAV);
  642. resMetadataMap[Ty] = MD;
  643. return MD;
  644. } break;
  645. case DXIL::ResourceClass::SRV: {
  646. DxilResource SRV;
  647. SetUAVSRV(loc, resClass, &SRV, RD);
  648. // Set global symbol to save type.
  649. SRV.SetGlobalSymbol(UndefValue::get(Ty));
  650. MDNode *MD = m_pHLModule->DxilSRVToMDNode(SRV);
  651. resMetadataMap[Ty] = MD;
  652. return MD;
  653. } break;
  654. case DXIL::ResourceClass::Sampler: {
  655. DxilSampler S;
  656. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RD->getName());
  657. S.SetSamplerKind(kind);
  658. // Set global symbol to save type.
  659. S.SetGlobalSymbol(UndefValue::get(Ty));
  660. MDNode *MD = m_pHLModule->DxilSamplerToMDNode(S);
  661. resMetadataMap[Ty] = MD;
  662. return MD;
  663. }
  664. default:
  665. // Skip OutputStream for GS.
  666. return nullptr;
  667. }
  668. }
  669. namespace {
  670. MatrixOrientation GetMatrixMajor(QualType Ty, bool bDefaultRowMajor) {
  671. DXASSERT(hlsl::IsHLSLMatType(Ty), "");
  672. bool bIsRowMajor = bDefaultRowMajor;
  673. HasHLSLMatOrientation(Ty, &bIsRowMajor);
  674. return bIsRowMajor ? MatrixOrientation::RowMajor
  675. : MatrixOrientation::ColumnMajor;
  676. }
  677. QualType GetArrayEltType(ASTContext& Context, QualType Ty) {
  678. while (const clang::ArrayType *ArrayTy = Context.getAsArrayType(Ty))
  679. Ty = ArrayTy->getElementType();
  680. return Ty;
  681. }
  682. } // namespace
  683. void CGMSHLSLRuntime::ConstructFieldAttributedAnnotation(
  684. DxilFieldAnnotation &fieldAnnotation, QualType fieldTy,
  685. bool bDefaultRowMajor) {
  686. QualType Ty = fieldTy;
  687. if (Ty->isReferenceType())
  688. Ty = Ty.getNonReferenceType();
  689. // Get element type.
  690. Ty = GetArrayEltType(CGM.getContext(), Ty);
  691. QualType EltTy = Ty;
  692. if (hlsl::IsHLSLMatType(Ty)) {
  693. DxilMatrixAnnotation Matrix;
  694. Matrix.Orientation = GetMatrixMajor(Ty, bDefaultRowMajor);
  695. hlsl::GetHLSLMatRowColCount(Ty, Matrix.Rows, Matrix.Cols);
  696. fieldAnnotation.SetMatrixAnnotation(Matrix);
  697. EltTy = hlsl::GetHLSLMatElementType(Ty);
  698. }
  699. if (hlsl::IsHLSLVecType(Ty))
  700. EltTy = hlsl::GetHLSLVecElementType(Ty);
  701. if (IsHLSLResourceType(Ty)) {
  702. MDNode *MD = GetOrAddResTypeMD(Ty);
  703. fieldAnnotation.SetResourceAttribute(MD);
  704. }
  705. bool bSNorm = false;
  706. bool bUNorm = false;
  707. if (HasHLSLUNormSNorm(Ty, &bSNorm) && !bSNorm)
  708. bUNorm = true;
  709. if (EltTy->isBuiltinType()) {
  710. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  711. CompType::Kind kind = BuiltinTyToCompTy(BTy, bSNorm, bUNorm);
  712. fieldAnnotation.SetCompType(kind);
  713. } else if (EltTy->isEnumeralType()) {
  714. const EnumType *ETy = EltTy->getAs<EnumType>();
  715. QualType type = ETy->getDecl()->getIntegerType();
  716. if (const BuiltinType *BTy =
  717. dyn_cast<BuiltinType>(type->getCanonicalTypeInternal()))
  718. fieldAnnotation.SetCompType(BuiltinTyToCompTy(BTy, bSNorm, bUNorm));
  719. } else {
  720. DXASSERT(!bSNorm && !bUNorm,
  721. "snorm/unorm on invalid type, validate at handleHLSLTypeAttr");
  722. }
  723. }
  724. static void ConstructFieldInterpolation(DxilFieldAnnotation &fieldAnnotation,
  725. FieldDecl *fieldDecl) {
  726. // Keep undefined for interpMode here.
  727. InterpolationMode InterpMode = {fieldDecl->hasAttr<HLSLNoInterpolationAttr>(),
  728. fieldDecl->hasAttr<HLSLLinearAttr>(),
  729. fieldDecl->hasAttr<HLSLNoPerspectiveAttr>(),
  730. fieldDecl->hasAttr<HLSLCentroidAttr>(),
  731. fieldDecl->hasAttr<HLSLSampleAttr>()};
  732. if (InterpMode.GetKind() != InterpolationMode::Kind::Undefined)
  733. fieldAnnotation.SetInterpolationMode(InterpMode);
  734. }
  735. unsigned CGMSHLSLRuntime::ConstructStructAnnotation(DxilStructAnnotation *annotation,
  736. const RecordDecl *RD,
  737. DxilTypeSystem &dxilTypeSys) {
  738. unsigned fieldIdx = 0;
  739. unsigned offset = 0;
  740. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  741. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  742. if (CXXRD->getNumBases()) {
  743. // Add base as field.
  744. for (const auto &I : CXXRD->bases()) {
  745. const CXXRecordDecl *BaseDecl =
  746. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  747. std::string fieldSemName = "";
  748. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  749. // Align offset.
  750. offset = AlignBaseOffset(parentTy, offset, bDefaultRowMajor, CGM,
  751. dataLayout);
  752. unsigned CBufferOffset = offset;
  753. unsigned arrayEltSize = 0;
  754. // Process field to make sure the size of field is ready.
  755. unsigned size =
  756. AddTypeAnnotation(parentTy, dxilTypeSys, arrayEltSize);
  757. // Update offset.
  758. offset += size;
  759. if (size > 0) {
  760. DxilFieldAnnotation &fieldAnnotation =
  761. annotation->GetFieldAnnotation(fieldIdx++);
  762. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  763. fieldAnnotation.SetFieldName(BaseDecl->getNameAsString());
  764. }
  765. }
  766. }
  767. }
  768. for (auto fieldDecl : RD->fields()) {
  769. std::string fieldSemName = "";
  770. QualType fieldTy = fieldDecl->getType();
  771. DXASSERT(!fieldDecl->isBitField(), "We should have already ensured we have no bitfields.");
  772. // Align offset.
  773. offset = AlignBaseOffset(fieldTy, offset, bDefaultRowMajor, CGM, dataLayout);
  774. unsigned CBufferOffset = offset;
  775. // Try to get info from fieldDecl.
  776. for (const hlsl::UnusualAnnotation *it :
  777. fieldDecl->getUnusualAnnotations()) {
  778. switch (it->getKind()) {
  779. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  780. const hlsl::SemanticDecl *sd = cast<hlsl::SemanticDecl>(it);
  781. fieldSemName = sd->SemanticName;
  782. } break;
  783. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  784. const hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  785. CBufferOffset = cp->Subcomponent << 2;
  786. CBufferOffset += cp->ComponentOffset;
  787. // Change to byte.
  788. CBufferOffset <<= 2;
  789. } break;
  790. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  791. // register assignment only works on global constant.
  792. DiagnosticsEngine &Diags = CGM.getDiags();
  793. unsigned DiagID = Diags.getCustomDiagID(
  794. DiagnosticsEngine::Error,
  795. "location semantics cannot be specified on members.");
  796. Diags.Report(it->Loc, DiagID);
  797. return 0;
  798. } break;
  799. default:
  800. llvm_unreachable("only semantic for input/output");
  801. break;
  802. }
  803. }
  804. unsigned arrayEltSize = 0;
  805. // Process field to make sure the size of field is ready.
  806. unsigned size = AddTypeAnnotation(fieldDecl->getType(), dxilTypeSys, arrayEltSize);
  807. // Update offset.
  808. offset += size;
  809. DxilFieldAnnotation &fieldAnnotation = annotation->GetFieldAnnotation(fieldIdx++);
  810. ConstructFieldAttributedAnnotation(fieldAnnotation, fieldTy, bDefaultRowMajor);
  811. ConstructFieldInterpolation(fieldAnnotation, fieldDecl);
  812. if (fieldDecl->hasAttr<HLSLPreciseAttr>())
  813. fieldAnnotation.SetPrecise();
  814. fieldAnnotation.SetCBufferOffset(CBufferOffset);
  815. fieldAnnotation.SetFieldName(fieldDecl->getName());
  816. if (!fieldSemName.empty())
  817. fieldAnnotation.SetSemanticString(fieldSemName);
  818. }
  819. annotation->SetCBufferSize(offset);
  820. if (offset == 0) {
  821. annotation->MarkEmptyStruct();
  822. }
  823. return offset;
  824. }
  825. static bool IsElementInputOutputType(QualType Ty) {
  826. return Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty) || Ty->isEnumeralType();
  827. }
  828. // Return the size for constant buffer of each decl.
  829. unsigned CGMSHLSLRuntime::AddTypeAnnotation(QualType Ty,
  830. DxilTypeSystem &dxilTypeSys,
  831. unsigned &arrayEltSize) {
  832. QualType paramTy = Ty.getCanonicalType();
  833. if (const ReferenceType *RefType = dyn_cast<ReferenceType>(paramTy))
  834. paramTy = RefType->getPointeeType();
  835. // Get size.
  836. llvm::Type *Type = CGM.getTypes().ConvertType(paramTy);
  837. unsigned size = dataLayout.getTypeAllocSize(Type);
  838. if (IsHLSLMatType(Ty)) {
  839. llvm::Type *EltTy = HLMatrixType::cast(Type).getElementTypeForReg();
  840. bool b64Bit = dataLayout.getTypeAllocSize(EltTy) == 8;
  841. size = GetMatrixSizeInCB(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor,
  842. b64Bit);
  843. }
  844. // Skip element types.
  845. if (IsElementInputOutputType(paramTy))
  846. return size;
  847. else if (IsHLSLStreamOutputType(Ty)) {
  848. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  849. arrayEltSize);
  850. } else if (IsHLSLInputPatchType(Ty))
  851. return AddTypeAnnotation(GetHLSLInputPatchElementType(Ty), dxilTypeSys,
  852. arrayEltSize);
  853. else if (IsHLSLOutputPatchType(Ty))
  854. return AddTypeAnnotation(GetHLSLOutputPatchElementType(Ty), dxilTypeSys,
  855. arrayEltSize);
  856. else if (const RecordType *RT = paramTy->getAsStructureType()) {
  857. RecordDecl *RD = RT->getDecl();
  858. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  859. // Skip if already created.
  860. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  861. unsigned structSize = annotation->GetCBufferSize();
  862. return structSize;
  863. }
  864. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  865. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  866. } else if (const RecordType *RT = dyn_cast<RecordType>(paramTy)) {
  867. // For this pointer.
  868. RecordDecl *RD = RT->getDecl();
  869. llvm::StructType *ST = CGM.getTypes().ConvertRecordDeclType(RD);
  870. // Skip if already created.
  871. if (DxilStructAnnotation *annotation = dxilTypeSys.GetStructAnnotation(ST)) {
  872. unsigned structSize = annotation->GetCBufferSize();
  873. return structSize;
  874. }
  875. DxilStructAnnotation *annotation = dxilTypeSys.AddStructAnnotation(ST);
  876. return ConstructStructAnnotation(annotation, RD, dxilTypeSys);
  877. } else if (IsHLSLResourceType(Ty)) {
  878. // Save result type info.
  879. AddTypeAnnotation(GetHLSLResourceResultType(Ty), dxilTypeSys, arrayEltSize);
  880. // Resource don't count for cbuffer size.
  881. return 0;
  882. } else if (IsStringType(Ty)) {
  883. // string won't be included in cbuffer
  884. return 0;
  885. } else {
  886. unsigned arraySize = 0;
  887. QualType arrayElementTy = Ty;
  888. if (Ty->isConstantArrayType()) {
  889. const ConstantArrayType *arrayTy =
  890. CGM.getContext().getAsConstantArrayType(Ty);
  891. DXASSERT(arrayTy != nullptr, "Must array type here");
  892. arraySize = arrayTy->getSize().getLimitedValue();
  893. arrayElementTy = arrayTy->getElementType();
  894. }
  895. else if (Ty->isIncompleteArrayType()) {
  896. const IncompleteArrayType *arrayTy = CGM.getContext().getAsIncompleteArrayType(Ty);
  897. arrayElementTy = arrayTy->getElementType();
  898. } else {
  899. DXASSERT(0, "Must array type here");
  900. }
  901. unsigned elementSize = AddTypeAnnotation(arrayElementTy, dxilTypeSys, arrayEltSize);
  902. // Only set arrayEltSize once.
  903. if (arrayEltSize == 0)
  904. arrayEltSize = elementSize;
  905. // Align to 4 * 4bytes.
  906. unsigned alignedSize = (elementSize + 15) & 0xfffffff0;
  907. return alignedSize * (arraySize - 1) + elementSize;
  908. }
  909. }
  910. static DxilResource::Kind KeywordToKind(StringRef keyword) {
  911. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  912. // compare)
  913. if (keyword == "Texture1D" || keyword == "RWTexture1D" || keyword == "RasterizerOrderedTexture1D")
  914. return DxilResource::Kind::Texture1D;
  915. if (keyword == "Texture2D" || keyword == "RWTexture2D" || keyword == "RasterizerOrderedTexture2D")
  916. return DxilResource::Kind::Texture2D;
  917. if (keyword == "Texture2DMS" || keyword == "RWTexture2DMS")
  918. return DxilResource::Kind::Texture2DMS;
  919. if (keyword == "Texture3D" || keyword == "RWTexture3D" || keyword == "RasterizerOrderedTexture3D")
  920. return DxilResource::Kind::Texture3D;
  921. if (keyword == "TextureCube" || keyword == "RWTextureCube")
  922. return DxilResource::Kind::TextureCube;
  923. if (keyword == "Texture1DArray" || keyword == "RWTexture1DArray" || keyword == "RasterizerOrderedTexture1DArray")
  924. return DxilResource::Kind::Texture1DArray;
  925. if (keyword == "Texture2DArray" || keyword == "RWTexture2DArray" || keyword == "RasterizerOrderedTexture2DArray")
  926. return DxilResource::Kind::Texture2DArray;
  927. if (keyword == "Texture2DMSArray" || keyword == "RWTexture2DMSArray")
  928. return DxilResource::Kind::Texture2DMSArray;
  929. if (keyword == "TextureCubeArray" || keyword == "RWTextureCubeArray")
  930. return DxilResource::Kind::TextureCubeArray;
  931. if (keyword == "ByteAddressBuffer" || keyword == "RWByteAddressBuffer" || keyword == "RasterizerOrderedByteAddressBuffer")
  932. return DxilResource::Kind::RawBuffer;
  933. if (keyword == "StructuredBuffer" || keyword == "RWStructuredBuffer" || keyword == "RasterizerOrderedStructuredBuffer")
  934. return DxilResource::Kind::StructuredBuffer;
  935. if (keyword == "AppendStructuredBuffer" || keyword == "ConsumeStructuredBuffer")
  936. return DxilResource::Kind::StructuredBuffer;
  937. // TODO: this is not efficient.
  938. bool isBuffer = keyword == "Buffer";
  939. isBuffer |= keyword == "RWBuffer";
  940. isBuffer |= keyword == "RasterizerOrderedBuffer";
  941. if (isBuffer)
  942. return DxilResource::Kind::TypedBuffer;
  943. if (keyword == "RaytracingAccelerationStructure")
  944. return DxilResource::Kind::RTAccelerationStructure;
  945. return DxilResource::Kind::Invalid;
  946. }
  947. void CGMSHLSLRuntime::AddHLSLFunctionInfo(Function *F, const FunctionDecl *FD) {
  948. // Add hlsl intrinsic attr
  949. unsigned intrinsicOpcode;
  950. StringRef intrinsicGroup;
  951. llvm::FunctionType *FT = F->getFunctionType();
  952. auto AddResourceMetadata = [&](QualType qTy, llvm::Type *Ty) {
  953. hlsl::DxilResourceBase::Class resClass = TypeToClass(qTy);
  954. if (resClass != hlsl::DxilResourceBase::Class::Invalid) {
  955. if (!resMetadataMap.count(Ty)) {
  956. MDNode *Meta = GetOrAddResTypeMD(qTy);
  957. DXASSERT(Meta, "else invalid resource type");
  958. resMetadataMap[Ty] = Meta;
  959. }
  960. }
  961. };
  962. if (hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup)) {
  963. AddHLSLIntrinsicOpcodeToFunction(F, intrinsicOpcode);
  964. F->addFnAttr(hlsl::HLPrefix, intrinsicGroup);
  965. unsigned iParamOffset = 0; // skip this on llvm function
  966. // Save resource type annotation.
  967. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
  968. iParamOffset = 1;
  969. const CXXRecordDecl *RD = MD->getParent();
  970. // For nested case like sample_slice_type.
  971. if (const CXXRecordDecl *PRD =
  972. dyn_cast<CXXRecordDecl>(RD->getDeclContext())) {
  973. RD = PRD;
  974. }
  975. QualType recordTy = MD->getASTContext().getRecordType(RD);
  976. llvm::Type *Ty = CGM.getTypes().ConvertType(recordTy);
  977. AddResourceMetadata(recordTy, Ty);
  978. }
  979. // Add metadata for any resources found in parameters
  980. for (unsigned iParam = 0; iParam < FD->getNumParams(); iParam++) {
  981. llvm::Type *Ty = FT->getParamType(iParam + iParamOffset);
  982. if (!Ty->isPointerTy())
  983. continue; // not a resource
  984. Ty = Ty->getPointerElementType();
  985. QualType paramTy = FD->getParamDecl(iParam)->getType();
  986. AddResourceMetadata(paramTy, Ty);
  987. }
  988. StringRef lower;
  989. if (hlsl::GetIntrinsicLowering(FD, lower))
  990. hlsl::SetHLLowerStrategy(F, lower);
  991. // Don't need to add FunctionQual for intrinsic function.
  992. return;
  993. }
  994. if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::FTZ) {
  995. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueFtzString);
  996. }
  997. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Preserve) {
  998. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValuePreserveString);
  999. }
  1000. else if (m_pHLModule->GetFloat32DenormMode() == DXIL::Float32DenormMode::Any) {
  1001. F->addFnAttr(DXIL::kFP32DenormKindString, DXIL::kFP32DenormValueAnyString);
  1002. }
  1003. // Set entry function
  1004. const std::string &entryName = m_pHLModule->GetEntryFunctionName();
  1005. bool isEntry = FD->getNameAsString() == entryName;
  1006. if (isEntry) {
  1007. Entry.Func = F;
  1008. Entry.SL = FD->getLocation();
  1009. }
  1010. DiagnosticsEngine &Diags = CGM.getDiags();
  1011. std::unique_ptr<DxilFunctionProps> funcProps =
  1012. llvm::make_unique<DxilFunctionProps>();
  1013. funcProps->shaderKind = DXIL::ShaderKind::Invalid;
  1014. bool isCS = false;
  1015. bool isGS = false;
  1016. bool isHS = false;
  1017. bool isDS = false;
  1018. bool isVS = false;
  1019. bool isPS = false;
  1020. bool isRay = false;
  1021. if (const HLSLShaderAttr *Attr = FD->getAttr<HLSLShaderAttr>()) {
  1022. // Stage is already validate in HandleDeclAttributeForHLSL.
  1023. // Here just check first letter (or two).
  1024. switch (Attr->getStage()[0]) {
  1025. case 'c':
  1026. switch (Attr->getStage()[1]) {
  1027. case 'o':
  1028. isCS = true;
  1029. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1030. break;
  1031. case 'l':
  1032. isRay = true;
  1033. funcProps->shaderKind = DXIL::ShaderKind::ClosestHit;
  1034. break;
  1035. case 'a':
  1036. isRay = true;
  1037. funcProps->shaderKind = DXIL::ShaderKind::Callable;
  1038. break;
  1039. default:
  1040. break;
  1041. }
  1042. break;
  1043. case 'v':
  1044. isVS = true;
  1045. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1046. break;
  1047. case 'h':
  1048. isHS = true;
  1049. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1050. break;
  1051. case 'd':
  1052. isDS = true;
  1053. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1054. break;
  1055. case 'g':
  1056. isGS = true;
  1057. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1058. break;
  1059. case 'p':
  1060. isPS = true;
  1061. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1062. break;
  1063. case 'r':
  1064. isRay = true;
  1065. funcProps->shaderKind = DXIL::ShaderKind::RayGeneration;
  1066. break;
  1067. case 'i':
  1068. isRay = true;
  1069. funcProps->shaderKind = DXIL::ShaderKind::Intersection;
  1070. break;
  1071. case 'a':
  1072. isRay = true;
  1073. funcProps->shaderKind = DXIL::ShaderKind::AnyHit;
  1074. break;
  1075. case 'm':
  1076. isRay = true;
  1077. funcProps->shaderKind = DXIL::ShaderKind::Miss;
  1078. break;
  1079. default:
  1080. break;
  1081. }
  1082. if (funcProps->shaderKind == DXIL::ShaderKind::Invalid) {
  1083. unsigned DiagID = Diags.getCustomDiagID(
  1084. DiagnosticsEngine::Error, "Invalid profile for shader attribute");
  1085. Diags.Report(Attr->getLocation(), DiagID);
  1086. }
  1087. if (isEntry && isRay) {
  1088. unsigned DiagID = Diags.getCustomDiagID(
  1089. DiagnosticsEngine::Error, "Ray function cannot be used as a global entry point");
  1090. Diags.Report(Attr->getLocation(), DiagID);
  1091. }
  1092. }
  1093. // Save patch constant function to patchConstantFunctionMap.
  1094. bool isPatchConstantFunction = false;
  1095. if (!isEntry && CGM.getContext().IsPatchConstantFunctionDecl(FD)) {
  1096. isPatchConstantFunction = true;
  1097. auto &PCI = patchConstantFunctionMap[FD->getName()];
  1098. PCI.SL = FD->getLocation();
  1099. PCI.Func = F;
  1100. ++PCI.NumOverloads;
  1101. for (ParmVarDecl *parmDecl : FD->parameters()) {
  1102. QualType Ty = parmDecl->getType();
  1103. if (IsHLSLOutputPatchType(Ty)) {
  1104. funcProps->ShaderProps.HS.outputControlPoints =
  1105. GetHLSLOutputPatchCount(parmDecl->getType());
  1106. } else if (IsHLSLInputPatchType(Ty)) {
  1107. funcProps->ShaderProps.HS.inputControlPoints =
  1108. GetHLSLInputPatchCount(parmDecl->getType());
  1109. }
  1110. }
  1111. // Mark patch constant functions that cannot be linked as exports
  1112. // InternalLinkage. Patch constant functions that are actually used
  1113. // will be set back to ExternalLinkage in FinishCodeGen.
  1114. if (funcProps->ShaderProps.HS.outputControlPoints ||
  1115. funcProps->ShaderProps.HS.inputControlPoints) {
  1116. PCI.Func->setLinkage(GlobalValue::InternalLinkage);
  1117. }
  1118. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1119. }
  1120. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1121. if (isEntry) {
  1122. funcProps->shaderKind = SM->GetKind();
  1123. }
  1124. // Geometry shader.
  1125. if (const HLSLMaxVertexCountAttr *Attr =
  1126. FD->getAttr<HLSLMaxVertexCountAttr>()) {
  1127. isGS = true;
  1128. funcProps->shaderKind = DXIL::ShaderKind::Geometry;
  1129. funcProps->ShaderProps.GS.maxVertexCount = Attr->getCount();
  1130. funcProps->ShaderProps.GS.inputPrimitive = DXIL::InputPrimitive::Undefined;
  1131. if (isEntry && !SM->IsGS()) {
  1132. unsigned DiagID =
  1133. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1134. "attribute maxvertexcount only valid for GS.");
  1135. Diags.Report(Attr->getLocation(), DiagID);
  1136. return;
  1137. }
  1138. }
  1139. if (const HLSLInstanceAttr *Attr = FD->getAttr<HLSLInstanceAttr>()) {
  1140. unsigned instanceCount = Attr->getCount();
  1141. funcProps->ShaderProps.GS.instanceCount = instanceCount;
  1142. if (isEntry && !SM->IsGS()) {
  1143. unsigned DiagID =
  1144. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1145. "attribute maxvertexcount only valid for GS.");
  1146. Diags.Report(Attr->getLocation(), DiagID);
  1147. return;
  1148. }
  1149. } else {
  1150. // Set default instance count.
  1151. if (isGS)
  1152. funcProps->ShaderProps.GS.instanceCount = 1;
  1153. }
  1154. // Computer shader.
  1155. if (const HLSLNumThreadsAttr *Attr = FD->getAttr<HLSLNumThreadsAttr>()) {
  1156. isCS = true;
  1157. funcProps->shaderKind = DXIL::ShaderKind::Compute;
  1158. funcProps->ShaderProps.CS.numThreads[0] = Attr->getX();
  1159. funcProps->ShaderProps.CS.numThreads[1] = Attr->getY();
  1160. funcProps->ShaderProps.CS.numThreads[2] = Attr->getZ();
  1161. if (isEntry && !SM->IsCS()) {
  1162. unsigned DiagID = Diags.getCustomDiagID(
  1163. DiagnosticsEngine::Error, "attribute numthreads only valid for CS.");
  1164. Diags.Report(Attr->getLocation(), DiagID);
  1165. return;
  1166. }
  1167. }
  1168. // Hull shader.
  1169. if (const HLSLPatchConstantFuncAttr *Attr =
  1170. FD->getAttr<HLSLPatchConstantFuncAttr>()) {
  1171. if (isEntry && !SM->IsHS()) {
  1172. unsigned DiagID = Diags.getCustomDiagID(
  1173. DiagnosticsEngine::Error,
  1174. "attribute patchconstantfunc only valid for HS.");
  1175. Diags.Report(Attr->getLocation(), DiagID);
  1176. return;
  1177. }
  1178. isHS = true;
  1179. funcProps->shaderKind = DXIL::ShaderKind::Hull;
  1180. HSEntryPatchConstantFuncAttr[F] = Attr;
  1181. } else {
  1182. // TODO: This is a duplicate check. We also have this check in
  1183. // hlsl::DiagnoseTranslationUnit(clang::Sema*).
  1184. if (isEntry && SM->IsHS()) {
  1185. unsigned DiagID = Diags.getCustomDiagID(
  1186. DiagnosticsEngine::Error,
  1187. "HS entry point must have the patchconstantfunc attribute");
  1188. Diags.Report(FD->getLocation(), DiagID);
  1189. return;
  1190. }
  1191. }
  1192. if (const HLSLOutputControlPointsAttr *Attr =
  1193. FD->getAttr<HLSLOutputControlPointsAttr>()) {
  1194. if (isHS) {
  1195. funcProps->ShaderProps.HS.outputControlPoints = Attr->getCount();
  1196. } else if (isEntry && !SM->IsHS()) {
  1197. unsigned DiagID = Diags.getCustomDiagID(
  1198. DiagnosticsEngine::Error,
  1199. "attribute outputcontrolpoints only valid for HS.");
  1200. Diags.Report(Attr->getLocation(), DiagID);
  1201. return;
  1202. }
  1203. }
  1204. if (const HLSLPartitioningAttr *Attr = FD->getAttr<HLSLPartitioningAttr>()) {
  1205. if (isHS) {
  1206. DXIL::TessellatorPartitioning partition =
  1207. StringToPartitioning(Attr->getScheme());
  1208. funcProps->ShaderProps.HS.partition = partition;
  1209. } else if (isEntry && !SM->IsHS()) {
  1210. unsigned DiagID =
  1211. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1212. "attribute partitioning only valid for HS.");
  1213. Diags.Report(Attr->getLocation(), DiagID);
  1214. }
  1215. }
  1216. if (const HLSLOutputTopologyAttr *Attr =
  1217. FD->getAttr<HLSLOutputTopologyAttr>()) {
  1218. if (isHS) {
  1219. DXIL::TessellatorOutputPrimitive primitive =
  1220. StringToTessOutputPrimitive(Attr->getTopology());
  1221. funcProps->ShaderProps.HS.outputPrimitive = primitive;
  1222. } else if (isEntry && !SM->IsHS()) {
  1223. unsigned DiagID =
  1224. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  1225. "attribute outputtopology only valid for HS.");
  1226. Diags.Report(Attr->getLocation(), DiagID);
  1227. }
  1228. }
  1229. if (isHS) {
  1230. funcProps->ShaderProps.HS.maxTessFactor = DXIL::kHSMaxTessFactorUpperBound;
  1231. funcProps->ShaderProps.HS.inputControlPoints = DXIL::kHSDefaultInputControlPointCount;
  1232. }
  1233. if (const HLSLMaxTessFactorAttr *Attr =
  1234. FD->getAttr<HLSLMaxTessFactorAttr>()) {
  1235. if (isHS) {
  1236. // TODO: change getFactor to return float.
  1237. llvm::APInt intV(32, Attr->getFactor());
  1238. funcProps->ShaderProps.HS.maxTessFactor = intV.bitsToFloat();
  1239. } else if (isEntry && !SM->IsHS()) {
  1240. unsigned DiagID =
  1241. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1242. "attribute maxtessfactor only valid for HS.");
  1243. Diags.Report(Attr->getLocation(), DiagID);
  1244. return;
  1245. }
  1246. }
  1247. // Hull or domain shader.
  1248. if (const HLSLDomainAttr *Attr = FD->getAttr<HLSLDomainAttr>()) {
  1249. if (isEntry && !SM->IsHS() && !SM->IsDS()) {
  1250. unsigned DiagID =
  1251. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1252. "attribute domain only valid for HS or DS.");
  1253. Diags.Report(Attr->getLocation(), DiagID);
  1254. return;
  1255. }
  1256. isDS = !isHS;
  1257. if (isDS)
  1258. funcProps->shaderKind = DXIL::ShaderKind::Domain;
  1259. DXIL::TessellatorDomain domain = StringToDomain(Attr->getDomainType());
  1260. if (isHS)
  1261. funcProps->ShaderProps.HS.domain = domain;
  1262. else
  1263. funcProps->ShaderProps.DS.domain = domain;
  1264. }
  1265. // Vertex shader.
  1266. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1267. if (isEntry && !SM->IsVS()) {
  1268. unsigned DiagID = Diags.getCustomDiagID(
  1269. DiagnosticsEngine::Error, "attribute clipplane only valid for VS.");
  1270. Diags.Report(Attr->getLocation(), DiagID);
  1271. return;
  1272. }
  1273. isVS = true;
  1274. // The real job is done at EmitHLSLFunctionProlog where debug info is
  1275. // available. Only set shader kind here.
  1276. funcProps->shaderKind = DXIL::ShaderKind::Vertex;
  1277. }
  1278. // Pixel shader.
  1279. if (const HLSLEarlyDepthStencilAttr *Attr =
  1280. FD->getAttr<HLSLEarlyDepthStencilAttr>()) {
  1281. if (isEntry && !SM->IsPS()) {
  1282. unsigned DiagID = Diags.getCustomDiagID(
  1283. DiagnosticsEngine::Error,
  1284. "attribute earlydepthstencil only valid for PS.");
  1285. Diags.Report(Attr->getLocation(), DiagID);
  1286. return;
  1287. }
  1288. isPS = true;
  1289. funcProps->ShaderProps.PS.EarlyDepthStencil = true;
  1290. funcProps->shaderKind = DXIL::ShaderKind::Pixel;
  1291. }
  1292. const unsigned profileAttributes = isCS + isHS + isDS + isGS + isVS + isPS + isRay;
  1293. // TODO: check this in front-end and report error.
  1294. DXASSERT(profileAttributes < 2, "profile attributes are mutual exclusive");
  1295. if (isEntry) {
  1296. switch (funcProps->shaderKind) {
  1297. case ShaderModel::Kind::Compute:
  1298. case ShaderModel::Kind::Hull:
  1299. case ShaderModel::Kind::Domain:
  1300. case ShaderModel::Kind::Geometry:
  1301. case ShaderModel::Kind::Vertex:
  1302. case ShaderModel::Kind::Pixel:
  1303. DXASSERT(funcProps->shaderKind == SM->GetKind(),
  1304. "attribute profile not match entry function profile");
  1305. break;
  1306. case ShaderModel::Kind::Library:
  1307. case ShaderModel::Kind::Invalid:
  1308. // Non-shader stage shadermodels don't have entry points.
  1309. break;
  1310. }
  1311. }
  1312. DxilFunctionAnnotation *FuncAnnotation =
  1313. m_pHLModule->AddFunctionAnnotation(F);
  1314. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  1315. // Param Info
  1316. unsigned streamIndex = 0;
  1317. unsigned inputPatchCount = 0;
  1318. unsigned outputPatchCount = 0;
  1319. unsigned ArgNo = 0;
  1320. unsigned ParmIdx = 0;
  1321. if (const CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FD)) {
  1322. if (MethodDecl->isInstance()) {
  1323. QualType ThisTy = MethodDecl->getThisType(FD->getASTContext());
  1324. DxilParameterAnnotation &paramAnnotation =
  1325. FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1326. // Construct annoation for this pointer.
  1327. ConstructFieldAttributedAnnotation(paramAnnotation, ThisTy,
  1328. bDefaultRowMajor);
  1329. }
  1330. }
  1331. // Ret Info
  1332. QualType retTy = FD->getReturnType();
  1333. DxilParameterAnnotation *pRetTyAnnotation = nullptr;
  1334. if (F->getReturnType()->isVoidTy() && !retTy->isVoidType()) {
  1335. // SRet.
  1336. pRetTyAnnotation = &FuncAnnotation->GetParameterAnnotation(ArgNo++);
  1337. } else {
  1338. pRetTyAnnotation = &FuncAnnotation->GetRetTypeAnnotation();
  1339. }
  1340. DxilParameterAnnotation &retTyAnnotation = *pRetTyAnnotation;
  1341. // keep Undefined here, we cannot decide for struct
  1342. retTyAnnotation.SetInterpolationMode(
  1343. GetInterpMode(FD, CompType::Kind::Invalid, /*bKeepUndefined*/ true)
  1344. .GetKind());
  1345. SourceLocation retTySemanticLoc = SetSemantic(FD, retTyAnnotation);
  1346. retTyAnnotation.SetParamInputQual(DxilParamInputQual::Out);
  1347. if (isEntry) {
  1348. if (CGM.getLangOpts().EnableDX9CompatMode && retTyAnnotation.HasSemanticString()) {
  1349. RemapObsoleteSemantic(retTyAnnotation, /*isPatchConstantFunction*/ false);
  1350. }
  1351. CheckParameterAnnotation(retTySemanticLoc, retTyAnnotation,
  1352. /*isPatchConstantFunction*/ false);
  1353. }
  1354. if (isRay && !retTy->isVoidType()) {
  1355. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1356. DiagnosticsEngine::Error, "return type for ray tracing shaders must be void"));
  1357. }
  1358. ConstructFieldAttributedAnnotation(retTyAnnotation, retTy, bDefaultRowMajor);
  1359. if (FD->hasAttr<HLSLPreciseAttr>())
  1360. retTyAnnotation.SetPrecise();
  1361. if (isRay) {
  1362. funcProps->ShaderProps.Ray.payloadSizeInBytes = 0;
  1363. funcProps->ShaderProps.Ray.attributeSizeInBytes = 0;
  1364. }
  1365. for (; ArgNo < F->arg_size(); ++ArgNo, ++ParmIdx) {
  1366. DxilParameterAnnotation &paramAnnotation =
  1367. FuncAnnotation->GetParameterAnnotation(ArgNo);
  1368. const ParmVarDecl *parmDecl = FD->getParamDecl(ParmIdx);
  1369. QualType fieldTy = parmDecl->getType();
  1370. // if parameter type is a typedef, try to desugar it first.
  1371. if (isa<TypedefType>(fieldTy.getTypePtr()))
  1372. fieldTy = fieldTy.getDesugaredType(FD->getASTContext());
  1373. ConstructFieldAttributedAnnotation(paramAnnotation, fieldTy,
  1374. bDefaultRowMajor);
  1375. if (parmDecl->hasAttr<HLSLPreciseAttr>())
  1376. paramAnnotation.SetPrecise();
  1377. // keep Undefined here, we cannot decide for struct
  1378. InterpolationMode paramIM =
  1379. GetInterpMode(parmDecl, CompType::Kind::Invalid, KeepUndefinedTrue);
  1380. paramAnnotation.SetInterpolationMode(paramIM);
  1381. SourceLocation paramSemanticLoc = SetSemantic(parmDecl, paramAnnotation);
  1382. DxilParamInputQual dxilInputQ = DxilParamInputQual::In;
  1383. if (parmDecl->hasAttr<HLSLInOutAttr>())
  1384. dxilInputQ = DxilParamInputQual::Inout;
  1385. else if (parmDecl->hasAttr<HLSLOutAttr>())
  1386. dxilInputQ = DxilParamInputQual::Out;
  1387. if (parmDecl->hasAttr<HLSLOutAttr>() && parmDecl->hasAttr<HLSLInAttr>())
  1388. dxilInputQ = DxilParamInputQual::Inout;
  1389. DXIL::InputPrimitive inputPrimitive = DXIL::InputPrimitive::Undefined;
  1390. if (IsHLSLOutputPatchType(parmDecl->getType())) {
  1391. outputPatchCount++;
  1392. if (dxilInputQ != DxilParamInputQual::In) {
  1393. unsigned DiagID = Diags.getCustomDiagID(
  1394. DiagnosticsEngine::Error,
  1395. "OutputPatch should not be out/inout parameter");
  1396. Diags.Report(parmDecl->getLocation(), DiagID);
  1397. continue;
  1398. }
  1399. dxilInputQ = DxilParamInputQual::OutputPatch;
  1400. if (isDS)
  1401. funcProps->ShaderProps.DS.inputControlPoints =
  1402. GetHLSLOutputPatchCount(parmDecl->getType());
  1403. } else if (IsHLSLInputPatchType(parmDecl->getType())) {
  1404. inputPatchCount++;
  1405. if (dxilInputQ != DxilParamInputQual::In) {
  1406. unsigned DiagID = Diags.getCustomDiagID(
  1407. DiagnosticsEngine::Error,
  1408. "InputPatch should not be out/inout parameter");
  1409. Diags.Report(parmDecl->getLocation(), DiagID);
  1410. continue;
  1411. }
  1412. dxilInputQ = DxilParamInputQual::InputPatch;
  1413. if (isHS) {
  1414. funcProps->ShaderProps.HS.inputControlPoints =
  1415. GetHLSLInputPatchCount(parmDecl->getType());
  1416. } else if (isGS) {
  1417. inputPrimitive = (DXIL::InputPrimitive)(
  1418. (unsigned)DXIL::InputPrimitive::ControlPointPatch1 +
  1419. GetHLSLInputPatchCount(parmDecl->getType()) - 1);
  1420. }
  1421. } else if (IsHLSLStreamOutputType(parmDecl->getType())) {
  1422. // TODO: validation this at ASTContext::getFunctionType in
  1423. // AST/ASTContext.cpp
  1424. DXASSERT(dxilInputQ == DxilParamInputQual::Inout,
  1425. "stream output parameter must be inout");
  1426. switch (streamIndex) {
  1427. case 0:
  1428. dxilInputQ = DxilParamInputQual::OutStream0;
  1429. break;
  1430. case 1:
  1431. dxilInputQ = DxilParamInputQual::OutStream1;
  1432. break;
  1433. case 2:
  1434. dxilInputQ = DxilParamInputQual::OutStream2;
  1435. break;
  1436. case 3:
  1437. default:
  1438. // TODO: validation this at ASTContext::getFunctionType in
  1439. // AST/ASTContext.cpp
  1440. DXASSERT(streamIndex == 3, "stream number out of bound");
  1441. dxilInputQ = DxilParamInputQual::OutStream3;
  1442. break;
  1443. }
  1444. DXIL::PrimitiveTopology &streamTopology =
  1445. funcProps->ShaderProps.GS.streamPrimitiveTopologies[streamIndex];
  1446. if (IsHLSLPointStreamType(parmDecl->getType()))
  1447. streamTopology = DXIL::PrimitiveTopology::PointList;
  1448. else if (IsHLSLLineStreamType(parmDecl->getType()))
  1449. streamTopology = DXIL::PrimitiveTopology::LineStrip;
  1450. else {
  1451. DXASSERT(IsHLSLTriangleStreamType(parmDecl->getType()),
  1452. "invalid StreamType");
  1453. streamTopology = DXIL::PrimitiveTopology::TriangleStrip;
  1454. }
  1455. if (streamIndex > 0) {
  1456. bool bAllPoint =
  1457. streamTopology == DXIL::PrimitiveTopology::PointList &&
  1458. funcProps->ShaderProps.GS.streamPrimitiveTopologies[0] ==
  1459. DXIL::PrimitiveTopology::PointList;
  1460. if (!bAllPoint) {
  1461. unsigned DiagID = Diags.getCustomDiagID(
  1462. DiagnosticsEngine::Error, "when multiple GS output streams are "
  1463. "used they must be pointlists.");
  1464. Diags.Report(FD->getLocation(), DiagID);
  1465. }
  1466. }
  1467. streamIndex++;
  1468. }
  1469. unsigned GsInputArrayDim = 0;
  1470. if (parmDecl->hasAttr<HLSLTriangleAttr>()) {
  1471. inputPrimitive = DXIL::InputPrimitive::Triangle;
  1472. GsInputArrayDim = 3;
  1473. } else if (parmDecl->hasAttr<HLSLTriangleAdjAttr>()) {
  1474. inputPrimitive = DXIL::InputPrimitive::TriangleWithAdjacency;
  1475. GsInputArrayDim = 6;
  1476. } else if (parmDecl->hasAttr<HLSLPointAttr>()) {
  1477. inputPrimitive = DXIL::InputPrimitive::Point;
  1478. GsInputArrayDim = 1;
  1479. } else if (parmDecl->hasAttr<HLSLLineAdjAttr>()) {
  1480. inputPrimitive = DXIL::InputPrimitive::LineWithAdjacency;
  1481. GsInputArrayDim = 4;
  1482. } else if (parmDecl->hasAttr<HLSLLineAttr>()) {
  1483. inputPrimitive = DXIL::InputPrimitive::Line;
  1484. GsInputArrayDim = 2;
  1485. }
  1486. if (inputPrimitive != DXIL::InputPrimitive::Undefined) {
  1487. // Set to InputPrimitive for GS.
  1488. dxilInputQ = DxilParamInputQual::InputPrimitive;
  1489. if (funcProps->ShaderProps.GS.inputPrimitive ==
  1490. DXIL::InputPrimitive::Undefined) {
  1491. funcProps->ShaderProps.GS.inputPrimitive = inputPrimitive;
  1492. } else if (funcProps->ShaderProps.GS.inputPrimitive != inputPrimitive) {
  1493. unsigned DiagID = Diags.getCustomDiagID(
  1494. DiagnosticsEngine::Error, "input parameter conflicts with geometry "
  1495. "specifier of previous input parameters");
  1496. Diags.Report(parmDecl->getLocation(), DiagID);
  1497. }
  1498. }
  1499. if (GsInputArrayDim != 0) {
  1500. QualType Ty = parmDecl->getType();
  1501. if (!Ty->isConstantArrayType()) {
  1502. unsigned DiagID = Diags.getCustomDiagID(
  1503. DiagnosticsEngine::Error,
  1504. "input types for geometry shader must be constant size arrays");
  1505. Diags.Report(parmDecl->getLocation(), DiagID);
  1506. } else {
  1507. const ConstantArrayType *CAT = cast<ConstantArrayType>(Ty);
  1508. if (CAT->getSize().getLimitedValue() != GsInputArrayDim) {
  1509. StringRef primtiveNames[] = {
  1510. "invalid", // 0
  1511. "point", // 1
  1512. "line", // 2
  1513. "triangle", // 3
  1514. "lineadj", // 4
  1515. "invalid", // 5
  1516. "triangleadj", // 6
  1517. };
  1518. DXASSERT(GsInputArrayDim < llvm::array_lengthof(primtiveNames),
  1519. "Invalid array dim");
  1520. unsigned DiagID = Diags.getCustomDiagID(
  1521. DiagnosticsEngine::Error, "array dimension for %0 must be %1");
  1522. Diags.Report(parmDecl->getLocation(), DiagID)
  1523. << primtiveNames[GsInputArrayDim] << GsInputArrayDim;
  1524. }
  1525. }
  1526. }
  1527. // Validate Ray Tracing function parameter (some validation may be pushed into front end)
  1528. if (isRay) {
  1529. switch (funcProps->shaderKind) {
  1530. case DXIL::ShaderKind::RayGeneration:
  1531. case DXIL::ShaderKind::Intersection:
  1532. // RayGeneration and Intersection shaders are not allowed to have any input parameters
  1533. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1534. DiagnosticsEngine::Error, "parameters are not allowed for %0 shader"))
  1535. << (funcProps->shaderKind == DXIL::ShaderKind::RayGeneration ?
  1536. "raygeneration" : "intersection");
  1537. break;
  1538. case DXIL::ShaderKind::AnyHit:
  1539. case DXIL::ShaderKind::ClosestHit:
  1540. if (0 == ArgNo && dxilInputQ != DxilParamInputQual::Inout) {
  1541. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1542. DiagnosticsEngine::Error,
  1543. "ray payload parameter must be inout"));
  1544. } else if (1 == ArgNo && dxilInputQ != DxilParamInputQual::In) {
  1545. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1546. DiagnosticsEngine::Error,
  1547. "intersection attributes parameter must be in"));
  1548. } else if (ArgNo > 1) {
  1549. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1550. DiagnosticsEngine::Error,
  1551. "too many parameters, expected payload and attributes parameters only."));
  1552. }
  1553. if (ArgNo < 2) {
  1554. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1555. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1556. DiagnosticsEngine::Error,
  1557. "payload and attribute structures must be user defined types with only numeric contents."));
  1558. } else {
  1559. DataLayout DL(&this->TheModule);
  1560. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1561. if (0 == ArgNo)
  1562. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1563. else
  1564. funcProps->ShaderProps.Ray.attributeSizeInBytes = size;
  1565. }
  1566. }
  1567. break;
  1568. case DXIL::ShaderKind::Miss:
  1569. if (ArgNo > 0) {
  1570. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1571. DiagnosticsEngine::Error,
  1572. "only one parameter (ray payload) allowed for miss shader"));
  1573. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1574. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1575. DiagnosticsEngine::Error,
  1576. "ray payload parameter must be declared inout"));
  1577. }
  1578. if (ArgNo < 1) {
  1579. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1580. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1581. DiagnosticsEngine::Error,
  1582. "ray payload parameter must be a user defined type with only numeric contents."));
  1583. } else {
  1584. DataLayout DL(&this->TheModule);
  1585. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1586. funcProps->ShaderProps.Ray.payloadSizeInBytes = size;
  1587. }
  1588. }
  1589. break;
  1590. case DXIL::ShaderKind::Callable:
  1591. if (ArgNo > 0) {
  1592. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1593. DiagnosticsEngine::Error,
  1594. "only one parameter allowed for callable shader"));
  1595. } else if (dxilInputQ != DxilParamInputQual::Inout) {
  1596. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1597. DiagnosticsEngine::Error,
  1598. "callable parameter must be declared inout"));
  1599. }
  1600. if (ArgNo < 1) {
  1601. if (!IsHLSLNumericUserDefinedType(parmDecl->getType())) {
  1602. Diags.Report(parmDecl->getLocation(), Diags.getCustomDiagID(
  1603. DiagnosticsEngine::Error,
  1604. "callable parameter must be a user defined type with only numeric contents."));
  1605. } else {
  1606. DataLayout DL(&this->TheModule);
  1607. unsigned size = DL.getTypeAllocSize(F->getFunctionType()->getFunctionParamType(ArgNo)->getPointerElementType());
  1608. funcProps->ShaderProps.Ray.paramSizeInBytes = size;
  1609. }
  1610. }
  1611. break;
  1612. }
  1613. }
  1614. paramAnnotation.SetParamInputQual(dxilInputQ);
  1615. if (isEntry) {
  1616. if (CGM.getLangOpts().EnableDX9CompatMode && paramAnnotation.HasSemanticString()) {
  1617. RemapObsoleteSemantic(paramAnnotation, /*isPatchConstantFunction*/ false);
  1618. }
  1619. CheckParameterAnnotation(paramSemanticLoc, paramAnnotation,
  1620. /*isPatchConstantFunction*/ false);
  1621. }
  1622. }
  1623. if (inputPatchCount > 1) {
  1624. unsigned DiagID = Diags.getCustomDiagID(
  1625. DiagnosticsEngine::Error, "may only have one InputPatch parameter");
  1626. Diags.Report(FD->getLocation(), DiagID);
  1627. }
  1628. if (outputPatchCount > 1) {
  1629. unsigned DiagID = Diags.getCustomDiagID(
  1630. DiagnosticsEngine::Error, "may only have one OutputPatch parameter");
  1631. Diags.Report(FD->getLocation(), DiagID);
  1632. }
  1633. // If Shader is a ray shader that requires parameters, make sure size is non-zero
  1634. if (isRay) {
  1635. bool bNeedsAttributes = false;
  1636. bool bNeedsPayload = false;
  1637. switch (funcProps->shaderKind) {
  1638. case DXIL::ShaderKind::AnyHit:
  1639. case DXIL::ShaderKind::ClosestHit:
  1640. bNeedsAttributes = true;
  1641. case DXIL::ShaderKind::Miss:
  1642. bNeedsPayload = true;
  1643. case DXIL::ShaderKind::Callable:
  1644. if (0 == funcProps->ShaderProps.Ray.payloadSizeInBytes) {
  1645. unsigned DiagID = bNeedsPayload ?
  1646. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1647. "shader must include inout payload structure parameter.") :
  1648. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  1649. "shader must include inout parameter structure.");
  1650. Diags.Report(FD->getLocation(), DiagID);
  1651. }
  1652. }
  1653. if (bNeedsAttributes &&
  1654. 0 == funcProps->ShaderProps.Ray.attributeSizeInBytes) {
  1655. Diags.Report(FD->getLocation(), Diags.getCustomDiagID(
  1656. DiagnosticsEngine::Error,
  1657. "shader must include attributes structure parameter."));
  1658. }
  1659. }
  1660. // Type annotation for parameters and return type.
  1661. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  1662. unsigned arrayEltSize = 0;
  1663. AddTypeAnnotation(FD->getReturnType(), dxilTypeSys, arrayEltSize);
  1664. // Type annotation for this pointer.
  1665. if (const CXXMethodDecl *MFD = dyn_cast<CXXMethodDecl>(FD)) {
  1666. const CXXRecordDecl *RD = MFD->getParent();
  1667. QualType Ty = CGM.getContext().getTypeDeclType(RD);
  1668. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1669. }
  1670. for (const ValueDecl *param : FD->params()) {
  1671. QualType Ty = param->getType();
  1672. AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  1673. }
  1674. // clear isExportedEntry if not exporting entry
  1675. bool isExportedEntry = profileAttributes != 0;
  1676. if (isExportedEntry) {
  1677. // use unmangled or mangled name depending on which is used for final entry function
  1678. StringRef name = isRay ? F->getName() : FD->getName();
  1679. if (!m_ExportMap.IsExported(name)) {
  1680. isExportedEntry = false;
  1681. }
  1682. }
  1683. // Only add functionProps when exist.
  1684. if (isExportedEntry || isEntry)
  1685. m_pHLModule->AddDxilFunctionProps(F, funcProps);
  1686. if (isPatchConstantFunction)
  1687. patchConstantFunctionPropsMap[F] = std::move(funcProps);
  1688. // Save F to entry map.
  1689. if (isExportedEntry) {
  1690. if (entryFunctionMap.count(FD->getName())) {
  1691. DiagnosticsEngine &Diags = CGM.getDiags();
  1692. unsigned DiagID = Diags.getCustomDiagID(
  1693. DiagnosticsEngine::Error,
  1694. "redefinition of %0");
  1695. Diags.Report(FD->getLocStart(), DiagID) << FD->getName();
  1696. }
  1697. auto &Entry = entryFunctionMap[FD->getNameAsString()];
  1698. Entry.SL = FD->getLocation();
  1699. Entry.Func= F;
  1700. }
  1701. // Add target-dependent experimental function attributes
  1702. for (const auto &Attr : FD->specific_attrs<HLSLExperimentalAttr>()) {
  1703. F->addFnAttr(Twine("exp-", Attr->getName()).str(), Attr->getValue());
  1704. }
  1705. }
  1706. void CGMSHLSLRuntime::RemapObsoleteSemantic(DxilParameterAnnotation &paramInfo, bool isPatchConstantFunction) {
  1707. DXASSERT(CGM.getLangOpts().EnableDX9CompatMode, "should be used only in back-compat mode");
  1708. const ShaderModel *SM = m_pHLModule->GetShaderModel();
  1709. DXIL::SigPointKind sigPointKind = SigPointFromInputQual(paramInfo.GetParamInputQual(), SM->GetKind(), isPatchConstantFunction);
  1710. hlsl::RemapObsoleteSemantic(paramInfo, sigPointKind, CGM.getLLVMContext());
  1711. }
  1712. void CGMSHLSLRuntime::EmitHLSLFunctionProlog(Function *F, const FunctionDecl *FD) {
  1713. // Support clip plane need debug info which not available when create function attribute.
  1714. if (const HLSLClipPlanesAttr *Attr = FD->getAttr<HLSLClipPlanesAttr>()) {
  1715. DxilFunctionProps &funcProps = m_pHLModule->GetDxilFunctionProps(F);
  1716. // Initialize to null.
  1717. memset(funcProps.ShaderProps.VS.clipPlanes, 0, sizeof(funcProps.ShaderProps.VS.clipPlanes));
  1718. // Create global for each clip plane, and use the clip plane val as init val.
  1719. auto AddClipPlane = [&](Expr *clipPlane, unsigned idx) {
  1720. if (DeclRefExpr *decl = dyn_cast<DeclRefExpr>(clipPlane)) {
  1721. const VarDecl *VD = cast<VarDecl>(decl->getDecl());
  1722. Constant *clipPlaneVal = CGM.GetAddrOfGlobalVar(VD);
  1723. funcProps.ShaderProps.VS.clipPlanes[idx] = clipPlaneVal;
  1724. if (m_bDebugInfo) {
  1725. CodeGenFunction CGF(CGM);
  1726. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1727. debugInfoMap[clipPlaneVal] = CGF.Builder.getCurrentDebugLocation();
  1728. }
  1729. } else {
  1730. // Must be a MemberExpr.
  1731. const MemberExpr *ME = cast<MemberExpr>(clipPlane);
  1732. CodeGenFunction CGF(CGM);
  1733. CodeGen::LValue LV = CGF.EmitMemberExpr(ME);
  1734. Value *addr = LV.getAddress();
  1735. funcProps.ShaderProps.VS.clipPlanes[idx] = cast<Constant>(addr);
  1736. if (m_bDebugInfo) {
  1737. CodeGenFunction CGF(CGM);
  1738. ApplyDebugLocation applyDebugLoc(CGF, clipPlane);
  1739. debugInfoMap[addr] = CGF.Builder.getCurrentDebugLocation();
  1740. }
  1741. }
  1742. };
  1743. if (Expr *clipPlane = Attr->getClipPlane1())
  1744. AddClipPlane(clipPlane, 0);
  1745. if (Expr *clipPlane = Attr->getClipPlane2())
  1746. AddClipPlane(clipPlane, 1);
  1747. if (Expr *clipPlane = Attr->getClipPlane3())
  1748. AddClipPlane(clipPlane, 2);
  1749. if (Expr *clipPlane = Attr->getClipPlane4())
  1750. AddClipPlane(clipPlane, 3);
  1751. if (Expr *clipPlane = Attr->getClipPlane5())
  1752. AddClipPlane(clipPlane, 4);
  1753. if (Expr *clipPlane = Attr->getClipPlane6())
  1754. AddClipPlane(clipPlane, 5);
  1755. clipPlaneFuncList.emplace_back(F);
  1756. }
  1757. // Update function linkage based on DefaultLinkage
  1758. // We will take care of patch constant functions later, once identified for certain.
  1759. if (!m_pHLModule->HasDxilFunctionProps(F)) {
  1760. if (F->getLinkage() == GlobalValue::LinkageTypes::ExternalLinkage) {
  1761. if (!FD->hasAttr<HLSLExportAttr>()) {
  1762. switch (CGM.getCodeGenOpts().DefaultLinkage) {
  1763. case DXIL::DefaultLinkage::Default:
  1764. if (m_pHLModule->GetShaderModel()->GetMinor() != ShaderModel::kOfflineMinor)
  1765. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  1766. break;
  1767. case DXIL::DefaultLinkage::Internal:
  1768. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  1769. break;
  1770. }
  1771. }
  1772. }
  1773. }
  1774. }
  1775. void CGMSHLSLRuntime::AddControlFlowHint(CodeGenFunction &CGF, const Stmt &S,
  1776. llvm::TerminatorInst *TI,
  1777. ArrayRef<const Attr *> Attrs) {
  1778. // Build hints.
  1779. bool bNoBranchFlatten = true;
  1780. bool bBranch = false;
  1781. bool bFlatten = false;
  1782. std::vector<DXIL::ControlFlowHint> hints;
  1783. for (const auto *Attr : Attrs) {
  1784. if (isa<HLSLBranchAttr>(Attr)) {
  1785. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1786. bNoBranchFlatten = false;
  1787. bBranch = true;
  1788. }
  1789. else if (isa<HLSLFlattenAttr>(Attr)) {
  1790. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1791. bNoBranchFlatten = false;
  1792. bFlatten = true;
  1793. } else if (isa<HLSLForceCaseAttr>(Attr)) {
  1794. if (isa<SwitchStmt>(&S)) {
  1795. hints.emplace_back(DXIL::ControlFlowHint::ForceCase);
  1796. }
  1797. }
  1798. // Ignore fastopt, allow_uav_condition and call for now.
  1799. }
  1800. if (bNoBranchFlatten) {
  1801. // CHECK control flow option.
  1802. if (CGF.CGM.getCodeGenOpts().HLSLPreferControlFlow)
  1803. hints.emplace_back(DXIL::ControlFlowHint::Branch);
  1804. else if (CGF.CGM.getCodeGenOpts().HLSLAvoidControlFlow)
  1805. hints.emplace_back(DXIL::ControlFlowHint::Flatten);
  1806. }
  1807. if (bFlatten && bBranch) {
  1808. DiagnosticsEngine &Diags = CGM.getDiags();
  1809. unsigned DiagID = Diags.getCustomDiagID(
  1810. DiagnosticsEngine::Error,
  1811. "can't use branch and flatten attributes together");
  1812. Diags.Report(S.getLocStart(), DiagID);
  1813. }
  1814. if (hints.size()) {
  1815. // Add meta data to the instruction.
  1816. MDNode *hintsNode = DxilMDHelper::EmitControlFlowHints(Context, hints);
  1817. TI->setMetadata(DxilMDHelper::kDxilControlFlowHintMDName, hintsNode);
  1818. }
  1819. }
  1820. void CGMSHLSLRuntime::FinishAutoVar(CodeGenFunction &CGF, const VarDecl &D, llvm::Value *V) {
  1821. if (D.hasAttr<HLSLPreciseAttr>()) {
  1822. AllocaInst *AI = cast<AllocaInst>(V);
  1823. HLModule::MarkPreciseAttributeWithMetadata(AI);
  1824. }
  1825. // Add type annotation for local variable.
  1826. DxilTypeSystem &typeSys = m_pHLModule->GetTypeSystem();
  1827. unsigned arrayEltSize = 0;
  1828. AddTypeAnnotation(D.getType(), typeSys, arrayEltSize);
  1829. }
  1830. hlsl::InterpolationMode CGMSHLSLRuntime::GetInterpMode(const Decl *decl,
  1831. CompType compType,
  1832. bool bKeepUndefined) {
  1833. InterpolationMode Interp(
  1834. decl->hasAttr<HLSLNoInterpolationAttr>(), decl->hasAttr<HLSLLinearAttr>(),
  1835. decl->hasAttr<HLSLNoPerspectiveAttr>(), decl->hasAttr<HLSLCentroidAttr>(),
  1836. decl->hasAttr<HLSLSampleAttr>());
  1837. DXASSERT(Interp.IsValid(), "otherwise front-end missing validation");
  1838. if (Interp.IsUndefined() && !bKeepUndefined) {
  1839. // Type-based default: linear for floats, constant for others.
  1840. if (compType.IsFloatTy())
  1841. Interp = InterpolationMode::Kind::Linear;
  1842. else
  1843. Interp = InterpolationMode::Kind::Constant;
  1844. }
  1845. return Interp;
  1846. }
  1847. hlsl::CompType CGMSHLSLRuntime::GetCompType(const BuiltinType *BT) {
  1848. hlsl::CompType ElementType = hlsl::CompType::getInvalid();
  1849. switch (BT->getKind()) {
  1850. case BuiltinType::Bool:
  1851. ElementType = hlsl::CompType::getI1();
  1852. break;
  1853. case BuiltinType::Double:
  1854. ElementType = hlsl::CompType::getF64();
  1855. break;
  1856. case BuiltinType::HalfFloat: // HLSL Change
  1857. case BuiltinType::Float:
  1858. ElementType = hlsl::CompType::getF32();
  1859. break;
  1860. // HLSL Changes begin
  1861. case BuiltinType::Min10Float:
  1862. case BuiltinType::Min16Float:
  1863. // HLSL Changes end
  1864. case BuiltinType::Half:
  1865. ElementType = hlsl::CompType::getF16();
  1866. break;
  1867. case BuiltinType::Int:
  1868. ElementType = hlsl::CompType::getI32();
  1869. break;
  1870. case BuiltinType::LongLong:
  1871. ElementType = hlsl::CompType::getI64();
  1872. break;
  1873. // HLSL Changes begin
  1874. case BuiltinType::Min12Int:
  1875. case BuiltinType::Min16Int:
  1876. // HLSL Changes end
  1877. case BuiltinType::Short:
  1878. ElementType = hlsl::CompType::getI16();
  1879. break;
  1880. case BuiltinType::UInt:
  1881. ElementType = hlsl::CompType::getU32();
  1882. break;
  1883. case BuiltinType::ULongLong:
  1884. ElementType = hlsl::CompType::getU64();
  1885. break;
  1886. case BuiltinType::Min16UInt: // HLSL Change
  1887. case BuiltinType::UShort:
  1888. ElementType = hlsl::CompType::getU16();
  1889. break;
  1890. default:
  1891. llvm_unreachable("unsupported type");
  1892. break;
  1893. }
  1894. return ElementType;
  1895. }
  1896. /// Add resource to the program
  1897. void CGMSHLSLRuntime::addResource(Decl *D) {
  1898. if (HLSLBufferDecl *BD = dyn_cast<HLSLBufferDecl>(D))
  1899. GetOrCreateCBuffer(BD);
  1900. else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  1901. hlsl::DxilResourceBase::Class resClass = TypeToClass(VD->getType());
  1902. // skip decl has init which is resource.
  1903. if (VD->hasInit() && resClass != DXIL::ResourceClass::Invalid)
  1904. return;
  1905. // skip static global.
  1906. if (!VD->hasExternalFormalLinkage()) {
  1907. if (VD->hasInit() && VD->getType().isConstQualified()) {
  1908. Expr* InitExp = VD->getInit();
  1909. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1910. // Only save const static global of struct type.
  1911. if (GV->getType()->getElementType()->isStructTy()) {
  1912. staticConstGlobalInitMap[InitExp] = GV;
  1913. }
  1914. }
  1915. return;
  1916. }
  1917. if (D->hasAttr<HLSLGroupSharedAttr>()) {
  1918. GlobalVariable *GV = cast<GlobalVariable>(CGM.GetAddrOfGlobalVar(VD));
  1919. m_pHLModule->AddGroupSharedVariable(GV);
  1920. return;
  1921. }
  1922. switch (resClass) {
  1923. case hlsl::DxilResourceBase::Class::Sampler:
  1924. AddSampler(VD);
  1925. break;
  1926. case hlsl::DxilResourceBase::Class::UAV:
  1927. case hlsl::DxilResourceBase::Class::SRV:
  1928. AddUAVSRV(VD, resClass);
  1929. break;
  1930. case hlsl::DxilResourceBase::Class::Invalid: {
  1931. // normal global constant, add to global CB
  1932. HLCBuffer &globalCB = GetGlobalCBuffer();
  1933. AddConstant(VD, globalCB);
  1934. break;
  1935. }
  1936. case DXIL::ResourceClass::CBuffer:
  1937. DXASSERT(0, "cbuffer should not be here");
  1938. break;
  1939. }
  1940. }
  1941. }
  1942. /// Add subobject to the module
  1943. void CGMSHLSLRuntime::addSubobject(Decl *D) {
  1944. VarDecl *VD = dyn_cast<VarDecl>(D);
  1945. DXASSERT(VD != nullptr, "must be a global variable");
  1946. if (CGM.getCodeGenOpts().HLSLValidatorMajorVer == 1 &&
  1947. CGM.getCodeGenOpts().HLSLValidatorMinorVer < 4) {
  1948. // subobjects unsupported with this validator
  1949. DiagnosticsEngine &Diags = CGM.getDiags();
  1950. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "subobjects are not supported by current validator version");
  1951. Diags.Report(D->getLocStart(), DiagID);
  1952. return;
  1953. }
  1954. DXIL::SubobjectKind subobjKind;
  1955. DXIL::HitGroupType hgType;
  1956. if (!hlsl::GetHLSLSubobjectKind(VD->getType(), subobjKind, hgType)) {
  1957. DXASSERT(false, "not a valid subobject declaration");
  1958. return;
  1959. }
  1960. Expr *initExpr = const_cast<Expr*>(VD->getAnyInitializer());
  1961. if (!initExpr) {
  1962. DiagnosticsEngine &Diags = CGM.getDiags();
  1963. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "subobject needs to be initialized");
  1964. Diags.Report(D->getLocStart(), DiagID);
  1965. return;
  1966. }
  1967. if (InitListExpr *initListExpr = dyn_cast<InitListExpr>(initExpr)) {
  1968. try {
  1969. CreateSubobject(subobjKind, VD->getName(), initListExpr->getInits(), initListExpr->getNumInits(), hgType);
  1970. } catch (hlsl::Exception&) {
  1971. DiagnosticsEngine &Diags = CGM.getDiags();
  1972. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "internal error creating subobject");
  1973. Diags.Report(initExpr->getLocStart(), DiagID);
  1974. return;
  1975. }
  1976. }
  1977. else {
  1978. DiagnosticsEngine &Diags = CGM.getDiags();
  1979. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "expected initialization list");
  1980. Diags.Report(initExpr->getLocStart(), DiagID);
  1981. return;
  1982. }
  1983. }
  1984. // TODO: collect such helper utility functions in one place.
  1985. static DxilResourceBase::Class KeywordToClass(const std::string &keyword) {
  1986. // TODO: refactor for faster search (switch by 1/2/3 first letters, then
  1987. // compare)
  1988. if (keyword == "SamplerState")
  1989. return DxilResourceBase::Class::Sampler;
  1990. if (keyword == "SamplerComparisonState")
  1991. return DxilResourceBase::Class::Sampler;
  1992. if (keyword == "ConstantBuffer")
  1993. return DxilResourceBase::Class::CBuffer;
  1994. if (keyword == "TextureBuffer")
  1995. return DxilResourceBase::Class::SRV;
  1996. bool isSRV = keyword == "Buffer";
  1997. isSRV |= keyword == "ByteAddressBuffer";
  1998. isSRV |= keyword == "RaytracingAccelerationStructure";
  1999. isSRV |= keyword == "StructuredBuffer";
  2000. isSRV |= keyword == "Texture1D";
  2001. isSRV |= keyword == "Texture1DArray";
  2002. isSRV |= keyword == "Texture2D";
  2003. isSRV |= keyword == "Texture2DArray";
  2004. isSRV |= keyword == "Texture3D";
  2005. isSRV |= keyword == "TextureCube";
  2006. isSRV |= keyword == "TextureCubeArray";
  2007. isSRV |= keyword == "Texture2DMS";
  2008. isSRV |= keyword == "Texture2DMSArray";
  2009. if (isSRV)
  2010. return DxilResourceBase::Class::SRV;
  2011. bool isUAV = keyword == "RWBuffer";
  2012. isUAV |= keyword == "RWByteAddressBuffer";
  2013. isUAV |= keyword == "RWStructuredBuffer";
  2014. isUAV |= keyword == "RWTexture1D";
  2015. isUAV |= keyword == "RWTexture1DArray";
  2016. isUAV |= keyword == "RWTexture2D";
  2017. isUAV |= keyword == "RWTexture2DArray";
  2018. isUAV |= keyword == "RWTexture3D";
  2019. isUAV |= keyword == "RWTextureCube";
  2020. isUAV |= keyword == "RWTextureCubeArray";
  2021. isUAV |= keyword == "RWTexture2DMS";
  2022. isUAV |= keyword == "RWTexture2DMSArray";
  2023. isUAV |= keyword == "AppendStructuredBuffer";
  2024. isUAV |= keyword == "ConsumeStructuredBuffer";
  2025. isUAV |= keyword == "RasterizerOrderedBuffer";
  2026. isUAV |= keyword == "RasterizerOrderedByteAddressBuffer";
  2027. isUAV |= keyword == "RasterizerOrderedStructuredBuffer";
  2028. isUAV |= keyword == "RasterizerOrderedTexture1D";
  2029. isUAV |= keyword == "RasterizerOrderedTexture1DArray";
  2030. isUAV |= keyword == "RasterizerOrderedTexture2D";
  2031. isUAV |= keyword == "RasterizerOrderedTexture2DArray";
  2032. isUAV |= keyword == "RasterizerOrderedTexture3D";
  2033. if (isUAV)
  2034. return DxilResourceBase::Class::UAV;
  2035. return DxilResourceBase::Class::Invalid;
  2036. }
  2037. // This should probably be refactored to ASTContextHLSL, and follow types
  2038. // rather than do string comparisons.
  2039. DXIL::ResourceClass
  2040. hlsl::GetResourceClassForType(const clang::ASTContext &context,
  2041. clang::QualType Ty) {
  2042. Ty = Ty.getCanonicalType();
  2043. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2044. return GetResourceClassForType(context, arrayType->getElementType());
  2045. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2046. return KeywordToClass(RT->getDecl()->getName());
  2047. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2048. if (const ClassTemplateSpecializationDecl *templateDecl =
  2049. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2050. return KeywordToClass(templateDecl->getName());
  2051. }
  2052. }
  2053. return hlsl::DxilResourceBase::Class::Invalid;
  2054. }
  2055. hlsl::DxilResourceBase::Class CGMSHLSLRuntime::TypeToClass(clang::QualType Ty) {
  2056. return hlsl::GetResourceClassForType(CGM.getContext(), Ty);
  2057. }
  2058. namespace {
  2059. void GetResourceDeclElemTypeAndRangeSize(CodeGenModule &CGM, HLModule &HL, VarDecl &VD,
  2060. QualType &ElemType, unsigned& rangeSize) {
  2061. ElemType = VD.getType().getCanonicalType();
  2062. rangeSize = 1;
  2063. while (const clang::ArrayType *arrayType = CGM.getContext().getAsArrayType(ElemType)) {
  2064. if (rangeSize != UINT_MAX) {
  2065. if (arrayType->isConstantArrayType()) {
  2066. rangeSize *= cast<ConstantArrayType>(arrayType)->getSize().getLimitedValue();
  2067. }
  2068. else {
  2069. if (HL.GetHLOptions().bLegacyResourceReservation) {
  2070. DiagnosticsEngine &Diags = CGM.getDiags();
  2071. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2072. "unbounded resources are not supported with -flegacy-resource-reservation");
  2073. Diags.Report(VD.getLocation(), DiagID);
  2074. }
  2075. rangeSize = UINT_MAX;
  2076. }
  2077. }
  2078. ElemType = arrayType->getElementType();
  2079. }
  2080. }
  2081. }
  2082. uint32_t CGMSHLSLRuntime::AddSampler(VarDecl *samplerDecl) {
  2083. llvm::GlobalVariable *val =
  2084. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(samplerDecl));
  2085. unique_ptr<DxilSampler> hlslRes(new DxilSampler);
  2086. hlslRes->SetLowerBound(UINT_MAX);
  2087. hlslRes->SetGlobalSymbol(val);
  2088. hlslRes->SetGlobalName(samplerDecl->getName());
  2089. QualType VarTy;
  2090. unsigned rangeSize;
  2091. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *samplerDecl,
  2092. VarTy, rangeSize);
  2093. hlslRes->SetRangeSize(rangeSize);
  2094. const RecordType *RT = VarTy->getAs<RecordType>();
  2095. DxilSampler::SamplerKind kind = KeywordToSamplerKind(RT->getDecl()->getName());
  2096. hlslRes->SetSamplerKind(kind);
  2097. for (hlsl::UnusualAnnotation *it : samplerDecl->getUnusualAnnotations()) {
  2098. switch (it->getKind()) {
  2099. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2100. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2101. hlslRes->SetLowerBound(ra->RegisterNumber);
  2102. hlslRes->SetSpaceID(ra->RegisterSpace);
  2103. break;
  2104. }
  2105. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2106. // Ignore Semantics
  2107. break;
  2108. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2109. // Should be handled by front-end
  2110. llvm_unreachable("packoffset on sampler");
  2111. break;
  2112. default:
  2113. llvm_unreachable("unknown UnusualAnnotation on sampler");
  2114. break;
  2115. }
  2116. }
  2117. hlslRes->SetID(m_pHLModule->GetSamplers().size());
  2118. return m_pHLModule->AddSampler(std::move(hlslRes));
  2119. }
  2120. bool CGMSHLSLRuntime::GetAsConstantUInt32(clang::Expr *expr, uint32_t *value) {
  2121. APSInt result;
  2122. if (!expr->EvaluateAsInt(result, CGM.getContext())) {
  2123. DiagnosticsEngine &Diags = CGM.getDiags();
  2124. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2125. "cannot convert to constant unsigned int");
  2126. Diags.Report(expr->getLocStart(), DiagID);
  2127. return false;
  2128. }
  2129. *value = result.getLimitedValue(UINT32_MAX);
  2130. return true;
  2131. }
  2132. bool CGMSHLSLRuntime::GetAsConstantString(clang::Expr *expr, StringRef *value, bool failWhenEmpty /*=false*/) {
  2133. Expr::EvalResult result;
  2134. DiagnosticsEngine &Diags = CGM.getDiags();
  2135. unsigned DiagID = 0;
  2136. if (expr->EvaluateAsRValue(result, CGM.getContext())) {
  2137. if (result.Val.isLValue()) {
  2138. DXASSERT_NOMSG(result.Val.getLValueOffset().isZero());
  2139. DXASSERT_NOMSG(result.Val.getLValueCallIndex() == 0);
  2140. const Expr *evExpr = result.Val.getLValueBase().get<const Expr *>();
  2141. if (const StringLiteral *strLit = dyn_cast<const StringLiteral>(evExpr)) {
  2142. *value = strLit->getBytes();
  2143. if (!failWhenEmpty || !(*value).empty()) {
  2144. return true;
  2145. }
  2146. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "empty string not expected here");
  2147. }
  2148. }
  2149. }
  2150. if (!DiagID)
  2151. DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, "cannot convert to constant string");
  2152. Diags.Report(expr->getLocStart(), DiagID);
  2153. return false;
  2154. }
  2155. std::vector<StringRef> CGMSHLSLRuntime::ParseSubobjectExportsAssociations(StringRef exports) {
  2156. std::vector<StringRef> parsedExports;
  2157. const char *pData = exports.data();
  2158. const char *pEnd = pData + exports.size();
  2159. const char *pLast = pData;
  2160. while (pData < pEnd) {
  2161. if (*pData == ';') {
  2162. if (pLast < pData) {
  2163. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2164. }
  2165. pLast = pData + 1;
  2166. }
  2167. pData++;
  2168. }
  2169. if (pLast < pData) {
  2170. parsedExports.emplace_back(StringRef(pLast, pData - pLast));
  2171. }
  2172. return std::move(parsedExports);
  2173. }
  2174. void CGMSHLSLRuntime::CreateSubobject(DXIL::SubobjectKind kind, const StringRef name,
  2175. clang::Expr **args, unsigned int argCount,
  2176. DXIL::HitGroupType hgType /*= (DXIL::HitGroupType)(-1)*/) {
  2177. DxilSubobjects *subobjects = m_pHLModule->GetSubobjects();
  2178. if (!subobjects) {
  2179. subobjects = new DxilSubobjects();
  2180. m_pHLModule->ResetSubobjects(subobjects);
  2181. }
  2182. DxilRootSignatureCompilationFlags flags = DxilRootSignatureCompilationFlags::GlobalRootSignature;
  2183. switch (kind) {
  2184. case DXIL::SubobjectKind::StateObjectConfig: {
  2185. uint32_t flags;
  2186. DXASSERT_NOMSG(argCount == 1);
  2187. if (GetAsConstantUInt32(args[0], &flags)) {
  2188. subobjects->CreateStateObjectConfig(name, flags);
  2189. }
  2190. break;
  2191. }
  2192. case DXIL::SubobjectKind::LocalRootSignature:
  2193. flags = DxilRootSignatureCompilationFlags::LocalRootSignature;
  2194. __fallthrough;
  2195. case DXIL::SubobjectKind::GlobalRootSignature: {
  2196. DXASSERT_NOMSG(argCount == 1);
  2197. StringRef signature;
  2198. if (!GetAsConstantString(args[0], &signature, true))
  2199. return;
  2200. RootSignatureHandle RootSigHandle;
  2201. CompileRootSignature(signature, CGM.getDiags(), args[0]->getLocStart(), rootSigVer, flags, &RootSigHandle);
  2202. if (!RootSigHandle.IsEmpty()) {
  2203. RootSigHandle.EnsureSerializedAvailable();
  2204. subobjects->CreateRootSignature(name, kind == DXIL::SubobjectKind::LocalRootSignature,
  2205. RootSigHandle.GetSerializedBytes(), RootSigHandle.GetSerializedSize(), &signature);
  2206. }
  2207. break;
  2208. }
  2209. case DXIL::SubobjectKind::SubobjectToExportsAssociation: {
  2210. DXASSERT_NOMSG(argCount == 2);
  2211. StringRef subObjName, exports;
  2212. if (!GetAsConstantString(args[0], &subObjName, true) ||
  2213. !GetAsConstantString(args[1], &exports, false))
  2214. return;
  2215. std::vector<StringRef> exportList = ParseSubobjectExportsAssociations(exports);
  2216. subobjects->CreateSubobjectToExportsAssociation(name, subObjName, exportList.data(), exportList.size());
  2217. break;
  2218. }
  2219. case DXIL::SubobjectKind::RaytracingShaderConfig: {
  2220. DXASSERT_NOMSG(argCount == 2);
  2221. uint32_t maxPayloadSize;
  2222. uint32_t MaxAttributeSize;
  2223. if (!GetAsConstantUInt32(args[0], &maxPayloadSize) ||
  2224. !GetAsConstantUInt32(args[1], &MaxAttributeSize))
  2225. return;
  2226. subobjects->CreateRaytracingShaderConfig(name, maxPayloadSize, MaxAttributeSize);
  2227. break;
  2228. }
  2229. case DXIL::SubobjectKind::RaytracingPipelineConfig: {
  2230. DXASSERT_NOMSG(argCount == 1);
  2231. uint32_t maxTraceRecursionDepth;
  2232. if (!GetAsConstantUInt32(args[0], &maxTraceRecursionDepth))
  2233. return;
  2234. subobjects->CreateRaytracingPipelineConfig(name, maxTraceRecursionDepth);
  2235. break;
  2236. }
  2237. case DXIL::SubobjectKind::HitGroup: {
  2238. switch (hgType) {
  2239. case DXIL::HitGroupType::Triangle: {
  2240. DXASSERT_NOMSG(argCount == 2);
  2241. StringRef anyhit, closesthit;
  2242. if (!GetAsConstantString(args[0], &anyhit) ||
  2243. !GetAsConstantString(args[1], &closesthit))
  2244. return;
  2245. subobjects->CreateHitGroup(name, DXIL::HitGroupType::Triangle, anyhit, closesthit, llvm::StringRef(""));
  2246. break;
  2247. }
  2248. case DXIL::HitGroupType::ProceduralPrimitive: {
  2249. DXASSERT_NOMSG(argCount == 3);
  2250. StringRef anyhit, closesthit, intersection;
  2251. if (!GetAsConstantString(args[0], &anyhit) ||
  2252. !GetAsConstantString(args[1], &closesthit) ||
  2253. !GetAsConstantString(args[2], &intersection, true))
  2254. return;
  2255. subobjects->CreateHitGroup(name, DXIL::HitGroupType::ProceduralPrimitive, anyhit, closesthit, intersection);
  2256. break;
  2257. }
  2258. default:
  2259. llvm_unreachable("unknown HitGroupType");
  2260. }
  2261. break;
  2262. }
  2263. default:
  2264. llvm_unreachable("unknown SubobjectKind");
  2265. break;
  2266. }
  2267. }
  2268. static void CollectScalarTypes(std::vector<QualType> &ScalarTys, QualType Ty) {
  2269. if (Ty->isRecordType()) {
  2270. if (hlsl::IsHLSLMatType(Ty)) {
  2271. QualType EltTy = hlsl::GetHLSLMatElementType(Ty);
  2272. unsigned row = 0;
  2273. unsigned col = 0;
  2274. hlsl::GetRowsAndCols(Ty, row, col);
  2275. unsigned size = col*row;
  2276. for (unsigned i = 0; i < size; i++) {
  2277. CollectScalarTypes(ScalarTys, EltTy);
  2278. }
  2279. } else if (hlsl::IsHLSLVecType(Ty)) {
  2280. QualType EltTy = hlsl::GetHLSLVecElementType(Ty);
  2281. unsigned row = 0;
  2282. unsigned col = 0;
  2283. hlsl::GetRowsAndColsForAny(Ty, row, col);
  2284. unsigned size = col;
  2285. for (unsigned i = 0; i < size; i++) {
  2286. CollectScalarTypes(ScalarTys, EltTy);
  2287. }
  2288. } else {
  2289. const RecordType *RT = Ty->getAsStructureType();
  2290. // For CXXRecord.
  2291. if (!RT)
  2292. RT = Ty->getAs<RecordType>();
  2293. RecordDecl *RD = RT->getDecl();
  2294. for (FieldDecl *field : RD->fields())
  2295. CollectScalarTypes(ScalarTys, field->getType());
  2296. }
  2297. } else if (Ty->isArrayType()) {
  2298. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  2299. QualType EltTy = AT->getElementType();
  2300. // Set it to 5 for unsized array.
  2301. unsigned size = 5;
  2302. if (AT->isConstantArrayType()) {
  2303. size = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  2304. }
  2305. for (unsigned i=0;i<size;i++) {
  2306. CollectScalarTypes(ScalarTys, EltTy);
  2307. }
  2308. } else {
  2309. ScalarTys.emplace_back(Ty);
  2310. }
  2311. }
  2312. bool CGMSHLSLRuntime::SetUAVSRV(SourceLocation loc,
  2313. hlsl::DxilResourceBase::Class resClass,
  2314. DxilResource *hlslRes, const RecordDecl *RD) {
  2315. hlsl::DxilResource::Kind kind = KeywordToKind(RD->getName());
  2316. hlslRes->SetKind(kind);
  2317. // Get the result type from handle field.
  2318. FieldDecl *FD = *(RD->field_begin());
  2319. DXASSERT(FD->getName() == "h", "must be handle field");
  2320. QualType resultTy = FD->getType();
  2321. // Type annotation for result type of resource.
  2322. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2323. unsigned arrayEltSize = 0;
  2324. AddTypeAnnotation(QualType(RD->getTypeForDecl(),0), dxilTypeSys, arrayEltSize);
  2325. if (kind == hlsl::DxilResource::Kind::Texture2DMS ||
  2326. kind == hlsl::DxilResource::Kind::Texture2DMSArray) {
  2327. const ClassTemplateSpecializationDecl *templateDecl =
  2328. cast<ClassTemplateSpecializationDecl>(RD);
  2329. const clang::TemplateArgument &sampleCountArg =
  2330. templateDecl->getTemplateArgs()[1];
  2331. uint32_t sampleCount = sampleCountArg.getAsIntegral().getLimitedValue();
  2332. hlslRes->SetSampleCount(sampleCount);
  2333. }
  2334. if (hlsl::DxilResource::IsAnyTexture(kind)) {
  2335. const ClassTemplateSpecializationDecl *templateDecl = cast<ClassTemplateSpecializationDecl>(RD);
  2336. const clang::TemplateArgument &texelTyArg = templateDecl->getTemplateArgs()[0];
  2337. llvm::Type *texelTy = CGM.getTypes().ConvertType(texelTyArg.getAsType());
  2338. if (!texelTy->isFloatingPointTy() && !texelTy->isIntegerTy()
  2339. && !hlsl::IsHLSLVecType(texelTyArg.getAsType())) {
  2340. DiagnosticsEngine &Diags = CGM.getDiags();
  2341. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2342. "texture resource texel type must be scalar or vector");
  2343. Diags.Report(loc, DiagID);
  2344. return false;
  2345. }
  2346. }
  2347. if (kind != hlsl::DxilResource::Kind::StructuredBuffer) {
  2348. QualType Ty = resultTy;
  2349. QualType EltTy = Ty;
  2350. if (hlsl::IsHLSLVecType(Ty)) {
  2351. EltTy = hlsl::GetHLSLVecElementType(Ty);
  2352. } else if (hlsl::IsHLSLMatType(Ty)) {
  2353. EltTy = hlsl::GetHLSLMatElementType(Ty);
  2354. } else if (hlsl::IsHLSLAggregateType(resultTy)) {
  2355. // Struct or array in a none-struct resource.
  2356. std::vector<QualType> ScalarTys;
  2357. CollectScalarTypes(ScalarTys, resultTy);
  2358. unsigned size = ScalarTys.size();
  2359. if (size == 0) {
  2360. DiagnosticsEngine &Diags = CGM.getDiags();
  2361. unsigned DiagID = Diags.getCustomDiagID(
  2362. DiagnosticsEngine::Error,
  2363. "object's templated type must have at least one element");
  2364. Diags.Report(loc, DiagID);
  2365. return false;
  2366. }
  2367. if (size > 4) {
  2368. DiagnosticsEngine &Diags = CGM.getDiags();
  2369. unsigned DiagID = Diags.getCustomDiagID(
  2370. DiagnosticsEngine::Error, "elements of typed buffers and textures "
  2371. "must fit in four 32-bit quantities");
  2372. Diags.Report(loc, DiagID);
  2373. return false;
  2374. }
  2375. EltTy = ScalarTys[0];
  2376. for (QualType ScalarTy : ScalarTys) {
  2377. if (ScalarTy != EltTy) {
  2378. DiagnosticsEngine &Diags = CGM.getDiags();
  2379. unsigned DiagID = Diags.getCustomDiagID(
  2380. DiagnosticsEngine::Error,
  2381. "all template type components must have the same type");
  2382. Diags.Report(loc, DiagID);
  2383. return false;
  2384. }
  2385. }
  2386. }
  2387. EltTy = EltTy.getCanonicalType();
  2388. bool bSNorm = false;
  2389. bool bHasNormAttribute = hlsl::HasHLSLUNormSNorm(Ty, &bSNorm);
  2390. if (EltTy->isBuiltinType()) {
  2391. const BuiltinType *BTy = EltTy->getAs<BuiltinType>();
  2392. CompType::Kind kind = BuiltinTyToCompTy(BTy, bHasNormAttribute && bSNorm, bHasNormAttribute && !bSNorm);
  2393. // 64bits types are implemented with u32.
  2394. if (kind == CompType::Kind::U64 || kind == CompType::Kind::I64 ||
  2395. kind == CompType::Kind::SNormF64 ||
  2396. kind == CompType::Kind::UNormF64 || kind == CompType::Kind::F64) {
  2397. kind = CompType::Kind::U32;
  2398. }
  2399. hlslRes->SetCompType(kind);
  2400. } else {
  2401. DXASSERT(!bHasNormAttribute, "snorm/unorm on invalid type");
  2402. }
  2403. }
  2404. hlslRes->SetROV(RD->getName().startswith("RasterizerOrdered"));
  2405. if (kind == hlsl::DxilResource::Kind::TypedBuffer ||
  2406. kind == hlsl::DxilResource::Kind::StructuredBuffer) {
  2407. const ClassTemplateSpecializationDecl *templateDecl =
  2408. cast<ClassTemplateSpecializationDecl>(RD);
  2409. const clang::TemplateArgument &retTyArg =
  2410. templateDecl->getTemplateArgs()[0];
  2411. llvm::Type *retTy = CGM.getTypes().ConvertType(retTyArg.getAsType());
  2412. uint32_t strideInBytes = dataLayout.getTypeAllocSize(retTy);
  2413. hlslRes->SetElementStride(strideInBytes);
  2414. }
  2415. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2416. if (hlslRes->IsGloballyCoherent()) {
  2417. DiagnosticsEngine &Diags = CGM.getDiags();
  2418. unsigned DiagID = Diags.getCustomDiagID(
  2419. DiagnosticsEngine::Error, "globallycoherent can only be used with "
  2420. "Unordered Access View buffers.");
  2421. Diags.Report(loc, DiagID);
  2422. return false;
  2423. }
  2424. hlslRes->SetRW(false);
  2425. hlslRes->SetID(m_pHLModule->GetSRVs().size());
  2426. } else {
  2427. hlslRes->SetRW(true);
  2428. hlslRes->SetID(m_pHLModule->GetUAVs().size());
  2429. }
  2430. return true;
  2431. }
  2432. uint32_t CGMSHLSLRuntime::AddUAVSRV(VarDecl *decl,
  2433. hlsl::DxilResourceBase::Class resClass) {
  2434. llvm::GlobalVariable *val =
  2435. cast<llvm::GlobalVariable>(CGM.GetAddrOfGlobalVar(decl));
  2436. unique_ptr<HLResource> hlslRes(new HLResource);
  2437. hlslRes->SetLowerBound(UINT_MAX);
  2438. hlslRes->SetGlobalSymbol(val);
  2439. hlslRes->SetGlobalName(decl->getName());
  2440. QualType VarTy;
  2441. unsigned rangeSize;
  2442. GetResourceDeclElemTypeAndRangeSize(CGM, *m_pHLModule, *decl,
  2443. VarTy, rangeSize);
  2444. hlslRes->SetRangeSize(rangeSize);
  2445. for (hlsl::UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  2446. switch (it->getKind()) {
  2447. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2448. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2449. hlslRes->SetLowerBound(ra->RegisterNumber);
  2450. hlslRes->SetSpaceID(ra->RegisterSpace);
  2451. break;
  2452. }
  2453. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2454. // Ignore Semantics
  2455. break;
  2456. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2457. // Should be handled by front-end
  2458. llvm_unreachable("packoffset on uav/srv");
  2459. break;
  2460. default:
  2461. llvm_unreachable("unknown UnusualAnnotation on uav/srv");
  2462. break;
  2463. }
  2464. }
  2465. const RecordType *RT = VarTy->getAs<RecordType>();
  2466. RecordDecl *RD = RT->getDecl();
  2467. if (decl->hasAttr<HLSLGloballyCoherentAttr>()) {
  2468. hlslRes->SetGloballyCoherent(true);
  2469. }
  2470. if (!SetUAVSRV(decl->getLocation(), resClass, hlslRes.get(), RD))
  2471. return 0;
  2472. if (resClass == hlsl::DxilResourceBase::Class::SRV) {
  2473. return m_pHLModule->AddSRV(std::move(hlslRes));
  2474. } else {
  2475. return m_pHLModule->AddUAV(std::move(hlslRes));
  2476. }
  2477. }
  2478. static bool IsResourceInType(const clang::ASTContext &context,
  2479. clang::QualType Ty) {
  2480. Ty = Ty.getCanonicalType();
  2481. if (const clang::ArrayType *arrayType = context.getAsArrayType(Ty)) {
  2482. return IsResourceInType(context, arrayType->getElementType());
  2483. } else if (const RecordType *RT = Ty->getAsStructureType()) {
  2484. if (KeywordToClass(RT->getDecl()->getName()) != DxilResourceBase::Class::Invalid)
  2485. return true;
  2486. const CXXRecordDecl* typeRecordDecl = RT->getAsCXXRecordDecl();
  2487. if (typeRecordDecl && !typeRecordDecl->isImplicit()) {
  2488. for (auto field : typeRecordDecl->fields()) {
  2489. if (IsResourceInType(context, field->getType()))
  2490. return true;
  2491. }
  2492. }
  2493. } else if (const RecordType *RT = Ty->getAs<RecordType>()) {
  2494. if (const ClassTemplateSpecializationDecl *templateDecl =
  2495. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl())) {
  2496. if (KeywordToClass(templateDecl->getName()) != DxilResourceBase::Class::Invalid)
  2497. return true;
  2498. }
  2499. }
  2500. return false; // no resources found
  2501. }
  2502. void CGMSHLSLRuntime::AddConstant(VarDecl *constDecl, HLCBuffer &CB) {
  2503. if (constDecl->getStorageClass() == SC_Static) {
  2504. // For static inside cbuffer, take as global static.
  2505. // Don't add to cbuffer.
  2506. CGM.EmitGlobal(constDecl);
  2507. // Add type annotation for static global types.
  2508. // May need it when cast from cbuf.
  2509. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2510. unsigned arraySize = 0;
  2511. AddTypeAnnotation(constDecl->getType(), dxilTypeSys, arraySize);
  2512. return;
  2513. }
  2514. // Search defined structure for resource objects and fail
  2515. if (CB.GetRangeSize() > 1 &&
  2516. IsResourceInType(CGM.getContext(), constDecl->getType())) {
  2517. DiagnosticsEngine &Diags = CGM.getDiags();
  2518. unsigned DiagID = Diags.getCustomDiagID(
  2519. DiagnosticsEngine::Error,
  2520. "object types not supported in cbuffer/tbuffer view arrays.");
  2521. Diags.Report(constDecl->getLocation(), DiagID);
  2522. return;
  2523. }
  2524. llvm::Constant *constVal = CGM.GetAddrOfGlobalVar(constDecl);
  2525. bool isGlobalCB = CB.GetID() == globalCBIndex;
  2526. uint32_t offset = 0;
  2527. bool userOffset = false;
  2528. for (hlsl::UnusualAnnotation *it : constDecl->getUnusualAnnotations()) {
  2529. switch (it->getKind()) {
  2530. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  2531. if (!isGlobalCB) {
  2532. // TODO: check cannot mix packoffset elements with nonpackoffset
  2533. // elements in a cbuffer.
  2534. hlsl::ConstantPacking *cp = cast<hlsl::ConstantPacking>(it);
  2535. offset = cp->Subcomponent << 2;
  2536. offset += cp->ComponentOffset;
  2537. // Change to byte.
  2538. offset <<= 2;
  2539. userOffset = true;
  2540. } else {
  2541. DiagnosticsEngine &Diags = CGM.getDiags();
  2542. unsigned DiagID = Diags.getCustomDiagID(
  2543. DiagnosticsEngine::Error,
  2544. "packoffset is only allowed in a constant buffer.");
  2545. Diags.Report(it->Loc, DiagID);
  2546. }
  2547. break;
  2548. }
  2549. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2550. if (isGlobalCB) {
  2551. RegisterAssignment *ra = cast<RegisterAssignment>(it);
  2552. offset = ra->RegisterNumber << 2;
  2553. // Change to byte.
  2554. offset <<= 2;
  2555. userOffset = true;
  2556. }
  2557. break;
  2558. }
  2559. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2560. // skip semantic on constant
  2561. break;
  2562. }
  2563. }
  2564. std::unique_ptr<DxilResourceBase> pHlslConst = llvm::make_unique<DxilResourceBase>(DXIL::ResourceClass::Invalid);
  2565. pHlslConst->SetLowerBound(UINT_MAX);
  2566. pHlslConst->SetGlobalSymbol(cast<llvm::GlobalVariable>(constVal));
  2567. pHlslConst->SetGlobalName(constDecl->getName());
  2568. if (userOffset) {
  2569. pHlslConst->SetLowerBound(offset);
  2570. }
  2571. DxilTypeSystem &dxilTypeSys = m_pHLModule->GetTypeSystem();
  2572. // Just add type annotation here.
  2573. // Offset will be allocated later.
  2574. QualType Ty = constDecl->getType();
  2575. if (CB.GetRangeSize() != 1) {
  2576. while (Ty->isArrayType()) {
  2577. Ty = Ty->getAsArrayTypeUnsafe()->getElementType();
  2578. }
  2579. }
  2580. unsigned arrayEltSize = 0;
  2581. unsigned size = AddTypeAnnotation(Ty, dxilTypeSys, arrayEltSize);
  2582. pHlslConst->SetRangeSize(size);
  2583. CB.AddConst(pHlslConst);
  2584. // Save fieldAnnotation for the const var.
  2585. DxilFieldAnnotation fieldAnnotation;
  2586. if (userOffset)
  2587. fieldAnnotation.SetCBufferOffset(offset);
  2588. // Get the nested element type.
  2589. if (Ty->isArrayType()) {
  2590. while (const ConstantArrayType *arrayTy =
  2591. CGM.getContext().getAsConstantArrayType(Ty)) {
  2592. Ty = arrayTy->getElementType();
  2593. }
  2594. }
  2595. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  2596. ConstructFieldAttributedAnnotation(fieldAnnotation, Ty, bDefaultRowMajor);
  2597. m_ConstVarAnnotationMap[constVal] = fieldAnnotation;
  2598. }
  2599. uint32_t CGMSHLSLRuntime::AddCBuffer(HLSLBufferDecl *D) {
  2600. unique_ptr<HLCBuffer> CB = llvm::make_unique<HLCBuffer>();
  2601. // setup the CB
  2602. CB->SetGlobalSymbol(nullptr);
  2603. CB->SetGlobalName(D->getNameAsString());
  2604. CB->SetLowerBound(UINT_MAX);
  2605. if (!D->isCBuffer()) {
  2606. CB->SetKind(DXIL::ResourceKind::TBuffer);
  2607. }
  2608. // the global variable will only used once by the createHandle?
  2609. // SetHandle(llvm::Value *pHandle);
  2610. for (hlsl::UnusualAnnotation *it : D->getUnusualAnnotations()) {
  2611. switch (it->getKind()) {
  2612. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  2613. hlsl::RegisterAssignment *ra = cast<hlsl::RegisterAssignment>(it);
  2614. uint32_t regNum = ra->RegisterNumber;
  2615. uint32_t regSpace = ra->RegisterSpace;
  2616. CB->SetSpaceID(regSpace);
  2617. CB->SetLowerBound(regNum);
  2618. break;
  2619. }
  2620. case hlsl::UnusualAnnotation::UA_SemanticDecl:
  2621. // skip semantic on constant buffer
  2622. break;
  2623. case hlsl::UnusualAnnotation::UA_ConstantPacking:
  2624. llvm_unreachable("no packoffset on constant buffer");
  2625. break;
  2626. }
  2627. }
  2628. // Add constant
  2629. if (D->isConstantBufferView()) {
  2630. VarDecl *constDecl = cast<VarDecl>(*D->decls_begin());
  2631. CB->SetRangeSize(1);
  2632. QualType Ty = constDecl->getType();
  2633. if (Ty->isArrayType()) {
  2634. if (!Ty->isIncompleteArrayType()) {
  2635. unsigned arraySize = 1;
  2636. while (Ty->isArrayType()) {
  2637. Ty = Ty->getCanonicalTypeUnqualified();
  2638. const ConstantArrayType *AT = cast<ConstantArrayType>(Ty);
  2639. arraySize *= AT->getSize().getLimitedValue();
  2640. Ty = AT->getElementType();
  2641. }
  2642. CB->SetRangeSize(arraySize);
  2643. } else {
  2644. CB->SetRangeSize(UINT_MAX);
  2645. }
  2646. }
  2647. AddConstant(constDecl, *CB.get());
  2648. } else {
  2649. auto declsEnds = D->decls_end();
  2650. CB->SetRangeSize(1);
  2651. for (auto it = D->decls_begin(); it != declsEnds; it++) {
  2652. if (VarDecl *constDecl = dyn_cast<VarDecl>(*it)) {
  2653. AddConstant(constDecl, *CB.get());
  2654. } else if (isa<EmptyDecl>(*it)) {
  2655. // Nothing to do for this declaration.
  2656. } else if (isa<CXXRecordDecl>(*it)) {
  2657. // Nothing to do for this declaration.
  2658. } else if (isa<FunctionDecl>(*it)) {
  2659. // A function within an cbuffer is effectively a top-level function,
  2660. // as it only refers to globally scoped declarations.
  2661. this->CGM.EmitTopLevelDecl(*it);
  2662. } else {
  2663. HLSLBufferDecl *inner = cast<HLSLBufferDecl>(*it);
  2664. GetOrCreateCBuffer(inner);
  2665. }
  2666. }
  2667. }
  2668. CB->SetID(m_pHLModule->GetCBuffers().size());
  2669. return m_pHLModule->AddCBuffer(std::move(CB));
  2670. }
  2671. HLCBuffer &CGMSHLSLRuntime::GetOrCreateCBuffer(HLSLBufferDecl *D) {
  2672. if (constantBufMap.count(D) != 0) {
  2673. uint32_t cbIndex = constantBufMap[D];
  2674. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbIndex)));
  2675. }
  2676. uint32_t cbID = AddCBuffer(D);
  2677. constantBufMap[D] = cbID;
  2678. return *static_cast<HLCBuffer*>(&(m_pHLModule->GetCBuffer(cbID)));
  2679. }
  2680. bool CGMSHLSLRuntime::IsPatchConstantFunction(const Function *F) {
  2681. DXASSERT_NOMSG(F != nullptr);
  2682. for (auto && p : patchConstantFunctionMap) {
  2683. if (p.second.Func == F) return true;
  2684. }
  2685. return false;
  2686. }
  2687. void CGMSHLSLRuntime::SetEntryFunction() {
  2688. if (Entry.Func == nullptr) {
  2689. DiagnosticsEngine &Diags = CGM.getDiags();
  2690. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  2691. "cannot find entry function %0");
  2692. Diags.Report(DiagID) << CGM.getCodeGenOpts().HLSLEntryFunction;
  2693. return;
  2694. }
  2695. m_pHLModule->SetEntryFunction(Entry.Func);
  2696. }
  2697. // Here the size is CB size. So don't need check type.
  2698. static unsigned AlignCBufferOffset(unsigned offset, unsigned size, llvm::Type *Ty) {
  2699. DXASSERT(!(offset & 1), "otherwise we have an invalid offset.");
  2700. bool bNeedNewRow = Ty->isArrayTy();
  2701. unsigned scalarSizeInBytes = Ty->getScalarSizeInBits() / 8;
  2702. return AlignBufferOffsetInLegacy(offset, size, scalarSizeInBytes, bNeedNewRow);
  2703. }
  2704. static unsigned AllocateDxilConstantBuffer(HLCBuffer &CB) {
  2705. unsigned offset = 0;
  2706. // Scan user allocated constants first.
  2707. // Update offset.
  2708. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2709. if (C->GetLowerBound() == UINT_MAX)
  2710. continue;
  2711. unsigned size = C->GetRangeSize();
  2712. unsigned nextOffset = size + C->GetLowerBound();
  2713. if (offset < nextOffset)
  2714. offset = nextOffset;
  2715. }
  2716. // Alloc after user allocated constants.
  2717. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2718. if (C->GetLowerBound() != UINT_MAX)
  2719. continue;
  2720. unsigned size = C->GetRangeSize();
  2721. llvm::Type *Ty = C->GetGlobalSymbol()->getType()->getPointerElementType();
  2722. // Align offset.
  2723. offset = AlignCBufferOffset(offset, size, Ty);
  2724. if (C->GetLowerBound() == UINT_MAX) {
  2725. C->SetLowerBound(offset);
  2726. }
  2727. offset += size;
  2728. }
  2729. return offset;
  2730. }
  2731. static void AllocateDxilConstantBuffers(HLModule *pHLModule) {
  2732. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  2733. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  2734. unsigned size = AllocateDxilConstantBuffer(CB);
  2735. CB.SetSize(size);
  2736. }
  2737. }
  2738. static void ReplaceUseInFunction(Value *V, Value *NewV, Function *F,
  2739. IRBuilder<> &Builder) {
  2740. for (auto U = V->user_begin(); U != V->user_end(); ) {
  2741. User *user = *(U++);
  2742. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2743. if (I->getParent()->getParent() == F) {
  2744. // replace use with GEP if in F
  2745. for (unsigned i = 0; i < I->getNumOperands(); i++) {
  2746. if (I->getOperand(i) == V)
  2747. I->setOperand(i, NewV);
  2748. }
  2749. }
  2750. } else {
  2751. // For constant operator, create local clone which use GEP.
  2752. // Only support GEP and bitcast.
  2753. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2754. std::vector<Value *> idxList(GEPOp->idx_begin(), GEPOp->idx_end());
  2755. Value *NewGEP = Builder.CreateInBoundsGEP(NewV, idxList);
  2756. ReplaceUseInFunction(GEPOp, NewGEP, F, Builder);
  2757. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2758. // Change the init val into NewV with Store.
  2759. GV->setInitializer(nullptr);
  2760. Builder.CreateStore(NewV, GV);
  2761. } else {
  2762. // Must be bitcast here.
  2763. BitCastOperator *BC = cast<BitCastOperator>(user);
  2764. Value *NewBC = Builder.CreateBitCast(NewV, BC->getType());
  2765. ReplaceUseInFunction(BC, NewBC, F, Builder);
  2766. }
  2767. }
  2768. }
  2769. }
  2770. void MarkUsedFunctionForConst(Value *V, std::unordered_set<Function*> &usedFunc) {
  2771. for (auto U = V->user_begin(); U != V->user_end();) {
  2772. User *user = *(U++);
  2773. if (Instruction *I = dyn_cast<Instruction>(user)) {
  2774. Function *F = I->getParent()->getParent();
  2775. usedFunc.insert(F);
  2776. } else {
  2777. // For constant operator, create local clone which use GEP.
  2778. // Only support GEP and bitcast.
  2779. if (GEPOperator *GEPOp = dyn_cast<GEPOperator>(user)) {
  2780. MarkUsedFunctionForConst(GEPOp, usedFunc);
  2781. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(user)) {
  2782. MarkUsedFunctionForConst(GV, usedFunc);
  2783. } else {
  2784. // Must be bitcast here.
  2785. BitCastOperator *BC = cast<BitCastOperator>(user);
  2786. MarkUsedFunctionForConst(BC, usedFunc);
  2787. }
  2788. }
  2789. }
  2790. }
  2791. static Function * GetOrCreateHLCreateHandle(HLModule &HLM, llvm::Type *HandleTy,
  2792. ArrayRef<Value*> paramList, MDNode *MD) {
  2793. SmallVector<llvm::Type *, 4> paramTyList;
  2794. for (Value *param : paramList) {
  2795. paramTyList.emplace_back(param->getType());
  2796. }
  2797. llvm::FunctionType *funcTy =
  2798. llvm::FunctionType::get(HandleTy, paramTyList, false);
  2799. llvm::Module &M = *HLM.GetModule();
  2800. Function *CreateHandle = GetOrCreateHLFunctionWithBody(M, funcTy, HLOpcodeGroup::HLCreateHandle,
  2801. /*opcode*/ 0, "");
  2802. if (CreateHandle->empty()) {
  2803. // Add body.
  2804. BasicBlock *BB =
  2805. BasicBlock::Create(CreateHandle->getContext(), "Entry", CreateHandle);
  2806. IRBuilder<> Builder(BB);
  2807. // Just return undef to make a body.
  2808. Builder.CreateRet(UndefValue::get(HandleTy));
  2809. // Mark resource attribute.
  2810. HLM.MarkDxilResourceAttrib(CreateHandle, MD);
  2811. }
  2812. return CreateHandle;
  2813. }
  2814. static bool CreateCBufferVariable(HLCBuffer &CB,
  2815. HLModule &HLM, llvm::Type *HandleTy) {
  2816. bool bUsed = false;
  2817. // Build Struct for CBuffer.
  2818. SmallVector<llvm::Type*, 4> Elements;
  2819. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2820. Value *GV = C->GetGlobalSymbol();
  2821. if (GV->hasNUsesOrMore(1))
  2822. bUsed = true;
  2823. // Global variable must be pointer type.
  2824. llvm::Type *Ty = GV->getType()->getPointerElementType();
  2825. Elements.emplace_back(Ty);
  2826. }
  2827. // Don't create CBuffer variable for unused cbuffer.
  2828. if (!bUsed)
  2829. return false;
  2830. llvm::Module &M = *HLM.GetModule();
  2831. bool isCBArray = CB.GetRangeSize() != 1;
  2832. llvm::GlobalVariable *cbGV = nullptr;
  2833. llvm::Type *cbTy = nullptr;
  2834. unsigned cbIndexDepth = 0;
  2835. if (!isCBArray) {
  2836. llvm::StructType *CBStructTy =
  2837. llvm::StructType::create(Elements, CB.GetGlobalName());
  2838. cbGV = new llvm::GlobalVariable(M, CBStructTy, /*IsConstant*/ true,
  2839. llvm::GlobalValue::ExternalLinkage,
  2840. /*InitVal*/ nullptr, CB.GetGlobalName());
  2841. cbTy = cbGV->getType();
  2842. } else {
  2843. // For array of ConstantBuffer, create array of struct instead of struct of
  2844. // array.
  2845. DXASSERT(CB.GetConstants().size() == 1,
  2846. "ConstantBuffer should have 1 constant");
  2847. Value *GV = CB.GetConstants()[0]->GetGlobalSymbol();
  2848. llvm::Type *CBEltTy =
  2849. GV->getType()->getPointerElementType()->getArrayElementType();
  2850. cbIndexDepth = 1;
  2851. while (CBEltTy->isArrayTy()) {
  2852. CBEltTy = CBEltTy->getArrayElementType();
  2853. cbIndexDepth++;
  2854. }
  2855. // Add one level struct type to match normal case.
  2856. llvm::StructType *CBStructTy =
  2857. llvm::StructType::create({CBEltTy}, CB.GetGlobalName());
  2858. llvm::ArrayType *CBArrayTy =
  2859. llvm::ArrayType::get(CBStructTy, CB.GetRangeSize());
  2860. cbGV = new llvm::GlobalVariable(M, CBArrayTy, /*IsConstant*/ true,
  2861. llvm::GlobalValue::ExternalLinkage,
  2862. /*InitVal*/ nullptr, CB.GetGlobalName());
  2863. cbTy = llvm::PointerType::get(CBStructTy,
  2864. cbGV->getType()->getPointerAddressSpace());
  2865. }
  2866. CB.SetGlobalSymbol(cbGV);
  2867. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  2868. llvm::Type *idxTy = opcodeTy;
  2869. Constant *zeroIdx = ConstantInt::get(opcodeTy, 0);
  2870. MDNode *MD = HLM.DxilCBufferToMDNode(CB);
  2871. Value *HandleArgs[] = { zeroIdx, cbGV, zeroIdx };
  2872. Function *CreateHandleFunc = GetOrCreateHLCreateHandle(HLM, HandleTy, HandleArgs, MD);
  2873. llvm::FunctionType *SubscriptFuncTy =
  2874. llvm::FunctionType::get(cbTy, { opcodeTy, HandleTy, idxTy}, false);
  2875. Function *subscriptFunc =
  2876. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  2877. (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2878. Constant *opArg = ConstantInt::get(opcodeTy, (unsigned)HLSubscriptOpcode::CBufferSubscript);
  2879. Value *args[] = { opArg, nullptr, zeroIdx };
  2880. llvm::LLVMContext &Context = M.getContext();
  2881. llvm::Type *i32Ty = llvm::Type::getInt32Ty(Context);
  2882. Value *zero = ConstantInt::get(i32Ty, (uint64_t)0);
  2883. std::vector<Value *> indexArray(CB.GetConstants().size());
  2884. std::vector<std::unordered_set<Function*>> constUsedFuncList(CB.GetConstants().size());
  2885. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2886. Value *idx = ConstantInt::get(i32Ty, C->GetID());
  2887. indexArray[C->GetID()] = idx;
  2888. Value *GV = C->GetGlobalSymbol();
  2889. MarkUsedFunctionForConst(GV, constUsedFuncList[C->GetID()]);
  2890. }
  2891. for (Function &F : M.functions()) {
  2892. if (F.isDeclaration())
  2893. continue;
  2894. if (GetHLOpcodeGroupByName(&F) != HLOpcodeGroup::NotHL)
  2895. continue;
  2896. IRBuilder<> Builder(F.getEntryBlock().getFirstInsertionPt());
  2897. // create HL subscript to make all the use of cbuffer start from it.
  2898. HandleArgs[HLOperandIndex::kCreateHandleResourceOpIdx] = cbGV;
  2899. CallInst *Handle = Builder.CreateCall(CreateHandleFunc, HandleArgs);
  2900. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2901. Instruction *cbSubscript =
  2902. cast<Instruction>(Builder.CreateCall(subscriptFunc, {args}));
  2903. // Replace constant var with GEP pGV
  2904. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2905. Value *GV = C->GetGlobalSymbol();
  2906. if (constUsedFuncList[C->GetID()].count(&F) == 0)
  2907. continue;
  2908. Value *idx = indexArray[C->GetID()];
  2909. if (!isCBArray) {
  2910. Instruction *GEP = cast<Instruction>(
  2911. Builder.CreateInBoundsGEP(cbSubscript, {zero, idx}));
  2912. // TODO: make sure the debug info is synced to GEP.
  2913. // GEP->setDebugLoc(GV);
  2914. ReplaceUseInFunction(GV, GEP, &F, Builder);
  2915. // Delete if no use in F.
  2916. if (GEP->user_empty())
  2917. GEP->eraseFromParent();
  2918. } else {
  2919. for (auto U = GV->user_begin(); U != GV->user_end();) {
  2920. User *user = *(U++);
  2921. if (user->user_empty())
  2922. continue;
  2923. Instruction *I = dyn_cast<Instruction>(user);
  2924. if (I && I->getParent()->getParent() != &F)
  2925. continue;
  2926. IRBuilder<> *instBuilder = &Builder;
  2927. unique_ptr<IRBuilder<>> B;
  2928. if (I) {
  2929. B = llvm::make_unique<IRBuilder<>>(I);
  2930. instBuilder = B.get();
  2931. }
  2932. GEPOperator *GEPOp = cast<GEPOperator>(user);
  2933. std::vector<Value *> idxList;
  2934. DXASSERT(GEPOp->getNumIndices() >= 1 + cbIndexDepth,
  2935. "must indexing ConstantBuffer array");
  2936. idxList.reserve(GEPOp->getNumIndices() - (cbIndexDepth - 1));
  2937. gep_type_iterator GI = gep_type_begin(*GEPOp),
  2938. E = gep_type_end(*GEPOp);
  2939. idxList.push_back(GI.getOperand());
  2940. // change array index with 0 for struct index.
  2941. idxList.push_back(zero);
  2942. GI++;
  2943. Value *arrayIdx = GI.getOperand();
  2944. GI++;
  2945. for (unsigned curIndex = 1; GI != E && curIndex < cbIndexDepth;
  2946. ++GI, ++curIndex) {
  2947. arrayIdx = instBuilder->CreateMul(
  2948. arrayIdx, Builder.getInt32(GI->getArrayNumElements()));
  2949. arrayIdx = instBuilder->CreateAdd(arrayIdx, GI.getOperand());
  2950. }
  2951. for (; GI != E; ++GI) {
  2952. idxList.push_back(GI.getOperand());
  2953. }
  2954. HandleArgs[HLOperandIndex::kCreateHandleIndexOpIdx] = arrayIdx;
  2955. CallInst *Handle =
  2956. instBuilder->CreateCall(CreateHandleFunc, HandleArgs);
  2957. args[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  2958. args[HLOperandIndex::kSubscriptIndexOpIdx] = arrayIdx;
  2959. Instruction *cbSubscript =
  2960. cast<Instruction>(instBuilder->CreateCall(subscriptFunc, {args}));
  2961. Instruction *NewGEP = cast<Instruction>(
  2962. instBuilder->CreateInBoundsGEP(cbSubscript, idxList));
  2963. ReplaceUseInFunction(GEPOp, NewGEP, &F, *instBuilder);
  2964. }
  2965. }
  2966. }
  2967. // Delete if no use in F.
  2968. if (cbSubscript->user_empty()) {
  2969. cbSubscript->eraseFromParent();
  2970. Handle->eraseFromParent();
  2971. } else {
  2972. // merge GEP use for cbSubscript.
  2973. HLModule::MergeGepUse(cbSubscript);
  2974. }
  2975. }
  2976. return true;
  2977. }
  2978. static void ConstructCBufferAnnotation(
  2979. HLCBuffer &CB, DxilTypeSystem &dxilTypeSys,
  2980. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  2981. Value *GV = CB.GetGlobalSymbol();
  2982. llvm::StructType *CBStructTy =
  2983. dyn_cast<llvm::StructType>(GV->getType()->getPointerElementType());
  2984. if (!CBStructTy) {
  2985. // For Array of ConstantBuffer.
  2986. llvm::ArrayType *CBArrayTy =
  2987. cast<llvm::ArrayType>(GV->getType()->getPointerElementType());
  2988. CBStructTy = cast<llvm::StructType>(CBArrayTy->getArrayElementType());
  2989. }
  2990. DxilStructAnnotation *CBAnnotation =
  2991. dxilTypeSys.AddStructAnnotation(CBStructTy);
  2992. CBAnnotation->SetCBufferSize(CB.GetSize());
  2993. // Set fieldAnnotation for each constant var.
  2994. for (const std::unique_ptr<DxilResourceBase> &C : CB.GetConstants()) {
  2995. Constant *GV = C->GetGlobalSymbol();
  2996. DxilFieldAnnotation &fieldAnnotation =
  2997. CBAnnotation->GetFieldAnnotation(C->GetID());
  2998. fieldAnnotation = AnnotationMap[GV];
  2999. // This is after CBuffer allocation.
  3000. fieldAnnotation.SetCBufferOffset(C->GetLowerBound());
  3001. fieldAnnotation.SetFieldName(C->GetGlobalName());
  3002. }
  3003. }
  3004. static void ConstructCBuffer(
  3005. HLModule *pHLModule,
  3006. llvm::Type *CBufferType,
  3007. std::unordered_map<Constant *, DxilFieldAnnotation> &AnnotationMap) {
  3008. DxilTypeSystem &dxilTypeSys = pHLModule->GetTypeSystem();
  3009. llvm::Type *HandleTy = pHLModule->GetOP()->GetHandleType();
  3010. for (unsigned i = 0; i < pHLModule->GetCBuffers().size(); i++) {
  3011. HLCBuffer &CB = *static_cast<HLCBuffer*>(&(pHLModule->GetCBuffer(i)));
  3012. if (CB.GetConstants().size() == 0) {
  3013. // Create Fake variable for cbuffer which is empty.
  3014. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  3015. *pHLModule->GetModule(), CBufferType, true,
  3016. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  3017. CB.SetGlobalSymbol(pGV);
  3018. } else {
  3019. bool bCreated =
  3020. CreateCBufferVariable(CB, *pHLModule, HandleTy);
  3021. if (bCreated)
  3022. ConstructCBufferAnnotation(CB, dxilTypeSys, AnnotationMap);
  3023. else {
  3024. // Create Fake variable for cbuffer which is unused.
  3025. llvm::GlobalVariable *pGV = new llvm::GlobalVariable(
  3026. *pHLModule->GetModule(), CBufferType, true,
  3027. llvm::GlobalValue::ExternalLinkage, nullptr, CB.GetGlobalName());
  3028. CB.SetGlobalSymbol(pGV);
  3029. }
  3030. }
  3031. // Clear the constants which useless now.
  3032. CB.GetConstants().clear();
  3033. }
  3034. }
  3035. static void ReplaceBoolVectorSubscript(CallInst *CI) {
  3036. Value *Ptr = CI->getArgOperand(0);
  3037. Value *Idx = CI->getArgOperand(1);
  3038. Value *IdxList[] = {ConstantInt::get(Idx->getType(), 0), Idx};
  3039. for (auto It = CI->user_begin(), E = CI->user_end(); It != E;) {
  3040. Instruction *user = cast<Instruction>(*(It++));
  3041. IRBuilder<> Builder(user);
  3042. Value *GEP = Builder.CreateInBoundsGEP(Ptr, IdxList);
  3043. if (LoadInst *LI = dyn_cast<LoadInst>(user)) {
  3044. Value *NewLd = Builder.CreateLoad(GEP);
  3045. Value *cast = Builder.CreateZExt(NewLd, LI->getType());
  3046. LI->replaceAllUsesWith(cast);
  3047. LI->eraseFromParent();
  3048. } else {
  3049. // Must be a store inst here.
  3050. StoreInst *SI = cast<StoreInst>(user);
  3051. Value *V = SI->getValueOperand();
  3052. Value *cast =
  3053. Builder.CreateICmpNE(V, llvm::ConstantInt::get(V->getType(), 0));
  3054. Builder.CreateStore(cast, GEP);
  3055. SI->eraseFromParent();
  3056. }
  3057. }
  3058. CI->eraseFromParent();
  3059. }
  3060. static void ReplaceBoolVectorSubscript(Function *F) {
  3061. for (auto It = F->user_begin(), E = F->user_end(); It != E; ) {
  3062. User *user = *(It++);
  3063. CallInst *CI = cast<CallInst>(user);
  3064. ReplaceBoolVectorSubscript(CI);
  3065. }
  3066. }
  3067. // Add function body for intrinsic if possible.
  3068. static Function *CreateOpFunction(llvm::Module &M, Function *F,
  3069. llvm::FunctionType *funcTy,
  3070. HLOpcodeGroup group, unsigned opcode) {
  3071. Function *opFunc = nullptr;
  3072. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3073. if (group == HLOpcodeGroup::HLIntrinsic) {
  3074. IntrinsicOp intriOp = static_cast<IntrinsicOp>(opcode);
  3075. switch (intriOp) {
  3076. case IntrinsicOp::MOP_Append:
  3077. case IntrinsicOp::MOP_Consume: {
  3078. bool bAppend = intriOp == IntrinsicOp::MOP_Append;
  3079. llvm::Type *handleTy = funcTy->getParamType(HLOperandIndex::kHandleOpIdx);
  3080. // Don't generate body for OutputStream::Append.
  3081. if (bAppend && HLModule::IsStreamOutputPtrType(handleTy)) {
  3082. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  3083. break;
  3084. }
  3085. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode,
  3086. bAppend ? "append" : "consume");
  3087. llvm::Type *counterTy = llvm::Type::getInt32Ty(M.getContext());
  3088. llvm::FunctionType *IncCounterFuncTy =
  3089. llvm::FunctionType::get(counterTy, {opcodeTy, handleTy}, false);
  3090. unsigned counterOpcode = bAppend ? (unsigned)IntrinsicOp::MOP_IncrementCounter:
  3091. (unsigned)IntrinsicOp::MOP_DecrementCounter;
  3092. Function *incCounterFunc =
  3093. GetOrCreateHLFunction(M, IncCounterFuncTy, group,
  3094. counterOpcode);
  3095. llvm::Type *idxTy = counterTy;
  3096. llvm::Type *valTy = bAppend ?
  3097. funcTy->getParamType(HLOperandIndex::kAppendValOpIndex):funcTy->getReturnType();
  3098. // Return type for subscript should be pointer type, hence in memory representation
  3099. llvm::Type *subscriptTy = valTy;
  3100. bool isBoolScalarOrVector = false;
  3101. if (!subscriptTy->isPointerTy()) {
  3102. if (subscriptTy->getScalarType()->isIntegerTy(1)) {
  3103. isBoolScalarOrVector = true;
  3104. llvm::Type *memReprType = llvm::IntegerType::get(subscriptTy->getContext(), 32);
  3105. subscriptTy = subscriptTy->isVectorTy()
  3106. ? llvm::VectorType::get(memReprType, subscriptTy->getVectorNumElements())
  3107. : memReprType;
  3108. }
  3109. subscriptTy = llvm::PointerType::get(subscriptTy, 0);
  3110. }
  3111. llvm::FunctionType *SubscriptFuncTy =
  3112. llvm::FunctionType::get(subscriptTy, {opcodeTy, handleTy, idxTy}, false);
  3113. Function *subscriptFunc =
  3114. GetOrCreateHLFunction(M, SubscriptFuncTy, HLOpcodeGroup::HLSubscript,
  3115. (unsigned)HLSubscriptOpcode::DefaultSubscript);
  3116. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  3117. IRBuilder<> Builder(BB);
  3118. auto argIter = opFunc->args().begin();
  3119. // Skip the opcode arg.
  3120. argIter++;
  3121. Argument *thisArg = argIter++;
  3122. // int counter = IncrementCounter/DecrementCounter(Buf);
  3123. Value *incCounterOpArg =
  3124. ConstantInt::get(idxTy, counterOpcode);
  3125. Value *counter =
  3126. Builder.CreateCall(incCounterFunc, {incCounterOpArg, thisArg});
  3127. // Buf[counter];
  3128. Value *subscriptOpArg = ConstantInt::get(
  3129. idxTy, (unsigned)HLSubscriptOpcode::DefaultSubscript);
  3130. Value *subscript =
  3131. Builder.CreateCall(subscriptFunc, {subscriptOpArg, thisArg, counter});
  3132. if (bAppend) {
  3133. Argument *valArg = argIter;
  3134. // Buf[counter] = val;
  3135. if (valTy->isPointerTy()) {
  3136. unsigned size = M.getDataLayout().getTypeAllocSize(subscript->getType()->getPointerElementType());
  3137. Builder.CreateMemCpy(subscript, valArg, size, 1);
  3138. }
  3139. else {
  3140. Value *storedVal = valArg;
  3141. // Convert to memory representation
  3142. if (isBoolScalarOrVector)
  3143. storedVal = Builder.CreateZExt(storedVal, subscriptTy->getPointerElementType(), "frombool");
  3144. Builder.CreateStore(storedVal, subscript);
  3145. }
  3146. Builder.CreateRetVoid();
  3147. } else {
  3148. // return Buf[counter];
  3149. if (valTy->isPointerTy())
  3150. Builder.CreateRet(subscript);
  3151. else {
  3152. Value *retVal = Builder.CreateLoad(subscript);
  3153. // Convert to register representation
  3154. if (isBoolScalarOrVector)
  3155. retVal = Builder.CreateICmpNE(retVal, Constant::getNullValue(retVal->getType()), "tobool");
  3156. Builder.CreateRet(retVal);
  3157. }
  3158. }
  3159. } break;
  3160. case IntrinsicOp::IOP_sincos: {
  3161. opFunc = GetOrCreateHLFunctionWithBody(M, funcTy, group, opcode, "sincos");
  3162. llvm::Type *valTy = funcTy->getParamType(HLOperandIndex::kTrinaryOpSrc0Idx);
  3163. llvm::FunctionType *sinFuncTy =
  3164. llvm::FunctionType::get(valTy, {opcodeTy, valTy}, false);
  3165. unsigned sinOp = static_cast<unsigned>(IntrinsicOp::IOP_sin);
  3166. unsigned cosOp = static_cast<unsigned>(IntrinsicOp::IOP_cos);
  3167. Function *sinFunc = GetOrCreateHLFunction(M, sinFuncTy, group, sinOp);
  3168. Function *cosFunc = GetOrCreateHLFunction(M, sinFuncTy, group, cosOp);
  3169. BasicBlock *BB = BasicBlock::Create(opFunc->getContext(), "Entry", opFunc);
  3170. IRBuilder<> Builder(BB);
  3171. auto argIter = opFunc->args().begin();
  3172. // Skip the opcode arg.
  3173. argIter++;
  3174. Argument *valArg = argIter++;
  3175. Argument *sinPtrArg = argIter++;
  3176. Argument *cosPtrArg = argIter++;
  3177. Value *sinOpArg =
  3178. ConstantInt::get(opcodeTy, sinOp);
  3179. Value *sinVal = Builder.CreateCall(sinFunc, {sinOpArg, valArg});
  3180. Builder.CreateStore(sinVal, sinPtrArg);
  3181. Value *cosOpArg =
  3182. ConstantInt::get(opcodeTy, cosOp);
  3183. Value *cosVal = Builder.CreateCall(cosFunc, {cosOpArg, valArg});
  3184. Builder.CreateStore(cosVal, cosPtrArg);
  3185. // Ret.
  3186. Builder.CreateRetVoid();
  3187. } break;
  3188. default:
  3189. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  3190. break;
  3191. }
  3192. }
  3193. else if (group == HLOpcodeGroup::HLExtIntrinsic) {
  3194. llvm::StringRef fnName = F->getName();
  3195. llvm::StringRef groupName = GetHLOpcodeGroupNameByAttr(F);
  3196. opFunc = GetOrCreateHLFunction(M, funcTy, group, &groupName, &fnName, opcode);
  3197. }
  3198. else {
  3199. opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  3200. }
  3201. // Add attribute
  3202. if (F->hasFnAttribute(Attribute::ReadNone))
  3203. opFunc->addFnAttr(Attribute::ReadNone);
  3204. if (F->hasFnAttribute(Attribute::ReadOnly))
  3205. opFunc->addFnAttr(Attribute::ReadOnly);
  3206. return opFunc;
  3207. }
  3208. static Value *CreateHandleFromResPtr(
  3209. Value *ResPtr, HLModule &HLM, llvm::Type *HandleTy,
  3210. std::unordered_map<llvm::Type *, MDNode *> &resMetaMap,
  3211. IRBuilder<> &Builder) {
  3212. llvm::Type *objTy = ResPtr->getType()->getPointerElementType();
  3213. DXASSERT(resMetaMap.count(objTy), "cannot find resource type");
  3214. MDNode *MD = resMetaMap[objTy];
  3215. // Load to make sure resource only have Ld/St use so mem2reg could remove
  3216. // temp resource.
  3217. Value *ldObj = Builder.CreateLoad(ResPtr);
  3218. Value *opcode = Builder.getInt32(0);
  3219. Value *args[] = {opcode, ldObj};
  3220. Function *CreateHandle = GetOrCreateHLCreateHandle(HLM, HandleTy, args, MD);
  3221. CallInst *Handle = Builder.CreateCall(CreateHandle, args);
  3222. return Handle;
  3223. }
  3224. static void AddOpcodeParamForIntrinsic(HLModule &HLM, Function *F,
  3225. unsigned opcode, llvm::Type *HandleTy,
  3226. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  3227. llvm::Module &M = *HLM.GetModule();
  3228. llvm::FunctionType *oldFuncTy = F->getFunctionType();
  3229. SmallVector<llvm::Type *, 4> paramTyList;
  3230. // Add the opcode param
  3231. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  3232. paramTyList.emplace_back(opcodeTy);
  3233. paramTyList.append(oldFuncTy->param_begin(), oldFuncTy->param_end());
  3234. for (unsigned i = 1; i < paramTyList.size(); i++) {
  3235. llvm::Type *Ty = paramTyList[i];
  3236. if (Ty->isPointerTy()) {
  3237. Ty = Ty->getPointerElementType();
  3238. if (dxilutil::IsHLSLObjectType(Ty) &&
  3239. // StreamOutput don't need handle.
  3240. !HLModule::IsStreamOutputType(Ty)) {
  3241. // Use handle type for object type.
  3242. // This will make sure temp object variable only used by createHandle.
  3243. paramTyList[i] = HandleTy;
  3244. }
  3245. }
  3246. }
  3247. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  3248. if (group == HLOpcodeGroup::HLSubscript &&
  3249. opcode == static_cast<unsigned>(HLSubscriptOpcode::VectorSubscript)) {
  3250. llvm::FunctionType *FT = F->getFunctionType();
  3251. llvm::Type *VecArgTy = FT->getParamType(0);
  3252. llvm::VectorType *VType =
  3253. cast<llvm::VectorType>(VecArgTy->getPointerElementType());
  3254. llvm::Type *Ty = VType->getElementType();
  3255. DXASSERT(Ty->isIntegerTy(), "Only bool could use VectorSubscript");
  3256. llvm::IntegerType *ITy = cast<IntegerType>(Ty);
  3257. DXASSERT_LOCALVAR(ITy, ITy->getBitWidth() == 1, "Only bool could use VectorSubscript");
  3258. // The return type is i8*.
  3259. // Replace all uses with i1*.
  3260. ReplaceBoolVectorSubscript(F);
  3261. return;
  3262. }
  3263. bool isDoubleSubscriptFunc = group == HLOpcodeGroup::HLSubscript &&
  3264. opcode == static_cast<unsigned>(HLSubscriptOpcode::DoubleSubscript);
  3265. llvm::Type *RetTy = oldFuncTy->getReturnType();
  3266. if (isDoubleSubscriptFunc) {
  3267. CallInst *doubleSub = cast<CallInst>(*F->user_begin());
  3268. // Change currentIdx type into coord type.
  3269. auto U = doubleSub->user_begin();
  3270. Value *user = *U;
  3271. CallInst *secSub = cast<CallInst>(user);
  3272. unsigned coordIdx = HLOperandIndex::kSubscriptIndexOpIdx;
  3273. // opcode operand not add yet, so the index need -1.
  3274. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  3275. coordIdx -= 1;
  3276. Value *coord = secSub->getArgOperand(coordIdx);
  3277. llvm::Type *coordTy = coord->getType();
  3278. paramTyList[HLOperandIndex::kSubscriptIndexOpIdx] = coordTy;
  3279. // Add the sampleIdx or mipLevel parameter to the end.
  3280. paramTyList.emplace_back(opcodeTy);
  3281. // Change return type to be resource ret type.
  3282. // opcode operand not add yet, so the index need -1.
  3283. Value *objPtr = doubleSub->getArgOperand(HLOperandIndex::kSubscriptObjectOpIdx-1);
  3284. // Must be a GEP
  3285. GEPOperator *objGEP = cast<GEPOperator>(objPtr);
  3286. gep_type_iterator GEPIt = gep_type_begin(objGEP), E = gep_type_end(objGEP);
  3287. llvm::Type *resTy = nullptr;
  3288. while (GEPIt != E) {
  3289. if (dxilutil::IsHLSLObjectType(*GEPIt)) {
  3290. resTy = *GEPIt;
  3291. break;
  3292. }
  3293. GEPIt++;
  3294. }
  3295. DXASSERT(resTy, "must find the resource type");
  3296. // Change object type to handle type.
  3297. paramTyList[HLOperandIndex::kSubscriptObjectOpIdx] = HandleTy;
  3298. // Change RetTy into pointer of resource reture type.
  3299. RetTy = cast<StructType>(resTy)->getElementType(0)->getPointerTo();
  3300. llvm::Type *sliceTy = objGEP->getType()->getPointerElementType();
  3301. DXIL::ResourceClass RC = HLM.GetResourceClass(sliceTy);
  3302. DXIL::ResourceKind RK = HLM.GetResourceKind(sliceTy);
  3303. HLM.AddResourceTypeAnnotation(resTy, RC, RK);
  3304. }
  3305. llvm::FunctionType *funcTy =
  3306. llvm::FunctionType::get(RetTy, paramTyList, false);
  3307. Function *opFunc = CreateOpFunction(M, F, funcTy, group, opcode);
  3308. StringRef lower = hlsl::GetHLLowerStrategy(F);
  3309. if (!lower.empty())
  3310. hlsl::SetHLLowerStrategy(opFunc, lower);
  3311. for (auto user = F->user_begin(); user != F->user_end();) {
  3312. // User must be a call.
  3313. CallInst *oldCI = cast<CallInst>(*(user++));
  3314. SmallVector<Value *, 4> opcodeParamList;
  3315. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  3316. opcodeParamList.emplace_back(opcodeConst);
  3317. opcodeParamList.append(oldCI->arg_operands().begin(),
  3318. oldCI->arg_operands().end());
  3319. IRBuilder<> Builder(oldCI);
  3320. if (isDoubleSubscriptFunc) {
  3321. // Change obj to the resource pointer.
  3322. Value *objVal = opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx];
  3323. GEPOperator *objGEP = cast<GEPOperator>(objVal);
  3324. SmallVector<Value *, 8> IndexList;
  3325. IndexList.append(objGEP->idx_begin(), objGEP->idx_end());
  3326. Value *lastIndex = IndexList.back();
  3327. ConstantInt *constIndex = cast<ConstantInt>(lastIndex);
  3328. DXASSERT_LOCALVAR(constIndex, constIndex->getLimitedValue() == 1, "last index must 1");
  3329. // Remove the last index.
  3330. IndexList.pop_back();
  3331. objVal = objGEP->getPointerOperand();
  3332. if (IndexList.size() > 1)
  3333. objVal = Builder.CreateInBoundsGEP(objVal, IndexList);
  3334. Value *Handle =
  3335. CreateHandleFromResPtr(objVal, HLM, HandleTy, resMetaMap, Builder);
  3336. // Change obj to the resource pointer.
  3337. opcodeParamList[HLOperandIndex::kSubscriptObjectOpIdx] = Handle;
  3338. // Set idx and mipIdx.
  3339. Value *mipIdx = opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx];
  3340. auto U = oldCI->user_begin();
  3341. Value *user = *U;
  3342. CallInst *secSub = cast<CallInst>(user);
  3343. unsigned idxOpIndex = HLOperandIndex::kSubscriptIndexOpIdx;
  3344. if (GetHLOpcodeGroupByName(secSub->getCalledFunction()) == HLOpcodeGroup::NotHL)
  3345. idxOpIndex--;
  3346. Value *idx = secSub->getArgOperand(idxOpIndex);
  3347. DXASSERT(secSub->hasOneUse(), "subscript should only has one use");
  3348. // Add the sampleIdx or mipLevel parameter to the end.
  3349. opcodeParamList[HLOperandIndex::kSubscriptIndexOpIdx] = idx;
  3350. opcodeParamList.emplace_back(mipIdx);
  3351. // Insert new call before secSub to make sure idx is ready to use.
  3352. Builder.SetInsertPoint(secSub);
  3353. }
  3354. for (unsigned i = 1; i < opcodeParamList.size(); i++) {
  3355. Value *arg = opcodeParamList[i];
  3356. llvm::Type *Ty = arg->getType();
  3357. if (Ty->isPointerTy()) {
  3358. Ty = Ty->getPointerElementType();
  3359. if (dxilutil::IsHLSLObjectType(Ty) &&
  3360. // StreamOutput don't need handle.
  3361. !HLModule::IsStreamOutputType(Ty)) {
  3362. // Use object type directly, not by pointer.
  3363. // This will make sure temp object variable only used by ld/st.
  3364. if (GEPOperator *argGEP = dyn_cast<GEPOperator>(arg)) {
  3365. std::vector<Value*> idxList(argGEP->idx_begin(), argGEP->idx_end());
  3366. // Create instruction to avoid GEPOperator.
  3367. GetElementPtrInst *GEP = GetElementPtrInst::CreateInBounds(argGEP->getPointerOperand(),
  3368. idxList);
  3369. Builder.Insert(GEP);
  3370. arg = GEP;
  3371. }
  3372. Value *Handle = CreateHandleFromResPtr(arg, HLM, HandleTy,
  3373. resMetaMap, Builder);
  3374. opcodeParamList[i] = Handle;
  3375. }
  3376. }
  3377. }
  3378. Value *CI = Builder.CreateCall(opFunc, opcodeParamList);
  3379. if (!isDoubleSubscriptFunc) {
  3380. // replace new call and delete the old call
  3381. oldCI->replaceAllUsesWith(CI);
  3382. oldCI->eraseFromParent();
  3383. } else {
  3384. // For double script.
  3385. // Replace single users use with new CI.
  3386. auto U = oldCI->user_begin();
  3387. Value *user = *U;
  3388. CallInst *secSub = cast<CallInst>(user);
  3389. secSub->replaceAllUsesWith(CI);
  3390. secSub->eraseFromParent();
  3391. oldCI->eraseFromParent();
  3392. }
  3393. }
  3394. // delete the function
  3395. F->eraseFromParent();
  3396. }
  3397. static void AddOpcodeParamForIntrinsics(HLModule &HLM
  3398. , std::vector<std::pair<Function *, unsigned>> &intrinsicMap,
  3399. std::unordered_map<llvm::Type *, MDNode*> &resMetaMap) {
  3400. llvm::Type *HandleTy = HLM.GetOP()->GetHandleType();
  3401. for (auto mapIter : intrinsicMap) {
  3402. Function *F = mapIter.first;
  3403. if (F->user_empty()) {
  3404. // delete the function
  3405. F->eraseFromParent();
  3406. continue;
  3407. }
  3408. unsigned opcode = mapIter.second;
  3409. AddOpcodeParamForIntrinsic(HLM, F, opcode, HandleTy, resMetaMap);
  3410. }
  3411. }
  3412. static Value *CastLdValue(Value *Ptr, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3413. if (ToTy->isVectorTy()) {
  3414. unsigned vecSize = ToTy->getVectorNumElements();
  3415. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3416. Value *V = Builder.CreateLoad(Ptr);
  3417. // ScalarToVec1Splat
  3418. // Change scalar into vec1.
  3419. Value *Vec1 = UndefValue::get(ToTy);
  3420. return Builder.CreateInsertElement(Vec1, V, (uint64_t)0);
  3421. } else if (vecSize == 1 && FromTy->isIntegerTy()
  3422. && ToTy->getVectorElementType()->isIntegerTy(1)) {
  3423. // load(bitcast i32* to <1 x i1>*)
  3424. // Rewrite to
  3425. // insertelement(icmp ne (load i32*), 0)
  3426. Value *IntV = Builder.CreateLoad(Ptr);
  3427. Value *BoolV = Builder.CreateICmpNE(IntV, ConstantInt::get(IntV->getType(), 0), "tobool");
  3428. Value *Vec1 = UndefValue::get(ToTy);
  3429. return Builder.CreateInsertElement(Vec1, BoolV, (uint64_t)0);
  3430. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3431. Value *V = Builder.CreateLoad(Ptr);
  3432. // VectorTrunc
  3433. // Change vector into vec1.
  3434. int mask[] = {0};
  3435. return Builder.CreateShuffleVector(V, V, mask);
  3436. } else if (FromTy->isArrayTy()) {
  3437. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3438. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3439. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3440. // ArrayToVector.
  3441. Value *NewLd = UndefValue::get(ToTy);
  3442. Value *zeroIdx = Builder.getInt32(0);
  3443. for (unsigned i = 0; i < vecSize; i++) {
  3444. Value *GEP = Builder.CreateInBoundsGEP(
  3445. Ptr, {zeroIdx, Builder.getInt32(i)});
  3446. Value *Elt = Builder.CreateLoad(GEP);
  3447. NewLd = Builder.CreateInsertElement(NewLd, Elt, i);
  3448. }
  3449. return NewLd;
  3450. }
  3451. }
  3452. } else if (FromTy == Builder.getInt1Ty()) {
  3453. Value *V = Builder.CreateLoad(Ptr);
  3454. // BoolCast
  3455. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3456. return Builder.CreateZExt(V, ToTy);
  3457. }
  3458. return nullptr;
  3459. }
  3460. static Value *CastStValue(Value *Ptr, Value *V, llvm::Type *FromTy, llvm::Type *ToTy, IRBuilder<> &Builder) {
  3461. if (ToTy->isVectorTy()) {
  3462. unsigned vecSize = ToTy->getVectorNumElements();
  3463. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3464. // ScalarToVec1Splat
  3465. // Change vec1 back to scalar.
  3466. Value *Elt = Builder.CreateExtractElement(V, (uint64_t)0);
  3467. return Elt;
  3468. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3469. // VectorTrunc
  3470. // Change vec1 into vector.
  3471. // Should not happen.
  3472. // Reported error at Sema::ImpCastExprToType.
  3473. DXASSERT_NOMSG(0);
  3474. } else if (FromTy->isArrayTy()) {
  3475. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3476. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3477. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3478. // ArrayToVector.
  3479. Value *zeroIdx = Builder.getInt32(0);
  3480. for (unsigned i = 0; i < vecSize; i++) {
  3481. Value *Elt = Builder.CreateExtractElement(V, i);
  3482. Value *GEP = Builder.CreateInBoundsGEP(
  3483. Ptr, {zeroIdx, Builder.getInt32(i)});
  3484. Builder.CreateStore(Elt, GEP);
  3485. }
  3486. // The store already done.
  3487. // Return null to ignore use of the return value.
  3488. return nullptr;
  3489. }
  3490. }
  3491. } else if (FromTy == Builder.getInt1Ty()) {
  3492. // BoolCast
  3493. // Change i1 to ToTy.
  3494. DXASSERT_NOMSG(ToTy->isIntegerTy());
  3495. Value *CastV = Builder.CreateICmpNE(V, ConstantInt::get(V->getType(), 0));
  3496. return CastV;
  3497. }
  3498. return nullptr;
  3499. }
  3500. static bool SimplifyBitCastLoad(LoadInst *LI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3501. IRBuilder<> Builder(LI);
  3502. // Cast FromLd to ToTy.
  3503. Value *CastV = CastLdValue(Ptr, FromTy, ToTy, Builder);
  3504. if (CastV) {
  3505. LI->replaceAllUsesWith(CastV);
  3506. return true;
  3507. } else {
  3508. return false;
  3509. }
  3510. }
  3511. static bool SimplifyBitCastStore(StoreInst *SI, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3512. IRBuilder<> Builder(SI);
  3513. Value *V = SI->getValueOperand();
  3514. // Cast Val to FromTy.
  3515. Value *CastV = CastStValue(Ptr, V, FromTy, ToTy, Builder);
  3516. if (CastV) {
  3517. Builder.CreateStore(CastV, Ptr);
  3518. return true;
  3519. } else {
  3520. return false;
  3521. }
  3522. }
  3523. static bool SimplifyBitCastGEP(GEPOperator *GEP, llvm::Type *FromTy, llvm::Type *ToTy, Value *Ptr) {
  3524. if (ToTy->isVectorTy()) {
  3525. unsigned vecSize = ToTy->getVectorNumElements();
  3526. if (vecSize == 1 && ToTy->getVectorElementType() == FromTy) {
  3527. // ScalarToVec1Splat
  3528. GEP->replaceAllUsesWith(Ptr);
  3529. return true;
  3530. } else if (FromTy->isVectorTy() && vecSize == 1) {
  3531. // VectorTrunc
  3532. DXASSERT_NOMSG(
  3533. !isa<llvm::VectorType>(GEP->getType()->getPointerElementType()));
  3534. IRBuilder<> Builder(FromTy->getContext());
  3535. if (Instruction *I = dyn_cast<Instruction>(GEP))
  3536. Builder.SetInsertPoint(I);
  3537. std::vector<Value *> idxList(GEP->idx_begin(), GEP->idx_end());
  3538. Value *NewGEP = Builder.CreateInBoundsGEP(Ptr, idxList);
  3539. GEP->replaceAllUsesWith(NewGEP);
  3540. return true;
  3541. } else if (FromTy->isArrayTy()) {
  3542. llvm::Type *FromEltTy = FromTy->getArrayElementType();
  3543. llvm::Type *ToEltTy = ToTy->getVectorElementType();
  3544. if (FromTy->getArrayNumElements() == vecSize && FromEltTy == ToEltTy) {
  3545. // ArrayToVector.
  3546. }
  3547. }
  3548. } else if (FromTy == llvm::Type::getInt1Ty(FromTy->getContext())) {
  3549. // BoolCast
  3550. }
  3551. return false;
  3552. }
  3553. typedef SmallPtrSet<Instruction *, 4> SmallInstSet;
  3554. static void SimplifyBitCast(BitCastOperator *BC, SmallInstSet &deadInsts) {
  3555. Value *Ptr = BC->getOperand(0);
  3556. llvm::Type *FromTy = Ptr->getType();
  3557. llvm::Type *ToTy = BC->getType();
  3558. if (!FromTy->isPointerTy() || !ToTy->isPointerTy())
  3559. return;
  3560. FromTy = FromTy->getPointerElementType();
  3561. ToTy = ToTy->getPointerElementType();
  3562. // Take care case like %2 = bitcast %struct.T* %1 to <1 x float>*.
  3563. bool GEPCreated = false;
  3564. if (FromTy->isStructTy()) {
  3565. IRBuilder<> Builder(FromTy->getContext());
  3566. if (Instruction *I = dyn_cast<Instruction>(BC))
  3567. Builder.SetInsertPoint(I);
  3568. Value *zeroIdx = Builder.getInt32(0);
  3569. unsigned nestLevel = 1;
  3570. while (llvm::StructType *ST = dyn_cast<llvm::StructType>(FromTy)) {
  3571. if (ST->getNumElements() == 0) break;
  3572. FromTy = ST->getElementType(0);
  3573. nestLevel++;
  3574. }
  3575. std::vector<Value *> idxList(nestLevel, zeroIdx);
  3576. Ptr = Builder.CreateGEP(Ptr, idxList);
  3577. GEPCreated = true;
  3578. }
  3579. for (User *U : BC->users()) {
  3580. if (LoadInst *LI = dyn_cast<LoadInst>(U)) {
  3581. if (SimplifyBitCastLoad(LI, FromTy, ToTy, Ptr)) {
  3582. LI->dropAllReferences();
  3583. deadInsts.insert(LI);
  3584. }
  3585. } else if (StoreInst *SI = dyn_cast<StoreInst>(U)) {
  3586. if (SimplifyBitCastStore(SI, FromTy, ToTy, Ptr)) {
  3587. SI->dropAllReferences();
  3588. deadInsts.insert(SI);
  3589. }
  3590. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  3591. if (SimplifyBitCastGEP(GEP, FromTy, ToTy, Ptr))
  3592. if (Instruction *I = dyn_cast<Instruction>(GEP)) {
  3593. I->dropAllReferences();
  3594. deadInsts.insert(I);
  3595. }
  3596. } else if (dyn_cast<CallInst>(U)) {
  3597. // Skip function call.
  3598. } else if (dyn_cast<BitCastInst>(U)) {
  3599. // Skip bitcast.
  3600. } else if (dyn_cast<AddrSpaceCastInst>(U)) {
  3601. // Skip addrspacecast.
  3602. } else {
  3603. DXASSERT(0, "not support yet");
  3604. }
  3605. }
  3606. // We created a GEP instruction but didn't end up consuming it, so delete it.
  3607. if (GEPCreated && Ptr->use_empty()) {
  3608. if (GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(Ptr))
  3609. GEP->eraseFromParent();
  3610. else
  3611. cast<Constant>(Ptr)->destroyConstant();
  3612. }
  3613. }
  3614. typedef float(__cdecl *FloatUnaryEvalFuncType)(float);
  3615. typedef double(__cdecl *DoubleUnaryEvalFuncType)(double);
  3616. typedef float(__cdecl *FloatBinaryEvalFuncType)(float, float);
  3617. typedef double(__cdecl *DoubleBinaryEvalFuncType)(double, double);
  3618. static Value * EvalUnaryIntrinsic(ConstantFP *fpV,
  3619. FloatUnaryEvalFuncType floatEvalFunc,
  3620. DoubleUnaryEvalFuncType doubleEvalFunc) {
  3621. llvm::Type *Ty = fpV->getType();
  3622. Value *Result = nullptr;
  3623. if (Ty->isDoubleTy()) {
  3624. double dV = fpV->getValueAPF().convertToDouble();
  3625. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV));
  3626. Result = dResult;
  3627. } else {
  3628. DXASSERT_NOMSG(Ty->isFloatTy());
  3629. float fV = fpV->getValueAPF().convertToFloat();
  3630. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV));
  3631. Result = dResult;
  3632. }
  3633. return Result;
  3634. }
  3635. static Value * EvalBinaryIntrinsic(ConstantFP *fpV0, ConstantFP *fpV1,
  3636. FloatBinaryEvalFuncType floatEvalFunc,
  3637. DoubleBinaryEvalFuncType doubleEvalFunc) {
  3638. llvm::Type *Ty = fpV0->getType();
  3639. Value *Result = nullptr;
  3640. if (Ty->isDoubleTy()) {
  3641. double dV0 = fpV0->getValueAPF().convertToDouble();
  3642. double dV1 = fpV1->getValueAPF().convertToDouble();
  3643. Value *dResult = ConstantFP::get(Ty, doubleEvalFunc(dV0, dV1));
  3644. Result = dResult;
  3645. } else {
  3646. DXASSERT_NOMSG(Ty->isFloatTy());
  3647. float fV0 = fpV0->getValueAPF().convertToFloat();
  3648. float fV1 = fpV1->getValueAPF().convertToFloat();
  3649. Value *dResult = ConstantFP::get(Ty, floatEvalFunc(fV0, fV1));
  3650. Result = dResult;
  3651. }
  3652. return Result;
  3653. }
  3654. static Value * EvalUnaryIntrinsic(CallInst *CI,
  3655. FloatUnaryEvalFuncType floatEvalFunc,
  3656. DoubleUnaryEvalFuncType doubleEvalFunc) {
  3657. Value *V = CI->getArgOperand(0);
  3658. llvm::Type *Ty = CI->getType();
  3659. Value *Result = nullptr;
  3660. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  3661. Result = UndefValue::get(Ty);
  3662. Constant *CV = cast<Constant>(V);
  3663. IRBuilder<> Builder(CI);
  3664. for (unsigned i=0;i<VT->getNumElements();i++) {
  3665. ConstantFP *fpV = cast<ConstantFP>(CV->getAggregateElement(i));
  3666. Value *EltResult = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  3667. Result = Builder.CreateInsertElement(Result, EltResult, i);
  3668. }
  3669. } else {
  3670. ConstantFP *fpV = cast<ConstantFP>(V);
  3671. Result = EvalUnaryIntrinsic(fpV, floatEvalFunc, doubleEvalFunc);
  3672. }
  3673. CI->replaceAllUsesWith(Result);
  3674. CI->eraseFromParent();
  3675. return Result;
  3676. }
  3677. static Value * EvalBinaryIntrinsic(CallInst *CI,
  3678. FloatBinaryEvalFuncType floatEvalFunc,
  3679. DoubleBinaryEvalFuncType doubleEvalFunc) {
  3680. Value *V0 = CI->getArgOperand(0);
  3681. Value *V1 = CI->getArgOperand(1);
  3682. llvm::Type *Ty = CI->getType();
  3683. Value *Result = nullptr;
  3684. if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  3685. Result = UndefValue::get(Ty);
  3686. Constant *CV0 = cast<Constant>(V0);
  3687. Constant *CV1 = cast<Constant>(V1);
  3688. IRBuilder<> Builder(CI);
  3689. for (unsigned i=0;i<VT->getNumElements();i++) {
  3690. ConstantFP *fpV0 = cast<ConstantFP>(CV0->getAggregateElement(i));
  3691. ConstantFP *fpV1 = cast<ConstantFP>(CV1->getAggregateElement(i));
  3692. Value *EltResult = EvalBinaryIntrinsic(fpV0, fpV1, floatEvalFunc, doubleEvalFunc);
  3693. Result = Builder.CreateInsertElement(Result, EltResult, i);
  3694. }
  3695. } else {
  3696. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3697. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3698. Result = EvalBinaryIntrinsic(fpV0, fpV1, floatEvalFunc, doubleEvalFunc);
  3699. }
  3700. CI->replaceAllUsesWith(Result);
  3701. CI->eraseFromParent();
  3702. return Result;
  3703. CI->eraseFromParent();
  3704. return Result;
  3705. }
  3706. static Value * TryEvalIntrinsic(CallInst *CI, IntrinsicOp intriOp) {
  3707. switch (intriOp) {
  3708. case IntrinsicOp::IOP_tan: {
  3709. return EvalUnaryIntrinsic(CI, tanf, tan);
  3710. } break;
  3711. case IntrinsicOp::IOP_tanh: {
  3712. return EvalUnaryIntrinsic(CI, tanhf, tanh);
  3713. } break;
  3714. case IntrinsicOp::IOP_sin: {
  3715. return EvalUnaryIntrinsic(CI, sinf, sin);
  3716. } break;
  3717. case IntrinsicOp::IOP_sinh: {
  3718. return EvalUnaryIntrinsic(CI, sinhf, sinh);
  3719. } break;
  3720. case IntrinsicOp::IOP_cos: {
  3721. return EvalUnaryIntrinsic(CI, cosf, cos);
  3722. } break;
  3723. case IntrinsicOp::IOP_cosh: {
  3724. return EvalUnaryIntrinsic(CI, coshf, cosh);
  3725. } break;
  3726. case IntrinsicOp::IOP_asin: {
  3727. return EvalUnaryIntrinsic(CI, asinf, asin);
  3728. } break;
  3729. case IntrinsicOp::IOP_acos: {
  3730. return EvalUnaryIntrinsic(CI, acosf, acos);
  3731. } break;
  3732. case IntrinsicOp::IOP_atan: {
  3733. return EvalUnaryIntrinsic(CI, atanf, atan);
  3734. } break;
  3735. case IntrinsicOp::IOP_atan2: {
  3736. Value *V0 = CI->getArgOperand(0);
  3737. ConstantFP *fpV0 = cast<ConstantFP>(V0);
  3738. Value *V1 = CI->getArgOperand(1);
  3739. ConstantFP *fpV1 = cast<ConstantFP>(V1);
  3740. llvm::Type *Ty = CI->getType();
  3741. Value *Result = nullptr;
  3742. if (Ty->isDoubleTy()) {
  3743. double dV0 = fpV0->getValueAPF().convertToDouble();
  3744. double dV1 = fpV1->getValueAPF().convertToDouble();
  3745. Value *atanV = ConstantFP::get(CI->getType(), atan2(dV0, dV1));
  3746. CI->replaceAllUsesWith(atanV);
  3747. Result = atanV;
  3748. } else {
  3749. DXASSERT_NOMSG(Ty->isFloatTy());
  3750. float fV0 = fpV0->getValueAPF().convertToFloat();
  3751. float fV1 = fpV1->getValueAPF().convertToFloat();
  3752. Value *atanV = ConstantFP::get(CI->getType(), atan2f(fV0, fV1));
  3753. CI->replaceAllUsesWith(atanV);
  3754. Result = atanV;
  3755. }
  3756. CI->eraseFromParent();
  3757. return Result;
  3758. } break;
  3759. case IntrinsicOp::IOP_sqrt: {
  3760. return EvalUnaryIntrinsic(CI, sqrtf, sqrt);
  3761. } break;
  3762. case IntrinsicOp::IOP_rsqrt: {
  3763. auto rsqrtF = [](float v) -> float { return 1.0 / sqrtf(v); };
  3764. auto rsqrtD = [](double v) -> double { return 1.0 / sqrt(v); };
  3765. return EvalUnaryIntrinsic(CI, rsqrtF, rsqrtD);
  3766. } break;
  3767. case IntrinsicOp::IOP_exp: {
  3768. return EvalUnaryIntrinsic(CI, expf, exp);
  3769. } break;
  3770. case IntrinsicOp::IOP_exp2: {
  3771. return EvalUnaryIntrinsic(CI, exp2f, exp2);
  3772. } break;
  3773. case IntrinsicOp::IOP_log: {
  3774. return EvalUnaryIntrinsic(CI, logf, log);
  3775. } break;
  3776. case IntrinsicOp::IOP_log10: {
  3777. return EvalUnaryIntrinsic(CI, log10f, log10);
  3778. } break;
  3779. case IntrinsicOp::IOP_log2: {
  3780. return EvalUnaryIntrinsic(CI, log2f, log2);
  3781. } break;
  3782. case IntrinsicOp::IOP_pow: {
  3783. return EvalBinaryIntrinsic(CI, powf, pow);
  3784. } break;
  3785. case IntrinsicOp::IOP_max: {
  3786. auto maxF = [](float a, float b) -> float { return a > b ? a:b; };
  3787. auto maxD = [](double a, double b) -> double { return a > b ? a:b; };
  3788. // Handled in DXIL constant folding
  3789. if (CI->getArgOperand(0)->getType()->getScalarType()->isIntegerTy())
  3790. return nullptr;
  3791. return EvalBinaryIntrinsic(CI, maxF, maxD);
  3792. } break;
  3793. case IntrinsicOp::IOP_min: {
  3794. auto minF = [](float a, float b) -> float { return a < b ? a:b; };
  3795. auto minD = [](double a, double b) -> double { return a < b ? a:b; };
  3796. // Handled in DXIL constant folding
  3797. if (CI->getArgOperand(0)->getType()->getScalarType()->isIntegerTy())
  3798. return nullptr;
  3799. return EvalBinaryIntrinsic(CI, minF, minD);
  3800. } break;
  3801. case IntrinsicOp::IOP_rcp: {
  3802. auto rcpF = [](float v) -> float { return 1.0 / v; };
  3803. auto rcpD = [](double v) -> double { return 1.0 / v; };
  3804. return EvalUnaryIntrinsic(CI, rcpF, rcpD);
  3805. } break;
  3806. case IntrinsicOp::IOP_ceil: {
  3807. return EvalUnaryIntrinsic(CI, ceilf, ceil);
  3808. } break;
  3809. case IntrinsicOp::IOP_floor: {
  3810. return EvalUnaryIntrinsic(CI, floorf, floor);
  3811. } break;
  3812. case IntrinsicOp::IOP_round: {
  3813. return EvalUnaryIntrinsic(CI, roundf, round);
  3814. } break;
  3815. case IntrinsicOp::IOP_trunc: {
  3816. return EvalUnaryIntrinsic(CI, truncf, trunc);
  3817. } break;
  3818. case IntrinsicOp::IOP_frac: {
  3819. auto fracF = [](float v) -> float {
  3820. int exp = 0;
  3821. return frexpf(v, &exp);
  3822. };
  3823. auto fracD = [](double v) -> double {
  3824. int exp = 0;
  3825. return frexp(v, &exp);
  3826. };
  3827. return EvalUnaryIntrinsic(CI, fracF, fracD);
  3828. } break;
  3829. case IntrinsicOp::IOP_isnan: {
  3830. Value *V = CI->getArgOperand(0);
  3831. ConstantFP *fV = cast<ConstantFP>(V);
  3832. bool isNan = fV->getValueAPF().isNaN();
  3833. Constant *cNan = ConstantInt::get(CI->getType(), isNan ? 1 : 0);
  3834. CI->replaceAllUsesWith(cNan);
  3835. CI->eraseFromParent();
  3836. return cNan;
  3837. } break;
  3838. default:
  3839. return nullptr;
  3840. }
  3841. }
  3842. static void SimpleTransformForHLDXIR(Instruction *I,
  3843. SmallInstSet &deadInsts) {
  3844. unsigned opcode = I->getOpcode();
  3845. switch (opcode) {
  3846. case Instruction::BitCast: {
  3847. BitCastOperator *BCI = cast<BitCastOperator>(I);
  3848. SimplifyBitCast(BCI, deadInsts);
  3849. } break;
  3850. case Instruction::Load: {
  3851. LoadInst *ldInst = cast<LoadInst>(I);
  3852. DXASSERT(!HLMatrixType::isa(ldInst->getType()),
  3853. "matrix load should use HL LdStMatrix");
  3854. Value *Ptr = ldInst->getPointerOperand();
  3855. if (ConstantExpr *CE = dyn_cast_or_null<ConstantExpr>(Ptr)) {
  3856. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3857. SimplifyBitCast(BCO, deadInsts);
  3858. }
  3859. }
  3860. } break;
  3861. case Instruction::Store: {
  3862. StoreInst *stInst = cast<StoreInst>(I);
  3863. Value *V = stInst->getValueOperand();
  3864. DXASSERT_LOCALVAR(V, !HLMatrixType::isa(V->getType()),
  3865. "matrix store should use HL LdStMatrix");
  3866. Value *Ptr = stInst->getPointerOperand();
  3867. if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ptr)) {
  3868. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(CE)) {
  3869. SimplifyBitCast(BCO, deadInsts);
  3870. }
  3871. }
  3872. } break;
  3873. case Instruction::LShr:
  3874. case Instruction::AShr:
  3875. case Instruction::Shl: {
  3876. llvm::BinaryOperator *BO = cast<llvm::BinaryOperator>(I);
  3877. Value *op2 = BO->getOperand(1);
  3878. IntegerType *Ty = cast<IntegerType>(BO->getType()->getScalarType());
  3879. unsigned bitWidth = Ty->getBitWidth();
  3880. // Clamp op2 to 0 ~ bitWidth-1
  3881. if (ConstantInt *cOp2 = dyn_cast<ConstantInt>(op2)) {
  3882. unsigned iOp2 = cOp2->getLimitedValue();
  3883. unsigned clampedOp2 = iOp2 & (bitWidth - 1);
  3884. if (iOp2 != clampedOp2) {
  3885. BO->setOperand(1, ConstantInt::get(op2->getType(), clampedOp2));
  3886. }
  3887. } else {
  3888. Value *mask = ConstantInt::get(op2->getType(), bitWidth - 1);
  3889. IRBuilder<> Builder(I);
  3890. op2 = Builder.CreateAnd(op2, mask);
  3891. BO->setOperand(1, op2);
  3892. }
  3893. } break;
  3894. }
  3895. }
  3896. // Do simple transform to make later lower pass easier.
  3897. static void SimpleTransformForHLDXIR(llvm::Module *pM) {
  3898. SmallInstSet deadInsts;
  3899. for (Function &F : pM->functions()) {
  3900. for (BasicBlock &BB : F.getBasicBlockList()) {
  3901. for (BasicBlock::iterator Iter = BB.begin(); Iter != BB.end(); ) {
  3902. Instruction *I = (Iter++);
  3903. if (deadInsts.count(I))
  3904. continue; // Skip dead instructions
  3905. SimpleTransformForHLDXIR(I, deadInsts);
  3906. }
  3907. }
  3908. }
  3909. for (Instruction * I : deadInsts)
  3910. I->dropAllReferences();
  3911. for (Instruction * I : deadInsts)
  3912. I->eraseFromParent();
  3913. deadInsts.clear();
  3914. for (GlobalVariable &GV : pM->globals()) {
  3915. if (dxilutil::IsStaticGlobal(&GV)) {
  3916. for (User *U : GV.users()) {
  3917. if (BitCastOperator *BCO = dyn_cast<BitCastOperator>(U)) {
  3918. SimplifyBitCast(BCO, deadInsts);
  3919. }
  3920. }
  3921. }
  3922. }
  3923. for (Instruction * I : deadInsts)
  3924. I->dropAllReferences();
  3925. for (Instruction * I : deadInsts)
  3926. I->eraseFromParent();
  3927. }
  3928. static Function *CloneFunction(Function *Orig,
  3929. const llvm::Twine &Name,
  3930. llvm::Module *llvmModule,
  3931. hlsl::DxilTypeSystem &TypeSys,
  3932. hlsl::DxilTypeSystem &SrcTypeSys) {
  3933. Function *F = Function::Create(Orig->getFunctionType(),
  3934. GlobalValue::LinkageTypes::ExternalLinkage,
  3935. Name, llvmModule);
  3936. SmallVector<ReturnInst *, 2> Returns;
  3937. ValueToValueMapTy vmap;
  3938. // Map params.
  3939. auto entryParamIt = F->arg_begin();
  3940. for (Argument &param : Orig->args()) {
  3941. vmap[&param] = (entryParamIt++);
  3942. }
  3943. llvm::CloneFunctionInto(F, Orig, vmap, /*ModuleLevelChagnes*/ false, Returns);
  3944. TypeSys.CopyFunctionAnnotation(F, Orig, SrcTypeSys);
  3945. return F;
  3946. }
  3947. // Clone shader entry function to be called by other functions.
  3948. // The original function will be used as shader entry.
  3949. static void CloneShaderEntry(Function *ShaderF, StringRef EntryName,
  3950. HLModule &HLM) {
  3951. Function *F = CloneFunction(ShaderF, "", HLM.GetModule(),
  3952. HLM.GetTypeSystem(), HLM.GetTypeSystem());
  3953. F->takeName(ShaderF);
  3954. F->setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  3955. // Set to name before mangled.
  3956. ShaderF->setName(EntryName);
  3957. DxilFunctionAnnotation *annot = HLM.GetFunctionAnnotation(F);
  3958. DxilParameterAnnotation &cloneRetAnnot = annot->GetRetTypeAnnotation();
  3959. // Clear semantic for cloned one.
  3960. cloneRetAnnot.SetSemanticString("");
  3961. cloneRetAnnot.SetSemanticIndexVec({});
  3962. for (unsigned i = 0; i < annot->GetNumParameters(); i++) {
  3963. DxilParameterAnnotation &cloneParamAnnot = annot->GetParameterAnnotation(i);
  3964. // Clear semantic for cloned one.
  3965. cloneParamAnnot.SetSemanticString("");
  3966. cloneParamAnnot.SetSemanticIndexVec({});
  3967. }
  3968. }
  3969. // For case like:
  3970. //cbuffer A {
  3971. // float a;
  3972. // int b;
  3973. //}
  3974. //
  3975. //const static struct {
  3976. // float a;
  3977. // int b;
  3978. //} ST = { a, b };
  3979. // Replace user of ST with a and b.
  3980. static bool ReplaceConstStaticGlobalUser(GEPOperator *GEP,
  3981. std::vector<Constant *> &InitList,
  3982. IRBuilder<> &Builder) {
  3983. if (GEP->getNumIndices() < 2) {
  3984. // Don't use sub element.
  3985. return false;
  3986. }
  3987. SmallVector<Value *, 4> idxList;
  3988. auto iter = GEP->idx_begin();
  3989. idxList.emplace_back(*(iter++));
  3990. ConstantInt *subIdx = dyn_cast<ConstantInt>(*(iter++));
  3991. DXASSERT(subIdx, "else dynamic indexing on struct field");
  3992. unsigned subIdxImm = subIdx->getLimitedValue();
  3993. DXASSERT(subIdxImm < InitList.size(), "else struct index out of bound");
  3994. Constant *subPtr = InitList[subIdxImm];
  3995. // Move every idx to idxList except idx for InitList.
  3996. while (iter != GEP->idx_end()) {
  3997. idxList.emplace_back(*(iter++));
  3998. }
  3999. Value *NewGEP = Builder.CreateGEP(subPtr, idxList);
  4000. GEP->replaceAllUsesWith(NewGEP);
  4001. return true;
  4002. }
  4003. static void ReplaceConstStaticGlobals(
  4004. std::unordered_map<GlobalVariable *, std::vector<Constant *>>
  4005. &staticConstGlobalInitListMap,
  4006. std::unordered_map<GlobalVariable *, Function *>
  4007. &staticConstGlobalCtorMap) {
  4008. for (auto &iter : staticConstGlobalInitListMap) {
  4009. GlobalVariable *GV = iter.first;
  4010. std::vector<Constant *> &InitList = iter.second;
  4011. LLVMContext &Ctx = GV->getContext();
  4012. // Do the replace.
  4013. bool bPass = true;
  4014. for (User *U : GV->users()) {
  4015. IRBuilder<> Builder(Ctx);
  4016. if (GetElementPtrInst *GEPInst = dyn_cast<GetElementPtrInst>(U)) {
  4017. Builder.SetInsertPoint(GEPInst);
  4018. bPass &= ReplaceConstStaticGlobalUser(cast<GEPOperator>(GEPInst), InitList, Builder);
  4019. } else if (GEPOperator *GEP = dyn_cast<GEPOperator>(U)) {
  4020. bPass &= ReplaceConstStaticGlobalUser(GEP, InitList, Builder);
  4021. } else {
  4022. DXASSERT(false, "invalid user of const static global");
  4023. }
  4024. }
  4025. // Clear the Ctor which is useless now.
  4026. if (bPass) {
  4027. Function *Ctor = staticConstGlobalCtorMap[GV];
  4028. Ctor->getBasicBlockList().clear();
  4029. BasicBlock *Entry = BasicBlock::Create(Ctx, "", Ctor);
  4030. IRBuilder<> Builder(Entry);
  4031. Builder.CreateRetVoid();
  4032. }
  4033. }
  4034. }
  4035. bool BuildImmInit(Function *Ctor) {
  4036. GlobalVariable *GV = nullptr;
  4037. SmallVector<Constant *, 4> ImmList;
  4038. bool allConst = true;
  4039. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E; ++I) {
  4040. if (StoreInst *SI = dyn_cast<StoreInst>(&(*I))) {
  4041. Value *V = SI->getValueOperand();
  4042. if (!isa<Constant>(V) || V->getType()->isPointerTy()) {
  4043. allConst = false;
  4044. break;
  4045. }
  4046. ImmList.emplace_back(cast<Constant>(V));
  4047. Value *Ptr = SI->getPointerOperand();
  4048. if (GEPOperator *GepOp = dyn_cast<GEPOperator>(Ptr)) {
  4049. Ptr = GepOp->getPointerOperand();
  4050. if (GlobalVariable *pGV = dyn_cast<GlobalVariable>(Ptr)) {
  4051. if (GV == nullptr)
  4052. GV = pGV;
  4053. else {
  4054. DXASSERT(GV == pGV, "else pointer mismatch");
  4055. }
  4056. }
  4057. }
  4058. } else {
  4059. if (!isa<ReturnInst>(*I)) {
  4060. allConst = false;
  4061. break;
  4062. }
  4063. }
  4064. }
  4065. if (!allConst)
  4066. return false;
  4067. if (!GV)
  4068. return false;
  4069. llvm::Type *Ty = GV->getType()->getElementType();
  4070. llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty);
  4071. // TODO: support other types.
  4072. if (!AT)
  4073. return false;
  4074. if (ImmList.size() != AT->getNumElements())
  4075. return false;
  4076. Constant *Init = llvm::ConstantArray::get(AT, ImmList);
  4077. GV->setInitializer(Init);
  4078. return true;
  4079. }
  4080. void ProcessCtorFunctions(llvm::Module &M, StringRef globalName,
  4081. Instruction *InsertPt) {
  4082. // add global call to entry func
  4083. GlobalVariable *GV = M.getGlobalVariable(globalName);
  4084. if (GV) {
  4085. if (ConstantArray *CA = dyn_cast<ConstantArray>(GV->getInitializer())) {
  4086. IRBuilder<> Builder(InsertPt);
  4087. for (User::op_iterator i = CA->op_begin(), e = CA->op_end(); i != e;
  4088. ++i) {
  4089. if (isa<ConstantAggregateZero>(*i))
  4090. continue;
  4091. ConstantStruct *CS = cast<ConstantStruct>(*i);
  4092. if (isa<ConstantPointerNull>(CS->getOperand(1)))
  4093. continue;
  4094. // Must have a function or null ptr.
  4095. if (!isa<Function>(CS->getOperand(1)))
  4096. continue;
  4097. Function *Ctor = cast<Function>(CS->getOperand(1));
  4098. DXASSERT(Ctor->getReturnType()->isVoidTy() && Ctor->arg_size() == 0,
  4099. "function type must be void (void)");
  4100. for (inst_iterator I = inst_begin(Ctor), E = inst_end(Ctor); I != E;
  4101. ++I) {
  4102. if (CallInst *CI = dyn_cast<CallInst>(&(*I))) {
  4103. Function *F = CI->getCalledFunction();
  4104. // Try to build imm initilizer.
  4105. // If not work, add global call to entry func.
  4106. if (BuildImmInit(F) == false) {
  4107. Builder.CreateCall(F);
  4108. }
  4109. } else {
  4110. DXASSERT(isa<ReturnInst>(&(*I)),
  4111. "else invalid Global constructor function");
  4112. }
  4113. }
  4114. }
  4115. // remove the GV
  4116. GV->eraseFromParent();
  4117. }
  4118. }
  4119. }
  4120. void CGMSHLSLRuntime::SetPatchConstantFunction(const EntryFunctionInfo &EntryFunc) {
  4121. auto AttrsIter = HSEntryPatchConstantFuncAttr.find(EntryFunc.Func);
  4122. DXASSERT(AttrsIter != HSEntryPatchConstantFuncAttr.end(),
  4123. "we have checked this in AddHLSLFunctionInfo()");
  4124. SetPatchConstantFunctionWithAttr(Entry, AttrsIter->second);
  4125. }
  4126. void CGMSHLSLRuntime::SetPatchConstantFunctionWithAttr(
  4127. const EntryFunctionInfo &EntryFunc,
  4128. const clang::HLSLPatchConstantFuncAttr *PatchConstantFuncAttr) {
  4129. StringRef funcName = PatchConstantFuncAttr->getFunctionName();
  4130. auto Entry = patchConstantFunctionMap.find(funcName);
  4131. if (Entry == patchConstantFunctionMap.end()) {
  4132. DiagnosticsEngine &Diags = CGM.getDiags();
  4133. unsigned DiagID =
  4134. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  4135. "Cannot find patchconstantfunc %0.");
  4136. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  4137. << funcName;
  4138. return;
  4139. }
  4140. if (Entry->second.NumOverloads != 1) {
  4141. DiagnosticsEngine &Diags = CGM.getDiags();
  4142. unsigned DiagID =
  4143. Diags.getCustomDiagID(DiagnosticsEngine::Warning,
  4144. "Multiple overloads of patchconstantfunc %0.");
  4145. unsigned NoteID =
  4146. Diags.getCustomDiagID(DiagnosticsEngine::Note,
  4147. "This overload was selected.");
  4148. Diags.Report(PatchConstantFuncAttr->getLocation(), DiagID)
  4149. << funcName;
  4150. Diags.Report(Entry->second.SL, NoteID);
  4151. }
  4152. Function *patchConstFunc = Entry->second.Func;
  4153. DXASSERT(m_pHLModule->HasDxilFunctionProps(EntryFunc.Func),
  4154. " else AddHLSLFunctionInfo did not save the dxil function props for the "
  4155. "HS entry.");
  4156. DxilFunctionProps *HSProps = &m_pHLModule->GetDxilFunctionProps(EntryFunc.Func);
  4157. m_pHLModule->SetPatchConstantFunctionForHS(EntryFunc.Func, patchConstFunc);
  4158. DXASSERT_NOMSG(patchConstantFunctionPropsMap.count(patchConstFunc));
  4159. // Check no inout parameter for patch constant function.
  4160. DxilFunctionAnnotation *patchConstFuncAnnotation =
  4161. m_pHLModule->GetFunctionAnnotation(patchConstFunc);
  4162. for (unsigned i = 0; i < patchConstFuncAnnotation->GetNumParameters(); i++) {
  4163. if (patchConstFuncAnnotation->GetParameterAnnotation(i)
  4164. .GetParamInputQual() == DxilParamInputQual::Inout) {
  4165. DiagnosticsEngine &Diags = CGM.getDiags();
  4166. unsigned DiagID = Diags.getCustomDiagID(
  4167. DiagnosticsEngine::Error,
  4168. "Patch Constant function %0 should not have inout param.");
  4169. Diags.Report(Entry->second.SL, DiagID) << funcName;
  4170. }
  4171. }
  4172. // Input/Output control point validation.
  4173. if (patchConstantFunctionPropsMap.count(patchConstFunc)) {
  4174. const DxilFunctionProps &patchProps =
  4175. *patchConstantFunctionPropsMap[patchConstFunc];
  4176. if (patchProps.ShaderProps.HS.inputControlPoints != 0 &&
  4177. patchProps.ShaderProps.HS.inputControlPoints !=
  4178. HSProps->ShaderProps.HS.inputControlPoints) {
  4179. DiagnosticsEngine &Diags = CGM.getDiags();
  4180. unsigned DiagID =
  4181. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  4182. "Patch constant function's input patch input "
  4183. "should have %0 elements, but has %1.");
  4184. Diags.Report(Entry->second.SL, DiagID)
  4185. << HSProps->ShaderProps.HS.inputControlPoints
  4186. << patchProps.ShaderProps.HS.inputControlPoints;
  4187. }
  4188. if (patchProps.ShaderProps.HS.outputControlPoints != 0 &&
  4189. patchProps.ShaderProps.HS.outputControlPoints !=
  4190. HSProps->ShaderProps.HS.outputControlPoints) {
  4191. DiagnosticsEngine &Diags = CGM.getDiags();
  4192. unsigned DiagID = Diags.getCustomDiagID(
  4193. DiagnosticsEngine::Error,
  4194. "Patch constant function's output patch input "
  4195. "should have %0 elements, but has %1.");
  4196. Diags.Report(Entry->second.SL, DiagID)
  4197. << HSProps->ShaderProps.HS.outputControlPoints
  4198. << patchProps.ShaderProps.HS.outputControlPoints;
  4199. }
  4200. }
  4201. }
  4202. static void ReportDisallowedTypeInExportParam(CodeGenModule &CGM, StringRef name) {
  4203. DiagnosticsEngine &Diags = CGM.getDiags();
  4204. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  4205. "Exported function %0 must not contain a resource in parameter or return type.");
  4206. std::string escaped;
  4207. llvm::raw_string_ostream os(escaped);
  4208. dxilutil::PrintEscapedString(name, os);
  4209. Diags.Report(DiagID) << os.str();
  4210. }
  4211. // Returns true a global value is being updated
  4212. static bool GlobalHasStoreUserRec(Value *V, std::set<Value *> &visited) {
  4213. bool isWriteEnabled = false;
  4214. if (V && visited.find(V) == visited.end()) {
  4215. visited.insert(V);
  4216. for (User *U : V->users()) {
  4217. if (isa<StoreInst>(U)) {
  4218. return true;
  4219. } else if (CallInst* CI = dyn_cast<CallInst>(U)) {
  4220. Function *F = CI->getCalledFunction();
  4221. if (!F->isIntrinsic()) {
  4222. HLOpcodeGroup hlGroup = GetHLOpcodeGroup(F);
  4223. switch (hlGroup) {
  4224. case HLOpcodeGroup::NotHL:
  4225. return true;
  4226. case HLOpcodeGroup::HLMatLoadStore:
  4227. {
  4228. HLMatLoadStoreOpcode opCode = static_cast<HLMatLoadStoreOpcode>(hlsl::GetHLOpcode(CI));
  4229. if (opCode == HLMatLoadStoreOpcode::ColMatStore || opCode == HLMatLoadStoreOpcode::RowMatStore)
  4230. return true;
  4231. break;
  4232. }
  4233. case HLOpcodeGroup::HLCast:
  4234. case HLOpcodeGroup::HLSubscript:
  4235. if (GlobalHasStoreUserRec(U, visited))
  4236. return true;
  4237. break;
  4238. default:
  4239. break;
  4240. }
  4241. }
  4242. } else if (isa<GEPOperator>(U) || isa<PHINode>(U) || isa<SelectInst>(U)) {
  4243. if (GlobalHasStoreUserRec(U, visited))
  4244. return true;
  4245. }
  4246. }
  4247. }
  4248. return isWriteEnabled;
  4249. }
  4250. // Returns true if any of the direct user of a global is a store inst
  4251. // otherwise recurse through the remaining users and check if any GEP
  4252. // exists and which in turn has a store inst as user.
  4253. static bool GlobalHasStoreUser(GlobalVariable *GV) {
  4254. std::set<Value *> visited;
  4255. Value *V = cast<Value>(GV);
  4256. return GlobalHasStoreUserRec(V, visited);
  4257. }
  4258. static GlobalVariable *CreateStaticGlobal(llvm::Module *M, GlobalVariable *GV) {
  4259. Constant *GC = M->getOrInsertGlobal(GV->getName().str() + ".static.copy",
  4260. GV->getType()->getPointerElementType());
  4261. GlobalVariable *NGV = cast<GlobalVariable>(GC);
  4262. if (GV->hasInitializer()) {
  4263. NGV->setInitializer(GV->getInitializer());
  4264. } else {
  4265. // The copy being static, it should be initialized per llvm rules
  4266. NGV->setInitializer(Constant::getNullValue(GV->getType()->getPointerElementType()));
  4267. }
  4268. // static global should have internal linkage
  4269. NGV->setLinkage(GlobalValue::InternalLinkage);
  4270. return NGV;
  4271. }
  4272. static void CreateWriteEnabledStaticGlobals(llvm::Module *M,
  4273. llvm::Function *EF) {
  4274. std::vector<GlobalVariable *> worklist;
  4275. for (GlobalVariable &GV : M->globals()) {
  4276. if (!GV.isConstant() && GV.getLinkage() != GlobalValue::InternalLinkage &&
  4277. // skip globals which are HLSL objects or group shared
  4278. !dxilutil::IsHLSLObjectType(GV.getType()->getPointerElementType()) &&
  4279. !dxilutil::IsSharedMemoryGlobal(&GV)) {
  4280. if (GlobalHasStoreUser(&GV))
  4281. worklist.emplace_back(&GV);
  4282. // TODO: Ensure that constant globals aren't using initializer
  4283. GV.setConstant(true);
  4284. }
  4285. }
  4286. IRBuilder<> Builder(
  4287. dxilutil::FirstNonAllocaInsertionPt(&EF->getEntryBlock()));
  4288. for (GlobalVariable *GV : worklist) {
  4289. GlobalVariable *NGV = CreateStaticGlobal(M, GV);
  4290. GV->replaceAllUsesWith(NGV);
  4291. // insert memcpy in all entryblocks
  4292. uint64_t size = M->getDataLayout().getTypeAllocSize(
  4293. GV->getType()->getPointerElementType());
  4294. Builder.CreateMemCpy(NGV, GV, size, 1);
  4295. }
  4296. }
  4297. void CGMSHLSLRuntime::FinishCodeGen() {
  4298. // Library don't have entry.
  4299. if (!m_bIsLib) {
  4300. SetEntryFunction();
  4301. // If at this point we haven't determined the entry function it's an error.
  4302. if (m_pHLModule->GetEntryFunction() == nullptr) {
  4303. assert(CGM.getDiags().hasErrorOccurred() &&
  4304. "else SetEntryFunction should have reported this condition");
  4305. return;
  4306. }
  4307. // In back-compat mode (with /Gec flag) create a static global for each const global
  4308. // to allow writing to it.
  4309. // TODO: Verfiy the behavior of static globals in hull shader
  4310. if(CGM.getLangOpts().EnableDX9CompatMode && CGM.getLangOpts().HLSLVersion <= 2016)
  4311. CreateWriteEnabledStaticGlobals(m_pHLModule->GetModule(), m_pHLModule->GetEntryFunction());
  4312. if (m_pHLModule->GetShaderModel()->IsHS()) {
  4313. SetPatchConstantFunction(Entry);
  4314. }
  4315. } else {
  4316. for (auto &it : entryFunctionMap) {
  4317. // skip clone if RT entry
  4318. if (m_pHLModule->GetDxilFunctionProps(it.second.Func).IsRay())
  4319. continue;
  4320. // TODO: change flattened function names to dx.entry.<name>:
  4321. //std::string entryName = (Twine(dxilutil::EntryPrefix) + it.getKey()).str();
  4322. CloneShaderEntry(it.second.Func, it.getKey(), *m_pHLModule);
  4323. auto AttrIter = HSEntryPatchConstantFuncAttr.find(it.second.Func);
  4324. if (AttrIter != HSEntryPatchConstantFuncAttr.end()) {
  4325. SetPatchConstantFunctionWithAttr(it.second, AttrIter->second);
  4326. }
  4327. }
  4328. }
  4329. ReplaceConstStaticGlobals(staticConstGlobalInitListMap,
  4330. staticConstGlobalCtorMap);
  4331. // Create copy for clip plane.
  4332. for (Function *F : clipPlaneFuncList) {
  4333. DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(F);
  4334. IRBuilder<> Builder(F->getEntryBlock().getFirstInsertionPt());
  4335. for (unsigned i = 0; i < DXIL::kNumClipPlanes; i++) {
  4336. Value *clipPlane = props.ShaderProps.VS.clipPlanes[i];
  4337. if (!clipPlane)
  4338. continue;
  4339. if (m_bDebugInfo) {
  4340. Builder.SetCurrentDebugLocation(debugInfoMap[clipPlane]);
  4341. }
  4342. llvm::Type *Ty = clipPlane->getType()->getPointerElementType();
  4343. // Constant *zeroInit = ConstantFP::get(Ty, 0);
  4344. GlobalVariable *GV = new llvm::GlobalVariable(
  4345. TheModule, Ty, /*IsConstant*/ false, // constant false to store.
  4346. llvm::GlobalValue::ExternalLinkage,
  4347. /*InitVal*/ nullptr, Twine("SV_ClipPlane") + Twine(i));
  4348. Value *initVal = Builder.CreateLoad(clipPlane);
  4349. Builder.CreateStore(initVal, GV);
  4350. props.ShaderProps.VS.clipPlanes[i] = GV;
  4351. }
  4352. }
  4353. // Allocate constant buffers.
  4354. AllocateDxilConstantBuffers(m_pHLModule);
  4355. // TODO: create temp variable for constant which has store use.
  4356. // Create Global variable and type annotation for each CBuffer.
  4357. ConstructCBuffer(m_pHLModule, CBufferType, m_ConstVarAnnotationMap);
  4358. if (!m_bIsLib) {
  4359. // need this for "llvm.global_dtors"?
  4360. ProcessCtorFunctions(TheModule ,"llvm.global_ctors",
  4361. Entry.Func->getEntryBlock().getFirstInsertionPt());
  4362. }
  4363. // translate opcode into parameter for intrinsic functions
  4364. AddOpcodeParamForIntrinsics(*m_pHLModule, m_IntrinsicMap, resMetadataMap);
  4365. // Register patch constant functions referenced by exported Hull Shaders
  4366. if (m_bIsLib && !m_ExportMap.empty()) {
  4367. for (auto &it : entryFunctionMap) {
  4368. if (m_pHLModule->HasDxilFunctionProps(it.second.Func)) {
  4369. const DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(it.second.Func);
  4370. if (props.IsHS())
  4371. m_ExportMap.RegisterExportedFunction(props.ShaderProps.HS.patchConstantFunc);
  4372. }
  4373. }
  4374. }
  4375. // Pin entry point and constant buffers, mark everything else internal.
  4376. for (Function &f : m_pHLModule->GetModule()->functions()) {
  4377. if (!m_bIsLib) {
  4378. if (&f == m_pHLModule->GetEntryFunction() ||
  4379. IsPatchConstantFunction(&f) || f.isDeclaration()) {
  4380. if (f.isDeclaration() && !f.isIntrinsic() &&
  4381. GetHLOpcodeGroup(&f) == HLOpcodeGroup::NotHL) {
  4382. DiagnosticsEngine &Diags = CGM.getDiags();
  4383. unsigned DiagID = Diags.getCustomDiagID(
  4384. DiagnosticsEngine::Error,
  4385. "External function used in non-library profile: %0");
  4386. std::string escaped;
  4387. llvm::raw_string_ostream os(escaped);
  4388. dxilutil::PrintEscapedString(f.getName(), os);
  4389. Diags.Report(DiagID) << os.str();
  4390. return;
  4391. }
  4392. f.setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  4393. } else {
  4394. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  4395. }
  4396. }
  4397. // Skip no inline functions.
  4398. if (f.hasFnAttribute(llvm::Attribute::NoInline))
  4399. continue;
  4400. // Always inline for used functions.
  4401. if (!f.user_empty() && !f.isDeclaration())
  4402. f.addFnAttr(llvm::Attribute::AlwaysInline);
  4403. }
  4404. if (m_bIsLib && !m_ExportMap.empty()) {
  4405. m_ExportMap.BeginProcessing();
  4406. for (Function &f : m_pHLModule->GetModule()->functions()) {
  4407. if (f.isDeclaration() || f.isIntrinsic() ||
  4408. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL)
  4409. continue;
  4410. m_ExportMap.ProcessFunction(&f, true);
  4411. }
  4412. // TODO: add subobject export names here.
  4413. if (!m_ExportMap.EndProcessing()) {
  4414. for (auto &name : m_ExportMap.GetNameCollisions()) {
  4415. DiagnosticsEngine &Diags = CGM.getDiags();
  4416. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  4417. "Export name collides with another export: %0");
  4418. std::string escaped;
  4419. llvm::raw_string_ostream os(escaped);
  4420. dxilutil::PrintEscapedString(name, os);
  4421. Diags.Report(DiagID) << os.str();
  4422. }
  4423. for (auto &name : m_ExportMap.GetUnusedExports()) {
  4424. DiagnosticsEngine &Diags = CGM.getDiags();
  4425. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  4426. "Could not find target for export: %0");
  4427. std::string escaped;
  4428. llvm::raw_string_ostream os(escaped);
  4429. dxilutil::PrintEscapedString(name, os);
  4430. Diags.Report(DiagID) << os.str();
  4431. }
  4432. }
  4433. }
  4434. for (auto &it : m_ExportMap.GetFunctionRenames()) {
  4435. Function *F = it.first;
  4436. auto &renames = it.second;
  4437. if (renames.empty())
  4438. continue;
  4439. // Rename the original, if necessary, then clone the rest
  4440. if (renames.find(F->getName()) == renames.end())
  4441. F->setName(*renames.begin());
  4442. for (auto &itName : renames) {
  4443. if (F->getName() != itName) {
  4444. Function *pClone = CloneFunction(F, itName, m_pHLModule->GetModule(),
  4445. m_pHLModule->GetTypeSystem(), m_pHLModule->GetTypeSystem());
  4446. // add DxilFunctionProps if entry
  4447. if (m_pHLModule->HasDxilFunctionProps(F)) {
  4448. DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(F);
  4449. auto newProps = llvm::make_unique<DxilFunctionProps>(props);
  4450. m_pHLModule->AddDxilFunctionProps(pClone, newProps);
  4451. }
  4452. }
  4453. }
  4454. }
  4455. if (CGM.getCodeGenOpts().ExportShadersOnly) {
  4456. for (Function &f : m_pHLModule->GetModule()->functions()) {
  4457. // Skip declarations, intrinsics, shaders, and non-external linkage
  4458. if (f.isDeclaration() || f.isIntrinsic() ||
  4459. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL ||
  4460. m_pHLModule->HasDxilFunctionProps(&f) ||
  4461. m_pHLModule->IsPatchConstantShader(&f) ||
  4462. f.getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage)
  4463. continue;
  4464. // Mark non-shader user functions as InternalLinkage
  4465. f.setLinkage(GlobalValue::LinkageTypes::InternalLinkage);
  4466. }
  4467. }
  4468. // Now iterate hull shaders and make sure their corresponding patch constant
  4469. // functions are marked ExternalLinkage:
  4470. for (Function &f : m_pHLModule->GetModule()->functions()) {
  4471. if (f.isDeclaration() || f.isIntrinsic() ||
  4472. GetHLOpcodeGroup(&f) != HLOpcodeGroup::NotHL ||
  4473. f.getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage ||
  4474. !m_pHLModule->HasDxilFunctionProps(&f))
  4475. continue;
  4476. DxilFunctionProps &props = m_pHLModule->GetDxilFunctionProps(&f);
  4477. if (!props.IsHS())
  4478. continue;
  4479. Function *PCFunc = props.ShaderProps.HS.patchConstantFunc;
  4480. if (PCFunc->getLinkage() != GlobalValue::LinkageTypes::ExternalLinkage)
  4481. PCFunc->setLinkage(GlobalValue::LinkageTypes::ExternalLinkage);
  4482. }
  4483. // Disallow resource arguments in (non-entry) function exports
  4484. // unless offline linking target.
  4485. if (m_bIsLib && m_pHLModule->GetShaderModel()->GetMinor() != ShaderModel::kOfflineMinor) {
  4486. for (Function &f : m_pHLModule->GetModule()->functions()) {
  4487. // Skip llvm intrinsics, non-external linkage, entry/patch constant func, and HL intrinsics
  4488. if (!f.isIntrinsic() &&
  4489. f.getLinkage() == GlobalValue::LinkageTypes::ExternalLinkage &&
  4490. !m_pHLModule->HasDxilFunctionProps(&f) &&
  4491. !m_pHLModule->IsPatchConstantShader(&f) &&
  4492. GetHLOpcodeGroup(&f) == HLOpcodeGroup::NotHL) {
  4493. // Verify no resources in param/return types
  4494. if (dxilutil::ContainsHLSLObjectType(f.getReturnType())) {
  4495. ReportDisallowedTypeInExportParam(CGM, f.getName());
  4496. continue;
  4497. }
  4498. for (auto &Arg : f.args()) {
  4499. if (dxilutil::ContainsHLSLObjectType(Arg.getType())) {
  4500. ReportDisallowedTypeInExportParam(CGM, f.getName());
  4501. break;
  4502. }
  4503. }
  4504. }
  4505. }
  4506. }
  4507. // Do simple transform to make later lower pass easier.
  4508. SimpleTransformForHLDXIR(m_pHLModule->GetModule());
  4509. // Handle lang extensions if provided.
  4510. if (CGM.getCodeGenOpts().HLSLExtensionsCodegen) {
  4511. // Add semantic defines for extensions if any are available.
  4512. HLSLExtensionsCodegenHelper::SemanticDefineErrorList errors =
  4513. CGM.getCodeGenOpts().HLSLExtensionsCodegen->WriteSemanticDefines(m_pHLModule->GetModule());
  4514. DiagnosticsEngine &Diags = CGM.getDiags();
  4515. for (const HLSLExtensionsCodegenHelper::SemanticDefineError& error : errors) {
  4516. DiagnosticsEngine::Level level = DiagnosticsEngine::Error;
  4517. if (error.IsWarning())
  4518. level = DiagnosticsEngine::Warning;
  4519. unsigned DiagID = Diags.getCustomDiagID(level, "%0");
  4520. Diags.Report(SourceLocation::getFromRawEncoding(error.Location()), DiagID) << error.Message();
  4521. }
  4522. // Add root signature from a #define. Overrides root signature in function attribute.
  4523. {
  4524. using Status = HLSLExtensionsCodegenHelper::CustomRootSignature::Status;
  4525. HLSLExtensionsCodegenHelper::CustomRootSignature customRootSig;
  4526. Status status = CGM.getCodeGenOpts().HLSLExtensionsCodegen->GetCustomRootSignature(&customRootSig);
  4527. if (status == Status::FOUND) {
  4528. RootSignatureHandle RootSigHandle;
  4529. CompileRootSignature(customRootSig.RootSignature, Diags,
  4530. SourceLocation::getFromRawEncoding(customRootSig.EncodedSourceLocation),
  4531. rootSigVer, DxilRootSignatureCompilationFlags::GlobalRootSignature, &RootSigHandle);
  4532. if (!RootSigHandle.IsEmpty()) {
  4533. RootSigHandle.EnsureSerializedAvailable();
  4534. m_pHLModule->SetSerializedRootSignature(
  4535. RootSigHandle.GetSerializedBytes(),
  4536. RootSigHandle.GetSerializedSize());
  4537. }
  4538. }
  4539. }
  4540. }
  4541. // At this point, we have a high-level DXIL module - record this.
  4542. SetPauseResumePasses(*m_pHLModule->GetModule(), "hlsl-hlemit", "hlsl-hlensure");
  4543. }
  4544. RValue CGMSHLSLRuntime::EmitHLSLBuiltinCallExpr(CodeGenFunction &CGF,
  4545. const FunctionDecl *FD,
  4546. const CallExpr *E,
  4547. ReturnValueSlot ReturnValue) {
  4548. const Decl *TargetDecl = E->getCalleeDecl();
  4549. llvm::Value *Callee = CGF.EmitScalarExpr(E->getCallee());
  4550. RValue RV = CGF.EmitCall(E->getCallee()->getType(), Callee, E, ReturnValue,
  4551. TargetDecl);
  4552. if (RV.isScalar() && RV.getScalarVal() != nullptr) {
  4553. if (CallInst *CI = dyn_cast<CallInst>(RV.getScalarVal())) {
  4554. Function *F = CI->getCalledFunction();
  4555. HLOpcodeGroup group = hlsl::GetHLOpcodeGroup(F);
  4556. if (group == HLOpcodeGroup::HLIntrinsic) {
  4557. bool allOperandImm = true;
  4558. for (auto &operand : CI->arg_operands()) {
  4559. bool isImm = isa<ConstantInt>(operand) || isa<ConstantFP>(operand) ||
  4560. isa<ConstantAggregateZero>(operand) || isa<ConstantDataVector>(operand);
  4561. if (!isImm) {
  4562. allOperandImm = false;
  4563. break;
  4564. } else if (operand->getType()->isHalfTy()) {
  4565. // Not support half Eval yet.
  4566. allOperandImm = false;
  4567. break;
  4568. }
  4569. }
  4570. if (allOperandImm) {
  4571. unsigned intrinsicOpcode;
  4572. StringRef intrinsicGroup;
  4573. hlsl::GetIntrinsicOp(FD, intrinsicOpcode, intrinsicGroup);
  4574. IntrinsicOp opcode = static_cast<IntrinsicOp>(intrinsicOpcode);
  4575. if (Value *Result = TryEvalIntrinsic(CI, opcode)) {
  4576. RV = RValue::get(Result);
  4577. }
  4578. }
  4579. }
  4580. }
  4581. }
  4582. return RV;
  4583. }
  4584. static HLOpcodeGroup GetHLOpcodeGroup(const clang::Stmt::StmtClass stmtClass) {
  4585. switch (stmtClass) {
  4586. case Stmt::CStyleCastExprClass:
  4587. case Stmt::ImplicitCastExprClass:
  4588. case Stmt::CXXFunctionalCastExprClass:
  4589. return HLOpcodeGroup::HLCast;
  4590. case Stmt::InitListExprClass:
  4591. return HLOpcodeGroup::HLInit;
  4592. case Stmt::BinaryOperatorClass:
  4593. case Stmt::CompoundAssignOperatorClass:
  4594. return HLOpcodeGroup::HLBinOp;
  4595. case Stmt::UnaryOperatorClass:
  4596. return HLOpcodeGroup::HLUnOp;
  4597. case Stmt::ExtMatrixElementExprClass:
  4598. return HLOpcodeGroup::HLSubscript;
  4599. case Stmt::CallExprClass:
  4600. return HLOpcodeGroup::HLIntrinsic;
  4601. case Stmt::ConditionalOperatorClass:
  4602. return HLOpcodeGroup::HLSelect;
  4603. default:
  4604. llvm_unreachable("not support operation");
  4605. }
  4606. }
  4607. // NOTE: This table must match BinaryOperator::Opcode
  4608. static const HLBinaryOpcode BinaryOperatorKindMap[] = {
  4609. HLBinaryOpcode::Invalid, // PtrMemD
  4610. HLBinaryOpcode::Invalid, // PtrMemI
  4611. HLBinaryOpcode::Mul, HLBinaryOpcode::Div, HLBinaryOpcode::Rem,
  4612. HLBinaryOpcode::Add, HLBinaryOpcode::Sub, HLBinaryOpcode::Shl,
  4613. HLBinaryOpcode::Shr, HLBinaryOpcode::LT, HLBinaryOpcode::GT,
  4614. HLBinaryOpcode::LE, HLBinaryOpcode::GE, HLBinaryOpcode::EQ,
  4615. HLBinaryOpcode::NE, HLBinaryOpcode::And, HLBinaryOpcode::Xor,
  4616. HLBinaryOpcode::Or, HLBinaryOpcode::LAnd, HLBinaryOpcode::LOr,
  4617. HLBinaryOpcode::Invalid, // Assign,
  4618. // The assign part is done by matrix store
  4619. HLBinaryOpcode::Mul, // MulAssign
  4620. HLBinaryOpcode::Div, // DivAssign
  4621. HLBinaryOpcode::Rem, // RemAssign
  4622. HLBinaryOpcode::Add, // AddAssign
  4623. HLBinaryOpcode::Sub, // SubAssign
  4624. HLBinaryOpcode::Shl, // ShlAssign
  4625. HLBinaryOpcode::Shr, // ShrAssign
  4626. HLBinaryOpcode::And, // AndAssign
  4627. HLBinaryOpcode::Xor, // XorAssign
  4628. HLBinaryOpcode::Or, // OrAssign
  4629. HLBinaryOpcode::Invalid, // Comma
  4630. };
  4631. // NOTE: This table must match UnaryOperator::Opcode
  4632. static const HLUnaryOpcode UnaryOperatorKindMap[] = {
  4633. HLUnaryOpcode::PostInc, HLUnaryOpcode::PostDec,
  4634. HLUnaryOpcode::PreInc, HLUnaryOpcode::PreDec,
  4635. HLUnaryOpcode::Invalid, // AddrOf,
  4636. HLUnaryOpcode::Invalid, // Deref,
  4637. HLUnaryOpcode::Plus, HLUnaryOpcode::Minus,
  4638. HLUnaryOpcode::Not, HLUnaryOpcode::LNot,
  4639. HLUnaryOpcode::Invalid, // Real,
  4640. HLUnaryOpcode::Invalid, // Imag,
  4641. HLUnaryOpcode::Invalid, // Extension
  4642. };
  4643. static unsigned GetHLOpcode(const Expr *E) {
  4644. switch (E->getStmtClass()) {
  4645. case Stmt::CompoundAssignOperatorClass:
  4646. case Stmt::BinaryOperatorClass: {
  4647. const clang::BinaryOperator *binOp = cast<clang::BinaryOperator>(E);
  4648. HLBinaryOpcode binOpcode = BinaryOperatorKindMap[binOp->getOpcode()];
  4649. if (HasUnsignedOpcode(binOpcode)) {
  4650. if (hlsl::IsHLSLUnsigned(binOp->getLHS()->getType())) {
  4651. binOpcode = GetUnsignedOpcode(binOpcode);
  4652. }
  4653. }
  4654. return static_cast<unsigned>(binOpcode);
  4655. }
  4656. case Stmt::UnaryOperatorClass: {
  4657. const UnaryOperator *unOp = cast<clang::UnaryOperator>(E);
  4658. HLUnaryOpcode unOpcode = UnaryOperatorKindMap[unOp->getOpcode()];
  4659. return static_cast<unsigned>(unOpcode);
  4660. }
  4661. case Stmt::ImplicitCastExprClass:
  4662. case Stmt::CStyleCastExprClass: {
  4663. const CastExpr *CE = cast<CastExpr>(E);
  4664. bool toUnsigned = hlsl::IsHLSLUnsigned(E->getType());
  4665. bool fromUnsigned = hlsl::IsHLSLUnsigned(CE->getSubExpr()->getType());
  4666. if (toUnsigned && fromUnsigned)
  4667. return static_cast<unsigned>(HLCastOpcode::UnsignedUnsignedCast);
  4668. else if (toUnsigned)
  4669. return static_cast<unsigned>(HLCastOpcode::ToUnsignedCast);
  4670. else if (fromUnsigned)
  4671. return static_cast<unsigned>(HLCastOpcode::FromUnsignedCast);
  4672. else
  4673. return static_cast<unsigned>(HLCastOpcode::DefaultCast);
  4674. }
  4675. default:
  4676. return 0;
  4677. }
  4678. }
  4679. static Value *
  4680. EmitHLSLMatrixOperationCallImp(CGBuilderTy &Builder, HLOpcodeGroup group,
  4681. unsigned opcode, llvm::Type *RetType,
  4682. ArrayRef<Value *> paramList, llvm::Module &M) {
  4683. SmallVector<llvm::Type *, 4> paramTyList;
  4684. // Add the opcode param
  4685. llvm::Type *opcodeTy = llvm::Type::getInt32Ty(M.getContext());
  4686. paramTyList.emplace_back(opcodeTy);
  4687. for (Value *param : paramList) {
  4688. paramTyList.emplace_back(param->getType());
  4689. }
  4690. llvm::FunctionType *funcTy =
  4691. llvm::FunctionType::get(RetType, paramTyList, false);
  4692. Function *opFunc = GetOrCreateHLFunction(M, funcTy, group, opcode);
  4693. SmallVector<Value *, 4> opcodeParamList;
  4694. Value *opcodeConst = Constant::getIntegerValue(opcodeTy, APInt(32, opcode));
  4695. opcodeParamList.emplace_back(opcodeConst);
  4696. opcodeParamList.append(paramList.begin(), paramList.end());
  4697. return Builder.CreateCall(opFunc, opcodeParamList);
  4698. }
  4699. static Value *EmitHLSLArrayInit(CGBuilderTy &Builder, HLOpcodeGroup group,
  4700. unsigned opcode, llvm::Type *RetType,
  4701. ArrayRef<Value *> paramList, llvm::Module &M) {
  4702. // It's a matrix init.
  4703. if (!RetType->isVoidTy())
  4704. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4705. paramList, M);
  4706. Value *arrayPtr = paramList[0];
  4707. llvm::ArrayType *AT =
  4708. cast<llvm::ArrayType>(arrayPtr->getType()->getPointerElementType());
  4709. // Avoid the arrayPtr.
  4710. unsigned paramSize = paramList.size() - 1;
  4711. // Support simple case here.
  4712. if (paramSize == AT->getArrayNumElements()) {
  4713. bool typeMatch = true;
  4714. llvm::Type *EltTy = AT->getArrayElementType();
  4715. if (EltTy->isAggregateType()) {
  4716. // Aggregate Type use pointer in initList.
  4717. EltTy = llvm::PointerType::get(EltTy, 0);
  4718. }
  4719. for (unsigned i = 1; i < paramList.size(); i++) {
  4720. if (paramList[i]->getType() != EltTy) {
  4721. typeMatch = false;
  4722. break;
  4723. }
  4724. }
  4725. // Both size and type match.
  4726. if (typeMatch) {
  4727. bool isPtr = EltTy->isPointerTy();
  4728. llvm::Type *i32Ty = llvm::Type::getInt32Ty(EltTy->getContext());
  4729. Constant *zero = ConstantInt::get(i32Ty, 0);
  4730. for (unsigned i = 1; i < paramList.size(); i++) {
  4731. Constant *idx = ConstantInt::get(i32Ty, i - 1);
  4732. Value *GEP = Builder.CreateInBoundsGEP(arrayPtr, {zero, idx});
  4733. Value *Elt = paramList[i];
  4734. if (isPtr) {
  4735. Elt = Builder.CreateLoad(Elt);
  4736. }
  4737. Builder.CreateStore(Elt, GEP);
  4738. }
  4739. // The return value will not be used.
  4740. return nullptr;
  4741. }
  4742. }
  4743. // Other case will be lowered in later pass.
  4744. return EmitHLSLMatrixOperationCallImp(Builder, group, opcode, RetType,
  4745. paramList, M);
  4746. }
  4747. void CGMSHLSLRuntime::FlattenValToInitList(CodeGenFunction &CGF, SmallVector<Value *, 4> &elts,
  4748. SmallVector<QualType, 4> &eltTys,
  4749. QualType Ty, Value *val) {
  4750. CGBuilderTy &Builder = CGF.Builder;
  4751. llvm::Type *valTy = val->getType();
  4752. if (valTy->isPointerTy()) {
  4753. llvm::Type *valEltTy = valTy->getPointerElementType();
  4754. if (valEltTy->isVectorTy() ||
  4755. valEltTy->isSingleValueType()) {
  4756. Value *ldVal = Builder.CreateLoad(val);
  4757. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4758. } else if (HLMatrixType::isa(valEltTy)) {
  4759. Value *ldVal = EmitHLSLMatrixLoad(Builder, val, Ty);
  4760. FlattenValToInitList(CGF, elts, eltTys, Ty, ldVal);
  4761. } else {
  4762. llvm::Type *i32Ty = llvm::Type::getInt32Ty(valTy->getContext());
  4763. Value *zero = ConstantInt::get(i32Ty, 0);
  4764. if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(valEltTy)) {
  4765. QualType EltTy = Ty->getAsArrayTypeUnsafe()->getElementType();
  4766. for (unsigned i = 0; i < AT->getArrayNumElements(); i++) {
  4767. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4768. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4769. FlattenValToInitList(CGF, elts, eltTys, EltTy,EltPtr);
  4770. }
  4771. } else {
  4772. // Struct.
  4773. StructType *ST = cast<StructType>(valEltTy);
  4774. if (dxilutil::IsHLSLObjectType(ST)) {
  4775. // Save object directly like basic type.
  4776. elts.emplace_back(Builder.CreateLoad(val));
  4777. eltTys.emplace_back(Ty);
  4778. } else {
  4779. RecordDecl *RD = Ty->getAsStructureType()->getDecl();
  4780. const CGRecordLayout& RL = CGF.getTypes().getCGRecordLayout(RD);
  4781. // Take care base.
  4782. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4783. if (CXXRD->getNumBases()) {
  4784. for (const auto &I : CXXRD->bases()) {
  4785. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4786. I.getType()->castAs<RecordType>()->getDecl());
  4787. if (BaseDecl->field_empty())
  4788. continue;
  4789. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4790. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4791. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4792. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4793. FlattenValToInitList(CGF, elts, eltTys, parentTy, EltPtr);
  4794. }
  4795. }
  4796. }
  4797. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  4798. fieldIter != fieldEnd; ++fieldIter) {
  4799. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  4800. Value *gepIdx = ConstantInt::get(i32Ty, i);
  4801. Value *EltPtr = Builder.CreateInBoundsGEP(val, {zero, gepIdx});
  4802. FlattenValToInitList(CGF, elts, eltTys, fieldIter->getType(), EltPtr);
  4803. }
  4804. }
  4805. }
  4806. }
  4807. } else {
  4808. if (HLMatrixType MatTy = HLMatrixType::dyn_cast(valTy)) {
  4809. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  4810. // All matrix Value should be row major.
  4811. // Init list is row major in scalar.
  4812. // So the order is match here, just cast to vector.
  4813. unsigned matSize = MatTy.getNumElements();
  4814. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  4815. HLCastOpcode opcode = isRowMajor ? HLCastOpcode::RowMatrixToVecCast
  4816. : HLCastOpcode::ColMatrixToVecCast;
  4817. // Cast to vector.
  4818. val = EmitHLSLMatrixOperationCallImp(
  4819. Builder, HLOpcodeGroup::HLCast,
  4820. static_cast<unsigned>(opcode),
  4821. llvm::VectorType::get(EltTy, matSize), {val}, TheModule);
  4822. valTy = val->getType();
  4823. }
  4824. if (valTy->isVectorTy()) {
  4825. QualType EltTy = hlsl::GetElementTypeOrType(Ty);
  4826. unsigned vecSize = valTy->getVectorNumElements();
  4827. for (unsigned i = 0; i < vecSize; i++) {
  4828. Value *Elt = Builder.CreateExtractElement(val, i);
  4829. elts.emplace_back(Elt);
  4830. eltTys.emplace_back(EltTy);
  4831. }
  4832. } else {
  4833. DXASSERT(valTy->isSingleValueType(), "must be single value type here");
  4834. elts.emplace_back(val);
  4835. eltTys.emplace_back(Ty);
  4836. }
  4837. }
  4838. }
  4839. static Value* ConvertScalarOrVector(CGBuilderTy& Builder, CodeGenTypes &Types,
  4840. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  4841. llvm::Type *SrcTy = Val->getType();
  4842. llvm::Type *DstTy = Types.ConvertType(DstQualTy);
  4843. DXASSERT(Val->getType() == Types.ConvertType(SrcQualTy), "QualType/Value mismatch!");
  4844. DXASSERT((SrcTy->isIntOrIntVectorTy() || SrcTy->isFPOrFPVectorTy())
  4845. && (DstTy->isIntOrIntVectorTy() || DstTy->isFPOrFPVectorTy()),
  4846. "EmitNumericConversion can only be used with int/float scalars/vectors.");
  4847. if (SrcTy == DstTy) return Val; // Valid no-op, including uint to int / int to uint
  4848. DXASSERT(SrcTy->isVectorTy()
  4849. ? (DstTy->isVectorTy() && SrcTy->getVectorNumElements() == DstTy->getVectorNumElements())
  4850. : !DstTy->isVectorTy(),
  4851. "EmitNumericConversion can only cast between scalars or vectors of matching sizes");
  4852. // Conversions to bools are comparisons
  4853. if (DstTy->getScalarSizeInBits() == 1) {
  4854. // fcmp une is what regular clang uses in C++ for (bool)f;
  4855. return SrcTy->isIntOrIntVectorTy()
  4856. ? Builder.CreateICmpNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool")
  4857. : Builder.CreateFCmpUNE(Val, llvm::Constant::getNullValue(SrcTy), "tobool");
  4858. }
  4859. // Cast necessary
  4860. auto CastOp = static_cast<Instruction::CastOps>(HLModule::GetNumericCastOp(
  4861. SrcTy, hlsl::IsHLSLUnsigned(SrcQualTy), DstTy, hlsl::IsHLSLUnsigned(DstQualTy)));
  4862. return Builder.CreateCast(CastOp, Val, DstTy);
  4863. }
  4864. static Value* ConvertScalarOrVector(CodeGenFunction &CGF,
  4865. Value *Val, QualType SrcQualTy, QualType DstQualTy) {
  4866. return ConvertScalarOrVector(CGF.Builder, CGF.getTypes(), Val, SrcQualTy, DstQualTy);
  4867. }
  4868. // Cast elements in initlist if not match the target type.
  4869. // idx is current element index in initlist, Ty is target type.
  4870. // TODO: Stop handling missing cast here. Handle the casting of non-scalar values
  4871. // to their destination type in init list expressions at AST level.
  4872. static void AddMissingCastOpsInInitList(SmallVector<Value *, 4> &elts, SmallVector<QualType, 4> &eltTys, unsigned &idx, QualType Ty, CodeGenFunction &CGF) {
  4873. if (Ty->isArrayType()) {
  4874. const clang::ArrayType *AT = Ty->getAsArrayTypeUnsafe();
  4875. // Must be ConstantArrayType here.
  4876. unsigned arraySize = cast<ConstantArrayType>(AT)->getSize().getLimitedValue();
  4877. QualType EltTy = AT->getElementType();
  4878. for (unsigned i = 0; i < arraySize; i++)
  4879. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4880. } else if (IsHLSLVecType(Ty)) {
  4881. QualType EltTy = GetHLSLVecElementType(Ty);
  4882. unsigned vecSize = GetHLSLVecSize(Ty);
  4883. for (unsigned i=0;i< vecSize;i++)
  4884. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4885. } else if (IsHLSLMatType(Ty)) {
  4886. QualType EltTy = GetHLSLMatElementType(Ty);
  4887. unsigned row, col;
  4888. GetHLSLMatRowColCount(Ty, row, col);
  4889. unsigned matSize = row*col;
  4890. for (unsigned i = 0; i < matSize; i++)
  4891. AddMissingCastOpsInInitList(elts, eltTys, idx, EltTy, CGF);
  4892. } else if (Ty->isRecordType()) {
  4893. if (dxilutil::IsHLSLObjectType(CGF.ConvertType(Ty))) {
  4894. // Skip hlsl object.
  4895. idx++;
  4896. } else {
  4897. const RecordType *RT = Ty->getAsStructureType();
  4898. // For CXXRecord.
  4899. if (!RT)
  4900. RT = Ty->getAs<RecordType>();
  4901. RecordDecl *RD = RT->getDecl();
  4902. // Take care base.
  4903. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4904. if (CXXRD->getNumBases()) {
  4905. for (const auto &I : CXXRD->bases()) {
  4906. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4907. I.getType()->castAs<RecordType>()->getDecl());
  4908. if (BaseDecl->field_empty())
  4909. continue;
  4910. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4911. AddMissingCastOpsInInitList(elts, eltTys, idx, parentTy, CGF);
  4912. }
  4913. }
  4914. }
  4915. for (FieldDecl *field : RD->fields())
  4916. AddMissingCastOpsInInitList(elts, eltTys, idx, field->getType(), CGF);
  4917. }
  4918. }
  4919. else {
  4920. // Basic type.
  4921. elts[idx] = ConvertScalarOrVector(CGF, elts[idx], eltTys[idx], Ty);
  4922. idx++;
  4923. }
  4924. }
  4925. static void StoreInitListToDestPtr(Value *DestPtr,
  4926. SmallVector<Value *, 4> &elts, unsigned &idx,
  4927. QualType Type, bool bDefaultRowMajor,
  4928. CodeGenFunction &CGF, llvm::Module &M) {
  4929. CodeGenTypes &Types = CGF.getTypes();
  4930. CGBuilderTy &Builder = CGF.Builder;
  4931. llvm::Type *Ty = DestPtr->getType()->getPointerElementType();
  4932. if (Ty->isVectorTy()) {
  4933. llvm::Type *RegTy = CGF.ConvertType(Type);
  4934. Value *Result = UndefValue::get(RegTy);
  4935. for (unsigned i = 0; i < RegTy->getVectorNumElements(); i++)
  4936. Result = Builder.CreateInsertElement(Result, elts[idx + i], i);
  4937. Result = CGF.EmitToMemory(Result, Type);
  4938. Builder.CreateStore(Result, DestPtr);
  4939. idx += Ty->getVectorNumElements();
  4940. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  4941. bool isRowMajor = hlsl::IsHLSLMatRowMajor(Type, bDefaultRowMajor);
  4942. std::vector<Value *> matInitList(MatTy.getNumElements());
  4943. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  4944. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  4945. unsigned matIdx = c * MatTy.getNumRows() + r;
  4946. matInitList[matIdx] = elts[idx + matIdx];
  4947. }
  4948. }
  4949. idx += MatTy.getNumElements();
  4950. Value *matVal =
  4951. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLInit,
  4952. /*opcode*/ 0, Ty, matInitList, M);
  4953. // matVal return from HLInit is row major.
  4954. // If DestPtr is row major, just store it directly.
  4955. if (!isRowMajor) {
  4956. // ColMatStore need a col major value.
  4957. // Cast row major matrix into col major.
  4958. // Then store it.
  4959. Value *colMatVal = EmitHLSLMatrixOperationCallImp(
  4960. Builder, HLOpcodeGroup::HLCast,
  4961. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix), Ty,
  4962. {matVal}, M);
  4963. EmitHLSLMatrixOperationCallImp(
  4964. Builder, HLOpcodeGroup::HLMatLoadStore,
  4965. static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore), Ty,
  4966. {DestPtr, colMatVal}, M);
  4967. } else {
  4968. EmitHLSLMatrixOperationCallImp(
  4969. Builder, HLOpcodeGroup::HLMatLoadStore,
  4970. static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore), Ty,
  4971. {DestPtr, matVal}, M);
  4972. }
  4973. } else if (Ty->isStructTy()) {
  4974. if (dxilutil::IsHLSLObjectType(Ty)) {
  4975. Builder.CreateStore(elts[idx], DestPtr);
  4976. idx++;
  4977. } else {
  4978. Constant *zero = Builder.getInt32(0);
  4979. const RecordType *RT = Type->getAsStructureType();
  4980. // For CXXRecord.
  4981. if (!RT)
  4982. RT = Type->getAs<RecordType>();
  4983. RecordDecl *RD = RT->getDecl();
  4984. const CGRecordLayout &RL = Types.getCGRecordLayout(RD);
  4985. // Take care base.
  4986. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4987. if (CXXRD->getNumBases()) {
  4988. for (const auto &I : CXXRD->bases()) {
  4989. const CXXRecordDecl *BaseDecl = cast<CXXRecordDecl>(
  4990. I.getType()->castAs<RecordType>()->getDecl());
  4991. if (BaseDecl->field_empty())
  4992. continue;
  4993. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4994. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  4995. Constant *gepIdx = Builder.getInt32(i);
  4996. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  4997. StoreInitListToDestPtr(GEP, elts, idx, parentTy,
  4998. bDefaultRowMajor, CGF, M);
  4999. }
  5000. }
  5001. }
  5002. for (FieldDecl *field : RD->fields()) {
  5003. unsigned i = RL.getLLVMFieldNo(field);
  5004. Constant *gepIdx = Builder.getInt32(i);
  5005. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  5006. StoreInitListToDestPtr(GEP, elts, idx, field->getType(),
  5007. bDefaultRowMajor, CGF, M);
  5008. }
  5009. }
  5010. } else if (Ty->isArrayTy()) {
  5011. Constant *zero = Builder.getInt32(0);
  5012. QualType EltType = Type->getAsArrayTypeUnsafe()->getElementType();
  5013. for (unsigned i = 0; i < Ty->getArrayNumElements(); i++) {
  5014. Constant *gepIdx = Builder.getInt32(i);
  5015. Value *GEP = Builder.CreateInBoundsGEP(DestPtr, {zero, gepIdx});
  5016. StoreInitListToDestPtr(GEP, elts, idx, EltType, bDefaultRowMajor,
  5017. CGF, M);
  5018. }
  5019. } else {
  5020. DXASSERT(Ty->isSingleValueType(), "invalid type");
  5021. llvm::Type *i1Ty = Builder.getInt1Ty();
  5022. Value *V = elts[idx];
  5023. if (V->getType() == i1Ty &&
  5024. DestPtr->getType()->getPointerElementType() != i1Ty) {
  5025. V = Builder.CreateZExt(V, DestPtr->getType()->getPointerElementType());
  5026. }
  5027. Builder.CreateStore(V, DestPtr);
  5028. idx++;
  5029. }
  5030. }
  5031. void CGMSHLSLRuntime::ScanInitList(CodeGenFunction &CGF, InitListExpr *E,
  5032. SmallVector<Value *, 4> &EltValList,
  5033. SmallVector<QualType, 4> &EltTyList) {
  5034. unsigned NumInitElements = E->getNumInits();
  5035. for (unsigned i = 0; i != NumInitElements; ++i) {
  5036. Expr *init = E->getInit(i);
  5037. QualType iType = init->getType();
  5038. if (InitListExpr *initList = dyn_cast<InitListExpr>(init)) {
  5039. ScanInitList(CGF, initList, EltValList, EltTyList);
  5040. } else if (CodeGenFunction::hasScalarEvaluationKind(iType)) {
  5041. llvm::Value *initVal = CGF.EmitScalarExpr(init);
  5042. FlattenValToInitList(CGF, EltValList, EltTyList, iType, initVal);
  5043. } else {
  5044. AggValueSlot Slot =
  5045. CGF.CreateAggTemp(init->getType(), "Agg.InitList.tmp");
  5046. CGF.EmitAggExpr(init, Slot);
  5047. llvm::Value *aggPtr = Slot.getAddr();
  5048. FlattenValToInitList(CGF, EltValList, EltTyList, iType, aggPtr);
  5049. }
  5050. }
  5051. }
  5052. // Is Type of E match Ty.
  5053. static bool ExpTypeMatch(Expr *E, QualType Ty, ASTContext &Ctx, CodeGenTypes &Types) {
  5054. if (InitListExpr *initList = dyn_cast<InitListExpr>(E)) {
  5055. unsigned NumInitElements = initList->getNumInits();
  5056. // Skip vector and matrix type.
  5057. if (Ty->isVectorType())
  5058. return false;
  5059. if (hlsl::IsHLSLVecMatType(Ty))
  5060. return false;
  5061. if (Ty->isStructureOrClassType()) {
  5062. RecordDecl *record = Ty->castAs<RecordType>()->getDecl();
  5063. bool bMatch = true;
  5064. unsigned i = 0;
  5065. for (auto it = record->field_begin(), end = record->field_end();
  5066. it != end; it++) {
  5067. if (i == NumInitElements) {
  5068. bMatch = false;
  5069. break;
  5070. }
  5071. Expr *init = initList->getInit(i++);
  5072. QualType EltTy = it->getType();
  5073. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  5074. if (!bMatch)
  5075. break;
  5076. }
  5077. bMatch &= i == NumInitElements;
  5078. if (bMatch && initList->getType()->isVoidType()) {
  5079. initList->setType(Ty);
  5080. }
  5081. return bMatch;
  5082. } else if (Ty->isArrayType() && !Ty->isIncompleteArrayType()) {
  5083. const ConstantArrayType *AT = Ctx.getAsConstantArrayType(Ty);
  5084. QualType EltTy = AT->getElementType();
  5085. unsigned size = AT->getSize().getZExtValue();
  5086. if (size != NumInitElements)
  5087. return false;
  5088. bool bMatch = true;
  5089. for (unsigned i = 0; i != NumInitElements; ++i) {
  5090. Expr *init = initList->getInit(i);
  5091. bMatch &= ExpTypeMatch(init, EltTy, Ctx, Types);
  5092. if (!bMatch)
  5093. break;
  5094. }
  5095. if (bMatch && initList->getType()->isVoidType()) {
  5096. initList->setType(Ty);
  5097. }
  5098. return bMatch;
  5099. } else {
  5100. return false;
  5101. }
  5102. } else {
  5103. llvm::Type *ExpTy = Types.ConvertType(E->getType());
  5104. llvm::Type *TargetTy = Types.ConvertType(Ty);
  5105. return ExpTy == TargetTy;
  5106. }
  5107. }
  5108. bool CGMSHLSLRuntime::IsTrivalInitListExpr(CodeGenFunction &CGF,
  5109. InitListExpr *E) {
  5110. QualType Ty = E->getType();
  5111. bool result = ExpTypeMatch(E, Ty, CGF.getContext(), CGF.getTypes());
  5112. if (result) {
  5113. auto iter = staticConstGlobalInitMap.find(E);
  5114. if (iter != staticConstGlobalInitMap.end()) {
  5115. GlobalVariable * GV = iter->second;
  5116. auto &InitConstants = staticConstGlobalInitListMap[GV];
  5117. // Add Constant to InitList.
  5118. for (unsigned i=0;i<E->getNumInits();i++) {
  5119. Expr *Expr = E->getInit(i);
  5120. if (ImplicitCastExpr *Cast = dyn_cast<ImplicitCastExpr>(Expr)) {
  5121. if (Cast->getCastKind() == CK_LValueToRValue) {
  5122. Expr = Cast->getSubExpr();
  5123. }
  5124. }
  5125. // Only do this on lvalue, if not lvalue, it will not be constant
  5126. // anyway.
  5127. if (Expr->isLValue()) {
  5128. LValue LV = CGF.EmitLValue(Expr);
  5129. if (LV.isSimple()) {
  5130. Constant *SrcPtr = dyn_cast<Constant>(LV.getAddress());
  5131. if (SrcPtr && !isa<UndefValue>(SrcPtr)) {
  5132. InitConstants.emplace_back(SrcPtr);
  5133. continue;
  5134. }
  5135. }
  5136. }
  5137. // Only support simple LV and Constant Ptr case.
  5138. // Other case just go normal path.
  5139. InitConstants.clear();
  5140. break;
  5141. }
  5142. if (InitConstants.empty())
  5143. staticConstGlobalInitListMap.erase(GV);
  5144. else
  5145. staticConstGlobalCtorMap[GV] = CGF.CurFn;
  5146. }
  5147. }
  5148. return result;
  5149. }
  5150. Value *CGMSHLSLRuntime::EmitHLSLInitListExpr(CodeGenFunction &CGF, InitListExpr *E,
  5151. // The destPtr when emiting aggregate init, for normal case, it will be null.
  5152. Value *DestPtr) {
  5153. if (DestPtr && E->getNumInits() == 1) {
  5154. llvm::Type *ExpTy = CGF.ConvertType(E->getType());
  5155. llvm::Type *TargetTy = CGF.ConvertType(E->getInit(0)->getType());
  5156. if (ExpTy == TargetTy) {
  5157. Expr *Expr = E->getInit(0);
  5158. LValue LV = CGF.EmitLValue(Expr);
  5159. if (LV.isSimple()) {
  5160. Value *SrcPtr = LV.getAddress();
  5161. SmallVector<Value *, 4> idxList;
  5162. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Expr->getType(),
  5163. E->getType(), SrcPtr->getType());
  5164. return nullptr;
  5165. }
  5166. }
  5167. }
  5168. SmallVector<Value *, 4> EltValList;
  5169. SmallVector<QualType, 4> EltTyList;
  5170. ScanInitList(CGF, E, EltValList, EltTyList);
  5171. QualType ResultTy = E->getType();
  5172. unsigned idx = 0;
  5173. // Create cast if need.
  5174. AddMissingCastOpsInInitList(EltValList, EltTyList, idx, ResultTy, CGF);
  5175. DXASSERT(idx == EltValList.size(), "size must match");
  5176. llvm::Type *RetTy = CGF.ConvertType(ResultTy);
  5177. if (DestPtr) {
  5178. SmallVector<Value *, 4> ParamList;
  5179. DXASSERT_NOMSG(RetTy->isAggregateType());
  5180. ParamList.emplace_back(DestPtr);
  5181. ParamList.append(EltValList.begin(), EltValList.end());
  5182. idx = 0;
  5183. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  5184. StoreInitListToDestPtr(DestPtr, EltValList, idx, ResultTy,
  5185. bDefaultRowMajor, CGF, TheModule);
  5186. return nullptr;
  5187. }
  5188. if (IsHLSLVecType(ResultTy)) {
  5189. Value *Result = UndefValue::get(RetTy);
  5190. for (unsigned i = 0; i < RetTy->getVectorNumElements(); i++)
  5191. Result = CGF.Builder.CreateInsertElement(Result, EltValList[i], i);
  5192. return Result;
  5193. } else {
  5194. // Must be matrix here.
  5195. DXASSERT(IsHLSLMatType(ResultTy), "must be matrix type here.");
  5196. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLInit,
  5197. /*opcode*/ 0, RetTy, EltValList,
  5198. TheModule);
  5199. }
  5200. }
  5201. static void FlatConstToList(CodeGenTypes &Types, bool bDefaultRowMajor,
  5202. Constant *C, QualType QualTy,
  5203. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys) {
  5204. llvm::Type *Ty = C->getType();
  5205. DXASSERT(Types.ConvertTypeForMem(QualTy) == Ty, "QualType/Type mismatch!");
  5206. if (llvm::VectorType *VecTy = dyn_cast<llvm::VectorType>(Ty)) {
  5207. DXASSERT(hlsl::IsHLSLVecType(QualTy), "QualType/Type mismatch!");
  5208. QualType VecElemQualTy = hlsl::GetHLSLVecElementType(QualTy);
  5209. for (unsigned i = 0; i < VecTy->getNumElements(); i++) {
  5210. EltVals.emplace_back(C->getAggregateElement(i));
  5211. EltQualTys.emplace_back(VecElemQualTy);
  5212. }
  5213. } else if (HLMatrixType::isa(Ty)) {
  5214. DXASSERT(hlsl::IsHLSLMatType(QualTy), "QualType/Type mismatch!");
  5215. // matrix type is struct { [rowcount x <colcount x T>] };
  5216. // Strip the struct level here.
  5217. Constant *RowArrayVal = C->getAggregateElement((unsigned)0);
  5218. QualType MatEltQualTy = hlsl::GetHLSLMatElementType(QualTy);
  5219. unsigned RowCount, ColCount;
  5220. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  5221. // Get all the elements from the array of row vectors.
  5222. // Matrices are never in memory representation so convert as needed.
  5223. SmallVector<Constant *, 16> MatElts;
  5224. for (unsigned r = 0; r < RowCount; ++r) {
  5225. Constant *RowVec = RowArrayVal->getAggregateElement(r);
  5226. for (unsigned c = 0; c < ColCount; ++c) {
  5227. Constant *MatElt = RowVec->getAggregateElement(c);
  5228. if (MatEltQualTy->isBooleanType()) {
  5229. DXASSERT(MatElt->getType()->isIntegerTy(1),
  5230. "Matrix elements should be in their register representation.");
  5231. MatElt = llvm::ConstantExpr::getZExt(MatElt, Types.ConvertTypeForMem(MatEltQualTy));
  5232. }
  5233. MatElts.emplace_back(MatElt);
  5234. }
  5235. }
  5236. // Return the elements in the order respecting the orientation.
  5237. // Constant initializers are used as the initial value for static variables,
  5238. // which live in memory. This is why they have to respect memory packing order.
  5239. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  5240. for (unsigned r = 0; r < RowCount; ++r) {
  5241. for (unsigned c = 0; c < ColCount; ++c) {
  5242. unsigned Idx = IsRowMajor ? (r * ColCount + c) : (c * RowCount + r);
  5243. EltVals.emplace_back(MatElts[Idx]);
  5244. EltQualTys.emplace_back(MatEltQualTy);
  5245. }
  5246. }
  5247. }
  5248. else if (const clang::ConstantArrayType *ClangArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  5249. QualType ArrayEltQualTy = ClangArrayTy->getElementType();
  5250. uint64_t ArraySize = ClangArrayTy->getSize().getLimitedValue();
  5251. DXASSERT(cast<llvm::ArrayType>(Ty)->getArrayNumElements() == ArraySize, "QualType/Type mismatch!");
  5252. for (unsigned i = 0; i < ArraySize; i++) {
  5253. FlatConstToList(Types, bDefaultRowMajor, C->getAggregateElement(i), ArrayEltQualTy,
  5254. EltVals, EltQualTys);
  5255. }
  5256. }
  5257. else if (const clang::RecordType* RecordTy = QualTy->getAs<clang::RecordType>()) {
  5258. DXASSERT(dyn_cast<llvm::StructType>(Ty) != nullptr, "QualType/Type mismatch!");
  5259. RecordDecl *RecordDecl = RecordTy->getDecl();
  5260. const CGRecordLayout &RL = Types.getCGRecordLayout(RecordDecl);
  5261. // Take care base.
  5262. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RecordDecl)) {
  5263. if (CXXRD->getNumBases()) {
  5264. for (const auto &I : CXXRD->bases()) {
  5265. const CXXRecordDecl *BaseDecl =
  5266. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5267. if (BaseDecl->field_empty())
  5268. continue;
  5269. QualType BaseQualTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5270. unsigned BaseFieldIdx = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5271. FlatConstToList(Types, bDefaultRowMajor,
  5272. C->getAggregateElement(BaseFieldIdx), BaseQualTy, EltVals, EltQualTys);
  5273. }
  5274. }
  5275. }
  5276. for (auto FieldIt = RecordDecl->field_begin(), fieldEnd = RecordDecl->field_end();
  5277. FieldIt != fieldEnd; ++FieldIt) {
  5278. unsigned FieldIndex = RL.getLLVMFieldNo(*FieldIt);
  5279. FlatConstToList(Types, bDefaultRowMajor,
  5280. C->getAggregateElement(FieldIndex), FieldIt->getType(), EltVals, EltQualTys);
  5281. }
  5282. }
  5283. else {
  5284. // At this point, we should have scalars in their memory representation
  5285. DXASSERT_NOMSG(QualTy->isBuiltinType());
  5286. EltVals.emplace_back(C);
  5287. EltQualTys.emplace_back(QualTy);
  5288. }
  5289. }
  5290. static bool ScanConstInitList(CodeGenModule &CGM, bool bDefaultRowMajor,
  5291. InitListExpr *InitList,
  5292. SmallVectorImpl<Constant *> &EltVals,
  5293. SmallVectorImpl<QualType> &EltQualTys) {
  5294. unsigned NumInitElements = InitList->getNumInits();
  5295. for (unsigned i = 0; i != NumInitElements; ++i) {
  5296. Expr *InitExpr = InitList->getInit(i);
  5297. QualType InitQualTy = InitExpr->getType();
  5298. if (InitListExpr *SubInitList = dyn_cast<InitListExpr>(InitExpr)) {
  5299. if (!ScanConstInitList(CGM, bDefaultRowMajor, SubInitList, EltVals, EltQualTys))
  5300. return false;
  5301. } else if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(InitExpr)) {
  5302. if (VarDecl *Var = dyn_cast<VarDecl>(DeclRef->getDecl())) {
  5303. if (!Var->hasInit())
  5304. return false;
  5305. if (Constant *InitVal = CGM.EmitConstantInit(*Var)) {
  5306. FlatConstToList(CGM.getTypes(), bDefaultRowMajor,
  5307. InitVal, InitQualTy, EltVals, EltQualTys);
  5308. } else {
  5309. return false;
  5310. }
  5311. } else {
  5312. return false;
  5313. }
  5314. } else if (hlsl::IsHLSLMatType(InitQualTy)) {
  5315. return false;
  5316. } else if (CodeGenFunction::hasScalarEvaluationKind(InitQualTy)) {
  5317. if (Constant *InitVal = CGM.EmitConstantExpr(InitExpr, InitQualTy)) {
  5318. FlatConstToList(CGM.getTypes(), bDefaultRowMajor, InitVal, InitQualTy, EltVals, EltQualTys);
  5319. } else {
  5320. return false;
  5321. }
  5322. } else {
  5323. return false;
  5324. }
  5325. }
  5326. return true;
  5327. }
  5328. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  5329. QualType QualTy, bool MemRepr,
  5330. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx);
  5331. static Constant *BuildConstMatrix(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  5332. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  5333. QualType MatEltTy = hlsl::GetHLSLMatElementType(QualTy);
  5334. unsigned RowCount, ColCount;
  5335. hlsl::GetHLSLMatRowColCount(QualTy, RowCount, ColCount);
  5336. bool IsRowMajor = hlsl::IsHLSLMatRowMajor(QualTy, bDefaultRowMajor);
  5337. // Save initializer elements first.
  5338. // Matrix initializer is row major.
  5339. SmallVector<Constant *, 16> RowMajorMatElts;
  5340. for (unsigned i = 0; i < RowCount * ColCount; i++) {
  5341. // Matrix elements are never in their memory representation,
  5342. // to preserve type information for later lowering.
  5343. bool MemRepr = false;
  5344. RowMajorMatElts.emplace_back(BuildConstInitializer(
  5345. Types, bDefaultRowMajor, MatEltTy, MemRepr,
  5346. EltVals, EltQualTys, EltIdx));
  5347. }
  5348. SmallVector<Constant *, 16> FinalMatElts;
  5349. if (IsRowMajor) {
  5350. FinalMatElts = RowMajorMatElts;
  5351. }
  5352. else {
  5353. // Cast row major to col major.
  5354. for (unsigned c = 0; c < ColCount; c++) {
  5355. for (unsigned r = 0; r < RowCount; r++) {
  5356. FinalMatElts.emplace_back(RowMajorMatElts[r * ColCount + c]);
  5357. }
  5358. }
  5359. }
  5360. // The type is vector<element, col>[row].
  5361. SmallVector<Constant *, 4> Rows;
  5362. unsigned idx = 0;
  5363. for (unsigned r = 0; r < RowCount; r++) {
  5364. SmallVector<Constant *, 4> RowElts;
  5365. for (unsigned c = 0; c < ColCount; c++) {
  5366. RowElts.emplace_back(FinalMatElts[idx++]);
  5367. }
  5368. Rows.emplace_back(llvm::ConstantVector::get(RowElts));
  5369. }
  5370. Constant *RowArray = llvm::ConstantArray::get(
  5371. llvm::ArrayType::get(Rows[0]->getType(), Rows.size()), Rows);
  5372. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertType(QualTy)), RowArray);
  5373. }
  5374. static Constant *BuildConstStruct(CodeGenTypes &Types, bool bDefaultRowMajor, QualType QualTy,
  5375. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  5376. const RecordDecl *Record = QualTy->castAs<RecordType>()->getDecl();
  5377. bool MemRepr = true; // Structs are always in their memory representation
  5378. SmallVector<Constant *, 4> FieldVals;
  5379. if (const CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(Record)) {
  5380. if (CXXRecord->getNumBases()) {
  5381. // Add base as field.
  5382. for (const auto &BaseSpec : CXXRecord->bases()) {
  5383. const CXXRecordDecl *BaseDecl =
  5384. cast<CXXRecordDecl>(BaseSpec.getType()->castAs<RecordType>()->getDecl());
  5385. // Skip empty struct.
  5386. if (BaseDecl->field_empty())
  5387. continue;
  5388. // Add base as a whole constant. Not as element.
  5389. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  5390. BaseSpec.getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  5391. }
  5392. }
  5393. }
  5394. for (auto FieldIt = Record->field_begin(), FieldEnd = Record->field_end();
  5395. FieldIt != FieldEnd; ++FieldIt) {
  5396. FieldVals.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  5397. FieldIt->getType(), MemRepr, EltVals, EltQualTys, EltIdx));
  5398. }
  5399. return llvm::ConstantStruct::get(cast<llvm::StructType>(Types.ConvertTypeForMem(QualTy)), FieldVals);
  5400. }
  5401. static Constant *BuildConstInitializer(CodeGenTypes &Types, bool bDefaultRowMajor,
  5402. QualType QualTy, bool MemRepr,
  5403. SmallVectorImpl<Constant *> &EltVals, SmallVectorImpl<QualType> &EltQualTys, unsigned &EltIdx) {
  5404. if (hlsl::IsHLSLVecType(QualTy)) {
  5405. QualType VecEltQualTy = hlsl::GetHLSLVecElementType(QualTy);
  5406. unsigned VecSize = hlsl::GetHLSLVecSize(QualTy);
  5407. SmallVector<Constant *, 4> VecElts;
  5408. for (unsigned i = 0; i < VecSize; i++) {
  5409. VecElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  5410. VecEltQualTy, MemRepr,
  5411. EltVals, EltQualTys, EltIdx));
  5412. }
  5413. return llvm::ConstantVector::get(VecElts);
  5414. }
  5415. else if (const clang::ConstantArrayType *ArrayTy = Types.getContext().getAsConstantArrayType(QualTy)) {
  5416. QualType ArrayEltQualTy = QualType(ArrayTy->getArrayElementTypeNoTypeQual(), 0);
  5417. uint64_t ArraySize = ArrayTy->getSize().getLimitedValue();
  5418. SmallVector<Constant *, 4> ArrayElts;
  5419. for (unsigned i = 0; i < ArraySize; i++) {
  5420. ArrayElts.emplace_back(BuildConstInitializer(Types, bDefaultRowMajor,
  5421. ArrayEltQualTy, true, // Array elements must be in their memory representation
  5422. EltVals, EltQualTys, EltIdx));
  5423. }
  5424. return llvm::ConstantArray::get(
  5425. cast<llvm::ArrayType>(Types.ConvertTypeForMem(QualTy)), ArrayElts);
  5426. }
  5427. else if (hlsl::IsHLSLMatType(QualTy)) {
  5428. return BuildConstMatrix(Types, bDefaultRowMajor, QualTy,
  5429. EltVals, EltQualTys, EltIdx);
  5430. }
  5431. else if (QualTy->getAs<clang::RecordType>() != nullptr) {
  5432. return BuildConstStruct(Types, bDefaultRowMajor, QualTy,
  5433. EltVals, EltQualTys, EltIdx);
  5434. } else {
  5435. DXASSERT_NOMSG(QualTy->isBuiltinType());
  5436. Constant *EltVal = EltVals[EltIdx];
  5437. QualType EltQualTy = EltQualTys[EltIdx];
  5438. EltIdx++;
  5439. // Initializer constants are in their memory representation.
  5440. if (EltQualTy == QualTy && MemRepr) return EltVal;
  5441. CGBuilderTy Builder(EltVal->getContext());
  5442. if (EltQualTy->isBooleanType()) {
  5443. // Convert to register representation
  5444. // We don't have access to CodeGenFunction::EmitFromMemory here
  5445. DXASSERT_NOMSG(!EltVal->getType()->isIntegerTy(1));
  5446. EltVal = cast<Constant>(Builder.CreateICmpNE(EltVal, Constant::getNullValue(EltVal->getType())));
  5447. }
  5448. Constant *Result = cast<Constant>(ConvertScalarOrVector(Builder, Types, EltVal, EltQualTy, QualTy));
  5449. if (QualTy->isBooleanType() && MemRepr) {
  5450. // Convert back to the memory representation
  5451. // We don't have access to CodeGenFunction::EmitToMemory here
  5452. DXASSERT_NOMSG(Result->getType()->isIntegerTy(1));
  5453. Result = cast<Constant>(Builder.CreateZExt(Result, Types.ConvertTypeForMem(QualTy)));
  5454. }
  5455. return Result;
  5456. }
  5457. }
  5458. Constant *CGMSHLSLRuntime::EmitHLSLConstInitListExpr(CodeGenModule &CGM,
  5459. InitListExpr *E) {
  5460. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  5461. SmallVector<Constant *, 4> EltVals;
  5462. SmallVector<QualType, 4> EltQualTys;
  5463. if (!ScanConstInitList(CGM, bDefaultRowMajor, E, EltVals, EltQualTys))
  5464. return nullptr;
  5465. QualType QualTy = E->getType();
  5466. unsigned EltIdx = 0;
  5467. bool MemRepr = true;
  5468. return BuildConstInitializer(CGM.getTypes(), bDefaultRowMajor,
  5469. QualTy, MemRepr, EltVals, EltQualTys, EltIdx);
  5470. }
  5471. Value *CGMSHLSLRuntime::EmitHLSLMatrixOperationCall(
  5472. CodeGenFunction &CGF, const clang::Expr *E, llvm::Type *RetType,
  5473. ArrayRef<Value *> paramList) {
  5474. HLOpcodeGroup group = GetHLOpcodeGroup(E->getStmtClass());
  5475. unsigned opcode = GetHLOpcode(E);
  5476. if (group == HLOpcodeGroup::HLInit)
  5477. return EmitHLSLArrayInit(CGF.Builder, group, opcode, RetType, paramList,
  5478. TheModule);
  5479. else
  5480. return EmitHLSLMatrixOperationCallImp(CGF.Builder, group, opcode, RetType,
  5481. paramList, TheModule);
  5482. }
  5483. void CGMSHLSLRuntime::EmitHLSLDiscard(CodeGenFunction &CGF) {
  5484. EmitHLSLMatrixOperationCallImp(
  5485. CGF.Builder, HLOpcodeGroup::HLIntrinsic,
  5486. static_cast<unsigned>(IntrinsicOp::IOP_clip),
  5487. llvm::Type::getVoidTy(CGF.getLLVMContext()),
  5488. {ConstantFP::get(llvm::Type::getFloatTy(CGF.getLLVMContext()), -1.0f)},
  5489. TheModule);
  5490. }
  5491. static llvm::Type *MergeIntType(llvm::IntegerType *T0, llvm::IntegerType *T1) {
  5492. if (T0->getBitWidth() > T1->getBitWidth())
  5493. return T0;
  5494. else
  5495. return T1;
  5496. }
  5497. static Value *CreateExt(CGBuilderTy &Builder, Value *Src, llvm::Type *DstTy,
  5498. bool bSigned) {
  5499. if (bSigned)
  5500. return Builder.CreateSExt(Src, DstTy);
  5501. else
  5502. return Builder.CreateZExt(Src, DstTy);
  5503. }
  5504. // For integer literal, try to get lowest precision.
  5505. static Value *CalcHLSLLiteralToLowestPrecision(CGBuilderTy &Builder, Value *Src,
  5506. bool bSigned) {
  5507. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  5508. APInt v = CI->getValue();
  5509. switch (v.getActiveWords()) {
  5510. case 4:
  5511. return Builder.getInt32(v.getLimitedValue());
  5512. case 8:
  5513. return Builder.getInt64(v.getLimitedValue());
  5514. case 2:
  5515. // TODO: use low precision type when support it in dxil.
  5516. // return Builder.getInt16(v.getLimitedValue());
  5517. return Builder.getInt32(v.getLimitedValue());
  5518. case 1:
  5519. // TODO: use precision type when support it in dxil.
  5520. // return Builder.getInt8(v.getLimitedValue());
  5521. return Builder.getInt32(v.getLimitedValue());
  5522. default:
  5523. return nullptr;
  5524. }
  5525. } else if (SelectInst *SI = dyn_cast<SelectInst>(Src)) {
  5526. if (SI->getType()->isIntegerTy()) {
  5527. Value *T = SI->getTrueValue();
  5528. Value *F = SI->getFalseValue();
  5529. Value *lowT = CalcHLSLLiteralToLowestPrecision(Builder, T, bSigned);
  5530. Value *lowF = CalcHLSLLiteralToLowestPrecision(Builder, F, bSigned);
  5531. if (lowT && lowF && lowT != T && lowF != F) {
  5532. llvm::IntegerType *TTy = cast<llvm::IntegerType>(lowT->getType());
  5533. llvm::IntegerType *FTy = cast<llvm::IntegerType>(lowF->getType());
  5534. llvm::Type *Ty = MergeIntType(TTy, FTy);
  5535. if (TTy != Ty) {
  5536. lowT = CreateExt(Builder, lowT, Ty, bSigned);
  5537. }
  5538. if (FTy != Ty) {
  5539. lowF = CreateExt(Builder, lowF, Ty, bSigned);
  5540. }
  5541. Value *Cond = SI->getCondition();
  5542. return Builder.CreateSelect(Cond, lowT, lowF);
  5543. }
  5544. }
  5545. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(Src)) {
  5546. Value *Src0 = BO->getOperand(0);
  5547. Value *Src1 = BO->getOperand(1);
  5548. Value *CastSrc0 = CalcHLSLLiteralToLowestPrecision(Builder, Src0, bSigned);
  5549. Value *CastSrc1 = CalcHLSLLiteralToLowestPrecision(Builder, Src1, bSigned);
  5550. if (Src0 != CastSrc0 && Src1 != CastSrc1 && CastSrc0 && CastSrc1 &&
  5551. CastSrc0->getType() == CastSrc1->getType()) {
  5552. llvm::IntegerType *Ty0 = cast<llvm::IntegerType>(CastSrc0->getType());
  5553. llvm::IntegerType *Ty1 = cast<llvm::IntegerType>(CastSrc0->getType());
  5554. llvm::Type *Ty = MergeIntType(Ty0, Ty1);
  5555. if (Ty0 != Ty) {
  5556. CastSrc0 = CreateExt(Builder, CastSrc0, Ty, bSigned);
  5557. }
  5558. if (Ty1 != Ty) {
  5559. CastSrc1 = CreateExt(Builder, CastSrc1, Ty, bSigned);
  5560. }
  5561. return Builder.CreateBinOp(BO->getOpcode(), CastSrc0, CastSrc1);
  5562. }
  5563. }
  5564. return nullptr;
  5565. }
  5566. Value *CGMSHLSLRuntime::EmitHLSLLiteralCast(CodeGenFunction &CGF, Value *Src,
  5567. QualType SrcType,
  5568. QualType DstType) {
  5569. auto &Builder = CGF.Builder;
  5570. llvm::Type *DstTy = CGF.ConvertType(DstType);
  5571. bool bDstSigned = DstType->isSignedIntegerType();
  5572. if (ConstantInt *CI = dyn_cast<ConstantInt>(Src)) {
  5573. APInt v = CI->getValue();
  5574. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5575. v = v.trunc(IT->getBitWidth());
  5576. switch (IT->getBitWidth()) {
  5577. case 32:
  5578. return Builder.getInt32(v.getLimitedValue());
  5579. case 64:
  5580. return Builder.getInt64(v.getLimitedValue());
  5581. case 16:
  5582. return Builder.getInt16(v.getLimitedValue());
  5583. case 8:
  5584. return Builder.getInt8(v.getLimitedValue());
  5585. default:
  5586. return nullptr;
  5587. }
  5588. } else {
  5589. DXASSERT_NOMSG(DstTy->isFloatingPointTy());
  5590. int64_t val = v.getLimitedValue();
  5591. if (v.isNegative())
  5592. val = 0-v.abs().getLimitedValue();
  5593. if (DstTy->isDoubleTy())
  5594. return ConstantFP::get(DstTy, (double)val);
  5595. else if (DstTy->isFloatTy())
  5596. return ConstantFP::get(DstTy, (float)val);
  5597. else {
  5598. if (bDstSigned)
  5599. return Builder.CreateSIToFP(Src, DstTy);
  5600. else
  5601. return Builder.CreateUIToFP(Src, DstTy);
  5602. }
  5603. }
  5604. } else if (ConstantFP *CF = dyn_cast<ConstantFP>(Src)) {
  5605. APFloat v = CF->getValueAPF();
  5606. double dv = v.convertToDouble();
  5607. if (llvm::IntegerType *IT = dyn_cast<llvm::IntegerType>(DstTy)) {
  5608. switch (IT->getBitWidth()) {
  5609. case 32:
  5610. return Builder.getInt32(dv);
  5611. case 64:
  5612. return Builder.getInt64(dv);
  5613. case 16:
  5614. return Builder.getInt16(dv);
  5615. case 8:
  5616. return Builder.getInt8(dv);
  5617. default:
  5618. return nullptr;
  5619. }
  5620. } else {
  5621. if (DstTy->isFloatTy()) {
  5622. float fv = dv;
  5623. return ConstantFP::get(DstTy->getContext(), APFloat(fv));
  5624. } else {
  5625. return Builder.CreateFPTrunc(Src, DstTy);
  5626. }
  5627. }
  5628. } else if (dyn_cast<UndefValue>(Src)) {
  5629. return UndefValue::get(DstTy);
  5630. } else {
  5631. Instruction *I = cast<Instruction>(Src);
  5632. if (SelectInst *SI = dyn_cast<SelectInst>(I)) {
  5633. Value *T = SI->getTrueValue();
  5634. Value *F = SI->getFalseValue();
  5635. Value *Cond = SI->getCondition();
  5636. if (isa<llvm::ConstantInt>(T) && isa<llvm::ConstantInt>(F)) {
  5637. llvm::APInt lhs = cast<llvm::ConstantInt>(T)->getValue();
  5638. llvm::APInt rhs = cast<llvm::ConstantInt>(F)->getValue();
  5639. if (DstTy == Builder.getInt32Ty()) {
  5640. T = Builder.getInt32(lhs.getLimitedValue());
  5641. F = Builder.getInt32(rhs.getLimitedValue());
  5642. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5643. return Sel;
  5644. } else if (DstTy->isFloatingPointTy()) {
  5645. T = ConstantFP::get(DstTy, int64_t(lhs.getLimitedValue()));
  5646. F = ConstantFP::get(DstTy, int64_t(rhs.getLimitedValue()));
  5647. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5648. return Sel;
  5649. }
  5650. } else if (isa<llvm::ConstantFP>(T) && isa<llvm::ConstantFP>(F)) {
  5651. llvm::APFloat lhs = cast<llvm::ConstantFP>(T)->getValueAPF();
  5652. llvm::APFloat rhs = cast<llvm::ConstantFP>(F)->getValueAPF();
  5653. double ld = lhs.convertToDouble();
  5654. double rd = rhs.convertToDouble();
  5655. if (DstTy->isFloatTy()) {
  5656. float lf = ld;
  5657. float rf = rd;
  5658. T = ConstantFP::get(DstTy->getContext(), APFloat(lf));
  5659. F = ConstantFP::get(DstTy->getContext(), APFloat(rf));
  5660. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5661. return Sel;
  5662. } else if (DstTy == Builder.getInt32Ty()) {
  5663. T = Builder.getInt32(ld);
  5664. F = Builder.getInt32(rd);
  5665. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5666. return Sel;
  5667. } else if (DstTy == Builder.getInt64Ty()) {
  5668. T = Builder.getInt64(ld);
  5669. F = Builder.getInt64(rd);
  5670. Value *Sel = Builder.CreateSelect(Cond, T, F, "cond");
  5671. return Sel;
  5672. }
  5673. }
  5674. } else if (llvm::BinaryOperator *BO = dyn_cast<llvm::BinaryOperator>(I)) {
  5675. // For integer binary operator, do the calc on lowest precision, then cast
  5676. // to dstTy.
  5677. if (I->getType()->isIntegerTy()) {
  5678. bool bSigned = DstType->isSignedIntegerType();
  5679. Value *CastResult =
  5680. CalcHLSLLiteralToLowestPrecision(Builder, BO, bSigned);
  5681. if (!CastResult)
  5682. return nullptr;
  5683. if (dyn_cast<llvm::IntegerType>(DstTy)) {
  5684. if (DstTy == CastResult->getType()) {
  5685. return CastResult;
  5686. } else {
  5687. if (bSigned)
  5688. return Builder.CreateSExtOrTrunc(CastResult, DstTy);
  5689. else
  5690. return Builder.CreateZExtOrTrunc(CastResult, DstTy);
  5691. }
  5692. } else {
  5693. if (bDstSigned)
  5694. return Builder.CreateSIToFP(CastResult, DstTy);
  5695. else
  5696. return Builder.CreateUIToFP(CastResult, DstTy);
  5697. }
  5698. }
  5699. }
  5700. // TODO: support other opcode if need.
  5701. return nullptr;
  5702. }
  5703. }
  5704. Value *CGMSHLSLRuntime::EmitHLSLMatrixSubscript(CodeGenFunction &CGF,
  5705. llvm::Type *RetType,
  5706. llvm::Value *Ptr,
  5707. llvm::Value *Idx,
  5708. clang::QualType Ty) {
  5709. bool isRowMajor =
  5710. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5711. unsigned opcode =
  5712. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatSubscript)
  5713. : static_cast<unsigned>(HLSubscriptOpcode::ColMatSubscript);
  5714. Value *matBase = Ptr;
  5715. DXASSERT(matBase->getType()->isPointerTy(),
  5716. "matrix subscript should return pointer");
  5717. RetType =
  5718. llvm::PointerType::get(RetType->getPointerElementType(),
  5719. matBase->getType()->getPointerAddressSpace());
  5720. // Lower mat[Idx] into real idx.
  5721. SmallVector<Value *, 8> args;
  5722. args.emplace_back(Ptr);
  5723. unsigned row, col;
  5724. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  5725. if (isRowMajor) {
  5726. Value *cCol = ConstantInt::get(Idx->getType(), col);
  5727. Value *Base = CGF.Builder.CreateMul(cCol, Idx);
  5728. for (unsigned i = 0; i < col; i++) {
  5729. Value *c = ConstantInt::get(Idx->getType(), i);
  5730. // r * col + c
  5731. Value *matIdx = CGF.Builder.CreateAdd(Base, c);
  5732. args.emplace_back(matIdx);
  5733. }
  5734. } else {
  5735. for (unsigned i = 0; i < col; i++) {
  5736. Value *cMulRow = ConstantInt::get(Idx->getType(), i * row);
  5737. // c * row + r
  5738. Value *matIdx = CGF.Builder.CreateAdd(cMulRow, Idx);
  5739. args.emplace_back(matIdx);
  5740. }
  5741. }
  5742. Value *matSub =
  5743. EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  5744. opcode, RetType, args, TheModule);
  5745. return matSub;
  5746. }
  5747. Value *CGMSHLSLRuntime::EmitHLSLMatrixElement(CodeGenFunction &CGF,
  5748. llvm::Type *RetType,
  5749. ArrayRef<Value *> paramList,
  5750. QualType Ty) {
  5751. bool isRowMajor =
  5752. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5753. unsigned opcode =
  5754. isRowMajor ? static_cast<unsigned>(HLSubscriptOpcode::RowMatElement)
  5755. : static_cast<unsigned>(HLSubscriptOpcode::ColMatElement);
  5756. Value *matBase = paramList[0];
  5757. DXASSERT(matBase->getType()->isPointerTy(),
  5758. "matrix element should return pointer");
  5759. RetType =
  5760. llvm::PointerType::get(RetType->getPointerElementType(),
  5761. matBase->getType()->getPointerAddressSpace());
  5762. Value *idx = paramList[HLOperandIndex::kMatSubscriptSubOpIdx-1];
  5763. // Lower _m00 into real idx.
  5764. // -1 to avoid opcode param which is added in EmitHLSLMatrixOperationCallImp.
  5765. Value *args[] = {paramList[HLOperandIndex::kMatSubscriptMatOpIdx - 1],
  5766. paramList[HLOperandIndex::kMatSubscriptSubOpIdx - 1]};
  5767. // For all zero idx. Still all zero idx.
  5768. if (ConstantAggregateZero *zeros = dyn_cast<ConstantAggregateZero>(idx)) {
  5769. Constant *zero = zeros->getAggregateElement((unsigned)0);
  5770. std::vector<Constant *> elts(zeros->getNumElements() >> 1, zero);
  5771. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(elts);
  5772. } else {
  5773. ConstantDataSequential *elts = cast<ConstantDataSequential>(idx);
  5774. unsigned count = elts->getNumElements();
  5775. unsigned row, col;
  5776. hlsl::GetHLSLMatRowColCount(Ty, row, col);
  5777. std::vector<Constant *> idxs(count >> 1);
  5778. for (unsigned i = 0; i < count; i += 2) {
  5779. unsigned rowIdx = elts->getElementAsInteger(i);
  5780. unsigned colIdx = elts->getElementAsInteger(i + 1);
  5781. unsigned matIdx = 0;
  5782. if (isRowMajor) {
  5783. matIdx = rowIdx * col + colIdx;
  5784. } else {
  5785. matIdx = colIdx * row + rowIdx;
  5786. }
  5787. idxs[i >> 1] = CGF.Builder.getInt32(matIdx);
  5788. }
  5789. args[HLOperandIndex::kMatSubscriptSubOpIdx - 1] = ConstantVector::get(idxs);
  5790. }
  5791. return EmitHLSLMatrixOperationCallImp(CGF.Builder, HLOpcodeGroup::HLSubscript,
  5792. opcode, RetType, args, TheModule);
  5793. }
  5794. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CGBuilderTy &Builder, Value *Ptr,
  5795. QualType Ty) {
  5796. bool isRowMajor =
  5797. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5798. unsigned opcode =
  5799. isRowMajor
  5800. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatLoad)
  5801. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatLoad);
  5802. Value *matVal = EmitHLSLMatrixOperationCallImp(
  5803. Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  5804. Ptr->getType()->getPointerElementType(), {Ptr}, TheModule);
  5805. if (!isRowMajor) {
  5806. // ColMatLoad will return a col major matrix.
  5807. // All matrix Value should be row major.
  5808. // Cast it to row major.
  5809. matVal = EmitHLSLMatrixOperationCallImp(
  5810. Builder, HLOpcodeGroup::HLCast,
  5811. static_cast<unsigned>(HLCastOpcode::ColMatrixToRowMatrix),
  5812. matVal->getType(), {matVal}, TheModule);
  5813. }
  5814. return matVal;
  5815. }
  5816. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CGBuilderTy &Builder, Value *Val,
  5817. Value *DestPtr, QualType Ty) {
  5818. bool isRowMajor =
  5819. hlsl::IsHLSLMatRowMajor(Ty, m_pHLModule->GetHLOptions().bDefaultRowMajor);
  5820. unsigned opcode =
  5821. isRowMajor
  5822. ? static_cast<unsigned>(HLMatLoadStoreOpcode::RowMatStore)
  5823. : static_cast<unsigned>(HLMatLoadStoreOpcode::ColMatStore);
  5824. if (!isRowMajor) {
  5825. Value *ColVal = nullptr;
  5826. // If Val is casted from col major. Just use the original col major val.
  5827. if (CallInst *CI = dyn_cast<CallInst>(Val)) {
  5828. hlsl::HLOpcodeGroup group =
  5829. hlsl::GetHLOpcodeGroupByName(CI->getCalledFunction());
  5830. if (group == HLOpcodeGroup::HLCast) {
  5831. HLCastOpcode castOp = static_cast<HLCastOpcode>(hlsl::GetHLOpcode(CI));
  5832. if (castOp == HLCastOpcode::ColMatrixToRowMatrix) {
  5833. ColVal = CI->getArgOperand(HLOperandIndex::kUnaryOpSrc0Idx);
  5834. }
  5835. }
  5836. }
  5837. if (ColVal) {
  5838. Val = ColVal;
  5839. } else {
  5840. // All matrix Value should be row major.
  5841. // ColMatStore need a col major value.
  5842. // Cast it to row major.
  5843. Val = EmitHLSLMatrixOperationCallImp(
  5844. Builder, HLOpcodeGroup::HLCast,
  5845. static_cast<unsigned>(HLCastOpcode::RowMatrixToColMatrix),
  5846. Val->getType(), {Val}, TheModule);
  5847. }
  5848. }
  5849. EmitHLSLMatrixOperationCallImp(Builder, HLOpcodeGroup::HLMatLoadStore, opcode,
  5850. Val->getType(), {DestPtr, Val}, TheModule);
  5851. }
  5852. Value *CGMSHLSLRuntime::EmitHLSLMatrixLoad(CodeGenFunction &CGF, Value *Ptr,
  5853. QualType Ty) {
  5854. return EmitHLSLMatrixLoad(CGF.Builder, Ptr, Ty);
  5855. }
  5856. void CGMSHLSLRuntime::EmitHLSLMatrixStore(CodeGenFunction &CGF, Value *Val,
  5857. Value *DestPtr, QualType Ty) {
  5858. EmitHLSLMatrixStore(CGF.Builder, Val, DestPtr, Ty);
  5859. }
  5860. // Copy data from srcPtr to destPtr.
  5861. static void SimplePtrCopy(Value *DestPtr, Value *SrcPtr,
  5862. ArrayRef<Value *> idxList, CGBuilderTy &Builder) {
  5863. if (idxList.size() > 1) {
  5864. DestPtr = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5865. SrcPtr = Builder.CreateInBoundsGEP(SrcPtr, idxList);
  5866. }
  5867. llvm::LoadInst *ld = Builder.CreateLoad(SrcPtr);
  5868. Builder.CreateStore(ld, DestPtr);
  5869. }
  5870. // Get Element val from SrvVal with extract value.
  5871. static Value *GetEltVal(Value *SrcVal, ArrayRef<Value*> idxList,
  5872. CGBuilderTy &Builder) {
  5873. Value *Val = SrcVal;
  5874. // Skip beginning pointer type.
  5875. for (unsigned i = 1; i < idxList.size(); i++) {
  5876. ConstantInt *idx = cast<ConstantInt>(idxList[i]);
  5877. llvm::Type *Ty = Val->getType();
  5878. if (Ty->isAggregateType()) {
  5879. Val = Builder.CreateExtractValue(Val, idx->getLimitedValue());
  5880. }
  5881. }
  5882. return Val;
  5883. }
  5884. // Copy srcVal to destPtr.
  5885. static void SimpleValCopy(Value *DestPtr, Value *SrcVal,
  5886. ArrayRef<Value*> idxList,
  5887. CGBuilderTy &Builder) {
  5888. Value *DestGEP = Builder.CreateInBoundsGEP(DestPtr, idxList);
  5889. Value *Val = GetEltVal(SrcVal, idxList, Builder);
  5890. Builder.CreateStore(Val, DestGEP);
  5891. }
  5892. static void SimpleCopy(Value *Dest, Value *Src,
  5893. ArrayRef<Value *> idxList,
  5894. CGBuilderTy &Builder) {
  5895. if (Src->getType()->isPointerTy())
  5896. SimplePtrCopy(Dest, Src, idxList, Builder);
  5897. else
  5898. SimpleValCopy(Dest, Src, idxList, Builder);
  5899. }
  5900. void CGMSHLSLRuntime::FlattenAggregatePtrToGepList(
  5901. CodeGenFunction &CGF, Value *Ptr, SmallVector<Value *, 4> &idxList,
  5902. clang::QualType Type, llvm::Type *Ty, SmallVector<Value *, 4> &GepList,
  5903. SmallVector<QualType, 4> &EltTyList) {
  5904. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  5905. Constant *idx = Constant::getIntegerValue(
  5906. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  5907. idxList.emplace_back(idx);
  5908. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, Type, PT->getElementType(),
  5909. GepList, EltTyList);
  5910. idxList.pop_back();
  5911. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  5912. // Use matLd/St for matrix.
  5913. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  5914. llvm::PointerType *EltPtrTy =
  5915. llvm::PointerType::get(EltTy, Ptr->getType()->getPointerAddressSpace());
  5916. QualType EltQualTy = hlsl::GetHLSLMatElementType(Type);
  5917. Value *matPtr = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5918. // Flatten matrix to elements.
  5919. for (unsigned r = 0; r < MatTy.getNumRows(); r++) {
  5920. for (unsigned c = 0; c < MatTy.getNumColumns(); c++) {
  5921. ConstantInt *cRow = CGF.Builder.getInt32(r);
  5922. ConstantInt *cCol = CGF.Builder.getInt32(c);
  5923. Constant *CV = llvm::ConstantVector::get({cRow, cCol});
  5924. GepList.push_back(
  5925. EmitHLSLMatrixElement(CGF, EltPtrTy, {matPtr, CV}, Type));
  5926. EltTyList.push_back(EltQualTy);
  5927. }
  5928. }
  5929. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  5930. if (dxilutil::IsHLSLObjectType(ST)) {
  5931. // Avoid split HLSL object.
  5932. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5933. GepList.push_back(GEP);
  5934. EltTyList.push_back(Type);
  5935. return;
  5936. }
  5937. const clang::RecordType *RT = Type->getAsStructureType();
  5938. RecordDecl *RD = RT->getDecl();
  5939. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  5940. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5941. if (CXXRD->getNumBases()) {
  5942. // Add base as field.
  5943. for (const auto &I : CXXRD->bases()) {
  5944. const CXXRecordDecl *BaseDecl =
  5945. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5946. // Skip empty struct.
  5947. if (BaseDecl->field_empty())
  5948. continue;
  5949. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5950. llvm::Type *parentType = CGF.ConvertType(parentTy);
  5951. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  5952. Constant *idx = llvm::Constant::getIntegerValue(
  5953. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5954. idxList.emplace_back(idx);
  5955. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, parentTy, parentType,
  5956. GepList, EltTyList);
  5957. idxList.pop_back();
  5958. }
  5959. }
  5960. }
  5961. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  5962. fieldIter != fieldEnd; ++fieldIter) {
  5963. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  5964. llvm::Type *ET = ST->getElementType(i);
  5965. Constant *idx = llvm::Constant::getIntegerValue(
  5966. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5967. idxList.emplace_back(idx);
  5968. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, fieldIter->getType(), ET,
  5969. GepList, EltTyList);
  5970. idxList.pop_back();
  5971. }
  5972. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  5973. llvm::Type *ET = AT->getElementType();
  5974. QualType EltType = CGF.getContext().getBaseElementType(Type);
  5975. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  5976. Constant *idx = Constant::getIntegerValue(
  5977. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  5978. idxList.emplace_back(idx);
  5979. FlattenAggregatePtrToGepList(CGF, Ptr, idxList, EltType, ET, GepList,
  5980. EltTyList);
  5981. idxList.pop_back();
  5982. }
  5983. } else if (llvm::VectorType *VT = dyn_cast<llvm::VectorType>(Ty)) {
  5984. // Flatten vector too.
  5985. QualType EltTy = hlsl::GetHLSLVecElementType(Type);
  5986. for (uint32_t i = 0; i < VT->getNumElements(); i++) {
  5987. Constant *idx = CGF.Builder.getInt32(i);
  5988. idxList.emplace_back(idx);
  5989. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5990. GepList.push_back(GEP);
  5991. EltTyList.push_back(EltTy);
  5992. idxList.pop_back();
  5993. }
  5994. } else {
  5995. Value *GEP = CGF.Builder.CreateInBoundsGEP(Ptr, idxList);
  5996. GepList.push_back(GEP);
  5997. EltTyList.push_back(Type);
  5998. }
  5999. }
  6000. void CGMSHLSLRuntime::LoadElements(CodeGenFunction &CGF,
  6001. ArrayRef<Value *> Ptrs, ArrayRef<QualType> QualTys,
  6002. SmallVector<Value *, 4> &Vals) {
  6003. for (size_t i = 0, e = Ptrs.size(); i < e; i++) {
  6004. Value *Ptr = Ptrs[i];
  6005. llvm::Type *Ty = Ptr->getType()->getPointerElementType();
  6006. DXASSERT_LOCALVAR(Ty, Ty->isIntegerTy() || Ty->isFloatingPointTy(), "Expected only element types.");
  6007. Value *Val = CGF.Builder.CreateLoad(Ptr);
  6008. Val = CGF.EmitFromMemory(Val, QualTys[i]);
  6009. Vals.push_back(Val);
  6010. }
  6011. }
  6012. void CGMSHLSLRuntime::ConvertAndStoreElements(CodeGenFunction &CGF,
  6013. ArrayRef<Value *> SrcVals, ArrayRef<QualType> SrcQualTys,
  6014. ArrayRef<Value *> DstPtrs, ArrayRef<QualType> DstQualTys) {
  6015. for (size_t i = 0, e = DstPtrs.size(); i < e; i++) {
  6016. Value *DstPtr = DstPtrs[i];
  6017. QualType DstQualTy = DstQualTys[i];
  6018. Value *SrcVal = SrcVals[i];
  6019. QualType SrcQualTy = SrcQualTys[i];
  6020. DXASSERT(SrcVal->getType()->isIntegerTy() || SrcVal->getType()->isFloatingPointTy(),
  6021. "Expected only element types.");
  6022. llvm::Value *Result = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstQualTy);
  6023. Result = CGF.EmitToMemory(Result, DstQualTy);
  6024. CGF.Builder.CreateStore(Result, DstPtr);
  6025. }
  6026. }
  6027. static bool AreMatrixArrayOrientationMatching(ASTContext& Context,
  6028. HLModule &Module, QualType LhsTy, QualType RhsTy) {
  6029. while (const clang::ArrayType *LhsArrayTy = Context.getAsArrayType(LhsTy)) {
  6030. LhsTy = LhsArrayTy->getElementType();
  6031. RhsTy = Context.getAsArrayType(RhsTy)->getElementType();
  6032. }
  6033. bool LhsRowMajor, RhsRowMajor;
  6034. LhsRowMajor = RhsRowMajor = Module.GetHLOptions().bDefaultRowMajor;
  6035. HasHLSLMatOrientation(LhsTy, &LhsRowMajor);
  6036. HasHLSLMatOrientation(RhsTy, &RhsRowMajor);
  6037. return LhsRowMajor == RhsRowMajor;
  6038. }
  6039. // Copy data from SrcPtr to DestPtr.
  6040. // For matrix, use MatLoad/MatStore.
  6041. // For matrix array, EmitHLSLAggregateCopy on each element.
  6042. // For struct or array, use memcpy.
  6043. // Other just load/store.
  6044. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(
  6045. CodeGenFunction &CGF, llvm::Value *SrcPtr, llvm::Value *DestPtr,
  6046. SmallVector<Value *, 4> &idxList, clang::QualType SrcType,
  6047. clang::QualType DestType, llvm::Type *Ty) {
  6048. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  6049. Constant *idx = Constant::getIntegerValue(
  6050. IntegerType::get(Ty->getContext(), 32), APInt(32, 0));
  6051. idxList.emplace_back(idx);
  6052. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, SrcType, DestType,
  6053. PT->getElementType());
  6054. idxList.pop_back();
  6055. } else if (HLMatrixType::isa(Ty)) {
  6056. // Use matLd/St for matrix.
  6057. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  6058. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  6059. Value *ldMat = EmitHLSLMatrixLoad(CGF, srcGEP, SrcType);
  6060. EmitHLSLMatrixStore(CGF, ldMat, dstGEP, DestType);
  6061. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  6062. if (dxilutil::IsHLSLObjectType(ST)) {
  6063. // Avoid split HLSL object.
  6064. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  6065. return;
  6066. }
  6067. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  6068. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  6069. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(ST);
  6070. // Memcpy struct.
  6071. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  6072. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  6073. if (!HLMatrixType::isMatrixArray(Ty)
  6074. || AreMatrixArrayOrientationMatching(CGF.getContext(), *m_pHLModule, SrcType, DestType)) {
  6075. Value *srcGEP = CGF.Builder.CreateInBoundsGEP(SrcPtr, idxList);
  6076. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  6077. unsigned size = this->TheModule.getDataLayout().getTypeAllocSize(AT);
  6078. // Memcpy non-matrix array.
  6079. CGF.Builder.CreateMemCpy(dstGEP, srcGEP, size, 1);
  6080. } else {
  6081. // Copy matrix arrays elementwise if orientation changes are needed.
  6082. llvm::Type *ET = AT->getElementType();
  6083. QualType EltDestType = CGF.getContext().getBaseElementType(DestType);
  6084. QualType EltSrcType = CGF.getContext().getBaseElementType(SrcType);
  6085. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  6086. Constant *idx = Constant::getIntegerValue(
  6087. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  6088. idxList.emplace_back(idx);
  6089. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, EltSrcType,
  6090. EltDestType, ET);
  6091. idxList.pop_back();
  6092. }
  6093. }
  6094. } else {
  6095. SimpleCopy(DestPtr, SrcPtr, idxList, CGF.Builder);
  6096. }
  6097. }
  6098. void CGMSHLSLRuntime::EmitHLSLAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  6099. llvm::Value *DestPtr,
  6100. clang::QualType Ty) {
  6101. SmallVector<Value *, 4> idxList;
  6102. EmitHLSLAggregateCopy(CGF, SrcPtr, DestPtr, idxList, Ty, Ty, SrcPtr->getType());
  6103. }
  6104. // To memcpy, need element type match.
  6105. // For struct type, the layout should match in cbuffer layout.
  6106. // struct { float2 x; float3 y; } will not match struct { float3 x; float2 y; }.
  6107. // struct { float2 x; float3 y; } will not match array of float.
  6108. static bool IsTypeMatchForMemcpy(llvm::Type *SrcTy, llvm::Type *DestTy) {
  6109. llvm::Type *SrcEltTy = dxilutil::GetArrayEltTy(SrcTy);
  6110. llvm::Type *DestEltTy = dxilutil::GetArrayEltTy(DestTy);
  6111. if (SrcEltTy == DestEltTy)
  6112. return true;
  6113. llvm::StructType *SrcST = dyn_cast<llvm::StructType>(SrcEltTy);
  6114. llvm::StructType *DestST = dyn_cast<llvm::StructType>(DestEltTy);
  6115. if (SrcST && DestST) {
  6116. // Only allow identical struct.
  6117. return SrcST->isLayoutIdentical(DestST);
  6118. } else if (!SrcST && !DestST) {
  6119. // For basic type, if one is array, one is not array, layout is different.
  6120. // If both array, type mismatch. If both basic, copy should be fine.
  6121. // So all return false.
  6122. return false;
  6123. } else {
  6124. // One struct, one basic type.
  6125. // Make sure all struct element match the basic type and basic type is
  6126. // vector4.
  6127. llvm::StructType *ST = SrcST ? SrcST : DestST;
  6128. llvm::Type *Ty = SrcST ? DestEltTy : SrcEltTy;
  6129. if (!Ty->isVectorTy())
  6130. return false;
  6131. if (Ty->getVectorNumElements() != 4)
  6132. return false;
  6133. for (llvm::Type *EltTy : ST->elements()) {
  6134. if (EltTy != Ty)
  6135. return false;
  6136. }
  6137. return true;
  6138. }
  6139. }
  6140. void CGMSHLSLRuntime::EmitHLSLFlatConversionAggregateCopy(CodeGenFunction &CGF, llvm::Value *SrcPtr,
  6141. clang::QualType SrcTy,
  6142. llvm::Value *DestPtr,
  6143. clang::QualType DestTy) {
  6144. llvm::Type *SrcPtrTy = SrcPtr->getType()->getPointerElementType();
  6145. llvm::Type *DestPtrTy = DestPtr->getType()->getPointerElementType();
  6146. bool bDefaultRowMajor = m_pHLModule->GetHLOptions().bDefaultRowMajor;
  6147. if (SrcPtrTy == DestPtrTy) {
  6148. bool bMatArrayRotate = false;
  6149. if (HLMatrixType::isMatrixArrayPtr(SrcPtr->getType())) {
  6150. QualType SrcEltTy = GetArrayEltType(CGM.getContext(), SrcTy);
  6151. QualType DestEltTy = GetArrayEltType(CGM.getContext(), DestTy);
  6152. if (GetMatrixMajor(SrcEltTy, bDefaultRowMajor) !=
  6153. GetMatrixMajor(DestEltTy, bDefaultRowMajor)) {
  6154. bMatArrayRotate = true;
  6155. }
  6156. }
  6157. if (!bMatArrayRotate) {
  6158. // Memcpy if type is match.
  6159. unsigned size = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  6160. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, size, 1);
  6161. return;
  6162. }
  6163. } else if (dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(SrcPtrTy)) &&
  6164. dxilutil::IsHLSLObjectType(dxilutil::GetArrayEltTy(DestPtrTy))) {
  6165. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  6166. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  6167. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::max(sizeSrc, sizeDest), 1);
  6168. return;
  6169. } else if (GlobalVariable *GV = dyn_cast<GlobalVariable>(DestPtr)) {
  6170. if (GV->isInternalLinkage(GV->getLinkage()) &&
  6171. IsTypeMatchForMemcpy(SrcPtrTy, DestPtrTy)) {
  6172. unsigned sizeSrc = TheModule.getDataLayout().getTypeAllocSize(SrcPtrTy);
  6173. unsigned sizeDest = TheModule.getDataLayout().getTypeAllocSize(DestPtrTy);
  6174. CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, std::min(sizeSrc, sizeDest), 1);
  6175. return;
  6176. }
  6177. }
  6178. // It is possible to implement EmitHLSLAggregateCopy, EmitHLSLAggregateStore
  6179. // the same way. But split value to scalar will generate many instruction when
  6180. // src type is same as dest type.
  6181. SmallVector<Value *, 4> GEPIdxStack;
  6182. SmallVector<Value *, 4> SrcPtrs;
  6183. SmallVector<QualType, 4> SrcQualTys;
  6184. FlattenAggregatePtrToGepList(CGF, SrcPtr, GEPIdxStack, SrcTy, SrcPtr->getType(),
  6185. SrcPtrs, SrcQualTys);
  6186. SmallVector<Value *, 4> SrcVals;
  6187. LoadElements(CGF, SrcPtrs, SrcQualTys, SrcVals);
  6188. GEPIdxStack.clear();
  6189. SmallVector<Value *, 4> DstPtrs;
  6190. SmallVector<QualType, 4> DstQualTys;
  6191. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, DestTy,
  6192. DestPtr->getType(), DstPtrs, DstQualTys);
  6193. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  6194. }
  6195. void CGMSHLSLRuntime::EmitHLSLAggregateStore(CodeGenFunction &CGF, llvm::Value *SrcVal,
  6196. llvm::Value *DestPtr,
  6197. clang::QualType Ty) {
  6198. DXASSERT(0, "aggregate return type will use SRet, no aggregate store should exist");
  6199. }
  6200. // Either copies a scalar to a scalar, a scalar to a vector, or splats a scalar to a vector
  6201. static void SimpleFlatValCopy(CodeGenFunction &CGF,
  6202. Value *SrcVal, QualType SrcQualTy, Value *DstPtr, QualType DstQualTy) {
  6203. DXASSERT(SrcVal->getType() == CGF.ConvertType(SrcQualTy), "QualType/Type mismatch!");
  6204. llvm::Type *DstTy = DstPtr->getType()->getPointerElementType();
  6205. DXASSERT(DstTy == CGF.ConvertTypeForMem(DstQualTy), "QualType/Type mismatch!");
  6206. llvm::VectorType *DstVecTy = dyn_cast<llvm::VectorType>(DstTy);
  6207. QualType DstScalarQualTy = DstQualTy;
  6208. if (DstVecTy) {
  6209. DstScalarQualTy = hlsl::GetHLSLVecElementType(DstQualTy);
  6210. }
  6211. Value *ResultScalar = ConvertScalarOrVector(CGF, SrcVal, SrcQualTy, DstScalarQualTy);
  6212. ResultScalar = CGF.EmitToMemory(ResultScalar, DstScalarQualTy);
  6213. if (DstVecTy) {
  6214. llvm::VectorType *DstScalarVecTy = llvm::VectorType::get(ResultScalar->getType(), 1);
  6215. Value *ResultScalarVec = CGF.Builder.CreateInsertElement(
  6216. UndefValue::get(DstScalarVecTy), ResultScalar, (uint64_t)0);
  6217. std::vector<int> ShufIdx(DstVecTy->getNumElements(), 0);
  6218. Value *ResultVec = CGF.Builder.CreateShuffleVector(ResultScalarVec, ResultScalarVec, ShufIdx);
  6219. CGF.Builder.CreateStore(ResultVec, DstPtr);
  6220. } else
  6221. CGF.Builder.CreateStore(ResultScalar, DstPtr);
  6222. }
  6223. void CGMSHLSLRuntime::EmitHLSLSplat(
  6224. CodeGenFunction &CGF, Value *SrcVal, llvm::Value *DestPtr,
  6225. SmallVector<Value *, 4> &idxList, QualType Type, QualType SrcType,
  6226. llvm::Type *Ty) {
  6227. if (llvm::PointerType *PT = dyn_cast<llvm::PointerType>(Ty)) {
  6228. idxList.emplace_back(CGF.Builder.getInt32(0));
  6229. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, Type,
  6230. SrcType, PT->getElementType());
  6231. idxList.pop_back();
  6232. } else if (HLMatrixType MatTy = HLMatrixType::dyn_cast(Ty)) {
  6233. // Use matLd/St for matrix.
  6234. Value *dstGEP = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  6235. llvm::Type *EltTy = MatTy.getElementTypeForReg();
  6236. llvm::VectorType *VT1 = llvm::VectorType::get(EltTy, 1);
  6237. SrcVal = ConvertScalarOrVector(CGF, SrcVal, SrcType, hlsl::GetHLSLMatElementType(Type));
  6238. // Splat the value
  6239. Value *V1 = CGF.Builder.CreateInsertElement(UndefValue::get(VT1), SrcVal,
  6240. (uint64_t)0);
  6241. std::vector<int> shufIdx(MatTy.getNumElements(), 0);
  6242. Value *VecMat = CGF.Builder.CreateShuffleVector(V1, V1, shufIdx);
  6243. Value *MatInit = EmitHLSLMatrixOperationCallImp(
  6244. CGF.Builder, HLOpcodeGroup::HLInit, 0, Ty, {VecMat}, TheModule);
  6245. EmitHLSLMatrixStore(CGF, MatInit, dstGEP, Type);
  6246. } else if (StructType *ST = dyn_cast<StructType>(Ty)) {
  6247. DXASSERT(!dxilutil::IsHLSLObjectType(ST), "cannot cast to hlsl object, Sema should reject");
  6248. const clang::RecordType *RT = Type->getAsStructureType();
  6249. RecordDecl *RD = RT->getDecl();
  6250. const CGRecordLayout &RL = CGF.getTypes().getCGRecordLayout(RD);
  6251. // Take care base.
  6252. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  6253. if (CXXRD->getNumBases()) {
  6254. for (const auto &I : CXXRD->bases()) {
  6255. const CXXRecordDecl *BaseDecl =
  6256. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  6257. if (BaseDecl->field_empty())
  6258. continue;
  6259. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  6260. unsigned i = RL.getNonVirtualBaseLLVMFieldNo(BaseDecl);
  6261. llvm::Type *ET = ST->getElementType(i);
  6262. Constant *idx = llvm::Constant::getIntegerValue(
  6263. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  6264. idxList.emplace_back(idx);
  6265. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, parentTy, SrcType, ET);
  6266. idxList.pop_back();
  6267. }
  6268. }
  6269. }
  6270. for (auto fieldIter = RD->field_begin(), fieldEnd = RD->field_end();
  6271. fieldIter != fieldEnd; ++fieldIter) {
  6272. unsigned i = RL.getLLVMFieldNo(*fieldIter);
  6273. llvm::Type *ET = ST->getElementType(i);
  6274. Constant *idx = llvm::Constant::getIntegerValue(
  6275. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  6276. idxList.emplace_back(idx);
  6277. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, fieldIter->getType(), SrcType, ET);
  6278. idxList.pop_back();
  6279. }
  6280. } else if (llvm::ArrayType *AT = dyn_cast<llvm::ArrayType>(Ty)) {
  6281. llvm::Type *ET = AT->getElementType();
  6282. QualType EltType = CGF.getContext().getBaseElementType(Type);
  6283. for (uint32_t i = 0; i < AT->getNumElements(); i++) {
  6284. Constant *idx = Constant::getIntegerValue(
  6285. IntegerType::get(Ty->getContext(), 32), APInt(32, i));
  6286. idxList.emplace_back(idx);
  6287. EmitHLSLSplat(CGF, SrcVal, DestPtr, idxList, EltType, SrcType, ET);
  6288. idxList.pop_back();
  6289. }
  6290. } else {
  6291. DestPtr = CGF.Builder.CreateInBoundsGEP(DestPtr, idxList);
  6292. SimpleFlatValCopy(CGF, SrcVal, SrcType, DestPtr, Type);
  6293. }
  6294. }
  6295. void CGMSHLSLRuntime::EmitHLSLFlatConversion(CodeGenFunction &CGF,
  6296. Value *Val,
  6297. Value *DestPtr,
  6298. QualType Ty,
  6299. QualType SrcTy) {
  6300. SmallVector<Value *, 4> SrcVals;
  6301. SmallVector<QualType, 4> SrcQualTys;
  6302. FlattenValToInitList(CGF, SrcVals, SrcQualTys, SrcTy, Val);
  6303. if (SrcVals.size() == 1) {
  6304. // Perform a splat
  6305. SmallVector<Value *, 4> GEPIdxStack;
  6306. GEPIdxStack.emplace_back(CGF.Builder.getInt32(0)); // Add first 0 for DestPtr.
  6307. EmitHLSLSplat(
  6308. CGF, SrcVals[0], DestPtr, GEPIdxStack, Ty, SrcQualTys[0],
  6309. DestPtr->getType()->getPointerElementType());
  6310. }
  6311. else {
  6312. SmallVector<Value *, 4> GEPIdxStack;
  6313. SmallVector<Value *, 4> DstPtrs;
  6314. SmallVector<QualType, 4> DstQualTys;
  6315. FlattenAggregatePtrToGepList(CGF, DestPtr, GEPIdxStack, Ty, DestPtr->getType(), DstPtrs, DstQualTys);
  6316. ConvertAndStoreElements(CGF, SrcVals, SrcQualTys, DstPtrs, DstQualTys);
  6317. }
  6318. }
  6319. void CGMSHLSLRuntime::EmitHLSLRootSignature(CodeGenFunction &CGF,
  6320. HLSLRootSignatureAttr *RSA,
  6321. Function *Fn) {
  6322. // Only parse root signature for entry function.
  6323. if (Fn != Entry.Func)
  6324. return;
  6325. StringRef StrRef = RSA->getSignatureName();
  6326. DiagnosticsEngine &Diags = CGF.getContext().getDiagnostics();
  6327. SourceLocation SLoc = RSA->getLocation();
  6328. RootSignatureHandle RootSigHandle;
  6329. clang::CompileRootSignature(StrRef, Diags, SLoc, rootSigVer, DxilRootSignatureCompilationFlags::GlobalRootSignature, &RootSigHandle);
  6330. if (!RootSigHandle.IsEmpty()) {
  6331. RootSigHandle.EnsureSerializedAvailable();
  6332. m_pHLModule->SetSerializedRootSignature(RootSigHandle.GetSerializedBytes(),
  6333. RootSigHandle.GetSerializedSize());
  6334. }
  6335. }
  6336. void CGMSHLSLRuntime::EmitHLSLOutParamConversionInit(
  6337. CodeGenFunction &CGF, const FunctionDecl *FD, const CallExpr *E,
  6338. llvm::SmallVector<LValue, 8> &castArgList,
  6339. llvm::SmallVector<const Stmt *, 8> &argList,
  6340. const std::function<void(const VarDecl *, llvm::Value *)> &TmpArgMap) {
  6341. // Special case: skip first argument of CXXOperatorCall (it is "this").
  6342. unsigned ArgsToSkip = isa<CXXOperatorCallExpr>(E) ? 1 : 0;
  6343. for (uint32_t i = 0; i < FD->getNumParams(); i++) {
  6344. const ParmVarDecl *Param = FD->getParamDecl(i);
  6345. const Expr *Arg = E->getArg(i+ArgsToSkip);
  6346. QualType ParamTy = Param->getType().getNonReferenceType();
  6347. bool isObject = dxilutil::IsHLSLObjectType(CGF.ConvertTypeForMem(ParamTy));
  6348. bool isAggregateType = !isObject &&
  6349. (ParamTy->isArrayType() || ParamTy->isRecordType()) &&
  6350. !hlsl::IsHLSLVecMatType(ParamTy);
  6351. bool EmitRValueAgg = false;
  6352. bool RValOnRef = false;
  6353. if (!Param->isModifierOut()) {
  6354. if (!isAggregateType && !isObject) {
  6355. if (Arg->isRValue() && Param->getType()->isReferenceType()) {
  6356. // RValue on a reference type.
  6357. if (const CStyleCastExpr *cCast = dyn_cast<CStyleCastExpr>(Arg)) {
  6358. // TODO: Evolving this to warn then fail in future language versions.
  6359. // Allow special case like cast uint to uint for back-compat.
  6360. if (cCast->getCastKind() == CastKind::CK_NoOp) {
  6361. if (const ImplicitCastExpr *cast =
  6362. dyn_cast<ImplicitCastExpr>(cCast->getSubExpr())) {
  6363. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  6364. // update the arg
  6365. argList[i] = cast->getSubExpr();
  6366. continue;
  6367. }
  6368. }
  6369. }
  6370. }
  6371. // EmitLValue will report error.
  6372. // Mark RValOnRef to create tmpArg for it.
  6373. RValOnRef = true;
  6374. } else {
  6375. continue;
  6376. }
  6377. } else if (isAggregateType) {
  6378. // aggregate in-only - emit RValue, unless LValueToRValue cast
  6379. EmitRValueAgg = true;
  6380. if (const ImplicitCastExpr *cast =
  6381. dyn_cast<ImplicitCastExpr>(Arg)) {
  6382. if (cast->getCastKind() == CastKind::CK_LValueToRValue) {
  6383. EmitRValueAgg = false;
  6384. }
  6385. }
  6386. } else {
  6387. // Must be object
  6388. DXASSERT(isObject, "otherwise, flow condition changed, breaking assumption");
  6389. // in-only objects should be skipped to preserve previous behavior.
  6390. continue;
  6391. }
  6392. }
  6393. // Skip unbounded array, since we cannot preserve copy-in copy-out
  6394. // semantics for these.
  6395. if (ParamTy->isIncompleteArrayType()) {
  6396. continue;
  6397. }
  6398. if (!Param->isModifierOut() && !RValOnRef) {
  6399. // No need to copy arg to in-only param for hlsl intrinsic.
  6400. if (const FunctionDecl *Callee = E->getDirectCallee()) {
  6401. if (Callee->hasAttr<HLSLIntrinsicAttr>())
  6402. continue;
  6403. }
  6404. }
  6405. // get original arg
  6406. // FIXME: This will not emit in correct argument order with the other
  6407. // arguments. This should be integrated into
  6408. // CodeGenFunction::EmitCallArg if possible.
  6409. RValue argRV; // emit this if aggregate arg on in-only param
  6410. LValue argLV; // otherwise, we may emit this
  6411. llvm::Value *argAddr = nullptr;
  6412. QualType argType = Arg->getType();
  6413. CharUnits argAlignment;
  6414. if (EmitRValueAgg) {
  6415. argRV = CGF.EmitAnyExprToTemp(Arg);
  6416. argAddr = argRV.getAggregateAddr(); // must be alloca
  6417. argAlignment = CharUnits::fromQuantity(cast<AllocaInst>(argAddr)->getAlignment());
  6418. argLV = LValue::MakeAddr(argAddr, ParamTy, argAlignment, CGF.getContext());
  6419. } else {
  6420. argLV = CGF.EmitLValue(Arg);
  6421. if (argLV.isSimple())
  6422. argAddr = argLV.getAddress();
  6423. argType = argLV.getType(); // TBD: Can this be different than Arg->getType()?
  6424. argAlignment = argLV.getAlignment();
  6425. }
  6426. // After emit Arg, we must update the argList[i],
  6427. // otherwise we get double emit of the expression.
  6428. // create temp Var
  6429. VarDecl *tmpArg =
  6430. VarDecl::Create(CGF.getContext(), const_cast<FunctionDecl *>(FD),
  6431. SourceLocation(), SourceLocation(),
  6432. /*IdentifierInfo*/ nullptr, ParamTy,
  6433. CGF.getContext().getTrivialTypeSourceInfo(ParamTy),
  6434. StorageClass::SC_Auto);
  6435. // Aggregate type will be indirect param convert to pointer type.
  6436. // So don't update to ReferenceType, use RValue for it.
  6437. const DeclRefExpr *tmpRef = DeclRefExpr::Create(
  6438. CGF.getContext(), NestedNameSpecifierLoc(), SourceLocation(), tmpArg,
  6439. /*enclosing*/ false, tmpArg->getLocation(), ParamTy,
  6440. (isAggregateType || isObject) ? VK_RValue : VK_LValue);
  6441. // must update the arg, since we did emit Arg, else we get double emit.
  6442. argList[i] = tmpRef;
  6443. // create alloc for the tmp arg
  6444. Value *tmpArgAddr = nullptr;
  6445. BasicBlock *InsertBlock = CGF.Builder.GetInsertBlock();
  6446. Function *F = InsertBlock->getParent();
  6447. // Make sure the alloca is in entry block to stop inline create stacksave.
  6448. IRBuilder<> AllocaBuilder(dxilutil::FindAllocaInsertionPt(F));
  6449. tmpArgAddr = AllocaBuilder.CreateAlloca(CGF.ConvertTypeForMem(ParamTy));
  6450. // add it to local decl map
  6451. TmpArgMap(tmpArg, tmpArgAddr);
  6452. LValue tmpLV = LValue::MakeAddr(tmpArgAddr, ParamTy, argAlignment,
  6453. CGF.getContext());
  6454. // save for cast after call
  6455. if (Param->isModifierOut()) {
  6456. castArgList.emplace_back(tmpLV);
  6457. castArgList.emplace_back(argLV);
  6458. }
  6459. // cast before the call
  6460. if (Param->isModifierIn() &&
  6461. // Don't copy object
  6462. !isObject) {
  6463. QualType ArgTy = Arg->getType();
  6464. Value *outVal = nullptr;
  6465. if (!isAggregateType) {
  6466. if (!IsHLSLMatType(ParamTy)) {
  6467. RValue outRVal = CGF.EmitLoadOfLValue(argLV, SourceLocation());
  6468. outVal = outRVal.getScalarVal();
  6469. } else {
  6470. DXASSERT(argAddr, "should be RV or simple LV");
  6471. outVal = EmitHLSLMatrixLoad(CGF, argAddr, ArgTy);
  6472. }
  6473. llvm::Type *ToTy = tmpArgAddr->getType()->getPointerElementType();
  6474. if (HLMatrixType::isa(ToTy)) {
  6475. Value *castVal = CGF.Builder.CreateBitCast(outVal, ToTy);
  6476. EmitHLSLMatrixStore(CGF, castVal, tmpArgAddr, ParamTy);
  6477. }
  6478. else {
  6479. Value *castVal = ConvertScalarOrVector(CGF, outVal, argType, ParamTy);
  6480. castVal = CGF.EmitToMemory(castVal, ParamTy);
  6481. CGF.Builder.CreateStore(castVal, tmpArgAddr);
  6482. }
  6483. } else {
  6484. DXASSERT(argAddr, "should be RV or simple LV");
  6485. SmallVector<Value *, 4> idxList;
  6486. EmitHLSLAggregateCopy(CGF, argAddr, tmpArgAddr,
  6487. idxList, ArgTy, ParamTy,
  6488. argAddr->getType());
  6489. }
  6490. }
  6491. }
  6492. }
  6493. void CGMSHLSLRuntime::EmitHLSLOutParamConversionCopyBack(
  6494. CodeGenFunction &CGF, llvm::SmallVector<LValue, 8> &castArgList) {
  6495. for (uint32_t i = 0; i < castArgList.size(); i += 2) {
  6496. // cast after the call
  6497. LValue tmpLV = castArgList[i];
  6498. LValue argLV = castArgList[i + 1];
  6499. QualType ArgTy = argLV.getType().getNonReferenceType();
  6500. QualType ParamTy = tmpLV.getType().getNonReferenceType();
  6501. Value *tmpArgAddr = tmpLV.getAddress();
  6502. Value *outVal = nullptr;
  6503. bool isAggregateTy = hlsl::IsHLSLAggregateType(ArgTy);
  6504. bool isObject = dxilutil::IsHLSLObjectType(
  6505. tmpArgAddr->getType()->getPointerElementType());
  6506. if (!isObject) {
  6507. if (!isAggregateTy) {
  6508. if (!IsHLSLMatType(ParamTy))
  6509. outVal = CGF.Builder.CreateLoad(tmpArgAddr);
  6510. else
  6511. outVal = EmitHLSLMatrixLoad(CGF, tmpArgAddr, ParamTy);
  6512. outVal = CGF.EmitFromMemory(outVal, ParamTy);
  6513. llvm::Type *ToTy = CGF.ConvertType(ArgTy);
  6514. llvm::Type *FromTy = outVal->getType();
  6515. Value *castVal = outVal;
  6516. if (ToTy == FromTy) {
  6517. // Don't need cast.
  6518. } else if (ToTy->getScalarType() == FromTy->getScalarType()) {
  6519. if (ToTy->getScalarType() == ToTy) {
  6520. DXASSERT(FromTy->isVectorTy() &&
  6521. FromTy->getVectorNumElements() == 1,
  6522. "must be vector of 1 element");
  6523. castVal = CGF.Builder.CreateExtractElement(outVal, (uint64_t)0);
  6524. } else {
  6525. DXASSERT(!FromTy->isVectorTy(), "must be scalar type");
  6526. DXASSERT(ToTy->isVectorTy() && ToTy->getVectorNumElements() == 1,
  6527. "must be vector of 1 element");
  6528. castVal = UndefValue::get(ToTy);
  6529. castVal =
  6530. CGF.Builder.CreateInsertElement(castVal, outVal, (uint64_t)0);
  6531. }
  6532. } else {
  6533. castVal = ConvertScalarOrVector(CGF,
  6534. outVal, tmpLV.getType(), argLV.getType());
  6535. }
  6536. if (!HLMatrixType::isa(ToTy))
  6537. CGF.EmitStoreThroughLValue(RValue::get(castVal), argLV);
  6538. else {
  6539. Value *destPtr = argLV.getAddress();
  6540. EmitHLSLMatrixStore(CGF, castVal, destPtr, ArgTy);
  6541. }
  6542. } else {
  6543. SmallVector<Value *, 4> idxList;
  6544. EmitHLSLAggregateCopy(CGF, tmpLV.getAddress(), argLV.getAddress(),
  6545. idxList, ParamTy, ArgTy,
  6546. argLV.getAddress()->getType());
  6547. }
  6548. } else
  6549. tmpArgAddr->replaceAllUsesWith(argLV.getAddress());
  6550. }
  6551. }
  6552. CGHLSLRuntime *CodeGen::CreateMSHLSLRuntime(CodeGenModule &CGM) {
  6553. return new CGMSHLSLRuntime(CGM);
  6554. }