HelperFunctionManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using System;
  3. using System.Collections.Generic;
  4. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  5. namespace Ryujinx.Graphics.Shader.Translation
  6. {
  7. class HelperFunctionManager
  8. {
  9. private readonly List<Function> _functionList;
  10. private readonly Dictionary<int, int> _functionIds;
  11. private readonly ShaderStage _stage;
  12. public HelperFunctionManager(List<Function> functionList, ShaderStage stage)
  13. {
  14. _functionList = functionList;
  15. _functionIds = new Dictionary<int, int>();
  16. _stage = stage;
  17. }
  18. public int AddFunction(Function function)
  19. {
  20. int functionId = _functionList.Count;
  21. _functionList.Add(function);
  22. return functionId;
  23. }
  24. public int GetOrCreateFunctionId(HelperFunctionName functionName)
  25. {
  26. if (_functionIds.TryGetValue((int)functionName, out int functionId))
  27. {
  28. return functionId;
  29. }
  30. Function function = GenerateFunction(functionName);
  31. functionId = AddFunction(function);
  32. _functionIds.Add((int)functionName, functionId);
  33. return functionId;
  34. }
  35. public int GetOrCreateFunctionId(HelperFunctionName functionName, int id)
  36. {
  37. int key = (int)functionName | (id << 16);
  38. if (_functionIds.TryGetValue(key, out int functionId))
  39. {
  40. return functionId;
  41. }
  42. Function function = GenerateFunction(functionName, id);
  43. functionId = AddFunction(function);
  44. _functionIds.Add(key, functionId);
  45. return functionId;
  46. }
  47. private Function GenerateFunction(HelperFunctionName functionName)
  48. {
  49. return functionName switch
  50. {
  51. HelperFunctionName.ConvertDoubleToFloat => GenerateConvertDoubleToFloatFunction(),
  52. HelperFunctionName.ConvertFloatToDouble => GenerateConvertFloatToDoubleFunction(),
  53. HelperFunctionName.TexelFetchScale => GenerateTexelFetchScaleFunction(),
  54. HelperFunctionName.TextureSizeUnscale => GenerateTextureSizeUnscaleFunction(),
  55. _ => throw new ArgumentException($"Invalid function name {functionName}")
  56. };
  57. }
  58. private Function GenerateConvertDoubleToFloatFunction()
  59. {
  60. EmitterContext context = new EmitterContext();
  61. Operand valueLow = Argument(0);
  62. Operand valueHigh = Argument(1);
  63. Operand mantissaLow = context.BitwiseAnd(valueLow, Const(((1 << 22) - 1)));
  64. Operand mantissa = context.ShiftRightU32(valueLow, Const(22));
  65. mantissa = context.BitwiseOr(mantissa, context.ShiftLeft(context.BitwiseAnd(valueHigh, Const(0xfffff)), Const(10)));
  66. mantissa = context.BitwiseOr(mantissa, context.ConditionalSelect(mantissaLow, Const(1), Const(0)));
  67. Operand exp = context.BitwiseAnd(context.ShiftRightU32(valueHigh, Const(20)), Const(0x7ff));
  68. Operand sign = context.ShiftRightS32(valueHigh, Const(31));
  69. Operand resultSign = context.ShiftLeft(sign, Const(31));
  70. Operand notZero = context.BitwiseOr(mantissa, exp);
  71. Operand lblNotZero = Label();
  72. context.BranchIfTrue(lblNotZero, notZero);
  73. context.Return(resultSign);
  74. context.MarkLabel(lblNotZero);
  75. Operand notNaNOrInf = context.ICompareNotEqual(exp, Const(0x7ff));
  76. mantissa = context.BitwiseOr(mantissa, Const(0x40000000));
  77. exp = context.ISubtract(exp, Const(0x381));
  78. // Note: Overflow cases are not handled here and might produce incorrect results.
  79. Operand roundBits = context.BitwiseAnd(mantissa, Const(0x7f));
  80. Operand roundBitsXor64 = context.BitwiseExclusiveOr(roundBits, Const(0x40));
  81. mantissa = context.ShiftRightU32(context.IAdd(mantissa, Const(0x40)), Const(7));
  82. mantissa = context.BitwiseAnd(mantissa, context.ConditionalSelect(roundBitsXor64, Const(~0), Const(~1)));
  83. exp = context.ConditionalSelect(mantissa, exp, Const(0));
  84. exp = context.ConditionalSelect(notNaNOrInf, exp, Const(0xff));
  85. Operand result = context.IAdd(context.IAdd(mantissa, context.ShiftLeft(exp, Const(23))), resultSign);
  86. context.Return(result);
  87. return new Function(ControlFlowGraph.Create(context.GetOperations()).Blocks, "ConvertDoubleToFloat", true, 2, 0);
  88. }
  89. private Function GenerateConvertFloatToDoubleFunction()
  90. {
  91. EmitterContext context = new EmitterContext();
  92. Operand value = Argument(0);
  93. Operand mantissa = context.BitwiseAnd(value, Const(0x7fffff));
  94. Operand exp = context.BitwiseAnd(context.ShiftRightU32(value, Const(23)), Const(0xff));
  95. Operand sign = context.ShiftRightS32(value, Const(31));
  96. Operand notNaNOrInf = context.ICompareNotEqual(exp, Const(0xff));
  97. Operand expNotZero = context.ICompareNotEqual(exp, Const(0));
  98. Operand notDenorm = context.BitwiseOr(expNotZero, context.ICompareEqual(mantissa, Const(0)));
  99. exp = context.IAdd(exp, Const(0x380));
  100. Operand shiftDist = context.ISubtract(Const(32), context.FindMSBU32(mantissa));
  101. Operand normExp = context.ISubtract(context.ISubtract(Const(1), shiftDist), Const(1));
  102. Operand normMant = context.ShiftLeft(mantissa, shiftDist);
  103. exp = context.ConditionalSelect(notNaNOrInf, exp, Const(0x7ff));
  104. exp = context.ConditionalSelect(notDenorm, exp, normExp);
  105. mantissa = context.ConditionalSelect(expNotZero, mantissa, normMant);
  106. Operand resultLow = context.ShiftLeft(mantissa, Const(29));
  107. Operand resultHigh = context.ShiftRightU32(mantissa, Const(3));
  108. resultHigh = context.IAdd(resultHigh, context.ShiftLeft(exp, Const(20)));
  109. resultHigh = context.IAdd(resultHigh, context.ShiftLeft(sign, Const(31)));
  110. context.Copy(Argument(1), resultLow);
  111. context.Copy(Argument(2), resultHigh);
  112. context.Return();
  113. return new Function(ControlFlowGraph.Create(context.GetOperations()).Blocks, "ConvertFloatToDouble", false, 1, 2);
  114. }
  115. private static Function GenerateFunction(HelperFunctionName functionName, int id)
  116. {
  117. return functionName switch
  118. {
  119. HelperFunctionName.SharedAtomicMaxS32 => GenerateSharedAtomicSigned(id, isMin: false),
  120. HelperFunctionName.SharedAtomicMinS32 => GenerateSharedAtomicSigned(id, isMin: true),
  121. HelperFunctionName.SharedStore8 => GenerateSharedStore8(id),
  122. HelperFunctionName.SharedStore16 => GenerateSharedStore16(id),
  123. _ => throw new ArgumentException($"Invalid function name {functionName}")
  124. };
  125. }
  126. private static Function GenerateSharedAtomicSigned(int id, bool isMin)
  127. {
  128. EmitterContext context = new EmitterContext();
  129. Operand wordOffset = Argument(0);
  130. Operand value = Argument(1);
  131. Operand result = GenerateSharedAtomicCasLoop(context, wordOffset, id, (memValue) =>
  132. {
  133. return isMin
  134. ? context.IMinimumS32(memValue, value)
  135. : context.IMaximumS32(memValue, value);
  136. });
  137. context.Return(result);
  138. return new Function(ControlFlowGraph.Create(context.GetOperations()).Blocks, $"SharedAtomic{(isMin ? "Min" : "Max")}_{id}", true, 2, 0);
  139. }
  140. private static Function GenerateSharedStore8(int id)
  141. {
  142. return GenerateSharedStore(id, 8);
  143. }
  144. private static Function GenerateSharedStore16(int id)
  145. {
  146. return GenerateSharedStore(id, 16);
  147. }
  148. private static Function GenerateSharedStore(int id, int bitSize)
  149. {
  150. EmitterContext context = new EmitterContext();
  151. Operand offset = Argument(0);
  152. Operand value = Argument(1);
  153. Operand wordOffset = context.ShiftRightU32(offset, Const(2));
  154. Operand bitOffset = GetBitOffset(context, offset);
  155. GenerateSharedAtomicCasLoop(context, wordOffset, id, (memValue) =>
  156. {
  157. return context.BitfieldInsert(memValue, value, bitOffset, Const(bitSize));
  158. });
  159. context.Return();
  160. return new Function(ControlFlowGraph.Create(context.GetOperations()).Blocks, $"SharedStore{bitSize}_{id}", false, 2, 0);
  161. }
  162. private Function GenerateTexelFetchScaleFunction()
  163. {
  164. EmitterContext context = new EmitterContext();
  165. Operand input = Argument(0);
  166. Operand samplerIndex = Argument(1);
  167. Operand index = GetScaleIndex(context, samplerIndex);
  168. Operand scale = context.Load(StorageKind.ConstantBuffer, 0, Const((int)SupportBufferField.RenderScale), index);
  169. Operand scaleIsOne = context.FPCompareEqual(scale, ConstF(1f));
  170. Operand lblScaleNotOne = Label();
  171. context.BranchIfFalse(lblScaleNotOne, scaleIsOne);
  172. context.Return(input);
  173. context.MarkLabel(lblScaleNotOne);
  174. int inArgumentsCount;
  175. if (_stage == ShaderStage.Fragment)
  176. {
  177. Operand scaleIsLessThanZero = context.FPCompareLess(scale, ConstF(0f));
  178. Operand lblScaleGreaterOrEqualZero = Label();
  179. context.BranchIfFalse(lblScaleGreaterOrEqualZero, scaleIsLessThanZero);
  180. Operand negScale = context.FPNegate(scale);
  181. Operand inputScaled = context.FPMultiply(context.IConvertS32ToFP32(input), negScale);
  182. Operand fragCoordX = context.Load(StorageKind.Input, IoVariable.FragmentCoord, null, Const(0));
  183. Operand fragCoordY = context.Load(StorageKind.Input, IoVariable.FragmentCoord, null, Const(1));
  184. Operand fragCoord = context.ConditionalSelect(Argument(2), fragCoordY, fragCoordX);
  185. Operand inputBias = context.FPModulo(fragCoord, negScale);
  186. Operand inputWithBias = context.FPAdd(inputScaled, inputBias);
  187. context.Return(context.FP32ConvertToS32(inputWithBias));
  188. context.MarkLabel(lblScaleGreaterOrEqualZero);
  189. inArgumentsCount = 3;
  190. }
  191. else
  192. {
  193. inArgumentsCount = 2;
  194. }
  195. Operand inputScaled2 = context.FPMultiply(context.IConvertS32ToFP32(input), scale);
  196. context.Return(context.FP32ConvertToS32(inputScaled2));
  197. return new Function(ControlFlowGraph.Create(context.GetOperations()).Blocks, "TexelFetchScale", true, inArgumentsCount, 0);
  198. }
  199. private Function GenerateTextureSizeUnscaleFunction()
  200. {
  201. EmitterContext context = new EmitterContext();
  202. Operand input = Argument(0);
  203. Operand samplerIndex = Argument(1);
  204. Operand index = GetScaleIndex(context, samplerIndex);
  205. Operand scale = context.FPAbsolute(context.Load(StorageKind.ConstantBuffer, 0, Const((int)SupportBufferField.RenderScale), index));
  206. Operand scaleIsOne = context.FPCompareEqual(scale, ConstF(1f));
  207. Operand lblScaleNotOne = Label();
  208. context.BranchIfFalse(lblScaleNotOne, scaleIsOne);
  209. context.Return(input);
  210. context.MarkLabel(lblScaleNotOne);
  211. Operand inputUnscaled = context.FPDivide(context.IConvertS32ToFP32(input), scale);
  212. context.Return(context.FP32ConvertToS32(inputUnscaled));
  213. return new Function(ControlFlowGraph.Create(context.GetOperations()).Blocks, "TextureSizeUnscale", true, 2, 0);
  214. }
  215. private Operand GetScaleIndex(EmitterContext context, Operand index)
  216. {
  217. switch (_stage)
  218. {
  219. case ShaderStage.Vertex:
  220. Operand fragScaleCount = context.Load(StorageKind.ConstantBuffer, 0, Const((int)SupportBufferField.FragmentRenderScaleCount));
  221. return context.IAdd(Const(1), context.IAdd(index, fragScaleCount));
  222. default:
  223. return context.IAdd(Const(1), index);
  224. }
  225. }
  226. public static Operand GetBitOffset(EmitterContext context, Operand offset)
  227. {
  228. return context.ShiftLeft(context.BitwiseAnd(offset, Const(3)), Const(3));
  229. }
  230. private static Operand GenerateSharedAtomicCasLoop(EmitterContext context, Operand wordOffset, int id, Func<Operand, Operand> opCallback)
  231. {
  232. Operand lblLoopHead = Label();
  233. context.MarkLabel(lblLoopHead);
  234. Operand oldValue = context.Load(StorageKind.SharedMemory, id, wordOffset);
  235. Operand newValue = opCallback(oldValue);
  236. Operand casResult = context.AtomicCompareAndSwap(StorageKind.SharedMemory, id, wordOffset, oldValue, newValue);
  237. Operand casFail = context.ICompareNotEqual(casResult, oldValue);
  238. context.BranchIfTrue(lblLoopHead, casFail);
  239. return oldValue;
  240. }
  241. }
  242. }