SemaHLSL.cpp 404 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816
  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/dxcapi.internal.h"
  35. #include "dxc/HlslIntrinsicOp.h"
  36. #include "gen_intrin_main_tables_15.h"
  37. #include "dxc/HLSL/HLOperations.h"
  38. #include "dxc/HLSL/DxilShaderModel.h"
  39. #include <array>
  40. enum ArBasicKind {
  41. AR_BASIC_BOOL,
  42. AR_BASIC_LITERAL_FLOAT,
  43. AR_BASIC_FLOAT16,
  44. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  45. AR_BASIC_FLOAT32,
  46. AR_BASIC_FLOAT64,
  47. AR_BASIC_LITERAL_INT,
  48. AR_BASIC_INT8,
  49. AR_BASIC_UINT8,
  50. AR_BASIC_INT16,
  51. AR_BASIC_UINT16,
  52. AR_BASIC_INT32,
  53. AR_BASIC_UINT32,
  54. AR_BASIC_INT64,
  55. AR_BASIC_UINT64,
  56. AR_BASIC_MIN10FLOAT,
  57. AR_BASIC_MIN16FLOAT,
  58. AR_BASIC_MIN12INT,
  59. AR_BASIC_MIN16INT,
  60. AR_BASIC_MIN16UINT,
  61. AR_BASIC_ENUM,
  62. AR_BASIC_COUNT,
  63. //
  64. // Pseudo-entries for intrinsic tables and such.
  65. //
  66. AR_BASIC_NONE,
  67. AR_BASIC_UNKNOWN,
  68. AR_BASIC_NOCAST,
  69. //
  70. // The following pseudo-entries represent higher-level
  71. // object types that are treated as units.
  72. //
  73. AR_BASIC_POINTER,
  74. AR_BASIC_ENUM_CLASS,
  75. AR_OBJECT_NULL,
  76. AR_OBJECT_STRING,
  77. // AR_OBJECT_TEXTURE,
  78. AR_OBJECT_TEXTURE1D,
  79. AR_OBJECT_TEXTURE1D_ARRAY,
  80. AR_OBJECT_TEXTURE2D,
  81. AR_OBJECT_TEXTURE2D_ARRAY,
  82. AR_OBJECT_TEXTURE3D,
  83. AR_OBJECT_TEXTURECUBE,
  84. AR_OBJECT_TEXTURECUBE_ARRAY,
  85. AR_OBJECT_TEXTURE2DMS,
  86. AR_OBJECT_TEXTURE2DMS_ARRAY,
  87. AR_OBJECT_SAMPLER,
  88. AR_OBJECT_SAMPLER1D,
  89. AR_OBJECT_SAMPLER2D,
  90. AR_OBJECT_SAMPLER3D,
  91. AR_OBJECT_SAMPLERCUBE,
  92. AR_OBJECT_SAMPLERCOMPARISON,
  93. AR_OBJECT_BUFFER,
  94. //
  95. // View objects are only used as variable/types within the Effects
  96. // framework, for example in calls to OMSetRenderTargets.
  97. //
  98. AR_OBJECT_RENDERTARGETVIEW,
  99. AR_OBJECT_DEPTHSTENCILVIEW,
  100. //
  101. // Shader objects are only used as variable/types within the Effects
  102. // framework, for example as a result of CompileShader().
  103. //
  104. AR_OBJECT_COMPUTESHADER,
  105. AR_OBJECT_DOMAINSHADER,
  106. AR_OBJECT_GEOMETRYSHADER,
  107. AR_OBJECT_HULLSHADER,
  108. AR_OBJECT_PIXELSHADER,
  109. AR_OBJECT_VERTEXSHADER,
  110. AR_OBJECT_PIXELFRAGMENT,
  111. AR_OBJECT_VERTEXFRAGMENT,
  112. AR_OBJECT_STATEBLOCK,
  113. AR_OBJECT_RASTERIZER,
  114. AR_OBJECT_DEPTHSTENCIL,
  115. AR_OBJECT_BLEND,
  116. AR_OBJECT_POINTSTREAM,
  117. AR_OBJECT_LINESTREAM,
  118. AR_OBJECT_TRIANGLESTREAM,
  119. AR_OBJECT_INPUTPATCH,
  120. AR_OBJECT_OUTPUTPATCH,
  121. AR_OBJECT_RWTEXTURE1D,
  122. AR_OBJECT_RWTEXTURE1D_ARRAY,
  123. AR_OBJECT_RWTEXTURE2D,
  124. AR_OBJECT_RWTEXTURE2D_ARRAY,
  125. AR_OBJECT_RWTEXTURE3D,
  126. AR_OBJECT_RWBUFFER,
  127. AR_OBJECT_BYTEADDRESS_BUFFER,
  128. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  129. AR_OBJECT_STRUCTURED_BUFFER,
  130. AR_OBJECT_RWSTRUCTURED_BUFFER,
  131. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  132. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  133. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  134. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  135. AR_OBJECT_CONSTANT_BUFFER,
  136. AR_OBJECT_TEXTURE_BUFFER,
  137. AR_OBJECT_ROVBUFFER,
  138. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  139. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  140. AR_OBJECT_ROVTEXTURE1D,
  141. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  142. AR_OBJECT_ROVTEXTURE2D,
  143. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  144. AR_OBJECT_ROVTEXTURE3D,
  145. // SPIRV change starts
  146. #ifdef ENABLE_SPIRV_CODEGEN
  147. AR_OBJECT_VK_SUBPASS_INPUT,
  148. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  149. #endif // ENABLE_SPIRV_CODEGEN
  150. // SPIRV change ends
  151. AR_OBJECT_INNER, // Used for internal type object
  152. AR_OBJECT_LEGACY_EFFECT,
  153. AR_OBJECT_WAVE,
  154. AR_BASIC_MAXIMUM_COUNT
  155. };
  156. #define AR_BASIC_TEXTURE_MS_CASES \
  157. case AR_OBJECT_TEXTURE2DMS: \
  158. case AR_OBJECT_TEXTURE2DMS_ARRAY
  159. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  160. case AR_OBJECT_TEXTURE1D: \
  161. case AR_OBJECT_TEXTURE1D_ARRAY: \
  162. case AR_OBJECT_TEXTURE2D: \
  163. case AR_OBJECT_TEXTURE2D_ARRAY: \
  164. case AR_OBJECT_TEXTURE3D: \
  165. case AR_OBJECT_TEXTURECUBE: \
  166. case AR_OBJECT_TEXTURECUBE_ARRAY
  167. #define AR_BASIC_TEXTURE_CASES \
  168. AR_BASIC_TEXTURE_MS_CASES: \
  169. AR_BASIC_NON_TEXTURE_MS_CASES
  170. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  171. case AR_OBJECT_SAMPLER: \
  172. case AR_OBJECT_SAMPLER1D: \
  173. case AR_OBJECT_SAMPLER2D: \
  174. case AR_OBJECT_SAMPLER3D: \
  175. case AR_OBJECT_SAMPLERCUBE
  176. #define AR_BASIC_ROBJECT_CASES \
  177. case AR_OBJECT_BLEND: \
  178. case AR_OBJECT_RASTERIZER: \
  179. case AR_OBJECT_DEPTHSTENCIL: \
  180. case AR_OBJECT_STATEBLOCK
  181. //
  182. // Properties of entries in the ArBasicKind enumeration.
  183. // These properties are intended to allow easy identification
  184. // of classes of basic kinds. More specific checks on the
  185. // actual kind values could then be done.
  186. //
  187. // The first four bits are used as a subtype indicator,
  188. // such as bit count for primitive kinds or specific
  189. // types for non-primitive-data kinds.
  190. #define BPROP_SUBTYPE_MASK 0x0000000f
  191. // Bit counts must be ordered from smaller to larger.
  192. #define BPROP_BITS0 0x00000000
  193. #define BPROP_BITS8 0x00000001
  194. #define BPROP_BITS10 0x00000002
  195. #define BPROP_BITS12 0x00000003
  196. #define BPROP_BITS16 0x00000004
  197. #define BPROP_BITS32 0x00000005
  198. #define BPROP_BITS64 0x00000006
  199. #define BPROP_BITS_NON_PRIM 0x00000007
  200. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  201. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  202. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  203. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  204. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  205. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  206. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  207. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  208. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  209. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  210. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  211. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  212. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  213. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  214. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  215. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  216. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  217. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  218. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  219. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  220. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  221. #define BPROP_ENUM 0x00800000 // Whether the type is a enum
  222. #define GET_BPROP_PRIM_KIND(_Props) \
  223. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  224. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  225. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  226. #define IS_BPROP_PRIMITIVE(_Props) \
  227. (((_Props) & BPROP_PRIMITIVE) != 0)
  228. #define IS_BPROP_BOOL(_Props) \
  229. (((_Props) & BPROP_BOOLEAN) != 0)
  230. #define IS_BPROP_FLOAT(_Props) \
  231. (((_Props) & BPROP_FLOATING) != 0)
  232. #define IS_BPROP_SINT(_Props) \
  233. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  234. BPROP_INTEGER)
  235. #define IS_BPROP_UINT(_Props) \
  236. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  237. (BPROP_INTEGER | BPROP_UNSIGNED))
  238. #define IS_BPROP_AINT(_Props) \
  239. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  240. #define IS_BPROP_STREAM(_Props) \
  241. (((_Props) & BPROP_STREAM) != 0)
  242. #define IS_BPROP_SAMPLER(_Props) \
  243. (((_Props) & BPROP_SAMPLER) != 0)
  244. #define IS_BPROP_TEXTURE(_Props) \
  245. (((_Props) & BPROP_TEXTURE) != 0)
  246. #define IS_BPROP_OBJECT(_Props) \
  247. (((_Props) & BPROP_OBJECT) != 0)
  248. #define IS_BPROP_MIN_PRECISION(_Props) \
  249. (((_Props) & BPROP_MIN_PRECISION) != 0)
  250. #define IS_BPROP_UNSIGNABLE(_Props) \
  251. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  252. #define IS_BPROP_ENUM(_Props) \
  253. (((_Props) & BPROP_ENUM) != 0)
  254. const UINT g_uBasicKindProps[] =
  255. {
  256. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  257. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  258. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  259. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  260. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  261. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  262. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  263. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  264. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  265. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  266. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  267. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  268. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  269. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  270. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  271. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  272. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  273. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  274. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  275. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  276. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  277. BPROP_OTHER, // AR_BASIC_COUNT
  278. //
  279. // Pseudo-entries for intrinsic tables and such.
  280. //
  281. 0, // AR_BASIC_NONE
  282. BPROP_OTHER, // AR_BASIC_UNKNOWN
  283. BPROP_OTHER, // AR_BASIC_NOCAST
  284. //
  285. // The following pseudo-entries represent higher-level
  286. // object types that are treated as units.
  287. //
  288. BPROP_POINTER, // AR_BASIC_POINTER
  289. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  290. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  291. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  292. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  293. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  294. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  295. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  296. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  297. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  298. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  299. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  300. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  301. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  302. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  303. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  304. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  305. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  306. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  307. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  308. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  309. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  310. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  311. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  312. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  313. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  314. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  315. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  316. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  317. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  318. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  319. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  320. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  321. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  322. BPROP_OBJECT, // AR_OBJECT_BLEND
  323. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  324. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  325. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  326. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  327. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  328. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  329. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  330. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  331. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  332. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  333. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  334. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  335. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  336. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  337. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  338. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  339. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  340. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  341. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  342. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  343. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  344. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  345. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  346. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  347. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  348. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  349. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  350. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  351. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  352. // SPIRV change starts
  353. #ifdef ENABLE_SPIRV_CODEGEN
  354. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  355. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  356. #endif // ENABLE_SPIRV_CODEGEN
  357. // SPIRV change ends
  358. BPROP_OBJECT, // AR_OBJECT_INNER
  359. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  360. BPROP_OBJECT, // AR_OBJECT_WAVE
  361. // AR_BASIC_MAXIMUM_COUNT
  362. };
  363. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  364. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  365. #define GET_BASIC_BITS(_Kind) \
  366. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  367. #define GET_BASIC_PRIM_KIND(_Kind) \
  368. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  369. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  370. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  371. #define IS_BASIC_PRIMITIVE(_Kind) \
  372. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  373. #define IS_BASIC_BOOL(_Kind) \
  374. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  375. #define IS_BASIC_FLOAT(_Kind) \
  376. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  377. #define IS_BASIC_SINT(_Kind) \
  378. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  379. #define IS_BASIC_UINT(_Kind) \
  380. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  381. #define IS_BASIC_AINT(_Kind) \
  382. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  383. #define IS_BASIC_STREAM(_Kind) \
  384. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  385. #define IS_BASIC_SAMPLER(_Kind) \
  386. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  387. #define IS_BASIC_TEXTURE(_Kind) \
  388. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  389. #define IS_BASIC_OBJECT(_Kind) \
  390. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  391. #define IS_BASIC_MIN_PRECISION(_Kind) \
  392. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  393. #define IS_BASIC_UNSIGNABLE(_Kind) \
  394. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  395. #define IS_BASIC_ENUM(_Kind) \
  396. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  397. #define BITWISE_ENUM_OPS(_Type) \
  398. inline _Type operator|(_Type F1, _Type F2) \
  399. { \
  400. return (_Type)((UINT)F1 | (UINT)F2); \
  401. } \
  402. inline _Type operator&(_Type F1, _Type F2) \
  403. { \
  404. return (_Type)((UINT)F1 & (UINT)F2); \
  405. } \
  406. inline _Type& operator|=(_Type& F1, _Type F2) \
  407. { \
  408. F1 = F1 | F2; \
  409. return F1; \
  410. } \
  411. inline _Type& operator&=(_Type& F1, _Type F2) \
  412. { \
  413. F1 = F1 & F2; \
  414. return F1; \
  415. } \
  416. inline _Type& operator&=(_Type& F1, UINT F2) \
  417. { \
  418. F1 = (_Type)((UINT)F1 & F2); \
  419. return F1; \
  420. }
  421. enum ArTypeObjectKind {
  422. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  423. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  424. AR_TOBJ_BASIC, // Represents a primitive type.
  425. AR_TOBJ_COMPOUND, // Represents a struct or class.
  426. AR_TOBJ_INTERFACE, // Represents an interface.
  427. AR_TOBJ_POINTER, // Represents a pointer to another type.
  428. AR_TOBJ_OBJECT, // Represents a built-in object.
  429. AR_TOBJ_ARRAY, // Represents an array of other types.
  430. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  431. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  432. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  433. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  434. // indexer object used to implement .mips[1].
  435. };
  436. enum TYPE_CONVERSION_FLAGS
  437. {
  438. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  439. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  440. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  441. };
  442. enum TYPE_CONVERSION_REMARKS
  443. {
  444. TYPE_CONVERSION_NONE = 0x00000000,
  445. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  446. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  447. TYPE_CONVERSION_TO_VOID = 0x00000004,
  448. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  449. };
  450. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  451. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  452. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  453. #define AR_TPROP_VOID 0x0000000000000001
  454. #define AR_TPROP_CONST 0x0000000000000002
  455. #define AR_TPROP_IMP_CONST 0x0000000000000004
  456. #define AR_TPROP_OBJECT 0x0000000000000008
  457. #define AR_TPROP_SCALAR 0x0000000000000010
  458. #define AR_TPROP_UNSIGNED 0x0000000000000020
  459. #define AR_TPROP_NUMERIC 0x0000000000000040
  460. #define AR_TPROP_INTEGRAL 0x0000000000000080
  461. #define AR_TPROP_FLOATING 0x0000000000000100
  462. #define AR_TPROP_LITERAL 0x0000000000000200
  463. #define AR_TPROP_POINTER 0x0000000000000400
  464. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  465. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  466. #define AR_TPROP_INH_IFACE 0x0000000000002000
  467. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  468. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  469. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  470. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  471. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  472. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  473. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  474. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  475. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  476. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  477. #define AR_TPROP_INDEXABLE 0x0000000001000000
  478. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  479. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  480. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  481. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  482. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  483. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  484. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  485. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  486. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  487. #define AR_TPROP_ALL 0xffffffffffffffff
  488. #define AR_TPROP_HAS_OBJECTS \
  489. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  490. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  491. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  492. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  493. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  494. #define AR_TPROP_HAS_BASIC_RESOURCES \
  495. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  496. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  497. AR_TPROP_HAS_UAVS)
  498. #define AR_TPROP_UNION_BITS \
  499. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  500. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  501. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  502. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  503. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  504. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  505. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  506. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  507. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  508. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  509. #define AR_TINFO_PACK_SCALAR 0x00000010
  510. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  511. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  512. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  513. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  514. #define AR_TINFO_PACK_CBUFFER 0
  515. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  516. #define AR_TINFO_SIMPLE_OBJECTS \
  517. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  518. struct ArTypeInfo {
  519. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  520. ArBasicKind EltKind; // The primitive type of elements in this type.
  521. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  522. UINT uRows;
  523. UINT uCols;
  524. UINT uTotalElts;
  525. };
  526. using namespace clang;
  527. using namespace clang::sema;
  528. using namespace hlsl;
  529. extern const char *HLSLScalarTypeNames[];
  530. static const int FirstTemplateDepth = 0;
  531. static const int FirstParamPosition = 0;
  532. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  533. static const bool InheritedFalse = false; // template parameter default value is not inherited.
  534. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  535. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  536. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  537. static const bool DelayTypeCreationFalse = false; // immediately create a type when the declaration is created
  538. static const unsigned int NoQuals = 0; // no qualifiers in effect
  539. static const SourceLocation NoLoc; // no source location attribution available
  540. static const SourceRange NoRange; // no source range attribution available
  541. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  542. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  543. static const bool IsConstexprFalse = false; // function is not constexpr
  544. static const bool ListInitializationFalse = false;// not performing a list initialization
  545. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  546. static const bool SuppressWarningsTrue = true; // suppress warning diagnostics
  547. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  548. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  549. static const int OneRow = 1; // a single row for a type
  550. static const bool MipsFalse = false; // a type does not support the .mips member
  551. static const bool MipsTrue = true; // a type supports the .mips member
  552. static const bool SampleFalse = false; // a type does not support the .sample member
  553. static const bool SampleTrue = true; // a type supports the .sample member
  554. static const size_t MaxVectorSize = 4; // maximum size for a vector
  555. static
  556. QualType GetOrCreateTemplateSpecialization(
  557. ASTContext& context,
  558. Sema& sema,
  559. _In_ ClassTemplateDecl* templateDecl,
  560. ArrayRef<TemplateArgument> templateArgs
  561. )
  562. {
  563. DXASSERT_NOMSG(templateDecl);
  564. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  565. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  566. for (const TemplateArgument& Arg : templateArgs) {
  567. if (Arg.getKind() == TemplateArgument::Type) {
  568. // the class template need to use CanonicalType
  569. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  570. }else
  571. templateArgsForDecl.emplace_back(Arg);
  572. }
  573. // First, try looking up existing specialization
  574. void* InsertPos = nullptr;
  575. ClassTemplateSpecializationDecl* specializationDecl =
  576. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  577. if (specializationDecl) {
  578. // Instantiate the class template if not yet.
  579. if (specializationDecl->getInstantiatedFrom().isNull()) {
  580. // InstantiateClassTemplateSpecialization returns true if it finds an
  581. // error.
  582. DXVERIFY_NOMSG(false ==
  583. sema.InstantiateClassTemplateSpecialization(
  584. NoLoc, specializationDecl,
  585. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  586. true));
  587. }
  588. return context.getTemplateSpecializationType(
  589. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  590. context.getTypeDeclType(specializationDecl));
  591. }
  592. specializationDecl = ClassTemplateSpecializationDecl::Create(
  593. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  594. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  595. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  596. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  597. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  598. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  599. specializationDecl->setImplicit(true);
  600. QualType canonType = context.getTypeDeclType(specializationDecl);
  601. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  602. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  603. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  604. for (unsigned i = 0; i < templateArgs.size(); i++) {
  605. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  606. }
  607. return context.getTemplateSpecializationType(
  608. TemplateName(templateDecl), templateArgumentList, canonType);
  609. }
  610. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  611. static
  612. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  613. _In_ ClassTemplateDecl* matrixTemplateDecl,
  614. QualType elementType, uint64_t rowCount, uint64_t colCount)
  615. {
  616. DXASSERT_NOMSG(sema);
  617. TemplateArgument templateArgs[3] = {
  618. TemplateArgument(elementType),
  619. TemplateArgument(
  620. context,
  621. llvm::APSInt(
  622. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  623. context.IntTy),
  624. TemplateArgument(
  625. context,
  626. llvm::APSInt(
  627. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  628. context.IntTy)};
  629. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  630. #ifdef DBG
  631. // Verify that we can read the field member from the template record.
  632. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  633. "type of non-dependent specialization is not a RecordType");
  634. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  635. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  636. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  637. #endif
  638. return matrixSpecializationType;
  639. }
  640. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  641. static
  642. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  643. _In_ ClassTemplateDecl* vectorTemplateDecl,
  644. QualType elementType, uint64_t colCount)
  645. {
  646. DXASSERT_NOMSG(sema);
  647. DXASSERT_NOMSG(vectorTemplateDecl);
  648. TemplateArgument templateArgs[2] = {
  649. TemplateArgument(elementType),
  650. TemplateArgument(
  651. context,
  652. llvm::APSInt(
  653. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  654. context.IntTy)};
  655. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  656. #ifdef DBG
  657. // Verify that we can read the field member from the template record.
  658. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  659. "type of non-dependent specialization is not a RecordType");
  660. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  661. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  662. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  663. #endif
  664. return vectorSpecializationType;
  665. }
  666. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  667. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  668. static const unsigned kAtomicDstOperandIdx = 1;
  669. static const ArTypeObjectKind g_ScalarTT[] =
  670. {
  671. AR_TOBJ_SCALAR,
  672. AR_TOBJ_UNKNOWN
  673. };
  674. static const ArTypeObjectKind g_VectorTT[] =
  675. {
  676. AR_TOBJ_VECTOR,
  677. AR_TOBJ_UNKNOWN
  678. };
  679. static const ArTypeObjectKind g_MatrixTT[] =
  680. {
  681. AR_TOBJ_MATRIX,
  682. AR_TOBJ_UNKNOWN
  683. };
  684. static const ArTypeObjectKind g_AnyTT[] =
  685. {
  686. AR_TOBJ_SCALAR,
  687. AR_TOBJ_VECTOR,
  688. AR_TOBJ_MATRIX,
  689. AR_TOBJ_UNKNOWN
  690. };
  691. static const ArTypeObjectKind g_ObjectTT[] =
  692. {
  693. AR_TOBJ_OBJECT,
  694. AR_TOBJ_UNKNOWN
  695. };
  696. static const ArTypeObjectKind g_NullTT[] =
  697. {
  698. AR_TOBJ_VOID,
  699. AR_TOBJ_UNKNOWN
  700. };
  701. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  702. {
  703. g_NullTT,
  704. g_ScalarTT,
  705. g_VectorTT,
  706. g_MatrixTT,
  707. g_AnyTT,
  708. g_ObjectTT,
  709. };
  710. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  711. //
  712. // The first one is used to name the representative group, so make
  713. // sure its name will make sense in error messages.
  714. //
  715. static const ArBasicKind g_BoolCT[] =
  716. {
  717. AR_BASIC_BOOL,
  718. AR_BASIC_UNKNOWN
  719. };
  720. static const ArBasicKind g_IntCT[] =
  721. {
  722. AR_BASIC_INT32,
  723. AR_BASIC_LITERAL_INT,
  724. AR_BASIC_UNKNOWN
  725. };
  726. static const ArBasicKind g_UIntCT[] =
  727. {
  728. AR_BASIC_UINT32,
  729. AR_BASIC_LITERAL_INT,
  730. AR_BASIC_UNKNOWN
  731. };
  732. // We use the first element for default if matching kind is missing in the list.
  733. // AR_BASIC_INT32 should be the default for any int since min precision integers should map to int32, not int16 or int64
  734. static const ArBasicKind g_AnyIntCT[] =
  735. {
  736. AR_BASIC_INT32,
  737. AR_BASIC_INT16,
  738. AR_BASIC_UINT32,
  739. AR_BASIC_UINT16,
  740. AR_BASIC_INT64,
  741. AR_BASIC_UINT64,
  742. AR_BASIC_LITERAL_INT,
  743. AR_BASIC_UNKNOWN
  744. };
  745. static const ArBasicKind g_AnyInt32CT[] =
  746. {
  747. AR_BASIC_INT32,
  748. AR_BASIC_UINT32,
  749. AR_BASIC_LITERAL_INT,
  750. AR_BASIC_UNKNOWN
  751. };
  752. static const ArBasicKind g_UIntOnlyCT[] =
  753. {
  754. AR_BASIC_UINT32,
  755. AR_BASIC_UINT64,
  756. AR_BASIC_LITERAL_INT,
  757. AR_BASIC_NOCAST,
  758. AR_BASIC_UNKNOWN
  759. };
  760. static const ArBasicKind g_FloatCT[] =
  761. {
  762. AR_BASIC_FLOAT32,
  763. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  764. AR_BASIC_LITERAL_FLOAT,
  765. AR_BASIC_UNKNOWN
  766. };
  767. static const ArBasicKind g_AnyFloatCT[] =
  768. {
  769. AR_BASIC_FLOAT32,
  770. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  771. AR_BASIC_FLOAT16,
  772. AR_BASIC_FLOAT64,
  773. AR_BASIC_LITERAL_FLOAT,
  774. AR_BASIC_MIN10FLOAT,
  775. AR_BASIC_MIN16FLOAT,
  776. AR_BASIC_UNKNOWN
  777. };
  778. static const ArBasicKind g_FloatLikeCT[] =
  779. {
  780. AR_BASIC_FLOAT32,
  781. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  782. AR_BASIC_FLOAT16,
  783. AR_BASIC_LITERAL_FLOAT,
  784. AR_BASIC_MIN10FLOAT,
  785. AR_BASIC_MIN16FLOAT,
  786. AR_BASIC_UNKNOWN
  787. };
  788. static const ArBasicKind g_FloatDoubleCT[] =
  789. {
  790. AR_BASIC_FLOAT32,
  791. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  792. AR_BASIC_FLOAT64,
  793. AR_BASIC_LITERAL_FLOAT,
  794. AR_BASIC_UNKNOWN
  795. };
  796. static const ArBasicKind g_DoubleCT[] =
  797. {
  798. AR_BASIC_FLOAT64,
  799. AR_BASIC_LITERAL_FLOAT,
  800. AR_BASIC_UNKNOWN
  801. };
  802. static const ArBasicKind g_DoubleOnlyCT[] =
  803. {
  804. AR_BASIC_FLOAT64,
  805. AR_BASIC_NOCAST,
  806. AR_BASIC_UNKNOWN
  807. };
  808. static const ArBasicKind g_NumericCT[] =
  809. {
  810. AR_BASIC_LITERAL_FLOAT,
  811. AR_BASIC_FLOAT32,
  812. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  813. AR_BASIC_FLOAT16,
  814. AR_BASIC_FLOAT64,
  815. AR_BASIC_MIN10FLOAT,
  816. AR_BASIC_MIN16FLOAT,
  817. AR_BASIC_LITERAL_INT,
  818. AR_BASIC_INT16,
  819. AR_BASIC_INT32,
  820. AR_BASIC_UINT16,
  821. AR_BASIC_UINT32,
  822. AR_BASIC_MIN12INT,
  823. AR_BASIC_MIN16INT,
  824. AR_BASIC_MIN16UINT,
  825. AR_BASIC_INT64,
  826. AR_BASIC_UINT64,
  827. AR_BASIC_UNKNOWN
  828. };
  829. static const ArBasicKind g_Numeric32CT[] =
  830. {
  831. AR_BASIC_LITERAL_FLOAT,
  832. AR_BASIC_FLOAT32,
  833. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  834. AR_BASIC_LITERAL_INT,
  835. AR_BASIC_INT32,
  836. AR_BASIC_UINT32,
  837. AR_BASIC_UNKNOWN
  838. };
  839. static const ArBasicKind g_Numeric32OnlyCT[] =
  840. {
  841. AR_BASIC_LITERAL_FLOAT,
  842. AR_BASIC_FLOAT32,
  843. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  844. AR_BASIC_LITERAL_INT,
  845. AR_BASIC_INT32,
  846. AR_BASIC_UINT32,
  847. AR_BASIC_NOCAST,
  848. AR_BASIC_UNKNOWN
  849. };
  850. static const ArBasicKind g_AnyCT[] =
  851. {
  852. AR_BASIC_LITERAL_FLOAT,
  853. AR_BASIC_FLOAT32,
  854. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  855. AR_BASIC_FLOAT16,
  856. AR_BASIC_FLOAT64,
  857. AR_BASIC_MIN10FLOAT,
  858. AR_BASIC_MIN16FLOAT,
  859. AR_BASIC_LITERAL_INT,
  860. AR_BASIC_INT16,
  861. AR_BASIC_UINT16,
  862. AR_BASIC_INT32,
  863. AR_BASIC_UINT32,
  864. AR_BASIC_MIN12INT,
  865. AR_BASIC_MIN16INT,
  866. AR_BASIC_MIN16UINT,
  867. AR_BASIC_BOOL,
  868. AR_BASIC_INT64,
  869. AR_BASIC_UINT64,
  870. AR_BASIC_UNKNOWN
  871. };
  872. static const ArBasicKind g_Sampler1DCT[] =
  873. {
  874. AR_OBJECT_SAMPLER1D,
  875. AR_BASIC_UNKNOWN
  876. };
  877. static const ArBasicKind g_Sampler2DCT[] =
  878. {
  879. AR_OBJECT_SAMPLER2D,
  880. AR_BASIC_UNKNOWN
  881. };
  882. static const ArBasicKind g_Sampler3DCT[] =
  883. {
  884. AR_OBJECT_SAMPLER3D,
  885. AR_BASIC_UNKNOWN
  886. };
  887. static const ArBasicKind g_SamplerCUBECT[] =
  888. {
  889. AR_OBJECT_SAMPLERCUBE,
  890. AR_BASIC_UNKNOWN
  891. };
  892. static const ArBasicKind g_SamplerCmpCT[] =
  893. {
  894. AR_OBJECT_SAMPLERCOMPARISON,
  895. AR_BASIC_UNKNOWN
  896. };
  897. static const ArBasicKind g_SamplerCT[] =
  898. {
  899. AR_OBJECT_SAMPLER,
  900. AR_BASIC_UNKNOWN
  901. };
  902. static const ArBasicKind g_StringCT[] =
  903. {
  904. AR_OBJECT_STRING,
  905. AR_BASIC_UNKNOWN
  906. };
  907. static const ArBasicKind g_NullCT[] =
  908. {
  909. AR_OBJECT_NULL,
  910. AR_BASIC_UNKNOWN
  911. };
  912. static const ArBasicKind g_WaveCT[] =
  913. {
  914. AR_OBJECT_WAVE,
  915. AR_BASIC_UNKNOWN
  916. };
  917. static const ArBasicKind g_UInt64CT[] =
  918. {
  919. AR_BASIC_UINT64,
  920. AR_BASIC_UNKNOWN
  921. };
  922. static const ArBasicKind g_Float16CT[] =
  923. {
  924. AR_BASIC_FLOAT16,
  925. AR_BASIC_LITERAL_FLOAT,
  926. AR_BASIC_UNKNOWN
  927. };
  928. static const ArBasicKind g_Int16CT[] =
  929. {
  930. AR_BASIC_INT16,
  931. AR_BASIC_LITERAL_INT,
  932. AR_BASIC_UNKNOWN
  933. };
  934. static const ArBasicKind g_UInt16CT[] =
  935. {
  936. AR_BASIC_UINT16,
  937. AR_BASIC_LITERAL_INT,
  938. AR_BASIC_UNKNOWN
  939. };
  940. static const ArBasicKind g_Numeric16OnlyCT[] =
  941. {
  942. AR_BASIC_FLOAT16,
  943. AR_BASIC_INT16,
  944. AR_BASIC_UINT16,
  945. AR_BASIC_LITERAL_FLOAT,
  946. AR_BASIC_LITERAL_INT,
  947. AR_BASIC_NOCAST,
  948. AR_BASIC_UNKNOWN
  949. };
  950. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  951. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  952. {
  953. g_NullCT, // LICOMPTYPE_VOID
  954. g_BoolCT, // LICOMPTYPE_BOOL
  955. g_IntCT, // LICOMPTYPE_INT
  956. g_UIntCT, // LICOMPTYPE_UINT
  957. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  958. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  959. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  960. g_FloatCT, // LICOMPTYPE_FLOAT
  961. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  962. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  963. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  964. g_DoubleCT, // LICOMPTYPE_DOUBLE
  965. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  966. g_NumericCT, // LICOMPTYPE_NUMERIC
  967. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  968. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  969. g_AnyCT, // LICOMPTYPE_ANY
  970. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  971. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  972. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  973. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  974. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  975. g_SamplerCT, // LICOMPTYPE_SAMPLER
  976. g_StringCT, // LICOMPTYPE_STRING
  977. g_WaveCT, // LICOMPTYPE_WAVE
  978. g_UInt64CT, // LICOMPTYPE_UINT64
  979. g_Float16CT, // LICOMPTYPE_FLOAT16
  980. g_Int16CT, // LICOMPTYPE_INT16
  981. g_UInt16CT, // LICOMPTYPE_UINT16
  982. g_Numeric16OnlyCT // LICOMPTYPE_NUMERIC16_ONLY
  983. };
  984. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT);
  985. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  986. // Basic kind objects that are represented as HLSL structures or templates.
  987. static
  988. const ArBasicKind g_ArBasicKindsAsTypes[] =
  989. {
  990. AR_OBJECT_BUFFER, // Buffer
  991. // AR_OBJECT_TEXTURE,
  992. AR_OBJECT_TEXTURE1D, // Texture1D
  993. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  994. AR_OBJECT_TEXTURE2D, // Texture2D
  995. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  996. AR_OBJECT_TEXTURE3D, // Texture3D
  997. AR_OBJECT_TEXTURECUBE, // TextureCube
  998. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  999. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1000. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1001. AR_OBJECT_SAMPLER,
  1002. //AR_OBJECT_SAMPLER1D,
  1003. //AR_OBJECT_SAMPLER2D,
  1004. //AR_OBJECT_SAMPLER3D,
  1005. //AR_OBJECT_SAMPLERCUBE,
  1006. AR_OBJECT_SAMPLERCOMPARISON,
  1007. AR_OBJECT_POINTSTREAM,
  1008. AR_OBJECT_LINESTREAM,
  1009. AR_OBJECT_TRIANGLESTREAM,
  1010. AR_OBJECT_INPUTPATCH,
  1011. AR_OBJECT_OUTPUTPATCH,
  1012. AR_OBJECT_RWTEXTURE1D,
  1013. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1014. AR_OBJECT_RWTEXTURE2D,
  1015. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1016. AR_OBJECT_RWTEXTURE3D,
  1017. AR_OBJECT_RWBUFFER,
  1018. AR_OBJECT_BYTEADDRESS_BUFFER,
  1019. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1020. AR_OBJECT_STRUCTURED_BUFFER,
  1021. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1022. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1023. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1024. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1025. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1026. AR_OBJECT_ROVBUFFER,
  1027. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1028. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1029. AR_OBJECT_ROVTEXTURE1D,
  1030. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1031. AR_OBJECT_ROVTEXTURE2D,
  1032. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1033. AR_OBJECT_ROVTEXTURE3D,
  1034. // SPIRV change starts
  1035. #ifdef ENABLE_SPIRV_CODEGEN
  1036. AR_OBJECT_VK_SUBPASS_INPUT,
  1037. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1038. #endif // ENABLE_SPIRV_CODEGEN
  1039. // SPIRV change ends
  1040. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1041. AR_OBJECT_WAVE
  1042. };
  1043. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1044. static
  1045. const uint8_t g_ArBasicKindsTemplateCount[] =
  1046. {
  1047. 1, // AR_OBJECT_BUFFER
  1048. // AR_OBJECT_TEXTURE,
  1049. 1, // AR_OBJECT_TEXTURE1D
  1050. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1051. 1, // AR_OBJECT_TEXTURE2D
  1052. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1053. 1, // AR_OBJECT_TEXTURE3D
  1054. 1, // AR_OBJECT_TEXTURECUBE
  1055. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1056. 2, // AR_OBJECT_TEXTURE2DMS
  1057. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1058. 0, // AR_OBJECT_SAMPLER
  1059. //AR_OBJECT_SAMPLER1D,
  1060. //AR_OBJECT_SAMPLER2D,
  1061. //AR_OBJECT_SAMPLER3D,
  1062. //AR_OBJECT_SAMPLERCUBE,
  1063. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1064. 1, // AR_OBJECT_POINTSTREAM
  1065. 1, // AR_OBJECT_LINESTREAM
  1066. 1, // AR_OBJECT_TRIANGLESTREAM
  1067. 2, // AR_OBJECT_INPUTPATCH
  1068. 2, // AR_OBJECT_OUTPUTPATCH
  1069. 1, // AR_OBJECT_RWTEXTURE1D
  1070. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1071. 1, // AR_OBJECT_RWTEXTURE2D
  1072. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1073. 1, // AR_OBJECT_RWTEXTURE3D
  1074. 1, // AR_OBJECT_RWBUFFER
  1075. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1076. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1077. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1078. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1079. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1080. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1081. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1082. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1083. 1, // AR_OBJECT_ROVBUFFER
  1084. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1085. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1086. 1, // AR_OBJECT_ROVTEXTURE1D
  1087. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1088. 1, // AR_OBJECT_ROVTEXTURE2D
  1089. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1090. 1, // AR_OBJECT_ROVTEXTURE3D
  1091. // SPIRV change starts
  1092. #ifdef ENABLE_SPIRV_CODEGEN
  1093. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1094. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1095. #endif // ENABLE_SPIRV_CODEGEN
  1096. // SPIRV change ends
  1097. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1098. 0, // AR_OBJECT_WAVE
  1099. };
  1100. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1101. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1102. struct SubscriptOperatorRecord
  1103. {
  1104. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1105. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1106. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1107. };
  1108. // Subscript operators for objects that are represented as HLSL structures or templates.
  1109. static
  1110. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1111. {
  1112. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1113. // AR_OBJECT_TEXTURE,
  1114. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1115. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1116. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1117. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1118. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1119. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1120. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1121. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1122. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1123. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1124. //AR_OBJECT_SAMPLER1D,
  1125. //AR_OBJECT_SAMPLER2D,
  1126. //AR_OBJECT_SAMPLER3D,
  1127. //AR_OBJECT_SAMPLERCUBE,
  1128. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1129. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1130. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1131. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1132. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1133. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1134. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1135. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1136. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1137. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1138. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1139. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1140. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1141. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1142. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1143. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1144. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1145. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1146. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1147. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1148. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1149. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1150. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1151. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1152. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1153. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1154. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1155. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1156. // SPIRV change starts
  1157. #ifdef ENABLE_SPIRV_CODEGEN
  1158. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1159. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1160. #endif // ENABLE_SPIRV_CODEGEN
  1161. // SPIRV change ends
  1162. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1163. { 0, MipsFalse, SampleFalse } // AR_OBJECT_WAVE
  1164. };
  1165. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1166. // Type names for ArBasicKind values.
  1167. static
  1168. const char* g_ArBasicTypeNames[] =
  1169. {
  1170. "bool", "float", "half", "half", "float", "double",
  1171. "int", "sbyte", "byte", "short", "ushort",
  1172. "int", "uint", "long", "ulong",
  1173. "min10float", "min16float",
  1174. "min12int", "min16int", "min16uint",
  1175. "enum",
  1176. "<count>",
  1177. "<none>",
  1178. "<unknown>",
  1179. "<nocast>",
  1180. "<pointer>",
  1181. "enum class",
  1182. "null",
  1183. "string",
  1184. // "texture",
  1185. "Texture1D",
  1186. "Texture1DArray",
  1187. "Texture2D",
  1188. "Texture2DArray",
  1189. "Texture3D",
  1190. "TextureCube",
  1191. "TextureCubeArray",
  1192. "Texture2DMS",
  1193. "Texture2DMSArray",
  1194. "SamplerState",
  1195. "sampler1D",
  1196. "sampler2D",
  1197. "sampler3D",
  1198. "samplerCUBE",
  1199. "SamplerComparisonState",
  1200. "Buffer",
  1201. "RenderTargetView",
  1202. "DepthStencilView",
  1203. "ComputeShader",
  1204. "DomainShader",
  1205. "GeometryShader",
  1206. "HullShader",
  1207. "PixelShader",
  1208. "VertexShader",
  1209. "pixelfragment",
  1210. "vertexfragment",
  1211. "StateBlock",
  1212. "Rasterizer",
  1213. "DepthStencil",
  1214. "Blend",
  1215. "PointStream",
  1216. "LineStream",
  1217. "TriangleStream",
  1218. "InputPatch",
  1219. "OutputPatch",
  1220. "RWTexture1D",
  1221. "RWTexture1DArray",
  1222. "RWTexture2D",
  1223. "RWTexture2DArray",
  1224. "RWTexture3D",
  1225. "RWBuffer",
  1226. "ByteAddressBuffer",
  1227. "RWByteAddressBuffer",
  1228. "StructuredBuffer",
  1229. "RWStructuredBuffer",
  1230. "RWStructuredBuffer(Incrementable)",
  1231. "RWStructuredBuffer(Decrementable)",
  1232. "AppendStructuredBuffer",
  1233. "ConsumeStructuredBuffer",
  1234. "ConstantBuffer",
  1235. "TextureBuffer",
  1236. "RasterizerOrderedBuffer",
  1237. "RasterizerOrderedByteAddressBuffer",
  1238. "RasterizerOrderedStructuredBuffer",
  1239. "RasterizerOrderedTexture1D",
  1240. "RasterizerOrderedTexture1DArray",
  1241. "RasterizerOrderedTexture2D",
  1242. "RasterizerOrderedTexture2DArray",
  1243. "RasterizerOrderedTexture3D",
  1244. // SPIRV change starts
  1245. #ifdef ENABLE_SPIRV_CODEGEN
  1246. "SubpassInput",
  1247. "SubpassInputMS",
  1248. #endif // ENABLE_SPIRV_CODEGEN
  1249. // SPIRV change ends
  1250. "<internal inner type object>",
  1251. "deprecated effect object",
  1252. "wave_t"
  1253. };
  1254. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1255. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1256. #define DXASSERT_VALIDBASICKIND(kind) \
  1257. DXASSERT(\
  1258. kind != AR_BASIC_COUNT && \
  1259. kind != AR_BASIC_NONE && \
  1260. kind != AR_BASIC_UNKNOWN && \
  1261. kind != AR_BASIC_NOCAST && \
  1262. kind != AR_BASIC_POINTER && \
  1263. kind != AR_OBJECT_RENDERTARGETVIEW && \
  1264. kind != AR_OBJECT_DEPTHSTENCILVIEW && \
  1265. kind != AR_OBJECT_COMPUTESHADER && \
  1266. kind != AR_OBJECT_DOMAINSHADER && \
  1267. kind != AR_OBJECT_GEOMETRYSHADER && \
  1268. kind != AR_OBJECT_HULLSHADER && \
  1269. kind != AR_OBJECT_PIXELSHADER && \
  1270. kind != AR_OBJECT_VERTEXSHADER && \
  1271. kind != AR_OBJECT_PIXELFRAGMENT && \
  1272. kind != AR_OBJECT_VERTEXFRAGMENT, "otherwise caller is using a special flag or an unsupported kind value");
  1273. static
  1274. const char* g_DeprecatedEffectObjectNames[] =
  1275. {
  1276. // These are case insensitive in fxc, but we'll just create two case aliases
  1277. // to capture the majority of cases
  1278. "texture", "Texture",
  1279. "pixelshader", "PixelShader",
  1280. "vertexshader", "VertexShader",
  1281. // These are case sensitive in fxc
  1282. "pixelfragment", // 13
  1283. "vertexfragment", // 14
  1284. "ComputeShader", // 13
  1285. "DomainShader", // 12
  1286. "GeometryShader", // 14
  1287. "HullShader", // 10
  1288. "BlendState", // 10
  1289. "DepthStencilState",// 17
  1290. "DepthStencilView", // 16
  1291. "RasterizerState", // 15
  1292. "RenderTargetView", // 16
  1293. };
  1294. // The CompareStringsWithLen function lexicographically compares LHS and RHS and
  1295. // returns a value indicating the relationship between the strings - < 0 if LHS is
  1296. // less than RHS, 0 if they are equal, > 0 if LHS is greater than RHS.
  1297. static
  1298. int CompareStringsWithLen(
  1299. _In_count_(LHSlen) const char* LHS, size_t LHSlen,
  1300. _In_count_(RHSlen) const char* RHS, size_t RHSlen
  1301. )
  1302. {
  1303. // Check whether the name is greater or smaller (without walking past end).
  1304. size_t maxNameComparable = std::min(LHSlen, RHSlen);
  1305. int comparison = strncmp(LHS, RHS, maxNameComparable);
  1306. if (comparison != 0) return comparison;
  1307. // Check whether the name is greater or smaller based on extra characters.
  1308. return LHSlen - RHSlen;
  1309. }
  1310. static hlsl::ParameterModifier
  1311. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1312. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1313. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1314. }
  1315. if (pArg->qwUsage == AR_QUAL_OUT) {
  1316. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1317. }
  1318. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1319. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1320. }
  1321. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1322. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1323. // The first argument is the return value, which isn't included.
  1324. for (UINT i = 1; i < pIntrinsic->uNumArgs; ++i) {
  1325. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1326. }
  1327. }
  1328. static bool IsAtomicOperation(IntrinsicOp op) {
  1329. switch (op) {
  1330. case IntrinsicOp::IOP_InterlockedAdd:
  1331. case IntrinsicOp::IOP_InterlockedAnd:
  1332. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1333. case IntrinsicOp::IOP_InterlockedCompareStore:
  1334. case IntrinsicOp::IOP_InterlockedExchange:
  1335. case IntrinsicOp::IOP_InterlockedMax:
  1336. case IntrinsicOp::IOP_InterlockedMin:
  1337. case IntrinsicOp::IOP_InterlockedOr:
  1338. case IntrinsicOp::IOP_InterlockedXor:
  1339. case IntrinsicOp::MOP_InterlockedAdd:
  1340. case IntrinsicOp::MOP_InterlockedAnd:
  1341. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1342. case IntrinsicOp::MOP_InterlockedCompareStore:
  1343. case IntrinsicOp::MOP_InterlockedExchange:
  1344. case IntrinsicOp::MOP_InterlockedMax:
  1345. case IntrinsicOp::MOP_InterlockedMin:
  1346. case IntrinsicOp::MOP_InterlockedOr:
  1347. case IntrinsicOp::MOP_InterlockedXor:
  1348. return true;
  1349. default:
  1350. return false;
  1351. }
  1352. }
  1353. static bool IsBuiltinTable(LPCSTR tableName) {
  1354. return tableName == kBuiltinIntrinsicTableName;
  1355. }
  1356. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1357. LPCSTR tableName, LPCSTR lowering,
  1358. const HLSL_INTRINSIC *pIntrinsic) {
  1359. unsigned opcode = (unsigned)pIntrinsic->Op;
  1360. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1361. QualType Ty = FD->getReturnType();
  1362. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(pIntrinsic->Op);
  1363. if (pIntrinsic->iOverloadParamIndex != -1) {
  1364. const FunctionProtoType *FT =
  1365. FD->getFunctionType()->getAs<FunctionProtoType>();
  1366. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1367. }
  1368. // TODO: refine the code for getting element type
  1369. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1370. Ty = VecTy->getElementType();
  1371. }
  1372. if (Ty->isUnsignedIntegerType()) {
  1373. opcode = hlsl::GetUnsignedOpcode(opcode);
  1374. }
  1375. }
  1376. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1377. if (pIntrinsic->bReadNone)
  1378. FD->addAttr(ConstAttr::CreateImplicit(context));
  1379. if (pIntrinsic->bReadOnly)
  1380. FD->addAttr(PureAttr::CreateImplicit(context));
  1381. }
  1382. static
  1383. FunctionDecl *AddHLSLIntrinsicFunction(
  1384. ASTContext &context, _In_ NamespaceDecl *NS,
  1385. LPCSTR tableName, LPCSTR lowering,
  1386. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1387. _In_count_(functionArgTypeCount) QualType *functionArgQualTypes,
  1388. _In_range_(0, g_MaxIntrinsicParamCount - 1) size_t functionArgTypeCount) {
  1389. DXASSERT(functionArgTypeCount - 1 < g_MaxIntrinsicParamCount,
  1390. "otherwise g_MaxIntrinsicParamCount should be larger");
  1391. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1392. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1393. InitParamMods(pIntrinsic, paramMods);
  1394. // Change dest address into reference type for atomic.
  1395. if (IsBuiltinTable(tableName)) {
  1396. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1397. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1398. "else operation was misrecognized");
  1399. functionArgQualTypes[kAtomicDstOperandIdx] =
  1400. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1401. }
  1402. }
  1403. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1404. // Change out/inout param to reference type.
  1405. if (paramMods[i-1].isAnyOut()) {
  1406. functionArgQualTypes[i] = context.getLValueReferenceType(functionArgQualTypes[i]);
  1407. }
  1408. }
  1409. IdentifierInfo &functionId = context.Idents.get(
  1410. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1411. DeclarationName functionName(&functionId);
  1412. QualType returnQualType = functionArgQualTypes[0];
  1413. QualType functionType = context.getFunctionType(
  1414. functionArgQualTypes[0],
  1415. ArrayRef<QualType>(functionArgQualTypes + 1,
  1416. functionArgQualTypes + functionArgTypeCount),
  1417. clang::FunctionProtoType::ExtProtoInfo(), paramMods);
  1418. FunctionDecl *functionDecl = FunctionDecl::Create(
  1419. context, currentDeclContext, NoLoc,
  1420. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1421. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1422. currentDeclContext->addDecl(functionDecl);
  1423. functionDecl->setLexicalDeclContext(currentDeclContext);
  1424. // put under hlsl namespace
  1425. functionDecl->setDeclContext(NS);
  1426. // Add intrinsic attribute
  1427. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1428. ParmVarDecl *paramDecls[g_MaxIntrinsicParamCount];
  1429. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1430. IdentifierInfo &parameterId = context.Idents.get(
  1431. StringRef(pIntrinsic->pArgs[i].pName), tok::TokenKind::identifier);
  1432. ParmVarDecl *paramDecl =
  1433. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1434. functionArgQualTypes[i], nullptr,
  1435. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1436. functionDecl->addDecl(paramDecl);
  1437. paramDecls[i - 1] = paramDecl;
  1438. }
  1439. functionDecl->setParams(
  1440. ArrayRef<ParmVarDecl *>(paramDecls, functionArgTypeCount - 1));
  1441. functionDecl->setImplicit(true);
  1442. return functionDecl;
  1443. }
  1444. /// <summary>
  1445. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1446. /// </summary>
  1447. static
  1448. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1449. {
  1450. DXASSERT_NOMSG(expr != nullptr);
  1451. expr = expr->IgnoreParens();
  1452. return
  1453. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1454. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1455. }
  1456. /// <summary>
  1457. /// Silences diagnostics for the initialization sequence, typically because they have already
  1458. /// been emitted.
  1459. /// </summary>
  1460. static
  1461. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1462. {
  1463. DXASSERT_NOMSG(initSequence != nullptr);
  1464. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1465. }
  1466. class UsedIntrinsic
  1467. {
  1468. public:
  1469. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1470. {
  1471. // The canonical representations are unique'd in an ASTContext, and so these
  1472. // should be stable.
  1473. return RHS.getTypePtr() - LHS.getTypePtr();
  1474. }
  1475. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1476. {
  1477. // The intrinsics are defined in a single static table, and so should be stable.
  1478. return RHS - LHS;
  1479. }
  1480. int compare(const UsedIntrinsic& other) const
  1481. {
  1482. // Check whether it's the same instance.
  1483. if (this == &other) return 0;
  1484. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1485. if (result != 0) return result;
  1486. // At this point, it's the exact same intrinsic name.
  1487. // Compare the arguments for ordering then.
  1488. DXASSERT(m_argLength == other.m_argLength, "intrinsics aren't overloaded on argument count, so we should never create a key with different #s");
  1489. for (size_t i = 0; i < m_argLength; i++) {
  1490. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1491. if (argComparison != 0) return argComparison;
  1492. }
  1493. // Exactly the same.
  1494. return 0;
  1495. }
  1496. public:
  1497. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, _In_count_(argCount) QualType* args, size_t argCount)
  1498. : m_argLength(argCount), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1499. {
  1500. std::copy(args, args + argCount, m_args);
  1501. }
  1502. void setFunctionDecl(FunctionDecl* value) const
  1503. {
  1504. DXASSERT(value != nullptr, "no reason to clear this out");
  1505. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1506. m_functionDecl = value;
  1507. }
  1508. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1509. bool operator==(const UsedIntrinsic& other) const
  1510. {
  1511. return compare(other) == 0;
  1512. }
  1513. bool operator<(const UsedIntrinsic& other) const
  1514. {
  1515. return compare(other) < 0;
  1516. }
  1517. private:
  1518. QualType m_args[g_MaxIntrinsicParamCount];
  1519. size_t m_argLength;
  1520. const HLSL_INTRINSIC* m_intrinsicSource;
  1521. mutable FunctionDecl* m_functionDecl;
  1522. };
  1523. template <typename T>
  1524. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1525. {
  1526. if (ptr != nullptr)
  1527. {
  1528. *ptr = value;
  1529. }
  1530. }
  1531. static bool CombineBasicTypes(
  1532. ArBasicKind LeftKind,
  1533. ArBasicKind RightKind,
  1534. _Out_ ArBasicKind* pOutKind,
  1535. _Out_opt_ CastKind* leftCastKind = nullptr,
  1536. _Out_opt_ CastKind* rightCastKind = nullptr)
  1537. {
  1538. AssignOpt(CastKind::CK_NoOp, leftCastKind);
  1539. AssignOpt(CastKind::CK_NoOp, rightCastKind);
  1540. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1541. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1542. return false;
  1543. }
  1544. if (LeftKind == RightKind) {
  1545. *pOutKind = LeftKind;
  1546. return true;
  1547. }
  1548. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1549. UINT uRightProps = GetBasicKindProps(RightKind);
  1550. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1551. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1552. UINT uBothFlags = uLeftProps & uRightProps;
  1553. UINT uEitherFlags = uLeftProps | uRightProps;
  1554. if ((BPROP_BOOLEAN & uBothFlags) != 0)
  1555. {
  1556. *pOutKind = AR_BASIC_BOOL;
  1557. return true;
  1558. }
  1559. if ((BPROP_LITERAL & uBothFlags) != 0)
  1560. {
  1561. if ((BPROP_INTEGER & uBothFlags) != 0)
  1562. {
  1563. *pOutKind = AR_BASIC_LITERAL_INT;
  1564. }
  1565. else
  1566. {
  1567. *pOutKind = AR_BASIC_LITERAL_FLOAT;
  1568. }
  1569. return true;
  1570. }
  1571. if ((BPROP_UNSIGNED & uBothFlags) != 0)
  1572. {
  1573. switch (uBits)
  1574. {
  1575. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1576. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1577. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1578. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1579. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1580. default: DXASSERT_NOMSG(false); break;
  1581. }
  1582. AssignOpt(CK_IntegralCast, leftCastKind);
  1583. AssignOpt(CK_IntegralCast, rightCastKind);
  1584. return true;
  1585. }
  1586. if ((BPROP_INTEGER & uBothFlags) != 0)
  1587. {
  1588. if ((BPROP_UNSIGNED & uEitherFlags) != 0)
  1589. {
  1590. switch (uBits)
  1591. {
  1592. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1593. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1594. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1595. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1596. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1597. default: DXASSERT_NOMSG(false); break;
  1598. }
  1599. }
  1600. else
  1601. {
  1602. switch (uBits)
  1603. {
  1604. case BPROP_BITS0: *pOutKind = AR_BASIC_LITERAL_INT; break;
  1605. case BPROP_BITS8: *pOutKind = AR_BASIC_INT8; break;
  1606. case BPROP_BITS12: *pOutKind = AR_BASIC_MIN12INT; break;
  1607. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1608. *pOutKind = AR_BASIC_MIN16INT : *pOutKind = AR_BASIC_INT16; break;
  1609. case BPROP_BITS32: *pOutKind = AR_BASIC_INT32; break;
  1610. case BPROP_BITS64: *pOutKind = AR_BASIC_INT64; break;
  1611. default: DXASSERT_NOMSG(false); break;
  1612. }
  1613. }
  1614. AssignOpt(CK_IntegralCast, leftCastKind);
  1615. AssignOpt(CK_IntegralCast, rightCastKind);
  1616. return true;
  1617. }
  1618. // At least one side is floating-point. Assume both are and fix later
  1619. // in this function.
  1620. DXASSERT_NOMSG((BPROP_FLOATING & uEitherFlags) != 0);
  1621. AssignOpt(CK_FloatingCast, leftCastKind);
  1622. AssignOpt(CK_FloatingCast, rightCastKind);
  1623. if ((BPROP_FLOATING & uBothFlags) == 0)
  1624. {
  1625. // One side is floating-point and one isn't,
  1626. // convert to the floating-point type.
  1627. if ((BPROP_FLOATING & uLeftProps) != 0)
  1628. {
  1629. uBits = GET_BPROP_BITS(uLeftProps);
  1630. AssignOpt(CK_IntegralToFloating, rightCastKind);
  1631. }
  1632. else
  1633. {
  1634. DXASSERT_NOMSG((BPROP_FLOATING & uRightProps) != 0);
  1635. uBits = GET_BPROP_BITS(uRightProps);
  1636. AssignOpt(CK_IntegralToFloating, leftCastKind);
  1637. }
  1638. if (uBits == 0)
  1639. {
  1640. // We have a literal plus a non-literal so drop
  1641. // any literalness.
  1642. uBits = BPROP_BITS32;
  1643. }
  1644. }
  1645. switch (uBits)
  1646. {
  1647. case BPROP_BITS10:
  1648. *pOutKind = AR_BASIC_MIN10FLOAT;
  1649. break;
  1650. case BPROP_BITS16:
  1651. if ((uEitherFlags & BPROP_MIN_PRECISION) != 0)
  1652. {
  1653. *pOutKind = AR_BASIC_MIN16FLOAT;
  1654. }
  1655. else
  1656. {
  1657. *pOutKind = AR_BASIC_FLOAT16;
  1658. }
  1659. break;
  1660. case BPROP_BITS32:
  1661. if ((uEitherFlags & BPROP_LITERAL) != 0 &&
  1662. (uEitherFlags & BPROP_PARTIAL_PRECISION) != 0)
  1663. {
  1664. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1665. }
  1666. else if ((uBothFlags & BPROP_PARTIAL_PRECISION) != 0)
  1667. {
  1668. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1669. }
  1670. else
  1671. {
  1672. *pOutKind = AR_BASIC_FLOAT32;
  1673. }
  1674. break;
  1675. case BPROP_BITS64:
  1676. *pOutKind = AR_BASIC_FLOAT64;
  1677. break;
  1678. default:
  1679. DXASSERT(false, "unexpected bit count");
  1680. *pOutKind = AR_BASIC_FLOAT32;
  1681. break;
  1682. }
  1683. return true;
  1684. }
  1685. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1686. {
  1687. };
  1688. static
  1689. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1690. {
  1691. DXASSERT_NOMSG(intrinsics != nullptr);
  1692. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1693. switch (kind)
  1694. {
  1695. case AR_OBJECT_TRIANGLESTREAM:
  1696. case AR_OBJECT_POINTSTREAM:
  1697. case AR_OBJECT_LINESTREAM:
  1698. *intrinsics = g_StreamMethods;
  1699. *intrinsicCount = _countof(g_StreamMethods);
  1700. break;
  1701. case AR_OBJECT_TEXTURE1D:
  1702. *intrinsics = g_Texture1DMethods;
  1703. *intrinsicCount = _countof(g_Texture1DMethods);
  1704. break;
  1705. case AR_OBJECT_TEXTURE1D_ARRAY:
  1706. *intrinsics = g_Texture1DArrayMethods;
  1707. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1708. break;
  1709. case AR_OBJECT_TEXTURE2D:
  1710. *intrinsics = g_Texture2DMethods;
  1711. *intrinsicCount = _countof(g_Texture2DMethods);
  1712. break;
  1713. case AR_OBJECT_TEXTURE2DMS:
  1714. *intrinsics = g_Texture2DMSMethods;
  1715. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1716. break;
  1717. case AR_OBJECT_TEXTURE2D_ARRAY:
  1718. *intrinsics = g_Texture2DArrayMethods;
  1719. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1720. break;
  1721. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1722. *intrinsics = g_Texture2DArrayMSMethods;
  1723. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1724. break;
  1725. case AR_OBJECT_TEXTURE3D:
  1726. *intrinsics = g_Texture3DMethods;
  1727. *intrinsicCount = _countof(g_Texture3DMethods);
  1728. break;
  1729. case AR_OBJECT_TEXTURECUBE:
  1730. *intrinsics = g_TextureCUBEMethods;
  1731. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1732. break;
  1733. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1734. *intrinsics = g_TextureCUBEArrayMethods;
  1735. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1736. break;
  1737. case AR_OBJECT_BUFFER:
  1738. *intrinsics = g_BufferMethods;
  1739. *intrinsicCount = _countof(g_BufferMethods);
  1740. break;
  1741. case AR_OBJECT_RWTEXTURE1D:
  1742. case AR_OBJECT_ROVTEXTURE1D:
  1743. *intrinsics = g_RWTexture1DMethods;
  1744. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1745. break;
  1746. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1747. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1748. *intrinsics = g_RWTexture1DArrayMethods;
  1749. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1750. break;
  1751. case AR_OBJECT_RWTEXTURE2D:
  1752. case AR_OBJECT_ROVTEXTURE2D:
  1753. *intrinsics = g_RWTexture2DMethods;
  1754. *intrinsicCount = _countof(g_RWTexture2DMethods);
  1755. break;
  1756. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  1757. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  1758. *intrinsics = g_RWTexture2DArrayMethods;
  1759. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  1760. break;
  1761. case AR_OBJECT_RWTEXTURE3D:
  1762. case AR_OBJECT_ROVTEXTURE3D:
  1763. *intrinsics = g_RWTexture3DMethods;
  1764. *intrinsicCount = _countof(g_RWTexture3DMethods);
  1765. break;
  1766. case AR_OBJECT_RWBUFFER:
  1767. case AR_OBJECT_ROVBUFFER:
  1768. *intrinsics = g_RWBufferMethods;
  1769. *intrinsicCount = _countof(g_RWBufferMethods);
  1770. break;
  1771. case AR_OBJECT_BYTEADDRESS_BUFFER:
  1772. *intrinsics = g_ByteAddressBufferMethods;
  1773. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  1774. break;
  1775. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  1776. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  1777. *intrinsics = g_RWByteAddressBufferMethods;
  1778. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  1779. break;
  1780. case AR_OBJECT_STRUCTURED_BUFFER:
  1781. *intrinsics = g_StructuredBufferMethods;
  1782. *intrinsicCount = _countof(g_StructuredBufferMethods);
  1783. break;
  1784. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  1785. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  1786. *intrinsics = g_RWStructuredBufferMethods;
  1787. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  1788. break;
  1789. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  1790. *intrinsics = g_AppendStructuredBufferMethods;
  1791. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  1792. break;
  1793. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  1794. *intrinsics = g_ConsumeStructuredBufferMethods;
  1795. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  1796. break;
  1797. // SPIRV change starts
  1798. #ifdef ENABLE_SPIRV_CODEGEN
  1799. case AR_OBJECT_VK_SUBPASS_INPUT:
  1800. *intrinsics = g_VkSubpassInputMethods;
  1801. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  1802. break;
  1803. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1804. *intrinsics = g_VkSubpassInputMSMethods;
  1805. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  1806. break;
  1807. #endif // ENABLE_SPIRV_CODEGEN
  1808. // SPIRV change ends
  1809. default:
  1810. *intrinsics = nullptr;
  1811. *intrinsicCount = 0;
  1812. break;
  1813. }
  1814. }
  1815. static
  1816. bool IsRowOrColumnVariable(size_t value)
  1817. {
  1818. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  1819. }
  1820. static
  1821. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  1822. {
  1823. return
  1824. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  1825. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  1826. value == LICOMPTYPE_ANY_FLOAT || // float or double
  1827. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  1828. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  1829. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  1830. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  1831. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  1832. value == LICOMPTYPE_ANY; // any time
  1833. }
  1834. static
  1835. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  1836. {
  1837. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  1838. }
  1839. static
  1840. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  1841. {
  1842. // Note that LITEMPLATE_OBJECT can accept different types, but it
  1843. // specifies a single 'layout'. In practice, this information is used
  1844. // together with a component type that specifies a single object.
  1845. return value == LITEMPLATE_ANY; // Any layout
  1846. }
  1847. static
  1848. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  1849. {
  1850. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  1851. }
  1852. static
  1853. bool DoesIntrinsicRequireTemplate(const HLSL_INTRINSIC* intrinsic)
  1854. {
  1855. const HLSL_INTRINSIC_ARGUMENT* argument = intrinsic->pArgs;
  1856. for (size_t i = 0; i < intrinsic->uNumArgs; i++)
  1857. {
  1858. // The intrinsic will require a template for any of these reasons:
  1859. // - A type template (layout) or component needs to match something else.
  1860. // - A parameter can take multiple types.
  1861. // - Row or columns numbers may vary.
  1862. if (
  1863. argument->uTemplateId != i ||
  1864. DoesLegalTemplateAcceptMultipleTypes(argument->uLegalTemplates) ||
  1865. DoesComponentTypeAcceptMultipleTypes(argument->uLegalComponentTypes) ||
  1866. IsRowOrColumnVariable(argument->uCols) ||
  1867. IsRowOrColumnVariable(argument->uRows))
  1868. {
  1869. return true;
  1870. }
  1871. argument++;
  1872. }
  1873. return false;
  1874. }
  1875. static
  1876. bool TemplateHasDefaultType(ArBasicKind kind)
  1877. {
  1878. switch (kind) {
  1879. case AR_OBJECT_BUFFER:
  1880. case AR_OBJECT_TEXTURE1D:
  1881. case AR_OBJECT_TEXTURE2D:
  1882. case AR_OBJECT_TEXTURE3D:
  1883. case AR_OBJECT_TEXTURE1D_ARRAY:
  1884. case AR_OBJECT_TEXTURE2D_ARRAY:
  1885. case AR_OBJECT_TEXTURECUBE:
  1886. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1887. // SPIRV change starts
  1888. #ifdef ENABLE_SPIRV_CODEGEN
  1889. case AR_OBJECT_VK_SUBPASS_INPUT:
  1890. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1891. #endif // ENABLE_SPIRV_CODEGEN
  1892. // SPIRV change ends
  1893. return true;
  1894. }
  1895. return false;
  1896. }
  1897. /// <summary>
  1898. /// Use this class to iterate over intrinsic definitions that come from an external source.
  1899. /// </summary>
  1900. class IntrinsicTableDefIter
  1901. {
  1902. private:
  1903. StringRef _typeName;
  1904. StringRef _functionName;
  1905. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  1906. const HLSL_INTRINSIC* _tableIntrinsic;
  1907. UINT64 _tableLookupCookie;
  1908. unsigned _tableIndex;
  1909. unsigned _argCount;
  1910. bool _firstChecked;
  1911. IntrinsicTableDefIter(
  1912. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1913. StringRef typeName,
  1914. StringRef functionName,
  1915. unsigned argCount) :
  1916. _typeName(typeName), _functionName(functionName), _tables(tables),
  1917. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  1918. _argCount(argCount), _firstChecked(false)
  1919. {
  1920. }
  1921. void CheckForIntrinsic() {
  1922. if (_tableIndex >= _tables.size()) {
  1923. return;
  1924. }
  1925. _firstChecked = true;
  1926. // TODO: review this - this will allocate at least once per string
  1927. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  1928. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  1929. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  1930. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  1931. _tableLookupCookie = 0;
  1932. _tableIntrinsic = nullptr;
  1933. }
  1934. }
  1935. void MoveToNext() {
  1936. for (;;) {
  1937. // If we don't have an intrinsic, try the following table.
  1938. if (_firstChecked && _tableIntrinsic == nullptr) {
  1939. _tableIndex++;
  1940. }
  1941. CheckForIntrinsic();
  1942. if (_tableIndex == _tables.size() ||
  1943. (_tableIntrinsic != nullptr &&
  1944. _tableIntrinsic->uNumArgs ==
  1945. (_argCount + 1))) // uNumArgs includes return
  1946. break;
  1947. }
  1948. }
  1949. public:
  1950. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1951. StringRef typeName,
  1952. StringRef functionName,
  1953. unsigned argCount)
  1954. {
  1955. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  1956. return result;
  1957. }
  1958. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  1959. {
  1960. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  1961. result._tableIndex = tables.size();
  1962. return result;
  1963. }
  1964. bool operator!=(const IntrinsicTableDefIter& other)
  1965. {
  1966. if (!_firstChecked) {
  1967. MoveToNext();
  1968. }
  1969. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  1970. }
  1971. const HLSL_INTRINSIC* operator*()
  1972. {
  1973. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  1974. return _tableIntrinsic;
  1975. }
  1976. LPCSTR GetTableName()
  1977. {
  1978. LPCSTR tableName = nullptr;
  1979. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  1980. return nullptr;
  1981. }
  1982. return tableName;
  1983. }
  1984. LPCSTR GetLoweringStrategy()
  1985. {
  1986. LPCSTR lowering = nullptr;
  1987. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  1988. return nullptr;
  1989. }
  1990. return lowering;
  1991. }
  1992. IntrinsicTableDefIter& operator++()
  1993. {
  1994. MoveToNext();
  1995. return *this;
  1996. }
  1997. };
  1998. /// <summary>
  1999. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2000. /// </summary>
  2001. class IntrinsicDefIter
  2002. {
  2003. const HLSL_INTRINSIC* _current;
  2004. const HLSL_INTRINSIC* _end;
  2005. IntrinsicTableDefIter _tableIter;
  2006. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2007. _current(value), _end(end), _tableIter(tableIter)
  2008. { }
  2009. public:
  2010. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2011. {
  2012. return IntrinsicDefIter(start, table + count, tableIter);
  2013. }
  2014. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2015. {
  2016. return IntrinsicDefIter(table + count, table + count, tableIter);
  2017. }
  2018. bool operator!=(const IntrinsicDefIter& other)
  2019. {
  2020. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2021. }
  2022. const HLSL_INTRINSIC* operator*()
  2023. {
  2024. return (_current != _end) ? _current : *_tableIter;
  2025. }
  2026. LPCSTR GetTableName()
  2027. {
  2028. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2029. }
  2030. LPCSTR GetLoweringStrategy()
  2031. {
  2032. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2033. }
  2034. IntrinsicDefIter& operator++()
  2035. {
  2036. if (_current != _end) {
  2037. const HLSL_INTRINSIC* next = _current + 1;
  2038. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2039. _current = next;
  2040. }
  2041. else {
  2042. _current = _end;
  2043. }
  2044. } else {
  2045. ++_tableIter;
  2046. }
  2047. return *this;
  2048. }
  2049. };
  2050. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2051. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2052. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2053. }
  2054. //
  2055. // This is similar to clang/Analysis/CallGraph, but the following differences
  2056. // motivate this:
  2057. //
  2058. // - track traversed vs. observed nodes explicitly
  2059. // - fully visit all reachable functions
  2060. // - merge graph visiting with checking for recursion
  2061. // - track global variables and types used (NYI)
  2062. //
  2063. namespace hlsl {
  2064. struct CallNode {
  2065. FunctionDecl *CallerFn;
  2066. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2067. };
  2068. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2069. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2070. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2071. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2072. // Returns the definition of a function.
  2073. // This serves two purposes - ignore built-in functions, and pick
  2074. // a single Decl * to be used in maps and sets.
  2075. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2076. if (!F) return nullptr;
  2077. if (F->doesThisDeclarationHaveABody()) return F;
  2078. F = F->getFirstDecl();
  2079. for (auto &&Candidate : F->redecls()) {
  2080. if (Candidate->doesThisDeclarationHaveABody()) {
  2081. return Candidate;
  2082. }
  2083. }
  2084. return nullptr;
  2085. }
  2086. // AST visitor that maintains visited and pending collections, as well
  2087. // as recording nodes of caller/callees.
  2088. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2089. private:
  2090. CallNodes &m_callNodes;
  2091. FunctionSet &m_visitedFunctions;
  2092. PendingFunctions &m_pendingFunctions;
  2093. FunctionDecl *m_source;
  2094. CallNodes::iterator m_sourceIt;
  2095. public:
  2096. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2097. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2098. : m_callNodes(callNodes),
  2099. m_visitedFunctions(visitedFunctions),
  2100. m_pendingFunctions(pendingFunctions) {}
  2101. void setSourceFn(FunctionDecl *F) {
  2102. F = getFunctionWithBody(F);
  2103. m_source = F;
  2104. m_sourceIt = m_callNodes.find(F);
  2105. }
  2106. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2107. ValueDecl *valueDecl = ref->getDecl();
  2108. FunctionDecl *fnDecl = dyn_cast_or_null<FunctionDecl>(valueDecl);
  2109. fnDecl = getFunctionWithBody(fnDecl);
  2110. if (fnDecl) {
  2111. if (m_sourceIt == m_callNodes.end()) {
  2112. auto result = m_callNodes.insert(
  2113. std::pair<FunctionDecl *, CallNode>(m_source, CallNode{ m_source }));
  2114. DXASSERT(result.second == true,
  2115. "else setSourceFn didn't assign m_sourceIt");
  2116. m_sourceIt = result.first;
  2117. }
  2118. m_sourceIt->second.CalleeFns.insert(fnDecl);
  2119. if (!m_visitedFunctions.count(fnDecl)) {
  2120. m_pendingFunctions.push_back(fnDecl);
  2121. }
  2122. }
  2123. return true;
  2124. }
  2125. };
  2126. // A call graph that can check for reachability and recursion efficiently.
  2127. class CallGraphWithRecurseGuard {
  2128. private:
  2129. CallNodes m_callNodes;
  2130. FunctionSet m_visitedFunctions;
  2131. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2132. FunctionDecl *D) const {
  2133. if (CallStack.insert(D).second == false)
  2134. return D;
  2135. auto node = m_callNodes.find(D);
  2136. if (node != m_callNodes.end()) {
  2137. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2138. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2139. if (pResult)
  2140. return pResult;
  2141. }
  2142. }
  2143. CallStack.erase(D);
  2144. return nullptr;
  2145. }
  2146. public:
  2147. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2148. DXASSERT_NOMSG(EntryFnDecl);
  2149. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2150. PendingFunctions pendingFunctions;
  2151. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2152. pendingFunctions.push_back(EntryFnDecl);
  2153. while (!pendingFunctions.empty()) {
  2154. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2155. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2156. visitor.setSourceFn(pendingDecl);
  2157. visitor.TraverseDecl(pendingDecl);
  2158. }
  2159. }
  2160. }
  2161. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2162. FnCallStack CallStack;
  2163. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2164. return CheckRecursion(CallStack, EntryFnDecl);
  2165. }
  2166. void dump() const {
  2167. OutputDebugStringW(L"Call Nodes:\r\n");
  2168. for (auto &node : m_callNodes) {
  2169. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), node.first);
  2170. for (auto callee : node.second.CalleeFns) {
  2171. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), callee);
  2172. }
  2173. }
  2174. }
  2175. };
  2176. }
  2177. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2178. static
  2179. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2180. {
  2181. DXASSERT_NOMSG(context != nullptr);
  2182. DXASSERT_NOMSG(ident != nullptr);
  2183. DXASSERT_NOMSG(!baseType.isNull());
  2184. DeclContext* declContext = context->getTranslationUnitDecl();
  2185. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2186. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2187. declContext->addDecl(decl);
  2188. decl->setImplicit(true);
  2189. return decl;
  2190. }
  2191. class HLSLExternalSource : public ExternalSemaSource {
  2192. private:
  2193. // Inner types.
  2194. struct FindStructBasicTypeResult {
  2195. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2196. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2197. FindStructBasicTypeResult(ArBasicKind kind,
  2198. unsigned int basicKindAsTypeIndex)
  2199. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2200. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2201. };
  2202. // Declaration for matrix and vector templates.
  2203. ClassTemplateDecl* m_matrixTemplateDecl;
  2204. ClassTemplateDecl* m_vectorTemplateDecl;
  2205. // Namespace decl for hlsl intrin functions
  2206. NamespaceDecl* m_hlslNSDecl;
  2207. // Context being processed.
  2208. _Notnull_ ASTContext* m_context;
  2209. // Semantic analyzer being processed.
  2210. Sema* m_sema;
  2211. // Intrinsic tables available externally.
  2212. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2213. // Scalar types indexed by HLSLScalarType.
  2214. QualType m_scalarTypes[HLSLScalarTypeCount];
  2215. // Scalar types already built.
  2216. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2217. // 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.
  2218. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2219. // Matrix types already built, in shorthand form.
  2220. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2221. // Vector types already built.
  2222. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2223. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2224. // BuiltinType for each scalar type.
  2225. QualType m_baseTypes[HLSLScalarTypeCount];
  2226. // Built-in object types declarations, indexed by basic kind constant.
  2227. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2228. // Map from object decl to the object index.
  2229. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2230. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2231. // Mask for object which not has methods created.
  2232. uint64_t m_objectTypeLazyInitMask;
  2233. UsedIntrinsicStore m_usedIntrinsics;
  2234. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2235. void AddBaseTypes();
  2236. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2237. void AddHLSLScalarTypes();
  2238. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2239. {
  2240. DXASSERT_NOMSG(recordDecl != nullptr);
  2241. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2242. NamedDecl* parameterDecl = parameterList->getParam(0);
  2243. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2244. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2245. return QualType(parmDecl->getTypeForDecl(), 0);
  2246. }
  2247. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2248. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2249. {
  2250. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2251. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2252. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2253. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2254. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2255. if (
  2256. templateRef >= 0 &&
  2257. templateArg->uTemplateId == templateRef &&
  2258. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2259. componentRef >= 0 &&
  2260. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2261. componentArg->uComponentTypeId == 0 &&
  2262. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2263. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2264. !IsRowOrColumnVariable(matrixArg->uRows))
  2265. {
  2266. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2267. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2268. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2269. }
  2270. return QualType();
  2271. }
  2272. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2273. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2274. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2275. _Inout_ size_t* templateParamNamedDeclsCount)
  2276. {
  2277. DXASSERT_NOMSG(name != nullptr);
  2278. DXASSERT_NOMSG(recordDecl != nullptr);
  2279. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2280. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2281. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2282. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2283. // Create the declaration for the template parameter.
  2284. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2285. TemplateTypeParmDecl* templateTypeParmDecl =
  2286. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2287. id, TypenameTrue, ParameterPackFalse);
  2288. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2289. // Create the type that the parameter represents.
  2290. QualType result = m_context->getTemplateTypeParmType(
  2291. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2292. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2293. // it need not concern itself with maintaining this value.
  2294. (*templateParamNamedDeclsCount)++;
  2295. return result;
  2296. }
  2297. // Adds a function specified by the given intrinsic to a record declaration.
  2298. // The template depth will be zero for records that don't have a "template<>" line
  2299. // even if conceptual; or one if it does have one.
  2300. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2301. {
  2302. DXASSERT_NOMSG(recordDecl != nullptr);
  2303. DXASSERT_NOMSG(intrinsic != nullptr);
  2304. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2305. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2306. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2307. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2308. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2309. //
  2310. // Build template parameters, parameter types, and the return type.
  2311. // Parameter declarations are built after the function is created, to use it as their scope.
  2312. //
  2313. unsigned int numParams = intrinsic->uNumArgs - 1;
  2314. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2315. size_t templateParamNamedDeclsCount = 0;
  2316. QualType argsQTs[g_MaxIntrinsicParamCount];
  2317. StringRef argNames[g_MaxIntrinsicParamCount];
  2318. QualType functionResultQT;
  2319. DXASSERT(
  2320. _countof(templateParamNamedDecls) >= numParams + 1,
  2321. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2322. // Handle the return type.
  2323. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2324. // if (functionResultQT.isNull()) {
  2325. // Workaround for template parameter argument count mismatch.
  2326. // Create template parameter for return type always
  2327. // TODO: reenable the check and skip template argument.
  2328. functionResultQT = AddTemplateParamToArray(
  2329. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2330. &templateParamNamedDeclsCount);
  2331. // }
  2332. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2333. InitParamMods(intrinsic, paramMods);
  2334. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2335. // Handle parameters.
  2336. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2337. {
  2338. //
  2339. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2340. //
  2341. // However this may produce template instantiations with equivalent template arguments
  2342. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2343. // but the current intrinsic table has rules that are hard to process in their current form
  2344. // to find all cases.
  2345. //
  2346. char name[g_MaxIntrinsicParamName + 2];
  2347. name[0] = 'T';
  2348. name[1] = '\0';
  2349. strcat_s(name, intrinsic->pArgs[i].pName);
  2350. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2351. // Change out/inout param to reference type.
  2352. if (paramMods[i-1].isAnyOut())
  2353. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2354. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2355. }
  2356. // Create the declaration.
  2357. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2358. DeclarationName declarationName = DeclarationName(ii);
  2359. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2360. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2361. declarationName, true);
  2362. functionDecl->setImplicit(true);
  2363. // If the function is a template function, create the declaration and cross-reference.
  2364. if (templateParamNamedDeclsCount > 0)
  2365. {
  2366. hlsl::CreateFunctionTemplateDecl(
  2367. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2368. }
  2369. }
  2370. // Checks whether the two specified intrinsics generate equivalent templates.
  2371. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2372. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2373. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2374. {
  2375. if (left == right)
  2376. {
  2377. return true;
  2378. }
  2379. if (left == nullptr || right == nullptr)
  2380. {
  2381. return false;
  2382. }
  2383. return (left->uNumArgs == right->uNumArgs &&
  2384. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2385. }
  2386. // Adds all the intrinsic methods that correspond to the specified type.
  2387. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2388. {
  2389. DXASSERT_NOMSG(recordDecl != nullptr);
  2390. DXASSERT_NOMSG(templateDepth >= 0);
  2391. const HLSL_INTRINSIC* intrinsics;
  2392. const HLSL_INTRINSIC* prior = nullptr;
  2393. size_t intrinsicCount;
  2394. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2395. DXASSERT(
  2396. (intrinsics == nullptr) == (intrinsicCount == 0),
  2397. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2398. while (intrinsicCount--)
  2399. {
  2400. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2401. {
  2402. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2403. prior = intrinsics;
  2404. }
  2405. intrinsics++;
  2406. }
  2407. }
  2408. void AddDoubleSubscriptSupport(
  2409. _In_ ClassTemplateDecl* typeDecl,
  2410. _In_ CXXRecordDecl* recordDecl,
  2411. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2412. _In_z_ const char* type0Name,
  2413. _In_z_ const char* type1Name,
  2414. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2415. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2416. {
  2417. DXASSERT_NOMSG(typeDecl != nullptr);
  2418. DXASSERT_NOMSG(recordDecl != nullptr);
  2419. DXASSERT_NOMSG(memberName != nullptr);
  2420. DXASSERT_NOMSG(!elementType.isNull());
  2421. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2422. DXASSERT_NOMSG(type0Name != nullptr);
  2423. DXASSERT_NOMSG(type1Name != nullptr);
  2424. DXASSERT_NOMSG(indexer0Name != nullptr);
  2425. DXASSERT_NOMSG(!indexer0Type.isNull());
  2426. DXASSERT_NOMSG(indexer1Name != nullptr);
  2427. DXASSERT_NOMSG(!indexer1Type.isNull());
  2428. //
  2429. // Add inner types to the templates to represent the following C++ code inside the class.
  2430. // public:
  2431. // class sample_slice_type
  2432. // {
  2433. // public: TElement operator[](uint3 index);
  2434. // };
  2435. // class sample_type
  2436. // {
  2437. // public: sample_slice_type operator[](uint slice);
  2438. // };
  2439. // sample_type sample;
  2440. //
  2441. // Variable names reflect this structure, but this code will also produce the types
  2442. // for .mips access.
  2443. //
  2444. const bool MutableTrue = true;
  2445. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2446. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2447. &m_context->Idents.get(StringRef(type1Name)));
  2448. sampleSliceTypeDecl->setAccess(AS_public);
  2449. sampleSliceTypeDecl->setImplicit();
  2450. recordDecl->addDecl(sampleSliceTypeDecl);
  2451. sampleSliceTypeDecl->startDefinition();
  2452. const bool MutableFalse = false;
  2453. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2454. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2455. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2456. sliceHandleDecl->setAccess(AS_private);
  2457. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2458. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2459. sampleSliceTypeDecl, elementType,
  2460. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2461. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2462. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2463. sampleSliceTypeDecl->completeDefinition();
  2464. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2465. &m_context->Idents.get(StringRef(type0Name)));
  2466. sampleTypeDecl->setAccess(AS_public);
  2467. recordDecl->addDecl(sampleTypeDecl);
  2468. sampleTypeDecl->startDefinition();
  2469. sampleTypeDecl->setImplicit();
  2470. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2471. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2472. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2473. sampleHandleDecl->setAccess(AS_private);
  2474. sampleTypeDecl->addDecl(sampleHandleDecl);
  2475. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2476. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2477. sampleTypeDecl, m_context->getRValueReferenceType(sampleSliceType), // TODO: choose LValueRef if writable.
  2478. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2479. sampleTypeDecl->completeDefinition();
  2480. // Add subscript attribute
  2481. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2482. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2483. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2484. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2485. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2486. sampleFieldDecl->setAccess(AS_public);
  2487. recordDecl->addDecl(sampleFieldDecl);
  2488. }
  2489. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2490. _In_ CXXRecordDecl *recordDecl,
  2491. SubscriptOperatorRecord op) {
  2492. DXASSERT_NOMSG(typeDecl != nullptr);
  2493. DXASSERT_NOMSG(recordDecl != nullptr);
  2494. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2495. op.SubscriptCardinality <= 3);
  2496. DXASSERT(op.SubscriptCardinality > 0 ||
  2497. (op.HasMips == false && op.HasSample == false),
  2498. "objects that have .mips or .sample member also have a plain "
  2499. "subscript defined (otherwise static table is "
  2500. "likely incorrect, and this function won't know the cardinality "
  2501. "of the position parameter");
  2502. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2503. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2504. "read/write objects don't have .mips or .sample members");
  2505. // Return early if there is no work to be done.
  2506. if (op.SubscriptCardinality == 0) {
  2507. return;
  2508. }
  2509. const unsigned int templateDepth = 1;
  2510. // Add an operator[].
  2511. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2512. typeDecl->getTemplateParameters()->getParam(0));
  2513. QualType resultType = m_context->getTemplateTypeParmType(
  2514. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2515. if (isReadWrite)
  2516. resultType = m_context->getLValueReferenceType(resultType, false);
  2517. else
  2518. resultType = m_context->getRValueReferenceType(resultType);
  2519. QualType indexType =
  2520. op.SubscriptCardinality == 1
  2521. ? m_context->UnsignedIntTy
  2522. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2523. op.SubscriptCardinality);
  2524. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2525. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2526. ArrayRef<StringRef>(StringRef("index")),
  2527. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2528. hlsl::CreateFunctionTemplateDecl(
  2529. *m_context, recordDecl, functionDecl,
  2530. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2531. // Add a .mips member if necessary.
  2532. QualType uintType = m_context->UnsignedIntTy;
  2533. if (op.HasMips) {
  2534. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2535. templateTypeParmDecl, "mips_type",
  2536. "mips_slice_type", "mipSlice", uintType, "pos",
  2537. indexType);
  2538. }
  2539. // Add a .sample member if necessary.
  2540. if (op.HasSample) {
  2541. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2542. templateTypeParmDecl, "sample_type",
  2543. "sample_slice_type", "sampleSlice", uintType,
  2544. "pos", indexType);
  2545. // TODO: support operator[][](indexType, uint).
  2546. }
  2547. }
  2548. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2549. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2550. return a.first < b.first;
  2551. };
  2552. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2553. auto begin = m_objectTypeDeclsMap.begin();
  2554. auto end = m_objectTypeDeclsMap.end();
  2555. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2556. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2557. if (low == end)
  2558. return -1;
  2559. if (recordDecl == low->first)
  2560. return low->second;
  2561. else
  2562. return -1;
  2563. }
  2564. // Adds all built-in HLSL object types.
  2565. void AddObjectTypes()
  2566. {
  2567. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  2568. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  2569. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  2570. m_objectTypeLazyInitMask = 0;
  2571. unsigned effectKindIndex = 0;
  2572. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  2573. {
  2574. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2575. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  2576. continue;
  2577. }
  2578. if (kind == AR_OBJECT_LEGACY_EFFECT)
  2579. effectKindIndex = i;
  2580. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  2581. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  2582. const char* typeName = g_ArBasicTypeNames[kind];
  2583. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2584. CXXRecordDecl* recordDecl = nullptr;
  2585. if (templateArgCount == 0)
  2586. {
  2587. AddRecordTypeWithHandle(*m_context, &recordDecl, typeName);
  2588. DXASSERT(recordDecl != nullptr, "AddRecordTypeWithHandle failed to return the object declaration");
  2589. recordDecl->setImplicit(true);
  2590. }
  2591. else
  2592. {
  2593. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  2594. ClassTemplateDecl* typeDecl = nullptr;
  2595. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  2596. AddTemplateTypeWithHandle(*m_context, &typeDecl, &recordDecl, typeName, templateArgCount, typeDefault);
  2597. DXASSERT(typeDecl != nullptr, "AddTemplateTypeWithHandle failed to return the object declaration");
  2598. typeDecl->setImplicit(true);
  2599. recordDecl->setImplicit(true);
  2600. }
  2601. m_objectTypeDecls[i] = recordDecl;
  2602. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  2603. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  2604. }
  2605. // Create an alias for SamplerState. 'sampler' is very commonly used.
  2606. {
  2607. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  2608. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  2609. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  2610. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  2611. currentDeclContext->addDecl(samplerDecl);
  2612. samplerDecl->setImplicit(true);
  2613. // Create decls for each deprecated effect object type:
  2614. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  2615. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  2616. for (int i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  2617. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  2618. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  2619. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  2620. currentDeclContext->addDecl(effectObjDecl);
  2621. effectObjDecl->setImplicit(true);
  2622. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  2623. }
  2624. }
  2625. // Make sure it's in order.
  2626. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  2627. }
  2628. FunctionDecl* AddSubscriptSpecialization(
  2629. _In_ FunctionTemplateDecl* functionTemplate,
  2630. QualType objectElement,
  2631. const FindStructBasicTypeResult& findResult);
  2632. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  2633. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2634. }
  2635. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  2636. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2637. }
  2638. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType);
  2639. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  2640. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2641. rowCount >= 0 && rowCount <= 4 && colCount >= 0 &&
  2642. colCount <= 4);
  2643. TypedefDecl *qts =
  2644. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  2645. if (qts == nullptr) {
  2646. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  2647. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  2648. rowCount, colCount);
  2649. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  2650. }
  2651. return qts;
  2652. }
  2653. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  2654. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2655. colCount >= 0 && colCount <= 4);
  2656. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  2657. if (qts == nullptr) {
  2658. QualType type = LookupVectorType(scalarType, colCount);
  2659. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  2660. colCount);
  2661. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  2662. }
  2663. return qts;
  2664. }
  2665. public:
  2666. HLSLExternalSource() :
  2667. m_matrixTemplateDecl(nullptr),
  2668. m_vectorTemplateDecl(nullptr),
  2669. m_context(nullptr),
  2670. m_sema(nullptr)
  2671. {
  2672. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  2673. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  2674. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  2675. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  2676. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  2677. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  2678. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  2679. }
  2680. ~HLSLExternalSource() { }
  2681. static HLSLExternalSource* FromSema(_In_ Sema* self)
  2682. {
  2683. DXASSERT_NOMSG(self != nullptr);
  2684. ExternalSemaSource* externalSource = self->getExternalSource();
  2685. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  2686. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  2687. return hlsl;
  2688. }
  2689. void InitializeSema(Sema& S) override
  2690. {
  2691. m_sema = &S;
  2692. S.addExternalSource(this);
  2693. AddObjectTypes();
  2694. AddStdIsEqualImplementation(S.getASTContext(), S);
  2695. for (auto && intrinsic : m_intrinsicTables) {
  2696. AddIntrinsicTableMethods(intrinsic);
  2697. }
  2698. }
  2699. void ForgetSema() override
  2700. {
  2701. m_sema = nullptr;
  2702. }
  2703. Sema* getSema() {
  2704. return m_sema;
  2705. }
  2706. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  2707. // We shouldn't create Typedef for built in scalar types.
  2708. // For built in scalar types, this funciton may be called for
  2709. // TypoCorrection. In that case, we return a nullptr.
  2710. if (m_scalarTypes[scalarType].isNull()) {
  2711. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  2712. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  2713. }
  2714. return m_scalarTypeDefs[scalarType];
  2715. }
  2716. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  2717. {
  2718. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  2719. if (qt.isNull()) {
  2720. // lazy initialization of scalar types
  2721. if (m_scalarTypes[scalarType].isNull()) {
  2722. LookupScalarTypeDef(scalarType);
  2723. }
  2724. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  2725. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  2726. }
  2727. return qt;
  2728. }
  2729. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  2730. {
  2731. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  2732. if (qt.isNull()) {
  2733. if (m_scalarTypes[scalarType].isNull()) {
  2734. LookupScalarTypeDef(scalarType);
  2735. }
  2736. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  2737. m_vectorTypes[scalarType][colCount - 1] = qt;
  2738. }
  2739. return qt;
  2740. }
  2741. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  2742. // TODO: enalbe this once we introduce precise master option
  2743. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  2744. if (type == HLSLScalarType_int_min12) {
  2745. const char *PromotedType =
  2746. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  2747. : HLSLScalarTypeNames[HLSLScalarType_int16];
  2748. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2749. << HLSLScalarTypeNames[type] << PromotedType;
  2750. } else if (type == HLSLScalarType_float_min10) {
  2751. const char *PromotedType =
  2752. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  2753. : HLSLScalarTypeNames[HLSLScalarType_float16];
  2754. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2755. << HLSLScalarTypeNames[type] << PromotedType;
  2756. }
  2757. if (!UseMinPrecision) {
  2758. if (type == HLSLScalarType_float_min16) {
  2759. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2760. << HLSLScalarTypeNames[type]
  2761. << HLSLScalarTypeNames[HLSLScalarType_float16];
  2762. } else if (type == HLSLScalarType_int_min16) {
  2763. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2764. << HLSLScalarTypeNames[type]
  2765. << HLSLScalarTypeNames[HLSLScalarType_int16];
  2766. } else if (type == HLSLScalarType_uint_min16) {
  2767. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2768. << HLSLScalarTypeNames[type]
  2769. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  2770. }
  2771. }
  2772. }
  2773. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  2774. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  2775. switch (type) {
  2776. case HLSLScalarType_float16:
  2777. case HLSLScalarType_float32:
  2778. case HLSLScalarType_float64:
  2779. case HLSLScalarType_int16:
  2780. case HLSLScalarType_int32:
  2781. case HLSLScalarType_uint16:
  2782. case HLSLScalarType_uint32:
  2783. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  2784. << HLSLScalarTypeNames[type] << "2018";
  2785. return false;
  2786. default:
  2787. break;
  2788. }
  2789. }
  2790. if (getSema()->getLangOpts().UseMinPrecision) {
  2791. switch (type) {
  2792. case HLSLScalarType_float16:
  2793. case HLSLScalarType_int16:
  2794. case HLSLScalarType_uint16:
  2795. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  2796. << HLSLScalarTypeNames[type];
  2797. return false;
  2798. default:
  2799. break;
  2800. }
  2801. }
  2802. return true;
  2803. }
  2804. bool LookupUnqualified(LookupResult &R, Scope *S) override
  2805. {
  2806. const DeclarationNameInfo declName = R.getLookupNameInfo();
  2807. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  2808. if (idInfo == nullptr) {
  2809. return false;
  2810. }
  2811. // Currently template instantiation is blocked when a fatal error is
  2812. // detected. So no faulting-in types at this point, instead we simply
  2813. // back out.
  2814. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  2815. return false;
  2816. }
  2817. StringRef nameIdentifier = idInfo->getName();
  2818. HLSLScalarType parsedType;
  2819. int rowCount;
  2820. int colCount;
  2821. // Try parsing hlsl scalar types that is not initialized at AST time.
  2822. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  2823. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  2824. if (rowCount == 0 && colCount == 0) { // scalar
  2825. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  2826. if (!typeDecl) return false;
  2827. R.addDecl(typeDecl);
  2828. }
  2829. else if (rowCount == 0) { // vector
  2830. QualType qt = LookupVectorType(parsedType, colCount);
  2831. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  2832. R.addDecl(qts);
  2833. }
  2834. else { // matrix
  2835. QualType qt = LookupMatrixType(parsedType, rowCount, colCount);
  2836. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  2837. R.addDecl(qts);
  2838. }
  2839. return true;
  2840. }
  2841. return false;
  2842. }
  2843. /// <summary>
  2844. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  2845. /// </sumary>
  2846. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  2847. {
  2848. DXASSERT_NOMSG(type != nullptr);
  2849. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  2850. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2851. if (templateSpecializationDecl) {
  2852. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  2853. if (decl == m_matrixTemplateDecl)
  2854. return AR_TOBJ_MATRIX;
  2855. else if (decl == m_vectorTemplateDecl)
  2856. return AR_TOBJ_VECTOR;
  2857. DXASSERT(decl->isImplicit(), "otherwise object template decl is not set to implicit");
  2858. return AR_TOBJ_OBJECT;
  2859. }
  2860. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  2861. if (typeRecordDecl->getDeclContext()->isFileContext())
  2862. return AR_TOBJ_OBJECT;
  2863. else
  2864. return AR_TOBJ_INNER_OBJ;
  2865. }
  2866. return AR_TOBJ_COMPOUND;
  2867. }
  2868. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  2869. bool IsBuiltInObjectType(QualType type)
  2870. {
  2871. type = GetStructuralForm(type);
  2872. if (!type.isNull() && type->isStructureOrClassType()) {
  2873. const RecordType* recordType = type->getAs<RecordType>();
  2874. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  2875. }
  2876. return false;
  2877. }
  2878. /// <summary>
  2879. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  2880. /// possibly refering to original template record if it's a specialization; this makes the result
  2881. /// suitable for looking up in initialization tables.
  2882. /// </summary>
  2883. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  2884. {
  2885. const CXXRecordDecl* recordDecl;
  2886. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  2887. {
  2888. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  2889. }
  2890. else
  2891. {
  2892. recordDecl = dyn_cast<CXXRecordDecl>(context);
  2893. }
  2894. return recordDecl;
  2895. }
  2896. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  2897. ArTypeObjectKind GetTypeObjectKind(QualType type)
  2898. {
  2899. DXASSERT_NOMSG(!type.isNull());
  2900. type = GetStructuralForm(type);
  2901. if (type->isVoidType()) return AR_TOBJ_VOID;
  2902. if (type->isArrayType()) return AR_TOBJ_ARRAY;
  2903. if (type->isPointerType()) {
  2904. return AR_TOBJ_POINTER;
  2905. }
  2906. if (type->isStructureOrClassType()) {
  2907. const RecordType* recordType = type->getAs<RecordType>();
  2908. return ClassifyRecordType(recordType);
  2909. } else if (const InjectedClassNameType *ClassNameTy =
  2910. type->getAs<InjectedClassNameType>()) {
  2911. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  2912. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  2913. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2914. if (templateSpecializationDecl) {
  2915. ClassTemplateDecl *decl =
  2916. templateSpecializationDecl->getSpecializedTemplate();
  2917. if (decl == m_matrixTemplateDecl)
  2918. return AR_TOBJ_MATRIX;
  2919. else if (decl == m_vectorTemplateDecl)
  2920. return AR_TOBJ_VECTOR;
  2921. DXASSERT(decl->isImplicit(),
  2922. "otherwise object template decl is not set to implicit");
  2923. return AR_TOBJ_OBJECT;
  2924. }
  2925. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  2926. if (typeRecordDecl->getDeclContext()->isFileContext())
  2927. return AR_TOBJ_OBJECT;
  2928. else
  2929. return AR_TOBJ_INNER_OBJ;
  2930. }
  2931. return AR_TOBJ_COMPOUND;
  2932. }
  2933. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  2934. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  2935. return AR_TOBJ_INVALID;
  2936. }
  2937. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  2938. QualType GetMatrixOrVectorElementType(QualType type)
  2939. {
  2940. type = GetStructuralForm(type);
  2941. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  2942. DXASSERT_NOMSG(typeRecordDecl);
  2943. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2944. DXASSERT_NOMSG(templateSpecializationDecl);
  2945. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  2946. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  2947. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  2948. }
  2949. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  2950. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  2951. QualType GetStructuralForm(QualType type)
  2952. {
  2953. if (type.isNull()) {
  2954. return type;
  2955. }
  2956. const ReferenceType *RefType = nullptr;
  2957. const AttributedType *AttrType = nullptr;
  2958. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  2959. (AttrType = dyn_cast<AttributedType>(type)))
  2960. {
  2961. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  2962. }
  2963. return type->getCanonicalTypeUnqualified();
  2964. }
  2965. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  2966. ArBasicKind GetTypeElementKind(QualType type)
  2967. {
  2968. type = GetStructuralForm(type);
  2969. ArTypeObjectKind kind = GetTypeObjectKind(type);
  2970. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  2971. QualType elementType = GetMatrixOrVectorElementType(type);
  2972. return GetTypeElementKind(elementType);
  2973. }
  2974. if (type->isArrayType()) {
  2975. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  2976. return GetTypeElementKind(arrayType->getElementType());
  2977. }
  2978. if (kind == AR_TOBJ_INNER_OBJ) {
  2979. return AR_OBJECT_INNER;
  2980. } else if (kind == AR_TOBJ_OBJECT) {
  2981. // Classify the object as the element type.
  2982. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  2983. int index = FindObjectBasicKindIndex(typeRecordDecl);
  2984. // NOTE: this will likely need to be updated for specialized records
  2985. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  2986. return g_ArBasicKindsAsTypes[index];
  2987. }
  2988. CanQualType canType = type->getCanonicalTypeUnqualified();
  2989. return BasicTypeForScalarType(canType);
  2990. }
  2991. ArBasicKind BasicTypeForScalarType(CanQualType type)
  2992. {
  2993. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  2994. {
  2995. switch (BT->getKind())
  2996. {
  2997. case BuiltinType::Bool: return AR_BASIC_BOOL;
  2998. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  2999. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3000. case BuiltinType::Half: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  3001. case BuiltinType::Int: return AR_BASIC_INT32;
  3002. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3003. case BuiltinType::Short: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  3004. case BuiltinType::UShort: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  3005. case BuiltinType::Long: return AR_BASIC_INT32;
  3006. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3007. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3008. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3009. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3010. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3011. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3012. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3013. }
  3014. }
  3015. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3016. if (ET->getDecl()->isScopedUsingClassTag())
  3017. return AR_BASIC_ENUM_CLASS;
  3018. return AR_BASIC_ENUM;
  3019. }
  3020. return AR_BASIC_UNKNOWN;
  3021. }
  3022. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3023. DXASSERT_NOMSG(table != nullptr);
  3024. // Function intrinsics are added on-demand, objects get template methods.
  3025. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3026. // Grab information already processed by AddObjectTypes.
  3027. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3028. const char *typeName = g_ArBasicTypeNames[kind];
  3029. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3030. DXASSERT(0 <= templateArgCount && templateArgCount <= 2,
  3031. "otherwise a new case has been added");
  3032. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3033. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3034. if (recordDecl == nullptr) {
  3035. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3036. continue;
  3037. }
  3038. // This is a variation of AddObjectMethods using the new table.
  3039. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3040. const HLSL_INTRINSIC *pPrior = nullptr;
  3041. UINT64 lookupCookie = 0;
  3042. CA2W wideTypeName(typeName);
  3043. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3044. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3045. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3046. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3047. // NOTE: this only works with the current implementation because
  3048. // intrinsics are alive as long as the table is alive.
  3049. pPrior = pIntrinsic;
  3050. }
  3051. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3052. }
  3053. }
  3054. }
  3055. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3056. DXASSERT_NOMSG(table != nullptr);
  3057. m_intrinsicTables.push_back(table);
  3058. // If already initialized, add methods immediately.
  3059. if (m_sema != nullptr) {
  3060. AddIntrinsicTableMethods(table);
  3061. }
  3062. }
  3063. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3064. {
  3065. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3066. switch (kind) {
  3067. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3068. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3069. case AR_BASIC_FLOAT16: return HLSLScalarType_float_min16;
  3070. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3071. return HLSLScalarType_float;
  3072. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3073. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3074. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3075. case AR_BASIC_INT8: return HLSLScalarType_int;
  3076. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3077. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3078. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3079. case AR_BASIC_INT32: return HLSLScalarType_int;
  3080. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3081. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3082. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3083. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3084. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3085. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3086. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3087. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3088. default:
  3089. return HLSLScalarType_unknown;
  3090. }
  3091. }
  3092. QualType GetBasicKindType(ArBasicKind kind)
  3093. {
  3094. DXASSERT_VALIDBASICKIND(kind);
  3095. switch (kind) {
  3096. case AR_OBJECT_NULL: return m_context->VoidTy;
  3097. case AR_BASIC_BOOL: return m_context->BoolTy;
  3098. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3099. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3100. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->FloatTy;
  3101. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3102. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3103. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3104. case AR_BASIC_INT8: return m_context->IntTy;
  3105. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3106. case AR_BASIC_INT16: return m_context->ShortTy;
  3107. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3108. case AR_BASIC_INT32: return m_context->IntTy;
  3109. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3110. case AR_BASIC_INT64: return m_context->LongLongTy;
  3111. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3112. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3113. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3114. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3115. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3116. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3117. case AR_OBJECT_STRING: return QualType();
  3118. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3119. case AR_OBJECT_TEXTURE1D:
  3120. case AR_OBJECT_TEXTURE1D_ARRAY:
  3121. case AR_OBJECT_TEXTURE2D:
  3122. case AR_OBJECT_TEXTURE2D_ARRAY:
  3123. case AR_OBJECT_TEXTURE3D:
  3124. case AR_OBJECT_TEXTURECUBE:
  3125. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3126. case AR_OBJECT_TEXTURE2DMS:
  3127. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3128. case AR_OBJECT_SAMPLER:
  3129. case AR_OBJECT_SAMPLERCOMPARISON:
  3130. case AR_OBJECT_BUFFER:
  3131. case AR_OBJECT_POINTSTREAM:
  3132. case AR_OBJECT_LINESTREAM:
  3133. case AR_OBJECT_TRIANGLESTREAM:
  3134. case AR_OBJECT_INPUTPATCH:
  3135. case AR_OBJECT_OUTPUTPATCH:
  3136. case AR_OBJECT_RWTEXTURE1D:
  3137. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3138. case AR_OBJECT_RWTEXTURE2D:
  3139. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3140. case AR_OBJECT_RWTEXTURE3D:
  3141. case AR_OBJECT_RWBUFFER:
  3142. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3143. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3144. case AR_OBJECT_STRUCTURED_BUFFER:
  3145. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3146. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3147. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3148. case AR_OBJECT_WAVE:
  3149. {
  3150. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3151. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3152. size_t index = match - g_ArBasicKindsAsTypes;
  3153. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3154. }
  3155. case AR_OBJECT_SAMPLER1D:
  3156. case AR_OBJECT_SAMPLER2D:
  3157. case AR_OBJECT_SAMPLER3D:
  3158. case AR_OBJECT_SAMPLERCUBE:
  3159. // Turn dimension-typed samplers into sampler states.
  3160. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3161. case AR_OBJECT_STATEBLOCK:
  3162. case AR_OBJECT_RASTERIZER:
  3163. case AR_OBJECT_DEPTHSTENCIL:
  3164. case AR_OBJECT_BLEND:
  3165. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3166. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3167. default:
  3168. return QualType();
  3169. }
  3170. }
  3171. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3172. /// <param name="E">Expression to typecast.</param>
  3173. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3174. ExprResult PromoteToIntIfBool(ExprResult& E);
  3175. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3176. {
  3177. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3178. (qwUsages);
  3179. return type;
  3180. }
  3181. QualType NewSimpleAggregateType(
  3182. _In_ ArTypeObjectKind ExplicitKind,
  3183. _In_ ArBasicKind componentType,
  3184. _In_ UINT64 qwQual,
  3185. _In_ UINT uRows,
  3186. _In_ UINT uCols)
  3187. {
  3188. DXASSERT_VALIDBASICKIND(componentType);
  3189. QualType pType; // The type to return.
  3190. QualType pEltType = GetBasicKindType(componentType);
  3191. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3192. // TODO: handle adding qualifications like const
  3193. pType = NewQualifiedType(
  3194. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3195. pEltType);
  3196. if (uRows > 1 ||
  3197. uCols > 1 ||
  3198. ExplicitKind == AR_TOBJ_VECTOR ||
  3199. ExplicitKind == AR_TOBJ_MATRIX)
  3200. {
  3201. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3202. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3203. if ((uRows == 1 &&
  3204. ExplicitKind != AR_TOBJ_MATRIX) ||
  3205. ExplicitKind == AR_TOBJ_VECTOR)
  3206. {
  3207. pType = LookupVectorType(scalarType, uCols);
  3208. }
  3209. else
  3210. {
  3211. pType = LookupMatrixType(scalarType, uRows, uCols);
  3212. }
  3213. // TODO: handle colmajor/rowmajor
  3214. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3215. //{
  3216. // VN(pType = NewQualifiedType(pSrcLoc,
  3217. // qwQual & (AR_QUAL_COLMAJOR |
  3218. // AR_QUAL_ROWMAJOR),
  3219. // pMatrix));
  3220. //}
  3221. //else
  3222. //{
  3223. // pType = pMatrix;
  3224. //}
  3225. }
  3226. return pType;
  3227. }
  3228. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3229. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3230. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3231. /// <param name="Args">Invocation arguments to match.</param>
  3232. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3233. /// <param name="argCount">After execution, number of arguments in argTypes.</param>
  3234. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3235. bool MatchArguments(
  3236. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3237. _In_ QualType objectElement,
  3238. _In_ ArrayRef<Expr *> Args,
  3239. _Out_writes_(g_MaxIntrinsicParamCount + 1) QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  3240. _Out_range_(0, g_MaxIntrinsicParamCount + 1) size_t* argCount);
  3241. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3242. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3243. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3244. bool IsValidateObjectElement(
  3245. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3246. _In_ QualType objectElement);
  3247. // Returns the iterator with the first entry that matches the requirement
  3248. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3249. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3250. size_t tableSize,
  3251. StringRef typeName,
  3252. StringRef nameIdentifier,
  3253. size_t argumentCount)
  3254. {
  3255. // This is implemented by a linear scan for now.
  3256. // We tested binary search on tables, and there was no performance gain on
  3257. // samples probably for the following reasons.
  3258. // 1. The tables are not big enough to make noticable difference
  3259. // 2. The user of this function assumes that it returns the first entry in
  3260. // the table that matches name and argument count. So even in the binary
  3261. // search, we have to scan backwards until the entry does not match the name
  3262. // or arg count. For linear search this is not a problem
  3263. for (unsigned int i = 0; i < tableSize; i++) {
  3264. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3265. // Do some quick checks to verify size and name.
  3266. if (pIntrinsic->uNumArgs != 1 + argumentCount) {
  3267. continue;
  3268. }
  3269. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3270. continue;
  3271. }
  3272. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3273. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3274. }
  3275. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3276. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3277. }
  3278. bool AddOverloadedCallCandidates(
  3279. UnresolvedLookupExpr *ULE,
  3280. ArrayRef<Expr *> Args,
  3281. OverloadCandidateSet &CandidateSet,
  3282. bool PartialOverloading) override
  3283. {
  3284. DXASSERT_NOMSG(ULE != nullptr);
  3285. const DeclarationNameInfo declName = ULE->getNameInfo();
  3286. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3287. if (idInfo == nullptr)
  3288. {
  3289. return false;
  3290. }
  3291. StringRef nameIdentifier = idInfo->getName();
  3292. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3293. g_Intrinsics, _countof(g_Intrinsics), StringRef(), nameIdentifier, Args.size());
  3294. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3295. g_Intrinsics, _countof(g_Intrinsics), IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3296. while (cursor != end)
  3297. {
  3298. // If this is the intrinsic we're interested in, build up a representation
  3299. // of the types we need.
  3300. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3301. LPCSTR tableName = cursor.GetTableName();
  3302. LPCSTR lowering = cursor.GetLoweringStrategy();
  3303. DXASSERT(
  3304. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3305. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3306. QualType functionArgTypes[g_MaxIntrinsicParamCount + 1];
  3307. size_t functionArgTypeCount = 0;
  3308. if (!MatchArguments(pIntrinsic, QualType(), Args, functionArgTypes, &functionArgTypeCount))
  3309. {
  3310. ++cursor;
  3311. continue;
  3312. }
  3313. // Get or create the overload we're interested in.
  3314. FunctionDecl* intrinsicFuncDecl = nullptr;
  3315. std::pair<UsedIntrinsicStore::iterator, bool> insertResult = m_usedIntrinsics.insert(UsedIntrinsic(
  3316. pIntrinsic, functionArgTypes, functionArgTypeCount));
  3317. bool insertedNewValue = insertResult.second;
  3318. if (insertedNewValue)
  3319. {
  3320. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3321. intrinsicFuncDecl = AddHLSLIntrinsicFunction(*m_context, m_hlslNSDecl, tableName, lowering, pIntrinsic, functionArgTypes, functionArgTypeCount);
  3322. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3323. }
  3324. else
  3325. {
  3326. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3327. }
  3328. OverloadCandidate& candidate = CandidateSet.addCandidate();
  3329. candidate.Function = intrinsicFuncDecl;
  3330. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3331. candidate.Viable = true;
  3332. return true;
  3333. }
  3334. return false;
  3335. }
  3336. bool Initialize(ASTContext& context)
  3337. {
  3338. m_context = &context;
  3339. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3340. /*Inline*/ false, SourceLocation(),
  3341. SourceLocation(), &context.Idents.get("hlsl"),
  3342. /*PrevDecl*/ nullptr);
  3343. m_hlslNSDecl->setImplicit();
  3344. AddBaseTypes();
  3345. AddHLSLScalarTypes();
  3346. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  3347. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  3348. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  3349. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  3350. return true;
  3351. }
  3352. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  3353. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  3354. /// <summary>Checks whether the specified type is a scalar type.</summary>
  3355. bool IsScalarType(const QualType& type) {
  3356. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  3357. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  3358. }
  3359. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  3360. bool IsValidVectorSize(size_t length) {
  3361. return 1 <= length && length <= 4;
  3362. }
  3363. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  3364. bool IsValidMatrixColOrRowSize(size_t length) {
  3365. return 1 <= length && length <= 4;
  3366. }
  3367. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  3368. if (type.isNull()) {
  3369. return false;
  3370. }
  3371. if (type.hasQualifiers()) {
  3372. return false;
  3373. }
  3374. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  3375. if (type->getTypeClass() == Type::TemplateTypeParm)
  3376. return true;
  3377. QualType qt = GetStructuralForm(type);
  3378. if (requireScalar) {
  3379. if (!IsScalarType(qt)) {
  3380. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  3381. return false;
  3382. }
  3383. return true;
  3384. }
  3385. else {
  3386. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  3387. if (qt->isArrayType()) {
  3388. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  3389. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  3390. }
  3391. else if (objectKind == AR_TOBJ_VECTOR) {
  3392. bool valid = true;
  3393. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  3394. valid = false;
  3395. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  3396. }
  3397. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3398. valid = false;
  3399. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3400. }
  3401. return valid;
  3402. }
  3403. else if (objectKind == AR_TOBJ_MATRIX) {
  3404. bool valid = true;
  3405. UINT rowCount, colCount;
  3406. GetRowsAndCols(type, rowCount, colCount);
  3407. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  3408. valid = false;
  3409. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  3410. }
  3411. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3412. valid = false;
  3413. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3414. }
  3415. return valid;
  3416. }
  3417. else if (qt->isStructureType()) {
  3418. const RecordType* recordType = qt->getAsStructureType();
  3419. objectKind = ClassifyRecordType(recordType);
  3420. switch (objectKind)
  3421. {
  3422. case AR_TOBJ_OBJECT:
  3423. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  3424. return false;
  3425. case AR_TOBJ_COMPOUND:
  3426. {
  3427. const RecordDecl* recordDecl = recordType->getDecl();
  3428. RecordDecl::field_iterator begin = recordDecl->field_begin();
  3429. RecordDecl::field_iterator end = recordDecl->field_end();
  3430. bool result = true;
  3431. while (begin != end) {
  3432. const FieldDecl* fieldDecl = *begin;
  3433. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  3434. m_sema->Diag(argLoc, diag::note_field_type_usage)
  3435. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  3436. result = false;
  3437. }
  3438. begin++;
  3439. }
  3440. return result;
  3441. }
  3442. default:
  3443. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3444. return false;
  3445. }
  3446. }
  3447. else if(IsScalarType(qt)) {
  3448. return true;
  3449. }
  3450. else {
  3451. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3452. return false;
  3453. }
  3454. }
  3455. }
  3456. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  3457. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  3458. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  3459. _Inout_opt_ StandardConversionSequence* sequence);
  3460. /// <summary>Produces an expression that turns the given expression into the specified numeric type.</summary>
  3461. Expr* CastExprToTypeNumeric(Expr* expr, QualType targetType);
  3462. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  3463. void GetConversionForm(
  3464. QualType type,
  3465. bool explicitConversion,
  3466. ArTypeInfo* pTypeInfo);
  3467. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  3468. bool suppressWarnings, bool suppressErrors,
  3469. _Inout_opt_ StandardConversionSequence* sequence);
  3470. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  3471. bool ValidateTypeRequirements(
  3472. SourceLocation loc,
  3473. ArBasicKind elementKind,
  3474. ArTypeObjectKind objectKind,
  3475. bool requiresIntegrals,
  3476. bool requiresNumerics);
  3477. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  3478. /// <param name="OpLoc">Source location for operator.</param>
  3479. /// <param name="Opc">Kind of binary operator.</param>
  3480. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  3481. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  3482. /// <param name="ResultTy">Result type for operator expression.</param>
  3483. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  3484. /// <param name="CompResultTy">Type of computation result.</param>
  3485. void CheckBinOpForHLSL(
  3486. SourceLocation OpLoc,
  3487. BinaryOperatorKind Opc,
  3488. ExprResult& LHS,
  3489. ExprResult& RHS,
  3490. QualType& ResultTy,
  3491. QualType& CompLHSTy,
  3492. QualType& CompResultTy);
  3493. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  3494. /// <param name="OpLoc">Source location for operator.</param>
  3495. /// <param name="Opc">Kind of operator.</param>
  3496. /// <param name="InputExpr">Input expression to the operator.</param>
  3497. /// <param name="VK">Value kind for resulting expression.</param>
  3498. /// <param name="OK">Object kind for resulting expression.</param>
  3499. /// <returns>The result type for the expression.</returns>
  3500. QualType CheckUnaryOpForHLSL(
  3501. SourceLocation OpLoc,
  3502. UnaryOperatorKind Opc,
  3503. ExprResult& InputExpr,
  3504. ExprValueKind& VK,
  3505. ExprObjectKind& OK);
  3506. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  3507. /// <param name="Cond">Vector condition expression.</param>
  3508. /// <param name="LHS">Left hand side.</param>
  3509. /// <param name="RHS">Right hand side.</param>
  3510. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  3511. /// <returns>Result type of vector conditional expression.</returns>
  3512. clang::QualType HLSLExternalSource::CheckVectorConditional(
  3513. _In_ ExprResult &Cond,
  3514. _In_ ExprResult &LHS,
  3515. _In_ ExprResult &RHS,
  3516. _In_ SourceLocation QuestionLoc);
  3517. clang::QualType ApplyTypeSpecSignToParsedType(
  3518. _In_ clang::QualType &type,
  3519. _In_ TypeSpecifierSign TSS,
  3520. _In_ SourceLocation Loc
  3521. );
  3522. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  3523. {
  3524. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  3525. {
  3526. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  3527. return true;
  3528. }
  3529. return false;
  3530. }
  3531. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  3532. bool
  3533. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  3534. SourceLocation /* TemplateLoc */,
  3535. TemplateArgumentListInfo &TemplateArgList) {
  3536. DXASSERT_NOMSG(Template != nullptr);
  3537. // Determine which object type the template refers to.
  3538. StringRef templateName = Template->getName();
  3539. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  3540. if (templateName.equals(StringRef("is_same"))) {
  3541. return false;
  3542. }
  3543. bool isMatrix = Template->getCanonicalDecl() ==
  3544. m_matrixTemplateDecl->getCanonicalDecl();
  3545. bool isVector = Template->getCanonicalDecl() ==
  3546. m_vectorTemplateDecl->getCanonicalDecl();
  3547. bool requireScalar = isMatrix || isVector;
  3548. // Check constraints on the type. Right now we only check that template
  3549. // types are primitive types.
  3550. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  3551. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  3552. SourceLocation argSrcLoc = argLoc.getLocation();
  3553. const TemplateArgument &arg = argLoc.getArgument();
  3554. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  3555. QualType argType = arg.getAsType();
  3556. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  3557. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  3558. return true;
  3559. }
  3560. }
  3561. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  3562. if (isMatrix || isVector) {
  3563. Expr *expr = arg.getAsExpr();
  3564. llvm::APSInt constantResult;
  3565. if (expr != nullptr &&
  3566. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  3567. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  3568. return true;
  3569. }
  3570. }
  3571. }
  3572. }
  3573. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  3574. if (isMatrix || isVector) {
  3575. llvm::APSInt Val = arg.getAsIntegral();
  3576. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  3577. return true;
  3578. }
  3579. }
  3580. }
  3581. }
  3582. return false;
  3583. }
  3584. /// <summary>Diagnoses an assignment operation.</summary>
  3585. /// <param name="ConvTy">Type of conversion assignment.</param>
  3586. /// <param name="Loc">Location for operation.</param>
  3587. /// <param name="DstType">Destination type.</param>
  3588. /// <param name="SrcType">Source type.</param>
  3589. /// <param name="SrcExpr">Source expression.</param>
  3590. /// <param name="Action">Action that triggers the assignment (assignment, passing, return, etc).</param>
  3591. /// <param name="Complained">Whether a diagnostic was emitted.</param>
  3592. void DiagnoseAssignmentResultForHLSL(
  3593. Sema::AssignConvertType ConvTy,
  3594. SourceLocation Loc,
  3595. QualType DstType, QualType SrcType,
  3596. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  3597. _Out_opt_ bool *Complained);
  3598. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  3599. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  3600. /// <param name="functionDeclContext">Declaration context of function.</param>
  3601. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  3602. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  3603. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  3604. void FindIntrinsicTable(
  3605. _In_ DeclContext* functionDeclContext,
  3606. _Outptr_result_z_ const char** name,
  3607. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  3608. _Out_ size_t* intrinsicCount);
  3609. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  3610. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  3611. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  3612. /// <param name="Args">Array of expressions being used as arguments.</param>
  3613. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  3614. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  3615. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  3616. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  3617. FunctionTemplateDecl *FunctionTemplate,
  3618. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  3619. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  3620. clang::OverloadingResult GetBestViableFunction(
  3621. clang::SourceLocation Loc,
  3622. clang::OverloadCandidateSet& set,
  3623. clang::OverloadCandidateSet::iterator& Best);
  3624. /// <summary>
  3625. /// Initializes the specified <paramref name="initSequence" /> describing how
  3626. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  3627. /// </summary>
  3628. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  3629. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  3630. /// <param name="Args">Arguments to the initialization.</param>
  3631. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  3632. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  3633. void InitializeInitSequenceForHLSL(
  3634. const InitializedEntity& Entity,
  3635. const InitializationKind& Kind,
  3636. MultiExprArg Args,
  3637. bool TopLevelOfInitList,
  3638. _Inout_ InitializationSequence* initSequence);
  3639. /// <summary>
  3640. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3641. /// </summary>
  3642. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3643. bool IsConversionToLessOrEqualElements(
  3644. const ExprResult& sourceExpr,
  3645. const QualType& targetType,
  3646. bool explicitConversion);
  3647. /// <summary>
  3648. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3649. /// </summary>
  3650. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3651. bool IsConversionToLessOrEqualElements(
  3652. const QualType& sourceType,
  3653. const QualType& targetType,
  3654. bool explicitConversion);
  3655. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  3656. /// <param name="BaseExpr">Base expression for member access.</param>
  3657. /// <param name="MemberName">Name of member to look up.</param>
  3658. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3659. /// <param name="OpLoc">Location of access operand.</param>
  3660. /// <param name="MemberLoc">Location of member.</param>
  3661. /// <param name="result">Result of lookup operation.</param>
  3662. /// <returns>true if the base type is a matrix and the lookup has been handled.</returns>
  3663. bool LookupMatrixMemberExprForHLSL(
  3664. Expr& BaseExpr,
  3665. DeclarationName MemberName,
  3666. bool IsArrow,
  3667. SourceLocation OpLoc,
  3668. SourceLocation MemberLoc,
  3669. ExprResult* result);
  3670. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  3671. /// <param name="BaseExpr">Base expression for member access.</param>
  3672. /// <param name="MemberName">Name of member to look up.</param>
  3673. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3674. /// <param name="OpLoc">Location of access operand.</param>
  3675. /// <param name="MemberLoc">Location of member.</param>
  3676. /// <param name="result">Result of lookup operation.</param>
  3677. /// <returns>true if the base type is a vector and the lookup has been handled.</returns>
  3678. bool LookupVectorMemberExprForHLSL(
  3679. Expr& BaseExpr,
  3680. DeclarationName MemberName,
  3681. bool IsArrow,
  3682. SourceLocation OpLoc,
  3683. SourceLocation MemberLoc,
  3684. ExprResult* result);
  3685. /// <summary>If E is a scalar, converts it to a 1-element vector.</summary>
  3686. /// <param name="E">Expression to convert.</param>
  3687. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  3688. ExprResult MaybeConvertScalarToVector(_In_ clang::Expr* E);
  3689. clang::Expr *HLSLImpCastToScalar(
  3690. _In_ clang::Sema* self,
  3691. _In_ clang::Expr* From,
  3692. ArTypeObjectKind FromShape,
  3693. ArBasicKind EltKind);
  3694. clang::ExprResult PerformHLSLConversion(
  3695. _In_ clang::Expr* From,
  3696. _In_ clang::QualType targetType,
  3697. _In_ const clang::StandardConversionSequence &SCS,
  3698. _In_ clang::Sema::CheckedConversionKind CCK);
  3699. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  3700. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  3701. /// <summary>
  3702. /// Checks if a static cast can be performed, and performs it if possible.
  3703. /// </summary>
  3704. /// <param name="SrcExpr">Expression to cast.</param>
  3705. /// <param name="DestType">Type to cast SrcExpr to.</param>
  3706. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  3707. /// <param name="OpRange">Source range for the cast operation.</param>
  3708. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  3709. /// <param name="Kind">The kind of operation required for a conversion.</param>
  3710. /// <param name="BasePath">A simple array of base specifiers.</param>
  3711. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  3712. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  3713. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  3714. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  3715. QualType DestType,
  3716. Sema::CheckedConversionKind CCK,
  3717. const SourceRange &OpRange, unsigned &msg,
  3718. CastKind &Kind, CXXCastPath &BasePath,
  3719. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  3720. _Inout_opt_ StandardConversionSequence* standard);
  3721. /// <summary>
  3722. /// Checks if a subscript index argument can be initialized from the given expression.
  3723. /// </summary>
  3724. /// <param name="SrcExpr">Source expression used as argument.</param>
  3725. /// <param name="DestType">Parameter type to initialize.</param>
  3726. /// <remarks>
  3727. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  3728. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  3729. /// </remarks>
  3730. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  3731. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  3732. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  3733. // Everything is ready.
  3734. if (m_objectTypeLazyInitMask == 0)
  3735. return;
  3736. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  3737. int idx = FindObjectBasicKindIndex(recordDecl);
  3738. // Not object type.
  3739. if (idx == -1)
  3740. return;
  3741. uint64_t bit = ((uint64_t)1)<<idx;
  3742. // Already created.
  3743. if ((m_objectTypeLazyInitMask & bit) == 0)
  3744. return;
  3745. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  3746. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  3747. int startDepth = 0;
  3748. if (templateArgCount > 0) {
  3749. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  3750. "otherwise a new case has been added");
  3751. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  3752. AddObjectSubscripts(kind, typeDecl, recordDecl,
  3753. g_ArBasicKindsSubscripts[idx]);
  3754. startDepth = 1;
  3755. }
  3756. AddObjectMethods(kind, recordDecl, startDepth);
  3757. // Clear the object.
  3758. m_objectTypeLazyInitMask &= ~bit;
  3759. }
  3760. FunctionDecl* AddHLSLIntrinsicMethod(
  3761. LPCSTR tableName,
  3762. LPCSTR lowering,
  3763. _In_ const HLSL_INTRINSIC* intrinsic,
  3764. _In_ FunctionTemplateDecl *FunctionTemplate,
  3765. ArrayRef<Expr *> Args,
  3766. _In_count_(parameterTypeCount) QualType* parameterTypes,
  3767. size_t parameterTypeCount)
  3768. {
  3769. DXASSERT_NOMSG(intrinsic != nullptr);
  3770. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  3771. DXASSERT_NOMSG(parameterTypes != nullptr);
  3772. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  3773. // Create the template arguments.
  3774. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  3775. for (size_t i = 0; i < parameterTypeCount; i++) {
  3776. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  3777. }
  3778. // Look for an existing specialization.
  3779. void *InsertPos = nullptr;
  3780. FunctionDecl *SpecFunc =
  3781. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  3782. if (SpecFunc != nullptr) {
  3783. return SpecFunc;
  3784. }
  3785. // Change return type to rvalue reference type for aggregate types
  3786. QualType retTy = parameterTypes[0];
  3787. if (retTy->isAggregateType() && !IsHLSLVecMatType(retTy))
  3788. parameterTypes[0] = m_context->getRValueReferenceType(retTy);
  3789. // Create a new specialization.
  3790. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  3791. InitParamMods(intrinsic, paramMods);
  3792. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3793. // Change out/inout parameter type to rvalue reference type.
  3794. if (paramMods[i - 1].isAnyOut()) {
  3795. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  3796. }
  3797. }
  3798. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  3799. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  3800. // Remove this when update intrinsic table not affect other things.
  3801. // Change vector<float,1> into float for bias.
  3802. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  3803. DXASSERT(parameterTypeCount > biasOperandID,
  3804. "else operation was misrecognized");
  3805. if (const ExtVectorType *VecTy =
  3806. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  3807. *m_context, parameterTypes[biasOperandID])) {
  3808. if (VecTy->getNumElements() == 1)
  3809. parameterTypes[biasOperandID] = VecTy->getElementType();
  3810. }
  3811. }
  3812. DeclContext *owner = FunctionTemplate->getDeclContext();
  3813. TemplateArgumentList templateArgumentList(
  3814. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  3815. templateArgs.size());
  3816. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  3817. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  3818. mlTemplateArgumentList);
  3819. FunctionProtoType::ExtProtoInfo EmptyEPI;
  3820. QualType functionType = m_context->getFunctionType(
  3821. parameterTypes[0],
  3822. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  3823. EmptyEPI, paramMods);
  3824. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  3825. FunctionProtoTypeLoc Proto =
  3826. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  3827. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  3828. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3829. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  3830. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  3831. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  3832. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  3833. Params.push_back(paramDecl);
  3834. }
  3835. QualType T = TInfo->getType();
  3836. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  3837. CXXMethodDecl* method = CXXMethodDecl::Create(
  3838. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  3839. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  3840. // Add intrinsic attr
  3841. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  3842. // Record this function template specialization.
  3843. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  3844. *m_context, templateArgs.data(), templateArgs.size());
  3845. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  3846. // Attach the parameters
  3847. for (unsigned P = 0; P < Params.size(); ++P) {
  3848. Params[P]->setOwningFunction(method);
  3849. Proto.setParam(P, Params[P]);
  3850. }
  3851. method->setParams(Params);
  3852. // Adjust access.
  3853. method->setAccess(AccessSpecifier::AS_public);
  3854. FunctionTemplate->setAccess(method->getAccess());
  3855. return method;
  3856. }
  3857. // Overload support.
  3858. UINT64 ScoreCast(QualType leftType, QualType rightType);
  3859. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  3860. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  3861. unsigned GetNumElements(QualType anyType);
  3862. unsigned GetNumBasicElements(QualType anyType);
  3863. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  3864. QualType GetNthElementType(QualType type, unsigned index);
  3865. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  3866. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3867. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3868. };
  3869. // Use this class to flatten a type into HLSL primitives and iterate through them.
  3870. class FlattenedTypeIterator
  3871. {
  3872. private:
  3873. enum FlattenedIterKind {
  3874. FK_Simple,
  3875. FK_Fields,
  3876. FK_Expressions,
  3877. FK_IncompleteArray,
  3878. FK_Bases,
  3879. };
  3880. // Use this struct to represent a specific point in the tracked tree.
  3881. struct FlattenedTypeTracker {
  3882. QualType Type; // Type at this position in the tree.
  3883. unsigned int Count; // Count of consecutive types
  3884. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  3885. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  3886. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  3887. RecordDecl::field_iterator EndField; // STL-style end of fields.
  3888. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  3889. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  3890. FlattenedIterKind IterKind; // Kind of tracker.
  3891. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  3892. FlattenedTypeTracker(QualType type)
  3893. : Type(type), Count(0), CurrentExpr(nullptr),
  3894. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  3895. FlattenedTypeTracker(QualType type, unsigned int count,
  3896. MultiExprArg::iterator expression)
  3897. : Type(type), Count(count), CurrentExpr(expression),
  3898. IterKind(FK_Simple), IsConsidered(false) {}
  3899. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  3900. RecordDecl::field_iterator end)
  3901. : Type(type), Count(0), CurrentField(current), EndField(end),
  3902. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  3903. FlattenedTypeTracker(MultiExprArg::iterator current,
  3904. MultiExprArg::iterator end)
  3905. : Count(0), CurrentExpr(current), EndExpr(end),
  3906. IterKind(FK_Expressions), IsConsidered(false) {}
  3907. FlattenedTypeTracker(QualType type,
  3908. CXXRecordDecl::base_class_iterator current,
  3909. CXXRecordDecl::base_class_iterator end)
  3910. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  3911. IterKind(FK_Bases), IsConsidered(false) {}
  3912. /// <summary>Gets the current expression if one is available.</summary>
  3913. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  3914. /// <summary>Replaces the current expression.</summary>
  3915. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  3916. };
  3917. HLSLExternalSource& m_source; // Source driving the iteration.
  3918. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  3919. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  3920. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  3921. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  3922. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  3923. QualType m_firstType; // Name of first type found, used for diagnostics.
  3924. SourceLocation m_loc; // Location used for diagnostics.
  3925. static const size_t MaxTypeDepth = 100;
  3926. void advanceLeafTracker();
  3927. /// <summary>Consumes leaves.</summary>
  3928. void consumeLeaf();
  3929. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  3930. bool considerLeaf();
  3931. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  3932. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  3933. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  3934. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  3935. public:
  3936. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  3937. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  3938. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  3939. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  3940. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  3941. QualType getCurrentElement() const;
  3942. /// <summary>Get the number of repeated current elements.</summary>
  3943. unsigned int getCurrentElementSize() const;
  3944. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  3945. bool hasCurrentElement() const;
  3946. /// <summary>Consumes count elements on this iterator.</summary>
  3947. void advanceCurrentElement(unsigned int count);
  3948. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  3949. unsigned int countRemaining();
  3950. /// <summary>Gets the current expression if one is available.</summary>
  3951. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  3952. /// <summary>Replaces the current expression.</summary>
  3953. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  3954. struct ComparisonResult
  3955. {
  3956. unsigned int LeftCount;
  3957. unsigned int RightCount;
  3958. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  3959. bool AreElementsEqual;
  3960. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  3961. bool CanConvertElements;
  3962. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  3963. bool IsConvertibleAndEqualLength() const {
  3964. return LeftCount == RightCount;
  3965. }
  3966. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  3967. bool IsConvertibleAndLeftLonger() const {
  3968. return CanConvertElements && LeftCount > RightCount;
  3969. }
  3970. bool IsRightLonger() const {
  3971. return RightCount > LeftCount;
  3972. }
  3973. };
  3974. static ComparisonResult CompareIterators(
  3975. HLSLExternalSource& source, SourceLocation loc,
  3976. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  3977. static ComparisonResult CompareTypes(
  3978. HLSLExternalSource& source,
  3979. SourceLocation leftLoc, SourceLocation rightLoc,
  3980. QualType left, QualType right);
  3981. // Compares the arguments to initialize the left type, modifying them if necessary.
  3982. static ComparisonResult CompareTypesForInit(
  3983. HLSLExternalSource& source, QualType left, MultiExprArg args,
  3984. SourceLocation leftLoc, SourceLocation rightLoc);
  3985. };
  3986. static
  3987. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  3988. {
  3989. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  3990. if (specialization) {
  3991. const TemplateArgumentList& list = specialization->getTemplateArgs();
  3992. if (list.size()) {
  3993. return list[0].getAsType();
  3994. }
  3995. }
  3996. return QualType();
  3997. }
  3998. static
  3999. QualType GetFirstElementType(QualType type)
  4000. {
  4001. if (!type.isNull()) {
  4002. const RecordType* record = type->getAs<RecordType>();
  4003. if (record) {
  4004. return GetFirstElementTypeFromDecl(record->getDecl());
  4005. }
  4006. }
  4007. return QualType();
  4008. }
  4009. void HLSLExternalSource::AddBaseTypes()
  4010. {
  4011. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4012. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4013. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4014. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4015. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4016. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->FloatTy : m_context->HalfTy;
  4017. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4018. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4019. m_baseTypes[HLSLScalarType_float_min10] = m_context->HalfTy;
  4020. m_baseTypes[HLSLScalarType_float_min16] = m_context->HalfTy;
  4021. m_baseTypes[HLSLScalarType_int_min12] = m_context->ShortTy;
  4022. m_baseTypes[HLSLScalarType_int_min16] = m_context->ShortTy;
  4023. m_baseTypes[HLSLScalarType_uint_min16] = m_context->UnsignedShortTy;
  4024. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4025. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4026. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4027. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4028. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4029. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4030. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4031. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4032. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4033. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4034. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4035. }
  4036. void HLSLExternalSource::AddHLSLScalarTypes()
  4037. {
  4038. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4039. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4040. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4041. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4042. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4043. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4044. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4045. }
  4046. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4047. _In_ FunctionTemplateDecl* functionTemplate,
  4048. QualType objectElement,
  4049. const FindStructBasicTypeResult& findResult)
  4050. {
  4051. DXASSERT_NOMSG(functionTemplate != nullptr);
  4052. DXASSERT_NOMSG(!objectElement.isNull());
  4053. DXASSERT_NOMSG(findResult.Found());
  4054. DXASSERT(
  4055. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4056. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4057. // Subscript is templated only on its return type.
  4058. // Create the template argument.
  4059. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4060. QualType resultType = objectElement;
  4061. if (isReadWrite)
  4062. resultType = m_context->getLValueReferenceType(resultType, false);
  4063. else {
  4064. // Add const to avoid write.
  4065. resultType = m_context->getConstType(resultType);
  4066. resultType = m_context->getLValueReferenceType(resultType);
  4067. }
  4068. TemplateArgument templateArgument(resultType);
  4069. unsigned subscriptCardinality =
  4070. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4071. QualType subscriptIndexType =
  4072. subscriptCardinality == 1
  4073. ? m_context->UnsignedIntTy
  4074. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4075. subscriptCardinality);
  4076. // Look for an existing specialization.
  4077. void* InsertPos = nullptr;
  4078. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4079. if (SpecFunc != nullptr) {
  4080. return SpecFunc;
  4081. }
  4082. // Create a new specialization.
  4083. DeclContext* owner = functionTemplate->getDeclContext();
  4084. TemplateArgumentList templateArgumentList(
  4085. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4086. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4087. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4088. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4089. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4090. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4091. QualType functionType = m_context->getFunctionType(
  4092. resultType, subscriptIndexType, templateEPI, None);
  4093. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4094. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4095. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4096. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4097. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4098. QualType T = TInfo->getType();
  4099. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4100. CXXMethodDecl* method = CXXMethodDecl::Create(
  4101. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4102. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4103. // Add subscript attribute
  4104. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4105. // Record this function template specialization.
  4106. method->setFunctionTemplateSpecialization(functionTemplate,
  4107. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4108. // Attach the parameters
  4109. indexerParam->setOwningFunction(method);
  4110. Proto.setParam(0, indexerParam);
  4111. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4112. // Adjust access.
  4113. method->setAccess(AccessSpecifier::AS_public);
  4114. functionTemplate->setAccess(method->getAccess());
  4115. return method;
  4116. }
  4117. /// <summary>
  4118. /// This routine combines Source into Target. If you have a symmetric operation
  4119. /// and want to treat either side equally you should call it twice, swapping the
  4120. /// parameter order.
  4121. /// </summary>
  4122. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4123. _Out_opt_ ArBasicKind *pCombined) {
  4124. if (Target == Source) {
  4125. AssignOpt(Target, pCombined);
  4126. return true;
  4127. }
  4128. if (Source == AR_OBJECT_NULL) {
  4129. // NULL is valid for any object type.
  4130. AssignOpt(Target, pCombined);
  4131. return true;
  4132. }
  4133. switch (Target) {
  4134. AR_BASIC_ROBJECT_CASES:
  4135. if (Source == AR_OBJECT_STATEBLOCK) {
  4136. AssignOpt(Target, pCombined);
  4137. return true;
  4138. }
  4139. break;
  4140. AR_BASIC_TEXTURE_CASES:
  4141. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4142. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4143. AssignOpt(Target, pCombined);
  4144. return true;
  4145. }
  4146. break;
  4147. case AR_OBJECT_SAMPLERCOMPARISON:
  4148. if (Source == AR_OBJECT_STATEBLOCK) {
  4149. AssignOpt(Target, pCombined);
  4150. return true;
  4151. }
  4152. break;
  4153. }
  4154. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4155. return false;
  4156. }
  4157. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4158. HLSLExternalSource *pHLSLExternalSource) {
  4159. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4160. llvm::APInt val = intLit->getValue();
  4161. unsigned width = val.getActiveBits();
  4162. bool isNeg = val.isNegative();
  4163. if (isNeg) {
  4164. // Signed.
  4165. if (width <= 32)
  4166. return ArBasicKind::AR_BASIC_INT32;
  4167. else
  4168. return ArBasicKind::AR_BASIC_INT64;
  4169. } else {
  4170. // Unsigned.
  4171. if (width <= 32)
  4172. return ArBasicKind::AR_BASIC_UINT32;
  4173. else
  4174. return ArBasicKind::AR_BASIC_UINT64;
  4175. }
  4176. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4177. llvm::APFloat val = floatLit->getValue();
  4178. unsigned width = val.getSizeInBits(val.getSemantics());
  4179. if (width <= 16)
  4180. return ArBasicKind::AR_BASIC_FLOAT16;
  4181. else if (width <= 32)
  4182. return ArBasicKind::AR_BASIC_FLOAT32;
  4183. else
  4184. return AR_BASIC_FLOAT64;
  4185. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4186. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4187. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4188. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4189. kind = ArBasicKind::AR_BASIC_INT32;
  4190. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4191. kind = ArBasicKind::AR_BASIC_INT64;
  4192. }
  4193. return kind;
  4194. } else if (HLSLVectorElementExpr *VEE = dyn_cast<HLSLVectorElementExpr>(litExpr)) {
  4195. return pHLSLExternalSource->GetTypeElementKind(VEE->getType());
  4196. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4197. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4198. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4199. CombineBasicTypes(kind, kind1, &kind);
  4200. return kind;
  4201. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4202. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4203. return kind;
  4204. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4205. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4206. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4207. CombineBasicTypes(kind, kind1, &kind);
  4208. return kind;
  4209. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4210. // Use target Type for cast.
  4211. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4212. return kind;
  4213. } else {
  4214. // Could only be function call.
  4215. CallExpr *CE = cast<CallExpr>(litExpr);
  4216. // TODO: calculate the function call result.
  4217. if (CE->getNumArgs() == 1)
  4218. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4219. else {
  4220. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4221. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4222. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4223. CombineBasicTypes(kind, kindI, &kind);
  4224. }
  4225. return kind;
  4226. }
  4227. }
  4228. }
  4229. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4230. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4231. if (kind == *pCT)
  4232. return true;
  4233. pCT++;
  4234. }
  4235. return false;
  4236. }
  4237. static ArBasicKind
  4238. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4239. unsigned uLegalComponentTypes,
  4240. HLSLExternalSource *pHLSLExternalSource) {
  4241. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4242. ArBasicKind defaultKind = *pCT;
  4243. // Use first none literal kind as defaultKind.
  4244. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4245. ArBasicKind kind = *pCT;
  4246. pCT++;
  4247. // Skip literal type.
  4248. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4249. continue;
  4250. defaultKind = kind;
  4251. break;
  4252. }
  4253. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4254. if (kind == AR_BASIC_LITERAL_INT) {
  4255. // Search for match first.
  4256. // For literal arg which don't affect return type, the search should always success.
  4257. // Unless use literal int on a float parameter.
  4258. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4259. return litKind;
  4260. // Return the default.
  4261. return defaultKind;
  4262. }
  4263. else {
  4264. // Search for float32 first.
  4265. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4266. return AR_BASIC_FLOAT32;
  4267. // Search for float64.
  4268. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4269. return AR_BASIC_FLOAT64;
  4270. // return default.
  4271. return defaultKind;
  4272. }
  4273. }
  4274. _Use_decl_annotations_ bool
  4275. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4276. QualType objectElement) {
  4277. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4278. switch (op) {
  4279. case IntrinsicOp::MOP_Sample:
  4280. case IntrinsicOp::MOP_SampleBias:
  4281. case IntrinsicOp::MOP_SampleCmp:
  4282. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4283. case IntrinsicOp::MOP_SampleGrad:
  4284. case IntrinsicOp::MOP_SampleLevel: {
  4285. ArBasicKind kind = GetTypeElementKind(objectElement);
  4286. UINT uBits = GET_BPROP_BITS(kind);
  4287. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4288. } break;
  4289. default:
  4290. return true;
  4291. }
  4292. }
  4293. _Use_decl_annotations_
  4294. bool HLSLExternalSource::MatchArguments(
  4295. const HLSL_INTRINSIC* pIntrinsic,
  4296. QualType objectElement,
  4297. ArrayRef<Expr *> Args,
  4298. QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  4299. size_t* argCount)
  4300. {
  4301. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4302. DXASSERT_NOMSG(argCount != nullptr);
  4303. static const UINT UnusedSize = 0xFF;
  4304. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4305. #define CAB(_) { if (!(_)) return false; }
  4306. *argCount = 0;
  4307. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4308. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4309. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4310. // Reset infos
  4311. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4312. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  4313. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  4314. const unsigned retArgIdx = 0;
  4315. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  4316. // Populate the template for each argument.
  4317. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  4318. ArrayRef<Expr*>::iterator end = Args.end();
  4319. unsigned int iArg = 1;
  4320. for (; iterArg != end; ++iterArg) {
  4321. Expr* pCallArg = *iterArg;
  4322. // No vararg support.
  4323. if (iArg >= _countof(Template) || iArg > pIntrinsic->uNumArgs) {
  4324. return false;
  4325. }
  4326. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  4327. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  4328. DXASSERT(pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS, "no vararg support");
  4329. // If we are a type and templateID requires one, this isn't a match.
  4330. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4331. ++iArg;
  4332. continue;
  4333. }
  4334. QualType pType = pCallArg->getType();
  4335. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  4336. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  4337. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  4338. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  4339. bool affectRetType =
  4340. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  4341. // For literal arg which don't affect return type, find concrete type.
  4342. // For literal arg affect return type,
  4343. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  4344. // where all argumentss are literal.
  4345. // CombineBasicTypes will cover the rest cases.
  4346. if (!affectRetType) {
  4347. TypeInfoEltKind = ConcreteLiteralType(
  4348. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  4349. }
  4350. }
  4351. UINT TypeInfoCols = 1;
  4352. UINT TypeInfoRows = 1;
  4353. switch (TypeInfoShapeKind) {
  4354. case AR_TOBJ_MATRIX:
  4355. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  4356. break;
  4357. case AR_TOBJ_VECTOR:
  4358. TypeInfoCols = GetHLSLVecSize(pType);
  4359. break;
  4360. case AR_TOBJ_BASIC:
  4361. case AR_TOBJ_OBJECT:
  4362. break;
  4363. default:
  4364. return false; // no struct, arrays or void
  4365. }
  4366. DXASSERT(
  4367. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  4368. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  4369. // Compare template
  4370. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  4371. (AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  4372. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind)) {
  4373. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  4374. }
  4375. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  4376. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  4377. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  4378. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  4379. return false;
  4380. }
  4381. }
  4382. else {
  4383. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  4384. return false;
  4385. }
  4386. }
  4387. DXASSERT(
  4388. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  4389. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  4390. // Merge ComponentTypes
  4391. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  4392. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  4393. }
  4394. else {
  4395. if (!CombineBasicTypes(
  4396. ComponentType[pIntrinsicArg->uComponentTypeId],
  4397. TypeInfoEltKind,
  4398. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  4399. return false;
  4400. }
  4401. }
  4402. // Rows
  4403. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4404. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  4405. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  4406. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4407. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  4408. uSpecialSize[uSpecialId] = TypeInfoRows;
  4409. }
  4410. }
  4411. else {
  4412. if (TypeInfoRows < pIntrinsicArg->uRows) {
  4413. return false;
  4414. }
  4415. }
  4416. }
  4417. // Columns
  4418. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4419. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  4420. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  4421. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4422. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  4423. uSpecialSize[uSpecialId] = TypeInfoCols;
  4424. }
  4425. }
  4426. else {
  4427. if (TypeInfoCols < pIntrinsicArg->uCols) {
  4428. return false;
  4429. }
  4430. }
  4431. }
  4432. // Usage
  4433. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  4434. if (pCallArg->getType().isConstQualified()) {
  4435. // Can't use a const type in an out or inout parameter.
  4436. return false;
  4437. }
  4438. }
  4439. iArg++;
  4440. }
  4441. DXASSERT(iterArg == end, "otherwise the argument list wasn't fully processed");
  4442. // Default template and component type for return value
  4443. if (pIntrinsic->pArgs[0].qwUsage && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE) {
  4444. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs);
  4445. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  4446. Template[pIntrinsic->pArgs[0].uTemplateId] =
  4447. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  4448. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4449. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  4450. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  4451. // half return type should map to float for min precision
  4452. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  4453. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  4454. getSema()->getLangOpts().UseMinPrecision) {
  4455. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4456. ArBasicKind::AR_BASIC_FLOAT32;
  4457. }
  4458. else {
  4459. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4460. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  4461. }
  4462. }
  4463. }
  4464. }
  4465. }
  4466. // Make sure all template, component type, and texture type selections are valid.
  4467. for (size_t i = 0; i < Args.size() + 1; i++) {
  4468. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4469. // Check template.
  4470. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4471. continue; // Already verified that this is available.
  4472. }
  4473. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  4474. if (AR_TOBJ_UNKNOWN != Template[i]) {
  4475. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  4476. Template[i] = *pTT;
  4477. }
  4478. else {
  4479. while (AR_TOBJ_UNKNOWN != *pTT) {
  4480. if (Template[i] == *pTT)
  4481. break;
  4482. pTT++;
  4483. }
  4484. }
  4485. if (AR_TOBJ_UNKNOWN == *pTT)
  4486. return false;
  4487. }
  4488. else if (pTT) {
  4489. Template[i] = *pTT;
  4490. }
  4491. // Check component type.
  4492. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  4493. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  4494. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4495. if (ComponentType[i] == *pCT)
  4496. break;
  4497. pCT++;
  4498. }
  4499. // has to be a strict match
  4500. if (*pCT == AR_BASIC_NOCAST)
  4501. return false;
  4502. // If it is an object, see if it can be cast to the first thing in the
  4503. // list, otherwise move on to next intrinsic.
  4504. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  4505. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  4506. return false;
  4507. }
  4508. }
  4509. if (AR_BASIC_UNKNOWN == *pCT) {
  4510. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  4511. }
  4512. }
  4513. else if (pCT) {
  4514. ComponentType[i] = *pCT;
  4515. }
  4516. }
  4517. // Default to a void return type.
  4518. argTypes[0] = m_context->VoidTy;
  4519. // Default specials sizes.
  4520. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  4521. if (UnusedSize == uSpecialSize[i]) {
  4522. uSpecialSize[i] = 1;
  4523. }
  4524. }
  4525. // Populate argTypes.
  4526. for (size_t i = 0; i <= Args.size(); i++) {
  4527. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4528. if (!pArgument->qwUsage)
  4529. continue;
  4530. QualType pNewType;
  4531. unsigned int quals = 0; // qualifications for this argument
  4532. // If we have no type, set it to our input type (templatized)
  4533. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4534. // Use the templated input type, but resize it if the
  4535. // intrinsic's rows/cols isn't 0
  4536. if (pArgument->uRows && pArgument->uCols) {
  4537. UINT uRows, uCols;
  4538. // if type is overriden, use new type size, for
  4539. // now it only supports scalars
  4540. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4541. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4542. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4543. uRows = uSpecialSize[uSpecialId];
  4544. }
  4545. else if (pArgument->uRows > 0) {
  4546. uRows = pArgument->uRows;
  4547. }
  4548. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4549. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4550. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4551. uCols = uSpecialSize[uSpecialId];
  4552. }
  4553. else if (pArgument->uCols > 0) {
  4554. uCols = pArgument->uCols;
  4555. }
  4556. // 1x1 numeric outputs are always scalar.. since these
  4557. // are most flexible
  4558. if ((1 == uCols) && (1 == uRows)) {
  4559. pNewType = objectElement;
  4560. if (pNewType.isNull()) {
  4561. return false;
  4562. }
  4563. }
  4564. else {
  4565. // non-scalars unsupported right now since nothing
  4566. // uses it, would have to create either a type
  4567. // list for sub-structures or just resize the
  4568. // given type
  4569. // VH(E_NOTIMPL);
  4570. return false;
  4571. }
  4572. }
  4573. else {
  4574. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  4575. if (objectElement.isNull()) {
  4576. return false;
  4577. }
  4578. pNewType = objectElement;
  4579. }
  4580. }
  4581. else {
  4582. ArBasicKind pEltType;
  4583. // ComponentType, if the Id is special then it gets the
  4584. // component type from the first component of the type, if
  4585. // we need more (for the second component, e.g.), then we
  4586. // can use more specials, etc.
  4587. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4588. if (objectElement.isNull()) {
  4589. return false;
  4590. }
  4591. pEltType = GetTypeElementKind(objectElement);
  4592. DXASSERT_VALIDBASICKIND(pEltType);
  4593. }
  4594. else {
  4595. pEltType = ComponentType[pArgument->uComponentTypeId];
  4596. DXASSERT_VALIDBASICKIND(pEltType);
  4597. }
  4598. UINT uRows, uCols;
  4599. // Rows
  4600. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4601. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4602. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4603. uRows = uSpecialSize[uSpecialId];
  4604. }
  4605. else {
  4606. uRows = pArgument->uRows;
  4607. }
  4608. // Cols
  4609. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4610. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4611. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4612. uCols = uSpecialSize[uSpecialId];
  4613. }
  4614. else {
  4615. uCols = pArgument->uCols;
  4616. }
  4617. // Verify that the final results are in bounds.
  4618. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize);
  4619. // Const
  4620. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  4621. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  4622. qwQual |= AR_QUAL_CONST;
  4623. DXASSERT_VALIDBASICKIND(pEltType);
  4624. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  4625. }
  4626. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  4627. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  4628. // TODO: support out modifier
  4629. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  4630. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  4631. //}
  4632. }
  4633. *argCount = iArg;
  4634. DXASSERT(
  4635. *argCount == pIntrinsic->uNumArgs,
  4636. "In the absence of varargs, a successful match would indicate we have as many arguments and types as the intrinsic template");
  4637. return true;
  4638. #undef CAB
  4639. }
  4640. _Use_decl_annotations_
  4641. HLSLExternalSource::FindStructBasicTypeResult
  4642. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  4643. {
  4644. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4645. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  4646. // may be a simple class, such as RWByteAddressBuffer.
  4647. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  4648. // We save the caller from filtering out other types of context (like the translation unit itself).
  4649. if (recordDecl != nullptr)
  4650. {
  4651. int index = FindObjectBasicKindIndex(recordDecl);
  4652. if (index != -1) {
  4653. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  4654. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  4655. }
  4656. }
  4657. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  4658. }
  4659. _Use_decl_annotations_
  4660. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  4661. {
  4662. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4663. DXASSERT_NOMSG(name != nullptr);
  4664. DXASSERT_NOMSG(intrinsics != nullptr);
  4665. DXASSERT_NOMSG(intrinsicCount != nullptr);
  4666. *intrinsics = nullptr;
  4667. *intrinsicCount = 0;
  4668. *name = nullptr;
  4669. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  4670. if (lookup.Found()) {
  4671. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  4672. *name = g_ArBasicTypeNames[lookup.Kind];
  4673. }
  4674. }
  4675. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  4676. {
  4677. return
  4678. // Arithmetic operators.
  4679. Opc == BinaryOperatorKind::BO_Add ||
  4680. Opc == BinaryOperatorKind::BO_AddAssign ||
  4681. Opc == BinaryOperatorKind::BO_Sub ||
  4682. Opc == BinaryOperatorKind::BO_SubAssign ||
  4683. Opc == BinaryOperatorKind::BO_Rem ||
  4684. Opc == BinaryOperatorKind::BO_RemAssign ||
  4685. Opc == BinaryOperatorKind::BO_Div ||
  4686. Opc == BinaryOperatorKind::BO_DivAssign ||
  4687. Opc == BinaryOperatorKind::BO_Mul ||
  4688. Opc == BinaryOperatorKind::BO_MulAssign;
  4689. }
  4690. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  4691. {
  4692. return
  4693. // Arithmetic-and-assignment operators.
  4694. Opc == BinaryOperatorKind::BO_AddAssign ||
  4695. Opc == BinaryOperatorKind::BO_SubAssign ||
  4696. Opc == BinaryOperatorKind::BO_RemAssign ||
  4697. Opc == BinaryOperatorKind::BO_DivAssign ||
  4698. Opc == BinaryOperatorKind::BO_MulAssign ||
  4699. // Bitwise-and-assignment operators.
  4700. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4701. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4702. Opc == BinaryOperatorKind::BO_AndAssign ||
  4703. Opc == BinaryOperatorKind::BO_OrAssign ||
  4704. Opc == BinaryOperatorKind::BO_XorAssign;
  4705. }
  4706. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  4707. {
  4708. return
  4709. Opc == BinaryOperatorKind::BO_AndAssign ||
  4710. Opc == BinaryOperatorKind::BO_OrAssign ||
  4711. Opc == BinaryOperatorKind::BO_XorAssign;
  4712. }
  4713. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  4714. {
  4715. return
  4716. Opc == BinaryOperatorKind::BO_Shl ||
  4717. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4718. Opc == BinaryOperatorKind::BO_Shr ||
  4719. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4720. Opc == BinaryOperatorKind::BO_And ||
  4721. Opc == BinaryOperatorKind::BO_AndAssign ||
  4722. Opc == BinaryOperatorKind::BO_Or ||
  4723. Opc == BinaryOperatorKind::BO_OrAssign ||
  4724. Opc == BinaryOperatorKind::BO_Xor ||
  4725. Opc == BinaryOperatorKind::BO_XorAssign;
  4726. }
  4727. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  4728. {
  4729. return
  4730. Opc == BinaryOperatorKind::BO_Shl ||
  4731. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4732. Opc == BinaryOperatorKind::BO_Shr ||
  4733. Opc == BinaryOperatorKind::BO_ShrAssign;
  4734. }
  4735. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  4736. {
  4737. return
  4738. Opc == BinaryOperatorKind::BO_EQ ||
  4739. Opc == BinaryOperatorKind::BO_NE;
  4740. }
  4741. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  4742. {
  4743. return
  4744. Opc == BinaryOperatorKind::BO_LT ||
  4745. Opc == BinaryOperatorKind::BO_GT ||
  4746. Opc == BinaryOperatorKind::BO_LE ||
  4747. Opc == BinaryOperatorKind::BO_GE;
  4748. }
  4749. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  4750. {
  4751. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  4752. }
  4753. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  4754. {
  4755. return
  4756. Opc == BinaryOperatorKind::BO_LAnd ||
  4757. Opc == BinaryOperatorKind::BO_LOr;
  4758. }
  4759. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  4760. {
  4761. return
  4762. BinaryOperatorKindIsArithmetic(Opc) ||
  4763. BinaryOperatorKindIsOrderComparison(Opc) ||
  4764. BinaryOperatorKindIsLogical(Opc);
  4765. }
  4766. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  4767. {
  4768. return BinaryOperatorKindIsBitwise(Opc);
  4769. }
  4770. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  4771. {
  4772. return
  4773. BinaryOperatorKindIsBitwise(Opc) ||
  4774. BinaryOperatorKindIsArithmetic(Opc);
  4775. }
  4776. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  4777. {
  4778. return Opc == UnaryOperatorKind::UO_Not;
  4779. }
  4780. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  4781. {
  4782. return
  4783. Opc == UnaryOperatorKind::UO_LNot ||
  4784. Opc == UnaryOperatorKind::UO_Plus ||
  4785. Opc == UnaryOperatorKind::UO_Minus ||
  4786. // The omission in fxc caused objects and structs to accept this.
  4787. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4788. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4789. }
  4790. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  4791. {
  4792. return
  4793. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4794. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4795. }
  4796. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  4797. {
  4798. return
  4799. Opc == UnaryOperatorKind::UO_Not ||
  4800. Opc == UnaryOperatorKind::UO_Plus ||
  4801. Opc == UnaryOperatorKind::UO_Minus;
  4802. }
  4803. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  4804. {
  4805. return
  4806. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4807. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4808. }
  4809. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  4810. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  4811. }
  4812. /// <summary>
  4813. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  4814. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  4815. /// </summary>
  4816. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  4817. {
  4818. return
  4819. value == AR_TOBJ_BASIC ||
  4820. value == AR_TOBJ_MATRIX ||
  4821. value == AR_TOBJ_VECTOR;
  4822. }
  4823. static bool IsBasicKindIntegral(ArBasicKind value)
  4824. {
  4825. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  4826. }
  4827. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  4828. {
  4829. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  4830. }
  4831. static bool IsBasicKindNumeric(ArBasicKind value)
  4832. {
  4833. return GetBasicKindProps(value) & BPROP_NUMERIC;
  4834. }
  4835. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  4836. {
  4837. // An invalid expression is pass-through at this point.
  4838. if (E.isInvalid())
  4839. {
  4840. return E;
  4841. }
  4842. QualType qt = E.get()->getType();
  4843. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  4844. if (elementKind != AR_BASIC_BOOL)
  4845. {
  4846. return E;
  4847. }
  4848. // Construct a scalar/vector/matrix type with the same shape as E.
  4849. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  4850. QualType targetType;
  4851. UINT colCount, rowCount;
  4852. GetRowsAndColsForAny(qt, rowCount, colCount);
  4853. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  4854. if (E.get()->isLValue()) {
  4855. E = m_sema->DefaultLvalueConversion(E.get()).get();
  4856. }
  4857. switch (objectKind)
  4858. {
  4859. case AR_TOBJ_SCALAR:
  4860. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  4861. case AR_TOBJ_ARRAY:
  4862. case AR_TOBJ_VECTOR:
  4863. case AR_TOBJ_MATRIX:
  4864. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  4865. default:
  4866. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  4867. }
  4868. return E;
  4869. }
  4870. _Use_decl_annotations_
  4871. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  4872. {
  4873. DXASSERT_NOMSG(pTypeInfo != nullptr);
  4874. DXASSERT_NOMSG(!type.isNull());
  4875. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  4876. pTypeInfo->ObjKind = GetTypeElementKind(type);
  4877. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  4878. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  4879. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  4880. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  4881. }
  4882. // Highest possible score (i.e., worst possible score).
  4883. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  4884. // Leave the first two score bits to handle higher-level
  4885. // variations like target type.
  4886. #define SCORE_MIN_SHIFT 2
  4887. // Space out scores to allow up to 128 parameters to
  4888. // vary between score sets spill into each other.
  4889. #define SCORE_PARAM_SHIFT 7
  4890. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  4891. if (anyType.isNull()) {
  4892. return 0;
  4893. }
  4894. anyType = GetStructuralForm(anyType);
  4895. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  4896. switch (kind) {
  4897. case AR_TOBJ_BASIC:
  4898. case AR_TOBJ_OBJECT:
  4899. return 1;
  4900. case AR_TOBJ_COMPOUND: {
  4901. // TODO: consider caching this value for perf
  4902. unsigned total = 0;
  4903. const RecordType *recordType = anyType->getAs<RecordType>();
  4904. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  4905. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  4906. while (fi != fend) {
  4907. total += GetNumElements(fi->getType());
  4908. ++fi;
  4909. }
  4910. return total;
  4911. }
  4912. case AR_TOBJ_ARRAY:
  4913. case AR_TOBJ_MATRIX:
  4914. case AR_TOBJ_VECTOR:
  4915. return GetElementCount(anyType);
  4916. default:
  4917. DXASSERT(kind == AR_TOBJ_VOID,
  4918. "otherwise the type cannot be classified or is not supported");
  4919. return 0;
  4920. }
  4921. }
  4922. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  4923. if (anyType.isNull()) {
  4924. return 0;
  4925. }
  4926. anyType = GetStructuralForm(anyType);
  4927. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  4928. switch (kind) {
  4929. case AR_TOBJ_BASIC:
  4930. case AR_TOBJ_OBJECT:
  4931. return 1;
  4932. case AR_TOBJ_COMPOUND: {
  4933. // TODO: consider caching this value for perf
  4934. unsigned total = 0;
  4935. const RecordType *recordType = anyType->getAs<RecordType>();
  4936. RecordDecl * RD = recordType->getDecl();
  4937. // Take care base.
  4938. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4939. if (CXXRD->getNumBases()) {
  4940. for (const auto &I : CXXRD->bases()) {
  4941. const CXXRecordDecl *BaseDecl =
  4942. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4943. if (BaseDecl->field_empty())
  4944. continue;
  4945. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4946. total += GetNumBasicElements(parentTy);
  4947. }
  4948. }
  4949. }
  4950. RecordDecl::field_iterator fi = RD->field_begin();
  4951. RecordDecl::field_iterator fend = RD->field_end();
  4952. while (fi != fend) {
  4953. total += GetNumBasicElements(fi->getType());
  4954. ++fi;
  4955. }
  4956. return total;
  4957. }
  4958. case AR_TOBJ_ARRAY: {
  4959. unsigned arraySize = GetElementCount(anyType);
  4960. unsigned eltSize = GetNumBasicElements(
  4961. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  4962. return arraySize * eltSize;
  4963. }
  4964. case AR_TOBJ_MATRIX:
  4965. case AR_TOBJ_VECTOR:
  4966. return GetElementCount(anyType);
  4967. default:
  4968. DXASSERT(kind == AR_TOBJ_VOID,
  4969. "otherwise the type cannot be classified or is not supported");
  4970. return 0;
  4971. }
  4972. }
  4973. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  4974. unsigned leftSize,
  4975. QualType rightType,
  4976. unsigned rightSize) {
  4977. // We can convert from a larger type to a smaller
  4978. // but not a smaller type to a larger so default
  4979. // to just comparing the destination size.
  4980. unsigned uElts = leftSize;
  4981. leftType = GetStructuralForm(leftType);
  4982. rightType = GetStructuralForm(rightType);
  4983. if (leftType->isArrayType() && rightType->isArrayType()) {
  4984. //
  4985. // If we're comparing arrays we don't
  4986. // need to compare every element of
  4987. // the arrays since all elements
  4988. // will have the same type.
  4989. // We only need to compare enough
  4990. // elements that we've tried every
  4991. // possible mix of dst and src elements.
  4992. //
  4993. // TODO: handle multidimensional arrays and arrays of arrays
  4994. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  4995. unsigned uDstEltSize = GetNumElements(pDstElt);
  4996. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  4997. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  4998. if (uDstEltSize == uSrcEltSize) {
  4999. uElts = uDstEltSize;
  5000. } else if (uDstEltSize > uSrcEltSize) {
  5001. // If one size is not an even multiple of the other we need to let the
  5002. // full compare run in order to try all alignments.
  5003. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5004. uElts = uDstEltSize;
  5005. }
  5006. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5007. uElts = uSrcEltSize;
  5008. }
  5009. }
  5010. return uElts;
  5011. }
  5012. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5013. if (type.isNull()) {
  5014. return type;
  5015. }
  5016. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5017. switch (kind) {
  5018. case AR_TOBJ_BASIC:
  5019. case AR_TOBJ_OBJECT:
  5020. return (index == 0) ? type : QualType();
  5021. case AR_TOBJ_COMPOUND: {
  5022. // TODO: consider caching this value for perf
  5023. const RecordType *recordType = type->getAsStructureType();
  5024. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5025. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5026. while (fi != fend) {
  5027. if (!fi->getType().isNull()) {
  5028. unsigned subElements = GetNumElements(fi->getType());
  5029. if (index < subElements) {
  5030. return GetNthElementType(fi->getType(), index);
  5031. } else {
  5032. index -= subElements;
  5033. }
  5034. }
  5035. ++fi;
  5036. }
  5037. return QualType();
  5038. }
  5039. case AR_TOBJ_ARRAY: {
  5040. unsigned arraySize;
  5041. QualType elementType;
  5042. unsigned elementCount;
  5043. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5044. elementCount = GetElementCount(elementType);
  5045. if (index < elementCount) {
  5046. return GetNthElementType(elementType, index);
  5047. }
  5048. arraySize = GetArraySize(type);
  5049. if (index >= arraySize * elementCount) {
  5050. return QualType();
  5051. }
  5052. return GetNthElementType(elementType, index % elementCount);
  5053. }
  5054. case AR_TOBJ_MATRIX:
  5055. case AR_TOBJ_VECTOR:
  5056. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5057. : QualType();
  5058. default:
  5059. DXASSERT(kind == AR_TOBJ_VOID,
  5060. "otherwise the type cannot be classified or is not supported");
  5061. return QualType();
  5062. }
  5063. }
  5064. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5065. // Eliminate exact matches first, then check for promotions.
  5066. if (leftKind == rightKind) {
  5067. return false;
  5068. }
  5069. switch (rightKind) {
  5070. case AR_BASIC_FLOAT16:
  5071. switch (leftKind) {
  5072. case AR_BASIC_FLOAT32:
  5073. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5074. case AR_BASIC_FLOAT64:
  5075. return true;
  5076. }
  5077. break;
  5078. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5079. switch (leftKind) {
  5080. case AR_BASIC_FLOAT32:
  5081. case AR_BASIC_FLOAT64:
  5082. return true;
  5083. }
  5084. break;
  5085. case AR_BASIC_FLOAT32:
  5086. switch (leftKind) {
  5087. case AR_BASIC_FLOAT64:
  5088. return true;
  5089. }
  5090. break;
  5091. case AR_BASIC_MIN10FLOAT:
  5092. switch (leftKind) {
  5093. case AR_BASIC_MIN16FLOAT:
  5094. case AR_BASIC_FLOAT16:
  5095. case AR_BASIC_FLOAT32:
  5096. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5097. case AR_BASIC_FLOAT64:
  5098. return true;
  5099. }
  5100. break;
  5101. case AR_BASIC_MIN16FLOAT:
  5102. switch (leftKind) {
  5103. case AR_BASIC_FLOAT16:
  5104. case AR_BASIC_FLOAT32:
  5105. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5106. case AR_BASIC_FLOAT64:
  5107. return true;
  5108. }
  5109. break;
  5110. case AR_BASIC_INT8:
  5111. case AR_BASIC_UINT8:
  5112. // For backwards compat we consider signed/unsigned the same.
  5113. switch (leftKind) {
  5114. case AR_BASIC_INT16:
  5115. case AR_BASIC_INT32:
  5116. case AR_BASIC_INT64:
  5117. case AR_BASIC_UINT16:
  5118. case AR_BASIC_UINT32:
  5119. case AR_BASIC_UINT64:
  5120. return true;
  5121. }
  5122. break;
  5123. case AR_BASIC_INT16:
  5124. case AR_BASIC_UINT16:
  5125. // For backwards compat we consider signed/unsigned the same.
  5126. switch (leftKind) {
  5127. case AR_BASIC_INT32:
  5128. case AR_BASIC_INT64:
  5129. case AR_BASIC_UINT32:
  5130. case AR_BASIC_UINT64:
  5131. return true;
  5132. }
  5133. break;
  5134. case AR_BASIC_INT32:
  5135. case AR_BASIC_UINT32:
  5136. // For backwards compat we consider signed/unsigned the same.
  5137. switch (leftKind) {
  5138. case AR_BASIC_INT64:
  5139. case AR_BASIC_UINT64:
  5140. return true;
  5141. }
  5142. break;
  5143. case AR_BASIC_MIN12INT:
  5144. switch (leftKind) {
  5145. case AR_BASIC_MIN16INT:
  5146. case AR_BASIC_INT32:
  5147. case AR_BASIC_INT64:
  5148. return true;
  5149. }
  5150. break;
  5151. case AR_BASIC_MIN16INT:
  5152. switch (leftKind) {
  5153. case AR_BASIC_INT32:
  5154. case AR_BASIC_INT64:
  5155. return true;
  5156. }
  5157. break;
  5158. case AR_BASIC_MIN16UINT:
  5159. switch (leftKind) {
  5160. case AR_BASIC_UINT32:
  5161. case AR_BASIC_UINT64:
  5162. return true;
  5163. }
  5164. break;
  5165. }
  5166. return false;
  5167. }
  5168. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5169. // Eliminate exact matches first, then check for casts.
  5170. if (leftKind == rightKind) {
  5171. return false;
  5172. }
  5173. //
  5174. // All minimum-bits types are only considered matches of themselves
  5175. // and thus are not in this table.
  5176. //
  5177. switch (leftKind) {
  5178. case AR_BASIC_LITERAL_INT:
  5179. switch (rightKind) {
  5180. case AR_BASIC_INT8:
  5181. case AR_BASIC_INT16:
  5182. case AR_BASIC_INT32:
  5183. case AR_BASIC_INT64:
  5184. case AR_BASIC_UINT8:
  5185. case AR_BASIC_UINT16:
  5186. case AR_BASIC_UINT32:
  5187. case AR_BASIC_UINT64:
  5188. return false;
  5189. }
  5190. break;
  5191. case AR_BASIC_INT8:
  5192. switch (rightKind) {
  5193. // For backwards compat we consider signed/unsigned the same.
  5194. case AR_BASIC_LITERAL_INT:
  5195. case AR_BASIC_UINT8:
  5196. return false;
  5197. }
  5198. break;
  5199. case AR_BASIC_INT16:
  5200. switch (rightKind) {
  5201. // For backwards compat we consider signed/unsigned the same.
  5202. case AR_BASIC_LITERAL_INT:
  5203. case AR_BASIC_UINT16:
  5204. return false;
  5205. }
  5206. break;
  5207. case AR_BASIC_INT32:
  5208. switch (rightKind) {
  5209. // For backwards compat we consider signed/unsigned the same.
  5210. case AR_BASIC_LITERAL_INT:
  5211. case AR_BASIC_UINT32:
  5212. return false;
  5213. }
  5214. break;
  5215. case AR_BASIC_INT64:
  5216. switch (rightKind) {
  5217. // For backwards compat we consider signed/unsigned the same.
  5218. case AR_BASIC_LITERAL_INT:
  5219. case AR_BASIC_UINT64:
  5220. return false;
  5221. }
  5222. break;
  5223. case AR_BASIC_UINT8:
  5224. switch (rightKind) {
  5225. // For backwards compat we consider signed/unsigned the same.
  5226. case AR_BASIC_LITERAL_INT:
  5227. case AR_BASIC_INT8:
  5228. return false;
  5229. }
  5230. break;
  5231. case AR_BASIC_UINT16:
  5232. switch (rightKind) {
  5233. // For backwards compat we consider signed/unsigned the same.
  5234. case AR_BASIC_LITERAL_INT:
  5235. case AR_BASIC_INT16:
  5236. return false;
  5237. }
  5238. break;
  5239. case AR_BASIC_UINT32:
  5240. switch (rightKind) {
  5241. // For backwards compat we consider signed/unsigned the same.
  5242. case AR_BASIC_LITERAL_INT:
  5243. case AR_BASIC_INT32:
  5244. return false;
  5245. }
  5246. break;
  5247. case AR_BASIC_UINT64:
  5248. switch (rightKind) {
  5249. // For backwards compat we consider signed/unsigned the same.
  5250. case AR_BASIC_LITERAL_INT:
  5251. case AR_BASIC_INT64:
  5252. return false;
  5253. }
  5254. break;
  5255. case AR_BASIC_LITERAL_FLOAT:
  5256. switch (rightKind) {
  5257. case AR_BASIC_LITERAL_FLOAT:
  5258. case AR_BASIC_FLOAT16:
  5259. case AR_BASIC_FLOAT32:
  5260. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5261. case AR_BASIC_FLOAT64:
  5262. return false;
  5263. }
  5264. break;
  5265. case AR_BASIC_FLOAT16:
  5266. switch (rightKind) {
  5267. case AR_BASIC_LITERAL_FLOAT:
  5268. return false;
  5269. }
  5270. break;
  5271. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5272. switch (rightKind) {
  5273. case AR_BASIC_LITERAL_FLOAT:
  5274. return false;
  5275. }
  5276. break;
  5277. case AR_BASIC_FLOAT32:
  5278. switch (rightKind) {
  5279. case AR_BASIC_LITERAL_FLOAT:
  5280. return false;
  5281. }
  5282. break;
  5283. case AR_BASIC_FLOAT64:
  5284. switch (rightKind) {
  5285. case AR_BASIC_LITERAL_FLOAT:
  5286. return false;
  5287. }
  5288. break;
  5289. }
  5290. return true;
  5291. }
  5292. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5293. // Eliminate exact matches first, then check for casts.
  5294. if (leftKind == rightKind) {
  5295. return false;
  5296. }
  5297. //
  5298. // All minimum-bits types are only considered matches of themselves
  5299. // and thus are not in this table.
  5300. //
  5301. switch (leftKind) {
  5302. case AR_BASIC_LITERAL_INT:
  5303. switch (rightKind) {
  5304. case AR_BASIC_INT8:
  5305. case AR_BASIC_INT16:
  5306. case AR_BASIC_INT32:
  5307. case AR_BASIC_INT64:
  5308. case AR_BASIC_UINT8:
  5309. case AR_BASIC_UINT16:
  5310. case AR_BASIC_UINT32:
  5311. case AR_BASIC_UINT64:
  5312. return false;
  5313. }
  5314. break;
  5315. case AR_BASIC_INT8:
  5316. case AR_BASIC_INT16:
  5317. case AR_BASIC_INT32:
  5318. case AR_BASIC_INT64:
  5319. case AR_BASIC_UINT8:
  5320. case AR_BASIC_UINT16:
  5321. case AR_BASIC_UINT32:
  5322. case AR_BASIC_UINT64:
  5323. switch (rightKind) {
  5324. case AR_BASIC_LITERAL_INT:
  5325. return false;
  5326. }
  5327. break;
  5328. case AR_BASIC_LITERAL_FLOAT:
  5329. switch (rightKind) {
  5330. case AR_BASIC_LITERAL_FLOAT:
  5331. case AR_BASIC_FLOAT16:
  5332. case AR_BASIC_FLOAT32:
  5333. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5334. case AR_BASIC_FLOAT64:
  5335. return false;
  5336. }
  5337. break;
  5338. case AR_BASIC_FLOAT16:
  5339. case AR_BASIC_FLOAT32:
  5340. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5341. case AR_BASIC_FLOAT64:
  5342. switch (rightKind) {
  5343. case AR_BASIC_LITERAL_FLOAT:
  5344. return false;
  5345. }
  5346. break;
  5347. }
  5348. return true;
  5349. }
  5350. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  5351. {
  5352. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  5353. return 0;
  5354. }
  5355. UINT64 uScore = 0;
  5356. UINT uLSize = GetNumElements(pLType);
  5357. UINT uRSize = GetNumElements(pRType);
  5358. UINT uCompareSize;
  5359. bool bLCast = false;
  5360. bool bRCast = false;
  5361. bool bLIntCast = false;
  5362. bool bRIntCast = false;
  5363. bool bLPromo = false;
  5364. bool bRPromo = false;
  5365. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  5366. if (uCompareSize > uRSize) {
  5367. uCompareSize = uRSize;
  5368. }
  5369. for (UINT i = 0; i < uCompareSize; i++) {
  5370. ArBasicKind LeftElementKind, RightElementKind;
  5371. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  5372. QualType leftSub = GetNthElementType(pLType, i);
  5373. QualType rightSub = GetNthElementType(pRType, i);
  5374. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  5375. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  5376. LeftElementKind = GetTypeElementKind(leftSub);
  5377. RightElementKind = GetTypeElementKind(rightSub);
  5378. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  5379. // information needed is the ShapeKind, EltKind and ObjKind.
  5380. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  5381. bool bCombine;
  5382. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  5383. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  5384. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  5385. ArBasicKind RightObjKind = RightElementKind;
  5386. LeftElementKind = LeftObjKind;
  5387. RightElementKind = RightObjKind;
  5388. if (leftKind != rightKind) {
  5389. bCombine = false;
  5390. }
  5391. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  5392. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  5393. }
  5394. }
  5395. else {
  5396. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  5397. }
  5398. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  5399. bLPromo = true;
  5400. }
  5401. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  5402. bLCast = true;
  5403. }
  5404. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  5405. bLIntCast = true;
  5406. }
  5407. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  5408. bRPromo = true;
  5409. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  5410. bRCast = true;
  5411. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  5412. bRIntCast = true;
  5413. }
  5414. } else {
  5415. bLCast = true;
  5416. bRCast = true;
  5417. }
  5418. }
  5419. #define SCORE_COND(shift, cond) { \
  5420. if (cond) uScore += 1UI64 << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  5421. SCORE_COND(0, uRSize < uLSize);
  5422. SCORE_COND(1, bLPromo);
  5423. SCORE_COND(2, bRPromo);
  5424. SCORE_COND(3, bLIntCast);
  5425. SCORE_COND(4, bRIntCast);
  5426. SCORE_COND(5, bLCast);
  5427. SCORE_COND(6, bRCast);
  5428. SCORE_COND(7, uLSize < uRSize);
  5429. #undef SCORE_COND
  5430. // Make sure our scores fit in a UINT64.
  5431. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  5432. return uScore;
  5433. }
  5434. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  5435. DXASSERT(ics, "otherwise conversion has not been initialized");
  5436. if (!ics->isInitialized()) {
  5437. return 0;
  5438. }
  5439. if (!ics->isStandard()) {
  5440. return SCORE_MAX;
  5441. }
  5442. QualType fromType = ics->Standard.getFromType();
  5443. QualType toType = ics->Standard.getToType(2); // final type
  5444. return ScoreCast(toType, fromType);
  5445. }
  5446. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  5447. // Ignore target version mismatches.
  5448. // in/out considerations have been taken care of by viability.
  5449. // 'this' considerations don't matter without inheritance, other
  5450. // than lookup and viability.
  5451. UINT64 result = 0;
  5452. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  5453. UINT64 score;
  5454. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  5455. if (score == SCORE_MAX) {
  5456. return SCORE_MAX;
  5457. }
  5458. result += score;
  5459. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  5460. if (score == SCORE_MAX) {
  5461. return SCORE_MAX;
  5462. }
  5463. result += score;
  5464. }
  5465. return result;
  5466. }
  5467. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  5468. SourceLocation Loc,
  5469. OverloadCandidateSet& set,
  5470. OverloadCandidateSet::iterator& Best)
  5471. {
  5472. UINT64 bestScore = SCORE_MAX;
  5473. unsigned scoreMatch = 0;
  5474. Best = set.end();
  5475. if (set.size() == 1 && set.begin()->Viable) {
  5476. Best = set.begin();
  5477. return OR_Success;
  5478. }
  5479. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  5480. if (Cand->Viable) {
  5481. UINT64 score = ScoreFunction(Cand);
  5482. if (score != SCORE_MAX) {
  5483. if (score == bestScore) {
  5484. ++scoreMatch;
  5485. } else if (score < bestScore) {
  5486. Best = Cand;
  5487. scoreMatch = 1;
  5488. bestScore = score;
  5489. }
  5490. }
  5491. }
  5492. }
  5493. if (Best == set.end()) {
  5494. return OR_No_Viable_Function;
  5495. }
  5496. if (scoreMatch > 1) {
  5497. Best = set.end();
  5498. return OR_Ambiguous;
  5499. }
  5500. // No need to check for deleted functions to yield OR_Deleted.
  5501. return OR_Success;
  5502. }
  5503. /// <summary>
  5504. /// Initializes the specified <paramref name="initSequence" /> describing how
  5505. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  5506. /// </summary>
  5507. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  5508. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  5509. /// <param name="Args">Arguments to the initialization.</param>
  5510. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  5511. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  5512. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  5513. const InitializedEntity& Entity,
  5514. const InitializationKind& Kind,
  5515. MultiExprArg Args,
  5516. bool TopLevelOfInitList,
  5517. _Inout_ InitializationSequence* initSequence)
  5518. {
  5519. DXASSERT_NOMSG(initSequence != nullptr);
  5520. // In HLSL there are no default initializers, eg float4x4 m();
  5521. if (Kind.getKind() == InitializationKind::IK_Default) {
  5522. return;
  5523. }
  5524. // Value initializers occur for temporaries with empty parens or braces.
  5525. if (Kind.getKind() == InitializationKind::IK_Value) {
  5526. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  5527. SilenceSequenceDiagnostics(initSequence);
  5528. return;
  5529. }
  5530. // If we have a DirectList, we should have a single InitListExprClass argument.
  5531. DXASSERT(
  5532. Kind.getKind() != InitializationKind::IK_DirectList ||
  5533. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  5534. "otherwise caller is passing in incorrect initialization configuration");
  5535. bool isCast = Kind.isCStyleCast();
  5536. QualType destType = Entity.getType();
  5537. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  5538. // Direct initialization occurs for explicit constructor arguments.
  5539. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  5540. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  5541. !Kind.isCStyleOrFunctionalCast()) {
  5542. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  5543. SilenceSequenceDiagnostics(initSequence);
  5544. return;
  5545. }
  5546. bool flatten =
  5547. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  5548. Kind.getKind() == InitializationKind::IK_DirectList ||
  5549. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  5550. if (flatten) {
  5551. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  5552. // array types to adjust the value - we do calculate this as part of type analysis.
  5553. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  5554. FlattenedTypeIterator::ComparisonResult comparisonResult =
  5555. FlattenedTypeIterator::CompareTypesForInit(
  5556. *this, destType, Args,
  5557. Kind.getLocation(), Kind.getLocation());
  5558. if (comparisonResult.IsConvertibleAndEqualLength() ||
  5559. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  5560. {
  5561. initSequence->AddListInitializationStep(destType);
  5562. }
  5563. else
  5564. {
  5565. SourceLocation diagLocation;
  5566. if (Args.size() > 0)
  5567. {
  5568. diagLocation = Args.front()->getLocStart();
  5569. }
  5570. else
  5571. {
  5572. diagLocation = Entity.getDiagLoc();
  5573. }
  5574. m_sema->Diag(diagLocation,
  5575. diag::err_vector_incorrect_num_initializers)
  5576. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  5577. << comparisonResult.LeftCount << comparisonResult.RightCount;
  5578. SilenceSequenceDiagnostics(initSequence);
  5579. }
  5580. }
  5581. else {
  5582. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  5583. Expr* firstArg = Args.front();
  5584. if (IsExpressionBinaryComma(firstArg)) {
  5585. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  5586. }
  5587. ExprResult expr = ExprResult(firstArg);
  5588. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  5589. Sema::CheckedConversionKind::CCK_CStyleCast :
  5590. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  5591. unsigned int msg = 0;
  5592. CastKind castKind;
  5593. CXXCastPath basePath;
  5594. SourceRange range = Kind.getRange();
  5595. ImplicitConversionSequence ics;
  5596. ics.setStandard();
  5597. bool castWorked = TryStaticCastForHLSL(
  5598. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  5599. if (castWorked) {
  5600. if (destType.getCanonicalType() ==
  5601. firstArg->getType().getCanonicalType() &&
  5602. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  5603. initSequence->AddCAssignmentStep(destType);
  5604. } else {
  5605. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  5606. }
  5607. }
  5608. else {
  5609. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  5610. }
  5611. }
  5612. }
  5613. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5614. const QualType& sourceType,
  5615. const QualType& targetType,
  5616. bool explicitConversion)
  5617. {
  5618. DXASSERT_NOMSG(!sourceType.isNull());
  5619. DXASSERT_NOMSG(!targetType.isNull());
  5620. ArTypeInfo sourceTypeInfo;
  5621. ArTypeInfo targetTypeInfo;
  5622. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  5623. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  5624. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  5625. {
  5626. return false;
  5627. }
  5628. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  5629. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  5630. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  5631. !isVecMatTrunc)
  5632. {
  5633. return false;
  5634. }
  5635. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  5636. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  5637. return true;
  5638. }
  5639. // Same struct is eqaul.
  5640. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  5641. sourceType.getCanonicalType().getUnqualifiedType() ==
  5642. targetType.getCanonicalType().getUnqualifiedType()) {
  5643. return true;
  5644. }
  5645. // DerivedFrom is less.
  5646. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  5647. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  5648. const RecordType *targetRT = targetType->getAsStructureType();
  5649. if (!targetRT)
  5650. targetRT = dyn_cast<RecordType>(targetType);
  5651. const RecordType *sourceRT = sourceType->getAsStructureType();
  5652. if (!sourceRT)
  5653. sourceRT = dyn_cast<RecordType>(sourceType);
  5654. if (targetRT && sourceRT) {
  5655. RecordDecl *targetRD = targetRT->getDecl();
  5656. RecordDecl *sourceRD = sourceRT->getDecl();
  5657. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  5658. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  5659. if (targetCXXRD && sourceCXXRD) {
  5660. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  5661. return true;
  5662. }
  5663. }
  5664. }
  5665. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  5666. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  5667. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  5668. {
  5669. return false;
  5670. }
  5671. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  5672. }
  5673. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5674. const ExprResult& sourceExpr,
  5675. const QualType& targetType,
  5676. bool explicitConversion)
  5677. {
  5678. if (sourceExpr.isInvalid() || targetType.isNull())
  5679. {
  5680. return false;
  5681. }
  5682. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  5683. }
  5684. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  5685. {
  5686. DXASSERT_NOMSG(!type.isNull());
  5687. DXASSERT_NOMSG(count != nullptr);
  5688. *count = 0;
  5689. UINT subCount = 0;
  5690. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  5691. switch (shapeKind)
  5692. {
  5693. case AR_TOBJ_ARRAY:
  5694. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  5695. {
  5696. *count = subCount * GetArraySize(type);
  5697. return true;
  5698. }
  5699. return false;
  5700. case AR_TOBJ_COMPOUND:
  5701. {
  5702. UINT maxCount = 0;
  5703. { // Determine maximum count to prevent infinite loop on incomplete array
  5704. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  5705. maxCount = itCount.countRemaining();
  5706. if (!maxCount) {
  5707. return false; // empty struct.
  5708. }
  5709. }
  5710. FlattenedTypeIterator it(SourceLocation(), type, *this);
  5711. while (it.hasCurrentElement()) {
  5712. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  5713. if (!isFieldNumeric) {
  5714. return false;
  5715. }
  5716. if (*count >= maxCount) {
  5717. // this element is an incomplete array at the end; iterator will not advance past this element.
  5718. // don't add to *count either, so *count will represent minimum size of the structure.
  5719. break;
  5720. }
  5721. *count += (subCount * it.getCurrentElementSize());
  5722. it.advanceCurrentElement(it.getCurrentElementSize());
  5723. }
  5724. return true;
  5725. }
  5726. default:
  5727. DXASSERT(false, "unreachable");
  5728. case AR_TOBJ_BASIC:
  5729. case AR_TOBJ_MATRIX:
  5730. case AR_TOBJ_VECTOR:
  5731. *count = GetElementCount(type);
  5732. return IsBasicKindNumeric(GetTypeElementKind(type));
  5733. case AR_TOBJ_OBJECT:
  5734. return false;
  5735. }
  5736. }
  5737. enum MatrixMemberAccessError {
  5738. MatrixMemberAccessError_None, // No errors found.
  5739. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  5740. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  5741. MatrixMemberAccessError_Empty, // No members specified.
  5742. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  5743. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  5744. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  5745. };
  5746. static
  5747. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  5748. {
  5749. DXASSERT_NOMSG(memberText != nullptr);
  5750. DXASSERT_NOMSG(value != nullptr);
  5751. if ('0' <= *memberText && *memberText <= '9')
  5752. {
  5753. *value = (*memberText) - '0';
  5754. }
  5755. else
  5756. {
  5757. return MatrixMemberAccessError_BadFormat;
  5758. }
  5759. memberText++;
  5760. return MatrixMemberAccessError_None;
  5761. }
  5762. static
  5763. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  5764. {
  5765. DXASSERT_NOMSG(memberText != nullptr);
  5766. DXASSERT_NOMSG(value != nullptr);
  5767. MatrixMemberAccessPositions result;
  5768. bool zeroBasedDecided = false;
  5769. bool zeroBased = false;
  5770. // Set the output value to invalid to allow early exits when errors are found.
  5771. value->IsValid = 0;
  5772. // Assume this is true until proven otherwise.
  5773. result.IsValid = 1;
  5774. result.Count = 0;
  5775. while (*memberText)
  5776. {
  5777. // Check for a leading underscore.
  5778. if (*memberText != '_')
  5779. {
  5780. return MatrixMemberAccessError_BadFormat;
  5781. }
  5782. ++memberText;
  5783. // Check whether we have an 'm' or a digit.
  5784. if (*memberText == 'm')
  5785. {
  5786. if (zeroBasedDecided && !zeroBased)
  5787. {
  5788. return MatrixMemberAccessError_MixingRefs;
  5789. }
  5790. zeroBased = true;
  5791. zeroBasedDecided = true;
  5792. ++memberText;
  5793. }
  5794. else if (!('0' <= *memberText && *memberText <= '9'))
  5795. {
  5796. return MatrixMemberAccessError_BadFormat;
  5797. }
  5798. else
  5799. {
  5800. if (zeroBasedDecided && zeroBased)
  5801. {
  5802. return MatrixMemberAccessError_MixingRefs;
  5803. }
  5804. zeroBased = false;
  5805. zeroBasedDecided = true;
  5806. }
  5807. // Consume two digits for the position.
  5808. uint32_t rowPosition;
  5809. uint32_t colPosition;
  5810. MatrixMemberAccessError digitError;
  5811. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  5812. {
  5813. return digitError;
  5814. }
  5815. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  5816. {
  5817. return digitError;
  5818. }
  5819. // Look for specific common errors (developer likely mixed up reference style).
  5820. if (zeroBased)
  5821. {
  5822. if (rowPosition == 4 || colPosition == 4)
  5823. {
  5824. return MatrixMemberAccessError_FourInZeroBased;
  5825. }
  5826. }
  5827. else
  5828. {
  5829. if (rowPosition == 0 || colPosition == 0)
  5830. {
  5831. return MatrixMemberAccessError_ZeroInOneBased;
  5832. }
  5833. // SetPosition will use zero-based indices.
  5834. --rowPosition;
  5835. --colPosition;
  5836. }
  5837. if (result.Count == 4)
  5838. {
  5839. return MatrixMemberAccessError_TooManyPositions;
  5840. }
  5841. result.SetPosition(result.Count, rowPosition, colPosition);
  5842. result.Count++;
  5843. }
  5844. if (result.Count == 0)
  5845. {
  5846. return MatrixMemberAccessError_Empty;
  5847. }
  5848. *value = result;
  5849. return MatrixMemberAccessError_None;
  5850. }
  5851. bool HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  5852. Expr& BaseExpr,
  5853. DeclarationName MemberName,
  5854. bool IsArrow,
  5855. SourceLocation OpLoc,
  5856. SourceLocation MemberLoc,
  5857. ExprResult* result)
  5858. {
  5859. DXASSERT_NOMSG(result != nullptr);
  5860. QualType BaseType = BaseExpr.getType();
  5861. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  5862. // Assume failure.
  5863. *result = ExprError();
  5864. if (GetTypeObjectKind(BaseType) != AR_TOBJ_MATRIX)
  5865. {
  5866. return false;
  5867. }
  5868. QualType elementType;
  5869. UINT rowCount, colCount;
  5870. GetRowsAndCols(BaseType, rowCount, colCount);
  5871. elementType = GetMatrixOrVectorElementType(BaseType);
  5872. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  5873. const char *memberText = member->getNameStart();
  5874. MatrixMemberAccessPositions positions;
  5875. MatrixMemberAccessError memberAccessError;
  5876. unsigned msg = 0;
  5877. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  5878. switch (memberAccessError)
  5879. {
  5880. case MatrixMemberAccessError_BadFormat:
  5881. msg = diag::err_hlsl_matrix_member_bad_format;
  5882. break;
  5883. case MatrixMemberAccessError_Empty:
  5884. msg = diag::err_hlsl_matrix_member_empty;
  5885. break;
  5886. case MatrixMemberAccessError_FourInZeroBased:
  5887. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  5888. break;
  5889. case MatrixMemberAccessError_MixingRefs:
  5890. msg = diag::err_hlsl_matrix_member_mixing_refs;
  5891. break;
  5892. case MatrixMemberAccessError_None:
  5893. msg = 0;
  5894. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5895. // Check the position with the type now.
  5896. for (unsigned int i = 0; i < positions.Count; i++)
  5897. {
  5898. uint32_t rowPos, colPos;
  5899. positions.GetPosition(i, &rowPos, &colPos);
  5900. if (rowPos >= rowCount || colPos >= colCount)
  5901. {
  5902. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  5903. break;
  5904. }
  5905. }
  5906. break;
  5907. case MatrixMemberAccessError_TooManyPositions:
  5908. msg = diag::err_hlsl_matrix_member_too_many_positions;
  5909. break;
  5910. case MatrixMemberAccessError_ZeroInOneBased:
  5911. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  5912. break;
  5913. default:
  5914. llvm_unreachable("Unknown MatrixMemberAccessError value");
  5915. }
  5916. if (msg != 0)
  5917. {
  5918. m_sema->Diag(MemberLoc, msg) << memberText;
  5919. // It's possible that it's a simple out-of-bounds condition. In this case,
  5920. // generate the member access expression with the correct arity and continue
  5921. // processing.
  5922. if (!positions.IsValid)
  5923. {
  5924. return true;
  5925. }
  5926. }
  5927. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5928. // Consume elements
  5929. QualType resultType;
  5930. if (positions.Count == 1)
  5931. resultType = elementType;
  5932. else
  5933. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  5934. // Add qualifiers from BaseType.
  5935. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  5936. ExprValueKind VK =
  5937. positions.ContainsDuplicateElements() ? VK_RValue :
  5938. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  5939. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  5940. *result = matrixExpr;
  5941. return true;
  5942. }
  5943. enum VectorMemberAccessError {
  5944. VectorMemberAccessError_None, // No errors found.
  5945. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  5946. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  5947. VectorMemberAccessError_Empty, // No members specified.
  5948. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  5949. };
  5950. static
  5951. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  5952. DXASSERT_NOMSG(memberText != nullptr);
  5953. DXASSERT_NOMSG(value != nullptr);
  5954. rgbaStyle = false;
  5955. switch (*memberText) {
  5956. case 'r':
  5957. rgbaStyle = true;
  5958. case 'x':
  5959. *value = 0;
  5960. break;
  5961. case 'g':
  5962. rgbaStyle = true;
  5963. case 'y':
  5964. *value = 1;
  5965. break;
  5966. case 'b':
  5967. rgbaStyle = true;
  5968. case 'z':
  5969. *value = 2;
  5970. break;
  5971. case 'a':
  5972. rgbaStyle = true;
  5973. case 'w':
  5974. *value = 3;
  5975. break;
  5976. default:
  5977. return VectorMemberAccessError_BadFormat;
  5978. }
  5979. memberText++;
  5980. return VectorMemberAccessError_None;
  5981. }
  5982. static
  5983. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  5984. DXASSERT_NOMSG(memberText != nullptr);
  5985. DXASSERT_NOMSG(value != nullptr);
  5986. VectorMemberAccessPositions result;
  5987. bool rgbaStyleDecided = false;
  5988. bool rgbaStyle = false;
  5989. // Set the output value to invalid to allow early exits when errors are found.
  5990. value->IsValid = 0;
  5991. // Assume this is true until proven otherwise.
  5992. result.IsValid = 1;
  5993. result.Count = 0;
  5994. while (*memberText) {
  5995. // Consume one character for the swizzle.
  5996. uint32_t colPosition;
  5997. VectorMemberAccessError digitError;
  5998. bool rgbaStyleTmp = false;
  5999. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6000. return digitError;
  6001. }
  6002. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6003. return VectorMemberAccessError_MixingStyles;
  6004. }
  6005. else {
  6006. rgbaStyleDecided = true;
  6007. rgbaStyle = rgbaStyleTmp;
  6008. }
  6009. if (result.Count == 4) {
  6010. return VectorMemberAccessError_TooManyPositions;
  6011. }
  6012. result.SetPosition(result.Count, colPosition);
  6013. result.Count++;
  6014. }
  6015. if (result.Count == 0) {
  6016. return VectorMemberAccessError_Empty;
  6017. }
  6018. *value = result;
  6019. return VectorMemberAccessError_None;
  6020. }
  6021. bool HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6022. Expr& BaseExpr,
  6023. DeclarationName MemberName,
  6024. bool IsArrow,
  6025. SourceLocation OpLoc,
  6026. SourceLocation MemberLoc,
  6027. ExprResult* result) {
  6028. DXASSERT_NOMSG(result != nullptr);
  6029. QualType BaseType = BaseExpr.getType();
  6030. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6031. // Assume failure.
  6032. *result = ExprError();
  6033. if (GetTypeObjectKind(BaseType) != AR_TOBJ_VECTOR) {
  6034. return false;
  6035. }
  6036. QualType elementType;
  6037. UINT colCount = GetHLSLVecSize(BaseType);
  6038. elementType = GetMatrixOrVectorElementType(BaseType);
  6039. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6040. const char *memberText = member->getNameStart();
  6041. VectorMemberAccessPositions positions;
  6042. VectorMemberAccessError memberAccessError;
  6043. unsigned msg = 0;
  6044. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6045. switch (memberAccessError) {
  6046. case VectorMemberAccessError_BadFormat:
  6047. msg = diag::err_hlsl_vector_member_bad_format;
  6048. break;
  6049. case VectorMemberAccessError_Empty:
  6050. msg = diag::err_hlsl_vector_member_empty;
  6051. break;
  6052. case VectorMemberAccessError_MixingStyles:
  6053. msg = diag::err_ext_vector_component_name_mixedsets;
  6054. break;
  6055. case VectorMemberAccessError_None:
  6056. msg = 0;
  6057. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6058. // Check the position with the type now.
  6059. for (unsigned int i = 0; i < positions.Count; i++) {
  6060. uint32_t colPos;
  6061. positions.GetPosition(i, &colPos);
  6062. if (colPos >= colCount) {
  6063. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6064. break;
  6065. }
  6066. }
  6067. break;
  6068. case VectorMemberAccessError_TooManyPositions:
  6069. msg = diag::err_hlsl_vector_member_too_many_positions;
  6070. break;
  6071. default:
  6072. llvm_unreachable("Unknown VectorMemberAccessError value");
  6073. }
  6074. if (msg != 0) {
  6075. m_sema->Diag(MemberLoc, msg) << memberText;
  6076. // It's possible that it's a simple out-of-bounds condition. In this case,
  6077. // generate the member access expression with the correct arity and continue
  6078. // processing.
  6079. if (!positions.IsValid) {
  6080. return true;
  6081. }
  6082. }
  6083. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6084. // Consume elements
  6085. QualType resultType;
  6086. if (positions.Count == 1)
  6087. resultType = elementType;
  6088. else
  6089. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6090. // Add qualifiers from BaseType.
  6091. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6092. ExprValueKind VK =
  6093. positions.ContainsDuplicateElements() ? VK_RValue :
  6094. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6095. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6096. *result = vectorExpr;
  6097. return true;
  6098. }
  6099. ExprResult HLSLExternalSource::MaybeConvertScalarToVector(_In_ clang::Expr* E) {
  6100. DXASSERT_NOMSG(E != nullptr);
  6101. ArBasicKind basic = GetTypeElementKind(E->getType());
  6102. if (!IS_BASIC_PRIMITIVE(basic)) {
  6103. return E;
  6104. }
  6105. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  6106. if (kind != AR_TOBJ_SCALAR) {
  6107. return E;
  6108. }
  6109. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  6110. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  6111. }
  6112. static clang::CastKind ImplicitConversionKindToCastKind(
  6113. clang::ImplicitConversionKind ICK,
  6114. ArBasicKind FromKind,
  6115. ArBasicKind ToKind) {
  6116. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  6117. // based on from/to kinds in order to determine CastKind?
  6118. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  6119. // problem.
  6120. switch (ICK) {
  6121. case ICK_Integral_Promotion:
  6122. case ICK_Integral_Conversion:
  6123. return CK_IntegralCast;
  6124. case ICK_Floating_Promotion:
  6125. case ICK_Floating_Conversion:
  6126. return CK_FloatingCast;
  6127. case ICK_Floating_Integral:
  6128. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  6129. return CK_FloatingToIntegral;
  6130. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  6131. return CK_IntegralToFloating;
  6132. break;
  6133. case ICK_Boolean_Conversion:
  6134. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  6135. return CK_FloatingToBoolean;
  6136. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  6137. return CK_IntegralToBoolean;
  6138. break;
  6139. }
  6140. return CK_Invalid;
  6141. }
  6142. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  6143. switch (CK) {
  6144. case CK_IntegralCast:
  6145. return CK_HLSLCC_IntegralCast;
  6146. case CK_FloatingCast:
  6147. return CK_HLSLCC_FloatingCast;
  6148. case CK_FloatingToIntegral:
  6149. return CK_HLSLCC_FloatingToIntegral;
  6150. case CK_IntegralToFloating:
  6151. return CK_HLSLCC_IntegralToFloating;
  6152. case CK_FloatingToBoolean:
  6153. return CK_HLSLCC_FloatingToBoolean;
  6154. case CK_IntegralToBoolean:
  6155. return CK_HLSLCC_IntegralToBoolean;
  6156. }
  6157. return CK_Invalid;
  6158. }
  6159. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  6160. _In_ clang::Sema* self,
  6161. _In_ clang::Expr* From,
  6162. ArTypeObjectKind FromShape,
  6163. ArBasicKind EltKind)
  6164. {
  6165. clang::CastKind CK = CK_Invalid;
  6166. if (AR_TOBJ_MATRIX == FromShape)
  6167. CK = CK_HLSLMatrixToScalarCast;
  6168. if (AR_TOBJ_VECTOR == FromShape)
  6169. CK = CK_HLSLVectorToScalarCast;
  6170. if (CK_Invalid != CK) {
  6171. return self->ImpCastExprToType(From,
  6172. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  6173. }
  6174. return From;
  6175. }
  6176. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  6177. _In_ clang::Expr* From,
  6178. _In_ clang::QualType targetType,
  6179. _In_ const clang::StandardConversionSequence &SCS,
  6180. _In_ clang::Sema::CheckedConversionKind CCK)
  6181. {
  6182. QualType sourceType = From->getType();
  6183. sourceType = GetStructuralForm(sourceType);
  6184. targetType = GetStructuralForm(targetType);
  6185. ArTypeInfo SourceInfo, TargetInfo;
  6186. CollectInfo(sourceType, &SourceInfo);
  6187. CollectInfo(targetType, &TargetInfo);
  6188. clang::CastKind CK = CK_Invalid;
  6189. QualType intermediateTarget;
  6190. // TODO: construct vector/matrix and component cast expressions
  6191. switch (SCS.Second) {
  6192. case ICK_Flat_Conversion: {
  6193. // TODO: determine how to handle individual component conversions:
  6194. // - have an array of conversions for ComponentConversion in SCS?
  6195. // convert that to an array of casts under a special kind of flat
  6196. // flat conversion node? What do component conversion casts cast
  6197. // from? We don't have a From expression for individiual components.
  6198. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6199. break;
  6200. }
  6201. case ICK_HLSL_Derived_To_Base: {
  6202. CXXCastPath BasePath;
  6203. if (m_sema->CheckDerivedToBaseConversion(
  6204. sourceType, targetType.getNonReferenceType(), From->getLocStart(),
  6205. From->getSourceRange(), &BasePath, /*IgnoreAccess=*/true))
  6206. return ExprError();
  6207. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), &BasePath, CCK).get();
  6208. break;
  6209. }
  6210. case ICK_HLSLVector_Splat: {
  6211. // 1. optionally convert from vec1 or mat1x1 to scalar
  6212. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6213. // 2. optionally convert component type
  6214. if (ICK_Identity != SCS.ComponentConversion) {
  6215. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6216. if (CK_Invalid != CK) {
  6217. From = m_sema->ImpCastExprToType(From,
  6218. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6219. }
  6220. }
  6221. // 3. splat scalar to final vector or matrix
  6222. CK = CK_Invalid;
  6223. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  6224. CK = CK_HLSLVectorSplat;
  6225. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  6226. CK = CK_HLSLMatrixSplat;
  6227. if (CK_Invalid != CK) {
  6228. From = m_sema->ImpCastExprToType(From,
  6229. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6230. }
  6231. break;
  6232. }
  6233. case ICK_HLSLVector_Scalar: {
  6234. // 1. select vector or matrix component
  6235. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6236. // 2. optionally convert component type
  6237. if (ICK_Identity != SCS.ComponentConversion) {
  6238. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6239. if (CK_Invalid != CK) {
  6240. From = m_sema->ImpCastExprToType(From,
  6241. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6242. }
  6243. }
  6244. break;
  6245. }
  6246. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  6247. // can be done with case fall-through, since this is the order in which we want to
  6248. // do the conversion operations.
  6249. case ICK_HLSLVector_Truncation: {
  6250. // 1. dimension truncation
  6251. // vector truncation or matrix truncation?
  6252. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  6253. From = m_sema->ImpCastExprToType(From,
  6254. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  6255. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6256. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  6257. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  6258. // Handle the column to vector case
  6259. From = m_sema->ImpCastExprToType(From,
  6260. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  6261. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6262. } else {
  6263. From = m_sema->ImpCastExprToType(From,
  6264. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6265. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6266. }
  6267. } else {
  6268. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  6269. }
  6270. }
  6271. __fallthrough;
  6272. case ICK_HLSLVector_Conversion: {
  6273. // 2. Do ShapeKind conversion if necessary
  6274. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  6275. switch (TargetInfo.ShapeKind) {
  6276. case AR_TOBJ_VECTOR:
  6277. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6278. From = m_sema->ImpCastExprToType(From,
  6279. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6280. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6281. break;
  6282. case AR_TOBJ_MATRIX:
  6283. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6284. From = m_sema->ImpCastExprToType(From,
  6285. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6286. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6287. break;
  6288. case AR_TOBJ_BASIC:
  6289. // Truncation may be followed by cast to scalar
  6290. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6291. break;
  6292. default:
  6293. DXASSERT(false, "otherwise, invalid casting sequence");
  6294. break;
  6295. }
  6296. }
  6297. // 3. Do component type conversion
  6298. if (ICK_Identity != SCS.ComponentConversion) {
  6299. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6300. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  6301. CK = ConvertToComponentCastKind(CK);
  6302. if (CK_Invalid != CK) {
  6303. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6304. }
  6305. }
  6306. break;
  6307. }
  6308. case ICK_Identity:
  6309. // Nothing to do.
  6310. break;
  6311. default:
  6312. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  6313. }
  6314. return From;
  6315. }
  6316. void HLSLExternalSource::GetConversionForm(
  6317. QualType type,
  6318. bool explicitConversion,
  6319. ArTypeInfo* pTypeInfo)
  6320. {
  6321. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  6322. CollectInfo(type, pTypeInfo);
  6323. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  6324. // but that value is only used for pointer conversions.
  6325. // When explicitly converting types complex aggregates can be treated
  6326. // as vectors if they are entirely numeric.
  6327. switch (pTypeInfo->ShapeKind)
  6328. {
  6329. case AR_TOBJ_COMPOUND:
  6330. case AR_TOBJ_ARRAY:
  6331. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  6332. {
  6333. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  6334. }
  6335. else
  6336. {
  6337. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  6338. }
  6339. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  6340. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  6341. break;
  6342. case AR_TOBJ_VECTOR:
  6343. case AR_TOBJ_MATRIX:
  6344. // Convert 1x1 types to scalars.
  6345. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  6346. {
  6347. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  6348. }
  6349. break;
  6350. }
  6351. }
  6352. static
  6353. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  6354. {
  6355. DXASSERT_NOMSG(allowed != nullptr);
  6356. bool applicable = true;
  6357. *allowed = true;
  6358. if (explicitConversion) {
  6359. // (void) non-void
  6360. if (target->isVoidType()) {
  6361. DXASSERT_NOMSG(*allowed);
  6362. }
  6363. // (non-void) void
  6364. else if (source->isVoidType()) {
  6365. *allowed = false;
  6366. }
  6367. else {
  6368. applicable = false;
  6369. }
  6370. }
  6371. else {
  6372. // (void) void
  6373. if (source->isVoidType() && target->isVoidType()) {
  6374. DXASSERT_NOMSG(*allowed);
  6375. }
  6376. // (void) non-void, (non-void) void
  6377. else if (source->isVoidType() || target->isVoidType()) {
  6378. *allowed = false;
  6379. }
  6380. else {
  6381. applicable = false;
  6382. }
  6383. }
  6384. return applicable;
  6385. }
  6386. _Use_decl_annotations_
  6387. bool HLSLExternalSource::CanConvert(
  6388. SourceLocation loc,
  6389. Expr* sourceExpr,
  6390. QualType target,
  6391. bool explicitConversion,
  6392. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  6393. _Inout_opt_ StandardConversionSequence* standard)
  6394. {
  6395. DXASSERT_NOMSG(sourceExpr != nullptr);
  6396. DXASSERT_NOMSG(!target.isNull());
  6397. // Implements the semantics of ArType::CanConvertTo.
  6398. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  6399. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  6400. QualType source = sourceExpr->getType();
  6401. // Cannot cast function type.
  6402. if (source->isFunctionType())
  6403. return false;
  6404. // Convert to an r-value to begin with.
  6405. bool needsLValueToRValue = sourceExpr->isLValue() &&
  6406. !target->isLValueReferenceType() &&
  6407. IsConversionToLessOrEqualElements(source, target, explicitConversion);
  6408. bool targetRef = target->isReferenceType();
  6409. // Initialize the output standard sequence if available.
  6410. if (standard != nullptr) {
  6411. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  6412. standard->setAsIdentityConversion();
  6413. if (needsLValueToRValue) {
  6414. standard->First = ICK_Lvalue_To_Rvalue;
  6415. }
  6416. standard->setFromType(source);
  6417. standard->setAllToTypes(target);
  6418. }
  6419. source = GetStructuralForm(source);
  6420. target = GetStructuralForm(target);
  6421. // Temporary conversion kind tracking which will be used/fixed up at the end
  6422. ImplicitConversionKind Second = ICK_Identity;
  6423. ImplicitConversionKind ComponentConversion = ICK_Identity;
  6424. // Identical types require no conversion.
  6425. if (source == target) {
  6426. Remarks = TYPE_CONVERSION_IDENTICAL;
  6427. goto lSuccess;
  6428. }
  6429. // Trivial cases for void.
  6430. bool allowed;
  6431. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  6432. if (allowed) {
  6433. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  6434. goto lSuccess;
  6435. }
  6436. else {
  6437. return false;
  6438. }
  6439. }
  6440. ArTypeInfo TargetInfo, SourceInfo;
  6441. CollectInfo(target, &TargetInfo);
  6442. CollectInfo(source, &SourceInfo);
  6443. UINT uTSize = TargetInfo.uTotalElts;
  6444. UINT uSSize = SourceInfo.uTotalElts;
  6445. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  6446. // are we missing cases?
  6447. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  6448. return false;
  6449. }
  6450. // Structure cast.
  6451. if (TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY ||
  6452. SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY) {
  6453. if (!explicitConversion && TargetInfo.ShapeKind != SourceInfo.ShapeKind)
  6454. {
  6455. return false;
  6456. }
  6457. const RecordType *targetRT = target->getAsStructureType();
  6458. if (!targetRT)
  6459. targetRT = dyn_cast<RecordType>(target);
  6460. const RecordType *sourceRT = source->getAsStructureType();
  6461. if (!sourceRT)
  6462. sourceRT = dyn_cast<RecordType>(source);
  6463. if (targetRT && sourceRT) {
  6464. RecordDecl *targetRD = targetRT->getDecl();
  6465. RecordDecl *sourceRD = sourceRT->getDecl();
  6466. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6467. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6468. if (targetCXXRD && sourceCXXRD) {
  6469. if (targetRD == sourceRD) {
  6470. Second = ICK_Flat_Conversion;
  6471. goto lSuccess;
  6472. }
  6473. if (sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  6474. Second = ICK_HLSL_Derived_To_Base;
  6475. goto lSuccess;
  6476. }
  6477. } else {
  6478. if (targetRD == sourceRD) {
  6479. Second = ICK_Flat_Conversion;
  6480. goto lSuccess;
  6481. }
  6482. }
  6483. }
  6484. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  6485. BuiltinType::Kind kind = BT->getKind();
  6486. switch (kind) {
  6487. case BuiltinType::Kind::UInt:
  6488. case BuiltinType::Kind::Int:
  6489. case BuiltinType::Kind::Float:
  6490. case BuiltinType::Kind::LitFloat:
  6491. case BuiltinType::Kind::LitInt:
  6492. if (explicitConversion) {
  6493. Second = ICK_Flat_Conversion;
  6494. goto lSuccess;
  6495. }
  6496. break;
  6497. }
  6498. }
  6499. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  6500. BuiltinType::Kind kind = BT->getKind();
  6501. switch (kind) {
  6502. case BuiltinType::Kind::UInt:
  6503. case BuiltinType::Kind::Int:
  6504. case BuiltinType::Kind::Float:
  6505. case BuiltinType::Kind::LitFloat:
  6506. case BuiltinType::Kind::LitInt:
  6507. if (explicitConversion) {
  6508. Second = ICK_Flat_Conversion;
  6509. goto lSuccess;
  6510. }
  6511. break;
  6512. }
  6513. }
  6514. FlattenedTypeIterator::ComparisonResult result =
  6515. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  6516. if (!result.CanConvertElements) {
  6517. return false;
  6518. }
  6519. // Only allow scalar to compound or array with explicit cast
  6520. if (result.IsConvertibleAndLeftLonger()) {
  6521. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  6522. return false;
  6523. }
  6524. }
  6525. // Assignment is valid if elements are exactly the same in type and size; if
  6526. // an explicit conversion is being done, we accept converted elements and a
  6527. // longer right-hand sequence.
  6528. if (!explicitConversion &&
  6529. (!result.AreElementsEqual || result.IsRightLonger()))
  6530. {
  6531. return false;
  6532. }
  6533. Second = ICK_Flat_Conversion;
  6534. goto lSuccess;
  6535. }
  6536. // Base type cast.
  6537. //
  6538. // The rules for aggregate conversions are:
  6539. // 1. A scalar can be replicated to any layout.
  6540. // 2. The result of two vectors is the smaller vector.
  6541. // 3. The result of two matrices is the smaller matrix.
  6542. // 4. The result of a vector and a matrix is:
  6543. // a. If the matrix has one row it's a vector-sized
  6544. // piece of the row.
  6545. // b. If the matrix has one column it's a vector-sized
  6546. // piece of the column.
  6547. // c. Otherwise the number of elements in the vector
  6548. // and matrix must match and the result is the vector.
  6549. // 5. The result of a matrix and a vector is similar to #4.
  6550. //
  6551. bool bCheckElt = false;
  6552. switch (TargetInfo.ShapeKind) {
  6553. case AR_TOBJ_BASIC:
  6554. switch (SourceInfo.ShapeKind)
  6555. {
  6556. case AR_TOBJ_BASIC:
  6557. Second = ICK_Identity;
  6558. break;
  6559. case AR_TOBJ_VECTOR:
  6560. if(1 < SourceInfo.uCols)
  6561. Second = ICK_HLSLVector_Truncation;
  6562. else
  6563. Second = ICK_HLSLVector_Scalar;
  6564. break;
  6565. case AR_TOBJ_MATRIX:
  6566. if(1 < SourceInfo.uRows * SourceInfo.uCols)
  6567. Second = ICK_HLSLVector_Truncation;
  6568. else
  6569. Second = ICK_HLSLVector_Scalar;
  6570. break;
  6571. case AR_TOBJ_OBJECT:
  6572. case AR_TOBJ_INTERFACE:
  6573. case AR_TOBJ_POINTER:
  6574. return false;
  6575. }
  6576. bCheckElt = true;
  6577. break;
  6578. case AR_TOBJ_VECTOR:
  6579. switch (SourceInfo.ShapeKind)
  6580. {
  6581. case AR_TOBJ_BASIC:
  6582. // Conversions between scalars and aggregates are always supported.
  6583. Second = ICK_HLSLVector_Splat;
  6584. break;
  6585. case AR_TOBJ_VECTOR:
  6586. if (TargetInfo.uCols > SourceInfo.uCols) {
  6587. if (SourceInfo.uCols == 1) {
  6588. Second = ICK_HLSLVector_Splat;
  6589. } else {
  6590. return false;
  6591. }
  6592. } else if (TargetInfo.uCols < SourceInfo.uCols) {
  6593. Second = ICK_HLSLVector_Truncation;
  6594. } else {
  6595. Second = ICK_Identity;
  6596. }
  6597. break;
  6598. case AR_TOBJ_MATRIX: {
  6599. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6600. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  6601. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  6602. Second = ICK_HLSLVector_Splat;
  6603. } else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  6604. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  6605. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  6606. return false;
  6607. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  6608. Second = ICK_HLSLVector_Truncation;
  6609. else // equalivalent: O == N*M
  6610. Second = ICK_HLSLVector_Conversion;
  6611. } else if (TargetInfo.uCols != SourceComponents) {
  6612. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  6613. return false;
  6614. } else {
  6615. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  6616. Second = ICK_HLSLVector_Conversion;
  6617. }
  6618. break;
  6619. }
  6620. case AR_TOBJ_OBJECT:
  6621. case AR_TOBJ_INTERFACE:
  6622. case AR_TOBJ_POINTER:
  6623. return false;
  6624. }
  6625. bCheckElt = true;
  6626. break;
  6627. case AR_TOBJ_MATRIX: {
  6628. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  6629. switch (SourceInfo.ShapeKind)
  6630. {
  6631. case AR_TOBJ_BASIC:
  6632. // Conversions between scalars and aggregates are always supported.
  6633. Second = ICK_HLSLVector_Splat;
  6634. break;
  6635. case AR_TOBJ_VECTOR: {
  6636. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  6637. // splat: vector<[..], 1> -> matrix<[..], M, N>
  6638. Second = ICK_HLSLVector_Splat;
  6639. } else if (1 == TargetInfo.uRows || 1 == TargetInfo.uCols) {
  6640. // cases for: vector<[..], O> -> matrix<[..], N, M>, where N == 1 or M == 1
  6641. if (TargetComponents > SourceInfo.uCols) // illegal: N*M > O
  6642. return false;
  6643. else if (TargetComponents < SourceInfo.uCols) // truncation: N*M < O
  6644. Second = ICK_HLSLVector_Truncation;
  6645. else // equalivalent: N*M == O
  6646. Second = ICK_HLSLVector_Conversion;
  6647. } else if (TargetComponents != SourceInfo.uCols) {
  6648. // illegal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O != N*M
  6649. return false;
  6650. } else {
  6651. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  6652. Second = ICK_HLSLVector_Conversion;
  6653. }
  6654. break;
  6655. }
  6656. case AR_TOBJ_MATRIX: {
  6657. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6658. if (1 == SourceComponents && TargetComponents != 1) {
  6659. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  6660. Second = ICK_HLSLVector_Splat;
  6661. } else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  6662. return false;
  6663. } else if(TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  6664. Second = ICK_HLSLVector_Truncation;
  6665. } else {
  6666. Second = ICK_Identity;
  6667. }
  6668. break;
  6669. }
  6670. case AR_TOBJ_OBJECT:
  6671. case AR_TOBJ_INTERFACE:
  6672. case AR_TOBJ_POINTER:
  6673. return false;
  6674. }
  6675. bCheckElt = true;
  6676. break;
  6677. }
  6678. case AR_TOBJ_OBJECT:
  6679. // There are no compatible object assignments that aren't
  6680. // from one type to itself, which is already covered.
  6681. DXASSERT(source != target, "otherwise trivial case was not checked by this function");
  6682. return false;
  6683. default:
  6684. DXASSERT_NOMSG(false);
  6685. return false;
  6686. }
  6687. if (bCheckElt)
  6688. {
  6689. bool precisionLoss = false;
  6690. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  6691. GET_BASIC_BITS(TargetInfo.EltKind) <
  6692. GET_BASIC_BITS(SourceInfo.EltKind))
  6693. {
  6694. precisionLoss = true;
  6695. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  6696. }
  6697. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  6698. {
  6699. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  6700. }
  6701. // enum -> enum not allowed
  6702. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  6703. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  6704. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  6705. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  6706. return false;
  6707. }
  6708. if (SourceInfo.EltKind != TargetInfo.EltKind)
  6709. {
  6710. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  6711. SourceInfo.EltKind == AR_BASIC_UNKNOWN)
  6712. {
  6713. Second = ICK_Flat_Conversion;
  6714. }
  6715. else if (IS_BASIC_BOOL(TargetInfo.EltKind))
  6716. {
  6717. ComponentConversion = ICK_Boolean_Conversion;
  6718. }
  6719. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  6720. {
  6721. // conversion to enum type not allowed
  6722. return false;
  6723. }
  6724. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  6725. {
  6726. // enum -> int/float
  6727. ComponentConversion = ICK_Integral_Conversion;
  6728. }
  6729. else
  6730. {
  6731. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  6732. if (IS_BASIC_AINT(SourceInfo.EltKind))
  6733. {
  6734. if (targetIsInt)
  6735. {
  6736. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  6737. }
  6738. else
  6739. {
  6740. ComponentConversion = ICK_Floating_Integral;
  6741. }
  6742. }
  6743. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  6744. {
  6745. DXASSERT(IS_BASIC_FLOAT(SourceInfo.EltKind), "otherwise should not be checking element types");
  6746. if (targetIsInt)
  6747. {
  6748. ComponentConversion = ICK_Floating_Integral;
  6749. }
  6750. else
  6751. {
  6752. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  6753. }
  6754. } else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  6755. if (targetIsInt)
  6756. ComponentConversion = ICK_Integral_Conversion;
  6757. else
  6758. ComponentConversion = ICK_Floating_Integral;
  6759. }
  6760. }
  6761. }
  6762. }
  6763. lSuccess:
  6764. if (standard)
  6765. {
  6766. if (sourceExpr->isLValue())
  6767. {
  6768. if (needsLValueToRValue) {
  6769. // We don't need LValueToRValue cast before casting a derived object
  6770. // to its base.
  6771. if (Second == ICK_HLSL_Derived_To_Base) {
  6772. standard->First = ICK_Identity;
  6773. } else {
  6774. standard->First = ICK_Lvalue_To_Rvalue;
  6775. }
  6776. } else {
  6777. switch (Second)
  6778. {
  6779. case ICK_NoReturn_Adjustment:
  6780. case ICK_Vector_Conversion:
  6781. case ICK_Vector_Splat:
  6782. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  6783. case ICK_Flat_Conversion:
  6784. case ICK_HLSLVector_Splat:
  6785. standard->First = ICK_Lvalue_To_Rvalue;
  6786. break;
  6787. }
  6788. switch (ComponentConversion)
  6789. {
  6790. case ICK_Integral_Promotion:
  6791. case ICK_Integral_Conversion:
  6792. case ICK_Floating_Promotion:
  6793. case ICK_Floating_Conversion:
  6794. case ICK_Floating_Integral:
  6795. case ICK_Boolean_Conversion:
  6796. standard->First = ICK_Lvalue_To_Rvalue;
  6797. break;
  6798. }
  6799. }
  6800. }
  6801. // Finally fix up the cases for scalar->scalar component conversion, and
  6802. // identity vector/matrix component conversion
  6803. if (ICK_Identity != ComponentConversion) {
  6804. if (Second == ICK_Identity) {
  6805. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  6806. // Scalar to scalar type conversion, use normal mechanism (Second)
  6807. Second = ComponentConversion;
  6808. ComponentConversion = ICK_Identity;
  6809. } else {
  6810. // vector or matrix dimensions are not being changed, but component type
  6811. // is being converted, so change Second to signal the conversion
  6812. Second = ICK_HLSLVector_Conversion;
  6813. }
  6814. }
  6815. }
  6816. standard->Second = Second;
  6817. standard->ComponentConversion = ComponentConversion;
  6818. // For conversion which change to RValue but targeting reference type
  6819. // Hold the conversion to codeGen
  6820. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  6821. standard->First = ICK_Identity;
  6822. standard->Second = ICK_Identity;
  6823. }
  6824. }
  6825. AssignOpt(Remarks, remarks);
  6826. return true;
  6827. }
  6828. Expr* HLSLExternalSource::CastExprToTypeNumeric(Expr* expr, QualType type)
  6829. {
  6830. DXASSERT_NOMSG(expr != nullptr);
  6831. DXASSERT_NOMSG(!type.isNull());
  6832. if (expr->getType() != type) {
  6833. StandardConversionSequence standard;
  6834. if (CanConvert(SourceLocation(), expr, type, /*explicitConversion*/false, nullptr, &standard) &&
  6835. (standard.First != ICK_Identity || !standard.isIdentityConversion())) {
  6836. ExprResult result = m_sema->PerformImplicitConversion(expr, type, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  6837. if (result.isUsable()) {
  6838. return result.get();
  6839. }
  6840. }
  6841. }
  6842. return expr;
  6843. }
  6844. bool HLSLExternalSource::ValidateTypeRequirements(
  6845. SourceLocation loc,
  6846. ArBasicKind elementKind,
  6847. ArTypeObjectKind objectKind,
  6848. bool requiresIntegrals,
  6849. bool requiresNumerics)
  6850. {
  6851. if (requiresIntegrals || requiresNumerics)
  6852. {
  6853. if (!IsObjectKindPrimitiveAggregate(objectKind))
  6854. {
  6855. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  6856. return false;
  6857. }
  6858. }
  6859. if (requiresIntegrals)
  6860. {
  6861. if (!IsBasicKindIntegral(elementKind))
  6862. {
  6863. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  6864. return false;
  6865. }
  6866. }
  6867. else if (requiresNumerics)
  6868. {
  6869. if (!IsBasicKindNumeric(elementKind))
  6870. {
  6871. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  6872. return false;
  6873. }
  6874. }
  6875. return true;
  6876. }
  6877. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  6878. {
  6879. bool isValid = true;
  6880. if (IsBuiltInObjectType(type)) {
  6881. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  6882. isValid = false;
  6883. }
  6884. if (kind == AR_TOBJ_COMPOUND) {
  6885. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  6886. isValid = false;
  6887. }
  6888. return isValid;
  6889. }
  6890. HRESULT HLSLExternalSource::CombineDimensions(QualType leftType, QualType rightType, QualType *resultType)
  6891. {
  6892. UINT leftRows, leftCols;
  6893. UINT rightRows, rightCols;
  6894. GetRowsAndColsForAny(leftType, leftRows, leftCols);
  6895. GetRowsAndColsForAny(rightType, rightRows, rightCols);
  6896. UINT leftTotal = leftRows * leftCols;
  6897. UINT rightTotal = rightRows * rightCols;
  6898. if (rightTotal == 1) {
  6899. *resultType = leftType;
  6900. return S_OK;
  6901. } else if (leftTotal == 1) {
  6902. *resultType = rightType;
  6903. return S_OK;
  6904. } else if (leftRows <= rightRows && leftCols <= rightCols) {
  6905. *resultType = leftType;
  6906. return S_OK;
  6907. } else if (rightRows <= leftRows && rightCols <= leftCols) {
  6908. *resultType = rightType;
  6909. return S_OK;
  6910. } else if ( (1 == leftRows || 1 == leftCols) &&
  6911. (1 == rightRows || 1 == rightCols)) {
  6912. // Handles cases where 1xN or Nx1 matrices are involved possibly mixed with vectors
  6913. if (leftTotal <= rightTotal) {
  6914. *resultType = leftType;
  6915. return S_OK;
  6916. } else {
  6917. *resultType = rightType;
  6918. return S_OK;
  6919. }
  6920. }
  6921. return E_FAIL;
  6922. }
  6923. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  6924. /// <param name="OpLoc">Source location for operator.</param>
  6925. /// <param name="Opc">Kind of binary operator.</param>
  6926. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  6927. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  6928. /// <param name="ResultTy">Result type for operator expression.</param>
  6929. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  6930. /// <param name="CompResultTy">Type of computation result.</param>
  6931. void HLSLExternalSource::CheckBinOpForHLSL(
  6932. SourceLocation OpLoc,
  6933. BinaryOperatorKind Opc,
  6934. ExprResult& LHS,
  6935. ExprResult& RHS,
  6936. QualType& ResultTy,
  6937. QualType& CompLHSTy,
  6938. QualType& CompResultTy)
  6939. {
  6940. // At the start, none of the output types should be valid.
  6941. DXASSERT_NOMSG(ResultTy.isNull());
  6942. DXASSERT_NOMSG(CompLHSTy.isNull());
  6943. DXASSERT_NOMSG(CompResultTy.isNull());
  6944. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  6945. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  6946. // If either expression is invalid to begin with, propagate that.
  6947. if (LHS.isInvalid() || RHS.isInvalid()) {
  6948. return;
  6949. }
  6950. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  6951. // Handle Assign and Comma operators and return
  6952. switch (Opc)
  6953. {
  6954. case BO_AddAssign:
  6955. case BO_AndAssign:
  6956. case BO_DivAssign:
  6957. case BO_MulAssign:
  6958. case BO_RemAssign:
  6959. case BO_ShlAssign:
  6960. case BO_ShrAssign:
  6961. case BO_SubAssign:
  6962. case BO_OrAssign:
  6963. case BO_XorAssign: {
  6964. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  6965. Sema & S);
  6966. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  6967. return;
  6968. }
  6969. } break;
  6970. case BO_Assign: {
  6971. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  6972. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  6973. return;
  6974. }
  6975. bool complained = false;
  6976. ResultTy = LHS.get()->getType();
  6977. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  6978. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  6979. Sema::AssignmentAction::AA_Assigning, &complained)) {
  6980. return;
  6981. }
  6982. StandardConversionSequence standard;
  6983. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  6984. ExplicitConversionFalse, complained, complained, &standard)) {
  6985. return;
  6986. }
  6987. if (RHS.get()->isLValue()) {
  6988. standard.First = ICK_Lvalue_To_Rvalue;
  6989. }
  6990. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  6991. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  6992. return;
  6993. }
  6994. break;
  6995. case BO_Comma:
  6996. // C performs conversions, C++ doesn't but still checks for type completeness.
  6997. // There are also diagnostics for improper comma use.
  6998. // In the HLSL case these cases don't apply or simply aren't surfaced.
  6999. ResultTy = RHS.get()->getType();
  7000. return;
  7001. }
  7002. // Leave this diagnostic for last to emulate fxc behavior.
  7003. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  7004. bool unsupportedBoolLvalue = isCompoundAssignment &&
  7005. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  7006. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  7007. // Turn operand inputs into r-values.
  7008. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  7009. if (!isCompoundAssignment) {
  7010. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  7011. }
  7012. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  7013. if (LHS.isInvalid() || RHS.isInvalid()) {
  7014. return;
  7015. }
  7016. // Promote bool to int now if necessary
  7017. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc) &&
  7018. !isCompoundAssignment) {
  7019. LHS = PromoteToIntIfBool(LHS);
  7020. }
  7021. // Gather type info
  7022. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7023. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7024. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7025. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7026. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7027. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7028. // Validate type requirements
  7029. {
  7030. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  7031. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  7032. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  7033. return;
  7034. }
  7035. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  7036. return;
  7037. }
  7038. }
  7039. // Promote rhs bool to int if necessary.
  7040. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7041. RHS = PromoteToIntIfBool(RHS);
  7042. }
  7043. if (unsupportedBoolLvalue) {
  7044. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7045. return;
  7046. }
  7047. // We don't support binary operators on built-in object types other than assignment or commas.
  7048. {
  7049. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  7050. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  7051. bool isValid;
  7052. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  7053. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  7054. isValid = false;
  7055. }
  7056. if (!isValid) {
  7057. return;
  7058. }
  7059. }
  7060. // We don't support equality comparisons on arrays.
  7061. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  7062. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  7063. return;
  7064. }
  7065. // Combine element types for computation.
  7066. ArBasicKind resultElementKind = leftElementKind;
  7067. {
  7068. if (BinaryOperatorKindIsLogical(Opc)) {
  7069. resultElementKind = AR_BASIC_BOOL;
  7070. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  7071. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  7072. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7073. return;
  7074. }
  7075. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  7076. (resultElementKind == AR_BASIC_LITERAL_INT ||
  7077. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  7078. rightElementKind != AR_BASIC_LITERAL_INT &&
  7079. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  7080. // For case like 1<<x.
  7081. resultElementKind = AR_BASIC_UINT32;
  7082. }
  7083. // The following combines the selected/combined element kind above with
  7084. // the dimensions that are legal to implicitly cast. This means that
  7085. // element kind may be taken from one side and the dimensions from the
  7086. // other.
  7087. if (!isCompoundAssignment) {
  7088. // Legal dimension combinations are identical, splat, and truncation.
  7089. // ResultTy will be set to whichever type can be converted to, if legal,
  7090. // with preference for leftType if both are possible.
  7091. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  7092. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7093. return;
  7094. }
  7095. } else {
  7096. ResultTy = LHS.get()->getType();
  7097. }
  7098. // Here, element kind is combined with dimensions for computation type.
  7099. UINT rowCount, colCount;
  7100. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7101. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7102. }
  7103. // Perform necessary conversion sequences for LHS and RHS
  7104. if (RHS.get()->getType() != ResultTy) {
  7105. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  7106. }
  7107. if (isCompoundAssignment) {
  7108. bool complained = false;
  7109. StandardConversionSequence standard;
  7110. if (!ValidateCast(OpLoc, RHS.get(), LHS.get()->getType(), ExplicitConversionFalse,
  7111. complained, complained, &standard)) {
  7112. ResultTy = QualType();
  7113. return;
  7114. }
  7115. CompResultTy = ResultTy;
  7116. CompLHSTy = CompResultTy;
  7117. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  7118. // then converts to the result type and then assigns.
  7119. //
  7120. // So int + float promotes the int to float, does a floating-point addition,
  7121. // then the result becomes and int and is assigned.
  7122. ResultTy = LHSTypeAsPossibleLValue;
  7123. } else if (LHS.get()->getType() != ResultTy) {
  7124. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  7125. }
  7126. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  7127. {
  7128. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  7129. // Return bool vector for vector types.
  7130. if (IsVectorType(m_sema, ResultTy)) {
  7131. UINT rowCount, colCount;
  7132. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7133. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  7134. } else if (IsMatrixType(m_sema, ResultTy)) {
  7135. UINT rowCount, colCount;
  7136. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7137. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  7138. } else
  7139. ResultTy = m_context->BoolTy.withConst();
  7140. }
  7141. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  7142. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  7143. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  7144. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  7145. return;
  7146. }
  7147. }
  7148. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  7149. if (resultElementKind == AR_BASIC_FLOAT64) {
  7150. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  7151. return;
  7152. }
  7153. }
  7154. }
  7155. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  7156. /// <param name="OpLoc">Source location for operator.</param>
  7157. /// <param name="Opc">Kind of operator.</param>
  7158. /// <param name="InputExpr">Input expression to the operator.</param>
  7159. /// <param name="VK">Value kind for resulting expression.</param>
  7160. /// <param name="OK">Object kind for resulting expression.</param>
  7161. /// <returns>The result type for the expression.</returns>
  7162. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  7163. SourceLocation OpLoc,
  7164. UnaryOperatorKind Opc,
  7165. ExprResult& InputExpr,
  7166. ExprValueKind& VK,
  7167. ExprObjectKind& OK)
  7168. {
  7169. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  7170. if (InputExpr.isInvalid())
  7171. return QualType();
  7172. // Reject unsupported operators * and &
  7173. switch (Opc) {
  7174. case UO_AddrOf:
  7175. case UO_Deref:
  7176. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  7177. return QualType();
  7178. }
  7179. Expr* expr = InputExpr.get();
  7180. if (expr->isTypeDependent())
  7181. return m_context->DependentTy;
  7182. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  7183. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  7184. if (elementKind == AR_BASIC_ENUM) {
  7185. bool isInc = IsIncrementOp(Opc);
  7186. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  7187. return QualType();
  7188. }
  7189. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7190. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  7191. return QualType();
  7192. } else {
  7193. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  7194. if (InputExpr.isInvalid()) return QualType();
  7195. }
  7196. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  7197. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7198. return QualType();
  7199. }
  7200. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7201. InputExpr = PromoteToIntIfBool(InputExpr);
  7202. expr = InputExpr.get();
  7203. elementKind = GetTypeElementKind(expr->getType());
  7204. }
  7205. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  7206. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  7207. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  7208. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  7209. return QualType();
  7210. }
  7211. if (Opc == UnaryOperatorKind::UO_Minus) {
  7212. if (IS_BASIC_UINT(Opc)) {
  7213. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  7214. }
  7215. }
  7216. // By default, the result type is the operand type.
  7217. // Logical not however should cast to a bool.
  7218. QualType resultType = expr->getType();
  7219. if (Opc == UnaryOperatorKind::UO_LNot) {
  7220. UINT rowCount, colCount;
  7221. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  7222. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  7223. StandardConversionSequence standard;
  7224. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  7225. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  7226. return QualType();
  7227. }
  7228. // Cast argument.
  7229. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7230. if (result.isUsable()) {
  7231. InputExpr = result.get();
  7232. }
  7233. }
  7234. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  7235. if (isPrefix) {
  7236. VK = VK_LValue;
  7237. return resultType;
  7238. }
  7239. else {
  7240. VK = VK_RValue;
  7241. return resultType.getUnqualifiedType();
  7242. }
  7243. }
  7244. clang::QualType HLSLExternalSource::CheckVectorConditional(
  7245. _In_ ExprResult &Cond,
  7246. _In_ ExprResult &LHS,
  7247. _In_ ExprResult &RHS,
  7248. _In_ SourceLocation QuestionLoc)
  7249. {
  7250. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  7251. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7252. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7253. // If either expression is invalid to begin with, propagate that.
  7254. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  7255. return QualType();
  7256. }
  7257. // Gather type info
  7258. QualType condType = GetStructuralForm(Cond.get()->getType());
  7259. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7260. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7261. ArBasicKind condElementKind = GetTypeElementKind(condType);
  7262. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7263. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7264. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  7265. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7266. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7267. QualType ResultTy = leftType;
  7268. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  7269. if (!condIsSimple) {
  7270. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  7271. return QualType();
  7272. }
  7273. UINT rowCountCond, colCountCond;
  7274. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  7275. bool leftIsSimple =
  7276. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  7277. leftObjectKind == AR_TOBJ_MATRIX;
  7278. bool rightIsSimple =
  7279. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  7280. rightObjectKind == AR_TOBJ_MATRIX;
  7281. UINT rowCount, colCount;
  7282. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7283. if (!leftIsSimple || !rightIsSimple) {
  7284. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  7285. if (leftType == rightType) {
  7286. return leftType;
  7287. }
  7288. }
  7289. // NOTE: Limiting this operator to working only on basic numeric types.
  7290. // This is due to extremely limited (and even broken) support for any other case.
  7291. // In the future we may decide to support more cases.
  7292. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  7293. return QualType();
  7294. }
  7295. // Types should be only scalar, vector, or matrix after this point.
  7296. ArBasicKind resultElementKind = leftElementKind;
  7297. // Combine LHS and RHS element types for computation.
  7298. if (leftElementKind != rightElementKind) {
  7299. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  7300. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  7301. return QualType();
  7302. }
  7303. }
  7304. // Combine LHS and RHS dimensions
  7305. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  7306. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  7307. return QualType();
  7308. }
  7309. // If result is scalar, use condition dimensions.
  7310. // Otherwise, condition must either match or is scalar, then use result dimensions
  7311. if (rowCount * colCount == 1) {
  7312. rowCount = rowCountCond;
  7313. colCount = colCountCond;
  7314. }
  7315. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  7316. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  7317. return QualType();
  7318. }
  7319. // Here, element kind is combined with dimensions for result type.
  7320. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7321. // Cast condition to RValue
  7322. if (Cond.get()->isLValue())
  7323. Cond.set(CreateLValueToRValueCast(Cond.get()));
  7324. // Convert condition component type to bool, using result component dimensions
  7325. if (condElementKind != AR_BASIC_BOOL) {
  7326. Cond = CastExprToTypeNumeric(Cond.get(),
  7327. NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal());
  7328. }
  7329. // Cast LHS/RHS to RValue
  7330. if (LHS.get()->isLValue())
  7331. LHS.set(CreateLValueToRValueCast(LHS.get()));
  7332. if (RHS.get()->isLValue())
  7333. RHS.set(CreateLValueToRValueCast(RHS.get()));
  7334. // TODO: Why isn't vector truncation being reported?
  7335. if (leftType != ResultTy) {
  7336. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  7337. }
  7338. if (rightType != ResultTy) {
  7339. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  7340. }
  7341. return ResultTy;
  7342. }
  7343. // Apply type specifier sign to the given QualType.
  7344. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  7345. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  7346. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  7347. _In_ clang::SourceLocation Loc) {
  7348. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  7349. return type;
  7350. }
  7351. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  7352. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  7353. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  7354. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  7355. return type;
  7356. }
  7357. // check if element type is unsigned and check if such vector exists
  7358. // If not create a new one, Make a QualType of the new kind
  7359. ArBasicKind elementKind = GetTypeElementKind(type);
  7360. // Only ints can have signed/unsigend ty
  7361. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  7362. return type;
  7363. }
  7364. else {
  7365. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  7366. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  7367. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  7368. // Get new vector types for a given TypeSpecifierSign.
  7369. if (objKind == AR_TOBJ_VECTOR) {
  7370. UINT colCount = GetHLSLVecSize(type);
  7371. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  7372. return m_context->getTypeDeclType(qts);
  7373. } else if (objKind == AR_TOBJ_MATRIX) {
  7374. UINT rowCount, colCount;
  7375. GetRowsAndCols(type, rowCount, colCount);
  7376. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  7377. return m_context->getTypeDeclType(qts);
  7378. } else {
  7379. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  7380. return m_scalarTypes[newScalarType];
  7381. }
  7382. }
  7383. }
  7384. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  7385. FunctionTemplateDecl *FunctionTemplate,
  7386. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  7387. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  7388. {
  7389. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  7390. // Get information about the function we have.
  7391. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  7392. DXASSERT(functionMethod != nullptr,
  7393. "otherwise this is standalone function rather than a method, which isn't supported in the HLSL object model");
  7394. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  7395. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  7396. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  7397. // Handle subscript overloads.
  7398. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  7399. {
  7400. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  7401. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  7402. if (!findResult.Found())
  7403. {
  7404. // This might be a nested type. Do a lookup on the parent.
  7405. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  7406. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  7407. {
  7408. return Sema::TemplateDeductionResult::TDK_Invalid;
  7409. }
  7410. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  7411. if (!findResult.Found())
  7412. {
  7413. return Sema::TemplateDeductionResult::TDK_Invalid;
  7414. }
  7415. DXASSERT(
  7416. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  7417. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  7418. "otherwise FindStructBasicType should have failed - no other types are allowed");
  7419. objectElement = GetFirstElementTypeFromDecl(
  7420. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  7421. }
  7422. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  7423. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  7424. FunctionTemplate->getCanonicalDecl());
  7425. return Sema::TemplateDeductionResult::TDK_Success;
  7426. }
  7427. // Reject overload lookups that aren't identifier-based.
  7428. if (!FunctionTemplate->getDeclName().isIdentifier())
  7429. {
  7430. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  7431. }
  7432. // Find the table of intrinsics based on the object type.
  7433. const HLSL_INTRINSIC* intrinsics;
  7434. size_t intrinsicCount;
  7435. const char* objectName;
  7436. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  7437. DXASSERT(intrinsics != nullptr,
  7438. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  7439. "or the parser let a user-defined template object through");
  7440. // Look for an intrinsic for which we can match arguments.
  7441. size_t argCount;
  7442. QualType argTypes[g_MaxIntrinsicParamCount + 1];
  7443. StringRef nameIdentifier = FunctionTemplate->getName();
  7444. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  7445. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  7446. while (cursor != end)
  7447. {
  7448. if (!MatchArguments(*cursor, objectElement, Args, argTypes, &argCount))
  7449. {
  7450. ++cursor;
  7451. continue;
  7452. }
  7453. // Currently only intrinsic we allow for explicit template arguments are
  7454. // for Load return types for ByteAddressBuffer/RWByteAddressBuffer
  7455. // TODO: handle template arguments for future intrinsics in a more natural way
  7456. // Check Explicit template arguments
  7457. UINT intrinsicOp = (*cursor)->Op;
  7458. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  7459. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  7460. bool IsBAB =
  7461. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  7462. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  7463. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  7464. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  7465. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  7466. bool isLegalTemplate = false;
  7467. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  7468. auto TemplateDiag =
  7469. !IsBABLoad
  7470. ? diag::err_hlsl_intrinsic_template_arg_unsupported
  7471. : !Is2018 ? diag::err_hlsl_intrinsic_template_arg_requires_2018
  7472. : diag::err_hlsl_intrinsic_template_arg_requires_2018;
  7473. if (IsBABLoad && Is2018 && ExplicitTemplateArgs->size() == 1) {
  7474. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  7475. QualType explicitType = (*ExplicitTemplateArgs)[0].getArgument().getAsType();
  7476. ArTypeObjectKind explicitKind = GetTypeObjectKind(explicitType);
  7477. if (explicitKind == AR_TOBJ_BASIC || explicitKind == AR_TOBJ_VECTOR) {
  7478. isLegalTemplate = GET_BASIC_BITS(GetTypeElementKind(explicitType)) != BPROP_BITS64 ||
  7479. GetNumElements(explicitType) <= 2;
  7480. }
  7481. if (isLegalTemplate) {
  7482. argTypes[0] = explicitType;
  7483. }
  7484. }
  7485. if (!isLegalTemplate) {
  7486. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  7487. return Sema::TemplateDeductionResult::TDK_Invalid;
  7488. }
  7489. } else if (IsBABStore) {
  7490. // Prior to HLSL 2018, Store operation only stored scalar uint.
  7491. if (!Is2018) {
  7492. if (GetNumElements(argTypes[2]) != 1) {
  7493. getSema()->Diag(Args[1]->getLocStart(),
  7494. diag::err_ovl_no_viable_member_function_in_call)
  7495. << intrinsicName;
  7496. return Sema::TemplateDeductionResult::TDK_Invalid;
  7497. }
  7498. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  7499. 32, /*signed*/ false);
  7500. } else {
  7501. // not supporting types > 16 bytes yet.
  7502. if (GET_BASIC_BITS(GetTypeElementKind(argTypes[2])) == BPROP_BITS64 &&
  7503. GetNumElements(argTypes[2]) > 2) {
  7504. getSema()->Diag(Args[1]->getLocStart(),
  7505. diag::err_ovl_no_viable_member_function_in_call)
  7506. << intrinsicName;
  7507. return Sema::TemplateDeductionResult::TDK_Invalid;
  7508. }
  7509. }
  7510. }
  7511. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes, argCount);
  7512. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  7513. FunctionTemplate->getCanonicalDecl());
  7514. if (!IsValidateObjectElement(*cursor, objectElement)) {
  7515. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  7516. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  7517. }
  7518. return Sema::TemplateDeductionResult::TDK_Success;
  7519. }
  7520. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  7521. }
  7522. void HLSLExternalSource::DiagnoseAssignmentResultForHLSL(
  7523. Sema::AssignConvertType ConvTy,
  7524. SourceLocation Loc,
  7525. QualType DstType, QualType SrcType,
  7526. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  7527. _Out_opt_ bool *Complained)
  7528. {
  7529. if (Complained) *Complained = false;
  7530. // No work to do if there is not type change.
  7531. if (DstType == SrcType) {
  7532. return;
  7533. }
  7534. // Don't generate a warning if the user is casting explicitly
  7535. // or if initializing - our initialization handling already emits this.
  7536. if (Action == Sema::AssignmentAction::AA_Casting ||
  7537. Action == Sema::AssignmentAction::AA_Initializing) {
  7538. return;
  7539. }
  7540. ArBasicKind src = BasicTypeForScalarType(SrcType->getCanonicalTypeUnqualified());
  7541. if (src == AR_BASIC_UNKNOWN || src == AR_BASIC_BOOL) {
  7542. return;
  7543. }
  7544. ArBasicKind dst = BasicTypeForScalarType(DstType->getCanonicalTypeUnqualified());
  7545. if (dst == AR_BASIC_UNKNOWN) {
  7546. return;
  7547. }
  7548. bool warnAboutNarrowing = false;
  7549. switch (dst) {
  7550. case AR_BASIC_FLOAT32:
  7551. case AR_BASIC_INT32:
  7552. case AR_BASIC_UINT32:
  7553. case AR_BASIC_FLOAT16:
  7554. warnAboutNarrowing = src == AR_BASIC_FLOAT64;
  7555. break;
  7556. case AR_BASIC_MIN16FLOAT:
  7557. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  7558. break;
  7559. case AR_BASIC_MIN16INT:
  7560. case AR_BASIC_MIN16UINT:
  7561. case AR_BASIC_MIN12INT:
  7562. case AR_BASIC_MIN10FLOAT:
  7563. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  7564. break;
  7565. }
  7566. // fxc errors looked like this:
  7567. // warning X3205: conversion from larger type to smaller, possible loss of data
  7568. if (warnAboutNarrowing) {
  7569. m_sema->Diag(Loc, diag::warn_hlsl_narrowing) << SrcType << DstType;
  7570. AssignOpt(true, Complained);
  7571. }
  7572. }
  7573. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  7574. {
  7575. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  7576. }
  7577. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  7578. QualType DestType,
  7579. Sema::CheckedConversionKind CCK,
  7580. const SourceRange &OpRange, unsigned &msg,
  7581. CastKind &Kind, CXXCastPath &BasePath,
  7582. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  7583. _Inout_opt_ StandardConversionSequence* standard)
  7584. {
  7585. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  7586. bool explicitConversion
  7587. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  7588. QualType sourceType = SrcExpr.get()->getType();
  7589. bool suppressWarnings = explicitConversion || SuppressWarnings;
  7590. SourceLocation loc = OpRange.getBegin();
  7591. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  7592. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  7593. // so do this here until we figure out why this is needed.
  7594. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  7595. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  7596. }
  7597. return true;
  7598. }
  7599. // ValidateCast includes its own error messages.
  7600. msg = 0;
  7601. return false;
  7602. }
  7603. /// <summary>
  7604. /// Checks if a subscript index argument can be initialized from the given expression.
  7605. /// </summary>
  7606. /// <param name="SrcExpr">Source expression used as argument.</param>
  7607. /// <param name="DestType">Parameter type to initialize.</param>
  7608. /// <remarks>
  7609. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  7610. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  7611. /// </remarks>
  7612. ImplicitConversionSequence
  7613. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  7614. clang::QualType DestType) {
  7615. DXASSERT_NOMSG(SrcExpr != nullptr);
  7616. DXASSERT_NOMSG(!DestType.isNull());
  7617. unsigned int msg = 0;
  7618. CastKind kind;
  7619. CXXCastPath path;
  7620. ImplicitConversionSequence sequence;
  7621. sequence.setStandard();
  7622. ExprResult sourceExpr(SrcExpr);
  7623. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  7624. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7625. SrcExpr->getType(), DestType);
  7626. } else if (!TryStaticCastForHLSL(
  7627. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  7628. msg, kind, path, ListInitializationFalse,
  7629. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  7630. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7631. SrcExpr->getType(), DestType);
  7632. }
  7633. return sequence;
  7634. }
  7635. template <typename T>
  7636. static
  7637. bool IsValueInRange(T value, T minValue, T maxValue) {
  7638. return minValue <= value && value <= maxValue;
  7639. }
  7640. #define D3DX_16F_MAX 6.550400e+004 // max value
  7641. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  7642. static
  7643. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  7644. {
  7645. DXASSERT_NOMSG(minValue != nullptr);
  7646. DXASSERT_NOMSG(maxValue != nullptr);
  7647. switch (basicKind) {
  7648. case AR_BASIC_MIN10FLOAT:
  7649. case AR_BASIC_MIN16FLOAT:
  7650. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  7651. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  7652. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  7653. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  7654. }
  7655. DXASSERT(false, "unreachable");
  7656. *minValue = 0; *maxValue = 0;
  7657. return;
  7658. }
  7659. static
  7660. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  7661. {
  7662. DXASSERT_NOMSG(maxValue != nullptr);
  7663. switch (basicKind) {
  7664. case AR_BASIC_BOOL: *maxValue = 1; return;
  7665. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  7666. case AR_BASIC_MIN16UINT:
  7667. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  7668. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  7669. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  7670. }
  7671. DXASSERT(false, "unreachable");
  7672. *maxValue = 0;
  7673. return;
  7674. }
  7675. static
  7676. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  7677. {
  7678. DXASSERT_NOMSG(minValue != nullptr);
  7679. DXASSERT_NOMSG(maxValue != nullptr);
  7680. switch (basicKind) {
  7681. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  7682. case AR_BASIC_MIN12INT:
  7683. case AR_BASIC_MIN16INT:
  7684. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  7685. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  7686. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  7687. }
  7688. DXASSERT(false, "unreachable");
  7689. *minValue = 0; *maxValue = 0;
  7690. return;
  7691. }
  7692. static
  7693. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  7694. {
  7695. if (IS_BASIC_FLOAT(basicKind)) {
  7696. double val;
  7697. if (value.isInt()) {
  7698. val = value.getInt().getLimitedValue();
  7699. } else if (value.isFloat()) {
  7700. llvm::APFloat floatValue = value.getFloat();
  7701. if (!floatValue.isFinite()) {
  7702. return false;
  7703. }
  7704. llvm::APFloat valueFloat = value.getFloat();
  7705. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  7706. val = value.getFloat().convertToFloat();
  7707. }
  7708. else {
  7709. val = value.getFloat().convertToDouble();
  7710. }
  7711. } else {
  7712. return false;
  7713. }
  7714. double minValue, maxValue;
  7715. GetFloatLimits(basicKind, &minValue, &maxValue);
  7716. return IsValueInRange(val, minValue, maxValue);
  7717. }
  7718. else if (IS_BASIC_SINT(basicKind)) {
  7719. if (!value.isInt()) {
  7720. return false;
  7721. }
  7722. int64_t val = value.getInt().getSExtValue();
  7723. int64_t minValue, maxValue;
  7724. GetSignedLimits(basicKind, &minValue, &maxValue);
  7725. return IsValueInRange(val, minValue, maxValue);
  7726. }
  7727. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  7728. if (!value.isInt()) {
  7729. return false;
  7730. }
  7731. uint64_t val = value.getInt().getLimitedValue();
  7732. uint64_t maxValue;
  7733. GetUnsignedLimit(basicKind, &maxValue);
  7734. return IsValueInRange(val, (uint64_t)0, maxValue);
  7735. }
  7736. else {
  7737. return false;
  7738. }
  7739. }
  7740. static
  7741. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  7742. {
  7743. DXASSERT_NOMSG(!targetType.isNull());
  7744. DXASSERT_NOMSG(sourceExpr != nullptr);
  7745. Expr::EvalResult evalResult;
  7746. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  7747. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  7748. return IsValueInBasicRange(targetKind, evalResult.Val);
  7749. }
  7750. }
  7751. return false;
  7752. }
  7753. bool HLSLExternalSource::ValidateCast(
  7754. SourceLocation OpLoc,
  7755. _In_ Expr* sourceExpr,
  7756. QualType target,
  7757. bool explicitConversion,
  7758. bool suppressWarnings,
  7759. bool suppressErrors,
  7760. _Inout_opt_ StandardConversionSequence* standard)
  7761. {
  7762. DXASSERT_NOMSG(sourceExpr != nullptr);
  7763. QualType source = sourceExpr->getType();
  7764. TYPE_CONVERSION_REMARKS remarks;
  7765. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  7766. {
  7767. const bool IsOutputParameter = false;
  7768. //
  7769. // Check whether the lack of explicit-ness matters.
  7770. //
  7771. // Setting explicitForDiagnostics to true in that case will avoid the message
  7772. // saying anything about the implicit nature of the cast, when adding the
  7773. // explicit cast won't make a difference.
  7774. //
  7775. bool explicitForDiagnostics = explicitConversion;
  7776. if (explicitConversion == false)
  7777. {
  7778. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  7779. {
  7780. // Can't convert either way - implicit/explicit doesn't matter.
  7781. explicitForDiagnostics = true;
  7782. }
  7783. }
  7784. if (!suppressErrors)
  7785. {
  7786. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  7787. << explicitForDiagnostics << IsOutputParameter << source << target;
  7788. }
  7789. return false;
  7790. }
  7791. if (!suppressWarnings)
  7792. {
  7793. if (!explicitConversion)
  7794. {
  7795. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  7796. {
  7797. // This is a much more restricted version of the analysis does
  7798. // StandardConversionSequence::getNarrowingKind
  7799. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  7800. {
  7801. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  7802. }
  7803. }
  7804. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  7805. {
  7806. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  7807. }
  7808. }
  7809. }
  7810. return true;
  7811. }
  7812. ////////////////////////////////////////////////////////////////////////////////
  7813. // Functions exported from this translation unit. //
  7814. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  7815. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  7816. SourceLocation OpLoc,
  7817. UnaryOperatorKind Opc,
  7818. ExprResult& InputExpr,
  7819. ExprValueKind& VK,
  7820. ExprObjectKind& OK)
  7821. {
  7822. ExternalSemaSource* externalSource = self.getExternalSource();
  7823. if (externalSource == nullptr) {
  7824. return QualType();
  7825. }
  7826. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7827. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  7828. }
  7829. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  7830. void hlsl::CheckBinOpForHLSL(Sema& self,
  7831. SourceLocation OpLoc,
  7832. BinaryOperatorKind Opc,
  7833. ExprResult& LHS,
  7834. ExprResult& RHS,
  7835. QualType& ResultTy,
  7836. QualType& CompLHSTy,
  7837. QualType& CompResultTy)
  7838. {
  7839. ExternalSemaSource* externalSource = self.getExternalSource();
  7840. if (externalSource == nullptr) {
  7841. return;
  7842. }
  7843. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7844. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  7845. }
  7846. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  7847. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  7848. {
  7849. DXASSERT_NOMSG(Template != nullptr);
  7850. ExternalSemaSource* externalSource = self.getExternalSource();
  7851. if (externalSource == nullptr) {
  7852. return false;
  7853. }
  7854. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7855. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  7856. }
  7857. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  7858. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  7859. FunctionTemplateDecl *FunctionTemplate,
  7860. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  7861. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  7862. {
  7863. return HLSLExternalSource::FromSema(self)
  7864. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  7865. }
  7866. void hlsl::DiagnoseAssignmentResultForHLSL(Sema* self,
  7867. Sema::AssignConvertType ConvTy,
  7868. SourceLocation Loc,
  7869. QualType DstType, QualType SrcType,
  7870. Expr *SrcExpr, Sema::AssignmentAction Action,
  7871. bool *Complained)
  7872. {
  7873. return HLSLExternalSource::FromSema(self)
  7874. ->DiagnoseAssignmentResultForHLSL(ConvTy, Loc, DstType, SrcType, SrcExpr, Action, Complained);
  7875. }
  7876. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  7877. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  7878. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  7879. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  7880. self->Diag(condExpr->getLocStart(),
  7881. diag::err_hlsl_control_flow_cond_not_scalar)
  7882. << StmtName;
  7883. return;
  7884. }
  7885. condExpr = IC->getSubExpr();
  7886. }
  7887. }
  7888. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  7889. {
  7890. // TODO: handle shorthand cases.
  7891. return left.size() == 0 || right.size() == 0 || left.equals(right);
  7892. }
  7893. void hlsl::DiagnosePackingOffset(
  7894. clang::Sema* self,
  7895. SourceLocation loc,
  7896. clang::QualType type,
  7897. int componentOffset)
  7898. {
  7899. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  7900. if (componentOffset > 0) {
  7901. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  7902. ArBasicKind element = source->GetTypeElementKind(type);
  7903. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  7904. // Only perform some simple validation for now.
  7905. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  7906. int count = GetElementCount(type);
  7907. if (count > (4 - componentOffset)) {
  7908. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  7909. }
  7910. }
  7911. }
  7912. }
  7913. void hlsl::DiagnoseRegisterType(
  7914. clang::Sema* self,
  7915. clang::SourceLocation loc,
  7916. clang::QualType type,
  7917. char registerType)
  7918. {
  7919. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  7920. ArBasicKind element = source->GetTypeElementKind(type);
  7921. StringRef expected("none");
  7922. bool isValid = true;
  7923. bool isWarning = false;
  7924. switch (element)
  7925. {
  7926. case AR_BASIC_BOOL:
  7927. case AR_BASIC_LITERAL_FLOAT:
  7928. case AR_BASIC_FLOAT16:
  7929. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  7930. case AR_BASIC_FLOAT32:
  7931. case AR_BASIC_FLOAT64:
  7932. case AR_BASIC_LITERAL_INT:
  7933. case AR_BASIC_INT8:
  7934. case AR_BASIC_UINT8:
  7935. case AR_BASIC_INT16:
  7936. case AR_BASIC_UINT16:
  7937. case AR_BASIC_INT32:
  7938. case AR_BASIC_UINT32:
  7939. case AR_BASIC_INT64:
  7940. case AR_BASIC_UINT64:
  7941. case AR_BASIC_MIN10FLOAT:
  7942. case AR_BASIC_MIN16FLOAT:
  7943. case AR_BASIC_MIN12INT:
  7944. case AR_BASIC_MIN16INT:
  7945. case AR_BASIC_MIN16UINT:
  7946. expected = "'b', 'c', or 'i'";
  7947. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i' ||
  7948. registerType == 'B' || registerType == 'C' || registerType == 'I';
  7949. break;
  7950. case AR_OBJECT_TEXTURE1D:
  7951. case AR_OBJECT_TEXTURE1D_ARRAY:
  7952. case AR_OBJECT_TEXTURE2D:
  7953. case AR_OBJECT_TEXTURE2D_ARRAY:
  7954. case AR_OBJECT_TEXTURE3D:
  7955. case AR_OBJECT_TEXTURECUBE:
  7956. case AR_OBJECT_TEXTURECUBE_ARRAY:
  7957. case AR_OBJECT_TEXTURE2DMS:
  7958. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  7959. expected = "'t' or 's'";
  7960. isValid = registerType == 't' || registerType == 's' ||
  7961. registerType == 'T' || registerType == 'S';
  7962. break;
  7963. case AR_OBJECT_SAMPLER:
  7964. case AR_OBJECT_SAMPLER1D:
  7965. case AR_OBJECT_SAMPLER2D:
  7966. case AR_OBJECT_SAMPLER3D:
  7967. case AR_OBJECT_SAMPLERCUBE:
  7968. case AR_OBJECT_SAMPLERCOMPARISON:
  7969. expected = "'s' or 't'";
  7970. isValid = registerType == 's' || registerType == 't' ||
  7971. registerType == 'S' || registerType == 'T';
  7972. break;
  7973. case AR_OBJECT_BUFFER:
  7974. expected = "'t'";
  7975. isValid = registerType == 't' || registerType == 'T';
  7976. break;
  7977. case AR_OBJECT_POINTSTREAM:
  7978. case AR_OBJECT_LINESTREAM:
  7979. case AR_OBJECT_TRIANGLESTREAM:
  7980. isValid = false;
  7981. isWarning = true;
  7982. break;
  7983. case AR_OBJECT_INPUTPATCH:
  7984. case AR_OBJECT_OUTPUTPATCH:
  7985. isValid = false;
  7986. isWarning = true;
  7987. break;
  7988. case AR_OBJECT_RWTEXTURE1D:
  7989. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  7990. case AR_OBJECT_RWTEXTURE2D:
  7991. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  7992. case AR_OBJECT_RWTEXTURE3D:
  7993. case AR_OBJECT_RWBUFFER:
  7994. expected = "'u'";
  7995. isValid = registerType == 'u' || registerType == 'U';
  7996. break;
  7997. case AR_OBJECT_BYTEADDRESS_BUFFER:
  7998. case AR_OBJECT_STRUCTURED_BUFFER:
  7999. expected = "'t'";
  8000. isValid = registerType == 't' || registerType == 'T';
  8001. break;
  8002. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  8003. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  8004. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  8005. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  8006. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  8007. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  8008. expected = "'u'";
  8009. isValid = registerType == 'u' || registerType == 'U';
  8010. break;
  8011. case AR_OBJECT_CONSTANT_BUFFER:
  8012. expected = "'b'";
  8013. isValid = registerType == 'b' || registerType == 'B';
  8014. break;
  8015. case AR_OBJECT_TEXTURE_BUFFER:
  8016. expected = "'t'";
  8017. isValid = registerType == 't' || registerType == 'T';
  8018. break;
  8019. case AR_OBJECT_ROVBUFFER:
  8020. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  8021. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  8022. case AR_OBJECT_ROVTEXTURE1D:
  8023. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  8024. case AR_OBJECT_ROVTEXTURE2D:
  8025. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  8026. case AR_OBJECT_ROVTEXTURE3D:
  8027. expected = "'u'";
  8028. isValid = registerType == 'u' || registerType == 'U';
  8029. break;
  8030. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  8031. isWarning = true;
  8032. break; // So we don't care what you tried to bind it to
  8033. };
  8034. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  8035. // a warning instead.
  8036. if (!isValid)
  8037. {
  8038. if (isWarning)
  8039. self->Diag(loc, diag::warn_hlsl_incorrect_bind_semantic) << expected;
  8040. else
  8041. self->Diag(loc, diag::err_hlsl_incorrect_bind_semantic) << expected;
  8042. }
  8043. }
  8044. struct NameLookup {
  8045. FunctionDecl *Found;
  8046. FunctionDecl *Other;
  8047. };
  8048. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  8049. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  8050. FunctionDecl *pFoundDecl = nullptr;
  8051. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  8052. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  8053. if (!pFnDecl) continue;
  8054. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  8055. if (pFoundDecl) {
  8056. return NameLookup{ pFoundDecl, pFnDecl };
  8057. }
  8058. pFoundDecl = pFnDecl;
  8059. }
  8060. return NameLookup{ pFoundDecl, nullptr };
  8061. }
  8062. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  8063. DXASSERT_NOMSG(self != nullptr);
  8064. // Don't bother with global validation if compilation has already failed.
  8065. if (self->getDiagnostics().hasErrorOccurred()) {
  8066. return;
  8067. }
  8068. // Don't check entry function for library.
  8069. if (self->getLangOpts().IsHLSLLibrary) {
  8070. // TODO: validate no recursion start from every function.
  8071. return;
  8072. }
  8073. // TODO: make these error 'real' errors rather than on-the-fly things
  8074. // Validate that the entry point is available.
  8075. ASTContext &Ctx = self->getASTContext();
  8076. DiagnosticsEngine &Diags = self->getDiagnostics();
  8077. FunctionDecl *pEntryPointDecl = nullptr;
  8078. FunctionDecl *pPatchFnDecl = nullptr;
  8079. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  8080. if (!EntryPointName.empty()) {
  8081. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  8082. if (NL.Found && NL.Other) {
  8083. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  8084. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  8085. // string, and so ambiguous points will produce an error earlier on.
  8086. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8087. "ambiguous entry point function");
  8088. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  8089. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  8090. return;
  8091. }
  8092. pEntryPointDecl = NL.Found;
  8093. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  8094. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8095. "missing entry point definition");
  8096. Diags.Report(id);
  8097. return;
  8098. }
  8099. }
  8100. // Validate that there is no recursion; start with the entry function.
  8101. // NOTE: the information gathered here could be used to bypass code generation
  8102. // on functions that are unreachable (as an early form of dead code elimination).
  8103. if (pEntryPointDecl) {
  8104. const auto *shaderModel =
  8105. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  8106. if (shaderModel->IsGS()) {
  8107. // Validate that GS has the maxvertexcount attribute
  8108. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  8109. self->Diag(pEntryPointDecl->getLocation(),
  8110. diag::err_hlsl_missing_maxvertexcount_attr);
  8111. return;
  8112. }
  8113. } else if (shaderModel->IsHS()) {
  8114. if (const HLSLPatchConstantFuncAttr *Attr =
  8115. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8116. NameLookup NL = GetSingleFunctionDeclByName(
  8117. self, Attr->getFunctionName(), /*checkPatch*/ true);
  8118. if (!NL.Found || !NL.Found->hasBody()) {
  8119. unsigned id =
  8120. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8121. "missing patch function definition");
  8122. Diags.Report(id);
  8123. return;
  8124. }
  8125. pPatchFnDecl = NL.Found;
  8126. } else {
  8127. self->Diag(pEntryPointDecl->getLocation(),
  8128. diag::err_hlsl_missing_patchconstantfunc_attr);
  8129. return;
  8130. }
  8131. }
  8132. hlsl::CallGraphWithRecurseGuard CG;
  8133. CG.BuildForEntry(pEntryPointDecl);
  8134. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  8135. if (pResult) {
  8136. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8137. "recursive functions not allowed");
  8138. Diags.Report(pResult->getSourceRange().getBegin(), id);
  8139. }
  8140. if (pPatchFnDecl) {
  8141. CG.BuildForEntry(pPatchFnDecl);
  8142. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  8143. if (pPatchFnDecl) {
  8144. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8145. "recursive functions not allowed (via patch function)");
  8146. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  8147. }
  8148. }
  8149. }
  8150. }
  8151. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  8152. Sema& S,
  8153. std::vector<hlsl::UnusualAnnotation *>& annotations)
  8154. {
  8155. bool packoffsetOverriddenReported = false;
  8156. auto && iter = annotations.begin();
  8157. auto && end = annotations.end();
  8158. for (; iter != end; ++iter) {
  8159. switch ((*iter)->getKind()) {
  8160. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  8161. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  8162. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  8163. if (!packoffsetOverriddenReported) {
  8164. auto newIter = iter;
  8165. ++newIter;
  8166. while (newIter != end) {
  8167. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  8168. if (other != nullptr &&
  8169. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  8170. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  8171. packoffsetOverriddenReported = true;
  8172. break;
  8173. }
  8174. ++newIter;
  8175. }
  8176. }
  8177. break;
  8178. }
  8179. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  8180. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  8181. // Check whether this will conflict with other register assignments of the same type.
  8182. auto newIter = iter;
  8183. ++newIter;
  8184. while (newIter != end) {
  8185. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  8186. // Same register bank and profile, but different number.
  8187. if (other != nullptr &&
  8188. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  8189. other->RegisterType == registerAssignment->RegisterType &&
  8190. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  8191. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  8192. // Obvious conflict - report it up front.
  8193. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  8194. }
  8195. ++newIter;
  8196. }
  8197. break;
  8198. }
  8199. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  8200. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  8201. // No common validation to be performed.
  8202. break;
  8203. }
  8204. }
  8205. }
  8206. }
  8207. clang::OverloadingResult
  8208. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  8209. clang::OverloadCandidateSet &set,
  8210. clang::OverloadCandidateSet::iterator &Best) {
  8211. return HLSLExternalSource::FromSema(&S)
  8212. ->GetBestViableFunction(Loc, set, Best);
  8213. }
  8214. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  8215. const InitializedEntity &Entity,
  8216. const InitializationKind &Kind,
  8217. MultiExprArg Args,
  8218. bool TopLevelOfInitList,
  8219. InitializationSequence *initSequence) {
  8220. return HLSLExternalSource::FromSema(self)
  8221. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  8222. }
  8223. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  8224. const clang::InitListExpr *InitList) {
  8225. unsigned totalSize = 0;
  8226. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  8227. const clang::Expr *EltInit = InitList->getInit(i);
  8228. QualType EltInitTy = EltInit->getType();
  8229. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  8230. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  8231. } else {
  8232. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  8233. }
  8234. }
  8235. return totalSize;
  8236. }
  8237. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  8238. _In_ clang::Sema* sema,
  8239. _In_ const clang::InitListExpr *InitList,
  8240. _In_ const clang::QualType EltTy) {
  8241. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  8242. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  8243. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  8244. if (totalSize > 0 && (totalSize % eltSize)==0) {
  8245. return totalSize / eltSize;
  8246. } else {
  8247. return 0;
  8248. }
  8249. }
  8250. bool hlsl::IsConversionToLessOrEqualElements(
  8251. _In_ clang::Sema* self,
  8252. const clang::ExprResult& sourceExpr,
  8253. const clang::QualType& targetType,
  8254. bool explicitConversion)
  8255. {
  8256. return HLSLExternalSource::FromSema(self)
  8257. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  8258. }
  8259. bool hlsl::LookupMatrixMemberExprForHLSL(
  8260. Sema* self,
  8261. Expr& BaseExpr,
  8262. DeclarationName MemberName,
  8263. bool IsArrow,
  8264. SourceLocation OpLoc,
  8265. SourceLocation MemberLoc,
  8266. ExprResult* result)
  8267. {
  8268. return HLSLExternalSource::FromSema(self)
  8269. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8270. }
  8271. bool hlsl::LookupVectorMemberExprForHLSL(
  8272. Sema* self,
  8273. Expr& BaseExpr,
  8274. DeclarationName MemberName,
  8275. bool IsArrow,
  8276. SourceLocation OpLoc,
  8277. SourceLocation MemberLoc,
  8278. ExprResult* result)
  8279. {
  8280. return HLSLExternalSource::FromSema(self)
  8281. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8282. }
  8283. clang::ExprResult hlsl::MaybeConvertScalarToVector(
  8284. _In_ clang::Sema* self,
  8285. _In_ clang::Expr* E)
  8286. {
  8287. return HLSLExternalSource::FromSema(self)->MaybeConvertScalarToVector(E);
  8288. }
  8289. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  8290. QualType DestType,
  8291. Sema::CheckedConversionKind CCK,
  8292. const SourceRange &OpRange, unsigned &msg,
  8293. CastKind &Kind, CXXCastPath &BasePath,
  8294. bool ListInitialization,
  8295. bool SuppressDiagnostics,
  8296. _Inout_opt_ StandardConversionSequence* standard)
  8297. {
  8298. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  8299. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  8300. SuppressDiagnostics, SuppressDiagnostics, standard);
  8301. }
  8302. clang::ExprResult hlsl::PerformHLSLConversion(
  8303. _In_ clang::Sema* self,
  8304. _In_ clang::Expr* From,
  8305. _In_ clang::QualType targetType,
  8306. _In_ const clang::StandardConversionSequence &SCS,
  8307. _In_ clang::Sema::CheckedConversionKind CCK)
  8308. {
  8309. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  8310. }
  8311. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  8312. _In_ clang::Sema* self,
  8313. _In_ clang::Expr* SrcExpr,
  8314. clang::QualType DestType)
  8315. {
  8316. return HLSLExternalSource::FromSema(self)
  8317. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  8318. }
  8319. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  8320. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  8321. {
  8322. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  8323. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  8324. if (hlslSource->Initialize(context)) {
  8325. context.setExternalSource(externalSource);
  8326. }
  8327. }
  8328. ////////////////////////////////////////////////////////////////////////////////
  8329. // FlattenedTypeIterator implementation //
  8330. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  8331. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  8332. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8333. {
  8334. if (pushTrackerForType(type, nullptr)) {
  8335. considerLeaf();
  8336. }
  8337. }
  8338. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  8339. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  8340. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8341. {
  8342. if (!args.empty()) {
  8343. MultiExprArg::iterator ii = args.begin();
  8344. MultiExprArg::iterator ie = args.end();
  8345. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  8346. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  8347. if (!considerLeaf()) {
  8348. m_typeTrackers.clear();
  8349. }
  8350. }
  8351. }
  8352. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  8353. QualType FlattenedTypeIterator::getCurrentElement() const
  8354. {
  8355. return m_typeTrackers.back().Type;
  8356. }
  8357. /// <summary>Get the number of repeated current elements.</summary>
  8358. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  8359. {
  8360. const FlattenedTypeTracker& back = m_typeTrackers.back();
  8361. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  8362. }
  8363. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  8364. bool FlattenedTypeIterator::hasCurrentElement() const
  8365. {
  8366. return m_typeTrackers.size() > 0;
  8367. }
  8368. /// <summary>Consumes count elements on this iterator.</summary>
  8369. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  8370. {
  8371. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8372. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  8373. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8374. if (tracker.IterKind == FK_IncompleteArray)
  8375. {
  8376. tracker.Count += count;
  8377. m_springLoaded = true;
  8378. }
  8379. else
  8380. {
  8381. tracker.Count -= count;
  8382. m_springLoaded = false;
  8383. if (m_typeTrackers.back().Count == 0)
  8384. {
  8385. advanceLeafTracker();
  8386. }
  8387. }
  8388. }
  8389. unsigned int FlattenedTypeIterator::countRemaining()
  8390. {
  8391. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  8392. size_t result = 0;
  8393. while (hasCurrentElement() && !m_springLoaded)
  8394. {
  8395. size_t pending = getCurrentElementSize();
  8396. result += pending;
  8397. advanceCurrentElement(pending);
  8398. }
  8399. return result;
  8400. }
  8401. void FlattenedTypeIterator::advanceLeafTracker()
  8402. {
  8403. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8404. for (;;)
  8405. {
  8406. consumeLeaf();
  8407. if (m_typeTrackers.empty()) {
  8408. return;
  8409. }
  8410. if (considerLeaf()) {
  8411. return;
  8412. }
  8413. }
  8414. }
  8415. bool FlattenedTypeIterator::considerLeaf()
  8416. {
  8417. if (m_typeTrackers.empty()) {
  8418. return false;
  8419. }
  8420. m_typeDepth++;
  8421. if (m_typeDepth > MaxTypeDepth) {
  8422. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  8423. m_typeTrackers.clear();
  8424. m_typeDepth--;
  8425. return false;
  8426. }
  8427. bool result = false;
  8428. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8429. tracker.IsConsidered = true;
  8430. switch (tracker.IterKind) {
  8431. case FlattenedIterKind::FK_Expressions:
  8432. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  8433. result = considerLeaf();
  8434. }
  8435. break;
  8436. case FlattenedIterKind::FK_Fields:
  8437. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  8438. result = considerLeaf();
  8439. } else {
  8440. // Pop empty struct.
  8441. m_typeTrackers.pop_back();
  8442. }
  8443. break;
  8444. case FlattenedIterKind::FK_Bases:
  8445. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  8446. result = considerLeaf();
  8447. } else {
  8448. // Pop empty base.
  8449. m_typeTrackers.pop_back();
  8450. }
  8451. break;
  8452. case FlattenedIterKind::FK_IncompleteArray:
  8453. m_springLoaded = true; // fall through.
  8454. default:
  8455. case FlattenedIterKind::FK_Simple: {
  8456. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  8457. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  8458. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT) {
  8459. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  8460. result = considerLeaf();
  8461. }
  8462. } else {
  8463. result = true;
  8464. }
  8465. }
  8466. }
  8467. m_typeDepth--;
  8468. return result;
  8469. }
  8470. void FlattenedTypeIterator::consumeLeaf()
  8471. {
  8472. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  8473. for (;;) {
  8474. if (m_typeTrackers.empty()) {
  8475. return;
  8476. }
  8477. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8478. // Reach a leaf which is not considered before.
  8479. // Stop here.
  8480. if (!tracker.IsConsidered) {
  8481. break;
  8482. }
  8483. switch (tracker.IterKind) {
  8484. case FlattenedIterKind::FK_Expressions:
  8485. ++tracker.CurrentExpr;
  8486. if (tracker.CurrentExpr == tracker.EndExpr) {
  8487. m_typeTrackers.pop_back();
  8488. topConsumed = false;
  8489. } else {
  8490. return;
  8491. }
  8492. break;
  8493. case FlattenedIterKind::FK_Fields:
  8494. ++tracker.CurrentField;
  8495. if (tracker.CurrentField == tracker.EndField) {
  8496. m_typeTrackers.pop_back();
  8497. topConsumed = false;
  8498. } else {
  8499. return;
  8500. }
  8501. break;
  8502. case FlattenedIterKind::FK_Bases:
  8503. ++tracker.CurrentBase;
  8504. if (tracker.CurrentBase == tracker.EndBase) {
  8505. m_typeTrackers.pop_back();
  8506. topConsumed = false;
  8507. } else {
  8508. return;
  8509. }
  8510. break;
  8511. case FlattenedIterKind::FK_IncompleteArray:
  8512. if (m_draining) {
  8513. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  8514. m_incompleteCount = tracker.Count;
  8515. m_typeTrackers.pop_back();
  8516. }
  8517. return;
  8518. default:
  8519. case FlattenedIterKind::FK_Simple: {
  8520. m_springLoaded = false;
  8521. if (!topConsumed) {
  8522. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  8523. --tracker.Count;
  8524. }
  8525. else {
  8526. topConsumed = false;
  8527. }
  8528. if (tracker.Count == 0) {
  8529. m_typeTrackers.pop_back();
  8530. } else {
  8531. return;
  8532. }
  8533. }
  8534. }
  8535. }
  8536. }
  8537. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  8538. {
  8539. Expr* e = *expression;
  8540. Stmt::StmtClass expressionClass = e->getStmtClass();
  8541. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  8542. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  8543. if (initExpr->getNumInits() == 0) {
  8544. return false;
  8545. }
  8546. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  8547. MultiExprArg::iterator ii = inits.begin();
  8548. MultiExprArg::iterator ie = inits.end();
  8549. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  8550. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  8551. return true;
  8552. }
  8553. return pushTrackerForType(e->getType(), expression);
  8554. }
  8555. // TODO: improve this to provide a 'peek' at intermediate types,
  8556. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  8557. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  8558. {
  8559. if (type->isVoidType()) {
  8560. return false;
  8561. }
  8562. if (type->isFunctionType()) {
  8563. return false;
  8564. }
  8565. if (m_firstType.isNull()) {
  8566. m_firstType = type;
  8567. }
  8568. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  8569. QualType elementType;
  8570. unsigned int elementCount;
  8571. const RecordType* recordType;
  8572. RecordDecl::field_iterator fi, fe;
  8573. switch (objectKind)
  8574. {
  8575. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  8576. // TODO: handle multi-dimensional arrays
  8577. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  8578. elementCount = GetArraySize(type);
  8579. if (elementCount == 0) {
  8580. if (type->isIncompleteArrayType()) {
  8581. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  8582. return true;
  8583. }
  8584. return false;
  8585. }
  8586. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8587. elementType, elementCount, nullptr));
  8588. return true;
  8589. case ArTypeObjectKind::AR_TOBJ_BASIC:
  8590. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  8591. return true;
  8592. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  8593. recordType = type->getAsStructureType();
  8594. if (recordType == nullptr)
  8595. recordType = dyn_cast<RecordType>(type.getTypePtr());
  8596. fi = recordType->getDecl()->field_begin();
  8597. fe = recordType->getDecl()->field_end();
  8598. bool bAddTracker = false;
  8599. // Skip empty struct.
  8600. if (fi != fe) {
  8601. m_typeTrackers.push_back(
  8602. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  8603. type = (*fi)->getType();
  8604. bAddTracker = true;
  8605. }
  8606. if (CXXRecordDecl *cxxRecordDecl =
  8607. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  8608. CXXRecordDecl::base_class_iterator bi, be;
  8609. bi = cxxRecordDecl->bases_begin();
  8610. be = cxxRecordDecl->bases_end();
  8611. if (bi != be) {
  8612. // Add type tracker for base.
  8613. // Add base after child to make sure base considered first.
  8614. m_typeTrackers.push_back(
  8615. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  8616. bAddTracker = true;
  8617. }
  8618. }
  8619. return bAddTracker;
  8620. }
  8621. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  8622. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8623. m_source.GetMatrixOrVectorElementType(type),
  8624. GetElementCount(type), nullptr));
  8625. return true;
  8626. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  8627. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8628. m_source.GetMatrixOrVectorElementType(type),
  8629. GetHLSLVecSize(type), nullptr));
  8630. return true;
  8631. case ArTypeObjectKind::AR_TOBJ_OBJECT:
  8632. // Object have no sub-types.
  8633. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type.getCanonicalType(), 1, expression));
  8634. return true;
  8635. default:
  8636. DXASSERT(false, "unreachable");
  8637. return false;
  8638. }
  8639. }
  8640. FlattenedTypeIterator::ComparisonResult
  8641. FlattenedTypeIterator::CompareIterators(
  8642. HLSLExternalSource& source,
  8643. SourceLocation loc,
  8644. FlattenedTypeIterator& leftIter,
  8645. FlattenedTypeIterator& rightIter)
  8646. {
  8647. FlattenedTypeIterator::ComparisonResult result;
  8648. result.LeftCount = 0;
  8649. result.RightCount = 0;
  8650. result.AreElementsEqual = true; // Until proven otherwise.
  8651. result.CanConvertElements = true; // Until proven otherwise.
  8652. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  8653. {
  8654. Expr* actualExpr = rightIter.getExprOrNull();
  8655. bool hasExpr = actualExpr != nullptr;
  8656. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  8657. StandardConversionSequence standard;
  8658. ExprResult convertedExpr;
  8659. if (!source.CanConvert(loc,
  8660. hasExpr ? actualExpr : &scratchExpr,
  8661. leftIter.getCurrentElement(),
  8662. ExplicitConversionFalse,
  8663. nullptr,
  8664. &standard)) {
  8665. result.AreElementsEqual = false;
  8666. result.CanConvertElements = false;
  8667. break;
  8668. }
  8669. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  8670. {
  8671. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  8672. leftIter.getCurrentElement(),
  8673. standard,
  8674. Sema::AA_Casting,
  8675. Sema::CCK_ImplicitConversion);
  8676. }
  8677. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  8678. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  8679. {
  8680. result.AreElementsEqual = false;
  8681. }
  8682. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  8683. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  8684. // If we need to apply conversions to the expressions, then advance a single element.
  8685. if (hasExpr && convertedExpr.isUsable()) {
  8686. rightIter.replaceExpr(convertedExpr.get());
  8687. advance = 1;
  8688. }
  8689. leftIter.advanceCurrentElement(advance);
  8690. rightIter.advanceCurrentElement(advance);
  8691. result.LeftCount += advance;
  8692. result.RightCount += advance;
  8693. }
  8694. result.LeftCount += leftIter.countRemaining();
  8695. result.RightCount += rightIter.countRemaining();
  8696. return result;
  8697. }
  8698. FlattenedTypeIterator::ComparisonResult
  8699. FlattenedTypeIterator::CompareTypes(
  8700. HLSLExternalSource& source,
  8701. SourceLocation leftLoc, SourceLocation rightLoc,
  8702. QualType left, QualType right)
  8703. {
  8704. FlattenedTypeIterator leftIter(leftLoc, left, source);
  8705. FlattenedTypeIterator rightIter(rightLoc, right, source);
  8706. return CompareIterators(source, leftLoc, leftIter, rightIter);
  8707. }
  8708. FlattenedTypeIterator::ComparisonResult
  8709. FlattenedTypeIterator::CompareTypesForInit(
  8710. HLSLExternalSource& source, QualType left, MultiExprArg args,
  8711. SourceLocation leftLoc, SourceLocation rightLoc)
  8712. {
  8713. FlattenedTypeIterator leftIter(leftLoc, left, source);
  8714. FlattenedTypeIterator rightIter(rightLoc, args, source);
  8715. return CompareIterators(source, leftLoc, leftIter, rightIter);
  8716. }
  8717. ////////////////////////////////////////////////////////////////////////////////
  8718. // Attribute processing support. //
  8719. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  8720. {
  8721. int64_t value = 0;
  8722. if (Attr.getNumArgs() > index)
  8723. {
  8724. Expr *E = nullptr;
  8725. if (!Attr.isArgExpr(index)) {
  8726. // For case arg is constant variable.
  8727. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  8728. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  8729. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  8730. Sema::LookupNameKind::LookupOrdinaryName));
  8731. if (!decl) {
  8732. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8733. return value;
  8734. }
  8735. Expr *init = decl->getInit();
  8736. if (!init) {
  8737. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8738. return value;
  8739. }
  8740. E = init;
  8741. } else
  8742. E = Attr.getArgAsExpr(index);
  8743. clang::APValue ArgNum;
  8744. bool displayError = false;
  8745. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  8746. {
  8747. displayError = true;
  8748. }
  8749. else
  8750. {
  8751. if (ArgNum.isInt())
  8752. {
  8753. value = ArgNum.getInt().getSExtValue();
  8754. }
  8755. else if (ArgNum.isFloat())
  8756. {
  8757. llvm::APSInt floatInt;
  8758. bool isPrecise;
  8759. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  8760. {
  8761. value = floatInt.getSExtValue();
  8762. }
  8763. else
  8764. {
  8765. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8766. }
  8767. }
  8768. else
  8769. {
  8770. displayError = true;
  8771. }
  8772. if (value < 0)
  8773. {
  8774. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8775. }
  8776. }
  8777. if (displayError)
  8778. {
  8779. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  8780. << Attr.getName() << AANT_ArgumentIntegerConstant
  8781. << E->getSourceRange();
  8782. }
  8783. }
  8784. return (int)value;
  8785. }
  8786. // TODO: support float arg directly.
  8787. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  8788. unsigned index = 0) {
  8789. int value = 0;
  8790. if (Attr.getNumArgs() > index) {
  8791. Expr *E = Attr.getArgAsExpr(index);
  8792. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  8793. llvm::APFloat flV = FL->getValue();
  8794. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  8795. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  8796. value = intV.getLimitedValue();
  8797. } else {
  8798. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  8799. value = intV.getLimitedValue();
  8800. }
  8801. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  8802. llvm::APInt intV =
  8803. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  8804. value = intV.getLimitedValue();
  8805. } else {
  8806. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  8807. << Attr.getName();
  8808. }
  8809. }
  8810. return value;
  8811. }
  8812. static Stmt* IgnoreParensAndDecay(Stmt* S)
  8813. {
  8814. for (;;)
  8815. {
  8816. switch (S->getStmtClass())
  8817. {
  8818. case Stmt::ParenExprClass:
  8819. S = cast<ParenExpr>(S)->getSubExpr();
  8820. break;
  8821. case Stmt::ImplicitCastExprClass:
  8822. {
  8823. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  8824. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  8825. castExpr->getCastKind() != CK_NoOp &&
  8826. castExpr->getCastKind() != CK_LValueToRValue)
  8827. {
  8828. return S;
  8829. }
  8830. S = castExpr->getSubExpr();
  8831. }
  8832. break;
  8833. default:
  8834. return S;
  8835. }
  8836. }
  8837. }
  8838. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  8839. {
  8840. DXASSERT_NOMSG(E != nullptr);
  8841. Expr* subscriptExpr = E->getIdx();
  8842. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  8843. if (subscriptExpr == nullptr ||
  8844. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  8845. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  8846. {
  8847. S.Diag(
  8848. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  8849. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  8850. return nullptr;
  8851. }
  8852. return E->getBase();
  8853. }
  8854. static bool IsValidClipPlaneDecl(Decl* D)
  8855. {
  8856. Decl::Kind kind = D->getKind();
  8857. if (kind == Decl::Var)
  8858. {
  8859. VarDecl* varDecl = cast<VarDecl>(D);
  8860. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  8861. varDecl->getType().isConstQualified())
  8862. {
  8863. return false;
  8864. }
  8865. return true;
  8866. }
  8867. else if (kind == Decl::Field)
  8868. {
  8869. return true;
  8870. }
  8871. return false;
  8872. }
  8873. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  8874. {
  8875. Stmt* cursor = E;
  8876. // clip plane expressions are a linear path, so no need to traverse the tree here.
  8877. while (cursor != nullptr)
  8878. {
  8879. bool supported = true;
  8880. cursor = IgnoreParensAndDecay(cursor);
  8881. switch (cursor->getStmtClass())
  8882. {
  8883. case Stmt::ArraySubscriptExprClass:
  8884. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  8885. if (cursor == nullptr)
  8886. {
  8887. // nullptr indicates failure, and the error message has already been printed out
  8888. return nullptr;
  8889. }
  8890. break;
  8891. case Stmt::DeclRefExprClass:
  8892. {
  8893. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  8894. Decl* decl = declRef->getDecl();
  8895. supported = IsValidClipPlaneDecl(decl);
  8896. cursor = supported ? nullptr : cursor;
  8897. }
  8898. break;
  8899. case Stmt::MemberExprClass:
  8900. {
  8901. MemberExpr* member = cast<MemberExpr>(cursor);
  8902. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  8903. cursor = supported ? member->getBase() : cursor;
  8904. }
  8905. break;
  8906. default:
  8907. supported = false;
  8908. break;
  8909. }
  8910. if (!supported)
  8911. {
  8912. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  8913. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  8914. return nullptr;
  8915. }
  8916. }
  8917. // Validate that the type is a float4.
  8918. QualType expressionType = E->getType();
  8919. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  8920. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  8921. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  8922. {
  8923. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  8924. return nullptr;
  8925. }
  8926. return E;
  8927. }
  8928. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  8929. {
  8930. Expr* clipExprs[6];
  8931. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  8932. {
  8933. if (A.getNumArgs() <= index)
  8934. {
  8935. clipExprs[index] = nullptr;
  8936. continue;
  8937. }
  8938. Expr *E = A.getArgAsExpr(index);
  8939. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  8940. }
  8941. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  8942. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  8943. A.getAttributeSpellingListIndex());
  8944. }
  8945. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  8946. {
  8947. int argValue = ValidateAttributeIntArg(S, Attr);
  8948. // Default value is 1.
  8949. if (Attr.getNumArgs() == 0) argValue = 1;
  8950. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  8951. argValue, Attr.getAttributeSpellingListIndex());
  8952. }
  8953. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  8954. {
  8955. Stmt::StmtClass stClass = St->getStmtClass();
  8956. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  8957. {
  8958. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  8959. << Attr.getName();
  8960. }
  8961. }
  8962. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  8963. {
  8964. Stmt::StmtClass stClass = St->getStmtClass();
  8965. if (stClass != Stmt::SwitchStmtClass)
  8966. {
  8967. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  8968. << Attr.getName();
  8969. }
  8970. }
  8971. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  8972. {
  8973. Stmt::StmtClass stClass = St->getStmtClass();
  8974. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  8975. {
  8976. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  8977. << Attr.getName();
  8978. }
  8979. }
  8980. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  8981. {
  8982. // values is an optional comma-separated list of potential values.
  8983. if (A.getNumArgs() <= index)
  8984. return StringRef();
  8985. Expr* E = A.getArgAsExpr(index);
  8986. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  8987. {
  8988. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  8989. << A.getName();
  8990. return StringRef();
  8991. }
  8992. StringLiteral* sl = cast<StringLiteral>(E);
  8993. StringRef result = sl->getString();
  8994. // Return result with no additional validation.
  8995. if (values == nullptr)
  8996. {
  8997. return result;
  8998. }
  8999. const char* value = values;
  9000. while (*value != '\0')
  9001. {
  9002. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  9003. // Look for a match.
  9004. const char* argData = result.data();
  9005. size_t argDataLen = result.size();
  9006. while (argDataLen != 0 && *argData == *value && *value)
  9007. {
  9008. ++argData;
  9009. ++value;
  9010. --argDataLen;
  9011. }
  9012. // Match found if every input character matched.
  9013. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  9014. {
  9015. return result;
  9016. }
  9017. // Move to next separator.
  9018. while (*value != '\0' && *value != ',')
  9019. {
  9020. ++value;
  9021. }
  9022. // Move to the start of the next item if any.
  9023. if (*value == ',') value++;
  9024. }
  9025. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  9026. // No match found.
  9027. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  9028. << A.getName() << values;
  9029. return StringRef();
  9030. }
  9031. static
  9032. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  9033. {
  9034. if (D->isFunctionOrFunctionTemplate())
  9035. {
  9036. return true;
  9037. }
  9038. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  9039. return false;
  9040. }
  9041. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  9042. {
  9043. DXASSERT_NOMSG(D != nullptr);
  9044. DXASSERT_NOMSG(!A.isInvalid());
  9045. Attr* declAttr = nullptr;
  9046. Handled = true;
  9047. switch (A.getKind())
  9048. {
  9049. case AttributeList::AT_HLSLIn:
  9050. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  9051. A.getAttributeSpellingListIndex());
  9052. break;
  9053. case AttributeList::AT_HLSLOut:
  9054. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  9055. A.getAttributeSpellingListIndex());
  9056. break;
  9057. case AttributeList::AT_HLSLInOut:
  9058. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  9059. A.getAttributeSpellingListIndex());
  9060. break;
  9061. case AttributeList::AT_HLSLNoInterpolation:
  9062. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  9063. A.getAttributeSpellingListIndex());
  9064. break;
  9065. case AttributeList::AT_HLSLLinear:
  9066. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  9067. A.getAttributeSpellingListIndex());
  9068. break;
  9069. case AttributeList::AT_HLSLNoPerspective:
  9070. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  9071. A.getAttributeSpellingListIndex());
  9072. break;
  9073. case AttributeList::AT_HLSLSample:
  9074. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  9075. A.getAttributeSpellingListIndex());
  9076. break;
  9077. case AttributeList::AT_HLSLCentroid:
  9078. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  9079. A.getAttributeSpellingListIndex());
  9080. break;
  9081. case AttributeList::AT_HLSLPrecise:
  9082. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  9083. A.getAttributeSpellingListIndex());
  9084. break;
  9085. case AttributeList::AT_HLSLShared:
  9086. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  9087. A.getAttributeSpellingListIndex());
  9088. break;
  9089. case AttributeList::AT_HLSLGroupShared:
  9090. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  9091. A.getAttributeSpellingListIndex());
  9092. break;
  9093. case AttributeList::AT_HLSLUniform:
  9094. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  9095. A.getAttributeSpellingListIndex());
  9096. break;
  9097. case AttributeList::AT_HLSLColumnMajor:
  9098. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  9099. A.getAttributeSpellingListIndex());
  9100. break;
  9101. case AttributeList::AT_HLSLRowMajor:
  9102. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  9103. A.getAttributeSpellingListIndex());
  9104. break;
  9105. case AttributeList::AT_HLSLUnorm:
  9106. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  9107. A.getAttributeSpellingListIndex());
  9108. break;
  9109. case AttributeList::AT_HLSLSnorm:
  9110. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  9111. A.getAttributeSpellingListIndex());
  9112. break;
  9113. case AttributeList::AT_HLSLPoint:
  9114. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  9115. A.getAttributeSpellingListIndex());
  9116. break;
  9117. case AttributeList::AT_HLSLLine:
  9118. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  9119. A.getAttributeSpellingListIndex());
  9120. break;
  9121. case AttributeList::AT_HLSLLineAdj:
  9122. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  9123. A.getAttributeSpellingListIndex());
  9124. break;
  9125. case AttributeList::AT_HLSLTriangle:
  9126. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  9127. A.getAttributeSpellingListIndex());
  9128. break;
  9129. case AttributeList::AT_HLSLTriangleAdj:
  9130. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  9131. A.getAttributeSpellingListIndex());
  9132. break;
  9133. case AttributeList::AT_HLSLGloballyCoherent:
  9134. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  9135. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9136. break;
  9137. default:
  9138. Handled = false;
  9139. break;
  9140. }
  9141. if (declAttr != nullptr)
  9142. {
  9143. DXASSERT_NOMSG(Handled);
  9144. D->addAttr(declAttr);
  9145. return;
  9146. }
  9147. Handled = true;
  9148. switch (A.getKind())
  9149. {
  9150. // These apply to statements, not declarations. The warning messages clarify this properly.
  9151. case AttributeList::AT_HLSLUnroll:
  9152. case AttributeList::AT_HLSLAllowUAVCondition:
  9153. case AttributeList::AT_HLSLLoop:
  9154. case AttributeList::AT_HLSLFastOpt:
  9155. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9156. << A.getName();
  9157. return;
  9158. case AttributeList::AT_HLSLBranch:
  9159. case AttributeList::AT_HLSLFlatten:
  9160. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9161. << A.getName();
  9162. return;
  9163. case AttributeList::AT_HLSLForceCase:
  9164. case AttributeList::AT_HLSLCall:
  9165. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9166. << A.getName();
  9167. return;
  9168. // These are the cases that actually apply to declarations.
  9169. case AttributeList::AT_HLSLClipPlanes:
  9170. declAttr = HandleClipPlanes(S, A);
  9171. break;
  9172. case AttributeList::AT_HLSLDomain:
  9173. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  9174. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  9175. break;
  9176. case AttributeList::AT_HLSLEarlyDepthStencil:
  9177. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9178. break;
  9179. case AttributeList::AT_HLSLInstance:
  9180. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  9181. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9182. break;
  9183. case AttributeList::AT_HLSLMaxTessFactor:
  9184. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  9185. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  9186. break;
  9187. case AttributeList::AT_HLSLNumThreads:
  9188. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  9189. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  9190. A.getAttributeSpellingListIndex());
  9191. break;
  9192. case AttributeList::AT_HLSLRootSignature:
  9193. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  9194. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  9195. A.getAttributeSpellingListIndex());
  9196. break;
  9197. case AttributeList::AT_HLSLOutputControlPoints:
  9198. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  9199. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9200. break;
  9201. case AttributeList::AT_HLSLOutputTopology:
  9202. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  9203. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  9204. break;
  9205. case AttributeList::AT_HLSLPartitioning:
  9206. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  9207. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  9208. break;
  9209. case AttributeList::AT_HLSLPatchConstantFunc:
  9210. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  9211. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  9212. break;
  9213. case AttributeList::AT_HLSLShader:
  9214. declAttr = ::new (S.Context) HLSLShaderAttr(
  9215. A.getRange(), S.Context,
  9216. ValidateAttributeStringArg(S, A,
  9217. "compute,vertex,pixel,hull,domain,geometry,raygeneration,intersection,anyhit,closesthit,miss,callable"),
  9218. A.getAttributeSpellingListIndex());
  9219. break;
  9220. case AttributeList::AT_HLSLMaxVertexCount:
  9221. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  9222. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9223. break;
  9224. case AttributeList::AT_HLSLExperimental:
  9225. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  9226. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  9227. A.getAttributeSpellingListIndex());
  9228. break;
  9229. case AttributeList::AT_NoInline:
  9230. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9231. break;
  9232. default:
  9233. Handled = false;
  9234. break; // SPIRV Change: was return;
  9235. }
  9236. if (declAttr != nullptr)
  9237. {
  9238. DXASSERT_NOMSG(Handled);
  9239. D->addAttr(declAttr);
  9240. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  9241. // and prevent code generation.
  9242. ValidateAttributeTargetIsFunction(S, D, A);
  9243. return; // SPIRV Change
  9244. }
  9245. // SPIRV Change Starts
  9246. Handled = true;
  9247. switch (A.getKind())
  9248. {
  9249. case AttributeList::AT_VKBuiltIn:
  9250. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  9251. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation"),
  9252. A.getAttributeSpellingListIndex());
  9253. break;
  9254. case AttributeList::AT_VKLocation:
  9255. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  9256. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9257. break;
  9258. case AttributeList::AT_VKBinding:
  9259. declAttr = ::new (S.Context) VKBindingAttr(A.getRange(), S.Context,
  9260. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1),
  9261. A.getAttributeSpellingListIndex());
  9262. break;
  9263. case AttributeList::AT_VKCounterBinding:
  9264. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  9265. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9266. break;
  9267. case AttributeList::AT_VKPushConstant:
  9268. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  9269. A.getAttributeSpellingListIndex());
  9270. break;
  9271. case AttributeList::AT_VKOffset:
  9272. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  9273. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9274. break;
  9275. case AttributeList::AT_VKInputAttachmentIndex:
  9276. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  9277. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  9278. A.getAttributeSpellingListIndex());
  9279. break;
  9280. case AttributeList::AT_VKConstantId:
  9281. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  9282. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9283. break;
  9284. default:
  9285. Handled = false;
  9286. return;
  9287. }
  9288. if (declAttr != nullptr)
  9289. {
  9290. DXASSERT_NOMSG(Handled);
  9291. D->addAttr(declAttr);
  9292. }
  9293. // SPIRV Change Ends
  9294. }
  9295. /// <summary>Processes an attribute for a statement.</summary>
  9296. /// <param name="S">Sema with context.</param>
  9297. /// <param name="St">Statement annotated.</param>
  9298. /// <param name="A">Single parsed attribute to process.</param>
  9299. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  9300. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  9301. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  9302. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  9303. {
  9304. // | Construct | Allowed Attributes |
  9305. // +------------------+--------------------------------------------+
  9306. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  9307. // | if | branch, flatten |
  9308. // | switch | branch, flatten, forcecase, call |
  9309. Attr * result = nullptr;
  9310. Handled = true;
  9311. switch (A.getKind())
  9312. {
  9313. case AttributeList::AT_HLSLUnroll:
  9314. ValidateAttributeOnLoop(S, St, A);
  9315. result = HandleUnrollAttribute(S, A);
  9316. break;
  9317. case AttributeList::AT_HLSLAllowUAVCondition:
  9318. ValidateAttributeOnLoop(S, St, A);
  9319. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  9320. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9321. break;
  9322. case AttributeList::AT_HLSLLoop:
  9323. ValidateAttributeOnLoop(S, St, A);
  9324. result = ::new (S.Context) HLSLLoopAttr(
  9325. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9326. break;
  9327. case AttributeList::AT_HLSLFastOpt:
  9328. ValidateAttributeOnLoop(S, St, A);
  9329. result = ::new (S.Context) HLSLFastOptAttr(
  9330. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9331. break;
  9332. case AttributeList::AT_HLSLBranch:
  9333. ValidateAttributeOnSwitchOrIf(S, St, A);
  9334. result = ::new (S.Context) HLSLBranchAttr(
  9335. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9336. break;
  9337. case AttributeList::AT_HLSLFlatten:
  9338. ValidateAttributeOnSwitchOrIf(S, St, A);
  9339. result = ::new (S.Context) HLSLFlattenAttr(
  9340. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9341. break;
  9342. case AttributeList::AT_HLSLForceCase:
  9343. ValidateAttributeOnSwitch(S, St, A);
  9344. result = ::new (S.Context) HLSLForceCaseAttr(
  9345. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9346. break;
  9347. case AttributeList::AT_HLSLCall:
  9348. ValidateAttributeOnSwitch(S, St, A);
  9349. result = ::new (S.Context) HLSLCallAttr(
  9350. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9351. break;
  9352. default:
  9353. Handled = false;
  9354. break;
  9355. }
  9356. return result;
  9357. }
  9358. ////////////////////////////////////////////////////////////////////////////////
  9359. // Implementation of Sema members. //
  9360. Decl* Sema::ActOnStartHLSLBuffer(
  9361. Scope* bufferScope,
  9362. bool cbuffer, SourceLocation KwLoc,
  9363. IdentifierInfo *Ident, SourceLocation IdentLoc,
  9364. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  9365. SourceLocation LBrace)
  9366. {
  9367. // For anonymous namespace, take the location of the left brace.
  9368. SourceLocation Loc = Ident ? IdentLoc : LBrace;
  9369. DeclContext* lexicalParent = getCurLexicalContext();
  9370. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9371. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  9372. Ident, IdentLoc, BufferAttributes, LBrace);
  9373. // Keep track of the currently active buffer.
  9374. HLSLBuffers.push_back(result);
  9375. // Validate unusual annotations and emit diagnostics.
  9376. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  9377. auto && unusualIter = BufferAttributes.begin();
  9378. auto && unusualEnd = BufferAttributes.end();
  9379. char expectedRegisterType = cbuffer ? 'b' : 't';
  9380. for (; unusualIter != unusualEnd; ++unusualIter) {
  9381. switch ((*unusualIter)->getKind()) {
  9382. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9383. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  9384. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  9385. break;
  9386. }
  9387. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9388. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  9389. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  9390. Diag(registerAssignment->Loc, cbuffer ? diag::err_hlsl_unsupported_cbuffer_register :
  9391. diag::err_hlsl_unsupported_tbuffer_register);
  9392. } else if (registerAssignment->ShaderProfile.size() > 0) {
  9393. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  9394. }
  9395. break;
  9396. }
  9397. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9398. // Ignore semantic declarations.
  9399. break;
  9400. }
  9401. }
  9402. }
  9403. PushOnScopeChains(result, bufferScope);
  9404. PushDeclContext(bufferScope, result);
  9405. ActOnDocumentableDecl(result);
  9406. return result;
  9407. }
  9408. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  9409. {
  9410. DXASSERT_NOMSG(Dcl != nullptr);
  9411. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9412. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  9413. HLSLBuffers.pop_back();
  9414. PopDeclContext();
  9415. }
  9416. Decl* Sema::getActiveHLSLBuffer() const
  9417. {
  9418. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  9419. }
  9420. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  9421. DeclGroupPtrTy &dcl, bool iscbuf) {
  9422. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9423. HLSLBuffers.pop_back();
  9424. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9425. Decl *decl = dcl.get().getSingleDecl();
  9426. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  9427. IdentifierInfo *Ident = namedDecl->getIdentifier();
  9428. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  9429. SourceLocation Loc = decl->getLocation();
  9430. // Prevent array type in template. The only way to specify an array in the template type
  9431. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  9432. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  9433. QualType declType = cast<VarDecl>(namedDecl)->getType();
  9434. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  9435. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  9436. declType = arrayType->getElementType();
  9437. }
  9438. if (declType->isArrayType()) {
  9439. Diag(Loc, diag::err_hlsl_typeintemplateargument) << "array";
  9440. return nullptr;
  9441. }
  9442. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  9443. DeclContext *lexicalParent = getCurLexicalContext();
  9444. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9445. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  9446. KwLoc, Ident, Loc, hlslAttrs, Loc);
  9447. // set relation
  9448. namedDecl->setDeclContext(result);
  9449. result->addDecl(namedDecl);
  9450. // move attribute from constant to constant buffer
  9451. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  9452. namedDecl->setUnusualAnnotations(hlslAttrs);
  9453. return result;
  9454. }
  9455. bool Sema::IsOnHLSLBufferView() {
  9456. // nullptr will not pushed for cbuffer.
  9457. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  9458. }
  9459. void Sema::ActOnStartHLSLBufferView() {
  9460. // Push nullptr to mark HLSLBufferView.
  9461. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9462. HLSLBuffers.emplace_back(nullptr);
  9463. }
  9464. HLSLBufferDecl::HLSLBufferDecl(
  9465. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  9466. IdentifierInfo *Id, SourceLocation IdLoc,
  9467. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9468. SourceLocation LBrace)
  9469. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  9470. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  9471. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  9472. if (!BufferAttributes.empty()) {
  9473. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  9474. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  9475. }
  9476. }
  9477. HLSLBufferDecl *
  9478. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  9479. bool constantbuffer, SourceLocation KwLoc,
  9480. IdentifierInfo *Id, SourceLocation IdLoc,
  9481. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9482. SourceLocation LBrace) {
  9483. DeclContext *DC = C.getTranslationUnitDecl();
  9484. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  9485. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  9486. if (DC != lexicalParent) {
  9487. result->setLexicalDeclContext(lexicalParent);
  9488. }
  9489. return result;
  9490. }
  9491. const char *HLSLBufferDecl::getDeclKindName() const {
  9492. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  9493. "ConstantBuffer"};
  9494. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  9495. return HLSLBufferNames[index];
  9496. }
  9497. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  9498. assert(NewDecl != nullptr);
  9499. if (!getLangOpts().HLSL) {
  9500. return;
  9501. }
  9502. if (!D.UnusualAnnotations.empty()) {
  9503. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  9504. getASTContext(), D.UnusualAnnotations.data(),
  9505. D.UnusualAnnotations.size()));
  9506. D.UnusualAnnotations.clear();
  9507. }
  9508. }
  9509. /// Checks whether a usage attribute is compatible with those seen so far and
  9510. /// maintains history.
  9511. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  9512. bool &usageOut) {
  9513. switch (kind) {
  9514. case AttributeList::AT_HLSLIn:
  9515. if (usageIn)
  9516. return false;
  9517. usageIn = true;
  9518. break;
  9519. case AttributeList::AT_HLSLOut:
  9520. if (usageOut)
  9521. return false;
  9522. usageOut = true;
  9523. break;
  9524. default:
  9525. assert(kind == AttributeList::AT_HLSLInOut);
  9526. if (usageOut || usageIn)
  9527. return false;
  9528. usageIn = usageOut = true;
  9529. break;
  9530. }
  9531. return true;
  9532. }
  9533. // Diagnose valid/invalid modifiers for HLSL.
  9534. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC,
  9535. TypeSourceInfo *TInfo, bool isParameter) {
  9536. assert(getLangOpts().HLSL &&
  9537. "otherwise this is called without checking language first");
  9538. // NOTE: some tests may declare templates.
  9539. if (DC->isNamespace() || DC->isDependentContext()) return true;
  9540. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  9541. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  9542. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  9543. assert(!DC->isNamespace() && "otherwise parser accepted a namespace instead of failing a syntax error");
  9544. bool result = true;
  9545. bool isTypedef = storage == DeclSpec::SCS_typedef;
  9546. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  9547. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  9548. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->getDeclKind() == Decl::HLSLBuffer);
  9549. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  9550. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  9551. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  9552. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  9553. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  9554. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  9555. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  9556. // Function declarations are not allowed in parameter declaration
  9557. // TODO : Remove this check once we support function declarations/pointers in HLSL
  9558. if (isParameter && isFunction) {
  9559. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  9560. D.setInvalidType();
  9561. return false;
  9562. }
  9563. assert(
  9564. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  9565. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  9566. (isParameter ? 1 : 0))
  9567. && "exactly one type of declarator is being processed");
  9568. // qt/pType captures either the type being modified, or the return type in the
  9569. // case of a function (or method).
  9570. QualType qt = TInfo->getType();
  9571. const Type* pType = qt.getTypePtrOrNull();
  9572. // Early checks - these are not simple attribution errors, but constructs that
  9573. // are fundamentally unsupported,
  9574. // and so we avoid errors that might indicate they can be repaired.
  9575. if (DC->isRecord()) {
  9576. unsigned int nestedDiagId = 0;
  9577. if (isTypedef) {
  9578. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  9579. }
  9580. if (nestedDiagId) {
  9581. Diag(D.getLocStart(), nestedDiagId);
  9582. D.setInvalidType();
  9583. return false;
  9584. }
  9585. }
  9586. const char* declarationType =
  9587. (isLocalVar) ? "local variable" :
  9588. (isTypedef) ? "typedef" :
  9589. (isFunction) ? "function" :
  9590. (isMethod) ? "method" :
  9591. (isGlobal) ? "global variable" :
  9592. (isParameter) ? "parameter" :
  9593. (isField) ? "field" : "<unknown>";
  9594. if (pType && D.isFunctionDeclarator()) {
  9595. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  9596. if (pFP) {
  9597. qt = pFP->getReturnType();
  9598. pType = qt.getTypePtrOrNull();
  9599. }
  9600. }
  9601. // Check for deprecated effect object type here, warn, and invalidate decl
  9602. bool bDeprecatedEffectObject = false;
  9603. bool bIsObject = false;
  9604. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  9605. bIsObject = true;
  9606. if (bDeprecatedEffectObject) {
  9607. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  9608. D.setInvalidType();
  9609. return false;
  9610. }
  9611. // Add methods if not ready.
  9612. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9613. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  9614. } else if (qt->isArrayType()) {
  9615. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  9616. while (eltQt->isArrayType())
  9617. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  9618. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  9619. // Add methods if not ready.
  9620. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9621. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  9622. }
  9623. }
  9624. if (isExtern) {
  9625. if (!(isFunction || isGlobal)) {
  9626. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  9627. << declarationType;
  9628. result = false;
  9629. }
  9630. }
  9631. if (isStatic) {
  9632. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  9633. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  9634. << declarationType;
  9635. result = false;
  9636. }
  9637. }
  9638. if (isVolatile) {
  9639. if (!(isLocalVar || isTypedef)) {
  9640. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  9641. << declarationType;
  9642. result = false;
  9643. }
  9644. }
  9645. if (isConst) {
  9646. if (isField && !isStatic) {
  9647. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  9648. << declarationType;
  9649. result = false;
  9650. }
  9651. }
  9652. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9653. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  9654. if (hasSignSpec) {
  9655. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  9656. // vectors or matrices can only have unsigned integer types.
  9657. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  9658. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  9659. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  9660. << g_ArBasicTypeNames[basicKind];
  9661. result = false;
  9662. }
  9663. }
  9664. else {
  9665. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  9666. result = false;
  9667. }
  9668. }
  9669. // Validate attributes
  9670. clang::AttributeList
  9671. *pPrecise = nullptr,
  9672. *pShared = nullptr,
  9673. *pGroupShared = nullptr,
  9674. *pUniform = nullptr,
  9675. *pUsage = nullptr,
  9676. *pNoInterpolation = nullptr,
  9677. *pLinear = nullptr,
  9678. *pNoPerspective = nullptr,
  9679. *pSample = nullptr,
  9680. *pCentroid = nullptr,
  9681. *pAnyLinear = nullptr, // first linear attribute found
  9682. *pTopology = nullptr;
  9683. bool usageIn = false;
  9684. bool usageOut = false;
  9685. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  9686. pAttr != NULL; pAttr = pAttr->getNext()) {
  9687. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  9688. continue;
  9689. switch (pAttr->getKind()) {
  9690. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  9691. pPrecise = pAttr;
  9692. break;
  9693. case AttributeList::AT_HLSLShared:
  9694. if (!isGlobal) {
  9695. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9696. << pAttr->getName() << declarationType << pAttr->getRange();
  9697. result = false;
  9698. }
  9699. if (isStatic) {
  9700. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9701. << "'static'" << pAttr->getName() << declarationType
  9702. << pAttr->getRange();
  9703. result = false;
  9704. }
  9705. pShared = pAttr;
  9706. break;
  9707. case AttributeList::AT_HLSLGroupShared:
  9708. if (!isGlobal) {
  9709. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9710. << pAttr->getName() << declarationType << pAttr->getRange();
  9711. result = false;
  9712. }
  9713. if (isExtern) {
  9714. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9715. << "'extern'" << pAttr->getName() << declarationType
  9716. << pAttr->getRange();
  9717. result = false;
  9718. }
  9719. pGroupShared = pAttr;
  9720. break;
  9721. case AttributeList::AT_HLSLGloballyCoherent:
  9722. if (!bIsObject) {
  9723. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9724. << pAttr->getName() << "non-UAV type";
  9725. result = false;
  9726. }
  9727. break;
  9728. case AttributeList::AT_HLSLUniform:
  9729. if (!(isGlobal || isParameter)) {
  9730. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9731. << pAttr->getName() << declarationType << pAttr->getRange();
  9732. result = false;
  9733. }
  9734. if (isStatic) {
  9735. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9736. << "'static'" << pAttr->getName() << declarationType
  9737. << pAttr->getRange();
  9738. result = false;
  9739. }
  9740. pUniform = pAttr;
  9741. break;
  9742. case AttributeList::AT_HLSLIn:
  9743. case AttributeList::AT_HLSLOut:
  9744. case AttributeList::AT_HLSLInOut:
  9745. if (!isParameter) {
  9746. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  9747. << pAttr->getName() << pAttr->getRange();
  9748. result = false;
  9749. }
  9750. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  9751. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  9752. << pAttr->getName() << pAttr->getRange();
  9753. result = false;
  9754. }
  9755. pUsage = pAttr;
  9756. break;
  9757. case AttributeList::AT_HLSLNoInterpolation:
  9758. if (!(isParameter || isField || isFunction)) {
  9759. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9760. << pAttr->getName() << declarationType << pAttr->getRange();
  9761. result = false;
  9762. }
  9763. if (pNoInterpolation) {
  9764. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9765. << pAttr->getName() << pAttr->getRange();
  9766. }
  9767. pNoInterpolation = pAttr;
  9768. break;
  9769. case AttributeList::AT_HLSLLinear:
  9770. case AttributeList::AT_HLSLNoPerspective:
  9771. case AttributeList::AT_HLSLSample:
  9772. case AttributeList::AT_HLSLCentroid:
  9773. if (!(isParameter || isField || isFunction)) {
  9774. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9775. << pAttr->getName() << declarationType << pAttr->getRange();
  9776. result = false;
  9777. }
  9778. if (nullptr == pAnyLinear)
  9779. pAnyLinear = pAttr;
  9780. switch (pAttr->getKind()) {
  9781. case AttributeList::AT_HLSLLinear:
  9782. if (pLinear) {
  9783. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9784. << pAttr->getName() << pAttr->getRange();
  9785. }
  9786. pLinear = pAttr;
  9787. break;
  9788. case AttributeList::AT_HLSLNoPerspective:
  9789. if (pNoPerspective) {
  9790. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9791. << pAttr->getName() << pAttr->getRange();
  9792. }
  9793. pNoPerspective = pAttr;
  9794. break;
  9795. case AttributeList::AT_HLSLSample:
  9796. if (pSample) {
  9797. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9798. << pAttr->getName() << pAttr->getRange();
  9799. }
  9800. pSample = pAttr;
  9801. break;
  9802. case AttributeList::AT_HLSLCentroid:
  9803. if (pCentroid) {
  9804. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9805. << pAttr->getName() << pAttr->getRange();
  9806. }
  9807. pCentroid = pAttr;
  9808. break;
  9809. }
  9810. break;
  9811. case AttributeList::AT_HLSLPoint:
  9812. case AttributeList::AT_HLSLLine:
  9813. case AttributeList::AT_HLSLLineAdj:
  9814. case AttributeList::AT_HLSLTriangle:
  9815. case AttributeList::AT_HLSLTriangleAdj:
  9816. if (!(isParameter)) {
  9817. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9818. << pAttr->getName() << declarationType << pAttr->getRange();
  9819. result = false;
  9820. }
  9821. if (pTopology) {
  9822. if (pTopology->getKind() == pAttr->getKind()) {
  9823. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9824. << pAttr->getName() << pAttr->getRange();
  9825. } else {
  9826. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9827. << pAttr->getName() << pTopology->getName()
  9828. << declarationType << pAttr->getRange();
  9829. result = false;
  9830. }
  9831. }
  9832. pTopology = pAttr;
  9833. break;
  9834. default:
  9835. break;
  9836. }
  9837. }
  9838. if (pNoInterpolation && pAnyLinear) {
  9839. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  9840. << pNoInterpolation->getName() << pAnyLinear->getName()
  9841. << declarationType << pNoInterpolation->getRange();
  9842. result = false;
  9843. }
  9844. if (pSample && pCentroid) {
  9845. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  9846. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  9847. }
  9848. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  9849. pNoInterpolation ? pNoInterpolation : pTopology);
  9850. if (pUniform && pNonUniformAttr) {
  9851. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  9852. << pNonUniformAttr->getName()
  9853. << pUniform->getName() << declarationType << pUniform->getRange();
  9854. result = false;
  9855. }
  9856. if (pAnyLinear && pTopology) {
  9857. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  9858. << pTopology->getName()
  9859. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  9860. result = false;
  9861. }
  9862. if (pNoInterpolation && pTopology) {
  9863. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  9864. << pTopology->getName()
  9865. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  9866. result = false;
  9867. }
  9868. if (pUniform && pUsage) {
  9869. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  9870. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  9871. << pUsage->getName() << pUniform->getName() << declarationType
  9872. << pUniform->getRange();
  9873. result = false;
  9874. }
  9875. }
  9876. // Validate that stream-ouput objects are marked as inout
  9877. if (isParameter && !(usageIn && usageOut) &&
  9878. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  9879. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  9880. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  9881. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  9882. result = false;
  9883. }
  9884. // SPIRV change starts
  9885. #ifdef ENABLE_SPIRV_CODEGEN
  9886. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  9887. if (!getLangOpts().SPIRV) {
  9888. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  9889. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  9890. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  9891. << g_ArBasicTypeNames[basicKind];
  9892. result = false;
  9893. }
  9894. }
  9895. #endif // ENABLE_SPIRV_CODEGEN
  9896. // SPIRV change ends
  9897. // Validate unusual annotations.
  9898. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  9899. auto && unusualIter = D.UnusualAnnotations.begin();
  9900. auto && unusualEnd = D.UnusualAnnotations.end();
  9901. for (; unusualIter != unusualEnd; ++unusualIter) {
  9902. switch ((*unusualIter)->getKind()) {
  9903. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9904. hlsl::ConstantPacking *constantPacking =
  9905. cast<hlsl::ConstantPacking>(*unusualIter);
  9906. if (!isGlobal || HLSLBuffers.size() == 0) {
  9907. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  9908. continue;
  9909. }
  9910. if (constantPacking->ComponentOffset > 0) {
  9911. // Validate that this will fit.
  9912. if (!qt.isNull()) {
  9913. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  9914. constantPacking->ComponentOffset);
  9915. }
  9916. }
  9917. break;
  9918. }
  9919. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9920. hlsl::RegisterAssignment *registerAssignment =
  9921. cast<hlsl::RegisterAssignment>(*unusualIter);
  9922. if (registerAssignment->IsValid) {
  9923. if (!qt.isNull()) {
  9924. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  9925. registerAssignment->RegisterType);
  9926. }
  9927. }
  9928. break;
  9929. }
  9930. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9931. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  9932. if (isTypedef || isLocalVar) {
  9933. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  9934. << "semantic" << declarationType;
  9935. }
  9936. break;
  9937. }
  9938. }
  9939. }
  9940. if (!result) {
  9941. D.setInvalidType();
  9942. }
  9943. return result;
  9944. }
  9945. // Diagnose HLSL types on lookup
  9946. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  9947. const DeclarationNameInfo declName = R.getLookupNameInfo();
  9948. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  9949. if (idInfo) {
  9950. StringRef nameIdentifier = idInfo->getName();
  9951. HLSLScalarType parsedType;
  9952. int rowCount, colCount;
  9953. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  9954. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  9955. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  9956. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  9957. }
  9958. }
  9959. return true;
  9960. }
  9961. static QualType getUnderlyingType(QualType Type)
  9962. {
  9963. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  9964. {
  9965. if (const TypedefNameDecl* pDecl = TD->getDecl())
  9966. Type = pDecl->getUnderlyingType();
  9967. else
  9968. break;
  9969. }
  9970. return Type;
  9971. }
  9972. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  9973. /// <param name="self">Sema with context.</param>
  9974. /// <param name="type">QualType to inspect.</param>
  9975. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  9976. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  9977. void hlsl::GetHLSLAttributedTypes(
  9978. _In_ clang::Sema* self,
  9979. clang::QualType type,
  9980. _Inout_opt_ const clang::AttributedType** ppMatrixOrientation,
  9981. _Inout_opt_ const clang::AttributedType** ppNorm)
  9982. {
  9983. if (ppMatrixOrientation)
  9984. *ppMatrixOrientation = nullptr;
  9985. if (ppNorm)
  9986. *ppNorm = nullptr;
  9987. // Note: we clear output pointers once set so we can stop searching
  9988. QualType Desugared = getUnderlyingType(type);
  9989. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  9990. while (AT && (ppMatrixOrientation || ppNorm)) {
  9991. AttributedType::Kind Kind = AT->getAttrKind();
  9992. if (Kind == AttributedType::attr_hlsl_row_major ||
  9993. Kind == AttributedType::attr_hlsl_column_major)
  9994. {
  9995. if (ppMatrixOrientation)
  9996. {
  9997. *ppMatrixOrientation = AT;
  9998. ppMatrixOrientation = nullptr;
  9999. }
  10000. }
  10001. else if (Kind == AttributedType::attr_hlsl_unorm ||
  10002. Kind == AttributedType::attr_hlsl_snorm)
  10003. {
  10004. if (ppNorm)
  10005. {
  10006. *ppNorm = AT;
  10007. ppNorm = nullptr;
  10008. }
  10009. }
  10010. Desugared = getUnderlyingType(AT->getEquivalentType());
  10011. AT = dyn_cast<AttributedType>(Desugared);
  10012. }
  10013. // Unwrap component type on vector or matrix and check snorm/unorm
  10014. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  10015. AT = dyn_cast<AttributedType>(Desugared);
  10016. while (AT && ppNorm) {
  10017. AttributedType::Kind Kind = AT->getAttrKind();
  10018. if (Kind == AttributedType::attr_hlsl_unorm ||
  10019. Kind == AttributedType::attr_hlsl_snorm)
  10020. {
  10021. *ppNorm = AT;
  10022. ppNorm = nullptr;
  10023. }
  10024. Desugared = getUnderlyingType(AT->getEquivalentType());
  10025. AT = dyn_cast<AttributedType>(Desugared);
  10026. }
  10027. }
  10028. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  10029. /// <param name="self">Sema with context.</param>
  10030. /// <param name="type">QualType to check.</param>
  10031. bool hlsl::IsMatrixType(
  10032. _In_ clang::Sema* self,
  10033. _In_ clang::QualType type)
  10034. {
  10035. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  10036. }
  10037. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  10038. /// <param name="self">Sema with context.</param>
  10039. /// <param name="type">QualType to check.</param>
  10040. bool hlsl::IsVectorType(
  10041. _In_ clang::Sema* self,
  10042. _In_ clang::QualType type)
  10043. {
  10044. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  10045. }
  10046. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  10047. /// <param name="self">Sema with context.</param>
  10048. /// <param name="type">Matrix or Vector type.</param>
  10049. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  10050. _In_ clang::QualType type)
  10051. {
  10052. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  10053. // without losing the AttributedType on the template parameter
  10054. if (const Type* pType = type.getTypePtrOrNull()) {
  10055. // A non-dependent template specialization type is always "sugar",
  10056. // typically for a RecordType. For example, a class template
  10057. // specialization type of @c vector<int> will refer to a tag type for
  10058. // the instantiation @c std::vector<int, std::allocator<int>>.
  10059. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  10060. // If we have enough arguments, pull them from the template directly, rather than doing
  10061. // the extra lookups.
  10062. if (pTemplate->getNumArgs() > 0)
  10063. return pTemplate->getArg(0).getAsType();
  10064. QualType templateRecord = pTemplate->desugar();
  10065. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  10066. if (pTemplateRecordType) {
  10067. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  10068. if (pTemplateTagType) {
  10069. const ClassTemplateSpecializationDecl *specializationDecl =
  10070. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  10071. pTemplateTagType->getDecl());
  10072. if (specializationDecl) {
  10073. return specializationDecl->getTemplateArgs()[0].getAsType();
  10074. }
  10075. }
  10076. }
  10077. }
  10078. }
  10079. return QualType();
  10080. }
  10081. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  10082. /// <param name="self">Sema with context.</param>
  10083. /// <param name="type">Input type.</param>
  10084. clang::QualType hlsl::GetOriginalElementType(
  10085. _In_ clang::Sema* self,
  10086. _In_ clang::QualType type)
  10087. {
  10088. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  10089. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  10090. return GetOriginalMatrixOrVectorElementType(type);
  10091. }
  10092. return type;
  10093. }
  10094. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  10095. switch (A->getKind()) {
  10096. // Parameter modifiers
  10097. case clang::attr::HLSLIn:
  10098. Out << "in ";
  10099. break;
  10100. case clang::attr::HLSLInOut:
  10101. Out << "inout ";
  10102. break;
  10103. case clang::attr::HLSLOut:
  10104. Out << "out ";
  10105. break;
  10106. // Interpolation modifiers
  10107. case clang::attr::HLSLLinear:
  10108. Out << "linear ";
  10109. break;
  10110. case clang::attr::HLSLCentroid:
  10111. Out << "centroid ";
  10112. break;
  10113. case clang::attr::HLSLNoInterpolation:
  10114. Out << "nointerpolation ";
  10115. break;
  10116. case clang::attr::HLSLNoPerspective:
  10117. Out << "noperspective ";
  10118. break;
  10119. case clang::attr::HLSLSample:
  10120. Out << "sample ";
  10121. break;
  10122. // Function attributes
  10123. case clang::attr::HLSLClipPlanes:
  10124. {
  10125. Attr * noconst = const_cast<Attr*>(A);
  10126. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  10127. if (!ACast->getClipPlane1())
  10128. break;
  10129. Indent(Indentation, Out);
  10130. Out << "[clipplanes(";
  10131. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  10132. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  10133. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  10134. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  10135. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  10136. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  10137. Out << ")]\n";
  10138. break;
  10139. }
  10140. case clang::attr::HLSLDomain:
  10141. {
  10142. Attr * noconst = const_cast<Attr*>(A);
  10143. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  10144. Indent(Indentation, Out);
  10145. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  10146. break;
  10147. }
  10148. case clang::attr::HLSLEarlyDepthStencil:
  10149. Indent(Indentation, Out);
  10150. Out << "[earlydepthstencil]\n";
  10151. break;
  10152. case clang::attr::HLSLInstance: //TODO - test
  10153. {
  10154. Attr * noconst = const_cast<Attr*>(A);
  10155. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  10156. Indent(Indentation, Out);
  10157. Out << "[instance(" << ACast->getCount() << ")]\n";
  10158. break;
  10159. }
  10160. case clang::attr::HLSLMaxTessFactor: //TODO - test
  10161. {
  10162. Attr * noconst = const_cast<Attr*>(A);
  10163. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  10164. Indent(Indentation, Out);
  10165. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  10166. break;
  10167. }
  10168. case clang::attr::HLSLNumThreads: //TODO - test
  10169. {
  10170. Attr * noconst = const_cast<Attr*>(A);
  10171. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  10172. Indent(Indentation, Out);
  10173. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  10174. break;
  10175. }
  10176. case clang::attr::HLSLRootSignature:
  10177. {
  10178. Attr * noconst = const_cast<Attr*>(A);
  10179. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  10180. Indent(Indentation, Out);
  10181. Out << "[RootSignature(" << ACast->getSignatureName() << ")]\n";
  10182. break;
  10183. }
  10184. case clang::attr::HLSLOutputControlPoints:
  10185. {
  10186. Attr * noconst = const_cast<Attr*>(A);
  10187. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  10188. Indent(Indentation, Out);
  10189. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  10190. break;
  10191. }
  10192. case clang::attr::HLSLOutputTopology:
  10193. {
  10194. Attr * noconst = const_cast<Attr*>(A);
  10195. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  10196. Indent(Indentation, Out);
  10197. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  10198. break;
  10199. }
  10200. case clang::attr::HLSLPartitioning:
  10201. {
  10202. Attr * noconst = const_cast<Attr*>(A);
  10203. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  10204. Indent(Indentation, Out);
  10205. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  10206. break;
  10207. }
  10208. case clang::attr::HLSLPatchConstantFunc:
  10209. {
  10210. Attr * noconst = const_cast<Attr*>(A);
  10211. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  10212. Indent(Indentation, Out);
  10213. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  10214. break;
  10215. }
  10216. case clang::attr::HLSLShader:
  10217. {
  10218. Attr * noconst = const_cast<Attr*>(A);
  10219. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  10220. Indent(Indentation, Out);
  10221. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  10222. break;
  10223. }
  10224. case clang::attr::HLSLExperimental:
  10225. {
  10226. Attr * noconst = const_cast<Attr*>(A);
  10227. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  10228. Indent(Indentation, Out);
  10229. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  10230. break;
  10231. }
  10232. case clang::attr::HLSLMaxVertexCount:
  10233. {
  10234. Attr * noconst = const_cast<Attr*>(A);
  10235. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  10236. Indent(Indentation, Out);
  10237. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  10238. break;
  10239. }
  10240. case clang::attr::NoInline:
  10241. Indent(Indentation, Out);
  10242. Out << "[noinline]\n";
  10243. break;
  10244. // Statement attributes
  10245. case clang::attr::HLSLAllowUAVCondition:
  10246. Indent(Indentation, Out);
  10247. Out << "[allow_uav_condition]\n";
  10248. break;
  10249. case clang::attr::HLSLBranch:
  10250. Indent(Indentation, Out);
  10251. Out << "[branch]\n";
  10252. break;
  10253. case clang::attr::HLSLCall:
  10254. Indent(Indentation, Out);
  10255. Out << "[call]\n";
  10256. break;
  10257. case clang::attr::HLSLFastOpt:
  10258. Indent(Indentation, Out);
  10259. Out << "[fastopt]\n";
  10260. break;
  10261. case clang::attr::HLSLFlatten:
  10262. Indent(Indentation, Out);
  10263. Out << "[flatten]\n";
  10264. break;
  10265. case clang::attr::HLSLForceCase:
  10266. Indent(Indentation, Out);
  10267. Out << "[forcecase]\n";
  10268. break;
  10269. case clang::attr::HLSLLoop:
  10270. Indent(Indentation, Out);
  10271. Out << "[loop]\n";
  10272. break;
  10273. case clang::attr::HLSLUnroll:
  10274. {
  10275. Attr * noconst = const_cast<Attr*>(A);
  10276. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  10277. Indent(Indentation, Out);
  10278. Out << "[unroll(" << ACast->getCount() << ")]\n";
  10279. break;
  10280. }
  10281. // Variable modifiers
  10282. case clang::attr::HLSLGroupShared:
  10283. Out << "groupshared ";
  10284. break;
  10285. case clang::attr::HLSLPrecise:
  10286. Out << "precise ";
  10287. break;
  10288. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  10289. break;
  10290. case clang::attr::HLSLShared:
  10291. Out << "shared ";
  10292. break;
  10293. case clang::attr::HLSLUniform:
  10294. Out << "uniform ";
  10295. break;
  10296. // These four cases are printed in TypePrinter::printAttributedBefore
  10297. case clang::attr::HLSLColumnMajor:
  10298. case clang::attr::HLSLRowMajor:
  10299. case clang::attr::HLSLSnorm:
  10300. case clang::attr::HLSLUnorm:
  10301. break;
  10302. case clang::attr::HLSLPoint:
  10303. Out << "point ";
  10304. break;
  10305. case clang::attr::HLSLLine:
  10306. Out << "line ";
  10307. break;
  10308. case clang::attr::HLSLLineAdj:
  10309. Out << "lineadj ";
  10310. break;
  10311. case clang::attr::HLSLTriangle:
  10312. Out << "triangle ";
  10313. break;
  10314. case clang::attr::HLSLTriangleAdj:
  10315. Out << "triangleadj ";
  10316. break;
  10317. case clang::attr::HLSLGloballyCoherent:
  10318. Out << "globallycoherent ";
  10319. break;
  10320. default:
  10321. A->printPretty(Out, Policy);
  10322. break;
  10323. }
  10324. }
  10325. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  10326. switch (AttrKind){
  10327. case clang::attr::HLSLAllowUAVCondition:
  10328. case clang::attr::HLSLBranch:
  10329. case clang::attr::HLSLCall:
  10330. case clang::attr::HLSLCentroid:
  10331. case clang::attr::HLSLClipPlanes:
  10332. case clang::attr::HLSLColumnMajor:
  10333. case clang::attr::HLSLDomain:
  10334. case clang::attr::HLSLEarlyDepthStencil:
  10335. case clang::attr::HLSLFastOpt:
  10336. case clang::attr::HLSLFlatten:
  10337. case clang::attr::HLSLForceCase:
  10338. case clang::attr::HLSLGroupShared:
  10339. case clang::attr::HLSLIn:
  10340. case clang::attr::HLSLInOut:
  10341. case clang::attr::HLSLInstance:
  10342. case clang::attr::HLSLLinear:
  10343. case clang::attr::HLSLLoop:
  10344. case clang::attr::HLSLMaxTessFactor:
  10345. case clang::attr::HLSLNoInterpolation:
  10346. case clang::attr::HLSLNoPerspective:
  10347. case clang::attr::HLSLNumThreads:
  10348. case clang::attr::HLSLRootSignature:
  10349. case clang::attr::HLSLOut:
  10350. case clang::attr::HLSLOutputControlPoints:
  10351. case clang::attr::HLSLOutputTopology:
  10352. case clang::attr::HLSLPartitioning:
  10353. case clang::attr::HLSLPatchConstantFunc:
  10354. case clang::attr::HLSLMaxVertexCount:
  10355. case clang::attr::HLSLPrecise:
  10356. case clang::attr::HLSLRowMajor:
  10357. case clang::attr::HLSLSample:
  10358. case clang::attr::HLSLSemantic:
  10359. case clang::attr::HLSLShared:
  10360. case clang::attr::HLSLSnorm:
  10361. case clang::attr::HLSLUniform:
  10362. case clang::attr::HLSLUnorm:
  10363. case clang::attr::HLSLUnroll:
  10364. case clang::attr::HLSLPoint:
  10365. case clang::attr::HLSLLine:
  10366. case clang::attr::HLSLLineAdj:
  10367. case clang::attr::HLSLTriangle:
  10368. case clang::attr::HLSLTriangleAdj:
  10369. case clang::attr::HLSLGloballyCoherent:
  10370. case clang::attr::NoInline:
  10371. return true;
  10372. }
  10373. return false;
  10374. }
  10375. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  10376. if (ClipPlane) {
  10377. Out << ", ";
  10378. ClipPlane->printPretty(Out, 0, Policy);
  10379. }
  10380. }
  10381. bool hlsl::IsObjectType(
  10382. _In_ clang::Sema* self,
  10383. _In_ clang::QualType type,
  10384. _Inout_opt_ bool *isDeprecatedEffectObject)
  10385. {
  10386. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  10387. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  10388. if (isDeprecatedEffectObject)
  10389. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  10390. return true;
  10391. }
  10392. if (isDeprecatedEffectObject)
  10393. *isDeprecatedEffectObject = false;
  10394. return false;
  10395. }
  10396. bool hlsl::CanConvert(
  10397. _In_ clang::Sema* self,
  10398. clang::SourceLocation loc,
  10399. _In_ clang::Expr* sourceExpr,
  10400. clang::QualType target,
  10401. bool explicitConversion,
  10402. _Inout_opt_ clang::StandardConversionSequence* standard)
  10403. {
  10404. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  10405. }
  10406. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  10407. {
  10408. for (unsigned i = 0; i != Indentation; ++i)
  10409. Out << " ";
  10410. }
  10411. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  10412. {
  10413. DXASSERT_NOMSG(self != nullptr);
  10414. DXASSERT_NOMSG(table != nullptr);
  10415. HLSLExternalSource* source = (HLSLExternalSource*)self;
  10416. source->RegisterIntrinsicTable(table);
  10417. }
  10418. clang::QualType hlsl::CheckVectorConditional(
  10419. _In_ clang::Sema* self,
  10420. _In_ clang::ExprResult &Cond,
  10421. _In_ clang::ExprResult &LHS,
  10422. _In_ clang::ExprResult &RHS,
  10423. _In_ clang::SourceLocation QuestionLoc)
  10424. {
  10425. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  10426. }
  10427. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  10428. UINT count;
  10429. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  10430. }
  10431. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  10432. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  10433. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  10434. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  10435. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  10436. llvm::APSInt index;
  10437. if (RHS->EvaluateAsInt(index, Context)) {
  10438. int64_t intIndex = index.getLimitedValue();
  10439. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  10440. if (IsVectorType(this, LHSQualType)) {
  10441. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  10442. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  10443. // we also have to check the first subscript oprator by recursively calling
  10444. // this funciton for the first CXXOperatorCallExpr
  10445. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  10446. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  10447. }
  10448. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  10449. Diag(RHS->getExprLoc(),
  10450. diag::err_hlsl_vector_element_index_out_of_bounds)
  10451. << (int)intIndex;
  10452. }
  10453. }
  10454. else if (IsMatrixType(this, LHSQualType)) {
  10455. uint32_t rowCount, colCount;
  10456. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  10457. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  10458. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  10459. << (int)intIndex;
  10460. }
  10461. }
  10462. }
  10463. }
  10464. clang::QualType ApplyTypeSpecSignToParsedType(
  10465. _In_ clang::Sema* self,
  10466. _In_ clang::QualType &type,
  10467. _In_ clang::TypeSpecifierSign TSS,
  10468. _In_ clang::SourceLocation Loc
  10469. )
  10470. {
  10471. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  10472. }