Decoder.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  1. using Ryujinx.Graphics.Shader.Instructions;
  2. using Ryujinx.Graphics.Shader.Translation;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using static Ryujinx.Graphics.Shader.IntermediateRepresentation.OperandHelper;
  7. namespace Ryujinx.Graphics.Shader.Decoders
  8. {
  9. static class Decoder
  10. {
  11. public static Block[][] Decode(ShaderConfig config, ulong startAddress)
  12. {
  13. List<Block[]> funcs = new List<Block[]>();
  14. Queue<ulong> funcQueue = new Queue<ulong>();
  15. HashSet<ulong> funcVisited = new HashSet<ulong>();
  16. void EnqueueFunction(ulong funcAddress)
  17. {
  18. if (funcVisited.Add(funcAddress))
  19. {
  20. funcQueue.Enqueue(funcAddress);
  21. }
  22. }
  23. funcQueue.Enqueue(0);
  24. while (funcQueue.TryDequeue(out ulong funcAddress))
  25. {
  26. List<Block> blocks = new List<Block>();
  27. Queue<Block> workQueue = new Queue<Block>();
  28. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  29. Block GetBlock(ulong blkAddress)
  30. {
  31. if (!visited.TryGetValue(blkAddress, out Block block))
  32. {
  33. block = new Block(blkAddress);
  34. workQueue.Enqueue(block);
  35. visited.Add(blkAddress, block);
  36. }
  37. return block;
  38. }
  39. GetBlock(funcAddress);
  40. bool hasNewTarget;
  41. do
  42. {
  43. while (workQueue.TryDequeue(out Block currBlock))
  44. {
  45. // Check if the current block is inside another block.
  46. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  47. {
  48. Block nBlock = blocks[nBlkIndex];
  49. if (nBlock.Address == currBlock.Address)
  50. {
  51. throw new InvalidOperationException("Found duplicate block address on the list.");
  52. }
  53. nBlock.Split(currBlock);
  54. blocks.Insert(nBlkIndex + 1, currBlock);
  55. continue;
  56. }
  57. // If we have a block after the current one, set the limit address.
  58. ulong limitAddress = ulong.MaxValue;
  59. if (nBlkIndex != blocks.Count)
  60. {
  61. Block nBlock = blocks[nBlkIndex];
  62. int nextIndex = nBlkIndex + 1;
  63. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  64. {
  65. limitAddress = blocks[nextIndex].Address;
  66. }
  67. else if (nBlock.Address > currBlock.Address)
  68. {
  69. limitAddress = blocks[nBlkIndex].Address;
  70. }
  71. }
  72. FillBlock(config, currBlock, limitAddress, startAddress);
  73. if (currBlock.OpCodes.Count != 0)
  74. {
  75. // We should have blocks for all possible branch targets,
  76. // including those from SSY/PBK instructions.
  77. foreach (OpCodePush pushOp in currBlock.PushOpCodes)
  78. {
  79. GetBlock(pushOp.GetAbsoluteAddress());
  80. }
  81. // Set child blocks. "Branch" is the block the branch instruction
  82. // points to (when taken), "Next" is the block at the next address,
  83. // executed when the branch is not taken. For Unconditional Branches
  84. // or end of program, Next is null.
  85. OpCode lastOp = currBlock.GetLastOp();
  86. if (lastOp is OpCodeBranch opBr)
  87. {
  88. if (lastOp.Emitter == InstEmit.Cal)
  89. {
  90. EnqueueFunction(opBr.GetAbsoluteAddress());
  91. }
  92. else
  93. {
  94. currBlock.Branch = GetBlock(opBr.GetAbsoluteAddress());
  95. }
  96. }
  97. if (!IsUnconditionalBranch(lastOp))
  98. {
  99. currBlock.Next = GetBlock(currBlock.EndAddress);
  100. }
  101. }
  102. // Insert the new block on the list (sorted by address).
  103. if (blocks.Count != 0)
  104. {
  105. Block nBlock = blocks[nBlkIndex];
  106. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  107. }
  108. else
  109. {
  110. blocks.Add(currBlock);
  111. }
  112. }
  113. // Propagate SSY/PBK addresses into their uses (SYNC/BRK).
  114. foreach (Block block in blocks.Where(x => x.PushOpCodes.Count != 0))
  115. {
  116. for (int pushOpIndex = 0; pushOpIndex < block.PushOpCodes.Count; pushOpIndex++)
  117. {
  118. PropagatePushOp(visited, block, pushOpIndex);
  119. }
  120. }
  121. // Try to find target for BRX (indirect branch) instructions.
  122. hasNewTarget = false;
  123. foreach (Block block in blocks)
  124. {
  125. if (block.GetLastOp() is OpCodeBranchIndir opBrIndir && opBrIndir.PossibleTargets.Count == 0)
  126. {
  127. ulong baseOffset = opBrIndir.Address + 8 + (ulong)opBrIndir.Offset;
  128. // An indirect branch could go anywhere,
  129. // try to get the possible target offsets from the constant buffer.
  130. (int cbBaseOffset, int cbOffsetsCount) = FindBrxTargetRange(block, opBrIndir.Ra.Index);
  131. if (cbOffsetsCount != 0)
  132. {
  133. hasNewTarget = true;
  134. }
  135. for (int i = 0; i < cbOffsetsCount; i++)
  136. {
  137. uint targetOffset = config.GpuAccessor.ConstantBuffer1Read(cbBaseOffset + i * 4);
  138. Block target = GetBlock(baseOffset + targetOffset);
  139. opBrIndir.PossibleTargets.Add(target);
  140. target.Predecessors.Add(block);
  141. }
  142. }
  143. }
  144. // If we discovered new branch targets from the BRX instruction,
  145. // we need another round of decoding to decode the new blocks.
  146. // Additionally, we may have more SSY/PBK targets to propagate,
  147. // and new BRX instructions.
  148. }
  149. while (hasNewTarget);
  150. funcs.Add(blocks.ToArray());
  151. }
  152. return funcs.ToArray();
  153. }
  154. private static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  155. {
  156. index = 0;
  157. int left = 0;
  158. int right = blocks.Count - 1;
  159. while (left <= right)
  160. {
  161. int size = right - left;
  162. int middle = left + (size >> 1);
  163. Block block = blocks[middle];
  164. index = middle;
  165. if (address >= block.Address && address < block.EndAddress)
  166. {
  167. return true;
  168. }
  169. if (address < block.Address)
  170. {
  171. right = middle - 1;
  172. }
  173. else
  174. {
  175. left = middle + 1;
  176. }
  177. }
  178. return false;
  179. }
  180. private static void FillBlock(ShaderConfig config, Block block, ulong limitAddress, ulong startAddress)
  181. {
  182. IGpuAccessor gpuAccessor = config.GpuAccessor;
  183. ulong address = block.Address;
  184. do
  185. {
  186. if (address + 7 >= limitAddress)
  187. {
  188. break;
  189. }
  190. // Ignore scheduling instructions, which are written every 32 bytes.
  191. if ((address & 0x1f) == 0)
  192. {
  193. address += 8;
  194. continue;
  195. }
  196. ulong opAddress = address;
  197. address += 8;
  198. long opCode = gpuAccessor.MemoryRead<long>(startAddress + opAddress);
  199. (InstEmitter emitter, OpCodeTable.MakeOp makeOp) = OpCodeTable.GetEmitter(opCode);
  200. if (emitter == null)
  201. {
  202. // TODO: Warning, illegal encoding.
  203. block.OpCodes.Add(new OpCode(null, opAddress, opCode));
  204. continue;
  205. }
  206. if (makeOp == null)
  207. {
  208. throw new ArgumentNullException(nameof(makeOp));
  209. }
  210. OpCode op = makeOp(emitter, opAddress, opCode);
  211. // We check these patterns to figure out the presence of bindless access
  212. if ((op is OpCodeImage image && image.IsBindless) ||
  213. (op is OpCodeTxd txd && txd.IsBindless) ||
  214. (op is OpCodeTld4B) ||
  215. (emitter == InstEmit.TexB) ||
  216. (emitter == InstEmit.TldB) ||
  217. (emitter == InstEmit.TmmlB) ||
  218. (emitter == InstEmit.TxqB))
  219. {
  220. config.SetUsedFeature(FeatureFlags.Bindless);
  221. }
  222. // Populate used attributes.
  223. if (op is IOpCodeAttribute opAttr)
  224. {
  225. for (int elemIndex = 0; elemIndex < opAttr.Count; elemIndex++)
  226. {
  227. int attr = opAttr.AttributeOffset + elemIndex * 4;
  228. if (attr >= AttributeConsts.UserAttributeBase && attr < AttributeConsts.UserAttributeEnd)
  229. {
  230. int index = (attr - AttributeConsts.UserAttributeBase) / 16;
  231. if (op.Emitter == InstEmit.Ast)
  232. {
  233. config.SetOutputUserAttribute(index);
  234. }
  235. else
  236. {
  237. config.SetInputUserAttribute(index);
  238. }
  239. }
  240. }
  241. }
  242. block.OpCodes.Add(op);
  243. }
  244. while (!IsControlFlowChange(block.GetLastOp()));
  245. block.EndAddress = address;
  246. block.UpdatePushOps();
  247. }
  248. private static bool IsUnconditionalBranch(OpCode opCode)
  249. {
  250. return IsUnconditional(opCode) && IsControlFlowChange(opCode);
  251. }
  252. private static bool IsUnconditional(OpCode opCode)
  253. {
  254. if (opCode is OpCodeExit op && op.Condition != Condition.Always)
  255. {
  256. return false;
  257. }
  258. return opCode.Predicate.Index == RegisterConsts.PredicateTrueIndex && !opCode.InvertPredicate;
  259. }
  260. private static bool IsControlFlowChange(OpCode opCode)
  261. {
  262. return (opCode is OpCodeBranch opBranch && !opBranch.PushTarget) ||
  263. opCode is OpCodeBranchIndir ||
  264. opCode is OpCodeBranchPop ||
  265. opCode is OpCodeExit;
  266. }
  267. private static (int, int) FindBrxTargetRange(Block block, int brxReg)
  268. {
  269. // Try to match the following pattern:
  270. //
  271. // IMNMX.U32 Rx, Rx, UpperBound, PT
  272. // SHL Rx, Rx, 0x2
  273. // LDC Rx, c[0x1][Rx+BaseOffset]
  274. //
  275. // Here, Rx is an arbitrary register, "UpperBound" and "BaseOffset" are constants.
  276. // The above pattern is assumed to be generated by the compiler before BRX,
  277. // as the instruction is usually used to implement jump tables for switch statement optimizations.
  278. // On a successful match, "BaseOffset" is the offset in bytes where the jump offsets are
  279. // located on the constant buffer, and "UpperBound" is the total number of offsets for the BRX, minus 1.
  280. HashSet<Block> visited = new HashSet<Block>();
  281. var ldcLocation = FindFirstRegWrite(visited, new BlockLocation(block, block.OpCodes.Count - 1), brxReg);
  282. if (ldcLocation.Block == null || ldcLocation.Block.OpCodes[ldcLocation.Index] is not OpCodeLdc opLdc)
  283. {
  284. return (0, 0);
  285. }
  286. if (opLdc.Slot != 1 || opLdc.IndexMode != CbIndexMode.Default)
  287. {
  288. return (0, 0);
  289. }
  290. var shlLocation = FindFirstRegWrite(visited, ldcLocation, opLdc.Ra.Index);
  291. if (shlLocation.Block == null || shlLocation.Block.OpCodes[shlLocation.Index] is not OpCodeAluImm opShl)
  292. {
  293. return (0, 0);
  294. }
  295. if (opShl.Emitter != InstEmit.Shl || opShl.Immediate != 2)
  296. {
  297. return (0, 0);
  298. }
  299. var imnmxLocation = FindFirstRegWrite(visited, shlLocation, opShl.Ra.Index);
  300. if (imnmxLocation.Block == null || imnmxLocation.Block.OpCodes[imnmxLocation.Index] is not OpCodeAluImm opImnmx)
  301. {
  302. return (0, 0);
  303. }
  304. bool isImnmxS32 = opImnmx.RawOpCode.Extract(48);
  305. if (opImnmx.Emitter != InstEmit.Imnmx || isImnmxS32 || !opImnmx.Predicate39.IsPT || opImnmx.InvertP)
  306. {
  307. return (0, 0);
  308. }
  309. return (opLdc.Offset, opImnmx.Immediate + 1);
  310. }
  311. private struct BlockLocation
  312. {
  313. public Block Block { get; }
  314. public int Index { get; }
  315. public BlockLocation(Block block, int index)
  316. {
  317. Block = block;
  318. Index = index;
  319. }
  320. }
  321. private static BlockLocation FindFirstRegWrite(HashSet<Block> visited, BlockLocation location, int regIndex)
  322. {
  323. Queue<BlockLocation> toVisit = new Queue<BlockLocation>();
  324. toVisit.Enqueue(location);
  325. visited.Add(location.Block);
  326. while (toVisit.TryDequeue(out var currentLocation))
  327. {
  328. Block block = currentLocation.Block;
  329. for (int i = currentLocation.Index - 1; i >= 0; i--)
  330. {
  331. if (WritesToRegister(block.OpCodes[i], regIndex))
  332. {
  333. return new BlockLocation(block, i);
  334. }
  335. }
  336. foreach (Block predecessor in block.Predecessors)
  337. {
  338. if (visited.Add(predecessor))
  339. {
  340. toVisit.Enqueue(new BlockLocation(predecessor, predecessor.OpCodes.Count));
  341. }
  342. }
  343. }
  344. return new BlockLocation(null, 0);
  345. }
  346. private static bool WritesToRegister(OpCode opCode, int regIndex)
  347. {
  348. // Predicate instruction only ever writes to predicate, so we shouldn't check those.
  349. if (opCode.Emitter == InstEmit.Fsetp ||
  350. opCode.Emitter == InstEmit.Hsetp2 ||
  351. opCode.Emitter == InstEmit.Isetp ||
  352. opCode.Emitter == InstEmit.R2p)
  353. {
  354. return false;
  355. }
  356. return opCode is IOpCodeRd opRd && opRd.Rd.Index == regIndex;
  357. }
  358. private enum MergeType
  359. {
  360. Brk = 0,
  361. Sync = 1
  362. }
  363. private struct PathBlockState
  364. {
  365. public Block Block { get; }
  366. private enum RestoreType
  367. {
  368. None,
  369. PopPushOp,
  370. PushBranchOp
  371. }
  372. private RestoreType _restoreType;
  373. private ulong _restoreValue;
  374. private MergeType _restoreMergeType;
  375. public bool ReturningFromVisit => _restoreType != RestoreType.None;
  376. public PathBlockState(Block block)
  377. {
  378. Block = block;
  379. _restoreType = RestoreType.None;
  380. _restoreValue = 0;
  381. _restoreMergeType = default;
  382. }
  383. public PathBlockState(int oldStackSize)
  384. {
  385. Block = null;
  386. _restoreType = RestoreType.PopPushOp;
  387. _restoreValue = (ulong)oldStackSize;
  388. _restoreMergeType = default;
  389. }
  390. public PathBlockState(ulong syncAddress, MergeType mergeType)
  391. {
  392. Block = null;
  393. _restoreType = RestoreType.PushBranchOp;
  394. _restoreValue = syncAddress;
  395. _restoreMergeType = mergeType;
  396. }
  397. public void RestoreStackState(Stack<(ulong, MergeType)> branchStack)
  398. {
  399. if (_restoreType == RestoreType.PushBranchOp)
  400. {
  401. branchStack.Push((_restoreValue, _restoreMergeType));
  402. }
  403. else if (_restoreType == RestoreType.PopPushOp)
  404. {
  405. while (branchStack.Count > (uint)_restoreValue)
  406. {
  407. branchStack.Pop();
  408. }
  409. }
  410. }
  411. }
  412. private static void PropagatePushOp(Dictionary<ulong, Block> blocks, Block currBlock, int pushOpIndex)
  413. {
  414. OpCodePush pushOp = currBlock.PushOpCodes[pushOpIndex];
  415. Block target = blocks[pushOp.GetAbsoluteAddress()];
  416. Stack<PathBlockState> workQueue = new Stack<PathBlockState>();
  417. HashSet<Block> visited = new HashSet<Block>();
  418. Stack<(ulong, MergeType)> branchStack = new Stack<(ulong, MergeType)>();
  419. void Push(PathBlockState pbs)
  420. {
  421. // When block is null, this means we are pushing a restore operation.
  422. // Restore operations are used to undo the work done inside a block
  423. // when we return from it, for example it pops addresses pushed by
  424. // SSY/PBK instructions inside the block, and pushes addresses poped
  425. // by SYNC/BRK.
  426. // For blocks, if it's already visited, we just ignore to avoid going
  427. // around in circles and getting stuck here.
  428. if (pbs.Block == null || !visited.Contains(pbs.Block))
  429. {
  430. workQueue.Push(pbs);
  431. }
  432. }
  433. Push(new PathBlockState(currBlock));
  434. while (workQueue.TryPop(out PathBlockState pbs))
  435. {
  436. if (pbs.ReturningFromVisit)
  437. {
  438. pbs.RestoreStackState(branchStack);
  439. continue;
  440. }
  441. Block current = pbs.Block;
  442. // If the block was already processed, we just ignore it, otherwise
  443. // we would push the same child blocks of an already processed block,
  444. // and go around in circles until memory is exhausted.
  445. if (!visited.Add(current))
  446. {
  447. continue;
  448. }
  449. int pushOpsCount = current.PushOpCodes.Count;
  450. if (pushOpsCount != 0)
  451. {
  452. Push(new PathBlockState(branchStack.Count));
  453. for (int index = pushOpIndex; index < pushOpsCount; index++)
  454. {
  455. OpCodePush currentPushOp = current.PushOpCodes[index];
  456. MergeType pushMergeType = currentPushOp.Emitter == InstEmit.Ssy ? MergeType.Sync : MergeType.Brk;
  457. branchStack.Push((currentPushOp.GetAbsoluteAddress(), pushMergeType));
  458. }
  459. }
  460. pushOpIndex = 0;
  461. if (current.Next != null)
  462. {
  463. Push(new PathBlockState(current.Next));
  464. }
  465. if (current.Branch != null)
  466. {
  467. Push(new PathBlockState(current.Branch));
  468. }
  469. else if (current.GetLastOp() is OpCodeBranchIndir brIndir)
  470. {
  471. // By adding them in descending order (sorted by address), we process the blocks
  472. // in order (of ascending address), since we work with a LIFO.
  473. foreach (Block possibleTarget in brIndir.PossibleTargets.OrderByDescending(x => x.Address))
  474. {
  475. Push(new PathBlockState(possibleTarget));
  476. }
  477. }
  478. else if (current.GetLastOp() is OpCodeBranchPop op)
  479. {
  480. MergeType popMergeType = op.Emitter == InstEmit.Sync ? MergeType.Sync : MergeType.Brk;
  481. bool found = true;
  482. ulong targetAddress = 0UL;
  483. MergeType mergeType;
  484. do
  485. {
  486. if (branchStack.Count == 0)
  487. {
  488. found = false;
  489. break;
  490. }
  491. (targetAddress, mergeType) = branchStack.Pop();
  492. // Push the target address (this will be used to push the address
  493. // back into the SSY/PBK stack when we return from that block),
  494. Push(new PathBlockState(targetAddress, mergeType));
  495. }
  496. while (mergeType != popMergeType);
  497. // Make sure we found the correct address,
  498. // the push and pop instruction types must match, so:
  499. // - BRK can only consume addresses pushed by PBK.
  500. // - SYNC can only consume addresses pushed by SSY.
  501. if (found)
  502. {
  503. if (branchStack.Count == 0)
  504. {
  505. // If the entire stack was consumed, then the current pop instruction
  506. // just consumed the address from our push instruction.
  507. if (op.Targets.TryAdd(pushOp, op.Targets.Count))
  508. {
  509. pushOp.PopOps.Add(op, Local());
  510. target.Predecessors.Add(current);
  511. }
  512. }
  513. else
  514. {
  515. // Push the block itself into the work "queue" (well, it's a stack)
  516. // for processing.
  517. Push(new PathBlockState(blocks[targetAddress]));
  518. }
  519. }
  520. }
  521. }
  522. }
  523. }
  524. }