shaderc_spirv.cpp 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214
  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("-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 != ')'
  504. && ptr < _strLine.c_str() + _strLine.size() )
  505. {
  506. if (*ptr >= '0' && *ptr <= '9')
  507. {
  508. if (start == NULL)
  509. {
  510. start = ptr;
  511. }
  512. end = ptr;
  513. }
  514. ptr++;
  515. }
  516. BX_CHECK(start != NULL && end != NULL, "cannot find register number");
  517. bx::StringView numberString(start, end - start + 1);
  518. int32_t regNumber = -1;
  519. bx::fromString(&regNumber, numberString);
  520. BX_CHECK(regNumber >= 0, "register number should be semi-positive integer");
  521. return regNumber;
  522. }
  523. bgfx::Attrib::Enum toAttribEnum(const bx::StringView& _name)
  524. {
  525. for (uint8_t ii = 0; ii < Attrib::Count; ++ii)
  526. {
  527. if (0 == bx::strCmp(s_attribName[ii], _name) )
  528. {
  529. return bgfx::Attrib::Enum(ii);
  530. }
  531. }
  532. return bgfx::Attrib::Count;
  533. }
  534. static const char* s_samplerTypes[] =
  535. {
  536. "BgfxSampler2D",
  537. "BgfxISampler2D",
  538. "BgfxUSampler2D",
  539. "BgfxSampler2DArray",
  540. "BgfxSampler2DShadow",
  541. "BgfxSampler2DArrayShadow",
  542. "BgfxSampler3D",
  543. "BgfxISampler3D",
  544. "BgfxUSampler3D",
  545. "BgfxSamplerCube",
  546. "BgfxSamplerCubeShadow",
  547. "BgfxSampler2DMS",
  548. };
  549. static uint16_t writeUniformArray(bx::WriterI* _writer, const UniformArray& uniforms, bool isFragmentShader)
  550. {
  551. uint16_t size = 0;
  552. uint16_t count = static_cast<uint16_t>(uniforms.size());
  553. bx::write(_writer, count);
  554. uint32_t fragmentBit = isFragmentShader ? BGFX_UNIFORM_FRAGMENTBIT : 0;
  555. for (uint16_t ii = 0; ii < count; ++ii)
  556. {
  557. const Uniform& un = uniforms[ii];
  558. if (un.type != UniformType::Sampler)
  559. size = bx::max(size, (uint16_t)(un.regIndex + un.regCount*16));
  560. uint8_t nameSize = (uint8_t)un.name.size();
  561. bx::write(_writer, nameSize);
  562. bx::write(_writer, un.name.c_str(), nameSize);
  563. bx::write(_writer, uint8_t(un.type | fragmentBit));
  564. bx::write(_writer, un.num);
  565. bx::write(_writer, un.regIndex);
  566. bx::write(_writer, un.regCount);
  567. BX_TRACE("%s, %s, %d, %d, %d"
  568. , un.name.c_str()
  569. , getUniformTypeName(un.type)
  570. , un.num
  571. , un.regIndex
  572. , un.regCount
  573. );
  574. }
  575. return size;
  576. }
  577. static bool compile(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer, bool _firstPass)
  578. {
  579. BX_UNUSED(_version);
  580. glslang::InitializeProcess();
  581. glslang::TProgram* program = new glslang::TProgram;
  582. EShLanguage stage = getLang(_options.shaderType);
  583. if (EShLangCount == stage)
  584. {
  585. bx::printf("Error: Unknown shader type '%c'.\n", _options.shaderType);
  586. return false;
  587. }
  588. glslang::TShader* shader = new glslang::TShader(stage);
  589. EShMessages messages = EShMessages(0
  590. | EShMsgDefault
  591. | EShMsgReadHlsl
  592. | EShMsgVulkanRules
  593. | EShMsgSpvRules
  594. );
  595. shader->setEntryPoint("main");
  596. shader->setAutoMapBindings(true);
  597. uint32_t bindingOffset = (stage == EShLanguage::EShLangFragment ? 48 : 0);
  598. shader->setShiftBinding(glslang::EResUbo, bindingOffset);
  599. shader->setShiftBinding(glslang::EResTexture, bindingOffset + 16);
  600. shader->setShiftBinding(glslang::EResSampler, bindingOffset + 32);
  601. shader->setShiftBinding(glslang::EResSsbo, bindingOffset + 16);
  602. shader->setShiftBinding(glslang::EResImage, bindingOffset + 32);
  603. const char* shaderStrings[] = { _code.c_str() };
  604. shader->setStrings(
  605. shaderStrings
  606. , BX_COUNTOF(shaderStrings)
  607. );
  608. bool compiled = shader->parse(&resourceLimits
  609. , 110
  610. , false
  611. , messages
  612. );
  613. bool linked = false;
  614. bool validated = true;
  615. if (!compiled)
  616. {
  617. const char* log = shader->getInfoLog();
  618. if (NULL != log)
  619. {
  620. int32_t source = 0;
  621. int32_t line = 0;
  622. int32_t column = 0;
  623. int32_t start = 0;
  624. int32_t end = INT32_MAX;
  625. bx::StringView err = bx::strFind(log, "ERROR:");
  626. bool found = false;
  627. if (!err.isEmpty() )
  628. {
  629. found = 2 == sscanf(err.getPtr(), "ERROR: %u:%u: '", &source, &line);
  630. if (found)
  631. {
  632. ++line;
  633. }
  634. }
  635. if (found)
  636. {
  637. start = bx::uint32_imax(1, line-10);
  638. end = start + 20;
  639. }
  640. printCode(_code.c_str(), line, start, end, column);
  641. bx::printf("%s\n", log);
  642. }
  643. }
  644. else
  645. {
  646. program->addShader(shader);
  647. linked = true
  648. && program->link(messages)
  649. && program->mapIO()
  650. ;
  651. if (!linked)
  652. {
  653. const char* log = program->getInfoLog();
  654. if (NULL != log)
  655. {
  656. bx::printf("%s\n", log);
  657. }
  658. }
  659. else
  660. {
  661. program->buildReflection();
  662. std::map<std::string, uint32_t> stageMap;
  663. if (_firstPass)
  664. {
  665. // first time through, we just find unused uniforms and get rid of them
  666. std::string output;
  667. bx::Error err;
  668. LineReader reader(_code.c_str() );
  669. while (err.isOk() )
  670. {
  671. char str[4096];
  672. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  673. if (err.isOk() )
  674. {
  675. std::string strLine(str, len);
  676. size_t index = strLine.find("uniform ");
  677. if (index != std::string::npos)
  678. {
  679. bool found = false;
  680. for (uint32_t ii = 0; ii < BX_COUNTOF(s_samplerTypes); ++ii)
  681. {
  682. if (!bx::findIdentifierMatch(strLine.c_str(), s_samplerTypes[ii]).isEmpty())
  683. {
  684. found = true;
  685. break;
  686. }
  687. }
  688. if (!found)
  689. {
  690. for (int32_t ii = 0, num = program->getNumLiveUniformVariables(); ii < num; ++ii)
  691. {
  692. // matching lines like: uniform u_name;
  693. // we want to replace "uniform" with "static" so that it's no longer
  694. // included in the uniform blob that the application must upload
  695. // we can't just remove them, because unused functions might still reference
  696. // them and cause a compile error when they're gone
  697. if (!bx::findIdentifierMatch(strLine.c_str(), program->getUniformName(ii)).isEmpty())
  698. {
  699. found = true;
  700. break;
  701. }
  702. }
  703. }
  704. if (!found)
  705. {
  706. strLine = strLine.replace(index, 7 /* uniform */, "static");
  707. }
  708. }
  709. output += strLine;
  710. }
  711. }
  712. // recompile with the unused uniforms converted to statics
  713. return compile(_options, _version, output.c_str(), _writer, false);
  714. }
  715. else
  716. {
  717. // second time, find sampler state and get its stage index
  718. bx::Error err;
  719. LineReader reader(_code.c_str());
  720. while (err.isOk())
  721. {
  722. char str[4096];
  723. int32_t len = bx::read(&reader, str, BX_COUNTOF(str), &err);
  724. if (err.isOk())
  725. {
  726. std::string strLine(str, len);
  727. size_t index = strLine.find("uniform ");
  728. if (index != std::string::npos)
  729. {
  730. if (!bx::findIdentifierMatch(strLine.c_str(), "SamplerState").isEmpty() ||
  731. !bx::findIdentifierMatch(strLine.c_str(), "SamplerComparisonState").isEmpty())
  732. {
  733. int32_t regNumber = extractStageNumber(strLine);
  734. bx::StringView found = bx::findIdentifierMatch(strLine.c_str(), "SamplerState");
  735. if (found.isEmpty() )
  736. {
  737. found = bx::findIdentifierMatch(
  738. strLine.c_str()
  739. , "SamplerComparisonState"
  740. );
  741. }
  742. const char* ptr = found.getPtr() + found.getLength();
  743. const char* start = NULL;
  744. const char* end = NULL;
  745. while (ptr < strLine.c_str() + strLine.size())
  746. {
  747. if (*ptr != ' ')
  748. {
  749. if (start == NULL)
  750. {
  751. start = ptr;
  752. }
  753. end = ptr;
  754. }
  755. else if (start != NULL)
  756. {
  757. break;
  758. }
  759. ptr++;
  760. }
  761. BX_CHECK(start != NULL && end != NULL, "sampler name cannot be found");
  762. std::string samplerName(start, end - start + 1);
  763. stageMap[samplerName] = regNumber;
  764. }
  765. }
  766. else if (!bx::findIdentifierMatch(strLine.c_str(), "StructuredBuffer").isEmpty()
  767. || !bx::findIdentifierMatch(strLine.c_str(), "RWStructuredBuffer").isEmpty() )
  768. {
  769. int32_t regNumber = extractStageNumber(strLine);
  770. const char* ptr = strLine.c_str();
  771. const char* start = NULL;
  772. const char* end = NULL;
  773. while (ptr < strLine.c_str() + strLine.size())
  774. {
  775. if (*ptr == '>')
  776. {
  777. start = ptr + 1;
  778. while (*start == ' ')
  779. {
  780. start++;
  781. }
  782. }
  783. if (*ptr == ':')
  784. {
  785. end = ptr - 1;
  786. while (*end == ' ')
  787. {
  788. end--;
  789. }
  790. }
  791. if (start != NULL && end != NULL)
  792. {
  793. break;
  794. }
  795. ptr++;
  796. }
  797. BX_CHECK(start != NULL && end != NULL, "sampler name cannot be found");
  798. std::string bufferName(start, end - start + 1);
  799. stageMap[bufferName] = regNumber;
  800. }
  801. }
  802. }
  803. }
  804. UniformArray uniforms;
  805. {
  806. uint16_t count = (uint16_t)program->getNumLiveUniformVariables();
  807. for (uint16_t ii = 0; ii < count; ++ii)
  808. {
  809. Uniform un;
  810. un.name = program->getUniformName(ii);
  811. un.num = uint8_t(program->getUniformArraySize(ii) );
  812. const uint32_t offset = program->getUniformBufferOffset(ii);
  813. un.regIndex = uint16_t(offset);
  814. un.regCount = un.num;
  815. switch (program->getUniformType(ii))
  816. {
  817. case 0x1404: // GL_INT:
  818. un.type = UniformType::Sampler;
  819. break;
  820. case 0x8B52: // GL_FLOAT_VEC4:
  821. un.type = UniformType::Vec4;
  822. break;
  823. case 0x8B5B: // GL_FLOAT_MAT3:
  824. un.type = UniformType::Mat3;
  825. un.regCount *= 3;
  826. break;
  827. case 0x8B5C: // GL_FLOAT_MAT4:
  828. un.type = UniformType::Mat4;
  829. un.regCount *= 4;
  830. break;
  831. default:
  832. un.type = UniformType::End;
  833. break;
  834. }
  835. uniforms.push_back(un);
  836. }
  837. }
  838. if (g_verbose)
  839. {
  840. program->dumpReflection();
  841. }
  842. BX_UNUSED(spv::MemorySemanticsAllMemory);
  843. glslang::TIntermediate* intermediate = program->getIntermediate(stage);
  844. std::vector<uint32_t> spirv;
  845. glslang::SpvOptions options;
  846. options.disableOptimizer = false;
  847. glslang::GlslangToSpv(*intermediate, spirv, &options);
  848. spvtools::Optimizer opt(SPV_ENV_VULKAN_1_0);
  849. auto print_msg_to_stderr = [](
  850. spv_message_level_t
  851. , const char*
  852. , const spv_position_t&
  853. , const char* m
  854. )
  855. {
  856. bx::printf("Error: %s\n", m);
  857. };
  858. opt.SetMessageConsumer(print_msg_to_stderr);
  859. opt.RegisterLegalizationPasses();
  860. spvtools::ValidatorOptions validatorOptions;
  861. validatorOptions.SetBeforeHlslLegalization(true);
  862. if (!opt.Run(
  863. spirv.data()
  864. , spirv.size()
  865. , &spirv
  866. , validatorOptions
  867. , false
  868. ) )
  869. {
  870. compiled = false;
  871. }
  872. else
  873. {
  874. bx::Error err;
  875. bx::WriterI* writer = bx::getDebugOut();
  876. bx::MemoryReader reader(spirv.data(), uint32_t(spirv.size()*4) );
  877. disassemble(writer, &reader, &err);
  878. spirv_cross::CompilerReflection refl(spirv);
  879. spirv_cross::ShaderResources resourcesrefl = refl.get_shader_resources();
  880. // Loop through the separate_images, and extract the uniform names:
  881. for (auto &resource : resourcesrefl.separate_images)
  882. {
  883. std::string name = refl.get_name(resource.id);
  884. if (name.size() > 7
  885. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  886. {
  887. auto uniform_name = name.substr(0, name.length() - 7);
  888. Uniform un;
  889. un.name = uniform_name;
  890. un.type = UniformType::Sampler;
  891. uint32_t texture_binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  892. uint32_t sampler_binding_index = 0;
  893. std::string sampler_name;
  894. for (auto& sampler_resource : resourcesrefl.separate_samplers)
  895. {
  896. sampler_name = refl.get_name(sampler_resource.id);
  897. if (sampler_name.size() > 7
  898. && !bx::strFind(sampler_name.c_str(), uniform_name.c_str()).isEmpty()
  899. && (0 == bx::strCmp(sampler_name.c_str() + name.length() - 7, "Sampler") ||
  900. 0 == bx::strCmp(sampler_name.c_str() + name.length() - 7, "SamplerComparison")
  901. ) )
  902. {
  903. sampler_binding_index = refl.get_decoration(sampler_resource.id, spv::Decoration::DecorationBinding);
  904. break;
  905. }
  906. }
  907. un.num = stageMap[sampler_name]; // want to write stage index
  908. un.regIndex = texture_binding_index; // for sampled image binding index
  909. un.regCount = sampler_binding_index; // for sampler binding index
  910. uniforms.push_back(un);
  911. }
  912. }
  913. // Loop through the separate_images, and extract the uniform names:
  914. for (auto &resource : resourcesrefl.storage_images)
  915. {
  916. std::string name = refl.get_name(resource.id);
  917. if (name.size() > 7
  918. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  919. {
  920. auto uniform_name = name.substr(0, name.length() - 7);
  921. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  922. std::string sampler_name = uniform_name + "Sampler";
  923. Uniform un;
  924. un.name = uniform_name;
  925. un.type = UniformType::End;
  926. un.num = stageMap[sampler_name]; // want to write stage index
  927. un.regIndex = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; // for descriptor type
  928. un.regCount = binding_index; // for image binding index
  929. uniforms.push_back(un);
  930. }
  931. }
  932. // Loop through the storage buffer, and extract the uniform names:
  933. for (auto& resource : resourcesrefl.storage_buffers)
  934. {
  935. std::string name = refl.get_name(resource.id);
  936. for (auto& uniform : uniforms)
  937. {
  938. if (!bx::strFind(uniform.name.c_str(), name.c_str()).isEmpty())
  939. {
  940. uint32_t binding_index = refl.get_decoration(resource.id, spv::Decoration::DecorationBinding);
  941. uniform.name = name;
  942. uniform.type = UniformType::End;
  943. uniform.num = stageMap[name];
  944. uniform.regIndex = VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
  945. uniform.regCount = binding_index;
  946. break;
  947. }
  948. }
  949. }
  950. uint16_t size = writeUniformArray( _writer, uniforms, _options.shaderType == 'f');
  951. if (_version == BX_MAKEFOURCC('M', 'T', 'L', 0) )
  952. {
  953. if (g_verbose)
  954. {
  955. glslang::SpirvToolsDisassemble(std::cout, spirv);
  956. }
  957. spirv_cross::CompilerMSL msl(std::move(spirv));
  958. spirv_cross::ShaderResources resources = msl.get_shader_resources();
  959. spirv_cross::SmallVector<spirv_cross::EntryPoint> entryPoints = msl.get_entry_points_and_stages();
  960. if (!entryPoints.empty() )
  961. {
  962. msl.rename_entry_point(
  963. entryPoints[0].name
  964. , "xlatMtlMain"
  965. , entryPoints[0].execution_model
  966. );
  967. }
  968. for (auto &resource : resources.uniform_buffers)
  969. {
  970. msl.set_name(resource.id, "_mtl_u");
  971. }
  972. for (auto &resource : resources.storage_buffers)
  973. {
  974. unsigned binding = msl.get_decoration(resource.id, spv::DecorationBinding);
  975. msl.set_decoration(resource.id, spv::DecorationBinding, binding + 1);
  976. }
  977. for (auto &resource : resources.separate_images)
  978. {
  979. std::string name = msl.get_name(resource.id);
  980. if (name.size() > 7
  981. && 0 == bx::strCmp(name.c_str() + name.length() - 7, "Texture") )
  982. {
  983. msl.set_name(resource.id, name.substr(0, name.length() - 7));
  984. }
  985. }
  986. std::string source = msl.compile();
  987. if ('c' == _options.shaderType)
  988. {
  989. for (int i = 0; i < 3; ++i)
  990. {
  991. uint16_t dim = (uint16_t)msl.get_execution_mode_argument(spv::ExecutionMode::ExecutionModeLocalSize, i);
  992. bx::write(_writer, dim);
  993. }
  994. }
  995. uint32_t shaderSize = (uint32_t)source.size();
  996. bx::write(_writer, shaderSize);
  997. bx::write(_writer, source.c_str(), shaderSize);
  998. uint8_t nul = 0;
  999. bx::write(_writer, nul);
  1000. }
  1001. else
  1002. {
  1003. uint32_t shaderSize = (uint32_t)spirv.size() * sizeof(uint32_t);
  1004. bx::write(_writer, shaderSize);
  1005. bx::write(_writer, spirv.data(), shaderSize);
  1006. uint8_t nul = 0;
  1007. bx::write(_writer, nul);
  1008. }
  1009. const uint8_t numAttr = (uint8_t)program->getNumLiveAttributes();
  1010. bx::write(_writer, numAttr);
  1011. for (uint8_t ii = 0; ii < numAttr; ++ii)
  1012. {
  1013. bgfx::Attrib::Enum attr = toAttribEnum(program->getAttributeName(ii) );
  1014. if (bgfx::Attrib::Count != attr)
  1015. {
  1016. bx::write(_writer, bgfx::attribToId(attr) );
  1017. }
  1018. else
  1019. {
  1020. bx::write(_writer, uint16_t(UINT16_MAX) );
  1021. }
  1022. }
  1023. bx::write(_writer, size);
  1024. }
  1025. }
  1026. }
  1027. delete program;
  1028. delete shader;
  1029. glslang::FinalizeProcess();
  1030. return compiled && linked && validated;
  1031. }
  1032. } // namespace spirv
  1033. bool compileSPIRVShader(const Options& _options, uint32_t _version, const std::string& _code, bx::WriterI* _writer)
  1034. {
  1035. return spirv::compile(_options, _version, _code, _writer, true);
  1036. }
  1037. } // namespace bgfx