Translator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  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 System.Numerics;
  9. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  10. namespace Ryujinx.Graphics.Shader.Translation
  11. {
  12. public static class Translator
  13. {
  14. private const int HeaderSize = 0x50;
  15. internal struct FunctionCode
  16. {
  17. public Operation[] Code { get; }
  18. public FunctionCode(Operation[] code)
  19. {
  20. Code = code;
  21. }
  22. }
  23. public static TranslatorContext CreateContext(
  24. ulong address,
  25. IGpuAccessor gpuAccessor,
  26. TranslationOptions options,
  27. TranslationCounts counts = null)
  28. {
  29. counts ??= new TranslationCounts();
  30. Block[][] cfg = DecodeShader(address, gpuAccessor, options, counts, out ShaderConfig config);
  31. return new TranslatorContext(address, cfg, config);
  32. }
  33. internal static ShaderProgram Translate(FunctionCode[] functions, ShaderConfig config, out ShaderProgramInfo shaderProgramInfo)
  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. Rewriter.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. ShaderProgram program;
  70. switch (config.Options.TargetLanguage)
  71. {
  72. case TargetLanguage.Glsl:
  73. program = new ShaderProgram(config.Stage, GlslGenerator.Generate(sInfo, config));
  74. break;
  75. default:
  76. throw new NotImplementedException(config.Options.TargetLanguage.ToString());
  77. }
  78. shaderProgramInfo = new ShaderProgramInfo(
  79. config.GetConstantBufferDescriptors(),
  80. config.GetStorageBufferDescriptors(),
  81. config.GetTextureDescriptors(),
  82. config.GetImageDescriptors(),
  83. config.UsedFeatures.HasFlag(FeatureFlags.InstanceId),
  84. config.UsedFeatures.HasFlag(FeatureFlags.RtLayer),
  85. config.ClipDistancesWritten);
  86. return program;
  87. }
  88. private static Block[][] DecodeShader(
  89. ulong address,
  90. IGpuAccessor gpuAccessor,
  91. TranslationOptions options,
  92. TranslationCounts counts,
  93. out ShaderConfig config)
  94. {
  95. Block[][] cfg;
  96. ulong maxEndAddress = 0;
  97. if ((options.Flags & TranslationFlags.Compute) != 0)
  98. {
  99. config = new ShaderConfig(gpuAccessor, options, counts);
  100. cfg = Decoder.Decode(config, address);
  101. }
  102. else
  103. {
  104. config = new ShaderConfig(new ShaderHeader(gpuAccessor, address), gpuAccessor, options, counts);
  105. cfg = Decoder.Decode(config, address + HeaderSize);
  106. }
  107. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  108. {
  109. for (int blkIndex = 0; blkIndex < cfg[funcIndex].Length; blkIndex++)
  110. {
  111. Block block = cfg[funcIndex][blkIndex];
  112. if (maxEndAddress < block.EndAddress)
  113. {
  114. maxEndAddress = block.EndAddress;
  115. }
  116. if (!config.UsedFeatures.HasFlag(FeatureFlags.Bindless))
  117. {
  118. for (int index = 0; index < block.OpCodes.Count; index++)
  119. {
  120. if (block.OpCodes[index] is OpCodeTextureBase texture)
  121. {
  122. config.TextureHandlesForCache.Add(texture.HandleOffset);
  123. }
  124. }
  125. }
  126. }
  127. }
  128. config.SizeAdd((int)maxEndAddress + (options.Flags.HasFlag(TranslationFlags.Compute) ? 0 : HeaderSize));
  129. return cfg;
  130. }
  131. internal static FunctionCode[] EmitShader(Block[][] cfg, ShaderConfig config, bool initializeOutputs, out int initializationOperations)
  132. {
  133. initializationOperations = 0;
  134. Dictionary<ulong, int> funcIds = new Dictionary<ulong, int>();
  135. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  136. {
  137. funcIds.Add(cfg[funcIndex][0].Address, funcIndex);
  138. }
  139. List<FunctionCode> funcs = new List<FunctionCode>();
  140. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  141. {
  142. EmitterContext context = new EmitterContext(config, funcIndex != 0, funcIds);
  143. if (initializeOutputs && funcIndex == 0)
  144. {
  145. EmitOutputsInitialization(context, config);
  146. initializationOperations = context.OperationsCount;
  147. }
  148. for (int blkIndex = 0; blkIndex < cfg[funcIndex].Length; blkIndex++)
  149. {
  150. Block block = cfg[funcIndex][blkIndex];
  151. context.CurrBlock = block;
  152. context.MarkLabel(context.GetLabel(block.Address));
  153. EmitOps(context, block);
  154. }
  155. funcs.Add(new FunctionCode(context.GetOperations()));
  156. }
  157. return funcs.ToArray();
  158. }
  159. private static void EmitOutputsInitialization(EmitterContext context, ShaderConfig config)
  160. {
  161. // Compute has no output attributes, and fragment is the last stage, so we
  162. // don't need to initialize outputs on those stages.
  163. if (config.Stage == ShaderStage.Compute || config.Stage == ShaderStage.Fragment)
  164. {
  165. return;
  166. }
  167. void InitializeOutput(int baseAttr)
  168. {
  169. for (int c = 0; c < 4; c++)
  170. {
  171. context.Copy(Attribute(baseAttr + c * 4), ConstF(c == 3 ? 1f : 0f));
  172. }
  173. }
  174. if (config.Stage == ShaderStage.Vertex)
  175. {
  176. InitializeOutput(AttributeConsts.PositionX);
  177. }
  178. int usedAttribtes = context.Config.UsedOutputAttributes;
  179. while (usedAttribtes != 0)
  180. {
  181. int index = BitOperations.TrailingZeroCount(usedAttribtes);
  182. InitializeOutput(AttributeConsts.UserAttributeBase + index * 16);
  183. usedAttribtes &= ~(1 << index);
  184. }
  185. }
  186. private static void EmitOps(EmitterContext context, Block block)
  187. {
  188. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  189. {
  190. OpCode op = block.OpCodes[opIndex];
  191. if ((context.Config.Options.Flags & TranslationFlags.DebugMode) != 0)
  192. {
  193. string instName;
  194. if (op.Emitter != null)
  195. {
  196. instName = op.Emitter.Method.Name;
  197. }
  198. else
  199. {
  200. instName = "???";
  201. context.Config.GpuAccessor.Log($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  202. }
  203. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  204. context.Add(new CommentNode(dbgComment));
  205. }
  206. if (op.NeverExecute)
  207. {
  208. continue;
  209. }
  210. Operand predSkipLbl = null;
  211. bool skipPredicateCheck = op is OpCodeBranch opBranch && !opBranch.PushTarget;
  212. if (op is OpCodeBranchPop opBranchPop)
  213. {
  214. // If the instruction is a SYNC or BRK instruction with only one
  215. // possible target address, then the instruction is basically
  216. // just a simple branch, we can generate code similar to branch
  217. // instructions, with the condition check on the branch itself.
  218. skipPredicateCheck = opBranchPop.Targets.Count < 2;
  219. }
  220. if (!(op.Predicate.IsPT || skipPredicateCheck))
  221. {
  222. Operand label;
  223. if (opIndex == block.OpCodes.Count - 1 && block.Next != null)
  224. {
  225. label = context.GetLabel(block.Next.Address);
  226. }
  227. else
  228. {
  229. label = Label();
  230. predSkipLbl = label;
  231. }
  232. Operand pred = Register(op.Predicate);
  233. if (op.InvertPredicate)
  234. {
  235. context.BranchIfTrue(label, pred);
  236. }
  237. else
  238. {
  239. context.BranchIfFalse(label, pred);
  240. }
  241. }
  242. context.CurrOp = op;
  243. op.Emitter?.Invoke(context);
  244. if (predSkipLbl != null)
  245. {
  246. context.MarkLabel(predSkipLbl);
  247. }
  248. }
  249. }
  250. }
  251. }