instruction.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068
  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. #include "source/opt/instruction.h"
  15. #include <initializer_list>
  16. #include "OpenCLDebugInfo100.h"
  17. #include "source/disassemble.h"
  18. #include "source/opt/fold.h"
  19. #include "source/opt/ir_context.h"
  20. #include "source/opt/reflect.h"
  21. namespace spvtools {
  22. namespace opt {
  23. namespace {
  24. // Indices used to get particular operands out of instructions using InOperand.
  25. constexpr uint32_t kTypeImageDimIndex = 1;
  26. constexpr uint32_t kLoadBaseIndex = 0;
  27. constexpr uint32_t kPointerTypeStorageClassIndex = 0;
  28. constexpr uint32_t kVariableStorageClassIndex = 0;
  29. constexpr uint32_t kTypeImageSampledIndex = 5;
  30. // Constants for OpenCL.DebugInfo.100 / NonSemantic.Shader.DebugInfo.100
  31. // extension instructions.
  32. constexpr uint32_t kExtInstSetIdInIdx = 0;
  33. constexpr uint32_t kExtInstInstructionInIdx = 1;
  34. constexpr uint32_t kDebugScopeNumWords = 7;
  35. constexpr uint32_t kDebugScopeNumWordsWithoutInlinedAt = 6;
  36. constexpr uint32_t kDebugNoScopeNumWords = 5;
  37. // Number of operands of an OpBranchConditional instruction
  38. // with weights.
  39. constexpr uint32_t kOpBranchConditionalWithWeightsNumOperands = 5;
  40. } // namespace
  41. Instruction::Instruction(IRContext* c)
  42. : utils::IntrusiveNodeBase<Instruction>(),
  43. context_(c),
  44. opcode_(spv::Op::OpNop),
  45. has_type_id_(false),
  46. has_result_id_(false),
  47. unique_id_(c->TakeNextUniqueId()),
  48. dbg_scope_(kNoDebugScope, kNoInlinedAt) {}
  49. Instruction::Instruction(IRContext* c, spv::Op op)
  50. : utils::IntrusiveNodeBase<Instruction>(),
  51. context_(c),
  52. opcode_(op),
  53. has_type_id_(false),
  54. has_result_id_(false),
  55. unique_id_(c->TakeNextUniqueId()),
  56. dbg_scope_(kNoDebugScope, kNoInlinedAt) {}
  57. Instruction::Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
  58. std::vector<Instruction>&& dbg_line)
  59. : utils::IntrusiveNodeBase<Instruction>(),
  60. context_(c),
  61. opcode_(static_cast<spv::Op>(inst.opcode)),
  62. has_type_id_(inst.type_id != 0),
  63. has_result_id_(inst.result_id != 0),
  64. unique_id_(c->TakeNextUniqueId()),
  65. dbg_line_insts_(std::move(dbg_line)),
  66. dbg_scope_(kNoDebugScope, kNoInlinedAt) {
  67. operands_.reserve(inst.num_operands);
  68. for (uint32_t i = 0; i < inst.num_operands; ++i) {
  69. const auto& current_payload = inst.operands[i];
  70. operands_.emplace_back(
  71. current_payload.type, inst.words + current_payload.offset,
  72. inst.words + current_payload.offset + current_payload.num_words);
  73. }
  74. assert((!IsLineInst() || dbg_line.empty()) &&
  75. "Op(No)Line attaching to Op(No)Line found");
  76. }
  77. Instruction::Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
  78. const DebugScope& dbg_scope)
  79. : utils::IntrusiveNodeBase<Instruction>(),
  80. context_(c),
  81. opcode_(static_cast<spv::Op>(inst.opcode)),
  82. has_type_id_(inst.type_id != 0),
  83. has_result_id_(inst.result_id != 0),
  84. unique_id_(c->TakeNextUniqueId()),
  85. dbg_scope_(dbg_scope) {
  86. operands_.reserve(inst.num_operands);
  87. for (uint32_t i = 0; i < inst.num_operands; ++i) {
  88. const auto& current_payload = inst.operands[i];
  89. operands_.emplace_back(
  90. current_payload.type, inst.words + current_payload.offset,
  91. inst.words + current_payload.offset + current_payload.num_words);
  92. }
  93. }
  94. Instruction::Instruction(IRContext* c, spv::Op op, uint32_t ty_id,
  95. uint32_t res_id, const OperandList& in_operands)
  96. : utils::IntrusiveNodeBase<Instruction>(),
  97. context_(c),
  98. opcode_(op),
  99. has_type_id_(ty_id != 0),
  100. has_result_id_(res_id != 0),
  101. unique_id_(c->TakeNextUniqueId()),
  102. operands_(),
  103. dbg_scope_(kNoDebugScope, kNoInlinedAt) {
  104. size_t operands_size = in_operands.size();
  105. if (has_type_id_) {
  106. operands_size++;
  107. }
  108. if (has_result_id_) {
  109. operands_size++;
  110. }
  111. operands_.reserve(operands_size);
  112. if (has_type_id_) {
  113. operands_.emplace_back(spv_operand_type_t::SPV_OPERAND_TYPE_TYPE_ID,
  114. std::initializer_list<uint32_t>{ty_id});
  115. }
  116. if (has_result_id_) {
  117. operands_.emplace_back(spv_operand_type_t::SPV_OPERAND_TYPE_RESULT_ID,
  118. std::initializer_list<uint32_t>{res_id});
  119. }
  120. operands_.insert(operands_.end(), in_operands.begin(), in_operands.end());
  121. }
  122. Instruction::Instruction(Instruction&& that)
  123. : utils::IntrusiveNodeBase<Instruction>(),
  124. context_(that.context_),
  125. opcode_(that.opcode_),
  126. has_type_id_(that.has_type_id_),
  127. has_result_id_(that.has_result_id_),
  128. unique_id_(that.unique_id_),
  129. operands_(std::move(that.operands_)),
  130. dbg_line_insts_(std::move(that.dbg_line_insts_)),
  131. dbg_scope_(that.dbg_scope_) {
  132. for (auto& i : dbg_line_insts_) {
  133. i.dbg_scope_ = that.dbg_scope_;
  134. }
  135. }
  136. Instruction& Instruction::operator=(Instruction&& that) {
  137. context_ = that.context_;
  138. opcode_ = that.opcode_;
  139. has_type_id_ = that.has_type_id_;
  140. has_result_id_ = that.has_result_id_;
  141. unique_id_ = that.unique_id_;
  142. operands_ = std::move(that.operands_);
  143. dbg_line_insts_ = std::move(that.dbg_line_insts_);
  144. dbg_scope_ = that.dbg_scope_;
  145. return *this;
  146. }
  147. Instruction* Instruction::Clone(IRContext* c) const {
  148. Instruction* clone = new Instruction(c);
  149. clone->opcode_ = opcode_;
  150. clone->has_type_id_ = has_type_id_;
  151. clone->has_result_id_ = has_result_id_;
  152. clone->unique_id_ = c->TakeNextUniqueId();
  153. clone->operands_ = operands_;
  154. clone->dbg_line_insts_ = dbg_line_insts_;
  155. for (auto& i : clone->dbg_line_insts_) {
  156. i.unique_id_ = c->TakeNextUniqueId();
  157. if (i.IsDebugLineInst()) i.SetResultId(c->TakeNextId());
  158. }
  159. clone->dbg_scope_ = dbg_scope_;
  160. return clone;
  161. }
  162. uint32_t Instruction::GetSingleWordOperand(uint32_t index) const {
  163. const auto& words = GetOperand(index).words;
  164. assert(words.size() == 1 && "expected the operand only taking one word");
  165. return words.front();
  166. }
  167. uint32_t Instruction::NumInOperandWords() const {
  168. uint32_t size = 0;
  169. for (uint32_t i = TypeResultIdCount(); i < operands_.size(); ++i)
  170. size += static_cast<uint32_t>(operands_[i].words.size());
  171. return size;
  172. }
  173. bool Instruction::HasBranchWeights() const {
  174. if (opcode_ == spv::Op::OpBranchConditional &&
  175. NumOperands() == kOpBranchConditionalWithWeightsNumOperands) {
  176. return true;
  177. }
  178. return false;
  179. }
  180. void Instruction::ToBinaryWithoutAttachedDebugInsts(
  181. std::vector<uint32_t>* binary) const {
  182. const uint32_t num_words = 1 + NumOperandWords();
  183. binary->push_back((num_words << 16) | static_cast<uint16_t>(opcode_));
  184. for (const auto& operand : operands_) {
  185. binary->insert(binary->end(), operand.words.begin(), operand.words.end());
  186. }
  187. }
  188. void Instruction::ReplaceOperands(const OperandList& new_operands) {
  189. operands_.clear();
  190. operands_.insert(operands_.begin(), new_operands.begin(), new_operands.end());
  191. }
  192. bool Instruction::IsReadOnlyLoad() const {
  193. if (IsLoad()) {
  194. Instruction* address_def = GetBaseAddress();
  195. if (!address_def) {
  196. return false;
  197. }
  198. if (address_def->opcode() == spv::Op::OpVariable) {
  199. if (address_def->IsReadOnlyPointer()) {
  200. return true;
  201. }
  202. }
  203. if (address_def->opcode() == spv::Op::OpLoad) {
  204. const analysis::Type* address_type =
  205. context()->get_type_mgr()->GetType(address_def->type_id());
  206. if (address_type->AsSampledImage() != nullptr) {
  207. const auto* image_type =
  208. address_type->AsSampledImage()->image_type()->AsImage();
  209. if (image_type->sampled() == 1) {
  210. return true;
  211. }
  212. }
  213. }
  214. }
  215. return false;
  216. }
  217. Instruction* Instruction::GetBaseAddress() const {
  218. uint32_t base = GetSingleWordInOperand(kLoadBaseIndex);
  219. Instruction* base_inst = context()->get_def_use_mgr()->GetDef(base);
  220. bool done = false;
  221. while (!done) {
  222. switch (base_inst->opcode()) {
  223. case spv::Op::OpAccessChain:
  224. case spv::Op::OpInBoundsAccessChain:
  225. case spv::Op::OpPtrAccessChain:
  226. case spv::Op::OpInBoundsPtrAccessChain:
  227. case spv::Op::OpImageTexelPointer:
  228. case spv::Op::OpCopyObject:
  229. // All of these instructions have the base pointer use a base pointer
  230. // in in-operand 0.
  231. base = base_inst->GetSingleWordInOperand(0);
  232. base_inst = context()->get_def_use_mgr()->GetDef(base);
  233. break;
  234. default:
  235. done = true;
  236. break;
  237. }
  238. }
  239. return base_inst;
  240. }
  241. bool Instruction::IsReadOnlyPointer() const {
  242. if (context()->get_feature_mgr()->HasCapability(spv::Capability::Shader))
  243. return IsReadOnlyPointerShaders();
  244. else
  245. return IsReadOnlyPointerKernel();
  246. }
  247. bool Instruction::IsVulkanStorageImage() const {
  248. if (opcode() != spv::Op::OpTypePointer) {
  249. return false;
  250. }
  251. spv::StorageClass storage_class =
  252. spv::StorageClass(GetSingleWordInOperand(kPointerTypeStorageClassIndex));
  253. if (storage_class != spv::StorageClass::UniformConstant) {
  254. return false;
  255. }
  256. Instruction* base_type =
  257. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  258. // Unpack the optional layer of arraying.
  259. if (base_type->opcode() == spv::Op::OpTypeArray ||
  260. base_type->opcode() == spv::Op::OpTypeRuntimeArray) {
  261. base_type = context()->get_def_use_mgr()->GetDef(
  262. base_type->GetSingleWordInOperand(0));
  263. }
  264. if (base_type->opcode() != spv::Op::OpTypeImage) {
  265. return false;
  266. }
  267. if (spv::Dim(base_type->GetSingleWordInOperand(kTypeImageDimIndex)) ==
  268. spv::Dim::Buffer) {
  269. return false;
  270. }
  271. // Check if the image is sampled. If we do not know for sure that it is,
  272. // then assume it is a storage image.
  273. return base_type->GetSingleWordInOperand(kTypeImageSampledIndex) != 1;
  274. }
  275. bool Instruction::IsVulkanSampledImage() const {
  276. if (opcode() != spv::Op::OpTypePointer) {
  277. return false;
  278. }
  279. spv::StorageClass storage_class =
  280. spv::StorageClass(GetSingleWordInOperand(kPointerTypeStorageClassIndex));
  281. if (storage_class != spv::StorageClass::UniformConstant) {
  282. return false;
  283. }
  284. Instruction* base_type =
  285. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  286. // Unpack the optional layer of arraying.
  287. if (base_type->opcode() == spv::Op::OpTypeArray ||
  288. base_type->opcode() == spv::Op::OpTypeRuntimeArray) {
  289. base_type = context()->get_def_use_mgr()->GetDef(
  290. base_type->GetSingleWordInOperand(0));
  291. }
  292. if (base_type->opcode() != spv::Op::OpTypeImage) {
  293. return false;
  294. }
  295. if (spv::Dim(base_type->GetSingleWordInOperand(kTypeImageDimIndex)) ==
  296. spv::Dim::Buffer) {
  297. return false;
  298. }
  299. // Check if the image is sampled. If we know for sure that it is,
  300. // then return true.
  301. return base_type->GetSingleWordInOperand(kTypeImageSampledIndex) == 1;
  302. }
  303. bool Instruction::IsVulkanStorageTexelBuffer() const {
  304. if (opcode() != spv::Op::OpTypePointer) {
  305. return false;
  306. }
  307. spv::StorageClass storage_class =
  308. spv::StorageClass(GetSingleWordInOperand(kPointerTypeStorageClassIndex));
  309. if (storage_class != spv::StorageClass::UniformConstant) {
  310. return false;
  311. }
  312. Instruction* base_type =
  313. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  314. // Unpack the optional layer of arraying.
  315. if (base_type->opcode() == spv::Op::OpTypeArray ||
  316. base_type->opcode() == spv::Op::OpTypeRuntimeArray) {
  317. base_type = context()->get_def_use_mgr()->GetDef(
  318. base_type->GetSingleWordInOperand(0));
  319. }
  320. if (base_type->opcode() != spv::Op::OpTypeImage) {
  321. return false;
  322. }
  323. if (spv::Dim(base_type->GetSingleWordInOperand(kTypeImageDimIndex)) !=
  324. spv::Dim::Buffer) {
  325. return false;
  326. }
  327. // Check if the image is sampled. If we do not know for sure that it is,
  328. // then assume it is a storage texel buffer.
  329. return base_type->GetSingleWordInOperand(kTypeImageSampledIndex) != 1;
  330. }
  331. bool Instruction::IsVulkanStorageBuffer() const {
  332. // Is there a difference between a "Storage buffer" and a "dynamic storage
  333. // buffer" in SPIR-V and do we care about the difference?
  334. if (opcode() != spv::Op::OpTypePointer) {
  335. return false;
  336. }
  337. Instruction* base_type =
  338. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  339. // Unpack the optional layer of arraying.
  340. if (base_type->opcode() == spv::Op::OpTypeArray ||
  341. base_type->opcode() == spv::Op::OpTypeRuntimeArray) {
  342. base_type = context()->get_def_use_mgr()->GetDef(
  343. base_type->GetSingleWordInOperand(0));
  344. }
  345. if (base_type->opcode() != spv::Op::OpTypeStruct) {
  346. return false;
  347. }
  348. spv::StorageClass storage_class =
  349. spv::StorageClass(GetSingleWordInOperand(kPointerTypeStorageClassIndex));
  350. if (storage_class == spv::StorageClass::Uniform) {
  351. bool is_buffer_block = false;
  352. context()->get_decoration_mgr()->ForEachDecoration(
  353. base_type->result_id(), uint32_t(spv::Decoration::BufferBlock),
  354. [&is_buffer_block](const Instruction&) { is_buffer_block = true; });
  355. return is_buffer_block;
  356. } else if (storage_class == spv::StorageClass::StorageBuffer) {
  357. bool is_block = false;
  358. context()->get_decoration_mgr()->ForEachDecoration(
  359. base_type->result_id(), uint32_t(spv::Decoration::Block),
  360. [&is_block](const Instruction&) { is_block = true; });
  361. return is_block;
  362. }
  363. return false;
  364. }
  365. bool Instruction::IsVulkanStorageBufferVariable() const {
  366. if (opcode() != spv::Op::OpVariable) {
  367. return false;
  368. }
  369. spv::StorageClass storage_class =
  370. spv::StorageClass(GetSingleWordInOperand(kVariableStorageClassIndex));
  371. if (storage_class == spv::StorageClass::StorageBuffer ||
  372. storage_class == spv::StorageClass::Uniform) {
  373. Instruction* var_type = context()->get_def_use_mgr()->GetDef(type_id());
  374. return var_type != nullptr && var_type->IsVulkanStorageBuffer();
  375. }
  376. return false;
  377. }
  378. bool Instruction::IsVulkanUniformBuffer() const {
  379. if (opcode() != spv::Op::OpTypePointer) {
  380. return false;
  381. }
  382. spv::StorageClass storage_class =
  383. spv::StorageClass(GetSingleWordInOperand(kPointerTypeStorageClassIndex));
  384. if (storage_class != spv::StorageClass::Uniform) {
  385. return false;
  386. }
  387. Instruction* base_type =
  388. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  389. // Unpack the optional layer of arraying.
  390. if (base_type->opcode() == spv::Op::OpTypeArray ||
  391. base_type->opcode() == spv::Op::OpTypeRuntimeArray) {
  392. base_type = context()->get_def_use_mgr()->GetDef(
  393. base_type->GetSingleWordInOperand(0));
  394. }
  395. if (base_type->opcode() != spv::Op::OpTypeStruct) {
  396. return false;
  397. }
  398. bool is_block = false;
  399. context()->get_decoration_mgr()->ForEachDecoration(
  400. base_type->result_id(), uint32_t(spv::Decoration::Block),
  401. [&is_block](const Instruction&) { is_block = true; });
  402. return is_block;
  403. }
  404. bool Instruction::IsReadOnlyPointerShaders() const {
  405. if (type_id() == 0) {
  406. return false;
  407. }
  408. Instruction* type_def = context()->get_def_use_mgr()->GetDef(type_id());
  409. if (type_def->opcode() != spv::Op::OpTypePointer) {
  410. return false;
  411. }
  412. spv::StorageClass storage_class = spv::StorageClass(
  413. type_def->GetSingleWordInOperand(kPointerTypeStorageClassIndex));
  414. switch (storage_class) {
  415. case spv::StorageClass::UniformConstant:
  416. if (!type_def->IsVulkanStorageImage() &&
  417. !type_def->IsVulkanStorageTexelBuffer()) {
  418. return true;
  419. }
  420. break;
  421. case spv::StorageClass::Uniform:
  422. if (!type_def->IsVulkanStorageBuffer()) {
  423. return true;
  424. }
  425. break;
  426. case spv::StorageClass::PushConstant:
  427. case spv::StorageClass::Input:
  428. return true;
  429. default:
  430. break;
  431. }
  432. bool is_nonwritable = false;
  433. context()->get_decoration_mgr()->ForEachDecoration(
  434. result_id(), uint32_t(spv::Decoration::NonWritable),
  435. [&is_nonwritable](const Instruction&) { is_nonwritable = true; });
  436. return is_nonwritable;
  437. }
  438. bool Instruction::IsReadOnlyPointerKernel() const {
  439. if (type_id() == 0) {
  440. return false;
  441. }
  442. Instruction* type_def = context()->get_def_use_mgr()->GetDef(type_id());
  443. if (type_def->opcode() != spv::Op::OpTypePointer) {
  444. return false;
  445. }
  446. spv::StorageClass storage_class = spv::StorageClass(
  447. type_def->GetSingleWordInOperand(kPointerTypeStorageClassIndex));
  448. return storage_class == spv::StorageClass::UniformConstant;
  449. }
  450. void Instruction::UpdateLexicalScope(uint32_t scope) {
  451. dbg_scope_.SetLexicalScope(scope);
  452. for (auto& i : dbg_line_insts_) {
  453. i.dbg_scope_.SetLexicalScope(scope);
  454. }
  455. if (!IsLineInst() &&
  456. context()->AreAnalysesValid(IRContext::kAnalysisDebugInfo)) {
  457. context()->get_debug_info_mgr()->AnalyzeDebugInst(this);
  458. }
  459. }
  460. void Instruction::UpdateDebugInlinedAt(uint32_t new_inlined_at) {
  461. dbg_scope_.SetInlinedAt(new_inlined_at);
  462. for (auto& i : dbg_line_insts_) {
  463. i.dbg_scope_.SetInlinedAt(new_inlined_at);
  464. }
  465. if (!IsLineInst() &&
  466. context()->AreAnalysesValid(IRContext::kAnalysisDebugInfo)) {
  467. context()->get_debug_info_mgr()->AnalyzeDebugInst(this);
  468. }
  469. }
  470. void Instruction::ClearDbgLineInsts() {
  471. if (context()->AreAnalysesValid(IRContext::kAnalysisDefUse)) {
  472. auto def_use_mgr = context()->get_def_use_mgr();
  473. for (auto& l_inst : dbg_line_insts_) def_use_mgr->ClearInst(&l_inst);
  474. }
  475. clear_dbg_line_insts();
  476. }
  477. void Instruction::UpdateDebugInfoFrom(const Instruction* from) {
  478. if (from == nullptr) return;
  479. ClearDbgLineInsts();
  480. if (!from->dbg_line_insts().empty())
  481. AddDebugLine(&from->dbg_line_insts().back());
  482. SetDebugScope(from->GetDebugScope());
  483. if (!IsLineInst() &&
  484. context()->AreAnalysesValid(IRContext::kAnalysisDebugInfo)) {
  485. context()->get_debug_info_mgr()->AnalyzeDebugInst(this);
  486. }
  487. }
  488. void Instruction::AddDebugLine(const Instruction* inst) {
  489. dbg_line_insts_.push_back(*inst);
  490. dbg_line_insts_.back().unique_id_ = context()->TakeNextUniqueId();
  491. if (inst->IsDebugLineInst())
  492. dbg_line_insts_.back().SetResultId(context_->TakeNextId());
  493. if (context()->AreAnalysesValid(IRContext::kAnalysisDefUse))
  494. context()->get_def_use_mgr()->AnalyzeInstDefUse(&dbg_line_insts_.back());
  495. }
  496. bool Instruction::IsDebugLineInst() const {
  497. NonSemanticShaderDebugInfo100Instructions ext_opt = GetShader100DebugOpcode();
  498. return ((ext_opt == NonSemanticShaderDebugInfo100DebugLine) ||
  499. (ext_opt == NonSemanticShaderDebugInfo100DebugNoLine));
  500. }
  501. bool Instruction::IsLineInst() const { return IsLine() || IsNoLine(); }
  502. bool Instruction::IsLine() const {
  503. if (opcode() == spv::Op::OpLine) return true;
  504. NonSemanticShaderDebugInfo100Instructions ext_opt = GetShader100DebugOpcode();
  505. return ext_opt == NonSemanticShaderDebugInfo100DebugLine;
  506. }
  507. bool Instruction::IsNoLine() const {
  508. if (opcode() == spv::Op::OpNoLine) return true;
  509. NonSemanticShaderDebugInfo100Instructions ext_opt = GetShader100DebugOpcode();
  510. return ext_opt == NonSemanticShaderDebugInfo100DebugNoLine;
  511. }
  512. Instruction* Instruction::InsertBefore(std::unique_ptr<Instruction>&& inst) {
  513. inst.get()->InsertBefore(this);
  514. return inst.release();
  515. }
  516. Instruction* Instruction::InsertBefore(
  517. std::vector<std::unique_ptr<Instruction>>&& list) {
  518. Instruction* first_node = list.front().get();
  519. for (auto& inst : list) {
  520. inst.release()->InsertBefore(this);
  521. }
  522. list.clear();
  523. return first_node;
  524. }
  525. bool Instruction::IsValidBasePointer() const {
  526. uint32_t tid = type_id();
  527. if (tid == 0) {
  528. return false;
  529. }
  530. Instruction* type = context()->get_def_use_mgr()->GetDef(tid);
  531. if (type->opcode() != spv::Op::OpTypePointer) {
  532. return false;
  533. }
  534. auto feature_mgr = context()->get_feature_mgr();
  535. if (feature_mgr->HasCapability(spv::Capability::Addresses)) {
  536. // TODO: The rules here could be more restrictive.
  537. return true;
  538. }
  539. if (opcode() == spv::Op::OpVariable ||
  540. opcode() == spv::Op::OpFunctionParameter) {
  541. return true;
  542. }
  543. // With variable pointers, there are more valid base pointer objects.
  544. // Variable pointers implicitly declares Variable pointers storage buffer.
  545. spv::StorageClass storage_class =
  546. static_cast<spv::StorageClass>(type->GetSingleWordInOperand(0));
  547. if ((feature_mgr->HasCapability(
  548. spv::Capability::VariablePointersStorageBuffer) &&
  549. storage_class == spv::StorageClass::StorageBuffer) ||
  550. (feature_mgr->HasCapability(spv::Capability::VariablePointers) &&
  551. storage_class == spv::StorageClass::Workgroup)) {
  552. switch (opcode()) {
  553. case spv::Op::OpPhi:
  554. case spv::Op::OpSelect:
  555. case spv::Op::OpFunctionCall:
  556. case spv::Op::OpConstantNull:
  557. return true;
  558. default:
  559. break;
  560. }
  561. }
  562. uint32_t pointee_type_id = type->GetSingleWordInOperand(1);
  563. Instruction* pointee_type_inst =
  564. context()->get_def_use_mgr()->GetDef(pointee_type_id);
  565. if (pointee_type_inst->IsOpaqueType()) {
  566. return true;
  567. }
  568. return false;
  569. }
  570. OpenCLDebugInfo100Instructions Instruction::GetOpenCL100DebugOpcode() const {
  571. if (opcode() != spv::Op::OpExtInst) {
  572. return OpenCLDebugInfo100InstructionsMax;
  573. }
  574. if (!context()->get_feature_mgr()->GetExtInstImportId_OpenCL100DebugInfo()) {
  575. return OpenCLDebugInfo100InstructionsMax;
  576. }
  577. if (GetSingleWordInOperand(kExtInstSetIdInIdx) !=
  578. context()->get_feature_mgr()->GetExtInstImportId_OpenCL100DebugInfo()) {
  579. return OpenCLDebugInfo100InstructionsMax;
  580. }
  581. return OpenCLDebugInfo100Instructions(
  582. GetSingleWordInOperand(kExtInstInstructionInIdx));
  583. }
  584. NonSemanticShaderDebugInfo100Instructions Instruction::GetShader100DebugOpcode()
  585. const {
  586. if (opcode() != spv::Op::OpExtInst) {
  587. return NonSemanticShaderDebugInfo100InstructionsMax;
  588. }
  589. if (!context()->get_feature_mgr()->GetExtInstImportId_Shader100DebugInfo()) {
  590. return NonSemanticShaderDebugInfo100InstructionsMax;
  591. }
  592. if (GetSingleWordInOperand(kExtInstSetIdInIdx) !=
  593. context()->get_feature_mgr()->GetExtInstImportId_Shader100DebugInfo()) {
  594. return NonSemanticShaderDebugInfo100InstructionsMax;
  595. }
  596. uint32_t opcode = GetSingleWordInOperand(kExtInstInstructionInIdx);
  597. if (opcode >= NonSemanticShaderDebugInfo100InstructionsMax) {
  598. return NonSemanticShaderDebugInfo100InstructionsMax;
  599. }
  600. return NonSemanticShaderDebugInfo100Instructions(opcode);
  601. }
  602. CommonDebugInfoInstructions Instruction::GetCommonDebugOpcode() const {
  603. if (opcode() != spv::Op::OpExtInst) {
  604. return CommonDebugInfoInstructionsMax;
  605. }
  606. const uint32_t opencl_set_id =
  607. context()->get_feature_mgr()->GetExtInstImportId_OpenCL100DebugInfo();
  608. const uint32_t shader_set_id =
  609. context()->get_feature_mgr()->GetExtInstImportId_Shader100DebugInfo();
  610. if (!opencl_set_id && !shader_set_id) {
  611. return CommonDebugInfoInstructionsMax;
  612. }
  613. const uint32_t used_set_id = GetSingleWordInOperand(kExtInstSetIdInIdx);
  614. if (used_set_id != opencl_set_id && used_set_id != shader_set_id) {
  615. return CommonDebugInfoInstructionsMax;
  616. }
  617. return CommonDebugInfoInstructions(
  618. GetSingleWordInOperand(kExtInstInstructionInIdx));
  619. }
  620. bool Instruction::IsValidBaseImage() const {
  621. uint32_t tid = type_id();
  622. if (tid == 0) {
  623. return false;
  624. }
  625. Instruction* type = context()->get_def_use_mgr()->GetDef(tid);
  626. return (type->opcode() == spv::Op::OpTypeImage ||
  627. type->opcode() == spv::Op::OpTypeSampledImage);
  628. }
  629. bool Instruction::IsOpaqueType() const {
  630. if (opcode() == spv::Op::OpTypeStruct) {
  631. bool is_opaque = false;
  632. ForEachInOperand([&is_opaque, this](const uint32_t* op_id) {
  633. Instruction* type_inst = context()->get_def_use_mgr()->GetDef(*op_id);
  634. is_opaque |= type_inst->IsOpaqueType();
  635. });
  636. return is_opaque;
  637. } else if (opcode() == spv::Op::OpTypeArray) {
  638. uint32_t sub_type_id = GetSingleWordInOperand(0);
  639. Instruction* sub_type_inst =
  640. context()->get_def_use_mgr()->GetDef(sub_type_id);
  641. return sub_type_inst->IsOpaqueType();
  642. } else {
  643. return opcode() == spv::Op::OpTypeRuntimeArray ||
  644. spvOpcodeIsBaseOpaqueType(opcode());
  645. }
  646. }
  647. bool Instruction::IsFoldable() const {
  648. return IsFoldableByFoldScalar() ||
  649. context()->get_instruction_folder().HasConstFoldingRule(this);
  650. }
  651. bool Instruction::IsFoldableByFoldScalar() const {
  652. const InstructionFolder& folder = context()->get_instruction_folder();
  653. if (!folder.IsFoldableOpcode(opcode())) {
  654. return false;
  655. }
  656. Instruction* type = context()->get_def_use_mgr()->GetDef(type_id());
  657. if (!folder.IsFoldableType(type)) {
  658. return false;
  659. }
  660. // Even if the type of the instruction is foldable, its operands may not be
  661. // foldable (e.g., comparisons of 64bit types). Check that all operand types
  662. // are foldable before accepting the instruction.
  663. return WhileEachInOperand([&folder, this](const uint32_t* op_id) {
  664. Instruction* def_inst = context()->get_def_use_mgr()->GetDef(*op_id);
  665. Instruction* def_inst_type =
  666. context()->get_def_use_mgr()->GetDef(def_inst->type_id());
  667. return folder.IsFoldableType(def_inst_type);
  668. });
  669. }
  670. bool Instruction::IsFloatingPointFoldingAllowed() const {
  671. // TODO: Add the rules for kernels. For now it will be pessimistic.
  672. // For now, do not support capabilities introduced by SPV_KHR_float_controls.
  673. if (!context_->get_feature_mgr()->HasCapability(spv::Capability::Shader) ||
  674. context_->get_feature_mgr()->HasCapability(
  675. spv::Capability::DenormPreserve) ||
  676. context_->get_feature_mgr()->HasCapability(
  677. spv::Capability::DenormFlushToZero) ||
  678. context_->get_feature_mgr()->HasCapability(
  679. spv::Capability::SignedZeroInfNanPreserve) ||
  680. context_->get_feature_mgr()->HasCapability(
  681. spv::Capability::RoundingModeRTZ) ||
  682. context_->get_feature_mgr()->HasCapability(
  683. spv::Capability::RoundingModeRTE)) {
  684. return false;
  685. }
  686. bool is_nocontract = false;
  687. context_->get_decoration_mgr()->WhileEachDecoration(
  688. result_id(), uint32_t(spv::Decoration::NoContraction),
  689. [&is_nocontract](const Instruction&) {
  690. is_nocontract = true;
  691. return false;
  692. });
  693. return !is_nocontract;
  694. }
  695. std::string Instruction::PrettyPrint(uint32_t options) const {
  696. // Convert the module to binary.
  697. std::vector<uint32_t> module_binary;
  698. context()->module()->ToBinary(&module_binary, /* skip_nop = */ false);
  699. // Convert the instruction to binary. This is used to identify the correct
  700. // stream of words to output from the module.
  701. std::vector<uint32_t> inst_binary;
  702. ToBinaryWithoutAttachedDebugInsts(&inst_binary);
  703. // Do not generate a header.
  704. return spvInstructionBinaryToText(
  705. context()->grammar().target_env(), inst_binary.data(), inst_binary.size(),
  706. module_binary.data(), module_binary.size(),
  707. options | SPV_BINARY_TO_TEXT_OPTION_NO_HEADER);
  708. }
  709. std::ostream& operator<<(std::ostream& str, const Instruction& inst) {
  710. str << inst.PrettyPrint();
  711. return str;
  712. }
  713. void Instruction::Dump() const {
  714. std::cerr << "Instruction #" << unique_id() << "\n" << *this << "\n";
  715. }
  716. bool Instruction::IsOpcodeCodeMotionSafe() const {
  717. switch (opcode_) {
  718. case spv::Op::OpNop:
  719. case spv::Op::OpUndef:
  720. case spv::Op::OpLoad:
  721. case spv::Op::OpAccessChain:
  722. case spv::Op::OpInBoundsAccessChain:
  723. case spv::Op::OpArrayLength:
  724. case spv::Op::OpVectorExtractDynamic:
  725. case spv::Op::OpVectorInsertDynamic:
  726. case spv::Op::OpVectorShuffle:
  727. case spv::Op::OpCompositeConstruct:
  728. case spv::Op::OpCompositeExtract:
  729. case spv::Op::OpCompositeInsert:
  730. case spv::Op::OpCopyObject:
  731. case spv::Op::OpTranspose:
  732. case spv::Op::OpConvertFToU:
  733. case spv::Op::OpConvertFToS:
  734. case spv::Op::OpConvertSToF:
  735. case spv::Op::OpConvertUToF:
  736. case spv::Op::OpUConvert:
  737. case spv::Op::OpSConvert:
  738. case spv::Op::OpFConvert:
  739. case spv::Op::OpQuantizeToF16:
  740. case spv::Op::OpBitcast:
  741. case spv::Op::OpSNegate:
  742. case spv::Op::OpFNegate:
  743. case spv::Op::OpIAdd:
  744. case spv::Op::OpFAdd:
  745. case spv::Op::OpISub:
  746. case spv::Op::OpFSub:
  747. case spv::Op::OpIMul:
  748. case spv::Op::OpFMul:
  749. case spv::Op::OpUDiv:
  750. case spv::Op::OpSDiv:
  751. case spv::Op::OpFDiv:
  752. case spv::Op::OpUMod:
  753. case spv::Op::OpSRem:
  754. case spv::Op::OpSMod:
  755. case spv::Op::OpFRem:
  756. case spv::Op::OpFMod:
  757. case spv::Op::OpVectorTimesScalar:
  758. case spv::Op::OpMatrixTimesScalar:
  759. case spv::Op::OpVectorTimesMatrix:
  760. case spv::Op::OpMatrixTimesVector:
  761. case spv::Op::OpMatrixTimesMatrix:
  762. case spv::Op::OpOuterProduct:
  763. case spv::Op::OpDot:
  764. case spv::Op::OpIAddCarry:
  765. case spv::Op::OpISubBorrow:
  766. case spv::Op::OpUMulExtended:
  767. case spv::Op::OpSMulExtended:
  768. case spv::Op::OpAny:
  769. case spv::Op::OpAll:
  770. case spv::Op::OpIsNan:
  771. case spv::Op::OpIsInf:
  772. case spv::Op::OpLogicalEqual:
  773. case spv::Op::OpLogicalNotEqual:
  774. case spv::Op::OpLogicalOr:
  775. case spv::Op::OpLogicalAnd:
  776. case spv::Op::OpLogicalNot:
  777. case spv::Op::OpSelect:
  778. case spv::Op::OpIEqual:
  779. case spv::Op::OpINotEqual:
  780. case spv::Op::OpUGreaterThan:
  781. case spv::Op::OpSGreaterThan:
  782. case spv::Op::OpUGreaterThanEqual:
  783. case spv::Op::OpSGreaterThanEqual:
  784. case spv::Op::OpULessThan:
  785. case spv::Op::OpSLessThan:
  786. case spv::Op::OpULessThanEqual:
  787. case spv::Op::OpSLessThanEqual:
  788. case spv::Op::OpFOrdEqual:
  789. case spv::Op::OpFUnordEqual:
  790. case spv::Op::OpFOrdNotEqual:
  791. case spv::Op::OpFUnordNotEqual:
  792. case spv::Op::OpFOrdLessThan:
  793. case spv::Op::OpFUnordLessThan:
  794. case spv::Op::OpFOrdGreaterThan:
  795. case spv::Op::OpFUnordGreaterThan:
  796. case spv::Op::OpFOrdLessThanEqual:
  797. case spv::Op::OpFUnordLessThanEqual:
  798. case spv::Op::OpFOrdGreaterThanEqual:
  799. case spv::Op::OpFUnordGreaterThanEqual:
  800. case spv::Op::OpShiftRightLogical:
  801. case spv::Op::OpShiftRightArithmetic:
  802. case spv::Op::OpShiftLeftLogical:
  803. case spv::Op::OpBitwiseOr:
  804. case spv::Op::OpBitwiseXor:
  805. case spv::Op::OpBitwiseAnd:
  806. case spv::Op::OpNot:
  807. case spv::Op::OpBitFieldInsert:
  808. case spv::Op::OpBitFieldSExtract:
  809. case spv::Op::OpBitFieldUExtract:
  810. case spv::Op::OpBitReverse:
  811. case spv::Op::OpBitCount:
  812. case spv::Op::OpSizeOf:
  813. return true;
  814. default:
  815. return false;
  816. }
  817. }
  818. bool Instruction::IsScalarizable() const {
  819. if (spvOpcodeIsScalarizable(opcode())) {
  820. return true;
  821. }
  822. if (opcode() == spv::Op::OpExtInst) {
  823. uint32_t instSetId =
  824. context()->get_feature_mgr()->GetExtInstImportId_GLSLstd450();
  825. if (GetSingleWordInOperand(kExtInstSetIdInIdx) == instSetId) {
  826. switch (GetSingleWordInOperand(kExtInstInstructionInIdx)) {
  827. case GLSLstd450Round:
  828. case GLSLstd450RoundEven:
  829. case GLSLstd450Trunc:
  830. case GLSLstd450FAbs:
  831. case GLSLstd450SAbs:
  832. case GLSLstd450FSign:
  833. case GLSLstd450SSign:
  834. case GLSLstd450Floor:
  835. case GLSLstd450Ceil:
  836. case GLSLstd450Fract:
  837. case GLSLstd450Radians:
  838. case GLSLstd450Degrees:
  839. case GLSLstd450Sin:
  840. case GLSLstd450Cos:
  841. case GLSLstd450Tan:
  842. case GLSLstd450Asin:
  843. case GLSLstd450Acos:
  844. case GLSLstd450Atan:
  845. case GLSLstd450Sinh:
  846. case GLSLstd450Cosh:
  847. case GLSLstd450Tanh:
  848. case GLSLstd450Asinh:
  849. case GLSLstd450Acosh:
  850. case GLSLstd450Atanh:
  851. case GLSLstd450Atan2:
  852. case GLSLstd450Pow:
  853. case GLSLstd450Exp:
  854. case GLSLstd450Log:
  855. case GLSLstd450Exp2:
  856. case GLSLstd450Log2:
  857. case GLSLstd450Sqrt:
  858. case GLSLstd450InverseSqrt:
  859. case GLSLstd450Modf:
  860. case GLSLstd450FMin:
  861. case GLSLstd450UMin:
  862. case GLSLstd450SMin:
  863. case GLSLstd450FMax:
  864. case GLSLstd450UMax:
  865. case GLSLstd450SMax:
  866. case GLSLstd450FClamp:
  867. case GLSLstd450UClamp:
  868. case GLSLstd450SClamp:
  869. case GLSLstd450FMix:
  870. case GLSLstd450Step:
  871. case GLSLstd450SmoothStep:
  872. case GLSLstd450Fma:
  873. case GLSLstd450Frexp:
  874. case GLSLstd450Ldexp:
  875. case GLSLstd450FindILsb:
  876. case GLSLstd450FindSMsb:
  877. case GLSLstd450FindUMsb:
  878. case GLSLstd450NMin:
  879. case GLSLstd450NMax:
  880. case GLSLstd450NClamp:
  881. return true;
  882. default:
  883. return false;
  884. }
  885. }
  886. }
  887. return false;
  888. }
  889. bool Instruction::IsOpcodeSafeToDelete() const {
  890. if (context()->IsCombinatorInstruction(this)) {
  891. return true;
  892. }
  893. switch (opcode()) {
  894. case spv::Op::OpDPdx:
  895. case spv::Op::OpDPdy:
  896. case spv::Op::OpFwidth:
  897. case spv::Op::OpDPdxFine:
  898. case spv::Op::OpDPdyFine:
  899. case spv::Op::OpFwidthFine:
  900. case spv::Op::OpDPdxCoarse:
  901. case spv::Op::OpDPdyCoarse:
  902. case spv::Op::OpFwidthCoarse:
  903. case spv::Op::OpImageQueryLod:
  904. return true;
  905. default:
  906. return false;
  907. }
  908. }
  909. bool Instruction::IsNonSemanticInstruction() const {
  910. if (!HasResultId()) return false;
  911. if (opcode() != spv::Op::OpExtInst) return false;
  912. auto import_inst =
  913. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(0));
  914. std::string import_name = import_inst->GetInOperand(0).AsString();
  915. return import_name.find("NonSemantic.") == 0;
  916. }
  917. void DebugScope::ToBinary(uint32_t type_id, uint32_t result_id,
  918. uint32_t ext_set,
  919. std::vector<uint32_t>* binary) const {
  920. uint32_t num_words = kDebugScopeNumWords;
  921. CommonDebugInfoInstructions dbg_opcode = CommonDebugInfoDebugScope;
  922. if (GetLexicalScope() == kNoDebugScope) {
  923. num_words = kDebugNoScopeNumWords;
  924. dbg_opcode = CommonDebugInfoDebugNoScope;
  925. } else if (GetInlinedAt() == kNoInlinedAt) {
  926. num_words = kDebugScopeNumWordsWithoutInlinedAt;
  927. }
  928. std::vector<uint32_t> operands = {
  929. (num_words << 16) | static_cast<uint16_t>(spv::Op::OpExtInst),
  930. type_id,
  931. result_id,
  932. ext_set,
  933. static_cast<uint32_t>(dbg_opcode),
  934. };
  935. binary->insert(binary->end(), operands.begin(), operands.end());
  936. if (GetLexicalScope() != kNoDebugScope) {
  937. binary->push_back(GetLexicalScope());
  938. if (GetInlinedAt() != kNoInlinedAt) binary->push_back(GetInlinedAt());
  939. }
  940. }
  941. } // namespace opt
  942. } // namespace spvtools