CGHLSLMS.cpp 229 KB

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