CGHLSLMS.cpp 267 KB

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