StructuredProgramContext.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. using Ryujinx.Graphics.Shader.IntermediateRepresentation;
  2. using Ryujinx.Graphics.Shader.Translation;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Numerics;
  6. using static Ryujinx.Graphics.Shader.StructuredIr.AstHelper;
  7. namespace Ryujinx.Graphics.Shader.StructuredIr
  8. {
  9. class StructuredProgramContext
  10. {
  11. private HashSet<BasicBlock> _loopTails;
  12. private Stack<(AstBlock Block, int CurrEndIndex, int LoopEndIndex)> _blockStack;
  13. private Dictionary<Operand, AstOperand> _localsMap;
  14. private Dictionary<int, AstAssignment> _gotoTempAsgs;
  15. private List<GotoStatement> _gotos;
  16. private AstBlock _currBlock;
  17. private int _currEndIndex;
  18. private int _loopEndIndex;
  19. public StructuredFunction CurrentFunction { get; private set; }
  20. public StructuredProgramInfo Info { get; }
  21. public ShaderConfig Config { get; }
  22. public StructuredProgramContext(ShaderConfig config)
  23. {
  24. Info = new StructuredProgramInfo();
  25. Config = config;
  26. if (config.GpPassthrough)
  27. {
  28. int passthroughAttributes = config.PassthroughAttributes;
  29. while (passthroughAttributes != 0)
  30. {
  31. int index = BitOperations.TrailingZeroCount(passthroughAttributes);
  32. int attrBase = AttributeConsts.UserAttributeBase + index * 16;
  33. Info.Inputs.Add(attrBase);
  34. Info.Inputs.Add(attrBase + 4);
  35. Info.Inputs.Add(attrBase + 8);
  36. Info.Inputs.Add(attrBase + 12);
  37. passthroughAttributes &= ~(1 << index);
  38. }
  39. Info.Inputs.Add(AttributeConsts.PositionX);
  40. Info.Inputs.Add(AttributeConsts.PositionY);
  41. Info.Inputs.Add(AttributeConsts.PositionZ);
  42. Info.Inputs.Add(AttributeConsts.PositionW);
  43. Info.Inputs.Add(AttributeConsts.PointSize);
  44. for (int i = 0; i < 8; i++)
  45. {
  46. Info.Inputs.Add(AttributeConsts.ClipDistance0 + i * 4);
  47. }
  48. }
  49. else if (config.Stage == ShaderStage.Fragment)
  50. {
  51. // Potentially used for texture coordinate scaling.
  52. Info.Inputs.Add(AttributeConsts.PositionX);
  53. Info.Inputs.Add(AttributeConsts.PositionY);
  54. }
  55. }
  56. public void EnterFunction(
  57. int blocksCount,
  58. string name,
  59. VariableType returnType,
  60. VariableType[] inArguments,
  61. VariableType[] outArguments)
  62. {
  63. _loopTails = new HashSet<BasicBlock>();
  64. _blockStack = new Stack<(AstBlock, int, int)>();
  65. _localsMap = new Dictionary<Operand, AstOperand>();
  66. _gotoTempAsgs = new Dictionary<int, AstAssignment>();
  67. _gotos = new List<GotoStatement>();
  68. _currBlock = new AstBlock(AstBlockType.Main);
  69. _currEndIndex = blocksCount;
  70. _loopEndIndex = blocksCount;
  71. CurrentFunction = new StructuredFunction(_currBlock, name, returnType, inArguments, outArguments);
  72. }
  73. public void LeaveFunction()
  74. {
  75. Info.Functions.Add(CurrentFunction);
  76. }
  77. public void EnterBlock(BasicBlock block)
  78. {
  79. while (_currEndIndex == block.Index)
  80. {
  81. (_currBlock, _currEndIndex, _loopEndIndex) = _blockStack.Pop();
  82. }
  83. if (_gotoTempAsgs.TryGetValue(block.Index, out AstAssignment gotoTempAsg))
  84. {
  85. AddGotoTempReset(block, gotoTempAsg);
  86. }
  87. LookForDoWhileStatements(block);
  88. }
  89. public void LeaveBlock(BasicBlock block, Operation branchOp)
  90. {
  91. LookForIfStatements(block, branchOp);
  92. }
  93. private void LookForDoWhileStatements(BasicBlock block)
  94. {
  95. // Check if we have any predecessor whose index is greater than the
  96. // current block, this indicates a loop.
  97. bool done = false;
  98. foreach (BasicBlock predecessor in block.Predecessors.OrderByDescending(x => x.Index))
  99. {
  100. // If not a loop, break.
  101. if (predecessor.Index < block.Index)
  102. {
  103. break;
  104. }
  105. // Check if we can create a do-while loop here (only possible if the loop end
  106. // falls inside the current scope), if not add a goto instead.
  107. if (predecessor.Index < _currEndIndex && !done)
  108. {
  109. // Create do-while loop block. We must avoid inserting a goto at the end
  110. // of the loop later, when the tail block is processed. So we add the predecessor
  111. // to a list of loop tails to prevent it from being processed later.
  112. Operation branchOp = (Operation)predecessor.GetLastOp();
  113. NewBlock(AstBlockType.DoWhile, branchOp, predecessor.Index + 1);
  114. _loopTails.Add(predecessor);
  115. done = true;
  116. }
  117. else
  118. {
  119. // Failed to create loop. Since this block is the loop head, we reset the
  120. // goto condition variable here. The variable is always reset on the jump
  121. // target, and this block is the jump target for some loop.
  122. AddGotoTempReset(block, GetGotoTempAsg(block.Index));
  123. break;
  124. }
  125. }
  126. }
  127. private void LookForIfStatements(BasicBlock block, Operation branchOp)
  128. {
  129. if (block.Branch == null)
  130. {
  131. return;
  132. }
  133. // We can only enclose the "if" when the branch lands before
  134. // the end of the current block. If the current enclosing block
  135. // is not a loop, then we can also do so if the branch lands
  136. // right at the end of the current block. When it is a loop,
  137. // this is not valid as the loop condition would be evaluated,
  138. // and it could erroneously jump back to the start of the loop.
  139. bool inRange =
  140. block.Branch.Index < _currEndIndex ||
  141. (block.Branch.Index == _currEndIndex && block.Branch.Index < _loopEndIndex);
  142. bool isLoop = block.Branch.Index <= block.Index;
  143. if (inRange && !isLoop)
  144. {
  145. NewBlock(AstBlockType.If, branchOp, block.Branch.Index);
  146. }
  147. else if (!_loopTails.Contains(block))
  148. {
  149. AstAssignment gotoTempAsg = GetGotoTempAsg(block.Branch.Index);
  150. // We use DoWhile type here, as the condition should be true for
  151. // unconditional branches, or it should jump if the condition is true otherwise.
  152. IAstNode cond = GetBranchCond(AstBlockType.DoWhile, branchOp);
  153. AddNode(Assign(gotoTempAsg.Destination, cond));
  154. AstOperation branch = new AstOperation(branchOp.Inst);
  155. AddNode(branch);
  156. GotoStatement gotoStmt = new GotoStatement(branch, gotoTempAsg, isLoop);
  157. _gotos.Add(gotoStmt);
  158. }
  159. }
  160. private AstAssignment GetGotoTempAsg(int index)
  161. {
  162. if (_gotoTempAsgs.TryGetValue(index, out AstAssignment gotoTempAsg))
  163. {
  164. return gotoTempAsg;
  165. }
  166. AstOperand gotoTemp = NewTemp(VariableType.Bool);
  167. gotoTempAsg = Assign(gotoTemp, Const(IrConsts.False));
  168. _gotoTempAsgs.Add(index, gotoTempAsg);
  169. return gotoTempAsg;
  170. }
  171. private void AddGotoTempReset(BasicBlock block, AstAssignment gotoTempAsg)
  172. {
  173. // If it was already added, we don't need to add it again.
  174. if (gotoTempAsg.Parent != null)
  175. {
  176. return;
  177. }
  178. AddNode(gotoTempAsg);
  179. // For block 0, we don't need to add the extra "reset" at the beginning,
  180. // because it is already the first node to be executed on the shader,
  181. // so it is reset to false by the "local" assignment anyway.
  182. if (block.Index != 0)
  183. {
  184. CurrentFunction.MainBlock.AddFirst(Assign(gotoTempAsg.Destination, Const(IrConsts.False)));
  185. }
  186. }
  187. private void NewBlock(AstBlockType type, Operation branchOp, int endIndex)
  188. {
  189. NewBlock(type, GetBranchCond(type, branchOp), endIndex);
  190. }
  191. private void NewBlock(AstBlockType type, IAstNode cond, int endIndex)
  192. {
  193. AstBlock childBlock = new AstBlock(type, cond);
  194. AddNode(childBlock);
  195. _blockStack.Push((_currBlock, _currEndIndex, _loopEndIndex));
  196. _currBlock = childBlock;
  197. _currEndIndex = endIndex;
  198. if (type == AstBlockType.DoWhile)
  199. {
  200. _loopEndIndex = endIndex;
  201. }
  202. }
  203. private IAstNode GetBranchCond(AstBlockType type, Operation branchOp)
  204. {
  205. IAstNode cond;
  206. if (branchOp.Inst == Instruction.Branch)
  207. {
  208. // If the branch is not conditional, the condition is a constant.
  209. // For if it's false (always jump over, if block never executed).
  210. // For loops it's always true (always loop).
  211. cond = Const(type == AstBlockType.If ? IrConsts.False : IrConsts.True);
  212. }
  213. else
  214. {
  215. cond = GetOperandUse(branchOp.GetSource(0));
  216. Instruction invInst = type == AstBlockType.If
  217. ? Instruction.BranchIfTrue
  218. : Instruction.BranchIfFalse;
  219. if (branchOp.Inst == invInst)
  220. {
  221. cond = new AstOperation(Instruction.LogicalNot, cond);
  222. }
  223. }
  224. return cond;
  225. }
  226. public void AddNode(IAstNode node)
  227. {
  228. _currBlock.Add(node);
  229. }
  230. public GotoStatement[] GetGotos()
  231. {
  232. return _gotos.ToArray();
  233. }
  234. private AstOperand NewTemp(VariableType type)
  235. {
  236. AstOperand newTemp = Local(type);
  237. CurrentFunction.Locals.Add(newTemp);
  238. return newTemp;
  239. }
  240. public AstOperand GetOperandDef(Operand operand)
  241. {
  242. if (operand.Type == OperandType.Attribute)
  243. {
  244. Info.Outputs.Add(operand.Value & AttributeConsts.Mask);
  245. }
  246. else if (operand.Type == OperandType.AttributePerPatch)
  247. {
  248. Info.OutputsPerPatch.Add(operand.Value & AttributeConsts.Mask);
  249. }
  250. return GetOperand(operand);
  251. }
  252. public AstOperand GetOperandUse(Operand operand)
  253. {
  254. // If this flag is set, we're reading from an output attribute instead.
  255. if (operand.Type.IsAttribute() && (operand.Value & AttributeConsts.LoadOutputMask) != 0)
  256. {
  257. return GetOperandDef(operand);
  258. }
  259. if (operand.Type == OperandType.Attribute)
  260. {
  261. Info.Inputs.Add(operand.Value);
  262. }
  263. else if (operand.Type == OperandType.AttributePerPatch)
  264. {
  265. Info.InputsPerPatch.Add(operand.Value);
  266. }
  267. return GetOperand(operand);
  268. }
  269. private AstOperand GetOperand(Operand operand)
  270. {
  271. if (operand == null)
  272. {
  273. return null;
  274. }
  275. if (operand.Type != OperandType.LocalVariable)
  276. {
  277. if (operand.Type == OperandType.ConstantBuffer)
  278. {
  279. Config.SetUsedConstantBuffer(operand.GetCbufSlot());
  280. }
  281. return new AstOperand(operand);
  282. }
  283. if (!_localsMap.TryGetValue(operand, out AstOperand astOperand))
  284. {
  285. astOperand = new AstOperand(operand);
  286. _localsMap.Add(operand, astOperand);
  287. CurrentFunction.Locals.Add(astOperand);
  288. }
  289. return astOperand;
  290. }
  291. }
  292. }