Translator.cs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  1. using ARMeilleure.Decoders;
  2. using ARMeilleure.Diagnostics;
  3. using ARMeilleure.Instructions;
  4. using ARMeilleure.IntermediateRepresentation;
  5. using ARMeilleure.Memory;
  6. using ARMeilleure.State;
  7. using System;
  8. using System.Collections.Concurrent;
  9. using System.Threading;
  10. using static ARMeilleure.IntermediateRepresentation.OperandHelper;
  11. namespace ARMeilleure.Translation
  12. {
  13. public class Translator
  14. {
  15. private const ulong CallFlag = InstEmitFlowHelper.CallFlag;
  16. private MemoryManager _memory;
  17. private ConcurrentDictionary<ulong, TranslatedFunction> _funcs;
  18. private PriorityQueue<ulong> _backgroundQueue;
  19. private AutoResetEvent _backgroundTranslatorEvent;
  20. private volatile int _threadCount;
  21. public Translator(MemoryManager memory)
  22. {
  23. _memory = memory;
  24. _funcs = new ConcurrentDictionary<ulong, TranslatedFunction>();
  25. _backgroundQueue = new PriorityQueue<ulong>(2);
  26. _backgroundTranslatorEvent = new AutoResetEvent(false);
  27. }
  28. private void TranslateQueuedSubs()
  29. {
  30. while (_threadCount != 0)
  31. {
  32. if (_backgroundQueue.TryDequeue(out ulong address))
  33. {
  34. TranslatedFunction func = Translate(address, ExecutionMode.Aarch64, highCq: true);
  35. _funcs.AddOrUpdate(address, func, (key, oldFunc) => func);
  36. }
  37. else
  38. {
  39. _backgroundTranslatorEvent.WaitOne();
  40. }
  41. }
  42. }
  43. public void Execute(State.ExecutionContext context, ulong address)
  44. {
  45. if (Interlocked.Increment(ref _threadCount) == 1)
  46. {
  47. Thread backgroundTranslatorThread = new Thread(TranslateQueuedSubs)
  48. {
  49. Name = "CPU.BackgroundTranslatorThread",
  50. Priority = ThreadPriority.Lowest
  51. };
  52. backgroundTranslatorThread.Start();
  53. }
  54. Statistics.InitializeTimer();
  55. NativeInterface.RegisterThread(context, _memory);
  56. do
  57. {
  58. address = ExecuteSingle(context, address);
  59. }
  60. while (context.Running && (address & ~1UL) != 0);
  61. NativeInterface.UnregisterThread();
  62. if (Interlocked.Decrement(ref _threadCount) == 0)
  63. {
  64. _backgroundTranslatorEvent.Set();
  65. }
  66. }
  67. public ulong ExecuteSingle(State.ExecutionContext context, ulong address)
  68. {
  69. TranslatedFunction func = GetOrTranslate(address, context.ExecutionMode);
  70. Statistics.StartTimer();
  71. ulong nextAddr = func.Execute(context);
  72. Statistics.StopTimer(address);
  73. return nextAddr;
  74. }
  75. private TranslatedFunction GetOrTranslate(ulong address, ExecutionMode mode)
  76. {
  77. // TODO: Investigate how we should handle code at unaligned addresses.
  78. // Currently, those low bits are used to store special flags.
  79. bool isCallTarget = (address & CallFlag) != 0;
  80. address &= ~CallFlag;
  81. if (!_funcs.TryGetValue(address, out TranslatedFunction func))
  82. {
  83. func = Translate(address, mode, highCq: false);
  84. _funcs.TryAdd(address, func);
  85. }
  86. else if (isCallTarget && func.ShouldRejit())
  87. {
  88. _backgroundQueue.Enqueue(0, address);
  89. _backgroundTranslatorEvent.Set();
  90. }
  91. return func;
  92. }
  93. private TranslatedFunction Translate(ulong address, ExecutionMode mode, bool highCq)
  94. {
  95. ArmEmitterContext context = new ArmEmitterContext(_memory, Aarch32Mode.User);
  96. Logger.StartPass(PassName.Decoding);
  97. Block[] blocks = highCq
  98. ? Decoder.DecodeFunction (_memory, address, mode)
  99. : Decoder.DecodeBasicBlock(_memory, address, mode);
  100. Logger.EndPass(PassName.Decoding);
  101. Logger.StartPass(PassName.Translation);
  102. EmitSynchronization(context);
  103. if (blocks[0].Address != address)
  104. {
  105. context.Branch(context.GetLabel(address));
  106. }
  107. ControlFlowGraph cfg = EmitAndGetCFG(context, blocks);
  108. Logger.EndPass(PassName.Translation);
  109. Logger.StartPass(PassName.RegisterUsage);
  110. RegisterUsage.RunPass(cfg, isCompleteFunction: false);
  111. Logger.EndPass(PassName.RegisterUsage);
  112. OperandType[] argTypes = new OperandType[] { OperandType.I64 };
  113. CompilerOptions options = highCq
  114. ? CompilerOptions.HighCq
  115. : CompilerOptions.None;
  116. GuestFunction func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options);
  117. return new TranslatedFunction(func, rejit: !highCq);
  118. }
  119. private static ControlFlowGraph EmitAndGetCFG(ArmEmitterContext context, Block[] blocks)
  120. {
  121. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  122. {
  123. Block block = blocks[blkIndex];
  124. context.CurrBlock = block;
  125. context.MarkLabel(context.GetLabel(block.Address));
  126. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  127. {
  128. OpCode opCode = block.OpCodes[opcIndex];
  129. context.CurrOp = opCode;
  130. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  131. if (isLastOp && block.Branch != null && block.Branch.Address <= block.Address)
  132. {
  133. EmitSynchronization(context);
  134. }
  135. Operand lblPredicateSkip = null;
  136. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  137. {
  138. lblPredicateSkip = Label();
  139. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
  140. }
  141. if (opCode.Instruction.Emitter != null)
  142. {
  143. opCode.Instruction.Emitter(context);
  144. }
  145. else
  146. {
  147. throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
  148. }
  149. if (lblPredicateSkip != null)
  150. {
  151. context.MarkLabel(lblPredicateSkip);
  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.Return(Const(opCode.Address + (ulong)opCode.OpCodeSizeInBytes));
  160. }
  161. }
  162. }
  163. }
  164. return context.GetControlFlowGraph();
  165. }
  166. private static void EmitSynchronization(EmitterContext context)
  167. {
  168. long countOffs = NativeContext.GetCounterOffset();
  169. Operand countAddr = context.Add(context.LoadArgument(OperandType.I64, 0), Const(countOffs));
  170. Operand count = context.Load(OperandType.I32, countAddr);
  171. Operand lblNonZero = Label();
  172. Operand lblExit = Label();
  173. context.BranchIfTrue(lblNonZero, count);
  174. context.Call(new _Void(NativeInterface.CheckSynchronization));
  175. context.Branch(lblExit);
  176. context.MarkLabel(lblNonZero);
  177. count = context.Subtract(count, Const(1));
  178. context.Store(countAddr, count);
  179. context.MarkLabel(lblExit);
  180. }
  181. }
  182. }