Translator.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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. public static ReadOnlySpan<byte> ExtractCode(ReadOnlySpan<byte> code, bool compute, out int headerSize)
  15. {
  16. headerSize = compute ? 0 : HeaderSize;
  17. Block[] cfg = Decoder.Decode(code, (ulong)headerSize);
  18. if (cfg == null)
  19. {
  20. return code;
  21. }
  22. ulong endAddress = 0;
  23. foreach (Block block in cfg)
  24. {
  25. if (endAddress < block.EndAddress)
  26. {
  27. endAddress = block.EndAddress;
  28. }
  29. }
  30. return code.Slice(0, headerSize + (int)endAddress);
  31. }
  32. public static ShaderProgram Translate(ReadOnlySpan<byte> code, TranslatorCallbacks callbacks, TranslationFlags flags)
  33. {
  34. Operation[] ops = DecodeShader(code, callbacks, flags, out ShaderConfig config, out int size);
  35. return Translate(ops, config, size);
  36. }
  37. public static ShaderProgram Translate(ReadOnlySpan<byte> vpACode, ReadOnlySpan<byte> vpBCode, TranslatorCallbacks callbacks, TranslationFlags flags)
  38. {
  39. Operation[] vpAOps = DecodeShader(vpACode, callbacks, flags, out _, out _);
  40. Operation[] vpBOps = DecodeShader(vpBCode, callbacks, flags, out ShaderConfig config, out int sizeB);
  41. return Translate(Combine(vpAOps, vpBOps), config, sizeB);
  42. }
  43. private static ShaderProgram Translate(Operation[] ops, ShaderConfig config, int size)
  44. {
  45. BasicBlock[] blocks = ControlFlowGraph.MakeCfg(ops);
  46. if (blocks.Length > 0)
  47. {
  48. Dominance.FindDominators(blocks[0], blocks.Length);
  49. Dominance.FindDominanceFrontiers(blocks);
  50. Ssa.Rename(blocks);
  51. Optimizer.RunPass(blocks, config);
  52. Lowering.RunPass(blocks, config);
  53. }
  54. StructuredProgramInfo sInfo = StructuredProgram.MakeStructuredProgram(blocks, config);
  55. GlslProgram program = GlslGenerator.Generate(sInfo, config);
  56. ShaderProgramInfo spInfo = new ShaderProgramInfo(
  57. program.CBufferDescriptors,
  58. program.SBufferDescriptors,
  59. program.TextureDescriptors,
  60. program.ImageDescriptors,
  61. sInfo.InterpolationQualifiers,
  62. sInfo.UsesInstanceId);
  63. string glslCode = program.Code;
  64. return new ShaderProgram(spInfo, config.Stage, glslCode, size);
  65. }
  66. private static Operation[] DecodeShader(
  67. ReadOnlySpan<byte> code,
  68. TranslatorCallbacks callbacks,
  69. TranslationFlags flags,
  70. out ShaderConfig config,
  71. out int size)
  72. {
  73. Block[] cfg;
  74. if ((flags & TranslationFlags.Compute) != 0)
  75. {
  76. config = new ShaderConfig(flags, callbacks);
  77. cfg = Decoder.Decode(code, 0);
  78. }
  79. else
  80. {
  81. config = new ShaderConfig(new ShaderHeader(code), flags, callbacks);
  82. cfg = Decoder.Decode(code, HeaderSize);
  83. }
  84. if (cfg == null)
  85. {
  86. config.PrintLog("Invalid branch detected, failed to build CFG.");
  87. size = 0;
  88. return Array.Empty<Operation>();
  89. }
  90. EmitterContext context = new EmitterContext(config);
  91. ulong maxEndAddress = 0;
  92. for (int blkIndex = 0; blkIndex < cfg.Length; blkIndex++)
  93. {
  94. Block block = cfg[blkIndex];
  95. if (maxEndAddress < block.EndAddress)
  96. {
  97. maxEndAddress = block.EndAddress;
  98. }
  99. context.CurrBlock = block;
  100. context.MarkLabel(context.GetLabel(block.Address));
  101. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  102. {
  103. OpCode op = block.OpCodes[opIndex];
  104. if ((flags & TranslationFlags.DebugMode) != 0)
  105. {
  106. string instName;
  107. if (op.Emitter != null)
  108. {
  109. instName = op.Emitter.Method.Name;
  110. }
  111. else
  112. {
  113. instName = "???";
  114. config.PrintLog($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  115. }
  116. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  117. context.Add(new CommentNode(dbgComment));
  118. }
  119. if (op.NeverExecute)
  120. {
  121. continue;
  122. }
  123. Operand predSkipLbl = null;
  124. bool skipPredicateCheck = op is OpCodeBranch opBranch && !opBranch.PushTarget;
  125. if (op is OpCodeBranchPop opBranchPop)
  126. {
  127. // If the instruction is a SYNC or BRK instruction with only one
  128. // possible target address, then the instruction is basically
  129. // just a simple branch, we can generate code similar to branch
  130. // instructions, with the condition check on the branch itself.
  131. skipPredicateCheck = opBranchPop.Targets.Count < 2;
  132. }
  133. if (!(op.Predicate.IsPT || skipPredicateCheck))
  134. {
  135. Operand label;
  136. if (opIndex == block.OpCodes.Count - 1 && block.Next != null)
  137. {
  138. label = context.GetLabel(block.Next.Address);
  139. }
  140. else
  141. {
  142. label = Label();
  143. predSkipLbl = label;
  144. }
  145. Operand pred = Register(op.Predicate);
  146. if (op.InvertPredicate)
  147. {
  148. context.BranchIfTrue(label, pred);
  149. }
  150. else
  151. {
  152. context.BranchIfFalse(label, pred);
  153. }
  154. }
  155. context.CurrOp = op;
  156. op.Emitter?.Invoke(context);
  157. if (predSkipLbl != null)
  158. {
  159. context.MarkLabel(predSkipLbl);
  160. }
  161. }
  162. }
  163. size = (int)maxEndAddress + (((flags & TranslationFlags.Compute) != 0) ? 0 : HeaderSize);
  164. return context.GetOperations();
  165. }
  166. private static Operation[] Combine(Operation[] a, Operation[] b)
  167. {
  168. // Here we combine two shaders.
  169. // For shader A:
  170. // - All user attribute stores on shader A are turned into copies to a
  171. // temporary variable. It's assumed that shader B will consume them.
  172. // - All return instructions are turned into branch instructions, the
  173. // branch target being the start of the shader B code.
  174. // For shader B:
  175. // - All user attribute loads on shader B are turned into copies from a
  176. // temporary variable, as long that attribute is written by shader A.
  177. List<Operation> output = new List<Operation>(a.Length + b.Length);
  178. Operand[] temps = new Operand[AttributeConsts.UserAttributesCount * 4];
  179. Operand lblB = Label();
  180. for (int index = 0; index < a.Length; index++)
  181. {
  182. Operation operation = a[index];
  183. if (IsUserAttribute(operation.Dest))
  184. {
  185. int tIndex = (operation.Dest.Value - AttributeConsts.UserAttributeBase) / 4;
  186. Operand temp = temps[tIndex];
  187. if (temp == null)
  188. {
  189. temp = Local();
  190. temps[tIndex] = temp;
  191. }
  192. operation.Dest = temp;
  193. }
  194. if (operation.Inst == Instruction.Return)
  195. {
  196. output.Add(new Operation(Instruction.Branch, lblB));
  197. }
  198. else
  199. {
  200. output.Add(operation);
  201. }
  202. }
  203. output.Add(new Operation(Instruction.MarkLabel, lblB));
  204. for (int index = 0; index < b.Length; index++)
  205. {
  206. Operation operation = b[index];
  207. for (int srcIndex = 0; srcIndex < operation.SourcesCount; srcIndex++)
  208. {
  209. Operand src = operation.GetSource(srcIndex);
  210. if (IsUserAttribute(src))
  211. {
  212. Operand temp = temps[(src.Value - AttributeConsts.UserAttributeBase) / 4];
  213. if (temp != null)
  214. {
  215. operation.SetSource(srcIndex, temp);
  216. }
  217. }
  218. }
  219. output.Add(operation);
  220. }
  221. return output.ToArray();
  222. }
  223. private static bool IsUserAttribute(Operand operand)
  224. {
  225. return operand != null &&
  226. operand.Type == OperandType.Attribute &&
  227. operand.Value >= AttributeConsts.UserAttributeBase &&
  228. operand.Value < AttributeConsts.UserAttributeEnd;
  229. }
  230. }
  231. }