shaderc_spirv.cpp 30 KB

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