Declarations.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.Shader.StructuredIr;
  3. using Ryujinx.Graphics.Shader.Translation;
  4. using Spv.Generator;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. using System.Linq;
  9. using static Spv.Specification;
  10. namespace Ryujinx.Graphics.Shader.CodeGen.Spirv
  11. {
  12. static class Declarations
  13. {
  14. // At least 16 attributes are guaranteed by the spec.
  15. public const int MaxAttributes = 16;
  16. private static readonly string[] StagePrefixes = new string[] { "cp", "vp", "tcp", "tep", "gp", "fp" };
  17. public static void DeclareParameters(CodeGenContext context, StructuredFunction function)
  18. {
  19. DeclareParameters(context, function.InArguments, 0);
  20. DeclareParameters(context, function.OutArguments, function.InArguments.Length);
  21. }
  22. private static void DeclareParameters(CodeGenContext context, IEnumerable<VariableType> argTypes, int argIndex)
  23. {
  24. foreach (var argType in argTypes)
  25. {
  26. var argPointerType = context.TypePointer(StorageClass.Function, context.GetType(argType.Convert()));
  27. var spvArg = context.FunctionParameter(argPointerType);
  28. context.DeclareArgument(argIndex++, spvArg);
  29. }
  30. }
  31. public static void DeclareLocals(CodeGenContext context, StructuredFunction function)
  32. {
  33. foreach (AstOperand local in function.Locals)
  34. {
  35. var localPointerType = context.TypePointer(StorageClass.Function, context.GetType(local.VarType.Convert()));
  36. var spvLocal = context.Variable(localPointerType, StorageClass.Function);
  37. context.AddLocalVariable(spvLocal);
  38. context.DeclareLocal(local, spvLocal);
  39. }
  40. var ivector2Type = context.TypeVector(context.TypeS32(), 2);
  41. var coordTempPointerType = context.TypePointer(StorageClass.Function, ivector2Type);
  42. var coordTemp = context.Variable(coordTempPointerType, StorageClass.Function);
  43. context.AddLocalVariable(coordTemp);
  44. context.CoordTemp = coordTemp;
  45. }
  46. public static void DeclareLocalForArgs(CodeGenContext context, List<StructuredFunction> functions)
  47. {
  48. for (int funcIndex = 0; funcIndex < functions.Count; funcIndex++)
  49. {
  50. StructuredFunction function = functions[funcIndex];
  51. Instruction[] locals = new Instruction[function.InArguments.Length];
  52. for (int i = 0; i < function.InArguments.Length; i++)
  53. {
  54. var type = function.GetArgumentType(i).Convert();
  55. var localPointerType = context.TypePointer(StorageClass.Function, context.GetType(type));
  56. var spvLocal = context.Variable(localPointerType, StorageClass.Function);
  57. context.AddLocalVariable(spvLocal);
  58. locals[i] = spvLocal;
  59. }
  60. context.DeclareLocalForArgs(funcIndex, locals);
  61. }
  62. }
  63. public static void DeclareAll(CodeGenContext context, StructuredProgramInfo info)
  64. {
  65. if (context.Config.Stage == ShaderStage.Compute)
  66. {
  67. int localMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeLocalMemorySize(), 4);
  68. if (localMemorySize != 0)
  69. {
  70. DeclareLocalMemory(context, localMemorySize);
  71. }
  72. int sharedMemorySize = BitUtils.DivRoundUp(context.Config.GpuAccessor.QueryComputeSharedMemorySize(), 4);
  73. if (sharedMemorySize != 0)
  74. {
  75. DeclareSharedMemory(context, sharedMemorySize);
  76. }
  77. }
  78. else if (context.Config.LocalMemorySize != 0)
  79. {
  80. int localMemorySize = BitUtils.DivRoundUp(context.Config.LocalMemorySize, 4);
  81. DeclareLocalMemory(context, localMemorySize);
  82. }
  83. DeclareSupportBuffer(context);
  84. DeclareUniformBuffers(context, context.Config.GetConstantBufferDescriptors());
  85. DeclareStorageBuffers(context, context.Config.GetStorageBufferDescriptors());
  86. DeclareSamplers(context, context.Config.GetTextureDescriptors());
  87. DeclareImages(context, context.Config.GetImageDescriptors());
  88. DeclareInputAttributes(context, info, perPatch: false);
  89. DeclareOutputAttributes(context, info, perPatch: false);
  90. DeclareInputAttributes(context, info, perPatch: true);
  91. DeclareOutputAttributes(context, info, perPatch: true);
  92. }
  93. private static void DeclareLocalMemory(CodeGenContext context, int size)
  94. {
  95. context.LocalMemory = DeclareMemory(context, StorageClass.Private, size);
  96. }
  97. private static void DeclareSharedMemory(CodeGenContext context, int size)
  98. {
  99. context.SharedMemory = DeclareMemory(context, StorageClass.Workgroup, size);
  100. }
  101. private static Instruction DeclareMemory(CodeGenContext context, StorageClass storage, int size)
  102. {
  103. var arrayType = context.TypeArray(context.TypeU32(), context.Constant(context.TypeU32(), size));
  104. var pointerType = context.TypePointer(storage, arrayType);
  105. var variable = context.Variable(pointerType, storage);
  106. context.AddGlobalVariable(variable);
  107. return variable;
  108. }
  109. private static void DeclareSupportBuffer(CodeGenContext context)
  110. {
  111. if (!context.Config.Stage.SupportsRenderScale() && !(context.Config.LastInVertexPipeline && context.Config.GpuAccessor.QueryViewportTransformDisable()))
  112. {
  113. return;
  114. }
  115. var isBgraArrayType = context.TypeArray(context.TypeU32(), context.Constant(context.TypeU32(), SupportBuffer.FragmentIsBgraCount));
  116. var viewportInverseVectorType = context.TypeVector(context.TypeFP32(), 4);
  117. var renderScaleArrayType = context.TypeArray(context.TypeFP32(), context.Constant(context.TypeU32(), SupportBuffer.RenderScaleMaxCount));
  118. context.Decorate(isBgraArrayType, Decoration.ArrayStride, (LiteralInteger)SupportBuffer.FieldSize);
  119. context.Decorate(renderScaleArrayType, Decoration.ArrayStride, (LiteralInteger)SupportBuffer.FieldSize);
  120. var supportBufferStructType = context.TypeStruct(false, context.TypeU32(), isBgraArrayType, viewportInverseVectorType, context.TypeS32(), renderScaleArrayType);
  121. context.MemberDecorate(supportBufferStructType, 0, Decoration.Offset, (LiteralInteger)SupportBuffer.FragmentAlphaTestOffset);
  122. context.MemberDecorate(supportBufferStructType, 1, Decoration.Offset, (LiteralInteger)SupportBuffer.FragmentIsBgraOffset);
  123. context.MemberDecorate(supportBufferStructType, 2, Decoration.Offset, (LiteralInteger)SupportBuffer.ViewportInverseOffset);
  124. context.MemberDecorate(supportBufferStructType, 3, Decoration.Offset, (LiteralInteger)SupportBuffer.FragmentRenderScaleCountOffset);
  125. context.MemberDecorate(supportBufferStructType, 4, Decoration.Offset, (LiteralInteger)SupportBuffer.GraphicsRenderScaleOffset);
  126. context.Decorate(supportBufferStructType, Decoration.Block);
  127. var supportBufferPointerType = context.TypePointer(StorageClass.Uniform, supportBufferStructType);
  128. var supportBufferVariable = context.Variable(supportBufferPointerType, StorageClass.Uniform);
  129. context.Decorate(supportBufferVariable, Decoration.DescriptorSet, (LiteralInteger)0);
  130. context.Decorate(supportBufferVariable, Decoration.Binding, (LiteralInteger)0);
  131. context.AddGlobalVariable(supportBufferVariable);
  132. context.SupportBuffer = supportBufferVariable;
  133. }
  134. private static void DeclareUniformBuffers(CodeGenContext context, BufferDescriptor[] descriptors)
  135. {
  136. if (descriptors.Length == 0)
  137. {
  138. return;
  139. }
  140. uint ubSize = Constants.ConstantBufferSize / 16;
  141. var ubArrayType = context.TypeArray(context.TypeVector(context.TypeFP32(), 4), context.Constant(context.TypeU32(), ubSize), true);
  142. context.Decorate(ubArrayType, Decoration.ArrayStride, (LiteralInteger)16);
  143. var ubStructType = context.TypeStruct(true, ubArrayType);
  144. context.Decorate(ubStructType, Decoration.Block);
  145. context.MemberDecorate(ubStructType, 0, Decoration.Offset, (LiteralInteger)0);
  146. if (context.Config.UsedFeatures.HasFlag(FeatureFlags.CbIndexing))
  147. {
  148. int count = descriptors.Max(x => x.Slot) + 1;
  149. var ubStructArrayType = context.TypeArray(ubStructType, context.Constant(context.TypeU32(), count));
  150. var ubPointerType = context.TypePointer(StorageClass.Uniform, ubStructArrayType);
  151. var ubVariable = context.Variable(ubPointerType, StorageClass.Uniform);
  152. context.Name(ubVariable, $"{GetStagePrefix(context.Config.Stage)}_u");
  153. context.Decorate(ubVariable, Decoration.DescriptorSet, (LiteralInteger)0);
  154. context.Decorate(ubVariable, Decoration.Binding, (LiteralInteger)context.Config.FirstConstantBufferBinding);
  155. context.AddGlobalVariable(ubVariable);
  156. context.UniformBuffersArray = ubVariable;
  157. }
  158. else
  159. {
  160. var ubPointerType = context.TypePointer(StorageClass.Uniform, ubStructType);
  161. foreach (var descriptor in descriptors)
  162. {
  163. var ubVariable = context.Variable(ubPointerType, StorageClass.Uniform);
  164. context.Name(ubVariable, $"{GetStagePrefix(context.Config.Stage)}_c{descriptor.Slot}");
  165. context.Decorate(ubVariable, Decoration.DescriptorSet, (LiteralInteger)0);
  166. context.Decorate(ubVariable, Decoration.Binding, (LiteralInteger)descriptor.Binding);
  167. context.AddGlobalVariable(ubVariable);
  168. context.UniformBuffers.Add(descriptor.Slot, ubVariable);
  169. }
  170. }
  171. }
  172. private static void DeclareStorageBuffers(CodeGenContext context, BufferDescriptor[] descriptors)
  173. {
  174. if (descriptors.Length == 0)
  175. {
  176. return;
  177. }
  178. int setIndex = context.Config.Options.TargetApi == TargetApi.Vulkan ? 1 : 0;
  179. int count = descriptors.Max(x => x.Slot) + 1;
  180. var sbArrayType = context.TypeRuntimeArray(context.TypeU32());
  181. context.Decorate(sbArrayType, Decoration.ArrayStride, (LiteralInteger)4);
  182. var sbStructType = context.TypeStruct(true, sbArrayType);
  183. context.Decorate(sbStructType, Decoration.BufferBlock);
  184. context.MemberDecorate(sbStructType, 0, Decoration.Offset, (LiteralInteger)0);
  185. var sbStructArrayType = context.TypeArray(sbStructType, context.Constant(context.TypeU32(), count));
  186. var sbPointerType = context.TypePointer(StorageClass.Uniform, sbStructArrayType);
  187. var sbVariable = context.Variable(sbPointerType, StorageClass.Uniform);
  188. context.Name(sbVariable, $"{GetStagePrefix(context.Config.Stage)}_s");
  189. context.Decorate(sbVariable, Decoration.DescriptorSet, (LiteralInteger)setIndex);
  190. context.Decorate(sbVariable, Decoration.Binding, (LiteralInteger)context.Config.FirstStorageBufferBinding);
  191. context.AddGlobalVariable(sbVariable);
  192. context.StorageBuffersArray = sbVariable;
  193. }
  194. private static void DeclareSamplers(CodeGenContext context, TextureDescriptor[] descriptors)
  195. {
  196. foreach (var descriptor in descriptors)
  197. {
  198. var meta = new TextureMeta(descriptor.CbufSlot, descriptor.HandleIndex, descriptor.Format);
  199. if (context.Samplers.ContainsKey(meta))
  200. {
  201. continue;
  202. }
  203. int setIndex = context.Config.Options.TargetApi == TargetApi.Vulkan ? 2 : 0;
  204. var dim = (descriptor.Type & SamplerType.Mask) switch
  205. {
  206. SamplerType.Texture1D => Dim.Dim1D,
  207. SamplerType.Texture2D => Dim.Dim2D,
  208. SamplerType.Texture3D => Dim.Dim3D,
  209. SamplerType.TextureCube => Dim.Cube,
  210. SamplerType.TextureBuffer => Dim.Buffer,
  211. _ => throw new InvalidOperationException($"Invalid sampler type \"{descriptor.Type & SamplerType.Mask}\".")
  212. };
  213. var imageType = context.TypeImage(
  214. context.TypeFP32(),
  215. dim,
  216. descriptor.Type.HasFlag(SamplerType.Shadow),
  217. descriptor.Type.HasFlag(SamplerType.Array),
  218. descriptor.Type.HasFlag(SamplerType.Multisample),
  219. 1,
  220. ImageFormat.Unknown);
  221. var nameSuffix = meta.CbufSlot < 0 ? $"_tcb_{meta.Handle:X}" : $"_cb{meta.CbufSlot}_{meta.Handle:X}";
  222. var sampledImageType = context.TypeSampledImage(imageType);
  223. var sampledImagePointerType = context.TypePointer(StorageClass.UniformConstant, sampledImageType);
  224. var sampledImageVariable = context.Variable(sampledImagePointerType, StorageClass.UniformConstant);
  225. context.Samplers.Add(meta, (imageType, sampledImageType, sampledImageVariable));
  226. context.SamplersTypes.Add(meta, descriptor.Type);
  227. context.Name(sampledImageVariable, $"{GetStagePrefix(context.Config.Stage)}_tex{nameSuffix}");
  228. context.Decorate(sampledImageVariable, Decoration.DescriptorSet, (LiteralInteger)setIndex);
  229. context.Decorate(sampledImageVariable, Decoration.Binding, (LiteralInteger)descriptor.Binding);
  230. context.AddGlobalVariable(sampledImageVariable);
  231. }
  232. }
  233. private static void DeclareImages(CodeGenContext context, TextureDescriptor[] descriptors)
  234. {
  235. foreach (var descriptor in descriptors)
  236. {
  237. var meta = new TextureMeta(descriptor.CbufSlot, descriptor.HandleIndex, descriptor.Format);
  238. if (context.Images.ContainsKey(meta))
  239. {
  240. continue;
  241. }
  242. int setIndex = context.Config.Options.TargetApi == TargetApi.Vulkan ? 3 : 0;
  243. var dim = GetDim(descriptor.Type);
  244. var imageType = context.TypeImage(
  245. context.GetType(meta.Format.GetComponentType().Convert()),
  246. dim,
  247. descriptor.Type.HasFlag(SamplerType.Shadow),
  248. descriptor.Type.HasFlag(SamplerType.Array),
  249. descriptor.Type.HasFlag(SamplerType.Multisample),
  250. AccessQualifier.ReadWrite,
  251. GetImageFormat(meta.Format));
  252. var nameSuffix = meta.CbufSlot < 0 ?
  253. $"_tcb_{meta.Handle:X}_{meta.Format.ToGlslFormat()}" :
  254. $"_cb{meta.CbufSlot}_{meta.Handle:X}_{meta.Format.ToGlslFormat()}";
  255. var imagePointerType = context.TypePointer(StorageClass.UniformConstant, imageType);
  256. var imageVariable = context.Variable(imagePointerType, StorageClass.UniformConstant);
  257. context.Images.Add(meta, (imageType, imageVariable));
  258. context.Name(imageVariable, $"{GetStagePrefix(context.Config.Stage)}_img{nameSuffix}");
  259. context.Decorate(imageVariable, Decoration.DescriptorSet, (LiteralInteger)setIndex);
  260. context.Decorate(imageVariable, Decoration.Binding, (LiteralInteger)descriptor.Binding);
  261. if (descriptor.Flags.HasFlag(TextureUsageFlags.ImageCoherent))
  262. {
  263. context.Decorate(imageVariable, Decoration.Coherent);
  264. }
  265. context.AddGlobalVariable(imageVariable);
  266. }
  267. }
  268. private static Dim GetDim(SamplerType type)
  269. {
  270. return (type & SamplerType.Mask) switch
  271. {
  272. SamplerType.Texture1D => Dim.Dim1D,
  273. SamplerType.Texture2D => Dim.Dim2D,
  274. SamplerType.Texture3D => Dim.Dim3D,
  275. SamplerType.TextureCube => Dim.Cube,
  276. SamplerType.TextureBuffer => Dim.Buffer,
  277. _ => throw new ArgumentException($"Invalid sampler type \"{type & SamplerType.Mask}\".")
  278. };
  279. }
  280. private static ImageFormat GetImageFormat(TextureFormat format)
  281. {
  282. return format switch
  283. {
  284. TextureFormat.Unknown => ImageFormat.Unknown,
  285. TextureFormat.R8Unorm => ImageFormat.R8,
  286. TextureFormat.R8Snorm => ImageFormat.R8Snorm,
  287. TextureFormat.R8Uint => ImageFormat.R8ui,
  288. TextureFormat.R8Sint => ImageFormat.R8i,
  289. TextureFormat.R16Float => ImageFormat.R16f,
  290. TextureFormat.R16Unorm => ImageFormat.R16,
  291. TextureFormat.R16Snorm => ImageFormat.R16Snorm,
  292. TextureFormat.R16Uint => ImageFormat.R16ui,
  293. TextureFormat.R16Sint => ImageFormat.R16i,
  294. TextureFormat.R32Float => ImageFormat.R32f,
  295. TextureFormat.R32Uint => ImageFormat.R32ui,
  296. TextureFormat.R32Sint => ImageFormat.R32i,
  297. TextureFormat.R8G8Unorm => ImageFormat.Rg8,
  298. TextureFormat.R8G8Snorm => ImageFormat.Rg8Snorm,
  299. TextureFormat.R8G8Uint => ImageFormat.Rg8ui,
  300. TextureFormat.R8G8Sint => ImageFormat.Rg8i,
  301. TextureFormat.R16G16Float => ImageFormat.Rg16f,
  302. TextureFormat.R16G16Unorm => ImageFormat.Rg16,
  303. TextureFormat.R16G16Snorm => ImageFormat.Rg16Snorm,
  304. TextureFormat.R16G16Uint => ImageFormat.Rg16ui,
  305. TextureFormat.R16G16Sint => ImageFormat.Rg16i,
  306. TextureFormat.R32G32Float => ImageFormat.Rg32f,
  307. TextureFormat.R32G32Uint => ImageFormat.Rg32ui,
  308. TextureFormat.R32G32Sint => ImageFormat.Rg32i,
  309. TextureFormat.R8G8B8A8Unorm => ImageFormat.Rgba8,
  310. TextureFormat.R8G8B8A8Snorm => ImageFormat.Rgba8Snorm,
  311. TextureFormat.R8G8B8A8Uint => ImageFormat.Rgba8ui,
  312. TextureFormat.R8G8B8A8Sint => ImageFormat.Rgba8i,
  313. TextureFormat.R16G16B16A16Float => ImageFormat.Rgba16f,
  314. TextureFormat.R16G16B16A16Unorm => ImageFormat.Rgba16,
  315. TextureFormat.R16G16B16A16Snorm => ImageFormat.Rgba16Snorm,
  316. TextureFormat.R16G16B16A16Uint => ImageFormat.Rgba16ui,
  317. TextureFormat.R16G16B16A16Sint => ImageFormat.Rgba16i,
  318. TextureFormat.R32G32B32A32Float => ImageFormat.Rgba32f,
  319. TextureFormat.R32G32B32A32Uint => ImageFormat.Rgba32ui,
  320. TextureFormat.R32G32B32A32Sint => ImageFormat.Rgba32i,
  321. TextureFormat.R10G10B10A2Unorm => ImageFormat.Rgb10A2,
  322. TextureFormat.R10G10B10A2Uint => ImageFormat.Rgb10a2ui,
  323. TextureFormat.R11G11B10Float => ImageFormat.R11fG11fB10f,
  324. _ => throw new ArgumentException($"Invalid texture format \"{format}\".")
  325. };
  326. }
  327. private static void DeclareInputAttributes(CodeGenContext context, StructuredProgramInfo info, bool perPatch)
  328. {
  329. bool iaIndexing = context.Config.UsedFeatures.HasFlag(FeatureFlags.IaIndexing);
  330. var inputs = perPatch ? info.InputsPerPatch : info.Inputs;
  331. foreach (int attr in inputs)
  332. {
  333. if (!AttributeInfo.Validate(context.Config, attr, isOutAttr: false, perPatch))
  334. {
  335. continue;
  336. }
  337. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  338. if (iaIndexing && isUserAttr && !perPatch)
  339. {
  340. if (context.InputsArray == null)
  341. {
  342. var attrType = context.TypeVector(context.TypeFP32(), (LiteralInteger)4);
  343. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)MaxAttributes));
  344. if (context.Config.Stage == ShaderStage.Geometry)
  345. {
  346. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)context.InputVertices));
  347. }
  348. var spvType = context.TypePointer(StorageClass.Input, attrType);
  349. var spvVar = context.Variable(spvType, StorageClass.Input);
  350. if (context.Config.PassthroughAttributes != 0 && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  351. {
  352. context.Decorate(spvVar, Decoration.PassthroughNV);
  353. }
  354. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)0);
  355. context.AddGlobalVariable(spvVar);
  356. context.InputsArray = spvVar;
  357. }
  358. }
  359. else
  360. {
  361. PixelImap iq = PixelImap.Unused;
  362. if (context.Config.Stage == ShaderStage.Fragment)
  363. {
  364. if (attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd)
  365. {
  366. iq = context.Config.ImapTypes[(attr - AttributeConsts.UserAttributeBase) / 16].GetFirstUsedType();
  367. }
  368. else
  369. {
  370. AttributeInfo attrInfo = AttributeInfo.From(context.Config, attr, isOutAttr: false);
  371. AggregateType elemType = attrInfo.Type & AggregateType.ElementTypeMask;
  372. if (attrInfo.IsBuiltin && (elemType == AggregateType.S32 || elemType == AggregateType.U32))
  373. {
  374. iq = PixelImap.Constant;
  375. }
  376. }
  377. }
  378. DeclareInputOrOutput(context, attr, perPatch, isOutAttr: false, iq);
  379. }
  380. }
  381. }
  382. private static void DeclareOutputAttributes(CodeGenContext context, StructuredProgramInfo info, bool perPatch)
  383. {
  384. bool oaIndexing = context.Config.UsedFeatures.HasFlag(FeatureFlags.OaIndexing);
  385. var outputs = perPatch ? info.OutputsPerPatch : info.Outputs;
  386. foreach (int attr in outputs)
  387. {
  388. if (!AttributeInfo.Validate(context.Config, attr, isOutAttr: true, perPatch))
  389. {
  390. continue;
  391. }
  392. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  393. if (oaIndexing && isUserAttr && !perPatch)
  394. {
  395. if (context.OutputsArray == null)
  396. {
  397. var attrType = context.TypeVector(context.TypeFP32(), (LiteralInteger)4);
  398. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)MaxAttributes));
  399. if (context.Config.Stage == ShaderStage.TessellationControl)
  400. {
  401. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), context.Config.ThreadsPerInputPrimitive));
  402. }
  403. var spvType = context.TypePointer(StorageClass.Output, attrType);
  404. var spvVar = context.Variable(spvType, StorageClass.Output);
  405. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)0);
  406. context.AddGlobalVariable(spvVar);
  407. context.OutputsArray = spvVar;
  408. }
  409. }
  410. else
  411. {
  412. DeclareOutputAttribute(context, attr, perPatch);
  413. }
  414. }
  415. if (context.Config.Stage == ShaderStage.Vertex)
  416. {
  417. DeclareOutputAttribute(context, AttributeConsts.PositionX, perPatch: false);
  418. }
  419. }
  420. private static void DeclareOutputAttribute(CodeGenContext context, int attr, bool perPatch)
  421. {
  422. DeclareInputOrOutput(context, attr, perPatch, isOutAttr: true);
  423. }
  424. public static void DeclareInvocationId(CodeGenContext context)
  425. {
  426. DeclareInputOrOutput(context, AttributeConsts.LaneId, perPatch: false, isOutAttr: false);
  427. }
  428. private static void DeclareInputOrOutput(CodeGenContext context, int attr, bool perPatch, bool isOutAttr, PixelImap iq = PixelImap.Unused)
  429. {
  430. bool isUserAttr = attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd;
  431. if (isUserAttr && context.Config.TransformFeedbackEnabled && !perPatch &&
  432. ((isOutAttr && context.Config.LastInVertexPipeline) ||
  433. (!isOutAttr && context.Config.Stage == ShaderStage.Fragment)))
  434. {
  435. DeclareTransformFeedbackInputOrOutput(context, attr, isOutAttr, iq);
  436. return;
  437. }
  438. var dict = perPatch
  439. ? (isOutAttr ? context.OutputsPerPatch : context.InputsPerPatch)
  440. : (isOutAttr ? context.Outputs : context.Inputs);
  441. var attrInfo = perPatch
  442. ? AttributeInfo.FromPatch(context.Config, attr, isOutAttr)
  443. : AttributeInfo.From(context.Config, attr, isOutAttr);
  444. if (dict.ContainsKey(attrInfo.BaseValue))
  445. {
  446. return;
  447. }
  448. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  449. var attrType = context.GetType(attrInfo.Type, attrInfo.Length);
  450. bool builtInPassthrough = false;
  451. if (AttributeInfo.IsArrayAttributeSpirv(context.Config.Stage, isOutAttr) && !perPatch && (!attrInfo.IsBuiltin || AttributeInfo.IsArrayBuiltIn(attr)))
  452. {
  453. int arraySize = context.Config.Stage == ShaderStage.Geometry ? context.InputVertices : 32;
  454. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)arraySize));
  455. if (context.Config.GpPassthrough && context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  456. {
  457. builtInPassthrough = true;
  458. }
  459. }
  460. if (context.Config.Stage == ShaderStage.TessellationControl && isOutAttr && !perPatch)
  461. {
  462. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), context.Config.ThreadsPerInputPrimitive));
  463. }
  464. var spvType = context.TypePointer(storageClass, attrType);
  465. var spvVar = context.Variable(spvType, storageClass);
  466. if (builtInPassthrough)
  467. {
  468. context.Decorate(spvVar, Decoration.PassthroughNV);
  469. }
  470. if (attrInfo.IsBuiltin)
  471. {
  472. if (perPatch)
  473. {
  474. context.Decorate(spvVar, Decoration.Patch);
  475. }
  476. context.Decorate(spvVar, Decoration.BuiltIn, (LiteralInteger)GetBuiltIn(context, attrInfo.BaseValue));
  477. if (context.Config.TransformFeedbackEnabled && context.Config.LastInVertexPipeline && isOutAttr)
  478. {
  479. var tfOutput = context.Info.GetTransformFeedbackOutput(attrInfo.BaseValue);
  480. if (tfOutput.Valid)
  481. {
  482. context.Decorate(spvVar, Decoration.XfbBuffer, (LiteralInteger)tfOutput.Buffer);
  483. context.Decorate(spvVar, Decoration.XfbStride, (LiteralInteger)tfOutput.Stride);
  484. context.Decorate(spvVar, Decoration.Offset, (LiteralInteger)tfOutput.Offset);
  485. }
  486. }
  487. }
  488. else if (perPatch)
  489. {
  490. context.Decorate(spvVar, Decoration.Patch);
  491. int location = context.Config.GetPerPatchAttributeLocation((attr - AttributeConsts.UserAttributePerPatchBase) / 16);
  492. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  493. }
  494. else if (isUserAttr)
  495. {
  496. int location = (attr - AttributeConsts.UserAttributeBase) / 16;
  497. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  498. if (!isOutAttr &&
  499. !perPatch &&
  500. (context.Config.PassthroughAttributes & (1 << location)) != 0 &&
  501. context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  502. {
  503. context.Decorate(spvVar, Decoration.PassthroughNV);
  504. }
  505. }
  506. else if (attr >= AttributeConsts.FragmentOutputColorBase && attr < AttributeConsts.FragmentOutputColorEnd)
  507. {
  508. int location = (attr - AttributeConsts.FragmentOutputColorBase) / 16;
  509. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  510. }
  511. if (!isOutAttr)
  512. {
  513. switch (iq)
  514. {
  515. case PixelImap.Constant:
  516. context.Decorate(spvVar, Decoration.Flat);
  517. break;
  518. case PixelImap.ScreenLinear:
  519. context.Decorate(spvVar, Decoration.NoPerspective);
  520. break;
  521. }
  522. }
  523. context.AddGlobalVariable(spvVar);
  524. dict.Add(attrInfo.BaseValue, spvVar);
  525. }
  526. private static void DeclareTransformFeedbackInputOrOutput(CodeGenContext context, int attr, bool isOutAttr, PixelImap iq = PixelImap.Unused)
  527. {
  528. var dict = isOutAttr ? context.Outputs : context.Inputs;
  529. var attrInfo = AttributeInfo.From(context.Config, attr, isOutAttr);
  530. bool hasComponent = true;
  531. int component = (attr >> 2) & 3;
  532. int components = 1;
  533. var type = attrInfo.Type & AggregateType.ElementTypeMask;
  534. if (context.Config.LastInPipeline && isOutAttr)
  535. {
  536. components = context.Info.GetTransformFeedbackOutputComponents(attr);
  537. if (components > 1)
  538. {
  539. attr &= ~0xf;
  540. type = AggregateType.Vector | AggregateType.FP32;
  541. hasComponent = false;
  542. }
  543. }
  544. if (dict.ContainsKey(attr))
  545. {
  546. return;
  547. }
  548. var storageClass = isOutAttr ? StorageClass.Output : StorageClass.Input;
  549. var attrType = context.GetType(type, components);
  550. if (AttributeInfo.IsArrayAttributeSpirv(context.Config.Stage, isOutAttr) && (!attrInfo.IsBuiltin || AttributeInfo.IsArrayBuiltIn(attr)))
  551. {
  552. int arraySize = context.Config.Stage == ShaderStage.Geometry ? context.InputVertices : 32;
  553. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), (LiteralInteger)arraySize));
  554. }
  555. if (context.Config.Stage == ShaderStage.TessellationControl && isOutAttr)
  556. {
  557. attrType = context.TypeArray(attrType, context.Constant(context.TypeU32(), context.Config.ThreadsPerInputPrimitive));
  558. }
  559. var spvType = context.TypePointer(storageClass, attrType);
  560. var spvVar = context.Variable(spvType, storageClass);
  561. Debug.Assert(attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd);
  562. int location = (attr - AttributeConsts.UserAttributeBase) / 16;
  563. context.Decorate(spvVar, Decoration.Location, (LiteralInteger)location);
  564. if (hasComponent)
  565. {
  566. context.Decorate(spvVar, Decoration.Component, (LiteralInteger)component);
  567. }
  568. if (isOutAttr)
  569. {
  570. var tfOutput = context.Info.GetTransformFeedbackOutput(attr);
  571. if (tfOutput.Valid)
  572. {
  573. context.Decorate(spvVar, Decoration.XfbBuffer, (LiteralInteger)tfOutput.Buffer);
  574. context.Decorate(spvVar, Decoration.XfbStride, (LiteralInteger)tfOutput.Stride);
  575. context.Decorate(spvVar, Decoration.Offset, (LiteralInteger)tfOutput.Offset);
  576. }
  577. }
  578. else
  579. {
  580. if ((context.Config.PassthroughAttributes & (1 << location)) != 0 &&
  581. context.Config.GpuAccessor.QueryHostSupportsGeometryShaderPassthrough())
  582. {
  583. context.Decorate(spvVar, Decoration.PassthroughNV);
  584. }
  585. switch (iq)
  586. {
  587. case PixelImap.Constant:
  588. context.Decorate(spvVar, Decoration.Flat);
  589. break;
  590. case PixelImap.ScreenLinear:
  591. context.Decorate(spvVar, Decoration.NoPerspective);
  592. break;
  593. }
  594. }
  595. context.AddGlobalVariable(spvVar);
  596. dict.Add(attr, spvVar);
  597. }
  598. private static BuiltIn GetBuiltIn(CodeGenContext context, int attr)
  599. {
  600. return attr switch
  601. {
  602. AttributeConsts.TessLevelOuter0 => BuiltIn.TessLevelOuter,
  603. AttributeConsts.TessLevelInner0 => BuiltIn.TessLevelInner,
  604. AttributeConsts.Layer => BuiltIn.Layer,
  605. AttributeConsts.ViewportIndex => BuiltIn.ViewportIndex,
  606. AttributeConsts.PointSize => BuiltIn.PointSize,
  607. AttributeConsts.PositionX => context.Config.Stage == ShaderStage.Fragment ? BuiltIn.FragCoord : BuiltIn.Position,
  608. AttributeConsts.ClipDistance0 => BuiltIn.ClipDistance,
  609. AttributeConsts.PointCoordX => BuiltIn.PointCoord,
  610. AttributeConsts.TessCoordX => BuiltIn.TessCoord,
  611. AttributeConsts.InstanceId => BuiltIn.InstanceId,
  612. AttributeConsts.VertexId => BuiltIn.VertexId,
  613. AttributeConsts.BaseInstance => BuiltIn.BaseInstance,
  614. AttributeConsts.BaseVertex => BuiltIn.BaseVertex,
  615. AttributeConsts.InstanceIndex => BuiltIn.InstanceIndex,
  616. AttributeConsts.VertexIndex => BuiltIn.VertexIndex,
  617. AttributeConsts.DrawIndex => BuiltIn.DrawIndex,
  618. AttributeConsts.FrontFacing => BuiltIn.FrontFacing,
  619. AttributeConsts.FragmentOutputDepth => BuiltIn.FragDepth,
  620. AttributeConsts.ThreadKill => BuiltIn.HelperInvocation,
  621. AttributeConsts.ThreadIdX => BuiltIn.LocalInvocationId,
  622. AttributeConsts.CtaIdX => BuiltIn.WorkgroupId,
  623. AttributeConsts.LaneId => BuiltIn.SubgroupLocalInvocationId,
  624. AttributeConsts.InvocationId => BuiltIn.InvocationId,
  625. AttributeConsts.PrimitiveId => BuiltIn.PrimitiveId,
  626. AttributeConsts.PatchVerticesIn => BuiltIn.PatchVertices,
  627. AttributeConsts.EqMask => BuiltIn.SubgroupEqMask,
  628. AttributeConsts.GeMask => BuiltIn.SubgroupGeMask,
  629. AttributeConsts.GtMask => BuiltIn.SubgroupGtMask,
  630. AttributeConsts.LeMask => BuiltIn.SubgroupLeMask,
  631. AttributeConsts.LtMask => BuiltIn.SubgroupLtMask,
  632. AttributeConsts.SupportBlockViewInverseX => BuiltIn.Position,
  633. AttributeConsts.SupportBlockViewInverseY => BuiltIn.Position,
  634. _ => throw new ArgumentException($"Invalid attribute number 0x{attr:X}.")
  635. };
  636. }
  637. private static string GetStagePrefix(ShaderStage stage)
  638. {
  639. return StagePrefixes[(int)stage];
  640. }
  641. }
  642. }