SpirvGenerator.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  3. using Ryujinx.Graphics.Shader.StructuredIr;
  4. using Ryujinx.Graphics.Shader.Translation;
  5. using System;
  6. using System.Collections.Generic;
  7. using static Spv.Specification;
  8. namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
  9. {
  10. using SpvInstruction = Spv.Generator.Instruction;
  11. using SpvInstructionPool = Spv.Generator.GeneratorPool<Spv.Generator.Instruction>;
  12. using SpvLiteralInteger = Spv.Generator.LiteralInteger;
  13. using SpvLiteralIntegerPool = Spv.Generator.GeneratorPool<Spv.Generator.LiteralInteger>;
  14. static class SpirvGenerator
  15. {
  16. // Resource pools for Spirv generation. Note: Increase count when more threads are being used.
  17. private const int GeneratorPoolCount = 1;
  18. private static ObjectPool<SpvInstructionPool> InstructionPool;
  19. private static ObjectPool<SpvLiteralIntegerPool> IntegerPool;
  20. private static object PoolLock;
  21. static SpirvGenerator()
  22. {
  23. InstructionPool = new (() => new SpvInstructionPool(), GeneratorPoolCount);
  24. IntegerPool = new (() => new SpvLiteralIntegerPool(), GeneratorPoolCount);
  25. PoolLock = new object();
  26. }
  27. private const HelperFunctionsMask NeedsInvocationIdMask =
  28. HelperFunctionsMask.Shuffle |
  29. HelperFunctionsMask.ShuffleDown |
  30. HelperFunctionsMask.ShuffleUp |
  31. HelperFunctionsMask.ShuffleXor |
  32. HelperFunctionsMask.SwizzleAdd;
  33. public static byte[] Generate(StructuredProgramInfo info, ShaderConfig config)
  34. {
  35. SpvInstructionPool instPool;
  36. SpvLiteralIntegerPool integerPool;
  37. lock (PoolLock)
  38. {
  39. instPool = InstructionPool.Allocate();
  40. integerPool = IntegerPool.Allocate();
  41. }
  42. CodeGenContext context = new CodeGenContext(info, config, instPool, integerPool);
  43. context.AddCapability(Capability.GroupNonUniformBallot);
  44. context.AddCapability(Capability.GroupNonUniformShuffle);
  45. context.AddCapability(Capability.GroupNonUniformVote);
  46. context.AddCapability(Capability.ImageBuffer);
  47. context.AddCapability(Capability.ImageGatherExtended);
  48. context.AddCapability(Capability.ImageQuery);
  49. context.AddCapability(Capability.SampledBuffer);
  50. if (config.TransformFeedbackEnabled && config.LastInVertexPipeline)
  51. {
  52. context.AddCapability(Capability.TransformFeedback);
  53. }
  54. if (config.Stage == ShaderStage.Fragment)
  55. {
  56. if (context.Info.IoDefinitions.Contains(new IoDefinition(StorageKind.Input, IoVariable.Layer)))
  57. {
  58. context.AddCapability(Capability.Geometry);
  59. }
  60. if (context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  61. {
  62. context.AddCapability(Capability.FragmentShaderPixelInterlockEXT);
  63. context.AddExtension("SPV_EXT_fragment_shader_interlock");
  64. }
  65. }
  66. else if (config.Stage == ShaderStage.Geometry)
  67. {
  68. context.AddCapability(Capability.Geometry);
  69. if (config.GpPassthrough && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  70. {
  71. context.AddExtension("SPV_NV_geometry_shader_passthrough");
  72. context.AddCapability(Capability.GeometryShaderPassthroughNV);
  73. }
  74. }
  75. else if (config.Stage == ShaderStage.TessellationControl || config.Stage == ShaderStage.TessellationEvaluation)
  76. {
  77. context.AddCapability(Capability.Tessellation);
  78. }
  79. else if (config.Stage == ShaderStage.Vertex)
  80. {
  81. context.AddCapability(Capability.DrawParameters);
  82. }
  83. if (context.Info.IoDefinitions.Contains(new IoDefinition(StorageKind.Output, IoVariable.ViewportMask)))
  84. {
  85. context.AddExtension("SPV_NV_viewport_array2");
  86. context.AddCapability(Capability.ShaderViewportMaskNV);
  87. }
  88. if ((info.HelperFunctionsMask & NeedsInvocationIdMask) != 0)
  89. {
  90. info.IoDefinitions.Add(new IoDefinition(StorageKind.Input, IoVariable.SubgroupLaneId));
  91. }
  92. Declarations.DeclareAll(context, info);
  93. for (int funcIndex = 0; funcIndex < info.Functions.Count; funcIndex++)
  94. {
  95. var function = info.Functions[funcIndex];
  96. var retType = context.GetType(function.ReturnType);
  97. var funcArgs = new SpvInstruction[function.InArguments.Length + function.OutArguments.Length];
  98. for (int argIndex = 0; argIndex < funcArgs.Length; argIndex++)
  99. {
  100. var argType = context.GetType(function.GetArgumentType(argIndex));
  101. var argPointerType = context.TypePointer(StorageClass.Function, argType);
  102. funcArgs[argIndex] = argPointerType;
  103. }
  104. var funcType = context.TypeFunction(retType, false, funcArgs);
  105. var spvFunc = context.Function(retType, FunctionControlMask.MaskNone, funcType);
  106. context.DeclareFunction(funcIndex, function, spvFunc);
  107. }
  108. for (int funcIndex = 0; funcIndex < info.Functions.Count; funcIndex++)
  109. {
  110. Generate(context, info, funcIndex);
  111. }
  112. byte[] result = context.Generate();
  113. lock (PoolLock)
  114. {
  115. InstructionPool.Release(instPool);
  116. IntegerPool.Release(integerPool);
  117. }
  118. return result;
  119. }
  120. private static void Generate(CodeGenContext context, StructuredProgramInfo info, int funcIndex)
  121. {
  122. var function = info.Functions[funcIndex];
  123. (_, var spvFunc) = context.GetFunction(funcIndex);
  124. context.AddFunction(spvFunc);
  125. context.StartFunction();
  126. Declarations.DeclareParameters(context, function);
  127. context.EnterBlock(function.MainBlock);
  128. Declarations.DeclareLocals(context, function);
  129. Declarations.DeclareLocalForArgs(context, info.Functions);
  130. Generate(context, function.MainBlock);
  131. // Functions must always end with a return.
  132. if (!(function.MainBlock.Last is AstOperation operation) ||
  133. (operation.Inst != Instruction.Return && operation.Inst != Instruction.Discard))
  134. {
  135. context.Return();
  136. }
  137. context.FunctionEnd();
  138. if (funcIndex == 0)
  139. {
  140. context.AddEntryPoint(context.Config.Stage.Convert(), spvFunc, "main", context.GetMainInterface());
  141. if (context.Config.Stage == ShaderStage.TessellationControl)
  142. {
  143. context.AddExecutionMode(spvFunc, ExecutionMode.OutputVertices, (SpvLiteralInteger)context.Config.ThreadsPerInputPrimitive);
  144. }
  145. else if (context.Config.Stage == ShaderStage.TessellationEvaluation)
  146. {
  147. switch (context.Config.GpuAccessor.QueryTessPatchType())
  148. {
  149. case TessPatchType.Isolines:
  150. context.AddExecutionMode(spvFunc, ExecutionMode.Isolines);
  151. break;
  152. case TessPatchType.Triangles:
  153. context.AddExecutionMode(spvFunc, ExecutionMode.Triangles);
  154. break;
  155. case TessPatchType.Quads:
  156. context.AddExecutionMode(spvFunc, ExecutionMode.Quads);
  157. break;
  158. }
  159. switch (context.Config.GpuAccessor.QueryTessSpacing())
  160. {
  161. case TessSpacing.EqualSpacing:
  162. context.AddExecutionMode(spvFunc, ExecutionMode.SpacingEqual);
  163. break;
  164. case TessSpacing.FractionalEventSpacing:
  165. context.AddExecutionMode(spvFunc, ExecutionMode.SpacingFractionalEven);
  166. break;
  167. case TessSpacing.FractionalOddSpacing:
  168. context.AddExecutionMode(spvFunc, ExecutionMode.SpacingFractionalOdd);
  169. break;
  170. }
  171. bool tessCw = context.Config.GpuAccessor.QueryTessCw();
  172. if (context.Config.Options.TargetApi == TargetApi.Vulkan)
  173. {
  174. // We invert the front face on Vulkan backend, so we need to do that here as well.
  175. tessCw = !tessCw;
  176. }
  177. if (tessCw)
  178. {
  179. context.AddExecutionMode(spvFunc, ExecutionMode.VertexOrderCw);
  180. }
  181. else
  182. {
  183. context.AddExecutionMode(spvFunc, ExecutionMode.VertexOrderCcw);
  184. }
  185. }
  186. else if (context.Config.Stage == ShaderStage.Geometry)
  187. {
  188. InputTopology inputTopology = context.Config.GpuAccessor.QueryPrimitiveTopology();
  189. context.AddExecutionMode(spvFunc, inputTopology switch
  190. {
  191. InputTopology.Points => ExecutionMode.InputPoints,
  192. InputTopology.Lines => ExecutionMode.InputLines,
  193. InputTopology.LinesAdjacency => ExecutionMode.InputLinesAdjacency,
  194. InputTopology.Triangles => ExecutionMode.Triangles,
  195. InputTopology.TrianglesAdjacency => ExecutionMode.InputTrianglesAdjacency,
  196. _ => throw new InvalidOperationException($"Invalid input topology \"{inputTopology}\".")
  197. });
  198. context.AddExecutionMode(spvFunc, ExecutionMode.Invocations, (SpvLiteralInteger)context.Config.ThreadsPerInputPrimitive);
  199. context.AddExecutionMode(spvFunc, context.Config.OutputTopology switch
  200. {
  201. OutputTopology.PointList => ExecutionMode.OutputPoints,
  202. OutputTopology.LineStrip => ExecutionMode.OutputLineStrip,
  203. OutputTopology.TriangleStrip => ExecutionMode.OutputTriangleStrip,
  204. _ => throw new InvalidOperationException($"Invalid output topology \"{context.Config.OutputTopology}\".")
  205. });
  206. int maxOutputVertices = context.Config.GpPassthrough ? context.InputVertices : context.Config.MaxOutputVertices;
  207. context.AddExecutionMode(spvFunc, ExecutionMode.OutputVertices, (SpvLiteralInteger)maxOutputVertices);
  208. }
  209. else if (context.Config.Stage == ShaderStage.Fragment)
  210. {
  211. context.AddExecutionMode(spvFunc, context.Config.Options.TargetApi == TargetApi.Vulkan
  212. ? ExecutionMode.OriginUpperLeft
  213. : ExecutionMode.OriginLowerLeft);
  214. if (context.Info.IoDefinitions.Contains(new IoDefinition(StorageKind.Output, IoVariable.FragmentOutputDepth)))
  215. {
  216. context.AddExecutionMode(spvFunc, ExecutionMode.DepthReplacing);
  217. }
  218. if (context.Config.GpuAccessor.QueryEarlyZForce())
  219. {
  220. context.AddExecutionMode(spvFunc, ExecutionMode.EarlyFragmentTests);
  221. }
  222. if ((info.HelperFunctionsMask & HelperFunctionsMask.FSI) != 0 &&
  223. context.Config.GpuAccessor.QueryHostSupportsFragmentShaderInterlock())
  224. {
  225. context.AddExecutionMode(spvFunc, ExecutionMode.PixelInterlockOrderedEXT);
  226. }
  227. }
  228. else if (context.Config.Stage == ShaderStage.Compute)
  229. {
  230. var localSizeX = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeX();
  231. var localSizeY = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeY();
  232. var localSizeZ = (SpvLiteralInteger)context.Config.GpuAccessor.QueryComputeLocalSizeZ();
  233. context.AddExecutionMode(
  234. spvFunc,
  235. ExecutionMode.LocalSize,
  236. localSizeX,
  237. localSizeY,
  238. localSizeZ);
  239. }
  240. if (context.Config.TransformFeedbackEnabled && context.Config.LastInVertexPipeline)
  241. {
  242. context.AddExecutionMode(spvFunc, ExecutionMode.Xfb);
  243. }
  244. }
  245. }
  246. private static void Generate(CodeGenContext context, AstBlock block)
  247. {
  248. AstBlockVisitor visitor = new AstBlockVisitor(block);
  249. var loopTargets = new Dictionary<AstBlock, (SpvInstruction, SpvInstruction)>();
  250. context.LoopTargets = loopTargets;
  251. visitor.BlockEntered += (sender, e) =>
  252. {
  253. AstBlock mergeBlock = e.Block.Parent;
  254. if (e.Block.Type == AstBlockType.If)
  255. {
  256. AstBlock ifTrueBlock = e.Block;
  257. AstBlock ifFalseBlock;
  258. if (AstHelper.Next(e.Block) is AstBlock nextBlock && nextBlock.Type == AstBlockType.Else)
  259. {
  260. ifFalseBlock = nextBlock;
  261. }
  262. else
  263. {
  264. ifFalseBlock = mergeBlock;
  265. }
  266. var condition = context.Get(AggregateType.Bool, e.Block.Condition);
  267. context.SelectionMerge(context.GetNextLabel(mergeBlock), SelectionControlMask.MaskNone);
  268. context.BranchConditional(condition, context.GetNextLabel(ifTrueBlock), context.GetNextLabel(ifFalseBlock));
  269. }
  270. else if (e.Block.Type == AstBlockType.DoWhile)
  271. {
  272. var continueTarget = context.Label();
  273. loopTargets.Add(e.Block, (context.NewBlock(), continueTarget));
  274. context.LoopMerge(context.GetNextLabel(mergeBlock), continueTarget, LoopControlMask.MaskNone);
  275. context.Branch(context.GetFirstLabel(e.Block));
  276. }
  277. context.EnterBlock(e.Block);
  278. };
  279. visitor.BlockLeft += (sender, e) =>
  280. {
  281. if (e.Block.Parent != null)
  282. {
  283. if (e.Block.Type == AstBlockType.DoWhile)
  284. {
  285. // This is a loop, we need to jump back to the loop header
  286. // if the condition is true.
  287. AstBlock mergeBlock = e.Block.Parent;
  288. (var loopTarget, var continueTarget) = loopTargets[e.Block];
  289. context.Branch(continueTarget);
  290. context.AddLabel(continueTarget);
  291. var condition = context.Get(AggregateType.Bool, e.Block.Condition);
  292. context.BranchConditional(condition, loopTarget, context.GetNextLabel(mergeBlock));
  293. }
  294. else
  295. {
  296. // We only need a branch if the last instruction didn't
  297. // already cause the program to exit or jump elsewhere.
  298. bool lastIsCf = e.Block.Last is AstOperation lastOp &&
  299. (lastOp.Inst == Instruction.Discard ||
  300. lastOp.Inst == Instruction.LoopBreak ||
  301. lastOp.Inst == Instruction.LoopContinue ||
  302. lastOp.Inst == Instruction.Return);
  303. if (!lastIsCf)
  304. {
  305. context.Branch(context.GetNextLabel(e.Block.Parent));
  306. }
  307. }
  308. bool hasElse = AstHelper.Next(e.Block) is AstBlock nextBlock &&
  309. (nextBlock.Type == AstBlockType.Else ||
  310. nextBlock.Type == AstBlockType.ElseIf);
  311. // Re-enter the parent block.
  312. if (e.Block.Parent != null && !hasElse)
  313. {
  314. context.EnterBlock(e.Block.Parent);
  315. }
  316. }
  317. };
  318. foreach (IAstNode node in visitor.Visit())
  319. {
  320. if (node is AstAssignment assignment)
  321. {
  322. var dest = (AstOperand)assignment.Destination;
  323. if (dest.Type == OperandType.LocalVariable)
  324. {
  325. var source = context.Get(dest.VarType, assignment.Source);
  326. context.Store(context.GetLocalPointer(dest), source);
  327. }
  328. else if (dest.Type == OperandType.Argument)
  329. {
  330. var source = context.Get(dest.VarType, assignment.Source);
  331. context.Store(context.GetArgumentPointer(dest), source);
  332. }
  333. else
  334. {
  335. throw new NotImplementedException(dest.Type.ToString());
  336. }
  337. }
  338. else if (node is AstOperation operation)
  339. {
  340. Instructions.Generate(context, operation);
  341. }
  342. }
  343. }
  344. }
  345. }