Translator.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 ARMeilleure.Translation.Cache;
  8. using ARMeilleure.Translation.PTC;
  9. using System;
  10. using System.Collections.Concurrent;
  11. using System.Collections.Generic;
  12. using System.Diagnostics;
  13. using System.Linq;
  14. using System.Threading;
  15. using static ARMeilleure.IntermediateRepresentation.OperandHelper;
  16. using static ARMeilleure.IntermediateRepresentation.OperationHelper;
  17. namespace ARMeilleure.Translation
  18. {
  19. public class Translator
  20. {
  21. private readonly IJitMemoryAllocator _allocator;
  22. private readonly IMemoryManager _memory;
  23. private readonly ConcurrentDictionary<ulong, TranslatedFunction> _funcs;
  24. private readonly ConcurrentQueue<KeyValuePair<ulong, IntPtr>> _oldFuncs;
  25. private readonly ConcurrentStack<RejitRequest> _backgroundStack;
  26. private readonly AutoResetEvent _backgroundTranslatorEvent;
  27. private readonly ReaderWriterLock _backgroundTranslatorLock;
  28. private JumpTable _jumpTable;
  29. private volatile int _threadCount;
  30. // FIXME: Remove this once the init logic of the emulator will be redone
  31. public static ManualResetEvent IsReadyForTranslation = new ManualResetEvent(false);
  32. public Translator(IJitMemoryAllocator allocator, IMemoryManager memory)
  33. {
  34. _allocator = allocator;
  35. _memory = memory;
  36. _funcs = new ConcurrentDictionary<ulong, TranslatedFunction>();
  37. _oldFuncs = new ConcurrentQueue<KeyValuePair<ulong, IntPtr>>();
  38. _backgroundStack = new ConcurrentStack<RejitRequest>();
  39. _backgroundTranslatorEvent = new AutoResetEvent(false);
  40. _backgroundTranslatorLock = new ReaderWriterLock();
  41. JitCache.Initialize(allocator);
  42. DirectCallStubs.InitializeStubs();
  43. }
  44. private void TranslateStackedSubs()
  45. {
  46. while (_threadCount != 0)
  47. {
  48. _backgroundTranslatorLock.AcquireReaderLock(Timeout.Infinite);
  49. if (_backgroundStack.TryPop(out RejitRequest request))
  50. {
  51. TranslatedFunction func = Translate(_memory, _jumpTable, request.Address, request.Mode, highCq: true);
  52. _funcs.AddOrUpdate(request.Address, func, (key, oldFunc) =>
  53. {
  54. EnqueueForDeletion(key, oldFunc);
  55. return func;
  56. });
  57. _jumpTable.RegisterFunction(request.Address, func);
  58. if (PtcProfiler.Enabled)
  59. {
  60. PtcProfiler.UpdateEntry(request.Address, request.Mode, highCq: true);
  61. }
  62. _backgroundTranslatorLock.ReleaseReaderLock();
  63. }
  64. else
  65. {
  66. _backgroundTranslatorLock.ReleaseReaderLock();
  67. _backgroundTranslatorEvent.WaitOne();
  68. }
  69. }
  70. _backgroundTranslatorEvent.Set(); // Wake up any other background translator threads, to encourage them to exit.
  71. }
  72. public void Execute(State.ExecutionContext context, ulong address)
  73. {
  74. if (Interlocked.Increment(ref _threadCount) == 1)
  75. {
  76. IsReadyForTranslation.WaitOne();
  77. Debug.Assert(_jumpTable == null);
  78. _jumpTable = new JumpTable(_allocator);
  79. if (Ptc.State == PtcState.Enabled)
  80. {
  81. Ptc.LoadTranslations(_funcs, _memory.PageTablePointer, _jumpTable);
  82. Ptc.MakeAndSaveTranslations(_funcs, _memory, _jumpTable);
  83. }
  84. PtcProfiler.Start();
  85. Ptc.Disable();
  86. // Simple heuristic, should be user configurable in future. (1 for 4 core/ht or less, 2 for 6 core+ht etc).
  87. // All threads are normal priority except from the last, which just fills as much of the last core as the os lets it with a low priority.
  88. // If we only have one rejit thread, it should be normal priority as highCq code is performance critical.
  89. // TODO: Use physical cores rather than logical. This only really makes sense for processors with hyperthreading. Requires OS specific code.
  90. int unboundedThreadCount = Math.Max(1, (Environment.ProcessorCount - 6) / 3);
  91. int threadCount = Math.Min(4, unboundedThreadCount);
  92. for (int i = 0; i < threadCount; i++)
  93. {
  94. bool last = i != 0 && i == unboundedThreadCount - 1;
  95. Thread backgroundTranslatorThread = new Thread(TranslateStackedSubs)
  96. {
  97. Name = "CPU.BackgroundTranslatorThread." + i,
  98. Priority = last ? ThreadPriority.Lowest : ThreadPriority.Normal
  99. };
  100. backgroundTranslatorThread.Start();
  101. }
  102. }
  103. Statistics.InitializeTimer();
  104. NativeInterface.RegisterThread(context, _memory, this);
  105. do
  106. {
  107. address = ExecuteSingle(context, address);
  108. }
  109. while (context.Running && address != 0);
  110. NativeInterface.UnregisterThread();
  111. if (Interlocked.Decrement(ref _threadCount) == 0)
  112. {
  113. _backgroundTranslatorEvent.Set();
  114. ClearJitCache();
  115. _jumpTable.Dispose();
  116. _jumpTable = null;
  117. }
  118. }
  119. public ulong ExecuteSingle(State.ExecutionContext context, ulong address)
  120. {
  121. TranslatedFunction func = GetOrTranslate(address, context.ExecutionMode);
  122. Statistics.StartTimer();
  123. ulong nextAddr = func.Execute(context);
  124. Statistics.StopTimer(address);
  125. return nextAddr;
  126. }
  127. internal TranslatedFunction GetOrTranslate(ulong address, ExecutionMode mode, bool hintRejit = false)
  128. {
  129. if (!_funcs.TryGetValue(address, out TranslatedFunction func))
  130. {
  131. func = Translate(_memory, _jumpTable, address, mode, highCq: false);
  132. TranslatedFunction getFunc = _funcs.GetOrAdd(address, func);
  133. if (getFunc != func)
  134. {
  135. JitCache.Unmap(func.FuncPtr);
  136. func = getFunc;
  137. }
  138. if (PtcProfiler.Enabled)
  139. {
  140. PtcProfiler.AddEntry(address, mode, highCq: false);
  141. }
  142. }
  143. if (hintRejit && func.ShouldRejit())
  144. {
  145. _backgroundStack.Push(new RejitRequest(address, mode));
  146. _backgroundTranslatorEvent.Set();
  147. }
  148. return func;
  149. }
  150. internal static TranslatedFunction Translate(IMemoryManager memory, JumpTable jumpTable, ulong address, ExecutionMode mode, bool highCq)
  151. {
  152. ArmEmitterContext context = new ArmEmitterContext(memory, jumpTable, address, highCq, Aarch32Mode.User);
  153. PrepareOperandPool(highCq);
  154. PrepareOperationPool(highCq);
  155. Logger.StartPass(PassName.Decoding);
  156. Block[] blocks = Decoder.Decode(memory, address, mode, highCq, singleBlock: false);
  157. Logger.EndPass(PassName.Decoding);
  158. Logger.StartPass(PassName.Translation);
  159. EmitSynchronization(context);
  160. if (blocks[0].Address != address)
  161. {
  162. context.Branch(context.GetLabel(address));
  163. }
  164. ControlFlowGraph cfg = EmitAndGetCFG(context, blocks, out Range funcRange);
  165. ulong funcSize = funcRange.End - funcRange.Start;
  166. Logger.EndPass(PassName.Translation);
  167. Logger.StartPass(PassName.RegisterUsage);
  168. RegisterUsage.RunPass(cfg, mode);
  169. Logger.EndPass(PassName.RegisterUsage);
  170. OperandType[] argTypes = new OperandType[] { OperandType.I64 };
  171. CompilerOptions options = highCq ? CompilerOptions.HighCq : CompilerOptions.None;
  172. GuestFunction func;
  173. if (Ptc.State == PtcState.Disabled)
  174. {
  175. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options);
  176. }
  177. else
  178. {
  179. using (PtcInfo ptcInfo = new PtcInfo())
  180. {
  181. func = Compiler.Compile<GuestFunction>(cfg, argTypes, OperandType.I64, options, ptcInfo);
  182. Ptc.WriteInfoCodeReloc(address, funcSize, highCq, ptcInfo);
  183. }
  184. }
  185. ResetOperandPool(highCq);
  186. ResetOperationPool(highCq);
  187. return new TranslatedFunction(func, funcSize, highCq);
  188. }
  189. private struct Range
  190. {
  191. public ulong Start { get; }
  192. public ulong End { get; }
  193. public Range(ulong start, ulong end)
  194. {
  195. Start = start;
  196. End = end;
  197. }
  198. }
  199. private static ControlFlowGraph EmitAndGetCFG(ArmEmitterContext context, Block[] blocks, out Range range)
  200. {
  201. ulong rangeStart = ulong.MaxValue;
  202. ulong rangeEnd = 0;
  203. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  204. {
  205. Block block = blocks[blkIndex];
  206. if (!block.Exit)
  207. {
  208. if (rangeStart > block.Address)
  209. {
  210. rangeStart = block.Address;
  211. }
  212. if (rangeEnd < block.EndAddress)
  213. {
  214. rangeEnd = block.EndAddress;
  215. }
  216. }
  217. context.CurrBlock = block;
  218. context.MarkLabel(context.GetLabel(block.Address));
  219. if (block.Exit)
  220. {
  221. InstEmitFlowHelper.EmitTailContinue(context, Const(block.Address), block.TailCall);
  222. }
  223. else
  224. {
  225. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  226. {
  227. OpCode opCode = block.OpCodes[opcIndex];
  228. context.CurrOp = opCode;
  229. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  230. if (isLastOp && block.Branch != null && !block.Branch.Exit && block.Branch.Address <= block.Address)
  231. {
  232. EmitSynchronization(context);
  233. }
  234. Operand lblPredicateSkip = null;
  235. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  236. {
  237. lblPredicateSkip = Label();
  238. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
  239. }
  240. if (opCode.Instruction.Emitter != null)
  241. {
  242. opCode.Instruction.Emitter(context);
  243. }
  244. else
  245. {
  246. throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
  247. }
  248. if (lblPredicateSkip != null)
  249. {
  250. context.MarkLabel(lblPredicateSkip);
  251. }
  252. }
  253. }
  254. }
  255. range = new Range(rangeStart, rangeEnd);
  256. return context.GetControlFlowGraph();
  257. }
  258. internal static void EmitSynchronization(EmitterContext context)
  259. {
  260. long countOffs = NativeContext.GetCounterOffset();
  261. Operand countAddr = context.Add(context.LoadArgument(OperandType.I64, 0), Const(countOffs));
  262. Operand count = context.Load(OperandType.I32, countAddr);
  263. Operand lblNonZero = Label();
  264. Operand lblExit = Label();
  265. context.BranchIfTrue(lblNonZero, count, BasicBlockFrequency.Cold);
  266. Operand running = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.CheckSynchronization)));
  267. context.BranchIfTrue(lblExit, running, BasicBlockFrequency.Cold);
  268. context.Return(Const(0L));
  269. context.MarkLabel(lblNonZero);
  270. count = context.Subtract(count, Const(1));
  271. context.Store(countAddr, count);
  272. context.MarkLabel(lblExit);
  273. }
  274. public void InvalidateJitCacheRegion(ulong address, ulong size)
  275. {
  276. static bool OverlapsWith(ulong funcAddress, ulong funcSize, ulong address, ulong size)
  277. {
  278. return funcAddress < address + size && address < funcAddress + funcSize;
  279. }
  280. // Make a copy of all overlapping functions, as we can't otherwise
  281. // remove elements from the collection we are iterating.
  282. // Doing that before clearing the rejit queue is fine, even
  283. // if a function is translated after this, it would only replace
  284. // a existing function, as rejit is only triggered on functions
  285. // that were already executed before.
  286. var toDelete = _funcs.Where(x => OverlapsWith(x.Key, x.Value.GuestSize, address, size)).ToArray();
  287. if (toDelete.Length != 0)
  288. {
  289. // If rejit is running, stop it as it may be trying to rejit the functions we are
  290. // supposed to remove.
  291. ClearRejitQueue();
  292. }
  293. foreach (var kv in toDelete)
  294. {
  295. if (_funcs.TryRemove(kv.Key, out TranslatedFunction func))
  296. {
  297. EnqueueForDeletion(kv.Key, func);
  298. }
  299. }
  300. }
  301. private void EnqueueForDeletion(ulong guestAddress, TranslatedFunction func)
  302. {
  303. _oldFuncs.Enqueue(new KeyValuePair<ulong, IntPtr>(guestAddress, func.FuncPtr));
  304. }
  305. private void ClearJitCache()
  306. {
  307. // Ensure no attempt will be made to compile new functions due to rejit.
  308. ClearRejitQueue();
  309. foreach (var kv in _funcs)
  310. {
  311. JitCache.Unmap(kv.Value.FuncPtr);
  312. }
  313. _funcs.Clear();
  314. while (_oldFuncs.TryDequeue(out var kv))
  315. {
  316. JitCache.Unmap(kv.Value);
  317. }
  318. }
  319. private void ClearRejitQueue()
  320. {
  321. _backgroundTranslatorLock.AcquireWriterLock(Timeout.Infinite);
  322. _backgroundStack.Clear();
  323. _backgroundTranslatorLock.ReleaseWriterLock();
  324. }
  325. }
  326. }