Coverage Report

Created: 2026-06-30 06:51

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