SpvPostProcess.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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 "SpvBuilder.h"
  43. #include "spirv.hpp"
  44. namespace spv {
  45. #include "GLSL.std.450.h"
  46. #include "GLSL.ext.KHR.h"
  47. #include "GLSL.ext.EXT.h"
  48. #include "GLSL.ext.AMD.h"
  49. #include "GLSL.ext.NV.h"
  50. }
  51. namespace spv {
  52. #ifndef GLSLANG_WEB
  53. // Hook to visit each operand type and result type of an instruction.
  54. // Will be called multiple times for one instruction, once for each typed
  55. // operand and the result.
  56. void Builder::postProcessType(const Instruction& inst, Id typeId)
  57. {
  58. // Characterize the type being questioned
  59. Id basicTypeOp = getMostBasicTypeClass(typeId);
  60. int width = 0;
  61. if (basicTypeOp == OpTypeFloat || basicTypeOp == OpTypeInt)
  62. width = getScalarTypeWidth(typeId);
  63. // Do opcode-specific checks
  64. switch (inst.getOpCode()) {
  65. case OpLoad:
  66. case OpStore:
  67. if (basicTypeOp == OpTypeStruct) {
  68. if (containsType(typeId, OpTypeInt, 8))
  69. addCapability(CapabilityInt8);
  70. if (containsType(typeId, OpTypeInt, 16))
  71. addCapability(CapabilityInt16);
  72. if (containsType(typeId, OpTypeFloat, 16))
  73. addCapability(CapabilityFloat16);
  74. } else {
  75. StorageClass storageClass = getStorageClass(inst.getIdOperand(0));
  76. if (width == 8) {
  77. switch (storageClass) {
  78. case StorageClassPhysicalStorageBufferEXT:
  79. case StorageClassUniform:
  80. case StorageClassStorageBuffer:
  81. case StorageClassPushConstant:
  82. break;
  83. default:
  84. addCapability(CapabilityInt8);
  85. break;
  86. }
  87. } else if (width == 16) {
  88. switch (storageClass) {
  89. case StorageClassPhysicalStorageBufferEXT:
  90. case StorageClassUniform:
  91. case StorageClassStorageBuffer:
  92. case StorageClassPushConstant:
  93. case StorageClassInput:
  94. case StorageClassOutput:
  95. break;
  96. default:
  97. if (basicTypeOp == OpTypeInt)
  98. addCapability(CapabilityInt16);
  99. if (basicTypeOp == OpTypeFloat)
  100. addCapability(CapabilityFloat16);
  101. break;
  102. }
  103. }
  104. }
  105. break;
  106. case OpCopyObject:
  107. break;
  108. case OpFConvert:
  109. case OpSConvert:
  110. case OpUConvert:
  111. // Look for any 8/16-bit storage capabilities. If there are none, assume that
  112. // the convert instruction requires the Float16/Int8/16 capability.
  113. if (containsType(typeId, OpTypeFloat, 16) || containsType(typeId, OpTypeInt, 16)) {
  114. bool foundStorage = false;
  115. for (auto it = capabilities.begin(); it != capabilities.end(); ++it) {
  116. spv::Capability cap = *it;
  117. if (cap == spv::CapabilityStorageInputOutput16 ||
  118. cap == spv::CapabilityStoragePushConstant16 ||
  119. cap == spv::CapabilityStorageUniformBufferBlock16 ||
  120. cap == spv::CapabilityStorageUniform16) {
  121. foundStorage = true;
  122. break;
  123. }
  124. }
  125. if (!foundStorage) {
  126. if (containsType(typeId, OpTypeFloat, 16))
  127. addCapability(CapabilityFloat16);
  128. if (containsType(typeId, OpTypeInt, 16))
  129. addCapability(CapabilityInt16);
  130. }
  131. }
  132. if (containsType(typeId, OpTypeInt, 8)) {
  133. bool foundStorage = false;
  134. for (auto it = capabilities.begin(); it != capabilities.end(); ++it) {
  135. spv::Capability cap = *it;
  136. if (cap == spv::CapabilityStoragePushConstant8 ||
  137. cap == spv::CapabilityUniformAndStorageBuffer8BitAccess ||
  138. cap == spv::CapabilityStorageBuffer8BitAccess) {
  139. foundStorage = true;
  140. break;
  141. }
  142. }
  143. if (!foundStorage) {
  144. addCapability(CapabilityInt8);
  145. }
  146. }
  147. break;
  148. case OpExtInst:
  149. switch (inst.getImmediateOperand(1)) {
  150. case GLSLstd450Frexp:
  151. case GLSLstd450FrexpStruct:
  152. if (getSpvVersion() < spv::Spv_1_3 && containsType(typeId, OpTypeInt, 16))
  153. addExtension(spv::E_SPV_AMD_gpu_shader_int16);
  154. break;
  155. case GLSLstd450InterpolateAtCentroid:
  156. case GLSLstd450InterpolateAtSample:
  157. case GLSLstd450InterpolateAtOffset:
  158. if (getSpvVersion() < spv::Spv_1_3 && containsType(typeId, OpTypeFloat, 16))
  159. addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  160. break;
  161. default:
  162. break;
  163. }
  164. break;
  165. case OpAccessChain:
  166. case OpPtrAccessChain:
  167. if (isPointerType(typeId))
  168. break;
  169. if (basicTypeOp == OpTypeInt) {
  170. if (width == 16)
  171. addCapability(CapabilityInt16);
  172. else if (width == 8)
  173. addCapability(CapabilityInt8);
  174. }
  175. default:
  176. if (basicTypeOp == OpTypeInt) {
  177. if (width == 16)
  178. addCapability(CapabilityInt16);
  179. else if (width == 8)
  180. addCapability(CapabilityInt8);
  181. else if (width == 64)
  182. addCapability(CapabilityInt64);
  183. } else if (basicTypeOp == OpTypeFloat) {
  184. if (width == 16)
  185. addCapability(CapabilityFloat16);
  186. else if (width == 64)
  187. addCapability(CapabilityFloat64);
  188. }
  189. break;
  190. }
  191. }
  192. // Called for each instruction that resides in a block.
  193. void Builder::postProcess(Instruction& inst)
  194. {
  195. // Add capabilities based simply on the opcode.
  196. switch (inst.getOpCode()) {
  197. case OpExtInst:
  198. switch (inst.getImmediateOperand(1)) {
  199. case GLSLstd450InterpolateAtCentroid:
  200. case GLSLstd450InterpolateAtSample:
  201. case GLSLstd450InterpolateAtOffset:
  202. addCapability(CapabilityInterpolationFunction);
  203. break;
  204. default:
  205. break;
  206. }
  207. break;
  208. case OpDPdxFine:
  209. case OpDPdyFine:
  210. case OpFwidthFine:
  211. case OpDPdxCoarse:
  212. case OpDPdyCoarse:
  213. case OpFwidthCoarse:
  214. addCapability(CapabilityDerivativeControl);
  215. break;
  216. case OpImageQueryLod:
  217. case OpImageQuerySize:
  218. case OpImageQuerySizeLod:
  219. case OpImageQuerySamples:
  220. case OpImageQueryLevels:
  221. addCapability(CapabilityImageQuery);
  222. break;
  223. case OpGroupNonUniformPartitionNV:
  224. addExtension(E_SPV_NV_shader_subgroup_partitioned);
  225. addCapability(CapabilityGroupNonUniformPartitionedNV);
  226. break;
  227. case OpLoad:
  228. case OpStore:
  229. {
  230. // For any load/store to a PhysicalStorageBufferEXT, walk the accesschain
  231. // index list to compute the misalignment. The pre-existing alignment value
  232. // (set via Builder::AccessChain::alignment) only accounts for the base of
  233. // the reference type and any scalar component selection in the accesschain,
  234. // and this function computes the rest from the SPIR-V Offset decorations.
  235. Instruction *accessChain = module.getInstruction(inst.getIdOperand(0));
  236. if (accessChain->getOpCode() == OpAccessChain) {
  237. Instruction *base = module.getInstruction(accessChain->getIdOperand(0));
  238. // Get the type of the base of the access chain. It must be a pointer type.
  239. Id typeId = base->getTypeId();
  240. Instruction *type = module.getInstruction(typeId);
  241. assert(type->getOpCode() == OpTypePointer);
  242. if (type->getImmediateOperand(0) != StorageClassPhysicalStorageBufferEXT) {
  243. break;
  244. }
  245. // Get the pointee type.
  246. typeId = type->getIdOperand(1);
  247. type = module.getInstruction(typeId);
  248. // Walk the index list for the access chain. For each index, find any
  249. // misalignment that can apply when accessing the member/element via
  250. // Offset/ArrayStride/MatrixStride decorations, and bitwise OR them all
  251. // together.
  252. int alignment = 0;
  253. for (int i = 1; i < accessChain->getNumOperands(); ++i) {
  254. Instruction *idx = module.getInstruction(accessChain->getIdOperand(i));
  255. if (type->getOpCode() == OpTypeStruct) {
  256. assert(idx->getOpCode() == OpConstant);
  257. unsigned int c = idx->getImmediateOperand(0);
  258. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  259. if (decoration.get()->getOpCode() == OpMemberDecorate &&
  260. decoration.get()->getIdOperand(0) == typeId &&
  261. decoration.get()->getImmediateOperand(1) == c &&
  262. (decoration.get()->getImmediateOperand(2) == DecorationOffset ||
  263. decoration.get()->getImmediateOperand(2) == DecorationMatrixStride)) {
  264. alignment |= decoration.get()->getImmediateOperand(3);
  265. }
  266. };
  267. std::for_each(decorations.begin(), decorations.end(), function);
  268. // get the next member type
  269. typeId = type->getIdOperand(c);
  270. type = module.getInstruction(typeId);
  271. } else if (type->getOpCode() == OpTypeArray ||
  272. type->getOpCode() == OpTypeRuntimeArray) {
  273. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  274. if (decoration.get()->getOpCode() == OpDecorate &&
  275. decoration.get()->getIdOperand(0) == typeId &&
  276. decoration.get()->getImmediateOperand(1) == DecorationArrayStride) {
  277. alignment |= decoration.get()->getImmediateOperand(2);
  278. }
  279. };
  280. std::for_each(decorations.begin(), decorations.end(), function);
  281. // Get the element type
  282. typeId = type->getIdOperand(0);
  283. type = module.getInstruction(typeId);
  284. } else {
  285. // Once we get to any non-aggregate type, we're done.
  286. break;
  287. }
  288. }
  289. assert(inst.getNumOperands() >= 3);
  290. unsigned int memoryAccess = inst.getImmediateOperand((inst.getOpCode() == OpStore) ? 2 : 1);
  291. assert(memoryAccess & MemoryAccessAlignedMask);
  292. static_cast<void>(memoryAccess);
  293. // Compute the index of the alignment operand.
  294. int alignmentIdx = 2;
  295. if (inst.getOpCode() == OpStore)
  296. alignmentIdx++;
  297. // Merge new and old (mis)alignment
  298. alignment |= inst.getImmediateOperand(alignmentIdx);
  299. // Pick the LSB
  300. alignment = alignment & ~(alignment & (alignment-1));
  301. // update the Aligned operand
  302. inst.setImmediateOperand(alignmentIdx, alignment);
  303. }
  304. break;
  305. }
  306. default:
  307. break;
  308. }
  309. // Checks based on type
  310. if (inst.getTypeId() != NoType)
  311. postProcessType(inst, inst.getTypeId());
  312. for (int op = 0; op < inst.getNumOperands(); ++op) {
  313. if (inst.isIdOperand(op)) {
  314. // In blocks, these are always result ids, but we are relying on
  315. // getTypeId() to return NoType for things like OpLabel.
  316. if (getTypeId(inst.getIdOperand(op)) != NoType)
  317. postProcessType(inst, getTypeId(inst.getIdOperand(op)));
  318. }
  319. }
  320. }
  321. #endif
  322. // comment in header
  323. void Builder::postProcessCFG()
  324. {
  325. // reachableBlocks is the set of blockss reached via control flow, or which are
  326. // unreachable continue targert or unreachable merge.
  327. std::unordered_set<const Block*> reachableBlocks;
  328. std::unordered_map<Block*, Block*> headerForUnreachableContinue;
  329. std::unordered_set<Block*> unreachableMerges;
  330. std::unordered_set<Id> unreachableDefinitions;
  331. // Collect IDs defined in unreachable blocks. For each function, label the
  332. // reachable blocks first. Then for each unreachable block, collect the
  333. // result IDs of the instructions in it.
  334. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  335. Function* f = *fi;
  336. Block* entry = f->getEntryBlock();
  337. inReadableOrder(entry,
  338. [&reachableBlocks, &unreachableMerges, &headerForUnreachableContinue]
  339. (Block* b, ReachReason why, Block* header) {
  340. reachableBlocks.insert(b);
  341. if (why == ReachDeadContinue) headerForUnreachableContinue[b] = header;
  342. if (why == ReachDeadMerge) unreachableMerges.insert(b);
  343. });
  344. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  345. Block* b = *bi;
  346. if (unreachableMerges.count(b) != 0 || headerForUnreachableContinue.count(b) != 0) {
  347. auto ii = b->getInstructions().cbegin();
  348. ++ii; // Keep potential decorations on the label.
  349. for (; ii != b->getInstructions().cend(); ++ii)
  350. unreachableDefinitions.insert(ii->get()->getResultId());
  351. } else if (reachableBlocks.count(b) == 0) {
  352. // The normal case for unreachable code. All definitions are considered dead.
  353. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ++ii)
  354. unreachableDefinitions.insert(ii->get()->getResultId());
  355. }
  356. }
  357. }
  358. // Modify unreachable merge blocks and unreachable continue targets.
  359. // Delete their contents.
  360. for (auto mergeIter = unreachableMerges.begin(); mergeIter != unreachableMerges.end(); ++mergeIter) {
  361. (*mergeIter)->rewriteAsCanonicalUnreachableMerge();
  362. }
  363. for (auto continueIter = headerForUnreachableContinue.begin();
  364. continueIter != headerForUnreachableContinue.end();
  365. ++continueIter) {
  366. Block* continue_target = continueIter->first;
  367. Block* header = continueIter->second;
  368. continue_target->rewriteAsCanonicalUnreachableContinue(header);
  369. }
  370. // Remove unneeded decorations, for unreachable instructions
  371. decorations.erase(std::remove_if(decorations.begin(), decorations.end(),
  372. [&unreachableDefinitions](std::unique_ptr<Instruction>& I) -> bool {
  373. Id decoration_id = I.get()->getIdOperand(0);
  374. return unreachableDefinitions.count(decoration_id) != 0;
  375. }),
  376. decorations.end());
  377. }
  378. #ifndef GLSLANG_WEB
  379. // comment in header
  380. void Builder::postProcessFeatures() {
  381. // Add per-instruction capabilities, extensions, etc.,
  382. // Look for any 8/16 bit type in physical storage buffer class, and set the
  383. // appropriate capability. This happens in createSpvVariable for other storage
  384. // classes, but there isn't always a variable for physical storage buffer.
  385. for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
  386. Instruction* type = groupedTypes[OpTypePointer][t];
  387. if (type->getImmediateOperand(0) == (unsigned)StorageClassPhysicalStorageBufferEXT) {
  388. if (containsType(type->getIdOperand(1), OpTypeInt, 8)) {
  389. addIncorporatedExtension(spv::E_SPV_KHR_8bit_storage, spv::Spv_1_5);
  390. addCapability(spv::CapabilityStorageBuffer8BitAccess);
  391. }
  392. if (containsType(type->getIdOperand(1), OpTypeInt, 16) ||
  393. containsType(type->getIdOperand(1), OpTypeFloat, 16)) {
  394. addIncorporatedExtension(spv::E_SPV_KHR_16bit_storage, spv::Spv_1_3);
  395. addCapability(spv::CapabilityStorageBuffer16BitAccess);
  396. }
  397. }
  398. }
  399. // process all block-contained instructions
  400. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  401. Function* f = *fi;
  402. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  403. Block* b = *bi;
  404. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ii++)
  405. postProcess(*ii->get());
  406. // For all local variables that contain pointers to PhysicalStorageBufferEXT, check whether
  407. // there is an existing restrict/aliased decoration. If we don't find one, add Aliased as the
  408. // default.
  409. for (auto vi = b->getLocalVariables().cbegin(); vi != b->getLocalVariables().cend(); vi++) {
  410. const Instruction& inst = *vi->get();
  411. Id resultId = inst.getResultId();
  412. if (containsPhysicalStorageBufferOrArray(getDerefTypeId(resultId))) {
  413. bool foundDecoration = false;
  414. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  415. if (decoration.get()->getIdOperand(0) == resultId &&
  416. decoration.get()->getOpCode() == OpDecorate &&
  417. (decoration.get()->getImmediateOperand(1) == spv::DecorationAliasedPointerEXT ||
  418. decoration.get()->getImmediateOperand(1) == spv::DecorationRestrictPointerEXT)) {
  419. foundDecoration = true;
  420. }
  421. };
  422. std::for_each(decorations.begin(), decorations.end(), function);
  423. if (!foundDecoration) {
  424. addDecoration(resultId, spv::DecorationAliasedPointerEXT);
  425. }
  426. }
  427. }
  428. }
  429. }
  430. // If any Vulkan memory model-specific functionality is used, update the
  431. // OpMemoryModel to match.
  432. if (capabilities.find(spv::CapabilityVulkanMemoryModelKHR) != capabilities.end()) {
  433. memoryModel = spv::MemoryModelVulkanKHR;
  434. addIncorporatedExtension(spv::E_SPV_KHR_vulkan_memory_model, spv::Spv_1_5);
  435. }
  436. // Add Aliased decoration if there's more than one Workgroup Block variable.
  437. if (capabilities.find(spv::CapabilityWorkgroupMemoryExplicitLayoutKHR) != capabilities.end()) {
  438. assert(entryPoints.size() == 1);
  439. auto &ep = entryPoints[0];
  440. std::vector<Id> workgroup_variables;
  441. for (int i = 0; i < (int)ep->getNumOperands(); i++) {
  442. if (!ep->isIdOperand(i))
  443. continue;
  444. const Id id = ep->getIdOperand(i);
  445. const Instruction *instr = module.getInstruction(id);
  446. if (instr->getOpCode() != spv::OpVariable)
  447. continue;
  448. if (instr->getImmediateOperand(0) == spv::StorageClassWorkgroup)
  449. workgroup_variables.push_back(id);
  450. }
  451. if (workgroup_variables.size() > 1) {
  452. for (size_t i = 0; i < workgroup_variables.size(); i++)
  453. addDecoration(workgroup_variables[i], spv::DecorationAliased);
  454. }
  455. }
  456. }
  457. #endif
  458. // comment in header
  459. void Builder::postProcess() {
  460. postProcessCFG();
  461. #ifndef GLSLANG_WEB
  462. postProcessFeatures();
  463. #endif
  464. }
  465. }; // end spv namespace