Translator.cs 15 KB

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