SemaHLSL.cpp 467 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466
  1. //===--- SemaHLSL.cpp - HLSL support for AST nodes and operations ---===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // SemaHLSL.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 file implements the semantic support for HLSL. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "llvm/ADT/SmallPtrSet.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExternalASTSource.h"
  21. #include "clang/AST/RecursiveASTVisitor.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "clang/AST/HlslTypes.h"
  24. #include "clang/Sema/Overload.h"
  25. #include "clang/Sema/SemaDiagnostic.h"
  26. #include "clang/Sema/Initialization.h"
  27. #include "clang/Sema/ExternalSemaSource.h"
  28. #include "clang/Sema/Lookup.h"
  29. #include "clang/Sema/Template.h"
  30. #include "clang/Sema/TemplateDeduction.h"
  31. #include "clang/Sema/SemaHLSL.h"
  32. #include "dxc/Support/Global.h"
  33. #include "dxc/Support/WinIncludes.h"
  34. #include "dxc/Support/WinAdapter.h"
  35. #include "dxc/dxcapi.internal.h"
  36. #include "dxc/HlslIntrinsicOp.h"
  37. #include "gen_intrin_main_tables_15.h"
  38. #include "VkConstantsTables.h"
  39. #include "dxc/HLSL/HLOperations.h"
  40. #include "dxc/DXIL/DxilShaderModel.h"
  41. #include <array>
  42. #include <algorithm>
  43. #include <float.h>
  44. enum ArBasicKind {
  45. AR_BASIC_BOOL,
  46. AR_BASIC_LITERAL_FLOAT,
  47. AR_BASIC_FLOAT16,
  48. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  49. AR_BASIC_FLOAT32,
  50. AR_BASIC_FLOAT64,
  51. AR_BASIC_LITERAL_INT,
  52. AR_BASIC_INT8,
  53. AR_BASIC_UINT8,
  54. AR_BASIC_INT16,
  55. AR_BASIC_UINT16,
  56. AR_BASIC_INT32,
  57. AR_BASIC_UINT32,
  58. AR_BASIC_INT64,
  59. AR_BASIC_UINT64,
  60. AR_BASIC_MIN10FLOAT,
  61. AR_BASIC_MIN16FLOAT,
  62. AR_BASIC_MIN12INT,
  63. AR_BASIC_MIN16INT,
  64. AR_BASIC_MIN16UINT,
  65. AR_BASIC_INT8_4PACKED,
  66. AR_BASIC_UINT8_4PACKED,
  67. AR_BASIC_ENUM,
  68. AR_BASIC_COUNT,
  69. //
  70. // Pseudo-entries for intrinsic tables and such.
  71. //
  72. AR_BASIC_NONE,
  73. AR_BASIC_UNKNOWN,
  74. AR_BASIC_NOCAST,
  75. //
  76. // The following pseudo-entries represent higher-level
  77. // object types that are treated as units.
  78. //
  79. AR_BASIC_POINTER,
  80. AR_BASIC_ENUM_CLASS,
  81. AR_OBJECT_NULL,
  82. AR_OBJECT_STRING_LITERAL,
  83. AR_OBJECT_STRING,
  84. // AR_OBJECT_TEXTURE,
  85. AR_OBJECT_TEXTURE1D,
  86. AR_OBJECT_TEXTURE1D_ARRAY,
  87. AR_OBJECT_TEXTURE2D,
  88. AR_OBJECT_TEXTURE2D_ARRAY,
  89. AR_OBJECT_TEXTURE3D,
  90. AR_OBJECT_TEXTURECUBE,
  91. AR_OBJECT_TEXTURECUBE_ARRAY,
  92. AR_OBJECT_TEXTURE2DMS,
  93. AR_OBJECT_TEXTURE2DMS_ARRAY,
  94. AR_OBJECT_SAMPLER,
  95. AR_OBJECT_SAMPLER1D,
  96. AR_OBJECT_SAMPLER2D,
  97. AR_OBJECT_SAMPLER3D,
  98. AR_OBJECT_SAMPLERCUBE,
  99. AR_OBJECT_SAMPLERCOMPARISON,
  100. AR_OBJECT_BUFFER,
  101. //
  102. // View objects are only used as variable/types within the Effects
  103. // framework, for example in calls to OMSetRenderTargets.
  104. //
  105. AR_OBJECT_RENDERTARGETVIEW,
  106. AR_OBJECT_DEPTHSTENCILVIEW,
  107. //
  108. // Shader objects are only used as variable/types within the Effects
  109. // framework, for example as a result of CompileShader().
  110. //
  111. AR_OBJECT_COMPUTESHADER,
  112. AR_OBJECT_DOMAINSHADER,
  113. AR_OBJECT_GEOMETRYSHADER,
  114. AR_OBJECT_HULLSHADER,
  115. AR_OBJECT_PIXELSHADER,
  116. AR_OBJECT_VERTEXSHADER,
  117. AR_OBJECT_PIXELFRAGMENT,
  118. AR_OBJECT_VERTEXFRAGMENT,
  119. AR_OBJECT_STATEBLOCK,
  120. AR_OBJECT_RASTERIZER,
  121. AR_OBJECT_DEPTHSTENCIL,
  122. AR_OBJECT_BLEND,
  123. AR_OBJECT_POINTSTREAM,
  124. AR_OBJECT_LINESTREAM,
  125. AR_OBJECT_TRIANGLESTREAM,
  126. AR_OBJECT_INPUTPATCH,
  127. AR_OBJECT_OUTPUTPATCH,
  128. AR_OBJECT_RWTEXTURE1D,
  129. AR_OBJECT_RWTEXTURE1D_ARRAY,
  130. AR_OBJECT_RWTEXTURE2D,
  131. AR_OBJECT_RWTEXTURE2D_ARRAY,
  132. AR_OBJECT_RWTEXTURE3D,
  133. AR_OBJECT_RWBUFFER,
  134. AR_OBJECT_BYTEADDRESS_BUFFER,
  135. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  136. AR_OBJECT_STRUCTURED_BUFFER,
  137. AR_OBJECT_RWSTRUCTURED_BUFFER,
  138. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  139. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  140. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  141. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  142. AR_OBJECT_CONSTANT_BUFFER,
  143. AR_OBJECT_TEXTURE_BUFFER,
  144. AR_OBJECT_ROVBUFFER,
  145. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  146. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  147. AR_OBJECT_ROVTEXTURE1D,
  148. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  149. AR_OBJECT_ROVTEXTURE2D,
  150. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  151. AR_OBJECT_ROVTEXTURE3D,
  152. AR_OBJECT_FEEDBACKTEXTURE2D,
  153. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  154. // SPIRV change starts
  155. #ifdef ENABLE_SPIRV_CODEGEN
  156. AR_OBJECT_VK_SUBPASS_INPUT,
  157. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  158. #endif // ENABLE_SPIRV_CODEGEN
  159. // SPIRV change ends
  160. AR_OBJECT_INNER, // Used for internal type object
  161. AR_OBJECT_LEGACY_EFFECT,
  162. AR_OBJECT_WAVE,
  163. AR_OBJECT_RAY_DESC,
  164. AR_OBJECT_ACCELERATION_STRUCT,
  165. AR_OBJECT_USER_DEFINED_TYPE,
  166. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  167. // subobjects
  168. AR_OBJECT_STATE_OBJECT_CONFIG,
  169. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  170. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  171. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  172. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  173. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  174. AR_OBJECT_TRIANGLE_HIT_GROUP,
  175. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  176. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  177. // RayQuery
  178. AR_OBJECT_RAY_QUERY,
  179. // Heap Resource
  180. AR_OBJECT_HEAP_RESOURCE,
  181. AR_OBJECT_HEAP_SAMPLER,
  182. AR_BASIC_MAXIMUM_COUNT
  183. };
  184. #define AR_BASIC_TEXTURE_MS_CASES \
  185. case AR_OBJECT_TEXTURE2DMS: \
  186. case AR_OBJECT_TEXTURE2DMS_ARRAY
  187. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  188. case AR_OBJECT_TEXTURE1D: \
  189. case AR_OBJECT_TEXTURE1D_ARRAY: \
  190. case AR_OBJECT_TEXTURE2D: \
  191. case AR_OBJECT_TEXTURE2D_ARRAY: \
  192. case AR_OBJECT_TEXTURE3D: \
  193. case AR_OBJECT_TEXTURECUBE: \
  194. case AR_OBJECT_TEXTURECUBE_ARRAY
  195. #define AR_BASIC_TEXTURE_CASES \
  196. AR_BASIC_TEXTURE_MS_CASES: \
  197. AR_BASIC_NON_TEXTURE_MS_CASES
  198. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  199. case AR_OBJECT_SAMPLER: \
  200. case AR_OBJECT_SAMPLER1D: \
  201. case AR_OBJECT_SAMPLER2D: \
  202. case AR_OBJECT_SAMPLER3D: \
  203. case AR_OBJECT_SAMPLERCUBE
  204. #define AR_BASIC_ROBJECT_CASES \
  205. case AR_OBJECT_BLEND: \
  206. case AR_OBJECT_RASTERIZER: \
  207. case AR_OBJECT_DEPTHSTENCIL: \
  208. case AR_OBJECT_STATEBLOCK
  209. //
  210. // Properties of entries in the ArBasicKind enumeration.
  211. // These properties are intended to allow easy identification
  212. // of classes of basic kinds. More specific checks on the
  213. // actual kind values could then be done.
  214. //
  215. // The first four bits are used as a subtype indicator,
  216. // such as bit count for primitive kinds or specific
  217. // types for non-primitive-data kinds.
  218. #define BPROP_SUBTYPE_MASK 0x0000000f
  219. // Bit counts must be ordered from smaller to larger.
  220. #define BPROP_BITS0 0x00000000
  221. #define BPROP_BITS8 0x00000001
  222. #define BPROP_BITS10 0x00000002
  223. #define BPROP_BITS12 0x00000003
  224. #define BPROP_BITS16 0x00000004
  225. #define BPROP_BITS32 0x00000005
  226. #define BPROP_BITS64 0x00000006
  227. #define BPROP_BITS_NON_PRIM 0x00000007
  228. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  229. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  230. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  231. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  232. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  233. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  234. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  235. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  236. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  237. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  238. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  239. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  240. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  241. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  242. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  243. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  244. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  245. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  246. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  247. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  248. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  249. #define BPROP_FEEDBACKTEXTURE 0x00800000 // Whether the type is a feedback texture.
  250. #define BPROP_ENUM 0x01000000 // Whether the type is a enum
  251. #define GET_BPROP_PRIM_KIND(_Props) \
  252. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  253. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  254. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  255. #define IS_BPROP_PRIMITIVE(_Props) \
  256. (((_Props) & BPROP_PRIMITIVE) != 0)
  257. #define IS_BPROP_BOOL(_Props) \
  258. (((_Props) & BPROP_BOOLEAN) != 0)
  259. #define IS_BPROP_FLOAT(_Props) \
  260. (((_Props) & BPROP_FLOATING) != 0)
  261. #define IS_BPROP_SINT(_Props) \
  262. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  263. BPROP_INTEGER)
  264. #define IS_BPROP_UINT(_Props) \
  265. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  266. (BPROP_INTEGER | BPROP_UNSIGNED))
  267. #define IS_BPROP_AINT(_Props) \
  268. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  269. #define IS_BPROP_STREAM(_Props) \
  270. (((_Props) & BPROP_STREAM) != 0)
  271. #define IS_BPROP_SAMPLER(_Props) \
  272. (((_Props) & BPROP_SAMPLER) != 0)
  273. #define IS_BPROP_TEXTURE(_Props) \
  274. (((_Props) & BPROP_TEXTURE) != 0)
  275. #define IS_BPROP_OBJECT(_Props) \
  276. (((_Props) & BPROP_OBJECT) != 0)
  277. #define IS_BPROP_MIN_PRECISION(_Props) \
  278. (((_Props) & BPROP_MIN_PRECISION) != 0)
  279. #define IS_BPROP_UNSIGNABLE(_Props) \
  280. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  281. #define IS_BPROP_ENUM(_Props) \
  282. (((_Props) & BPROP_ENUM) != 0)
  283. const UINT g_uBasicKindProps[] =
  284. {
  285. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  286. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  287. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  288. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  289. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  290. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  291. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  292. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  293. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  294. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  295. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  296. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  297. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  298. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  299. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  300. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  301. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  302. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  303. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  304. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  305. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_INT8_4PACKED
  306. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT8_4PACKED
  307. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  308. BPROP_OTHER, // AR_BASIC_COUNT
  309. //
  310. // Pseudo-entries for intrinsic tables and such.
  311. //
  312. 0, // AR_BASIC_NONE
  313. BPROP_OTHER, // AR_BASIC_UNKNOWN
  314. BPROP_OTHER, // AR_BASIC_NOCAST
  315. //
  316. // The following pseudo-entries represent higher-level
  317. // object types that are treated as units.
  318. //
  319. BPROP_POINTER, // AR_BASIC_POINTER
  320. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  321. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  322. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING_LITERAL
  323. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  324. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  325. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  326. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  327. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  328. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  329. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  330. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  331. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  332. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  333. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  334. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  335. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  336. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  337. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  338. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  339. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  340. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  341. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  342. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  343. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  344. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  345. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  346. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  347. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  348. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  349. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  350. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  351. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  352. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  353. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  354. BPROP_OBJECT, // AR_OBJECT_BLEND
  355. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  356. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  357. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  358. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  359. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  360. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  361. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  362. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  363. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  364. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  365. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  366. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  367. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  368. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  369. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  370. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  371. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  372. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  373. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  374. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  375. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  376. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  377. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  378. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  379. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  380. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  381. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  382. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  383. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  384. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D
  385. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  386. // SPIRV change starts
  387. #ifdef ENABLE_SPIRV_CODEGEN
  388. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  389. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  390. #endif // ENABLE_SPIRV_CODEGEN
  391. // SPIRV change ends
  392. BPROP_OBJECT, // AR_OBJECT_INNER
  393. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  394. BPROP_OBJECT, // AR_OBJECT_WAVE
  395. LICOMPTYPE_RAYDESC, // AR_OBJECT_RAY_DESC
  396. LICOMPTYPE_ACCELERATION_STRUCT, // AR_OBJECT_ACCELERATION_STRUCT
  397. LICOMPTYPE_USER_DEFINED_TYPE, // AR_OBJECT_USER_DEFINED_TYPE
  398. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  399. // subobjects
  400. 0, //AR_OBJECT_STATE_OBJECT_CONFIG,
  401. 0, //AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  402. 0, //AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  403. 0, //AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  404. 0, //AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  405. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  406. 0, //AR_OBJECT_TRIANGLE_HIT_GROUP,
  407. 0, //AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  408. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  409. 0, //AR_OBJECT_RAY_QUERY,
  410. 0, //AR_OBJECT_HEAP_RESOURCE,
  411. 0, //AR_OBJECT_HEAP_SAMPLER,
  412. // AR_BASIC_MAXIMUM_COUNT
  413. };
  414. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  415. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  416. #define GET_BASIC_BITS(_Kind) \
  417. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  418. #define GET_BASIC_PRIM_KIND(_Kind) \
  419. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  420. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  421. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  422. #define IS_BASIC_PRIMITIVE(_Kind) \
  423. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  424. #define IS_BASIC_BOOL(_Kind) \
  425. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  426. #define IS_BASIC_FLOAT(_Kind) \
  427. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  428. #define IS_BASIC_SINT(_Kind) \
  429. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  430. #define IS_BASIC_UINT(_Kind) \
  431. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  432. #define IS_BASIC_AINT(_Kind) \
  433. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  434. #define IS_BASIC_STREAM(_Kind) \
  435. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  436. #define IS_BASIC_SAMPLER(_Kind) \
  437. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  438. #define IS_BASIC_TEXTURE(_Kind) \
  439. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  440. #define IS_BASIC_OBJECT(_Kind) \
  441. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  442. #define IS_BASIC_MIN_PRECISION(_Kind) \
  443. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  444. #define IS_BASIC_UNSIGNABLE(_Kind) \
  445. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  446. #define IS_BASIC_ENUM(_Kind) \
  447. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  448. #define BITWISE_ENUM_OPS(_Type) \
  449. inline _Type operator|(_Type F1, _Type F2) \
  450. { \
  451. return (_Type)((UINT)F1 | (UINT)F2); \
  452. } \
  453. inline _Type operator&(_Type F1, _Type F2) \
  454. { \
  455. return (_Type)((UINT)F1 & (UINT)F2); \
  456. } \
  457. inline _Type& operator|=(_Type& F1, _Type F2) \
  458. { \
  459. F1 = F1 | F2; \
  460. return F1; \
  461. } \
  462. inline _Type& operator&=(_Type& F1, _Type F2) \
  463. { \
  464. F1 = F1 & F2; \
  465. return F1; \
  466. } \
  467. inline _Type& operator&=(_Type& F1, UINT F2) \
  468. { \
  469. F1 = (_Type)((UINT)F1 & F2); \
  470. return F1; \
  471. }
  472. enum ArTypeObjectKind {
  473. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  474. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  475. AR_TOBJ_BASIC, // Represents a primitive type.
  476. AR_TOBJ_COMPOUND, // Represents a struct or class.
  477. AR_TOBJ_INTERFACE, // Represents an interface.
  478. AR_TOBJ_POINTER, // Represents a pointer to another type.
  479. AR_TOBJ_OBJECT, // Represents a built-in object.
  480. AR_TOBJ_ARRAY, // Represents an array of other types.
  481. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  482. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  483. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  484. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  485. // indexer object used to implement .mips[1].
  486. AR_TOBJ_STRING, // Represents a string
  487. };
  488. enum TYPE_CONVERSION_FLAGS
  489. {
  490. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  491. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  492. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  493. };
  494. enum TYPE_CONVERSION_REMARKS
  495. {
  496. TYPE_CONVERSION_NONE = 0x00000000,
  497. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  498. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  499. TYPE_CONVERSION_TO_VOID = 0x00000004,
  500. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  501. };
  502. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  503. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  504. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  505. #define AR_TPROP_VOID 0x0000000000000001
  506. #define AR_TPROP_CONST 0x0000000000000002
  507. #define AR_TPROP_IMP_CONST 0x0000000000000004
  508. #define AR_TPROP_OBJECT 0x0000000000000008
  509. #define AR_TPROP_SCALAR 0x0000000000000010
  510. #define AR_TPROP_UNSIGNED 0x0000000000000020
  511. #define AR_TPROP_NUMERIC 0x0000000000000040
  512. #define AR_TPROP_INTEGRAL 0x0000000000000080
  513. #define AR_TPROP_FLOATING 0x0000000000000100
  514. #define AR_TPROP_LITERAL 0x0000000000000200
  515. #define AR_TPROP_POINTER 0x0000000000000400
  516. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  517. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  518. #define AR_TPROP_INH_IFACE 0x0000000000002000
  519. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  520. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  521. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  522. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  523. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  524. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  525. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  526. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  527. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  528. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  529. #define AR_TPROP_INDEXABLE 0x0000000001000000
  530. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  531. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  532. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  533. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  534. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  535. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  536. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  537. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  538. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  539. #define AR_TPROP_ALL 0xffffffffffffffff
  540. #define AR_TPROP_HAS_OBJECTS \
  541. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  542. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  543. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  544. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  545. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  546. #define AR_TPROP_HAS_BASIC_RESOURCES \
  547. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  548. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  549. AR_TPROP_HAS_UAVS)
  550. #define AR_TPROP_UNION_BITS \
  551. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  552. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  553. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  554. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  555. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  556. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  557. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  558. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  559. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  560. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  561. #define AR_TINFO_PACK_SCALAR 0x00000010
  562. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  563. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  564. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  565. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  566. #define AR_TINFO_PACK_CBUFFER 0
  567. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  568. #define AR_TINFO_SIMPLE_OBJECTS \
  569. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  570. struct ArTypeInfo {
  571. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  572. ArBasicKind EltKind; // The primitive type of elements in this type.
  573. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  574. UINT uRows;
  575. UINT uCols;
  576. UINT uTotalElts;
  577. };
  578. using namespace clang;
  579. using namespace clang::sema;
  580. using namespace hlsl;
  581. extern const char *HLSLScalarTypeNames[];
  582. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  583. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  584. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  585. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  586. static const SourceLocation NoLoc; // no source location attribution available
  587. static const SourceRange NoRange; // no source range attribution available
  588. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  589. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  590. static const bool IsConstexprFalse = false; // function is not constexpr
  591. static const bool ListInitializationFalse = false;// not performing a list initialization
  592. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  593. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  594. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  595. static const int OneRow = 1; // a single row for a type
  596. static const bool MipsFalse = false; // a type does not support the .mips member
  597. static const bool MipsTrue = true; // a type supports the .mips member
  598. static const bool SampleFalse = false; // a type does not support the .sample member
  599. static const bool SampleTrue = true; // a type supports the .sample member
  600. static const size_t MaxVectorSize = 4; // maximum size for a vector
  601. static
  602. QualType GetOrCreateTemplateSpecialization(
  603. ASTContext& context,
  604. Sema& sema,
  605. _In_ ClassTemplateDecl* templateDecl,
  606. ArrayRef<TemplateArgument> templateArgs
  607. )
  608. {
  609. DXASSERT_NOMSG(templateDecl);
  610. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  611. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  612. for (const TemplateArgument& Arg : templateArgs) {
  613. if (Arg.getKind() == TemplateArgument::Type) {
  614. // the class template need to use CanonicalType
  615. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  616. }else
  617. templateArgsForDecl.emplace_back(Arg);
  618. }
  619. // First, try looking up existing specialization
  620. void* InsertPos = nullptr;
  621. ClassTemplateSpecializationDecl* specializationDecl =
  622. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  623. if (specializationDecl) {
  624. // Instantiate the class template if not yet.
  625. if (specializationDecl->getInstantiatedFrom().isNull()) {
  626. // InstantiateClassTemplateSpecialization returns true if it finds an
  627. // error.
  628. DXVERIFY_NOMSG(false ==
  629. sema.InstantiateClassTemplateSpecialization(
  630. NoLoc, specializationDecl,
  631. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  632. true));
  633. }
  634. return context.getTemplateSpecializationType(
  635. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  636. context.getTypeDeclType(specializationDecl));
  637. }
  638. specializationDecl = ClassTemplateSpecializationDecl::Create(
  639. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  640. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  641. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  642. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  643. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  644. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  645. specializationDecl->setImplicit(true);
  646. QualType canonType = context.getTypeDeclType(specializationDecl);
  647. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  648. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  649. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  650. for (unsigned i = 0; i < templateArgs.size(); i++) {
  651. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  652. }
  653. return context.getTemplateSpecializationType(
  654. TemplateName(templateDecl), templateArgumentList, canonType);
  655. }
  656. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  657. static
  658. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  659. _In_ ClassTemplateDecl* matrixTemplateDecl,
  660. QualType elementType, uint64_t rowCount, uint64_t colCount)
  661. {
  662. DXASSERT_NOMSG(sema);
  663. TemplateArgument templateArgs[3] = {
  664. TemplateArgument(elementType),
  665. TemplateArgument(
  666. context,
  667. llvm::APSInt(
  668. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  669. context.IntTy),
  670. TemplateArgument(
  671. context,
  672. llvm::APSInt(
  673. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  674. context.IntTy)};
  675. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  676. #ifdef DBG
  677. // Verify that we can read the field member from the template record.
  678. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  679. "type of non-dependent specialization is not a RecordType");
  680. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  681. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  682. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  683. #endif
  684. return matrixSpecializationType;
  685. }
  686. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  687. static
  688. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  689. _In_ ClassTemplateDecl* vectorTemplateDecl,
  690. QualType elementType, uint64_t colCount)
  691. {
  692. DXASSERT_NOMSG(sema);
  693. DXASSERT_NOMSG(vectorTemplateDecl);
  694. TemplateArgument templateArgs[2] = {
  695. TemplateArgument(elementType),
  696. TemplateArgument(
  697. context,
  698. llvm::APSInt(
  699. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  700. context.IntTy)};
  701. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  702. #ifdef DBG
  703. // Verify that we can read the field member from the template record.
  704. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  705. "type of non-dependent specialization is not a RecordType");
  706. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  707. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  708. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  709. #endif
  710. return vectorSpecializationType;
  711. }
  712. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  713. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  714. static const unsigned kAtomicDstOperandIdx = 1;
  715. static const ArTypeObjectKind g_ScalarTT[] =
  716. {
  717. AR_TOBJ_SCALAR,
  718. AR_TOBJ_UNKNOWN
  719. };
  720. static const ArTypeObjectKind g_VectorTT[] =
  721. {
  722. AR_TOBJ_VECTOR,
  723. AR_TOBJ_UNKNOWN
  724. };
  725. static const ArTypeObjectKind g_MatrixTT[] =
  726. {
  727. AR_TOBJ_MATRIX,
  728. AR_TOBJ_UNKNOWN
  729. };
  730. static const ArTypeObjectKind g_AnyTT[] =
  731. {
  732. AR_TOBJ_SCALAR,
  733. AR_TOBJ_VECTOR,
  734. AR_TOBJ_MATRIX,
  735. AR_TOBJ_UNKNOWN
  736. };
  737. static const ArTypeObjectKind g_ObjectTT[] =
  738. {
  739. AR_TOBJ_OBJECT,
  740. AR_TOBJ_UNKNOWN
  741. };
  742. static const ArTypeObjectKind g_NullTT[] =
  743. {
  744. AR_TOBJ_VOID,
  745. AR_TOBJ_UNKNOWN
  746. };
  747. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  748. {
  749. g_NullTT,
  750. g_ScalarTT,
  751. g_VectorTT,
  752. g_MatrixTT,
  753. g_AnyTT,
  754. g_ObjectTT,
  755. };
  756. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  757. //
  758. // The first one is used to name the representative group, so make
  759. // sure its name will make sense in error messages.
  760. //
  761. static const ArBasicKind g_BoolCT[] =
  762. {
  763. AR_BASIC_BOOL,
  764. AR_BASIC_UNKNOWN
  765. };
  766. static const ArBasicKind g_IntCT[] =
  767. {
  768. AR_BASIC_INT32,
  769. AR_BASIC_LITERAL_INT,
  770. AR_BASIC_UNKNOWN
  771. };
  772. static const ArBasicKind g_UIntCT[] =
  773. {
  774. AR_BASIC_UINT32,
  775. AR_BASIC_LITERAL_INT,
  776. AR_BASIC_UNKNOWN
  777. };
  778. // We use the first element for default if matching kind is missing in the list.
  779. // AR_BASIC_INT32 should be the default for any int since min precision integers should map to int32, not int16 or int64
  780. static const ArBasicKind g_AnyIntCT[] =
  781. {
  782. AR_BASIC_INT32,
  783. AR_BASIC_INT16,
  784. AR_BASIC_UINT32,
  785. AR_BASIC_UINT16,
  786. AR_BASIC_INT64,
  787. AR_BASIC_UINT64,
  788. AR_BASIC_LITERAL_INT,
  789. AR_BASIC_UNKNOWN
  790. };
  791. static const ArBasicKind g_AnyInt32CT[] =
  792. {
  793. AR_BASIC_INT32,
  794. AR_BASIC_UINT32,
  795. AR_BASIC_LITERAL_INT,
  796. AR_BASIC_UNKNOWN
  797. };
  798. static const ArBasicKind g_UIntOnlyCT[] =
  799. {
  800. AR_BASIC_UINT32,
  801. AR_BASIC_UINT64,
  802. AR_BASIC_LITERAL_INT,
  803. AR_BASIC_NOCAST,
  804. AR_BASIC_UNKNOWN
  805. };
  806. static const ArBasicKind g_FloatCT[] =
  807. {
  808. AR_BASIC_FLOAT32,
  809. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  810. AR_BASIC_LITERAL_FLOAT,
  811. AR_BASIC_UNKNOWN
  812. };
  813. static const ArBasicKind g_AnyFloatCT[] =
  814. {
  815. AR_BASIC_FLOAT32,
  816. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  817. AR_BASIC_FLOAT16,
  818. AR_BASIC_FLOAT64,
  819. AR_BASIC_LITERAL_FLOAT,
  820. AR_BASIC_MIN10FLOAT,
  821. AR_BASIC_MIN16FLOAT,
  822. AR_BASIC_UNKNOWN
  823. };
  824. static const ArBasicKind g_FloatLikeCT[] =
  825. {
  826. AR_BASIC_FLOAT32,
  827. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  828. AR_BASIC_FLOAT16,
  829. AR_BASIC_LITERAL_FLOAT,
  830. AR_BASIC_MIN10FLOAT,
  831. AR_BASIC_MIN16FLOAT,
  832. AR_BASIC_UNKNOWN
  833. };
  834. static const ArBasicKind g_FloatDoubleCT[] =
  835. {
  836. AR_BASIC_FLOAT32,
  837. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  838. AR_BASIC_FLOAT64,
  839. AR_BASIC_LITERAL_FLOAT,
  840. AR_BASIC_UNKNOWN
  841. };
  842. static const ArBasicKind g_DoubleCT[] =
  843. {
  844. AR_BASIC_FLOAT64,
  845. AR_BASIC_LITERAL_FLOAT,
  846. AR_BASIC_UNKNOWN
  847. };
  848. static const ArBasicKind g_DoubleOnlyCT[] =
  849. {
  850. AR_BASIC_FLOAT64,
  851. AR_BASIC_LITERAL_FLOAT,
  852. AR_BASIC_NOCAST,
  853. AR_BASIC_UNKNOWN
  854. };
  855. static const ArBasicKind g_NumericCT[] =
  856. {
  857. AR_BASIC_FLOAT32,
  858. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  859. AR_BASIC_FLOAT16,
  860. AR_BASIC_FLOAT64,
  861. AR_BASIC_LITERAL_FLOAT,
  862. AR_BASIC_MIN10FLOAT,
  863. AR_BASIC_MIN16FLOAT,
  864. AR_BASIC_LITERAL_INT,
  865. AR_BASIC_INT16,
  866. AR_BASIC_INT32,
  867. AR_BASIC_UINT16,
  868. AR_BASIC_UINT32,
  869. AR_BASIC_MIN12INT,
  870. AR_BASIC_MIN16INT,
  871. AR_BASIC_MIN16UINT,
  872. AR_BASIC_INT64,
  873. AR_BASIC_UINT64,
  874. AR_BASIC_UNKNOWN
  875. };
  876. static const ArBasicKind g_Numeric32CT[] =
  877. {
  878. AR_BASIC_FLOAT32,
  879. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  880. AR_BASIC_LITERAL_FLOAT,
  881. AR_BASIC_LITERAL_INT,
  882. AR_BASIC_INT32,
  883. AR_BASIC_UINT32,
  884. AR_BASIC_UNKNOWN
  885. };
  886. static const ArBasicKind g_Numeric32OnlyCT[] =
  887. {
  888. AR_BASIC_FLOAT32,
  889. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  890. AR_BASIC_LITERAL_FLOAT,
  891. AR_BASIC_LITERAL_INT,
  892. AR_BASIC_INT32,
  893. AR_BASIC_UINT32,
  894. AR_BASIC_NOCAST,
  895. AR_BASIC_UNKNOWN
  896. };
  897. static const ArBasicKind g_AnyCT[] =
  898. {
  899. AR_BASIC_FLOAT32,
  900. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  901. AR_BASIC_FLOAT16,
  902. AR_BASIC_FLOAT64,
  903. AR_BASIC_LITERAL_FLOAT,
  904. AR_BASIC_MIN10FLOAT,
  905. AR_BASIC_MIN16FLOAT,
  906. AR_BASIC_INT16,
  907. AR_BASIC_UINT16,
  908. AR_BASIC_LITERAL_INT,
  909. AR_BASIC_INT32,
  910. AR_BASIC_UINT32,
  911. AR_BASIC_MIN12INT,
  912. AR_BASIC_MIN16INT,
  913. AR_BASIC_MIN16UINT,
  914. AR_BASIC_BOOL,
  915. AR_BASIC_INT64,
  916. AR_BASIC_UINT64,
  917. AR_BASIC_UNKNOWN
  918. };
  919. static const ArBasicKind g_Sampler1DCT[] =
  920. {
  921. AR_OBJECT_SAMPLER1D,
  922. AR_BASIC_UNKNOWN
  923. };
  924. static const ArBasicKind g_Sampler2DCT[] =
  925. {
  926. AR_OBJECT_SAMPLER2D,
  927. AR_BASIC_UNKNOWN
  928. };
  929. static const ArBasicKind g_Sampler3DCT[] =
  930. {
  931. AR_OBJECT_SAMPLER3D,
  932. AR_BASIC_UNKNOWN
  933. };
  934. static const ArBasicKind g_SamplerCUBECT[] =
  935. {
  936. AR_OBJECT_SAMPLERCUBE,
  937. AR_BASIC_UNKNOWN
  938. };
  939. static const ArBasicKind g_SamplerCmpCT[] =
  940. {
  941. AR_OBJECT_SAMPLERCOMPARISON,
  942. AR_BASIC_UNKNOWN
  943. };
  944. static const ArBasicKind g_SamplerCT[] =
  945. {
  946. AR_OBJECT_SAMPLER,
  947. AR_BASIC_UNKNOWN
  948. };
  949. static const ArBasicKind g_Texture2DCT[] =
  950. {
  951. AR_OBJECT_TEXTURE2D,
  952. AR_BASIC_UNKNOWN
  953. };
  954. static const ArBasicKind g_Texture2DArrayCT[] =
  955. {
  956. AR_OBJECT_TEXTURE2D_ARRAY,
  957. AR_BASIC_UNKNOWN
  958. };
  959. static const ArBasicKind g_ResourceCT[] = {AR_OBJECT_HEAP_RESOURCE,
  960. AR_BASIC_UNKNOWN};
  961. static const ArBasicKind g_RayDescCT[] =
  962. {
  963. AR_OBJECT_RAY_DESC,
  964. AR_BASIC_UNKNOWN
  965. };
  966. static const ArBasicKind g_AccelerationStructCT[] =
  967. {
  968. AR_OBJECT_ACCELERATION_STRUCT,
  969. AR_BASIC_UNKNOWN
  970. };
  971. static const ArBasicKind g_UDTCT[] =
  972. {
  973. AR_OBJECT_USER_DEFINED_TYPE,
  974. AR_BASIC_UNKNOWN
  975. };
  976. static const ArBasicKind g_StringCT[] =
  977. {
  978. AR_OBJECT_STRING_LITERAL,
  979. AR_OBJECT_STRING,
  980. AR_BASIC_UNKNOWN
  981. };
  982. static const ArBasicKind g_NullCT[] =
  983. {
  984. AR_OBJECT_NULL,
  985. AR_BASIC_UNKNOWN
  986. };
  987. static const ArBasicKind g_WaveCT[] =
  988. {
  989. AR_OBJECT_WAVE,
  990. AR_BASIC_UNKNOWN
  991. };
  992. static const ArBasicKind g_UInt64CT[] =
  993. {
  994. AR_BASIC_UINT64,
  995. AR_BASIC_UNKNOWN
  996. };
  997. static const ArBasicKind g_Float16CT[] =
  998. {
  999. AR_BASIC_FLOAT16,
  1000. AR_BASIC_LITERAL_FLOAT,
  1001. AR_BASIC_UNKNOWN
  1002. };
  1003. static const ArBasicKind g_Int16CT[] =
  1004. {
  1005. AR_BASIC_INT16,
  1006. AR_BASIC_LITERAL_INT,
  1007. AR_BASIC_UNKNOWN
  1008. };
  1009. static const ArBasicKind g_UInt16CT[] =
  1010. {
  1011. AR_BASIC_UINT16,
  1012. AR_BASIC_LITERAL_INT,
  1013. AR_BASIC_UNKNOWN
  1014. };
  1015. static const ArBasicKind g_Numeric16OnlyCT[] =
  1016. {
  1017. AR_BASIC_FLOAT16,
  1018. AR_BASIC_INT16,
  1019. AR_BASIC_UINT16,
  1020. AR_BASIC_LITERAL_FLOAT,
  1021. AR_BASIC_LITERAL_INT,
  1022. AR_BASIC_NOCAST,
  1023. AR_BASIC_UNKNOWN
  1024. };
  1025. static const ArBasicKind g_Int32OnlyCT[] =
  1026. {
  1027. AR_BASIC_INT32,
  1028. AR_BASIC_UINT32,
  1029. AR_BASIC_LITERAL_INT,
  1030. AR_BASIC_NOCAST,
  1031. AR_BASIC_UNKNOWN
  1032. };
  1033. static const ArBasicKind g_Float32OnlyCT[] =
  1034. {
  1035. AR_BASIC_FLOAT32,
  1036. AR_BASIC_LITERAL_FLOAT,
  1037. AR_BASIC_NOCAST,
  1038. AR_BASIC_UNKNOWN
  1039. };
  1040. static const ArBasicKind g_Int64OnlyCT[] =
  1041. {
  1042. AR_BASIC_UINT64,
  1043. AR_BASIC_INT64,
  1044. AR_BASIC_LITERAL_INT,
  1045. AR_BASIC_NOCAST,
  1046. AR_BASIC_UNKNOWN
  1047. };
  1048. static const ArBasicKind g_AnyInt64CT[] =
  1049. {
  1050. AR_BASIC_INT64,
  1051. AR_BASIC_UINT64,
  1052. AR_BASIC_LITERAL_INT,
  1053. AR_BASIC_UNKNOWN
  1054. };
  1055. static const ArBasicKind g_Int8_4PackedCT[] =
  1056. {
  1057. AR_BASIC_INT8_4PACKED,
  1058. AR_BASIC_UINT32,
  1059. AR_BASIC_LITERAL_INT,
  1060. AR_BASIC_UNKNOWN
  1061. };
  1062. static const ArBasicKind g_UInt8_4PackedCT[] =
  1063. {
  1064. AR_BASIC_UINT8_4PACKED,
  1065. AR_BASIC_UINT32,
  1066. AR_BASIC_LITERAL_INT,
  1067. AR_BASIC_UNKNOWN
  1068. };
  1069. static const ArBasicKind g_AnyInt16Or32CT[] = {
  1070. AR_BASIC_INT32,
  1071. AR_BASIC_UINT32,
  1072. AR_BASIC_INT16,
  1073. AR_BASIC_UINT16,
  1074. AR_BASIC_LITERAL_INT,
  1075. AR_BASIC_UNKNOWN
  1076. };
  1077. static const ArBasicKind g_SInt16Or32OnlyCT[] =
  1078. {
  1079. AR_BASIC_INT32,
  1080. AR_BASIC_INT16,
  1081. AR_BASIC_LITERAL_INT,
  1082. AR_BASIC_NOCAST,
  1083. AR_BASIC_UNKNOWN
  1084. };
  1085. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  1086. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  1087. {
  1088. g_NullCT, // LICOMPTYPE_VOID
  1089. g_BoolCT, // LICOMPTYPE_BOOL
  1090. g_IntCT, // LICOMPTYPE_INT
  1091. g_UIntCT, // LICOMPTYPE_UINT
  1092. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  1093. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  1094. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  1095. g_FloatCT, // LICOMPTYPE_FLOAT
  1096. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  1097. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  1098. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  1099. g_DoubleCT, // LICOMPTYPE_DOUBLE
  1100. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  1101. g_NumericCT, // LICOMPTYPE_NUMERIC
  1102. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  1103. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  1104. g_AnyCT, // LICOMPTYPE_ANY
  1105. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  1106. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  1107. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  1108. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  1109. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  1110. g_SamplerCT, // LICOMPTYPE_SAMPLER
  1111. g_StringCT, // LICOMPTYPE_STRING
  1112. g_WaveCT, // LICOMPTYPE_WAVE
  1113. g_UInt64CT, // LICOMPTYPE_UINT64
  1114. g_Float16CT, // LICOMPTYPE_FLOAT16
  1115. g_Int16CT, // LICOMPTYPE_INT16
  1116. g_UInt16CT, // LICOMPTYPE_UINT16
  1117. g_Numeric16OnlyCT, // LICOMPTYPE_NUMERIC16_ONLY
  1118. g_RayDescCT, // LICOMPTYPE_RAYDESC
  1119. g_AccelerationStructCT, // LICOMPTYPE_ACCELERATION_STRUCT,
  1120. g_UDTCT, // LICOMPTYPE_USER_DEFINED_TYPE
  1121. g_Texture2DCT, // LICOMPTYPE_TEXTURE2D
  1122. g_Texture2DArrayCT, // LICOMPTYPE_TEXTURE2DARRAY
  1123. g_ResourceCT, // LICOMPTYPE_RESOURCE
  1124. g_Int32OnlyCT, // LICOMPTYPE_INT32_ONLY
  1125. g_Int64OnlyCT, // LICOMPTYPE_INT64_ONLY
  1126. g_AnyInt64CT, // LICOMPTYPE_ANY_INT64
  1127. g_Float32OnlyCT, // LICOMPTYPE_FLOAT32_ONLY
  1128. g_Int8_4PackedCT, // LICOMPTYPE_INT8_4PACKED
  1129. g_UInt8_4PackedCT, // LICOMPTYPE_UINT8_4PACKED
  1130. g_AnyInt16Or32CT, // LICOMPTYPE_ANY_INT16_OR_32
  1131. g_SInt16Or32OnlyCT, // LICOMPTYPE_SINT16_OR_32_ONLY
  1132. };
  1133. static_assert(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT,
  1134. "Intrinsic comp type table must be updated when new enumerants are added.");
  1135. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  1136. // Basic kind objects that are represented as HLSL structures or templates.
  1137. static
  1138. const ArBasicKind g_ArBasicKindsAsTypes[] =
  1139. {
  1140. AR_OBJECT_BUFFER, // Buffer
  1141. // AR_OBJECT_TEXTURE,
  1142. AR_OBJECT_TEXTURE1D, // Texture1D
  1143. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  1144. AR_OBJECT_TEXTURE2D, // Texture2D
  1145. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  1146. AR_OBJECT_TEXTURE3D, // Texture3D
  1147. AR_OBJECT_TEXTURECUBE, // TextureCube
  1148. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  1149. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1150. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1151. AR_OBJECT_SAMPLER,
  1152. //AR_OBJECT_SAMPLER1D,
  1153. //AR_OBJECT_SAMPLER2D,
  1154. //AR_OBJECT_SAMPLER3D,
  1155. //AR_OBJECT_SAMPLERCUBE,
  1156. AR_OBJECT_SAMPLERCOMPARISON,
  1157. AR_OBJECT_CONSTANT_BUFFER,
  1158. AR_OBJECT_TEXTURE_BUFFER,
  1159. AR_OBJECT_POINTSTREAM,
  1160. AR_OBJECT_LINESTREAM,
  1161. AR_OBJECT_TRIANGLESTREAM,
  1162. AR_OBJECT_INPUTPATCH,
  1163. AR_OBJECT_OUTPUTPATCH,
  1164. AR_OBJECT_RWTEXTURE1D,
  1165. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1166. AR_OBJECT_RWTEXTURE2D,
  1167. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1168. AR_OBJECT_RWTEXTURE3D,
  1169. AR_OBJECT_RWBUFFER,
  1170. AR_OBJECT_BYTEADDRESS_BUFFER,
  1171. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1172. AR_OBJECT_STRUCTURED_BUFFER,
  1173. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1174. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1175. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1176. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1177. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1178. AR_OBJECT_ROVBUFFER,
  1179. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1180. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1181. AR_OBJECT_ROVTEXTURE1D,
  1182. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1183. AR_OBJECT_ROVTEXTURE2D,
  1184. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1185. AR_OBJECT_ROVTEXTURE3D,
  1186. AR_OBJECT_FEEDBACKTEXTURE2D,
  1187. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  1188. // SPIRV change starts
  1189. #ifdef ENABLE_SPIRV_CODEGEN
  1190. AR_OBJECT_VK_SUBPASS_INPUT,
  1191. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1192. #endif // ENABLE_SPIRV_CODEGEN
  1193. // SPIRV change ends
  1194. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1195. AR_OBJECT_WAVE,
  1196. AR_OBJECT_RAY_DESC,
  1197. AR_OBJECT_ACCELERATION_STRUCT,
  1198. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  1199. // subobjects
  1200. AR_OBJECT_STATE_OBJECT_CONFIG,
  1201. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1202. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1203. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1204. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1205. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1206. AR_OBJECT_TRIANGLE_HIT_GROUP,
  1207. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1208. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1209. AR_OBJECT_RAY_QUERY,
  1210. AR_OBJECT_HEAP_RESOURCE,
  1211. AR_OBJECT_HEAP_SAMPLER,
  1212. };
  1213. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1214. static
  1215. const uint8_t g_ArBasicKindsTemplateCount[] =
  1216. {
  1217. 1, // AR_OBJECT_BUFFER
  1218. // AR_OBJECT_TEXTURE,
  1219. 1, // AR_OBJECT_TEXTURE1D
  1220. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1221. 1, // AR_OBJECT_TEXTURE2D
  1222. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1223. 1, // AR_OBJECT_TEXTURE3D
  1224. 1, // AR_OBJECT_TEXTURECUBE
  1225. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1226. 2, // AR_OBJECT_TEXTURE2DMS
  1227. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1228. 0, // AR_OBJECT_SAMPLER
  1229. //AR_OBJECT_SAMPLER1D,
  1230. //AR_OBJECT_SAMPLER2D,
  1231. //AR_OBJECT_SAMPLER3D,
  1232. //AR_OBJECT_SAMPLERCUBE,
  1233. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1234. 1, //AR_OBJECT_CONSTANT_BUFFER,
  1235. 1, //AR_OBJECT_TEXTURE_BUFFER,
  1236. 1, // AR_OBJECT_POINTSTREAM
  1237. 1, // AR_OBJECT_LINESTREAM
  1238. 1, // AR_OBJECT_TRIANGLESTREAM
  1239. 2, // AR_OBJECT_INPUTPATCH
  1240. 2, // AR_OBJECT_OUTPUTPATCH
  1241. 1, // AR_OBJECT_RWTEXTURE1D
  1242. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1243. 1, // AR_OBJECT_RWTEXTURE2D
  1244. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1245. 1, // AR_OBJECT_RWTEXTURE3D
  1246. 1, // AR_OBJECT_RWBUFFER
  1247. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1248. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1249. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1250. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1251. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1252. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1253. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1254. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1255. 1, // AR_OBJECT_ROVBUFFER
  1256. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1257. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1258. 1, // AR_OBJECT_ROVTEXTURE1D
  1259. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1260. 1, // AR_OBJECT_ROVTEXTURE2D
  1261. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1262. 1, // AR_OBJECT_ROVTEXTURE3D
  1263. 1, // AR_OBJECT_FEEDBACKTEXTURE2D
  1264. 1, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1265. // SPIRV change starts
  1266. #ifdef ENABLE_SPIRV_CODEGEN
  1267. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1268. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1269. #endif // ENABLE_SPIRV_CODEGEN
  1270. // SPIRV change ends
  1271. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1272. 0, // AR_OBJECT_WAVE
  1273. 0, // AR_OBJECT_RAY_DESC
  1274. 0, // AR_OBJECT_ACCELERATION_STRUCT
  1275. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1276. 0, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1277. 0, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1278. 0, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1279. 0, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1280. 0, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1281. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1282. 0, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1283. 0, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1284. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1285. 1, // AR_OBJECT_RAY_QUERY,
  1286. 0, // AR_OBJECT_HEAP_RESOURCE,
  1287. 0, // AR_OBJECT_HEAP_SAMPLER,
  1288. };
  1289. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1290. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1291. struct SubscriptOperatorRecord
  1292. {
  1293. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1294. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1295. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1296. };
  1297. // Subscript operators for objects that are represented as HLSL structures or templates.
  1298. static
  1299. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1300. {
  1301. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1302. // AR_OBJECT_TEXTURE,
  1303. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1304. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1305. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1306. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1307. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1308. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1309. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1310. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1311. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1312. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1313. //AR_OBJECT_SAMPLER1D,
  1314. //AR_OBJECT_SAMPLER2D,
  1315. //AR_OBJECT_SAMPLER3D,
  1316. //AR_OBJECT_SAMPLERCUBE,
  1317. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1318. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSTANT_BUFFER
  1319. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURE_BUFFER
  1320. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1321. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1322. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1323. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1324. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1325. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1326. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1327. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1328. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1329. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1330. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1331. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1332. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1333. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1334. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1335. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1336. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1337. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1338. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1339. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1340. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1341. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1342. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1343. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1344. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1345. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1346. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1347. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D
  1348. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1349. // SPIRV change starts
  1350. #ifdef ENABLE_SPIRV_CODEGEN
  1351. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1352. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1353. #endif // ENABLE_SPIRV_CODEGEN
  1354. // SPIRV change ends
  1355. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1356. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_WAVE
  1357. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_DESC
  1358. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ACCELERATION_STRUCT
  1359. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1360. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1361. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1362. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1363. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1364. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1365. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1366. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1367. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1368. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1369. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_QUERY,
  1370. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_HEAP_RESOURCE,
  1371. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_HEAP_SAMPLER,
  1372. };
  1373. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1374. // Type names for ArBasicKind values.
  1375. static
  1376. const char* g_ArBasicTypeNames[] =
  1377. {
  1378. "bool", "float", "half", "half", "float", "double",
  1379. "int", "sbyte", "byte", "short", "ushort",
  1380. "int", "uint", "long", "ulong",
  1381. "min10float", "min16float",
  1382. "min12int", "min16int", "min16uint",
  1383. "int8_t4_packed", "uint8_t4_packed",
  1384. "enum",
  1385. "<count>",
  1386. "<none>",
  1387. "<unknown>",
  1388. "<nocast>",
  1389. "<pointer>",
  1390. "enum class",
  1391. "null",
  1392. "literal string",
  1393. "string",
  1394. // "texture",
  1395. "Texture1D",
  1396. "Texture1DArray",
  1397. "Texture2D",
  1398. "Texture2DArray",
  1399. "Texture3D",
  1400. "TextureCube",
  1401. "TextureCubeArray",
  1402. "Texture2DMS",
  1403. "Texture2DMSArray",
  1404. "SamplerState",
  1405. "sampler1D",
  1406. "sampler2D",
  1407. "sampler3D",
  1408. "samplerCUBE",
  1409. "SamplerComparisonState",
  1410. "Buffer",
  1411. "RenderTargetView",
  1412. "DepthStencilView",
  1413. "ComputeShader",
  1414. "DomainShader",
  1415. "GeometryShader",
  1416. "HullShader",
  1417. "PixelShader",
  1418. "VertexShader",
  1419. "pixelfragment",
  1420. "vertexfragment",
  1421. "StateBlock",
  1422. "Rasterizer",
  1423. "DepthStencil",
  1424. "Blend",
  1425. "PointStream",
  1426. "LineStream",
  1427. "TriangleStream",
  1428. "InputPatch",
  1429. "OutputPatch",
  1430. "RWTexture1D",
  1431. "RWTexture1DArray",
  1432. "RWTexture2D",
  1433. "RWTexture2DArray",
  1434. "RWTexture3D",
  1435. "RWBuffer",
  1436. "ByteAddressBuffer",
  1437. "RWByteAddressBuffer",
  1438. "StructuredBuffer",
  1439. "RWStructuredBuffer",
  1440. "RWStructuredBuffer(Incrementable)",
  1441. "RWStructuredBuffer(Decrementable)",
  1442. "AppendStructuredBuffer",
  1443. "ConsumeStructuredBuffer",
  1444. "ConstantBuffer",
  1445. "TextureBuffer",
  1446. "RasterizerOrderedBuffer",
  1447. "RasterizerOrderedByteAddressBuffer",
  1448. "RasterizerOrderedStructuredBuffer",
  1449. "RasterizerOrderedTexture1D",
  1450. "RasterizerOrderedTexture1DArray",
  1451. "RasterizerOrderedTexture2D",
  1452. "RasterizerOrderedTexture2DArray",
  1453. "RasterizerOrderedTexture3D",
  1454. "FeedbackTexture2D",
  1455. "FeedbackTexture2DArray",
  1456. // SPIRV change starts
  1457. #ifdef ENABLE_SPIRV_CODEGEN
  1458. "SubpassInput",
  1459. "SubpassInputMS",
  1460. #endif // ENABLE_SPIRV_CODEGEN
  1461. // SPIRV change ends
  1462. "<internal inner type object>",
  1463. "deprecated effect object",
  1464. "wave_t",
  1465. "RayDesc",
  1466. "RaytracingAccelerationStructure",
  1467. "user defined type",
  1468. "BuiltInTriangleIntersectionAttributes",
  1469. // subobjects
  1470. "StateObjectConfig",
  1471. "GlobalRootSignature",
  1472. "LocalRootSignature",
  1473. "SubobjectToExportsAssociation",
  1474. "RaytracingShaderConfig",
  1475. "RaytracingPipelineConfig",
  1476. "TriangleHitGroup",
  1477. "ProceduralPrimitiveHitGroup",
  1478. "RaytracingPipelineConfig1",
  1479. "RayQuery",
  1480. "HEAP_Resource",
  1481. "HEAP_Sampler",
  1482. };
  1483. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1484. static bool IsValidBasicKind(ArBasicKind kind) {
  1485. return kind != AR_BASIC_COUNT &&
  1486. kind != AR_BASIC_NONE &&
  1487. kind != AR_BASIC_UNKNOWN &&
  1488. kind != AR_BASIC_NOCAST &&
  1489. kind != AR_BASIC_POINTER &&
  1490. kind != AR_OBJECT_RENDERTARGETVIEW &&
  1491. kind != AR_OBJECT_DEPTHSTENCILVIEW &&
  1492. kind != AR_OBJECT_COMPUTESHADER &&
  1493. kind != AR_OBJECT_DOMAINSHADER &&
  1494. kind != AR_OBJECT_GEOMETRYSHADER &&
  1495. kind != AR_OBJECT_HULLSHADER &&
  1496. kind != AR_OBJECT_PIXELSHADER &&
  1497. kind != AR_OBJECT_VERTEXSHADER &&
  1498. kind != AR_OBJECT_PIXELFRAGMENT &&
  1499. kind != AR_OBJECT_VERTEXFRAGMENT;
  1500. }
  1501. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1502. #define DXASSERT_VALIDBASICKIND(kind) \
  1503. DXASSERT(IsValidBasicKind(kind), "otherwise caller is using a special flag or an unsupported kind value");
  1504. static
  1505. const char* g_DeprecatedEffectObjectNames[] =
  1506. {
  1507. // These are case insensitive in fxc, but we'll just create two case aliases
  1508. // to capture the majority of cases
  1509. "texture", "Texture",
  1510. "pixelshader", "PixelShader",
  1511. "vertexshader", "VertexShader",
  1512. // These are case sensitive in fxc
  1513. "pixelfragment", // 13
  1514. "vertexfragment", // 14
  1515. "ComputeShader", // 13
  1516. "DomainShader", // 12
  1517. "GeometryShader", // 14
  1518. "HullShader", // 10
  1519. "BlendState", // 10
  1520. "DepthStencilState",// 17
  1521. "DepthStencilView", // 16
  1522. "RasterizerState", // 15
  1523. "RenderTargetView", // 16
  1524. };
  1525. static bool IsVariadicIntrinsicFunction(const HLSL_INTRINSIC *fn) {
  1526. return fn->pArgs[fn->uNumArgs - 1].uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1527. }
  1528. static bool IsVariadicArgument(const HLSL_INTRINSIC_ARGUMENT &arg) {
  1529. return arg.uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1530. }
  1531. static hlsl::ParameterModifier
  1532. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1533. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1534. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1535. }
  1536. if (pArg->qwUsage == AR_QUAL_OUT) {
  1537. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1538. }
  1539. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1540. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1541. }
  1542. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1543. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1544. // The first argument is the return value, which isn't included.
  1545. UINT i = 1, size = paramMods.size();
  1546. for (; i < pIntrinsic->uNumArgs; ++i) {
  1547. // Once we reach varargs we can break out of this loop.
  1548. if (IsVariadicArgument(pIntrinsic->pArgs[i]))
  1549. break;
  1550. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1551. }
  1552. // For variadic functions, any argument not explicitly specified will be
  1553. // considered an input argument.
  1554. if (IsVariadicIntrinsicFunction(pIntrinsic)) {
  1555. for (; i < size; ++i) {
  1556. paramMods.push_back(
  1557. hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In));
  1558. }
  1559. }
  1560. }
  1561. static bool IsAtomicOperation(IntrinsicOp op) {
  1562. switch (op) {
  1563. case IntrinsicOp::IOP_InterlockedAdd:
  1564. case IntrinsicOp::IOP_InterlockedAnd:
  1565. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1566. case IntrinsicOp::IOP_InterlockedCompareStore:
  1567. case IntrinsicOp::IOP_InterlockedCompareExchangeFloatBitwise:
  1568. case IntrinsicOp::IOP_InterlockedCompareStoreFloatBitwise:
  1569. case IntrinsicOp::IOP_InterlockedExchange:
  1570. case IntrinsicOp::IOP_InterlockedMax:
  1571. case IntrinsicOp::IOP_InterlockedMin:
  1572. case IntrinsicOp::IOP_InterlockedOr:
  1573. case IntrinsicOp::IOP_InterlockedXor:
  1574. case IntrinsicOp::MOP_InterlockedAdd:
  1575. case IntrinsicOp::MOP_InterlockedAnd:
  1576. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1577. case IntrinsicOp::MOP_InterlockedCompareStore:
  1578. case IntrinsicOp::MOP_InterlockedExchange:
  1579. case IntrinsicOp::MOP_InterlockedMax:
  1580. case IntrinsicOp::MOP_InterlockedMin:
  1581. case IntrinsicOp::MOP_InterlockedOr:
  1582. case IntrinsicOp::MOP_InterlockedXor:
  1583. case IntrinsicOp::MOP_InterlockedAdd64:
  1584. case IntrinsicOp::MOP_InterlockedAnd64:
  1585. case IntrinsicOp::MOP_InterlockedCompareExchange64:
  1586. case IntrinsicOp::MOP_InterlockedCompareStore64:
  1587. case IntrinsicOp::MOP_InterlockedExchange64:
  1588. case IntrinsicOp::MOP_InterlockedMax64:
  1589. case IntrinsicOp::MOP_InterlockedMin64:
  1590. case IntrinsicOp::MOP_InterlockedOr64:
  1591. case IntrinsicOp::MOP_InterlockedXor64:
  1592. case IntrinsicOp::MOP_InterlockedExchangeFloat:
  1593. case IntrinsicOp::MOP_InterlockedCompareExchangeFloatBitwise:
  1594. case IntrinsicOp::MOP_InterlockedCompareStoreFloatBitwise:
  1595. return true;
  1596. default:
  1597. return false;
  1598. }
  1599. }
  1600. static bool IsBuiltinTable(LPCSTR tableName) {
  1601. return tableName == kBuiltinIntrinsicTableName;
  1602. }
  1603. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1604. LPCSTR tableName, LPCSTR lowering,
  1605. const HLSL_INTRINSIC *pIntrinsic) {
  1606. unsigned opcode = (unsigned)pIntrinsic->Op;
  1607. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1608. QualType Ty = FD->getReturnType();
  1609. if (pIntrinsic->iOverloadParamIndex != -1) {
  1610. const FunctionProtoType *FT =
  1611. FD->getFunctionType()->getAs<FunctionProtoType>();
  1612. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1613. // To go thru reference type.
  1614. if (Ty->isReferenceType())
  1615. Ty = Ty.getNonReferenceType();
  1616. }
  1617. // TODO: refine the code for getting element type
  1618. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1619. Ty = VecTy->getElementType();
  1620. }
  1621. // Make sure to use unsigned op when return type is 'unsigned' matrix
  1622. bool isUnsignedMatOp =
  1623. IsHLSLMatType(Ty) && GetHLSLMatElementType(Ty)->isUnsignedIntegerType();
  1624. if (Ty->isUnsignedIntegerType() || isUnsignedMatOp) {
  1625. opcode = hlsl::GetUnsignedOpcode(opcode);
  1626. }
  1627. }
  1628. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1629. if (pIntrinsic->bReadNone)
  1630. FD->addAttr(ConstAttr::CreateImplicit(context));
  1631. if (pIntrinsic->bReadOnly)
  1632. FD->addAttr(PureAttr::CreateImplicit(context));
  1633. if (pIntrinsic->bIsWave)
  1634. FD->addAttr(HLSLWaveSensitiveAttr::CreateImplicit(context));
  1635. }
  1636. static
  1637. FunctionDecl *AddHLSLIntrinsicFunction(
  1638. ASTContext &context, _In_ NamespaceDecl *NS,
  1639. LPCSTR tableName, LPCSTR lowering,
  1640. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1641. std::vector<QualType> *functionArgQualTypesVector)
  1642. {
  1643. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1644. std::vector<QualType> &functionArgQualTypes = *functionArgQualTypesVector;
  1645. const size_t functionArgTypeCount = functionArgQualTypes.size();
  1646. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  1647. DXASSERT(isVariadic || functionArgTypeCount - 1 <= g_MaxIntrinsicParamCount,
  1648. "otherwise g_MaxIntrinsicParamCount should be larger");
  1649. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1650. if (isVariadic) {
  1651. // For variadic functions, the number of arguments is larger than the
  1652. // function declaration signature.
  1653. paramMods.resize(functionArgTypeCount);
  1654. }
  1655. InitParamMods(pIntrinsic, paramMods);
  1656. // Change dest address into reference type for atomic.
  1657. if (IsBuiltinTable(tableName)) {
  1658. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1659. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1660. "else operation was misrecognized");
  1661. functionArgQualTypes[kAtomicDstOperandIdx] =
  1662. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1663. }
  1664. }
  1665. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1666. // Change out/inout param to reference type.
  1667. if (paramMods[i-1].isAnyOut()) {
  1668. QualType Ty = functionArgQualTypes[i];
  1669. // Aggregate type will be indirect param convert to pointer type.
  1670. // Don't need add reference for it.
  1671. if ((!Ty->isArrayType() && !Ty->isRecordType()) ||
  1672. hlsl::IsHLSLVecMatType(Ty)) {
  1673. functionArgQualTypes[i] = context.getLValueReferenceType(Ty);
  1674. }
  1675. }
  1676. }
  1677. IdentifierInfo &functionId = context.Idents.get(
  1678. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1679. DeclarationName functionName(&functionId);
  1680. auto protoInfo = clang::FunctionProtoType::ExtProtoInfo();
  1681. protoInfo.Variadic = isVariadic;
  1682. // functionArgQualTypes first element is the function return type, and
  1683. // function argument types start at index 1.
  1684. const QualType fnReturnType = functionArgQualTypes[0];
  1685. std::vector<QualType> fnArgTypes(functionArgQualTypes.begin() + 1,
  1686. functionArgQualTypes.end());
  1687. QualType functionType =
  1688. context.getFunctionType(fnReturnType, fnArgTypes, protoInfo, paramMods);
  1689. FunctionDecl *functionDecl = FunctionDecl::Create(
  1690. context, currentDeclContext, NoLoc,
  1691. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1692. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1693. currentDeclContext->addDecl(functionDecl);
  1694. functionDecl->setLexicalDeclContext(currentDeclContext);
  1695. // put under hlsl namespace
  1696. functionDecl->setDeclContext(NS);
  1697. // Add intrinsic attribute
  1698. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1699. llvm::SmallVector<ParmVarDecl *, 4> paramDecls;
  1700. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1701. // For variadic functions all non-explicit arguments will have the same
  1702. // name: "..."
  1703. std::string name = i < pIntrinsic->uNumArgs - 1
  1704. ? pIntrinsic->pArgs[i].pName
  1705. : pIntrinsic->pArgs[pIntrinsic->uNumArgs - 1].pName;
  1706. IdentifierInfo &parameterId =
  1707. context.Idents.get(name, tok::TokenKind::identifier);
  1708. ParmVarDecl *paramDecl =
  1709. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1710. functionArgQualTypes[i], nullptr,
  1711. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1712. functionDecl->addDecl(paramDecl);
  1713. paramDecls.push_back(paramDecl);
  1714. }
  1715. functionDecl->setParams(paramDecls);
  1716. functionDecl->setImplicit(true);
  1717. return functionDecl;
  1718. }
  1719. /// <summary>
  1720. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1721. /// </summary>
  1722. static
  1723. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1724. {
  1725. DXASSERT_NOMSG(expr != nullptr);
  1726. expr = expr->IgnoreParens();
  1727. return
  1728. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1729. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1730. }
  1731. /// <summary>
  1732. /// Silences diagnostics for the initialization sequence, typically because they have already
  1733. /// been emitted.
  1734. /// </summary>
  1735. static
  1736. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1737. {
  1738. DXASSERT_NOMSG(initSequence != nullptr);
  1739. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1740. }
  1741. class UsedIntrinsic
  1742. {
  1743. public:
  1744. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1745. {
  1746. // The canonical representations are unique'd in an ASTContext, and so these
  1747. // should be stable.
  1748. return RHS.getTypePtr() - LHS.getTypePtr();
  1749. }
  1750. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1751. {
  1752. // The intrinsics are defined in a single static table, and so should be stable.
  1753. return RHS - LHS;
  1754. }
  1755. int compare(const UsedIntrinsic& other) const
  1756. {
  1757. // Check whether it's the same instance.
  1758. if (this == &other) return 0;
  1759. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1760. if (result != 0) return result;
  1761. // At this point, it's the exact same intrinsic name.
  1762. // Compare the arguments for ordering then.
  1763. DXASSERT(IsVariadicIntrinsicFunction(m_intrinsicSource) ||
  1764. m_args.size() == other.m_args.size(),
  1765. "only variadic intrinsics can be overloaded on argument count");
  1766. // For variadic functions with different number of args, order by number of
  1767. // arguments.
  1768. if (m_args.size() != other.m_args.size())
  1769. return m_args.size() - other.m_args.size();
  1770. for (size_t i = 0; i < m_args.size(); i++) {
  1771. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1772. if (argComparison != 0) return argComparison;
  1773. }
  1774. // Exactly the same.
  1775. return 0;
  1776. }
  1777. public:
  1778. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, llvm::ArrayRef<QualType> args)
  1779. : m_args(args.begin(), args.end()), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1780. {
  1781. }
  1782. void setFunctionDecl(FunctionDecl* value) const
  1783. {
  1784. DXASSERT(value != nullptr, "no reason to clear this out");
  1785. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1786. m_functionDecl = value;
  1787. }
  1788. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1789. bool operator==(const UsedIntrinsic& other) const
  1790. {
  1791. return compare(other) == 0;
  1792. }
  1793. bool operator<(const UsedIntrinsic& other) const
  1794. {
  1795. return compare(other) < 0;
  1796. }
  1797. private:
  1798. std::vector<QualType> m_args;
  1799. const HLSL_INTRINSIC* m_intrinsicSource;
  1800. mutable FunctionDecl* m_functionDecl;
  1801. };
  1802. template <typename T>
  1803. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1804. {
  1805. if (ptr != nullptr)
  1806. {
  1807. *ptr = value;
  1808. }
  1809. }
  1810. static bool CombineBasicTypes(ArBasicKind LeftKind,
  1811. ArBasicKind RightKind,
  1812. _Out_ ArBasicKind* pOutKind)
  1813. {
  1814. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1815. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1816. return false;
  1817. }
  1818. if (LeftKind == RightKind) {
  1819. *pOutKind = LeftKind;
  1820. return true;
  1821. }
  1822. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1823. UINT uRightProps = GetBasicKindProps(RightKind);
  1824. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1825. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1826. UINT uBothFlags = uLeftProps & uRightProps;
  1827. UINT uEitherFlags = uLeftProps | uRightProps;
  1828. // Notes: all numeric types have either BPROP_FLOATING or BPROP_INTEGER (even bool)
  1829. // unsigned only applies to non-literal ints, not bool or enum
  1830. // literals, bool, and enum are all BPROP_BITS0
  1831. if (uBothFlags & BPROP_BOOLEAN) {
  1832. *pOutKind = AR_BASIC_BOOL;
  1833. return true;
  1834. }
  1835. bool bFloatResult = 0 != (uEitherFlags & BPROP_FLOATING);
  1836. if (uBothFlags & BPROP_LITERAL) {
  1837. *pOutKind = bFloatResult ? AR_BASIC_LITERAL_FLOAT : AR_BASIC_LITERAL_INT;
  1838. return true;
  1839. }
  1840. // Starting approximation of result properties:
  1841. // - float if either are float, otherwise int (see Notes above)
  1842. // - min/partial precision if both have same flag
  1843. // - if not float, add unsigned if either is unsigned
  1844. UINT uResultFlags =
  1845. (uBothFlags & (BPROP_INTEGER | BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION)) |
  1846. (uEitherFlags & BPROP_FLOATING) |
  1847. (!bFloatResult ? (uEitherFlags & BPROP_UNSIGNED) : 0);
  1848. // If one is literal/bool/enum, use min/partial precision from the other
  1849. if (uEitherFlags & (BPROP_LITERAL | BPROP_BOOLEAN | BPROP_ENUM)) {
  1850. uResultFlags |= uEitherFlags & (BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION);
  1851. }
  1852. // Now if we have partial precision, we know the result must be half
  1853. if (uResultFlags & BPROP_PARTIAL_PRECISION) {
  1854. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1855. return true;
  1856. }
  1857. // uBits are already initialized to max of either side, so now:
  1858. // if only one is float, get result props from float side
  1859. // min16float + int -> min16float
  1860. // also take min precision from that side
  1861. if (bFloatResult && 0 == (uBothFlags & BPROP_FLOATING)) {
  1862. uResultFlags = (uLeftProps & BPROP_FLOATING) ? uLeftProps : uRightProps;
  1863. uBits = GET_BPROP_BITS(uResultFlags);
  1864. uResultFlags &= ~BPROP_LITERAL;
  1865. }
  1866. bool bMinPrecisionResult = uResultFlags & BPROP_MIN_PRECISION;
  1867. // if uBits is 0 here, upgrade to 32-bits
  1868. // this happens if bool, literal or enum on both sides,
  1869. // or if float came from literal side
  1870. if (uBits == BPROP_BITS0)
  1871. uBits = BPROP_BITS32;
  1872. DXASSERT(uBits != BPROP_BITS0, "CombineBasicTypes: uBits should not be zero at this point");
  1873. DXASSERT(uBits != BPROP_BITS8, "CombineBasicTypes: 8-bit types not supported at this time");
  1874. if (bMinPrecisionResult) {
  1875. DXASSERT(uBits < BPROP_BITS32, "CombineBasicTypes: min-precision result must be less than 32-bits");
  1876. } else {
  1877. DXASSERT(uBits > BPROP_BITS12, "CombineBasicTypes: 10 or 12 bit result must be min precision");
  1878. }
  1879. if (bFloatResult) {
  1880. DXASSERT(uBits != BPROP_BITS12, "CombineBasicTypes: 12-bit result must be int");
  1881. } else {
  1882. DXASSERT(uBits != BPROP_BITS10, "CombineBasicTypes: 10-bit result must be float");
  1883. }
  1884. if (uBits == BPROP_BITS12) {
  1885. DXASSERT(!(uResultFlags & BPROP_UNSIGNED), "CombineBasicTypes: 12-bit result must not be unsigned");
  1886. }
  1887. if (bFloatResult) {
  1888. switch (uBits) {
  1889. case BPROP_BITS10:
  1890. *pOutKind = AR_BASIC_MIN10FLOAT;
  1891. break;
  1892. case BPROP_BITS16:
  1893. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  1894. break;
  1895. case BPROP_BITS32:
  1896. *pOutKind = AR_BASIC_FLOAT32;
  1897. break;
  1898. case BPROP_BITS64:
  1899. *pOutKind = AR_BASIC_FLOAT64;
  1900. break;
  1901. default:
  1902. DXASSERT(false, "Unexpected bit count for float result");
  1903. break;
  1904. }
  1905. } else {
  1906. // int or unsigned int
  1907. switch (uBits) {
  1908. case BPROP_BITS12:
  1909. *pOutKind = AR_BASIC_MIN12INT;
  1910. break;
  1911. case BPROP_BITS16:
  1912. if (uResultFlags & BPROP_UNSIGNED)
  1913. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  1914. else
  1915. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  1916. break;
  1917. case BPROP_BITS32:
  1918. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT32 : AR_BASIC_INT32;
  1919. break;
  1920. case BPROP_BITS64:
  1921. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT64 : AR_BASIC_INT64;
  1922. break;
  1923. default:
  1924. DXASSERT(false, "Unexpected bit count for int result");
  1925. break;
  1926. }
  1927. }
  1928. return true;
  1929. }
  1930. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1931. {
  1932. };
  1933. static
  1934. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1935. {
  1936. DXASSERT_NOMSG(intrinsics != nullptr);
  1937. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1938. switch (kind)
  1939. {
  1940. case AR_OBJECT_TRIANGLESTREAM:
  1941. case AR_OBJECT_POINTSTREAM:
  1942. case AR_OBJECT_LINESTREAM:
  1943. *intrinsics = g_StreamMethods;
  1944. *intrinsicCount = _countof(g_StreamMethods);
  1945. break;
  1946. case AR_OBJECT_TEXTURE1D:
  1947. *intrinsics = g_Texture1DMethods;
  1948. *intrinsicCount = _countof(g_Texture1DMethods);
  1949. break;
  1950. case AR_OBJECT_TEXTURE1D_ARRAY:
  1951. *intrinsics = g_Texture1DArrayMethods;
  1952. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1953. break;
  1954. case AR_OBJECT_TEXTURE2D:
  1955. *intrinsics = g_Texture2DMethods;
  1956. *intrinsicCount = _countof(g_Texture2DMethods);
  1957. break;
  1958. case AR_OBJECT_TEXTURE2DMS:
  1959. *intrinsics = g_Texture2DMSMethods;
  1960. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1961. break;
  1962. case AR_OBJECT_TEXTURE2D_ARRAY:
  1963. *intrinsics = g_Texture2DArrayMethods;
  1964. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1965. break;
  1966. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1967. *intrinsics = g_Texture2DArrayMSMethods;
  1968. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1969. break;
  1970. case AR_OBJECT_TEXTURE3D:
  1971. *intrinsics = g_Texture3DMethods;
  1972. *intrinsicCount = _countof(g_Texture3DMethods);
  1973. break;
  1974. case AR_OBJECT_TEXTURECUBE:
  1975. *intrinsics = g_TextureCUBEMethods;
  1976. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1977. break;
  1978. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1979. *intrinsics = g_TextureCUBEArrayMethods;
  1980. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1981. break;
  1982. case AR_OBJECT_BUFFER:
  1983. *intrinsics = g_BufferMethods;
  1984. *intrinsicCount = _countof(g_BufferMethods);
  1985. break;
  1986. case AR_OBJECT_RWTEXTURE1D:
  1987. case AR_OBJECT_ROVTEXTURE1D:
  1988. *intrinsics = g_RWTexture1DMethods;
  1989. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1990. break;
  1991. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1992. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1993. *intrinsics = g_RWTexture1DArrayMethods;
  1994. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1995. break;
  1996. case AR_OBJECT_RWTEXTURE2D:
  1997. case AR_OBJECT_ROVTEXTURE2D:
  1998. *intrinsics = g_RWTexture2DMethods;
  1999. *intrinsicCount = _countof(g_RWTexture2DMethods);
  2000. break;
  2001. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  2002. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  2003. *intrinsics = g_RWTexture2DArrayMethods;
  2004. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  2005. break;
  2006. case AR_OBJECT_RWTEXTURE3D:
  2007. case AR_OBJECT_ROVTEXTURE3D:
  2008. *intrinsics = g_RWTexture3DMethods;
  2009. *intrinsicCount = _countof(g_RWTexture3DMethods);
  2010. break;
  2011. case AR_OBJECT_FEEDBACKTEXTURE2D:
  2012. *intrinsics = g_FeedbackTexture2DMethods;
  2013. *intrinsicCount = _countof(g_FeedbackTexture2DMethods);
  2014. break;
  2015. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  2016. *intrinsics = g_FeedbackTexture2DArrayMethods;
  2017. *intrinsicCount = _countof(g_FeedbackTexture2DArrayMethods);
  2018. break;
  2019. case AR_OBJECT_RWBUFFER:
  2020. case AR_OBJECT_ROVBUFFER:
  2021. *intrinsics = g_RWBufferMethods;
  2022. *intrinsicCount = _countof(g_RWBufferMethods);
  2023. break;
  2024. case AR_OBJECT_BYTEADDRESS_BUFFER:
  2025. *intrinsics = g_ByteAddressBufferMethods;
  2026. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  2027. break;
  2028. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  2029. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  2030. *intrinsics = g_RWByteAddressBufferMethods;
  2031. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  2032. break;
  2033. case AR_OBJECT_STRUCTURED_BUFFER:
  2034. *intrinsics = g_StructuredBufferMethods;
  2035. *intrinsicCount = _countof(g_StructuredBufferMethods);
  2036. break;
  2037. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  2038. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  2039. *intrinsics = g_RWStructuredBufferMethods;
  2040. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  2041. break;
  2042. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  2043. *intrinsics = g_AppendStructuredBufferMethods;
  2044. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  2045. break;
  2046. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  2047. *intrinsics = g_ConsumeStructuredBufferMethods;
  2048. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  2049. break;
  2050. case AR_OBJECT_RAY_QUERY:
  2051. *intrinsics = g_RayQueryMethods;
  2052. *intrinsicCount = _countof(g_RayQueryMethods);
  2053. break;
  2054. // SPIRV change starts
  2055. #ifdef ENABLE_SPIRV_CODEGEN
  2056. case AR_OBJECT_VK_SUBPASS_INPUT:
  2057. *intrinsics = g_VkSubpassInputMethods;
  2058. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  2059. break;
  2060. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  2061. *intrinsics = g_VkSubpassInputMSMethods;
  2062. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  2063. break;
  2064. #endif // ENABLE_SPIRV_CODEGEN
  2065. // SPIRV change ends
  2066. default:
  2067. *intrinsics = nullptr;
  2068. *intrinsicCount = 0;
  2069. break;
  2070. }
  2071. }
  2072. static
  2073. bool IsRowOrColumnVariable(size_t value)
  2074. {
  2075. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  2076. }
  2077. static
  2078. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  2079. {
  2080. return
  2081. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  2082. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  2083. value == LICOMPTYPE_ANY_FLOAT || // float or double
  2084. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  2085. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  2086. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  2087. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  2088. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  2089. value == LICOMPTYPE_ANY; // any time
  2090. }
  2091. static
  2092. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  2093. {
  2094. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  2095. }
  2096. static
  2097. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  2098. {
  2099. // Note that LITEMPLATE_OBJECT can accept different types, but it
  2100. // specifies a single 'layout'. In practice, this information is used
  2101. // together with a component type that specifies a single object.
  2102. return value == LITEMPLATE_ANY; // Any layout
  2103. }
  2104. static
  2105. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  2106. {
  2107. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  2108. }
  2109. static
  2110. bool TemplateHasDefaultType(ArBasicKind kind)
  2111. {
  2112. switch (kind) {
  2113. case AR_OBJECT_BUFFER:
  2114. case AR_OBJECT_TEXTURE1D:
  2115. case AR_OBJECT_TEXTURE2D:
  2116. case AR_OBJECT_TEXTURE3D:
  2117. case AR_OBJECT_TEXTURE1D_ARRAY:
  2118. case AR_OBJECT_TEXTURE2D_ARRAY:
  2119. case AR_OBJECT_TEXTURECUBE:
  2120. case AR_OBJECT_TEXTURECUBE_ARRAY:
  2121. // SPIRV change starts
  2122. #ifdef ENABLE_SPIRV_CODEGEN
  2123. case AR_OBJECT_VK_SUBPASS_INPUT:
  2124. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  2125. #endif // ENABLE_SPIRV_CODEGEN
  2126. // SPIRV change ends
  2127. return true;
  2128. default:
  2129. // Objects with default types return true. Everything else is false.
  2130. return false;
  2131. }
  2132. }
  2133. /// <summary>
  2134. /// Use this class to iterate over intrinsic definitions that come from an external source.
  2135. /// </summary>
  2136. class IntrinsicTableDefIter
  2137. {
  2138. private:
  2139. StringRef _typeName;
  2140. StringRef _functionName;
  2141. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  2142. const HLSL_INTRINSIC* _tableIntrinsic;
  2143. UINT64 _tableLookupCookie;
  2144. unsigned _tableIndex;
  2145. unsigned _argCount;
  2146. bool _firstChecked;
  2147. IntrinsicTableDefIter(
  2148. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2149. StringRef typeName,
  2150. StringRef functionName,
  2151. unsigned argCount) :
  2152. _typeName(typeName), _functionName(functionName), _tables(tables),
  2153. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  2154. _argCount(argCount), _firstChecked(false)
  2155. {
  2156. }
  2157. void CheckForIntrinsic() {
  2158. if (_tableIndex >= _tables.size()) {
  2159. return;
  2160. }
  2161. _firstChecked = true;
  2162. // TODO: review this - this will allocate at least once per string
  2163. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  2164. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  2165. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  2166. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  2167. _tableLookupCookie = 0;
  2168. _tableIntrinsic = nullptr;
  2169. }
  2170. }
  2171. void MoveToNext() {
  2172. for (;;) {
  2173. // If we don't have an intrinsic, try the following table.
  2174. if (_firstChecked && _tableIntrinsic == nullptr) {
  2175. _tableIndex++;
  2176. }
  2177. CheckForIntrinsic();
  2178. if (_tableIndex == _tables.size() ||
  2179. (_tableIntrinsic != nullptr &&
  2180. _tableIntrinsic->uNumArgs ==
  2181. (_argCount + 1))) // uNumArgs includes return
  2182. break;
  2183. }
  2184. }
  2185. public:
  2186. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2187. StringRef typeName,
  2188. StringRef functionName,
  2189. unsigned argCount)
  2190. {
  2191. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  2192. return result;
  2193. }
  2194. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  2195. {
  2196. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  2197. result._tableIndex = tables.size();
  2198. return result;
  2199. }
  2200. bool operator!=(const IntrinsicTableDefIter& other)
  2201. {
  2202. if (!_firstChecked) {
  2203. MoveToNext();
  2204. }
  2205. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  2206. }
  2207. const HLSL_INTRINSIC* operator*()
  2208. {
  2209. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  2210. return _tableIntrinsic;
  2211. }
  2212. LPCSTR GetTableName()
  2213. {
  2214. LPCSTR tableName = nullptr;
  2215. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  2216. return nullptr;
  2217. }
  2218. return tableName;
  2219. }
  2220. LPCSTR GetLoweringStrategy()
  2221. {
  2222. LPCSTR lowering = nullptr;
  2223. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  2224. return nullptr;
  2225. }
  2226. return lowering;
  2227. }
  2228. IntrinsicTableDefIter& operator++()
  2229. {
  2230. MoveToNext();
  2231. return *this;
  2232. }
  2233. };
  2234. /// <summary>
  2235. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2236. /// </summary>
  2237. class IntrinsicDefIter
  2238. {
  2239. const HLSL_INTRINSIC* _current;
  2240. const HLSL_INTRINSIC* _end;
  2241. IntrinsicTableDefIter _tableIter;
  2242. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2243. _current(value), _end(end), _tableIter(tableIter)
  2244. { }
  2245. public:
  2246. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2247. {
  2248. return IntrinsicDefIter(start, table + count, tableIter);
  2249. }
  2250. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2251. {
  2252. return IntrinsicDefIter(table + count, table + count, tableIter);
  2253. }
  2254. bool operator!=(const IntrinsicDefIter& other)
  2255. {
  2256. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2257. }
  2258. const HLSL_INTRINSIC* operator*()
  2259. {
  2260. return (_current != _end) ? _current : *_tableIter;
  2261. }
  2262. LPCSTR GetTableName()
  2263. {
  2264. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2265. }
  2266. LPCSTR GetLoweringStrategy()
  2267. {
  2268. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2269. }
  2270. IntrinsicDefIter& operator++()
  2271. {
  2272. if (_current != _end) {
  2273. const HLSL_INTRINSIC* next = _current + 1;
  2274. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2275. _current = next;
  2276. }
  2277. else {
  2278. _current = _end;
  2279. }
  2280. } else {
  2281. ++_tableIter;
  2282. }
  2283. return *this;
  2284. }
  2285. };
  2286. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2287. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2288. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2289. }
  2290. static void CreateSimpleField(clang::ASTContext &context, CXXRecordDecl *recordDecl, StringRef Name,
  2291. QualType Ty, AccessSpecifier access = AccessSpecifier::AS_public) {
  2292. IdentifierInfo &fieldId =
  2293. context.Idents.get(Name, tok::TokenKind::identifier);
  2294. TypeSourceInfo *filedTypeSource = context.getTrivialTypeSourceInfo(Ty, NoLoc);
  2295. const bool MutableFalse = false;
  2296. const InClassInitStyle initStyle = InClassInitStyle::ICIS_NoInit;
  2297. FieldDecl *fieldDecl =
  2298. FieldDecl::Create(context, recordDecl, NoLoc, NoLoc, &fieldId, Ty,
  2299. filedTypeSource, nullptr, MutableFalse, initStyle);
  2300. fieldDecl->setAccess(access);
  2301. fieldDecl->setImplicit(true);
  2302. recordDecl->addDecl(fieldDecl);
  2303. }
  2304. // struct RayDesc
  2305. //{
  2306. // float3 Origin;
  2307. // float TMin;
  2308. // float3 Direction;
  2309. // float TMax;
  2310. //};
  2311. static CXXRecordDecl *CreateRayDescStruct(clang::ASTContext &context,
  2312. QualType float3Ty) {
  2313. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  2314. IdentifierInfo &rayDesc =
  2315. context.Idents.get(StringRef("RayDesc"), tok::TokenKind::identifier);
  2316. CXXRecordDecl *rayDescDecl = CXXRecordDecl::Create(
  2317. context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc,
  2318. &rayDesc, nullptr, DelayTypeCreationTrue);
  2319. rayDescDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2320. rayDescDecl->startDefinition();
  2321. QualType floatTy = context.FloatTy;
  2322. // float3 Origin;
  2323. CreateSimpleField(context, rayDescDecl, "Origin", float3Ty);
  2324. // float TMin;
  2325. CreateSimpleField(context, rayDescDecl, "TMin", floatTy);
  2326. // float3 Direction;
  2327. CreateSimpleField(context, rayDescDecl, "Direction", float3Ty);
  2328. // float TMax;
  2329. CreateSimpleField(context, rayDescDecl, "TMax", floatTy);
  2330. rayDescDecl->completeDefinition();
  2331. // Both declarations need to be present for correct handling.
  2332. currentDeclContext->addDecl(rayDescDecl);
  2333. rayDescDecl->setImplicit(true);
  2334. return rayDescDecl;
  2335. }
  2336. // struct BuiltInTriangleIntersectionAttributes
  2337. // {
  2338. // float2 barycentrics;
  2339. // };
  2340. static CXXRecordDecl *AddBuiltInTriangleIntersectionAttributes(ASTContext& context, QualType baryType) {
  2341. DeclContext *curDC = context.getTranslationUnitDecl();
  2342. IdentifierInfo &attributesId =
  2343. context.Idents.get(StringRef("BuiltInTriangleIntersectionAttributes"),
  2344. tok::TokenKind::identifier);
  2345. CXXRecordDecl *attributesDecl = CXXRecordDecl::Create(
  2346. context, TagTypeKind::TTK_Struct, curDC, NoLoc, NoLoc,
  2347. &attributesId, nullptr, DelayTypeCreationTrue);
  2348. attributesDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2349. attributesDecl->startDefinition();
  2350. // float2 barycentrics;
  2351. CreateSimpleField(context, attributesDecl, "barycentrics", baryType);
  2352. attributesDecl->completeDefinition();
  2353. attributesDecl->setImplicit(true);
  2354. curDC->addDecl(attributesDecl);
  2355. return attributesDecl;
  2356. }
  2357. //
  2358. // Subobjects
  2359. static CXXRecordDecl *StartSubobjectDecl(ASTContext& context, const char *name) {
  2360. IdentifierInfo &id = context.Idents.get(StringRef(name), tok::TokenKind::identifier);
  2361. CXXRecordDecl *decl = CXXRecordDecl::Create( context, TagTypeKind::TTK_Struct,
  2362. context.getTranslationUnitDecl(), NoLoc, NoLoc, &id, nullptr, DelayTypeCreationTrue);
  2363. decl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2364. decl->startDefinition();
  2365. return decl;
  2366. }
  2367. void FinishSubobjectDecl(ASTContext& context, CXXRecordDecl *decl) {
  2368. decl->completeDefinition();
  2369. context.getTranslationUnitDecl()->addDecl(decl);
  2370. decl->setImplicit(true);
  2371. }
  2372. // struct StateObjectConfig
  2373. // {
  2374. // uint32_t Flags;
  2375. // };
  2376. static CXXRecordDecl *CreateSubobjectStateObjectConfig(ASTContext& context) {
  2377. CXXRecordDecl *decl = StartSubobjectDecl(context, "StateObjectConfig");
  2378. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2379. FinishSubobjectDecl(context, decl);
  2380. return decl;
  2381. }
  2382. // struct GlobalRootSignature
  2383. // {
  2384. // string signature;
  2385. // };
  2386. static CXXRecordDecl *CreateSubobjectRootSignature(ASTContext& context, bool global) {
  2387. CXXRecordDecl *decl = StartSubobjectDecl(context, global ? "GlobalRootSignature" : "LocalRootSignature");
  2388. CreateSimpleField(context, decl, "Data", context.HLSLStringTy, AccessSpecifier::AS_private);
  2389. FinishSubobjectDecl(context, decl);
  2390. return decl;
  2391. }
  2392. // struct SubobjectToExportsAssociation
  2393. // {
  2394. // string Subobject;
  2395. // string Exports;
  2396. // };
  2397. static CXXRecordDecl *CreateSubobjectSubobjectToExportsAssoc(ASTContext& context) {
  2398. CXXRecordDecl *decl = StartSubobjectDecl(context, "SubobjectToExportsAssociation");
  2399. CreateSimpleField(context, decl, "Subobject", context.HLSLStringTy, AccessSpecifier::AS_private);
  2400. CreateSimpleField(context, decl, "Exports", context.HLSLStringTy, AccessSpecifier::AS_private);
  2401. FinishSubobjectDecl(context, decl);
  2402. return decl;
  2403. }
  2404. // struct RaytracingShaderConfig
  2405. // {
  2406. // uint32_t MaxPayloadSizeInBytes;
  2407. // uint32_t MaxAttributeSizeInBytes;
  2408. // };
  2409. static CXXRecordDecl *CreateSubobjectRaytracingShaderConfig(ASTContext& context) {
  2410. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingShaderConfig");
  2411. CreateSimpleField(context, decl, "MaxPayloadSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2412. CreateSimpleField(context, decl, "MaxAttributeSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2413. FinishSubobjectDecl(context, decl);
  2414. return decl;
  2415. }
  2416. // struct RaytracingPipelineConfig
  2417. // {
  2418. // uint32_t MaxTraceRecursionDepth;
  2419. // };
  2420. static CXXRecordDecl *CreateSubobjectRaytracingPipelineConfig(ASTContext& context) {
  2421. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingPipelineConfig");
  2422. CreateSimpleField(context, decl, "MaxTraceRecursionDepth", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2423. FinishSubobjectDecl(context, decl);
  2424. return decl;
  2425. }
  2426. // struct RaytracingPipelineConfig1
  2427. // {
  2428. // uint32_t MaxTraceRecursionDepth;
  2429. // uint32_t Flags;
  2430. // };
  2431. static CXXRecordDecl *
  2432. CreateSubobjectRaytracingPipelineConfig1(ASTContext &context) {
  2433. CXXRecordDecl *decl =
  2434. StartSubobjectDecl(context, "RaytracingPipelineConfig1");
  2435. CreateSimpleField(context, decl, "MaxTraceRecursionDepth",
  2436. context.UnsignedIntTy, AccessSpecifier::AS_private);
  2437. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy,
  2438. AccessSpecifier::AS_private);
  2439. FinishSubobjectDecl(context, decl);
  2440. return decl;
  2441. }
  2442. // struct TriangleHitGroup
  2443. // {
  2444. // string AnyHit;
  2445. // string ClosestHit;
  2446. // };
  2447. static CXXRecordDecl *CreateSubobjectTriangleHitGroup(ASTContext& context) {
  2448. CXXRecordDecl *decl = StartSubobjectDecl(context, "TriangleHitGroup");
  2449. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2450. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2451. FinishSubobjectDecl(context, decl);
  2452. return decl;
  2453. }
  2454. // struct ProceduralPrimitiveHitGroup
  2455. // {
  2456. // string AnyHit;
  2457. // string ClosestHit;
  2458. // string Intersection;
  2459. // };
  2460. static CXXRecordDecl *CreateSubobjectProceduralPrimitiveHitGroup(ASTContext& context) {
  2461. CXXRecordDecl *decl = StartSubobjectDecl(context, "ProceduralPrimitiveHitGroup");
  2462. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2463. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2464. CreateSimpleField(context, decl, "Intersection", context.HLSLStringTy, AccessSpecifier::AS_private);
  2465. FinishSubobjectDecl(context, decl);
  2466. return decl;
  2467. }
  2468. //
  2469. // This is similar to clang/Analysis/CallGraph, but the following differences
  2470. // motivate this:
  2471. //
  2472. // - track traversed vs. observed nodes explicitly
  2473. // - fully visit all reachable functions
  2474. // - merge graph visiting with checking for recursion
  2475. // - track global variables and types used (NYI)
  2476. //
  2477. namespace hlsl {
  2478. struct CallNode {
  2479. FunctionDecl *CallerFn;
  2480. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2481. };
  2482. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2483. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2484. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2485. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2486. // Returns the definition of a function.
  2487. // This serves two purposes - ignore built-in functions, and pick
  2488. // a single Decl * to be used in maps and sets.
  2489. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2490. if (!F) return nullptr;
  2491. if (F->doesThisDeclarationHaveABody()) return F;
  2492. F = F->getFirstDecl();
  2493. for (auto &&Candidate : F->redecls()) {
  2494. if (Candidate->doesThisDeclarationHaveABody()) {
  2495. return Candidate;
  2496. }
  2497. }
  2498. return nullptr;
  2499. }
  2500. // AST visitor that maintains visited and pending collections, as well
  2501. // as recording nodes of caller/callees.
  2502. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2503. private:
  2504. CallNodes &m_callNodes;
  2505. FunctionSet &m_visitedFunctions;
  2506. PendingFunctions &m_pendingFunctions;
  2507. FunctionDecl *m_source;
  2508. CallNodes::iterator m_sourceIt;
  2509. public:
  2510. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2511. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2512. : m_callNodes(callNodes),
  2513. m_visitedFunctions(visitedFunctions),
  2514. m_pendingFunctions(pendingFunctions) {}
  2515. void setSourceFn(FunctionDecl *F) {
  2516. F = getFunctionWithBody(F);
  2517. m_source = F;
  2518. m_sourceIt = m_callNodes.find(F);
  2519. }
  2520. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2521. ValueDecl *valueDecl = ref->getDecl();
  2522. RecordFunctionDecl(dyn_cast_or_null<FunctionDecl>(valueDecl));
  2523. return true;
  2524. }
  2525. bool VisitCXXMemberCallExpr(CXXMemberCallExpr* callExpr)
  2526. {
  2527. RecordFunctionDecl(callExpr->getMethodDecl());
  2528. return true;
  2529. }
  2530. void RecordFunctionDecl(FunctionDecl* funcDecl)
  2531. {
  2532. funcDecl = getFunctionWithBody(funcDecl);
  2533. if (funcDecl) {
  2534. if (m_sourceIt == m_callNodes.end()) {
  2535. auto result = m_callNodes.insert(
  2536. std::make_pair(m_source, CallNode{m_source, {}}));
  2537. DXASSERT(result.second == true,
  2538. "else setSourceFn didn't assign m_sourceIt");
  2539. m_sourceIt = result.first;
  2540. }
  2541. m_sourceIt->second.CalleeFns.insert(funcDecl);
  2542. if (!m_visitedFunctions.count(funcDecl)) {
  2543. m_pendingFunctions.push_back(funcDecl);
  2544. }
  2545. }
  2546. }
  2547. };
  2548. // A call graph that can check for reachability and recursion efficiently.
  2549. class CallGraphWithRecurseGuard {
  2550. private:
  2551. CallNodes m_callNodes;
  2552. FunctionSet m_visitedFunctions;
  2553. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2554. FunctionDecl *D) const {
  2555. if (CallStack.insert(D).second == false)
  2556. return D;
  2557. auto node = m_callNodes.find(D);
  2558. if (node != m_callNodes.end()) {
  2559. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2560. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2561. if (pResult)
  2562. return pResult;
  2563. }
  2564. }
  2565. CallStack.erase(D);
  2566. return nullptr;
  2567. }
  2568. public:
  2569. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2570. DXASSERT_NOMSG(EntryFnDecl);
  2571. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2572. PendingFunctions pendingFunctions;
  2573. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2574. pendingFunctions.push_back(EntryFnDecl);
  2575. while (!pendingFunctions.empty()) {
  2576. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2577. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2578. visitor.setSourceFn(pendingDecl);
  2579. visitor.TraverseDecl(pendingDecl);
  2580. }
  2581. }
  2582. }
  2583. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2584. FnCallStack CallStack;
  2585. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2586. return CheckRecursion(CallStack, EntryFnDecl);
  2587. }
  2588. const CallNodes &GetCallGraph() { return m_callNodes; }
  2589. void dump() const {
  2590. OutputDebugStringW(L"Call Nodes:\r\n");
  2591. for (auto &node : m_callNodes) {
  2592. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), (void*)node.first);
  2593. for (auto callee : node.second.CalleeFns) {
  2594. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), (void*)callee);
  2595. }
  2596. }
  2597. }
  2598. };
  2599. }
  2600. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2601. static
  2602. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2603. {
  2604. DXASSERT_NOMSG(context != nullptr);
  2605. DXASSERT_NOMSG(ident != nullptr);
  2606. DXASSERT_NOMSG(!baseType.isNull());
  2607. DeclContext* declContext = context->getTranslationUnitDecl();
  2608. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2609. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2610. declContext->addDecl(decl);
  2611. decl->setImplicit(true);
  2612. return decl;
  2613. }
  2614. class HLSLExternalSource : public ExternalSemaSource {
  2615. private:
  2616. // Inner types.
  2617. struct FindStructBasicTypeResult {
  2618. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2619. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2620. FindStructBasicTypeResult(ArBasicKind kind,
  2621. unsigned int basicKindAsTypeIndex)
  2622. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2623. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2624. };
  2625. // Declaration for matrix and vector templates.
  2626. ClassTemplateDecl* m_matrixTemplateDecl;
  2627. ClassTemplateDecl* m_vectorTemplateDecl;
  2628. // Namespace decl for hlsl intrinsic functions
  2629. NamespaceDecl* m_hlslNSDecl;
  2630. // Namespace decl for Vulkan-specific intrinsic functions
  2631. NamespaceDecl* m_vkNSDecl;
  2632. // Context being processed.
  2633. _Notnull_ ASTContext* m_context;
  2634. // Semantic analyzer being processed.
  2635. Sema* m_sema;
  2636. // Intrinsic tables available externally.
  2637. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2638. // Scalar types indexed by HLSLScalarType.
  2639. QualType m_scalarTypes[HLSLScalarTypeCount];
  2640. // Scalar types already built.
  2641. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2642. // Matrix types already built indexed by type, row-count, col-count. Should probably move to a sparse map. Instrument to figure out best initial size.
  2643. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2644. // Matrix types already built, in shorthand form.
  2645. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2646. // Vector types already built.
  2647. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2648. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2649. // BuiltinType for each scalar type.
  2650. QualType m_baseTypes[HLSLScalarTypeCount];
  2651. // String type
  2652. QualType m_hlslStringType;
  2653. TypedefDecl* m_hlslStringTypedef;
  2654. // Built-in object types declarations, indexed by basic kind constant.
  2655. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2656. // Map from object decl to the object index.
  2657. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2658. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2659. // Mask for object which not has methods created.
  2660. uint64_t m_objectTypeLazyInitMask;
  2661. UsedIntrinsicStore m_usedIntrinsics;
  2662. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2663. void AddBaseTypes();
  2664. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2665. void AddHLSLScalarTypes();
  2666. /// <summary>Adds string type QualType for HSLS string declarations</summary>
  2667. void AddHLSLStringType();
  2668. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2669. {
  2670. DXASSERT_NOMSG(recordDecl != nullptr);
  2671. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2672. NamedDecl* parameterDecl = parameterList->getParam(0);
  2673. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2674. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2675. return QualType(parmDecl->getTypeForDecl(), 0);
  2676. }
  2677. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2678. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2679. {
  2680. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2681. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2682. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2683. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2684. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2685. if (
  2686. templateRef >= 0 &&
  2687. templateArg->uTemplateId == templateRef &&
  2688. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2689. componentRef >= 0 &&
  2690. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2691. componentArg->uComponentTypeId == 0 &&
  2692. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2693. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2694. !IsRowOrColumnVariable(matrixArg->uRows))
  2695. {
  2696. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2697. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2698. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2699. }
  2700. return QualType();
  2701. }
  2702. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2703. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2704. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2705. _Inout_ size_t* templateParamNamedDeclsCount)
  2706. {
  2707. DXASSERT_NOMSG(name != nullptr);
  2708. DXASSERT_NOMSG(recordDecl != nullptr);
  2709. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2710. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2711. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2712. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2713. // Create the declaration for the template parameter.
  2714. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2715. TemplateTypeParmDecl* templateTypeParmDecl =
  2716. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2717. id, TypenameTrue, ParameterPackFalse);
  2718. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2719. // Create the type that the parameter represents.
  2720. QualType result = m_context->getTemplateTypeParmType(
  2721. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2722. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2723. // it need not concern itself with maintaining this value.
  2724. (*templateParamNamedDeclsCount)++;
  2725. return result;
  2726. }
  2727. // Adds a function specified by the given intrinsic to a record declaration.
  2728. // The template depth will be zero for records that don't have a "template<>" line
  2729. // even if conceptual; or one if it does have one.
  2730. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2731. {
  2732. DXASSERT_NOMSG(recordDecl != nullptr);
  2733. DXASSERT_NOMSG(intrinsic != nullptr);
  2734. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2735. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2736. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2737. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2738. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2739. //
  2740. // Build template parameters, parameter types, and the return type.
  2741. // Parameter declarations are built after the function is created, to use it as their scope.
  2742. //
  2743. unsigned int numParams = intrinsic->uNumArgs - 1;
  2744. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2745. size_t templateParamNamedDeclsCount = 0;
  2746. QualType argsQTs[g_MaxIntrinsicParamCount];
  2747. StringRef argNames[g_MaxIntrinsicParamCount];
  2748. QualType functionResultQT = recordDecl->getASTContext().VoidTy;
  2749. DXASSERT(
  2750. _countof(templateParamNamedDecls) >= numParams + 1,
  2751. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2752. // Handle the return type.
  2753. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2754. // if (functionResultQT.isNull()) {
  2755. // Workaround for template parameter argument count mismatch.
  2756. // Create template parameter for return type always
  2757. // TODO: reenable the check and skip template argument.
  2758. functionResultQT = AddTemplateParamToArray(
  2759. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2760. &templateParamNamedDeclsCount);
  2761. // }
  2762. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2763. InitParamMods(intrinsic, paramMods);
  2764. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2765. // Handle parameters.
  2766. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2767. {
  2768. //
  2769. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2770. //
  2771. // However this may produce template instantiations with equivalent template arguments
  2772. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2773. // but the current intrinsic table has rules that are hard to process in their current form
  2774. // to find all cases.
  2775. //
  2776. char name[g_MaxIntrinsicParamName + 2];
  2777. name[0] = 'T';
  2778. name[1] = '\0';
  2779. strcat_s(name, intrinsic->pArgs[i].pName);
  2780. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2781. // Change out/inout param to reference type.
  2782. if (paramMods[i-1].isAnyOut())
  2783. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2784. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2785. }
  2786. // Create the declaration.
  2787. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2788. DeclarationName declarationName = DeclarationName(ii);
  2789. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2790. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2791. declarationName, true);
  2792. functionDecl->setImplicit(true);
  2793. // If the function is a template function, create the declaration and cross-reference.
  2794. if (templateParamNamedDeclsCount > 0)
  2795. {
  2796. hlsl::CreateFunctionTemplateDecl(
  2797. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2798. }
  2799. }
  2800. // Checks whether the two specified intrinsics generate equivalent templates.
  2801. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2802. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2803. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2804. {
  2805. if (left == right)
  2806. {
  2807. return true;
  2808. }
  2809. if (left == nullptr || right == nullptr)
  2810. {
  2811. return false;
  2812. }
  2813. return (left->uNumArgs == right->uNumArgs &&
  2814. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2815. }
  2816. // Adds all the intrinsic methods that correspond to the specified type.
  2817. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2818. {
  2819. DXASSERT_NOMSG(recordDecl != nullptr);
  2820. DXASSERT_NOMSG(templateDepth >= 0);
  2821. const HLSL_INTRINSIC* intrinsics;
  2822. const HLSL_INTRINSIC* prior = nullptr;
  2823. size_t intrinsicCount;
  2824. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2825. DXASSERT(
  2826. (intrinsics == nullptr) == (intrinsicCount == 0),
  2827. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2828. while (intrinsicCount--)
  2829. {
  2830. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2831. {
  2832. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2833. prior = intrinsics;
  2834. }
  2835. intrinsics++;
  2836. }
  2837. }
  2838. void AddDoubleSubscriptSupport(
  2839. _In_ ClassTemplateDecl* typeDecl,
  2840. _In_ CXXRecordDecl* recordDecl,
  2841. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2842. _In_z_ const char* type0Name,
  2843. _In_z_ const char* type1Name,
  2844. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2845. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2846. {
  2847. DXASSERT_NOMSG(typeDecl != nullptr);
  2848. DXASSERT_NOMSG(recordDecl != nullptr);
  2849. DXASSERT_NOMSG(memberName != nullptr);
  2850. DXASSERT_NOMSG(!elementType.isNull());
  2851. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2852. DXASSERT_NOMSG(type0Name != nullptr);
  2853. DXASSERT_NOMSG(type1Name != nullptr);
  2854. DXASSERT_NOMSG(indexer0Name != nullptr);
  2855. DXASSERT_NOMSG(!indexer0Type.isNull());
  2856. DXASSERT_NOMSG(indexer1Name != nullptr);
  2857. DXASSERT_NOMSG(!indexer1Type.isNull());
  2858. //
  2859. // Add inner types to the templates to represent the following C++ code inside the class.
  2860. // public:
  2861. // class sample_slice_type
  2862. // {
  2863. // public: TElement operator[](uint3 index);
  2864. // };
  2865. // class sample_type
  2866. // {
  2867. // public: sample_slice_type operator[](uint slice);
  2868. // };
  2869. // sample_type sample;
  2870. //
  2871. // Variable names reflect this structure, but this code will also produce the types
  2872. // for .mips access.
  2873. //
  2874. const bool MutableTrue = true;
  2875. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2876. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2877. &m_context->Idents.get(StringRef(type1Name)));
  2878. sampleSliceTypeDecl->setAccess(AS_public);
  2879. sampleSliceTypeDecl->setImplicit();
  2880. recordDecl->addDecl(sampleSliceTypeDecl);
  2881. sampleSliceTypeDecl->startDefinition();
  2882. const bool MutableFalse = false;
  2883. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2884. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2885. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2886. sliceHandleDecl->setAccess(AS_private);
  2887. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2888. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2889. sampleSliceTypeDecl, elementType,
  2890. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2891. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2892. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2893. sampleSliceTypeDecl->completeDefinition();
  2894. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2895. &m_context->Idents.get(StringRef(type0Name)));
  2896. sampleTypeDecl->setAccess(AS_public);
  2897. recordDecl->addDecl(sampleTypeDecl);
  2898. sampleTypeDecl->startDefinition();
  2899. sampleTypeDecl->setImplicit();
  2900. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2901. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2902. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2903. sampleHandleDecl->setAccess(AS_private);
  2904. sampleTypeDecl->addDecl(sampleHandleDecl);
  2905. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2906. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2907. sampleTypeDecl, m_context->getLValueReferenceType(sampleSliceType),
  2908. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2909. sampleTypeDecl->completeDefinition();
  2910. // Add subscript attribute
  2911. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2912. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2913. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2914. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2915. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2916. sampleFieldDecl->setAccess(AS_public);
  2917. recordDecl->addDecl(sampleFieldDecl);
  2918. }
  2919. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2920. _In_ CXXRecordDecl *recordDecl,
  2921. SubscriptOperatorRecord op) {
  2922. DXASSERT_NOMSG(typeDecl != nullptr);
  2923. DXASSERT_NOMSG(recordDecl != nullptr);
  2924. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2925. op.SubscriptCardinality <= 3);
  2926. DXASSERT(op.SubscriptCardinality > 0 ||
  2927. (op.HasMips == false && op.HasSample == false),
  2928. "objects that have .mips or .sample member also have a plain "
  2929. "subscript defined (otherwise static table is "
  2930. "likely incorrect, and this function won't know the cardinality "
  2931. "of the position parameter");
  2932. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2933. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2934. "read/write objects don't have .mips or .sample members");
  2935. // Return early if there is no work to be done.
  2936. if (op.SubscriptCardinality == 0) {
  2937. return;
  2938. }
  2939. const unsigned int templateDepth = 1;
  2940. // Add an operator[].
  2941. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2942. typeDecl->getTemplateParameters()->getParam(0));
  2943. QualType resultType = m_context->getTemplateTypeParmType(
  2944. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2945. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  2946. resultType = m_context->getLValueReferenceType(resultType);
  2947. QualType indexType =
  2948. op.SubscriptCardinality == 1
  2949. ? m_context->UnsignedIntTy
  2950. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2951. op.SubscriptCardinality);
  2952. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2953. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2954. ArrayRef<StringRef>(StringRef("index")),
  2955. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2956. hlsl::CreateFunctionTemplateDecl(
  2957. *m_context, recordDecl, functionDecl,
  2958. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2959. // Add a .mips member if necessary.
  2960. QualType uintType = m_context->UnsignedIntTy;
  2961. if (op.HasMips) {
  2962. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2963. templateTypeParmDecl, "mips_type",
  2964. "mips_slice_type", "mipSlice", uintType, "pos",
  2965. indexType);
  2966. }
  2967. // Add a .sample member if necessary.
  2968. if (op.HasSample) {
  2969. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2970. templateTypeParmDecl, "sample_type",
  2971. "sample_slice_type", "sampleSlice", uintType,
  2972. "pos", indexType);
  2973. // TODO: support operator[][](indexType, uint).
  2974. }
  2975. }
  2976. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2977. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2978. return a.first < b.first;
  2979. };
  2980. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2981. auto begin = m_objectTypeDeclsMap.begin();
  2982. auto end = m_objectTypeDeclsMap.end();
  2983. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2984. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2985. if (low == end)
  2986. return -1;
  2987. if (recordDecl == low->first)
  2988. return low->second;
  2989. else
  2990. return -1;
  2991. }
  2992. #ifdef ENABLE_SPIRV_CODEGEN
  2993. // Adds intrinsic function declarations to the "vk" namespace.
  2994. // It does so only if SPIR-V code generation is being done.
  2995. // Assumes the implicit "vk" namespace has already been created.
  2996. void AddVkIntrinsicFunctions() {
  2997. // If not doing SPIR-V CodeGen, return.
  2998. if (!m_sema->getLangOpts().SPIRV)
  2999. return;
  3000. DXASSERT(m_vkNSDecl, "caller has not created the vk namespace yet");
  3001. auto &context = m_sema->getASTContext();
  3002. for (uint32_t i = 0; i < _countof(g_VkIntrinsics); ++i) {
  3003. const HLSL_INTRINSIC *intrinsic = &g_VkIntrinsics[i];
  3004. const IdentifierInfo &fnII = context.Idents.get(
  3005. intrinsic->pArgs->pName, tok::TokenKind::identifier);
  3006. DeclarationName functionName(&fnII);
  3007. FunctionDecl *functionDecl = FunctionDecl::Create(
  3008. context, m_vkNSDecl, NoLoc, DeclarationNameInfo(functionName, NoLoc),
  3009. /*functionType*/ {}, nullptr, StorageClass::SC_Extern,
  3010. InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  3011. m_vkNSDecl->addDecl(functionDecl);
  3012. functionDecl->setLexicalDeclContext(m_vkNSDecl);
  3013. functionDecl->setDeclContext(m_vkNSDecl);
  3014. functionDecl->setImplicit(true);
  3015. }
  3016. }
  3017. // Adds implicitly defined Vulkan-specific constants to the "vk" namespace.
  3018. // It does so only if SPIR-V code generation is being done.
  3019. // Assumes the implicit "vk" namespace has already been created.
  3020. void AddVkIntrinsicConstants() {
  3021. // If not doing SPIR-V CodeGen, return.
  3022. if (!m_sema->getLangOpts().SPIRV)
  3023. return;
  3024. DXASSERT(m_vkNSDecl, "caller has not created the vk namespace yet");
  3025. for (auto intConst : GetVkIntegerConstants()) {
  3026. const llvm::StringRef name = intConst.first;
  3027. const uint32_t value = intConst.second;
  3028. auto &context = m_sema->getASTContext();
  3029. QualType type = context.getConstType(context.UnsignedIntTy);
  3030. IdentifierInfo &Id = context.Idents.get(name, tok::TokenKind::identifier);
  3031. VarDecl *varDecl =
  3032. VarDecl::Create(context, m_vkNSDecl, NoLoc, NoLoc, &Id, type,
  3033. context.getTrivialTypeSourceInfo(type),
  3034. clang::StorageClass::SC_Static);
  3035. Expr *exprVal = IntegerLiteral::Create(
  3036. context, llvm::APInt(context.getIntWidth(type), value), type, NoLoc);
  3037. varDecl->setInit(exprVal);
  3038. varDecl->setImplicit(true);
  3039. m_vkNSDecl->addDecl(varDecl);
  3040. }
  3041. }
  3042. #endif // ENABLE_SPIRV_CODEGEN
  3043. // Adds all built-in HLSL object types.
  3044. void AddObjectTypes()
  3045. {
  3046. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  3047. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  3048. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  3049. m_objectTypeLazyInitMask = 0;
  3050. unsigned effectKindIndex = 0;
  3051. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  3052. {
  3053. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3054. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  3055. continue;
  3056. }
  3057. if (kind == AR_OBJECT_LEGACY_EFFECT)
  3058. effectKindIndex = i;
  3059. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  3060. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  3061. const char* typeName = g_ArBasicTypeNames[kind];
  3062. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3063. CXXRecordDecl* recordDecl = nullptr;
  3064. if (kind == AR_OBJECT_RAY_DESC) {
  3065. QualType float3Ty = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 3);
  3066. recordDecl = CreateRayDescStruct(*m_context, float3Ty);
  3067. } else if (kind == AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES) {
  3068. QualType float2Type = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 2);
  3069. recordDecl = AddBuiltInTriangleIntersectionAttributes(*m_context, float2Type);
  3070. } else if (IsSubobjectBasicKind(kind)) {
  3071. switch (kind) {
  3072. case AR_OBJECT_STATE_OBJECT_CONFIG:
  3073. recordDecl = CreateSubobjectStateObjectConfig(*m_context);
  3074. break;
  3075. case AR_OBJECT_GLOBAL_ROOT_SIGNATURE:
  3076. recordDecl = CreateSubobjectRootSignature(*m_context, true);
  3077. break;
  3078. case AR_OBJECT_LOCAL_ROOT_SIGNATURE:
  3079. recordDecl = CreateSubobjectRootSignature(*m_context, false);
  3080. break;
  3081. case AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC:
  3082. recordDecl = CreateSubobjectSubobjectToExportsAssoc(*m_context);
  3083. break;
  3084. case AR_OBJECT_RAYTRACING_SHADER_CONFIG:
  3085. recordDecl = CreateSubobjectRaytracingShaderConfig(*m_context);
  3086. break;
  3087. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG:
  3088. recordDecl = CreateSubobjectRaytracingPipelineConfig(*m_context);
  3089. break;
  3090. case AR_OBJECT_TRIANGLE_HIT_GROUP:
  3091. recordDecl = CreateSubobjectTriangleHitGroup(*m_context);
  3092. break;
  3093. case AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP:
  3094. recordDecl = CreateSubobjectProceduralPrimitiveHitGroup(*m_context);
  3095. break;
  3096. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1:
  3097. recordDecl = CreateSubobjectRaytracingPipelineConfig1(*m_context);
  3098. break;
  3099. }
  3100. } else if (kind == AR_OBJECT_CONSTANT_BUFFER) {
  3101. recordDecl = DeclareConstantBufferViewType(*m_context, /*bTBuf*/false);
  3102. } else if (kind == AR_OBJECT_TEXTURE_BUFFER) {
  3103. recordDecl = DeclareConstantBufferViewType(*m_context, /*bTBuf*/true);
  3104. } else if (kind == AR_OBJECT_RAY_QUERY) {
  3105. recordDecl = DeclareRayQueryType(*m_context);
  3106. } else if (kind == AR_OBJECT_HEAP_RESOURCE) {
  3107. recordDecl = DeclareResourceType(*m_context, /*bSampler*/false);
  3108. // create Resource ResourceDescriptorHeap;
  3109. DeclareBuiltinGlobal("ResourceDescriptorHeap",
  3110. m_context->getRecordType(recordDecl), *m_context);
  3111. } else if (kind == AR_OBJECT_HEAP_SAMPLER) {
  3112. recordDecl = DeclareResourceType(*m_context, /*bSampler*/true);
  3113. // create Resource SamplerDescriptorHeap;
  3114. DeclareBuiltinGlobal("SamplerDescriptorHeap",
  3115. m_context->getRecordType(recordDecl), *m_context);
  3116. }
  3117. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D) {
  3118. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2D", "kind");
  3119. }
  3120. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY) {
  3121. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2DArray", "kind");
  3122. }
  3123. else if (templateArgCount == 0) {
  3124. recordDecl = DeclareRecordTypeWithHandle(*m_context, typeName);
  3125. }
  3126. else
  3127. {
  3128. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  3129. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  3130. recordDecl = DeclareTemplateTypeWithHandle(*m_context, typeName, templateArgCount, typeDefault);
  3131. }
  3132. m_objectTypeDecls[i] = recordDecl;
  3133. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  3134. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  3135. }
  3136. // Create an alias for SamplerState. 'sampler' is very commonly used.
  3137. {
  3138. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  3139. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  3140. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  3141. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  3142. currentDeclContext->addDecl(samplerDecl);
  3143. samplerDecl->setImplicit(true);
  3144. // Create decls for each deprecated effect object type:
  3145. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  3146. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  3147. for (unsigned i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  3148. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  3149. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  3150. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  3151. currentDeclContext->addDecl(effectObjDecl);
  3152. effectObjDecl->setImplicit(true);
  3153. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  3154. }
  3155. }
  3156. // Make sure it's in order.
  3157. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  3158. }
  3159. FunctionDecl* AddSubscriptSpecialization(
  3160. _In_ FunctionTemplateDecl* functionTemplate,
  3161. QualType objectElement,
  3162. const FindStructBasicTypeResult& findResult);
  3163. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  3164. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  3165. }
  3166. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  3167. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  3168. }
  3169. static TYPE_CONVERSION_REMARKS RemarksUnused;
  3170. static ImplicitConversionKind ImplicitConversionKindUnused;
  3171. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType,
  3172. ImplicitConversionKind &convKind = ImplicitConversionKindUnused,
  3173. TYPE_CONVERSION_REMARKS &Remarks = RemarksUnused);
  3174. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  3175. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3176. rowCount <= 4 && colCount <= 4);
  3177. TypedefDecl *qts =
  3178. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  3179. if (qts == nullptr) {
  3180. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  3181. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  3182. rowCount, colCount);
  3183. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  3184. }
  3185. return qts;
  3186. }
  3187. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  3188. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3189. colCount <= 4);
  3190. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  3191. if (qts == nullptr) {
  3192. QualType type = LookupVectorType(scalarType, colCount);
  3193. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  3194. colCount);
  3195. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  3196. }
  3197. return qts;
  3198. }
  3199. public:
  3200. HLSLExternalSource() :
  3201. m_matrixTemplateDecl(nullptr),
  3202. m_vectorTemplateDecl(nullptr),
  3203. m_hlslNSDecl(nullptr),
  3204. m_vkNSDecl(nullptr),
  3205. m_context(nullptr),
  3206. m_sema(nullptr),
  3207. m_hlslStringTypedef(nullptr)
  3208. {
  3209. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  3210. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  3211. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  3212. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  3213. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  3214. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  3215. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  3216. }
  3217. ~HLSLExternalSource() { }
  3218. static HLSLExternalSource* FromSema(_In_ Sema* self)
  3219. {
  3220. DXASSERT_NOMSG(self != nullptr);
  3221. ExternalSemaSource* externalSource = self->getExternalSource();
  3222. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  3223. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  3224. return hlsl;
  3225. }
  3226. void InitializeSema(Sema& S) override
  3227. {
  3228. auto &context = S.getASTContext();
  3229. m_sema = &S;
  3230. S.addExternalSource(this);
  3231. AddObjectTypes();
  3232. AddStdIsEqualImplementation(context, S);
  3233. for (auto && intrinsic : m_intrinsicTables) {
  3234. AddIntrinsicTableMethods(intrinsic);
  3235. }
  3236. #ifdef ENABLE_SPIRV_CODEGEN
  3237. if (m_sema->getLangOpts().SPIRV) {
  3238. // Create the "vk" namespace which contains Vulkan-specific intrinsics.
  3239. m_vkNSDecl =
  3240. NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3241. /*Inline*/ false, SourceLocation(),
  3242. SourceLocation(), &context.Idents.get("vk"),
  3243. /*PrevDecl*/ nullptr);
  3244. context.getTranslationUnitDecl()->addDecl(m_vkNSDecl);
  3245. // Add Vulkan-specific intrinsics.
  3246. AddVkIntrinsicFunctions();
  3247. AddVkIntrinsicConstants();
  3248. }
  3249. #endif // ENABLE_SPIRV_CODEGEN
  3250. }
  3251. void ForgetSema() override
  3252. {
  3253. m_sema = nullptr;
  3254. }
  3255. Sema* getSema() {
  3256. return m_sema;
  3257. }
  3258. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  3259. // We shouldn't create Typedef for built in scalar types.
  3260. // For built in scalar types, this funciton may be called for
  3261. // TypoCorrection. In that case, we return a nullptr.
  3262. if (m_scalarTypes[scalarType].isNull()) {
  3263. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  3264. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  3265. }
  3266. return m_scalarTypeDefs[scalarType];
  3267. }
  3268. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  3269. {
  3270. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  3271. if (qt.isNull()) {
  3272. // lazy initialization of scalar types
  3273. if (m_scalarTypes[scalarType].isNull()) {
  3274. LookupScalarTypeDef(scalarType);
  3275. }
  3276. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  3277. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  3278. }
  3279. return qt;
  3280. }
  3281. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  3282. {
  3283. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  3284. if (qt.isNull()) {
  3285. if (m_scalarTypes[scalarType].isNull()) {
  3286. LookupScalarTypeDef(scalarType);
  3287. }
  3288. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  3289. m_vectorTypes[scalarType][colCount - 1] = qt;
  3290. }
  3291. return qt;
  3292. }
  3293. TypedefDecl* GetStringTypedef() {
  3294. if (m_hlslStringTypedef == nullptr) {
  3295. m_hlslStringTypedef = CreateGlobalTypedef(m_context, "string", m_hlslStringType);
  3296. m_hlslStringType = m_context->getTypeDeclType(m_hlslStringTypedef);
  3297. }
  3298. DXASSERT_NOMSG(m_hlslStringTypedef != nullptr);
  3299. return m_hlslStringTypedef;
  3300. }
  3301. static bool IsSubobjectBasicKind(ArBasicKind kind) {
  3302. return kind >= AR_OBJECT_STATE_OBJECT_CONFIG && kind <= AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1;
  3303. }
  3304. bool IsSubobjectType(QualType type) {
  3305. return IsSubobjectBasicKind(GetTypeElementKind(type));
  3306. }
  3307. bool IsRayQueryBasicKind(ArBasicKind kind) {
  3308. return kind == AR_OBJECT_RAY_QUERY;
  3309. }
  3310. bool IsRayQueryType(QualType type) {
  3311. return IsRayQueryBasicKind(GetTypeElementKind(type));
  3312. }
  3313. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  3314. // TODO: enalbe this once we introduce precise master option
  3315. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  3316. if (type == HLSLScalarType_int_min12) {
  3317. const char *PromotedType =
  3318. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  3319. : HLSLScalarTypeNames[HLSLScalarType_int16];
  3320. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3321. << HLSLScalarTypeNames[type] << PromotedType;
  3322. } else if (type == HLSLScalarType_float_min10) {
  3323. const char *PromotedType =
  3324. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  3325. : HLSLScalarTypeNames[HLSLScalarType_float16];
  3326. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3327. << HLSLScalarTypeNames[type] << PromotedType;
  3328. }
  3329. if (!UseMinPrecision) {
  3330. if (type == HLSLScalarType_float_min16) {
  3331. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3332. << HLSLScalarTypeNames[type]
  3333. << HLSLScalarTypeNames[HLSLScalarType_float16];
  3334. } else if (type == HLSLScalarType_int_min16) {
  3335. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3336. << HLSLScalarTypeNames[type]
  3337. << HLSLScalarTypeNames[HLSLScalarType_int16];
  3338. } else if (type == HLSLScalarType_uint_min16) {
  3339. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3340. << HLSLScalarTypeNames[type]
  3341. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  3342. }
  3343. }
  3344. }
  3345. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  3346. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  3347. switch (type) {
  3348. case HLSLScalarType_float16:
  3349. case HLSLScalarType_float32:
  3350. case HLSLScalarType_float64:
  3351. case HLSLScalarType_int16:
  3352. case HLSLScalarType_int32:
  3353. case HLSLScalarType_uint16:
  3354. case HLSLScalarType_uint32:
  3355. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  3356. << HLSLScalarTypeNames[type] << "2018";
  3357. return false;
  3358. default:
  3359. break;
  3360. }
  3361. }
  3362. if (getSema()->getLangOpts().UseMinPrecision) {
  3363. switch (type) {
  3364. case HLSLScalarType_float16:
  3365. case HLSLScalarType_int16:
  3366. case HLSLScalarType_uint16:
  3367. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  3368. << HLSLScalarTypeNames[type];
  3369. return false;
  3370. default:
  3371. break;
  3372. }
  3373. }
  3374. return true;
  3375. }
  3376. bool LookupUnqualified(LookupResult &R, Scope *S) override
  3377. {
  3378. const DeclarationNameInfo declName = R.getLookupNameInfo();
  3379. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3380. if (idInfo == nullptr) {
  3381. return false;
  3382. }
  3383. // Currently template instantiation is blocked when a fatal error is
  3384. // detected. So no faulting-in types at this point, instead we simply
  3385. // back out.
  3386. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  3387. return false;
  3388. }
  3389. StringRef nameIdentifier = idInfo->getName();
  3390. HLSLScalarType parsedType;
  3391. int rowCount;
  3392. int colCount;
  3393. // Try parsing hlsl scalar types that is not initialized at AST time.
  3394. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  3395. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  3396. if (rowCount == 0 && colCount == 0) { // scalar
  3397. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  3398. if (!typeDecl) return false;
  3399. R.addDecl(typeDecl);
  3400. }
  3401. else if (rowCount == 0) { // vector
  3402. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  3403. R.addDecl(qts);
  3404. }
  3405. else { // matrix
  3406. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  3407. R.addDecl(qts);
  3408. }
  3409. return true;
  3410. }
  3411. // string
  3412. else if (TryParseString(nameIdentifier.data(), nameIdentifier.size(), getSema()->getLangOpts())) {
  3413. TypedefDecl *strDecl = GetStringTypedef();
  3414. R.addDecl(strDecl);
  3415. }
  3416. return false;
  3417. }
  3418. /// <summary>
  3419. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  3420. /// </sumary>
  3421. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  3422. {
  3423. DXASSERT_NOMSG(type != nullptr);
  3424. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3425. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3426. if (templateSpecializationDecl) {
  3427. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  3428. if (decl == m_matrixTemplateDecl)
  3429. return AR_TOBJ_MATRIX;
  3430. else if (decl == m_vectorTemplateDecl)
  3431. return AR_TOBJ_VECTOR;
  3432. DXASSERT(decl->isImplicit(), "otherwise object template decl is not set to implicit");
  3433. return AR_TOBJ_OBJECT;
  3434. }
  3435. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3436. if (typeRecordDecl->getDeclContext()->isFileContext()) {
  3437. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3438. if (index != -1) {
  3439. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  3440. if ( AR_OBJECT_RAY_DESC == kind || AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES == kind)
  3441. return AR_TOBJ_COMPOUND;
  3442. }
  3443. return AR_TOBJ_OBJECT;
  3444. }
  3445. else
  3446. return AR_TOBJ_INNER_OBJ;
  3447. }
  3448. return AR_TOBJ_COMPOUND;
  3449. }
  3450. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  3451. bool IsBuiltInObjectType(QualType type)
  3452. {
  3453. type = GetStructuralForm(type);
  3454. if (!type.isNull() && type->isStructureOrClassType()) {
  3455. const RecordType* recordType = type->getAs<RecordType>();
  3456. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  3457. }
  3458. return false;
  3459. }
  3460. /// <summary>
  3461. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  3462. /// possibly refering to original template record if it's a specialization; this makes the result
  3463. /// suitable for looking up in initialization tables.
  3464. /// </summary>
  3465. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  3466. {
  3467. const CXXRecordDecl* recordDecl;
  3468. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  3469. {
  3470. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  3471. }
  3472. else
  3473. {
  3474. recordDecl = dyn_cast<CXXRecordDecl>(context);
  3475. }
  3476. return recordDecl;
  3477. }
  3478. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  3479. ArTypeObjectKind GetTypeObjectKind(QualType type)
  3480. {
  3481. DXASSERT_NOMSG(!type.isNull());
  3482. type = GetStructuralForm(type);
  3483. if (type->isVoidType()) return AR_TOBJ_VOID;
  3484. if (type->isArrayType()) {
  3485. return hlsl::IsArrayConstantStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_ARRAY;
  3486. }
  3487. if (type->isPointerType()) {
  3488. return hlsl::IsPointerStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_POINTER;
  3489. }
  3490. if (type->isStructureOrClassType()) {
  3491. const RecordType* recordType = type->getAs<RecordType>();
  3492. return ClassifyRecordType(recordType);
  3493. } else if (const InjectedClassNameType *ClassNameTy =
  3494. type->getAs<InjectedClassNameType>()) {
  3495. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  3496. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  3497. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3498. if (templateSpecializationDecl) {
  3499. ClassTemplateDecl *decl =
  3500. templateSpecializationDecl->getSpecializedTemplate();
  3501. if (decl == m_matrixTemplateDecl)
  3502. return AR_TOBJ_MATRIX;
  3503. else if (decl == m_vectorTemplateDecl)
  3504. return AR_TOBJ_VECTOR;
  3505. DXASSERT(decl->isImplicit(),
  3506. "otherwise object template decl is not set to implicit");
  3507. return AR_TOBJ_OBJECT;
  3508. }
  3509. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3510. if (typeRecordDecl->getDeclContext()->isFileContext())
  3511. return AR_TOBJ_OBJECT;
  3512. else
  3513. return AR_TOBJ_INNER_OBJ;
  3514. }
  3515. return AR_TOBJ_COMPOUND;
  3516. }
  3517. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  3518. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  3519. return AR_TOBJ_INVALID;
  3520. }
  3521. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  3522. QualType GetMatrixOrVectorElementType(QualType type)
  3523. {
  3524. type = GetStructuralForm(type);
  3525. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3526. DXASSERT_NOMSG(typeRecordDecl);
  3527. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3528. DXASSERT_NOMSG(templateSpecializationDecl);
  3529. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  3530. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  3531. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  3532. }
  3533. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  3534. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  3535. QualType GetStructuralForm(QualType type)
  3536. {
  3537. if (type.isNull()) {
  3538. return type;
  3539. }
  3540. const ReferenceType *RefType = nullptr;
  3541. const AttributedType *AttrType = nullptr;
  3542. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  3543. (AttrType = dyn_cast<AttributedType>(type)))
  3544. {
  3545. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  3546. }
  3547. // Despite its name, getCanonicalTypeUnqualified will preserve const for array elements or something
  3548. return QualType(type->getCanonicalTypeUnqualified()->getTypePtr(), 0);
  3549. }
  3550. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  3551. ArBasicKind GetTypeElementKind(QualType type)
  3552. {
  3553. type = GetStructuralForm(type);
  3554. ArTypeObjectKind kind = GetTypeObjectKind(type);
  3555. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  3556. QualType elementType = GetMatrixOrVectorElementType(type);
  3557. return GetTypeElementKind(elementType);
  3558. }
  3559. if (kind == AR_TOBJ_STRING) {
  3560. return type->isArrayType() ? AR_OBJECT_STRING_LITERAL : AR_OBJECT_STRING;
  3561. }
  3562. if (type->isArrayType()) {
  3563. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  3564. return GetTypeElementKind(arrayType->getElementType());
  3565. }
  3566. if (kind == AR_TOBJ_INNER_OBJ) {
  3567. return AR_OBJECT_INNER;
  3568. } else if (kind == AR_TOBJ_OBJECT) {
  3569. // Classify the object as the element type.
  3570. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  3571. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3572. // NOTE: this will likely need to be updated for specialized records
  3573. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  3574. return g_ArBasicKindsAsTypes[index];
  3575. }
  3576. CanQualType canType = type->getCanonicalTypeUnqualified();
  3577. return BasicTypeForScalarType(canType);
  3578. }
  3579. ArBasicKind BasicTypeForScalarType(CanQualType type)
  3580. {
  3581. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  3582. {
  3583. switch (BT->getKind())
  3584. {
  3585. case BuiltinType::Bool: return AR_BASIC_BOOL;
  3586. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  3587. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3588. case BuiltinType::Half: return AR_BASIC_FLOAT16;
  3589. case BuiltinType::HalfFloat: return AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  3590. case BuiltinType::Int: return AR_BASIC_INT32;
  3591. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3592. case BuiltinType::Short: return AR_BASIC_INT16;
  3593. case BuiltinType::UShort: return AR_BASIC_UINT16;
  3594. case BuiltinType::Long: return AR_BASIC_INT32;
  3595. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3596. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3597. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3598. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3599. case BuiltinType::Min16Float: return AR_BASIC_MIN16FLOAT;
  3600. case BuiltinType::Min16Int: return AR_BASIC_MIN16INT;
  3601. case BuiltinType::Min16UInt: return AR_BASIC_MIN16UINT;
  3602. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3603. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3604. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3605. case BuiltinType::Int8_4Packed: return AR_BASIC_INT8_4PACKED;
  3606. case BuiltinType::UInt8_4Packed: return AR_BASIC_UINT8_4PACKED;
  3607. default:
  3608. // Only builtin types that have basickind equivalents.
  3609. break;
  3610. }
  3611. }
  3612. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3613. if (ET->getDecl()->isScopedUsingClassTag())
  3614. return AR_BASIC_ENUM_CLASS;
  3615. return AR_BASIC_ENUM;
  3616. }
  3617. return AR_BASIC_UNKNOWN;
  3618. }
  3619. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3620. DXASSERT_NOMSG(table != nullptr);
  3621. // Function intrinsics are added on-demand, objects get template methods.
  3622. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3623. // Grab information already processed by AddObjectTypes.
  3624. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3625. const char *typeName = g_ArBasicTypeNames[kind];
  3626. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3627. DXASSERT(templateArgCount <= 2, "otherwise a new case has been added");
  3628. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3629. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3630. if (recordDecl == nullptr) {
  3631. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3632. continue;
  3633. }
  3634. // This is a variation of AddObjectMethods using the new table.
  3635. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3636. const HLSL_INTRINSIC *pPrior = nullptr;
  3637. UINT64 lookupCookie = 0;
  3638. CA2W wideTypeName(typeName, CP_UTF8);
  3639. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3640. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3641. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3642. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3643. // NOTE: this only works with the current implementation because
  3644. // intrinsics are alive as long as the table is alive.
  3645. pPrior = pIntrinsic;
  3646. }
  3647. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3648. }
  3649. }
  3650. }
  3651. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3652. DXASSERT_NOMSG(table != nullptr);
  3653. m_intrinsicTables.push_back(table);
  3654. // If already initialized, add methods immediately.
  3655. if (m_sema != nullptr) {
  3656. AddIntrinsicTableMethods(table);
  3657. }
  3658. }
  3659. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3660. {
  3661. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3662. switch (kind) {
  3663. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3664. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3665. case AR_BASIC_FLOAT16: return HLSLScalarType_half;
  3666. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3667. return HLSLScalarType_float;
  3668. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3669. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3670. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3671. case AR_BASIC_INT8: return HLSLScalarType_int;
  3672. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3673. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3674. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3675. case AR_BASIC_INT32: return HLSLScalarType_int;
  3676. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3677. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3678. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3679. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3680. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3681. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3682. case AR_BASIC_INT8_4PACKED: return HLSLScalarType_int8_4packed;
  3683. case AR_BASIC_UINT8_4PACKED: return HLSLScalarType_uint8_4packed;
  3684. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3685. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3686. case AR_BASIC_ENUM: return HLSLScalarType_int;
  3687. default:
  3688. return HLSLScalarType_unknown;
  3689. }
  3690. }
  3691. QualType GetBasicKindType(ArBasicKind kind)
  3692. {
  3693. DXASSERT_VALIDBASICKIND(kind);
  3694. switch (kind) {
  3695. case AR_OBJECT_NULL: return m_context->VoidTy;
  3696. case AR_BASIC_BOOL: return m_context->BoolTy;
  3697. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3698. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3699. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->HalfFloatTy;
  3700. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3701. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3702. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3703. case AR_BASIC_INT8: return m_context->IntTy;
  3704. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3705. case AR_BASIC_INT16: return m_context->ShortTy;
  3706. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3707. case AR_BASIC_INT32: return m_context->IntTy;
  3708. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3709. case AR_BASIC_INT64: return m_context->LongLongTy;
  3710. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3711. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3712. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3713. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3714. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3715. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3716. case AR_BASIC_INT8_4PACKED: return m_scalarTypes[HLSLScalarType_int8_4packed];
  3717. case AR_BASIC_UINT8_4PACKED: return m_scalarTypes[HLSLScalarType_uint8_4packed];
  3718. case AR_BASIC_ENUM: return m_context->IntTy;
  3719. case AR_BASIC_ENUM_CLASS: return m_context->IntTy;
  3720. case AR_OBJECT_STRING: return m_hlslStringType;
  3721. case AR_OBJECT_STRING_LITERAL:
  3722. // m_hlslStringType is defined as 'char *'.
  3723. // for STRING_LITERAL we should use 'const char *'.
  3724. return m_context->getPointerType(m_context->CharTy.withConst());
  3725. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3726. case AR_OBJECT_TEXTURE1D:
  3727. case AR_OBJECT_TEXTURE1D_ARRAY:
  3728. case AR_OBJECT_TEXTURE2D:
  3729. case AR_OBJECT_TEXTURE2D_ARRAY:
  3730. case AR_OBJECT_TEXTURE3D:
  3731. case AR_OBJECT_TEXTURECUBE:
  3732. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3733. case AR_OBJECT_TEXTURE2DMS:
  3734. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3735. case AR_OBJECT_SAMPLER:
  3736. case AR_OBJECT_SAMPLERCOMPARISON:
  3737. case AR_OBJECT_HEAP_RESOURCE:
  3738. case AR_OBJECT_HEAP_SAMPLER:
  3739. case AR_OBJECT_BUFFER:
  3740. case AR_OBJECT_POINTSTREAM:
  3741. case AR_OBJECT_LINESTREAM:
  3742. case AR_OBJECT_TRIANGLESTREAM:
  3743. case AR_OBJECT_INPUTPATCH:
  3744. case AR_OBJECT_OUTPUTPATCH:
  3745. case AR_OBJECT_RWTEXTURE1D:
  3746. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3747. case AR_OBJECT_RWTEXTURE2D:
  3748. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3749. case AR_OBJECT_RWTEXTURE3D:
  3750. case AR_OBJECT_RWBUFFER:
  3751. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3752. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3753. case AR_OBJECT_STRUCTURED_BUFFER:
  3754. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3755. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3756. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3757. case AR_OBJECT_WAVE:
  3758. case AR_OBJECT_ACCELERATION_STRUCT:
  3759. case AR_OBJECT_RAY_DESC:
  3760. case AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES:
  3761. {
  3762. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3763. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3764. size_t index = match - g_ArBasicKindsAsTypes;
  3765. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3766. }
  3767. case AR_OBJECT_SAMPLER1D:
  3768. case AR_OBJECT_SAMPLER2D:
  3769. case AR_OBJECT_SAMPLER3D:
  3770. case AR_OBJECT_SAMPLERCUBE:
  3771. // Turn dimension-typed samplers into sampler states.
  3772. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3773. case AR_OBJECT_STATEBLOCK:
  3774. case AR_OBJECT_RASTERIZER:
  3775. case AR_OBJECT_DEPTHSTENCIL:
  3776. case AR_OBJECT_BLEND:
  3777. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3778. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3779. default:
  3780. return QualType();
  3781. }
  3782. }
  3783. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3784. /// <param name="E">Expression to typecast.</param>
  3785. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3786. ExprResult PromoteToIntIfBool(ExprResult& E);
  3787. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3788. {
  3789. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3790. (void)(qwUsages);
  3791. return type;
  3792. }
  3793. QualType NewSimpleAggregateType(
  3794. _In_ ArTypeObjectKind ExplicitKind,
  3795. _In_ ArBasicKind componentType,
  3796. _In_ UINT64 qwQual,
  3797. _In_ UINT uRows,
  3798. _In_ UINT uCols)
  3799. {
  3800. DXASSERT_VALIDBASICKIND(componentType);
  3801. QualType pType; // The type to return.
  3802. if (componentType < AR_BASIC_COUNT) {
  3803. // If basic numeric, call LookupScalarTypeDef to ensure on-demand
  3804. // initialization
  3805. LookupScalarTypeDef(ScalarTypeForBasic(componentType));
  3806. }
  3807. QualType pEltType = GetBasicKindType(componentType);
  3808. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3809. // TODO: handle adding qualifications like const
  3810. pType = NewQualifiedType(
  3811. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3812. pEltType);
  3813. if (uRows > 1 ||
  3814. uCols > 1 ||
  3815. ExplicitKind == AR_TOBJ_VECTOR ||
  3816. ExplicitKind == AR_TOBJ_MATRIX)
  3817. {
  3818. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3819. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3820. if ((uRows == 1 &&
  3821. ExplicitKind != AR_TOBJ_MATRIX) ||
  3822. ExplicitKind == AR_TOBJ_VECTOR)
  3823. {
  3824. pType = LookupVectorType(scalarType, uCols);
  3825. }
  3826. else
  3827. {
  3828. pType = LookupMatrixType(scalarType, uRows, uCols);
  3829. }
  3830. // TODO: handle colmajor/rowmajor
  3831. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3832. //{
  3833. // VN(pType = NewQualifiedType(pSrcLoc,
  3834. // qwQual & (AR_QUAL_COLMAJOR |
  3835. // AR_QUAL_ROWMAJOR),
  3836. // pMatrix));
  3837. //}
  3838. //else
  3839. //{
  3840. // pType = pMatrix;
  3841. //}
  3842. }
  3843. return pType;
  3844. }
  3845. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3846. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3847. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3848. /// <param name="Args">Invocation arguments to match.</param>
  3849. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3850. /// <param name="badArgIdx">The first argument to mismatch if any</param>
  3851. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3852. bool MatchArguments(
  3853. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3854. _In_ QualType objectElement,
  3855. _In_ QualType functionTemplateTypeArg,
  3856. _In_ ArrayRef<Expr *> Args,
  3857. _Out_ std::vector<QualType> *,
  3858. _Out_ size_t &badArgIdx);
  3859. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3860. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3861. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3862. bool IsValidateObjectElement(
  3863. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3864. _In_ QualType objectElement);
  3865. // Returns the iterator with the first entry that matches the requirement
  3866. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3867. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3868. size_t tableSize,
  3869. StringRef typeName,
  3870. StringRef nameIdentifier,
  3871. size_t argumentCount)
  3872. {
  3873. // This is implemented by a linear scan for now.
  3874. // We tested binary search on tables, and there was no performance gain on
  3875. // samples probably for the following reasons.
  3876. // 1. The tables are not big enough to make noticable difference
  3877. // 2. The user of this function assumes that it returns the first entry in
  3878. // the table that matches name and argument count. So even in the binary
  3879. // search, we have to scan backwards until the entry does not match the name
  3880. // or arg count. For linear search this is not a problem
  3881. for (unsigned int i = 0; i < tableSize; i++) {
  3882. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3883. const bool isVariadicFn = IsVariadicIntrinsicFunction(pIntrinsic);
  3884. // Do some quick checks to verify size and name.
  3885. if (!isVariadicFn && pIntrinsic->uNumArgs != 1 + argumentCount) {
  3886. continue;
  3887. }
  3888. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3889. continue;
  3890. }
  3891. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3892. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3893. }
  3894. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3895. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3896. }
  3897. bool AddOverloadedCallCandidates(
  3898. UnresolvedLookupExpr *ULE,
  3899. ArrayRef<Expr *> Args,
  3900. OverloadCandidateSet &CandidateSet,
  3901. bool PartialOverloading) override
  3902. {
  3903. DXASSERT_NOMSG(ULE != nullptr);
  3904. const bool isQualified = ULE->getQualifier();
  3905. const bool isGlobalNamespace =
  3906. ULE->getQualifier() &&
  3907. ULE->getQualifier()->getKind() == NestedNameSpecifier::Global;
  3908. const bool isVkNamespace =
  3909. ULE->getQualifier() &&
  3910. ULE->getQualifier()->getKind() == NestedNameSpecifier::Namespace &&
  3911. ULE->getQualifier()->getAsNamespace()->getName() == "vk";
  3912. // Intrinsics live in the global namespace, so references to their names
  3913. // should be either unqualified or '::'-prefixed.
  3914. // Exception: Vulkan-specific intrinsics live in the 'vk::' namespace.
  3915. if (isQualified && !isGlobalNamespace && !isVkNamespace) {
  3916. return false;
  3917. }
  3918. const DeclarationNameInfo declName = ULE->getNameInfo();
  3919. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3920. if (idInfo == nullptr)
  3921. {
  3922. return false;
  3923. }
  3924. StringRef nameIdentifier = idInfo->getName();
  3925. const HLSL_INTRINSIC *table = g_Intrinsics;
  3926. auto tableCount = _countof(g_Intrinsics);
  3927. #ifdef ENABLE_SPIRV_CODEGEN
  3928. if (isVkNamespace) {
  3929. table = g_VkIntrinsics;
  3930. tableCount = _countof(g_VkIntrinsics);
  3931. }
  3932. #endif // ENABLE_SPIRV_CODEGEN
  3933. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3934. table, tableCount, StringRef(), nameIdentifier, Args.size());
  3935. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3936. table, tableCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3937. for (;cursor != end; ++cursor)
  3938. {
  3939. // If this is the intrinsic we're interested in, build up a representation
  3940. // of the types we need.
  3941. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3942. LPCSTR tableName = cursor.GetTableName();
  3943. LPCSTR lowering = cursor.GetLoweringStrategy();
  3944. DXASSERT(
  3945. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3946. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3947. std::vector<QualType> functionArgTypes;
  3948. size_t badArgIdx;
  3949. bool argsMatch = MatchArguments(pIntrinsic, QualType(), QualType(), Args, &functionArgTypes, badArgIdx);
  3950. if (!functionArgTypes.size())
  3951. return false;
  3952. // Get or create the overload we're interested in.
  3953. FunctionDecl* intrinsicFuncDecl = nullptr;
  3954. std::pair<UsedIntrinsicStore::iterator, bool> insertResult =
  3955. m_usedIntrinsics.insert(UsedIntrinsic(pIntrinsic, functionArgTypes));
  3956. bool insertedNewValue = insertResult.second;
  3957. if (insertedNewValue)
  3958. {
  3959. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3960. intrinsicFuncDecl = AddHLSLIntrinsicFunction(
  3961. *m_context, isVkNamespace ? m_vkNSDecl : m_hlslNSDecl, tableName,
  3962. lowering, pIntrinsic, &functionArgTypes);
  3963. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3964. }
  3965. else
  3966. {
  3967. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3968. }
  3969. OverloadCandidate& candidate = CandidateSet.addCandidate(Args.size());
  3970. candidate.Function = intrinsicFuncDecl;
  3971. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3972. candidate.Viable = argsMatch;
  3973. CandidateSet.isNewCandidate(intrinsicFuncDecl); // used to insert into set
  3974. if (argsMatch)
  3975. return true;
  3976. if (badArgIdx) {
  3977. candidate.FailureKind = ovl_fail_bad_conversion;
  3978. QualType ParamType = functionArgTypes[badArgIdx];
  3979. candidate.Conversions[badArgIdx-1].setBad(BadConversionSequence::no_conversion, Args[badArgIdx-1], ParamType);
  3980. } else {
  3981. // A less informative error. Needed when the failure relates to the return type
  3982. candidate.FailureKind = ovl_fail_bad_final_conversion;
  3983. }
  3984. }
  3985. return false;
  3986. }
  3987. bool Initialize(ASTContext& context)
  3988. {
  3989. m_context = &context;
  3990. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3991. /*Inline*/ false, SourceLocation(),
  3992. SourceLocation(), &context.Idents.get("hlsl"),
  3993. /*PrevDecl*/ nullptr);
  3994. m_hlslNSDecl->setImplicit();
  3995. AddBaseTypes();
  3996. AddHLSLScalarTypes();
  3997. AddHLSLStringType();
  3998. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  3999. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  4000. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  4001. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  4002. // Initializing built in integers for ray tracing
  4003. AddRaytracingConstants(*m_context);
  4004. AddSamplerFeedbackConstants(*m_context);
  4005. return true;
  4006. }
  4007. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  4008. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  4009. /// <summary>Checks whether the specified type is a scalar type.</summary>
  4010. bool IsScalarType(const QualType& type) {
  4011. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  4012. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  4013. }
  4014. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  4015. bool IsValidVectorSize(size_t length) {
  4016. return 1 <= length && length <= 4;
  4017. }
  4018. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  4019. bool IsValidMatrixColOrRowSize(size_t length) {
  4020. return 1 <= length && length <= 4;
  4021. }
  4022. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  4023. if (type.isNull()) {
  4024. return false;
  4025. }
  4026. if (type.hasQualifiers()) {
  4027. return false;
  4028. }
  4029. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  4030. if (type->getTypeClass() == Type::TemplateTypeParm)
  4031. return true;
  4032. QualType qt = GetStructuralForm(type);
  4033. if (requireScalar) {
  4034. if (!IsScalarType(qt)) {
  4035. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  4036. return false;
  4037. }
  4038. return true;
  4039. }
  4040. else {
  4041. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  4042. if (qt->isArrayType()) {
  4043. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  4044. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  4045. }
  4046. else if (objectKind == AR_TOBJ_VECTOR) {
  4047. bool valid = true;
  4048. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  4049. valid = false;
  4050. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  4051. }
  4052. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  4053. valid = false;
  4054. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  4055. }
  4056. return valid;
  4057. }
  4058. else if (objectKind == AR_TOBJ_MATRIX) {
  4059. bool valid = true;
  4060. UINT rowCount, colCount;
  4061. GetRowsAndCols(type, rowCount, colCount);
  4062. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  4063. valid = false;
  4064. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  4065. }
  4066. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  4067. valid = false;
  4068. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  4069. }
  4070. return valid;
  4071. }
  4072. else if (qt->isStructureType()) {
  4073. const RecordType* recordType = qt->getAsStructureType();
  4074. objectKind = ClassifyRecordType(recordType);
  4075. switch (objectKind)
  4076. {
  4077. case AR_TOBJ_OBJECT:
  4078. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  4079. return false;
  4080. case AR_TOBJ_COMPOUND:
  4081. {
  4082. const RecordDecl* recordDecl = recordType->getDecl();
  4083. RecordDecl::field_iterator begin = recordDecl->field_begin();
  4084. RecordDecl::field_iterator end = recordDecl->field_end();
  4085. bool result = true;
  4086. while (begin != end) {
  4087. const FieldDecl* fieldDecl = *begin;
  4088. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  4089. m_sema->Diag(argLoc, diag::note_field_type_usage)
  4090. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  4091. result = false;
  4092. }
  4093. begin++;
  4094. }
  4095. return result;
  4096. }
  4097. default:
  4098. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  4099. return false;
  4100. }
  4101. }
  4102. else if(IsScalarType(qt)) {
  4103. return true;
  4104. }
  4105. else {
  4106. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  4107. return false;
  4108. }
  4109. }
  4110. }
  4111. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  4112. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  4113. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  4114. _Inout_opt_ StandardConversionSequence* sequence);
  4115. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  4116. void GetConversionForm(
  4117. QualType type,
  4118. bool explicitConversion,
  4119. ArTypeInfo* pTypeInfo);
  4120. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  4121. bool suppressWarnings, bool suppressErrors,
  4122. _Inout_opt_ StandardConversionSequence* sequence);
  4123. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  4124. bool ValidateTypeRequirements(
  4125. SourceLocation loc,
  4126. ArBasicKind elementKind,
  4127. ArTypeObjectKind objectKind,
  4128. bool requiresIntegrals,
  4129. bool requiresNumerics);
  4130. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  4131. /// <param name="OpLoc">Source location for operator.</param>
  4132. /// <param name="Opc">Kind of binary operator.</param>
  4133. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  4134. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  4135. /// <param name="ResultTy">Result type for operator expression.</param>
  4136. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  4137. /// <param name="CompResultTy">Type of computation result.</param>
  4138. void CheckBinOpForHLSL(
  4139. SourceLocation OpLoc,
  4140. BinaryOperatorKind Opc,
  4141. ExprResult& LHS,
  4142. ExprResult& RHS,
  4143. QualType& ResultTy,
  4144. QualType& CompLHSTy,
  4145. QualType& CompResultTy);
  4146. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  4147. /// <param name="OpLoc">Source location for operator.</param>
  4148. /// <param name="Opc">Kind of operator.</param>
  4149. /// <param name="InputExpr">Input expression to the operator.</param>
  4150. /// <param name="VK">Value kind for resulting expression.</param>
  4151. /// <param name="OK">Object kind for resulting expression.</param>
  4152. /// <returns>The result type for the expression.</returns>
  4153. QualType CheckUnaryOpForHLSL(
  4154. SourceLocation OpLoc,
  4155. UnaryOperatorKind Opc,
  4156. ExprResult& InputExpr,
  4157. ExprValueKind& VK,
  4158. ExprObjectKind& OK);
  4159. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  4160. /// <param name="Cond">Vector condition expression.</param>
  4161. /// <param name="LHS">Left hand side.</param>
  4162. /// <param name="RHS">Right hand side.</param>
  4163. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  4164. /// <returns>Result type of vector conditional expression.</returns>
  4165. clang::QualType CheckVectorConditional(
  4166. _In_ ExprResult &Cond,
  4167. _In_ ExprResult &LHS,
  4168. _In_ ExprResult &RHS,
  4169. _In_ SourceLocation QuestionLoc);
  4170. clang::QualType ApplyTypeSpecSignToParsedType(
  4171. _In_ clang::QualType &type,
  4172. _In_ TypeSpecifierSign TSS,
  4173. _In_ SourceLocation Loc
  4174. );
  4175. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  4176. {
  4177. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  4178. {
  4179. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  4180. return true;
  4181. }
  4182. return false;
  4183. }
  4184. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  4185. bool
  4186. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  4187. SourceLocation /* TemplateLoc */,
  4188. TemplateArgumentListInfo &TemplateArgList) {
  4189. DXASSERT_NOMSG(Template != nullptr);
  4190. // Determine which object type the template refers to.
  4191. StringRef templateName = Template->getName();
  4192. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  4193. if (templateName.equals(StringRef("is_same"))) {
  4194. return false;
  4195. }
  4196. // Allow object type for Constant/TextureBuffer.
  4197. if (templateName == "ConstantBuffer" || templateName == "TextureBuffer") {
  4198. if (TemplateArgList.size() == 1) {
  4199. const TemplateArgumentLoc &argLoc = TemplateArgList[0];
  4200. const TemplateArgument &arg = argLoc.getArgument();
  4201. DXASSERT(arg.getKind() == TemplateArgument::ArgKind::Type, "");
  4202. QualType argType = arg.getAsType();
  4203. SourceLocation argSrcLoc = argLoc.getLocation();
  4204. if (IsScalarType(argType) || IsVectorType(m_sema, argType) ||
  4205. IsMatrixType(m_sema, argType) || argType->isArrayType()) {
  4206. m_sema->Diag(argSrcLoc,
  4207. diag::err_hlsl_typeintemplateargument_requires_struct)
  4208. << argType;
  4209. return true;
  4210. }
  4211. if (const RecordType* recordType = argType->getAsStructureType()) {
  4212. if (!recordType->getDecl()->isCompleteDefinition()) {
  4213. m_sema->Diag(argSrcLoc, diag::err_typecheck_decl_incomplete_type)
  4214. << argType;
  4215. return true;
  4216. }
  4217. }
  4218. }
  4219. return false;
  4220. }
  4221. bool isMatrix = Template->getCanonicalDecl() ==
  4222. m_matrixTemplateDecl->getCanonicalDecl();
  4223. bool isVector = Template->getCanonicalDecl() ==
  4224. m_vectorTemplateDecl->getCanonicalDecl();
  4225. bool requireScalar = isMatrix || isVector;
  4226. // Check constraints on the type. Right now we only check that template
  4227. // types are primitive types.
  4228. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  4229. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  4230. SourceLocation argSrcLoc = argLoc.getLocation();
  4231. const TemplateArgument &arg = argLoc.getArgument();
  4232. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  4233. QualType argType = arg.getAsType();
  4234. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  4235. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  4236. return true;
  4237. }
  4238. }
  4239. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  4240. if (isMatrix || isVector) {
  4241. Expr *expr = arg.getAsExpr();
  4242. llvm::APSInt constantResult;
  4243. if (expr != nullptr &&
  4244. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  4245. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  4246. return true;
  4247. }
  4248. }
  4249. }
  4250. }
  4251. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  4252. if (isMatrix || isVector) {
  4253. llvm::APSInt Val = arg.getAsIntegral();
  4254. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  4255. return true;
  4256. }
  4257. }
  4258. }
  4259. }
  4260. return false;
  4261. }
  4262. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  4263. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  4264. /// <param name="functionDeclContext">Declaration context of function.</param>
  4265. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  4266. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  4267. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  4268. void FindIntrinsicTable(
  4269. _In_ DeclContext* functionDeclContext,
  4270. _Outptr_result_z_ const char** name,
  4271. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  4272. _Out_ size_t* intrinsicCount);
  4273. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  4274. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  4275. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  4276. /// <param name="Args">Array of expressions being used as arguments.</param>
  4277. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  4278. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  4279. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  4280. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  4281. FunctionTemplateDecl *FunctionTemplate,
  4282. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  4283. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  4284. clang::OverloadingResult GetBestViableFunction(
  4285. clang::SourceLocation Loc,
  4286. clang::OverloadCandidateSet& set,
  4287. clang::OverloadCandidateSet::iterator& Best);
  4288. /// <summary>
  4289. /// Initializes the specified <paramref name="initSequence" /> describing how
  4290. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  4291. /// </summary>
  4292. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  4293. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  4294. /// <param name="Args">Arguments to the initialization.</param>
  4295. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  4296. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  4297. void InitializeInitSequenceForHLSL(
  4298. const InitializedEntity& Entity,
  4299. const InitializationKind& Kind,
  4300. MultiExprArg Args,
  4301. bool TopLevelOfInitList,
  4302. _Inout_ InitializationSequence* initSequence);
  4303. /// <summary>
  4304. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4305. /// </summary>
  4306. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4307. bool IsConversionToLessOrEqualElements(
  4308. const ExprResult& sourceExpr,
  4309. const QualType& targetType,
  4310. bool explicitConversion);
  4311. /// <summary>
  4312. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4313. /// </summary>
  4314. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4315. bool IsConversionToLessOrEqualElements(
  4316. const QualType& sourceType,
  4317. const QualType& targetType,
  4318. bool explicitConversion);
  4319. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  4320. /// <param name="BaseExpr">Base expression for member access.</param>
  4321. /// <param name="MemberName">Name of member to look up.</param>
  4322. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4323. /// <param name="OpLoc">Location of access operand.</param>
  4324. /// <param name="MemberLoc">Location of member.</param>
  4325. /// <returns>Result of lookup operation.</returns>
  4326. ExprResult LookupMatrixMemberExprForHLSL(
  4327. Expr& BaseExpr,
  4328. DeclarationName MemberName,
  4329. bool IsArrow,
  4330. SourceLocation OpLoc,
  4331. SourceLocation MemberLoc);
  4332. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  4333. /// <param name="BaseExpr">Base expression for member access.</param>
  4334. /// <param name="MemberName">Name of member to look up.</param>
  4335. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4336. /// <param name="OpLoc">Location of access operand.</param>
  4337. /// <param name="MemberLoc">Location of member.</param>
  4338. /// <returns>Result of lookup operation.</returns>
  4339. ExprResult LookupVectorMemberExprForHLSL(
  4340. Expr& BaseExpr,
  4341. DeclarationName MemberName,
  4342. bool IsArrow,
  4343. SourceLocation OpLoc,
  4344. SourceLocation MemberLoc);
  4345. /// <summary>Performs a member lookup on the specified BaseExpr if it's an array.</summary>
  4346. /// <param name="BaseExpr">Base expression for member access.</param>
  4347. /// <param name="MemberName">Name of member to look up.</param>
  4348. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4349. /// <param name="OpLoc">Location of access operand.</param>
  4350. /// <param name="MemberLoc">Location of member.</param>
  4351. /// <returns>Result of lookup operation.</returns>
  4352. ExprResult LookupArrayMemberExprForHLSL(
  4353. Expr& BaseExpr,
  4354. DeclarationName MemberName,
  4355. bool IsArrow,
  4356. SourceLocation OpLoc,
  4357. SourceLocation MemberLoc);
  4358. /// <summary>If E is a scalar, converts it to a 1-element vector. If E is a
  4359. /// Constant/TextureBuffer<T>, converts it to const T.</summary>
  4360. /// <param name="E">Expression to convert.</param>
  4361. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  4362. ExprResult MaybeConvertMemberAccess(_In_ clang::Expr* E);
  4363. clang::Expr *HLSLImpCastToScalar(
  4364. _In_ clang::Sema* self,
  4365. _In_ clang::Expr* From,
  4366. ArTypeObjectKind FromShape,
  4367. ArBasicKind EltKind);
  4368. clang::ExprResult PerformHLSLConversion(
  4369. _In_ clang::Expr* From,
  4370. _In_ clang::QualType targetType,
  4371. _In_ const clang::StandardConversionSequence &SCS,
  4372. _In_ clang::Sema::CheckedConversionKind CCK);
  4373. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  4374. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  4375. /// <summary>
  4376. /// Checks if a static cast can be performed, and performs it if possible.
  4377. /// </summary>
  4378. /// <param name="SrcExpr">Expression to cast.</param>
  4379. /// <param name="DestType">Type to cast SrcExpr to.</param>
  4380. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  4381. /// <param name="OpRange">Source range for the cast operation.</param>
  4382. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  4383. /// <param name="Kind">The kind of operation required for a conversion.</param>
  4384. /// <param name="BasePath">A simple array of base specifiers.</param>
  4385. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  4386. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  4387. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  4388. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  4389. QualType DestType,
  4390. Sema::CheckedConversionKind CCK,
  4391. const SourceRange &OpRange, unsigned &msg,
  4392. CastKind &Kind, CXXCastPath &BasePath,
  4393. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  4394. _Inout_opt_ StandardConversionSequence* standard);
  4395. /// <summary>
  4396. /// Checks if a subscript index argument can be initialized from the given expression.
  4397. /// </summary>
  4398. /// <param name="SrcExpr">Source expression used as argument.</param>
  4399. /// <param name="DestType">Parameter type to initialize.</param>
  4400. /// <remarks>
  4401. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  4402. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  4403. /// </remarks>
  4404. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  4405. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  4406. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  4407. // Everything is ready.
  4408. if (m_objectTypeLazyInitMask == 0)
  4409. return;
  4410. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  4411. int idx = FindObjectBasicKindIndex(recordDecl);
  4412. // Not object type.
  4413. if (idx == -1)
  4414. return;
  4415. uint64_t bit = ((uint64_t)1)<<idx;
  4416. // Already created.
  4417. if ((m_objectTypeLazyInitMask & bit) == 0)
  4418. return;
  4419. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  4420. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  4421. int startDepth = 0;
  4422. if (templateArgCount > 0) {
  4423. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  4424. "otherwise a new case has been added");
  4425. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  4426. AddObjectSubscripts(kind, typeDecl, recordDecl,
  4427. g_ArBasicKindsSubscripts[idx]);
  4428. startDepth = 1;
  4429. }
  4430. AddObjectMethods(kind, recordDecl, startDepth);
  4431. // Clear the object.
  4432. m_objectTypeLazyInitMask &= ~bit;
  4433. }
  4434. FunctionDecl* AddHLSLIntrinsicMethod(
  4435. LPCSTR tableName,
  4436. LPCSTR lowering,
  4437. _In_ const HLSL_INTRINSIC* intrinsic,
  4438. _In_ FunctionTemplateDecl *FunctionTemplate,
  4439. ArrayRef<Expr *> Args,
  4440. _In_count_(parameterTypeCount) QualType* parameterTypes,
  4441. size_t parameterTypeCount)
  4442. {
  4443. DXASSERT_NOMSG(intrinsic != nullptr);
  4444. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  4445. DXASSERT_NOMSG(parameterTypes != nullptr);
  4446. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  4447. // Create the template arguments.
  4448. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  4449. for (size_t i = 0; i < parameterTypeCount; i++) {
  4450. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  4451. }
  4452. // Look for an existing specialization.
  4453. void *InsertPos = nullptr;
  4454. FunctionDecl *SpecFunc =
  4455. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  4456. if (SpecFunc != nullptr) {
  4457. return SpecFunc;
  4458. }
  4459. // Change return type to lvalue reference type for aggregate types
  4460. QualType retTy = parameterTypes[0];
  4461. if (hlsl::IsHLSLAggregateType(retTy))
  4462. parameterTypes[0] = m_context->getLValueReferenceType(retTy);
  4463. // Create a new specialization.
  4464. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  4465. InitParamMods(intrinsic, paramMods);
  4466. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4467. // Change out/inout parameter type to rvalue reference type.
  4468. if (paramMods[i - 1].isAnyOut()) {
  4469. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  4470. }
  4471. }
  4472. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  4473. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  4474. // Remove this when update intrinsic table not affect other things.
  4475. // Change vector<float,1> into float for bias.
  4476. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  4477. DXASSERT(parameterTypeCount > biasOperandID,
  4478. "else operation was misrecognized");
  4479. if (const ExtVectorType *VecTy =
  4480. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  4481. *m_context, parameterTypes[biasOperandID])) {
  4482. if (VecTy->getNumElements() == 1)
  4483. parameterTypes[biasOperandID] = VecTy->getElementType();
  4484. }
  4485. }
  4486. DeclContext *owner = FunctionTemplate->getDeclContext();
  4487. TemplateArgumentList templateArgumentList(
  4488. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  4489. templateArgs.size());
  4490. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4491. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  4492. mlTemplateArgumentList);
  4493. FunctionProtoType::ExtProtoInfo EmptyEPI;
  4494. QualType functionType = m_context->getFunctionType(
  4495. parameterTypes[0],
  4496. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  4497. EmptyEPI, paramMods);
  4498. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4499. FunctionProtoTypeLoc Proto =
  4500. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4501. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  4502. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4503. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  4504. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  4505. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  4506. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  4507. Params.push_back(paramDecl);
  4508. }
  4509. QualType T = TInfo->getType();
  4510. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  4511. CXXMethodDecl* method = CXXMethodDecl::Create(
  4512. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4513. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4514. // Add intrinsic attr
  4515. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  4516. // Record this function template specialization.
  4517. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  4518. *m_context, templateArgs.data(), templateArgs.size());
  4519. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  4520. // Attach the parameters
  4521. for (unsigned P = 0; P < Params.size(); ++P) {
  4522. Params[P]->setOwningFunction(method);
  4523. Proto.setParam(P, Params[P]);
  4524. }
  4525. method->setParams(Params);
  4526. // Adjust access.
  4527. method->setAccess(AccessSpecifier::AS_public);
  4528. FunctionTemplate->setAccess(method->getAccess());
  4529. return method;
  4530. }
  4531. // Overload support.
  4532. UINT64 ScoreCast(QualType leftType, QualType rightType);
  4533. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  4534. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  4535. unsigned GetNumElements(QualType anyType);
  4536. unsigned GetNumBasicElements(QualType anyType);
  4537. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  4538. QualType GetNthElementType(QualType type, unsigned index);
  4539. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  4540. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4541. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4542. };
  4543. TYPE_CONVERSION_REMARKS HLSLExternalSource::RemarksUnused = TYPE_CONVERSION_REMARKS::TYPE_CONVERSION_NONE;
  4544. ImplicitConversionKind HLSLExternalSource::ImplicitConversionKindUnused = ImplicitConversionKind::ICK_Identity;
  4545. // Use this class to flatten a type into HLSL primitives and iterate through them.
  4546. class FlattenedTypeIterator
  4547. {
  4548. private:
  4549. enum FlattenedIterKind {
  4550. FK_Simple,
  4551. FK_Fields,
  4552. FK_Expressions,
  4553. FK_IncompleteArray,
  4554. FK_Bases,
  4555. };
  4556. // Use this struct to represent a specific point in the tracked tree.
  4557. struct FlattenedTypeTracker {
  4558. QualType Type; // Type at this position in the tree.
  4559. unsigned int Count; // Count of consecutive types
  4560. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  4561. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  4562. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  4563. RecordDecl::field_iterator EndField; // STL-style end of fields.
  4564. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  4565. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  4566. FlattenedIterKind IterKind; // Kind of tracker.
  4567. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  4568. FlattenedTypeTracker(QualType type)
  4569. : Type(type), Count(0), CurrentExpr(nullptr),
  4570. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  4571. FlattenedTypeTracker(QualType type, unsigned int count,
  4572. MultiExprArg::iterator expression)
  4573. : Type(type), Count(count), CurrentExpr(expression),
  4574. IterKind(FK_Simple), IsConsidered(false) {}
  4575. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  4576. RecordDecl::field_iterator end)
  4577. : Type(type), Count(0), CurrentField(current), EndField(end),
  4578. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  4579. FlattenedTypeTracker(MultiExprArg::iterator current,
  4580. MultiExprArg::iterator end)
  4581. : Count(0), CurrentExpr(current), EndExpr(end),
  4582. IterKind(FK_Expressions), IsConsidered(false) {}
  4583. FlattenedTypeTracker(QualType type,
  4584. CXXRecordDecl::base_class_iterator current,
  4585. CXXRecordDecl::base_class_iterator end)
  4586. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  4587. IterKind(FK_Bases), IsConsidered(false) {}
  4588. /// <summary>Gets the current expression if one is available.</summary>
  4589. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  4590. /// <summary>Replaces the current expression.</summary>
  4591. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  4592. };
  4593. HLSLExternalSource& m_source; // Source driving the iteration.
  4594. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  4595. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  4596. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  4597. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  4598. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  4599. QualType m_firstType; // Name of first type found, used for diagnostics.
  4600. SourceLocation m_loc; // Location used for diagnostics.
  4601. static const size_t MaxTypeDepth = 100;
  4602. void advanceLeafTracker();
  4603. /// <summary>Consumes leaves.</summary>
  4604. void consumeLeaf();
  4605. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  4606. bool considerLeaf();
  4607. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  4608. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  4609. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  4610. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  4611. public:
  4612. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  4613. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  4614. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  4615. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  4616. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  4617. QualType getCurrentElement() const;
  4618. /// <summary>Get the number of repeated current elements.</summary>
  4619. unsigned int getCurrentElementSize() const;
  4620. /// <summary>Gets the current element's Iterkind.</summary>
  4621. FlattenedIterKind getCurrentElementKind() const { return m_typeTrackers.back().IterKind; }
  4622. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  4623. bool hasCurrentElement() const;
  4624. /// <summary>Consumes count elements on this iterator.</summary>
  4625. void advanceCurrentElement(unsigned int count);
  4626. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  4627. unsigned int countRemaining();
  4628. /// <summary>Gets the current expression if one is available.</summary>
  4629. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  4630. /// <summary>Replaces the current expression.</summary>
  4631. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  4632. struct ComparisonResult
  4633. {
  4634. unsigned int LeftCount;
  4635. unsigned int RightCount;
  4636. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  4637. bool AreElementsEqual;
  4638. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  4639. bool CanConvertElements;
  4640. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  4641. bool IsConvertibleAndEqualLength() const {
  4642. return CanConvertElements && LeftCount == RightCount;
  4643. }
  4644. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  4645. bool IsConvertibleAndLeftLonger() const {
  4646. return CanConvertElements && LeftCount > RightCount;
  4647. }
  4648. bool IsRightLonger() const {
  4649. return RightCount > LeftCount;
  4650. }
  4651. bool IsEqualLength() const {
  4652. return LeftCount == RightCount;
  4653. }
  4654. };
  4655. static ComparisonResult CompareIterators(
  4656. HLSLExternalSource& source, SourceLocation loc,
  4657. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  4658. static ComparisonResult CompareTypes(
  4659. HLSLExternalSource& source,
  4660. SourceLocation leftLoc, SourceLocation rightLoc,
  4661. QualType left, QualType right);
  4662. // Compares the arguments to initialize the left type, modifying them if necessary.
  4663. static ComparisonResult CompareTypesForInit(
  4664. HLSLExternalSource& source, QualType left, MultiExprArg args,
  4665. SourceLocation leftLoc, SourceLocation rightLoc);
  4666. };
  4667. static
  4668. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  4669. {
  4670. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  4671. if (specialization) {
  4672. const TemplateArgumentList& list = specialization->getTemplateArgs();
  4673. if (list.size()) {
  4674. if (list[0].getKind() == TemplateArgument::ArgKind::Type)
  4675. return list[0].getAsType();
  4676. }
  4677. }
  4678. return QualType();
  4679. }
  4680. void HLSLExternalSource::AddBaseTypes()
  4681. {
  4682. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4683. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4684. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4685. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4686. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4687. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->HalfFloatTy : m_context->HalfTy;
  4688. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4689. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4690. m_baseTypes[HLSLScalarType_float_min10] = m_context->Min10FloatTy;
  4691. m_baseTypes[HLSLScalarType_float_min16] = m_context->Min16FloatTy;
  4692. m_baseTypes[HLSLScalarType_int_min12] = m_context->Min12IntTy;
  4693. m_baseTypes[HLSLScalarType_int_min16] = m_context->Min16IntTy;
  4694. m_baseTypes[HLSLScalarType_uint_min16] = m_context->Min16UIntTy;
  4695. m_baseTypes[HLSLScalarType_int8_4packed] = m_context->Int8_4PackedTy;
  4696. m_baseTypes[HLSLScalarType_uint8_4packed] = m_context->UInt8_4PackedTy;
  4697. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4698. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4699. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4700. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4701. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4702. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4703. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4704. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4705. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4706. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4707. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4708. }
  4709. void HLSLExternalSource::AddHLSLScalarTypes()
  4710. {
  4711. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4712. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4713. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4714. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4715. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4716. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4717. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4718. }
  4719. void HLSLExternalSource::AddHLSLStringType() {
  4720. m_hlslStringType = m_context->HLSLStringTy;
  4721. }
  4722. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4723. _In_ FunctionTemplateDecl* functionTemplate,
  4724. QualType objectElement,
  4725. const FindStructBasicTypeResult& findResult)
  4726. {
  4727. DXASSERT_NOMSG(functionTemplate != nullptr);
  4728. DXASSERT_NOMSG(!objectElement.isNull());
  4729. DXASSERT_NOMSG(findResult.Found());
  4730. DXASSERT(
  4731. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4732. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4733. // Subscript is templated only on its return type.
  4734. // Create the template argument.
  4735. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4736. QualType resultType = objectElement;
  4737. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  4738. resultType = m_context->getLValueReferenceType(resultType);
  4739. TemplateArgument templateArgument(resultType);
  4740. unsigned subscriptCardinality =
  4741. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4742. QualType subscriptIndexType =
  4743. subscriptCardinality == 1
  4744. ? m_context->UnsignedIntTy
  4745. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4746. subscriptCardinality);
  4747. // Look for an existing specialization.
  4748. void* InsertPos = nullptr;
  4749. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4750. if (SpecFunc != nullptr) {
  4751. return SpecFunc;
  4752. }
  4753. // Create a new specialization.
  4754. DeclContext* owner = functionTemplate->getDeclContext();
  4755. TemplateArgumentList templateArgumentList(
  4756. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4757. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4758. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4759. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4760. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4761. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4762. QualType functionType = m_context->getFunctionType(
  4763. resultType, subscriptIndexType, templateEPI, None);
  4764. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4765. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4766. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4767. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4768. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4769. QualType T = TInfo->getType();
  4770. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4771. CXXMethodDecl* method = CXXMethodDecl::Create(
  4772. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4773. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4774. // Add subscript attribute
  4775. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4776. // Record this function template specialization.
  4777. method->setFunctionTemplateSpecialization(functionTemplate,
  4778. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4779. // Attach the parameters
  4780. indexerParam->setOwningFunction(method);
  4781. Proto.setParam(0, indexerParam);
  4782. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4783. // Adjust access.
  4784. method->setAccess(AccessSpecifier::AS_public);
  4785. functionTemplate->setAccess(method->getAccess());
  4786. return method;
  4787. }
  4788. /// <summary>
  4789. /// This routine combines Source into Target. If you have a symmetric operation
  4790. /// and want to treat either side equally you should call it twice, swapping the
  4791. /// parameter order.
  4792. /// </summary>
  4793. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4794. _Out_opt_ ArBasicKind *pCombined) {
  4795. if (Target == Source) {
  4796. AssignOpt(Target, pCombined);
  4797. return true;
  4798. }
  4799. if (Source == AR_OBJECT_NULL) {
  4800. // NULL is valid for any object type.
  4801. AssignOpt(Target, pCombined);
  4802. return true;
  4803. }
  4804. switch (Target) {
  4805. AR_BASIC_ROBJECT_CASES:
  4806. if (Source == AR_OBJECT_STATEBLOCK) {
  4807. AssignOpt(Target, pCombined);
  4808. return true;
  4809. }
  4810. break;
  4811. AR_BASIC_TEXTURE_CASES:
  4812. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4813. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4814. AssignOpt(Target, pCombined);
  4815. return true;
  4816. }
  4817. break;
  4818. case AR_OBJECT_SAMPLERCOMPARISON:
  4819. if (Source == AR_OBJECT_STATEBLOCK) {
  4820. AssignOpt(Target, pCombined);
  4821. return true;
  4822. }
  4823. break;
  4824. default:
  4825. // Not a combinable target.
  4826. break;
  4827. }
  4828. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4829. return false;
  4830. }
  4831. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4832. HLSLExternalSource *pHLSLExternalSource) {
  4833. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4834. llvm::APInt val = intLit->getValue();
  4835. unsigned width = val.getActiveBits();
  4836. bool isNeg = val.isNegative();
  4837. if (isNeg) {
  4838. // Signed.
  4839. if (width <= 32)
  4840. return ArBasicKind::AR_BASIC_INT32;
  4841. else
  4842. return ArBasicKind::AR_BASIC_INT64;
  4843. } else {
  4844. // Unsigned.
  4845. if (width <= 32)
  4846. return ArBasicKind::AR_BASIC_UINT32;
  4847. else
  4848. return ArBasicKind::AR_BASIC_UINT64;
  4849. }
  4850. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4851. llvm::APFloat val = floatLit->getValue();
  4852. unsigned width = val.getSizeInBits(val.getSemantics());
  4853. if (width <= 16)
  4854. return ArBasicKind::AR_BASIC_FLOAT16;
  4855. else if (width <= 32)
  4856. return ArBasicKind::AR_BASIC_FLOAT32;
  4857. else
  4858. return AR_BASIC_FLOAT64;
  4859. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4860. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4861. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4862. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4863. kind = ArBasicKind::AR_BASIC_INT32;
  4864. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4865. kind = ArBasicKind::AR_BASIC_INT64;
  4866. }
  4867. return kind;
  4868. } else if (HLSLVectorElementExpr *VEE = dyn_cast<HLSLVectorElementExpr>(litExpr)) {
  4869. return pHLSLExternalSource->GetTypeElementKind(VEE->getType());
  4870. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4871. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4872. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4873. CombineBasicTypes(kind, kind1, &kind);
  4874. return kind;
  4875. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4876. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4877. return kind;
  4878. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4879. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4880. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4881. CombineBasicTypes(kind, kind1, &kind);
  4882. return kind;
  4883. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4884. // Use target Type for cast.
  4885. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4886. return kind;
  4887. } else {
  4888. // Could only be function call.
  4889. CallExpr *CE = cast<CallExpr>(litExpr);
  4890. // TODO: calculate the function call result.
  4891. if (CE->getNumArgs() == 1)
  4892. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4893. else {
  4894. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4895. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4896. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4897. CombineBasicTypes(kind, kindI, &kind);
  4898. }
  4899. return kind;
  4900. }
  4901. }
  4902. }
  4903. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4904. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4905. if (kind == *pCT)
  4906. return true;
  4907. pCT++;
  4908. }
  4909. return false;
  4910. }
  4911. static ArBasicKind
  4912. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4913. unsigned uLegalComponentTypes,
  4914. HLSLExternalSource *pHLSLExternalSource) {
  4915. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4916. ArBasicKind defaultKind = *pCT;
  4917. // Use first none literal kind as defaultKind.
  4918. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4919. ArBasicKind kind = *pCT;
  4920. pCT++;
  4921. // Skip literal type.
  4922. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4923. continue;
  4924. defaultKind = kind;
  4925. break;
  4926. }
  4927. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4928. if (kind == AR_BASIC_LITERAL_INT) {
  4929. // Search for match first.
  4930. // For literal arg which don't affect return type, the search should always success.
  4931. // Unless use literal int on a float parameter.
  4932. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4933. return litKind;
  4934. // Return the default.
  4935. return defaultKind;
  4936. }
  4937. else {
  4938. // Search for float32 first.
  4939. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4940. return AR_BASIC_FLOAT32;
  4941. // Search for float64.
  4942. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4943. return AR_BASIC_FLOAT64;
  4944. // return default.
  4945. return defaultKind;
  4946. }
  4947. }
  4948. _Use_decl_annotations_ bool
  4949. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4950. QualType objectElement) {
  4951. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4952. switch (op) {
  4953. case IntrinsicOp::MOP_Sample:
  4954. case IntrinsicOp::MOP_SampleBias:
  4955. case IntrinsicOp::MOP_SampleCmp:
  4956. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4957. case IntrinsicOp::MOP_SampleGrad:
  4958. case IntrinsicOp::MOP_SampleLevel: {
  4959. ArBasicKind kind = GetTypeElementKind(objectElement);
  4960. UINT uBits = GET_BPROP_BITS(kind);
  4961. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4962. } break;
  4963. default:
  4964. return true;
  4965. }
  4966. }
  4967. _Use_decl_annotations_
  4968. bool HLSLExternalSource::MatchArguments(
  4969. const HLSL_INTRINSIC* pIntrinsic,
  4970. QualType objectElement,
  4971. QualType functionTemplateTypeArg,
  4972. ArrayRef<Expr *> Args,
  4973. std::vector<QualType> *argTypesVector,
  4974. size_t &badArgIdx)
  4975. {
  4976. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4977. DXASSERT_NOMSG(argTypesVector != nullptr);
  4978. std::vector<QualType> &argTypes = *argTypesVector;
  4979. argTypes.clear();
  4980. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  4981. static const UINT UnusedSize = 0xFF;
  4982. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4983. #define CAB(cond,arg) { if (!(cond)) { badArgIdx = (arg); return false; } }
  4984. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4985. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4986. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4987. badArgIdx = MaxIntrinsicArgs;
  4988. // Reset infos
  4989. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4990. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  4991. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  4992. const unsigned retArgIdx = 0;
  4993. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  4994. // Populate the template for each argument.
  4995. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  4996. ArrayRef<Expr*>::iterator end = Args.end();
  4997. size_t iArg = 1;
  4998. for (; iterArg != end; ++iterArg) {
  4999. Expr* pCallArg = *iterArg;
  5000. // If vararg is reached, we can break out of this loop.
  5001. if(pIntrinsic->pArgs[iArg].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5002. break;
  5003. // Check bounds for non-variadic functions.
  5004. if (iArg >= MaxIntrinsicArgs || iArg > pIntrinsic->uNumArgs) {
  5005. // Currently never reached
  5006. badArgIdx = iArg;
  5007. return false;
  5008. }
  5009. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  5010. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  5011. DXASSERT(isVariadic ||
  5012. pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS,
  5013. "found vararg for non-variadic function");
  5014. QualType pType = pCallArg->getType();
  5015. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  5016. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  5017. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_RAYDESC) {
  5018. if (TypeInfoShapeKind == AR_TOBJ_COMPOUND) {
  5019. if (CXXRecordDecl *pDecl = pType->getAsCXXRecordDecl()) {
  5020. int index = FindObjectBasicKindIndex(pDecl);
  5021. if (index != -1 && AR_OBJECT_RAY_DESC == g_ArBasicKindsAsTypes[index]) {
  5022. ++iArg;
  5023. continue;
  5024. }
  5025. }
  5026. }
  5027. m_sema->Diag(pCallArg->getExprLoc(),
  5028. diag::err_hlsl_ray_desc_required);
  5029. badArgIdx = iArg;
  5030. return false;
  5031. }
  5032. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5033. DXASSERT_NOMSG(objectElement.isNull());
  5034. QualType Ty = pCallArg->getType();
  5035. // Must be user define type for LICOMPTYPE_USER_DEFINED_TYPE arg.
  5036. if (TypeInfoShapeKind != AR_TOBJ_COMPOUND) {
  5037. m_sema->Diag(pCallArg->getExprLoc(),
  5038. diag::err_hlsl_no_struct_user_defined_type);
  5039. badArgIdx = iArg;
  5040. return false;
  5041. }
  5042. objectElement = Ty;
  5043. ++iArg;
  5044. continue;
  5045. }
  5046. // If we are a type and templateID requires one, this isn't a match.
  5047. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  5048. || pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5049. ++iArg;
  5050. continue;
  5051. }
  5052. // Verify TypeInfoEltKind can be cast to something legal for this param
  5053. if (AR_BASIC_UNKNOWN != TypeInfoEltKind) {
  5054. for (const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pIntrinsicArg->uLegalComponentTypes];
  5055. AR_BASIC_UNKNOWN != *pCT; pCT++) {
  5056. if (TypeInfoEltKind == *pCT)
  5057. break;
  5058. else if ((TypeInfoEltKind == AR_BASIC_LITERAL_INT && *pCT == AR_BASIC_LITERAL_FLOAT) ||
  5059. (TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT && *pCT == AR_BASIC_LITERAL_INT))
  5060. break;
  5061. else if (*pCT == AR_BASIC_NOCAST) {
  5062. badArgIdx = std::min(badArgIdx, iArg);
  5063. }
  5064. }
  5065. }
  5066. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  5067. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  5068. bool affectRetType =
  5069. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  5070. // For literal arg which don't affect return type, find concrete type.
  5071. // For literal arg affect return type,
  5072. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  5073. // where all argumentss are literal.
  5074. // CombineBasicTypes will cover the rest cases.
  5075. if (!affectRetType) {
  5076. TypeInfoEltKind = ConcreteLiteralType(
  5077. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  5078. }
  5079. }
  5080. UINT TypeInfoCols = 1;
  5081. UINT TypeInfoRows = 1;
  5082. switch (TypeInfoShapeKind) {
  5083. case AR_TOBJ_MATRIX:
  5084. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  5085. break;
  5086. case AR_TOBJ_VECTOR:
  5087. TypeInfoCols = GetHLSLVecSize(pType);
  5088. break;
  5089. case AR_TOBJ_BASIC:
  5090. case AR_TOBJ_OBJECT:
  5091. case AR_TOBJ_STRING:
  5092. break;
  5093. default:
  5094. badArgIdx = std::min(badArgIdx, iArg); // no struct, arrays or void
  5095. }
  5096. DXASSERT(
  5097. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  5098. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  5099. // Compare template
  5100. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  5101. ((AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  5102. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind))) {
  5103. // Unrestricted or truncation of tuples to scalars are allowed
  5104. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  5105. }
  5106. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  5107. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  5108. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  5109. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  5110. // Scalars to tuples can be splatted, scalar to anything else is not allowed
  5111. badArgIdx = std::min(badArgIdx, iArg);
  5112. }
  5113. }
  5114. else {
  5115. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  5116. // Outside of simple splats and truncations, templates must match
  5117. badArgIdx = std::min(badArgIdx, iArg);
  5118. }
  5119. }
  5120. DXASSERT(
  5121. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  5122. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  5123. // Merge ComponentTypes
  5124. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  5125. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  5126. }
  5127. else {
  5128. if (!CombineBasicTypes(
  5129. ComponentType[pIntrinsicArg->uComponentTypeId],
  5130. TypeInfoEltKind,
  5131. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  5132. badArgIdx = std::min(badArgIdx, iArg);
  5133. }
  5134. }
  5135. // Rows
  5136. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  5137. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  5138. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  5139. CAB(uSpecialId < IA_SPECIAL_SLOTS, iArg);
  5140. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  5141. uSpecialSize[uSpecialId] = TypeInfoRows;
  5142. }
  5143. }
  5144. else {
  5145. if (TypeInfoRows < pIntrinsicArg->uRows) {
  5146. badArgIdx = std::min(badArgIdx, iArg);
  5147. }
  5148. }
  5149. }
  5150. // Columns
  5151. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  5152. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  5153. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  5154. CAB(uSpecialId < IA_SPECIAL_SLOTS, iArg);
  5155. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  5156. uSpecialSize[uSpecialId] = TypeInfoCols;
  5157. }
  5158. }
  5159. else {
  5160. if (TypeInfoCols < pIntrinsicArg->uCols) {
  5161. badArgIdx = std::min(badArgIdx, iArg);
  5162. }
  5163. }
  5164. }
  5165. // Usage
  5166. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  5167. if (pCallArg->getType().isConstQualified()) {
  5168. // Can't use a const type in an out or inout parameter.
  5169. badArgIdx = std::min(badArgIdx, iArg);
  5170. }
  5171. }
  5172. iArg++;
  5173. }
  5174. DXASSERT(isVariadic || iterArg == end,
  5175. "otherwise the argument list wasn't fully processed");
  5176. // Default template and component type for return value
  5177. if (pIntrinsic->pArgs[0].qwUsage
  5178. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE
  5179. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_FUNCTION) {
  5180. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs, 0);
  5181. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  5182. Template[pIntrinsic->pArgs[0].uTemplateId] =
  5183. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  5184. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  5185. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  5186. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  5187. // half return type should map to float for min precision
  5188. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  5189. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  5190. getSema()->getLangOpts().UseMinPrecision) {
  5191. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  5192. ArBasicKind::AR_BASIC_FLOAT32;
  5193. }
  5194. else {
  5195. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  5196. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  5197. }
  5198. }
  5199. }
  5200. }
  5201. }
  5202. // Make sure all template, component type, and texture type selections are valid.
  5203. for (size_t i = 0; i < Args.size() + 1; i++) {
  5204. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  5205. // If vararg is reached, we can break out of this loop.
  5206. if(pIntrinsic->pArgs[i].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5207. break;
  5208. // Check template.
  5209. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  5210. || pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5211. continue; // Already verified that this is available.
  5212. }
  5213. if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5214. continue;
  5215. }
  5216. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  5217. if (AR_TOBJ_UNKNOWN != Template[i]) {
  5218. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  5219. Template[i] = *pTT;
  5220. }
  5221. else if(AR_TOBJ_STRING == Template[i] && *pTT == AR_TOBJ_OBJECT) {
  5222. Template[i] = *pTT;
  5223. }
  5224. else {
  5225. while (AR_TOBJ_UNKNOWN != *pTT) {
  5226. if (Template[i] == *pTT)
  5227. break;
  5228. pTT++;
  5229. }
  5230. }
  5231. if (AR_TOBJ_UNKNOWN == *pTT) {
  5232. Template[i] = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates][0];
  5233. badArgIdx = std::min(badArgIdx, i);
  5234. }
  5235. }
  5236. else if (pTT) {
  5237. Template[i] = *pTT;
  5238. }
  5239. // Check component type.
  5240. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  5241. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  5242. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  5243. if (ComponentType[i] == *pCT)
  5244. break;
  5245. pCT++;
  5246. }
  5247. // has to be a strict match
  5248. if (*pCT == AR_BASIC_NOCAST) {
  5249. badArgIdx = std::min(badArgIdx, i);
  5250. // the match has failed, but the types are useful for errors. Present the cannonical overload for error
  5251. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  5252. }
  5253. // If it is an object, see if it can be cast to the first thing in the
  5254. // list, otherwise move on to next intrinsic.
  5255. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  5256. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  5257. badArgIdx = std::min(badArgIdx, i);
  5258. }
  5259. }
  5260. if (AR_BASIC_UNKNOWN == *pCT) {
  5261. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  5262. }
  5263. }
  5264. else if (pCT) {
  5265. ComponentType[i] = *pCT;
  5266. }
  5267. }
  5268. argTypes.resize(1 + Args.size()); // +1 for return type
  5269. // Default to a void return type.
  5270. argTypes[0] = m_context->VoidTy;
  5271. // Default specials sizes.
  5272. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  5273. if (UnusedSize == uSpecialSize[i]) {
  5274. uSpecialSize[i] = 1;
  5275. }
  5276. }
  5277. // Populate argTypes.
  5278. for (size_t i = 0; i <= Args.size(); i++) {
  5279. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  5280. // If vararg is reached, we can break out of this loop.
  5281. if (pArgument->uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5282. break;
  5283. if (!pArgument->qwUsage)
  5284. continue;
  5285. QualType pNewType;
  5286. unsigned int quals = 0; // qualifications for this argument
  5287. // If we have no type, set it to our input type (templatized)
  5288. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  5289. // Use the templated input type, but resize it if the
  5290. // intrinsic's rows/cols isn't 0
  5291. if (pArgument->uRows && pArgument->uCols) {
  5292. UINT uRows, uCols = 0;
  5293. // if type is overriden, use new type size, for
  5294. // now it only supports scalars
  5295. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5296. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5297. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5298. uRows = uSpecialSize[uSpecialId];
  5299. }
  5300. else if (pArgument->uRows > 0) {
  5301. uRows = pArgument->uRows;
  5302. }
  5303. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5304. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5305. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5306. uCols = uSpecialSize[uSpecialId];
  5307. }
  5308. else if (pArgument->uCols > 0) {
  5309. uCols = pArgument->uCols;
  5310. }
  5311. // 1x1 numeric outputs are always scalar.. since these
  5312. // are most flexible
  5313. if ((1 == uCols) && (1 == uRows)) {
  5314. pNewType = objectElement;
  5315. if (pNewType.isNull()) {
  5316. badArgIdx = std::min(badArgIdx, i);
  5317. }
  5318. }
  5319. else {
  5320. // non-scalars unsupported right now since nothing
  5321. // uses it, would have to create either a type
  5322. // list for sub-structures or just resize the
  5323. // given type
  5324. // VH(E_NOTIMPL);
  5325. badArgIdx = std::min(badArgIdx, i);
  5326. }
  5327. }
  5328. else {
  5329. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  5330. if (objectElement.isNull()) {
  5331. badArgIdx = std::min(badArgIdx, i);
  5332. }
  5333. pNewType = objectElement;
  5334. }
  5335. }
  5336. else if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5337. if (functionTemplateTypeArg.isNull()) {
  5338. if (i == 0) {
  5339. // [RW]ByteAddressBuffer.Load, default to uint
  5340. pNewType = m_context->UnsignedIntTy;
  5341. }
  5342. else {
  5343. // [RW]ByteAddressBuffer.Store, default to argument type
  5344. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5345. if (const BuiltinType *BuiltinTy = pNewType->getAs<BuiltinType>()) {
  5346. // For backcompat, ensure that Store(0, 42 or 42.0) matches a uint/float overload
  5347. // rather than a uint64_t/double one.
  5348. if (BuiltinTy->getKind() == BuiltinType::LitInt) {
  5349. pNewType = m_context->UnsignedIntTy;
  5350. } else if (BuiltinTy->getKind() == BuiltinType::LitFloat) {
  5351. pNewType = m_context->FloatTy;
  5352. }
  5353. }
  5354. }
  5355. }
  5356. else {
  5357. pNewType = functionTemplateTypeArg;
  5358. }
  5359. }
  5360. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5361. if (objectElement.isNull()) {
  5362. badArgIdx = std::min(badArgIdx, i);
  5363. }
  5364. pNewType = objectElement;
  5365. }
  5366. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2D
  5367. || pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2DARRAY) {
  5368. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5369. }
  5370. else {
  5371. ArBasicKind pEltType;
  5372. // ComponentType, if the Id is special then it gets the
  5373. // component type from the first component of the type, if
  5374. // we need more (for the second component, e.g.), then we
  5375. // can use more specials, etc.
  5376. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  5377. if (objectElement.isNull()) {
  5378. badArgIdx = std::min(badArgIdx, i);
  5379. return false;
  5380. }
  5381. pEltType = GetTypeElementKind(objectElement);
  5382. if (!IsValidBasicKind(pEltType)) {
  5383. // This can happen with Texture2D<Struct> or other invalid declarations
  5384. badArgIdx = std::min(badArgIdx, i);
  5385. return false;
  5386. }
  5387. }
  5388. else {
  5389. pEltType = ComponentType[pArgument->uComponentTypeId];
  5390. DXASSERT_VALIDBASICKIND(pEltType);
  5391. }
  5392. UINT uRows, uCols;
  5393. // Rows
  5394. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5395. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5396. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5397. uRows = uSpecialSize[uSpecialId];
  5398. }
  5399. else {
  5400. uRows = pArgument->uRows;
  5401. }
  5402. // Cols
  5403. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5404. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5405. CAB(uSpecialId < IA_SPECIAL_SLOTS, i);
  5406. uCols = uSpecialSize[uSpecialId];
  5407. }
  5408. else {
  5409. uCols = pArgument->uCols;
  5410. }
  5411. // Verify that the final results are in bounds.
  5412. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize, i);
  5413. // Const
  5414. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  5415. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  5416. qwQual |= AR_QUAL_CONST;
  5417. DXASSERT_VALIDBASICKIND(pEltType);
  5418. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  5419. }
  5420. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  5421. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  5422. // TODO: support out modifier
  5423. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  5424. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  5425. //}
  5426. }
  5427. // For variadic functions, we need to add the additional arguments here.
  5428. if(isVariadic) {
  5429. for (; iArg <= Args.size(); ++iArg) {
  5430. argTypes[iArg] = Args[iArg - 1]->getType().getNonReferenceType();
  5431. }
  5432. } else {
  5433. DXASSERT(iArg == pIntrinsic->uNumArgs,
  5434. "In the absence of varargs, a successful match would indicate we "
  5435. "have as many arguments and types as the intrinsic template");
  5436. }
  5437. return badArgIdx == MaxIntrinsicArgs;
  5438. #undef CAB
  5439. }
  5440. _Use_decl_annotations_
  5441. HLSLExternalSource::FindStructBasicTypeResult
  5442. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  5443. {
  5444. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5445. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  5446. // may be a simple class, such as RWByteAddressBuffer.
  5447. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  5448. // We save the caller from filtering out other types of context (like the translation unit itself).
  5449. if (recordDecl != nullptr)
  5450. {
  5451. int index = FindObjectBasicKindIndex(recordDecl);
  5452. if (index != -1) {
  5453. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  5454. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  5455. }
  5456. }
  5457. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  5458. }
  5459. _Use_decl_annotations_
  5460. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  5461. {
  5462. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5463. DXASSERT_NOMSG(name != nullptr);
  5464. DXASSERT_NOMSG(intrinsics != nullptr);
  5465. DXASSERT_NOMSG(intrinsicCount != nullptr);
  5466. *intrinsics = nullptr;
  5467. *intrinsicCount = 0;
  5468. *name = nullptr;
  5469. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  5470. if (lookup.Found()) {
  5471. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  5472. *name = g_ArBasicTypeNames[lookup.Kind];
  5473. }
  5474. }
  5475. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  5476. {
  5477. return
  5478. // Arithmetic operators.
  5479. Opc == BinaryOperatorKind::BO_Add ||
  5480. Opc == BinaryOperatorKind::BO_AddAssign ||
  5481. Opc == BinaryOperatorKind::BO_Sub ||
  5482. Opc == BinaryOperatorKind::BO_SubAssign ||
  5483. Opc == BinaryOperatorKind::BO_Rem ||
  5484. Opc == BinaryOperatorKind::BO_RemAssign ||
  5485. Opc == BinaryOperatorKind::BO_Div ||
  5486. Opc == BinaryOperatorKind::BO_DivAssign ||
  5487. Opc == BinaryOperatorKind::BO_Mul ||
  5488. Opc == BinaryOperatorKind::BO_MulAssign;
  5489. }
  5490. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  5491. {
  5492. return
  5493. // Arithmetic-and-assignment operators.
  5494. Opc == BinaryOperatorKind::BO_AddAssign ||
  5495. Opc == BinaryOperatorKind::BO_SubAssign ||
  5496. Opc == BinaryOperatorKind::BO_RemAssign ||
  5497. Opc == BinaryOperatorKind::BO_DivAssign ||
  5498. Opc == BinaryOperatorKind::BO_MulAssign ||
  5499. // Bitwise-and-assignment operators.
  5500. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5501. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5502. Opc == BinaryOperatorKind::BO_AndAssign ||
  5503. Opc == BinaryOperatorKind::BO_OrAssign ||
  5504. Opc == BinaryOperatorKind::BO_XorAssign;
  5505. }
  5506. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  5507. {
  5508. return
  5509. Opc == BinaryOperatorKind::BO_AndAssign ||
  5510. Opc == BinaryOperatorKind::BO_OrAssign ||
  5511. Opc == BinaryOperatorKind::BO_XorAssign;
  5512. }
  5513. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  5514. {
  5515. return
  5516. Opc == BinaryOperatorKind::BO_Shl ||
  5517. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5518. Opc == BinaryOperatorKind::BO_Shr ||
  5519. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5520. Opc == BinaryOperatorKind::BO_And ||
  5521. Opc == BinaryOperatorKind::BO_AndAssign ||
  5522. Opc == BinaryOperatorKind::BO_Or ||
  5523. Opc == BinaryOperatorKind::BO_OrAssign ||
  5524. Opc == BinaryOperatorKind::BO_Xor ||
  5525. Opc == BinaryOperatorKind::BO_XorAssign;
  5526. }
  5527. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  5528. {
  5529. return
  5530. Opc == BinaryOperatorKind::BO_Shl ||
  5531. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5532. Opc == BinaryOperatorKind::BO_Shr ||
  5533. Opc == BinaryOperatorKind::BO_ShrAssign;
  5534. }
  5535. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  5536. {
  5537. return
  5538. Opc == BinaryOperatorKind::BO_EQ ||
  5539. Opc == BinaryOperatorKind::BO_NE;
  5540. }
  5541. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  5542. {
  5543. return
  5544. Opc == BinaryOperatorKind::BO_LT ||
  5545. Opc == BinaryOperatorKind::BO_GT ||
  5546. Opc == BinaryOperatorKind::BO_LE ||
  5547. Opc == BinaryOperatorKind::BO_GE;
  5548. }
  5549. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  5550. {
  5551. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  5552. }
  5553. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  5554. {
  5555. return
  5556. Opc == BinaryOperatorKind::BO_LAnd ||
  5557. Opc == BinaryOperatorKind::BO_LOr;
  5558. }
  5559. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  5560. {
  5561. return
  5562. BinaryOperatorKindIsArithmetic(Opc) ||
  5563. BinaryOperatorKindIsOrderComparison(Opc) ||
  5564. BinaryOperatorKindIsLogical(Opc);
  5565. }
  5566. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  5567. {
  5568. return BinaryOperatorKindIsBitwise(Opc);
  5569. }
  5570. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  5571. {
  5572. return
  5573. BinaryOperatorKindIsBitwise(Opc) ||
  5574. BinaryOperatorKindIsArithmetic(Opc);
  5575. }
  5576. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  5577. {
  5578. return Opc == UnaryOperatorKind::UO_Not;
  5579. }
  5580. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  5581. {
  5582. return
  5583. Opc == UnaryOperatorKind::UO_LNot ||
  5584. Opc == UnaryOperatorKind::UO_Plus ||
  5585. Opc == UnaryOperatorKind::UO_Minus ||
  5586. // The omission in fxc caused objects and structs to accept this.
  5587. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5588. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5589. }
  5590. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  5591. {
  5592. return
  5593. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5594. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5595. }
  5596. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  5597. {
  5598. return
  5599. Opc == UnaryOperatorKind::UO_Not ||
  5600. Opc == UnaryOperatorKind::UO_Plus ||
  5601. Opc == UnaryOperatorKind::UO_Minus;
  5602. }
  5603. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  5604. {
  5605. return
  5606. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5607. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5608. }
  5609. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  5610. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  5611. }
  5612. /// <summary>
  5613. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  5614. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  5615. /// </summary>
  5616. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  5617. {
  5618. return
  5619. value == AR_TOBJ_BASIC ||
  5620. value == AR_TOBJ_MATRIX ||
  5621. value == AR_TOBJ_VECTOR;
  5622. }
  5623. static bool IsBasicKindIntegral(ArBasicKind value)
  5624. {
  5625. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  5626. }
  5627. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  5628. {
  5629. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  5630. }
  5631. static bool IsBasicKindNumeric(ArBasicKind value)
  5632. {
  5633. return GetBasicKindProps(value) & BPROP_NUMERIC;
  5634. }
  5635. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  5636. {
  5637. // An invalid expression is pass-through at this point.
  5638. if (E.isInvalid())
  5639. {
  5640. return E;
  5641. }
  5642. QualType qt = E.get()->getType();
  5643. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  5644. if (elementKind != AR_BASIC_BOOL)
  5645. {
  5646. return E;
  5647. }
  5648. // Construct a scalar/vector/matrix type with the same shape as E.
  5649. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  5650. QualType targetType;
  5651. UINT colCount, rowCount;
  5652. GetRowsAndColsForAny(qt, rowCount, colCount);
  5653. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  5654. if (E.get()->isLValue()) {
  5655. E = m_sema->DefaultLvalueConversion(E.get()).get();
  5656. }
  5657. switch (objectKind)
  5658. {
  5659. case AR_TOBJ_SCALAR:
  5660. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5661. case AR_TOBJ_ARRAY:
  5662. case AR_TOBJ_VECTOR:
  5663. case AR_TOBJ_MATRIX:
  5664. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5665. default:
  5666. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  5667. }
  5668. return E;
  5669. }
  5670. _Use_decl_annotations_
  5671. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  5672. {
  5673. DXASSERT_NOMSG(pTypeInfo != nullptr);
  5674. DXASSERT_NOMSG(!type.isNull());
  5675. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  5676. // TODO: Get* functions used here add up to a bunch of redundant code.
  5677. // Try to inline that here, making it cheaper to use this function
  5678. // when retrieving multiple properties.
  5679. pTypeInfo->ObjKind = GetTypeElementKind(type);
  5680. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  5681. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  5682. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  5683. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  5684. }
  5685. // Highest possible score (i.e., worst possible score).
  5686. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  5687. // Leave the first two score bits to handle higher-level
  5688. // variations like target type.
  5689. #define SCORE_MIN_SHIFT 2
  5690. // Space out scores to allow up to 128 parameters to
  5691. // vary between score sets spill into each other.
  5692. #define SCORE_PARAM_SHIFT 7
  5693. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  5694. if (anyType.isNull()) {
  5695. return 0;
  5696. }
  5697. anyType = GetStructuralForm(anyType);
  5698. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5699. switch (kind) {
  5700. case AR_TOBJ_BASIC:
  5701. case AR_TOBJ_OBJECT:
  5702. case AR_TOBJ_STRING:
  5703. return 1;
  5704. case AR_TOBJ_COMPOUND: {
  5705. // TODO: consider caching this value for perf
  5706. unsigned total = 0;
  5707. const RecordType *recordType = anyType->getAs<RecordType>();
  5708. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5709. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5710. while (fi != fend) {
  5711. total += GetNumElements(fi->getType());
  5712. ++fi;
  5713. }
  5714. return total;
  5715. }
  5716. case AR_TOBJ_ARRAY:
  5717. case AR_TOBJ_MATRIX:
  5718. case AR_TOBJ_VECTOR:
  5719. return GetElementCount(anyType);
  5720. default:
  5721. DXASSERT(kind == AR_TOBJ_VOID,
  5722. "otherwise the type cannot be classified or is not supported");
  5723. return 0;
  5724. }
  5725. }
  5726. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  5727. if (anyType.isNull()) {
  5728. return 0;
  5729. }
  5730. anyType = GetStructuralForm(anyType);
  5731. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5732. switch (kind) {
  5733. case AR_TOBJ_BASIC:
  5734. case AR_TOBJ_OBJECT:
  5735. case AR_TOBJ_STRING:
  5736. return 1;
  5737. case AR_TOBJ_COMPOUND: {
  5738. // TODO: consider caching this value for perf
  5739. unsigned total = 0;
  5740. const RecordType *recordType = anyType->getAs<RecordType>();
  5741. RecordDecl * RD = recordType->getDecl();
  5742. // Take care base.
  5743. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5744. if (CXXRD->getNumBases()) {
  5745. for (const auto &I : CXXRD->bases()) {
  5746. const CXXRecordDecl *BaseDecl =
  5747. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5748. if (BaseDecl->field_empty())
  5749. continue;
  5750. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5751. total += GetNumBasicElements(parentTy);
  5752. }
  5753. }
  5754. }
  5755. RecordDecl::field_iterator fi = RD->field_begin();
  5756. RecordDecl::field_iterator fend = RD->field_end();
  5757. while (fi != fend) {
  5758. total += GetNumBasicElements(fi->getType());
  5759. ++fi;
  5760. }
  5761. return total;
  5762. }
  5763. case AR_TOBJ_ARRAY: {
  5764. unsigned arraySize = GetElementCount(anyType);
  5765. unsigned eltSize = GetNumBasicElements(
  5766. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  5767. return arraySize * eltSize;
  5768. }
  5769. case AR_TOBJ_MATRIX:
  5770. case AR_TOBJ_VECTOR:
  5771. return GetElementCount(anyType);
  5772. default:
  5773. DXASSERT(kind == AR_TOBJ_VOID,
  5774. "otherwise the type cannot be classified or is not supported");
  5775. return 0;
  5776. }
  5777. }
  5778. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  5779. unsigned leftSize,
  5780. QualType rightType,
  5781. unsigned rightSize) {
  5782. // We can convert from a larger type to a smaller
  5783. // but not a smaller type to a larger so default
  5784. // to just comparing the destination size.
  5785. unsigned uElts = leftSize;
  5786. leftType = GetStructuralForm(leftType);
  5787. rightType = GetStructuralForm(rightType);
  5788. if (leftType->isArrayType() && rightType->isArrayType()) {
  5789. //
  5790. // If we're comparing arrays we don't
  5791. // need to compare every element of
  5792. // the arrays since all elements
  5793. // will have the same type.
  5794. // We only need to compare enough
  5795. // elements that we've tried every
  5796. // possible mix of dst and src elements.
  5797. //
  5798. // TODO: handle multidimensional arrays and arrays of arrays
  5799. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  5800. unsigned uDstEltSize = GetNumElements(pDstElt);
  5801. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  5802. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  5803. if (uDstEltSize == uSrcEltSize) {
  5804. uElts = uDstEltSize;
  5805. } else if (uDstEltSize > uSrcEltSize) {
  5806. // If one size is not an even multiple of the other we need to let the
  5807. // full compare run in order to try all alignments.
  5808. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5809. uElts = uDstEltSize;
  5810. }
  5811. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5812. uElts = uSrcEltSize;
  5813. }
  5814. }
  5815. return uElts;
  5816. }
  5817. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5818. if (type.isNull()) {
  5819. return type;
  5820. }
  5821. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5822. switch (kind) {
  5823. case AR_TOBJ_BASIC:
  5824. case AR_TOBJ_OBJECT:
  5825. case AR_TOBJ_STRING:
  5826. return (index == 0) ? type : QualType();
  5827. case AR_TOBJ_COMPOUND: {
  5828. // TODO: consider caching this value for perf
  5829. const RecordType *recordType = type->getAsStructureType();
  5830. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5831. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5832. while (fi != fend) {
  5833. if (!fi->getType().isNull()) {
  5834. unsigned subElements = GetNumElements(fi->getType());
  5835. if (index < subElements) {
  5836. return GetNthElementType(fi->getType(), index);
  5837. } else {
  5838. index -= subElements;
  5839. }
  5840. }
  5841. ++fi;
  5842. }
  5843. return QualType();
  5844. }
  5845. case AR_TOBJ_ARRAY: {
  5846. unsigned arraySize;
  5847. QualType elementType;
  5848. unsigned elementCount;
  5849. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5850. elementCount = GetElementCount(elementType);
  5851. if (index < elementCount) {
  5852. return GetNthElementType(elementType, index);
  5853. }
  5854. arraySize = GetArraySize(type);
  5855. if (index >= arraySize * elementCount) {
  5856. return QualType();
  5857. }
  5858. return GetNthElementType(elementType, index % elementCount);
  5859. }
  5860. case AR_TOBJ_MATRIX:
  5861. case AR_TOBJ_VECTOR:
  5862. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5863. : QualType();
  5864. default:
  5865. DXASSERT(kind == AR_TOBJ_VOID,
  5866. "otherwise the type cannot be classified or is not supported");
  5867. return QualType();
  5868. }
  5869. }
  5870. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5871. // Eliminate exact matches first, then check for promotions.
  5872. if (leftKind == rightKind) {
  5873. return false;
  5874. }
  5875. switch (rightKind) {
  5876. case AR_BASIC_FLOAT16:
  5877. switch (leftKind) {
  5878. case AR_BASIC_FLOAT32:
  5879. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5880. case AR_BASIC_FLOAT64:
  5881. return true;
  5882. default:
  5883. return false; // No other type is a promotion.
  5884. }
  5885. break;
  5886. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5887. switch (leftKind) {
  5888. case AR_BASIC_FLOAT32:
  5889. case AR_BASIC_FLOAT64:
  5890. return true;
  5891. default:
  5892. return false; // No other type is a promotion.
  5893. }
  5894. break;
  5895. case AR_BASIC_FLOAT32:
  5896. switch (leftKind) {
  5897. case AR_BASIC_FLOAT64:
  5898. return true;
  5899. default:
  5900. return false; // No other type is a promotion.
  5901. }
  5902. break;
  5903. case AR_BASIC_MIN10FLOAT:
  5904. switch (leftKind) {
  5905. case AR_BASIC_MIN16FLOAT:
  5906. case AR_BASIC_FLOAT16:
  5907. case AR_BASIC_FLOAT32:
  5908. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5909. case AR_BASIC_FLOAT64:
  5910. return true;
  5911. default:
  5912. return false; // No other type is a promotion.
  5913. }
  5914. break;
  5915. case AR_BASIC_MIN16FLOAT:
  5916. switch (leftKind) {
  5917. case AR_BASIC_FLOAT16:
  5918. case AR_BASIC_FLOAT32:
  5919. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5920. case AR_BASIC_FLOAT64:
  5921. return true;
  5922. default:
  5923. return false; // No other type is a promotion.
  5924. }
  5925. break;
  5926. case AR_BASIC_INT8:
  5927. case AR_BASIC_UINT8:
  5928. // For backwards compat we consider signed/unsigned the same.
  5929. switch (leftKind) {
  5930. case AR_BASIC_INT16:
  5931. case AR_BASIC_INT32:
  5932. case AR_BASIC_INT64:
  5933. case AR_BASIC_UINT16:
  5934. case AR_BASIC_UINT32:
  5935. case AR_BASIC_UINT64:
  5936. return true;
  5937. default:
  5938. return false; // No other type is a promotion.
  5939. }
  5940. break;
  5941. case AR_BASIC_INT16:
  5942. case AR_BASIC_UINT16:
  5943. // For backwards compat we consider signed/unsigned the same.
  5944. switch (leftKind) {
  5945. case AR_BASIC_INT32:
  5946. case AR_BASIC_INT64:
  5947. case AR_BASIC_UINT32:
  5948. case AR_BASIC_UINT64:
  5949. return true;
  5950. default:
  5951. return false; // No other type is a promotion.
  5952. }
  5953. break;
  5954. case AR_BASIC_INT32:
  5955. case AR_BASIC_UINT32:
  5956. // For backwards compat we consider signed/unsigned the same.
  5957. switch (leftKind) {
  5958. case AR_BASIC_INT64:
  5959. case AR_BASIC_UINT64:
  5960. return true;
  5961. default:
  5962. return false; // No other type is a promotion.
  5963. }
  5964. break;
  5965. case AR_BASIC_MIN12INT:
  5966. switch (leftKind) {
  5967. case AR_BASIC_MIN16INT:
  5968. case AR_BASIC_INT32:
  5969. case AR_BASIC_INT64:
  5970. return true;
  5971. default:
  5972. return false; // No other type is a promotion.
  5973. }
  5974. break;
  5975. case AR_BASIC_MIN16INT:
  5976. switch (leftKind) {
  5977. case AR_BASIC_INT32:
  5978. case AR_BASIC_INT64:
  5979. return true;
  5980. default:
  5981. return false; // No other type is a promotion.
  5982. }
  5983. break;
  5984. case AR_BASIC_MIN16UINT:
  5985. switch (leftKind) {
  5986. case AR_BASIC_UINT32:
  5987. case AR_BASIC_UINT64:
  5988. return true;
  5989. default:
  5990. return false; // No other type is a promotion.
  5991. }
  5992. break;
  5993. }
  5994. return false;
  5995. }
  5996. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5997. // Eliminate exact matches first, then check for casts.
  5998. if (leftKind == rightKind) {
  5999. return false;
  6000. }
  6001. //
  6002. // All minimum-bits types are only considered matches of themselves
  6003. // and thus are not in this table.
  6004. //
  6005. switch (leftKind) {
  6006. case AR_BASIC_LITERAL_INT:
  6007. switch (rightKind) {
  6008. case AR_BASIC_INT8:
  6009. case AR_BASIC_INT16:
  6010. case AR_BASIC_INT32:
  6011. case AR_BASIC_INT64:
  6012. case AR_BASIC_UINT8:
  6013. case AR_BASIC_UINT16:
  6014. case AR_BASIC_UINT32:
  6015. case AR_BASIC_UINT64:
  6016. return false;
  6017. default:
  6018. break; // No other valid cast types
  6019. }
  6020. break;
  6021. case AR_BASIC_INT8:
  6022. switch (rightKind) {
  6023. // For backwards compat we consider signed/unsigned the same.
  6024. case AR_BASIC_LITERAL_INT:
  6025. case AR_BASIC_UINT8:
  6026. return false;
  6027. default:
  6028. break; // No other valid cast types
  6029. }
  6030. break;
  6031. case AR_BASIC_INT16:
  6032. switch (rightKind) {
  6033. // For backwards compat we consider signed/unsigned the same.
  6034. case AR_BASIC_LITERAL_INT:
  6035. case AR_BASIC_UINT16:
  6036. return false;
  6037. default:
  6038. break; // No other valid cast types
  6039. }
  6040. break;
  6041. case AR_BASIC_INT32:
  6042. switch (rightKind) {
  6043. // For backwards compat we consider signed/unsigned the same.
  6044. case AR_BASIC_LITERAL_INT:
  6045. case AR_BASIC_UINT32:
  6046. return false;
  6047. default:
  6048. break; // No other valid cast types.
  6049. }
  6050. break;
  6051. case AR_BASIC_INT64:
  6052. switch (rightKind) {
  6053. // For backwards compat we consider signed/unsigned the same.
  6054. case AR_BASIC_LITERAL_INT:
  6055. case AR_BASIC_UINT64:
  6056. return false;
  6057. default:
  6058. break; // No other valid cast types.
  6059. }
  6060. break;
  6061. case AR_BASIC_UINT8:
  6062. switch (rightKind) {
  6063. // For backwards compat we consider signed/unsigned the same.
  6064. case AR_BASIC_LITERAL_INT:
  6065. case AR_BASIC_INT8:
  6066. return false;
  6067. default:
  6068. break; // No other valid cast types.
  6069. }
  6070. break;
  6071. case AR_BASIC_UINT16:
  6072. switch (rightKind) {
  6073. // For backwards compat we consider signed/unsigned the same.
  6074. case AR_BASIC_LITERAL_INT:
  6075. case AR_BASIC_INT16:
  6076. return false;
  6077. default:
  6078. break; // No other valid cast types.
  6079. }
  6080. break;
  6081. case AR_BASIC_UINT32:
  6082. switch (rightKind) {
  6083. // For backwards compat we consider signed/unsigned the same.
  6084. case AR_BASIC_LITERAL_INT:
  6085. case AR_BASIC_INT32:
  6086. return false;
  6087. default:
  6088. break; // No other valid cast types.
  6089. }
  6090. break;
  6091. case AR_BASIC_UINT64:
  6092. switch (rightKind) {
  6093. // For backwards compat we consider signed/unsigned the same.
  6094. case AR_BASIC_LITERAL_INT:
  6095. case AR_BASIC_INT64:
  6096. return false;
  6097. default:
  6098. break; // No other valid cast types.
  6099. }
  6100. break;
  6101. case AR_BASIC_LITERAL_FLOAT:
  6102. switch (rightKind) {
  6103. case AR_BASIC_LITERAL_FLOAT:
  6104. case AR_BASIC_FLOAT16:
  6105. case AR_BASIC_FLOAT32:
  6106. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6107. case AR_BASIC_FLOAT64:
  6108. return false;
  6109. default:
  6110. break; // No other valid cast types.
  6111. }
  6112. break;
  6113. case AR_BASIC_FLOAT16:
  6114. switch (rightKind) {
  6115. case AR_BASIC_LITERAL_FLOAT:
  6116. return false;
  6117. default:
  6118. break; // No other valid cast types.
  6119. }
  6120. break;
  6121. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6122. switch (rightKind) {
  6123. case AR_BASIC_LITERAL_FLOAT:
  6124. return false;
  6125. default:
  6126. break; // No other valid cast types.
  6127. }
  6128. break;
  6129. case AR_BASIC_FLOAT32:
  6130. switch (rightKind) {
  6131. case AR_BASIC_LITERAL_FLOAT:
  6132. return false;
  6133. default:
  6134. break; // No other valid cast types.
  6135. }
  6136. break;
  6137. case AR_BASIC_FLOAT64:
  6138. switch (rightKind) {
  6139. case AR_BASIC_LITERAL_FLOAT:
  6140. return false;
  6141. default:
  6142. break; // No other valid cast types.
  6143. }
  6144. break;
  6145. default:
  6146. break; // No other relevant targets.
  6147. }
  6148. return true;
  6149. }
  6150. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  6151. // Eliminate exact matches first, then check for casts.
  6152. if (leftKind == rightKind) {
  6153. return false;
  6154. }
  6155. //
  6156. // All minimum-bits types are only considered matches of themselves
  6157. // and thus are not in this table.
  6158. //
  6159. switch (leftKind) {
  6160. case AR_BASIC_LITERAL_INT:
  6161. switch (rightKind) {
  6162. case AR_BASIC_INT8:
  6163. case AR_BASIC_INT16:
  6164. case AR_BASIC_INT32:
  6165. case AR_BASIC_INT64:
  6166. case AR_BASIC_UINT8:
  6167. case AR_BASIC_UINT16:
  6168. case AR_BASIC_UINT32:
  6169. case AR_BASIC_UINT64:
  6170. return false;
  6171. default:
  6172. break; // No other valid conversions
  6173. }
  6174. break;
  6175. case AR_BASIC_INT8:
  6176. case AR_BASIC_INT16:
  6177. case AR_BASIC_INT32:
  6178. case AR_BASIC_INT64:
  6179. case AR_BASIC_UINT8:
  6180. case AR_BASIC_UINT16:
  6181. case AR_BASIC_UINT32:
  6182. case AR_BASIC_UINT64:
  6183. switch (rightKind) {
  6184. case AR_BASIC_LITERAL_INT:
  6185. return false;
  6186. default:
  6187. break; // No other valid conversions
  6188. }
  6189. break;
  6190. case AR_BASIC_LITERAL_FLOAT:
  6191. switch (rightKind) {
  6192. case AR_BASIC_LITERAL_FLOAT:
  6193. case AR_BASIC_FLOAT16:
  6194. case AR_BASIC_FLOAT32:
  6195. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6196. case AR_BASIC_FLOAT64:
  6197. return false;
  6198. default:
  6199. break; // No other valid conversions
  6200. }
  6201. break;
  6202. case AR_BASIC_FLOAT16:
  6203. case AR_BASIC_FLOAT32:
  6204. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  6205. case AR_BASIC_FLOAT64:
  6206. switch (rightKind) {
  6207. case AR_BASIC_LITERAL_FLOAT:
  6208. return false;
  6209. default:
  6210. break; // No other valid conversions
  6211. }
  6212. break;
  6213. default:
  6214. // No other relevant targets
  6215. break;
  6216. }
  6217. return true;
  6218. }
  6219. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  6220. {
  6221. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  6222. return 0;
  6223. }
  6224. UINT64 uScore = 0;
  6225. UINT uLSize = GetNumElements(pLType);
  6226. UINT uRSize = GetNumElements(pRType);
  6227. UINT uCompareSize;
  6228. bool bLCast = false;
  6229. bool bRCast = false;
  6230. bool bLIntCast = false;
  6231. bool bRIntCast = false;
  6232. bool bLPromo = false;
  6233. bool bRPromo = false;
  6234. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  6235. if (uCompareSize > uRSize) {
  6236. uCompareSize = uRSize;
  6237. }
  6238. for (UINT i = 0; i < uCompareSize; i++) {
  6239. ArBasicKind LeftElementKind, RightElementKind;
  6240. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  6241. QualType leftSub = GetNthElementType(pLType, i);
  6242. QualType rightSub = GetNthElementType(pRType, i);
  6243. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  6244. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  6245. LeftElementKind = GetTypeElementKind(leftSub);
  6246. RightElementKind = GetTypeElementKind(rightSub);
  6247. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  6248. // information needed is the ShapeKind, EltKind and ObjKind.
  6249. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  6250. bool bCombine;
  6251. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  6252. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  6253. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  6254. ArBasicKind RightObjKind = RightElementKind;
  6255. LeftElementKind = LeftObjKind;
  6256. RightElementKind = RightObjKind;
  6257. if (leftKind != rightKind) {
  6258. bCombine = false;
  6259. }
  6260. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  6261. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  6262. }
  6263. }
  6264. else {
  6265. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  6266. }
  6267. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  6268. bLPromo = true;
  6269. }
  6270. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  6271. bLCast = true;
  6272. }
  6273. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  6274. bLIntCast = true;
  6275. }
  6276. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  6277. bRPromo = true;
  6278. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  6279. bRCast = true;
  6280. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  6281. bRIntCast = true;
  6282. }
  6283. } else {
  6284. bLCast = true;
  6285. bRCast = true;
  6286. }
  6287. }
  6288. #define SCORE_COND(shift, cond) { \
  6289. if (cond) uScore += 1ULL << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  6290. SCORE_COND(0, uRSize < uLSize);
  6291. SCORE_COND(1, bLPromo);
  6292. SCORE_COND(2, bRPromo);
  6293. SCORE_COND(3, bLIntCast);
  6294. SCORE_COND(4, bRIntCast);
  6295. SCORE_COND(5, bLCast);
  6296. SCORE_COND(6, bRCast);
  6297. SCORE_COND(7, uLSize < uRSize);
  6298. #undef SCORE_COND
  6299. // Make sure our scores fit in a UINT64.
  6300. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  6301. return uScore;
  6302. }
  6303. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  6304. DXASSERT(ics, "otherwise conversion has not been initialized");
  6305. if (!ics->isInitialized()) {
  6306. return 0;
  6307. }
  6308. if (!ics->isStandard()) {
  6309. return SCORE_MAX;
  6310. }
  6311. QualType fromType = ics->Standard.getFromType();
  6312. QualType toType = ics->Standard.getToType(2); // final type
  6313. return ScoreCast(toType, fromType);
  6314. }
  6315. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  6316. // Ignore target version mismatches.
  6317. // in/out considerations have been taken care of by viability.
  6318. // 'this' considerations don't matter without inheritance, other
  6319. // than lookup and viability.
  6320. UINT64 result = 0;
  6321. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  6322. UINT64 score;
  6323. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  6324. if (score == SCORE_MAX) {
  6325. return SCORE_MAX;
  6326. }
  6327. result += score;
  6328. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  6329. if (score == SCORE_MAX) {
  6330. return SCORE_MAX;
  6331. }
  6332. result += score;
  6333. }
  6334. return result;
  6335. }
  6336. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  6337. SourceLocation Loc,
  6338. OverloadCandidateSet& set,
  6339. OverloadCandidateSet::iterator& Best)
  6340. {
  6341. UINT64 bestScore = SCORE_MAX;
  6342. unsigned scoreMatch = 0;
  6343. Best = set.end();
  6344. if (set.size() == 1 && set.begin()->Viable) {
  6345. Best = set.begin();
  6346. return OR_Success;
  6347. }
  6348. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  6349. if (Cand->Viable) {
  6350. UINT64 score = ScoreFunction(Cand);
  6351. if (score != SCORE_MAX) {
  6352. if (score == bestScore) {
  6353. ++scoreMatch;
  6354. } else if (score < bestScore) {
  6355. Best = Cand;
  6356. scoreMatch = 1;
  6357. bestScore = score;
  6358. }
  6359. }
  6360. }
  6361. }
  6362. if (Best == set.end()) {
  6363. return OR_No_Viable_Function;
  6364. }
  6365. if (scoreMatch > 1) {
  6366. Best = set.end();
  6367. return OR_Ambiguous;
  6368. }
  6369. // No need to check for deleted functions to yield OR_Deleted.
  6370. return OR_Success;
  6371. }
  6372. /// <summary>
  6373. /// Initializes the specified <paramref name="initSequence" /> describing how
  6374. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  6375. /// </summary>
  6376. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  6377. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  6378. /// <param name="Args">Arguments to the initialization.</param>
  6379. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  6380. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  6381. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  6382. const InitializedEntity& Entity,
  6383. const InitializationKind& Kind,
  6384. MultiExprArg Args,
  6385. bool TopLevelOfInitList,
  6386. _Inout_ InitializationSequence* initSequence)
  6387. {
  6388. DXASSERT_NOMSG(initSequence != nullptr);
  6389. // In HLSL there are no default initializers, eg float4x4 m();
  6390. // Except for RayQuery constructor (also handle InitializationKind::IK_Value)
  6391. if (Kind.getKind() == InitializationKind::IK_Default ||
  6392. Kind.getKind() == InitializationKind::IK_Value) {
  6393. QualType destBaseType = m_context->getBaseElementType(Entity.getType());
  6394. ArTypeObjectKind destBaseShape = GetTypeObjectKind(destBaseType);
  6395. if (destBaseShape == AR_TOBJ_OBJECT) {
  6396. const CXXRecordDecl *typeRecordDecl = destBaseType->getAsCXXRecordDecl();
  6397. int index = FindObjectBasicKindIndex(GetRecordDeclForBuiltInOrStruct(typeRecordDecl));
  6398. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  6399. if (g_ArBasicKindsAsTypes[index] == AR_OBJECT_RAY_QUERY) {
  6400. CXXConstructorDecl *Constructor = *typeRecordDecl->ctor_begin();
  6401. initSequence->AddConstructorInitializationStep(
  6402. Constructor, AccessSpecifier::AS_public, destBaseType, false, false, false);
  6403. return;
  6404. }
  6405. }
  6406. // Value initializers occur for temporaries with empty parens or braces.
  6407. if (Kind.getKind() == InitializationKind::IK_Value) {
  6408. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  6409. SilenceSequenceDiagnostics(initSequence);
  6410. }
  6411. return;
  6412. }
  6413. // If we have a DirectList, we should have a single InitListExprClass argument.
  6414. DXASSERT(
  6415. Kind.getKind() != InitializationKind::IK_DirectList ||
  6416. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  6417. "otherwise caller is passing in incorrect initialization configuration");
  6418. bool isCast = Kind.isCStyleCast();
  6419. QualType destType = Entity.getType();
  6420. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  6421. // Direct initialization occurs for explicit constructor arguments.
  6422. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  6423. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  6424. !Kind.isCStyleOrFunctionalCast()) {
  6425. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  6426. SilenceSequenceDiagnostics(initSequence);
  6427. return;
  6428. }
  6429. bool flatten =
  6430. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  6431. Kind.getKind() == InitializationKind::IK_DirectList ||
  6432. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  6433. if (flatten) {
  6434. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  6435. // array types to adjust the value - we do calculate this as part of type analysis.
  6436. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  6437. FlattenedTypeIterator::ComparisonResult comparisonResult =
  6438. FlattenedTypeIterator::CompareTypesForInit(
  6439. *this, destType, Args,
  6440. Kind.getLocation(), Kind.getLocation());
  6441. if (comparisonResult.IsConvertibleAndEqualLength() ||
  6442. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  6443. {
  6444. initSequence->AddListInitializationStep(destType);
  6445. }
  6446. else
  6447. {
  6448. SourceLocation diagLocation;
  6449. if (Args.size() > 0)
  6450. {
  6451. diagLocation = Args.front()->getLocStart();
  6452. }
  6453. else
  6454. {
  6455. diagLocation = Entity.getDiagLoc();
  6456. }
  6457. if (comparisonResult.IsEqualLength()) {
  6458. m_sema->Diag(diagLocation, diag::err_hlsl_type_mismatch);
  6459. }
  6460. else {
  6461. m_sema->Diag(diagLocation,
  6462. diag::err_incorrect_num_initializers)
  6463. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  6464. << IsSubobjectType(destType)
  6465. << comparisonResult.LeftCount << comparisonResult.RightCount;
  6466. }
  6467. SilenceSequenceDiagnostics(initSequence);
  6468. }
  6469. }
  6470. else {
  6471. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  6472. Expr* firstArg = Args.front();
  6473. if (IsExpressionBinaryComma(firstArg)) {
  6474. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  6475. }
  6476. ExprResult expr = ExprResult(firstArg);
  6477. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  6478. Sema::CheckedConversionKind::CCK_CStyleCast :
  6479. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  6480. unsigned int msg = 0;
  6481. CastKind castKind;
  6482. CXXCastPath basePath;
  6483. SourceRange range = Kind.getRange();
  6484. ImplicitConversionSequence ics;
  6485. ics.setStandard();
  6486. bool castWorked = TryStaticCastForHLSL(
  6487. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  6488. if (castWorked) {
  6489. if (destType.getCanonicalType() ==
  6490. firstArg->getType().getCanonicalType() &&
  6491. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  6492. initSequence->AddCAssignmentStep(destType);
  6493. } else {
  6494. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  6495. }
  6496. }
  6497. else {
  6498. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  6499. }
  6500. }
  6501. }
  6502. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6503. const QualType& sourceType,
  6504. const QualType& targetType,
  6505. bool explicitConversion)
  6506. {
  6507. DXASSERT_NOMSG(!sourceType.isNull());
  6508. DXASSERT_NOMSG(!targetType.isNull());
  6509. ArTypeInfo sourceTypeInfo;
  6510. ArTypeInfo targetTypeInfo;
  6511. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  6512. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  6513. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  6514. {
  6515. return false;
  6516. }
  6517. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  6518. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  6519. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  6520. !isVecMatTrunc)
  6521. {
  6522. return false;
  6523. }
  6524. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  6525. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  6526. return true;
  6527. }
  6528. // Same struct is eqaul.
  6529. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  6530. sourceType.getCanonicalType().getUnqualifiedType() ==
  6531. targetType.getCanonicalType().getUnqualifiedType()) {
  6532. return true;
  6533. }
  6534. // DerivedFrom is less.
  6535. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  6536. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  6537. const RecordType *targetRT = targetType->getAsStructureType();
  6538. if (!targetRT)
  6539. targetRT = dyn_cast<RecordType>(targetType);
  6540. const RecordType *sourceRT = sourceType->getAsStructureType();
  6541. if (!sourceRT)
  6542. sourceRT = dyn_cast<RecordType>(sourceType);
  6543. if (targetRT && sourceRT) {
  6544. RecordDecl *targetRD = targetRT->getDecl();
  6545. RecordDecl *sourceRD = sourceRT->getDecl();
  6546. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6547. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6548. if (targetCXXRD && sourceCXXRD) {
  6549. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  6550. return true;
  6551. }
  6552. }
  6553. }
  6554. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  6555. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  6556. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  6557. {
  6558. return false;
  6559. }
  6560. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  6561. }
  6562. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6563. const ExprResult& sourceExpr,
  6564. const QualType& targetType,
  6565. bool explicitConversion)
  6566. {
  6567. if (sourceExpr.isInvalid() || targetType.isNull())
  6568. {
  6569. return false;
  6570. }
  6571. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  6572. }
  6573. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  6574. {
  6575. DXASSERT_NOMSG(!type.isNull());
  6576. DXASSERT_NOMSG(count != nullptr);
  6577. *count = 0;
  6578. UINT subCount = 0;
  6579. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  6580. switch (shapeKind)
  6581. {
  6582. case AR_TOBJ_ARRAY:
  6583. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  6584. {
  6585. *count = subCount * GetArraySize(type);
  6586. return true;
  6587. }
  6588. return false;
  6589. case AR_TOBJ_COMPOUND:
  6590. {
  6591. UINT maxCount = 0;
  6592. { // Determine maximum count to prevent infinite loop on incomplete array
  6593. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  6594. maxCount = itCount.countRemaining();
  6595. if (!maxCount) {
  6596. return false; // empty struct.
  6597. }
  6598. }
  6599. FlattenedTypeIterator it(SourceLocation(), type, *this);
  6600. while (it.hasCurrentElement()) {
  6601. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  6602. if (!isFieldNumeric) {
  6603. return false;
  6604. }
  6605. if (*count >= maxCount) {
  6606. // this element is an incomplete array at the end; iterator will not advance past this element.
  6607. // don't add to *count either, so *count will represent minimum size of the structure.
  6608. break;
  6609. }
  6610. *count += (subCount * it.getCurrentElementSize());
  6611. it.advanceCurrentElement(it.getCurrentElementSize());
  6612. }
  6613. return true;
  6614. }
  6615. default:
  6616. DXASSERT(false, "unreachable");
  6617. case AR_TOBJ_BASIC:
  6618. case AR_TOBJ_MATRIX:
  6619. case AR_TOBJ_VECTOR:
  6620. *count = GetElementCount(type);
  6621. return IsBasicKindNumeric(GetTypeElementKind(type));
  6622. case AR_TOBJ_OBJECT:
  6623. case AR_TOBJ_STRING:
  6624. return false;
  6625. }
  6626. }
  6627. enum MatrixMemberAccessError {
  6628. MatrixMemberAccessError_None, // No errors found.
  6629. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  6630. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  6631. MatrixMemberAccessError_Empty, // No members specified.
  6632. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  6633. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  6634. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6635. };
  6636. static
  6637. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  6638. {
  6639. DXASSERT_NOMSG(memberText != nullptr);
  6640. DXASSERT_NOMSG(value != nullptr);
  6641. if ('0' <= *memberText && *memberText <= '9')
  6642. {
  6643. *value = (*memberText) - '0';
  6644. }
  6645. else
  6646. {
  6647. return MatrixMemberAccessError_BadFormat;
  6648. }
  6649. memberText++;
  6650. return MatrixMemberAccessError_None;
  6651. }
  6652. static
  6653. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  6654. {
  6655. DXASSERT_NOMSG(memberText != nullptr);
  6656. DXASSERT_NOMSG(value != nullptr);
  6657. MatrixMemberAccessPositions result;
  6658. bool zeroBasedDecided = false;
  6659. bool zeroBased = false;
  6660. // Set the output value to invalid to allow early exits when errors are found.
  6661. value->IsValid = 0;
  6662. // Assume this is true until proven otherwise.
  6663. result.IsValid = 1;
  6664. result.Count = 0;
  6665. while (*memberText)
  6666. {
  6667. // Check for a leading underscore.
  6668. if (*memberText != '_')
  6669. {
  6670. return MatrixMemberAccessError_BadFormat;
  6671. }
  6672. ++memberText;
  6673. // Check whether we have an 'm' or a digit.
  6674. if (*memberText == 'm')
  6675. {
  6676. if (zeroBasedDecided && !zeroBased)
  6677. {
  6678. return MatrixMemberAccessError_MixingRefs;
  6679. }
  6680. zeroBased = true;
  6681. zeroBasedDecided = true;
  6682. ++memberText;
  6683. }
  6684. else if (!('0' <= *memberText && *memberText <= '9'))
  6685. {
  6686. return MatrixMemberAccessError_BadFormat;
  6687. }
  6688. else
  6689. {
  6690. if (zeroBasedDecided && zeroBased)
  6691. {
  6692. return MatrixMemberAccessError_MixingRefs;
  6693. }
  6694. zeroBased = false;
  6695. zeroBasedDecided = true;
  6696. }
  6697. // Consume two digits for the position.
  6698. uint32_t rowPosition;
  6699. uint32_t colPosition;
  6700. MatrixMemberAccessError digitError;
  6701. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  6702. {
  6703. return digitError;
  6704. }
  6705. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  6706. {
  6707. return digitError;
  6708. }
  6709. // Look for specific common errors (developer likely mixed up reference style).
  6710. if (zeroBased)
  6711. {
  6712. if (rowPosition == 4 || colPosition == 4)
  6713. {
  6714. return MatrixMemberAccessError_FourInZeroBased;
  6715. }
  6716. }
  6717. else
  6718. {
  6719. if (rowPosition == 0 || colPosition == 0)
  6720. {
  6721. return MatrixMemberAccessError_ZeroInOneBased;
  6722. }
  6723. // SetPosition will use zero-based indices.
  6724. --rowPosition;
  6725. --colPosition;
  6726. }
  6727. if (result.Count == 4)
  6728. {
  6729. return MatrixMemberAccessError_TooManyPositions;
  6730. }
  6731. result.SetPosition(result.Count, rowPosition, colPosition);
  6732. result.Count++;
  6733. }
  6734. if (result.Count == 0)
  6735. {
  6736. return MatrixMemberAccessError_Empty;
  6737. }
  6738. *value = result;
  6739. return MatrixMemberAccessError_None;
  6740. }
  6741. ExprResult HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  6742. Expr& BaseExpr,
  6743. DeclarationName MemberName,
  6744. bool IsArrow,
  6745. SourceLocation OpLoc,
  6746. SourceLocation MemberLoc)
  6747. {
  6748. QualType BaseType = BaseExpr.getType();
  6749. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6750. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_MATRIX, "Should only be called on known matrix types");
  6751. QualType elementType;
  6752. UINT rowCount, colCount;
  6753. GetRowsAndCols(BaseType, rowCount, colCount);
  6754. elementType = GetMatrixOrVectorElementType(BaseType);
  6755. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6756. const char *memberText = member->getNameStart();
  6757. MatrixMemberAccessPositions positions;
  6758. MatrixMemberAccessError memberAccessError;
  6759. unsigned msg = 0;
  6760. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  6761. switch (memberAccessError)
  6762. {
  6763. case MatrixMemberAccessError_BadFormat:
  6764. msg = diag::err_hlsl_matrix_member_bad_format;
  6765. break;
  6766. case MatrixMemberAccessError_Empty:
  6767. msg = diag::err_hlsl_matrix_member_empty;
  6768. break;
  6769. case MatrixMemberAccessError_FourInZeroBased:
  6770. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  6771. break;
  6772. case MatrixMemberAccessError_MixingRefs:
  6773. msg = diag::err_hlsl_matrix_member_mixing_refs;
  6774. break;
  6775. case MatrixMemberAccessError_None:
  6776. msg = 0;
  6777. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6778. // Check the position with the type now.
  6779. for (unsigned int i = 0; i < positions.Count; i++)
  6780. {
  6781. uint32_t rowPos, colPos;
  6782. positions.GetPosition(i, &rowPos, &colPos);
  6783. if (rowPos >= rowCount || colPos >= colCount)
  6784. {
  6785. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  6786. break;
  6787. }
  6788. }
  6789. break;
  6790. case MatrixMemberAccessError_TooManyPositions:
  6791. msg = diag::err_hlsl_matrix_member_too_many_positions;
  6792. break;
  6793. case MatrixMemberAccessError_ZeroInOneBased:
  6794. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  6795. break;
  6796. default:
  6797. llvm_unreachable("Unknown MatrixMemberAccessError value");
  6798. }
  6799. if (msg != 0)
  6800. {
  6801. m_sema->Diag(MemberLoc, msg) << memberText;
  6802. // It's possible that it's a simple out-of-bounds condition. In this case,
  6803. // generate the member access expression with the correct arity and continue
  6804. // processing.
  6805. if (!positions.IsValid)
  6806. {
  6807. return ExprError();
  6808. }
  6809. }
  6810. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6811. // Consume elements
  6812. QualType resultType;
  6813. if (positions.Count == 1)
  6814. resultType = elementType;
  6815. else
  6816. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6817. // Add qualifiers from BaseType.
  6818. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6819. ExprValueKind VK =
  6820. positions.ContainsDuplicateElements() ? VK_RValue :
  6821. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6822. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6823. return matrixExpr;
  6824. }
  6825. enum VectorMemberAccessError {
  6826. VectorMemberAccessError_None, // No errors found.
  6827. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  6828. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  6829. VectorMemberAccessError_Empty, // No members specified.
  6830. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6831. };
  6832. static
  6833. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  6834. DXASSERT_NOMSG(memberText != nullptr);
  6835. DXASSERT_NOMSG(value != nullptr);
  6836. rgbaStyle = false;
  6837. switch (*memberText) {
  6838. case 'r':
  6839. rgbaStyle = true;
  6840. case 'x':
  6841. *value = 0;
  6842. break;
  6843. case 'g':
  6844. rgbaStyle = true;
  6845. case 'y':
  6846. *value = 1;
  6847. break;
  6848. case 'b':
  6849. rgbaStyle = true;
  6850. case 'z':
  6851. *value = 2;
  6852. break;
  6853. case 'a':
  6854. rgbaStyle = true;
  6855. case 'w':
  6856. *value = 3;
  6857. break;
  6858. default:
  6859. return VectorMemberAccessError_BadFormat;
  6860. }
  6861. memberText++;
  6862. return VectorMemberAccessError_None;
  6863. }
  6864. static
  6865. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  6866. DXASSERT_NOMSG(memberText != nullptr);
  6867. DXASSERT_NOMSG(value != nullptr);
  6868. VectorMemberAccessPositions result;
  6869. bool rgbaStyleDecided = false;
  6870. bool rgbaStyle = false;
  6871. // Set the output value to invalid to allow early exits when errors are found.
  6872. value->IsValid = 0;
  6873. // Assume this is true until proven otherwise.
  6874. result.IsValid = 1;
  6875. result.Count = 0;
  6876. while (*memberText) {
  6877. // Consume one character for the swizzle.
  6878. uint32_t colPosition;
  6879. VectorMemberAccessError digitError;
  6880. bool rgbaStyleTmp = false;
  6881. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6882. return digitError;
  6883. }
  6884. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6885. return VectorMemberAccessError_MixingStyles;
  6886. }
  6887. else {
  6888. rgbaStyleDecided = true;
  6889. rgbaStyle = rgbaStyleTmp;
  6890. }
  6891. if (result.Count == 4) {
  6892. return VectorMemberAccessError_TooManyPositions;
  6893. }
  6894. result.SetPosition(result.Count, colPosition);
  6895. result.Count++;
  6896. }
  6897. if (result.Count == 0) {
  6898. return VectorMemberAccessError_Empty;
  6899. }
  6900. *value = result;
  6901. return VectorMemberAccessError_None;
  6902. }
  6903. bool IsExprAccessingOutIndicesArray(Expr* BaseExpr) {
  6904. switch(BaseExpr->getStmtClass()) {
  6905. case Stmt::ArraySubscriptExprClass: {
  6906. ArraySubscriptExpr* ase = cast<ArraySubscriptExpr>(BaseExpr);
  6907. return IsExprAccessingOutIndicesArray(ase->getBase());
  6908. }
  6909. case Stmt::ImplicitCastExprClass: {
  6910. ImplicitCastExpr* ice = cast<ImplicitCastExpr>(BaseExpr);
  6911. return IsExprAccessingOutIndicesArray(ice->getSubExpr());
  6912. }
  6913. case Stmt::DeclRefExprClass: {
  6914. DeclRefExpr* dre = cast<DeclRefExpr>(BaseExpr);
  6915. ValueDecl* vd = dre->getDecl();
  6916. if (vd->getAttr<HLSLIndicesAttr>() && vd->getAttr<HLSLOutAttr>()) {
  6917. return true;
  6918. }
  6919. return false;
  6920. }
  6921. default:
  6922. return false;
  6923. }
  6924. }
  6925. ExprResult HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6926. Expr& BaseExpr,
  6927. DeclarationName MemberName,
  6928. bool IsArrow,
  6929. SourceLocation OpLoc,
  6930. SourceLocation MemberLoc) {
  6931. QualType BaseType = BaseExpr.getType();
  6932. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6933. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_VECTOR, "Should only be called on known vector types");
  6934. QualType elementType;
  6935. UINT colCount = GetHLSLVecSize(BaseType);
  6936. elementType = GetMatrixOrVectorElementType(BaseType);
  6937. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6938. const char *memberText = member->getNameStart();
  6939. VectorMemberAccessPositions positions;
  6940. VectorMemberAccessError memberAccessError;
  6941. unsigned msg = 0;
  6942. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6943. switch (memberAccessError) {
  6944. case VectorMemberAccessError_BadFormat:
  6945. msg = diag::err_hlsl_vector_member_bad_format;
  6946. break;
  6947. case VectorMemberAccessError_Empty:
  6948. msg = diag::err_hlsl_vector_member_empty;
  6949. break;
  6950. case VectorMemberAccessError_MixingStyles:
  6951. msg = diag::err_ext_vector_component_name_mixedsets;
  6952. break;
  6953. case VectorMemberAccessError_None:
  6954. msg = 0;
  6955. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6956. // Check the position with the type now.
  6957. for (unsigned int i = 0; i < positions.Count; i++) {
  6958. uint32_t colPos;
  6959. positions.GetPosition(i, &colPos);
  6960. if (colPos >= colCount) {
  6961. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6962. break;
  6963. }
  6964. }
  6965. break;
  6966. case VectorMemberAccessError_TooManyPositions:
  6967. msg = diag::err_hlsl_vector_member_too_many_positions;
  6968. break;
  6969. default:
  6970. llvm_unreachable("Unknown VectorMemberAccessError value");
  6971. }
  6972. if (msg != 0) {
  6973. m_sema->Diag(MemberLoc, msg) << memberText;
  6974. // It's possible that it's a simple out-of-bounds condition. In this case,
  6975. // generate the member access expression with the correct arity and continue
  6976. // processing.
  6977. if (!positions.IsValid) {
  6978. return ExprError();
  6979. }
  6980. }
  6981. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6982. // Disallow component access for out indices for DXIL path. We still allow
  6983. // this in SPIR-V path.
  6984. if (!m_sema->getLangOpts().SPIRV &&
  6985. IsExprAccessingOutIndicesArray(&BaseExpr) && positions.Count < colCount) {
  6986. m_sema->Diag(MemberLoc, diag::err_hlsl_out_indices_array_incorrect_access);
  6987. return ExprError();
  6988. }
  6989. // Consume elements
  6990. QualType resultType;
  6991. if (positions.Count == 1)
  6992. resultType = elementType;
  6993. else
  6994. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6995. // Add qualifiers from BaseType.
  6996. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6997. ExprValueKind VK =
  6998. positions.ContainsDuplicateElements() ? VK_RValue :
  6999. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  7000. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  7001. return vectorExpr;
  7002. }
  7003. ExprResult HLSLExternalSource::LookupArrayMemberExprForHLSL(
  7004. Expr& BaseExpr,
  7005. DeclarationName MemberName,
  7006. bool IsArrow,
  7007. SourceLocation OpLoc,
  7008. SourceLocation MemberLoc) {
  7009. QualType BaseType = BaseExpr.getType();
  7010. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  7011. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_ARRAY, "Should only be called on known array types");
  7012. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  7013. const char *memberText = member->getNameStart();
  7014. // The only property available on arrays is Length; it is deprecated and available only on HLSL version <=2018
  7015. if (member->getLength() == 6 && 0 == strcmp(memberText, "Length")) {
  7016. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(BaseType)) {
  7017. // check version support
  7018. unsigned hlslVer = getSema()->getLangOpts().HLSLVersion;
  7019. if (hlslVer > 2016) {
  7020. m_sema->Diag(MemberLoc, diag::err_hlsl_unsupported_for_version_lower) << "Length" << "2016";
  7021. return ExprError();
  7022. }
  7023. if (hlslVer == 2016) {
  7024. m_sema->Diag(MemberLoc, diag::warn_deprecated) << "Length";
  7025. }
  7026. UnaryExprOrTypeTraitExpr *arrayLenExpr = new (m_context) UnaryExprOrTypeTraitExpr(
  7027. UETT_ArrayLength, &BaseExpr, m_context->getSizeType(), MemberLoc, BaseExpr.getSourceRange().getEnd());
  7028. return arrayLenExpr;
  7029. }
  7030. }
  7031. m_sema->Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
  7032. << BaseType << BaseExpr.getSourceRange() << MemberLoc;
  7033. return ExprError();
  7034. }
  7035. ExprResult HLSLExternalSource::MaybeConvertMemberAccess(_In_ clang::Expr* E) {
  7036. DXASSERT_NOMSG(E != nullptr);
  7037. if (IsHLSLBufferViewType(E->getType())) {
  7038. QualType targetType =
  7039. m_context->getConstType(hlsl::GetHLSLResourceResultType(E->getType()));
  7040. return ImplicitCastExpr::Create(*m_context, targetType,
  7041. CastKind::CK_FlatConversion, E, nullptr,
  7042. E->getValueKind());
  7043. }
  7044. ArBasicKind basic = GetTypeElementKind(E->getType());
  7045. if (!IS_BASIC_PRIMITIVE(basic)) {
  7046. return E;
  7047. }
  7048. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  7049. if (kind != AR_TOBJ_SCALAR) {
  7050. return E;
  7051. }
  7052. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  7053. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  7054. }
  7055. static clang::CastKind ImplicitConversionKindToCastKind(
  7056. clang::ImplicitConversionKind ICK,
  7057. ArBasicKind FromKind,
  7058. ArBasicKind ToKind) {
  7059. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  7060. // based on from/to kinds in order to determine CastKind?
  7061. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  7062. // problem.
  7063. switch (ICK) {
  7064. case ICK_Integral_Promotion:
  7065. case ICK_Integral_Conversion:
  7066. return CK_IntegralCast;
  7067. case ICK_Floating_Promotion:
  7068. case ICK_Floating_Conversion:
  7069. return CK_FloatingCast;
  7070. case ICK_Floating_Integral:
  7071. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  7072. return CK_FloatingToIntegral;
  7073. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  7074. return CK_IntegralToFloating;
  7075. break;
  7076. case ICK_Boolean_Conversion:
  7077. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  7078. return CK_FloatingToBoolean;
  7079. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  7080. return CK_IntegralToBoolean;
  7081. break;
  7082. default:
  7083. // Only covers implicit conversions with cast kind equivalents.
  7084. return CK_Invalid;
  7085. }
  7086. return CK_Invalid;
  7087. }
  7088. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  7089. switch (CK) {
  7090. case CK_IntegralCast:
  7091. return CK_HLSLCC_IntegralCast;
  7092. case CK_FloatingCast:
  7093. return CK_HLSLCC_FloatingCast;
  7094. case CK_FloatingToIntegral:
  7095. return CK_HLSLCC_FloatingToIntegral;
  7096. case CK_IntegralToFloating:
  7097. return CK_HLSLCC_IntegralToFloating;
  7098. case CK_FloatingToBoolean:
  7099. return CK_HLSLCC_FloatingToBoolean;
  7100. case CK_IntegralToBoolean:
  7101. return CK_HLSLCC_IntegralToBoolean;
  7102. default:
  7103. // Only HLSLCC castkinds are relevant. Ignore the rest.
  7104. return CK_Invalid;
  7105. }
  7106. return CK_Invalid;
  7107. }
  7108. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  7109. _In_ clang::Sema* self,
  7110. _In_ clang::Expr* From,
  7111. ArTypeObjectKind FromShape,
  7112. ArBasicKind EltKind)
  7113. {
  7114. clang::CastKind CK = CK_Invalid;
  7115. if (AR_TOBJ_MATRIX == FromShape)
  7116. CK = CK_HLSLMatrixToScalarCast;
  7117. if (AR_TOBJ_VECTOR == FromShape)
  7118. CK = CK_HLSLVectorToScalarCast;
  7119. if (CK_Invalid != CK) {
  7120. return self->ImpCastExprToType(From,
  7121. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  7122. }
  7123. return From;
  7124. }
  7125. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  7126. _In_ clang::Expr* From,
  7127. _In_ clang::QualType targetType,
  7128. _In_ const clang::StandardConversionSequence &SCS,
  7129. _In_ clang::Sema::CheckedConversionKind CCK)
  7130. {
  7131. QualType sourceType = From->getType();
  7132. sourceType = GetStructuralForm(sourceType);
  7133. targetType = GetStructuralForm(targetType);
  7134. ArTypeInfo SourceInfo, TargetInfo;
  7135. CollectInfo(sourceType, &SourceInfo);
  7136. CollectInfo(targetType, &TargetInfo);
  7137. clang::CastKind CK = CK_Invalid;
  7138. QualType intermediateTarget;
  7139. // TODO: construct vector/matrix and component cast expressions
  7140. switch (SCS.Second) {
  7141. case ICK_Flat_Conversion: {
  7142. // TODO: determine how to handle individual component conversions:
  7143. // - have an array of conversions for ComponentConversion in SCS?
  7144. // convert that to an array of casts under a special kind of flat
  7145. // flat conversion node? What do component conversion casts cast
  7146. // from? We don't have a From expression for individiual components.
  7147. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7148. break;
  7149. }
  7150. case ICK_HLSL_Derived_To_Base: {
  7151. CXXCastPath BasePath;
  7152. if (m_sema->CheckDerivedToBaseConversion(
  7153. sourceType, targetType.getNonReferenceType(), From->getLocStart(),
  7154. From->getSourceRange(), &BasePath, /*IgnoreAccess=*/true))
  7155. return ExprError();
  7156. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), &BasePath, CCK).get();
  7157. break;
  7158. }
  7159. case ICK_HLSLVector_Splat: {
  7160. // 1. optionally convert from vec1 or mat1x1 to scalar
  7161. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  7162. // 2. optionally convert component type
  7163. if (ICK_Identity != SCS.ComponentConversion) {
  7164. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  7165. if (CK_Invalid != CK) {
  7166. From = m_sema->ImpCastExprToType(From,
  7167. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7168. }
  7169. }
  7170. // 3. splat scalar to final vector or matrix
  7171. CK = CK_Invalid;
  7172. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  7173. CK = CK_HLSLVectorSplat;
  7174. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  7175. CK = CK_HLSLMatrixSplat;
  7176. if (CK_Invalid != CK) {
  7177. From = m_sema->ImpCastExprToType(From,
  7178. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7179. }
  7180. break;
  7181. }
  7182. case ICK_HLSLVector_Scalar: {
  7183. // 1. select vector or matrix component
  7184. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  7185. // 2. optionally convert component type
  7186. if (ICK_Identity != SCS.ComponentConversion) {
  7187. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  7188. if (CK_Invalid != CK) {
  7189. From = m_sema->ImpCastExprToType(From,
  7190. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7191. }
  7192. }
  7193. break;
  7194. }
  7195. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  7196. // can be done with case fall-through, since this is the order in which we want to
  7197. // do the conversion operations.
  7198. case ICK_HLSLVector_Truncation: {
  7199. // 1. dimension truncation
  7200. // vector truncation or matrix truncation?
  7201. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  7202. From = m_sema->ImpCastExprToType(From,
  7203. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  7204. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7205. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  7206. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  7207. // Handle the column to vector case
  7208. From = m_sema->ImpCastExprToType(From,
  7209. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  7210. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7211. } else {
  7212. From = m_sema->ImpCastExprToType(From,
  7213. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  7214. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7215. }
  7216. } else {
  7217. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  7218. }
  7219. }
  7220. __fallthrough;
  7221. case ICK_HLSLVector_Conversion: {
  7222. // 2. Do ShapeKind conversion if necessary
  7223. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  7224. switch (TargetInfo.ShapeKind) {
  7225. case AR_TOBJ_VECTOR:
  7226. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  7227. From = m_sema->ImpCastExprToType(From,
  7228. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  7229. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7230. break;
  7231. case AR_TOBJ_MATRIX:
  7232. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  7233. From = m_sema->ImpCastExprToType(From,
  7234. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  7235. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7236. break;
  7237. case AR_TOBJ_BASIC:
  7238. // Truncation may be followed by cast to scalar
  7239. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  7240. break;
  7241. default:
  7242. DXASSERT(false, "otherwise, invalid casting sequence");
  7243. break;
  7244. }
  7245. }
  7246. // 3. Do component type conversion
  7247. if (ICK_Identity != SCS.ComponentConversion) {
  7248. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  7249. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  7250. CK = ConvertToComponentCastKind(CK);
  7251. if (CK_Invalid != CK) {
  7252. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  7253. }
  7254. }
  7255. break;
  7256. }
  7257. case ICK_Identity:
  7258. // Nothing to do.
  7259. break;
  7260. default:
  7261. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  7262. }
  7263. return From;
  7264. }
  7265. void HLSLExternalSource::GetConversionForm(
  7266. QualType type,
  7267. bool explicitConversion,
  7268. ArTypeInfo* pTypeInfo)
  7269. {
  7270. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  7271. CollectInfo(type, pTypeInfo);
  7272. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  7273. // but that value is only used for pointer conversions.
  7274. // When explicitly converting types complex aggregates can be treated
  7275. // as vectors if they are entirely numeric.
  7276. switch (pTypeInfo->ShapeKind)
  7277. {
  7278. case AR_TOBJ_COMPOUND:
  7279. case AR_TOBJ_ARRAY:
  7280. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  7281. {
  7282. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  7283. }
  7284. else
  7285. {
  7286. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  7287. }
  7288. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  7289. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  7290. break;
  7291. case AR_TOBJ_VECTOR:
  7292. case AR_TOBJ_MATRIX:
  7293. // Convert 1x1 types to scalars.
  7294. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  7295. {
  7296. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  7297. }
  7298. break;
  7299. default:
  7300. // Only convertable shapekinds are relevant.
  7301. break;
  7302. }
  7303. }
  7304. static
  7305. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  7306. {
  7307. DXASSERT_NOMSG(allowed != nullptr);
  7308. bool applicable = true;
  7309. *allowed = true;
  7310. if (explicitConversion) {
  7311. // (void) non-void
  7312. if (target->isVoidType()) {
  7313. DXASSERT_NOMSG(*allowed);
  7314. }
  7315. // (non-void) void
  7316. else if (source->isVoidType()) {
  7317. *allowed = false;
  7318. }
  7319. else {
  7320. applicable = false;
  7321. }
  7322. }
  7323. else {
  7324. // (void) void
  7325. if (source->isVoidType() && target->isVoidType()) {
  7326. DXASSERT_NOMSG(*allowed);
  7327. }
  7328. // (void) non-void, (non-void) void
  7329. else if (source->isVoidType() || target->isVoidType()) {
  7330. *allowed = false;
  7331. }
  7332. else {
  7333. applicable = false;
  7334. }
  7335. }
  7336. return applicable;
  7337. }
  7338. static bool ConvertDimensions(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7339. ImplicitConversionKind &Second,
  7340. TYPE_CONVERSION_REMARKS &Remarks) {
  7341. // The rules for aggregate conversions are:
  7342. // 1. A scalar can be replicated to any layout.
  7343. // 2. Any type may be truncated to anything else with one component.
  7344. // 3. A vector may be truncated to a smaller vector.
  7345. // 4. A matrix may be truncated to a smaller matrix.
  7346. // 5. The result of a vector and a matrix is:
  7347. // a. If the matrix has one row it's a vector-sized
  7348. // piece of the row.
  7349. // b. If the matrix has one column it's a vector-sized
  7350. // piece of the column.
  7351. // c. Otherwise the number of elements in the vector
  7352. // and matrix must match and the result is the vector.
  7353. // 6. The result of a matrix and a vector is similar to #5.
  7354. switch (TargetInfo.ShapeKind) {
  7355. case AR_TOBJ_BASIC:
  7356. switch (SourceInfo.ShapeKind)
  7357. {
  7358. case AR_TOBJ_BASIC:
  7359. Second = ICK_Identity;
  7360. break;
  7361. case AR_TOBJ_VECTOR:
  7362. if (1 < SourceInfo.uCols)
  7363. Second = ICK_HLSLVector_Truncation;
  7364. else
  7365. Second = ICK_HLSLVector_Scalar;
  7366. break;
  7367. case AR_TOBJ_MATRIX:
  7368. if (1 < SourceInfo.uRows * SourceInfo.uCols)
  7369. Second = ICK_HLSLVector_Truncation;
  7370. else
  7371. Second = ICK_HLSLVector_Scalar;
  7372. break;
  7373. default:
  7374. return false;
  7375. }
  7376. break;
  7377. case AR_TOBJ_VECTOR:
  7378. switch (SourceInfo.ShapeKind)
  7379. {
  7380. case AR_TOBJ_BASIC:
  7381. // Conversions between scalars and aggregates are always supported.
  7382. Second = ICK_HLSLVector_Splat;
  7383. break;
  7384. case AR_TOBJ_VECTOR:
  7385. if (TargetInfo.uCols > SourceInfo.uCols) {
  7386. if (SourceInfo.uCols == 1) {
  7387. Second = ICK_HLSLVector_Splat;
  7388. }
  7389. else {
  7390. return false;
  7391. }
  7392. }
  7393. else if (TargetInfo.uCols < SourceInfo.uCols) {
  7394. Second = ICK_HLSLVector_Truncation;
  7395. }
  7396. else {
  7397. Second = ICK_Identity;
  7398. }
  7399. break;
  7400. case AR_TOBJ_MATRIX: {
  7401. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7402. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  7403. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  7404. Second = ICK_HLSLVector_Splat;
  7405. }
  7406. else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  7407. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  7408. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  7409. return false;
  7410. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  7411. Second = ICK_HLSLVector_Truncation;
  7412. else // equalivalent: O == N*M
  7413. Second = ICK_HLSLVector_Conversion;
  7414. }
  7415. else if (TargetInfo.uCols == 1 && SourceComponents > 1) {
  7416. Second = ICK_HLSLVector_Truncation;
  7417. }
  7418. else if (TargetInfo.uCols != SourceComponents) {
  7419. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  7420. return false;
  7421. }
  7422. else {
  7423. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  7424. Second = ICK_HLSLVector_Conversion;
  7425. }
  7426. break;
  7427. }
  7428. default:
  7429. return false;
  7430. }
  7431. break;
  7432. case AR_TOBJ_MATRIX: {
  7433. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  7434. switch (SourceInfo.ShapeKind)
  7435. {
  7436. case AR_TOBJ_BASIC:
  7437. // Conversions between scalars and aggregates are always supported.
  7438. Second = ICK_HLSLVector_Splat;
  7439. break;
  7440. case AR_TOBJ_VECTOR: {
  7441. // We can only convert vector to matrix in following cases:
  7442. // - splat from vector<...,1>
  7443. // - same number of components
  7444. // - one target component (truncate to scalar)
  7445. // - matrix has one row or one column, and fewer components (truncation)
  7446. // Other cases disallowed even if implicitly convertable in two steps (truncation+conversion).
  7447. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  7448. // splat: vector<[..], 1> -> matrix<[..], M, N>
  7449. Second = ICK_HLSLVector_Splat;
  7450. }
  7451. else if (TargetComponents == SourceInfo.uCols) {
  7452. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  7453. Second = ICK_HLSLVector_Conversion;
  7454. }
  7455. else if (1 == TargetComponents) {
  7456. // truncate to scalar: matrix<[..], 1, 1>
  7457. Second = ICK_HLSLVector_Truncation;
  7458. }
  7459. else if ((1 == TargetInfo.uRows || 1 == TargetInfo.uCols) &&
  7460. TargetComponents < SourceInfo.uCols) {
  7461. Second = ICK_HLSLVector_Truncation;
  7462. }
  7463. else {
  7464. // illegal: change in components without going to or from scalar equivalent
  7465. return false;
  7466. }
  7467. break;
  7468. }
  7469. case AR_TOBJ_MATRIX: {
  7470. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7471. if (1 == SourceComponents && TargetComponents != 1) {
  7472. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  7473. Second = ICK_HLSLVector_Splat;
  7474. }
  7475. else if (TargetComponents == 1) {
  7476. Second = ICK_HLSLVector_Truncation;
  7477. }
  7478. else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  7479. return false;
  7480. }
  7481. else if (TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  7482. Second = ICK_HLSLVector_Truncation;
  7483. }
  7484. else {
  7485. Second = ICK_Identity;
  7486. }
  7487. break;
  7488. }
  7489. default:
  7490. return false;
  7491. }
  7492. break;
  7493. }
  7494. case AR_TOBJ_STRING:
  7495. if (SourceInfo.ShapeKind == AR_TOBJ_STRING) {
  7496. Second = ICK_Identity;
  7497. break;
  7498. }
  7499. else {
  7500. return false;
  7501. }
  7502. default:
  7503. return false;
  7504. }
  7505. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  7506. {
  7507. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  7508. }
  7509. return true;
  7510. }
  7511. static bool ConvertComponent(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7512. ImplicitConversionKind &ComponentConversion,
  7513. TYPE_CONVERSION_REMARKS &Remarks) {
  7514. // Conversion to/from unknown types not supported.
  7515. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  7516. SourceInfo.EltKind == AR_BASIC_UNKNOWN) {
  7517. return false;
  7518. }
  7519. bool precisionLoss = false;
  7520. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  7521. GET_BASIC_BITS(TargetInfo.EltKind) <
  7522. GET_BASIC_BITS(SourceInfo.EltKind))
  7523. {
  7524. precisionLoss = true;
  7525. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  7526. }
  7527. // enum -> enum not allowed
  7528. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  7529. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  7530. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  7531. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  7532. return false;
  7533. }
  7534. if (SourceInfo.EltKind != TargetInfo.EltKind)
  7535. {
  7536. if (IS_BASIC_BOOL(TargetInfo.EltKind))
  7537. {
  7538. ComponentConversion = ICK_Boolean_Conversion;
  7539. }
  7540. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  7541. {
  7542. // conversion to enum type not allowed
  7543. return false;
  7544. }
  7545. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  7546. {
  7547. // enum -> int/float
  7548. ComponentConversion = ICK_Integral_Conversion;
  7549. }
  7550. else if (TargetInfo.EltKind == AR_OBJECT_STRING)
  7551. {
  7552. if (SourceInfo.EltKind == AR_OBJECT_STRING_LITERAL) {
  7553. ComponentConversion = ICK_Array_To_Pointer;
  7554. }
  7555. else
  7556. {
  7557. return false;
  7558. }
  7559. }
  7560. else
  7561. {
  7562. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  7563. if (IS_BASIC_AINT(SourceInfo.EltKind))
  7564. {
  7565. if (targetIsInt)
  7566. {
  7567. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  7568. }
  7569. else
  7570. {
  7571. ComponentConversion = ICK_Floating_Integral;
  7572. }
  7573. }
  7574. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  7575. {
  7576. if (targetIsInt)
  7577. {
  7578. ComponentConversion = ICK_Floating_Integral;
  7579. }
  7580. else
  7581. {
  7582. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  7583. }
  7584. }
  7585. else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  7586. if (targetIsInt)
  7587. ComponentConversion = ICK_Integral_Conversion;
  7588. else
  7589. ComponentConversion = ICK_Floating_Integral;
  7590. }
  7591. }
  7592. }
  7593. return true;
  7594. }
  7595. _Use_decl_annotations_
  7596. bool HLSLExternalSource::CanConvert(
  7597. SourceLocation loc,
  7598. Expr* sourceExpr,
  7599. QualType target,
  7600. bool explicitConversion,
  7601. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  7602. _Inout_opt_ StandardConversionSequence* standard)
  7603. {
  7604. UINT uTSize, uSSize;
  7605. bool SourceIsAggregate, TargetIsAggregate; // Early declarations due to gotos below
  7606. DXASSERT_NOMSG(sourceExpr != nullptr);
  7607. DXASSERT_NOMSG(!target.isNull());
  7608. // Implements the semantics of ArType::CanConvertTo.
  7609. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  7610. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  7611. QualType source = sourceExpr->getType();
  7612. // Cannot cast function type.
  7613. if (source->isFunctionType())
  7614. return false;
  7615. // Convert to an r-value to begin with, with an exception for strings
  7616. // since they are not first-class values and we want to preserve them as literals.
  7617. bool needsLValueToRValue = sourceExpr->isLValue() && !target->isLValueReferenceType()
  7618. && sourceExpr->getStmtClass() != Expr::StringLiteralClass;
  7619. bool targetRef = target->isReferenceType();
  7620. // Initialize the output standard sequence if available.
  7621. if (standard != nullptr) {
  7622. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  7623. standard->setAsIdentityConversion();
  7624. if (needsLValueToRValue) {
  7625. standard->First = ICK_Lvalue_To_Rvalue;
  7626. }
  7627. standard->setFromType(source);
  7628. standard->setAllToTypes(target);
  7629. }
  7630. source = GetStructuralForm(source);
  7631. target = GetStructuralForm(target);
  7632. // Temporary conversion kind tracking which will be used/fixed up at the end
  7633. ImplicitConversionKind Second = ICK_Identity;
  7634. ImplicitConversionKind ComponentConversion = ICK_Identity;
  7635. // Identical types require no conversion.
  7636. if (source == target) {
  7637. Remarks = TYPE_CONVERSION_IDENTICAL;
  7638. goto lSuccess;
  7639. }
  7640. // Trivial cases for void.
  7641. bool allowed;
  7642. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  7643. if (allowed) {
  7644. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  7645. goto lSuccess;
  7646. }
  7647. else {
  7648. return false;
  7649. }
  7650. }
  7651. ArTypeInfo TargetInfo, SourceInfo;
  7652. CollectInfo(target, &TargetInfo);
  7653. CollectInfo(source, &SourceInfo);
  7654. uTSize = TargetInfo.uTotalElts;
  7655. uSSize = SourceInfo.uTotalElts;
  7656. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  7657. // are we missing cases?
  7658. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  7659. return false;
  7660. }
  7661. // Cast cbuffer to its result value.
  7662. if ((SourceInfo.EltKind == AR_OBJECT_CONSTANT_BUFFER ||
  7663. SourceInfo.EltKind == AR_OBJECT_TEXTURE_BUFFER) &&
  7664. TargetInfo.ShapeKind == AR_TOBJ_COMPOUND) {
  7665. if (standard)
  7666. standard->Second = ICK_Flat_Conversion;
  7667. return hlsl::GetHLSLResourceResultType(source) == target;
  7668. }
  7669. // Structure cast.
  7670. SourceIsAggregate = SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY;
  7671. TargetIsAggregate = TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY;
  7672. if (SourceIsAggregate || TargetIsAggregate) {
  7673. // For implicit conversions, FXC treats arrays the same as structures
  7674. // and rejects conversions between them and numeric types
  7675. if (!explicitConversion && SourceIsAggregate != TargetIsAggregate)
  7676. {
  7677. return false;
  7678. }
  7679. // Structure to structure cases
  7680. const RecordType *targetRT = dyn_cast<RecordType>(target);
  7681. const RecordType *sourceRT = dyn_cast<RecordType>(source);
  7682. if (targetRT && sourceRT) {
  7683. RecordDecl *targetRD = targetRT->getDecl();
  7684. RecordDecl *sourceRD = sourceRT->getDecl();
  7685. if (sourceRT && targetRT) {
  7686. if (targetRD == sourceRD) {
  7687. Second = ICK_Flat_Conversion;
  7688. goto lSuccess;
  7689. }
  7690. const CXXRecordDecl* targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  7691. const CXXRecordDecl* sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  7692. if (targetCXXRD && sourceCXXRD && sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  7693. Second = ICK_HLSL_Derived_To_Base;
  7694. goto lSuccess;
  7695. }
  7696. }
  7697. }
  7698. // Handle explicit splats from single element numerical types (scalars, vector1s and matrix1x1s) to aggregate types.
  7699. if (explicitConversion) {
  7700. const BuiltinType *sourceSingleElementBuiltinType = source->getAs<BuiltinType>();
  7701. if (sourceSingleElementBuiltinType == nullptr
  7702. && hlsl::IsHLSLVecMatType(source)
  7703. && hlsl::GetElementCount(source) == 1) {
  7704. sourceSingleElementBuiltinType = hlsl::GetElementTypeOrType(source)->getAs<BuiltinType>();
  7705. }
  7706. // We can only splat to target types that do not contain object/resource types
  7707. if (sourceSingleElementBuiltinType != nullptr && hlsl::IsHLSLNumericOrAggregateOfNumericType(target)) {
  7708. BuiltinType::Kind kind = sourceSingleElementBuiltinType->getKind();
  7709. switch (kind) {
  7710. case BuiltinType::Kind::UInt:
  7711. case BuiltinType::Kind::Int:
  7712. case BuiltinType::Kind::Float:
  7713. case BuiltinType::Kind::LitFloat:
  7714. case BuiltinType::Kind::LitInt:
  7715. Second = ICK_Flat_Conversion;
  7716. goto lSuccess;
  7717. default:
  7718. // Only flat conversion kinds are relevant.
  7719. break;
  7720. }
  7721. }
  7722. }
  7723. FlattenedTypeIterator::ComparisonResult result =
  7724. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  7725. if (!result.CanConvertElements) {
  7726. return false;
  7727. }
  7728. // Only allow scalar to compound or array with explicit cast
  7729. if (result.IsConvertibleAndLeftLonger()) {
  7730. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  7731. return false;
  7732. }
  7733. }
  7734. // Assignment is valid if elements are exactly the same in type and size; if
  7735. // an explicit conversion is being done, we accept converted elements and a
  7736. // longer right-hand sequence.
  7737. if (!explicitConversion &&
  7738. (!result.AreElementsEqual || result.IsRightLonger()))
  7739. {
  7740. return false;
  7741. }
  7742. Second = ICK_Flat_Conversion;
  7743. goto lSuccess;
  7744. }
  7745. // Cast from Resource to Object types.
  7746. if (SourceInfo.EltKind == AR_OBJECT_HEAP_RESOURCE ||
  7747. SourceInfo.EltKind == AR_OBJECT_HEAP_SAMPLER) {
  7748. // TODO: skip things like PointStream.
  7749. if (TargetInfo.ShapeKind == AR_TOBJ_OBJECT) {
  7750. Second = ICK_Flat_Conversion;
  7751. goto lSuccess;
  7752. }
  7753. }
  7754. // Convert scalar/vector/matrix dimensions
  7755. if (!ConvertDimensions(TargetInfo, SourceInfo, Second, Remarks))
  7756. return false;
  7757. // Convert component type
  7758. if (!ConvertComponent(TargetInfo, SourceInfo, ComponentConversion, Remarks))
  7759. return false;
  7760. lSuccess:
  7761. if (standard)
  7762. {
  7763. if (sourceExpr->isLValue())
  7764. {
  7765. if (needsLValueToRValue) {
  7766. // We don't need LValueToRValue cast before casting a derived object
  7767. // to its base.
  7768. if (Second == ICK_HLSL_Derived_To_Base) {
  7769. standard->First = ICK_Identity;
  7770. } else {
  7771. standard->First = ICK_Lvalue_To_Rvalue;
  7772. }
  7773. } else {
  7774. switch (Second)
  7775. {
  7776. case ICK_NoReturn_Adjustment:
  7777. case ICK_Vector_Conversion:
  7778. case ICK_Vector_Splat:
  7779. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  7780. case ICK_Flat_Conversion:
  7781. case ICK_HLSLVector_Splat:
  7782. standard->First = ICK_Lvalue_To_Rvalue;
  7783. break;
  7784. default:
  7785. // Only flat and splat conversions handled.
  7786. break;
  7787. }
  7788. switch (ComponentConversion)
  7789. {
  7790. case ICK_Integral_Promotion:
  7791. case ICK_Integral_Conversion:
  7792. case ICK_Floating_Promotion:
  7793. case ICK_Floating_Conversion:
  7794. case ICK_Floating_Integral:
  7795. case ICK_Boolean_Conversion:
  7796. standard->First = ICK_Lvalue_To_Rvalue;
  7797. break;
  7798. case ICK_Array_To_Pointer:
  7799. standard->First = ICK_Array_To_Pointer;
  7800. break;
  7801. default:
  7802. // Only potential assignments above covered.
  7803. break;
  7804. }
  7805. }
  7806. }
  7807. // Finally fix up the cases for scalar->scalar component conversion, and
  7808. // identity vector/matrix component conversion
  7809. if (ICK_Identity != ComponentConversion) {
  7810. if (Second == ICK_Identity) {
  7811. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  7812. // Scalar to scalar type conversion, use normal mechanism (Second)
  7813. Second = ComponentConversion;
  7814. ComponentConversion = ICK_Identity;
  7815. }
  7816. else if (TargetInfo.ShapeKind != AR_TOBJ_STRING) {
  7817. // vector or matrix dimensions are not being changed, but component type
  7818. // is being converted, so change Second to signal the conversion
  7819. Second = ICK_HLSLVector_Conversion;
  7820. }
  7821. }
  7822. }
  7823. standard->Second = Second;
  7824. standard->ComponentConversion = ComponentConversion;
  7825. // For conversion which change to RValue but targeting reference type
  7826. // Hold the conversion to codeGen
  7827. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  7828. standard->First = ICK_Identity;
  7829. standard->Second = ICK_Identity;
  7830. }
  7831. }
  7832. AssignOpt(Remarks, remarks);
  7833. return true;
  7834. }
  7835. bool HLSLExternalSource::ValidateTypeRequirements(
  7836. SourceLocation loc,
  7837. ArBasicKind elementKind,
  7838. ArTypeObjectKind objectKind,
  7839. bool requiresIntegrals,
  7840. bool requiresNumerics)
  7841. {
  7842. if (requiresIntegrals || requiresNumerics)
  7843. {
  7844. if (!IsObjectKindPrimitiveAggregate(objectKind))
  7845. {
  7846. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  7847. return false;
  7848. }
  7849. }
  7850. if (requiresIntegrals)
  7851. {
  7852. if (!IsBasicKindIntegral(elementKind))
  7853. {
  7854. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  7855. return false;
  7856. }
  7857. }
  7858. else if (requiresNumerics)
  7859. {
  7860. if (!IsBasicKindNumeric(elementKind))
  7861. {
  7862. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  7863. return false;
  7864. }
  7865. }
  7866. return true;
  7867. }
  7868. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  7869. {
  7870. bool isValid = true;
  7871. if (IsBuiltInObjectType(type)) {
  7872. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  7873. isValid = false;
  7874. }
  7875. if (kind == AR_TOBJ_COMPOUND) {
  7876. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  7877. isValid = false;
  7878. }
  7879. return isValid;
  7880. }
  7881. HRESULT HLSLExternalSource::CombineDimensions(
  7882. QualType leftType, QualType rightType, QualType *resultType,
  7883. ImplicitConversionKind &convKind, TYPE_CONVERSION_REMARKS &Remarks)
  7884. {
  7885. ArTypeInfo leftInfo, rightInfo;
  7886. CollectInfo(leftType, &leftInfo);
  7887. CollectInfo(rightType, &rightInfo);
  7888. // Prefer larger, or left if same.
  7889. if (leftInfo.uTotalElts >= rightInfo.uTotalElts) {
  7890. if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7891. *resultType = leftType;
  7892. else if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7893. *resultType = rightType;
  7894. else
  7895. return E_FAIL;
  7896. } else {
  7897. if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7898. *resultType = rightType;
  7899. else if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7900. *resultType = leftType;
  7901. else
  7902. return E_FAIL;
  7903. }
  7904. return S_OK;
  7905. }
  7906. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  7907. /// <param name="OpLoc">Source location for operator.</param>
  7908. /// <param name="Opc">Kind of binary operator.</param>
  7909. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  7910. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  7911. /// <param name="ResultTy">Result type for operator expression.</param>
  7912. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  7913. /// <param name="CompResultTy">Type of computation result.</param>
  7914. void HLSLExternalSource::CheckBinOpForHLSL(
  7915. SourceLocation OpLoc,
  7916. BinaryOperatorKind Opc,
  7917. ExprResult& LHS,
  7918. ExprResult& RHS,
  7919. QualType& ResultTy,
  7920. QualType& CompLHSTy,
  7921. QualType& CompResultTy)
  7922. {
  7923. // At the start, none of the output types should be valid.
  7924. DXASSERT_NOMSG(ResultTy.isNull());
  7925. DXASSERT_NOMSG(CompLHSTy.isNull());
  7926. DXASSERT_NOMSG(CompResultTy.isNull());
  7927. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7928. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7929. // If either expression is invalid to begin with, propagate that.
  7930. if (LHS.isInvalid() || RHS.isInvalid()) {
  7931. return;
  7932. }
  7933. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  7934. // Handle Assign and Comma operators and return
  7935. switch (Opc)
  7936. {
  7937. case BO_AddAssign:
  7938. case BO_AndAssign:
  7939. case BO_DivAssign:
  7940. case BO_MulAssign:
  7941. case BO_RemAssign:
  7942. case BO_ShlAssign:
  7943. case BO_ShrAssign:
  7944. case BO_SubAssign:
  7945. case BO_OrAssign:
  7946. case BO_XorAssign: {
  7947. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  7948. Sema & S);
  7949. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7950. return;
  7951. }
  7952. } break;
  7953. case BO_Assign: {
  7954. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7955. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7956. return;
  7957. }
  7958. bool complained = false;
  7959. ResultTy = LHS.get()->getType();
  7960. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  7961. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  7962. Sema::AssignmentAction::AA_Assigning, &complained)) {
  7963. return;
  7964. }
  7965. StandardConversionSequence standard;
  7966. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  7967. ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7968. return;
  7969. }
  7970. if (RHS.get()->isLValue()) {
  7971. standard.First = ICK_Lvalue_To_Rvalue;
  7972. }
  7973. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  7974. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  7975. return;
  7976. }
  7977. break;
  7978. case BO_Comma:
  7979. // C performs conversions, C++ doesn't but still checks for type completeness.
  7980. // There are also diagnostics for improper comma use.
  7981. // In the HLSL case these cases don't apply or simply aren't surfaced.
  7982. ResultTy = RHS.get()->getType();
  7983. return;
  7984. default:
  7985. // Only assign and comma operations handled.
  7986. break;
  7987. }
  7988. // Leave this diagnostic for last to emulate fxc behavior.
  7989. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  7990. bool unsupportedBoolLvalue = isCompoundAssignment &&
  7991. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  7992. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  7993. // Turn operand inputs into r-values.
  7994. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  7995. if (!isCompoundAssignment) {
  7996. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  7997. }
  7998. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  7999. if (LHS.isInvalid() || RHS.isInvalid()) {
  8000. return;
  8001. }
  8002. // Gather type info
  8003. QualType leftType = GetStructuralForm(LHS.get()->getType());
  8004. QualType rightType = GetStructuralForm(RHS.get()->getType());
  8005. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  8006. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  8007. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  8008. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  8009. // Validate type requirements
  8010. {
  8011. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  8012. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  8013. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  8014. return;
  8015. }
  8016. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  8017. return;
  8018. }
  8019. }
  8020. if (unsupportedBoolLvalue) {
  8021. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  8022. return;
  8023. }
  8024. // We don't support binary operators on built-in object types other than assignment or commas.
  8025. {
  8026. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  8027. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  8028. bool isValid;
  8029. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  8030. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  8031. isValid = false;
  8032. }
  8033. if (!isValid) {
  8034. return;
  8035. }
  8036. }
  8037. // We don't support equality comparisons on arrays.
  8038. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  8039. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  8040. return;
  8041. }
  8042. // Combine element types for computation.
  8043. ArBasicKind resultElementKind = leftElementKind;
  8044. {
  8045. if (BinaryOperatorKindIsLogical(Opc)) {
  8046. resultElementKind = AR_BASIC_BOOL;
  8047. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  8048. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  8049. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  8050. return;
  8051. }
  8052. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  8053. (resultElementKind == AR_BASIC_LITERAL_INT ||
  8054. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  8055. rightElementKind != AR_BASIC_LITERAL_INT &&
  8056. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  8057. // For case like 1<<x.
  8058. m_sema->Diag(OpLoc, diag::warn_hlsl_ambiguous_literal_shift);
  8059. if (rightElementKind == AR_BASIC_UINT32)
  8060. resultElementKind = AR_BASIC_UINT32;
  8061. else
  8062. resultElementKind = AR_BASIC_INT32;
  8063. } else if (resultElementKind == AR_BASIC_BOOL &&
  8064. BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  8065. resultElementKind = AR_BASIC_INT32;
  8066. }
  8067. // The following combines the selected/combined element kind above with
  8068. // the dimensions that are legal to implicitly cast. This means that
  8069. // element kind may be taken from one side and the dimensions from the
  8070. // other.
  8071. if (!isCompoundAssignment) {
  8072. // Legal dimension combinations are identical, splat, and truncation.
  8073. // ResultTy will be set to whichever type can be converted to, if legal,
  8074. // with preference for leftType if both are possible.
  8075. if (FAILED(CombineDimensions(LHS.get()->getType(), RHS.get()->getType(), &ResultTy))) {
  8076. // Just choose leftType, and allow ValidateCast to catch this later
  8077. ResultTy = LHS.get()->getType();
  8078. }
  8079. } else {
  8080. ResultTy = LHS.get()->getType();
  8081. }
  8082. // Here, element kind is combined with dimensions for computation type, if different.
  8083. if (resultElementKind != GetTypeElementKind(ResultTy)) {
  8084. UINT rowCount, colCount;
  8085. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8086. ResultTy = NewSimpleAggregateType(GetTypeObjectKind(ResultTy), resultElementKind, 0, rowCount, colCount);
  8087. }
  8088. }
  8089. bool bFailedFirstRHSCast = false;
  8090. // Perform necessary conversion sequences for LHS and RHS
  8091. if (RHS.get()->getType() != ResultTy) {
  8092. StandardConversionSequence standard;
  8093. // Suppress type narrowing or truncation warnings for RHS on bitwise shift, since we only care about the LHS type.
  8094. bool bSuppressWarnings = BinaryOperatorKindIsBitwiseShift(Opc);
  8095. // Suppress errors on compound assignment, since we will vaildate the cast to the final type later.
  8096. bool bSuppressErrors = isCompoundAssignment;
  8097. // If compound assignment, suppress errors until later, but report warning (vector truncation/type narrowing) here.
  8098. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, bSuppressWarnings, bSuppressErrors, &standard)) {
  8099. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8100. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8101. } else if (!isCompoundAssignment) {
  8102. // If compound assignment, validate cast from RHS directly to LHS later, otherwise, fail here.
  8103. ResultTy = QualType();
  8104. return;
  8105. } else {
  8106. bFailedFirstRHSCast = true;
  8107. }
  8108. }
  8109. if (isCompoundAssignment) {
  8110. CompResultTy = ResultTy;
  8111. CompLHSTy = CompResultTy;
  8112. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  8113. // then converts to the result type and then assigns.
  8114. //
  8115. // So int + float promotes the int to float, does a floating-point addition,
  8116. // then the result becomes and int and is assigned.
  8117. ResultTy = LHSTypeAsPossibleLValue;
  8118. // Validate remainder of cast from computation type to final result type
  8119. StandardConversionSequence standard;
  8120. if (!ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8121. ResultTy = QualType();
  8122. return;
  8123. }
  8124. DXASSERT_LOCALVAR(bFailedFirstRHSCast, !bFailedFirstRHSCast,
  8125. "otherwise, hit compound assign case that failed RHS -> CompResultTy cast, but succeeded RHS -> LHS cast.");
  8126. } else if (LHS.get()->getType() != ResultTy) {
  8127. StandardConversionSequence standard;
  8128. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8129. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8130. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8131. } else {
  8132. ResultTy = QualType();
  8133. return;
  8134. }
  8135. }
  8136. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  8137. {
  8138. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  8139. // Return bool vector for vector types.
  8140. if (IsVectorType(m_sema, ResultTy)) {
  8141. UINT rowCount, colCount;
  8142. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8143. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  8144. } else if (IsMatrixType(m_sema, ResultTy)) {
  8145. UINT rowCount, colCount;
  8146. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8147. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  8148. } else
  8149. ResultTy = m_context->BoolTy.withConst();
  8150. }
  8151. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  8152. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  8153. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  8154. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  8155. return;
  8156. }
  8157. }
  8158. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  8159. if (resultElementKind == AR_BASIC_FLOAT64) {
  8160. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  8161. return;
  8162. }
  8163. }
  8164. }
  8165. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  8166. /// <param name="OpLoc">Source location for operator.</param>
  8167. /// <param name="Opc">Kind of operator.</param>
  8168. /// <param name="InputExpr">Input expression to the operator.</param>
  8169. /// <param name="VK">Value kind for resulting expression.</param>
  8170. /// <param name="OK">Object kind for resulting expression.</param>
  8171. /// <returns>The result type for the expression.</returns>
  8172. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  8173. SourceLocation OpLoc,
  8174. UnaryOperatorKind Opc,
  8175. ExprResult& InputExpr,
  8176. ExprValueKind& VK,
  8177. ExprObjectKind& OK)
  8178. {
  8179. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  8180. if (InputExpr.isInvalid())
  8181. return QualType();
  8182. // Reject unsupported operators * and &
  8183. switch (Opc) {
  8184. case UO_AddrOf:
  8185. case UO_Deref:
  8186. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  8187. return QualType();
  8188. default:
  8189. // Only * and & covered.
  8190. break;
  8191. }
  8192. Expr* expr = InputExpr.get();
  8193. if (expr->isTypeDependent())
  8194. return m_context->DependentTy;
  8195. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  8196. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  8197. if (elementKind == AR_BASIC_ENUM) {
  8198. bool isInc = IsIncrementOp(Opc);
  8199. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  8200. return QualType();
  8201. }
  8202. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  8203. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  8204. return QualType();
  8205. } else {
  8206. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  8207. if (InputExpr.isInvalid()) return QualType();
  8208. }
  8209. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  8210. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  8211. return QualType();
  8212. }
  8213. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  8214. InputExpr = PromoteToIntIfBool(InputExpr);
  8215. expr = InputExpr.get();
  8216. elementKind = GetTypeElementKind(expr->getType());
  8217. }
  8218. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  8219. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  8220. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  8221. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  8222. return QualType();
  8223. }
  8224. if (Opc == UnaryOperatorKind::UO_Minus) {
  8225. if (IS_BASIC_UINT(Opc)) {
  8226. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  8227. }
  8228. }
  8229. // By default, the result type is the operand type.
  8230. // Logical not however should cast to a bool.
  8231. QualType resultType = expr->getType();
  8232. if (Opc == UnaryOperatorKind::UO_LNot) {
  8233. UINT rowCount, colCount;
  8234. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  8235. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  8236. StandardConversionSequence standard;
  8237. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  8238. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  8239. return QualType();
  8240. }
  8241. // Cast argument.
  8242. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8243. if (result.isUsable()) {
  8244. InputExpr = result.get();
  8245. }
  8246. }
  8247. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  8248. if (isPrefix) {
  8249. VK = VK_LValue;
  8250. return resultType;
  8251. }
  8252. else {
  8253. VK = VK_RValue;
  8254. return resultType.getUnqualifiedType();
  8255. }
  8256. }
  8257. clang::QualType HLSLExternalSource::CheckVectorConditional(
  8258. _In_ ExprResult &Cond,
  8259. _In_ ExprResult &LHS,
  8260. _In_ ExprResult &RHS,
  8261. _In_ SourceLocation QuestionLoc)
  8262. {
  8263. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  8264. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  8265. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  8266. // If either expression is invalid to begin with, propagate that.
  8267. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  8268. return QualType();
  8269. }
  8270. // Gather type info
  8271. QualType condType = GetStructuralForm(Cond.get()->getType());
  8272. QualType leftType = GetStructuralForm(LHS.get()->getType());
  8273. QualType rightType = GetStructuralForm(RHS.get()->getType());
  8274. ArBasicKind condElementKind = GetTypeElementKind(condType);
  8275. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  8276. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  8277. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  8278. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  8279. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  8280. QualType ResultTy = leftType;
  8281. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  8282. if (!condIsSimple) {
  8283. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  8284. return QualType();
  8285. }
  8286. UINT rowCountCond, colCountCond;
  8287. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  8288. bool leftIsSimple =
  8289. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  8290. leftObjectKind == AR_TOBJ_MATRIX;
  8291. bool rightIsSimple =
  8292. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  8293. rightObjectKind == AR_TOBJ_MATRIX;
  8294. if (!leftIsSimple || !rightIsSimple) {
  8295. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  8296. if (leftType == rightType) {
  8297. return leftType;
  8298. }
  8299. }
  8300. // NOTE: Limiting this operator to working only on basic numeric types.
  8301. // This is due to extremely limited (and even broken) support for any other case.
  8302. // In the future we may decide to support more cases.
  8303. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  8304. return QualType();
  8305. }
  8306. // Types should be only scalar, vector, or matrix after this point.
  8307. ArBasicKind resultElementKind = leftElementKind;
  8308. // Combine LHS and RHS element types for computation.
  8309. if (leftElementKind != rightElementKind) {
  8310. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  8311. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  8312. return QualType();
  8313. }
  8314. }
  8315. // Restore left/right type to original to avoid stripping attributed type or typedef type
  8316. leftType = LHS.get()->getType();
  8317. rightType = RHS.get()->getType();
  8318. // Combine LHS and RHS dimensions
  8319. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  8320. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  8321. return QualType();
  8322. }
  8323. UINT rowCount, colCount;
  8324. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8325. // If result is scalar, use condition dimensions.
  8326. // Otherwise, condition must either match or is scalar, then use result dimensions
  8327. if (rowCount * colCount == 1) {
  8328. rowCount = rowCountCond;
  8329. colCount = colCountCond;
  8330. }
  8331. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  8332. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  8333. return QualType();
  8334. }
  8335. // Here, element kind is combined with dimensions for result type.
  8336. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8337. // Cast condition to RValue
  8338. if (Cond.get()->isLValue())
  8339. Cond.set(CreateLValueToRValueCast(Cond.get()));
  8340. // Convert condition component type to bool, using result component dimensions
  8341. if (condElementKind != AR_BASIC_BOOL) {
  8342. QualType boolType = NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8343. StandardConversionSequence standard;
  8344. if (ValidateCast(SourceLocation(), Cond.get(), boolType, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8345. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8346. Cond = m_sema->PerformImplicitConversion(Cond.get(), boolType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8347. }
  8348. else {
  8349. return QualType();
  8350. }
  8351. }
  8352. // TODO: Is this correct? Does fxc support lvalue return here?
  8353. // Cast LHS/RHS to RValue
  8354. if (LHS.get()->isLValue())
  8355. LHS.set(CreateLValueToRValueCast(LHS.get()));
  8356. if (RHS.get()->isLValue())
  8357. RHS.set(CreateLValueToRValueCast(RHS.get()));
  8358. if (leftType != ResultTy) {
  8359. StandardConversionSequence standard;
  8360. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8361. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8362. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8363. }
  8364. else {
  8365. return QualType();
  8366. }
  8367. }
  8368. if (rightType != ResultTy) {
  8369. StandardConversionSequence standard;
  8370. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8371. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8372. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8373. }
  8374. else {
  8375. return QualType();
  8376. }
  8377. }
  8378. return ResultTy;
  8379. }
  8380. // Apply type specifier sign to the given QualType.
  8381. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  8382. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  8383. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  8384. _In_ clang::SourceLocation Loc) {
  8385. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  8386. return type;
  8387. }
  8388. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  8389. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  8390. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  8391. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  8392. return type;
  8393. }
  8394. // check if element type is unsigned and check if such vector exists
  8395. // If not create a new one, Make a QualType of the new kind
  8396. ArBasicKind elementKind = GetTypeElementKind(type);
  8397. // Only ints can have signed/unsigend ty
  8398. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  8399. return type;
  8400. }
  8401. else {
  8402. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  8403. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  8404. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  8405. // Get new vector types for a given TypeSpecifierSign.
  8406. if (objKind == AR_TOBJ_VECTOR) {
  8407. UINT colCount = GetHLSLVecSize(type);
  8408. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  8409. return m_context->getTypeDeclType(qts);
  8410. } else if (objKind == AR_TOBJ_MATRIX) {
  8411. UINT rowCount, colCount;
  8412. GetRowsAndCols(type, rowCount, colCount);
  8413. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  8414. return m_context->getTypeDeclType(qts);
  8415. } else {
  8416. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  8417. return m_scalarTypes[newScalarType];
  8418. }
  8419. }
  8420. }
  8421. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  8422. FunctionTemplateDecl *FunctionTemplate,
  8423. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8424. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8425. {
  8426. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  8427. // Get information about the function we have.
  8428. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  8429. DXASSERT(functionMethod != nullptr,
  8430. "otherwise this is standalone function rather than a method, which isn't supported in the HLSL object model");
  8431. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  8432. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  8433. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  8434. QualType functionTemplateTypeArg {};
  8435. if (ExplicitTemplateArgs != nullptr && ExplicitTemplateArgs->size() == 1) {
  8436. const TemplateArgument &firstTemplateArg = (*ExplicitTemplateArgs)[0].getArgument();
  8437. if (firstTemplateArg.getKind() == TemplateArgument::ArgKind::Type)
  8438. functionTemplateTypeArg = firstTemplateArg.getAsType();
  8439. }
  8440. // Handle subscript overloads.
  8441. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  8442. {
  8443. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  8444. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  8445. if (!findResult.Found())
  8446. {
  8447. // This might be a nested type. Do a lookup on the parent.
  8448. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  8449. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  8450. {
  8451. return Sema::TemplateDeductionResult::TDK_Invalid;
  8452. }
  8453. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  8454. if (!findResult.Found())
  8455. {
  8456. return Sema::TemplateDeductionResult::TDK_Invalid;
  8457. }
  8458. DXASSERT(
  8459. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  8460. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  8461. "otherwise FindStructBasicType should have failed - no other types are allowed");
  8462. objectElement = GetFirstElementTypeFromDecl(
  8463. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  8464. }
  8465. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  8466. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8467. FunctionTemplate->getCanonicalDecl());
  8468. return Sema::TemplateDeductionResult::TDK_Success;
  8469. }
  8470. // Reject overload lookups that aren't identifier-based.
  8471. if (!FunctionTemplate->getDeclName().isIdentifier())
  8472. {
  8473. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8474. }
  8475. // Find the table of intrinsics based on the object type.
  8476. const HLSL_INTRINSIC* intrinsics = nullptr;
  8477. size_t intrinsicCount = 0;
  8478. const char* objectName = nullptr;
  8479. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  8480. DXASSERT(objectName != nullptr &&
  8481. (intrinsics != nullptr || m_intrinsicTables.size() > 0),
  8482. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  8483. "or the parser let a user-defined template object through");
  8484. // Look for an intrinsic for which we can match arguments.
  8485. std::vector<QualType> argTypes;
  8486. StringRef nameIdentifier = FunctionTemplate->getName();
  8487. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  8488. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  8489. while (cursor != end)
  8490. {
  8491. size_t badArgIdx;
  8492. if (!MatchArguments(*cursor, objectElement, functionTemplateTypeArg, Args, &argTypes, badArgIdx))
  8493. {
  8494. ++cursor;
  8495. continue;
  8496. }
  8497. // Currently only intrinsic we allow for explicit template arguments are
  8498. // for Load/Store for ByteAddressBuffer/RWByteAddressBuffer
  8499. // Check Explicit template arguments
  8500. UINT intrinsicOp = (*cursor)->Op;
  8501. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  8502. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  8503. bool IsBAB =
  8504. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  8505. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  8506. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  8507. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  8508. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  8509. bool isLegalTemplate = false;
  8510. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  8511. auto TemplateDiag = diag::err_hlsl_intrinsic_template_arg_unsupported;
  8512. if (ExplicitTemplateArgs->size() >= 1 && (IsBABLoad || IsBABStore)) {
  8513. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_requires_2018;
  8514. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  8515. if (Is2018) {
  8516. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_numeric;
  8517. if (ExplicitTemplateArgs->size() == 1
  8518. && !functionTemplateTypeArg.isNull()
  8519. && hlsl::IsHLSLNumericOrAggregateOfNumericType(functionTemplateTypeArg)) {
  8520. isLegalTemplate = true;
  8521. }
  8522. }
  8523. }
  8524. if (!isLegalTemplate) {
  8525. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  8526. return Sema::TemplateDeductionResult::TDK_Invalid;
  8527. }
  8528. } else if (IsBABStore) {
  8529. // Prior to HLSL 2018, Store operation only stored scalar uint.
  8530. if (!Is2018) {
  8531. if (GetNumElements(argTypes[2]) != 1) {
  8532. getSema()->Diag(Args[1]->getLocStart(),
  8533. diag::err_ovl_no_viable_member_function_in_call)
  8534. << intrinsicName;
  8535. return Sema::TemplateDeductionResult::TDK_Invalid;
  8536. }
  8537. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  8538. 32, /*signed*/ false);
  8539. }
  8540. }
  8541. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes.data(), argTypes.size());
  8542. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8543. FunctionTemplate->getCanonicalDecl());
  8544. if (!IsValidateObjectElement(*cursor, objectElement)) {
  8545. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  8546. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  8547. }
  8548. return Sema::TemplateDeductionResult::TDK_Success;
  8549. }
  8550. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8551. }
  8552. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  8553. {
  8554. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  8555. }
  8556. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  8557. QualType DestType,
  8558. Sema::CheckedConversionKind CCK,
  8559. const SourceRange &OpRange, unsigned &msg,
  8560. CastKind &Kind, CXXCastPath &BasePath,
  8561. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  8562. _Inout_opt_ StandardConversionSequence* standard)
  8563. {
  8564. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  8565. bool explicitConversion
  8566. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  8567. bool suppressWarnings = explicitConversion || SuppressWarnings;
  8568. SourceLocation loc = OpRange.getBegin();
  8569. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  8570. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  8571. // so do this here until we figure out why this is needed.
  8572. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  8573. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  8574. }
  8575. return true;
  8576. }
  8577. // ValidateCast includes its own error messages.
  8578. msg = 0;
  8579. return false;
  8580. }
  8581. /// <summary>
  8582. /// Checks if a subscript index argument can be initialized from the given expression.
  8583. /// </summary>
  8584. /// <param name="SrcExpr">Source expression used as argument.</param>
  8585. /// <param name="DestType">Parameter type to initialize.</param>
  8586. /// <remarks>
  8587. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  8588. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  8589. /// </remarks>
  8590. ImplicitConversionSequence
  8591. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  8592. clang::QualType DestType) {
  8593. DXASSERT_NOMSG(SrcExpr != nullptr);
  8594. DXASSERT_NOMSG(!DestType.isNull());
  8595. unsigned int msg = 0;
  8596. CastKind kind;
  8597. CXXCastPath path;
  8598. ImplicitConversionSequence sequence;
  8599. sequence.setStandard();
  8600. ExprResult sourceExpr(SrcExpr);
  8601. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  8602. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8603. SrcExpr->getType(), DestType);
  8604. } else if (!TryStaticCastForHLSL(
  8605. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  8606. msg, kind, path, ListInitializationFalse,
  8607. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  8608. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8609. SrcExpr->getType(), DestType);
  8610. }
  8611. return sequence;
  8612. }
  8613. template <typename T>
  8614. static
  8615. bool IsValueInRange(T value, T minValue, T maxValue) {
  8616. return minValue <= value && value <= maxValue;
  8617. }
  8618. #define D3DX_16F_MAX 6.550400e+004 // max value
  8619. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  8620. static
  8621. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  8622. {
  8623. DXASSERT_NOMSG(minValue != nullptr);
  8624. DXASSERT_NOMSG(maxValue != nullptr);
  8625. switch (basicKind) {
  8626. case AR_BASIC_MIN10FLOAT:
  8627. case AR_BASIC_MIN16FLOAT:
  8628. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  8629. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8630. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  8631. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  8632. default:
  8633. // No other float types.
  8634. break;
  8635. }
  8636. DXASSERT(false, "unreachable");
  8637. *minValue = 0; *maxValue = 0;
  8638. return;
  8639. }
  8640. static
  8641. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  8642. {
  8643. DXASSERT_NOMSG(maxValue != nullptr);
  8644. switch (basicKind) {
  8645. case AR_BASIC_BOOL: *maxValue = 1; return;
  8646. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  8647. case AR_BASIC_MIN16UINT:
  8648. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  8649. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  8650. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  8651. default:
  8652. // No other unsigned int types.
  8653. break;
  8654. }
  8655. DXASSERT(false, "unreachable");
  8656. *maxValue = 0;
  8657. return;
  8658. }
  8659. static
  8660. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  8661. {
  8662. DXASSERT_NOMSG(minValue != nullptr);
  8663. DXASSERT_NOMSG(maxValue != nullptr);
  8664. switch (basicKind) {
  8665. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  8666. case AR_BASIC_MIN12INT:
  8667. case AR_BASIC_MIN16INT:
  8668. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  8669. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  8670. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  8671. default:
  8672. // No other signed int types.
  8673. break;
  8674. }
  8675. DXASSERT(false, "unreachable");
  8676. *minValue = 0; *maxValue = 0;
  8677. return;
  8678. }
  8679. static
  8680. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  8681. {
  8682. if (IS_BASIC_FLOAT(basicKind)) {
  8683. double val;
  8684. if (value.isInt()) {
  8685. val = value.getInt().getLimitedValue();
  8686. } else if (value.isFloat()) {
  8687. llvm::APFloat floatValue = value.getFloat();
  8688. if (!floatValue.isFinite()) {
  8689. return false;
  8690. }
  8691. llvm::APFloat valueFloat = value.getFloat();
  8692. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  8693. val = value.getFloat().convertToFloat();
  8694. }
  8695. else {
  8696. val = value.getFloat().convertToDouble();
  8697. }
  8698. } else {
  8699. return false;
  8700. }
  8701. double minValue, maxValue;
  8702. GetFloatLimits(basicKind, &minValue, &maxValue);
  8703. return IsValueInRange(val, minValue, maxValue);
  8704. }
  8705. else if (IS_BASIC_SINT(basicKind)) {
  8706. if (!value.isInt()) {
  8707. return false;
  8708. }
  8709. int64_t val = value.getInt().getSExtValue();
  8710. int64_t minValue, maxValue;
  8711. GetSignedLimits(basicKind, &minValue, &maxValue);
  8712. return IsValueInRange(val, minValue, maxValue);
  8713. }
  8714. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  8715. if (!value.isInt()) {
  8716. return false;
  8717. }
  8718. uint64_t val = value.getInt().getLimitedValue();
  8719. uint64_t maxValue;
  8720. GetUnsignedLimit(basicKind, &maxValue);
  8721. return IsValueInRange(val, (uint64_t)0, maxValue);
  8722. }
  8723. else {
  8724. return false;
  8725. }
  8726. }
  8727. static
  8728. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  8729. {
  8730. DXASSERT_NOMSG(!targetType.isNull());
  8731. DXASSERT_NOMSG(sourceExpr != nullptr);
  8732. Expr::EvalResult evalResult;
  8733. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  8734. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  8735. return IsValueInBasicRange(targetKind, evalResult.Val);
  8736. }
  8737. }
  8738. return false;
  8739. }
  8740. bool HLSLExternalSource::ValidateCast(
  8741. SourceLocation OpLoc,
  8742. _In_ Expr* sourceExpr,
  8743. QualType target,
  8744. bool explicitConversion,
  8745. bool suppressWarnings,
  8746. bool suppressErrors,
  8747. _Inout_opt_ StandardConversionSequence* standard)
  8748. {
  8749. DXASSERT_NOMSG(sourceExpr != nullptr);
  8750. if (OpLoc.isInvalid())
  8751. OpLoc = sourceExpr->getExprLoc();
  8752. QualType source = sourceExpr->getType();
  8753. TYPE_CONVERSION_REMARKS remarks = TYPE_CONVERSION_NONE;
  8754. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  8755. {
  8756. //
  8757. // Check whether the lack of explicit-ness matters.
  8758. //
  8759. // Setting explicitForDiagnostics to true in that case will avoid the message
  8760. // saying anything about the implicit nature of the cast, when adding the
  8761. // explicit cast won't make a difference.
  8762. //
  8763. bool explicitForDiagnostics = explicitConversion;
  8764. if (explicitConversion == false)
  8765. {
  8766. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  8767. {
  8768. // Can't convert either way - implicit/explicit doesn't matter.
  8769. explicitForDiagnostics = true;
  8770. }
  8771. }
  8772. if (!suppressErrors)
  8773. {
  8774. bool IsOutputParameter = false;
  8775. if (clang::DeclRefExpr *OutFrom = dyn_cast<clang::DeclRefExpr>(sourceExpr)) {
  8776. if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(OutFrom->getDecl())) {
  8777. IsOutputParameter = Param->isModifierOut();
  8778. }
  8779. }
  8780. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  8781. << explicitForDiagnostics << IsOutputParameter << source << target;
  8782. }
  8783. return false;
  8784. }
  8785. if (!suppressWarnings)
  8786. {
  8787. if (!explicitConversion)
  8788. {
  8789. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  8790. {
  8791. // This is a much more restricted version of the analysis does
  8792. // StandardConversionSequence::getNarrowingKind
  8793. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  8794. {
  8795. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  8796. }
  8797. }
  8798. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  8799. {
  8800. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  8801. }
  8802. }
  8803. }
  8804. return true;
  8805. }
  8806. ////////////////////////////////////////////////////////////////////////////////
  8807. // Functions exported from this translation unit. //
  8808. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  8809. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  8810. SourceLocation OpLoc,
  8811. UnaryOperatorKind Opc,
  8812. ExprResult& InputExpr,
  8813. ExprValueKind& VK,
  8814. ExprObjectKind& OK)
  8815. {
  8816. ExternalSemaSource* externalSource = self.getExternalSource();
  8817. if (externalSource == nullptr) {
  8818. return QualType();
  8819. }
  8820. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8821. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  8822. }
  8823. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  8824. void hlsl::CheckBinOpForHLSL(Sema& self,
  8825. SourceLocation OpLoc,
  8826. BinaryOperatorKind Opc,
  8827. ExprResult& LHS,
  8828. ExprResult& RHS,
  8829. QualType& ResultTy,
  8830. QualType& CompLHSTy,
  8831. QualType& CompResultTy)
  8832. {
  8833. ExternalSemaSource* externalSource = self.getExternalSource();
  8834. if (externalSource == nullptr) {
  8835. return;
  8836. }
  8837. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8838. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  8839. }
  8840. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  8841. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  8842. {
  8843. DXASSERT_NOMSG(Template != nullptr);
  8844. ExternalSemaSource* externalSource = self.getExternalSource();
  8845. if (externalSource == nullptr) {
  8846. return false;
  8847. }
  8848. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8849. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  8850. }
  8851. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  8852. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  8853. FunctionTemplateDecl *FunctionTemplate,
  8854. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8855. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8856. {
  8857. return HLSLExternalSource::FromSema(self)
  8858. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  8859. }
  8860. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  8861. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  8862. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  8863. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  8864. self->Diag(condExpr->getLocStart(),
  8865. diag::err_hlsl_control_flow_cond_not_scalar)
  8866. << StmtName;
  8867. return;
  8868. }
  8869. condExpr = IC->getSubExpr();
  8870. }
  8871. }
  8872. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  8873. {
  8874. // TODO: handle shorthand cases.
  8875. return left.size() == 0 || right.size() == 0 || left.equals(right);
  8876. }
  8877. void hlsl::DiagnosePackingOffset(
  8878. clang::Sema* self,
  8879. SourceLocation loc,
  8880. clang::QualType type,
  8881. int componentOffset)
  8882. {
  8883. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  8884. if (componentOffset > 0) {
  8885. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8886. ArBasicKind element = source->GetTypeElementKind(type);
  8887. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  8888. // Only perform some simple validation for now.
  8889. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  8890. int count = GetElementCount(type);
  8891. if (count > (4 - componentOffset)) {
  8892. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  8893. }
  8894. }
  8895. }
  8896. }
  8897. void hlsl::DiagnoseRegisterType(
  8898. clang::Sema* self,
  8899. clang::SourceLocation loc,
  8900. clang::QualType type,
  8901. char registerType)
  8902. {
  8903. // Register type can be zero if only a register space was provided.
  8904. if (registerType == 0)
  8905. return;
  8906. if (registerType >= 'A' && registerType <= 'Z')
  8907. registerType = registerType + ('a' - 'A');
  8908. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8909. ArBasicKind element = source->GetTypeElementKind(type);
  8910. StringRef expected("none");
  8911. bool isValid = true;
  8912. bool isWarning = false;
  8913. switch (element)
  8914. {
  8915. case AR_BASIC_BOOL:
  8916. case AR_BASIC_LITERAL_FLOAT:
  8917. case AR_BASIC_FLOAT16:
  8918. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8919. case AR_BASIC_FLOAT32:
  8920. case AR_BASIC_FLOAT64:
  8921. case AR_BASIC_LITERAL_INT:
  8922. case AR_BASIC_INT8:
  8923. case AR_BASIC_UINT8:
  8924. case AR_BASIC_INT16:
  8925. case AR_BASIC_UINT16:
  8926. case AR_BASIC_INT32:
  8927. case AR_BASIC_UINT32:
  8928. case AR_BASIC_INT64:
  8929. case AR_BASIC_UINT64:
  8930. case AR_BASIC_MIN10FLOAT:
  8931. case AR_BASIC_MIN16FLOAT:
  8932. case AR_BASIC_MIN12INT:
  8933. case AR_BASIC_MIN16INT:
  8934. case AR_BASIC_MIN16UINT:
  8935. expected = "'b', 'c', or 'i'";
  8936. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i';
  8937. break;
  8938. case AR_OBJECT_TEXTURE1D:
  8939. case AR_OBJECT_TEXTURE1D_ARRAY:
  8940. case AR_OBJECT_TEXTURE2D:
  8941. case AR_OBJECT_TEXTURE2D_ARRAY:
  8942. case AR_OBJECT_TEXTURE3D:
  8943. case AR_OBJECT_TEXTURECUBE:
  8944. case AR_OBJECT_TEXTURECUBE_ARRAY:
  8945. case AR_OBJECT_TEXTURE2DMS:
  8946. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  8947. expected = "'t' or 's'";
  8948. isValid = registerType == 't' || registerType == 's';
  8949. break;
  8950. case AR_OBJECT_SAMPLER:
  8951. case AR_OBJECT_SAMPLER1D:
  8952. case AR_OBJECT_SAMPLER2D:
  8953. case AR_OBJECT_SAMPLER3D:
  8954. case AR_OBJECT_SAMPLERCUBE:
  8955. case AR_OBJECT_SAMPLERCOMPARISON:
  8956. expected = "'s' or 't'";
  8957. isValid = registerType == 's' || registerType == 't';
  8958. break;
  8959. case AR_OBJECT_BUFFER:
  8960. expected = "'t'";
  8961. isValid = registerType == 't';
  8962. break;
  8963. case AR_OBJECT_POINTSTREAM:
  8964. case AR_OBJECT_LINESTREAM:
  8965. case AR_OBJECT_TRIANGLESTREAM:
  8966. isValid = false;
  8967. isWarning = true;
  8968. break;
  8969. case AR_OBJECT_INPUTPATCH:
  8970. case AR_OBJECT_OUTPUTPATCH:
  8971. isValid = false;
  8972. isWarning = true;
  8973. break;
  8974. case AR_OBJECT_RWTEXTURE1D:
  8975. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  8976. case AR_OBJECT_RWTEXTURE2D:
  8977. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  8978. case AR_OBJECT_RWTEXTURE3D:
  8979. case AR_OBJECT_RWBUFFER:
  8980. expected = "'u'";
  8981. isValid = registerType == 'u';
  8982. break;
  8983. case AR_OBJECT_BYTEADDRESS_BUFFER:
  8984. case AR_OBJECT_STRUCTURED_BUFFER:
  8985. expected = "'t'";
  8986. isValid = registerType == 't';
  8987. break;
  8988. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  8989. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  8990. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  8991. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  8992. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  8993. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  8994. expected = "'u'";
  8995. isValid = registerType == 'u';
  8996. break;
  8997. case AR_OBJECT_CONSTANT_BUFFER:
  8998. expected = "'b'";
  8999. isValid = registerType == 'b';
  9000. break;
  9001. case AR_OBJECT_TEXTURE_BUFFER:
  9002. expected = "'t'";
  9003. isValid = registerType == 't';
  9004. break;
  9005. case AR_OBJECT_ROVBUFFER:
  9006. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  9007. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  9008. case AR_OBJECT_ROVTEXTURE1D:
  9009. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  9010. case AR_OBJECT_ROVTEXTURE2D:
  9011. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  9012. case AR_OBJECT_ROVTEXTURE3D:
  9013. case AR_OBJECT_FEEDBACKTEXTURE2D:
  9014. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  9015. expected = "'u'";
  9016. isValid = registerType == 'u';
  9017. break;
  9018. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  9019. isWarning = true;
  9020. break; // So we don't care what you tried to bind it to
  9021. default: // Other types have no associated registers.
  9022. break;
  9023. }
  9024. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  9025. // a warning instead.
  9026. if (!isValid) {
  9027. unsigned DiagID = isWarning ? diag::warn_hlsl_incorrect_bind_semantic : diag::err_hlsl_incorrect_bind_semantic;
  9028. self->Diag(loc, DiagID) << expected;
  9029. }
  9030. }
  9031. struct NameLookup {
  9032. FunctionDecl *Found;
  9033. FunctionDecl *Other;
  9034. };
  9035. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  9036. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  9037. FunctionDecl *pFoundDecl = nullptr;
  9038. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  9039. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  9040. if (!pFnDecl) continue;
  9041. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  9042. if (pFoundDecl) {
  9043. return NameLookup{ pFoundDecl, pFnDecl };
  9044. }
  9045. pFoundDecl = pFnDecl;
  9046. }
  9047. return NameLookup{ pFoundDecl, nullptr };
  9048. }
  9049. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  9050. DXASSERT_NOMSG(self != nullptr);
  9051. // Don't bother with global validation if compilation has already failed.
  9052. if (self->getDiagnostics().hasErrorOccurred()) {
  9053. return;
  9054. }
  9055. // Check RT shader if available for their payload use and match payload access
  9056. // against availiable payload modifiers.
  9057. // We have to do it late because we could have payload access in a called function
  9058. // and have to check the callgraph if the root shader has the right access
  9059. // rights to the payload structure.
  9060. if (self->getLangOpts().IsHLSLLibrary) {
  9061. if (self->getLangOpts().EnablePayloadAccessQualifiers) {
  9062. ASTContext &ctx = self->getASTContext();
  9063. TranslationUnitDecl *TU = ctx.getTranslationUnitDecl();
  9064. DiagnoseRaytracingPayloadAccess(*self, TU);
  9065. }
  9066. }
  9067. // Don't check entry function for library.
  9068. if (self->getLangOpts().IsHLSLLibrary) {
  9069. // TODO: validate no recursion start from every function.
  9070. return;
  9071. }
  9072. // TODO: make these error 'real' errors rather than on-the-fly things
  9073. // Validate that the entry point is available.
  9074. DiagnosticsEngine &Diags = self->getDiagnostics();
  9075. FunctionDecl *pEntryPointDecl = nullptr;
  9076. FunctionDecl *pPatchFnDecl = nullptr;
  9077. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  9078. if (!EntryPointName.empty()) {
  9079. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  9080. if (NL.Found && NL.Other) {
  9081. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  9082. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  9083. // string, and so ambiguous points will produce an error earlier on.
  9084. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9085. "ambiguous entry point function");
  9086. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  9087. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  9088. return;
  9089. }
  9090. pEntryPointDecl = NL.Found;
  9091. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  9092. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9093. "missing entry point definition");
  9094. Diags.Report(id);
  9095. return;
  9096. }
  9097. }
  9098. // Validate that there is no recursion; start with the entry function.
  9099. // NOTE: the information gathered here could be used to bypass code generation
  9100. // on functions that are unreachable (as an early form of dead code elimination).
  9101. if (pEntryPointDecl) {
  9102. const auto *shaderModel =
  9103. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  9104. if (shaderModel->IsGS()) {
  9105. // Validate that GS has the maxvertexcount attribute
  9106. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  9107. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9108. << "GS"
  9109. << "maxvertexcount";
  9110. return;
  9111. }
  9112. } else if (shaderModel->IsHS()) {
  9113. if (const HLSLPatchConstantFuncAttr *Attr =
  9114. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  9115. NameLookup NL = GetSingleFunctionDeclByName(
  9116. self, Attr->getFunctionName(), /*checkPatch*/ true);
  9117. if (!NL.Found || !NL.Found->hasBody()) {
  9118. unsigned id =
  9119. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9120. "missing patch function definition");
  9121. Diags.Report(id);
  9122. return;
  9123. }
  9124. pPatchFnDecl = NL.Found;
  9125. } else {
  9126. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9127. << "HS"
  9128. << "patchconstantfunc";
  9129. return;
  9130. }
  9131. } else if (shaderModel->IsMS()) {
  9132. // Validate that MS has the numthreads attribute
  9133. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  9134. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9135. << "MS"
  9136. << "numthreads";
  9137. return;
  9138. }
  9139. // Validate that MS has the outputtopology attribute
  9140. if (!pEntryPointDecl->hasAttr<HLSLOutputTopologyAttr>()) {
  9141. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9142. << "MS"
  9143. << "outputtopology";
  9144. return;
  9145. }
  9146. } else if (shaderModel->IsAS()) {
  9147. // Validate that AS has the numthreads attribute
  9148. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  9149. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  9150. << "AS"
  9151. << "numthreads";
  9152. return;
  9153. }
  9154. }
  9155. hlsl::CallGraphWithRecurseGuard CG;
  9156. CG.BuildForEntry(pEntryPointDecl);
  9157. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  9158. if (pResult) {
  9159. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9160. "recursive functions not allowed");
  9161. Diags.Report(pResult->getSourceRange().getBegin(), id);
  9162. }
  9163. if (pPatchFnDecl) {
  9164. CG.BuildForEntry(pPatchFnDecl);
  9165. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  9166. if (pPatchFnDecl) {
  9167. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  9168. "recursive functions not allowed (via patch function)");
  9169. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  9170. }
  9171. }
  9172. }
  9173. }
  9174. void hlsl::DiagnosePayloadAccessQualifierAnnotations(
  9175. Sema &S, Declarator& D, const QualType& T, const std::vector<hlsl::UnusualAnnotation *>& annotations) {
  9176. auto &&iter = annotations.begin();
  9177. auto &&end = annotations.end();
  9178. hlsl::PayloadAccessAnnotation *readAnnotation = nullptr;
  9179. hlsl::PayloadAccessAnnotation *writeAnnotation = nullptr;
  9180. for (; iter != end; ++iter) {
  9181. switch ((*iter)->getKind()) {
  9182. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  9183. hlsl::PayloadAccessAnnotation *annotation =
  9184. cast<hlsl::PayloadAccessAnnotation>(*iter);
  9185. if (annotation->qualifier == DXIL::PayloadAccessQualifier::Read) {
  9186. if (!readAnnotation)
  9187. readAnnotation = annotation;
  9188. else {
  9189. S.Diag(annotation->Loc,
  9190. diag::err_hlsl_payload_access_qualifier_multiple_defined)
  9191. << "read";
  9192. return;
  9193. }
  9194. } else if (annotation->qualifier == DXIL::PayloadAccessQualifier::Write) {
  9195. if (!writeAnnotation)
  9196. writeAnnotation = annotation;
  9197. else {
  9198. S.Diag(annotation->Loc,
  9199. diag::err_hlsl_payload_access_qualifier_multiple_defined)
  9200. << "write";
  9201. return;
  9202. }
  9203. }
  9204. break;
  9205. }
  9206. default:
  9207. // Ignore all other annotations here.
  9208. break;
  9209. }
  9210. }
  9211. struct PayloadAccessQualifierInformation{
  9212. bool anyhit = false;
  9213. bool closesthit = false;
  9214. bool miss = false;
  9215. bool caller = false;
  9216. } readQualContains, writeQualContains;
  9217. auto collectInformationAboutShaderStages =
  9218. [&](hlsl::PayloadAccessAnnotation *annotation,
  9219. PayloadAccessQualifierInformation &info) {
  9220. for (auto shaderType : annotation->ShaderStages) {
  9221. if (shaderType == DXIL::PayloadAccessShaderStage::Anyhit)
  9222. info.anyhit = true;
  9223. else if (shaderType == DXIL::PayloadAccessShaderStage::Closesthit)
  9224. info.closesthit = true;
  9225. else if (shaderType == DXIL::PayloadAccessShaderStage::Miss)
  9226. info.miss = true;
  9227. else if (shaderType == DXIL::PayloadAccessShaderStage::Caller)
  9228. info.caller = true;
  9229. }
  9230. return true;
  9231. };
  9232. if (readAnnotation) {
  9233. if (!collectInformationAboutShaderStages(readAnnotation, readQualContains))
  9234. return;
  9235. }
  9236. if (writeAnnotation) {
  9237. if (!collectInformationAboutShaderStages(writeAnnotation, writeQualContains))
  9238. return;
  9239. }
  9240. if (writeAnnotation) {
  9241. // Note: keep the following two checks separated to diagnose both
  9242. // stages (closesthit and miss)
  9243. // If closesthit/miss writes a value the caller must consume it.
  9244. if (writeQualContains.miss) {
  9245. if (!readAnnotation || !readQualContains.caller) {
  9246. S.Diag(writeAnnotation->Loc,
  9247. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9248. << D.getIdentifier()
  9249. << "write"
  9250. << "miss"
  9251. << "consumer";
  9252. }
  9253. }
  9254. if (writeQualContains.closesthit) {
  9255. if (!readAnnotation || !readQualContains.caller) {
  9256. S.Diag(writeAnnotation->Loc,
  9257. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9258. << D.getIdentifier()
  9259. << "write"
  9260. << "closesthit"
  9261. << "consumer";
  9262. }
  9263. }
  9264. // If anyhit writes, we need at least one consumer
  9265. if (writeQualContains.anyhit && !readAnnotation) {
  9266. S.Diag(writeAnnotation->Loc,
  9267. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9268. << D.getIdentifier()
  9269. << "write"
  9270. << "anyhit"
  9271. << "consumer";
  9272. }
  9273. // If the caller writes, we need at least one consumer
  9274. if (writeQualContains.caller && !readAnnotation) {
  9275. S.Diag(writeAnnotation->Loc,
  9276. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9277. << D.getIdentifier()
  9278. << "write"
  9279. << "caller"
  9280. << "consumer";
  9281. }
  9282. }
  9283. // Validate the read qualifer if present.
  9284. if (readAnnotation) {
  9285. // Note: keep the following two checks separated to diagnose both
  9286. // stages (closesthit and miss)
  9287. // If closeshit/miss consume a value we need a producer.
  9288. // Valid producers are the caller and anyhit.
  9289. if (readQualContains.miss) {
  9290. if (!writeAnnotation ||
  9291. !(writeQualContains.anyhit || writeQualContains.caller)) {
  9292. S.Diag(readAnnotation->Loc,
  9293. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9294. << D.getIdentifier()
  9295. << "read"
  9296. << "miss"
  9297. << "producer";
  9298. }
  9299. }
  9300. // If closeshit/miss consume a value we need a producer.
  9301. // Valid producers are the caller and anyhit.
  9302. if (readQualContains.closesthit) {
  9303. if (!writeAnnotation ||
  9304. !(writeQualContains.anyhit || writeQualContains.caller)) {
  9305. S.Diag(readAnnotation->Loc,
  9306. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9307. << D.getIdentifier()
  9308. << "read"
  9309. << "closesthit"
  9310. << "producer";
  9311. }
  9312. }
  9313. // If anyhit consumes the value we need a producer.
  9314. // Valid producers are the caller and antoher anyhit.
  9315. if (readQualContains.anyhit) {
  9316. if (!writeAnnotation ||
  9317. !(writeQualContains.anyhit || writeQualContains.caller)) {
  9318. S.Diag(readAnnotation->Loc,
  9319. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9320. << D.getIdentifier()
  9321. << "read"
  9322. << "anyhit"
  9323. << "producer";
  9324. }
  9325. }
  9326. // If the caller consumes the value we need a valid producer.
  9327. if (readQualContains.caller && !writeAnnotation) {
  9328. S.Diag(readAnnotation->Loc,
  9329. diag::err_hlsl_payload_access_qualifier_invalid_combination)
  9330. << D.getIdentifier()
  9331. << "read"
  9332. << "caller"
  9333. << "producer";
  9334. }
  9335. }
  9336. }
  9337. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  9338. Sema& S,
  9339. std::vector<hlsl::UnusualAnnotation *>& annotations)
  9340. {
  9341. bool packoffsetOverriddenReported = false;
  9342. auto && iter = annotations.begin();
  9343. auto && end = annotations.end();
  9344. for (; iter != end; ++iter) {
  9345. switch ((*iter)->getKind()) {
  9346. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9347. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  9348. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  9349. if (!packoffsetOverriddenReported) {
  9350. auto newIter = iter;
  9351. ++newIter;
  9352. while (newIter != end) {
  9353. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  9354. if (other != nullptr &&
  9355. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  9356. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  9357. packoffsetOverriddenReported = true;
  9358. break;
  9359. }
  9360. ++newIter;
  9361. }
  9362. }
  9363. break;
  9364. }
  9365. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9366. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  9367. // Check whether this will conflict with other register assignments of the same type.
  9368. auto newIter = iter;
  9369. ++newIter;
  9370. while (newIter != end) {
  9371. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  9372. // Same register bank and profile, but different number.
  9373. if (other != nullptr &&
  9374. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  9375. other->RegisterType == registerAssignment->RegisterType &&
  9376. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  9377. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  9378. // Obvious conflict - report it up front.
  9379. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  9380. }
  9381. ++newIter;
  9382. }
  9383. break;
  9384. }
  9385. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9386. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  9387. // No common validation to be performed.
  9388. break;
  9389. }
  9390. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  9391. // Validation happens sperately
  9392. break;
  9393. }
  9394. }
  9395. }
  9396. }
  9397. clang::OverloadingResult
  9398. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  9399. clang::OverloadCandidateSet &set,
  9400. clang::OverloadCandidateSet::iterator &Best) {
  9401. return HLSLExternalSource::FromSema(&S)
  9402. ->GetBestViableFunction(Loc, set, Best);
  9403. }
  9404. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  9405. const InitializedEntity &Entity,
  9406. const InitializationKind &Kind,
  9407. MultiExprArg Args,
  9408. bool TopLevelOfInitList,
  9409. InitializationSequence *initSequence) {
  9410. return HLSLExternalSource::FromSema(self)
  9411. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  9412. }
  9413. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  9414. const clang::InitListExpr *InitList) {
  9415. unsigned totalSize = 0;
  9416. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  9417. const clang::Expr *EltInit = InitList->getInit(i);
  9418. QualType EltInitTy = EltInit->getType();
  9419. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  9420. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  9421. } else {
  9422. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  9423. }
  9424. }
  9425. return totalSize;
  9426. }
  9427. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  9428. _In_ clang::Sema* sema,
  9429. _In_ const clang::InitListExpr *InitList,
  9430. _In_ const clang::QualType EltTy) {
  9431. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  9432. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  9433. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  9434. if (totalSize > 0 && (totalSize % eltSize)==0) {
  9435. return totalSize / eltSize;
  9436. } else {
  9437. return 0;
  9438. }
  9439. }
  9440. bool hlsl::IsConversionToLessOrEqualElements(
  9441. _In_ clang::Sema* self,
  9442. const clang::ExprResult& sourceExpr,
  9443. const clang::QualType& targetType,
  9444. bool explicitConversion)
  9445. {
  9446. return HLSLExternalSource::FromSema(self)
  9447. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  9448. }
  9449. ExprResult hlsl::LookupMatrixMemberExprForHLSL(
  9450. Sema* self,
  9451. Expr& BaseExpr,
  9452. DeclarationName MemberName,
  9453. bool IsArrow,
  9454. SourceLocation OpLoc,
  9455. SourceLocation MemberLoc)
  9456. {
  9457. return HLSLExternalSource::FromSema(self)
  9458. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9459. }
  9460. ExprResult hlsl::LookupVectorMemberExprForHLSL(
  9461. Sema* self,
  9462. Expr& BaseExpr,
  9463. DeclarationName MemberName,
  9464. bool IsArrow,
  9465. SourceLocation OpLoc,
  9466. SourceLocation MemberLoc)
  9467. {
  9468. return HLSLExternalSource::FromSema(self)
  9469. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9470. }
  9471. ExprResult hlsl::LookupArrayMemberExprForHLSL(
  9472. Sema* self,
  9473. Expr& BaseExpr,
  9474. DeclarationName MemberName,
  9475. bool IsArrow,
  9476. SourceLocation OpLoc,
  9477. SourceLocation MemberLoc)
  9478. {
  9479. return HLSLExternalSource::FromSema(self)
  9480. ->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9481. }
  9482. bool hlsl::LookupRecordMemberExprForHLSL(
  9483. Sema* self,
  9484. Expr& BaseExpr,
  9485. DeclarationName MemberName,
  9486. bool IsArrow,
  9487. SourceLocation OpLoc,
  9488. SourceLocation MemberLoc,
  9489. ExprResult &result)
  9490. {
  9491. HLSLExternalSource *source = HLSLExternalSource::FromSema(self);
  9492. switch (source->GetTypeObjectKind(BaseExpr.getType())) {
  9493. case AR_TOBJ_MATRIX:
  9494. result = source->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9495. return true;
  9496. case AR_TOBJ_VECTOR:
  9497. result = source->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9498. return true;
  9499. case AR_TOBJ_ARRAY:
  9500. result = source->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9501. return true;
  9502. default:
  9503. return false;
  9504. }
  9505. return false;
  9506. }
  9507. clang::ExprResult hlsl::MaybeConvertMemberAccess(
  9508. _In_ clang::Sema* self,
  9509. _In_ clang::Expr* E)
  9510. {
  9511. return HLSLExternalSource::FromSema(self)->MaybeConvertMemberAccess(E);
  9512. }
  9513. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  9514. QualType DestType,
  9515. Sema::CheckedConversionKind CCK,
  9516. const SourceRange &OpRange, unsigned &msg,
  9517. CastKind &Kind, CXXCastPath &BasePath,
  9518. bool ListInitialization,
  9519. bool SuppressDiagnostics,
  9520. _Inout_opt_ StandardConversionSequence* standard)
  9521. {
  9522. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  9523. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  9524. SuppressDiagnostics, SuppressDiagnostics, standard);
  9525. }
  9526. clang::ExprResult hlsl::PerformHLSLConversion(
  9527. _In_ clang::Sema* self,
  9528. _In_ clang::Expr* From,
  9529. _In_ clang::QualType targetType,
  9530. _In_ const clang::StandardConversionSequence &SCS,
  9531. _In_ clang::Sema::CheckedConversionKind CCK)
  9532. {
  9533. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  9534. }
  9535. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  9536. _In_ clang::Sema* self,
  9537. _In_ clang::Expr* SrcExpr,
  9538. clang::QualType DestType)
  9539. {
  9540. return HLSLExternalSource::FromSema(self)
  9541. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  9542. }
  9543. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  9544. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  9545. {
  9546. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  9547. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  9548. if (hlslSource->Initialize(context)) {
  9549. context.setExternalSource(externalSource);
  9550. }
  9551. }
  9552. ////////////////////////////////////////////////////////////////////////////////
  9553. // FlattenedTypeIterator implementation //
  9554. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  9555. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  9556. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9557. {
  9558. if (pushTrackerForType(type, nullptr)) {
  9559. while (!m_typeTrackers.empty() && !considerLeaf())
  9560. consumeLeaf();
  9561. }
  9562. }
  9563. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  9564. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  9565. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9566. {
  9567. if (!args.empty()) {
  9568. MultiExprArg::iterator ii = args.begin();
  9569. MultiExprArg::iterator ie = args.end();
  9570. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  9571. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9572. if (!considerLeaf()) {
  9573. m_typeTrackers.clear();
  9574. }
  9575. }
  9576. }
  9577. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  9578. QualType FlattenedTypeIterator::getCurrentElement() const
  9579. {
  9580. return m_typeTrackers.back().Type;
  9581. }
  9582. /// <summary>Get the number of repeated current elements.</summary>
  9583. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  9584. {
  9585. const FlattenedTypeTracker& back = m_typeTrackers.back();
  9586. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  9587. }
  9588. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  9589. bool FlattenedTypeIterator::hasCurrentElement() const
  9590. {
  9591. return m_typeTrackers.size() > 0;
  9592. }
  9593. /// <summary>Consumes count elements on this iterator.</summary>
  9594. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  9595. {
  9596. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9597. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  9598. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9599. if (tracker.IterKind == FK_IncompleteArray)
  9600. {
  9601. tracker.Count += count;
  9602. m_springLoaded = true;
  9603. }
  9604. else
  9605. {
  9606. tracker.Count -= count;
  9607. m_springLoaded = false;
  9608. if (m_typeTrackers.back().Count == 0)
  9609. {
  9610. advanceLeafTracker();
  9611. }
  9612. }
  9613. }
  9614. unsigned int FlattenedTypeIterator::countRemaining()
  9615. {
  9616. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  9617. size_t result = 0;
  9618. while (hasCurrentElement() && !m_springLoaded)
  9619. {
  9620. size_t pending = getCurrentElementSize();
  9621. result += pending;
  9622. advanceCurrentElement(pending);
  9623. }
  9624. return result;
  9625. }
  9626. void FlattenedTypeIterator::advanceLeafTracker()
  9627. {
  9628. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9629. for (;;)
  9630. {
  9631. consumeLeaf();
  9632. if (m_typeTrackers.empty()) {
  9633. return;
  9634. }
  9635. if (considerLeaf()) {
  9636. return;
  9637. }
  9638. }
  9639. }
  9640. bool FlattenedTypeIterator::considerLeaf()
  9641. {
  9642. if (m_typeTrackers.empty()) {
  9643. return false;
  9644. }
  9645. m_typeDepth++;
  9646. if (m_typeDepth > MaxTypeDepth) {
  9647. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  9648. m_typeTrackers.clear();
  9649. m_typeDepth--;
  9650. return false;
  9651. }
  9652. bool result = false;
  9653. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9654. tracker.IsConsidered = true;
  9655. switch (tracker.IterKind) {
  9656. case FlattenedIterKind::FK_Expressions:
  9657. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  9658. result = considerLeaf();
  9659. }
  9660. break;
  9661. case FlattenedIterKind::FK_Fields:
  9662. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  9663. result = considerLeaf();
  9664. }
  9665. break;
  9666. case FlattenedIterKind::FK_Bases:
  9667. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  9668. result = considerLeaf();
  9669. }
  9670. break;
  9671. case FlattenedIterKind::FK_IncompleteArray:
  9672. m_springLoaded = true; // fall through.
  9673. default:
  9674. case FlattenedIterKind::FK_Simple: {
  9675. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  9676. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  9677. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT &&
  9678. objectKind != ArTypeObjectKind::AR_TOBJ_STRING) {
  9679. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  9680. result = considerLeaf();
  9681. }
  9682. } else {
  9683. result = true;
  9684. }
  9685. }
  9686. }
  9687. m_typeDepth--;
  9688. return result;
  9689. }
  9690. void FlattenedTypeIterator::consumeLeaf()
  9691. {
  9692. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  9693. for (;;) {
  9694. if (m_typeTrackers.empty()) {
  9695. return;
  9696. }
  9697. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9698. // Reach a leaf which is not considered before.
  9699. // Stop here.
  9700. if (!tracker.IsConsidered) {
  9701. break;
  9702. }
  9703. switch (tracker.IterKind) {
  9704. case FlattenedIterKind::FK_Expressions:
  9705. ++tracker.CurrentExpr;
  9706. if (tracker.CurrentExpr == tracker.EndExpr) {
  9707. m_typeTrackers.pop_back();
  9708. topConsumed = false;
  9709. } else {
  9710. return;
  9711. }
  9712. break;
  9713. case FlattenedIterKind::FK_Fields:
  9714. ++tracker.CurrentField;
  9715. if (tracker.CurrentField == tracker.EndField) {
  9716. m_typeTrackers.pop_back();
  9717. topConsumed = false;
  9718. } else {
  9719. return;
  9720. }
  9721. break;
  9722. case FlattenedIterKind::FK_Bases:
  9723. ++tracker.CurrentBase;
  9724. if (tracker.CurrentBase == tracker.EndBase) {
  9725. m_typeTrackers.pop_back();
  9726. topConsumed = false;
  9727. } else {
  9728. return;
  9729. }
  9730. break;
  9731. case FlattenedIterKind::FK_IncompleteArray:
  9732. if (m_draining) {
  9733. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  9734. m_incompleteCount = tracker.Count;
  9735. m_typeTrackers.pop_back();
  9736. }
  9737. return;
  9738. default:
  9739. case FlattenedIterKind::FK_Simple: {
  9740. m_springLoaded = false;
  9741. if (!topConsumed) {
  9742. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  9743. --tracker.Count;
  9744. }
  9745. else {
  9746. topConsumed = false;
  9747. }
  9748. if (tracker.Count == 0) {
  9749. m_typeTrackers.pop_back();
  9750. } else {
  9751. return;
  9752. }
  9753. }
  9754. }
  9755. }
  9756. }
  9757. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  9758. {
  9759. Expr* e = *expression;
  9760. Stmt::StmtClass expressionClass = e->getStmtClass();
  9761. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  9762. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  9763. if (initExpr->getNumInits() == 0) {
  9764. return false;
  9765. }
  9766. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  9767. MultiExprArg::iterator ii = inits.begin();
  9768. MultiExprArg::iterator ie = inits.end();
  9769. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  9770. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9771. return true;
  9772. }
  9773. return pushTrackerForType(e->getType(), expression);
  9774. }
  9775. // TODO: improve this to provide a 'peek' at intermediate types,
  9776. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  9777. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  9778. {
  9779. if (type->isVoidType()) {
  9780. return false;
  9781. }
  9782. if (type->isFunctionType()) {
  9783. return false;
  9784. }
  9785. if (m_firstType.isNull()) {
  9786. m_firstType = type;
  9787. }
  9788. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  9789. QualType elementType;
  9790. unsigned int elementCount;
  9791. const RecordType* recordType;
  9792. RecordDecl::field_iterator fi, fe;
  9793. switch (objectKind)
  9794. {
  9795. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  9796. // TODO: handle multi-dimensional arrays
  9797. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  9798. elementCount = GetArraySize(type);
  9799. if (elementCount == 0) {
  9800. if (type->isIncompleteArrayType()) {
  9801. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  9802. return true;
  9803. }
  9804. return false;
  9805. }
  9806. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9807. elementType, elementCount, nullptr));
  9808. return true;
  9809. case ArTypeObjectKind::AR_TOBJ_BASIC:
  9810. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  9811. return true;
  9812. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  9813. recordType = type->getAsStructureType();
  9814. if (recordType == nullptr)
  9815. recordType = dyn_cast<RecordType>(type.getTypePtr());
  9816. fi = recordType->getDecl()->field_begin();
  9817. fe = recordType->getDecl()->field_end();
  9818. bool bAddTracker = false;
  9819. // Skip empty struct.
  9820. if (fi != fe) {
  9821. m_typeTrackers.push_back(
  9822. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9823. type = (*fi)->getType();
  9824. bAddTracker = true;
  9825. }
  9826. if (CXXRecordDecl *cxxRecordDecl =
  9827. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  9828. // We'll error elsewhere if the record has no definition,
  9829. // just don't attempt to use it.
  9830. if (cxxRecordDecl->hasDefinition()) {
  9831. CXXRecordDecl::base_class_iterator bi, be;
  9832. bi = cxxRecordDecl->bases_begin();
  9833. be = cxxRecordDecl->bases_end();
  9834. if (bi != be) {
  9835. // Add type tracker for base.
  9836. // Add base after child to make sure base considered first.
  9837. m_typeTrackers.push_back(
  9838. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  9839. bAddTracker = true;
  9840. }
  9841. }
  9842. }
  9843. return bAddTracker;
  9844. }
  9845. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  9846. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9847. m_source.GetMatrixOrVectorElementType(type),
  9848. GetElementCount(type), nullptr));
  9849. return true;
  9850. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  9851. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9852. m_source.GetMatrixOrVectorElementType(type),
  9853. GetHLSLVecSize(type), nullptr));
  9854. return true;
  9855. case ArTypeObjectKind::AR_TOBJ_OBJECT: {
  9856. if (m_source.IsSubobjectType(type)) {
  9857. // subobjects are initialized with initialization lists
  9858. recordType = type->getAsStructureType();
  9859. fi = recordType->getDecl()->field_begin();
  9860. fe = recordType->getDecl()->field_end();
  9861. m_typeTrackers.push_back(
  9862. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9863. return true;
  9864. }
  9865. else {
  9866. // Object have no sub-types.
  9867. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9868. type.getCanonicalType(), 1, expression));
  9869. return true;
  9870. }
  9871. }
  9872. case ArTypeObjectKind::AR_TOBJ_STRING: {
  9873. // Strings have no sub-types.
  9874. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9875. type.getCanonicalType(), 1, expression));
  9876. return true;
  9877. }
  9878. default:
  9879. DXASSERT(false, "unreachable");
  9880. return false;
  9881. }
  9882. }
  9883. FlattenedTypeIterator::ComparisonResult
  9884. FlattenedTypeIterator::CompareIterators(
  9885. HLSLExternalSource& source,
  9886. SourceLocation loc,
  9887. FlattenedTypeIterator& leftIter,
  9888. FlattenedTypeIterator& rightIter)
  9889. {
  9890. FlattenedTypeIterator::ComparisonResult result;
  9891. result.LeftCount = 0;
  9892. result.RightCount = 0;
  9893. result.AreElementsEqual = true; // Until proven otherwise.
  9894. result.CanConvertElements = true; // Until proven otherwise.
  9895. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  9896. {
  9897. Expr* actualExpr = rightIter.getExprOrNull();
  9898. bool hasExpr = actualExpr != nullptr;
  9899. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  9900. StandardConversionSequence standard;
  9901. ExprResult convertedExpr;
  9902. if (!source.CanConvert(loc,
  9903. hasExpr ? actualExpr : &scratchExpr,
  9904. leftIter.getCurrentElement(),
  9905. ExplicitConversionFalse,
  9906. nullptr,
  9907. &standard)) {
  9908. result.AreElementsEqual = false;
  9909. result.CanConvertElements = false;
  9910. break;
  9911. }
  9912. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  9913. {
  9914. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  9915. leftIter.getCurrentElement(),
  9916. standard,
  9917. Sema::AA_Casting,
  9918. Sema::CCK_ImplicitConversion);
  9919. }
  9920. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  9921. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  9922. {
  9923. result.AreElementsEqual = false;
  9924. }
  9925. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  9926. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  9927. // If we need to apply conversions to the expressions, then advance a single element.
  9928. if (hasExpr && convertedExpr.isUsable()) {
  9929. rightIter.replaceExpr(convertedExpr.get());
  9930. advance = 1;
  9931. }
  9932. // If both elements are unbound arrays, break out or we'll never finish
  9933. if (leftIter.getCurrentElementKind() == FK_IncompleteArray &&
  9934. rightIter.getCurrentElementKind() == FK_IncompleteArray)
  9935. break;
  9936. leftIter.advanceCurrentElement(advance);
  9937. rightIter.advanceCurrentElement(advance);
  9938. result.LeftCount += advance;
  9939. result.RightCount += advance;
  9940. }
  9941. result.LeftCount += leftIter.countRemaining();
  9942. result.RightCount += rightIter.countRemaining();
  9943. return result;
  9944. }
  9945. FlattenedTypeIterator::ComparisonResult
  9946. FlattenedTypeIterator::CompareTypes(
  9947. HLSLExternalSource& source,
  9948. SourceLocation leftLoc, SourceLocation rightLoc,
  9949. QualType left, QualType right)
  9950. {
  9951. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9952. FlattenedTypeIterator rightIter(rightLoc, right, source);
  9953. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9954. }
  9955. FlattenedTypeIterator::ComparisonResult
  9956. FlattenedTypeIterator::CompareTypesForInit(
  9957. HLSLExternalSource& source, QualType left, MultiExprArg args,
  9958. SourceLocation leftLoc, SourceLocation rightLoc)
  9959. {
  9960. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9961. FlattenedTypeIterator rightIter(rightLoc, args, source);
  9962. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9963. }
  9964. ////////////////////////////////////////////////////////////////////////////////
  9965. // Attribute processing support. //
  9966. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  9967. {
  9968. int64_t value = 0;
  9969. if (Attr.getNumArgs() > index)
  9970. {
  9971. Expr *E = nullptr;
  9972. if (!Attr.isArgExpr(index)) {
  9973. // For case arg is constant variable.
  9974. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  9975. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  9976. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  9977. Sema::LookupNameKind::LookupOrdinaryName));
  9978. if (!decl) {
  9979. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9980. return value;
  9981. }
  9982. Expr *init = decl->getInit();
  9983. if (!init) {
  9984. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9985. return value;
  9986. }
  9987. E = init;
  9988. } else
  9989. E = Attr.getArgAsExpr(index);
  9990. clang::APValue ArgNum;
  9991. bool displayError = false;
  9992. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  9993. {
  9994. displayError = true;
  9995. }
  9996. else
  9997. {
  9998. if (ArgNum.isInt())
  9999. {
  10000. value = ArgNum.getInt().getSExtValue();
  10001. }
  10002. else if (ArgNum.isFloat())
  10003. {
  10004. llvm::APSInt floatInt;
  10005. bool isPrecise;
  10006. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  10007. {
  10008. value = floatInt.getSExtValue();
  10009. }
  10010. else
  10011. {
  10012. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  10013. }
  10014. }
  10015. else
  10016. {
  10017. displayError = true;
  10018. }
  10019. if (value < 0)
  10020. {
  10021. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  10022. }
  10023. }
  10024. if (displayError)
  10025. {
  10026. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  10027. << Attr.getName() << AANT_ArgumentIntegerConstant
  10028. << E->getSourceRange();
  10029. }
  10030. }
  10031. return (int)value;
  10032. }
  10033. // TODO: support float arg directly.
  10034. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  10035. unsigned index = 0) {
  10036. int value = 0;
  10037. if (Attr.getNumArgs() > index) {
  10038. Expr *E = Attr.getArgAsExpr(index);
  10039. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  10040. llvm::APFloat flV = FL->getValue();
  10041. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  10042. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  10043. value = intV.getLimitedValue();
  10044. } else {
  10045. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  10046. value = intV.getLimitedValue();
  10047. }
  10048. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  10049. llvm::APInt intV =
  10050. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  10051. value = intV.getLimitedValue();
  10052. } else {
  10053. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  10054. << Attr.getName();
  10055. }
  10056. }
  10057. return value;
  10058. }
  10059. template <typename AttrType, typename EnumType,
  10060. bool (*ConvertStrToEnumType)(StringRef, EnumType &)>
  10061. static EnumType ValidateAttributeEnumArg(Sema &S, const AttributeList &Attr,
  10062. EnumType defaultValue,
  10063. unsigned index = 0) {
  10064. EnumType value(defaultValue);
  10065. StringRef Str = "";
  10066. SourceLocation ArgLoc;
  10067. if (Attr.getNumArgs() > index) {
  10068. if (!S.checkStringLiteralArgumentAttr(Attr, 0, Str, &ArgLoc))
  10069. return value;
  10070. if (!ConvertStrToEnumType(Str, value)) {
  10071. S.Diag(Attr.getLoc(), diag::warn_attribute_type_not_supported)
  10072. << Attr.getName() << Str << ArgLoc;
  10073. }
  10074. return value;
  10075. }
  10076. return value;
  10077. }
  10078. static Stmt* IgnoreParensAndDecay(Stmt* S)
  10079. {
  10080. for (;;)
  10081. {
  10082. switch (S->getStmtClass())
  10083. {
  10084. case Stmt::ParenExprClass:
  10085. S = cast<ParenExpr>(S)->getSubExpr();
  10086. break;
  10087. case Stmt::ImplicitCastExprClass:
  10088. {
  10089. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  10090. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  10091. castExpr->getCastKind() != CK_NoOp &&
  10092. castExpr->getCastKind() != CK_LValueToRValue)
  10093. {
  10094. return S;
  10095. }
  10096. S = castExpr->getSubExpr();
  10097. }
  10098. break;
  10099. default:
  10100. return S;
  10101. }
  10102. }
  10103. }
  10104. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  10105. {
  10106. DXASSERT_NOMSG(E != nullptr);
  10107. Expr* subscriptExpr = E->getIdx();
  10108. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  10109. if (subscriptExpr == nullptr ||
  10110. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  10111. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  10112. {
  10113. S.Diag(
  10114. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  10115. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  10116. return nullptr;
  10117. }
  10118. return E->getBase();
  10119. }
  10120. static bool IsValidClipPlaneDecl(Decl* D)
  10121. {
  10122. Decl::Kind kind = D->getKind();
  10123. if (kind == Decl::Var)
  10124. {
  10125. VarDecl* varDecl = cast<VarDecl>(D);
  10126. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  10127. varDecl->getType().isConstQualified())
  10128. {
  10129. return false;
  10130. }
  10131. return true;
  10132. }
  10133. else if (kind == Decl::Field)
  10134. {
  10135. return true;
  10136. }
  10137. return false;
  10138. }
  10139. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  10140. {
  10141. Stmt* cursor = E;
  10142. // clip plane expressions are a linear path, so no need to traverse the tree here.
  10143. while (cursor != nullptr)
  10144. {
  10145. bool supported = true;
  10146. cursor = IgnoreParensAndDecay(cursor);
  10147. switch (cursor->getStmtClass())
  10148. {
  10149. case Stmt::ArraySubscriptExprClass:
  10150. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  10151. if (cursor == nullptr)
  10152. {
  10153. // nullptr indicates failure, and the error message has already been printed out
  10154. return nullptr;
  10155. }
  10156. break;
  10157. case Stmt::DeclRefExprClass:
  10158. {
  10159. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  10160. Decl* decl = declRef->getDecl();
  10161. supported = IsValidClipPlaneDecl(decl);
  10162. cursor = supported ? nullptr : cursor;
  10163. }
  10164. break;
  10165. case Stmt::MemberExprClass:
  10166. {
  10167. MemberExpr* member = cast<MemberExpr>(cursor);
  10168. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  10169. cursor = supported ? member->getBase() : cursor;
  10170. }
  10171. break;
  10172. default:
  10173. supported = false;
  10174. break;
  10175. }
  10176. if (!supported)
  10177. {
  10178. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  10179. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  10180. return nullptr;
  10181. }
  10182. }
  10183. // Validate that the type is a float4.
  10184. QualType expressionType = E->getType();
  10185. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  10186. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  10187. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  10188. {
  10189. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  10190. return nullptr;
  10191. }
  10192. return E;
  10193. }
  10194. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  10195. {
  10196. Expr* clipExprs[6];
  10197. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  10198. {
  10199. if (A.getNumArgs() <= index)
  10200. {
  10201. clipExprs[index] = nullptr;
  10202. continue;
  10203. }
  10204. Expr *E = A.getArgAsExpr(index);
  10205. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  10206. }
  10207. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  10208. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  10209. A.getAttributeSpellingListIndex());
  10210. }
  10211. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  10212. {
  10213. int argValue = ValidateAttributeIntArg(S, Attr);
  10214. // Default value is 0 (full unroll).
  10215. if (Attr.getNumArgs() == 0) argValue = 0;
  10216. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  10217. argValue, Attr.getAttributeSpellingListIndex());
  10218. }
  10219. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  10220. {
  10221. Stmt::StmtClass stClass = St->getStmtClass();
  10222. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  10223. {
  10224. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  10225. << Attr.getName();
  10226. }
  10227. }
  10228. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  10229. {
  10230. Stmt::StmtClass stClass = St->getStmtClass();
  10231. if (stClass != Stmt::SwitchStmtClass)
  10232. {
  10233. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  10234. << Attr.getName();
  10235. }
  10236. }
  10237. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  10238. {
  10239. Stmt::StmtClass stClass = St->getStmtClass();
  10240. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  10241. {
  10242. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  10243. << Attr.getName();
  10244. }
  10245. }
  10246. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  10247. {
  10248. // values is an optional comma-separated list of potential values.
  10249. if (A.getNumArgs() <= index)
  10250. return StringRef();
  10251. Expr* E = A.getArgAsExpr(index);
  10252. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  10253. {
  10254. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  10255. << A.getName();
  10256. return StringRef();
  10257. }
  10258. StringLiteral* sl = cast<StringLiteral>(E);
  10259. StringRef result = sl->getString();
  10260. // Return result with no additional validation.
  10261. if (values == nullptr)
  10262. {
  10263. return result;
  10264. }
  10265. const char* value = values;
  10266. while (*value != '\0')
  10267. {
  10268. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  10269. // Look for a match.
  10270. const char* argData = result.data();
  10271. size_t argDataLen = result.size();
  10272. while (argDataLen != 0 && *argData == *value && *value)
  10273. {
  10274. ++argData;
  10275. ++value;
  10276. --argDataLen;
  10277. }
  10278. // Match found if every input character matched.
  10279. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  10280. {
  10281. return result;
  10282. }
  10283. // Move to next separator.
  10284. while (*value != '\0' && *value != ',')
  10285. {
  10286. ++value;
  10287. }
  10288. // Move to the start of the next item if any.
  10289. if (*value == ',') value++;
  10290. }
  10291. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  10292. // No match found.
  10293. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  10294. << A.getName() << values;
  10295. return StringRef();
  10296. }
  10297. static
  10298. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  10299. {
  10300. if (D->isFunctionOrFunctionTemplate())
  10301. {
  10302. return true;
  10303. }
  10304. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  10305. return false;
  10306. }
  10307. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  10308. {
  10309. DXASSERT_NOMSG(D != nullptr);
  10310. DXASSERT_NOMSG(!A.isInvalid());
  10311. Attr* declAttr = nullptr;
  10312. Handled = true;
  10313. switch (A.getKind())
  10314. {
  10315. case AttributeList::AT_HLSLIn:
  10316. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  10317. A.getAttributeSpellingListIndex());
  10318. break;
  10319. case AttributeList::AT_HLSLOut:
  10320. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  10321. A.getAttributeSpellingListIndex());
  10322. break;
  10323. case AttributeList::AT_HLSLInOut:
  10324. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  10325. A.getAttributeSpellingListIndex());
  10326. break;
  10327. case AttributeList::AT_HLSLNoInterpolation:
  10328. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  10329. A.getAttributeSpellingListIndex());
  10330. break;
  10331. case AttributeList::AT_HLSLLinear:
  10332. case AttributeList::AT_HLSLCenter:
  10333. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  10334. A.getAttributeSpellingListIndex());
  10335. break;
  10336. case AttributeList::AT_HLSLNoPerspective:
  10337. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  10338. A.getAttributeSpellingListIndex());
  10339. break;
  10340. case AttributeList::AT_HLSLSample:
  10341. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  10342. A.getAttributeSpellingListIndex());
  10343. break;
  10344. case AttributeList::AT_HLSLCentroid:
  10345. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  10346. A.getAttributeSpellingListIndex());
  10347. break;
  10348. case AttributeList::AT_HLSLPrecise:
  10349. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  10350. A.getAttributeSpellingListIndex());
  10351. break;
  10352. case AttributeList::AT_HLSLShared:
  10353. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  10354. A.getAttributeSpellingListIndex());
  10355. break;
  10356. case AttributeList::AT_HLSLGroupShared:
  10357. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  10358. A.getAttributeSpellingListIndex());
  10359. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  10360. VD->setType(S.Context.getAddrSpaceQualType(VD->getType(), DXIL::kTGSMAddrSpace));
  10361. }
  10362. break;
  10363. case AttributeList::AT_HLSLUniform:
  10364. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  10365. A.getAttributeSpellingListIndex());
  10366. break;
  10367. case AttributeList::AT_HLSLColumnMajor:
  10368. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  10369. A.getAttributeSpellingListIndex());
  10370. break;
  10371. case AttributeList::AT_HLSLRowMajor:
  10372. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  10373. A.getAttributeSpellingListIndex());
  10374. break;
  10375. case AttributeList::AT_HLSLUnorm:
  10376. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  10377. A.getAttributeSpellingListIndex());
  10378. break;
  10379. case AttributeList::AT_HLSLSnorm:
  10380. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  10381. A.getAttributeSpellingListIndex());
  10382. break;
  10383. case AttributeList::AT_HLSLPoint:
  10384. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  10385. A.getAttributeSpellingListIndex());
  10386. break;
  10387. case AttributeList::AT_HLSLLine:
  10388. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  10389. A.getAttributeSpellingListIndex());
  10390. break;
  10391. case AttributeList::AT_HLSLLineAdj:
  10392. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  10393. A.getAttributeSpellingListIndex());
  10394. break;
  10395. case AttributeList::AT_HLSLTriangle:
  10396. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  10397. A.getAttributeSpellingListIndex());
  10398. break;
  10399. case AttributeList::AT_HLSLTriangleAdj:
  10400. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  10401. A.getAttributeSpellingListIndex());
  10402. break;
  10403. case AttributeList::AT_HLSLGloballyCoherent:
  10404. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  10405. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10406. break;
  10407. case AttributeList::AT_HLSLIndices:
  10408. declAttr = ::new (S.Context) HLSLIndicesAttr(
  10409. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10410. break;
  10411. case AttributeList::AT_HLSLVertices:
  10412. declAttr = ::new (S.Context) HLSLVerticesAttr(
  10413. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10414. break;
  10415. case AttributeList::AT_HLSLPrimitives:
  10416. declAttr = ::new (S.Context) HLSLPrimitivesAttr(
  10417. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10418. break;
  10419. case AttributeList::AT_HLSLPayload:
  10420. declAttr = ::new (S.Context) HLSLPayloadAttr(
  10421. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10422. break;
  10423. case AttributeList::AT_HLSLRayPayload:
  10424. declAttr = ::new (S.Context) HLSLRayPayloadAttr(
  10425. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10426. break;
  10427. default:
  10428. Handled = false;
  10429. break;
  10430. }
  10431. if (declAttr != nullptr)
  10432. {
  10433. DXASSERT_NOMSG(Handled);
  10434. D->addAttr(declAttr);
  10435. return;
  10436. }
  10437. Handled = true;
  10438. switch (A.getKind())
  10439. {
  10440. // These apply to statements, not declarations. The warning messages clarify this properly.
  10441. case AttributeList::AT_HLSLUnroll:
  10442. case AttributeList::AT_HLSLAllowUAVCondition:
  10443. case AttributeList::AT_HLSLLoop:
  10444. case AttributeList::AT_HLSLFastOpt:
  10445. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  10446. << A.getName();
  10447. return;
  10448. case AttributeList::AT_HLSLBranch:
  10449. case AttributeList::AT_HLSLFlatten:
  10450. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  10451. << A.getName();
  10452. return;
  10453. case AttributeList::AT_HLSLForceCase:
  10454. case AttributeList::AT_HLSLCall:
  10455. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  10456. << A.getName();
  10457. return;
  10458. // These are the cases that actually apply to declarations.
  10459. case AttributeList::AT_HLSLClipPlanes:
  10460. declAttr = HandleClipPlanes(S, A);
  10461. break;
  10462. case AttributeList::AT_HLSLDomain:
  10463. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  10464. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  10465. break;
  10466. case AttributeList::AT_HLSLEarlyDepthStencil:
  10467. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10468. break;
  10469. case AttributeList::AT_HLSLInstance:
  10470. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  10471. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10472. break;
  10473. case AttributeList::AT_HLSLMaxTessFactor:
  10474. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  10475. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  10476. break;
  10477. case AttributeList::AT_HLSLNumThreads:
  10478. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  10479. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  10480. A.getAttributeSpellingListIndex());
  10481. break;
  10482. case AttributeList::AT_HLSLRootSignature:
  10483. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  10484. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  10485. A.getAttributeSpellingListIndex());
  10486. break;
  10487. case AttributeList::AT_HLSLOutputControlPoints:
  10488. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  10489. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10490. break;
  10491. case AttributeList::AT_HLSLOutputTopology:
  10492. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  10493. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  10494. break;
  10495. case AttributeList::AT_HLSLPartitioning:
  10496. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  10497. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  10498. break;
  10499. case AttributeList::AT_HLSLPatchConstantFunc:
  10500. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  10501. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  10502. break;
  10503. case AttributeList::AT_HLSLShader:
  10504. declAttr = ::new (S.Context) HLSLShaderAttr(
  10505. A.getRange(), S.Context,
  10506. ValidateAttributeStringArg(
  10507. S, A,
  10508. "compute,vertex,pixel,hull,domain,geometry,raygeneration,"
  10509. "intersection,anyhit,closesthit,miss,callable,mesh,amplification"),
  10510. A.getAttributeSpellingListIndex());
  10511. break;
  10512. case AttributeList::AT_HLSLMaxVertexCount:
  10513. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  10514. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10515. break;
  10516. case AttributeList::AT_HLSLExperimental:
  10517. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  10518. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  10519. A.getAttributeSpellingListIndex());
  10520. break;
  10521. case AttributeList::AT_NoInline:
  10522. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10523. break;
  10524. case AttributeList::AT_HLSLExport:
  10525. declAttr = ::new (S.Context) HLSLExportAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10526. break;
  10527. case AttributeList::AT_HLSLWaveSensitive:
  10528. declAttr = ::new (S.Context) HLSLWaveSensitiveAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10529. break;
  10530. case AttributeList::AT_HLSLWaveSize:
  10531. declAttr = ::new (S.Context) HLSLWaveSizeAttr(A.getRange(), S.Context,
  10532. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10533. break;
  10534. default:
  10535. Handled = false;
  10536. break; // SPIRV Change: was return;
  10537. }
  10538. if (declAttr != nullptr)
  10539. {
  10540. DXASSERT_NOMSG(Handled);
  10541. D->addAttr(declAttr);
  10542. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  10543. // and prevent code generation.
  10544. ValidateAttributeTargetIsFunction(S, D, A);
  10545. return; // SPIRV Change
  10546. }
  10547. // SPIRV Change Starts
  10548. Handled = true;
  10549. switch (A.getKind())
  10550. {
  10551. case AttributeList::AT_VKBuiltIn:
  10552. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  10553. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation,BaseVertex,BaseInstance,DrawIndex,DeviceIndex,ViewportMaskNV"),
  10554. A.getAttributeSpellingListIndex());
  10555. break;
  10556. case AttributeList::AT_VKLocation:
  10557. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  10558. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10559. break;
  10560. case AttributeList::AT_VKIndex:
  10561. declAttr = ::new (S.Context) VKIndexAttr(A.getRange(), S.Context,
  10562. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10563. break;
  10564. case AttributeList::AT_VKBinding:
  10565. declAttr = ::new (S.Context) VKBindingAttr(
  10566. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10567. A.getNumArgs() < 2 ? INT_MIN : ValidateAttributeIntArg(S, A, 1),
  10568. A.getAttributeSpellingListIndex());
  10569. break;
  10570. case AttributeList::AT_VKCounterBinding:
  10571. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  10572. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10573. break;
  10574. case AttributeList::AT_VKPushConstant:
  10575. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  10576. A.getAttributeSpellingListIndex());
  10577. break;
  10578. case AttributeList::AT_VKOffset:
  10579. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  10580. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10581. break;
  10582. case AttributeList::AT_VKImageFormat: {
  10583. VKImageFormatAttr::ImageFormatType Kind = ValidateAttributeEnumArg<
  10584. VKImageFormatAttr, VKImageFormatAttr::ImageFormatType,
  10585. VKImageFormatAttr::ConvertStrToImageFormatType>(
  10586. S, A, VKImageFormatAttr::ImageFormatType::unknown);
  10587. declAttr = ::new (S.Context) VKImageFormatAttr(
  10588. A.getRange(), S.Context, Kind, A.getAttributeSpellingListIndex());
  10589. break;
  10590. }
  10591. case AttributeList::AT_VKInputAttachmentIndex:
  10592. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  10593. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10594. A.getAttributeSpellingListIndex());
  10595. break;
  10596. case AttributeList::AT_VKConstantId:
  10597. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  10598. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10599. break;
  10600. case AttributeList::AT_VKPostDepthCoverage:
  10601. declAttr = ::new (S.Context) VKPostDepthCoverageAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10602. break;
  10603. case AttributeList::AT_VKShaderRecordNV:
  10604. declAttr = ::new (S.Context) VKShaderRecordNVAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10605. break;
  10606. case AttributeList::AT_VKShaderRecordEXT:
  10607. declAttr = ::new (S.Context) VKShaderRecordEXTAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10608. break;
  10609. default:
  10610. Handled = false;
  10611. return;
  10612. }
  10613. if (declAttr != nullptr)
  10614. {
  10615. DXASSERT_NOMSG(Handled);
  10616. D->addAttr(declAttr);
  10617. }
  10618. // SPIRV Change Ends
  10619. }
  10620. /// <summary>Processes an attribute for a statement.</summary>
  10621. /// <param name="S">Sema with context.</param>
  10622. /// <param name="St">Statement annotated.</param>
  10623. /// <param name="A">Single parsed attribute to process.</param>
  10624. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  10625. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  10626. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  10627. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  10628. {
  10629. // | Construct | Allowed Attributes |
  10630. // +------------------+--------------------------------------------+
  10631. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  10632. // | if | branch, flatten |
  10633. // | switch | branch, flatten, forcecase, call |
  10634. Attr * result = nullptr;
  10635. Handled = true;
  10636. switch (A.getKind())
  10637. {
  10638. case AttributeList::AT_HLSLUnroll:
  10639. ValidateAttributeOnLoop(S, St, A);
  10640. result = HandleUnrollAttribute(S, A);
  10641. break;
  10642. case AttributeList::AT_HLSLAllowUAVCondition:
  10643. ValidateAttributeOnLoop(S, St, A);
  10644. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  10645. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10646. break;
  10647. case AttributeList::AT_HLSLLoop:
  10648. ValidateAttributeOnLoop(S, St, A);
  10649. result = ::new (S.Context) HLSLLoopAttr(
  10650. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10651. break;
  10652. case AttributeList::AT_HLSLFastOpt:
  10653. ValidateAttributeOnLoop(S, St, A);
  10654. result = ::new (S.Context) HLSLFastOptAttr(
  10655. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10656. break;
  10657. case AttributeList::AT_HLSLBranch:
  10658. ValidateAttributeOnSwitchOrIf(S, St, A);
  10659. result = ::new (S.Context) HLSLBranchAttr(
  10660. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10661. break;
  10662. case AttributeList::AT_HLSLFlatten:
  10663. ValidateAttributeOnSwitchOrIf(S, St, A);
  10664. result = ::new (S.Context) HLSLFlattenAttr(
  10665. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10666. break;
  10667. case AttributeList::AT_HLSLForceCase:
  10668. ValidateAttributeOnSwitch(S, St, A);
  10669. result = ::new (S.Context) HLSLForceCaseAttr(
  10670. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10671. break;
  10672. case AttributeList::AT_HLSLCall:
  10673. ValidateAttributeOnSwitch(S, St, A);
  10674. result = ::new (S.Context) HLSLCallAttr(
  10675. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10676. break;
  10677. default:
  10678. Handled = false;
  10679. break;
  10680. }
  10681. return result;
  10682. }
  10683. ////////////////////////////////////////////////////////////////////////////////
  10684. // Implementation of Sema members. //
  10685. Decl* Sema::ActOnStartHLSLBuffer(
  10686. Scope* bufferScope,
  10687. bool cbuffer, SourceLocation KwLoc,
  10688. IdentifierInfo *Ident, SourceLocation IdentLoc,
  10689. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  10690. SourceLocation LBrace)
  10691. {
  10692. // For anonymous namespace, take the location of the left brace.
  10693. DeclContext* lexicalParent = getCurLexicalContext();
  10694. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10695. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  10696. Ident, IdentLoc, BufferAttributes, LBrace);
  10697. // Keep track of the currently active buffer.
  10698. HLSLBuffers.push_back(result);
  10699. // Validate unusual annotations and emit diagnostics.
  10700. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  10701. auto && unusualIter = BufferAttributes.begin();
  10702. auto && unusualEnd = BufferAttributes.end();
  10703. char expectedRegisterType = cbuffer ? 'b' : 't';
  10704. for (; unusualIter != unusualEnd; ++unusualIter) {
  10705. switch ((*unusualIter)->getKind()) {
  10706. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10707. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  10708. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  10709. break;
  10710. }
  10711. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10712. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  10713. if (registerAssignment->isSpaceOnly())
  10714. continue;
  10715. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  10716. Diag(registerAssignment->Loc, diag::err_hlsl_incorrect_bind_semantic) << (cbuffer ? "'b'" : "'t'");
  10717. } else if (registerAssignment->ShaderProfile.size() > 0) {
  10718. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  10719. }
  10720. break;
  10721. }
  10722. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10723. // Ignore semantic declarations.
  10724. break;
  10725. }
  10726. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  10727. hlsl::PayloadAccessAnnotation* annotation = cast<hlsl::PayloadAccessAnnotation>(*unusualIter);
  10728. Diag( annotation->Loc, diag::err_hlsl_unsupported_payload_access_qualifier);
  10729. break;
  10730. }
  10731. }
  10732. }
  10733. PushOnScopeChains(result, bufferScope);
  10734. PushDeclContext(bufferScope, result);
  10735. ActOnDocumentableDecl(result);
  10736. return result;
  10737. }
  10738. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  10739. {
  10740. DXASSERT_NOMSG(Dcl != nullptr);
  10741. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10742. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  10743. HLSLBuffers.pop_back();
  10744. PopDeclContext();
  10745. }
  10746. Decl* Sema::getActiveHLSLBuffer() const
  10747. {
  10748. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  10749. }
  10750. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  10751. DeclGroupPtrTy &dcl, bool iscbuf) {
  10752. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10753. HLSLBuffers.pop_back();
  10754. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10755. Decl *decl = dcl.get().getSingleDecl();
  10756. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  10757. IdentifierInfo *Ident = namedDecl->getIdentifier();
  10758. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  10759. SourceLocation Loc = decl->getLocation();
  10760. // Prevent array type in template. The only way to specify an array in the template type
  10761. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  10762. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  10763. QualType declType = cast<VarDecl>(namedDecl)->getType();
  10764. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  10765. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  10766. declType = arrayType->getElementType();
  10767. }
  10768. // Check to make that sure only structs are allowed as parameter types for
  10769. // ConstantBuffer and TextureBuffer.
  10770. if (!declType->isStructureType()) {
  10771. Diag(decl->getLocStart(),
  10772. diag::err_hlsl_typeintemplateargument_requires_struct)
  10773. << declType;
  10774. return nullptr;
  10775. }
  10776. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  10777. DeclContext *lexicalParent = getCurLexicalContext();
  10778. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10779. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  10780. KwLoc, Ident, Loc, hlslAttrs, Loc);
  10781. // set relation
  10782. namedDecl->setDeclContext(result);
  10783. result->addDecl(namedDecl);
  10784. // move attribute from constant to constant buffer
  10785. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  10786. namedDecl->setUnusualAnnotations(hlslAttrs);
  10787. return result;
  10788. }
  10789. bool Sema::IsOnHLSLBufferView() {
  10790. // nullptr will not pushed for cbuffer.
  10791. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  10792. }
  10793. void Sema::ActOnStartHLSLBufferView() {
  10794. // Push nullptr to mark HLSLBufferView.
  10795. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10796. HLSLBuffers.emplace_back(nullptr);
  10797. }
  10798. HLSLBufferDecl::HLSLBufferDecl(
  10799. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  10800. IdentifierInfo *Id, SourceLocation IdLoc,
  10801. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10802. SourceLocation LBrace)
  10803. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  10804. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  10805. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  10806. if (!BufferAttributes.empty()) {
  10807. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10808. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  10809. }
  10810. }
  10811. HLSLBufferDecl *
  10812. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  10813. bool constantbuffer, SourceLocation KwLoc,
  10814. IdentifierInfo *Id, SourceLocation IdLoc,
  10815. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10816. SourceLocation LBrace) {
  10817. DeclContext *DC = C.getTranslationUnitDecl();
  10818. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  10819. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  10820. if (DC != lexicalParent) {
  10821. result->setLexicalDeclContext(lexicalParent);
  10822. }
  10823. return result;
  10824. }
  10825. const char *HLSLBufferDecl::getDeclKindName() const {
  10826. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  10827. "ConstantBuffer"};
  10828. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  10829. return HLSLBufferNames[index];
  10830. }
  10831. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  10832. assert(NewDecl != nullptr);
  10833. if (!getLangOpts().HLSL) {
  10834. return;
  10835. }
  10836. if (!D.UnusualAnnotations.empty()) {
  10837. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10838. getASTContext(), D.UnusualAnnotations.data(),
  10839. D.UnusualAnnotations.size()));
  10840. D.UnusualAnnotations.clear();
  10841. }
  10842. }
  10843. /// Checks whether a usage attribute is compatible with those seen so far and
  10844. /// maintains history.
  10845. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  10846. bool &usageOut) {
  10847. switch (kind) {
  10848. case AttributeList::AT_HLSLIn:
  10849. if (usageIn)
  10850. return false;
  10851. usageIn = true;
  10852. break;
  10853. case AttributeList::AT_HLSLOut:
  10854. if (usageOut)
  10855. return false;
  10856. usageOut = true;
  10857. break;
  10858. default:
  10859. assert(kind == AttributeList::AT_HLSLInOut);
  10860. if (usageOut || usageIn)
  10861. return false;
  10862. usageIn = usageOut = true;
  10863. break;
  10864. }
  10865. return true;
  10866. }
  10867. // Diagnose valid/invalid modifiers for HLSL.
  10868. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC, Expr *BitWidth,
  10869. TypeSourceInfo *TInfo, bool isParameter) {
  10870. assert(getLangOpts().HLSL &&
  10871. "otherwise this is called without checking language first");
  10872. // NOTE: some tests may declare templates.
  10873. if (DC->isDependentContext()) return true;
  10874. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  10875. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  10876. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  10877. bool result = true;
  10878. bool isTypedef = storage == DeclSpec::SCS_typedef;
  10879. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  10880. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  10881. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->isNamespace() || DC->getDeclKind() == Decl::HLSLBuffer);
  10882. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  10883. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  10884. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  10885. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  10886. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  10887. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  10888. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  10889. // Function declarations are not allowed in parameter declaration
  10890. // TODO : Remove this check once we support function declarations/pointers in HLSL
  10891. if (isParameter && isFunction) {
  10892. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  10893. D.setInvalidType();
  10894. return false;
  10895. }
  10896. assert(
  10897. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  10898. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  10899. (isParameter ? 1 : 0))
  10900. && "exactly one type of declarator is being processed");
  10901. // qt/pType captures either the type being modified, or the return type in the
  10902. // case of a function (or method).
  10903. QualType qt = TInfo->getType();
  10904. const Type* pType = qt.getTypePtrOrNull();
  10905. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  10906. // Early checks - these are not simple attribution errors, but constructs that
  10907. // are fundamentally unsupported,
  10908. // and so we avoid errors that might indicate they can be repaired.
  10909. if (DC->isRecord()) {
  10910. unsigned int nestedDiagId = 0;
  10911. if (isTypedef) {
  10912. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  10913. }
  10914. if (isField && pType && pType->isIncompleteArrayType()) {
  10915. nestedDiagId = diag::err_hlsl_unsupported_incomplete_array;
  10916. }
  10917. if (nestedDiagId) {
  10918. Diag(D.getLocStart(), nestedDiagId);
  10919. D.setInvalidType();
  10920. return false;
  10921. }
  10922. }
  10923. // String and subobject declarations are supported only as top level global variables.
  10924. // Const and static modifiers are implied - add them if missing.
  10925. if ((hlsl::IsStringType(qt) || hlslSource->IsSubobjectType(qt)) && !D.isInvalidType()) {
  10926. // string are supported only as top level global variables
  10927. if (!DC->isTranslationUnit()) {
  10928. Diag(D.getLocStart(), diag::err_hlsl_object_not_global) << (int)hlsl::IsStringType(qt);
  10929. result = false;
  10930. }
  10931. if (isExtern) {
  10932. Diag(D.getLocStart(), diag::err_hlsl_object_extern_not_supported) << (int)hlsl::IsStringType(qt);
  10933. result = false;
  10934. }
  10935. const char *PrevSpec = nullptr;
  10936. unsigned DiagID = 0;
  10937. if (!isStatic) {
  10938. D.getMutableDeclSpec().SetStorageClassSpec(*this, DeclSpec::SCS_static, D.getLocStart(), PrevSpec, DiagID, Context.getPrintingPolicy());
  10939. isStatic = true;
  10940. }
  10941. if (!isConst) {
  10942. D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, D.getLocStart(), PrevSpec, DiagID, getLangOpts());
  10943. isConst = true;
  10944. }
  10945. }
  10946. const char* declarationType =
  10947. (isLocalVar) ? "local variable" :
  10948. (isTypedef) ? "typedef" :
  10949. (isFunction) ? "function" :
  10950. (isMethod) ? "method" :
  10951. (isGlobal) ? "global variable" :
  10952. (isParameter) ? "parameter" :
  10953. (isField) ? "field" : "<unknown>";
  10954. if (pType && D.isFunctionDeclarator()) {
  10955. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  10956. if (pFP) {
  10957. qt = pFP->getReturnType();
  10958. pType = qt.getTypePtrOrNull();
  10959. // prohibit string as a return type
  10960. if (hlsl::IsStringType(qt)) {
  10961. static const unsigned selectReturnValueIdx = 2;
  10962. Diag(D.getLocStart(), diag::err_hlsl_unsupported_string_decl) << selectReturnValueIdx;
  10963. D.setInvalidType();
  10964. }
  10965. }
  10966. }
  10967. // Check for deprecated effect object type here, warn, and invalidate decl
  10968. bool bDeprecatedEffectObject = false;
  10969. bool bIsObject = false;
  10970. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  10971. bIsObject = true;
  10972. if (bDeprecatedEffectObject) {
  10973. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  10974. D.setInvalidType();
  10975. return false;
  10976. }
  10977. // Add methods if not ready.
  10978. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  10979. } else if (qt->isArrayType()) {
  10980. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  10981. while (eltQt->isArrayType())
  10982. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  10983. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  10984. // Add methods if not ready.
  10985. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  10986. bIsObject = true;
  10987. }
  10988. }
  10989. if (isExtern) {
  10990. if (!(isFunction || isGlobal)) {
  10991. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  10992. << declarationType;
  10993. result = false;
  10994. }
  10995. }
  10996. if (isStatic) {
  10997. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  10998. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  10999. << declarationType;
  11000. result = false;
  11001. }
  11002. }
  11003. if (isVolatile) {
  11004. if (!(isLocalVar || isTypedef)) {
  11005. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  11006. << declarationType;
  11007. result = false;
  11008. }
  11009. }
  11010. if (isConst) {
  11011. if (isField && !isStatic) {
  11012. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  11013. << declarationType;
  11014. result = false;
  11015. }
  11016. }
  11017. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  11018. if (hasSignSpec) {
  11019. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  11020. // vectors or matrices can only have unsigned integer types.
  11021. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  11022. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  11023. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  11024. << g_ArBasicTypeNames[basicKind];
  11025. result = false;
  11026. }
  11027. }
  11028. else {
  11029. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  11030. result = false;
  11031. }
  11032. }
  11033. // Validate attributes
  11034. clang::AttributeList
  11035. *pUniform = nullptr,
  11036. *pUsage = nullptr,
  11037. *pNoInterpolation = nullptr,
  11038. *pLinear = nullptr,
  11039. *pNoPerspective = nullptr,
  11040. *pSample = nullptr,
  11041. *pCentroid = nullptr,
  11042. *pCenter = nullptr,
  11043. *pAnyLinear = nullptr, // first linear attribute found
  11044. *pTopology = nullptr,
  11045. *pMeshModifier = nullptr;
  11046. bool usageIn = false;
  11047. bool usageOut = false;
  11048. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  11049. pAttr != NULL; pAttr = pAttr->getNext()) {
  11050. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  11051. continue;
  11052. switch (pAttr->getKind()) {
  11053. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  11054. break;
  11055. case AttributeList::AT_HLSLShared:
  11056. if (!isGlobal) {
  11057. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11058. << pAttr->getName() << declarationType << pAttr->getRange();
  11059. result = false;
  11060. }
  11061. if (isStatic) {
  11062. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11063. << "'static'" << pAttr->getName() << declarationType
  11064. << pAttr->getRange();
  11065. result = false;
  11066. }
  11067. break;
  11068. case AttributeList::AT_HLSLGroupShared:
  11069. if (!isGlobal) {
  11070. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11071. << pAttr->getName() << declarationType << pAttr->getRange();
  11072. result = false;
  11073. }
  11074. if (isExtern) {
  11075. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11076. << "'extern'" << pAttr->getName() << declarationType
  11077. << pAttr->getRange();
  11078. result = false;
  11079. }
  11080. break;
  11081. case AttributeList::AT_HLSLGloballyCoherent:
  11082. if (!bIsObject) {
  11083. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11084. << pAttr->getName() << "non-UAV type";
  11085. result = false;
  11086. }
  11087. break;
  11088. case AttributeList::AT_HLSLUniform:
  11089. if (!(isGlobal || isParameter)) {
  11090. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11091. << pAttr->getName() << declarationType << pAttr->getRange();
  11092. result = false;
  11093. }
  11094. if (isStatic) {
  11095. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11096. << "'static'" << pAttr->getName() << declarationType
  11097. << pAttr->getRange();
  11098. result = false;
  11099. }
  11100. pUniform = pAttr;
  11101. break;
  11102. case AttributeList::AT_HLSLIn:
  11103. case AttributeList::AT_HLSLOut:
  11104. case AttributeList::AT_HLSLInOut:
  11105. if (!isParameter) {
  11106. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  11107. << pAttr->getName() << pAttr->getRange();
  11108. result = false;
  11109. }
  11110. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  11111. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  11112. << pAttr->getName() << pAttr->getRange();
  11113. result = false;
  11114. }
  11115. pUsage = pAttr;
  11116. break;
  11117. case AttributeList::AT_HLSLNoInterpolation:
  11118. if (!(isParameter || isField || isFunction)) {
  11119. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11120. << pAttr->getName() << declarationType << pAttr->getRange();
  11121. result = false;
  11122. }
  11123. if (pNoInterpolation) {
  11124. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11125. << pAttr->getName() << pAttr->getRange();
  11126. }
  11127. pNoInterpolation = pAttr;
  11128. break;
  11129. case AttributeList::AT_HLSLLinear:
  11130. case AttributeList::AT_HLSLCenter:
  11131. case AttributeList::AT_HLSLNoPerspective:
  11132. case AttributeList::AT_HLSLSample:
  11133. case AttributeList::AT_HLSLCentroid:
  11134. if (!(isParameter || isField || isFunction)) {
  11135. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11136. << pAttr->getName() << declarationType << pAttr->getRange();
  11137. result = false;
  11138. }
  11139. if (nullptr == pAnyLinear)
  11140. pAnyLinear = pAttr;
  11141. switch (pAttr->getKind()) {
  11142. case AttributeList::AT_HLSLLinear:
  11143. if (pLinear) {
  11144. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11145. << pAttr->getName() << pAttr->getRange();
  11146. }
  11147. pLinear = pAttr;
  11148. break;
  11149. case AttributeList::AT_HLSLCenter:
  11150. if (pCenter) {
  11151. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11152. << pAttr->getName() << pAttr->getRange();
  11153. }
  11154. pCenter = pAttr;
  11155. break;
  11156. case AttributeList::AT_HLSLNoPerspective:
  11157. if (pNoPerspective) {
  11158. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11159. << pAttr->getName() << pAttr->getRange();
  11160. }
  11161. pNoPerspective = pAttr;
  11162. break;
  11163. case AttributeList::AT_HLSLSample:
  11164. if (pSample) {
  11165. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11166. << pAttr->getName() << pAttr->getRange();
  11167. }
  11168. pSample = pAttr;
  11169. break;
  11170. case AttributeList::AT_HLSLCentroid:
  11171. if (pCentroid) {
  11172. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11173. << pAttr->getName() << pAttr->getRange();
  11174. }
  11175. pCentroid = pAttr;
  11176. break;
  11177. default:
  11178. // Only relevant to the four attribs included in this block.
  11179. break;
  11180. }
  11181. break;
  11182. case AttributeList::AT_HLSLPoint:
  11183. case AttributeList::AT_HLSLLine:
  11184. case AttributeList::AT_HLSLLineAdj:
  11185. case AttributeList::AT_HLSLTriangle:
  11186. case AttributeList::AT_HLSLTriangleAdj:
  11187. if (!(isParameter)) {
  11188. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11189. << pAttr->getName() << declarationType << pAttr->getRange();
  11190. result = false;
  11191. }
  11192. if (pTopology) {
  11193. if (pTopology->getKind() == pAttr->getKind()) {
  11194. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11195. << pAttr->getName() << pAttr->getRange();
  11196. } else {
  11197. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11198. << pAttr->getName() << pTopology->getName()
  11199. << declarationType << pAttr->getRange();
  11200. result = false;
  11201. }
  11202. }
  11203. pTopology = pAttr;
  11204. break;
  11205. case AttributeList::AT_HLSLExport:
  11206. if (!isFunction) {
  11207. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11208. << pAttr->getName() << declarationType << pAttr->getRange();
  11209. result = false;
  11210. }
  11211. if (isStatic) {
  11212. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11213. << "'static'" << pAttr->getName() << declarationType
  11214. << pAttr->getRange();
  11215. result = false;
  11216. }
  11217. break;
  11218. case AttributeList::AT_HLSLIndices:
  11219. case AttributeList::AT_HLSLVertices:
  11220. case AttributeList::AT_HLSLPrimitives:
  11221. case AttributeList::AT_HLSLPayload:
  11222. if (!(isParameter)) {
  11223. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  11224. << pAttr->getName() << declarationType << pAttr->getRange();
  11225. result = false;
  11226. }
  11227. if (pMeshModifier) {
  11228. if (pMeshModifier->getKind() == pAttr->getKind()) {
  11229. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  11230. << pAttr->getName() << pAttr->getRange();
  11231. } else {
  11232. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  11233. << pAttr->getName() << pMeshModifier->getName()
  11234. << declarationType << pAttr->getRange();
  11235. result = false;
  11236. }
  11237. }
  11238. pMeshModifier = pAttr;
  11239. break;
  11240. default:
  11241. break;
  11242. }
  11243. }
  11244. if (pNoInterpolation && pAnyLinear) {
  11245. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  11246. << pNoInterpolation->getName() << pAnyLinear->getName()
  11247. << declarationType << pNoInterpolation->getRange();
  11248. result = false;
  11249. }
  11250. if (pSample && pCentroid) {
  11251. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  11252. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  11253. }
  11254. if (pCenter && pCentroid) {
  11255. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  11256. << pCenter->getName() << pCentroid->getName() << pCenter->getRange();
  11257. }
  11258. if (pSample && pCenter) {
  11259. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  11260. << pCenter->getName() << pSample->getName() << pCenter->getRange();
  11261. }
  11262. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  11263. pNoInterpolation ? pNoInterpolation : pTopology);
  11264. if (pUniform && pNonUniformAttr) {
  11265. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  11266. << pNonUniformAttr->getName()
  11267. << pUniform->getName() << declarationType << pUniform->getRange();
  11268. result = false;
  11269. }
  11270. if (pAnyLinear && pTopology) {
  11271. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  11272. << pTopology->getName()
  11273. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  11274. result = false;
  11275. }
  11276. if (pNoInterpolation && pTopology) {
  11277. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  11278. << pTopology->getName()
  11279. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  11280. result = false;
  11281. }
  11282. if (pUniform && pUsage) {
  11283. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  11284. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  11285. << pUsage->getName() << pUniform->getName() << declarationType
  11286. << pUniform->getRange();
  11287. result = false;
  11288. }
  11289. }
  11290. if (pMeshModifier) {
  11291. if (pMeshModifier->getKind() == AttributeList::Kind::AT_HLSLPayload) {
  11292. if (!usageIn) {
  11293. Diag(D.getLocStart(), diag::err_hlsl_missing_in_attr)
  11294. << pMeshModifier->getName();
  11295. result = false;
  11296. }
  11297. } else {
  11298. if (!usageOut) {
  11299. Diag(D.getLocStart(), diag::err_hlsl_missing_out_attr)
  11300. << pMeshModifier->getName();
  11301. result = false;
  11302. }
  11303. }
  11304. }
  11305. // Validate that stream-ouput objects are marked as inout
  11306. if (isParameter && !(usageIn && usageOut) &&
  11307. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  11308. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  11309. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  11310. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  11311. result = false;
  11312. }
  11313. // SPIRV change starts
  11314. #ifdef ENABLE_SPIRV_CODEGEN
  11315. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  11316. if (!getLangOpts().SPIRV) {
  11317. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  11318. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  11319. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  11320. << g_ArBasicTypeNames[basicKind];
  11321. result = false;
  11322. }
  11323. }
  11324. #endif // ENABLE_SPIRV_CODEGEN
  11325. // SPIRV change ends
  11326. // Disallow bitfields
  11327. if (BitWidth) {
  11328. Diag(BitWidth->getExprLoc(), diag::err_hlsl_bitfields);
  11329. result = false;
  11330. }
  11331. // Validate unusual annotations.
  11332. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  11333. if (isField)
  11334. hlsl::DiagnosePayloadAccessQualifierAnnotations(*this, D, qt,
  11335. D.UnusualAnnotations);
  11336. auto && unusualIter = D.UnusualAnnotations.begin();
  11337. auto && unusualEnd = D.UnusualAnnotations.end();
  11338. for (; unusualIter != unusualEnd; ++unusualIter) {
  11339. switch ((*unusualIter)->getKind()) {
  11340. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  11341. hlsl::ConstantPacking *constantPacking =
  11342. cast<hlsl::ConstantPacking>(*unusualIter);
  11343. if (!isGlobal || HLSLBuffers.size() == 0) {
  11344. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  11345. continue;
  11346. }
  11347. if (constantPacking->ComponentOffset > 0) {
  11348. // Validate that this will fit.
  11349. if (!qt.isNull()) {
  11350. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  11351. constantPacking->ComponentOffset);
  11352. }
  11353. }
  11354. break;
  11355. }
  11356. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  11357. hlsl::RegisterAssignment *registerAssignment =
  11358. cast<hlsl::RegisterAssignment>(*unusualIter);
  11359. if (registerAssignment->IsValid) {
  11360. if (!qt.isNull()) {
  11361. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  11362. registerAssignment->RegisterType);
  11363. }
  11364. }
  11365. break;
  11366. }
  11367. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  11368. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  11369. if (isTypedef || isLocalVar) {
  11370. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  11371. << "semantic" << declarationType;
  11372. }
  11373. break;
  11374. }
  11375. case hlsl::UnusualAnnotation::UA_PayloadAccessQualifier: {
  11376. hlsl::PayloadAccessAnnotation *annotation = cast<hlsl::PayloadAccessAnnotation>(*unusualIter);
  11377. if (!isField) {
  11378. Diag(annotation->Loc, diag::err_hlsl_unsupported_payload_access_qualifier);
  11379. }
  11380. break;
  11381. }
  11382. }
  11383. }
  11384. if (!result) {
  11385. D.setInvalidType();
  11386. }
  11387. return result;
  11388. }
  11389. // Diagnose HLSL types on lookup
  11390. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  11391. const DeclarationNameInfo declName = R.getLookupNameInfo();
  11392. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  11393. if (idInfo) {
  11394. StringRef nameIdentifier = idInfo->getName();
  11395. HLSLScalarType parsedType;
  11396. int rowCount, colCount;
  11397. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  11398. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  11399. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  11400. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  11401. }
  11402. }
  11403. return true;
  11404. }
  11405. static QualType getUnderlyingType(QualType Type)
  11406. {
  11407. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  11408. {
  11409. if (const TypedefNameDecl* pDecl = TD->getDecl())
  11410. Type = pDecl->getUnderlyingType();
  11411. else
  11412. break;
  11413. }
  11414. return Type;
  11415. }
  11416. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  11417. /// <param name="self">Sema with context.</param>
  11418. /// <param name="type">QualType to inspect.</param>
  11419. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  11420. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  11421. void hlsl::GetHLSLAttributedTypes(
  11422. _In_ clang::Sema *self, clang::QualType type,
  11423. _Inout_opt_ const clang::AttributedType **ppMatrixOrientation,
  11424. _Inout_opt_ const clang::AttributedType **ppNorm,
  11425. _Inout_opt_ const clang::AttributedType **ppGLC) {
  11426. AssignOpt<const clang::AttributedType *>(nullptr, ppMatrixOrientation);
  11427. AssignOpt<const clang::AttributedType *>(nullptr, ppNorm);
  11428. AssignOpt<const clang::AttributedType *>(nullptr, ppGLC);
  11429. // Note: we clear output pointers once set so we can stop searching
  11430. QualType Desugared = getUnderlyingType(type);
  11431. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  11432. while (AT && (ppMatrixOrientation || ppNorm || ppGLC)) {
  11433. AttributedType::Kind Kind = AT->getAttrKind();
  11434. if (Kind == AttributedType::attr_hlsl_row_major ||
  11435. Kind == AttributedType::attr_hlsl_column_major)
  11436. {
  11437. if (ppMatrixOrientation)
  11438. {
  11439. *ppMatrixOrientation = AT;
  11440. ppMatrixOrientation = nullptr;
  11441. }
  11442. }
  11443. else if (Kind == AttributedType::attr_hlsl_unorm ||
  11444. Kind == AttributedType::attr_hlsl_snorm)
  11445. {
  11446. if (ppNorm)
  11447. {
  11448. *ppNorm = AT;
  11449. ppNorm = nullptr;
  11450. }
  11451. }
  11452. else if (Kind == AttributedType::attr_hlsl_globallycoherent) {
  11453. if (ppGLC) {
  11454. *ppGLC = AT;
  11455. ppGLC = nullptr;
  11456. }
  11457. }
  11458. Desugared = getUnderlyingType(AT->getEquivalentType());
  11459. AT = dyn_cast<AttributedType>(Desugared);
  11460. }
  11461. // Unwrap component type on vector or matrix and check snorm/unorm
  11462. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  11463. AT = dyn_cast<AttributedType>(Desugared);
  11464. while (AT && ppNorm) {
  11465. AttributedType::Kind Kind = AT->getAttrKind();
  11466. if (Kind == AttributedType::attr_hlsl_unorm ||
  11467. Kind == AttributedType::attr_hlsl_snorm)
  11468. {
  11469. *ppNorm = AT;
  11470. ppNorm = nullptr;
  11471. }
  11472. Desugared = getUnderlyingType(AT->getEquivalentType());
  11473. AT = dyn_cast<AttributedType>(Desugared);
  11474. }
  11475. }
  11476. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  11477. /// <param name="self">Sema with context.</param>
  11478. /// <param name="type">QualType to check.</param>
  11479. bool hlsl::IsMatrixType(
  11480. _In_ clang::Sema* self,
  11481. _In_ clang::QualType type)
  11482. {
  11483. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  11484. }
  11485. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  11486. /// <param name="self">Sema with context.</param>
  11487. /// <param name="type">QualType to check.</param>
  11488. bool hlsl::IsVectorType(
  11489. _In_ clang::Sema* self,
  11490. _In_ clang::QualType type)
  11491. {
  11492. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  11493. }
  11494. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  11495. /// <param name="self">Sema with context.</param>
  11496. /// <param name="type">Matrix or Vector type.</param>
  11497. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  11498. _In_ clang::QualType type)
  11499. {
  11500. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  11501. // without losing the AttributedType on the template parameter
  11502. if (const Type* pType = type.getTypePtrOrNull()) {
  11503. // A non-dependent template specialization type is always "sugar",
  11504. // typically for a RecordType. For example, a class template
  11505. // specialization type of @c vector<int> will refer to a tag type for
  11506. // the instantiation @c std::vector<int, std::allocator<int>>.
  11507. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  11508. // If we have enough arguments, pull them from the template directly, rather than doing
  11509. // the extra lookups.
  11510. if (pTemplate->getNumArgs() > 0)
  11511. return pTemplate->getArg(0).getAsType();
  11512. QualType templateRecord = pTemplate->desugar();
  11513. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  11514. if (pTemplateRecordType) {
  11515. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  11516. if (pTemplateTagType) {
  11517. const ClassTemplateSpecializationDecl *specializationDecl =
  11518. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  11519. pTemplateTagType->getDecl());
  11520. if (specializationDecl) {
  11521. return specializationDecl->getTemplateArgs()[0].getAsType();
  11522. }
  11523. }
  11524. }
  11525. }
  11526. }
  11527. return QualType();
  11528. }
  11529. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  11530. /// <param name="self">Sema with context.</param>
  11531. /// <param name="type">Input type.</param>
  11532. clang::QualType hlsl::GetOriginalElementType(
  11533. _In_ clang::Sema* self,
  11534. _In_ clang::QualType type)
  11535. {
  11536. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  11537. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  11538. return GetOriginalMatrixOrVectorElementType(type);
  11539. }
  11540. return type;
  11541. }
  11542. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  11543. switch (A->getKind()) {
  11544. // Parameter modifiers
  11545. case clang::attr::HLSLIn:
  11546. Out << "in ";
  11547. break;
  11548. case clang::attr::HLSLInOut:
  11549. Out << "inout ";
  11550. break;
  11551. case clang::attr::HLSLOut:
  11552. Out << "out ";
  11553. break;
  11554. // Interpolation modifiers
  11555. case clang::attr::HLSLLinear:
  11556. Out << "linear ";
  11557. break;
  11558. case clang::attr::HLSLCenter:
  11559. Out << "center ";
  11560. break;
  11561. case clang::attr::HLSLCentroid:
  11562. Out << "centroid ";
  11563. break;
  11564. case clang::attr::HLSLNoInterpolation:
  11565. Out << "nointerpolation ";
  11566. break;
  11567. case clang::attr::HLSLNoPerspective:
  11568. Out << "noperspective ";
  11569. break;
  11570. case clang::attr::HLSLSample:
  11571. Out << "sample ";
  11572. break;
  11573. // Function attributes
  11574. case clang::attr::HLSLClipPlanes:
  11575. {
  11576. Attr * noconst = const_cast<Attr*>(A);
  11577. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  11578. if (!ACast->getClipPlane1())
  11579. break;
  11580. Indent(Indentation, Out);
  11581. Out << "[clipplanes(";
  11582. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  11583. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  11584. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  11585. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  11586. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  11587. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  11588. Out << ")]\n";
  11589. break;
  11590. }
  11591. case clang::attr::HLSLDomain:
  11592. {
  11593. Attr * noconst = const_cast<Attr*>(A);
  11594. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  11595. Indent(Indentation, Out);
  11596. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  11597. break;
  11598. }
  11599. case clang::attr::HLSLEarlyDepthStencil:
  11600. Indent(Indentation, Out);
  11601. Out << "[earlydepthstencil]\n";
  11602. break;
  11603. case clang::attr::HLSLInstance: //TODO - test
  11604. {
  11605. Attr * noconst = const_cast<Attr*>(A);
  11606. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  11607. Indent(Indentation, Out);
  11608. Out << "[instance(" << ACast->getCount() << ")]\n";
  11609. break;
  11610. }
  11611. case clang::attr::HLSLMaxTessFactor: //TODO - test
  11612. {
  11613. Attr * noconst = const_cast<Attr*>(A);
  11614. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  11615. Indent(Indentation, Out);
  11616. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  11617. break;
  11618. }
  11619. case clang::attr::HLSLNumThreads: //TODO - test
  11620. {
  11621. Attr * noconst = const_cast<Attr*>(A);
  11622. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  11623. Indent(Indentation, Out);
  11624. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  11625. break;
  11626. }
  11627. case clang::attr::HLSLRootSignature:
  11628. {
  11629. Attr * noconst = const_cast<Attr*>(A);
  11630. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  11631. Indent(Indentation, Out);
  11632. Out << "[RootSignature(\"" << ACast->getSignatureName() << "\")]\n";
  11633. break;
  11634. }
  11635. case clang::attr::HLSLOutputControlPoints:
  11636. {
  11637. Attr * noconst = const_cast<Attr*>(A);
  11638. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  11639. Indent(Indentation, Out);
  11640. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  11641. break;
  11642. }
  11643. case clang::attr::HLSLOutputTopology:
  11644. {
  11645. Attr * noconst = const_cast<Attr*>(A);
  11646. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  11647. Indent(Indentation, Out);
  11648. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  11649. break;
  11650. }
  11651. case clang::attr::HLSLPartitioning:
  11652. {
  11653. Attr * noconst = const_cast<Attr*>(A);
  11654. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  11655. Indent(Indentation, Out);
  11656. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  11657. break;
  11658. }
  11659. case clang::attr::HLSLPatchConstantFunc:
  11660. {
  11661. Attr * noconst = const_cast<Attr*>(A);
  11662. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  11663. Indent(Indentation, Out);
  11664. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  11665. break;
  11666. }
  11667. case clang::attr::HLSLShader:
  11668. {
  11669. Attr * noconst = const_cast<Attr*>(A);
  11670. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  11671. Indent(Indentation, Out);
  11672. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  11673. break;
  11674. }
  11675. case clang::attr::HLSLExperimental:
  11676. {
  11677. Attr * noconst = const_cast<Attr*>(A);
  11678. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  11679. Indent(Indentation, Out);
  11680. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  11681. break;
  11682. }
  11683. case clang::attr::HLSLMaxVertexCount:
  11684. {
  11685. Attr * noconst = const_cast<Attr*>(A);
  11686. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  11687. Indent(Indentation, Out);
  11688. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  11689. break;
  11690. }
  11691. case clang::attr::NoInline:
  11692. Indent(Indentation, Out);
  11693. Out << "[noinline]\n";
  11694. break;
  11695. case clang::attr::HLSLExport:
  11696. Indent(Indentation, Out);
  11697. Out << "export\n";
  11698. break;
  11699. // Statement attributes
  11700. case clang::attr::HLSLAllowUAVCondition:
  11701. Indent(Indentation, Out);
  11702. Out << "[allow_uav_condition]\n";
  11703. break;
  11704. case clang::attr::HLSLBranch:
  11705. Indent(Indentation, Out);
  11706. Out << "[branch]\n";
  11707. break;
  11708. case clang::attr::HLSLCall:
  11709. Indent(Indentation, Out);
  11710. Out << "[call]\n";
  11711. break;
  11712. case clang::attr::HLSLFastOpt:
  11713. Indent(Indentation, Out);
  11714. Out << "[fastopt]\n";
  11715. break;
  11716. case clang::attr::HLSLFlatten:
  11717. Indent(Indentation, Out);
  11718. Out << "[flatten]\n";
  11719. break;
  11720. case clang::attr::HLSLForceCase:
  11721. Indent(Indentation, Out);
  11722. Out << "[forcecase]\n";
  11723. break;
  11724. case clang::attr::HLSLLoop:
  11725. Indent(Indentation, Out);
  11726. Out << "[loop]\n";
  11727. break;
  11728. case clang::attr::HLSLUnroll:
  11729. {
  11730. Attr * noconst = const_cast<Attr*>(A);
  11731. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  11732. Indent(Indentation, Out);
  11733. if (ACast->getCount() == 0)
  11734. Out << "[unroll]\n";
  11735. else
  11736. Out << "[unroll(" << ACast->getCount() << ")]\n";
  11737. break;
  11738. }
  11739. case clang::attr::HLSLWaveSize:
  11740. {
  11741. Attr * noconst = const_cast<Attr*>(A);
  11742. HLSLWaveSizeAttr *ACast = static_cast<HLSLWaveSizeAttr*>(noconst);
  11743. Indent(Indentation, Out);
  11744. Out << "[wavesize(" << ACast->getSize() << ")]\n";
  11745. break;
  11746. }
  11747. // Variable modifiers
  11748. case clang::attr::HLSLGroupShared:
  11749. Out << "groupshared ";
  11750. break;
  11751. case clang::attr::HLSLPrecise:
  11752. Out << "precise ";
  11753. break;
  11754. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  11755. break;
  11756. case clang::attr::HLSLShared:
  11757. Out << "shared ";
  11758. break;
  11759. case clang::attr::HLSLUniform:
  11760. Out << "uniform ";
  11761. break;
  11762. // These four cases are printed in TypePrinter::printAttributedBefore
  11763. case clang::attr::HLSLColumnMajor:
  11764. case clang::attr::HLSLRowMajor:
  11765. case clang::attr::HLSLSnorm:
  11766. case clang::attr::HLSLUnorm:
  11767. break;
  11768. case clang::attr::HLSLPoint:
  11769. Out << "point ";
  11770. break;
  11771. case clang::attr::HLSLLine:
  11772. Out << "line ";
  11773. break;
  11774. case clang::attr::HLSLLineAdj:
  11775. Out << "lineadj ";
  11776. break;
  11777. case clang::attr::HLSLTriangle:
  11778. Out << "triangle ";
  11779. break;
  11780. case clang::attr::HLSLTriangleAdj:
  11781. Out << "triangleadj ";
  11782. break;
  11783. case clang::attr::HLSLGloballyCoherent:
  11784. Out << "globallycoherent ";
  11785. break;
  11786. case clang::attr::HLSLIndices:
  11787. Out << "indices ";
  11788. break;
  11789. case clang::attr::HLSLVertices:
  11790. Out << "vertices ";
  11791. break;
  11792. case clang::attr::HLSLPrimitives:
  11793. Out << "primitives ";
  11794. break;
  11795. case clang::attr::HLSLPayload:
  11796. Out << "payload ";
  11797. break;
  11798. default:
  11799. A->printPretty(Out, Policy);
  11800. break;
  11801. }
  11802. }
  11803. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  11804. switch (AttrKind){
  11805. case clang::attr::HLSLAllowUAVCondition:
  11806. case clang::attr::HLSLBranch:
  11807. case clang::attr::HLSLCall:
  11808. case clang::attr::HLSLCentroid:
  11809. case clang::attr::HLSLClipPlanes:
  11810. case clang::attr::HLSLColumnMajor:
  11811. case clang::attr::HLSLDomain:
  11812. case clang::attr::HLSLEarlyDepthStencil:
  11813. case clang::attr::HLSLFastOpt:
  11814. case clang::attr::HLSLFlatten:
  11815. case clang::attr::HLSLForceCase:
  11816. case clang::attr::HLSLGroupShared:
  11817. case clang::attr::HLSLIn:
  11818. case clang::attr::HLSLInOut:
  11819. case clang::attr::HLSLInstance:
  11820. case clang::attr::HLSLLinear:
  11821. case clang::attr::HLSLCenter:
  11822. case clang::attr::HLSLLoop:
  11823. case clang::attr::HLSLMaxTessFactor:
  11824. case clang::attr::HLSLNoInterpolation:
  11825. case clang::attr::HLSLNoPerspective:
  11826. case clang::attr::HLSLNumThreads:
  11827. case clang::attr::HLSLRootSignature:
  11828. case clang::attr::HLSLOut:
  11829. case clang::attr::HLSLOutputControlPoints:
  11830. case clang::attr::HLSLOutputTopology:
  11831. case clang::attr::HLSLPartitioning:
  11832. case clang::attr::HLSLPatchConstantFunc:
  11833. case clang::attr::HLSLMaxVertexCount:
  11834. case clang::attr::HLSLPrecise:
  11835. case clang::attr::HLSLRowMajor:
  11836. case clang::attr::HLSLSample:
  11837. case clang::attr::HLSLSemantic:
  11838. case clang::attr::HLSLShared:
  11839. case clang::attr::HLSLSnorm:
  11840. case clang::attr::HLSLUniform:
  11841. case clang::attr::HLSLUnorm:
  11842. case clang::attr::HLSLUnroll:
  11843. case clang::attr::HLSLPoint:
  11844. case clang::attr::HLSLLine:
  11845. case clang::attr::HLSLLineAdj:
  11846. case clang::attr::HLSLTriangle:
  11847. case clang::attr::HLSLTriangleAdj:
  11848. case clang::attr::HLSLGloballyCoherent:
  11849. case clang::attr::HLSLIndices:
  11850. case clang::attr::HLSLVertices:
  11851. case clang::attr::HLSLPrimitives:
  11852. case clang::attr::HLSLPayload:
  11853. case clang::attr::NoInline:
  11854. case clang::attr::HLSLExport:
  11855. case clang::attr::HLSLWaveSensitive:
  11856. case clang::attr::HLSLWaveSize:
  11857. case clang::attr::VKBinding:
  11858. case clang::attr::VKBuiltIn:
  11859. case clang::attr::VKConstantId:
  11860. case clang::attr::VKCounterBinding:
  11861. case clang::attr::VKIndex:
  11862. case clang::attr::VKInputAttachmentIndex:
  11863. case clang::attr::VKLocation:
  11864. case clang::attr::VKOffset:
  11865. case clang::attr::VKPushConstant:
  11866. case clang::attr::VKShaderRecordNV:
  11867. case clang::attr::VKShaderRecordEXT:
  11868. return true;
  11869. default:
  11870. // Only HLSL/VK Attributes return true. Only used for printPretty(), which doesn't support them.
  11871. break;
  11872. }
  11873. return false;
  11874. }
  11875. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  11876. if (ClipPlane) {
  11877. Out << ", ";
  11878. ClipPlane->printPretty(Out, 0, Policy);
  11879. }
  11880. }
  11881. bool hlsl::IsObjectType(
  11882. _In_ clang::Sema* self,
  11883. _In_ clang::QualType type,
  11884. _Inout_opt_ bool *isDeprecatedEffectObject)
  11885. {
  11886. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  11887. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  11888. if (isDeprecatedEffectObject)
  11889. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  11890. return true;
  11891. }
  11892. if (isDeprecatedEffectObject)
  11893. *isDeprecatedEffectObject = false;
  11894. return false;
  11895. }
  11896. bool hlsl::CanConvert(
  11897. _In_ clang::Sema* self,
  11898. clang::SourceLocation loc,
  11899. _In_ clang::Expr* sourceExpr,
  11900. clang::QualType target,
  11901. bool explicitConversion,
  11902. _Inout_opt_ clang::StandardConversionSequence* standard)
  11903. {
  11904. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  11905. }
  11906. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  11907. {
  11908. for (unsigned i = 0; i != Indentation; ++i)
  11909. Out << " ";
  11910. }
  11911. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  11912. {
  11913. DXASSERT_NOMSG(self != nullptr);
  11914. DXASSERT_NOMSG(table != nullptr);
  11915. HLSLExternalSource* source = (HLSLExternalSource*)self;
  11916. source->RegisterIntrinsicTable(table);
  11917. }
  11918. clang::QualType hlsl::CheckVectorConditional(
  11919. _In_ clang::Sema* self,
  11920. _In_ clang::ExprResult &Cond,
  11921. _In_ clang::ExprResult &LHS,
  11922. _In_ clang::ExprResult &RHS,
  11923. _In_ clang::SourceLocation QuestionLoc)
  11924. {
  11925. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  11926. }
  11927. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  11928. UINT count;
  11929. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  11930. }
  11931. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  11932. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  11933. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  11934. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  11935. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  11936. llvm::APSInt index;
  11937. if (RHS->EvaluateAsInt(index, Context)) {
  11938. int64_t intIndex = index.getLimitedValue();
  11939. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  11940. if (IsVectorType(this, LHSQualType)) {
  11941. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  11942. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  11943. // we also have to check the first subscript oprator by recursively calling
  11944. // this funciton for the first CXXOperatorCallExpr
  11945. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  11946. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  11947. }
  11948. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  11949. Diag(RHS->getExprLoc(),
  11950. diag::err_hlsl_vector_element_index_out_of_bounds)
  11951. << (int)intIndex;
  11952. }
  11953. }
  11954. else if (IsMatrixType(this, LHSQualType)) {
  11955. uint32_t rowCount, colCount;
  11956. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  11957. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  11958. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  11959. << (int)intIndex;
  11960. }
  11961. }
  11962. }
  11963. }
  11964. clang::QualType ApplyTypeSpecSignToParsedType(
  11965. _In_ clang::Sema* self,
  11966. _In_ clang::QualType &type,
  11967. _In_ clang::TypeSpecifierSign TSS,
  11968. _In_ clang::SourceLocation Loc
  11969. )
  11970. {
  11971. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  11972. }