Translator.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. InstOp op = block.OpCodes[index];
  121. if (op.Props.HasFlag(InstProps.Tex))
  122. {
  123. int tidB = (int)((op.RawOpCode >> 36) & 0x1fff);
  124. config.TextureHandlesForCache.Add(tidB);
  125. }
  126. }
  127. }
  128. }
  129. }
  130. config.SizeAdd((int)maxEndAddress + (options.Flags.HasFlag(TranslationFlags.Compute) ? 0 : HeaderSize));
  131. return cfg;
  132. }
  133. internal static FunctionCode[] EmitShader(Block[][] cfg, ShaderConfig config, bool initializeOutputs, out int initializationOperations)
  134. {
  135. initializationOperations = 0;
  136. Dictionary<ulong, int> funcIds = new Dictionary<ulong, int>();
  137. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  138. {
  139. funcIds.Add(cfg[funcIndex][0].Address, funcIndex);
  140. }
  141. List<FunctionCode> funcs = new List<FunctionCode>();
  142. for (int funcIndex = 0; funcIndex < cfg.Length; funcIndex++)
  143. {
  144. EmitterContext context = new EmitterContext(config, funcIndex != 0, funcIds);
  145. if (initializeOutputs && funcIndex == 0)
  146. {
  147. EmitOutputsInitialization(context, config);
  148. initializationOperations = context.OperationsCount;
  149. }
  150. for (int blkIndex = 0; blkIndex < cfg[funcIndex].Length; blkIndex++)
  151. {
  152. Block block = cfg[funcIndex][blkIndex];
  153. context.CurrBlock = block;
  154. context.MarkLabel(context.GetLabel(block.Address));
  155. EmitOps(context, block);
  156. }
  157. funcs.Add(new FunctionCode(context.GetOperations()));
  158. }
  159. return funcs.ToArray();
  160. }
  161. private static void EmitOutputsInitialization(EmitterContext context, ShaderConfig config)
  162. {
  163. // Compute has no output attributes, and fragment is the last stage, so we
  164. // don't need to initialize outputs on those stages.
  165. if (config.Stage == ShaderStage.Compute || config.Stage == ShaderStage.Fragment)
  166. {
  167. return;
  168. }
  169. void InitializeOutput(int baseAttr)
  170. {
  171. for (int c = 0; c < 4; c++)
  172. {
  173. context.Copy(Attribute(baseAttr + c * 4), ConstF(c == 3 ? 1f : 0f));
  174. }
  175. }
  176. if (config.Stage == ShaderStage.Vertex)
  177. {
  178. InitializeOutput(AttributeConsts.PositionX);
  179. }
  180. int usedAttribtes = context.Config.UsedOutputAttributes;
  181. while (usedAttribtes != 0)
  182. {
  183. int index = BitOperations.TrailingZeroCount(usedAttribtes);
  184. InitializeOutput(AttributeConsts.UserAttributeBase + index * 16);
  185. usedAttribtes &= ~(1 << index);
  186. }
  187. }
  188. private static void EmitOps(EmitterContext context, Block block)
  189. {
  190. for (int opIndex = 0; opIndex < block.OpCodes.Count; opIndex++)
  191. {
  192. InstOp op = block.OpCodes[opIndex];
  193. if (context.Config.Options.Flags.HasFlag(TranslationFlags.DebugMode))
  194. {
  195. string instName;
  196. if (op.Emitter != null)
  197. {
  198. instName = op.Name.ToString();
  199. }
  200. else
  201. {
  202. instName = "???";
  203. context.Config.GpuAccessor.Log($"Invalid instruction at 0x{op.Address:X6} (0x{op.RawOpCode:X16}).");
  204. }
  205. string dbgComment = $"0x{op.Address:X6}: 0x{op.RawOpCode:X16} {instName}";
  206. context.Add(new CommentNode(dbgComment));
  207. }
  208. InstConditional opConditional = new InstConditional(op.RawOpCode);
  209. bool noPred = op.Props.HasFlag(InstProps.NoPred);
  210. if (!noPred && opConditional.Pred == RegisterConsts.PredicateTrueIndex && opConditional.PredInv)
  211. {
  212. continue;
  213. }
  214. Operand predSkipLbl = null;
  215. if (op.Name == InstName.Sync || op.Name == InstName.Brk)
  216. {
  217. // If the instruction is a SYNC or BRK instruction with only one
  218. // possible target address, then the instruction is basically
  219. // just a simple branch, we can generate code similar to branch
  220. // instructions, with the condition check on the branch itself.
  221. noPred = block.SyncTargets.Count <= 1;
  222. }
  223. else if (op.Name == InstName.Bra)
  224. {
  225. noPred = true;
  226. }
  227. if (!(opConditional.Pred == RegisterConsts.PredicateTrueIndex || noPred))
  228. {
  229. Operand label;
  230. if (opIndex == block.OpCodes.Count - 1 && block.HasNext())
  231. {
  232. label = context.GetLabel(block.Successors[0].Address);
  233. }
  234. else
  235. {
  236. label = Label();
  237. predSkipLbl = label;
  238. }
  239. Operand pred = Register(opConditional.Pred, RegisterType.Predicate);
  240. if (opConditional.PredInv)
  241. {
  242. context.BranchIfTrue(label, pred);
  243. }
  244. else
  245. {
  246. context.BranchIfFalse(label, pred);
  247. }
  248. }
  249. context.CurrOp = op;
  250. op.Emitter?.Invoke(context);
  251. if (predSkipLbl != null)
  252. {
  253. context.MarkLabel(predSkipLbl);
  254. }
  255. }
  256. }
  257. }
  258. }