Translator.cs 19 KB

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