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