Translator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. using Ryujinx.Graphics.Shader.CodeGen.Glsl;
  2. using Ryujinx.Graphics.Shader.Decoders;
  3. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  4. using Ryujinx.Graphics.Shader.StructuredIr;
  5. using Ryujinx.Graphics.Shader.Translation.Optimizations;
  6. using System;
  7. using System.Collections.Generic;
  8. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  9. namespace Ryujinx.Graphics.Shader.Translation
  10. {
  11. public static class Translator
  12. {
  13. private const int HeaderSize = 0x50;
  14. private struct FunctionCode
  15. {
  16. public Operation[] Code { get; }
  17. public FunctionCode(Operation[] code)
  18. {
  19. Code = code;
  20. }
  21. }
  22. public static ShaderProgram Translate(ulong address, IGpuAccessor gpuAccessor, TranslationFlags flags)
  23. {
  24. return Translate(DecodeShader(address, gpuAccessor, flags, out ShaderConfig config), config);
  25. }
  26. public static ShaderProgram Translate(ulong addressA, ulong addressB, IGpuAccessor gpuAccessor, TranslationFlags flags)
  27. {
  28. FunctionCode[] funcA = DecodeShader(addressA, gpuAccessor, flags | TranslationFlags.VertexA, out ShaderConfig configA);
  29. FunctionCode[] funcB = DecodeShader(addressB, gpuAccessor, flags, out ShaderConfig config);
  30. config.SetUsedFeature(configA.UsedFeatures);
  31. return Translate(Combine(funcA, funcB), config, configA.Size);
  32. }
  33. private static ShaderProgram Translate(FunctionCode[] functions, ShaderConfig config, int sizeA = 0)
  34. {
  35. var cfgs = new ControlFlowGraph[functions.Length];
  36. var frus = new RegisterUsage.FunctionRegisterUsage[functions.Length];
  37. for (int i = 0; i < functions.Length; i++)
  38. {
  39. cfgs[i] = ControlFlowGraph.Create(functions[i].Code);
  40. if (i != 0)
  41. {
  42. frus[i] = RegisterUsage.RunPass(cfgs[i]);
  43. }
  44. }
  45. Function[] funcs = new Function[functions.Length];
  46. for (int i = 0; i < functions.Length; i++)
  47. {
  48. var cfg = cfgs[i];
  49. int inArgumentsCount = 0;
  50. int outArgumentsCount = 0;
  51. if (i != 0)
  52. {
  53. var fru = frus[i];
  54. inArgumentsCount = fru.InArguments.Length;
  55. outArgumentsCount = fru.OutArguments.Length;
  56. }
  57. if (cfg.Blocks.Length != 0)
  58. {
  59. RegisterUsage.FixupCalls(cfg.Blocks, frus);
  60. Dominance.FindDominators(cfg);
  61. Dominance.FindDominanceFrontiers(cfg.Blocks);
  62. Ssa.Rename(cfg.Blocks);
  63. Optimizer.RunPass(cfg.Blocks, config);
  64. Lowering.RunPass(cfg.Blocks, config);
  65. }
  66. funcs[i] = new Function(cfg.Blocks, $"fun{i}", false, inArgumentsCount, outArgumentsCount);
  67. }
  68. StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram(funcs, config);
  69. GlslProgram program = GlslGenerator.Generate(sInfo, config);
  70. ShaderProgramInfo spInfo = new ShaderProgramInfo(
  71. program.CBufferDescriptors,
  72. program.SBufferDescriptors,
  73. program.TextureDescriptors,
  74. program.ImageDescriptors,
  75. sInfo.UsesInstanceId);
  76. string glslCode = program.Code;
  77. return new ShaderProgram(spInfo, config.Stage, glslCode, config.Size, sizeA);
  78. }
  79. private static FunctionCode[] DecodeShader(ulong address, IGpuAccessor gpuAccessor, TranslationFlags flags, out ShaderConfig config)
  80. {
  81. Block[][] cfg;
  82. if ((flags & TranslationFlags.Compute) != 0)
  83. {
  84. config = new ShaderConfig(gpuAccessor, flags);
  85. cfg = Decoder.Decode(gpuAccessor, address);
  86. }
  87. else
  88. {
  89. config = new ShaderConfig(new ShaderHeader(gpuAccessor, address), gpuAccessor, flags);
  90. cfg = Decoder.Decode(gpuAccessor, address + HeaderSize);
  91. }
  92. if (cfg == null)
  93. {
  94. gpuAccessor.Log("Invalid branch detected, failed to build CFG.");
  95. return Array.Empty<FunctionCode>();
  96. }
  97. Dictionary<ulong, int> funcIds = new Dictionary<ulong, int>();
  98. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  99. {
  100. funcIds.Add(cfg[funcIndex][0].Address, funcIndex);
  101. }
  102. List<FunctionCode> funcs = new List<FunctionCode>();
  103. ulong maxEndAddress = 0;
  104. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  105. {
  106. EmitterContext context = new EmitterContext(config, funcIndex != 0, funcIds);
  107. for (int blkIndex = 0; blkIndex < cfg[funcIndex].Length; blkIndex++)
  108. {
  109. Block block = cfg[funcIndex][blkIndex];
  110. if (maxEndAddress < block.EndAddress)
  111. {
  112. maxEndAddress = block.EndAddress;
  113. }
  114. context.CurrBlock = block;
  115. context.MarkLabel(context.GetLabel(block.Address));
  116. EmitOps(context, block);
  117. }
  118. funcs.Add(new FunctionCode(context.GetOperations()));
  119. }
  120. config.SizeAdd((int)maxEndAddress + (flags.HasFlag(TranslationFlags.Compute) ? 0 : HeaderSize));
  121. return funcs.ToArray();
  122. }
  123. internal static void EmitOps(EmitterContext context, Block block)
  124. {
  125. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  126. {
  127. OpCode op = block.OpCodes[opIndex];
  128. if ((context.Config.Flags & TranslationFlags.DebugMode) != 0)
  129. {
  130. string instName;
  131. if (op.Emitter != null)
  132. {
  133. instName = op.Emitter.Method.Name;
  134. }
  135. else
  136. {
  137. instName = "???";
  138. context.Config.GpuAccessor.Log($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  139. }
  140. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  141. context.Add(new CommentNode(dbgComment));
  142. }
  143. if (op.NeverExecute)
  144. {
  145. continue;
  146. }
  147. Operand predSkipLbl = null;
  148. bool skipPredicateCheck = op is OpCodeBranch opBranch && !opBranch.PushTarget;
  149. if (op is OpCodeBranchPop opBranchPop)
  150. {
  151. // If the instruction is a SYNC or BRK instruction with only one
  152. // possible target address, then the instruction is basically
  153. // just a simple branch, we can generate code similar to branch
  154. // instructions, with the condition check on the branch itself.
  155. skipPredicateCheck = opBranchPop.Targets.Count < 2;
  156. }
  157. if (!(op.Predicate.IsPT || skipPredicateCheck))
  158. {
  159. Operand label;
  160. if (opIndex == block.OpCodes.Count - 1 && block.Next != null)
  161. {
  162. label = context.GetLabel(block.Next.Address);
  163. }
  164. else
  165. {
  166. label = Label();
  167. predSkipLbl = label;
  168. }
  169. Operand pred = Register(op.Predicate);
  170. if (op.InvertPredicate)
  171. {
  172. context.BranchIfTrue(label, pred);
  173. }
  174. else
  175. {
  176. context.BranchIfFalse(label, pred);
  177. }
  178. }
  179. context.CurrOp = op;
  180. op.Emitter?.Invoke(context);
  181. if (predSkipLbl != null)
  182. {
  183. context.MarkLabel(predSkipLbl);
  184. }
  185. }
  186. }
  187. private static FunctionCode[] Combine(FunctionCode[] a, FunctionCode[] b)
  188. {
  189. // Here we combine two shaders.
  190. // For shader A:
  191. // - All user attribute stores on shader A are turned into copies to a
  192. // temporary variable. It's assumed that shader B will consume them.
  193. // - All return instructions are turned into branch instructions, the
  194. // branch target being the start of the shader B code.
  195. // For shader B:
  196. // - All user attribute loads on shader B are turned into copies from a
  197. // temporary variable, as long that attribute is written by shader A.
  198. FunctionCode[] output = new FunctionCode[a.Length + b.Length - 1];
  199. List<Operation> ops = new List<Operation>(a.Length + b.Length);
  200. Operand[] temps = new Operand[AttributeConsts.UserAttributesCount * 4];
  201. Operand lblB = Label();
  202. for (int index = 0; index < a[0].Code.Length; index++)
  203. {
  204. Operation operation = a[0].Code[index];
  205. if (IsUserAttribute(operation.Dest))
  206. {
  207. int tIndex = (operation.Dest.Value - AttributeConsts.UserAttributeBase) / 4;
  208. Operand temp = temps[tIndex];
  209. if (temp == null)
  210. {
  211. temp = Local();
  212. temps[tIndex] = temp;
  213. }
  214. operation.Dest = temp;
  215. }
  216. if (operation.Inst == Instruction.Return)
  217. {
  218. ops.Add(new Operation(Instruction.Branch, lblB));
  219. }
  220. else
  221. {
  222. ops.Add(operation);
  223. }
  224. }
  225. ops.Add(new Operation(Instruction.MarkLabel, lblB));
  226. for (int index = 0; index < b[0].Code.Length; index++)
  227. {
  228. Operation operation = b[0].Code[index];
  229. for (int srcIndex = 0; srcIndex < operation.SourcesCount; srcIndex++)
  230. {
  231. Operand src = operation.GetSource(srcIndex);
  232. if (IsUserAttribute(src))
  233. {
  234. Operand temp = temps[(src.Value - AttributeConsts.UserAttributeBase) / 4];
  235. if (temp != null)
  236. {
  237. operation.SetSource(srcIndex, temp);
  238. }
  239. }
  240. }
  241. ops.Add(operation);
  242. }
  243. output[0] = new FunctionCode(ops.ToArray());
  244. for (int i = 1; i < a.Length; i++)
  245. {
  246. output[i] = a[i];
  247. }
  248. for (int i = 1; i < b.Length; i++)
  249. {
  250. output[a.Length + i - 1] = b[i];
  251. }
  252. return output;
  253. }
  254. private static bool IsUserAttribute(Operand operand)
  255. {
  256. return operand != null &&
  257. operand.Type == OperandType.Attribute &&
  258. operand.Value >= AttributeConsts.UserAttributeBase &&
  259. operand.Value < AttributeConsts.UserAttributeEnd;
  260. }
  261. }
  262. }