SpvPostProcess.cpp 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. //
  2. // Copyright (C) 2018 Google, Inc.
  3. //
  4. // All rights reserved.
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions
  8. // are met:
  9. //
  10. // Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. //
  13. // Redistributions in binary form must reproduce the above
  14. // copyright notice, this list of conditions and the following
  15. // disclaimer in the documentation and/or other materials provided
  16. // with the distribution.
  17. //
  18. // Neither the name of 3Dlabs Inc. Ltd. nor the names of its
  19. // contributors may be used to endorse or promote products derived
  20. // from this software without specific prior written permission.
  21. //
  22. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  23. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  24. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
  25. // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
  26. // COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
  27. // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  28. // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  29. // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  30. // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  31. // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
  32. // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. // POSSIBILITY OF SUCH DAMAGE.
  34. //
  35. // Post-processing for SPIR-V IR, in internal form, not standard binary form.
  36. //
  37. #include <cassert>
  38. #include <cstdlib>
  39. #include <unordered_map>
  40. #include <unordered_set>
  41. #include <algorithm>
  42. #include "SPIRV/spvIR.h"
  43. #include "SpvBuilder.h"
  44. #include "spirv.hpp11"
  45. #include "spvUtil.h"
  46. namespace spv {
  47. #include "GLSL.std.450.h"
  48. #include "GLSL.ext.KHR.h"
  49. #include "GLSL.ext.EXT.h"
  50. #include "GLSL.ext.AMD.h"
  51. #include "GLSL.ext.NV.h"
  52. #include "GLSL.ext.ARM.h"
  53. #include "GLSL.ext.QCOM.h"
  54. }
  55. namespace spv {
  56. // Hook to visit each operand type and result type of an instruction.
  57. // Will be called multiple times for one instruction, once for each typed
  58. // operand and the result.
  59. void Builder::postProcessType(const Instruction& inst, Id typeId)
  60. {
  61. // Characterize the type being questioned
  62. Op basicTypeOp = getMostBasicTypeClass(typeId);
  63. int width = 0;
  64. if (basicTypeOp == Op::OpTypeFloat || basicTypeOp == Op::OpTypeInt)
  65. width = getScalarTypeWidth(typeId);
  66. // Do opcode-specific checks
  67. switch (inst.getOpCode()) {
  68. case Op::OpLoad:
  69. case Op::OpStore:
  70. if (basicTypeOp == Op::OpTypeStruct) {
  71. if (containsType(typeId, Op::OpTypeInt, 8))
  72. addCapability(Capability::Int8);
  73. if (containsType(typeId, Op::OpTypeInt, 16))
  74. addCapability(Capability::Int16);
  75. if (containsType(typeId, Op::OpTypeFloat, 16))
  76. addCapability(Capability::Float16);
  77. } else {
  78. StorageClass storageClass = getStorageClass(inst.getIdOperand(0));
  79. if (width == 8) {
  80. switch (storageClass) {
  81. case StorageClass::PhysicalStorageBufferEXT:
  82. case StorageClass::Uniform:
  83. case StorageClass::StorageBuffer:
  84. case StorageClass::PushConstant:
  85. break;
  86. default:
  87. addCapability(Capability::Int8);
  88. break;
  89. }
  90. } else if (width == 16) {
  91. switch (storageClass) {
  92. case StorageClass::PhysicalStorageBufferEXT:
  93. case StorageClass::Uniform:
  94. case StorageClass::StorageBuffer:
  95. case StorageClass::PushConstant:
  96. case StorageClass::Input:
  97. case StorageClass::Output:
  98. break;
  99. default:
  100. if (basicTypeOp == Op::OpTypeInt)
  101. addCapability(Capability::Int16);
  102. if (basicTypeOp == Op::OpTypeFloat)
  103. addCapability(Capability::Float16);
  104. break;
  105. }
  106. }
  107. }
  108. break;
  109. case Op::OpCopyObject:
  110. break;
  111. case Op::OpFConvert:
  112. case Op::OpSConvert:
  113. case Op::OpUConvert:
  114. // Look for any 8/16-bit storage capabilities. If there are none, assume that
  115. // the convert instruction requires the Float16/Int8/16 capability.
  116. if (containsType(typeId, Op::OpTypeFloat, 16) || containsType(typeId, Op::OpTypeInt, 16)) {
  117. bool foundStorage = false;
  118. for (auto it = capabilities.begin(); it != capabilities.end(); ++it) {
  119. spv::Capability cap = *it;
  120. if (cap == spv::Capability::StorageInputOutput16 ||
  121. cap == spv::Capability::StoragePushConstant16 ||
  122. cap == spv::Capability::StorageUniformBufferBlock16 ||
  123. cap == spv::Capability::StorageUniform16) {
  124. foundStorage = true;
  125. break;
  126. }
  127. }
  128. if (!foundStorage) {
  129. if (containsType(typeId, Op::OpTypeFloat, 16))
  130. addCapability(Capability::Float16);
  131. if (containsType(typeId, Op::OpTypeInt, 16))
  132. addCapability(Capability::Int16);
  133. }
  134. }
  135. if (containsType(typeId, Op::OpTypeInt, 8)) {
  136. bool foundStorage = false;
  137. for (auto it = capabilities.begin(); it != capabilities.end(); ++it) {
  138. spv::Capability cap = *it;
  139. if (cap == spv::Capability::StoragePushConstant8 ||
  140. cap == spv::Capability::UniformAndStorageBuffer8BitAccess ||
  141. cap == spv::Capability::StorageBuffer8BitAccess) {
  142. foundStorage = true;
  143. break;
  144. }
  145. }
  146. if (!foundStorage) {
  147. addCapability(Capability::Int8);
  148. }
  149. }
  150. break;
  151. case Op::OpExtInst:
  152. switch (inst.getImmediateOperand(1)) {
  153. case GLSLstd450Frexp:
  154. case GLSLstd450FrexpStruct:
  155. if (getSpvVersion() < spv::Spv_1_3 && containsType(typeId, Op::OpTypeInt, 16))
  156. addExtension(spv::E_SPV_AMD_gpu_shader_int16);
  157. break;
  158. case GLSLstd450InterpolateAtCentroid:
  159. case GLSLstd450InterpolateAtSample:
  160. case GLSLstd450InterpolateAtOffset:
  161. if (getSpvVersion() < spv::Spv_1_3 && containsType(typeId, Op::OpTypeFloat, 16))
  162. addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  163. break;
  164. default:
  165. break;
  166. }
  167. break;
  168. case Op::OpAccessChain:
  169. case Op::OpPtrAccessChain:
  170. if (isPointerType(typeId))
  171. break;
  172. if (basicTypeOp == Op::OpTypeInt) {
  173. if (width == 16)
  174. addCapability(Capability::Int16);
  175. else if (width == 8)
  176. addCapability(Capability::Int8);
  177. }
  178. break;
  179. default:
  180. if (basicTypeOp == Op::OpTypeInt) {
  181. if (width == 16)
  182. addCapability(Capability::Int16);
  183. else if (width == 8)
  184. addCapability(Capability::Int8);
  185. else if (width == 64)
  186. addCapability(Capability::Int64);
  187. } else if (basicTypeOp == Op::OpTypeFloat) {
  188. if (width == 16)
  189. addCapability(Capability::Float16);
  190. else if (width == 64)
  191. addCapability(Capability::Float64);
  192. }
  193. break;
  194. }
  195. }
  196. unsigned int Builder::postProcessGetLargestScalarSize(const Instruction& type)
  197. {
  198. switch (type.getOpCode()) {
  199. case Op::OpTypeBool:
  200. return 1;
  201. case Op::OpTypeInt:
  202. case Op::OpTypeFloat:
  203. return type.getImmediateOperand(0) / 8;
  204. case Op::OpTypePointer:
  205. return 8;
  206. case Op::OpTypeVector:
  207. case Op::OpTypeMatrix:
  208. case Op::OpTypeArray:
  209. case Op::OpTypeRuntimeArray: {
  210. const Instruction* elem_type = module.getInstruction(type.getIdOperand(0));
  211. return postProcessGetLargestScalarSize(*elem_type);
  212. }
  213. case Op::OpTypeStruct: {
  214. unsigned int largest = 0;
  215. for (int i = 0; i < type.getNumOperands(); ++i) {
  216. const Instruction* elem_type = module.getInstruction(type.getIdOperand(i));
  217. unsigned int elem_size = postProcessGetLargestScalarSize(*elem_type);
  218. largest = std::max(largest, elem_size);
  219. }
  220. return largest;
  221. }
  222. default:
  223. return 0;
  224. }
  225. }
  226. // Called for each instruction that resides in a block.
  227. void Builder::postProcess(Instruction& inst)
  228. {
  229. // Add capabilities based simply on the opcode.
  230. switch (inst.getOpCode()) {
  231. case Op::OpExtInst:
  232. switch (inst.getImmediateOperand(1)) {
  233. case GLSLstd450InterpolateAtCentroid:
  234. case GLSLstd450InterpolateAtSample:
  235. case GLSLstd450InterpolateAtOffset:
  236. addCapability(Capability::InterpolationFunction);
  237. break;
  238. default:
  239. break;
  240. }
  241. break;
  242. case Op::OpDPdxFine:
  243. case Op::OpDPdyFine:
  244. case Op::OpFwidthFine:
  245. case Op::OpDPdxCoarse:
  246. case Op::OpDPdyCoarse:
  247. case Op::OpFwidthCoarse:
  248. addCapability(Capability::DerivativeControl);
  249. break;
  250. case Op::OpImageQueryLod:
  251. case Op::OpImageQuerySize:
  252. case Op::OpImageQuerySizeLod:
  253. case Op::OpImageQuerySamples:
  254. case Op::OpImageQueryLevels:
  255. addCapability(Capability::ImageQuery);
  256. break;
  257. case Op::OpGroupNonUniformPartitionNV:
  258. addExtension(E_SPV_NV_shader_subgroup_partitioned);
  259. addCapability(Capability::GroupNonUniformPartitionedNV);
  260. break;
  261. case Op::OpLoad:
  262. case Op::OpStore:
  263. {
  264. // For any load/store to a PhysicalStorageBufferEXT, walk the accesschain
  265. // index list to compute the misalignment. The pre-existing alignment value
  266. // (set via Builder::AccessChain::alignment) only accounts for the base of
  267. // the reference type and any scalar component selection in the accesschain,
  268. // and this function computes the rest from the SPIR-V Offset decorations.
  269. Instruction *accessChain = module.getInstruction(inst.getIdOperand(0));
  270. if (accessChain->getOpCode() == Op::OpAccessChain) {
  271. const Instruction* base = module.getInstruction(accessChain->getIdOperand(0));
  272. // Get the type of the base of the access chain. It must be a pointer type.
  273. Id typeId = base->getTypeId();
  274. Instruction *type = module.getInstruction(typeId);
  275. assert(type->getOpCode() == Op::OpTypePointer);
  276. if (type->getImmediateOperand(0) != StorageClass::PhysicalStorageBuffer) {
  277. break;
  278. }
  279. // Get the pointee type.
  280. typeId = type->getIdOperand(1);
  281. type = module.getInstruction(typeId);
  282. // Walk the index list for the access chain. For each index, find any
  283. // misalignment that can apply when accessing the member/element via
  284. // Offset/ArrayStride/MatrixStride decorations, and bitwise OR them all
  285. // together.
  286. int alignment = 0;
  287. bool first_struct_elem = false;
  288. for (int i = 1; i < accessChain->getNumOperands(); ++i) {
  289. Instruction *idx = module.getInstruction(accessChain->getIdOperand(i));
  290. if (type->getOpCode() == Op::OpTypeStruct) {
  291. assert(idx->getOpCode() == Op::OpConstant);
  292. unsigned int c = idx->getImmediateOperand(0);
  293. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  294. if (decoration.get()->getOpCode() == Op::OpMemberDecorate &&
  295. decoration.get()->getIdOperand(0) == typeId &&
  296. decoration.get()->getImmediateOperand(1) == c &&
  297. (decoration.get()->getImmediateOperand(2) == Decoration::Offset ||
  298. decoration.get()->getImmediateOperand(2) == Decoration::MatrixStride)) {
  299. unsigned int opernad_value = decoration.get()->getImmediateOperand(3);
  300. alignment |= opernad_value;
  301. if (opernad_value == 0 &&
  302. decoration.get()->getImmediateOperand(2) == Decoration::Offset) {
  303. first_struct_elem = true;
  304. }
  305. }
  306. };
  307. std::for_each(decorations.begin(), decorations.end(), function);
  308. // get the next member type
  309. typeId = type->getIdOperand(c);
  310. type = module.getInstruction(typeId);
  311. } else if (type->getOpCode() == Op::OpTypeArray ||
  312. type->getOpCode() == Op::OpTypeRuntimeArray) {
  313. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  314. if (decoration.get()->getOpCode() == Op::OpDecorate &&
  315. decoration.get()->getIdOperand(0) == typeId &&
  316. decoration.get()->getImmediateOperand(1) == Decoration::ArrayStride) {
  317. alignment |= decoration.get()->getImmediateOperand(2);
  318. }
  319. };
  320. std::for_each(decorations.begin(), decorations.end(), function);
  321. // Get the element type
  322. typeId = type->getIdOperand(0);
  323. type = module.getInstruction(typeId);
  324. } else {
  325. // Once we get to any non-aggregate type, we're done.
  326. break;
  327. }
  328. }
  329. assert(inst.getNumOperands() >= 3);
  330. const bool is_store = inst.getOpCode() == Op::OpStore;
  331. auto const memoryAccess = (MemoryAccessMask)inst.getImmediateOperand(is_store ? 2 : 1);
  332. assert(anySet(memoryAccess, MemoryAccessMask::Aligned));
  333. static_cast<void>(memoryAccess);
  334. // Compute the index of the alignment operand.
  335. int alignmentIdx = 2;
  336. if (is_store)
  337. alignmentIdx++;
  338. // Merge new and old (mis)alignment
  339. alignment |= inst.getImmediateOperand(alignmentIdx);
  340. if (!is_store) {
  341. Instruction* inst_type = module.getInstruction(inst.getTypeId());
  342. if (inst_type->getOpCode() == Op::OpTypePointer &&
  343. inst_type->getImmediateOperand(0) == StorageClass::PhysicalStorageBuffer) {
  344. // This means we are loading a pointer which means need to ensure it is at least 8-byte aligned
  345. // See https://github.com/KhronosGroup/glslang/issues/4084
  346. // In case the alignment is currently 4, need to ensure it is 8 before grabbing the LSB
  347. alignment |= 8;
  348. alignment &= 8;
  349. }
  350. }
  351. // Pick the LSB
  352. alignment = alignment & ~(alignment & (alignment-1));
  353. // The edge case we find is when copying a struct to another struct, we never find the alignment anywhere,
  354. // so in this case, fallback to doing a full size lookup on the type
  355. if (alignment == 0 && first_struct_elem) {
  356. // Quick get the struct type back
  357. const Instruction* pointer_type = module.getInstruction(base->getTypeId());
  358. const Instruction* struct_type = module.getInstruction(pointer_type->getIdOperand(1));
  359. assert(struct_type->getOpCode() == Op::OpTypeStruct);
  360. const Instruction* elem_type = module.getInstruction(struct_type->getIdOperand(0));
  361. unsigned int largest_scalar = postProcessGetLargestScalarSize(*elem_type);
  362. if (largest_scalar != 0) {
  363. alignment = largest_scalar;
  364. } else {
  365. alignment = 16; // fallback if can't determine a godo alignment
  366. }
  367. }
  368. // update the Aligned operand
  369. assert(alignment != 0);
  370. inst.setImmediateOperand(alignmentIdx, alignment);
  371. }
  372. break;
  373. }
  374. default:
  375. break;
  376. }
  377. // Checks based on type
  378. if (inst.getTypeId() != NoType)
  379. postProcessType(inst, inst.getTypeId());
  380. for (int op = 0; op < inst.getNumOperands(); ++op) {
  381. if (inst.isIdOperand(op)) {
  382. // In blocks, these are always result ids, but we are relying on
  383. // getTypeId() to return NoType for things like OpLabel.
  384. if (getTypeId(inst.getIdOperand(op)) != NoType)
  385. postProcessType(inst, getTypeId(inst.getIdOperand(op)));
  386. }
  387. }
  388. }
  389. // comment in header
  390. void Builder::postProcessCFG()
  391. {
  392. // reachableBlocks is the set of blockss reached via control flow, or which are
  393. // unreachable continue targert or unreachable merge.
  394. std::unordered_set<const Block*> reachableBlocks;
  395. std::unordered_map<Block*, Block*> headerForUnreachableContinue;
  396. std::unordered_set<Block*> unreachableMerges;
  397. std::unordered_set<Id> unreachableDefinitions;
  398. // Collect IDs defined in unreachable blocks. For each function, label the
  399. // reachable blocks first. Then for each unreachable block, collect the
  400. // result IDs of the instructions in it.
  401. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  402. Function* f = *fi;
  403. Block* entry = f->getEntryBlock();
  404. inReadableOrder(entry,
  405. [&reachableBlocks, &unreachableMerges, &headerForUnreachableContinue]
  406. (Block* b, ReachReason why, Block* header) {
  407. reachableBlocks.insert(b);
  408. if (why == ReachDeadContinue) headerForUnreachableContinue[b] = header;
  409. if (why == ReachDeadMerge) unreachableMerges.insert(b);
  410. });
  411. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  412. Block* b = *bi;
  413. if (unreachableMerges.count(b) != 0 || headerForUnreachableContinue.count(b) != 0) {
  414. auto ii = b->getInstructions().cbegin();
  415. ++ii; // Keep potential decorations on the label.
  416. for (; ii != b->getInstructions().cend(); ++ii)
  417. unreachableDefinitions.insert(ii->get()->getResultId());
  418. } else if (reachableBlocks.count(b) == 0) {
  419. // The normal case for unreachable code. All definitions are considered dead.
  420. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ++ii)
  421. unreachableDefinitions.insert(ii->get()->getResultId());
  422. }
  423. }
  424. }
  425. // Modify unreachable merge blocks and unreachable continue targets.
  426. // Delete their contents.
  427. for (auto mergeIter = unreachableMerges.begin(); mergeIter != unreachableMerges.end(); ++mergeIter) {
  428. (*mergeIter)->rewriteAsCanonicalUnreachableMerge();
  429. }
  430. for (auto continueIter = headerForUnreachableContinue.begin();
  431. continueIter != headerForUnreachableContinue.end();
  432. ++continueIter) {
  433. Block* continue_target = continueIter->first;
  434. Block* header = continueIter->second;
  435. continue_target->rewriteAsCanonicalUnreachableContinue(header);
  436. }
  437. // Remove unneeded decorations, for unreachable instructions
  438. for (auto decorationIter = decorations.begin(); decorationIter != decorations.end();) {
  439. Id decorationId = (*decorationIter)->getIdOperand(0);
  440. if (unreachableDefinitions.count(decorationId) != 0) {
  441. decorationIter = decorations.erase(decorationIter);
  442. } else {
  443. ++decorationIter;
  444. }
  445. }
  446. }
  447. // comment in header
  448. void Builder::postProcessFeatures() {
  449. // Add per-instruction capabilities, extensions, etc.,
  450. // Look for any 8/16 bit type in physical storage buffer class, and set the
  451. // appropriate capability. This happens in createSpvVariable for other storage
  452. // classes, but there isn't always a variable for physical storage buffer.
  453. for (int t = 0; t < (int)groupedTypes[enumCast(Op::OpTypePointer)].size(); ++t) {
  454. Instruction* type = groupedTypes[enumCast(Op::OpTypePointer)][t];
  455. if (type->getImmediateOperand(0) == (unsigned)StorageClass::PhysicalStorageBufferEXT) {
  456. if (containsType(type->getIdOperand(1), Op::OpTypeInt, 8)) {
  457. addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
  458. addCapability(spv::Capability::StorageBuffer8BitAccess);
  459. }
  460. if (containsType(type->getIdOperand(1), Op::OpTypeInt, 16) ||
  461. containsType(type->getIdOperand(1), Op::OpTypeFloat, 16)) {
  462. addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
  463. addCapability(spv::Capability::StorageBuffer16BitAccess);
  464. }
  465. }
  466. }
  467. // process all block-contained instructions
  468. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  469. Function* f = *fi;
  470. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  471. Block* b = *bi;
  472. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ii++)
  473. postProcess(*ii->get());
  474. // For all local variables that contain pointers to PhysicalStorageBufferEXT, check whether
  475. // there is an existing restrict/aliased decoration. If we don't find one, add Aliased as the
  476. // default.
  477. for (auto vi = b->getLocalVariables().cbegin(); vi != b->getLocalVariables().cend(); vi++) {
  478. const Instruction& inst = *vi->get();
  479. Id resultId = inst.getResultId();
  480. if (containsPhysicalStorageBufferOrArray(getDerefTypeId(resultId))) {
  481. bool foundDecoration = false;
  482. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  483. if (decoration.get()->getIdOperand(0) == resultId &&
  484. decoration.get()->getOpCode() == Op::OpDecorate &&
  485. (decoration.get()->getImmediateOperand(1) == spv::Decoration::AliasedPointerEXT ||
  486. decoration.get()->getImmediateOperand(1) == spv::Decoration::RestrictPointerEXT)) {
  487. foundDecoration = true;
  488. }
  489. };
  490. std::for_each(decorations.begin(), decorations.end(), function);
  491. if (!foundDecoration) {
  492. addDecoration(resultId, spv::Decoration::AliasedPointerEXT);
  493. }
  494. }
  495. }
  496. }
  497. }
  498. // If any Vulkan memory model-specific functionality is used, update the
  499. // OpMemoryModel to match.
  500. if (capabilities.find(spv::Capability::VulkanMemoryModelKHR) != capabilities.end()) {
  501. memoryModel = spv::MemoryModel::VulkanKHR;
  502. addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
  503. }
  504. // Add Aliased decoration if there's more than one Workgroup Block variable.
  505. if (capabilities.find(spv::Capability::WorkgroupMemoryExplicitLayoutKHR) != capabilities.end()) {
  506. assert(entryPoints.size() == 1);
  507. auto &ep = entryPoints[0];
  508. std::vector<Id> workgroup_variables;
  509. for (int i = 0; i < (int)ep->getNumOperands(); i++) {
  510. if (!ep->isIdOperand(i))
  511. continue;
  512. const Id id = ep->getIdOperand(i);
  513. const Instruction *instr = module.getInstruction(id);
  514. if (instr->getOpCode() != spv::Op::OpVariable)
  515. continue;
  516. if (instr->getImmediateOperand(0) == spv::StorageClass::Workgroup)
  517. workgroup_variables.push_back(id);
  518. }
  519. if (workgroup_variables.size() > 1) {
  520. for (size_t i = 0; i < workgroup_variables.size(); i++)
  521. addDecoration(workgroup_variables[i], spv::Decoration::Aliased);
  522. }
  523. }
  524. }
  525. // SPIR-V requires that any instruction consuming the result of an OpSampledImage
  526. // be in the same block as the OpSampledImage instruction. This pass goes finds
  527. // uses of OpSampledImage where that is not the case and duplicates the
  528. // OpSampledImage to be immediately before the instruction that consumes it.
  529. // The old OpSampledImage is left in place, potentially with no users.
  530. void Builder::postProcessSamplers()
  531. {
  532. // first, find all OpSampledImage instructions and store them in a map.
  533. std::map<Id, Instruction*> sampledImageInstrs;
  534. for (auto f: module.getFunctions()) {
  535. for (auto b: f->getBlocks()) {
  536. for (auto &i: b->getInstructions()) {
  537. if (i->getOpCode() == spv::Op::OpSampledImage) {
  538. sampledImageInstrs[i->getResultId()] = i.get();
  539. }
  540. }
  541. }
  542. }
  543. // next find all uses of the given ids and rewrite them if needed.
  544. for (auto f: module.getFunctions()) {
  545. for (auto b: f->getBlocks()) {
  546. auto &instrs = b->getInstructions();
  547. for (size_t idx = 0; idx < instrs.size(); idx++) {
  548. Instruction *i = instrs[idx].get();
  549. for (int opnum = 0; opnum < i->getNumOperands(); opnum++) {
  550. // Is this operand of the current instruction the result of an OpSampledImage?
  551. if (i->isIdOperand(opnum) &&
  552. sampledImageInstrs.count(i->getIdOperand(opnum)))
  553. {
  554. Instruction *opSampImg = sampledImageInstrs[i->getIdOperand(opnum)];
  555. if (i->getBlock() != opSampImg->getBlock()) {
  556. Instruction *newInstr = new Instruction(getUniqueId(),
  557. opSampImg->getTypeId(),
  558. spv::Op::OpSampledImage);
  559. newInstr->addIdOperand(opSampImg->getIdOperand(0));
  560. newInstr->addIdOperand(opSampImg->getIdOperand(1));
  561. newInstr->setBlock(b);
  562. // rewrite the user of the OpSampledImage to use the new instruction.
  563. i->setIdOperand(opnum, newInstr->getResultId());
  564. // insert the new OpSampledImage right before the current instruction.
  565. instrs.insert(instrs.begin() + idx,
  566. std::unique_ptr<Instruction>(newInstr));
  567. idx++;
  568. }
  569. }
  570. }
  571. }
  572. }
  573. }
  574. }
  575. // comment in header
  576. void Builder::postProcess(bool compileOnly)
  577. {
  578. // postProcessCFG needs an entrypoint to determine what is reachable, but if we are not creating an "executable" shader, we don't have an entrypoint
  579. if (!compileOnly)
  580. postProcessCFG();
  581. postProcessFeatures();
  582. postProcessSamplers();
  583. }
  584. } // end spv namespace