Translator.cs 18 KB

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