CGHLSLMS.cpp 281 KB

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