StructuredProgramContext.cs 12 KB

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