Translator.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567
  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 TranslatorCache<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 TranslatorCache<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.GuestSize, 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. private 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. public ulong Step(State.ExecutionContext context, ulong address)
  171. {
  172. TranslatedFunction func = Translate(address, context.ExecutionMode, highCq: false, singleStep: true);
  173. address = func.Execute(context);
  174. EnqueueForDeletion(address, func);
  175. return address;
  176. }
  177. internal TranslatedFunction GetOrTranslate(ulong address, ExecutionMode mode)
  178. {
  179. if (!Functions.TryGetValue(address, out TranslatedFunction func))
  180. {
  181. func = Translate(address, mode, highCq: false);
  182. TranslatedFunction oldFunc = Functions.GetOrAdd(address, func.GuestSize, func);
  183. if (oldFunc != func)
  184. {
  185. JitCache.Unmap(func.FuncPtr);
  186. func = oldFunc;
  187. }
  188. if (PtcProfiler.Enabled)
  189. {
  190. PtcProfiler.AddEntry(address, mode, highCq: false);
  191. }
  192. RegisterFunction(address, func);
  193. }
  194. return func;
  195. }
  196. internal void RegisterFunction(ulong guestAddress, TranslatedFunction func)
  197. {
  198. if (FunctionTable.IsValid(guestAddress) && (Optimizations.AllowLcqInFunctionTable || func.HighCq))
  199. {
  200. Volatile.Write(ref FunctionTable.GetValue(guestAddress), (ulong)func.FuncPtr);
  201. }
  202. }
  203. internal TranslatedFunction Translate(ulong address, ExecutionMode mode, bool highCq, bool singleStep = false)
  204. {
  205. var context = new ArmEmitterContext(
  206. Memory,
  207. CountTable,
  208. FunctionTable,
  209. Stubs,
  210. address,
  211. highCq,
  212. mode: Aarch32Mode.User);
  213. Logger.StartPass(PassName.Decoding);
  214. Block[] blocks = Decoder.Decode(Memory, address, mode, highCq, singleStep ? DecoderMode.SingleInstruction : DecoderMode.MultipleBlocks);
  215. Logger.EndPass(PassName.Decoding);
  216. Logger.StartPass(PassName.Translation);
  217. EmitSynchronization(context);
  218. if (blocks[0].Address != address)
  219. {
  220. context.Branch(context.GetLabel(address));
  221. }
  222. ControlFlowGraph cfg = EmitAndGetCFG(context, blocks, out Range funcRange, out Counter<uint> counter);
  223. ulong funcSize = funcRange.End - funcRange.Start;
  224. Logger.EndPass(PassName.Translation, cfg);
  225. Logger.StartPass(PassName.RegisterUsage);
  226. RegisterUsage.RunPass(cfg, mode);
  227. Logger.EndPass(PassName.RegisterUsage);
  228. var retType = OperandType.I64;
  229. var argTypes = new OperandType[] { OperandType.I64 };
  230. var options = highCq ? CompilerOptions.HighCq : CompilerOptions.None;
  231. if (context.HasPtc && !singleStep)
  232. {
  233. options |= CompilerOptions.Relocatable;
  234. }
  235. CompiledFunction compiledFunc = Compiler.Compile(cfg, argTypes, retType, options);
  236. if (context.HasPtc && !singleStep)
  237. {
  238. Hash128 hash = Ptc.ComputeHash(Memory, address, funcSize);
  239. Ptc.WriteCompiledFunction(address, funcSize, hash, highCq, compiledFunc);
  240. }
  241. GuestFunction func = compiledFunc.Map<GuestFunction>();
  242. Allocators.ResetAll();
  243. return new TranslatedFunction(func, counter, funcSize, highCq);
  244. }
  245. private struct Range
  246. {
  247. public ulong Start { get; }
  248. public ulong End { get; }
  249. public Range(ulong start, ulong end)
  250. {
  251. Start = start;
  252. End = end;
  253. }
  254. }
  255. private static ControlFlowGraph EmitAndGetCFG(
  256. ArmEmitterContext context,
  257. Block[] blocks,
  258. out Range range,
  259. out Counter<uint> counter)
  260. {
  261. counter = null;
  262. ulong rangeStart = ulong.MaxValue;
  263. ulong rangeEnd = 0;
  264. for (int blkIndex = 0; blkIndex < blocks.Length; blkIndex++)
  265. {
  266. Block block = blocks[blkIndex];
  267. if (!block.Exit)
  268. {
  269. if (rangeStart > block.Address)
  270. {
  271. rangeStart = block.Address;
  272. }
  273. if (rangeEnd < block.EndAddress)
  274. {
  275. rangeEnd = block.EndAddress;
  276. }
  277. }
  278. if (block.Address == context.EntryAddress && !context.HighCq)
  279. {
  280. EmitRejitCheck(context, out counter);
  281. }
  282. context.CurrBlock = block;
  283. context.MarkLabel(context.GetLabel(block.Address));
  284. if (block.Exit)
  285. {
  286. // Left option here as it may be useful if we need to return to managed rather than tail call in
  287. // future. (eg. for debug)
  288. bool useReturns = false;
  289. InstEmitFlowHelper.EmitVirtualJump(context, Const(block.Address), isReturn: useReturns);
  290. }
  291. else
  292. {
  293. for (int opcIndex = 0; opcIndex < block.OpCodes.Count; opcIndex++)
  294. {
  295. OpCode opCode = block.OpCodes[opcIndex];
  296. context.CurrOp = opCode;
  297. bool isLastOp = opcIndex == block.OpCodes.Count - 1;
  298. if (isLastOp && block.Branch != null && !block.Branch.Exit && block.Branch.Address <= block.Address)
  299. {
  300. EmitSynchronization(context);
  301. }
  302. Operand lblPredicateSkip = default;
  303. if (context.IsInIfThenBlock && context.CurrentIfThenBlockCond != Condition.Al)
  304. {
  305. lblPredicateSkip = Label();
  306. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, context.CurrentIfThenBlockCond.Invert());
  307. }
  308. if (opCode is OpCode32 op && op.Cond < Condition.Al)
  309. {
  310. lblPredicateSkip = Label();
  311. InstEmitFlowHelper.EmitCondBranch(context, lblPredicateSkip, op.Cond.Invert());
  312. }
  313. if (opCode.Instruction.Emitter != null)
  314. {
  315. opCode.Instruction.Emitter(context);
  316. }
  317. else
  318. {
  319. throw new InvalidOperationException($"Invalid instruction \"{opCode.Instruction.Name}\".");
  320. }
  321. if (lblPredicateSkip != default)
  322. {
  323. context.MarkLabel(lblPredicateSkip);
  324. }
  325. if (context.IsInIfThenBlock && opCode.Instruction.Name != InstName.It)
  326. {
  327. context.AdvanceIfThenBlockState();
  328. }
  329. }
  330. }
  331. }
  332. range = new Range(rangeStart, rangeEnd);
  333. return context.GetControlFlowGraph();
  334. }
  335. internal static void EmitRejitCheck(ArmEmitterContext context, out Counter<uint> counter)
  336. {
  337. const int MinsCallForRejit = 100;
  338. counter = new Counter<uint>(context.CountTable);
  339. Operand lblEnd = Label();
  340. Operand address = !context.HasPtc ?
  341. Const(ref counter.Value) :
  342. Const(ref counter.Value, Ptc.CountTableSymbol);
  343. Operand curCount = context.Load(OperandType.I32, address);
  344. Operand count = context.Add(curCount, Const(1));
  345. context.Store(address, count);
  346. context.BranchIf(lblEnd, curCount, Const(MinsCallForRejit), Comparison.NotEqual, BasicBlockFrequency.Cold);
  347. context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.EnqueueForRejit)), Const(context.EntryAddress));
  348. context.MarkLabel(lblEnd);
  349. }
  350. internal static void EmitSynchronization(EmitterContext context)
  351. {
  352. long countOffs = NativeContext.GetCounterOffset();
  353. Operand lblNonZero = Label();
  354. Operand lblExit = Label();
  355. Operand countAddr = context.Add(context.LoadArgument(OperandType.I64, 0), Const(countOffs));
  356. Operand count = context.Load(OperandType.I32, countAddr);
  357. context.BranchIfTrue(lblNonZero, count, BasicBlockFrequency.Cold);
  358. Operand running = context.Call(typeof(NativeInterface).GetMethod(nameof(NativeInterface.CheckSynchronization)));
  359. context.BranchIfTrue(lblExit, running, BasicBlockFrequency.Cold);
  360. context.Return(Const(0L));
  361. context.MarkLabel(lblNonZero);
  362. count = context.Subtract(count, Const(1));
  363. context.Store(countAddr, count);
  364. context.MarkLabel(lblExit);
  365. }
  366. public void InvalidateJitCacheRegion(ulong address, ulong size)
  367. {
  368. // If rejit is running, stop it as it may be trying to rejit a function on the invalidated region.
  369. ClearRejitQueue(allowRequeue: true);
  370. ulong[] overlapAddresses = Array.Empty<ulong>();
  371. int overlapsCount = Functions.GetOverlaps(address, size, ref overlapAddresses);
  372. for (int index = 0; index < overlapsCount; index++)
  373. {
  374. ulong overlapAddress = overlapAddresses[index];
  375. if (Functions.TryGetValue(overlapAddress, out TranslatedFunction overlap))
  376. {
  377. Functions.Remove(overlapAddress);
  378. Volatile.Write(ref FunctionTable.GetValue(overlapAddress), FunctionTable.Fill);
  379. EnqueueForDeletion(overlapAddress, overlap);
  380. }
  381. }
  382. // TODO: Remove overlapping functions from the JitCache aswell.
  383. // This should be done safely, with a mechanism to ensure the function is not being executed.
  384. }
  385. internal void EnqueueForRejit(ulong guestAddress, ExecutionMode mode)
  386. {
  387. if (_backgroundSet.TryAdd(guestAddress, null))
  388. {
  389. _backgroundStack.Push(new RejitRequest(guestAddress, mode));
  390. _backgroundTranslatorEvent.Set();
  391. }
  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. _backgroundTranslatorLock.AcquireWriterLock(Timeout.Infinite);
  417. if (allowRequeue)
  418. {
  419. while (_backgroundStack.TryPop(out var request))
  420. {
  421. if (Functions.TryGetValue(request.Address, out var func) && func.CallCounter != null)
  422. {
  423. Volatile.Write(ref func.CallCounter.Value, 0);
  424. }
  425. _backgroundSet.TryRemove(request.Address, out _);
  426. }
  427. }
  428. else
  429. {
  430. _backgroundStack.Clear();
  431. }
  432. _backgroundTranslatorLock.ReleaseWriterLock();
  433. }
  434. }
  435. }