disassemble.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. // Copyright (c) 2015-2020 The Khronos Group Inc.
  2. // Modifications Copyright (C) 2020 Advanced Micro Devices, Inc. All rights
  3. // reserved.
  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. // This file contains a disassembler: It converts a SPIR-V binary
  17. // to text.
  18. #include "source/disassemble.h"
  19. #include <algorithm>
  20. #include <cassert>
  21. #include <cstring>
  22. #include <iomanip>
  23. #include <ios>
  24. #include <memory>
  25. #include <set>
  26. #include <sstream>
  27. #include <stack>
  28. #include <unordered_map>
  29. #include <utility>
  30. #include "source/assembly_grammar.h"
  31. #include "source/binary.h"
  32. #include "source/diagnostic.h"
  33. #include "source/ext_inst.h"
  34. #include "source/opcode.h"
  35. #include "source/parsed_operand.h"
  36. #include "source/print.h"
  37. #include "source/spirv_constant.h"
  38. #include "source/spirv_endian.h"
  39. #include "source/util/hex_float.h"
  40. #include "source/util/make_unique.h"
  41. #include "spirv-tools/libspirv.h"
  42. namespace spvtools {
  43. namespace {
  44. // Indices to ControlFlowGraph's list of blocks from one block to its successors
  45. struct BlockSuccessors {
  46. // Merge block in OpLoopMerge and OpSelectionMerge
  47. uint32_t merge_block_id = 0;
  48. // The continue block in OpLoopMerge
  49. uint32_t continue_block_id = 0;
  50. // The true and false blocks in OpBranchConditional
  51. uint32_t true_block_id = 0;
  52. uint32_t false_block_id = 0;
  53. // The body block of a loop, as specified by OpBranch after a merge
  54. // instruction
  55. uint32_t body_block_id = 0;
  56. // The same-nesting-level block that follows this one, indicated by an
  57. // OpBranch with no merge instruction.
  58. uint32_t next_block_id = 0;
  59. // The cases (including default) of an OpSwitch
  60. std::vector<uint32_t> case_block_ids;
  61. };
  62. class ParsedInstruction {
  63. public:
  64. ParsedInstruction(const spv_parsed_instruction_t* instruction) {
  65. // Make a copy of the parsed instruction, including stable memory for its
  66. // operands.
  67. instruction_ = *instruction;
  68. operands_ =
  69. std::make_unique<spv_parsed_operand_t[]>(instruction->num_operands);
  70. memcpy(operands_.get(), instruction->operands,
  71. instruction->num_operands * sizeof(*instruction->operands));
  72. instruction_.operands = operands_.get();
  73. }
  74. const spv_parsed_instruction_t* get() const { return &instruction_; }
  75. private:
  76. spv_parsed_instruction_t instruction_;
  77. std::unique_ptr<spv_parsed_operand_t[]> operands_;
  78. };
  79. // One block in the CFG
  80. struct SingleBlock {
  81. // The byte offset in the SPIR-V where the block starts. Used for printing in
  82. // a comment.
  83. size_t byte_offset;
  84. // Block instructions
  85. std::vector<ParsedInstruction> instructions;
  86. // Successors of this block
  87. BlockSuccessors successors;
  88. // The nesting level for this block.
  89. uint32_t nest_level = 0;
  90. bool nest_level_assigned = false;
  91. // Whether the block was reachable
  92. bool reachable = false;
  93. };
  94. // CFG for one function
  95. struct ControlFlowGraph {
  96. std::vector<SingleBlock> blocks;
  97. };
  98. // A Disassembler instance converts a SPIR-V binary to its assembly
  99. // representation.
  100. class Disassembler {
  101. public:
  102. Disassembler(const AssemblyGrammar& grammar, uint32_t options,
  103. NameMapper name_mapper)
  104. : print_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options)),
  105. nested_indent_(
  106. spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NESTED_INDENT, options)),
  107. reorder_blocks_(
  108. spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_REORDER_BLOCKS, options)),
  109. text_(),
  110. out_(print_ ? out_stream() : out_stream(text_)),
  111. instruction_disassembler_(grammar, out_.get(), options, name_mapper),
  112. header_(!spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NO_HEADER, options)),
  113. byte_offset_(0) {}
  114. // Emits the assembly header for the module, and sets up internal state
  115. // so subsequent callbacks can handle the cases where the entire module
  116. // is either big-endian or little-endian.
  117. spv_result_t HandleHeader(spv_endianness_t endian, uint32_t version,
  118. uint32_t generator, uint32_t id_bound,
  119. uint32_t schema);
  120. // Emits the assembly text for the given instruction.
  121. spv_result_t HandleInstruction(const spv_parsed_instruction_t& inst);
  122. // If not printing, populates text_result with the accumulated text.
  123. // Returns SPV_SUCCESS on success.
  124. spv_result_t SaveTextResult(spv_text* text_result) const;
  125. private:
  126. void EmitCFG();
  127. const bool print_; // Should we also print to the standard output stream?
  128. const bool nested_indent_; // Should the blocks be indented according to the
  129. // control flow structure?
  130. const bool
  131. reorder_blocks_; // Should the blocks be reordered for readability?
  132. spv_endianness_t endian_; // The detected endianness of the binary.
  133. std::stringstream text_; // Captures the text, if not printing.
  134. out_stream out_; // The Output stream. Either to text_ or standard output.
  135. disassemble::InstructionDisassembler instruction_disassembler_;
  136. const bool header_; // Should we output header as the leading comment?
  137. size_t byte_offset_; // The number of bytes processed so far.
  138. bool inserted_decoration_space_ = false;
  139. bool inserted_debug_space_ = false;
  140. bool inserted_type_space_ = false;
  141. // The CFG for the current function
  142. ControlFlowGraph current_function_cfg_;
  143. };
  144. spv_result_t Disassembler::HandleHeader(spv_endianness_t endian,
  145. uint32_t version, uint32_t generator,
  146. uint32_t id_bound, uint32_t schema) {
  147. endian_ = endian;
  148. if (header_) {
  149. instruction_disassembler_.EmitHeaderSpirv();
  150. instruction_disassembler_.EmitHeaderVersion(version);
  151. instruction_disassembler_.EmitHeaderGenerator(generator);
  152. instruction_disassembler_.EmitHeaderIdBound(id_bound);
  153. instruction_disassembler_.EmitHeaderSchema(schema);
  154. }
  155. byte_offset_ = SPV_INDEX_INSTRUCTION * sizeof(uint32_t);
  156. return SPV_SUCCESS;
  157. }
  158. spv_result_t Disassembler::HandleInstruction(
  159. const spv_parsed_instruction_t& inst) {
  160. instruction_disassembler_.EmitSectionComment(inst, inserted_decoration_space_,
  161. inserted_debug_space_,
  162. inserted_type_space_);
  163. // When nesting needs to be calculated or when the blocks are reordered, we
  164. // have to have the full picture of the CFG first. Defer processing of the
  165. // instructions until the entire function is visited. This is not done
  166. // without those options (even if simpler) to improve debuggability; for
  167. // example to be able to see whatever is parsed so far even if there is a
  168. // parse error.
  169. if (nested_indent_ || reorder_blocks_) {
  170. switch (static_cast<spv::Op>(inst.opcode)) {
  171. case spv::Op::OpLabel: {
  172. // Add a new block to the CFG
  173. SingleBlock new_block;
  174. new_block.byte_offset = byte_offset_;
  175. new_block.instructions.emplace_back(&inst);
  176. current_function_cfg_.blocks.push_back(std::move(new_block));
  177. break;
  178. }
  179. case spv::Op::OpFunctionEnd:
  180. // Process the CFG and output the instructions
  181. EmitCFG();
  182. // Output OpFunctionEnd itself too
  183. [[fallthrough]];
  184. default:
  185. if (!current_function_cfg_.blocks.empty()) {
  186. // If in a function, stash the instruction for later.
  187. current_function_cfg_.blocks.back().instructions.emplace_back(&inst);
  188. } else {
  189. // Otherwise emit the instruction right away.
  190. instruction_disassembler_.EmitInstruction(inst, byte_offset_);
  191. }
  192. break;
  193. }
  194. } else {
  195. instruction_disassembler_.EmitInstruction(inst, byte_offset_);
  196. }
  197. byte_offset_ += inst.num_words * sizeof(uint32_t);
  198. return SPV_SUCCESS;
  199. }
  200. // Helper to get the operand of an instruction as an id.
  201. uint32_t GetOperand(const spv_parsed_instruction_t* instruction,
  202. uint32_t operand) {
  203. return instruction->words[instruction->operands[operand].offset];
  204. }
  205. std::unordered_map<uint32_t, uint32_t> BuildControlFlowGraph(
  206. ControlFlowGraph& cfg) {
  207. std::unordered_map<uint32_t, uint32_t> id_to_index;
  208. for (size_t index = 0; index < cfg.blocks.size(); ++index) {
  209. SingleBlock& block = cfg.blocks[index];
  210. // For future use, build the ID->index map
  211. assert(static_cast<spv::Op>(block.instructions[0].get()->opcode) ==
  212. spv::Op::OpLabel);
  213. const uint32_t id = block.instructions[0].get()->result_id;
  214. id_to_index[id] = static_cast<uint32_t>(index);
  215. // Look for a merge instruction first. The function of OpBranch depends on
  216. // that.
  217. if (block.instructions.size() >= 3) {
  218. const spv_parsed_instruction_t* maybe_merge =
  219. block.instructions[block.instructions.size() - 2].get();
  220. switch (static_cast<spv::Op>(maybe_merge->opcode)) {
  221. case spv::Op::OpLoopMerge:
  222. block.successors.merge_block_id = GetOperand(maybe_merge, 0);
  223. block.successors.continue_block_id = GetOperand(maybe_merge, 1);
  224. break;
  225. case spv::Op::OpSelectionMerge:
  226. block.successors.merge_block_id = GetOperand(maybe_merge, 0);
  227. break;
  228. default:
  229. break;
  230. }
  231. }
  232. // Then look at the last instruction; it must be a branch
  233. assert(block.instructions.size() >= 2);
  234. const spv_parsed_instruction_t* branch = block.instructions.back().get();
  235. switch (static_cast<spv::Op>(branch->opcode)) {
  236. case spv::Op::OpBranch:
  237. if (block.successors.merge_block_id != 0) {
  238. block.successors.body_block_id = GetOperand(branch, 0);
  239. } else {
  240. block.successors.next_block_id = GetOperand(branch, 0);
  241. }
  242. break;
  243. case spv::Op::OpBranchConditional:
  244. block.successors.true_block_id = GetOperand(branch, 1);
  245. block.successors.false_block_id = GetOperand(branch, 2);
  246. break;
  247. case spv::Op::OpSwitch:
  248. for (uint32_t case_index = 1; case_index < branch->num_operands;
  249. case_index += 2) {
  250. block.successors.case_block_ids.push_back(
  251. GetOperand(branch, case_index));
  252. }
  253. break;
  254. default:
  255. break;
  256. }
  257. }
  258. return id_to_index;
  259. }
  260. // Helper to deal with nesting and non-existing ids / previously-assigned
  261. // levels. It assigns a given nesting level `level` to the block identified by
  262. // `id` (unless that block already has a nesting level assigned).
  263. void Nest(ControlFlowGraph& cfg,
  264. const std::unordered_map<uint32_t, uint32_t>& id_to_index,
  265. uint32_t id, uint32_t level) {
  266. if (id == 0) {
  267. return;
  268. }
  269. const uint32_t block_index = id_to_index.at(id);
  270. SingleBlock& block = cfg.blocks[block_index];
  271. if (!block.nest_level_assigned) {
  272. block.nest_level = level;
  273. block.nest_level_assigned = true;
  274. }
  275. }
  276. // For a given block, assign nesting level to its successors.
  277. void NestSuccessors(ControlFlowGraph& cfg, const SingleBlock& block,
  278. const std::unordered_map<uint32_t, uint32_t>& id_to_index) {
  279. assert(block.nest_level_assigned);
  280. // Nest loops as such:
  281. //
  282. // %loop = OpLabel
  283. // OpLoopMerge %merge %cont ...
  284. // OpBranch %body
  285. // %body = OpLabel
  286. // Op...
  287. // %cont = OpLabel
  288. // Op...
  289. // %merge = OpLabel
  290. // Op...
  291. //
  292. // Nest conditional branches as such:
  293. //
  294. // %header = OpLabel
  295. // OpSelectionMerge %merge ...
  296. // OpBranchConditional ... %true %false
  297. // %true = OpLabel
  298. // Op...
  299. // %false = OpLabel
  300. // Op...
  301. // %merge = OpLabel
  302. // Op...
  303. //
  304. // Nest switch/case as such:
  305. //
  306. // %header = OpLabel
  307. // OpSelectionMerge %merge ...
  308. // OpSwitch ... %default ... %case0 ... %case1 ...
  309. // %default = OpLabel
  310. // Op...
  311. // %case0 = OpLabel
  312. // Op...
  313. // %case1 = OpLabel
  314. // Op...
  315. // ...
  316. // %merge = OpLabel
  317. // Op...
  318. //
  319. // The following can be observed:
  320. //
  321. // - In all cases, the merge block has the same nesting as this block
  322. // - The continue block of loops is nested 1 level deeper
  323. // - The body/branches/cases are nested 2 levels deeper
  324. //
  325. // Back branches to the header block, branches to the merge block, etc
  326. // are correctly handled by processing the header block first (that is
  327. // _this_ block, already processed), then following the above rules
  328. // (in the same order) for any block that is not already processed.
  329. Nest(cfg, id_to_index, block.successors.merge_block_id, block.nest_level);
  330. Nest(cfg, id_to_index, block.successors.continue_block_id,
  331. block.nest_level + 1);
  332. Nest(cfg, id_to_index, block.successors.true_block_id, block.nest_level + 2);
  333. Nest(cfg, id_to_index, block.successors.false_block_id, block.nest_level + 2);
  334. Nest(cfg, id_to_index, block.successors.body_block_id, block.nest_level + 2);
  335. Nest(cfg, id_to_index, block.successors.next_block_id, block.nest_level);
  336. for (uint32_t case_block_id : block.successors.case_block_ids) {
  337. Nest(cfg, id_to_index, case_block_id, block.nest_level + 2);
  338. }
  339. }
  340. struct StackEntry {
  341. // The index of the block (in ControlFlowGraph::blocks) to process.
  342. uint32_t block_index;
  343. // Whether this is the pre or post visit of the block. Because a post-visit
  344. // traversal is needed, the same block is pushed back on the stack on
  345. // pre-visit so it can be visited again on post-visit.
  346. bool post_visit = false;
  347. };
  348. // Helper to deal with DFS traversal and non-existing ids
  349. void VisitSuccesor(std::stack<StackEntry>* dfs_stack,
  350. const std::unordered_map<uint32_t, uint32_t>& id_to_index,
  351. uint32_t id) {
  352. if (id != 0) {
  353. dfs_stack->push({id_to_index.at(id), false});
  354. }
  355. }
  356. // Given the control flow graph, calculates and returns the reverse post-order
  357. // ordering of the blocks. The blocks are then disassembled in that order for
  358. // readability.
  359. std::vector<uint32_t> OrderBlocks(
  360. ControlFlowGraph& cfg,
  361. const std::unordered_map<uint32_t, uint32_t>& id_to_index) {
  362. std::vector<uint32_t> post_order;
  363. // Nest level of a function's first block is 0.
  364. cfg.blocks[0].nest_level = 0;
  365. cfg.blocks[0].nest_level_assigned = true;
  366. // Stack of block indices as they are visited.
  367. std::stack<StackEntry> dfs_stack;
  368. dfs_stack.push({0, false});
  369. std::set<uint32_t> visited;
  370. while (!dfs_stack.empty()) {
  371. const uint32_t block_index = dfs_stack.top().block_index;
  372. const bool post_visit = dfs_stack.top().post_visit;
  373. dfs_stack.pop();
  374. // If this is the second time the block is visited, that's the post-order
  375. // visit.
  376. if (post_visit) {
  377. post_order.push_back(block_index);
  378. continue;
  379. }
  380. // If already visited, another path got to it first (like a case
  381. // fallthrough), avoid reprocessing it.
  382. if (visited.count(block_index) > 0) {
  383. continue;
  384. }
  385. visited.insert(block_index);
  386. // Push it back in the stack for post-order visit
  387. dfs_stack.push({block_index, true});
  388. SingleBlock& block = cfg.blocks[block_index];
  389. // Assign nest levels of successors right away. The successors are either
  390. // nested under this block, or are back or forward edges to blocks outside
  391. // this nesting level (no farther than the merge block), whose nesting
  392. // levels are already assigned before this block is visited.
  393. NestSuccessors(cfg, block, id_to_index);
  394. block.reachable = true;
  395. // The post-order visit yields the order in which the blocks are naturally
  396. // ordered _backwards_. So blocks to be ordered last should be visited
  397. // first. In other words, they should be pushed to the DFS stack last.
  398. VisitSuccesor(&dfs_stack, id_to_index, block.successors.true_block_id);
  399. VisitSuccesor(&dfs_stack, id_to_index, block.successors.false_block_id);
  400. VisitSuccesor(&dfs_stack, id_to_index, block.successors.body_block_id);
  401. VisitSuccesor(&dfs_stack, id_to_index, block.successors.next_block_id);
  402. for (uint32_t case_block_id : block.successors.case_block_ids) {
  403. VisitSuccesor(&dfs_stack, id_to_index, case_block_id);
  404. }
  405. VisitSuccesor(&dfs_stack, id_to_index, block.successors.continue_block_id);
  406. VisitSuccesor(&dfs_stack, id_to_index, block.successors.merge_block_id);
  407. }
  408. std::vector<uint32_t> order(post_order.rbegin(), post_order.rend());
  409. // Finally, dump all unreachable blocks at the end
  410. for (size_t index = 0; index < cfg.blocks.size(); ++index) {
  411. SingleBlock& block = cfg.blocks[index];
  412. if (!block.reachable) {
  413. order.push_back(static_cast<uint32_t>(index));
  414. block.nest_level = 0;
  415. block.nest_level_assigned = true;
  416. }
  417. }
  418. return order;
  419. }
  420. void Disassembler::EmitCFG() {
  421. // Build the CFG edges. At the same time, build an ID->block index map to
  422. // simplify building the CFG edges.
  423. const std::unordered_map<uint32_t, uint32_t> id_to_index =
  424. BuildControlFlowGraph(current_function_cfg_);
  425. // Walk the CFG in reverse post-order to find the best ordering of blocks for
  426. // presentation
  427. std::vector<uint32_t> block_order =
  428. OrderBlocks(current_function_cfg_, id_to_index);
  429. assert(block_order.size() == current_function_cfg_.blocks.size());
  430. // Walk the CFG either in block order or input order based on whether the
  431. // reorder_blocks_ option is given.
  432. for (uint32_t index = 0; index < current_function_cfg_.blocks.size();
  433. ++index) {
  434. const uint32_t block_index = reorder_blocks_ ? block_order[index] : index;
  435. const SingleBlock& block = current_function_cfg_.blocks[block_index];
  436. // Emit instructions for this block
  437. size_t byte_offset = block.byte_offset;
  438. assert(block.nest_level_assigned);
  439. for (const ParsedInstruction& inst : block.instructions) {
  440. instruction_disassembler_.EmitInstructionInBlock(*inst.get(), byte_offset,
  441. block.nest_level);
  442. byte_offset += inst.get()->num_words * sizeof(uint32_t);
  443. }
  444. }
  445. current_function_cfg_.blocks.clear();
  446. }
  447. spv_result_t Disassembler::SaveTextResult(spv_text* text_result) const {
  448. if (!print_) {
  449. size_t length = text_.str().size();
  450. char* str = new char[length + 1];
  451. if (!str) return SPV_ERROR_OUT_OF_MEMORY;
  452. strncpy(str, text_.str().c_str(), length + 1);
  453. spv_text text = new spv_text_t();
  454. if (!text) {
  455. delete[] str;
  456. return SPV_ERROR_OUT_OF_MEMORY;
  457. }
  458. text->str = str;
  459. text->length = length;
  460. *text_result = text;
  461. }
  462. return SPV_SUCCESS;
  463. }
  464. spv_result_t DisassembleHeader(void* user_data, spv_endianness_t endian,
  465. uint32_t /* magic */, uint32_t version,
  466. uint32_t generator, uint32_t id_bound,
  467. uint32_t schema) {
  468. assert(user_data);
  469. auto disassembler = static_cast<Disassembler*>(user_data);
  470. return disassembler->HandleHeader(endian, version, generator, id_bound,
  471. schema);
  472. }
  473. spv_result_t DisassembleInstruction(
  474. void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
  475. assert(user_data);
  476. auto disassembler = static_cast<Disassembler*>(user_data);
  477. return disassembler->HandleInstruction(*parsed_instruction);
  478. }
  479. // Simple wrapper class to provide extra data necessary for targeted
  480. // instruction disassembly.
  481. class WrappedDisassembler {
  482. public:
  483. WrappedDisassembler(Disassembler* dis, const uint32_t* binary, size_t wc)
  484. : disassembler_(dis), inst_binary_(binary), word_count_(wc) {}
  485. Disassembler* disassembler() { return disassembler_; }
  486. const uint32_t* inst_binary() const { return inst_binary_; }
  487. size_t word_count() const { return word_count_; }
  488. private:
  489. Disassembler* disassembler_;
  490. const uint32_t* inst_binary_;
  491. const size_t word_count_;
  492. };
  493. spv_result_t DisassembleTargetHeader(void* user_data, spv_endianness_t endian,
  494. uint32_t /* magic */, uint32_t version,
  495. uint32_t generator, uint32_t id_bound,
  496. uint32_t schema) {
  497. assert(user_data);
  498. auto wrapped = static_cast<WrappedDisassembler*>(user_data);
  499. return wrapped->disassembler()->HandleHeader(endian, version, generator,
  500. id_bound, schema);
  501. }
  502. spv_result_t DisassembleTargetInstruction(
  503. void* user_data, const spv_parsed_instruction_t* parsed_instruction) {
  504. assert(user_data);
  505. auto wrapped = static_cast<WrappedDisassembler*>(user_data);
  506. // Check if this is the instruction we want to disassemble.
  507. if (wrapped->word_count() == parsed_instruction->num_words &&
  508. std::equal(wrapped->inst_binary(),
  509. wrapped->inst_binary() + wrapped->word_count(),
  510. parsed_instruction->words)) {
  511. // Found the target instruction. Disassemble it and signal that we should
  512. // stop searching so we don't output the same instruction again.
  513. if (auto error =
  514. wrapped->disassembler()->HandleInstruction(*parsed_instruction))
  515. return error;
  516. return SPV_REQUESTED_TERMINATION;
  517. }
  518. return SPV_SUCCESS;
  519. }
  520. uint32_t GetLineLengthWithoutColor(const std::string line) {
  521. // Currently, every added color is in the form \x1b...m, so instead of doing a
  522. // lot of string comparisons with spvtools::clr::* strings, we just ignore
  523. // those ranges.
  524. uint32_t length = 0;
  525. for (size_t i = 0; i < line.size(); ++i) {
  526. if (line[i] == '\x1b') {
  527. do {
  528. ++i;
  529. } while (i < line.size() && line[i] != 'm');
  530. continue;
  531. }
  532. ++length;
  533. }
  534. return length;
  535. }
  536. constexpr int kStandardIndent = 15;
  537. constexpr int kBlockNestIndent = 2;
  538. constexpr int kBlockBodyIndentOffset = 2;
  539. constexpr uint32_t kCommentColumn = 50;
  540. } // namespace
  541. namespace disassemble {
  542. InstructionDisassembler::InstructionDisassembler(const AssemblyGrammar& grammar,
  543. std::ostream& stream,
  544. uint32_t options,
  545. NameMapper name_mapper)
  546. : grammar_(grammar),
  547. stream_(stream),
  548. print_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_PRINT, options)),
  549. color_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COLOR, options)),
  550. indent_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_INDENT, options)
  551. ? kStandardIndent
  552. : 0),
  553. nested_indent_(
  554. spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_NESTED_INDENT, options)),
  555. comment_(spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_COMMENT, options)),
  556. show_byte_offset_(
  557. spvIsInBitfield(SPV_BINARY_TO_TEXT_OPTION_SHOW_BYTE_OFFSET, options)),
  558. name_mapper_(std::move(name_mapper)),
  559. last_instruction_comment_alignment_(0) {}
  560. void InstructionDisassembler::EmitHeaderSpirv() { stream_ << "; SPIR-V\n"; }
  561. void InstructionDisassembler::EmitHeaderVersion(uint32_t version) {
  562. stream_ << "; Version: " << SPV_SPIRV_VERSION_MAJOR_PART(version) << "."
  563. << SPV_SPIRV_VERSION_MINOR_PART(version) << "\n";
  564. }
  565. void InstructionDisassembler::EmitHeaderGenerator(uint32_t generator) {
  566. const char* generator_tool =
  567. spvGeneratorStr(SPV_GENERATOR_TOOL_PART(generator));
  568. stream_ << "; Generator: " << generator_tool;
  569. // For unknown tools, print the numeric tool value.
  570. if (0 == strcmp("Unknown", generator_tool)) {
  571. stream_ << "(" << SPV_GENERATOR_TOOL_PART(generator) << ")";
  572. }
  573. // Print the miscellaneous part of the generator word on the same
  574. // line as the tool name.
  575. stream_ << "; " << SPV_GENERATOR_MISC_PART(generator) << "\n";
  576. }
  577. void InstructionDisassembler::EmitHeaderIdBound(uint32_t id_bound) {
  578. stream_ << "; Bound: " << id_bound << "\n";
  579. }
  580. void InstructionDisassembler::EmitHeaderSchema(uint32_t schema) {
  581. stream_ << "; Schema: " << schema << "\n";
  582. }
  583. void InstructionDisassembler::EmitInstruction(
  584. const spv_parsed_instruction_t& inst, size_t inst_byte_offset) {
  585. EmitInstructionImpl(inst, inst_byte_offset, 0, false);
  586. }
  587. void InstructionDisassembler::EmitInstructionInBlock(
  588. const spv_parsed_instruction_t& inst, size_t inst_byte_offset,
  589. uint32_t block_indent) {
  590. EmitInstructionImpl(inst, inst_byte_offset, block_indent, true);
  591. }
  592. void InstructionDisassembler::EmitInstructionImpl(
  593. const spv_parsed_instruction_t& inst, size_t inst_byte_offset,
  594. uint32_t block_indent, bool is_in_block) {
  595. auto opcode = static_cast<spv::Op>(inst.opcode);
  596. // To better align the comments (if any), write the instruction to a line
  597. // first so its length can be readily available.
  598. std::ostringstream line;
  599. if (nested_indent_ && opcode == spv::Op::OpLabel) {
  600. // Separate the blocks by an empty line to make them easier to separate
  601. stream_ << std::endl;
  602. }
  603. if (inst.result_id) {
  604. SetBlue();
  605. const std::string id_name = name_mapper_(inst.result_id);
  606. if (indent_)
  607. line << std::setw(std::max(0, indent_ - 3 - int(id_name.size())));
  608. line << "%" << id_name;
  609. ResetColor();
  610. line << " = ";
  611. } else {
  612. line << std::string(indent_, ' ');
  613. }
  614. if (nested_indent_ && is_in_block) {
  615. // Output OpLabel at the specified nest level, and instructions inside
  616. // blocks nested a little more.
  617. uint32_t indent = block_indent;
  618. bool body_indent = opcode != spv::Op::OpLabel;
  619. line << std::string(
  620. indent * kBlockNestIndent + (body_indent ? kBlockBodyIndentOffset : 0),
  621. ' ');
  622. }
  623. line << "Op" << spvOpcodeString(opcode);
  624. for (uint16_t i = 0; i < inst.num_operands; i++) {
  625. const spv_operand_type_t type = inst.operands[i].type;
  626. assert(type != SPV_OPERAND_TYPE_NONE);
  627. if (type == SPV_OPERAND_TYPE_RESULT_ID) continue;
  628. line << " ";
  629. EmitOperand(line, inst, i);
  630. }
  631. // For the sake of comment generation, store information from some
  632. // instructions for the future.
  633. if (comment_) {
  634. GenerateCommentForDecoratedId(inst);
  635. }
  636. std::ostringstream comments;
  637. const char* comment_separator = "";
  638. if (show_byte_offset_) {
  639. SetGrey(comments);
  640. auto saved_flags = comments.flags();
  641. auto saved_fill = comments.fill();
  642. comments << comment_separator << "0x" << std::setw(8) << std::hex
  643. << std::setfill('0') << inst_byte_offset;
  644. comments.flags(saved_flags);
  645. comments.fill(saved_fill);
  646. ResetColor(comments);
  647. comment_separator = ", ";
  648. }
  649. if (comment_ && opcode == spv::Op::OpName) {
  650. const spv_parsed_operand_t& operand = inst.operands[0];
  651. const uint32_t word = inst.words[operand.offset];
  652. comments << comment_separator << "id %" << word;
  653. comment_separator = ", ";
  654. }
  655. if (comment_ && inst.result_id && id_comments_.count(inst.result_id) > 0) {
  656. comments << comment_separator << id_comments_[inst.result_id].str();
  657. comment_separator = ", ";
  658. }
  659. stream_ << line.str();
  660. if (!comments.str().empty()) {
  661. // Align the comments
  662. const uint32_t line_length = GetLineLengthWithoutColor(line.str());
  663. uint32_t align = std::max(
  664. {line_length + 2, last_instruction_comment_alignment_, kCommentColumn});
  665. // Round up the alignment to a multiple of 4 for more niceness.
  666. align = (align + 3) & ~0x3u;
  667. last_instruction_comment_alignment_ = align;
  668. stream_ << std::string(align - line_length, ' ') << "; " << comments.str();
  669. } else {
  670. last_instruction_comment_alignment_ = 0;
  671. }
  672. stream_ << "\n";
  673. }
  674. void InstructionDisassembler::GenerateCommentForDecoratedId(
  675. const spv_parsed_instruction_t& inst) {
  676. assert(comment_);
  677. auto opcode = static_cast<spv::Op>(inst.opcode);
  678. std::ostringstream partial;
  679. uint32_t id = 0;
  680. const char* separator = "";
  681. switch (opcode) {
  682. case spv::Op::OpDecorate:
  683. // Take everything after `OpDecorate %id` and associate it with id.
  684. id = inst.words[inst.operands[0].offset];
  685. for (uint16_t i = 1; i < inst.num_operands; i++) {
  686. partial << separator;
  687. separator = " ";
  688. EmitOperand(partial, inst, i);
  689. }
  690. break;
  691. default:
  692. break;
  693. }
  694. if (id == 0) {
  695. return;
  696. }
  697. // Add the new comment to the comments of this id
  698. std::ostringstream& id_comment = id_comments_[id];
  699. if (!id_comment.str().empty()) {
  700. id_comment << ", ";
  701. }
  702. id_comment << partial.str();
  703. }
  704. void InstructionDisassembler::EmitSectionComment(
  705. const spv_parsed_instruction_t& inst, bool& inserted_decoration_space,
  706. bool& inserted_debug_space, bool& inserted_type_space) {
  707. auto opcode = static_cast<spv::Op>(inst.opcode);
  708. if (comment_ && opcode == spv::Op::OpFunction) {
  709. stream_ << std::endl;
  710. if (nested_indent_) {
  711. // Double the empty lines between Function sections since nested_indent_
  712. // also separates blocks by a blank.
  713. stream_ << std::endl;
  714. }
  715. stream_ << std::string(indent_, ' ');
  716. stream_ << "; Function " << name_mapper_(inst.result_id) << std::endl;
  717. }
  718. if (comment_ && !inserted_decoration_space && spvOpcodeIsDecoration(opcode)) {
  719. inserted_decoration_space = true;
  720. stream_ << std::endl;
  721. stream_ << std::string(indent_, ' ');
  722. stream_ << "; Annotations" << std::endl;
  723. }
  724. if (comment_ && !inserted_debug_space && spvOpcodeIsDebug(opcode)) {
  725. inserted_debug_space = true;
  726. stream_ << std::endl;
  727. stream_ << std::string(indent_, ' ');
  728. stream_ << "; Debug Information" << std::endl;
  729. }
  730. if (comment_ && !inserted_type_space && spvOpcodeGeneratesType(opcode)) {
  731. inserted_type_space = true;
  732. stream_ << std::endl;
  733. stream_ << std::string(indent_, ' ');
  734. stream_ << "; Types, variables and constants" << std::endl;
  735. }
  736. }
  737. void InstructionDisassembler::EmitOperand(std::ostream& stream,
  738. const spv_parsed_instruction_t& inst,
  739. const uint16_t operand_index) const {
  740. assert(operand_index < inst.num_operands);
  741. const spv_parsed_operand_t& operand = inst.operands[operand_index];
  742. const uint32_t word = inst.words[operand.offset];
  743. switch (operand.type) {
  744. case SPV_OPERAND_TYPE_RESULT_ID:
  745. assert(false && "<result-id> is not supposed to be handled here");
  746. SetBlue(stream);
  747. stream << "%" << name_mapper_(word);
  748. break;
  749. case SPV_OPERAND_TYPE_ID:
  750. case SPV_OPERAND_TYPE_TYPE_ID:
  751. case SPV_OPERAND_TYPE_SCOPE_ID:
  752. case SPV_OPERAND_TYPE_MEMORY_SEMANTICS_ID:
  753. SetYellow(stream);
  754. stream << "%" << name_mapper_(word);
  755. break;
  756. case SPV_OPERAND_TYPE_EXTENSION_INSTRUCTION_NUMBER: {
  757. spv_ext_inst_desc ext_inst;
  758. SetRed(stream);
  759. if (grammar_.lookupExtInst(inst.ext_inst_type, word, &ext_inst) ==
  760. SPV_SUCCESS) {
  761. stream << ext_inst->name;
  762. } else {
  763. if (!spvExtInstIsNonSemantic(inst.ext_inst_type)) {
  764. assert(false && "should have caught this earlier");
  765. } else {
  766. // for non-semantic instruction sets we can just print the number
  767. stream << word;
  768. }
  769. }
  770. } break;
  771. case SPV_OPERAND_TYPE_SPEC_CONSTANT_OP_NUMBER: {
  772. spv_opcode_desc opcode_desc;
  773. if (grammar_.lookupOpcode(spv::Op(word), &opcode_desc))
  774. assert(false && "should have caught this earlier");
  775. SetRed(stream);
  776. stream << opcode_desc->name;
  777. } break;
  778. case SPV_OPERAND_TYPE_LITERAL_INTEGER:
  779. case SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER:
  780. case SPV_OPERAND_TYPE_LITERAL_FLOAT: {
  781. SetRed(stream);
  782. EmitNumericLiteral(&stream, inst, operand);
  783. ResetColor(stream);
  784. } break;
  785. case SPV_OPERAND_TYPE_LITERAL_STRING: {
  786. stream << "\"";
  787. SetGreen(stream);
  788. std::string str = spvDecodeLiteralStringOperand(inst, operand_index);
  789. for (char const& c : str) {
  790. if (c == '"' || c == '\\') stream << '\\';
  791. stream << c;
  792. }
  793. ResetColor(stream);
  794. stream << '"';
  795. } break;
  796. case SPV_OPERAND_TYPE_CAPABILITY:
  797. case SPV_OPERAND_TYPE_SOURCE_LANGUAGE:
  798. case SPV_OPERAND_TYPE_EXECUTION_MODEL:
  799. case SPV_OPERAND_TYPE_ADDRESSING_MODEL:
  800. case SPV_OPERAND_TYPE_MEMORY_MODEL:
  801. case SPV_OPERAND_TYPE_EXECUTION_MODE:
  802. case SPV_OPERAND_TYPE_STORAGE_CLASS:
  803. case SPV_OPERAND_TYPE_DIMENSIONALITY:
  804. case SPV_OPERAND_TYPE_SAMPLER_ADDRESSING_MODE:
  805. case SPV_OPERAND_TYPE_SAMPLER_FILTER_MODE:
  806. case SPV_OPERAND_TYPE_SAMPLER_IMAGE_FORMAT:
  807. case SPV_OPERAND_TYPE_FP_ROUNDING_MODE:
  808. case SPV_OPERAND_TYPE_LINKAGE_TYPE:
  809. case SPV_OPERAND_TYPE_ACCESS_QUALIFIER:
  810. case SPV_OPERAND_TYPE_FUNCTION_PARAMETER_ATTRIBUTE:
  811. case SPV_OPERAND_TYPE_DECORATION:
  812. case SPV_OPERAND_TYPE_BUILT_IN:
  813. case SPV_OPERAND_TYPE_GROUP_OPERATION:
  814. case SPV_OPERAND_TYPE_KERNEL_ENQ_FLAGS:
  815. case SPV_OPERAND_TYPE_KERNEL_PROFILING_INFO:
  816. case SPV_OPERAND_TYPE_RAY_FLAGS:
  817. case SPV_OPERAND_TYPE_RAY_QUERY_INTERSECTION:
  818. case SPV_OPERAND_TYPE_RAY_QUERY_COMMITTED_INTERSECTION_TYPE:
  819. case SPV_OPERAND_TYPE_RAY_QUERY_CANDIDATE_INTERSECTION_TYPE:
  820. case SPV_OPERAND_TYPE_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  821. case SPV_OPERAND_TYPE_DEBUG_COMPOSITE_TYPE:
  822. case SPV_OPERAND_TYPE_DEBUG_TYPE_QUALIFIER:
  823. case SPV_OPERAND_TYPE_DEBUG_OPERATION:
  824. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_BASE_TYPE_ATTRIBUTE_ENCODING:
  825. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_COMPOSITE_TYPE:
  826. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_TYPE_QUALIFIER:
  827. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_OPERATION:
  828. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_IMPORTED_ENTITY:
  829. case SPV_OPERAND_TYPE_FPDENORM_MODE:
  830. case SPV_OPERAND_TYPE_FPOPERATION_MODE:
  831. case SPV_OPERAND_TYPE_QUANTIZATION_MODES:
  832. case SPV_OPERAND_TYPE_FPENCODING:
  833. case SPV_OPERAND_TYPE_OVERFLOW_MODES: {
  834. spv_operand_desc entry;
  835. if (grammar_.lookupOperand(operand.type, word, &entry))
  836. assert(false && "should have caught this earlier");
  837. stream << entry->name;
  838. } break;
  839. case SPV_OPERAND_TYPE_FP_FAST_MATH_MODE:
  840. case SPV_OPERAND_TYPE_FUNCTION_CONTROL:
  841. case SPV_OPERAND_TYPE_LOOP_CONTROL:
  842. case SPV_OPERAND_TYPE_IMAGE:
  843. case SPV_OPERAND_TYPE_MEMORY_ACCESS:
  844. case SPV_OPERAND_TYPE_SELECTION_CONTROL:
  845. case SPV_OPERAND_TYPE_DEBUG_INFO_FLAGS:
  846. case SPV_OPERAND_TYPE_CLDEBUG100_DEBUG_INFO_FLAGS:
  847. case SPV_OPERAND_TYPE_RAW_ACCESS_CHAIN_OPERANDS:
  848. EmitMaskOperand(stream, operand.type, word);
  849. break;
  850. default:
  851. if (spvOperandIsConcreteMask(operand.type)) {
  852. EmitMaskOperand(stream, operand.type, word);
  853. } else if (spvOperandIsConcrete(operand.type)) {
  854. spv_operand_desc entry;
  855. if (grammar_.lookupOperand(operand.type, word, &entry))
  856. assert(false && "should have caught this earlier");
  857. stream << entry->name;
  858. } else {
  859. assert(false && "unhandled or invalid case");
  860. }
  861. break;
  862. }
  863. ResetColor(stream);
  864. }
  865. void InstructionDisassembler::EmitMaskOperand(std::ostream& stream,
  866. const spv_operand_type_t type,
  867. const uint32_t word) const {
  868. // Scan the mask from least significant bit to most significant bit. For each
  869. // set bit, emit the name of that bit. Separate multiple names with '|'.
  870. uint32_t remaining_word = word;
  871. uint32_t mask;
  872. int num_emitted = 0;
  873. for (mask = 1; remaining_word; mask <<= 1) {
  874. if (remaining_word & mask) {
  875. remaining_word ^= mask;
  876. spv_operand_desc entry;
  877. if (grammar_.lookupOperand(type, mask, &entry))
  878. assert(false && "should have caught this earlier");
  879. if (num_emitted) stream << "|";
  880. stream << entry->name;
  881. num_emitted++;
  882. }
  883. }
  884. if (!num_emitted) {
  885. // An operand value of 0 was provided, so represent it by the name
  886. // of the 0 value. In many cases, that's "None".
  887. spv_operand_desc entry;
  888. if (SPV_SUCCESS == grammar_.lookupOperand(type, 0, &entry))
  889. stream << entry->name;
  890. }
  891. }
  892. void InstructionDisassembler::ResetColor(std::ostream& stream) const {
  893. if (color_) stream << spvtools::clr::reset{print_};
  894. }
  895. void InstructionDisassembler::SetGrey(std::ostream& stream) const {
  896. if (color_) stream << spvtools::clr::grey{print_};
  897. }
  898. void InstructionDisassembler::SetBlue(std::ostream& stream) const {
  899. if (color_) stream << spvtools::clr::blue{print_};
  900. }
  901. void InstructionDisassembler::SetYellow(std::ostream& stream) const {
  902. if (color_) stream << spvtools::clr::yellow{print_};
  903. }
  904. void InstructionDisassembler::SetRed(std::ostream& stream) const {
  905. if (color_) stream << spvtools::clr::red{print_};
  906. }
  907. void InstructionDisassembler::SetGreen(std::ostream& stream) const {
  908. if (color_) stream << spvtools::clr::green{print_};
  909. }
  910. void InstructionDisassembler::ResetColor() { ResetColor(stream_); }
  911. void InstructionDisassembler::SetGrey() { SetGrey(stream_); }
  912. void InstructionDisassembler::SetBlue() { SetBlue(stream_); }
  913. void InstructionDisassembler::SetYellow() { SetYellow(stream_); }
  914. void InstructionDisassembler::SetRed() { SetRed(stream_); }
  915. void InstructionDisassembler::SetGreen() { SetGreen(stream_); }
  916. } // namespace disassemble
  917. std::string spvInstructionBinaryToText(const spv_target_env env,
  918. const uint32_t* instCode,
  919. const size_t instWordCount,
  920. const uint32_t* code,
  921. const size_t wordCount,
  922. const uint32_t options) {
  923. spv_context context = spvContextCreate(env);
  924. const AssemblyGrammar grammar(context);
  925. if (!grammar.isValid()) {
  926. spvContextDestroy(context);
  927. return "";
  928. }
  929. // Generate friendly names for Ids if requested.
  930. std::unique_ptr<FriendlyNameMapper> friendly_mapper;
  931. NameMapper name_mapper = GetTrivialNameMapper();
  932. if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
  933. friendly_mapper = MakeUnique<FriendlyNameMapper>(context, code, wordCount);
  934. name_mapper = friendly_mapper->GetNameMapper();
  935. }
  936. // Now disassemble!
  937. Disassembler disassembler(grammar, options, name_mapper);
  938. WrappedDisassembler wrapped(&disassembler, instCode, instWordCount);
  939. spvBinaryParse(context, &wrapped, code, wordCount, DisassembleTargetHeader,
  940. DisassembleTargetInstruction, nullptr);
  941. spv_text text = nullptr;
  942. std::string output;
  943. if (disassembler.SaveTextResult(&text) == SPV_SUCCESS) {
  944. output.assign(text->str, text->str + text->length);
  945. // Drop trailing newline characters.
  946. while (!output.empty() && output.back() == '\n') output.pop_back();
  947. }
  948. spvTextDestroy(text);
  949. spvContextDestroy(context);
  950. return output;
  951. }
  952. } // namespace spvtools
  953. spv_result_t spvBinaryToText(const spv_const_context context,
  954. const uint32_t* code, const size_t wordCount,
  955. const uint32_t options, spv_text* pText,
  956. spv_diagnostic* pDiagnostic) {
  957. spv_context_t hijack_context = *context;
  958. if (pDiagnostic) {
  959. *pDiagnostic = nullptr;
  960. spvtools::UseDiagnosticAsMessageConsumer(&hijack_context, pDiagnostic);
  961. }
  962. const spvtools::AssemblyGrammar grammar(&hijack_context);
  963. if (!grammar.isValid()) return SPV_ERROR_INVALID_TABLE;
  964. // Generate friendly names for Ids if requested.
  965. std::unique_ptr<spvtools::FriendlyNameMapper> friendly_mapper;
  966. spvtools::NameMapper name_mapper = spvtools::GetTrivialNameMapper();
  967. if (options & SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES) {
  968. friendly_mapper = spvtools::MakeUnique<spvtools::FriendlyNameMapper>(
  969. &hijack_context, code, wordCount);
  970. name_mapper = friendly_mapper->GetNameMapper();
  971. }
  972. // Now disassemble!
  973. spvtools::Disassembler disassembler(grammar, options, name_mapper);
  974. if (auto error =
  975. spvBinaryParse(&hijack_context, &disassembler, code, wordCount,
  976. spvtools::DisassembleHeader,
  977. spvtools::DisassembleInstruction, pDiagnostic)) {
  978. return error;
  979. }
  980. return disassembler.SaveTextResult(pText);
  981. }