emit_glsl.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // SPDX-FileCopyrightText: Copyright 2021 yuzu Emulator Project
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include <algorithm>
  4. #include <string>
  5. #include <tuple>
  6. #include <type_traits>
  7. #include "common/div_ceil.h"
  8. #include "common/settings.h"
  9. #include "shader_recompiler/backend/glsl/emit_glsl.h"
  10. #include "shader_recompiler/backend/glsl/emit_glsl_instructions.h"
  11. #include "shader_recompiler/backend/glsl/glsl_emit_context.h"
  12. #include "shader_recompiler/frontend/ir/ir_emitter.h"
  13. namespace Shader::Backend::GLSL {
  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. auto Arg(EmitContext& ctx, const IR::Value& arg) {
  30. if constexpr (std::is_same_v<ArgType, std::string_view>) {
  31. return ctx.var_alloc.Consume(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::Attribute>) {
  37. return arg.Attribute();
  38. } else if constexpr (std::is_same_v<ArgType, IR::Patch>) {
  39. return arg.Patch();
  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. bool IsReference(IR::Inst& inst) {
  88. return inst.GetOpcode() == IR::Opcode::Reference;
  89. }
  90. void PrecolorInst(IR::Inst& phi) {
  91. // Insert phi moves before references to avoid overwriting other phis
  92. const size_t num_args{phi.NumArgs()};
  93. for (size_t i = 0; i < num_args; ++i) {
  94. IR::Block& phi_block{*phi.PhiBlock(i)};
  95. auto it{std::find_if_not(phi_block.rbegin(), phi_block.rend(), IsReference).base()};
  96. IR::IREmitter ir{phi_block, it};
  97. const IR::Value arg{phi.Arg(i)};
  98. if (arg.IsImmediate()) {
  99. ir.PhiMove(phi, arg);
  100. } else {
  101. ir.PhiMove(phi, IR::Value{arg.InstRecursive()});
  102. }
  103. }
  104. for (size_t i = 0; i < num_args; ++i) {
  105. IR::IREmitter{*phi.PhiBlock(i)}.Reference(IR::Value{&phi});
  106. }
  107. }
  108. void Precolor(const IR::Program& program) {
  109. for (IR::Block* const block : program.blocks) {
  110. for (IR::Inst& phi : block->Instructions()) {
  111. if (!IR::IsPhi(phi)) {
  112. break;
  113. }
  114. PrecolorInst(phi);
  115. }
  116. }
  117. }
  118. void EmitCode(EmitContext& ctx, const IR::Program& program) {
  119. for (const IR::AbstractSyntaxNode& node : program.syntax_list) {
  120. switch (node.type) {
  121. case IR::AbstractSyntaxNode::Type::Block:
  122. for (IR::Inst& inst : node.data.block->Instructions()) {
  123. EmitInst(ctx, &inst);
  124. }
  125. break;
  126. case IR::AbstractSyntaxNode::Type::If:
  127. ctx.Add("if({}){{", ctx.var_alloc.Consume(node.data.if_node.cond));
  128. break;
  129. case IR::AbstractSyntaxNode::Type::EndIf:
  130. ctx.Add("}}");
  131. break;
  132. case IR::AbstractSyntaxNode::Type::Break:
  133. if (node.data.break_node.cond.IsImmediate()) {
  134. if (node.data.break_node.cond.U1()) {
  135. ctx.Add("break;");
  136. }
  137. } else {
  138. ctx.Add("if({}){{break;}}", ctx.var_alloc.Consume(node.data.break_node.cond));
  139. }
  140. break;
  141. case IR::AbstractSyntaxNode::Type::Return:
  142. case IR::AbstractSyntaxNode::Type::Unreachable:
  143. ctx.Add("return;");
  144. break;
  145. case IR::AbstractSyntaxNode::Type::Loop:
  146. ctx.Add("for(;;){{");
  147. break;
  148. case IR::AbstractSyntaxNode::Type::Repeat:
  149. if (Settings::values.disable_shader_loop_safety_checks) {
  150. ctx.Add("if(!{}){{break;}}}}", ctx.var_alloc.Consume(node.data.repeat.cond));
  151. } else {
  152. ctx.Add("if(--loop{}<0 || !{}){{break;}}}}", ctx.num_safety_loop_vars++,
  153. ctx.var_alloc.Consume(node.data.repeat.cond));
  154. }
  155. break;
  156. default:
  157. throw NotImplementedException("AbstractSyntaxNode Type {}", node.type);
  158. }
  159. }
  160. }
  161. std::string GlslVersionSpecifier(const EmitContext& ctx) {
  162. if (ctx.uses_y_direction) {
  163. return " compatibility";
  164. }
  165. return "";
  166. }
  167. bool IsPreciseType(GlslVarType type) {
  168. switch (type) {
  169. case GlslVarType::PrecF32:
  170. case GlslVarType::PrecF64:
  171. return true;
  172. default:
  173. return false;
  174. }
  175. }
  176. void DefineVariables(const EmitContext& ctx, std::string& header) {
  177. for (u32 i = 0; i < static_cast<u32>(GlslVarType::Void); ++i) {
  178. const auto type{static_cast<GlslVarType>(i)};
  179. const auto& tracker{ctx.var_alloc.GetUseTracker(type)};
  180. const auto type_name{ctx.var_alloc.GetGlslType(type)};
  181. const bool has_precise_bug{ctx.stage == Stage::Fragment && ctx.profile.has_gl_precise_bug};
  182. const auto precise{!has_precise_bug && IsPreciseType(type) ? "precise " : ""};
  183. // Temps/return types that are never used are stored at index 0
  184. if (tracker.uses_temp) {
  185. header += fmt::format("{}{} t{}={}(0);", precise, type_name,
  186. ctx.var_alloc.Representation(0, type), type_name);
  187. }
  188. for (u32 index = 0; index < tracker.num_used; ++index) {
  189. header += fmt::format("{}{} {}={}(0);", precise, type_name,
  190. ctx.var_alloc.Representation(index, type), type_name);
  191. }
  192. }
  193. for (u32 i = 0; i < ctx.num_safety_loop_vars; ++i) {
  194. header += fmt::format("int loop{}=0x2000;", i);
  195. }
  196. }
  197. } // Anonymous namespace
  198. std::string EmitGLSL(const Profile& profile, const RuntimeInfo& runtime_info, IR::Program& program,
  199. Bindings& bindings) {
  200. EmitContext ctx{program, bindings, profile, runtime_info};
  201. Precolor(program);
  202. EmitCode(ctx, program);
  203. const std::string version{fmt::format("#version 460{}\n", GlslVersionSpecifier(ctx))};
  204. ctx.header.insert(0, version);
  205. if (program.shared_memory_size > 0) {
  206. const auto requested_size{program.shared_memory_size};
  207. const auto max_size{profile.gl_max_compute_smem_size};
  208. const bool needs_clamp{requested_size > max_size};
  209. if (needs_clamp) {
  210. LOG_WARNING(Shader_GLSL, "Requested shared memory size ({}) exceeds device limit ({})",
  211. requested_size, max_size);
  212. }
  213. const auto smem_size{needs_clamp ? max_size : requested_size};
  214. ctx.header += fmt::format("shared uint smem[{}];", Common::DivCeil(smem_size, 4U));
  215. }
  216. ctx.header += "void main(){\n";
  217. if (program.local_memory_size > 0) {
  218. ctx.header += fmt::format("uint lmem[{}];", Common::DivCeil(program.local_memory_size, 4U));
  219. }
  220. DefineVariables(ctx, ctx.header);
  221. if (ctx.uses_cc_carry) {
  222. ctx.header += "uint carry;";
  223. }
  224. if (program.info.uses_subgroup_shuffles) {
  225. ctx.header += "bool shfl_in_bounds;";
  226. ctx.header += "uint shfl_result;";
  227. }
  228. ctx.code.insert(0, ctx.header);
  229. ctx.code += '}';
  230. return ctx.code;
  231. }
  232. } // namespace Shader::Backend::GLSL