Coverage Report

Created: 2026-05-16 06:52

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