Translator.cs 12 KB

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