2
0

spirv_parser.cpp 30 KB

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