SpvPostProcess.cpp 21 KB

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