Translator.cs 19 KB

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