shaderc_spirv.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248
  1. /*
  2. * Copyright 2011-2021 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. EShLanguage stage = getLang(_options.shaderType);
  654. if (EShLangCount == stage)
  655. {
  656. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  657. return false;
  658. }
  659. glslang::TProgram* program = new glslang::TProgram;
  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. delete program;
  820. delete shader;
  821. return compile(_options, _version, output.c_str(), _writer, false);
  822. }
  823. else
  824. {
  825. // second time, do nothing (todo remove)
  826. }
  827. UniformArray uniforms;
  828. {
  829. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  830. for (uint16_t ii = 0; ii < count; ++ii)
  831. {
  832. Uniform un;
  833. un.name = program->getUniformName(ii);
  834. un.num = uint8_t(program->getUniformArraySize(ii) );
  835. const uint32_t offset = program->getUniformBufferOffset(ii);
  836. un.regIndex = uint16_t(offset);
  837. un.regCount = un.num;
  838. switch (program->getUniformType(ii) )
  839. {
  840. case 0x1404: // GL_INT:
  841. un.type = UniformType::Sampler;
  842. break;
  843. case 0x8B52: // GL_FLOAT_VEC4:
  844. un.type = UniformType::Vec4;
  845. break;
  846. case 0x8B5B: // GL_FLOAT_MAT3:
  847. un.type = UniformType::Mat3;
  848. un.regCount *= 3;
  849. break;
  850. case 0x8B5C: // GL_FLOAT_MAT4:
  851. un.type = UniformType::Mat4;
  852. un.regCount *= 4;
  853. break;
  854. default:
  855. un.type = UniformType::End;
  856. break;
  857. }
  858. uniforms.push_back(un);
  859. }
  860. }
  861. if (g_verbose)
  862. {
  863. program->dumpReflection();
  864. }
  865. BX_UNUSED(spv::MemorySemanticsAllMemory);
  866. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  867. std::vector<uint32_t> spirv;
  868. glslang::SpvOptions options;
  869. options.disableOptimizer = false;
  870. glslang::GlslangToSpv(*intermediate, spirv, &options);
  871. spvtools::Optimizer opt(getSpirvTargetVersion(_version));
  872. auto print_msg_to_stderr = [](
  873. spv_message_level_t
  874. , const char*
  875. , const spv_position_t&
  876. , const char* m
  877. )
  878. {
  879. bx::printf("Error: %s\n", m);
  880. };
  881. opt.SetMessageConsumer(print_msg_to_stderr);
  882. opt.RegisterLegalizationPasses();
  883. spvtools::ValidatorOptions validatorOptions;
  884. validatorOptions.SetBeforeHlslLegalization(true);
  885. if (!opt.Run(
  886. spirv.data()
  887. , spirv.size()
  888. , &spirv
  889. , validatorOptions
  890. , false
  891. ) )
  892. {
  893. compiled = false;
  894. }
  895. else
  896. {
  897. bx::Error err;
  898. bx::WriterI* writer = bx::getDebugOut();
  899. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  900. disassemble(writer, &reader, &err);
  901. spirv_cross::CompilerReflection refl(spirv);
  902. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  903. if (g_verbose)
  904. {
  905. glslang::SpirvToolsDisassemble(std::cout, spirv, getSpirvTargetVersion(_version) );
  906. }
  907. // Loop through the separate_images, and extract the uniform names:
  908. for (auto &resource : resourcesrefl.separate_images)
  909. {
  910. std::string name = refl.get_name(resource.id);
  911. if (name.size() > 7
  912. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  913. {
  914. std::string uniform_name = name.substr(0, name.length() - 7);
  915. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  916. auto imageType = refl.get_type(resource.base_type_id).image;
  917. auto componentType = refl.get_type(imageType.type).basetype;
  918. bool isCompareSampler = false;
  919. for (auto& sampler : resourcesrefl.separate_samplers)
  920. {
  921. if (binding_index + 16 == refl.get_decoration(sampler.id, spv::Decoration::DecorationBinding) )
  922. {
  923. std::string samplerName = refl.get_name(sampler.id);
  924. isCompareSampler = refl.variable_is_depth_or_compare(sampler.id) || samplerName.find("Comparison") != std::string::npos;
  925. break;
  926. }
  927. }
  928. Uniform un;
  929. un.name = uniform_name;
  930. un.type = UniformType::Enum(UniformType::Sampler
  931. | kUniformSamplerBit
  932. | (isCompareSampler ? kUniformCompareBit : 0)
  933. );
  934. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType) );
  935. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  936. un.regIndex = binding_index;
  937. un.regCount = 0; // unused
  938. uniforms.push_back(un);
  939. }
  940. }
  941. // Loop through the storage_images, and extract the uniform names:
  942. for (auto &resource : resourcesrefl.storage_images)
  943. {
  944. std::string name = refl.get_name(resource.id);
  945. if (name.size() > 7
  946. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  947. {
  948. std::string uniform_name = name.substr(0, name.length() - 7);
  949. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  950. auto imageType = refl.get_type(resource.base_type_id).image;
  951. auto componentType = refl.get_type(imageType.type).basetype;
  952. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  953. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  954. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  955. : UniformType::End;
  956. Uniform un;
  957. un.name = uniform_name;
  958. un.type = type;
  959. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType) );
  960. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  961. un.regIndex = binding_index;
  962. un.regCount = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; // for descriptor type
  963. uniforms.push_back(un);
  964. }
  965. }
  966. // Loop through the storage buffer, and extract the uniform names:
  967. for (auto& resource : resourcesrefl.storage_buffers)
  968. {
  969. std::string name = refl.get_name(resource.id);
  970. for (auto& uniform : uniforms)
  971. {
  972. if (!bx::strFind(uniform.name.c_str(), name.c_str() ).isEmpty() )
  973. {
  974. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  975. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  976. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  977. : UniformType::End;
  978. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  979. uniform.name = name;
  980. uniform.type = type;
  981. uniform.regIndex = binding_index;
  982. uniform.regCount = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  983. break;
  984. }
  985. }
  986. }
  987. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  988. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  989. {
  990. spirv_cross::CompilerMSL msl(std::move(spirv) );
  991. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  992. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  993. if (!entryPoints.empty() )
  994. {
  995. msl.rename_entry_point(
  996. entryPoints[0].name
  997. , "xlatMtlMain"
  998. , entryPoints[0].execution_model
  999. );
  1000. }
  1001. for (auto &resource : resources.uniform_buffers)
  1002. {
  1003. msl.set_name(resource.id, "_mtl_u");
  1004. }
  1005. for (auto &resource : resources.storage_buffers)
  1006. {
  1007. unsigned binding = msl.get_decoration(resource.id, spv::DecorationBinding);
  1008. msl.set_decoration(resource.id, spv::DecorationBinding, binding + 1);
  1009. }
  1010. for (auto &resource : resources.separate_images)
  1011. {
  1012. std::string name = msl.get_name(resource.id);
  1013. if (name.size() > 7
  1014. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  1015. {
  1016. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  1017. }
  1018. }
  1019. std::string source = msl.compile();
  1020. if ('c' == _options.shaderType)
  1021. {
  1022. for (int i = 0; i < 3; ++i)
  1023. {
  1024. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  1025. bx::write(_writer, dim);
  1026. }
  1027. }
  1028. uint32_t shaderSize = (uint32_t)source.size();
  1029. bx::write(_writer, shaderSize);
  1030. bx::write(_writer, source.c_str(), shaderSize);
  1031. uint8_t nul = 0;
  1032. bx::write(_writer, nul);
  1033. }
  1034. else
  1035. {
  1036. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  1037. bx::write(_writer, shaderSize);
  1038. bx::write(_writer, spirv.data(), shaderSize);
  1039. uint8_t nul = 0;
  1040. bx::write(_writer, nul);
  1041. }
  1042. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  1043. bx::write(_writer, numAttr);
  1044. for (uint8_t ii = 0; ii < numAttr; ++ii)
  1045. {
  1046. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  1047. if (bgfx::Attrib::Count != attr)
  1048. {
  1049. bx::write(_writer, bgfx::attribToId(attr) );
  1050. }
  1051. else
  1052. {
  1053. bx::write(_writer, uint16_t(UINT16_MAX) );
  1054. }
  1055. }
  1056. bx::write(_writer, size);
  1057. }
  1058. }
  1059. }
  1060. delete program;
  1061. delete shader;
  1062. glslang::FinalizeProcess();
  1063. return compiled && linked && validated;
  1064. }
  1065. } // namespace spirv
  1066. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  1067. {
  1068. return spirv::compile(_options, _version, _code, _writer, true);
  1069. }
  1070. } // namespace bgfx