SpvPostProcess.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  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_set>
  40. #include <algorithm>
  41. #include "SpvBuilder.h"
  42. #include "spirv.hpp"
  43. #include "GlslangToSpv.h"
  44. #include "SpvBuilder.h"
  45. namespace spv {
  46. #include "GLSL.std.450.h"
  47. #include "GLSL.ext.KHR.h"
  48. #include "GLSL.ext.EXT.h"
  49. #ifdef AMD_EXTENSIONS
  50. #include "GLSL.ext.AMD.h"
  51. #endif
  52. #ifdef NV_EXTENSIONS
  53. #include "GLSL.ext.NV.h"
  54. #endif
  55. }
  56. namespace spv {
  57. // Hook to visit each operand type and result type of an instruction.
  58. // Will be called multiple times for one instruction, once for each typed
  59. // operand and the result.
  60. void Builder::postProcessType(const Instruction& inst, Id typeId)
  61. {
  62. // Characterize the type being questioned
  63. Id basicTypeOp = getMostBasicTypeClass(typeId);
  64. int width = 0;
  65. if (basicTypeOp == OpTypeFloat || basicTypeOp == OpTypeInt)
  66. width = getScalarTypeWidth(typeId);
  67. // Do opcode-specific checks
  68. switch (inst.getOpCode()) {
  69. case OpLoad:
  70. case OpStore:
  71. if (basicTypeOp == OpTypeStruct) {
  72. if (containsType(typeId, OpTypeInt, 8))
  73. addCapability(CapabilityInt8);
  74. if (containsType(typeId, OpTypeInt, 16))
  75. addCapability(CapabilityInt16);
  76. if (containsType(typeId, OpTypeFloat, 16))
  77. addCapability(CapabilityFloat16);
  78. } else {
  79. StorageClass storageClass = getStorageClass(inst.getIdOperand(0));
  80. if (width == 8) {
  81. switch (storageClass) {
  82. case StorageClassPhysicalStorageBufferEXT:
  83. case StorageClassUniform:
  84. case StorageClassStorageBuffer:
  85. case StorageClassPushConstant:
  86. break;
  87. default:
  88. addCapability(CapabilityInt8);
  89. break;
  90. }
  91. } else if (width == 16) {
  92. switch (storageClass) {
  93. case StorageClassPhysicalStorageBufferEXT:
  94. case StorageClassUniform:
  95. case StorageClassStorageBuffer:
  96. case StorageClassPushConstant:
  97. case StorageClassInput:
  98. case StorageClassOutput:
  99. break;
  100. default:
  101. if (basicTypeOp == OpTypeInt)
  102. addCapability(CapabilityInt16);
  103. if (basicTypeOp == OpTypeFloat)
  104. addCapability(CapabilityFloat16);
  105. break;
  106. }
  107. }
  108. }
  109. break;
  110. case OpAccessChain:
  111. case OpPtrAccessChain:
  112. case OpCopyObject:
  113. case OpFConvert:
  114. case OpSConvert:
  115. case OpUConvert:
  116. break;
  117. case OpExtInst:
  118. #if AMD_EXTENSIONS
  119. switch (inst.getImmediateOperand(1)) {
  120. case GLSLstd450Frexp:
  121. case GLSLstd450FrexpStruct:
  122. if (getSpvVersion() < glslang::EShTargetSpv_1_3 && containsType(typeId, OpTypeInt, 16))
  123. addExtension(spv::E_SPV_AMD_gpu_shader_int16);
  124. break;
  125. case GLSLstd450InterpolateAtCentroid:
  126. case GLSLstd450InterpolateAtSample:
  127. case GLSLstd450InterpolateAtOffset:
  128. if (getSpvVersion() < glslang::EShTargetSpv_1_3 && containsType(typeId, OpTypeFloat, 16))
  129. addExtension(spv::E_SPV_AMD_gpu_shader_half_float);
  130. break;
  131. default:
  132. break;
  133. }
  134. #endif
  135. break;
  136. default:
  137. if (basicTypeOp == OpTypeFloat && width == 16)
  138. addCapability(CapabilityFloat16);
  139. if (basicTypeOp == OpTypeInt && width == 16)
  140. addCapability(CapabilityInt16);
  141. if (basicTypeOp == OpTypeInt && width == 8)
  142. addCapability(CapabilityInt8);
  143. break;
  144. }
  145. }
  146. // Called for each instruction that resides in a block.
  147. void Builder::postProcess(Instruction& inst)
  148. {
  149. // Add capabilities based simply on the opcode.
  150. switch (inst.getOpCode()) {
  151. case OpExtInst:
  152. switch (inst.getImmediateOperand(1)) {
  153. case GLSLstd450InterpolateAtCentroid:
  154. case GLSLstd450InterpolateAtSample:
  155. case GLSLstd450InterpolateAtOffset:
  156. addCapability(CapabilityInterpolationFunction);
  157. break;
  158. default:
  159. break;
  160. }
  161. break;
  162. case OpDPdxFine:
  163. case OpDPdyFine:
  164. case OpFwidthFine:
  165. case OpDPdxCoarse:
  166. case OpDPdyCoarse:
  167. case OpFwidthCoarse:
  168. addCapability(CapabilityDerivativeControl);
  169. break;
  170. case OpImageQueryLod:
  171. case OpImageQuerySize:
  172. case OpImageQuerySizeLod:
  173. case OpImageQuerySamples:
  174. case OpImageQueryLevels:
  175. addCapability(CapabilityImageQuery);
  176. break;
  177. #ifdef NV_EXTENSIONS
  178. case OpGroupNonUniformPartitionNV:
  179. addExtension(E_SPV_NV_shader_subgroup_partitioned);
  180. addCapability(CapabilityGroupNonUniformPartitionedNV);
  181. break;
  182. #endif
  183. case OpLoad:
  184. case OpStore:
  185. {
  186. // For any load/store to a PhysicalStorageBufferEXT, walk the accesschain
  187. // index list to compute the misalignment. The pre-existing alignment value
  188. // (set via Builder::AccessChain::alignment) only accounts for the base of
  189. // the reference type and any scalar component selection in the accesschain,
  190. // and this function computes the rest from the SPIR-V Offset decorations.
  191. Instruction *accessChain = module.getInstruction(inst.getIdOperand(0));
  192. if (accessChain->getOpCode() == OpAccessChain) {
  193. Instruction *base = module.getInstruction(accessChain->getIdOperand(0));
  194. // Get the type of the base of the access chain. It must be a pointer type.
  195. Id typeId = base->getTypeId();
  196. Instruction *type = module.getInstruction(typeId);
  197. assert(type->getOpCode() == OpTypePointer);
  198. if (type->getImmediateOperand(0) != StorageClassPhysicalStorageBufferEXT) {
  199. break;
  200. }
  201. // Get the pointee type.
  202. typeId = type->getIdOperand(1);
  203. type = module.getInstruction(typeId);
  204. // Walk the index list for the access chain. For each index, find any
  205. // misalignment that can apply when accessing the member/element via
  206. // Offset/ArrayStride/MatrixStride decorations, and bitwise OR them all
  207. // together.
  208. int alignment = 0;
  209. for (int i = 1; i < accessChain->getNumOperands(); ++i) {
  210. Instruction *idx = module.getInstruction(accessChain->getIdOperand(i));
  211. if (type->getOpCode() == OpTypeStruct) {
  212. assert(idx->getOpCode() == OpConstant);
  213. unsigned int c = idx->getImmediateOperand(0);
  214. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  215. if (decoration.get()->getOpCode() == OpMemberDecorate &&
  216. decoration.get()->getIdOperand(0) == typeId &&
  217. decoration.get()->getImmediateOperand(1) == c &&
  218. (decoration.get()->getImmediateOperand(2) == DecorationOffset ||
  219. decoration.get()->getImmediateOperand(2) == DecorationMatrixStride)) {
  220. alignment |= decoration.get()->getImmediateOperand(3);
  221. }
  222. };
  223. std::for_each(decorations.begin(), decorations.end(), function);
  224. // get the next member type
  225. typeId = type->getIdOperand(c);
  226. type = module.getInstruction(typeId);
  227. } else if (type->getOpCode() == OpTypeArray ||
  228. type->getOpCode() == OpTypeRuntimeArray) {
  229. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  230. if (decoration.get()->getOpCode() == OpDecorate &&
  231. decoration.get()->getIdOperand(0) == typeId &&
  232. decoration.get()->getImmediateOperand(1) == DecorationArrayStride) {
  233. alignment |= decoration.get()->getImmediateOperand(2);
  234. }
  235. };
  236. std::for_each(decorations.begin(), decorations.end(), function);
  237. // Get the element type
  238. typeId = type->getIdOperand(0);
  239. type = module.getInstruction(typeId);
  240. } else {
  241. // Once we get to any non-aggregate type, we're done.
  242. break;
  243. }
  244. }
  245. assert(inst.getNumOperands() >= 3);
  246. unsigned int memoryAccess = inst.getImmediateOperand((inst.getOpCode() == OpStore) ? 2 : 1);
  247. assert(memoryAccess & MemoryAccessAlignedMask);
  248. static_cast<void>(memoryAccess);
  249. // Compute the index of the alignment operand.
  250. int alignmentIdx = 2;
  251. if (inst.getOpCode() == OpStore)
  252. alignmentIdx++;
  253. // Merge new and old (mis)alignment
  254. alignment |= inst.getImmediateOperand(alignmentIdx);
  255. // Pick the LSB
  256. alignment = alignment & ~(alignment & (alignment-1));
  257. // update the Aligned operand
  258. inst.setImmediateOperand(alignmentIdx, alignment);
  259. }
  260. break;
  261. }
  262. default:
  263. break;
  264. }
  265. // Checks based on type
  266. if (inst.getTypeId() != NoType)
  267. postProcessType(inst, inst.getTypeId());
  268. for (int op = 0; op < inst.getNumOperands(); ++op) {
  269. if (inst.isIdOperand(op)) {
  270. // In blocks, these are always result ids, but we are relying on
  271. // getTypeId() to return NoType for things like OpLabel.
  272. if (getTypeId(inst.getIdOperand(op)) != NoType)
  273. postProcessType(inst, getTypeId(inst.getIdOperand(op)));
  274. }
  275. }
  276. }
  277. // Called for each instruction in a reachable block.
  278. void Builder::postProcessReachable(const Instruction&)
  279. {
  280. // did have code here, but questionable to do so without deleting the instructions
  281. }
  282. // comment in header
  283. void Builder::postProcess()
  284. {
  285. std::unordered_set<const Block*> reachableBlocks;
  286. std::unordered_set<Id> unreachableDefinitions;
  287. // Collect IDs defined in unreachable blocks. For each function, label the
  288. // reachable blocks first. Then for each unreachable block, collect the
  289. // result IDs of the instructions in it.
  290. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  291. Function* f = *fi;
  292. Block* entry = f->getEntryBlock();
  293. inReadableOrder(entry, [&reachableBlocks](const Block* b) { reachableBlocks.insert(b); });
  294. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  295. Block* b = *bi;
  296. if (reachableBlocks.count(b) == 0) {
  297. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ii++)
  298. unreachableDefinitions.insert(ii->get()->getResultId());
  299. }
  300. }
  301. }
  302. // Remove unneeded decorations, for unreachable instructions
  303. decorations.erase(std::remove_if(decorations.begin(), decorations.end(),
  304. [&unreachableDefinitions](std::unique_ptr<Instruction>& I) -> bool {
  305. Id decoration_id = I.get()->getIdOperand(0);
  306. return unreachableDefinitions.count(decoration_id) != 0;
  307. }),
  308. decorations.end());
  309. // Add per-instruction capabilities, extensions, etc.,
  310. // process all reachable instructions...
  311. for (auto bi = reachableBlocks.cbegin(); bi != reachableBlocks.cend(); ++bi) {
  312. const Block* block = *bi;
  313. const auto function = [this](const std::unique_ptr<Instruction>& inst) { postProcessReachable(*inst.get()); };
  314. std::for_each(block->getInstructions().begin(), block->getInstructions().end(), function);
  315. }
  316. // process all block-contained instructions
  317. for (auto fi = module.getFunctions().cbegin(); fi != module.getFunctions().cend(); fi++) {
  318. Function* f = *fi;
  319. for (auto bi = f->getBlocks().cbegin(); bi != f->getBlocks().cend(); bi++) {
  320. Block* b = *bi;
  321. for (auto ii = b->getInstructions().cbegin(); ii != b->getInstructions().cend(); ii++)
  322. postProcess(*ii->get());
  323. // For all local variables that contain pointers to PhysicalStorageBufferEXT, check whether
  324. // there is an existing restrict/aliased decoration. If we don't find one, add Aliased as the
  325. // default.
  326. for (auto vi = b->getLocalVariables().cbegin(); vi != b->getLocalVariables().cend(); vi++) {
  327. const Instruction& inst = *vi->get();
  328. Id resultId = inst.getResultId();
  329. if (containsPhysicalStorageBufferOrArray(getDerefTypeId(resultId))) {
  330. bool foundDecoration = false;
  331. const auto function = [&](const std::unique_ptr<Instruction>& decoration) {
  332. if (decoration.get()->getIdOperand(0) == resultId &&
  333. decoration.get()->getOpCode() == OpDecorate &&
  334. (decoration.get()->getImmediateOperand(1) == spv::DecorationAliasedPointerEXT ||
  335. decoration.get()->getImmediateOperand(1) == spv::DecorationRestrictPointerEXT)) {
  336. foundDecoration = true;
  337. }
  338. };
  339. std::for_each(decorations.begin(), decorations.end(), function);
  340. if (!foundDecoration) {
  341. addDecoration(resultId, spv::DecorationAliasedPointerEXT);
  342. }
  343. }
  344. }
  345. }
  346. }
  347. // Look for any 8/16 bit type in physical storage buffer class, and set the
  348. // appropriate capability. This happens in createSpvVariable for other storage
  349. // classes, but there isn't always a variable for physical storage buffer.
  350. for (int t = 0; t < (int)groupedTypes[OpTypePointer].size(); ++t) {
  351. Instruction* type = groupedTypes[OpTypePointer][t];
  352. if (type->getImmediateOperand(0) == (unsigned)StorageClassPhysicalStorageBufferEXT) {
  353. if (containsType(type->getIdOperand(1), OpTypeInt, 8)) {
  354. addExtension(spv::E_SPV_KHR_8bit_storage);
  355. addCapability(spv::CapabilityStorageBuffer8BitAccess);
  356. }
  357. if (containsType(type->getIdOperand(1), OpTypeInt, 16) ||
  358. containsType(type->getIdOperand(1), OpTypeFloat, 16)) {
  359. addExtension(spv::E_SPV_KHR_16bit_storage);
  360. addCapability(spv::CapabilityStorageBuffer16BitAccess);
  361. }
  362. }
  363. }
  364. }
  365. }; // end spv namespace