instruction.h 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924
  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. // Adds a copy of |operand| to the list of operands of this instruction.
  257. inline void AddOperand(const Operand& operand);
  258. // Gets the |index|-th logical operand as a single SPIR-V word. This method is
  259. // not expected to be used with logical operands consisting of multiple SPIR-V
  260. // words.
  261. uint32_t GetSingleWordOperand(uint32_t index) const;
  262. // Sets the |index|-th in-operand's data to the given |data|.
  263. inline void SetInOperand(uint32_t index, Operand::OperandData&& data);
  264. // Sets the |index|-th operand's data to the given |data|.
  265. // This is for in-operands modification only, but with |index| expressed in
  266. // terms of operand index rather than in-operand index.
  267. inline void SetOperand(uint32_t index, Operand::OperandData&& data);
  268. // Replace all of the in operands with those in |new_operands|.
  269. inline void SetInOperands(OperandList&& new_operands);
  270. // Sets the result type id.
  271. inline void SetResultType(uint32_t ty_id);
  272. inline bool HasResultType() const { return has_type_id_; }
  273. // Sets the result id
  274. inline void SetResultId(uint32_t res_id);
  275. inline bool HasResultId() const { return has_result_id_; }
  276. // Sets DebugScope.
  277. inline void SetDebugScope(const DebugScope& scope);
  278. inline const DebugScope& GetDebugScope() const { return dbg_scope_; }
  279. // Add debug line inst. Renew result id if Debug[No]Line
  280. void AddDebugLine(const Instruction* inst);
  281. // Updates DebugInlinedAt of DebugScope and OpLine.
  282. void UpdateDebugInlinedAt(uint32_t new_inlined_at);
  283. // Clear line-related debug instructions attached to this instruction
  284. // along with def-use entries.
  285. void ClearDbgLineInsts();
  286. // Return true if Shader100:Debug[No]Line
  287. bool IsDebugLineInst() const;
  288. // Return true if Op[No]Line or Shader100:Debug[No]Line
  289. bool IsLineInst() const;
  290. // Return true if OpLine or Shader100:DebugLine
  291. bool IsLine() const;
  292. // Return true if OpNoLine or Shader100:DebugNoLine
  293. bool IsNoLine() const;
  294. inline uint32_t GetDebugInlinedAt() const {
  295. return dbg_scope_.GetInlinedAt();
  296. }
  297. // Updates lexical scope of DebugScope and OpLine.
  298. void UpdateLexicalScope(uint32_t scope);
  299. // Updates OpLine and DebugScope based on the information of |from|.
  300. void UpdateDebugInfoFrom(const Instruction* from);
  301. // Remove the |index|-th operand
  302. void RemoveOperand(uint32_t index) {
  303. operands_.erase(operands_.begin() + index);
  304. }
  305. // Insert an operand before the |index|-th operand
  306. void InsertOperand(uint32_t index, Operand&& operand) {
  307. operands_.insert(operands_.begin() + index, operand);
  308. }
  309. // The following methods are similar to the above, but are for in operands.
  310. uint32_t NumInOperands() const {
  311. return static_cast<uint32_t>(operands_.size() - TypeResultIdCount());
  312. }
  313. uint32_t NumInOperandWords() const;
  314. Operand& GetInOperand(uint32_t index) {
  315. return GetOperand(index + TypeResultIdCount());
  316. }
  317. const Operand& GetInOperand(uint32_t index) const {
  318. return GetOperand(index + TypeResultIdCount());
  319. }
  320. uint32_t GetSingleWordInOperand(uint32_t index) const {
  321. return GetSingleWordOperand(index + TypeResultIdCount());
  322. }
  323. void RemoveInOperand(uint32_t index) {
  324. operands_.erase(operands_.begin() + index + TypeResultIdCount());
  325. }
  326. // Returns true if this instruction is OpNop.
  327. inline bool IsNop() const;
  328. // Turns this instruction to OpNop. This does not clear out all preceding
  329. // line-related debug instructions.
  330. inline void ToNop();
  331. // Runs the given function |f| on this instruction and optionally on the
  332. // preceding debug line instructions. The function will always be run
  333. // if this is itself a debug line instruction.
  334. inline void ForEachInst(const std::function<void(Instruction*)>& f,
  335. bool run_on_debug_line_insts = false);
  336. inline void ForEachInst(const std::function<void(const Instruction*)>& f,
  337. bool run_on_debug_line_insts = false) const;
  338. // Runs the given function |f| on this instruction and optionally on the
  339. // preceding debug line instructions. The function will always be run
  340. // if this is itself a debug line instruction. If |f| returns false,
  341. // iteration is terminated and this function returns false.
  342. inline bool WhileEachInst(const std::function<bool(Instruction*)>& f,
  343. bool run_on_debug_line_insts = false);
  344. inline bool WhileEachInst(const std::function<bool(const Instruction*)>& f,
  345. bool run_on_debug_line_insts = false) const;
  346. // Runs the given function |f| on all operand ids.
  347. //
  348. // |f| should not transform an ID into 0, as 0 is an invalid ID.
  349. inline void ForEachId(const std::function<void(uint32_t*)>& f);
  350. inline void ForEachId(const std::function<void(const uint32_t*)>& f) const;
  351. // Runs the given function |f| on all "in" operand ids.
  352. inline void ForEachInId(const std::function<void(uint32_t*)>& f);
  353. inline void ForEachInId(const std::function<void(const uint32_t*)>& f) const;
  354. // Runs the given function |f| on all "in" operand ids. If |f| returns false,
  355. // iteration is terminated and this function returns false.
  356. inline bool WhileEachInId(const std::function<bool(uint32_t*)>& f);
  357. inline bool WhileEachInId(
  358. const std::function<bool(const uint32_t*)>& f) const;
  359. // Runs the given function |f| on all "in" operands.
  360. inline void ForEachInOperand(const std::function<void(uint32_t*)>& f);
  361. inline void ForEachInOperand(
  362. const std::function<void(const uint32_t*)>& f) const;
  363. // Runs the given function |f| on all "in" operands. If |f| returns false,
  364. // iteration is terminated and this function return false.
  365. inline bool WhileEachInOperand(const std::function<bool(uint32_t*)>& f);
  366. inline bool WhileEachInOperand(
  367. const std::function<bool(const uint32_t*)>& f) const;
  368. // Returns true if it's an OpBranchConditional instruction
  369. // with branch weights.
  370. bool HasBranchWeights() const;
  371. // Returns true if any operands can be labels
  372. inline bool HasLabels() const;
  373. // Pushes the binary segments for this instruction into the back of *|binary|.
  374. void ToBinaryWithoutAttachedDebugInsts(std::vector<uint32_t>* binary) const;
  375. // Replaces the operands to the instruction with |new_operands|. The caller
  376. // is responsible for building a complete and valid list of operands for
  377. // this instruction.
  378. void ReplaceOperands(const OperandList& new_operands);
  379. // Returns true if the instruction annotates an id with a decoration.
  380. inline bool IsDecoration() const;
  381. // Returns true if the instruction is known to be a load from read-only
  382. // memory.
  383. bool IsReadOnlyLoad() const;
  384. // Returns the instruction that gives the base address of an address
  385. // calculation. The instruction must be a load, as defined by |IsLoad|,
  386. // store, copy, or access chain instruction. In logical addressing mode, will
  387. // return an OpVariable or OpFunctionParameter instruction. For relaxed
  388. // logical addressing, it would also return a load of a pointer to an opaque
  389. // object. For physical addressing mode, could return other types of
  390. // instructions.
  391. Instruction* GetBaseAddress() const;
  392. // Returns true if the instruction loads from memory or samples an image, and
  393. // stores the result into an id. It considers only core instructions.
  394. // Memory-to-memory instructions are not considered loads.
  395. inline bool IsLoad() const;
  396. // Returns true if the instruction generates a pointer that is definitely
  397. // read-only. This is determined by analysing the pointer type's storage
  398. // class and decorations that target the pointer's id. It does not analyse
  399. // other instructions that the pointer may be derived from. Thus if 'true' is
  400. // returned, the pointer is definitely read-only, while if 'false' is returned
  401. // it is possible that the pointer may actually be read-only if it is derived
  402. // from another pointer that is decorated as read-only.
  403. bool IsReadOnlyPointer() const;
  404. // The following functions check for the various descriptor types defined in
  405. // the Vulkan specification section 13.1.
  406. // Returns true if the instruction defines a pointer type that points to a
  407. // storage image.
  408. bool IsVulkanStorageImage() const;
  409. // Returns true if the instruction defines a pointer type that points to a
  410. // sampled image.
  411. bool IsVulkanSampledImage() const;
  412. // Returns true if the instruction defines a pointer type that points to a
  413. // storage texel buffer.
  414. bool IsVulkanStorageTexelBuffer() const;
  415. // Returns true if the instruction defines a pointer type that points to a
  416. // storage buffer.
  417. bool IsVulkanStorageBuffer() const;
  418. // Returns true if the instruction defines a variable in StorageBuffer or
  419. // Uniform storage class with a pointer type that points to a storage buffer.
  420. bool IsVulkanStorageBufferVariable() const;
  421. // Returns true if the instruction defines a pointer type that points to a
  422. // uniform buffer.
  423. bool IsVulkanUniformBuffer() const;
  424. // Returns true if the instruction is an atom operation that uses original
  425. // value.
  426. inline bool IsAtomicWithLoad() const;
  427. // Returns true if the instruction is an atom operation.
  428. inline bool IsAtomicOp() const;
  429. // Returns true if this instruction is a branch or switch instruction (either
  430. // conditional or not).
  431. bool IsBranch() const { return spvOpcodeIsBranch(opcode()); }
  432. // Returns true if this instruction causes the function to finish execution
  433. // and return to its caller
  434. bool IsReturn() const { return spvOpcodeIsReturn(opcode()); }
  435. // Returns true if this instruction exits this function or aborts execution.
  436. bool IsReturnOrAbort() const { return spvOpcodeIsReturnOrAbort(opcode()); }
  437. // Returns true if this instruction is a basic block terminator.
  438. bool IsBlockTerminator() const {
  439. return spvOpcodeIsBlockTerminator(opcode());
  440. }
  441. // Returns true if |this| is an instruction that define an opaque type. Since
  442. // runtime array have similar characteristics they are included as opaque
  443. // types.
  444. bool IsOpaqueType() const;
  445. // Returns true if |this| is an instruction which could be folded into a
  446. // constant value.
  447. bool IsFoldable() const;
  448. // Returns true if |this| is an instruction which could be folded into a
  449. // constant value by |FoldScalar|.
  450. bool IsFoldableByFoldScalar() const;
  451. // Returns true if |this| is an instruction which could be folded into a
  452. // constant value by |FoldVector|.
  453. bool IsFoldableByFoldVector() const;
  454. // Returns true if we are allowed to fold or otherwise manipulate the
  455. // instruction that defines |id| in the given context. This includes not
  456. // handling NaN values.
  457. bool IsFloatingPointFoldingAllowed() const;
  458. inline bool operator==(const Instruction&) const;
  459. inline bool operator!=(const Instruction&) const;
  460. inline bool operator<(const Instruction&) const;
  461. // Takes ownership of the instruction owned by |i| and inserts it immediately
  462. // before |this|. Returns the inserted instruction.
  463. Instruction* InsertBefore(std::unique_ptr<Instruction>&& i);
  464. // Takes ownership of the instructions in |list| and inserts them in order
  465. // immediately before |this|. Returns the first inserted instruction.
  466. // Assumes the list is non-empty.
  467. Instruction* InsertBefore(std::vector<std::unique_ptr<Instruction>>&& list);
  468. using utils::IntrusiveNodeBase<Instruction>::InsertBefore;
  469. // Returns true if |this| is an instruction defining a constant, but not a
  470. // Spec constant.
  471. inline bool IsConstant() const;
  472. // Returns true if |this| is an instruction with an opcode safe to move
  473. bool IsOpcodeCodeMotionSafe() const;
  474. // Pretty-prints |inst|.
  475. //
  476. // Provides the disassembly of a specific instruction. Utilizes |inst|'s
  477. // context to provide the correct interpretation of types, constants, etc.
  478. //
  479. // |options| are the disassembly options. SPV_BINARY_TO_TEXT_OPTION_NO_HEADER
  480. // is always added to |options|.
  481. std::string PrettyPrint(uint32_t options = 0u) const;
  482. // Returns true if the result can be a vector and the result of each component
  483. // depends on the corresponding component of any vector inputs.
  484. bool IsScalarizable() const;
  485. // Return true if the only effect of this instructions is the result.
  486. bool IsOpcodeSafeToDelete() const;
  487. // Returns true if it is valid to use the result of |inst| as the base
  488. // pointer for a load or store. In this case, valid is defined by the relaxed
  489. // logical addressing rules when using logical addressing. Normal validation
  490. // rules for physical addressing.
  491. bool IsValidBasePointer() const;
  492. // Returns debug opcode of an OpenCL.100.DebugInfo instruction. If
  493. // it is not an OpenCL.100.DebugInfo instruction, just returns
  494. // OpenCLDebugInfo100InstructionsMax.
  495. OpenCLDebugInfo100Instructions GetOpenCL100DebugOpcode() const;
  496. // Returns debug opcode of an NonSemantic.Shader.DebugInfo.100 instruction. If
  497. // it is not an NonSemantic.Shader.DebugInfo.100 instruction, just return
  498. // NonSemanticShaderDebugInfo100InstructionsMax.
  499. NonSemanticShaderDebugInfo100Instructions GetShader100DebugOpcode() const;
  500. // Returns debug opcode of an OpenCL.100.DebugInfo or
  501. // NonSemantic.Shader.DebugInfo.100 instruction. Since these overlap, we
  502. // return the OpenCLDebugInfo code
  503. CommonDebugInfoInstructions GetCommonDebugOpcode() const;
  504. // Returns true if it is an OpenCL.DebugInfo.100 instruction.
  505. bool IsOpenCL100DebugInstr() const {
  506. return GetOpenCL100DebugOpcode() != OpenCLDebugInfo100InstructionsMax;
  507. }
  508. // Returns true if it is an NonSemantic.Shader.DebugInfo.100 instruction.
  509. bool IsShader100DebugInstr() const {
  510. return GetShader100DebugOpcode() !=
  511. NonSemanticShaderDebugInfo100InstructionsMax;
  512. }
  513. bool IsCommonDebugInstr() const {
  514. return GetCommonDebugOpcode() != CommonDebugInfoInstructionsMax;
  515. }
  516. // Returns true if this instructions a non-semantic instruction.
  517. bool IsNonSemanticInstruction() const;
  518. // Dump this instruction on stderr. Useful when running interactive
  519. // debuggers.
  520. void Dump() const;
  521. private:
  522. // Returns the total count of result type id and result id.
  523. uint32_t TypeResultIdCount() const {
  524. if (has_type_id_ && has_result_id_) return 2;
  525. if (has_type_id_ || has_result_id_) return 1;
  526. return 0;
  527. }
  528. // Returns true if the instruction generates a read-only pointer, with the
  529. // same caveats documented in the comment for IsReadOnlyPointer. The first
  530. // version assumes the module is a shader module. The second assumes a
  531. // kernel.
  532. bool IsReadOnlyPointerShaders() const;
  533. bool IsReadOnlyPointerKernel() const;
  534. // Returns true if the result of |inst| can be used as the base image for an
  535. // instruction that samples a image, reads an image, or writes to an image.
  536. bool IsValidBaseImage() const;
  537. IRContext* context_; // IR Context
  538. spv::Op opcode_; // Opcode
  539. bool has_type_id_; // True if the instruction has a type id
  540. bool has_result_id_; // True if the instruction has a result id
  541. uint32_t unique_id_; // Unique instruction id
  542. // All logical operands, including result type id and result id.
  543. OperandList operands_;
  544. // Op[No]Line or Debug[No]Line instructions preceding this instruction. Note
  545. // that for Instructions representing Op[No]Line or Debug[No]Line themselves,
  546. // this field should be empty.
  547. std::vector<Instruction> dbg_line_insts_;
  548. // DebugScope that wraps this instruction.
  549. DebugScope dbg_scope_;
  550. friend InstructionList;
  551. };
  552. // Pretty-prints |inst| to |str| and returns |str|.
  553. //
  554. // Provides the disassembly of a specific instruction. Utilizes |inst|'s context
  555. // to provide the correct interpretation of types, constants, etc.
  556. //
  557. // Disassembly uses raw ids (not pretty printed names).
  558. std::ostream& operator<<(std::ostream& str, const Instruction& inst);
  559. inline bool Instruction::operator==(const Instruction& other) const {
  560. return unique_id() == other.unique_id();
  561. }
  562. inline bool Instruction::operator!=(const Instruction& other) const {
  563. return !(*this == other);
  564. }
  565. inline bool Instruction::operator<(const Instruction& other) const {
  566. return unique_id() < other.unique_id();
  567. }
  568. inline Operand& Instruction::GetOperand(uint32_t index) {
  569. assert(index < operands_.size() && "operand index out of bound");
  570. return operands_[index];
  571. }
  572. inline const Operand& Instruction::GetOperand(uint32_t index) const {
  573. assert(index < operands_.size() && "operand index out of bound");
  574. return operands_[index];
  575. }
  576. inline void Instruction::AddOperand(Operand&& operand) {
  577. operands_.push_back(std::move(operand));
  578. }
  579. inline void Instruction::AddOperand(const Operand& operand) {
  580. operands_.push_back(operand);
  581. }
  582. inline void Instruction::SetInOperand(uint32_t index,
  583. Operand::OperandData&& data) {
  584. SetOperand(index + TypeResultIdCount(), std::move(data));
  585. }
  586. inline void Instruction::SetOperand(uint32_t index,
  587. Operand::OperandData&& data) {
  588. assert(index < operands_.size() && "operand index out of bound");
  589. assert(index >= TypeResultIdCount() && "operand is not a in-operand");
  590. operands_[index].words = std::move(data);
  591. }
  592. inline void Instruction::SetInOperands(OperandList&& new_operands) {
  593. // Remove the old in operands.
  594. operands_.erase(operands_.begin() + TypeResultIdCount(), operands_.end());
  595. // Add the new in operands.
  596. operands_.insert(operands_.end(), new_operands.begin(), new_operands.end());
  597. }
  598. inline void Instruction::SetResultId(uint32_t res_id) {
  599. // TODO(dsinclair): Allow setting a result id if there wasn't one
  600. // previously. Need to make room in the operands_ array to place the result,
  601. // and update the has_result_id_ flag.
  602. assert(has_result_id_);
  603. // TODO(dsinclair): Allow removing the result id. This needs to make sure,
  604. // if there was a result id previously to remove it from the operands_ array
  605. // and reset the has_result_id_ flag.
  606. assert(res_id != 0);
  607. auto ridx = has_type_id_ ? 1 : 0;
  608. operands_[ridx].words = {res_id};
  609. }
  610. inline void Instruction::SetDebugScope(const DebugScope& scope) {
  611. dbg_scope_ = scope;
  612. for (auto& i : dbg_line_insts_) {
  613. i.dbg_scope_ = scope;
  614. }
  615. }
  616. inline void Instruction::SetResultType(uint32_t ty_id) {
  617. // TODO(dsinclair): Allow setting a type id if there wasn't one
  618. // previously. Need to make room in the operands_ array to place the result,
  619. // and update the has_type_id_ flag.
  620. assert(has_type_id_);
  621. // TODO(dsinclair): Allow removing the type id. This needs to make sure,
  622. // if there was a type id previously to remove it from the operands_ array
  623. // and reset the has_type_id_ flag.
  624. assert(ty_id != 0);
  625. operands_.front().words = {ty_id};
  626. }
  627. inline bool Instruction::IsNop() const {
  628. return opcode_ == spv::Op::OpNop && !has_type_id_ && !has_result_id_ &&
  629. operands_.empty();
  630. }
  631. inline void Instruction::ToNop() {
  632. opcode_ = spv::Op::OpNop;
  633. has_type_id_ = false;
  634. has_result_id_ = false;
  635. operands_.clear();
  636. }
  637. inline bool Instruction::WhileEachInst(
  638. const std::function<bool(Instruction*)>& f, bool run_on_debug_line_insts) {
  639. if (run_on_debug_line_insts) {
  640. for (auto& dbg_line : dbg_line_insts_) {
  641. if (!f(&dbg_line)) return false;
  642. }
  643. }
  644. return f(this);
  645. }
  646. inline bool Instruction::WhileEachInst(
  647. const std::function<bool(const Instruction*)>& f,
  648. bool run_on_debug_line_insts) const {
  649. if (run_on_debug_line_insts) {
  650. for (auto& dbg_line : dbg_line_insts_) {
  651. if (!f(&dbg_line)) return false;
  652. }
  653. }
  654. return f(this);
  655. }
  656. inline void Instruction::ForEachInst(const std::function<void(Instruction*)>& f,
  657. bool run_on_debug_line_insts) {
  658. WhileEachInst(
  659. [&f](Instruction* inst) {
  660. f(inst);
  661. return true;
  662. },
  663. run_on_debug_line_insts);
  664. }
  665. inline void Instruction::ForEachInst(
  666. const std::function<void(const Instruction*)>& f,
  667. bool run_on_debug_line_insts) const {
  668. WhileEachInst(
  669. [&f](const Instruction* inst) {
  670. f(inst);
  671. return true;
  672. },
  673. run_on_debug_line_insts);
  674. }
  675. inline void Instruction::ForEachId(const std::function<void(uint32_t*)>& f) {
  676. for (auto& operand : operands_)
  677. if (spvIsIdType(operand.type)) f(&operand.words[0]);
  678. }
  679. inline void Instruction::ForEachId(
  680. const std::function<void(const uint32_t*)>& f) const {
  681. for (const auto& operand : operands_)
  682. if (spvIsIdType(operand.type)) f(&operand.words[0]);
  683. }
  684. inline bool Instruction::WhileEachInId(
  685. const std::function<bool(uint32_t*)>& f) {
  686. for (auto& operand : operands_) {
  687. if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
  688. return false;
  689. }
  690. }
  691. return true;
  692. }
  693. inline bool Instruction::WhileEachInId(
  694. const std::function<bool(const uint32_t*)>& f) const {
  695. for (const auto& operand : operands_) {
  696. if (spvIsInIdType(operand.type) && !f(&operand.words[0])) {
  697. return false;
  698. }
  699. }
  700. return true;
  701. }
  702. inline void Instruction::ForEachInId(const std::function<void(uint32_t*)>& f) {
  703. WhileEachInId([&f](uint32_t* id) {
  704. f(id);
  705. return true;
  706. });
  707. }
  708. inline void Instruction::ForEachInId(
  709. const std::function<void(const uint32_t*)>& f) const {
  710. WhileEachInId([&f](const uint32_t* id) {
  711. f(id);
  712. return true;
  713. });
  714. }
  715. inline bool Instruction::WhileEachInOperand(
  716. const std::function<bool(uint32_t*)>& f) {
  717. for (auto& operand : operands_) {
  718. switch (operand.type) {
  719. case SPV_OPERAND_TYPE_RESULT_ID:
  720. case SPV_OPERAND_TYPE_TYPE_ID:
  721. break;
  722. default:
  723. if (!f(&operand.words[0])) return false;
  724. break;
  725. }
  726. }
  727. return true;
  728. }
  729. inline bool Instruction::WhileEachInOperand(
  730. const std::function<bool(const uint32_t*)>& f) const {
  731. for (const auto& operand : operands_) {
  732. switch (operand.type) {
  733. case SPV_OPERAND_TYPE_RESULT_ID:
  734. case SPV_OPERAND_TYPE_TYPE_ID:
  735. break;
  736. default:
  737. if (!f(&operand.words[0])) return false;
  738. break;
  739. }
  740. }
  741. return true;
  742. }
  743. inline void Instruction::ForEachInOperand(
  744. const std::function<void(uint32_t*)>& f) {
  745. WhileEachInOperand([&f](uint32_t* operand) {
  746. f(operand);
  747. return true;
  748. });
  749. }
  750. inline void Instruction::ForEachInOperand(
  751. const std::function<void(const uint32_t*)>& f) const {
  752. WhileEachInOperand([&f](const uint32_t* operand) {
  753. f(operand);
  754. return true;
  755. });
  756. }
  757. inline bool Instruction::HasLabels() const {
  758. switch (opcode_) {
  759. case spv::Op::OpSelectionMerge:
  760. case spv::Op::OpBranch:
  761. case spv::Op::OpLoopMerge:
  762. case spv::Op::OpBranchConditional:
  763. case spv::Op::OpSwitch:
  764. case spv::Op::OpPhi:
  765. return true;
  766. break;
  767. default:
  768. break;
  769. }
  770. return false;
  771. }
  772. bool Instruction::IsDecoration() const {
  773. return spvOpcodeIsDecoration(opcode());
  774. }
  775. bool Instruction::IsLoad() const { return spvOpcodeIsLoad(opcode()); }
  776. bool Instruction::IsAtomicWithLoad() const {
  777. return spvOpcodeIsAtomicWithLoad(opcode());
  778. }
  779. bool Instruction::IsAtomicOp() const { return spvOpcodeIsAtomicOp(opcode()); }
  780. bool Instruction::IsConstant() const {
  781. return IsConstantInst(opcode()) && !IsSpecConstantInst(opcode());
  782. }
  783. } // namespace opt
  784. } // namespace spvtools
  785. #endif // SOURCE_OPT_INSTRUCTION_H_