Translator.cs 10 KB

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