Translator.cs 7.9 KB

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