emit_glsl.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. // Copyright 2021 yuzu Emulator Project
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #include <algorithm>
  5. #include <string>
  6. #include <tuple>
  7. #include <type_traits>
  8. #include "common/div_ceil.h"
  9. #include "common/settings.h"
  10. #include "shader_recompiler/backend/glsl/emit_context.h"
  11. #include "shader_recompiler/backend/glsl/emit_glsl.h"
  12. #include "shader_recompiler/backend/glsl/emit_glsl_instructions.h"
  13. #include "shader_recompiler/frontend/ir/ir_emitter.h"
  14. namespace Shader::Backend::GLSL {
  15. namespace {
  16. template <class Func>
  17. struct FuncTraits {};
  18. template <class ReturnType_, class... Args>
  19. struct FuncTraits<ReturnType_ (*)(Args...)> {
  20. using ReturnType = ReturnType_;
  21. static constexpr size_t NUM_ARGS = sizeof...(Args);
  22. template <size_t I>
  23. using ArgType = std::tuple_element_t<I, std::tuple<Args...>>;
  24. };
  25. template <auto func, typename... Args>
  26. void SetDefinition(EmitContext& ctx, IR::Inst* inst, Args... args) {
  27. inst->SetDefinition<Id>(func(ctx, std::forward<Args>(args)...));
  28. }
  29. template <typename ArgType>
  30. auto Arg(EmitContext& ctx, const IR::Value& arg) {
  31. if constexpr (std::is_same_v<ArgType, std::string_view>) {
  32. return ctx.var_alloc.Consume(arg);
  33. } else if constexpr (std::is_same_v<ArgType, const IR::Value&>) {
  34. return arg;
  35. } else if constexpr (std::is_same_v<ArgType, u32>) {
  36. return arg.U32();
  37. } else if constexpr (std::is_same_v<ArgType, IR::Attribute>) {
  38. return arg.Attribute();
  39. } else if constexpr (std::is_same_v<ArgType, IR::Patch>) {
  40. return arg.Patch();
  41. } else if constexpr (std::is_same_v<ArgType, IR::Reg>) {
  42. return arg.Reg();
  43. }
  44. }
  45. template <auto func, bool is_first_arg_inst, size_t... I>
  46. void Invoke(EmitContext& ctx, IR::Inst* inst, std::index_sequence<I...>) {
  47. using Traits = FuncTraits<decltype(func)>;
  48. if constexpr (std::is_same_v<typename Traits::ReturnType, Id>) {
  49. if constexpr (is_first_arg_inst) {
  50. SetDefinition<func>(
  51. ctx, inst, *inst,
  52. Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...);
  53. } else {
  54. SetDefinition<func>(
  55. ctx, inst, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...);
  56. }
  57. } else {
  58. if constexpr (is_first_arg_inst) {
  59. func(ctx, *inst, Arg<typename Traits::template ArgType<I + 2>>(ctx, inst->Arg(I))...);
  60. } else {
  61. func(ctx, Arg<typename Traits::template ArgType<I + 1>>(ctx, inst->Arg(I))...);
  62. }
  63. }
  64. }
  65. template <auto func>
  66. void Invoke(EmitContext& ctx, IR::Inst* inst) {
  67. using Traits = FuncTraits<decltype(func)>;
  68. static_assert(Traits::NUM_ARGS >= 1, "Insufficient arguments");
  69. if constexpr (Traits::NUM_ARGS == 1) {
  70. Invoke<func, false>(ctx, inst, std::make_index_sequence<0>{});
  71. } else {
  72. using FirstArgType = typename Traits::template ArgType<1>;
  73. static constexpr bool is_first_arg_inst = std::is_same_v<FirstArgType, IR::Inst&>;
  74. using Indices = std::make_index_sequence<Traits::NUM_ARGS - (is_first_arg_inst ? 2 : 1)>;
  75. Invoke<func, is_first_arg_inst>(ctx, inst, Indices{});
  76. }
  77. }
  78. void EmitInst(EmitContext& ctx, IR::Inst* inst) {
  79. switch (inst->GetOpcode()) {
  80. #define OPCODE(name, result_type, ...) \
  81. case IR::Opcode::name: \
  82. return Invoke<&Emit##name>(ctx, inst);
  83. #include "shader_recompiler/frontend/ir/opcodes.inc"
  84. #undef OPCODE
  85. }
  86. throw LogicError("Invalid opcode {}", inst->GetOpcode());
  87. }
  88. bool IsReference(IR::Inst& inst) {
  89. return inst.GetOpcode() == IR::Opcode::Reference;
  90. }
  91. void PrecolorInst(IR::Inst& phi) {
  92. // Insert phi moves before references to avoid overwritting other phis
  93. const size_t num_args{phi.NumArgs()};
  94. for (size_t i = 0; i < num_args; ++i) {
  95. IR::Block& phi_block{*phi.PhiBlock(i)};
  96. auto it{std::find_if_not(phi_block.rbegin(), phi_block.rend(), IsReference).base()};
  97. IR::IREmitter ir{phi_block, it};
  98. const IR::Value arg{phi.Arg(i)};
  99. if (arg.IsImmediate()) {
  100. ir.PhiMove(phi, arg);
  101. } else {
  102. ir.PhiMove(phi, IR::Value{arg.InstRecursive()});
  103. }
  104. }
  105. for (size_t i = 0; i < num_args; ++i) {
  106. IR::IREmitter{*phi.PhiBlock(i)}.Reference(IR::Value{&phi});
  107. }
  108. }
  109. void Precolor(const IR::Program& program) {
  110. for (IR::Block* const block : program.blocks) {
  111. for (IR::Inst& phi : block->Instructions()) {
  112. if (!IR::IsPhi(phi)) {
  113. break;
  114. }
  115. PrecolorInst(phi);
  116. }
  117. }
  118. }
  119. void EmitCode(EmitContext& ctx, const IR::Program& program) {
  120. for (const IR::AbstractSyntaxNode& node : program.syntax_list) {
  121. switch (node.type) {
  122. case IR::AbstractSyntaxNode::Type::Block:
  123. for (IR::Inst& inst : node.data.block->Instructions()) {
  124. EmitInst(ctx, &inst);
  125. }
  126. break;
  127. case IR::AbstractSyntaxNode::Type::If:
  128. ctx.Add("if({}){{", ctx.var_alloc.Consume(node.data.if_node.cond));
  129. break;
  130. case IR::AbstractSyntaxNode::Type::EndIf:
  131. ctx.Add("}}");
  132. break;
  133. case IR::AbstractSyntaxNode::Type::Break:
  134. if (node.data.break_node.cond.IsImmediate()) {
  135. if (node.data.break_node.cond.U1()) {
  136. ctx.Add("break;");
  137. }
  138. } else {
  139. ctx.Add("if({}){{break;}}", ctx.var_alloc.Consume(node.data.break_node.cond));
  140. }
  141. break;
  142. case IR::AbstractSyntaxNode::Type::Return:
  143. case IR::AbstractSyntaxNode::Type::Unreachable:
  144. ctx.Add("return;");
  145. break;
  146. case IR::AbstractSyntaxNode::Type::Loop:
  147. ctx.Add("for(;;){{");
  148. break;
  149. case IR::AbstractSyntaxNode::Type::Repeat:
  150. if (Settings::values.disable_shader_loop_safety_checks) {
  151. ctx.Add("if(!{}){{break;}}}}", ctx.var_alloc.Consume(node.data.repeat.cond));
  152. } else {
  153. ctx.Add("if(--loop{}<0 || !{}){{break;}}}}", ctx.num_safety_loop_vars++,
  154. ctx.var_alloc.Consume(node.data.repeat.cond));
  155. }
  156. break;
  157. default:
  158. throw NotImplementedException("AbstractSyntaxNode Type {}", node.type);
  159. }
  160. }
  161. }
  162. std::string GlslVersionSpecifier(const EmitContext& ctx) {
  163. if (ctx.uses_y_direction || ctx.info.stores.Legacy() || ctx.info.loads.Legacy()) {
  164. return " compatibility";
  165. }
  166. return "";
  167. }
  168. bool IsPreciseType(GlslVarType type) {
  169. switch (type) {
  170. case GlslVarType::PrecF32:
  171. case GlslVarType::PrecF64:
  172. return true;
  173. default:
  174. return false;
  175. }
  176. }
  177. void DefineVariables(const EmitContext& ctx, std::string& header) {
  178. for (u32 i = 0; i < static_cast<u32>(GlslVarType::Void); ++i) {
  179. const auto type{static_cast<GlslVarType>(i)};
  180. const auto& tracker{ctx.var_alloc.GetUseTracker(type)};
  181. const auto type_name{ctx.var_alloc.GetGlslType(type)};
  182. const bool has_precise_bug{ctx.stage == Stage::Fragment && ctx.profile.has_gl_precise_bug};
  183. const auto precise{!has_precise_bug && IsPreciseType(type) ? "precise " : ""};
  184. // Temps/return types that are never used are stored at index 0
  185. if (tracker.uses_temp) {
  186. header += fmt::format("{}{} t{}={}(0);", precise, type_name,
  187. ctx.var_alloc.Representation(0, type), type_name);
  188. }
  189. for (u32 index = 0; index < tracker.num_used; ++index) {
  190. header += fmt::format("{}{} {}={}(0);", precise, type_name,
  191. ctx.var_alloc.Representation(index, type), type_name);
  192. }
  193. }
  194. for (u32 i = 0; i < ctx.num_safety_loop_vars; ++i) {
  195. header += fmt::format("int loop{}=0x2000;", i);
  196. }
  197. }
  198. } // Anonymous namespace
  199. std::string EmitGLSL(const Profile& profile, const RuntimeInfo& runtime_info, IR::Program& program,
  200. Bindings& bindings) {
  201. EmitContext ctx{program, bindings, profile, runtime_info};
  202. Precolor(program);
  203. EmitCode(ctx, program);
  204. const std::string version{fmt::format("#version 450{}\n", GlslVersionSpecifier(ctx))};
  205. ctx.header.insert(0, version);
  206. if (program.shared_memory_size > 0) {
  207. const auto requested_size{program.shared_memory_size};
  208. const auto max_size{profile.gl_max_compute_smem_size};
  209. const bool needs_clamp{requested_size > max_size};
  210. if (needs_clamp) {
  211. LOG_WARNING(Shader_GLSL, "Requested shared memory size ({}) exceeds device limit ({})",
  212. requested_size, max_size);
  213. }
  214. const auto smem_size{needs_clamp ? max_size : requested_size};
  215. ctx.header += fmt::format("shared uint smem[{}];", Common::DivCeil(smem_size, 4U));
  216. }
  217. ctx.header += "void main(){\n";
  218. if (program.local_memory_size > 0) {
  219. ctx.header += fmt::format("uint lmem[{}];", Common::DivCeil(program.local_memory_size, 4U));
  220. }
  221. DefineVariables(ctx, ctx.header);
  222. if (ctx.uses_cc_carry) {
  223. ctx.header += "uint carry;";
  224. }
  225. if (program.info.uses_subgroup_shuffles) {
  226. ctx.header += "bool shfl_in_bounds;";
  227. }
  228. ctx.code.insert(0, ctx.header);
  229. ctx.code += '}';
  230. return ctx.code;
  231. }
  232. } // namespace Shader::Backend::GLSL