Translator.cs 18 KB

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