instruction.cpp 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  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() || IsFoldableByFoldVector() ||
  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.IsFoldableScalarType(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.IsFoldableScalarType(def_inst_type);
  668. });
  669. }
  670. bool Instruction::IsFoldableByFoldVector() const {
  671. const InstructionFolder& folder = context()->get_instruction_folder();
  672. if (!folder.IsFoldableOpcode(opcode())) {
  673. return false;
  674. }
  675. Instruction* type = context()->get_def_use_mgr()->GetDef(type_id());
  676. if (!folder.IsFoldableVectorType(type)) {
  677. return false;
  678. }
  679. // Even if the type of the instruction is foldable, its operands may not be
  680. // foldable (e.g., comparisons of 64bit types). Check that all operand types
  681. // are foldable before accepting the instruction.
  682. return WhileEachInOperand([&folder, this](const uint32_t* op_id) {
  683. Instruction* def_inst = context()->get_def_use_mgr()->GetDef(*op_id);
  684. Instruction* def_inst_type =
  685. context()->get_def_use_mgr()->GetDef(def_inst->type_id());
  686. return folder.IsFoldableVectorType(def_inst_type);
  687. });
  688. }
  689. bool Instruction::IsFloatingPointFoldingAllowed() const {
  690. // TODO: Add the rules for kernels. For now it will be pessimistic.
  691. // For now, do not support capabilities introduced by SPV_KHR_float_controls.
  692. if (!context_->get_feature_mgr()->HasCapability(spv::Capability::Shader) ||
  693. context_->get_feature_mgr()->HasCapability(
  694. spv::Capability::DenormPreserve) ||
  695. context_->get_feature_mgr()->HasCapability(
  696. spv::Capability::DenormFlushToZero) ||
  697. context_->get_feature_mgr()->HasCapability(
  698. spv::Capability::SignedZeroInfNanPreserve) ||
  699. context_->get_feature_mgr()->HasCapability(
  700. spv::Capability::RoundingModeRTZ) ||
  701. context_->get_feature_mgr()->HasCapability(
  702. spv::Capability::RoundingModeRTE)) {
  703. return false;
  704. }
  705. bool is_nocontract = false;
  706. context_->get_decoration_mgr()->WhileEachDecoration(
  707. result_id(), uint32_t(spv::Decoration::NoContraction),
  708. [&is_nocontract](const Instruction&) {
  709. is_nocontract = true;
  710. return false;
  711. });
  712. return !is_nocontract;
  713. }
  714. std::string Instruction::PrettyPrint(uint32_t options) const {
  715. // Convert the module to binary.
  716. std::vector<uint32_t> module_binary;
  717. context()->module()->ToBinary(&module_binary, /* skip_nop = */ false);
  718. // Convert the instruction to binary. This is used to identify the correct
  719. // stream of words to output from the module.
  720. std::vector<uint32_t> inst_binary;
  721. ToBinaryWithoutAttachedDebugInsts(&inst_binary);
  722. // Do not generate a header.
  723. return spvInstructionBinaryToText(
  724. context()->grammar().target_env(), inst_binary.data(), inst_binary.size(),
  725. module_binary.data(), module_binary.size(),
  726. options | SPV_BINARY_TO_TEXT_OPTION_NO_HEADER);
  727. }
  728. std::ostream& operator<<(std::ostream& str, const Instruction& inst) {
  729. str << inst.PrettyPrint();
  730. return str;
  731. }
  732. void Instruction::Dump() const {
  733. std::cerr << "Instruction #" << unique_id() << "\n" << *this << "\n";
  734. }
  735. bool Instruction::IsOpcodeCodeMotionSafe() const {
  736. switch (opcode_) {
  737. case spv::Op::OpNop:
  738. case spv::Op::OpUndef:
  739. case spv::Op::OpLoad:
  740. case spv::Op::OpAccessChain:
  741. case spv::Op::OpInBoundsAccessChain:
  742. case spv::Op::OpArrayLength:
  743. case spv::Op::OpVectorExtractDynamic:
  744. case spv::Op::OpVectorInsertDynamic:
  745. case spv::Op::OpVectorShuffle:
  746. case spv::Op::OpCompositeConstruct:
  747. case spv::Op::OpCompositeExtract:
  748. case spv::Op::OpCompositeInsert:
  749. case spv::Op::OpCopyObject:
  750. case spv::Op::OpTranspose:
  751. case spv::Op::OpConvertFToU:
  752. case spv::Op::OpConvertFToS:
  753. case spv::Op::OpConvertSToF:
  754. case spv::Op::OpConvertUToF:
  755. case spv::Op::OpUConvert:
  756. case spv::Op::OpSConvert:
  757. case spv::Op::OpFConvert:
  758. case spv::Op::OpQuantizeToF16:
  759. case spv::Op::OpBitcast:
  760. case spv::Op::OpSNegate:
  761. case spv::Op::OpFNegate:
  762. case spv::Op::OpIAdd:
  763. case spv::Op::OpFAdd:
  764. case spv::Op::OpISub:
  765. case spv::Op::OpFSub:
  766. case spv::Op::OpIMul:
  767. case spv::Op::OpFMul:
  768. case spv::Op::OpUDiv:
  769. case spv::Op::OpSDiv:
  770. case spv::Op::OpFDiv:
  771. case spv::Op::OpUMod:
  772. case spv::Op::OpSRem:
  773. case spv::Op::OpSMod:
  774. case spv::Op::OpFRem:
  775. case spv::Op::OpFMod:
  776. case spv::Op::OpVectorTimesScalar:
  777. case spv::Op::OpMatrixTimesScalar:
  778. case spv::Op::OpVectorTimesMatrix:
  779. case spv::Op::OpMatrixTimesVector:
  780. case spv::Op::OpMatrixTimesMatrix:
  781. case spv::Op::OpOuterProduct:
  782. case spv::Op::OpDot:
  783. case spv::Op::OpIAddCarry:
  784. case spv::Op::OpISubBorrow:
  785. case spv::Op::OpUMulExtended:
  786. case spv::Op::OpSMulExtended:
  787. case spv::Op::OpAny:
  788. case spv::Op::OpAll:
  789. case spv::Op::OpIsNan:
  790. case spv::Op::OpIsInf:
  791. case spv::Op::OpLogicalEqual:
  792. case spv::Op::OpLogicalNotEqual:
  793. case spv::Op::OpLogicalOr:
  794. case spv::Op::OpLogicalAnd:
  795. case spv::Op::OpLogicalNot:
  796. case spv::Op::OpSelect:
  797. case spv::Op::OpIEqual:
  798. case spv::Op::OpINotEqual:
  799. case spv::Op::OpUGreaterThan:
  800. case spv::Op::OpSGreaterThan:
  801. case spv::Op::OpUGreaterThanEqual:
  802. case spv::Op::OpSGreaterThanEqual:
  803. case spv::Op::OpULessThan:
  804. case spv::Op::OpSLessThan:
  805. case spv::Op::OpULessThanEqual:
  806. case spv::Op::OpSLessThanEqual:
  807. case spv::Op::OpFOrdEqual:
  808. case spv::Op::OpFUnordEqual:
  809. case spv::Op::OpFOrdNotEqual:
  810. case spv::Op::OpFUnordNotEqual:
  811. case spv::Op::OpFOrdLessThan:
  812. case spv::Op::OpFUnordLessThan:
  813. case spv::Op::OpFOrdGreaterThan:
  814. case spv::Op::OpFUnordGreaterThan:
  815. case spv::Op::OpFOrdLessThanEqual:
  816. case spv::Op::OpFUnordLessThanEqual:
  817. case spv::Op::OpFOrdGreaterThanEqual:
  818. case spv::Op::OpFUnordGreaterThanEqual:
  819. case spv::Op::OpShiftRightLogical:
  820. case spv::Op::OpShiftRightArithmetic:
  821. case spv::Op::OpShiftLeftLogical:
  822. case spv::Op::OpBitwiseOr:
  823. case spv::Op::OpBitwiseXor:
  824. case spv::Op::OpBitwiseAnd:
  825. case spv::Op::OpNot:
  826. case spv::Op::OpBitFieldInsert:
  827. case spv::Op::OpBitFieldSExtract:
  828. case spv::Op::OpBitFieldUExtract:
  829. case spv::Op::OpBitReverse:
  830. case spv::Op::OpBitCount:
  831. case spv::Op::OpSizeOf:
  832. return true;
  833. default:
  834. return false;
  835. }
  836. }
  837. bool Instruction::IsScalarizable() const {
  838. if (spvOpcodeIsScalarizable(opcode())) {
  839. return true;
  840. }
  841. if (opcode() == spv::Op::OpExtInst) {
  842. uint32_t instSetId =
  843. context()->get_feature_mgr()->GetExtInstImportId_GLSLstd450();
  844. if (GetSingleWordInOperand(kExtInstSetIdInIdx) == instSetId) {
  845. switch (GetSingleWordInOperand(kExtInstInstructionInIdx)) {
  846. case GLSLstd450Round:
  847. case GLSLstd450RoundEven:
  848. case GLSLstd450Trunc:
  849. case GLSLstd450FAbs:
  850. case GLSLstd450SAbs:
  851. case GLSLstd450FSign:
  852. case GLSLstd450SSign:
  853. case GLSLstd450Floor:
  854. case GLSLstd450Ceil:
  855. case GLSLstd450Fract:
  856. case GLSLstd450Radians:
  857. case GLSLstd450Degrees:
  858. case GLSLstd450Sin:
  859. case GLSLstd450Cos:
  860. case GLSLstd450Tan:
  861. case GLSLstd450Asin:
  862. case GLSLstd450Acos:
  863. case GLSLstd450Atan:
  864. case GLSLstd450Sinh:
  865. case GLSLstd450Cosh:
  866. case GLSLstd450Tanh:
  867. case GLSLstd450Asinh:
  868. case GLSLstd450Acosh:
  869. case GLSLstd450Atanh:
  870. case GLSLstd450Atan2:
  871. case GLSLstd450Pow:
  872. case GLSLstd450Exp:
  873. case GLSLstd450Log:
  874. case GLSLstd450Exp2:
  875. case GLSLstd450Log2:
  876. case GLSLstd450Sqrt:
  877. case GLSLstd450InverseSqrt:
  878. case GLSLstd450Modf:
  879. case GLSLstd450FMin:
  880. case GLSLstd450UMin:
  881. case GLSLstd450SMin:
  882. case GLSLstd450FMax:
  883. case GLSLstd450UMax:
  884. case GLSLstd450SMax:
  885. case GLSLstd450FClamp:
  886. case GLSLstd450UClamp:
  887. case GLSLstd450SClamp:
  888. case GLSLstd450FMix:
  889. case GLSLstd450Step:
  890. case GLSLstd450SmoothStep:
  891. case GLSLstd450Fma:
  892. case GLSLstd450Frexp:
  893. case GLSLstd450Ldexp:
  894. case GLSLstd450FindILsb:
  895. case GLSLstd450FindSMsb:
  896. case GLSLstd450FindUMsb:
  897. case GLSLstd450NMin:
  898. case GLSLstd450NMax:
  899. case GLSLstd450NClamp:
  900. return true;
  901. default:
  902. return false;
  903. }
  904. }
  905. }
  906. return false;
  907. }
  908. bool Instruction::IsOpcodeSafeToDelete() const {
  909. if (context()->IsCombinatorInstruction(this)) {
  910. return true;
  911. }
  912. switch (opcode()) {
  913. case spv::Op::OpDPdx:
  914. case spv::Op::OpDPdy:
  915. case spv::Op::OpFwidth:
  916. case spv::Op::OpDPdxFine:
  917. case spv::Op::OpDPdyFine:
  918. case spv::Op::OpFwidthFine:
  919. case spv::Op::OpDPdxCoarse:
  920. case spv::Op::OpDPdyCoarse:
  921. case spv::Op::OpFwidthCoarse:
  922. case spv::Op::OpImageQueryLod:
  923. return true;
  924. default:
  925. return false;
  926. }
  927. }
  928. bool Instruction::IsNonSemanticInstruction() const {
  929. if (!HasResultId()) return false;
  930. if (opcode() != spv::Op::OpExtInst) return false;
  931. auto import_inst =
  932. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(0));
  933. std::string import_name = import_inst->GetInOperand(0).AsString();
  934. return import_name.find("NonSemantic.") == 0;
  935. }
  936. void DebugScope::ToBinary(uint32_t type_id, uint32_t result_id,
  937. uint32_t ext_set,
  938. std::vector<uint32_t>* binary) const {
  939. uint32_t num_words = kDebugScopeNumWords;
  940. CommonDebugInfoInstructions dbg_opcode = CommonDebugInfoDebugScope;
  941. if (GetLexicalScope() == kNoDebugScope) {
  942. num_words = kDebugNoScopeNumWords;
  943. dbg_opcode = CommonDebugInfoDebugNoScope;
  944. } else if (GetInlinedAt() == kNoInlinedAt) {
  945. num_words = kDebugScopeNumWordsWithoutInlinedAt;
  946. }
  947. std::vector<uint32_t> operands = {
  948. (num_words << 16) | static_cast<uint16_t>(spv::Op::OpExtInst),
  949. type_id,
  950. result_id,
  951. ext_set,
  952. static_cast<uint32_t>(dbg_opcode),
  953. };
  954. binary->insert(binary->end(), operands.begin(), operands.end());
  955. if (GetLexicalScope() != kNoDebugScope) {
  956. binary->push_back(GetLexicalScope());
  957. if (GetInlinedAt() != kNoInlinedAt) binary->push_back(GetInlinedAt());
  958. }
  959. }
  960. } // namespace opt
  961. } // namespace spvtools