Translator.cs 18 KB

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