Translator.cs 17 KB

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