instruction.h 34 KB

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