Debian Codegraph @

third_party/spirv-tools/source/opt/instruction.h

raw
1 // Copyright (c) 2016 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #ifndef SOURCE_OPT_INSTRUCTION_H_
16 #define SOURCE_OPT_INSTRUCTION_H_
17
18 #include <cassert>
19 #include <functional>
20 #include <memory>
21 #include <string>
22 #include <utility>
23 #include <vector>
24
25 #include "OpenCLDebugInfo100.h"
26 #include "source/latest_version_glsl_std_450_header.h"
27 #include "source/latest_version_spirv_header.h"
28 #include "source/opcode.h"
29 #include "source/operand.h"
30 #include "source/opt/reflect.h"
31 #include "source/util/ilist_node.h"
32 #include "source/util/small_vector.h"
33 #include "spirv-tools/libspirv.h"
34
35 const uint32_t kNoDebugScope = 0;
36 const uint32_t kNoInlinedAt = 0;
37
38 namespace spvtools {
39 namespace opt {
40
41 class Function;
42 class IRContext;
43 class Module;
44 class InstructionList;
45
46 // Relaxed logical addressing:
47 //
48 // In the logical addressing model, pointers cannot be stored or loaded. This
49 // is a useful assumption because it simplifies the aliasing significantly.
50 // However, for the purpose of legalizing code generated from HLSL, we will have
51 // to allow storing and loading of pointers to opaque objects and runtime
52 // arrays. This relaxation of the rule still implies that function and private
53 // scope variables do not have any aliasing, so we can treat them as before.
54 // This will be call the relaxed logical addressing model.
55 //
56 // This relaxation of the rule will be allowed by |GetBaseAddress|, but it will
57 // enforce that no other pointers are stored or loaded.
58
59 // About operand:
60 //
61 // In the SPIR-V specification, the term "operand" is used to mean any single
62 // SPIR-V word following the leading wordcount-opcode word. Here, the term
63 // "operand" is used to mean a *logical* operand. A logical operand may consist
64 // of multiple SPIR-V words, which together make up the same component. For
65 // example, a logical operand of a 64-bit integer needs two words to express.
66 //
67 // Further, we categorize logical operands into *in* and *out* operands.
68 // In operands are operands actually serve as input to operations, while out
69 // operands are operands that represent ids generated from operations (result
70 // type id or result id). For example, for "OpIAdd %rtype %rid %inop1 %inop2",
71 // "%inop1" and "%inop2" are in operands, while "%rtype" and "%rid" are out
72 // operands.
73
74 // A *logical* operand to a SPIR-V instruction. It can be the type id, result
75 // id, or other additional operands carried in an instruction.
76 struct Operand {
77 using OperandData = utils::SmallVector<uint32_t, 2>;
78 Operand(spv_operand_type_t t, OperandData&& w)
79 : type(t), words(std::move(w)) {}
80
81 Operand(spv_operand_type_t t, const OperandData& w) : type(t), words(w) {}
82
83 spv_operand_type_t type; // Type of this logical operand.
84 OperandData words; // Binary segments of this logical operand.
85
86 // Returns a string operand as a C-style string.
87 const char* AsCString() const {
88 assert(type == SPV_OPERAND_TYPE_LITERAL_STRING);
89 return reinterpret_cast<const char*>(words.data());
90 }
91
92 // Returns a string operand as a std::string.
93 std::string AsString() const { return AsCString(); }
94
95 // Returns a literal integer operand as a uint64_t
96 uint64_t AsLiteralUint64() const {
97 assert(type == SPV_OPERAND_TYPE_TYPED_LITERAL_NUMBER);
98 assert(1 <= words.size());
99 assert(words.size() <= 2);
100 // Load the low word.
101 uint64_t result = uint64_t(words[0]);
102 if (words.size() > 1) {
103 result = result | (uint64_t(words[1]) << 32);
104 }
105 return result;
106 }
107
108 friend bool operator==(const Operand& o1, const Operand& o2) {
109 return o1.type == o2.type && o1.words == o2.words;
110 }
111
112 // TODO(antiagainst): create fields for literal number kind, width, etc.
113 };
114
115 inline bool operator!=(const Operand& o1, const Operand& o2) {
116 return !(o1 == o2);
117 }
118
119 // This structure is used to represent a DebugScope instruction from
120 // the OpenCL.100.DebugInfo extened instruction set. Note that we can
121 // ignore the result id of DebugScope instruction because it is not
122 // used for anything. We do not keep it to reduce the size of
123 // structure.
124 // TODO: Let validator check that the result id is not used anywhere.
125 class DebugScope {
126 public:
127 DebugScope(uint32_t lexical_scope, uint32_t inlined_at)
128 : lexical_scope_(lexical_scope), inlined_at_(inlined_at) {}
129
130 inline bool operator!=(const DebugScope& d) const {
131 return lexical_scope_ != d.lexical_scope_ || inlined_at_ != d.inlined_at_;
132 }
133
134 // Accessor functions for |lexical_scope_|.
135 uint32_t GetLexicalScope() const { return lexical_scope_; }
136 void SetLexicalScope(uint32_t scope) { lexical_scope_ = scope; }
137
138 // Accessor functions for |inlined_at_|.
139 uint32_t GetInlinedAt() const { return inlined_at_; }
140 void SetInlinedAt(uint32_t at) { inlined_at_ = at; }
141
142 // Pushes the binary segments for this DebugScope instruction into
143 // the back of *|binary|.
144 void ToBinary(uint32_t type_id, uint32_t result_id, uint32_t ext_set,
145 std::vector<uint32_t>* binary) const;
146
147 private:
148 // The result id of the lexical scope in which this debug scope is
149 // contained. The value is kNoDebugScope if there is no scope.
150 uint32_t lexical_scope_;
151
152 // The result id of DebugInlinedAt if instruction in this debug scope
153 // is inlined. The value is kNoInlinedAt if it is not inlined.
154 uint32_t inlined_at_;
155 };
156
157 // A SPIR-V instruction. It contains the opcode and any additional logical
158 // operand, including the result id (if any) and result type id (if any). It
159 // may also contain line-related debug instruction (OpLine, OpNoLine) directly
160 // appearing before this instruction. Note that the result id of an instruction
161 // should never change after the instruction being built. If the result id
162 // needs to change, the user should create a new instruction instead.
163 class Instruction : public utils::IntrusiveNodeBase<Instruction> {
164 public:
165 using OperandList = std::vector<Operand>;
166 using iterator = OperandList::iterator;
167 using const_iterator = OperandList::const_iterator;
168
169 // Creates a default OpNop instruction.
170 // This exists solely for containers that can't do without. Should be removed.
171 Instruction()
172 : utils::IntrusiveNodeBase<Instruction>(),
173 context_(nullptr),
174 opcode_(SpvOpNop),
175 has_type_id_(false),
176 has_result_id_(false),
177 unique_id_(0),
178 dbg_scope_(kNoDebugScope, kNoInlinedAt) {}
179
180 // Creates a default OpNop instruction.
181 Instruction(IRContext*);
182 // Creates an instruction with the given opcode |op| and no additional logical
183 // operands.
184 Instruction(IRContext*, SpvOp);
185 // Creates an instruction using the given spv_parsed_instruction_t |inst|. All
186 // the data inside |inst| will be copied and owned in this instance. And keep
187 // record of line-related debug instructions |dbg_line| ahead of this
188 // instruction, if any.
189 Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
190 std::vector<Instruction>&& dbg_line = {});
191
192 Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
193 const DebugScope& dbg_scope);
194
195 // Creates an instruction with the given opcode |op|, type id: |ty_id|,
196 // result id: |res_id| and input operands: |in_operands|.
197 Instruction(IRContext* c, SpvOp op, uint32_t ty_id, uint32_t res_id,
198 const OperandList& in_operands);
199
200 // TODO: I will want to remove these, but will first have to remove the use of
201 // std::vector<Instruction>.
202 Instruction(const Instruction&) = default;
203 Instruction& operator=(const Instruction&) = default;
204
205 Instruction(Instruction&&);
206 Instruction& operator=(Instruction&&);
207
208 virtual ~Instruction() = default;
209
210 // Returns a newly allocated instruction that has the same operands, result,
211 // and type as |this|. The new instruction is not linked into any list.
212 // It is the responsibility of the caller to make sure that the storage is
213 // removed. It is the caller's responsibility to make sure that there is only
214 // one instruction for each result id.
215 Instruction* Clone(IRContext* c) const;
216
217 IRContext* context() const { return context_; }
218
219 SpvOp opcode() const { return opcode_; }
220 // Sets the opcode of this instruction to a specific opcode. Note this may
221 // invalidate the instruction.
222 // TODO(qining): Remove this function when instruction building and insertion
223 // is well implemented.
224 void SetOpcode(SpvOp op) { opcode_ = op; }
225 uint32_t type_id() const {
226 return has_type_id_ ? GetSingleWordOperand(0) : 0;
227 }
228 uint32_t result_id() const {
229 return has_result_id_ ? GetSingleWordOperand(has_type_id_ ? 1 : 0) : 0;
230 }
231 uint32_t unique_id() const {
232 assert(unique_id_ != 0);
233 return unique_id_;
234 }
235 // Returns the vector of line-related debug instructions attached to this
236 // instruction and the caller can directly modify them.
237 std::vector<Instruction>& dbg_line_insts() { return dbg_line_insts_; }
238 const std::vector<Instruction>& dbg_line_insts() const {
239 return dbg_line_insts_;
240 }
241
242 const Instruction* dbg_line_inst() const {
243 return dbg_line_insts_.empty() ? nullptr : &dbg_line_insts_[0];
244 }
245
246 // Clear line-related debug instructions attached to this instruction.
247 void clear_dbg_line_insts() { dbg_line_insts_.clear(); }
248
249 // Set line-related debug instructions.
250 void set_dbg_line_insts(const std::vector<Instruction>& lines) {
251 dbg_line_insts_ = lines;
252 }
253
254 // Same semantics as in the base class except the list the InstructionList
255 // containing |pos| will now assume ownership of |this|.
256 // inline void MoveBefore(Instruction* pos);
257 // inline void InsertAfter(Instruction* pos);
258
259 // Begin and end iterators for operands.
260 iterator begin() { return operands_.begin(); }
261 iterator end() { return operands_.end(); }
262 const_iterator begin() const { return operands_.cbegin(); }
263 const_iterator end() const { return operands_.cend(); }
264 // Const begin and end iterators for operands.
265 const_iterator cbegin() const { return operands_.cbegin(); }
266 const_iterator cend() const { return operands_.cend(); }
267
268 // Gets the number of logical operands.
269 uint32_t NumOperands() const {
270 return static_cast<uint32_t>(operands_.size());
271 }
272 // Gets the number of SPIR-V words occupied by all logical operands.
273 uint32_t NumOperandWords() const {
274 return NumInOperandWords() + TypeResultIdCount();
275 }
276 // Gets the |index|-th logical operand.
277 inline Operand& GetOperand(uint32_t index);
278 inline const Operand& GetOperand(uint32_t index) const;
279 // Adds |operand| to the list of operands of this instruction.
280 // It is the responsibility of the caller to make sure
281 // that the instruction remains valid.
282 inline void AddOperand(Operand&& operand);
283 // Gets the |index|-th logical operand as a single SPIR-V word. This method is
284 // not expected to be used with logical operands consisting of multiple SPIR-V
285 // words.
286 uint32_t GetSingleWordOperand(uint32_t index) const;
287 // Sets the |index|-th in-operand's data to the given |data|.
288 inline void SetInOperand(uint32_t index, Operand::OperandData&& data);
289 // Sets the |index|-th operand's data to the given |data|.
290 // This is for in-operands modification only, but with |index| expressed in
291 // terms of operand index rather than in-operand index.
292 inline void SetOperand(uint32_t index, Operand::OperandData&& data);
293 // Replace all of the in operands with those in |new_operands|.
294 inline void SetInOperands(OperandList&& new_operands);
295 // Sets the result type id.
296 inline void SetResultType(uint32_t ty_id);
297 // Sets the result id
298 inline void SetResultId(uint32_t res_id);
299 inline bool HasResultId() const { return has_result_id_; }
300 // Sets DebugScope.
301 inline void SetDebugScope(const DebugScope& scope);
302 inline const DebugScope& GetDebugScope() const { return dbg_scope_; }
303 // Updates DebugInlinedAt of DebugScope and OpLine.
304 void UpdateDebugInlinedAt(uint32_t new_inlined_at);
305 inline uint32_t GetDebugInlinedAt() const {
306 return dbg_scope_.GetInlinedAt();
307 }
308 // Updates lexical scope of DebugScope and OpLine.
309 void UpdateLexicalScope(uint32_t scope);
310 // Updates OpLine and DebugScope based on the information of |from|.
311 void UpdateDebugInfoFrom(const Instruction* from);
312 // Remove the |index|-th operand
313 void RemoveOperand(uint32_t index) {
314 operands_.erase(operands_.begin() + index);
315 }
316 // Insert an operand before the |index|-th operand
317 void InsertOperand(uint32_t index, Operand&& operand) {
318 operands_.insert(operands_.begin() + index, operand);
319 }
320
321 // The following methods are similar to the above, but are for in operands.
322 uint32_t NumInOperands() const {
323 return static_cast<uint32_t>(operands_.size() - TypeResultIdCount());
324 }
325 uint32_t NumInOperandWords() const;
326 Operand& GetInOperand(uint32_t index) {
327 return GetOperand(index + TypeResultIdCount());
328 }
329 const Operand& GetInOperand(uint32_t index) const {
330 return GetOperand(index + TypeResultIdCount());
331 }
332 uint32_t GetSingleWordInOperand(uint32_t index) const {
333 return GetSingleWordOperand(index + TypeResultIdCount());
334 }
335 void RemoveInOperand(uint32_t index) {
336 operands_.erase(operands_.begin() + index + TypeResultIdCount());
337 }
338
339 // Returns true if this instruction is OpNop.
340 inline bool IsNop() const;
341 // Turns this instruction to OpNop. This does not clear out all preceding
342 // line-related debug instructions.
343 inline void ToNop();
344
345 // Runs the given function |f| on this instruction and optionally on the
346 // preceding debug line instructions. The function will always be run
347 // if this is itself a debug line instruction.
348 inline void ForEachInst(const std::function<void(Instruction*)>& f,
349 bool run_on_debug_line_insts = false);
350 inline void ForEachInst(const std::function<void(const Instruction*)>& f,
351 bool run_on_debug_line_insts = false) const;
352
353 // Runs the given function |f| on this instruction and optionally on the
354 // preceding debug line instructions. The function will always be run
355 // if this is itself a debug line instruction. If |f| returns false,
356 // iteration is terminated and this function returns false.
357 inline bool WhileEachInst(const std::function<bool(Instruction*)>& f,
358 bool run_on_debug_line_insts = false);
359 inline bool WhileEachInst(const std::function<bool(const Instruction*)>& f,
360 bool run_on_debug_line_insts = false) const;
361
362 // Runs the given function |f| on all operand ids.
363 //
364 // |f| should not transform an ID into 0, as 0 is an invalid ID.
365 inline void ForEachId(const std::function<void(uint32_t*)>& f);
366 inline void ForEachId(const std::function<void(const uint32_t*)>& f) const;
367
368 // Runs the given function |f| on all "in" operand ids.
369 inline void ForEachInId(const std::function<void(uint32_t*)>& f);
370 inline void ForEachInId(const std::function<void(const uint32_t*)>& f) const;
371
372 // Runs the given function |f| on all "in" operand ids. If |f| returns false,
373 // iteration is terminated and this function returns false.
374 inline bool WhileEachInId(const std::function<bool(uint32_t*)>& f);
375 inline bool WhileEachInId(
376 const std::function<bool(const uint32_t*)>& f) const;
377
378 // Runs the given function |f| on all "in" operands.
379 inline void ForEachInOperand(const std::function<void(uint32_t*)>& f);
380 inline void ForEachInOperand(
381 const std::function<void(const uint32_t*)>& f) const;
382
383 // Runs the given function |f| on all "in" operands. If |f| returns false,
384 // iteration is terminated and this function return false.
385 inline bool WhileEachInOperand(const std::function<bool(uint32_t*)>& f);
386 inline bool WhileEachInOperand(
387 const std::function<bool(const uint32_t*)>& f) const;
388
389 // Returns true if it's an OpBranchConditional instruction
390 // with branch weights.
391 bool HasBranchWeights() const;
392
393 // Returns true if any operands can be labels
394 inline bool HasLabels() const;
395
396 // Pushes the binary segments for this instruction into the back of *|binary|.
397 void ToBinaryWithoutAttachedDebugInsts(std::vector<uint32_t>* binary) const;
398
399 // Replaces the operands to the instruction with |new_operands|. The caller
400 // is responsible for building a complete and valid list of operands for
401 // this instruction.
402 void ReplaceOperands(const OperandList& new_operands);
403
404 // Returns true if the instruction annotates an id with a decoration.
405 inline bool IsDecoration() const;
406
407 // Returns true if the instruction is known to be a load from read-only
408 // memory.
409 bool IsReadOnlyLoad() const;
410
411 // Returns the instruction that gives the base address of an address
412 // calculation. The instruction must be a load, as defined by |IsLoad|,
413 // store, copy, or access chain instruction. In logical addressing mode, will
414 // return an OpVariable or OpFunctionParameter instruction. For relaxed
415 // logical addressing, it would also return a load of a pointer to an opaque
416 // object. For physical addressing mode, could return other types of
417 // instructions.
418 Instruction* GetBaseAddress() const;
419
420 // Returns true if the instruction loads from memory or samples an image, and
421 // stores the result into an id. It considers only core instructions.
422 // Memory-to-memory instructions are not considered loads.
423 inline bool IsLoad() const;
424
425 // Returns true if the instruction generates a pointer that is definitely
426 // read-only. This is determined by analysing the pointer type's storage
427 // class and decorations that target the pointer's id. It does not analyse
428 // other instructions that the pointer may be derived from. Thus if 'true' is
429 // returned, the pointer is definitely read-only, while if 'false' is returned
430 // it is possible that the pointer may actually be read-only if it is derived
431 // from another pointer that is decorated as read-only.
432 bool IsReadOnlyPointer() const;
433
434 // The following functions check for the various descriptor types defined in
435 // the Vulkan specification section 13.1.
436
437 // Returns true if the instruction defines a pointer type that points to a
438 // storage image.
439 bool IsVulkanStorageImage() const;
440
441 // Returns true if the instruction defines a pointer type that points to a
442 // sampled image.
443 bool IsVulkanSampledImage() const;
444
445 // Returns true if the instruction defines a pointer type that points to a
446 // storage texel buffer.
447 bool IsVulkanStorageTexelBuffer() const;
448
449 // Returns true if the instruction defines a pointer type that points to a
450 // storage buffer.
451 bool IsVulkanStorageBuffer() const;
452
453 // Returns true if the instruction defines a pointer type that points to a
454 // uniform buffer.
455 bool IsVulkanUniformBuffer() const;
456
457 // Returns true if the instruction is an atom operation that uses original
458 // value.
459 inline bool IsAtomicWithLoad() const;
460
461 // Returns true if the instruction is an atom operation.
462 inline bool IsAtomicOp() const;
463
464 // Returns true if this instruction is a branch or switch instruction (either
465 // conditional or not).
466 bool IsBranch() const { return spvOpcodeIsBranch(opcode()); }
467
468 // Returns true if this instruction causes the function to finish execution
469 // and return to its caller
470 bool IsReturn() const { return spvOpcodeIsReturn(opcode()); }
471
472 // Returns true if this instruction exits this function or aborts execution.
473 bool IsReturnOrAbort() const { return spvOpcodeIsReturnOrAbort(opcode()); }
474
475 // Returns the id for the |element|'th subtype. If the |this| is not a
476 // composite type, this function returns 0.
477 uint32_t GetTypeComponent(uint32_t element) const;
478
479 // Returns true if this instruction is a basic block terminator.
480 bool IsBlockTerminator() const {
481 return spvOpcodeIsBlockTerminator(opcode());
482 }
483
484 // Returns true if |this| is an instruction that define an opaque type. Since
485 // runtime array have similar characteristics they are included as opaque
486 // types.
487 bool IsOpaqueType() const;
488
489 // Returns true if |this| is an instruction which could be folded into a
490 // constant value.
491 bool IsFoldable() const;
492
493 // Returns true if |this| is an instruction which could be folded into a
494 // constant value by |FoldScalar|.
495 bool IsFoldableByFoldScalar() const;
496
497 // Returns true if we are allowed to fold or otherwise manipulate the
498 // instruction that defines |id| in the given context. This includes not
499 // handling NaN values.
500 bool IsFloatingPointFoldingAllowed() const;
501
502 inline bool operator==(const Instruction&) const;
503 inline bool operator!=(const Instruction&) const;
504 inline bool operator<(const Instruction&) const;
505
506 // Takes ownership of the instruction owned by |i| and inserts it immediately
507 // before |this|. Returns the inserted instruction.
508 Instruction* InsertBefore(std::unique_ptr<Instruction>&& i);
509 // Takes ownership of the instructions in |list| and inserts them in order
510 // immediately before |this|. Returns the first inserted instruction.
511 // Assumes the list is non-empty.
512 Instruction* InsertBefore(std::vector<std::unique_ptr<Instruction>>&& list);
513 using utils::IntrusiveNodeBase<Instruction>::InsertBefore;
514
515 // Returns true if |this| is an instruction defining a constant, but not a
516 // Spec constant.
517 inline bool IsConstant() const;
518
519 // Returns true if |this| is an instruction with an opcode safe to move
520 bool IsOpcodeCodeMotionSafe() const;
521
522 // Pretty-prints |inst|.
523 //
524 // Provides the disassembly of a specific instruction. Utilizes |inst|'s
525 // context to provide the correct interpretation of types, constants, etc.
526 //
527 // |options| are the disassembly options. SPV_BINARY_TO_TEXT_OPTION_NO_HEADER
528 // is always added to |options|.
529 std::string PrettyPrint(uint32_t options = 0u) const;
530
531 // Returns true if the result can be a vector and the result of each component
532 // depends on the corresponding component of any vector inputs.
533 bool IsScalarizable() const;
534
535 // Return true if the only effect of this instructions is the result.
536 bool IsOpcodeSafeToDelete() const;
537
538 // Returns true if it is valid to use the result of |inst| as the base
539 // pointer for a load or store. In this case, valid is defined by the relaxed
540 // logical addressing rules when using logical addressing. Normal validation
541 // rules for physical addressing.
542 bool IsValidBasePointer() const;
543
544 // Returns debug opcode of an OpenCL.100.DebugInfo instruction. If
545 // it is not an OpenCL.100.DebugInfo instruction, just returns
546 // OpenCLDebugInfo100InstructionsMax.
547 OpenCLDebugInfo100Instructions GetOpenCL100DebugOpcode() const;
548
549 // Returns true if it is an OpenCL.DebugInfo.100 instruction.
550 bool IsOpenCL100DebugInstr() const {
551 return GetOpenCL100DebugOpcode() != OpenCLDebugInfo100InstructionsMax;
552 }
553
554 // Returns true if this instructions a non-semantic instruction.
555 bool IsNonSemanticInstruction() const;
556
557 // Dump this instruction on stderr. Useful when running interactive
558 // debuggers.
559 void Dump() const;
560
561 private:
562 // Returns the total count of result type id and result id.
563 uint32_t TypeResultIdCount() const {
564 if (has_type_id_ && has_result_id_) return 2;
565 if (has_type_id_ || has_result_id_) return 1;
566 return 0;
567 }
568
569 // Returns true if the instruction generates a read-only pointer, with the
570 // same caveats documented in the comment for IsReadOnlyPointer. The first
571 // version assumes the module is a shader module. The second assumes a
572 // kernel.
573 bool IsReadOnlyPointerShaders() const;
574 bool IsReadOnlyPointerKernel() const;
575
576 // Returns true if the result of |inst| can be used as the base image for an
577 // instruction that samples a image, reads an image, or writes to an image.
578 bool IsValidBaseImage() const;
579
580 IRContext* context_; // IR Context
581 SpvOp opcode_; // Opcode
582 bool has_type_id_; // True if the instruction has a type id
583 bool has_result_id_; // True if the instruction has a result id
584 uint32_t unique_id_; // Unique instruction id
585 // All logical operands, including result type id and result id.
586 OperandList operands_;
587 // Opline and OpNoLine instructions preceding this instruction. Note that for
588 // Instructions representing OpLine or OpNonLine itself, this field should be
589 // empty.
590 std::vector<Instruction> dbg_line_insts_;
591
592 // DebugScope that wraps this instruction.
593 DebugScope dbg_scope_;
594
595 friend InstructionList;
596 };
597
598 // Pretty-prints |inst| to |str| and returns |str|.
599 //
600 // Provides the disassembly of a specific instruction. Utilizes |inst|'s context
601 // to provide the correct interpretation of types, constants, etc.
602 //
603 // Disassembly uses raw ids (not pretty printed names).
604 std::ostream& operator<<(std::ostream& str, const Instruction& inst);
605
606 inline bool Instruction::operator==(const Instruction& other) const {
607 return unique_id() == other.unique_id();
608 }
609
610 inline bool Instruction::operator!=(const Instruction& other) const {
611 return !(*this == other);
612 }
613
614 inline bool Instruction::operator<(const Instruction& other) const {
615 return unique_id() < other.unique_id();
616 }
617
618 inline Operand& Instruction::GetOperand(uint32_t index) {
619 assert(index < operands_.size() && "operand index out of bound");
620 return operands_[index];
621 }
622
623 inline const Operand& Instruction::GetOperand(uint32_t index) const {
624 assert(index < operands_.size() && "operand index out of bound");
625 return operands_[index];
626 }
627
628 inline void Instruction::AddOperand(Operand&& operand) {
629 operands_.push_back(std::move(operand));
630 }
631
632 inline void Instruction::SetInOperand(uint32_t index,
633 Operand::OperandData&& data) {
634 SetOperand(index + TypeResultIdCount(), std::move(data));
635 }
636
637 inline void Instruction::SetOperand(uint32_t index,
638 Operand::OperandData&& data) {
639 assert(index < operands_.size() && "operand index out of bound");
640 assert(index >= TypeResultIdCount() && "operand is not a in-operand");
641 operands_[index].words = std::move(data);
642 }
643
644 inline void Instruction::SetInOperands(OperandList&& new_operands) {
645 // Remove the old in operands.
646 operands_.erase(operands_.begin() + TypeResultIdCount(), operands_.end());
647 // Add the new in operands.
648 operands_.insert(operands_.end(), new_operands.begin(), new_operands.end());
649 }
650
651 inline void Instruction::SetResultId(uint32_t res_id) {
652 // TODO(dsinclair): Allow setting a result id if there wasn't one
653 // previously. Need to make room in the operands_ array to place the result,
654 // and update the has_result_id_ flag.
655 assert(has_result_id_);
656
657 // TODO(dsinclair): Allow removing the result id. This needs to make sure,
658 // if there was a result id previously to remove it from the operands_ array
659 // and reset the has_result_id_ flag.
660 assert(res_id != 0);
661
662 auto ridx = has_type_id_ ? 1 : 0;
663 operands_[ridx].words = {res_id};
664 }
665
666 inline void Instruction::SetDebugScope(const DebugScope& scope) {
667 dbg_scope_ = scope;
668 for (auto& i : dbg_line_insts_) {
669 i.dbg_scope_ = scope;
670 }
671 }
672
673 inline void Instruction::SetResultType(uint32_t ty_id) {
674 // TODO(dsinclair): Allow setting a type id if there wasn't one
675 // previously. Need to make room in the operands_ array to place the result,
676 // and update the has_type_id_ flag.
677 assert(has_type_id_);
678
679 // TODO(dsinclair): Allow removing the type id. This needs to make sure,
680 // if there was a type id previously to remove it from the operands_ array
681 // and reset the has_type_id_ flag.
682 assert(ty_id != 0);
683
684 operands_.front().words = {ty_id};
685 }
686
687 inline bool Instruction::IsNop() const {
688 return opcode_ == SpvOpNop && !has_type_id_ && !has_result_id_ &&
689 operands_.empty();
690 }
691
692 inline void Instruction::ToNop() {
693 opcode_ = SpvOpNop;
694 has_type_id_ = false;
695 has_result_id_ = false;
696 operands_.clear();
697 }
698
699 inline bool Instruction::WhileEachInst(
700 const std::function<bool(Instruction*)>& f, bool run_on_debug_line_insts) {
701 if (run_on_debug_line_insts) {
702 for (auto& dbg_line : dbg_line_insts_) {
703 if (!f(&dbg_line)) return false;
704 }
705 }
706 return f(this);
707 }
708
709 inline bool Instruction::WhileEachInst(
710 const std::function<bool(const Instruction*)>& f,
711 bool run_on_debug_line_insts) const {
712 if (run_on_debug_line_insts) {
713 for (auto& dbg_line : dbg_line_insts_) {
714 if (!f(&dbg_line)) return false;
715 }
716 }
717 return f(this);
718 }
719
720 inline void Instruction::ForEachInst(const std::function<void(Instruction*)>& f,
721 bool run_on_debug_line_insts) {
722 WhileEachInst(
723 [&f](Instruction* inst) {
724 f(inst);
725 return true;
726 },
727 run_on_debug_line_insts);
728 }
729
730 inline void Instruction::ForEachInst(
731 const std::function<void(const Instruction*)>& f,
732 bool run_on_debug_line_insts) const {
733 WhileEachInst(
734 [&f](const Instruction* inst) {
735 f(inst);
736 return true;
737 },
738 run_on_debug_line_insts);
739 }
740
741 inline void Instruction::ForEachId(const std::function<void(uint32_t*)>& f) {
742 for (auto& operand : operands_)
743 if (spvIsIdType(operand.type)) f(&operand.words[0]);
744 }
745
746 inline void Instruction::ForEachId(
747 const std::function<void(const uint32_t*)>& f) const {
748 for (const auto& operand : operands_)
749 if (spvIsIdType(operand.type)) f(&operand.words[0]);
750 }
751
752 inline bool Instruction::WhileEachInId(
753 const std::function<bool(uint32_t*)>& f) {
754 for (auto& operand : operands_) {
755 if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
756 return false;
757 }
758 }
759 return true;
760 }
761
762 inline bool Instruction::WhileEachInId(
763 const std::function<bool(const uint32_t*)>& f) const {
764 for (const auto& operand : operands_) {
765 if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
766 return false;
767 }
768 }
769 return true;
770 }
771
772 inline void Instruction::ForEachInId(const std::function<void(uint32_t*)>& f) {
773 WhileEachInId([&f](uint32_t* id) {
774 f(id);
775 return true;
776 });
777 }
778
779 inline void Instruction::ForEachInId(
780 const std::function<void(const uint32_t*)>& f) const {
781 WhileEachInId([&f](const uint32_t* id) {
782 f(id);
783 return true;
784 });
785 }
786
787 inline bool Instruction::WhileEachInOperand(
788 const std::function<bool(uint32_t*)>& f) {
789 for (auto& operand : operands_) {
790 switch (operand.type) {
791 case SPV_OPERAND_TYPE_RESULT_ID:
792 case SPV_OPERAND_TYPE_TYPE_ID:
793 break;
794 default:
795 if (!f(&operand.words[0])) return false;
796 break;
797 }
798 }
799 return true;
800 }
801
802 inline bool Instruction::WhileEachInOperand(
803 const std::function<bool(const uint32_t*)>& f) const {
804 for (const auto& operand : operands_) {
805 switch (operand.type) {
806 case SPV_OPERAND_TYPE_RESULT_ID:
807 case SPV_OPERAND_TYPE_TYPE_ID:
808 break;
809 default:
810 if (!f(&operand.words[0])) return false;
811 break;
812 }
813 }
814 return true;
815 }
816
817 inline void Instruction::ForEachInOperand(
818 const std::function<void(uint32_t*)>& f) {
819 WhileEachInOperand([&f](uint32_t* operand) {
820 f(operand);
821 return true;
822 });
823 }
824
825 inline void Instruction::ForEachInOperand(
826 const std::function<void(const uint32_t*)>& f) const {
827 WhileEachInOperand([&f](const uint32_t* operand) {
828 f(operand);
829 return true;
830 });
831 }
832
833 inline bool Instruction::HasLabels() const {
834 switch (opcode_) {
835 case SpvOpSelectionMerge:
836 case SpvOpBranch:
837 case SpvOpLoopMerge:
838 case SpvOpBranchConditional:
839 case SpvOpSwitch:
840 case SpvOpPhi:
841 return true;
842 break;
843 default:
844 break;
845 }
846 return false;
847 }
848
849 bool Instruction::IsDecoration() const {
850 return spvOpcodeIsDecoration(opcode());
851 }
852
853 bool Instruction::IsLoad() const { return spvOpcodeIsLoad(opcode()); }
854
855 bool Instruction::IsAtomicWithLoad() const {
856 return spvOpcodeIsAtomicWithLoad(opcode());
857 }
858
859 bool Instruction::IsAtomicOp() const { return spvOpcodeIsAtomicOp(opcode()); }
860
861 bool Instruction::IsConstant() const {
862 return IsCompileTimeConstantInst(opcode());
863 }
864 } // namespace opt
865 } // namespace spvtools
866
867 #endif // SOURCE_OPT_INSTRUCTION_H_