Translator.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. using ChocolArm64.Decoders;
  2. using ChocolArm64.Events;
  3. using ChocolArm64.IntermediateRepresentation;
  4. using ChocolArm64.Memory;
  5. using ChocolArm64.State;
  6. using System;
  7. using System.Reflection.Emit;
  8. using System.Threading;
  9. namespace ChocolArm64.Translation
  10. {
  11. public class Translator
  12. {
  13. private MemoryManager _memory;
  14. private CpuThreadState _dummyThreadState;
  15. private TranslatorCache _cache;
  16. private TranslatorQueue _queue;
  17. private Thread _backgroundTranslator;
  18. public event EventHandler<CpuTraceEventArgs> CpuTrace;
  19. public bool EnableCpuTrace { get; set; }
  20. private volatile int _threadCount;
  21. public Translator(MemoryManager memory)
  22. {
  23. _memory = memory;
  24. _dummyThreadState = new CpuThreadState();
  25. _dummyThreadState.Running = false;
  26. _cache = new TranslatorCache();
  27. _queue = new TranslatorQueue();
  28. }
  29. internal void ExecuteSubroutine(CpuThread thread, long position)
  30. {
  31. if (Interlocked.Increment(ref _threadCount) == 1)
  32. {
  33. _backgroundTranslator = new Thread(TranslateQueuedSubs);
  34. _backgroundTranslator.Start();
  35. }
  36. ExecuteSubroutine(thread.ThreadState, position);
  37. if (Interlocked.Decrement(ref _threadCount) == 0)
  38. {
  39. _queue.ForceSignal();
  40. }
  41. }
  42. private void ExecuteSubroutine(CpuThreadState state, long position)
  43. {
  44. state.CurrentTranslator = this;
  45. do
  46. {
  47. if (EnableCpuTrace)
  48. {
  49. CpuTrace?.Invoke(this, new CpuTraceEventArgs(position));
  50. }
  51. if (!_cache.TryGetSubroutine(position, out TranslatedSub sub))
  52. {
  53. sub = TranslateLowCq(position, state.GetExecutionMode());
  54. }
  55. position = sub.Execute(state, _memory);
  56. }
  57. while (position != 0 && state.Running);
  58. state.CurrentTranslator = null;
  59. }
  60. internal ArmSubroutine GetOrTranslateSubroutine(CpuThreadState state, long position, CallType cs)
  61. {
  62. if (!_cache.TryGetSubroutine(position, out TranslatedSub sub))
  63. {
  64. sub = TranslateLowCq(position, state.GetExecutionMode());
  65. }
  66. if (sub.Rejit())
  67. {
  68. bool isComplete = cs == CallType.Call ||
  69. cs == CallType.VirtualCall;
  70. _queue.Enqueue(position, state.GetExecutionMode(), TranslationTier.Tier1, isComplete);
  71. }
  72. return sub.Delegate;
  73. }
  74. private void TranslateQueuedSubs()
  75. {
  76. while (_threadCount != 0)
  77. {
  78. if (_queue.TryDequeue(out TranslatorQueueItem item))
  79. {
  80. bool isCached = _cache.TryGetSubroutine(item.Position, out TranslatedSub sub);
  81. if (isCached && item.Tier <= sub.Tier)
  82. {
  83. continue;
  84. }
  85. if (item.Tier == TranslationTier.Tier0)
  86. {
  87. TranslateLowCq(item.Position, item.Mode);
  88. }
  89. else
  90. {
  91. TranslateHighCq(item.Position, item.Mode, item.IsComplete);
  92. }
  93. }
  94. else
  95. {
  96. _queue.WaitForItems();
  97. }
  98. }
  99. }
  100. private TranslatedSub TranslateLowCq(long position, ExecutionMode mode)
  101. {
  102. Block[] blocks = Decoder.DecodeBasicBlock(_memory, (ulong)position, mode);
  103. ILEmitterCtx context = new ILEmitterCtx(_memory, _cache, _queue, TranslationTier.Tier0);
  104. BasicBlock[] bbs = EmitAndGetBlocks(context, blocks);
  105. TranslatedSubBuilder builder = new TranslatedSubBuilder(mode);
  106. string name = GetSubroutineName(position);
  107. TranslatedSub subroutine = builder.Build(bbs, name, TranslationTier.Tier0);
  108. return _cache.GetOrAdd(position, subroutine, GetOpsCount(bbs));
  109. }
  110. private TranslatedSub TranslateHighCq(long position, ExecutionMode mode, bool isComplete)
  111. {
  112. Block[] blocks = Decoder.DecodeSubroutine(_memory, (ulong)position, mode);
  113. ILEmitterCtx context = new ILEmitterCtx(_memory, _cache, _queue, TranslationTier.Tier1);
  114. if (blocks[0].Address != (ulong)position)
  115. {
  116. context.Emit(OpCodes.Br, context.GetLabel(position));
  117. }
  118. BasicBlock[] bbs = EmitAndGetBlocks(context, blocks);
  119. isComplete &= !context.HasIndirectJump;
  120. TranslatedSubBuilder builder = new TranslatedSubBuilder(mode, isComplete);
  121. string name = GetSubroutineName(position);
  122. TranslatedSub subroutine = builder.Build(bbs, name, TranslationTier.Tier1, context.HasSlowCall);
  123. ForceAheadOfTimeCompilation(subroutine);
  124. _cache.AddOrUpdate(position, subroutine, GetOpsCount(bbs));
  125. return subroutine;
  126. }
  127. private static BasicBlock[] EmitAndGetBlocks(ILEmitterCtx context, Block[] blocks)
  128. {
  129. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  130. {
  131. Block block = blocks[blkIndex];
  132. context.CurrBlock = block;
  133. context.MarkLabel(context.GetLabel((long)block.Address));
  134. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  135. {
  136. OpCode64 opCode = block.OpCodes[opcIndex];
  137. context.CurrOp = opCode;
  138. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  139. if (isLastOp && block.Branch != null && block.Branch.Address <= block.Address)
  140. {
  141. context.EmitSynchronization();
  142. }
  143. ILLabel lblPredicateSkip = null;
  144. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  145. {
  146. lblPredicateSkip = new ILLabel();
  147. context.EmitCondBranch(lblPredicateSkip, op.Cond.Invert());
  148. }
  149. opCode.Emitter(context);
  150. if (lblPredicateSkip != null)
  151. {
  152. context.MarkLabel(lblPredicateSkip);
  153. context.ResetBlockStateForPredicatedOp();
  154. // If this is the last op on the block, and there's no "next" block
  155. // after this one, then we have to return right now, with the address
  156. // of the next instruction to be executed (in the case that the condition
  157. // is false, and the branch was not taken, as all basic blocks should end
  158. // with some kind of branch).
  159. if (isLastOp && block.Next == null)
  160. {
  161. context.EmitStoreContext();
  162. context.EmitLdc_I8(opCode.Position + opCode.OpCodeSizeInBytes);
  163. context.Emit(OpCodes.Ret);
  164. }
  165. }
  166. }
  167. }
  168. return context.GetBlocks();
  169. }
  170. private static string GetSubroutineName(long position)
  171. {
  172. return $"Sub{position:x16}";
  173. }
  174. private static int GetOpsCount(BasicBlock[] blocks)
  175. {
  176. int opCount = 0;
  177. foreach (BasicBlock block in blocks)
  178. {
  179. opCount += block.Count;
  180. }
  181. return opCount;
  182. }
  183. private void ForceAheadOfTimeCompilation(TranslatedSub subroutine)
  184. {
  185. subroutine.Execute(_dummyThreadState, null);
  186. }
  187. }
  188. }