emit_spirv.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <span>
  5. #include <tuple>
  6. #include <type_traits>
  7. #include <utility>
  8. #include <vector>
  9. #include "shader_recompiler/backend/spirv/emit_spirv.h"
  10. #include "shader_recompiler/frontend/ir/basic_block.h"
  11. #include "shader_recompiler/frontend/ir/microinstruction.h"
  12. #include "shader_recompiler/frontend/ir/program.h"
  13. namespace Shader::Backend::SPIRV {
  14. namespace {
  15. template <class Func>
  16. struct FuncTraits {};
  17. template <class ReturnType_, class... Args>
  18. struct FuncTraits<ReturnType_ (*)(Args...)> {
  19. using ReturnType = ReturnType_;
  20. static constexpr size_t NUM_ARGS = sizeof...(Args);
  21. template <size_t I>
  22. using ArgType = std::tuple_element_t<I, std::tuple<Args...>>;
  23. };
  24. template <auto func, typename... Args>
  25. void SetDefinition(EmitContext& ctx, IR::Inst* inst, Args... args) {
  26. inst->SetDefinition<Id>(func(ctx, std::forward<Args>(args)...));
  27. }
  28. template <typename ArgType>
  29. ArgType Arg(EmitContext& ctx, const IR::Value& arg) {
  30. if constexpr (std::is_same_v<ArgType, Id>) {
  31. return ctx.Def(arg);
  32. } else if constexpr (std::is_same_v<ArgType, const IR::Value&>) {
  33. return arg;
  34. } else if constexpr (std::is_same_v<ArgType, u32>) {
  35. return arg.U32();
  36. } else if constexpr (std::is_same_v<ArgType, IR::Block*>) {
  37. return arg.Label();
  38. } else if constexpr (std::is_same_v<ArgType, IR::Attribute>) {
  39. return arg.Attribute();
  40. } else if constexpr (std::is_same_v<ArgType, IR::Reg>) {
  41. return arg.Reg();
  42. }
  43. }
  44. template <auto func, bool is_first_arg_inst, size_t... I>
  45. void Invoke(EmitContext& ctx, IR::Inst* inst, std::index_sequence<I...>) {
  46. using Traits = FuncTraits<decltype(func)>;
  47. if constexpr (std::is_same_v<typename Traits::ReturnType, Id>) {
  48. if constexpr (is_first_arg_inst) {
  49. SetDefinition<func>(
  50. ctx, inst, inst,
  51. Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...);
  52. } else {
  53. SetDefinition<func>(
  54. ctx, inst, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...);
  55. }
  56. } else {
  57. if constexpr (is_first_arg_inst) {
  58. func(ctx, inst, Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...);
  59. } else {
  60. func(ctx, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...);
  61. }
  62. }
  63. }
  64. template <auto func>
  65. void Invoke(EmitContext& ctx, IR::Inst* inst) {
  66. using Traits = FuncTraits<decltype(func)>;
  67. static_assert(Traits::NUM_ARGS >= 1, "Insufficient arguments");
  68. if constexpr (Traits::NUM_ARGS == 1) {
  69. Invoke<func, false>(ctx, inst, std::make_index_sequence<0>{});
  70. } else {
  71. using FirstArgType = typename Traits::template ArgType<1>;
  72. static constexpr bool is_first_arg_inst = std::is_same_v<FirstArgType, IR::Inst*>;
  73. using Indices = std::make_index_sequence<Traits::NUM_ARGS - (is_first_arg_inst ? 2 : 1)>;
  74. Invoke<func, is_first_arg_inst>(ctx, inst, Indices{});
  75. }
  76. }
  77. void EmitInst(EmitContext& ctx, IR::Inst* inst) {
  78. switch (inst->GetOpcode()) {
  79. #define OPCODE(name, result_type, ...) \
  80. case IR::Opcode::name: \
  81. return Invoke<&Emit##name>(ctx, inst);
  82. #include "shader_recompiler/frontend/ir/opcodes.inc"
  83. #undef OPCODE
  84. }
  85. throw LogicError("Invalid opcode {}", inst->GetOpcode());
  86. }
  87. Id TypeId(const EmitContext& ctx, IR::Type type) {
  88. switch (type) {
  89. case IR::Type::U1:
  90. return ctx.U1;
  91. case IR::Type::U32:
  92. return ctx.U32[1];
  93. default:
  94. throw NotImplementedException("Phi node type {}", type);
  95. }
  96. }
  97. Id DefineMain(EmitContext& ctx, IR::Program& program) {
  98. const Id void_function{ctx.TypeFunction(ctx.void_id)};
  99. const Id main{ctx.OpFunction(ctx.void_id, spv::FunctionControlMask::MaskNone, void_function)};
  100. for (IR::Block* const block : program.blocks) {
  101. ctx.AddLabel(block->Definition<Id>());
  102. for (IR::Inst& inst : block->Instructions()) {
  103. EmitInst(ctx, &inst);
  104. }
  105. }
  106. ctx.OpFunctionEnd();
  107. return main;
  108. }
  109. void DefineEntryPoint(const IR::Program& program, EmitContext& ctx, Id main) {
  110. const std::span interfaces(ctx.interfaces.data(), ctx.interfaces.size());
  111. spv::ExecutionModel execution_model{};
  112. switch (program.stage) {
  113. case Shader::Stage::Compute: {
  114. const std::array<u32, 3> workgroup_size{program.workgroup_size};
  115. execution_model = spv::ExecutionModel::GLCompute;
  116. ctx.AddExecutionMode(main, spv::ExecutionMode::LocalSize, workgroup_size[0],
  117. workgroup_size[1], workgroup_size[2]);
  118. break;
  119. }
  120. case Shader::Stage::VertexB:
  121. execution_model = spv::ExecutionModel::Vertex;
  122. break;
  123. case Shader::Stage::Fragment:
  124. execution_model = spv::ExecutionModel::Fragment;
  125. ctx.AddExecutionMode(main, spv::ExecutionMode::OriginUpperLeft);
  126. if (program.info.stores_frag_depth) {
  127. ctx.AddExecutionMode(main, spv::ExecutionMode::DepthReplacing);
  128. }
  129. break;
  130. default:
  131. throw NotImplementedException("Stage {}", program.stage);
  132. }
  133. ctx.AddEntryPoint(execution_model, main, "main", interfaces);
  134. }
  135. void SetupDenormControl(const Profile& profile, const IR::Program& program, EmitContext& ctx,
  136. Id main_func) {
  137. const Info& info{program.info};
  138. if (info.uses_fp32_denorms_flush && info.uses_fp32_denorms_preserve) {
  139. // LOG_ERROR(HW_GPU, "Fp32 denorm flush and preserve on the same shader");
  140. } else if (info.uses_fp32_denorms_flush) {
  141. if (profile.support_fp32_denorm_flush) {
  142. ctx.AddCapability(spv::Capability::DenormFlushToZero);
  143. ctx.AddExecutionMode(main_func, spv::ExecutionMode::DenormFlushToZero, 32U);
  144. } else {
  145. // Drivers will most likely flush denorms by default, no need to warn
  146. }
  147. } else if (info.uses_fp32_denorms_preserve) {
  148. if (profile.support_fp32_denorm_preserve) {
  149. ctx.AddCapability(spv::Capability::DenormPreserve);
  150. ctx.AddExecutionMode(main_func, spv::ExecutionMode::DenormPreserve, 32U);
  151. } else {
  152. // LOG_WARNING(HW_GPU, "Fp32 denorm preserve used in shader without host support");
  153. }
  154. }
  155. if (!profile.support_separate_denorm_behavior) {
  156. // No separate denorm behavior
  157. return;
  158. }
  159. if (info.uses_fp16_denorms_flush && info.uses_fp16_denorms_preserve) {
  160. // LOG_ERROR(HW_GPU, "Fp16 denorm flush and preserve on the same shader");
  161. } else if (info.uses_fp16_denorms_flush) {
  162. if (profile.support_fp16_denorm_flush) {
  163. ctx.AddCapability(spv::Capability::DenormFlushToZero);
  164. ctx.AddExecutionMode(main_func, spv::ExecutionMode::DenormFlushToZero, 16U);
  165. } else {
  166. // Same as fp32, no need to warn as most drivers will flush by default
  167. }
  168. } else if (info.uses_fp16_denorms_preserve) {
  169. if (profile.support_fp16_denorm_preserve) {
  170. ctx.AddCapability(spv::Capability::DenormPreserve);
  171. ctx.AddExecutionMode(main_func, spv::ExecutionMode::DenormPreserve, 16U);
  172. } else {
  173. // LOG_WARNING(HW_GPU, "Fp16 denorm preserve used in shader without host support");
  174. }
  175. }
  176. }
  177. void SetupSignedNanCapabilities(const Profile& profile, const IR::Program& program,
  178. EmitContext& ctx, Id main_func) {
  179. if (program.info.uses_fp16 && profile.support_fp16_signed_zero_nan_preserve) {
  180. ctx.AddCapability(spv::Capability::SignedZeroInfNanPreserve);
  181. ctx.AddExecutionMode(main_func, spv::ExecutionMode::SignedZeroInfNanPreserve, 16U);
  182. }
  183. if (profile.support_fp32_signed_zero_nan_preserve) {
  184. ctx.AddCapability(spv::Capability::SignedZeroInfNanPreserve);
  185. ctx.AddExecutionMode(main_func, spv::ExecutionMode::SignedZeroInfNanPreserve, 32U);
  186. }
  187. if (program.info.uses_fp64 && profile.support_fp64_signed_zero_nan_preserve) {
  188. ctx.AddCapability(spv::Capability::SignedZeroInfNanPreserve);
  189. ctx.AddExecutionMode(main_func, spv::ExecutionMode::SignedZeroInfNanPreserve, 64U);
  190. }
  191. }
  192. void SetupCapabilities(const Profile& profile, const Info& info, EmitContext& ctx) {
  193. if (info.uses_sampled_1d) {
  194. ctx.AddCapability(spv::Capability::Sampled1D);
  195. }
  196. if (info.uses_sparse_residency) {
  197. ctx.AddCapability(spv::Capability::SparseResidency);
  198. }
  199. if (info.uses_demote_to_helper_invocation) {
  200. ctx.AddExtension("SPV_EXT_demote_to_helper_invocation");
  201. ctx.AddCapability(spv::Capability::DemoteToHelperInvocationEXT);
  202. }
  203. if (info.stores_viewport_index) {
  204. ctx.AddCapability(spv::Capability::MultiViewport);
  205. if (profile.support_viewport_index_layer_non_geometry &&
  206. ctx.stage != Shader::Stage::Geometry) {
  207. ctx.AddExtension("SPV_EXT_shader_viewport_index_layer");
  208. ctx.AddCapability(spv::Capability::ShaderViewportIndexLayerEXT);
  209. }
  210. }
  211. if (!profile.support_vertex_instance_id && (info.loads_instance_id || info.loads_vertex_id)) {
  212. ctx.AddExtension("SPV_KHR_shader_draw_parameters");
  213. ctx.AddCapability(spv::Capability::DrawParameters);
  214. }
  215. if ((info.uses_subgroup_vote || info.uses_subgroup_invocation_id) && profile.support_vote) {
  216. ctx.AddExtension("SPV_KHR_shader_ballot");
  217. ctx.AddCapability(spv::Capability::SubgroupBallotKHR);
  218. if (!profile.warp_size_potentially_larger_than_guest) {
  219. // vote ops are only used when not taking the long path
  220. ctx.AddExtension("SPV_KHR_subgroup_vote");
  221. ctx.AddCapability(spv::Capability::SubgroupVoteKHR);
  222. }
  223. }
  224. if (info.uses_typeless_image_reads && profile.support_typeless_image_loads) {
  225. ctx.AddCapability(spv::Capability::StorageImageReadWithoutFormat);
  226. }
  227. // TODO: Track this usage
  228. ctx.AddCapability(spv::Capability::ImageGatherExtended);
  229. ctx.AddCapability(spv::Capability::ImageQuery);
  230. ctx.AddCapability(spv::Capability::SampledBuffer);
  231. }
  232. void PatchPhiNodes(IR::Program& program, EmitContext& ctx) {
  233. auto inst{program.blocks.front()->begin()};
  234. size_t block_index{0};
  235. ctx.PatchDeferredPhi([&](size_t phi_arg) {
  236. if (phi_arg == 0) {
  237. ++inst;
  238. if (inst == program.blocks[block_index]->end() ||
  239. inst->GetOpcode() != IR::Opcode::Phi) {
  240. do {
  241. ++block_index;
  242. inst = program.blocks[block_index]->begin();
  243. } while (inst->GetOpcode() != IR::Opcode::Phi);
  244. }
  245. }
  246. return ctx.Def(inst->Arg(phi_arg));
  247. });
  248. }
  249. } // Anonymous namespace
  250. std::vector<u32> EmitSPIRV(const Profile& profile, IR::Program& program, u32& binding) {
  251. EmitContext ctx{profile, program, binding};
  252. const Id main{DefineMain(ctx, program)};
  253. DefineEntryPoint(program, ctx, main);
  254. if (profile.support_float_controls) {
  255. ctx.AddExtension("SPV_KHR_float_controls");
  256. SetupDenormControl(profile, program, ctx, main);
  257. SetupSignedNanCapabilities(profile, program, ctx, main);
  258. }
  259. SetupCapabilities(profile, program.info, ctx);
  260. PatchPhiNodes(program, ctx);
  261. return ctx.Assemble();
  262. }
  263. Id EmitPhi(EmitContext& ctx, IR::Inst* inst) {
  264. const size_t num_args{inst->NumArgs()};
  265. boost::container::small_vector<Id, 32> blocks;
  266. blocks.reserve(num_args);
  267. for (size_t index = 0; index < num_args; ++index) {
  268. blocks.push_back(inst->PhiBlock(index)->Definition<Id>());
  269. }
  270. // The type of a phi instruction is stored in its flags
  271. const Id result_type{TypeId(ctx, inst->Flags<IR::Type>())};
  272. return ctx.DeferredOpPhi(result_type, std::span(blocks.data(), blocks.size()));
  273. }
  274. void EmitVoid(EmitContext&) {}
  275. Id EmitIdentity(EmitContext& ctx, const IR::Value& value) {
  276. const Id id{ctx.Def(value)};
  277. if (!Sirit::ValidId(id)) {
  278. throw NotImplementedException("Forward identity declaration");
  279. }
  280. return id;
  281. }
  282. void EmitGetZeroFromOp(EmitContext&) {
  283. throw LogicError("Unreachable instruction");
  284. }
  285. void EmitGetSignFromOp(EmitContext&) {
  286. throw LogicError("Unreachable instruction");
  287. }
  288. void EmitGetCarryFromOp(EmitContext&) {
  289. throw LogicError("Unreachable instruction");
  290. }
  291. void EmitGetOverflowFromOp(EmitContext&) {
  292. throw LogicError("Unreachable instruction");
  293. }
  294. void EmitGetSparseFromOp(EmitContext&) {
  295. throw LogicError("Unreachable instruction");
  296. }
  297. void EmitGetInBoundsFromOp(EmitContext&) {
  298. throw LogicError("Unreachable instruction");
  299. }
  300. } // namespace Shader::Backend::SPIRV