2
0

spirv_parser.cpp 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561
  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 "NonSemanticShaderDebugInfo100.h"
  24. #include <assert.h>
  25. using namespace std;
  26. using namespace SPIRV_CROSS_SPV_HEADER_NAMESPACE;
  27. namespace SPIRV_CROSS_NAMESPACE
  28. {
  29. Parser::Parser(vector<uint32_t> spirv)
  30. {
  31. ir.spirv = std::move(spirv);
  32. }
  33. Parser::Parser(const uint32_t *spirv_data, size_t word_count)
  34. {
  35. ir.spirv = vector<uint32_t>(spirv_data, spirv_data + word_count);
  36. }
  37. static bool decoration_is_string(Decoration decoration)
  38. {
  39. switch (decoration)
  40. {
  41. case DecorationUserSemantic:
  42. return true;
  43. default:
  44. return false;
  45. }
  46. }
  47. static inline uint32_t swap_endian(uint32_t v)
  48. {
  49. return ((v >> 24) & 0x000000ffu) | ((v >> 8) & 0x0000ff00u) | ((v << 8) & 0x00ff0000u) | ((v << 24) & 0xff000000u);
  50. }
  51. static bool is_valid_spirv_version(uint32_t version)
  52. {
  53. switch (version)
  54. {
  55. // Allow v99 since it tends to just work.
  56. case 99:
  57. case 0x10000: // SPIR-V 1.0
  58. case 0x10100: // SPIR-V 1.1
  59. case 0x10200: // SPIR-V 1.2
  60. case 0x10300: // SPIR-V 1.3
  61. case 0x10400: // SPIR-V 1.4
  62. case 0x10500: // SPIR-V 1.5
  63. case 0x10600: // SPIR-V 1.6
  64. return true;
  65. default:
  66. return false;
  67. }
  68. }
  69. void Parser::parse()
  70. {
  71. auto &spirv = ir.spirv;
  72. auto len = spirv.size();
  73. if (len < 5)
  74. SPIRV_CROSS_THROW("SPIRV file too small.");
  75. auto s = spirv.data();
  76. // Endian-swap if we need to.
  77. if (s[0] == swap_endian(MagicNumber))
  78. transform(begin(spirv), end(spirv), begin(spirv), [](uint32_t c) { return swap_endian(c); });
  79. if (s[0] != MagicNumber || !is_valid_spirv_version(s[1]))
  80. SPIRV_CROSS_THROW("Invalid SPIRV format.");
  81. uint32_t bound = s[3];
  82. const uint32_t MaximumNumberOfIDs = 0x3fffff;
  83. if (bound > MaximumNumberOfIDs)
  84. SPIRV_CROSS_THROW("ID bound exceeds limit of 0x3fffff.\n");
  85. ir.set_id_bounds(bound);
  86. uint32_t offset = 5;
  87. SmallVector<Instruction> instructions;
  88. while (offset < len)
  89. {
  90. Instruction instr = {};
  91. instr.op = spirv[offset] & 0xffff;
  92. instr.count = (spirv[offset] >> 16) & 0xffff;
  93. if (instr.count == 0)
  94. SPIRV_CROSS_THROW("SPIR-V instructions cannot consume 0 words. Invalid SPIR-V file.");
  95. instr.offset = offset + 1;
  96. instr.length = instr.count - 1;
  97. offset += instr.count;
  98. if (offset > spirv.size())
  99. SPIRV_CROSS_THROW("SPIR-V instruction goes out of bounds.");
  100. instructions.push_back(instr);
  101. }
  102. for (auto &i : instructions)
  103. parse(i);
  104. for (auto &fixup : forward_pointer_fixups)
  105. {
  106. auto &target = get<SPIRType>(fixup.first);
  107. auto &source = get<SPIRType>(fixup.second);
  108. target.member_types = source.member_types;
  109. target.basetype = source.basetype;
  110. target.self = source.self;
  111. }
  112. forward_pointer_fixups.clear();
  113. for (auto &source : ir.sources)
  114. {
  115. auto cmp = [](const ParsedIR::Source::Marker &a, const ParsedIR::Source::Marker &b) {
  116. return a.line < b.line;
  117. };
  118. std::sort(source.line_markers.begin(), source.line_markers.end(), cmp);
  119. }
  120. if (current_function)
  121. SPIRV_CROSS_THROW("Function was not terminated.");
  122. if (current_block)
  123. SPIRV_CROSS_THROW("Block was not terminated.");
  124. if (ir.default_entry_point == 0)
  125. SPIRV_CROSS_THROW("There is no entry point in the SPIR-V module.");
  126. }
  127. const uint32_t *Parser::stream(const Instruction &instr) const
  128. {
  129. // If we're not going to use any arguments, just return nullptr.
  130. // We want to avoid case where we return an out of range pointer
  131. // that trips debug assertions on some platforms.
  132. if (!instr.length)
  133. return nullptr;
  134. if (instr.offset + instr.length > ir.spirv.size())
  135. SPIRV_CROSS_THROW("Compiler::stream() out of range.");
  136. return &ir.spirv[instr.offset];
  137. }
  138. static string extract_string(const vector<uint32_t> &spirv, uint32_t offset)
  139. {
  140. string ret;
  141. for (uint32_t i = offset; i < spirv.size(); i++)
  142. {
  143. uint32_t w = spirv[i];
  144. for (uint32_t j = 0; j < 4; j++, w >>= 8)
  145. {
  146. char c = w & 0xff;
  147. if (c == '\0')
  148. return ret;
  149. ret += c;
  150. }
  151. }
  152. SPIRV_CROSS_THROW("String was not terminated before EOF");
  153. }
  154. void Parser::parse(const Instruction &instruction)
  155. {
  156. auto *ops = stream(instruction);
  157. auto op = static_cast<Op>(instruction.op);
  158. uint32_t length = instruction.length;
  159. // HACK for glslang that might emit OpEmitMeshTasksEXT followed by return / branch.
  160. // Instead of failing hard, just ignore it.
  161. if (ignore_trailing_block_opcodes)
  162. {
  163. ignore_trailing_block_opcodes = false;
  164. if (op == OpReturn || op == OpBranch || op == OpUnreachable)
  165. return;
  166. }
  167. switch (op)
  168. {
  169. case OpSourceExtension:
  170. case OpNop:
  171. case OpModuleProcessed:
  172. break;
  173. case OpString:
  174. {
  175. set<SPIRString>(ops[0], extract_string(ir.spirv, instruction.offset + 1));
  176. break;
  177. }
  178. case OpMemoryModel:
  179. ir.addressing_model = static_cast<AddressingModel>(ops[0]);
  180. ir.memory_model = static_cast<MemoryModel>(ops[1]);
  181. break;
  182. case OpSource:
  183. {
  184. ir.sources.emplace_back();
  185. auto &source = ir.sources.back();
  186. source.lang = static_cast<SourceLanguage>(ops[0]);
  187. switch (source.lang)
  188. {
  189. case SourceLanguageESSL:
  190. source.es = true;
  191. source.version = ops[1];
  192. source.known = true;
  193. source.hlsl = false;
  194. break;
  195. case SourceLanguageGLSL:
  196. source.es = false;
  197. source.version = ops[1];
  198. source.known = true;
  199. source.hlsl = false;
  200. break;
  201. case SourceLanguageHLSL:
  202. // For purposes of cross-compiling, this is GLSL 450.
  203. source.es = false;
  204. source.version = 450;
  205. source.known = true;
  206. source.hlsl = true;
  207. break;
  208. default:
  209. source.known = false;
  210. break;
  211. }
  212. if (length >= 3)
  213. source.file_id = ops[2];
  214. if (length >= 4)
  215. source.source = extract_string(ir.spirv, instruction.offset + 3);
  216. break;
  217. }
  218. case OpSourceContinued:
  219. if (!ir.sources.empty())
  220. ir.sources.back().source += extract_string(ir.spirv, instruction.offset);
  221. break;
  222. case OpUndef:
  223. {
  224. uint32_t result_type = ops[0];
  225. uint32_t id = ops[1];
  226. set<SPIRUndef>(id, result_type);
  227. if (current_block)
  228. current_block->ops.push_back(instruction);
  229. break;
  230. }
  231. case OpCapability:
  232. {
  233. uint32_t cap = ops[0];
  234. if (cap == CapabilityKernel)
  235. SPIRV_CROSS_THROW("Kernel capability not supported.");
  236. ir.declared_capabilities.push_back(static_cast<Capability>(ops[0]));
  237. break;
  238. }
  239. case OpExtension:
  240. {
  241. auto ext = extract_string(ir.spirv, instruction.offset);
  242. ir.declared_extensions.push_back(std::move(ext));
  243. break;
  244. }
  245. case OpExtInstImport:
  246. {
  247. uint32_t id = ops[0];
  248. SPIRExtension::Extension spirv_ext = SPIRExtension::Unsupported;
  249. auto ext = extract_string(ir.spirv, instruction.offset + 1);
  250. if (ext == "GLSL.std.450")
  251. spirv_ext = SPIRExtension::GLSL;
  252. else if (ext == "DebugInfo")
  253. spirv_ext = SPIRExtension::SPV_debug_info;
  254. else if (ext == "SPV_AMD_shader_ballot")
  255. spirv_ext = SPIRExtension::SPV_AMD_shader_ballot;
  256. else if (ext == "SPV_AMD_shader_explicit_vertex_parameter")
  257. spirv_ext = SPIRExtension::SPV_AMD_shader_explicit_vertex_parameter;
  258. else if (ext == "SPV_AMD_shader_trinary_minmax")
  259. spirv_ext = SPIRExtension::SPV_AMD_shader_trinary_minmax;
  260. else if (ext == "SPV_AMD_gcn_shader")
  261. spirv_ext = SPIRExtension::SPV_AMD_gcn_shader;
  262. else if (ext == "NonSemantic.DebugPrintf")
  263. spirv_ext = SPIRExtension::NonSemanticDebugPrintf;
  264. else if (ext == "NonSemantic.Shader.DebugInfo.100")
  265. spirv_ext = SPIRExtension::NonSemanticShaderDebugInfo;
  266. else if (ext.find("NonSemantic.") == 0)
  267. spirv_ext = SPIRExtension::NonSemanticGeneric;
  268. set<SPIRExtension>(id, spirv_ext);
  269. // Other SPIR-V extensions which have ExtInstrs are currently not supported.
  270. break;
  271. }
  272. case OpExtInst:
  273. case OpExtInstWithForwardRefsKHR:
  274. {
  275. // The SPIR-V debug information extended instructions might come at global scope.
  276. if (current_block)
  277. {
  278. current_block->ops.push_back(instruction);
  279. if (length >= 2)
  280. {
  281. const auto *type = maybe_get<SPIRType>(ops[0]);
  282. if (type)
  283. ir.load_type_width.insert({ ops[1], type->width });
  284. }
  285. }
  286. if (op == OpExtInst && length > 4)
  287. {
  288. // Don't want to deal with ForwardRefs here.
  289. auto &ext = get<SPIRExtension>(ops[2]);
  290. if (ext.ext == SPIRExtension::NonSemanticShaderDebugInfo)
  291. {
  292. const auto instr = ops[3];
  293. if (instr == NonSemanticShaderDebugInfo100DebugSource)
  294. {
  295. set<SPIRString>(ops[1], get<SPIRString>(ops[4]).str);
  296. ir.sources.emplace_back();
  297. auto &source = ir.sources.back();
  298. source.file_id = ops[4];
  299. source.define_id = ops[1];
  300. if (length >= 6)
  301. source.source = ir.get<SPIRString>(ops[5]).str;
  302. }
  303. else if (instr == NonSemanticShaderDebugInfo100DebugSourceContinued)
  304. {
  305. if (length < 5)
  306. SPIRV_CROSS_THROW("Invalid arguments for ShaderDebugInfo100DebugSourceContinued");
  307. if (!ir.sources.empty())
  308. ir.sources.back().source += ir.get<SPIRString>(ops[4]).str;
  309. }
  310. else if (instr == NonSemanticShaderDebugInfo100DebugLine)
  311. {
  312. if (length < 9)
  313. SPIRV_CROSS_THROW("Invalid arguments for ShaderDebugInfo100DebugLine");
  314. auto source_id = ops[4];
  315. auto line_start = ir.get<SPIRConstant>(ops[5]).scalar_i32();
  316. auto col_start = ir.get<SPIRConstant>(ops[7]).scalar_i32();
  317. for (auto &source : ir.sources)
  318. {
  319. if (source.define_id != source_id)
  320. continue;
  321. source.line_markers.emplace_back();
  322. auto &marker = source.line_markers.back();
  323. marker.line = line_start;
  324. marker.col = col_start;
  325. marker.offset = instruction.offset - 1;
  326. marker.function_id = current_function ? current_function->self : ID(0);
  327. marker.block_id = current_block ? current_block->self : ID(0);
  328. break;
  329. }
  330. }
  331. else if (instr == NonSemanticShaderDebugInfo100DebugLocalVariable)
  332. {
  333. if (length < 11)
  334. SPIRV_CROSS_THROW("Invalid arguments for ShaderDebugInfo100DebugLocalVariable");
  335. auto &lvar = set<SPIRDebugLocalVariable>(ops[1]);
  336. lvar.name_id = ops[4];
  337. }
  338. else if (instr == NonSemanticShaderDebugInfo100DebugDeclare)
  339. {
  340. if (length < 7)
  341. SPIRV_CROSS_THROW("Invalid arguments for ShaderDebugInfo100DebugDeclare");
  342. auto &lvar = get<SPIRDebugLocalVariable>(ops[4]);
  343. auto &var = get<SPIRVariable>(ops[5]);
  344. var.debug_local_variables.push_back(lvar.self);
  345. }
  346. }
  347. }
  348. break;
  349. }
  350. case OpEntryPoint:
  351. {
  352. auto itr =
  353. ir.entry_points.insert(make_pair(ops[1], SPIREntryPoint(ops[1], static_cast<ExecutionModel>(ops[0]),
  354. extract_string(ir.spirv, instruction.offset + 2))));
  355. auto &e = itr.first->second;
  356. // Strings need nul-terminator and consume the whole word.
  357. uint32_t strlen_words = uint32_t((e.name.size() + 1 + 3) >> 2);
  358. for (uint32_t i = strlen_words + 2; i < instruction.length; i++)
  359. e.interface_variables.push_back(ops[i]);
  360. // Set the name of the entry point in case OpName is not provided later.
  361. ir.set_name(ops[1], e.name);
  362. // If we don't have an entry, make the first one our "default".
  363. if (!ir.default_entry_point)
  364. ir.default_entry_point = ops[1];
  365. break;
  366. }
  367. case OpExecutionMode:
  368. {
  369. auto &execution = ir.entry_points[ops[0]];
  370. auto mode = static_cast<ExecutionMode>(ops[1]);
  371. execution.flags.set(mode);
  372. switch (mode)
  373. {
  374. case ExecutionModeInvocations:
  375. execution.invocations = ops[2];
  376. break;
  377. case ExecutionModeLocalSize:
  378. execution.workgroup_size.x = ops[2];
  379. execution.workgroup_size.y = ops[3];
  380. execution.workgroup_size.z = ops[4];
  381. break;
  382. case ExecutionModeOutputVertices:
  383. execution.output_vertices = ops[2];
  384. break;
  385. case ExecutionModeOutputPrimitivesEXT:
  386. execution.output_primitives = ops[2];
  387. break;
  388. case ExecutionModeSignedZeroInfNanPreserve:
  389. switch (ops[2])
  390. {
  391. case 8:
  392. execution.signed_zero_inf_nan_preserve_8 = true;
  393. break;
  394. case 16:
  395. execution.signed_zero_inf_nan_preserve_16 = true;
  396. break;
  397. case 32:
  398. execution.signed_zero_inf_nan_preserve_32 = true;
  399. break;
  400. case 64:
  401. execution.signed_zero_inf_nan_preserve_64 = true;
  402. break;
  403. default:
  404. SPIRV_CROSS_THROW("Invalid bit-width for SignedZeroInfNanPreserve.");
  405. }
  406. break;
  407. default:
  408. break;
  409. }
  410. break;
  411. }
  412. case OpExecutionModeId:
  413. {
  414. auto &execution = ir.entry_points[ops[0]];
  415. auto mode = static_cast<ExecutionMode>(ops[1]);
  416. execution.flags.set(mode);
  417. switch (mode)
  418. {
  419. case ExecutionModeLocalSizeId:
  420. execution.workgroup_size.id_x = ops[2];
  421. execution.workgroup_size.id_y = ops[3];
  422. execution.workgroup_size.id_z = ops[4];
  423. break;
  424. case ExecutionModeFPFastMathDefault:
  425. execution.fp_fast_math_defaults[ops[2]] = ops[3];
  426. break;
  427. default:
  428. break;
  429. }
  430. break;
  431. }
  432. case OpName:
  433. {
  434. uint32_t id = ops[0];
  435. ir.set_name(id, extract_string(ir.spirv, instruction.offset + 1));
  436. break;
  437. }
  438. case OpMemberName:
  439. {
  440. uint32_t id = ops[0];
  441. uint32_t member = ops[1];
  442. ir.set_member_name(id, member, extract_string(ir.spirv, instruction.offset + 2));
  443. break;
  444. }
  445. case OpDecorationGroup:
  446. {
  447. // Noop, this simply means an ID should be a collector of decorations.
  448. // The meta array is already a flat array of decorations which will contain the relevant decorations.
  449. break;
  450. }
  451. case OpGroupDecorate:
  452. {
  453. uint32_t group_id = ops[0];
  454. auto &decorations = ir.meta[group_id].decoration;
  455. auto &flags = decorations.decoration_flags;
  456. // Copies decorations from one ID to another. Only copy decorations which are set in the group,
  457. // i.e., we cannot just copy the meta structure directly.
  458. for (uint32_t i = 1; i < length; i++)
  459. {
  460. uint32_t target = ops[i];
  461. flags.for_each_bit([&](uint32_t bit) {
  462. auto decoration = static_cast<Decoration>(bit);
  463. if (decoration_is_string(decoration))
  464. {
  465. ir.set_decoration_string(target, decoration, ir.get_decoration_string(group_id, decoration));
  466. }
  467. else
  468. {
  469. ir.meta[target].decoration_word_offset[decoration] =
  470. ir.meta[group_id].decoration_word_offset[decoration];
  471. ir.set_decoration(target, decoration, ir.get_decoration(group_id, decoration));
  472. }
  473. });
  474. }
  475. break;
  476. }
  477. case OpGroupMemberDecorate:
  478. {
  479. uint32_t group_id = ops[0];
  480. auto &flags = ir.meta[group_id].decoration.decoration_flags;
  481. // Copies decorations from one ID to another. Only copy decorations which are set in the group,
  482. // i.e., we cannot just copy the meta structure directly.
  483. for (uint32_t i = 1; i + 1 < length; i += 2)
  484. {
  485. uint32_t target = ops[i + 0];
  486. uint32_t index = ops[i + 1];
  487. flags.for_each_bit([&](uint32_t bit) {
  488. auto decoration = static_cast<Decoration>(bit);
  489. if (decoration_is_string(decoration))
  490. ir.set_member_decoration_string(target, index, decoration,
  491. ir.get_decoration_string(group_id, decoration));
  492. else
  493. ir.set_member_decoration(target, index, decoration, ir.get_decoration(group_id, decoration));
  494. });
  495. }
  496. break;
  497. }
  498. case OpDecorate:
  499. case OpDecorateId:
  500. {
  501. // OpDecorateId technically supports an array of arguments, but our only supported decorations are single uint,
  502. // so merge decorate and decorate-id here.
  503. uint32_t id = ops[0];
  504. auto decoration = static_cast<Decoration>(ops[1]);
  505. if (length >= 3)
  506. {
  507. ir.meta[id].decoration_word_offset[decoration] = uint32_t(&ops[2] - ir.spirv.data());
  508. ir.set_decoration(id, decoration, ops[2]);
  509. }
  510. else
  511. ir.set_decoration(id, decoration);
  512. break;
  513. }
  514. case OpDecorateStringGOOGLE:
  515. {
  516. uint32_t id = ops[0];
  517. auto decoration = static_cast<Decoration>(ops[1]);
  518. ir.set_decoration_string(id, decoration, extract_string(ir.spirv, instruction.offset + 2));
  519. break;
  520. }
  521. case OpMemberDecorate:
  522. {
  523. uint32_t id = ops[0];
  524. uint32_t member = ops[1];
  525. auto decoration = static_cast<Decoration>(ops[2]);
  526. if (length >= 4)
  527. ir.set_member_decoration(id, member, decoration, ops[3]);
  528. else
  529. ir.set_member_decoration(id, member, decoration);
  530. break;
  531. }
  532. case OpMemberDecorateStringGOOGLE:
  533. {
  534. uint32_t id = ops[0];
  535. uint32_t member = ops[1];
  536. auto decoration = static_cast<Decoration>(ops[2]);
  537. ir.set_member_decoration_string(id, member, decoration, extract_string(ir.spirv, instruction.offset + 3));
  538. break;
  539. }
  540. // Build up basic types.
  541. case OpTypeVoid:
  542. {
  543. uint32_t id = ops[0];
  544. auto &type = set<SPIRType>(id, op);
  545. type.basetype = SPIRType::Void;
  546. break;
  547. }
  548. case OpTypeBool:
  549. {
  550. uint32_t id = ops[0];
  551. auto &type = set<SPIRType>(id, op);
  552. type.basetype = SPIRType::Boolean;
  553. type.width = 1;
  554. break;
  555. }
  556. case OpTypeFloat:
  557. {
  558. uint32_t id = ops[0];
  559. uint32_t width = ops[1];
  560. auto &type = set<SPIRType>(id, op);
  561. if (width != 16 && width != 8 && length > 2)
  562. SPIRV_CROSS_THROW("Unrecognized FP encoding mode for OpTypeFloat.");
  563. if (width == 64)
  564. type.basetype = SPIRType::Double;
  565. else if (width == 32)
  566. type.basetype = SPIRType::Float;
  567. else if (width == 16)
  568. {
  569. if (length > 2)
  570. {
  571. if (ops[2] == FPEncodingBFloat16KHR)
  572. type.basetype = SPIRType::BFloat16;
  573. else
  574. SPIRV_CROSS_THROW("Unrecognized encoding for OpTypeFloat 16.");
  575. }
  576. else
  577. type.basetype = SPIRType::Half;
  578. }
  579. else if (width == 8)
  580. {
  581. if (length < 2)
  582. SPIRV_CROSS_THROW("Missing encoding for OpTypeFloat 8.");
  583. else if (ops[2] == FPEncodingFloat8E4M3EXT)
  584. type.basetype = SPIRType::FloatE4M3;
  585. else if (ops[2] == FPEncodingFloat8E5M2EXT)
  586. type.basetype = SPIRType::FloatE5M2;
  587. else
  588. SPIRV_CROSS_THROW("Invalid encoding for OpTypeFloat 8.");
  589. }
  590. else
  591. SPIRV_CROSS_THROW("Unrecognized bit-width of floating point type.");
  592. type.width = width;
  593. break;
  594. }
  595. case OpTypeInt:
  596. {
  597. uint32_t id = ops[0];
  598. uint32_t width = ops[1];
  599. bool signedness = ops[2] != 0;
  600. auto &type = set<SPIRType>(id, op);
  601. type.basetype = signedness ? to_signed_basetype(width) : to_unsigned_basetype(width);
  602. type.width = width;
  603. break;
  604. }
  605. // Build composite types by "inheriting".
  606. // NOTE: The self member is also copied! For pointers and array modifiers this is a good thing
  607. // since we can refer to decorations on pointee classes which is needed for UBO/SSBO, I/O blocks in geometry/tess etc.
  608. case OpTypeVector:
  609. {
  610. uint32_t id = ops[0];
  611. uint32_t vecsize = ops[2];
  612. auto &base = get<SPIRType>(ops[1]);
  613. auto &vecbase = set<SPIRType>(id, base);
  614. vecbase.op = op;
  615. vecbase.vecsize = vecsize;
  616. vecbase.self = id;
  617. vecbase.parent_type = ops[1];
  618. break;
  619. }
  620. case OpTypeMatrix:
  621. {
  622. uint32_t id = ops[0];
  623. uint32_t colcount = ops[2];
  624. auto &base = get<SPIRType>(ops[1]);
  625. auto &matrixbase = set<SPIRType>(id, base);
  626. matrixbase.op = op;
  627. matrixbase.columns = colcount;
  628. matrixbase.self = id;
  629. matrixbase.parent_type = ops[1];
  630. break;
  631. }
  632. case OpTypeCooperativeMatrixKHR:
  633. {
  634. uint32_t id = ops[0];
  635. auto &base = get<SPIRType>(ops[1]);
  636. auto &matrixbase = set<SPIRType>(id, base);
  637. matrixbase.op = op;
  638. matrixbase.ext.cooperative.scope_id = ops[2];
  639. matrixbase.ext.cooperative.rows_id = ops[3];
  640. matrixbase.ext.cooperative.columns_id = ops[4];
  641. matrixbase.ext.cooperative.use_id = ops[5];
  642. matrixbase.self = id;
  643. matrixbase.parent_type = ops[1];
  644. break;
  645. }
  646. case OpTypeCooperativeVectorNV:
  647. {
  648. uint32_t id = ops[0];
  649. auto &type = set<SPIRType>(id, op);
  650. type.basetype = SPIRType::CoopVecNV;
  651. type.op = op;
  652. type.ext.coopVecNV.component_type_id = ops[1];
  653. type.ext.coopVecNV.component_count_id = ops[2];
  654. type.parent_type = ops[1];
  655. // CoopVec-Nv can be used with integer operations like SMax where
  656. // where spirv-opt does explicit checks on integer bitwidth
  657. auto component_type = get<SPIRType>(type.ext.coopVecNV.component_type_id);
  658. type.width = component_type.width;
  659. break;
  660. }
  661. case OpTypeArray:
  662. {
  663. uint32_t id = ops[0];
  664. uint32_t tid = ops[1];
  665. auto &base = get<SPIRType>(tid);
  666. auto &arraybase = set<SPIRType>(id, base);
  667. arraybase.op = op;
  668. arraybase.parent_type = tid;
  669. uint32_t cid = ops[2];
  670. ir.mark_used_as_array_length(cid);
  671. auto *c = maybe_get<SPIRConstant>(cid);
  672. bool literal = c && !c->specialization;
  673. // We're copying type information into Array types, so we'll need a fixup for any physical pointer
  674. // references.
  675. if (base.forward_pointer)
  676. forward_pointer_fixups.push_back({ id, tid });
  677. arraybase.array_size_literal.push_back(literal);
  678. arraybase.array.push_back(literal ? c->scalar() : cid);
  679. // .self resolves down to non-array/non-pointer type.
  680. arraybase.self = base.self;
  681. break;
  682. }
  683. case OpTypeRuntimeArray:
  684. {
  685. uint32_t id = ops[0];
  686. auto &base = get<SPIRType>(ops[1]);
  687. auto &arraybase = set<SPIRType>(id, base);
  688. // We're copying type information into Array types, so we'll need a fixup for any physical pointer
  689. // references.
  690. if (base.forward_pointer)
  691. forward_pointer_fixups.push_back({ id, ops[1] });
  692. arraybase.op = op;
  693. arraybase.array.push_back(0);
  694. arraybase.array_size_literal.push_back(true);
  695. arraybase.parent_type = ops[1];
  696. // .self resolves down to non-array/non-pointer type.
  697. arraybase.self = base.self;
  698. break;
  699. }
  700. case OpTypeImage:
  701. {
  702. uint32_t id = ops[0];
  703. auto &type = set<SPIRType>(id, op);
  704. type.basetype = SPIRType::Image;
  705. type.image.type = ops[1];
  706. type.image.dim = static_cast<Dim>(ops[2]);
  707. type.image.depth = ops[3] == 1;
  708. type.image.arrayed = ops[4] != 0;
  709. type.image.ms = ops[5] != 0;
  710. type.image.sampled = ops[6];
  711. type.image.format = static_cast<ImageFormat>(ops[7]);
  712. type.image.access = (length >= 9) ? static_cast<AccessQualifier>(ops[8]) : AccessQualifierMax;
  713. break;
  714. }
  715. case OpTypeSampledImage:
  716. {
  717. uint32_t id = ops[0];
  718. uint32_t imagetype = ops[1];
  719. auto &type = set<SPIRType>(id, op);
  720. type = get<SPIRType>(imagetype);
  721. type.basetype = SPIRType::SampledImage;
  722. type.self = id;
  723. break;
  724. }
  725. case OpTypeSampler:
  726. {
  727. uint32_t id = ops[0];
  728. auto &type = set<SPIRType>(id, op);
  729. type.basetype = SPIRType::Sampler;
  730. break;
  731. }
  732. case OpTypePointer:
  733. {
  734. uint32_t id = ops[0];
  735. // Very rarely, we might receive a FunctionPrototype here.
  736. // We won't be able to compile it, but we shouldn't crash when parsing.
  737. // We should be able to reflect.
  738. auto *base = maybe_get<SPIRType>(ops[2]);
  739. auto &ptrbase = set<SPIRType>(id, op);
  740. if (base)
  741. {
  742. ptrbase = *base;
  743. ptrbase.op = op;
  744. }
  745. ptrbase.pointer = true;
  746. ptrbase.pointer_depth++;
  747. ptrbase.storage = static_cast<StorageClass>(ops[1]);
  748. if (ptrbase.storage == StorageClassAtomicCounter)
  749. ptrbase.basetype = SPIRType::AtomicCounter;
  750. if (base && base->forward_pointer)
  751. forward_pointer_fixups.push_back({ id, ops[2] });
  752. ptrbase.parent_type = ops[2];
  753. // Do NOT set ptrbase.self!
  754. break;
  755. }
  756. case OpTypeForwardPointer:
  757. {
  758. uint32_t id = ops[0];
  759. auto &ptrbase = set<SPIRType>(id, op);
  760. ptrbase.pointer = true;
  761. ptrbase.pointer_depth++;
  762. ptrbase.storage = static_cast<StorageClass>(ops[1]);
  763. ptrbase.forward_pointer = true;
  764. if (ptrbase.storage == StorageClassAtomicCounter)
  765. ptrbase.basetype = SPIRType::AtomicCounter;
  766. break;
  767. }
  768. case OpTypeStruct:
  769. {
  770. uint32_t id = ops[0];
  771. auto &type = set<SPIRType>(id, op);
  772. type.basetype = SPIRType::Struct;
  773. for (uint32_t i = 1; i < length; i++)
  774. type.member_types.push_back(ops[i]);
  775. // Check if we have seen this struct type before, with just different
  776. // decorations.
  777. //
  778. // Add workaround for issue #17 as well by looking at OpName for the struct
  779. // types, which we shouldn't normally do.
  780. // We should not normally have to consider type aliases like this to begin with
  781. // however ... glslang issues #304, #307 cover this.
  782. // For stripped names, never consider struct type aliasing.
  783. // We risk declaring the same struct multiple times, but type-punning is not allowed
  784. // so this is safe.
  785. bool consider_aliasing = !ir.get_name(type.self).empty();
  786. if (consider_aliasing)
  787. {
  788. for (auto &other : global_struct_cache)
  789. {
  790. if (ir.get_name(type.self) == ir.get_name(other) &&
  791. types_are_logically_equivalent(type, get<SPIRType>(other)))
  792. {
  793. type.type_alias = other;
  794. break;
  795. }
  796. }
  797. if (type.type_alias == TypeID(0))
  798. global_struct_cache.push_back(id);
  799. }
  800. break;
  801. }
  802. case OpTypeFunction:
  803. {
  804. uint32_t id = ops[0];
  805. uint32_t ret = ops[1];
  806. auto &func = set<SPIRFunctionPrototype>(id, ret);
  807. for (uint32_t i = 2; i < length; i++)
  808. func.parameter_types.push_back(ops[i]);
  809. break;
  810. }
  811. case OpTypeAccelerationStructureKHR:
  812. {
  813. uint32_t id = ops[0];
  814. auto &type = set<SPIRType>(id, op);
  815. type.basetype = SPIRType::AccelerationStructure;
  816. break;
  817. }
  818. case OpTypeRayQueryKHR:
  819. {
  820. uint32_t id = ops[0];
  821. auto &type = set<SPIRType>(id, op);
  822. type.basetype = SPIRType::RayQuery;
  823. break;
  824. }
  825. case OpTypeTensorARM:
  826. {
  827. uint32_t id = ops[0];
  828. auto &type = set<SPIRType>(id, op);
  829. type.basetype = SPIRType::Tensor;
  830. type.ext.tensor = {};
  831. type.ext.tensor.type = ops[1];
  832. if (length >= 3)
  833. type.ext.tensor.rank = ops[2];
  834. if (length >= 4)
  835. type.ext.tensor.shape = ops[3];
  836. break;
  837. }
  838. // Variable declaration
  839. // All variables are essentially pointers with a storage qualifier.
  840. case OpVariable:
  841. {
  842. uint32_t type = ops[0];
  843. uint32_t id = ops[1];
  844. auto storage = static_cast<StorageClass>(ops[2]);
  845. uint32_t initializer = length == 4 ? ops[3] : 0;
  846. if (storage == StorageClassFunction)
  847. {
  848. if (!current_function)
  849. SPIRV_CROSS_THROW("No function currently in scope");
  850. current_function->add_local_variable(id);
  851. }
  852. set<SPIRVariable>(id, type, storage, initializer);
  853. break;
  854. }
  855. // OpPhi
  856. // OpPhi is a fairly magical opcode.
  857. // It selects temporary variables based on which parent block we *came from*.
  858. // In high-level languages we can "de-SSA" by creating a function local, and flush out temporaries to this function-local
  859. // variable to emulate SSA Phi.
  860. case OpPhi:
  861. {
  862. if (!current_function)
  863. SPIRV_CROSS_THROW("No function currently in scope");
  864. if (!current_block)
  865. SPIRV_CROSS_THROW("No block currently in scope");
  866. uint32_t result_type = ops[0];
  867. uint32_t id = ops[1];
  868. // Instead of a temporary, create a new function-wide temporary with this ID instead.
  869. auto &var = set<SPIRVariable>(id, result_type, StorageClassFunction);
  870. var.phi_variable = true;
  871. current_function->add_local_variable(id);
  872. for (uint32_t i = 2; i + 2 <= length; i += 2)
  873. current_block->phi_variables.push_back({ ops[i], ops[i + 1], id });
  874. break;
  875. }
  876. // Constants
  877. case OpSpecConstant:
  878. case OpConstant:
  879. case OpConstantCompositeReplicateEXT:
  880. case OpSpecConstantCompositeReplicateEXT:
  881. {
  882. uint32_t id = ops[1];
  883. auto &type = get<SPIRType>(ops[0]);
  884. if (op == OpConstantCompositeReplicateEXT || op == OpSpecConstantCompositeReplicateEXT)
  885. {
  886. auto subconstant = uint32_t(ops[2]);
  887. set<SPIRConstant>(id, ops[0], &subconstant, 1, op == OpSpecConstantCompositeReplicateEXT, true);
  888. }
  889. else
  890. {
  891. if (type.width > 32)
  892. set<SPIRConstant>(id, ops[0], ops[2] | (uint64_t(ops[3]) << 32), op == OpSpecConstant);
  893. else
  894. set<SPIRConstant>(id, ops[0], ops[2], op == OpSpecConstant);
  895. }
  896. break;
  897. }
  898. case OpSpecConstantFalse:
  899. case OpConstantFalse:
  900. {
  901. uint32_t id = ops[1];
  902. set<SPIRConstant>(id, ops[0], uint32_t(0), op == OpSpecConstantFalse);
  903. break;
  904. }
  905. case OpSpecConstantTrue:
  906. case OpConstantTrue:
  907. {
  908. uint32_t id = ops[1];
  909. set<SPIRConstant>(id, ops[0], uint32_t(1), op == OpSpecConstantTrue);
  910. break;
  911. }
  912. case OpConstantNull:
  913. {
  914. uint32_t id = ops[1];
  915. uint32_t type = ops[0];
  916. ir.make_constant_null(id, type, true);
  917. break;
  918. }
  919. case OpSpecConstantComposite:
  920. case OpConstantComposite:
  921. {
  922. uint32_t id = ops[1];
  923. uint32_t type = ops[0];
  924. auto &ctype = get<SPIRType>(type);
  925. // We can have constants which are structs and arrays.
  926. // In this case, our SPIRConstant will be a list of other SPIRConstant ids which we
  927. // can refer to.
  928. if (ctype.basetype == SPIRType::Struct || !ctype.array.empty())
  929. {
  930. set<SPIRConstant>(id, type, ops + 2, length - 2, op == OpSpecConstantComposite);
  931. }
  932. else
  933. {
  934. uint32_t elements = length - 2;
  935. if (elements > 4)
  936. SPIRV_CROSS_THROW("OpConstantComposite only supports 1, 2, 3 and 4 elements.");
  937. SPIRConstant remapped_constant_ops[4];
  938. const SPIRConstant *c[4];
  939. for (uint32_t i = 0; i < elements; i++)
  940. {
  941. // Specialization constants operations can also be part of this.
  942. // We do not know their value, so any attempt to query SPIRConstant later
  943. // will fail. We can only propagate the ID of the expression and use to_expression on it.
  944. auto *constant_op = maybe_get<SPIRConstantOp>(ops[2 + i]);
  945. auto *undef_op = maybe_get<SPIRUndef>(ops[2 + i]);
  946. if (constant_op)
  947. {
  948. if (op == OpConstantComposite)
  949. SPIRV_CROSS_THROW("Specialization constant operation used in OpConstantComposite.");
  950. remapped_constant_ops[i].make_null(get<SPIRType>(constant_op->basetype));
  951. remapped_constant_ops[i].self = constant_op->self;
  952. remapped_constant_ops[i].constant_type = constant_op->basetype;
  953. remapped_constant_ops[i].specialization = true;
  954. c[i] = &remapped_constant_ops[i];
  955. }
  956. else if (undef_op)
  957. {
  958. // Undefined, just pick 0.
  959. remapped_constant_ops[i].make_null(get<SPIRType>(undef_op->basetype));
  960. remapped_constant_ops[i].constant_type = undef_op->basetype;
  961. c[i] = &remapped_constant_ops[i];
  962. }
  963. else
  964. c[i] = &get<SPIRConstant>(ops[2 + i]);
  965. }
  966. set<SPIRConstant>(id, type, c, elements, op == OpSpecConstantComposite);
  967. }
  968. break;
  969. }
  970. // Functions
  971. case OpFunction:
  972. {
  973. uint32_t res = ops[0];
  974. uint32_t id = ops[1];
  975. // Control
  976. uint32_t type = ops[3];
  977. if (current_function)
  978. SPIRV_CROSS_THROW("Must end a function before starting a new one!");
  979. current_function = &set<SPIRFunction>(id, res, type);
  980. break;
  981. }
  982. case OpFunctionParameter:
  983. {
  984. uint32_t type = ops[0];
  985. uint32_t id = ops[1];
  986. if (!current_function)
  987. SPIRV_CROSS_THROW("Must be in a function!");
  988. current_function->add_parameter(type, id);
  989. set<SPIRVariable>(id, type, StorageClassFunction);
  990. break;
  991. }
  992. case OpFunctionEnd:
  993. {
  994. if (current_block)
  995. {
  996. // Very specific error message, but seems to come up quite often.
  997. SPIRV_CROSS_THROW(
  998. "Cannot end a function before ending the current block.\n"
  999. "Likely cause: If this SPIR-V was created from glslang HLSL, make sure the entry point is valid.");
  1000. }
  1001. current_function = nullptr;
  1002. break;
  1003. }
  1004. // Blocks
  1005. case OpLabel:
  1006. {
  1007. // OpLabel always starts a block.
  1008. if (!current_function)
  1009. SPIRV_CROSS_THROW("Blocks cannot exist outside functions!");
  1010. uint32_t id = ops[0];
  1011. current_function->blocks.push_back(id);
  1012. if (!current_function->entry_block)
  1013. current_function->entry_block = id;
  1014. if (current_block)
  1015. SPIRV_CROSS_THROW("Cannot start a block before ending the current block.");
  1016. current_block = &set<SPIRBlock>(id);
  1017. break;
  1018. }
  1019. // Branch instructions end blocks.
  1020. case OpBranch:
  1021. {
  1022. if (!current_block)
  1023. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1024. uint32_t target = ops[0];
  1025. current_block->terminator = SPIRBlock::Direct;
  1026. current_block->next_block = target;
  1027. current_block = nullptr;
  1028. break;
  1029. }
  1030. case OpBranchConditional:
  1031. {
  1032. if (!current_block)
  1033. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1034. current_block->condition = ops[0];
  1035. current_block->true_block = ops[1];
  1036. current_block->false_block = ops[2];
  1037. current_block->terminator = SPIRBlock::Select;
  1038. if (current_block->true_block == current_block->false_block)
  1039. {
  1040. // Bogus conditional, translate to a direct branch.
  1041. // Avoids some ugly edge cases later when analyzing CFGs.
  1042. // There are some super jank cases where the merge block is different from the true/false,
  1043. // and later branches can "break" out of the selection construct this way.
  1044. // This is complete nonsense, but CTS hits this case.
  1045. // In this scenario, we should see the selection construct as more of a Switch with one default case.
  1046. // The problem here is that this breaks any attempt to break out of outer switch statements,
  1047. // but it's theoretically solvable if this ever comes up using the ladder breaking system ...
  1048. if (current_block->true_block != current_block->next_block &&
  1049. current_block->merge == SPIRBlock::MergeSelection)
  1050. {
  1051. uint32_t ids = ir.increase_bound_by(2);
  1052. auto &type = set<SPIRType>(ids, OpTypeInt);
  1053. type.basetype = SPIRType::Int;
  1054. type.width = 32;
  1055. auto &c = set<SPIRConstant>(ids + 1, ids);
  1056. current_block->condition = c.self;
  1057. current_block->default_block = current_block->true_block;
  1058. current_block->terminator = SPIRBlock::MultiSelect;
  1059. ir.block_meta[current_block->next_block] &= ~ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
  1060. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
  1061. }
  1062. else
  1063. {
  1064. // Collapse loops if we have to.
  1065. bool collapsed_loop = current_block->true_block == current_block->merge_block &&
  1066. current_block->merge == SPIRBlock::MergeLoop;
  1067. if (collapsed_loop)
  1068. {
  1069. ir.block_meta[current_block->merge_block] &= ~ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
  1070. ir.block_meta[current_block->continue_block] &= ~ParsedIR::BLOCK_META_CONTINUE_BIT;
  1071. }
  1072. current_block->next_block = current_block->true_block;
  1073. current_block->condition = 0;
  1074. current_block->true_block = 0;
  1075. current_block->false_block = 0;
  1076. current_block->merge_block = 0;
  1077. current_block->merge = SPIRBlock::MergeNone;
  1078. current_block->terminator = SPIRBlock::Direct;
  1079. }
  1080. }
  1081. current_block = nullptr;
  1082. break;
  1083. }
  1084. case OpSwitch:
  1085. {
  1086. if (!current_block)
  1087. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1088. current_block->terminator = SPIRBlock::MultiSelect;
  1089. current_block->condition = ops[0];
  1090. current_block->default_block = ops[1];
  1091. uint32_t remaining_ops = length - 2;
  1092. if ((remaining_ops % 2) == 0)
  1093. {
  1094. for (uint32_t i = 2; i + 2 <= length; i += 2)
  1095. current_block->cases_32bit.push_back({ ops[i], ops[i + 1] });
  1096. }
  1097. if ((remaining_ops % 3) == 0)
  1098. {
  1099. for (uint32_t i = 2; i + 3 <= length; i += 3)
  1100. {
  1101. uint64_t value = (static_cast<uint64_t>(ops[i + 1]) << 32) | ops[i];
  1102. current_block->cases_64bit.push_back({ value, ops[i + 2] });
  1103. }
  1104. }
  1105. // If we jump to next block, make it break instead since we're inside a switch case block at that point.
  1106. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_MULTISELECT_MERGE_BIT;
  1107. current_block = nullptr;
  1108. break;
  1109. }
  1110. case OpKill:
  1111. case OpTerminateInvocation:
  1112. {
  1113. if (!current_block)
  1114. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1115. current_block->terminator = SPIRBlock::Kill;
  1116. current_block = nullptr;
  1117. break;
  1118. }
  1119. case OpTerminateRayKHR:
  1120. // NV variant is not a terminator.
  1121. if (!current_block)
  1122. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1123. current_block->terminator = SPIRBlock::TerminateRay;
  1124. current_block = nullptr;
  1125. break;
  1126. case OpIgnoreIntersectionKHR:
  1127. // NV variant is not a terminator.
  1128. if (!current_block)
  1129. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1130. current_block->terminator = SPIRBlock::IgnoreIntersection;
  1131. current_block = nullptr;
  1132. break;
  1133. case OpEmitMeshTasksEXT:
  1134. if (!current_block)
  1135. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1136. current_block->terminator = SPIRBlock::EmitMeshTasks;
  1137. for (uint32_t i = 0; i < 3; i++)
  1138. current_block->mesh.groups[i] = ops[i];
  1139. current_block->mesh.payload = length >= 4 ? ops[3] : 0;
  1140. current_block = nullptr;
  1141. // Currently glslang is bugged and does not treat EmitMeshTasksEXT as a terminator.
  1142. ignore_trailing_block_opcodes = true;
  1143. break;
  1144. case OpReturn:
  1145. {
  1146. if (!current_block)
  1147. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1148. current_block->terminator = SPIRBlock::Return;
  1149. current_block = nullptr;
  1150. break;
  1151. }
  1152. case OpReturnValue:
  1153. {
  1154. if (!current_block)
  1155. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1156. current_block->terminator = SPIRBlock::Return;
  1157. current_block->return_value = ops[0];
  1158. current_block = nullptr;
  1159. break;
  1160. }
  1161. case OpUnreachable:
  1162. {
  1163. if (!current_block)
  1164. SPIRV_CROSS_THROW("Trying to end a non-existing block.");
  1165. current_block->terminator = SPIRBlock::Unreachable;
  1166. current_block = nullptr;
  1167. break;
  1168. }
  1169. case OpSelectionMerge:
  1170. {
  1171. if (!current_block)
  1172. SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
  1173. current_block->next_block = ops[0];
  1174. current_block->merge = SPIRBlock::MergeSelection;
  1175. ir.block_meta[current_block->next_block] |= ParsedIR::BLOCK_META_SELECTION_MERGE_BIT;
  1176. if (length >= 2)
  1177. {
  1178. if (ops[1] & SelectionControlFlattenMask)
  1179. current_block->hint = SPIRBlock::HintFlatten;
  1180. else if (ops[1] & SelectionControlDontFlattenMask)
  1181. current_block->hint = SPIRBlock::HintDontFlatten;
  1182. }
  1183. break;
  1184. }
  1185. case OpLoopMerge:
  1186. {
  1187. if (!current_block)
  1188. SPIRV_CROSS_THROW("Trying to modify a non-existing block.");
  1189. current_block->merge_block = ops[0];
  1190. current_block->continue_block = ops[1];
  1191. current_block->merge = SPIRBlock::MergeLoop;
  1192. ir.block_meta[current_block->self] |= ParsedIR::BLOCK_META_LOOP_HEADER_BIT;
  1193. ir.block_meta[current_block->merge_block] |= ParsedIR::BLOCK_META_LOOP_MERGE_BIT;
  1194. ir.continue_block_to_loop_header[current_block->continue_block] = BlockID(current_block->self);
  1195. // Don't add loop headers to continue blocks,
  1196. // which would make it impossible branch into the loop header since
  1197. // they are treated as continues.
  1198. if (current_block->continue_block != BlockID(current_block->self))
  1199. ir.block_meta[current_block->continue_block] |= ParsedIR::BLOCK_META_CONTINUE_BIT;
  1200. if (length >= 3)
  1201. {
  1202. if (ops[2] & LoopControlUnrollMask)
  1203. current_block->hint = SPIRBlock::HintUnroll;
  1204. else if (ops[2] & LoopControlDontUnrollMask)
  1205. current_block->hint = SPIRBlock::HintDontUnroll;
  1206. }
  1207. break;
  1208. }
  1209. case OpSpecConstantOp:
  1210. {
  1211. if (length < 3)
  1212. SPIRV_CROSS_THROW("OpSpecConstantOp not enough arguments.");
  1213. uint32_t result_type = ops[0];
  1214. uint32_t id = ops[1];
  1215. auto spec_op = static_cast<Op>(ops[2]);
  1216. set<SPIRConstantOp>(id, result_type, spec_op, ops + 3, length - 3);
  1217. break;
  1218. }
  1219. case OpLine:
  1220. {
  1221. // OpLine might come at global scope, but we don't care about those since they will not be declared in any
  1222. // meaningful correct order.
  1223. // Ignore all OpLine directives which live outside a function.
  1224. if (current_block)
  1225. current_block->ops.push_back(instruction);
  1226. // Line directives may arrive before first OpLabel.
  1227. // Treat this as the line of the function declaration,
  1228. // so warnings for arguments can propagate properly.
  1229. if (current_function)
  1230. {
  1231. // Store the first one we find and emit it before creating the function prototype.
  1232. if (current_function->entry_line.file_id == 0)
  1233. {
  1234. current_function->entry_line.file_id = ops[0];
  1235. current_function->entry_line.line_literal = ops[1];
  1236. }
  1237. }
  1238. uint32_t file = ops[0];
  1239. uint32_t line = ops[1];
  1240. for (auto &source : ir.sources)
  1241. {
  1242. if (source.file_id == file)
  1243. {
  1244. source.line_markers.emplace_back();
  1245. auto &marker = source.line_markers.back();
  1246. marker.line = line;
  1247. marker.offset = instruction.offset - 1;
  1248. marker.function_id = current_function ? current_function->self : ID(0);
  1249. marker.block_id = current_block ? current_block->self : ID(0);
  1250. break;
  1251. }
  1252. }
  1253. break;
  1254. }
  1255. case OpNoLine:
  1256. {
  1257. // OpNoLine might come at global scope.
  1258. if (current_block)
  1259. current_block->ops.push_back(instruction);
  1260. break;
  1261. }
  1262. // Actual opcodes.
  1263. default:
  1264. {
  1265. if (length >= 2)
  1266. {
  1267. const auto *type = maybe_get<SPIRType>(ops[0]);
  1268. if (type)
  1269. ir.load_type_width.insert({ ops[1], type->width });
  1270. }
  1271. if (!current_block)
  1272. SPIRV_CROSS_THROW("Currently no block to insert opcode.");
  1273. current_block->ops.push_back(instruction);
  1274. break;
  1275. }
  1276. }
  1277. }
  1278. bool Parser::types_are_logically_equivalent(const SPIRType &a, const SPIRType &b) const
  1279. {
  1280. if (a.basetype != b.basetype)
  1281. return false;
  1282. if (a.width != b.width)
  1283. return false;
  1284. if (a.vecsize != b.vecsize)
  1285. return false;
  1286. if (a.columns != b.columns)
  1287. return false;
  1288. if (a.array.size() != b.array.size())
  1289. return false;
  1290. size_t array_count = a.array.size();
  1291. if (array_count && memcmp(a.array.data(), b.array.data(), array_count * sizeof(uint32_t)) != 0)
  1292. return false;
  1293. if (a.basetype == SPIRType::Image || a.basetype == SPIRType::SampledImage)
  1294. {
  1295. if (memcmp(&a.image, &b.image, sizeof(SPIRType::Image)) != 0)
  1296. return false;
  1297. }
  1298. if (a.member_types.size() != b.member_types.size())
  1299. return false;
  1300. size_t member_types = a.member_types.size();
  1301. for (size_t i = 0; i < member_types; i++)
  1302. {
  1303. if (!types_are_logically_equivalent(get<SPIRType>(a.member_types[i]), get<SPIRType>(b.member_types[i])))
  1304. return false;
  1305. }
  1306. return true;
  1307. }
  1308. bool Parser::variable_storage_is_aliased(const SPIRVariable &v) const
  1309. {
  1310. auto &type = get<SPIRType>(v.basetype);
  1311. auto *type_meta = ir.find_meta(type.self);
  1312. bool ssbo = v.storage == StorageClassStorageBuffer ||
  1313. (type_meta && type_meta->decoration.decoration_flags.get(DecorationBufferBlock));
  1314. bool image = type.basetype == SPIRType::Image;
  1315. bool counter = type.basetype == SPIRType::AtomicCounter;
  1316. bool is_restrict;
  1317. if (ssbo)
  1318. is_restrict = ir.get_buffer_block_flags(v).get(DecorationRestrict);
  1319. else
  1320. is_restrict = ir.has_decoration(v.self, DecorationRestrict);
  1321. return !is_restrict && (ssbo || image || counter);
  1322. }
  1323. } // namespace SPIRV_CROSS_NAMESPACE