spirv_parser.cpp 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244
  1. /*
  2. * Copyright 2018-2021 Arm Limited
  3. * SPDX-License-Identifier: Apache-2.0 OR MIT
  4. *
  5. * Licensed under the Apache License, Version 2.0 (the "License");
  6. * you may not use this file except in compliance with the License.
  7. * You may obtain a copy of the License at
  8. *
  9. * http://www.apache.org/licenses/LICENSE-2.0
  10. *
  11. * Unless required by applicable law or agreed to in writing, software
  12. * distributed under the License is distributed on an "AS IS" BASIS,
  13. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. * See the License for the specific language governing permissions and
  15. * limitations under the License.
  16. */
  17. /*
  18. * At your option, you may choose to accept this material under either:
  19. * 1. The Apache License, Version 2.0, found at <http://www.apache.org/licenses/LICENSE-2.0>, or
  20. * 2. The MIT License, found at <http://opensource.org/licenses/MIT>.
  21. */
  22. #include "spirv_parser.hpp"
  23. #include <assert.h>
  24. using namespace std;
  25. using namespace spv;
  26. namespace SPIRV_CROSS_NAMESPACE
  27. {
  28. Parser::Parser(vector<uint32_t> spirv)
  29. {
  30. ir.spirv = move(spirv);
  31. }
  32. Parser::Parser(const uint32_t *spirv_data, size_t word_count)
  33. {
  34. ir.spirv = vector<uint32_t>(spirv_data, spirv_data + word_count);
  35. }
  36. static bool decoration_is_string(Decoration decoration)
  37. {
  38. switch (decoration)
  39. {
  40. case DecorationHlslSemanticGOOGLE:
  41. return true;
  42. default:
  43. return false;
  44. }
  45. }
  46. static inline uint32_t swap_endian(uint32_t v)
  47. {
  48. return ((v >> 24) & 0x000000ffu) | ((v >> 8) & 0x0000ff00u) | ((v << 8) & 0x00ff0000u) | ((v << 24) & 0xff000000u);
  49. }
  50. static bool is_valid_spirv_version(uint32_t version)
  51. {
  52. switch (version)
  53. {
  54. // Allow v99 since it tends to just work.
  55. case 99:
  56. case 0x10000: // SPIR-V 1.0
  57. case 0x10100: // SPIR-V 1.1
  58. case 0x10200: // SPIR-V 1.2
  59. case 0x10300: // SPIR-V 1.3
  60. case 0x10400: // SPIR-V 1.4
  61. case 0x10500: // SPIR-V 1.5
  62. return true;
  63. default:
  64. return false;
  65. }
  66. }
  67. void Parser::parse()
  68. {
  69. auto &spirv = ir.spirv;
  70. auto len = spirv.size();
  71. if (len < 5)
  72. SPIRV_CROSS_THROW("SPIRV file too small.");
  73. auto s = spirv.data();
  74. // Endian-swap if we need to.
  75. if (s[0] == swap_endian(MagicNumber))
  76. transform(begin(spirv), end(spirv), begin(spirv), [](uint32_t c) { return swap_endian(c); });
  77. if (s[0] != MagicNumber || !is_valid_spirv_version(s[1]))
  78. SPIRV_CROSS_THROW("Invalid SPIRV format.");
  79. uint32_t bound = s[3];
  80. const uint32_t MaximumNumberOfIDs = 0x3fffff;
  81. if (bound > MaximumNumberOfIDs)
  82. SPIRV_CROSS_THROW("ID bound exceeds limit of 0x3fffff.\n");
  83. ir.set_id_bounds(bound);
  84. uint32_t offset = 5;
  85. SmallVector<Instruction> instructions;
  86. while (offset < len)
  87. {
  88. Instruction instr = {};
  89. instr.op = spirv[offset] & 0xffff;
  90. instr.count = (spirv[offset] >> 16) & 0xffff;
  91. if (instr.count == 0)
  92. SPIRV_CROSS_THROW("SPIR-V instructions cannot consume 0 words. Invalid SPIR-V file.");
  93. instr.offset = offset + 1;
  94. instr.length = instr.count - 1;
  95. offset += instr.count;
  96. if (offset > spirv.size())
  97. SPIRV_CROSS_THROW("SPIR-V instruction goes out of bounds.");
  98. instructions.push_back(instr);
  99. }
  100. for (auto &i : instructions)
  101. parse(i);
  102. for (auto &fixup : forward_pointer_fixups)
  103. {
  104. auto &target = get<SPIRType>(fixup.first);
  105. auto &source = get<SPIRType>(fixup.second);
  106. target.member_types = source.member_types;
  107. target.basetype = source.basetype;
  108. target.self = source.self;
  109. }
  110. forward_pointer_fixups.clear();
  111. if (current_function)
  112. SPIRV_CROSS_THROW("Function was not terminated.");
  113. if (current_block)
  114. SPIRV_CROSS_THROW("Block was not terminated.");
  115. if (ir.default_entry_point == 0)
  116. SPIRV_CROSS_THROW("There is no entry point in the SPIR-V module.");
  117. }
  118. const uint32_t *Parser::stream(const Instruction &instr) const
  119. {
  120. // If we're not going to use any arguments, just return nullptr.
  121. // We want to avoid case where we return an out of range pointer
  122. // that trips debug assertions on some platforms.
  123. if (!instr.length)
  124. return nullptr;
  125. if (instr.offset + instr.length > ir.spirv.size())
  126. SPIRV_CROSS_THROW("Compiler::stream() out of range.");
  127. return &ir.spirv[instr.offset];
  128. }
  129. static string extract_string(const vector<uint32_t> &spirv, uint32_t offset)
  130. {
  131. string ret;
  132. for (uint32_t i = offset; i < spirv.size(); i++)
  133. {
  134. uint32_t w = spirv[i];
  135. for (uint32_t j = 0; j < 4; j++, w >>= 8)
  136. {
  137. char c = w & 0xff;
  138. if (c == '\0')
  139. return ret;
  140. ret += c;
  141. }
  142. }
  143. SPIRV_CROSS_THROW("String was not terminated before EOF");
  144. }
  145. void Parser::parse(const Instruction &instruction)
  146. {
  147. auto *ops = stream(instruction);
  148. auto op = static_cast<Op>(instruction.op);
  149. uint32_t length = instruction.length;
  150. switch (op)
  151. {
  152. case OpSourceContinued:
  153. case OpSourceExtension:
  154. case OpNop:
  155. case OpModuleProcessed:
  156. break;
  157. case OpString:
  158. {
  159. set<SPIRString>(ops[0], extract_string(ir.spirv, instruction.offset + 1));
  160. break;
  161. }
  162. case OpMemoryModel:
  163. ir.addressing_model = static_cast<AddressingModel>(ops[0]);
  164. ir.memory_model = static_cast<MemoryModel>(ops[1]);
  165. break;
  166. case OpSource:
  167. {
  168. auto lang = static_cast<SourceLanguage>(ops[0]);
  169. switch (lang)
  170. {
  171. case SourceLanguageESSL:
  172. ir.source.es = true;
  173. ir.source.version = ops[1];
  174. ir.source.known = true;
  175. ir.source.hlsl = false;
  176. break;
  177. case SourceLanguageGLSL:
  178. ir.source.es = false;
  179. ir.source.version = ops[1];
  180. ir.source.known = true;
  181. ir.source.hlsl = false;
  182. break;
  183. case SourceLanguageHLSL:
  184. // For purposes of cross-compiling, this is GLSL 450.
  185. ir.source.es = false;
  186. ir.source.version = 450;
  187. ir.source.known = true;
  188. ir.source.hlsl = true;
  189. break;
  190. default:
  191. ir.source.known = false;
  192. break;
  193. }
  194. break;
  195. }
  196. case OpUndef:
  197. {
  198. uint32_t result_type = ops[0];
  199. uint32_t id = ops[1];
  200. set<SPIRUndef>(id, result_type);
  201. if (current_block)
  202. current_block->ops.push_back(instruction);
  203. break;
  204. }
  205. case OpCapability:
  206. {
  207. uint32_t cap = ops[0];
  208. if (cap == CapabilityKernel)
  209. SPIRV_CROSS_THROW("Kernel capability not supported.");
  210. ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
  211. break;
  212. }
  213. case OpExtension:
  214. {
  215. auto ext = extract_string(ir.spirv, instruction.offset);
  216. ir.declared_extensions.push_back(move(ext));
  217. break;
  218. }
  219. case OpExtInstImport:
  220. {
  221. uint32_t id = ops[0];
  222. auto ext = extract_string(ir.spirv, instruction.offset + 1);
  223. if (ext == "GLSL.std.450")
  224. set<SPIRExtension>(id, SPIRExtension::GLSL);
  225. else if (ext == "DebugInfo")
  226. set<SPIRExtension>(id, SPIRExtension::SPV_debug_info);
  227. else if (ext == "SPV_AMD_shader_ballot")
  228. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_ballot);
  229. else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
  230. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter);
  231. else if (ext == "SPV_AMD_shader_trinary_minmax")
  232. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_shader_trinary_minmax);
  233. else if (ext == "SPV_AMD_gcn_shader")
  234. set<SPIRExtension>(id, SPIRExtension::SPV_AMD_gcn_shader);
  235. else
  236. set<SPIRExtension>(id, SPIRExtension::Unsupported);
  237. // Other SPIR-V extensions which have ExtInstrs are currently not supported.
  238. break;
  239. }
  240. case OpExtInst:
  241. {
  242. // The SPIR-V debug information extended instructions might come at global scope.
  243. if (current_block)
  244. current_block->ops.push_back(instruction);
  245. break;
  246. }
  247. case OpEntryPoint:
  248. {
  249. auto itr =
  250. ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
  251. extract_string(ir.spirv, instruction.offset + 2))));
  252. auto &e = itr.first->second;
  253. // Strings need nul-terminator and consume the whole word.
  254. uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
  255. for (uint32_t i = strlen_words + 2; i < instruction.length; i++)
  256. e.interface_variables.push_back(ops[i]);
  257. // Set the name of the entry point in case OpName is not provided later.
  258. ir.set_name(ops[1], e.name);
  259. // If we don't have an entry, make the first one our "default".
  260. if (!ir.default_entry_point)
  261. ir.default_entry_point = ops[1];
  262. break;
  263. }
  264. case OpExecutionMode:
  265. {
  266. auto &execution = ir.entry_points[ops[0]];
  267. auto mode = static_cast<ExecutionMode>(ops[1]);
  268. execution.flags.set(mode);
  269. switch (mode)
  270. {
  271. case ExecutionModeInvocations:
  272. execution.invocations = ops[2];
  273. break;
  274. case ExecutionModeLocalSize:
  275. execution.workgroup_size.x = ops[2];
  276. execution.workgroup_size.y = ops[3];
  277. execution.workgroup_size.z = ops[4];
  278. break;
  279. case ExecutionModeOutputVertices:
  280. execution.output_vertices = ops[2];
  281. break;
  282. default:
  283. break;
  284. }
  285. break;
  286. }
  287. case OpName:
  288. {
  289. uint32_t id = ops[0];
  290. ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
  291. break;
  292. }
  293. case OpMemberName:
  294. {
  295. uint32_t id = ops[0];
  296. uint32_t member = ops[1];
  297. ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
  298. break;
  299. }
  300. case OpDecorationGroup:
  301. {
  302. // Noop, this simply means an ID should be a collector of decorations.
  303. // The meta array is already a flat array of decorations which will contain the relevant decorations.
  304. break;
  305. }
  306. case OpGroupDecorate:
  307. {
  308. uint32_t group_id = ops[0];
  309. auto &decorations = ir.meta[group_id].decoration;
  310. auto &flags = decorations.decoration_flags;
  311. // Copies decorations from one ID to another. Only copy decorations which are set in the group,
  312. // i.e., we cannot just copy the meta structure directly.
  313. for (uint32_t i = 1; i < length; i++)
  314. {
  315. uint32_t target = ops[i];
  316. flags.for_each_bit([&](uint32_t bit) {
  317. auto decoration = static_cast<Decoration>(bit);
  318. if (decoration_is_string(decoration))
  319. {
  320. ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
  321. }
  322. else
  323. {
  324. ir.meta[target].decoration_word_offset[decoration] =
  325. ir.meta[group_id].decoration_word_offset[decoration];
  326. ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
  327. }
  328. });
  329. }
  330. break;
  331. }
  332. case OpGroupMemberDecorate:
  333. {
  334. uint32_t group_id = ops[0];
  335. auto &flags = ir.meta[group_id].decoration.decoration_flags;
  336. // Copies decorations from one ID to another. Only copy decorations which are set in the group,
  337. // i.e., we cannot just copy the meta structure directly.
  338. for (uint32_t i = 1; i + 1 < length; i += 2)
  339. {
  340. uint32_t target = ops[i + 0];
  341. uint32_t index = ops[i + 1];
  342. flags.for_each_bit([&](uint32_t bit) {
  343. auto decoration = static_cast<Decoration>(bit);
  344. if (decoration_is_string(decoration))
  345. ir.set_member_decoration_string(target, index, decoration,
  346. ir.get_decoration_string(group_id, decoration));
  347. else
  348. ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
  349. });
  350. }
  351. break;
  352. }
  353. case OpDecorate:
  354. case OpDecorateId:
  355. {
  356. // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
  357. // so merge decorate and decorate-id here.
  358. uint32_t id = ops[0];
  359. auto decoration = static_cast<Decoration>(ops[1]);
  360. if (length >= 3)
  361. {
  362. ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
  363. ir.set_decoration(id, decoration, ops[2]);
  364. }
  365. else
  366. ir.set_decoration(id, decoration);
  367. break;
  368. }
  369. case OpDecorateStringGOOGLE:
  370. {
  371. uint32_t id = ops[0];
  372. auto decoration = static_cast<Decoration>(ops[1]);
  373. ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
  374. break;
  375. }
  376. case OpMemberDecorate:
  377. {
  378. uint32_t id = ops[0];
  379. uint32_t member = ops[1];
  380. auto decoration = static_cast<Decoration>(ops[2]);
  381. if (length >= 4)
  382. ir.set_member_decoration(id, member, decoration, ops[3]);
  383. else
  384. ir.set_member_decoration(id, member, decoration);
  385. break;
  386. }
  387. case OpMemberDecorateStringGOOGLE:
  388. {
  389. uint32_t id = ops[0];
  390. uint32_t member = ops[1];
  391. auto decoration = static_cast<Decoration>(ops[2]);
  392. ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
  393. break;
  394. }
  395. // Build up basic types.
  396. case OpTypeVoid:
  397. {
  398. uint32_t id = ops[0];
  399. auto &type = set<SPIRType>(id);
  400. type.basetype = SPIRType::Void;
  401. break;
  402. }
  403. case OpTypeBool:
  404. {
  405. uint32_t id = ops[0];
  406. auto &type = set<SPIRType>(id);
  407. type.basetype = SPIRType::Boolean;
  408. type.width = 1;
  409. break;
  410. }
  411. case OpTypeFloat:
  412. {
  413. uint32_t id = ops[0];
  414. uint32_t width = ops[1];
  415. auto &type = set<SPIRType>(id);
  416. if (width == 64)
  417. type.basetype = SPIRType::Double;
  418. else if (width == 32)
  419. type.basetype = SPIRType::Float;
  420. else if (width == 16)
  421. type.basetype = SPIRType::Half;
  422. else
  423. SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
  424. type.width = width;
  425. break;
  426. }
  427. case OpTypeInt:
  428. {
  429. uint32_t id = ops[0];
  430. uint32_t width = ops[1];
  431. bool signedness = ops[2] != 0;
  432. auto &type = set<SPIRType>(id);
  433. type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
  434. type.width = width;
  435. break;
  436. }
  437. // Build composite types by "inheriting".
  438. // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
  439. // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
  440. case OpTypeVector:
  441. {
  442. uint32_t id = ops[0];
  443. uint32_t vecsize = ops[2];
  444. auto &base = get<SPIRType>(ops[1]);
  445. auto &vecbase = set<SPIRType>(id);
  446. vecbase = base;
  447. vecbase.vecsize = vecsize;
  448. vecbase.self = id;
  449. vecbase.parent_type = ops[1];
  450. break;
  451. }
  452. case OpTypeMatrix:
  453. {
  454. uint32_t id = ops[0];
  455. uint32_t colcount = ops[2];
  456. auto &base = get<SPIRType>(ops[1]);
  457. auto &matrixbase = set<SPIRType>(id);
  458. matrixbase = base;
  459. matrixbase.columns = colcount;
  460. matrixbase.self = id;
  461. matrixbase.parent_type = ops[1];
  462. break;
  463. }
  464. case OpTypeArray:
  465. {
  466. uint32_t id = ops[0];
  467. auto &arraybase = set<SPIRType>(id);
  468. uint32_t tid = ops[1];
  469. auto &base = get<SPIRType>(tid);
  470. arraybase = base;
  471. arraybase.parent_type = tid;
  472. uint32_t cid = ops[2];
  473. ir.mark_used_as_array_length(cid);
  474. auto *c = maybe_get<SPIRConstant>(cid);
  475. bool literal = c && !c->specialization;
  476. // We're copying type information into Array types, so we'll need a fixup for any physical pointer
  477. // references.
  478. if (base.forward_pointer)
  479. forward_pointer_fixups.push_back({ id, tid });
  480. arraybase.array_size_literal.push_back(literal);
  481. arraybase.array.push_back(literal ? c->scalar() : cid);
  482. // Do NOT set arraybase.self!
  483. break;
  484. }
  485. case OpTypeRuntimeArray:
  486. {
  487. uint32_t id = ops[0];
  488. auto &base = get<SPIRType>(ops[1]);
  489. auto &arraybase = set<SPIRType>(id);
  490. // We're copying type information into Array types, so we'll need a fixup for any physical pointer
  491. // references.
  492. if (base.forward_pointer)
  493. forward_pointer_fixups.push_back({ id, ops[1] });
  494. arraybase = base;
  495. arraybase.array.push_back(0);
  496. arraybase.array_size_literal.push_back(true);
  497. arraybase.parent_type = ops[1];
  498. // Do NOT set arraybase.self!
  499. break;
  500. }
  501. case OpTypeImage:
  502. {
  503. uint32_t id = ops[0];
  504. auto &type = set<SPIRType>(id);
  505. type.basetype = SPIRType::Image;
  506. type.image.type = ops[1];
  507. type.image.dim = static_cast<Dim>(ops[2]);
  508. type.image.depth = ops[3] == 1;
  509. type.image.arrayed = ops[4] != 0;
  510. type.image.ms = ops[5] != 0;
  511. type.image.sampled = ops[6];
  512. type.image.format = static_cast<ImageFormat>(ops[7]);
  513. type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
  514. break;
  515. }
  516. case OpTypeSampledImage:
  517. {
  518. uint32_t id = ops[0];
  519. uint32_t imagetype = ops[1];
  520. auto &type = set<SPIRType>(id);
  521. type = get<SPIRType>(imagetype);
  522. type.basetype = SPIRType::SampledImage;
  523. type.self = id;
  524. break;
  525. }
  526. case OpTypeSampler:
  527. {
  528. uint32_t id = ops[0];
  529. auto &type = set<SPIRType>(id);
  530. type.basetype = SPIRType::Sampler;
  531. break;
  532. }
  533. case OpTypePointer:
  534. {
  535. uint32_t id = ops[0];
  536. // Very rarely, we might receive a FunctionPrototype here.
  537. // We won't be able to compile it, but we shouldn't crash when parsing.
  538. // We should be able to reflect.
  539. auto *base = maybe_get<SPIRType>(ops[2]);
  540. auto &ptrbase = set<SPIRType>(id);
  541. if (base)
  542. ptrbase = *base;
  543. ptrbase.pointer = true;
  544. ptrbase.pointer_depth++;
  545. ptrbase.storage = static_cast<StorageClass>(ops[1]);
  546. if (ptrbase.storage == StorageClassAtomicCounter)
  547. ptrbase.basetype = SPIRType::AtomicCounter;
  548. if (base && base->forward_pointer)
  549. forward_pointer_fixups.push_back({ id, ops[2] });
  550. ptrbase.parent_type = ops[2];
  551. // Do NOT set ptrbase.self!
  552. break;
  553. }
  554. case OpTypeForwardPointer:
  555. {
  556. uint32_t id = ops[0];
  557. auto &ptrbase = set<SPIRType>(id);
  558. ptrbase.pointer = true;
  559. ptrbase.pointer_depth++;
  560. ptrbase.storage = static_cast<StorageClass>(ops[1]);
  561. ptrbase.forward_pointer = true;
  562. if (ptrbase.storage == StorageClassAtomicCounter)
  563. ptrbase.basetype = SPIRType::AtomicCounter;
  564. break;
  565. }
  566. case OpTypeStruct:
  567. {
  568. uint32_t id = ops[0];
  569. auto &type = set<SPIRType>(id);
  570. type.basetype = SPIRType::Struct;
  571. for (uint32_t i = 1; i < length; i++)
  572. type.member_types.push_back(ops[i]);
  573. // Check if we have seen this struct type before, with just different
  574. // decorations.
  575. //
  576. // Add workaround for issue #17 as well by looking at OpName for the struct
  577. // types, which we shouldn't normally do.
  578. // We should not normally have to consider type aliases like this to begin with
  579. // however ... glslang issues #304, #307 cover this.
  580. // For stripped names, never consider struct type aliasing.
  581. // We risk declaring the same struct multiple times, but type-punning is not allowed
  582. // so this is safe.
  583. bool consider_aliasing = !ir.get_name(type.self).empty();
  584. if (consider_aliasing)
  585. {
  586. for (auto &other : global_struct_cache)
  587. {
  588. if (ir.get_name(type.self) == ir.get_name(other) &&
  589. types_are_logically_equivalent(type, get<SPIRType>(other)))
  590. {
  591. type.type_alias = other;
  592. break;
  593. }
  594. }
  595. if (type.type_alias == TypeID(0))
  596. global_struct_cache.push_back(id);
  597. }
  598. break;
  599. }
  600. case OpTypeFunction:
  601. {
  602. uint32_t id = ops[0];
  603. uint32_t ret = ops[1];
  604. auto &func = set<SPIRFunctionPrototype>(id, ret);
  605. for (uint32_t i = 2; i < length; i++)
  606. func.parameter_types.push_back(ops[i]);
  607. break;
  608. }
  609. case OpTypeAccelerationStructureKHR:
  610. {
  611. uint32_t id = ops[0];
  612. auto &type = set<SPIRType>(id);
  613. type.basetype = SPIRType::AccelerationStructure;
  614. break;
  615. }
  616. case OpTypeRayQueryKHR:
  617. {
  618. uint32_t id = ops[0];
  619. auto &type = set<SPIRType>(id);
  620. type.basetype = SPIRType::RayQuery;
  621. break;
  622. }
  623. // Variable declaration
  624. // All variables are essentially pointers with a storage qualifier.
  625. case OpVariable:
  626. {
  627. uint32_t type = ops[0];
  628. uint32_t id = ops[1];
  629. auto storage = static_cast<StorageClass>(ops[2]);
  630. uint32_t initializer = length == 4 ? ops[3] : 0;
  631. if (storage == StorageClassFunction)
  632. {
  633. if (!current_function)
  634. SPIRV_CROSS_THROW("No function currently in scope");
  635. current_function->add_local_variable(id);
  636. }
  637. set<SPIRVariable>(id, type, storage, initializer);
  638. break;
  639. }
  640. // OpPhi
  641. // OpPhi is a fairly magical opcode.
  642. // It selects temporary variables based on which parent block we *came from*.
  643. // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
  644. // variable to emulate SSA Phi.
  645. case OpPhi:
  646. {
  647. if (!current_function)
  648. SPIRV_CROSS_THROW("No function currently in scope");
  649. if (!current_block)
  650. SPIRV_CROSS_THROW("No block currently in scope");
  651. uint32_t result_type = ops[0];
  652. uint32_t id = ops[1];
  653. // Instead of a temporary, create a new function-wide temporary with this ID instead.
  654. auto &var = set<SPIRVariable>(id, result_type, spv::StorageClassFunction);
  655. var.phi_variable = true;
  656. current_function->add_local_variable(id);
  657. for (uint32_t i = 2; i + 2 <= length; i += 2)
  658. current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
  659. break;
  660. }
  661. // Constants
  662. case OpSpecConstant:
  663. case OpConstant:
  664. {
  665. uint32_t id = ops[1];
  666. auto &type = get<SPIRType>(ops[0]);
  667. if (type.width > 32)
  668. set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
  669. else
  670. set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
  671. break;
  672. }
  673. case OpSpecConstantFalse:
  674. case OpConstantFalse:
  675. {
  676. uint32_t id = ops[1];
  677. set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
  678. break;
  679. }
  680. case OpSpecConstantTrue:
  681. case OpConstantTrue:
  682. {
  683. uint32_t id = ops[1];
  684. set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
  685. break;
  686. }
  687. case OpConstantNull:
  688. {
  689. uint32_t id = ops[1];
  690. uint32_t type = ops[0];
  691. ir.make_constant_null(id, type, true);
  692. break;
  693. }
  694. case OpSpecConstantComposite:
  695. case OpConstantComposite:
  696. {
  697. uint32_t id = ops[1];
  698. uint32_t type = ops[0];
  699. auto &ctype = get<SPIRType>(type);
  700. // We can have constants which are structs and arrays.
  701. // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
  702. // can refer to.
  703. if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
  704. {
  705. set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
  706. }
  707. else
  708. {
  709. uint32_t elements = length - 2;
  710. if (elements > 4)
  711. SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
  712. SPIRConstant remapped_constant_ops[4];
  713. const SPIRConstant *c[4];
  714. for (uint32_t i = 0; i < elements; i++)
  715. {
  716. // Specialization constants operations can also be part of this.
  717. // We do not know their value, so any attempt to query SPIRConstant later
  718. // will fail. We can only propagate the ID of the expression and use to_expression on it.
  719. auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
  720. auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
  721. if (constant_op)
  722. {
  723. if (op == OpConstantComposite)
  724. SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
  725. remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
  726. remapped_constant_ops[i].self = constant_op->self;
  727. remapped_constant_ops[i].constant_type = constant_op->basetype;
  728. remapped_constant_ops[i].specialization = true;
  729. c[i] = &remapped_constant_ops[i];
  730. }
  731. else if (undef_op)
  732. {
  733. // Undefined, just pick 0.
  734. remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
  735. remapped_constant_ops[i].constant_type = undef_op->basetype;
  736. c[i] = &remapped_constant_ops[i];
  737. }
  738. else
  739. c[i] = &get<SPIRConstant>(ops[2 + i]);
  740. }
  741. set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
  742. }
  743. break;
  744. }
  745. // Functions
  746. case OpFunction:
  747. {
  748. uint32_t res = ops[0];
  749. uint32_t id = ops[1];
  750. // Control
  751. uint32_t type = ops[3];
  752. if (current_function)
  753. SPIRV_CROSS_THROW("Must end a function before starting a new one!");
  754. current_function = &set<SPIRFunction>(id, res, type);
  755. break;
  756. }
  757. case OpFunctionParameter:
  758. {
  759. uint32_t type = ops[0];
  760. uint32_t id = ops[1];
  761. if (!current_function)
  762. SPIRV_CROSS_THROW("Must be in a function!");
  763. current_function->add_parameter(type, id);
  764. set<SPIRVariable>(id, type, StorageClassFunction);
  765. break;
  766. }
  767. case OpFunctionEnd:
  768. {
  769. if (current_block)
  770. {
  771. // Very specific error message, but seems to come up quite often.
  772. SPIRV_CROSS_THROW(
  773. "Cannot end a function before ending the current block.\n"
  774. "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
  775. }
  776. current_function = nullptr;
  777. break;
  778. }
  779. // Blocks
  780. case OpLabel:
  781. {
  782. // OpLabel always starts a block.
  783. if (!current_function)
  784. SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
  785. uint32_t id = ops[0];
  786. current_function->blocks.push_back(id);
  787. if (!current_function->entry_block)
  788. current_function->entry_block = id;
  789. if (current_block)
  790. SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
  791. current_block = &set<SPIRBlock>(id);
  792. break;
  793. }
  794. // Branch instructions end blocks.
  795. case OpBranch:
  796. {
  797. if (!current_block)
  798. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  799. uint32_t target = ops[0];
  800. current_block->terminator = SPIRBlock::Direct;
  801. current_block->next_block = target;
  802. current_block = nullptr;
  803. break;
  804. }
  805. case OpBranchConditional:
  806. {
  807. if (!current_block)
  808. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  809. current_block->condition = ops[0];
  810. current_block->true_block = ops[1];
  811. current_block->false_block = ops[2];
  812. current_block->terminator = SPIRBlock::Select;
  813. if (current_block->true_block == current_block->false_block)
  814. {
  815. // Bogus conditional, translate to a direct branch.
  816. // Avoids some ugly edge cases later when analyzing CFGs.
  817. // There are some super jank cases where the merge block is different from the true/false,
  818. // and later branches can "break" out of the selection construct this way.
  819. // This is complete nonsense, but CTS hits this case.
  820. // In this scenario, we should see the selection construct as more of a Switch with one default case.
  821. // The problem here is that this breaks any attempt to break out of outer switch statements,
  822. // but it's theoretically solvable if this ever comes up using the ladder breaking system ...
  823. if (current_block->true_block != current_block->next_block &&
  824. current_block->merge == SPIRBlock::MergeSelection)
  825. {
  826. uint32_t ids = ir.increase_bound_by(2);
  827. SPIRType type;
  828. type.basetype = SPIRType::Int;
  829. type.width = 32;
  830. set<SPIRType>(ids, type);
  831. auto &c = set<SPIRConstant>(ids + 1, ids);
  832. current_block->condition = c.self;
  833. current_block->default_block = current_block->true_block;
  834. current_block->terminator = SPIRBlock::MultiSelect;
  835. ir.block_meta[current_block->next_block] &= ~ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
  836. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
  837. }
  838. else
  839. {
  840. ir.block_meta[current_block->next_block] &= ~ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
  841. current_block->next_block = current_block->true_block;
  842. current_block->condition = 0;
  843. current_block->true_block = 0;
  844. current_block->false_block = 0;
  845. current_block->merge_block = 0;
  846. current_block->merge = SPIRBlock::MergeNone;
  847. current_block->terminator = SPIRBlock::Direct;
  848. }
  849. }
  850. current_block = nullptr;
  851. break;
  852. }
  853. case OpSwitch:
  854. {
  855. if (!current_block)
  856. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  857. current_block->terminator = SPIRBlock::MultiSelect;
  858. current_block->condition = ops[0];
  859. current_block->default_block = ops[1];
  860. for (uint32_t i = 2; i + 2 <= length; i += 2)
  861. current_block->cases.push_back({ ops[i], ops[i + 1] });
  862. // If we jump to next block, make it break instead since we're inside a switch case block at that point.
  863. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
  864. current_block = nullptr;
  865. break;
  866. }
  867. case OpKill:
  868. {
  869. if (!current_block)
  870. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  871. current_block->terminator = SPIRBlock::Kill;
  872. current_block = nullptr;
  873. break;
  874. }
  875. case OpTerminateRayKHR:
  876. // NV variant is not a terminator.
  877. if (!current_block)
  878. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  879. current_block->terminator = SPIRBlock::TerminateRay;
  880. current_block = nullptr;
  881. break;
  882. case OpIgnoreIntersectionKHR:
  883. // NV variant is not a terminator.
  884. if (!current_block)
  885. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  886. current_block->terminator = SPIRBlock::IgnoreIntersection;
  887. current_block = nullptr;
  888. break;
  889. case OpReturn:
  890. {
  891. if (!current_block)
  892. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  893. current_block->terminator = SPIRBlock::Return;
  894. current_block = nullptr;
  895. break;
  896. }
  897. case OpReturnValue:
  898. {
  899. if (!current_block)
  900. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  901. current_block->terminator = SPIRBlock::Return;
  902. current_block->return_value = ops[0];
  903. current_block = nullptr;
  904. break;
  905. }
  906. case OpUnreachable:
  907. {
  908. if (!current_block)
  909. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  910. current_block->terminator = SPIRBlock::Unreachable;
  911. current_block = nullptr;
  912. break;
  913. }
  914. case OpSelectionMerge:
  915. {
  916. if (!current_block)
  917. SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
  918. current_block->next_block = ops[0];
  919. current_block->merge = SPIRBlock::MergeSelection;
  920. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
  921. if (length >= 2)
  922. {
  923. if (ops[1] & SelectionControlFlattenMask)
  924. current_block->hint = SPIRBlock::HintFlatten;
  925. else if (ops[1] & SelectionControlDontFlattenMask)
  926. current_block->hint = SPIRBlock::HintDontFlatten;
  927. }
  928. break;
  929. }
  930. case OpLoopMerge:
  931. {
  932. if (!current_block)
  933. SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
  934. current_block->merge_block = ops[0];
  935. current_block->continue_block = ops[1];
  936. current_block->merge = SPIRBlock::MergeLoop;
  937. ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
  938. ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
  939. ir.continue_block_to_loop_header[current_block->continue_block] = BlockID(current_block->self);
  940. // Don't add loop headers to continue blocks,
  941. // which would make it impossible branch into the loop header since
  942. // they are treated as continues.
  943. if (current_block->continue_block != BlockID(current_block->self))
  944. ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
  945. if (length >= 3)
  946. {
  947. if (ops[2] & LoopControlUnrollMask)
  948. current_block->hint = SPIRBlock::HintUnroll;
  949. else if (ops[2] & LoopControlDontUnrollMask)
  950. current_block->hint = SPIRBlock::HintDontUnroll;
  951. }
  952. break;
  953. }
  954. case OpSpecConstantOp:
  955. {
  956. if (length < 3)
  957. SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
  958. uint32_t result_type = ops[0];
  959. uint32_t id = ops[1];
  960. auto spec_op = static_cast<Op>(ops[2]);
  961. set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
  962. break;
  963. }
  964. case OpLine:
  965. {
  966. // OpLine might come at global scope, but we don't care about those since they will not be declared in any
  967. // meaningful correct order.
  968. // Ignore all OpLine directives which live outside a function.
  969. if (current_block)
  970. current_block->ops.push_back(instruction);
  971. // Line directives may arrive before first OpLabel.
  972. // Treat this as the line of the function declaration,
  973. // so warnings for arguments can propagate properly.
  974. if (current_function)
  975. {
  976. // Store the first one we find and emit it before creating the function prototype.
  977. if (current_function->entry_line.file_id == 0)
  978. {
  979. current_function->entry_line.file_id = ops[0];
  980. current_function->entry_line.line_literal = ops[1];
  981. }
  982. }
  983. break;
  984. }
  985. case OpNoLine:
  986. {
  987. // OpNoLine might come at global scope.
  988. if (current_block)
  989. current_block->ops.push_back(instruction);
  990. break;
  991. }
  992. // Actual opcodes.
  993. default:
  994. {
  995. if (!current_block)
  996. SPIRV_CROSS_THROW("Currently no block to insert opcode.");
  997. current_block->ops.push_back(instruction);
  998. break;
  999. }
  1000. }
  1001. }
  1002. bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
  1003. {
  1004. if (a.basetype != b.basetype)
  1005. return false;
  1006. if (a.width != b.width)
  1007. return false;
  1008. if (a.vecsize != b.vecsize)
  1009. return false;
  1010. if (a.columns != b.columns)
  1011. return false;
  1012. if (a.array.size() != b.array.size())
  1013. return false;
  1014. size_t array_count = a.array.size();
  1015. if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
  1016. return false;
  1017. if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
  1018. {
  1019. if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
  1020. return false;
  1021. }
  1022. if (a.member_types.size() != b.member_types.size())
  1023. return false;
  1024. size_t member_types = a.member_types.size();
  1025. for (size_t i = 0; i < member_types; i++)
  1026. {
  1027. if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
  1028. return false;
  1029. }
  1030. return true;
  1031. }
  1032. bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
  1033. {
  1034. auto &type = get<SPIRType>(v.basetype);
  1035. auto *type_meta = ir.find_meta(type.self);
  1036. bool ssbo = v.storage == StorageClassStorageBuffer ||
  1037. (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
  1038. bool image = type.basetype == SPIRType::Image;
  1039. bool counter = type.basetype == SPIRType::AtomicCounter;
  1040. bool is_restrict;
  1041. if (ssbo)
  1042. is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
  1043. else
  1044. is_restrict = ir.has_decoration(v.self, DecorationRestrict);
  1045. return !is_restrict && (ssbo || image || counter);
  1046. }
  1047. } // namespace SPIRV_CROSS_NAMESPACE