Rewriter.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Linq;
  5. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  6. using static Ryujinx.Graphics.Shader.Translation.GlobalMemory;
  7. namespace Ryujinx.Graphics.Shader.Translation
  8. {
  9. static class Rewriter
  10. {
  11. public static void RunPass(BasicBlock[] blocks, ShaderConfig config)
  12. {
  13. bool isVertexShader = config.Stage == ShaderStage.Vertex;
  14. bool hasConstantBufferDrawParameters = config.GpuAccessor.QueryHasConstantBufferDrawParameters();
  15. bool supportsSnormBufferTextureFormat = config.GpuAccessor.QueryHostSupportsSnormBufferTextureFormat();
  16. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  17. {
  18. BasicBlock block = blocks[blkIndex];
  19. for (LinkedListNode<INode> node = block.Operations.First; node != null; node = node.Next)
  20. {
  21. if (node.Value is not Operation operation)
  22. {
  23. continue;
  24. }
  25. if (isVertexShader)
  26. {
  27. if (hasConstantBufferDrawParameters)
  28. {
  29. if (ReplaceConstantBufferWithDrawParameters(operation))
  30. {
  31. config.SetUsedFeature(FeatureFlags.DrawParameters);
  32. }
  33. }
  34. else if (HasConstantBufferDrawParameters(operation))
  35. {
  36. config.SetUsedFeature(FeatureFlags.DrawParameters);
  37. }
  38. }
  39. if (UsesGlobalMemory(operation.Inst))
  40. {
  41. node = RewriteGlobalAccess(node, config);
  42. }
  43. if (operation is TextureOperation texOp)
  44. {
  45. if (texOp.Inst == Instruction.TextureSample)
  46. {
  47. node = RewriteTextureSample(node, config);
  48. if (texOp.Type == SamplerType.TextureBuffer && !supportsSnormBufferTextureFormat)
  49. {
  50. node = InsertSnormNormalization(node, config);
  51. }
  52. }
  53. }
  54. }
  55. }
  56. }
  57. private static LinkedListNode<INode> RewriteGlobalAccess(LinkedListNode<INode> node, ShaderConfig config)
  58. {
  59. Operation operation = (Operation)node.Value;
  60. bool isAtomic = operation.Inst.IsAtomic();
  61. bool isStg16Or8 = operation.Inst == Instruction.StoreGlobal16 || operation.Inst == Instruction.StoreGlobal8;
  62. bool isWrite = isAtomic || operation.Inst == Instruction.StoreGlobal || isStg16Or8;
  63. Operation storageOp;
  64. Operand PrependOperation(Instruction inst, params Operand[] sources)
  65. {
  66. Operand local = Local();
  67. node.List.AddBefore(node, new Operation(inst, local, sources));
  68. return local;
  69. }
  70. Operand addrLow = operation.GetSource(0);
  71. Operand addrHigh = operation.GetSource(1);
  72. Operand sbBaseAddrLow = Const(0);
  73. Operand sbSlot = Const(0);
  74. for (int slot = 0; slot < StorageMaxCount; slot++)
  75. {
  76. config.SetUsedStorageBuffer(slot, isWrite);
  77. int cbOffset = GetStorageCbOffset(config.Stage, slot);
  78. Operand baseAddrLow = Cbuf(0, cbOffset);
  79. Operand baseAddrHigh = Cbuf(0, cbOffset + 1);
  80. Operand size = Cbuf(0, cbOffset + 2);
  81. Operand offset = PrependOperation(Instruction.Subtract, addrLow, baseAddrLow);
  82. Operand borrow = PrependOperation(Instruction.CompareLessU32, addrLow, baseAddrLow);
  83. Operand inRangeLow = PrependOperation(Instruction.CompareLessU32, offset, size);
  84. Operand addrHighBorrowed = PrependOperation(Instruction.Add, addrHigh, borrow);
  85. Operand inRangeHigh = PrependOperation(Instruction.CompareEqual, addrHighBorrowed, baseAddrHigh);
  86. Operand inRange = PrependOperation(Instruction.BitwiseAnd, inRangeLow, inRangeHigh);
  87. sbBaseAddrLow = PrependOperation(Instruction.ConditionalSelect, inRange, baseAddrLow, sbBaseAddrLow);
  88. sbSlot = PrependOperation(Instruction.ConditionalSelect, inRange, Const(slot), sbSlot);
  89. }
  90. Operand alignMask = Const(-config.GpuAccessor.QueryHostStorageBufferOffsetAlignment());
  91. Operand baseAddrTrunc = PrependOperation(Instruction.BitwiseAnd, sbBaseAddrLow, alignMask);
  92. Operand byteOffset = PrependOperation(Instruction.Subtract, addrLow, baseAddrTrunc);
  93. Operand[] sources = new Operand[operation.SourcesCount];
  94. sources[0] = sbSlot;
  95. if (isStg16Or8)
  96. {
  97. sources[1] = byteOffset;
  98. }
  99. else
  100. {
  101. sources[1] = PrependOperation(Instruction.ShiftRightU32, byteOffset, Const(2));
  102. }
  103. for (int index = 2; index < operation.SourcesCount; index++)
  104. {
  105. sources[index] = operation.GetSource(index);
  106. }
  107. if (isAtomic)
  108. {
  109. Instruction inst = (operation.Inst & ~Instruction.MrMask) | Instruction.MrStorage;
  110. storageOp = new Operation(inst, operation.Dest, sources);
  111. }
  112. else if (operation.Inst == Instruction.LoadGlobal)
  113. {
  114. storageOp = new Operation(Instruction.LoadStorage, operation.Dest, sources);
  115. }
  116. else
  117. {
  118. Instruction storeInst = operation.Inst switch
  119. {
  120. Instruction.StoreGlobal16 => Instruction.StoreStorage16,
  121. Instruction.StoreGlobal8 => Instruction.StoreStorage8,
  122. _ => Instruction.StoreStorage
  123. };
  124. storageOp = new Operation(storeInst, null, sources);
  125. }
  126. for (int index = 0; index < operation.SourcesCount; index++)
  127. {
  128. operation.SetSource(index, null);
  129. }
  130. LinkedListNode<INode> oldNode = node;
  131. node = node.List.AddBefore(node, storageOp);
  132. node.List.Remove(oldNode);
  133. return node;
  134. }
  135. private static LinkedListNode<INode> RewriteTextureSample(LinkedListNode<INode> node, ShaderConfig config)
  136. {
  137. TextureOperation texOp = (TextureOperation)node.Value;
  138. bool hasOffset = (texOp.Flags & TextureFlags.Offset) != 0;
  139. bool hasOffsets = (texOp.Flags & TextureFlags.Offsets) != 0;
  140. bool hasInvalidOffset = (hasOffset || hasOffsets) && !config.GpuAccessor.QueryHostSupportsNonConstantTextureOffset();
  141. bool isBindless = (texOp.Flags & TextureFlags.Bindless) != 0;
  142. bool isCoordNormalized = isBindless || config.GpuAccessor.QueryTextureCoordNormalized(texOp.Handle, texOp.CbufSlot);
  143. if (!hasInvalidOffset && isCoordNormalized)
  144. {
  145. return node;
  146. }
  147. bool isGather = (texOp.Flags & TextureFlags.Gather) != 0;
  148. bool hasDerivatives = (texOp.Flags & TextureFlags.Derivatives) != 0;
  149. bool intCoords = (texOp.Flags & TextureFlags.IntCoords) != 0;
  150. bool hasLodBias = (texOp.Flags & TextureFlags.LodBias) != 0;
  151. bool hasLodLevel = (texOp.Flags & TextureFlags.LodLevel) != 0;
  152. bool isArray = (texOp.Type & SamplerType.Array) != 0;
  153. bool isIndexed = (texOp.Type & SamplerType.Indexed) != 0;
  154. bool isMultisample = (texOp.Type & SamplerType.Multisample) != 0;
  155. bool isShadow = (texOp.Type & SamplerType.Shadow) != 0;
  156. int coordsCount = texOp.Type.GetDimensions();
  157. int offsetsCount;
  158. if (hasOffsets)
  159. {
  160. offsetsCount = coordsCount * 4;
  161. }
  162. else if (hasOffset)
  163. {
  164. offsetsCount = coordsCount;
  165. }
  166. else
  167. {
  168. offsetsCount = 0;
  169. }
  170. Operand[] offsets = new Operand[offsetsCount];
  171. Operand[] sources = new Operand[texOp.SourcesCount - offsetsCount];
  172. int copyCount = 0;
  173. if (isBindless || isIndexed)
  174. {
  175. copyCount++;
  176. }
  177. Operand[] lodSources = new Operand[copyCount + coordsCount];
  178. for (int index = 0; index < lodSources.Length; index++)
  179. {
  180. lodSources[index] = texOp.GetSource(index);
  181. }
  182. copyCount += coordsCount;
  183. if (isArray)
  184. {
  185. copyCount++;
  186. }
  187. if (isShadow)
  188. {
  189. copyCount++;
  190. }
  191. if (hasDerivatives)
  192. {
  193. copyCount += coordsCount * 2;
  194. }
  195. if (isMultisample)
  196. {
  197. copyCount++;
  198. }
  199. else if (hasLodLevel)
  200. {
  201. copyCount++;
  202. }
  203. int srcIndex = 0;
  204. int dstIndex = 0;
  205. for (int index = 0; index < copyCount; index++)
  206. {
  207. sources[dstIndex++] = texOp.GetSource(srcIndex++);
  208. }
  209. bool areAllOffsetsConstant = true;
  210. for (int index = 0; index < offsetsCount; index++)
  211. {
  212. Operand offset = texOp.GetSource(srcIndex++);
  213. areAllOffsetsConstant &= offset.Type == OperandType.Constant;
  214. offsets[index] = offset;
  215. }
  216. hasInvalidOffset &= !areAllOffsetsConstant;
  217. if (!hasInvalidOffset && isCoordNormalized)
  218. {
  219. return node;
  220. }
  221. if (hasLodBias)
  222. {
  223. sources[dstIndex++] = texOp.GetSource(srcIndex++);
  224. }
  225. if (isGather && !isShadow)
  226. {
  227. sources[dstIndex++] = texOp.GetSource(srcIndex++);
  228. }
  229. int coordsIndex = isBindless || isIndexed ? 1 : 0;
  230. int componentIndex = texOp.Index;
  231. Operand Int(Operand value)
  232. {
  233. Operand res = Local();
  234. node.List.AddBefore(node, new Operation(Instruction.ConvertFP32ToS32, res, value));
  235. return res;
  236. }
  237. Operand Float(Operand value)
  238. {
  239. Operand res = Local();
  240. node.List.AddBefore(node, new Operation(Instruction.ConvertS32ToFP32, res, value));
  241. return res;
  242. }
  243. // Emulate non-normalized coordinates by normalizing the coordinates on the shader.
  244. // Without normalization, the coordinates are expected to the in the [0, W or H] range,
  245. // and otherwise, it is expected to be in the [0, 1] range.
  246. // We normalize by dividing the coords by the texture size.
  247. if (!isCoordNormalized && !intCoords)
  248. {
  249. config.SetUsedFeature(FeatureFlags.IntegerSampling);
  250. int normCoordsCount = (texOp.Type & SamplerType.Mask) == SamplerType.TextureCube ? 2 : coordsCount;
  251. for (int index = 0; index < normCoordsCount; index++)
  252. {
  253. Operand coordSize = Local();
  254. Operand[] texSizeSources;
  255. if (isBindless || isIndexed)
  256. {
  257. texSizeSources = new Operand[] { sources[0], Const(0) };
  258. }
  259. else
  260. {
  261. texSizeSources = new Operand[] { Const(0) };
  262. }
  263. node.List.AddBefore(node, new TextureOperation(
  264. Instruction.TextureSize,
  265. texOp.Type,
  266. texOp.Format,
  267. texOp.Flags,
  268. texOp.CbufSlot,
  269. texOp.Handle,
  270. index,
  271. coordSize,
  272. texSizeSources));
  273. config.SetUsedTexture(Instruction.TextureSize, texOp.Type, texOp.Format, texOp.Flags, texOp.CbufSlot, texOp.Handle);
  274. Operand source = sources[coordsIndex + index];
  275. Operand coordNormalized = Local();
  276. node.List.AddBefore(node, new Operation(Instruction.FP32 | Instruction.Divide, coordNormalized, source, Float(coordSize)));
  277. sources[coordsIndex + index] = coordNormalized;
  278. }
  279. }
  280. // Technically, non-constant texture offsets are not allowed (according to the spec),
  281. // however some GPUs does support that.
  282. // For GPUs where it is not supported, we can replace the instruction with the following:
  283. // For texture*Offset, we replace it by texture*, and add the offset to the P coords.
  284. // The offset can be calculated as offset / textureSize(lod), where lod = textureQueryLod(coords).
  285. // For texelFetchOffset, we replace it by texelFetch and add the offset to the P coords directly.
  286. // For textureGatherOffset, we take advantage of the fact that the operation is already broken down
  287. // to read the 4 pixels separately, and just replace it with 4 textureGather with a different offset
  288. // for each pixel.
  289. if (hasInvalidOffset)
  290. {
  291. if (intCoords)
  292. {
  293. for (int index = 0; index < coordsCount; index++)
  294. {
  295. Operand source = sources[coordsIndex + index];
  296. Operand coordPlusOffset = Local();
  297. node.List.AddBefore(node, new Operation(Instruction.Add, coordPlusOffset, source, offsets[index]));
  298. sources[coordsIndex + index] = coordPlusOffset;
  299. }
  300. }
  301. else
  302. {
  303. config.SetUsedFeature(FeatureFlags.IntegerSampling);
  304. Operand lod = Local();
  305. node.List.AddBefore(node, new TextureOperation(
  306. Instruction.Lod,
  307. texOp.Type,
  308. texOp.Format,
  309. texOp.Flags,
  310. texOp.CbufSlot,
  311. texOp.Handle,
  312. 0,
  313. lod,
  314. lodSources));
  315. for (int index = 0; index < coordsCount; index++)
  316. {
  317. Operand coordSize = Local();
  318. Operand[] texSizeSources;
  319. if (isBindless || isIndexed)
  320. {
  321. texSizeSources = new Operand[] { sources[0], Int(lod) };
  322. }
  323. else
  324. {
  325. texSizeSources = new Operand[] { Int(lod) };
  326. }
  327. node.List.AddBefore(node, new TextureOperation(
  328. Instruction.TextureSize,
  329. texOp.Type,
  330. texOp.Format,
  331. texOp.Flags,
  332. texOp.CbufSlot,
  333. texOp.Handle,
  334. index,
  335. coordSize,
  336. texSizeSources));
  337. config.SetUsedTexture(Instruction.TextureSize, texOp.Type, texOp.Format, texOp.Flags, texOp.CbufSlot, texOp.Handle);
  338. Operand offset = Local();
  339. Operand intOffset = offsets[index + (hasOffsets ? texOp.Index * coordsCount : 0)];
  340. node.List.AddBefore(node, new Operation(Instruction.FP32 | Instruction.Divide, offset, Float(intOffset), Float(coordSize)));
  341. Operand source = sources[coordsIndex + index];
  342. Operand coordPlusOffset = Local();
  343. node.List.AddBefore(node, new Operation(Instruction.FP32 | Instruction.Add, coordPlusOffset, source, offset));
  344. sources[coordsIndex + index] = coordPlusOffset;
  345. }
  346. }
  347. if (isGather && !isShadow)
  348. {
  349. Operand gatherComponent = sources[dstIndex - 1];
  350. Debug.Assert(gatherComponent.Type == OperandType.Constant);
  351. componentIndex = gatherComponent.Value;
  352. }
  353. }
  354. TextureOperation newTexOp = new TextureOperation(
  355. Instruction.TextureSample,
  356. texOp.Type,
  357. texOp.Format,
  358. texOp.Flags & ~(TextureFlags.Offset | TextureFlags.Offsets),
  359. texOp.CbufSlot,
  360. texOp.Handle,
  361. componentIndex,
  362. texOp.Dest,
  363. sources);
  364. for (int index = 0; index < texOp.SourcesCount; index++)
  365. {
  366. texOp.SetSource(index, null);
  367. }
  368. LinkedListNode<INode> oldNode = node;
  369. node = node.List.AddBefore(node, newTexOp);
  370. node.List.Remove(oldNode);
  371. return node;
  372. }
  373. private static LinkedListNode<INode> InsertSnormNormalization(LinkedListNode<INode> node, ShaderConfig config)
  374. {
  375. TextureOperation texOp = (TextureOperation)node.Value;
  376. // We can't query the format of a bindless texture,
  377. // because the handle is unknown, it can have any format.
  378. if (texOp.Flags.HasFlag(TextureFlags.Bindless))
  379. {
  380. return node;
  381. }
  382. TextureFormat format = config.GpuAccessor.QueryTextureFormat(texOp.Handle, texOp.CbufSlot);
  383. int maxPositive = format switch
  384. {
  385. TextureFormat.R8Snorm => sbyte.MaxValue,
  386. TextureFormat.R8G8Snorm => sbyte.MaxValue,
  387. TextureFormat.R8G8B8A8Snorm => sbyte.MaxValue,
  388. TextureFormat.R16Snorm => short.MaxValue,
  389. TextureFormat.R16G16Snorm => short.MaxValue,
  390. TextureFormat.R16G16B16A16Snorm => short.MaxValue,
  391. _ => 0
  392. };
  393. // The value being 0 means that the format is not a SNORM format,
  394. // so there's nothing to do here.
  395. if (maxPositive == 0)
  396. {
  397. return node;
  398. }
  399. // Do normalization. We assume SINT formats are being used
  400. // as replacement for SNORM (which is not supported).
  401. INode[] uses = texOp.Dest.UseOps.ToArray();
  402. Operation convOp = new Operation(Instruction.ConvertS32ToFP32, Local(), texOp.Dest);
  403. Operation normOp = new Operation(Instruction.FP32 | Instruction.Multiply, Local(), convOp.Dest, ConstF(1f / maxPositive));
  404. node = node.List.AddAfter(node, convOp);
  405. node = node.List.AddAfter(node, normOp);
  406. foreach (INode useOp in uses)
  407. {
  408. if (useOp is not Operation op)
  409. {
  410. continue;
  411. }
  412. // Replace all uses of the texture pixel value with the normalized value.
  413. for (int index = 0; index < op.SourcesCount; index++)
  414. {
  415. if (op.GetSource(index) == texOp.Dest)
  416. {
  417. op.SetSource(index, normOp.Dest);
  418. }
  419. }
  420. }
  421. return node;
  422. }
  423. private static bool ReplaceConstantBufferWithDrawParameters(Operation operation)
  424. {
  425. bool modified = false;
  426. for (int srcIndex = 0; srcIndex < operation.SourcesCount; srcIndex++)
  427. {
  428. Operand src = operation.GetSource(srcIndex);
  429. if (src.Type == OperandType.ConstantBuffer && src.GetCbufSlot() == 0)
  430. {
  431. switch (src.GetCbufOffset())
  432. {
  433. case Constants.NvnBaseVertexByteOffset / 4:
  434. operation.SetSource(srcIndex, Attribute(AttributeConsts.BaseVertex));
  435. modified = true;
  436. break;
  437. case Constants.NvnBaseInstanceByteOffset / 4:
  438. operation.SetSource(srcIndex, Attribute(AttributeConsts.BaseInstance));
  439. modified = true;
  440. break;
  441. case Constants.NvnDrawIndexByteOffset / 4:
  442. operation.SetSource(srcIndex, Attribute(AttributeConsts.DrawIndex));
  443. modified = true;
  444. break;
  445. }
  446. }
  447. }
  448. return modified;
  449. }
  450. private static bool HasConstantBufferDrawParameters(Operation operation)
  451. {
  452. for (int srcIndex = 0; srcIndex < operation.SourcesCount; srcIndex++)
  453. {
  454. Operand src = operation.GetSource(srcIndex);
  455. if (src.Type == OperandType.ConstantBuffer && src.GetCbufSlot() == 0)
  456. {
  457. switch (src.GetCbufOffset())
  458. {
  459. case Constants.NvnBaseVertexByteOffset / 4:
  460. case Constants.NvnBaseInstanceByteOffset / 4:
  461. case Constants.NvnDrawIndexByteOffset / 4:
  462. return true;
  463. }
  464. }
  465. }
  466. return false;
  467. }
  468. }
  469. }