shaderc_spirv.cpp 32 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. /*
  2. * Copyright 2011-2020 Branimir Karadzic. All rights reserved.
  3. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause
  4. */
  5. #include "shaderc.h"
  6. BX_PRAGMA_DIAGNOSTIC_PUSH()
  7. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4100) // error C4100: 'inclusionDepth' : unreferenced formal parameter
  8. BX_PRAGMA_DIAGNOSTIC_IGNORED_MSVC(4265) // error C4265: 'spv::spirvbin_t': class has virtual functions, but destructor is not virtual
  9. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wattributes") // warning: attribute ignored
  10. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wdeprecated-declarations") // warning: ‘MSLVertexAttr’ is deprecated
  11. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wtype-limits") // warning: comparison of unsigned expression in ‘< 0’ is always false
  12. BX_PRAGMA_DIAGNOSTIC_IGNORED_CLANG_GCC("-Wshadow") // warning: declaration of 'userData' shadows a member of 'glslang::TShader::Includer::IncludeResult'
  13. #define ENABLE_OPT 1
  14. #include <ShaderLang.h>
  15. #include <ResourceLimits.h>
  16. #include <SPIRV/SPVRemapper.h>
  17. #include <SPIRV/GlslangToSpv.h>
  18. #include <webgpu/webgpu_cpp.h>
  19. #define SPIRV_CROSS_EXCEPTIONS_TO_ASSERTIONS
  20. #include <spirv_msl.hpp>
  21. #include <spirv_reflect.hpp>
  22. #include <spirv-tools/optimizer.hpp>
  23. BX_PRAGMA_DIAGNOSTIC_POP()
  24. namespace bgfx
  25. {
  26. static bx::DefaultAllocator s_allocator;
  27. bx::AllocatorI* g_allocator = &s_allocator;
  28. struct TinyStlAllocator
  29. {
  30. static void* static_allocate(size_t _bytes);
  31. static void static_deallocate(void* _ptr, size_t /*_bytes*/);
  32. };
  33. void* TinyStlAllocator::static_allocate(size_t _bytes)
  34. {
  35. return BX_ALLOC(g_allocator, _bytes);
  36. }
  37. void TinyStlAllocator::static_deallocate(void* _ptr, size_t /*_bytes*/)
  38. {
  39. if (NULL != _ptr)
  40. {
  41. BX_FREE(g_allocator, _ptr);
  42. }
  43. }
  44. } // namespace bgfx
  45. #define TINYSTL_ALLOCATOR bgfx::TinyStlAllocator
  46. #include <tinystl/allocator.h>
  47. #include <tinystl/string.h>
  48. #include <tinystl/unordered_map.h>
  49. #include <tinystl/vector.h>
  50. namespace stl = tinystl;
  51. #include "../../src/shader_spirv.h"
  52. #include "../../3rdparty/khronos/vulkan-local/vulkan.h"
  53. namespace bgfx { namespace spirv
  54. {
  55. const TBuiltInResource resourceLimits =
  56. {
  57. 32, // MaxLights
  58. 6, // MaxClipPlanes
  59. 32, // MaxTextureUnits
  60. 32, // MaxTextureCoords
  61. 64, // MaxVertexAttribs
  62. 4096, // MaxVertexUniformComponents
  63. 64, // MaxVaryingFloats
  64. 32, // MaxVertexTextureImageUnits
  65. 80, // MaxCombinedTextureImageUnits
  66. 32, // MaxTextureImageUnits
  67. 4096, // MaxFragmentUniformComponents
  68. 32, // MaxDrawBuffers
  69. 128, // MaxVertexUniformVectors
  70. 8, // MaxVaryingVectors
  71. 16, // MaxFragmentUniformVectors
  72. 16, // MaxVertexOutputVectors
  73. 15, // MaxFragmentInputVectors
  74. -8, // MinProgramTexelOffset
  75. 7, // MaxProgramTexelOffset
  76. 8, // MaxClipDistances
  77. 65535, // MaxComputeWorkGroupCountX
  78. 65535, // MaxComputeWorkGroupCountY
  79. 65535, // MaxComputeWorkGroupCountZ
  80. 1024, // MaxComputeWorkGroupSizeX
  81. 1024, // MaxComputeWorkGroupSizeY
  82. 64, // MaxComputeWorkGroupSizeZ
  83. 1024, // MaxComputeUniformComponents
  84. 16, // MaxComputeTextureImageUnits
  85. 8, // MaxComputeImageUniforms
  86. 8, // MaxComputeAtomicCounters
  87. 1, // MaxComputeAtomicCounterBuffers
  88. 60, // MaxVaryingComponents
  89. 64, // MaxVertexOutputComponents
  90. 64, // MaxGeometryInputComponents
  91. 128, // MaxGeometryOutputComponents
  92. 128, // MaxFragmentInputComponents
  93. 8, // MaxImageUnits
  94. 8, // MaxCombinedImageUnitsAndFragmentOutputs
  95. 8, // MaxCombinedShaderOutputResources
  96. 0, // MaxImageSamples
  97. 0, // MaxVertexImageUniforms
  98. 0, // MaxTessControlImageUniforms
  99. 0, // MaxTessEvaluationImageUniforms
  100. 0, // MaxGeometryImageUniforms
  101. 8, // MaxFragmentImageUniforms
  102. 8, // MaxCombinedImageUniforms
  103. 16, // MaxGeometryTextureImageUnits
  104. 256, // MaxGeometryOutputVertices
  105. 1024, // MaxGeometryTotalOutputComponents
  106. 1024, // MaxGeometryUniformComponents
  107. 64, // MaxGeometryVaryingComponents
  108. 128, // MaxTessControlInputComponents
  109. 128, // MaxTessControlOutputComponents
  110. 16, // MaxTessControlTextureImageUnits
  111. 1024, // MaxTessControlUniformComponents
  112. 4096, // MaxTessControlTotalOutputComponents
  113. 128, // MaxTessEvaluationInputComponents
  114. 128, // MaxTessEvaluationOutputComponents
  115. 16, // MaxTessEvaluationTextureImageUnits
  116. 1024, // MaxTessEvaluationUniformComponents
  117. 120, // MaxTessPatchComponents
  118. 32, // MaxPatchVertices
  119. 64, // MaxTessGenLevel
  120. 16, // MaxViewports
  121. 0, // MaxVertexAtomicCounters
  122. 0, // MaxTessControlAtomicCounters
  123. 0, // MaxTessEvaluationAtomicCounters
  124. 0, // MaxGeometryAtomicCounters
  125. 8, // MaxFragmentAtomicCounters
  126. 8, // MaxCombinedAtomicCounters
  127. 1, // MaxAtomicCounterBindings
  128. 0, // MaxVertexAtomicCounterBuffers
  129. 0, // MaxTessControlAtomicCounterBuffers
  130. 0, // MaxTessEvaluationAtomicCounterBuffers
  131. 0, // MaxGeometryAtomicCounterBuffers
  132. 1, // MaxFragmentAtomicCounterBuffers
  133. 1, // MaxCombinedAtomicCounterBuffers
  134. 16384, // MaxAtomicCounterBufferSize
  135. 4, // MaxTransformFeedbackBuffers
  136. 64, // MaxTransformFeedbackInterleavedComponents
  137. 8, // MaxCullDistances
  138. 8, // MaxCombinedClipAndCullDistances
  139. 4, // MaxSamples
  140. 0, // maxMeshOutputVerticesNV
  141. 0, // maxMeshOutputPrimitivesNV
  142. 0, // maxMeshWorkGroupSizeX_NV
  143. 0, // maxMeshWorkGroupSizeY_NV
  144. 0, // maxMeshWorkGroupSizeZ_NV
  145. 0, // maxTaskWorkGroupSizeX_NV
  146. 0, // maxTaskWorkGroupSizeY_NV
  147. 0, // maxTaskWorkGroupSizeZ_NV
  148. 0, // maxMeshViewCountNV
  149. 0, // maxDualSourceDrawBuffersEXT
  150. { // limits
  151. true, // nonInductiveForLoops
  152. true, // whileLoops
  153. true, // doWhileLoops
  154. true, // generalUniformIndexing
  155. true, // generalAttributeMatrixVectorIndexing
  156. true, // generalVaryingIndexing
  157. true, // generalSamplerIndexing
  158. true, // generalVariableIndexing
  159. true, // generalConstantMatrixVectorIndexing
  160. },
  161. };
  162. bool printAsm(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  163. {
  164. BX_UNUSED(_userData);
  165. char temp[512];
  166. toString(temp, sizeof(temp), _instruction);
  167. BX_TRACE("%5d: %s", _offset, temp);
  168. return true;
  169. }
  170. wgpu::TextureComponentType SpirvCrossBaseTypeToFormatType(spirv_cross::SPIRType::BaseType spirvBaseType)
  171. {
  172. switch (spirvBaseType)
  173. {
  174. case spirv_cross::SPIRType::Float:
  175. return wgpu::TextureComponentType::Float;
  176. case spirv_cross::SPIRType::Int:
  177. return wgpu::TextureComponentType::Sint;
  178. case spirv_cross::SPIRType::UInt:
  179. return wgpu::TextureComponentType::Uint;
  180. default:
  181. return wgpu::TextureComponentType::Float;
  182. }
  183. }
  184. wgpu::TextureViewDimension SpirvDimToTextureViewDimension(spv::Dim dim, bool arrayed)
  185. {
  186. switch (dim)
  187. {
  188. case spv::Dim::Dim1D:
  189. return wgpu::TextureViewDimension::e1D;
  190. case spv::Dim::Dim2D:
  191. return arrayed
  192. ? wgpu::TextureViewDimension::e2DArray
  193. : wgpu::TextureViewDimension::e2D;
  194. case spv::Dim::Dim3D:
  195. return wgpu::TextureViewDimension::e3D;
  196. case spv::Dim::DimCube:
  197. return arrayed
  198. ? wgpu::TextureViewDimension::CubeArray
  199. : wgpu::TextureViewDimension::Cube;
  200. default:
  201. return wgpu::TextureViewDimension::Undefined;
  202. }
  203. }
  204. struct SpvReflection
  205. {
  206. struct TypeId
  207. {
  208. enum Enum
  209. {
  210. Void,
  211. Bool,
  212. Int32,
  213. Int64,
  214. Uint32,
  215. Uint64,
  216. Float,
  217. Double,
  218. Vector,
  219. Matrix,
  220. Count
  221. };
  222. TypeId()
  223. : baseType(Enum::Count)
  224. , type(Enum::Count)
  225. , numComponents(0)
  226. {
  227. }
  228. Enum baseType;
  229. Enum type;
  230. uint32_t numComponents;
  231. stl::string toString()
  232. {
  233. stl::string result;
  234. switch (type)
  235. {
  236. case Float:
  237. result.append("float");
  238. break;
  239. case Vector:
  240. bx::stringPrintf(result, "vec%d"
  241. , numComponents
  242. );
  243. break;
  244. case Matrix:
  245. bx::stringPrintf(result, "mat%d"
  246. , numComponents
  247. );
  248. default:
  249. break;
  250. }
  251. return result;
  252. }
  253. };
  254. struct Id
  255. {
  256. struct Variable
  257. {
  258. Variable()
  259. : decoration(SpvDecoration::Count)
  260. , builtin(SpvBuiltin::Count)
  261. , storageClass(SpvStorageClass::Count)
  262. , location(UINT32_MAX)
  263. , offset(UINT32_MAX)
  264. , type(UINT32_MAX)
  265. {
  266. }
  267. stl::string name;
  268. SpvDecoration::Enum decoration;
  269. SpvBuiltin::Enum builtin;
  270. SpvStorageClass::Enum storageClass;
  271. uint32_t location;
  272. uint32_t offset;
  273. uint32_t type;
  274. };
  275. typedef stl::vector<Variable> MemberArray;
  276. Variable var;
  277. MemberArray members;
  278. };
  279. typedef stl::unordered_map<uint32_t, TypeId> TypeIdMap;
  280. typedef stl::unordered_map<uint32_t, Id> IdMap;
  281. TypeIdMap typeIdMap;
  282. IdMap idMap;
  283. stl::string getTypeName(uint32_t _typeId)
  284. {
  285. return getTypeId(_typeId).toString();
  286. }
  287. Id& getId(uint32_t _id)
  288. {
  289. IdMap::iterator it = idMap.find(_id);
  290. if (it == idMap.end() )
  291. {
  292. Id id;
  293. stl::pair<IdMap::iterator, bool> result = idMap.insert(stl::make_pair(_id, id) );
  294. it = result.first;
  295. }
  296. return it->second;
  297. }
  298. Id::Variable& get(uint32_t _id, uint32_t _idx)
  299. {
  300. Id& id = getId(_id);
  301. id.members.resize(bx::uint32_max(_idx+1, uint32_t(id.members.size() ) ) );
  302. return id.members[_idx];
  303. }
  304. TypeId& getTypeId(uint32_t _id)
  305. {
  306. TypeIdMap::iterator it = typeIdMap.find(_id);
  307. if (it == typeIdMap.end() )
  308. {
  309. TypeId id;
  310. stl::pair<TypeIdMap::iterator, bool> result = typeIdMap.insert(stl::make_pair(_id, id) );
  311. it = result.first;
  312. }
  313. return it->second;
  314. }
  315. void update(uint32_t _id, const stl::string& _name)
  316. {
  317. getId(_id).var.name = _name;
  318. }
  319. BX_NO_INLINE void update(Id::Variable& _variable, SpvDecoration::Enum _decoration, uint32_t _literal)
  320. {
  321. _variable.decoration = _decoration;
  322. switch (_decoration)
  323. {
  324. case SpvDecoration::Location:
  325. _variable.location = _literal;
  326. break;
  327. case SpvDecoration::Offset:
  328. _variable.offset = _literal;
  329. break;
  330. case SpvDecoration::BuiltIn:
  331. _variable.builtin = SpvBuiltin::Enum(_literal);
  332. break;
  333. default:
  334. break;
  335. }
  336. }
  337. BX_NO_INLINE void update(Id::Variable& _variable, uint32_t _type, SpvStorageClass::Enum _storageClass)
  338. {
  339. _variable.type = _type;
  340. _variable.storageClass = _storageClass;
  341. }
  342. void update(uint32_t _id, SpvDecoration::Enum _decoration, uint32_t _literal)
  343. {
  344. update(getId(_id).var, _decoration, _literal);
  345. }
  346. void update(uint32_t _id, uint32_t _type, SpvStorageClass::Enum _storageClass)
  347. {
  348. update(getId(_id).var, _type, _storageClass);
  349. }
  350. void update(uint32_t _id, uint32_t _idx, const stl::string& _name)
  351. {
  352. Id::Variable& var = get(_id, _idx);
  353. var.name = _name;
  354. }
  355. BX_NO_INLINE void update(uint32_t _id, uint32_t _idx, SpvDecoration::Enum _decoration, uint32_t _literal)
  356. {
  357. update(get(_id, _idx), _decoration, _literal);
  358. }
  359. void update(uint32_t _id, TypeId::Enum _type)
  360. {
  361. TypeId& type = getTypeId(_id);
  362. type.type = _type;
  363. }
  364. void update(uint32_t _id, TypeId::Enum _type, uint32_t _baseTypeId, uint32_t _numComonents)
  365. {
  366. TypeId& type = getTypeId(_id);
  367. type.type = _type;
  368. type.baseType = getTypeId(_baseTypeId).type;
  369. type.numComponents = _numComonents;
  370. }
  371. };
  372. bool spvParse(uint32_t _offset, const SpvInstruction& _instruction, void* _userData)
  373. {
  374. BX_UNUSED(_offset);
  375. SpvReflection* spv = (SpvReflection*)_userData;
  376. switch (_instruction.opcode)
  377. {
  378. case SpvOpcode::Name:
  379. spv->update(_instruction.result
  380. , _instruction.operand[0].literalString
  381. );
  382. break;
  383. case SpvOpcode::Decorate:
  384. spv->update(_instruction.operand[0].data
  385. , SpvDecoration::Enum(_instruction.operand[1].data)
  386. , _instruction.operand[2].data
  387. );
  388. break;
  389. case SpvOpcode::MemberName:
  390. spv->update(_instruction.result
  391. , _instruction.operand[0].data
  392. , _instruction.operand[1].literalString
  393. );
  394. break;
  395. case SpvOpcode::MemberDecorate:
  396. spv->update(_instruction.operand[0].data
  397. , _instruction.operand[1].data
  398. , SpvDecoration::Enum(_instruction.operand[2].data)
  399. , _instruction.operand[3].data
  400. );
  401. break;
  402. case SpvOpcode::Variable:
  403. spv->update(_instruction.result
  404. , _instruction.type
  405. , SpvStorageClass::Enum(_instruction.operand[0].data)
  406. );
  407. break;
  408. case SpvOpcode::TypeVoid:
  409. spv->update(_instruction.result, SpvReflection::TypeId::Void);
  410. break;
  411. case SpvOpcode::TypeBool:
  412. spv->update(_instruction.result, SpvReflection::TypeId::Bool);
  413. break;
  414. case SpvOpcode::TypeInt:
  415. spv->update(_instruction.result
  416. , 32 == _instruction.operand[0].data
  417. ? 0 == _instruction.operand[1].data
  418. ? SpvReflection::TypeId::Uint32
  419. : SpvReflection::TypeId::Int32
  420. : 0 == _instruction.operand[1].data
  421. ? SpvReflection::TypeId::Uint64
  422. : SpvReflection::TypeId::Int64
  423. );
  424. break;
  425. case SpvOpcode::TypeFloat:
  426. spv->update(_instruction.result
  427. , 32 == _instruction.operand[0].data
  428. ? SpvReflection::TypeId::Float
  429. : SpvReflection::TypeId::Double
  430. );
  431. break;
  432. case SpvOpcode::TypeVector:
  433. spv->update(_instruction.result
  434. , SpvReflection::TypeId::Vector
  435. , _instruction.operand[0].data
  436. , _instruction.operand[1].data
  437. );
  438. break;
  439. case SpvOpcode::TypeMatrix:
  440. spv->update(_instruction.result
  441. , SpvReflection::TypeId::Matrix
  442. , _instruction.operand[0].data
  443. , _instruction.operand[1].data
  444. );
  445. break;
  446. case SpvOpcode::TypeImage:
  447. case SpvOpcode::TypeSampler:
  448. case SpvOpcode::TypeSampledImage:
  449. break;
  450. case SpvOpcode::TypeStruct:
  451. for (uint32_t ii = 0, num = _instruction.numOperands; ii < num; ++ii)
  452. {
  453. SpvReflection::Id::Variable& var = spv->get(_instruction.result, ii);
  454. var.type = _instruction.operand[ii].data;
  455. }
  456. break;
  457. default:
  458. break;
  459. }
  460. return true;
  461. }
  462. #define DBG(...) // bx::debugPrintf(__VA_ARGS__)
  463. void disassemble(bx::WriterI* _writer, bx::ReaderSeekerI* _reader, bx::Error* _err)
  464. {
  465. BX_UNUSED(_writer);
  466. uint32_t magic;
  467. bx::peek(_reader, magic);
  468. SpvReflection spvx;
  469. if (magic == SPV_CHUNK_HEADER)
  470. {
  471. SpirV spirv;
  472. read(_reader, spirv, _err);
  473. parse(spirv.shader, spvParse, &spvx, _err);
  474. for (SpvReflection::IdMap::const_iterator it = spvx.idMap.begin(), itEnd = spvx.idMap.end(); it != itEnd; ++it)
  475. {
  476. const SpvReflection::Id& id = it->second;
  477. uint32_t num = uint32_t(id.members.size() );
  478. if (0 < num
  479. && 0 != bx::strCmp(id.var.name.c_str(), "gl_PerVertex") )
  480. {
  481. DBG("%3d: %s %d %s\n"
  482. , it->first
  483. , id.var.name.c_str()
  484. , id.var.location
  485. , getName(id.var.storageClass)
  486. );
  487. DBG("{\n");
  488. for (uint32_t ii = 0; ii < num; ++ii)
  489. {
  490. const SpvReflection::Id::Variable& var = id.members[ii];
  491. DBG("\t\t%s %s %d %s\n"
  492. , spvx.getTypeName(var.type).c_str()
  493. , var.name.c_str()
  494. , var.offset
  495. , getName(var.storageClass)
  496. );
  497. BX_UNUSED(var);
  498. }
  499. DBG("}\n");
  500. }
  501. }
  502. }
  503. }
  504. static EShLanguage getLang(char _p)
  505. {
  506. switch (_p)
  507. {
  508. case 'c': return EShLangCompute;
  509. case 'f': return EShLangFragment;
  510. case 'v': return EShLangVertex;
  511. default: return EShLangCount;
  512. }
  513. }
  514. static const char* s_attribName[] =
  515. {
  516. "a_position",
  517. "a_normal",
  518. "a_tangent",
  519. "a_bitangent",
  520. "a_color0",
  521. "a_color1",
  522. "a_color2",
  523. "a_color3",
  524. "a_indices",
  525. "a_weight",
  526. "a_texcoord0",
  527. "a_texcoord1",
  528. "a_texcoord2",
  529. "a_texcoord3",
  530. "a_texcoord4",
  531. "a_texcoord5",
  532. "a_texcoord6",
  533. "a_texcoord7",
  534. };
  535. BX_STATIC_ASSERT(bgfx::Attrib::Count == BX_COUNTOF(s_attribName) );
  536. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  537. {
  538. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  539. {
  540. if (0 == bx::strCmp(s_attribName[ii], _name) )
  541. {
  542. return bgfx::Attrib::Enum(ii);
  543. }
  544. }
  545. return bgfx::Attrib::Count;
  546. }
  547. static const char* s_samplerTypes[] =
  548. {
  549. "BgfxSampler2D",
  550. "BgfxISampler2D",
  551. "BgfxUSampler2D",
  552. "BgfxSampler2DArray",
  553. "BgfxSampler2DShadow",
  554. "BgfxSampler2DArrayShadow",
  555. "BgfxSampler3D",
  556. "BgfxISampler3D",
  557. "BgfxUSampler3D",
  558. "BgfxSamplerCube",
  559. "BgfxSamplerCubeShadow",
  560. "BgfxSampler2DMS",
  561. };
  562. static uint16_t writeUniformArray(bx::WriterI* _writer, const UniformArray& uniforms, bool isFragmentShader)
  563. {
  564. uint16_t size = 0;
  565. uint16_t count = static_cast<uint16_t>(uniforms.size() );
  566. bx::write(_writer, count);
  567. uint32_t fragmentBit = isFragmentShader ? kUniformFragmentBit : 0;
  568. for (uint16_t ii = 0; ii < count; ++ii)
  569. {
  570. const Uniform& un = uniforms[ii];
  571. if ( (un.type & ~kUniformMask) > UniformType::End)
  572. {
  573. size = bx::max(size, (uint16_t)(un.regIndex + un.regCount*16) );
  574. }
  575. uint8_t nameSize = (uint8_t)un.name.size();
  576. bx::write(_writer, nameSize);
  577. bx::write(_writer, un.name.c_str(), nameSize);
  578. bx::write(_writer, uint8_t(un.type | fragmentBit) );
  579. bx::write(_writer, un.num);
  580. bx::write(_writer, un.regIndex);
  581. bx::write(_writer, un.regCount);
  582. bx::write(_writer, un.texComponent);
  583. bx::write(_writer, un.texDimension);
  584. BX_TRACE("%s, %s, %d, %d, %d"
  585. , un.name.c_str()
  586. , getUniformTypeName(un.type)
  587. , un.num
  588. , un.regIndex
  589. , un.regCount
  590. );
  591. }
  592. return size;
  593. }
  594. static spv_target_env getSpirvTargetVersion(uint32_t version)
  595. {
  596. switch (version)
  597. {
  598. case 1010:
  599. return SPV_ENV_VULKAN_1_0;
  600. case 1311:
  601. return SPV_ENV_VULKAN_1_1;
  602. case 1411:
  603. return SPV_ENV_VULKAN_1_1_SPIRV_1_4;
  604. case 1512:
  605. return SPV_ENV_VULKAN_1_2;
  606. default:
  607. BX_ASSERT(0, "Unknown SPIR-V version requested. Returning SPV_ENV_VULKAN_1_0 as default.");
  608. return SPV_ENV_VULKAN_1_0;
  609. }
  610. }
  611. static glslang::EShTargetClientVersion getGlslangTargetVulkanVersion(uint32_t version)
  612. {
  613. switch (version)
  614. {
  615. case 1010:
  616. return glslang::EShTargetVulkan_1_0;
  617. case 1311:
  618. case 1411:
  619. return glslang::EShTargetVulkan_1_1;
  620. case 1512:
  621. return glslang::EShTargetVulkan_1_2;
  622. default:
  623. BX_ASSERT(0, "Unknown SPIR-V version requested. Returning EShTargetVulkan_1_0 as default.");
  624. return glslang::EShTargetVulkan_1_0;
  625. }
  626. }
  627. static glslang::EShTargetLanguageVersion getGlslangTargetSpirvVersion(uint32_t version)
  628. {
  629. switch (version)
  630. {
  631. case 1010:
  632. return glslang::EShTargetSpv_1_0;
  633. case 1311:
  634. return glslang::EShTargetSpv_1_3;
  635. case 1411:
  636. return glslang::EShTargetSpv_1_4;
  637. case 1512:
  638. return glslang::EShTargetSpv_1_5;
  639. default:
  640. BX_ASSERT(0, "Unknown SPIR-V version requested. Returning EShTargetSpv_1_0 as default.");
  641. return glslang::EShTargetSpv_1_0;
  642. }
  643. }
  644. /// This is the value used to fill out GLSLANG's SpvVersion object.
  645. /// The required value is that which is defined by GL_KHR_vulkan_glsl, which is defined here:
  646. /// https://github.com/KhronosGroup/GLSL/blob/master/extensions/khr/GL_KHR_vulkan_glsl.txt
  647. /// The value is 100.
  648. constexpr int s_GLSL_VULKAN_CLIENT_VERSION = 100;
  649. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  650. {
  651. BX_UNUSED(_version);
  652. glslang::InitializeProcess();
  653. glslang::TProgram* program = new glslang::TProgram;
  654. EShLanguage stage = getLang(_options.shaderType);
  655. if (EShLangCount == stage)
  656. {
  657. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  658. return false;
  659. }
  660. glslang::TShader* shader = new glslang::TShader(stage);
  661. EShMessages messages = EShMessages(0
  662. | EShMsgDefault
  663. | EShMsgReadHlsl
  664. | EShMsgVulkanRules
  665. | EShMsgSpvRules
  666. );
  667. shader->setEntryPoint("main");
  668. shader->setAutoMapBindings(true);
  669. shader->setEnvInput(glslang::EShSourceHlsl, stage, glslang::EShClientVulkan, s_GLSL_VULKAN_CLIENT_VERSION);
  670. shader->setEnvClient(glslang::EShClientVulkan, getGlslangTargetVulkanVersion(_version));
  671. shader->setEnvTarget(glslang::EShTargetSpv, getGlslangTargetSpirvVersion(_version));
  672. uint32_t bindingOffset = (stage == EShLanguage::EShLangFragment ? 48 : 0);
  673. shader->setShiftBinding(glslang::EResUbo, bindingOffset);
  674. shader->setShiftBinding(glslang::EResTexture, bindingOffset + 16);
  675. shader->setShiftBinding(glslang::EResSampler, bindingOffset + 32);
  676. shader->setShiftBinding(glslang::EResSsbo, bindingOffset + 16);
  677. shader->setShiftBinding(glslang::EResImage, bindingOffset + 32);
  678. const char* shaderStrings[] = { _code.c_str() };
  679. shader->setStrings(
  680. shaderStrings
  681. , BX_COUNTOF(shaderStrings)
  682. );
  683. bool compiled = shader->parse(&resourceLimits
  684. , 110
  685. , false
  686. , messages
  687. );
  688. bool linked = false;
  689. bool validated = true;
  690. if (!compiled)
  691. {
  692. const char* log = shader->getInfoLog();
  693. if (NULL != log)
  694. {
  695. int32_t source = 0;
  696. int32_t line = 0;
  697. int32_t column = 0;
  698. int32_t start = 0;
  699. int32_t end = INT32_MAX;
  700. bx::StringView err = bx::strFind(log, "ERROR:");
  701. bool found = false;
  702. if (!err.isEmpty() )
  703. {
  704. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  705. if (found)
  706. {
  707. ++line;
  708. }
  709. }
  710. if (found)
  711. {
  712. start = bx::uint32_imax(1, line-10);
  713. end = start + 20;
  714. }
  715. printCode(_code.c_str(), line, start, end, column);
  716. bx::printf("%s\n", log);
  717. }
  718. }
  719. else
  720. {
  721. program->addShader(shader);
  722. linked = true
  723. && program->link(messages)
  724. && program->mapIO()
  725. ;
  726. if (!linked)
  727. {
  728. const char* log = program->getInfoLog();
  729. if (NULL != log)
  730. {
  731. bx::printf("%s\n", log);
  732. }
  733. }
  734. else
  735. {
  736. program->buildReflection();
  737. if (_firstPass)
  738. {
  739. // first time through, we just find unused uniforms and get rid of them
  740. std::string output;
  741. struct Uniform
  742. {
  743. std::string name;
  744. std::string decl;
  745. };
  746. std::vector<Uniform> uniforms;
  747. bx::LineReader reader(_code.c_str() );
  748. while (!reader.isDone() )
  749. {
  750. bx::StringView strLine = reader.next();
  751. bool moved = false;
  752. bx::StringView str = strFind(strLine, "uniform ");
  753. if (!str.isEmpty() )
  754. {
  755. bool found = false;
  756. bool sampler = false;
  757. std::string name = "";
  758. // add to samplers
  759. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  760. {
  761. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  762. {
  763. found = true;
  764. sampler = true;
  765. break;
  766. }
  767. }
  768. if (!found)
  769. {
  770. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  771. {
  772. // matching lines like: uniform u_name;
  773. // we want to replace "uniform" with "static" so that it's no longer
  774. // included in the uniform blob that the application must upload
  775. // we can't just remove them, because unused functions might still reference
  776. // them and cause a compile error when they're gone
  777. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  778. {
  779. found = true;
  780. name = program->getUniformName(ii);
  781. break;
  782. }
  783. }
  784. }
  785. if (!found)
  786. {
  787. output.append(strLine.getPtr(), str.getPtr() );
  788. output += "static ";
  789. output.append(str.getTerm(), strLine.getTerm() );
  790. output += "\n";
  791. moved = true;
  792. }
  793. else if (!sampler)
  794. {
  795. Uniform uniform;
  796. uniform.name = name;
  797. uniform.decl = std::string(strLine.getPtr(), strLine.getTerm() );
  798. uniforms.push_back(uniform);
  799. moved = true;
  800. }
  801. }
  802. if (!moved)
  803. {
  804. output.append(strLine.getPtr(), strLine.getTerm() );
  805. output += "\n";
  806. }
  807. }
  808. std::string uniformBlock;
  809. uniformBlock += "cbuffer UniformBlock\n";
  810. uniformBlock += "{\n";
  811. for (const Uniform& uniform : uniforms)
  812. {
  813. uniformBlock += uniform.decl.substr(7 /* uniform */);
  814. uniformBlock += "\n";
  815. }
  816. uniformBlock += "};\n";
  817. output = uniformBlock + output;
  818. // recompile with the unused uniforms converted to statics
  819. return compile(_options, _version, output.c_str(), _writer, false);
  820. }
  821. else
  822. {
  823. // second time, do nothing (todo remove)
  824. }
  825. UniformArray uniforms;
  826. {
  827. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  828. for (uint16_t ii = 0; ii < count; ++ii)
  829. {
  830. Uniform un;
  831. un.name = program->getUniformName(ii);
  832. un.num = uint8_t(program->getUniformArraySize(ii) );
  833. const uint32_t offset = program->getUniformBufferOffset(ii);
  834. un.regIndex = uint16_t(offset);
  835. un.regCount = un.num;
  836. switch (program->getUniformType(ii) )
  837. {
  838. case 0x1404: // GL_INT:
  839. un.type = UniformType::Sampler;
  840. break;
  841. case 0x8B52: // GL_FLOAT_VEC4:
  842. un.type = UniformType::Vec4;
  843. break;
  844. case 0x8B5B: // GL_FLOAT_MAT3:
  845. un.type = UniformType::Mat3;
  846. un.regCount *= 3;
  847. break;
  848. case 0x8B5C: // GL_FLOAT_MAT4:
  849. un.type = UniformType::Mat4;
  850. un.regCount *= 4;
  851. break;
  852. default:
  853. un.type = UniformType::End;
  854. break;
  855. }
  856. uniforms.push_back(un);
  857. }
  858. }
  859. if (g_verbose)
  860. {
  861. program->dumpReflection();
  862. }
  863. BX_UNUSED(spv::MemorySemanticsAllMemory);
  864. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  865. std::vector<uint32_t> spirv;
  866. glslang::SpvOptions options;
  867. options.disableOptimizer = false;
  868. glslang::GlslangToSpv(*intermediate, spirv, &options);
  869. spvtools::Optimizer opt(getSpirvTargetVersion(_version));
  870. auto print_msg_to_stderr = [](
  871. spv_message_level_t
  872. , const char*
  873. , const spv_position_t&
  874. , const char* m
  875. )
  876. {
  877. bx::printf("Error: %s\n", m);
  878. };
  879. opt.SetMessageConsumer(print_msg_to_stderr);
  880. opt.RegisterLegalizationPasses();
  881. spvtools::ValidatorOptions validatorOptions;
  882. validatorOptions.SetBeforeHlslLegalization(true);
  883. if (!opt.Run(
  884. spirv.data()
  885. , spirv.size()
  886. , &spirv
  887. , validatorOptions
  888. , false
  889. ) )
  890. {
  891. compiled = false;
  892. }
  893. else
  894. {
  895. bx::Error err;
  896. bx::WriterI* writer = bx::getDebugOut();
  897. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  898. disassemble(writer, &reader, &err);
  899. spirv_cross::CompilerReflection refl(spirv);
  900. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  901. if (g_verbose)
  902. {
  903. glslang::SpirvToolsDisassemble(std::cout, spirv, getSpirvTargetVersion(_version) );
  904. }
  905. // Loop through the separate_images, and extract the uniform names:
  906. for (auto &resource : resourcesrefl.separate_images)
  907. {
  908. std::string name = refl.get_name(resource.id);
  909. if (name.size() > 7
  910. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  911. {
  912. std::string uniform_name = name.substr(0, name.length() - 7);
  913. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  914. auto imageType = refl.get_type(resource.base_type_id).image;
  915. auto componentType = refl.get_type(imageType.type).basetype;
  916. bool isCompareSampler = false;
  917. for (auto& sampler : resourcesrefl.separate_samplers)
  918. {
  919. if (binding_index + 16 == refl.get_decoration(sampler.id, spv::Decoration::DecorationBinding) )
  920. {
  921. std::string samplerName = refl.get_name(sampler.id);
  922. isCompareSampler = refl.variable_is_depth_or_compare(sampler.id) || samplerName.find("Comparison") != std::string::npos;
  923. break;
  924. }
  925. }
  926. Uniform un;
  927. un.name = uniform_name;
  928. un.type = UniformType::Enum(UniformType::Sampler
  929. | kUniformSamplerBit
  930. | (isCompareSampler ? kUniformCompareBit : 0)
  931. );
  932. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType) );
  933. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  934. un.regIndex = binding_index;
  935. un.regCount = 0; // unused
  936. uniforms.push_back(un);
  937. }
  938. }
  939. // Loop through the storage_images, and extract the uniform names:
  940. for (auto &resource : resourcesrefl.storage_images)
  941. {
  942. std::string name = refl.get_name(resource.id);
  943. if (name.size() > 7
  944. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  945. {
  946. std::string uniform_name = name.substr(0, name.length() - 7);
  947. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  948. auto imageType = refl.get_type(resource.base_type_id).image;
  949. auto componentType = refl.get_type(imageType.type).basetype;
  950. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  951. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  952. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  953. : UniformType::End;
  954. Uniform un;
  955. un.name = uniform_name;
  956. un.type = type;
  957. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType) );
  958. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  959. un.regIndex = binding_index;
  960. un.regCount = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; // for descriptor type
  961. uniforms.push_back(un);
  962. }
  963. }
  964. // Loop through the storage buffer, and extract the uniform names:
  965. for (auto& resource : resourcesrefl.storage_buffers)
  966. {
  967. std::string name = refl.get_name(resource.id);
  968. for (auto& uniform : uniforms)
  969. {
  970. if (!bx::strFind(uniform.name.c_str(), name.c_str() ).isEmpty() )
  971. {
  972. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  973. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  974. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  975. : UniformType::End;
  976. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  977. uniform.name = name;
  978. uniform.type = type;
  979. uniform.regIndex = binding_index;
  980. uniform.regCount = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  981. break;
  982. }
  983. }
  984. }
  985. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  986. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  987. {
  988. spirv_cross::CompilerMSL msl(std::move(spirv) );
  989. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  990. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  991. if (!entryPoints.empty() )
  992. {
  993. msl.rename_entry_point(
  994. entryPoints[0].name
  995. , "xlatMtlMain"
  996. , entryPoints[0].execution_model
  997. );
  998. }
  999. for (auto &resource : resources.uniform_buffers)
  1000. {
  1001. msl.set_name(resource.id, "_mtl_u");
  1002. }
  1003. for (auto &resource : resources.storage_buffers)
  1004. {
  1005. unsigned binding = msl.get_decoration(resource.id, spv::DecorationBinding);
  1006. msl.set_decoration(resource.id, spv::DecorationBinding, binding + 1);
  1007. }
  1008. for (auto &resource : resources.separate_images)
  1009. {
  1010. std::string name = msl.get_name(resource.id);
  1011. if (name.size() > 7
  1012. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  1013. {
  1014. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  1015. }
  1016. }
  1017. std::string source = msl.compile();
  1018. if ('c' == _options.shaderType)
  1019. {
  1020. for (int i = 0; i < 3; ++i)
  1021. {
  1022. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  1023. bx::write(_writer, dim);
  1024. }
  1025. }
  1026. uint32_t shaderSize = (uint32_t)source.size();
  1027. bx::write(_writer, shaderSize);
  1028. bx::write(_writer, source.c_str(), shaderSize);
  1029. uint8_t nul = 0;
  1030. bx::write(_writer, nul);
  1031. }
  1032. else
  1033. {
  1034. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  1035. bx::write(_writer, shaderSize);
  1036. bx::write(_writer, spirv.data(), shaderSize);
  1037. uint8_t nul = 0;
  1038. bx::write(_writer, nul);
  1039. }
  1040. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  1041. bx::write(_writer, numAttr);
  1042. for (uint8_t ii = 0; ii < numAttr; ++ii)
  1043. {
  1044. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  1045. if (bgfx::Attrib::Count != attr)
  1046. {
  1047. bx::write(_writer, bgfx::attribToId(attr) );
  1048. }
  1049. else
  1050. {
  1051. bx::write(_writer, uint16_t(UINT16_MAX) );
  1052. }
  1053. }
  1054. bx::write(_writer, size);
  1055. }
  1056. }
  1057. }
  1058. delete program;
  1059. delete shader;
  1060. glslang::FinalizeProcess();
  1061. return compiled && linked && validated;
  1062. }
  1063. } // namespace spirv
  1064. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  1065. {
  1066. return spirv::compile(_options, _version, _code, _writer, true);
  1067. }
  1068. } // namespace bgfx