shaderc_spirv.cpp 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184
  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 bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  595. {
  596. BX_UNUSED(_version);
  597. glslang::InitializeProcess();
  598. glslang::TProgram* program = new glslang::TProgram;
  599. EShLanguage stage = getLang(_options.shaderType);
  600. if (EShLangCount == stage)
  601. {
  602. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  603. return false;
  604. }
  605. glslang::TShader* shader = new glslang::TShader(stage);
  606. EShMessages messages = EShMessages(0
  607. | EShMsgDefault
  608. | EShMsgReadHlsl
  609. | EShMsgVulkanRules
  610. | EShMsgSpvRules
  611. );
  612. shader->setEntryPoint("main");
  613. shader->setAutoMapBindings(true);
  614. uint32_t bindingOffset = (stage == EShLanguage::EShLangFragment ? 48 : 0);
  615. shader->setShiftBinding(glslang::EResUbo, bindingOffset);
  616. shader->setShiftBinding(glslang::EResTexture, bindingOffset + 16);
  617. shader->setShiftBinding(glslang::EResSampler, bindingOffset + 32);
  618. shader->setShiftBinding(glslang::EResSsbo, bindingOffset + 16);
  619. shader->setShiftBinding(glslang::EResImage, bindingOffset + 32);
  620. const char* shaderStrings[] = { _code.c_str() };
  621. shader->setStrings(
  622. shaderStrings
  623. , BX_COUNTOF(shaderStrings)
  624. );
  625. bool compiled = shader->parse(&resourceLimits
  626. , 110
  627. , false
  628. , messages
  629. );
  630. bool linked = false;
  631. bool validated = true;
  632. if (!compiled)
  633. {
  634. const char* log = shader->getInfoLog();
  635. if (NULL != log)
  636. {
  637. int32_t source = 0;
  638. int32_t line = 0;
  639. int32_t column = 0;
  640. int32_t start = 0;
  641. int32_t end = INT32_MAX;
  642. bx::StringView err = bx::strFind(log, "ERROR:");
  643. bool found = false;
  644. if (!err.isEmpty() )
  645. {
  646. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  647. if (found)
  648. {
  649. ++line;
  650. }
  651. }
  652. if (found)
  653. {
  654. start = bx::uint32_imax(1, line-10);
  655. end = start + 20;
  656. }
  657. printCode(_code.c_str(), line, start, end, column);
  658. bx::printf("%s\n", log);
  659. }
  660. }
  661. else
  662. {
  663. program->addShader(shader);
  664. linked = true
  665. && program->link(messages)
  666. && program->mapIO()
  667. ;
  668. if (!linked)
  669. {
  670. const char* log = program->getInfoLog();
  671. if (NULL != log)
  672. {
  673. bx::printf("%s\n", log);
  674. }
  675. }
  676. else
  677. {
  678. program->buildReflection();
  679. if (_firstPass)
  680. {
  681. // first time through, we just find unused uniforms and get rid of them
  682. std::string output;
  683. struct Uniform
  684. {
  685. std::string name;
  686. std::string decl;
  687. };
  688. std::vector<Uniform> uniforms;
  689. bx::LineReader reader(_code.c_str() );
  690. while (!reader.isDone() )
  691. {
  692. bx::StringView strLine = reader.next();
  693. bool moved = false;
  694. bx::StringView str = strFind(strLine, "uniform ");
  695. if (!str.isEmpty() )
  696. {
  697. bool found = false;
  698. bool sampler = false;
  699. std::string name = "";
  700. // add to samplers
  701. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  702. {
  703. if (!bx::findIdentifierMatch(strLine, s_samplerTypes[ii]).isEmpty() )
  704. {
  705. found = true;
  706. sampler = true;
  707. break;
  708. }
  709. }
  710. if (!found)
  711. {
  712. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  713. {
  714. // matching lines like: uniform u_name;
  715. // we want to replace "uniform" with "static" so that it's no longer
  716. // included in the uniform blob that the application must upload
  717. // we can't just remove them, because unused functions might still reference
  718. // them and cause a compile error when they're gone
  719. if (!bx::findIdentifierMatch(strLine, program->getUniformName(ii) ).isEmpty() )
  720. {
  721. found = true;
  722. name = program->getUniformName(ii);
  723. break;
  724. }
  725. }
  726. }
  727. if (!found)
  728. {
  729. output.append(strLine.getPtr(), str.getPtr() );
  730. output += "static ";
  731. output.append(str.getTerm(), strLine.getTerm() );
  732. output += "\n";
  733. moved = true;
  734. }
  735. else if (!sampler)
  736. {
  737. Uniform uniform;
  738. uniform.name = name;
  739. uniform.decl = std::string(strLine.getPtr(), strLine.getTerm() );
  740. uniforms.push_back(uniform);
  741. moved = true;
  742. }
  743. }
  744. if (!moved)
  745. {
  746. output.append(strLine.getPtr(), strLine.getTerm() );
  747. output += "\n";
  748. }
  749. }
  750. std::string uniformBlock;
  751. uniformBlock += "cbuffer UniformBlock\n";
  752. uniformBlock += "{\n";
  753. for (const Uniform& uniform : uniforms)
  754. {
  755. uniformBlock += uniform.decl.substr(7 /* uniform */);
  756. uniformBlock += "\n";
  757. }
  758. uniformBlock += "};\n";
  759. output = uniformBlock + output;
  760. // recompile with the unused uniforms converted to statics
  761. return compile(_options, _version, output.c_str(), _writer, false);
  762. }
  763. else
  764. {
  765. // second time, do nothing (todo remove)
  766. }
  767. UniformArray uniforms;
  768. {
  769. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  770. for (uint16_t ii = 0; ii < count; ++ii)
  771. {
  772. Uniform un;
  773. un.name = program->getUniformName(ii);
  774. un.num = uint8_t(program->getUniformArraySize(ii) );
  775. const uint32_t offset = program->getUniformBufferOffset(ii);
  776. un.regIndex = uint16_t(offset);
  777. un.regCount = un.num;
  778. switch (program->getUniformType(ii) )
  779. {
  780. case 0x1404: // GL_INT:
  781. un.type = UniformType::Sampler;
  782. break;
  783. case 0x8B52: // GL_FLOAT_VEC4:
  784. un.type = UniformType::Vec4;
  785. break;
  786. case 0x8B5B: // GL_FLOAT_MAT3:
  787. un.type = UniformType::Mat3;
  788. un.regCount *= 3;
  789. break;
  790. case 0x8B5C: // GL_FLOAT_MAT4:
  791. un.type = UniformType::Mat4;
  792. un.regCount *= 4;
  793. break;
  794. default:
  795. un.type = UniformType::End;
  796. break;
  797. }
  798. uniforms.push_back(un);
  799. }
  800. }
  801. if (g_verbose)
  802. {
  803. program->dumpReflection();
  804. }
  805. BX_UNUSED(spv::MemorySemanticsAllMemory);
  806. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  807. std::vector<uint32_t> spirv;
  808. glslang::SpvOptions options;
  809. options.disableOptimizer = false;
  810. glslang::GlslangToSpv(*intermediate, spirv, &options);
  811. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  812. auto print_msg_to_stderr = [](
  813. spv_message_level_t
  814. , const char*
  815. , const spv_position_t&
  816. , const char* m
  817. )
  818. {
  819. bx::printf("Error: %s\n", m);
  820. };
  821. opt.SetMessageConsumer(print_msg_to_stderr);
  822. opt.RegisterLegalizationPasses();
  823. spvtools::ValidatorOptions validatorOptions;
  824. validatorOptions.SetBeforeHlslLegalization(true);
  825. if (!opt.Run(
  826. spirv.data()
  827. , spirv.size()
  828. , &spirv
  829. , validatorOptions
  830. , false
  831. ) )
  832. {
  833. compiled = false;
  834. }
  835. else
  836. {
  837. bx::Error err;
  838. bx::WriterI* writer = bx::getDebugOut();
  839. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  840. disassemble(writer, &reader, &err);
  841. spirv_cross::CompilerReflection refl(spirv);
  842. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  843. if (g_verbose)
  844. {
  845. glslang::SpirvToolsDisassemble(std::cout, spirv);
  846. }
  847. // Loop through the separate_images, and extract the uniform names:
  848. for (auto &resource : resourcesrefl.separate_images)
  849. {
  850. std::string name = refl.get_name(resource.id);
  851. if (name.size() > 7
  852. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  853. {
  854. std::string uniform_name = name.substr(0, name.length() - 7);
  855. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  856. auto imageType = refl.get_type(resource.base_type_id).image;
  857. auto componentType = refl.get_type(imageType.type).basetype;
  858. bool isCompareSampler = false;
  859. for (auto& sampler : resourcesrefl.separate_samplers)
  860. {
  861. if (binding_index + 16 == refl.get_decoration(sampler.id, spv::Decoration::DecorationBinding) )
  862. {
  863. std::string samplerName = refl.get_name(sampler.id);
  864. isCompareSampler = refl.variable_is_depth_or_compare(sampler.id) || samplerName.find("Comparison") != std::string::npos;
  865. break;
  866. }
  867. }
  868. Uniform un;
  869. un.name = uniform_name;
  870. un.type = UniformType::Enum(UniformType::Sampler
  871. | kUniformSamplerBit
  872. | (isCompareSampler ? kUniformCompareBit : 0)
  873. );
  874. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType) );
  875. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  876. un.regIndex = binding_index;
  877. un.regCount = 0; // unused
  878. uniforms.push_back(un);
  879. }
  880. }
  881. // Loop through the separate_images, and extract the uniform names:
  882. for (auto &resource : resourcesrefl.storage_images)
  883. {
  884. std::string name = refl.get_name(resource.id);
  885. if (name.size() > 7
  886. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  887. {
  888. std::string uniform_name = name.substr(0, name.length() - 7);
  889. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  890. auto imageType = refl.get_type(resource.base_type_id).image;
  891. auto componentType = refl.get_type(imageType.type).basetype;
  892. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  893. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  894. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  895. : UniformType::End;
  896. Uniform un;
  897. un.name = uniform_name;
  898. un.type = type;
  899. un.texComponent = uint8_t(SpirvCrossBaseTypeToFormatType(componentType) );
  900. un.texDimension = uint8_t(SpirvDimToTextureViewDimension(imageType.dim, imageType.arrayed) );
  901. un.regIndex = binding_index;
  902. un.regCount = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; // for descriptor type
  903. uniforms.push_back(un);
  904. }
  905. }
  906. // Loop through the storage buffer, and extract the uniform names:
  907. for (auto& resource : resourcesrefl.storage_buffers)
  908. {
  909. std::string name = refl.get_name(resource.id);
  910. for (auto& uniform : uniforms)
  911. {
  912. if (!bx::strFind(uniform.name.c_str(), name.c_str() ).isEmpty() )
  913. {
  914. spirv_cross::Bitset flags = refl.get_buffer_block_flags(resource.id);
  915. UniformType::Enum type = flags.get(spv::DecorationNonWritable)
  916. ? UniformType::Enum(kUniformReadOnlyBit | UniformType::End)
  917. : UniformType::End;
  918. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  919. uniform.name = name;
  920. uniform.type = type;
  921. uniform.regIndex = binding_index;
  922. uniform.regCount = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  923. break;
  924. }
  925. }
  926. }
  927. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  928. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  929. {
  930. spirv_cross::CompilerMSL msl(std::move(spirv) );
  931. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  932. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  933. if (!entryPoints.empty() )
  934. {
  935. msl.rename_entry_point(
  936. entryPoints[0].name
  937. , "xlatMtlMain"
  938. , entryPoints[0].execution_model
  939. );
  940. }
  941. for (auto &resource : resources.uniform_buffers)
  942. {
  943. msl.set_name(resource.id, "_mtl_u");
  944. }
  945. for (auto &resource : resources.storage_buffers)
  946. {
  947. unsigned binding = msl.get_decoration(resource.id, spv::DecorationBinding);
  948. msl.set_decoration(resource.id, spv::DecorationBinding, binding + 1);
  949. }
  950. for (auto &resource : resources.separate_images)
  951. {
  952. std::string name = msl.get_name(resource.id);
  953. if (name.size() > 7
  954. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  955. {
  956. msl.set_name(resource.id, name.substr(0, name.length() - 7) );
  957. }
  958. }
  959. std::string source = msl.compile();
  960. if ('c' == _options.shaderType)
  961. {
  962. for (int i = 0; i < 3; ++i)
  963. {
  964. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  965. bx::write(_writer, dim);
  966. }
  967. }
  968. uint32_t shaderSize = (uint32_t)source.size();
  969. bx::write(_writer, shaderSize);
  970. bx::write(_writer, source.c_str(), shaderSize);
  971. uint8_t nul = 0;
  972. bx::write(_writer, nul);
  973. }
  974. else
  975. {
  976. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  977. bx::write(_writer, shaderSize);
  978. bx::write(_writer, spirv.data(), shaderSize);
  979. uint8_t nul = 0;
  980. bx::write(_writer, nul);
  981. }
  982. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  983. bx::write(_writer, numAttr);
  984. for (uint8_t ii = 0; ii < numAttr; ++ii)
  985. {
  986. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  987. if (bgfx::Attrib::Count != attr)
  988. {
  989. bx::write(_writer, bgfx::attribToId(attr) );
  990. }
  991. else
  992. {
  993. bx::write(_writer, uint16_t(UINT16_MAX) );
  994. }
  995. }
  996. bx::write(_writer, size);
  997. }
  998. }
  999. }
  1000. delete program;
  1001. delete shader;
  1002. glslang::FinalizeProcess();
  1003. return compiled && linked && validated;
  1004. }
  1005. } // namespace spirv
  1006. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  1007. {
  1008. return spirv::compile(_options, _version, _code, _writer, true);
  1009. }
  1010. } // namespace bgfx