ILEmitterCtx.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726
  1. using ChocolArm64.Decoders;
  2. using ChocolArm64.Instructions;
  3. using ChocolArm64.State;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Reflection;
  7. using System.Reflection.Emit;
  8. namespace ChocolArm64.Translation
  9. {
  10. class ILEmitterCtx
  11. {
  12. private TranslatorCache _cache;
  13. private TranslatorQueue _queue;
  14. private Dictionary<long, ILLabel> _labels;
  15. private long _subPosition;
  16. private int _opcIndex;
  17. private Block _currBlock;
  18. public Block CurrBlock => _currBlock;
  19. public OpCode64 CurrOp => _currBlock?.OpCodes[_opcIndex];
  20. public TranslationTier Tier { get; }
  21. public Aarch32Mode Mode { get; } = Aarch32Mode.User; //TODO
  22. private Dictionary<Block, ILBlock> _visitedBlocks;
  23. private Queue<Block> _branchTargets;
  24. private List<ILBlock> _ilBlocks;
  25. private ILBlock _ilBlock;
  26. private OpCode64 _optOpLastCompare;
  27. private OpCode64 _optOpLastFlagSet;
  28. //This is the index of the temporary register, used to store temporary
  29. //values needed by some functions, since IL doesn't have a swap instruction.
  30. //You can use any value here as long it doesn't conflict with the indices
  31. //for the other registers. Any value >= 64 or < 0 will do.
  32. private const int IntTmpIndex = -1;
  33. private const int RorTmpIndex = -2;
  34. private const int CmpOptTmp1Index = -3;
  35. private const int CmpOptTmp2Index = -4;
  36. private const int VecTmp1Index = -5;
  37. private const int VecTmp2Index = -6;
  38. public ILEmitterCtx(TranslatorCache cache, TranslatorQueue queue, TranslationTier tier, Block graph)
  39. {
  40. _cache = cache ?? throw new ArgumentNullException(nameof(cache));
  41. _queue = queue ?? throw new ArgumentNullException(nameof(queue));
  42. _currBlock = graph ?? throw new ArgumentNullException(nameof(graph));
  43. Tier = tier;
  44. _labels = new Dictionary<long, ILLabel>();
  45. _visitedBlocks = new Dictionary<Block, ILBlock>();
  46. _visitedBlocks.Add(graph, new ILBlock());
  47. _branchTargets = new Queue<Block>();
  48. _ilBlocks = new List<ILBlock>();
  49. _subPosition = graph.Position;
  50. ResetBlockState();
  51. AdvanceOpCode();
  52. }
  53. public ILBlock[] GetILBlocks()
  54. {
  55. EmitAllOpCodes();
  56. return _ilBlocks.ToArray();
  57. }
  58. private void EmitAllOpCodes()
  59. {
  60. do
  61. {
  62. EmitOpCode();
  63. }
  64. while (AdvanceOpCode());
  65. }
  66. private void EmitOpCode()
  67. {
  68. if (_currBlock == null)
  69. {
  70. return;
  71. }
  72. if (_opcIndex == 0)
  73. {
  74. MarkLabel(GetLabel(_currBlock.Position));
  75. EmitSynchronization();
  76. }
  77. //On AARCH32 mode, (almost) all instruction can be conditionally
  78. //executed, and the required condition is encoded on the opcode.
  79. //We handle that here, skipping the instruction if the condition
  80. //is not met. We can just ignore it when the condition is "Always",
  81. //because in this case the instruction is always going to be executed.
  82. //Condition "Never" is also ignored because this is a special encoding
  83. //used by some unconditional instructions.
  84. ILLabel lblSkip = null;
  85. if (CurrOp is OpCode32 op && op.Cond < Condition.Al)
  86. {
  87. lblSkip = new ILLabel();
  88. EmitCondBranch(lblSkip, GetInverseCond(op.Cond));
  89. }
  90. CurrOp.Emitter(this);
  91. if (lblSkip != null)
  92. {
  93. MarkLabel(lblSkip);
  94. //If this is the last op on the block, and there's no "next" block
  95. //after this one, then we have to return right now, with the address
  96. //of the next instruction to be executed (in the case that the condition
  97. //is false, and the branch was not taken, as all basic blocks should end with
  98. //some kind of branch).
  99. if (CurrOp == CurrBlock.GetLastOp() && CurrBlock.Next == null)
  100. {
  101. EmitStoreState();
  102. EmitLdc_I8(CurrOp.Position + CurrOp.OpCodeSizeInBytes);
  103. Emit(OpCodes.Ret);
  104. }
  105. }
  106. _ilBlock.Add(new ILBarrier());
  107. }
  108. private Condition GetInverseCond(Condition cond)
  109. {
  110. //Bit 0 of all conditions is basically a negation bit, so
  111. //inverting this bit has the effect of inverting the condition.
  112. return (Condition)((int)cond ^ 1);
  113. }
  114. private void EmitSynchronization()
  115. {
  116. EmitLdarg(TranslatedSub.StateArgIdx);
  117. EmitLdc_I4(_currBlock.OpCodes.Count);
  118. EmitPrivateCall(typeof(CpuThreadState), nameof(CpuThreadState.Synchronize));
  119. EmitLdc_I4(0);
  120. ILLabel lblContinue = new ILLabel();
  121. Emit(OpCodes.Bne_Un_S, lblContinue);
  122. EmitLdc_I8(0);
  123. Emit(OpCodes.Ret);
  124. MarkLabel(lblContinue);
  125. }
  126. private bool AdvanceOpCode()
  127. {
  128. if (_currBlock == null)
  129. {
  130. return false;
  131. }
  132. while (++_opcIndex >= _currBlock.OpCodes.Count)
  133. {
  134. if (!AdvanceBlock())
  135. {
  136. return false;
  137. }
  138. ResetBlockState();
  139. }
  140. return true;
  141. }
  142. private bool AdvanceBlock()
  143. {
  144. if (_currBlock.Branch != null)
  145. {
  146. if (_visitedBlocks.TryAdd(_currBlock.Branch, _ilBlock.Branch))
  147. {
  148. _branchTargets.Enqueue(_currBlock.Branch);
  149. }
  150. }
  151. if (_currBlock.Next != null)
  152. {
  153. if (_visitedBlocks.TryAdd(_currBlock.Next, _ilBlock.Next))
  154. {
  155. _currBlock = _currBlock.Next;
  156. return true;
  157. }
  158. else
  159. {
  160. Emit(OpCodes.Br, GetLabel(_currBlock.Next.Position));
  161. }
  162. }
  163. return _branchTargets.TryDequeue(out _currBlock);
  164. }
  165. private void ResetBlockState()
  166. {
  167. _ilBlock = _visitedBlocks[_currBlock];
  168. _ilBlocks.Add(_ilBlock);
  169. _ilBlock.Next = GetOrCreateILBlock(_currBlock.Next);
  170. _ilBlock.Branch = GetOrCreateILBlock(_currBlock.Branch);
  171. _opcIndex = -1;
  172. _optOpLastFlagSet = null;
  173. _optOpLastCompare = null;
  174. }
  175. private ILBlock GetOrCreateILBlock(Block block)
  176. {
  177. if (block == null)
  178. {
  179. return null;
  180. }
  181. if (_visitedBlocks.TryGetValue(block, out ILBlock ilBlock))
  182. {
  183. return ilBlock;
  184. }
  185. return new ILBlock();
  186. }
  187. public void TranslateAhead(long position, ExecutionMode mode = ExecutionMode.Aarch64)
  188. {
  189. if (_cache.TryGetSubroutine(position, out TranslatedSub sub) && sub.Tier != TranslationTier.Tier0)
  190. {
  191. return;
  192. }
  193. _queue.Enqueue(new TranslatorQueueItem(position, mode, TranslationTier.Tier1));
  194. }
  195. public bool TryOptEmitSubroutineCall()
  196. {
  197. if (_currBlock.Next == null)
  198. {
  199. return false;
  200. }
  201. if (CurrOp.Emitter != InstEmit.Bl)
  202. {
  203. return false;
  204. }
  205. if (!_cache.TryGetSubroutine(((OpCodeBImmAl64)CurrOp).Imm, out TranslatedSub subroutine))
  206. {
  207. return false;
  208. }
  209. for (int index = 0; index < TranslatedSub.FixedArgTypes.Length; index++)
  210. {
  211. EmitLdarg(index);
  212. }
  213. EmitCall(subroutine.Method);
  214. return true;
  215. }
  216. public void TryOptMarkCondWithoutCmp()
  217. {
  218. _optOpLastCompare = CurrOp;
  219. InstEmitAluHelper.EmitAluLoadOpers(this);
  220. Stloc(CmpOptTmp2Index, IoType.Int);
  221. Stloc(CmpOptTmp1Index, IoType.Int);
  222. }
  223. private Dictionary<Condition, OpCode> _branchOps = new Dictionary<Condition, OpCode>()
  224. {
  225. { Condition.Eq, OpCodes.Beq },
  226. { Condition.Ne, OpCodes.Bne_Un },
  227. { Condition.GeUn, OpCodes.Bge_Un },
  228. { Condition.LtUn, OpCodes.Blt_Un },
  229. { Condition.GtUn, OpCodes.Bgt_Un },
  230. { Condition.LeUn, OpCodes.Ble_Un },
  231. { Condition.Ge, OpCodes.Bge },
  232. { Condition.Lt, OpCodes.Blt },
  233. { Condition.Gt, OpCodes.Bgt },
  234. { Condition.Le, OpCodes.Ble }
  235. };
  236. public void EmitCondBranch(ILLabel target, Condition cond)
  237. {
  238. if (_optOpLastCompare != null &&
  239. _optOpLastCompare == _optOpLastFlagSet && _branchOps.ContainsKey(cond))
  240. {
  241. if (_optOpLastCompare.Emitter == InstEmit.Subs)
  242. {
  243. Ldloc(CmpOptTmp1Index, IoType.Int, _optOpLastCompare.RegisterSize);
  244. Ldloc(CmpOptTmp2Index, IoType.Int, _optOpLastCompare.RegisterSize);
  245. Emit(_branchOps[cond], target);
  246. return;
  247. }
  248. else if (_optOpLastCompare.Emitter == InstEmit.Adds && cond != Condition.GeUn
  249. && cond != Condition.LtUn
  250. && cond != Condition.GtUn
  251. && cond != Condition.LeUn)
  252. {
  253. //There are several limitations that needs to be taken into account for CMN comparisons:
  254. //* The unsigned comparisons are not valid, as they depend on the
  255. //carry flag value, and they will have different values for addition and
  256. //subtraction. For addition, it's carry, and for subtraction, it's borrow.
  257. //So, we need to make sure we're not doing a unsigned compare for the CMN case.
  258. //* We can only do the optimization for the immediate variants,
  259. //because when the second operand value is exactly INT_MIN, we can't
  260. //negate the value as theres no positive counterpart.
  261. //Such invalid values can't be encoded on the immediate encodings.
  262. if (_optOpLastCompare is IOpCodeAluImm64 op)
  263. {
  264. Ldloc(CmpOptTmp1Index, IoType.Int, _optOpLastCompare.RegisterSize);
  265. if (_optOpLastCompare.RegisterSize == RegisterSize.Int32)
  266. {
  267. EmitLdc_I4((int)-op.Imm);
  268. }
  269. else
  270. {
  271. EmitLdc_I8(-op.Imm);
  272. }
  273. Emit(_branchOps[cond], target);
  274. return;
  275. }
  276. }
  277. }
  278. OpCode ilOp;
  279. int intCond = (int)cond;
  280. if (intCond < 14)
  281. {
  282. int condTrue = intCond >> 1;
  283. switch (condTrue)
  284. {
  285. case 0: EmitLdflg((int)PState.ZBit); break;
  286. case 1: EmitLdflg((int)PState.CBit); break;
  287. case 2: EmitLdflg((int)PState.NBit); break;
  288. case 3: EmitLdflg((int)PState.VBit); break;
  289. case 4:
  290. EmitLdflg((int)PState.CBit);
  291. EmitLdflg((int)PState.ZBit);
  292. Emit(OpCodes.Not);
  293. Emit(OpCodes.And);
  294. break;
  295. case 5:
  296. case 6:
  297. EmitLdflg((int)PState.NBit);
  298. EmitLdflg((int)PState.VBit);
  299. Emit(OpCodes.Ceq);
  300. if (condTrue == 6)
  301. {
  302. EmitLdflg((int)PState.ZBit);
  303. Emit(OpCodes.Not);
  304. Emit(OpCodes.And);
  305. }
  306. break;
  307. }
  308. ilOp = (intCond & 1) != 0
  309. ? OpCodes.Brfalse
  310. : OpCodes.Brtrue;
  311. }
  312. else
  313. {
  314. ilOp = OpCodes.Br;
  315. }
  316. Emit(ilOp, target);
  317. }
  318. public void EmitCast(IntType intType)
  319. {
  320. switch (intType)
  321. {
  322. case IntType.UInt8: Emit(OpCodes.Conv_U1); break;
  323. case IntType.UInt16: Emit(OpCodes.Conv_U2); break;
  324. case IntType.UInt32: Emit(OpCodes.Conv_U4); break;
  325. case IntType.UInt64: Emit(OpCodes.Conv_U8); break;
  326. case IntType.Int8: Emit(OpCodes.Conv_I1); break;
  327. case IntType.Int16: Emit(OpCodes.Conv_I2); break;
  328. case IntType.Int32: Emit(OpCodes.Conv_I4); break;
  329. case IntType.Int64: Emit(OpCodes.Conv_I8); break;
  330. }
  331. bool sz64 = CurrOp.RegisterSize != RegisterSize.Int32;
  332. if (sz64 == (intType == IntType.UInt64 ||
  333. intType == IntType.Int64))
  334. {
  335. return;
  336. }
  337. if (sz64)
  338. {
  339. Emit(intType >= IntType.Int8
  340. ? OpCodes.Conv_I8
  341. : OpCodes.Conv_U8);
  342. }
  343. else
  344. {
  345. Emit(OpCodes.Conv_U4);
  346. }
  347. }
  348. public void EmitLsl(int amount) => EmitILShift(amount, OpCodes.Shl);
  349. public void EmitLsr(int amount) => EmitILShift(amount, OpCodes.Shr_Un);
  350. public void EmitAsr(int amount) => EmitILShift(amount, OpCodes.Shr);
  351. private void EmitILShift(int amount, OpCode ilOp)
  352. {
  353. if (amount > 0)
  354. {
  355. EmitLdc_I4(amount);
  356. Emit(ilOp);
  357. }
  358. }
  359. public void EmitRor(int amount)
  360. {
  361. if (amount > 0)
  362. {
  363. Stloc(RorTmpIndex, IoType.Int);
  364. Ldloc(RorTmpIndex, IoType.Int);
  365. EmitLdc_I4(amount);
  366. Emit(OpCodes.Shr_Un);
  367. Ldloc(RorTmpIndex, IoType.Int);
  368. EmitLdc_I4(CurrOp.GetBitsCount() - amount);
  369. Emit(OpCodes.Shl);
  370. Emit(OpCodes.Or);
  371. }
  372. }
  373. public ILLabel GetLabel(long position)
  374. {
  375. if (!_labels.TryGetValue(position, out ILLabel output))
  376. {
  377. output = new ILLabel();
  378. _labels.Add(position, output);
  379. }
  380. return output;
  381. }
  382. public void MarkLabel(ILLabel label)
  383. {
  384. _ilBlock.Add(label);
  385. }
  386. public void Emit(OpCode ilOp)
  387. {
  388. _ilBlock.Add(new ILOpCode(ilOp));
  389. }
  390. public void Emit(OpCode ilOp, ILLabel label)
  391. {
  392. _ilBlock.Add(new ILOpCodeBranch(ilOp, label));
  393. }
  394. public void EmitFieldLoad(FieldInfo info)
  395. {
  396. _ilBlock.Add(new ILOpCodeLoadField(info));
  397. }
  398. public void EmitPrint(string text)
  399. {
  400. _ilBlock.Add(new ILOpCodeLog(text));
  401. }
  402. public void EmitLdarg(int index)
  403. {
  404. _ilBlock.Add(new ILOpCodeLoad(index, IoType.Arg));
  405. }
  406. public void EmitLdintzr(int index)
  407. {
  408. if (index != RegisterAlias.Zr)
  409. {
  410. EmitLdint(index);
  411. }
  412. else
  413. {
  414. EmitLdc_I(0);
  415. }
  416. }
  417. public void EmitStintzr(int index)
  418. {
  419. if (index != RegisterAlias.Zr)
  420. {
  421. EmitStint(index);
  422. }
  423. else
  424. {
  425. Emit(OpCodes.Pop);
  426. }
  427. }
  428. public void EmitLoadState()
  429. {
  430. if (_ilBlock.Next == null)
  431. {
  432. throw new InvalidOperationException("Can't load state for next block, because there's no next block.");
  433. }
  434. _ilBlock.Add(new ILOpCodeLoadState(_ilBlock.Next));
  435. }
  436. public void EmitStoreState()
  437. {
  438. _ilBlock.Add(new ILOpCodeStoreState(_ilBlock));
  439. }
  440. public void EmitLdtmp() => EmitLdint(IntTmpIndex);
  441. public void EmitSttmp() => EmitStint(IntTmpIndex);
  442. public void EmitLdvectmp() => EmitLdvec(VecTmp1Index);
  443. public void EmitStvectmp() => EmitStvec(VecTmp1Index);
  444. public void EmitLdvectmp2() => EmitLdvec(VecTmp2Index);
  445. public void EmitStvectmp2() => EmitStvec(VecTmp2Index);
  446. public void EmitLdint(int index) => Ldloc(index, IoType.Int);
  447. public void EmitStint(int index) => Stloc(index, IoType.Int);
  448. public void EmitLdvec(int index) => Ldloc(index, IoType.Vector);
  449. public void EmitStvec(int index) => Stloc(index, IoType.Vector);
  450. public void EmitLdflg(int index) => Ldloc(index, IoType.Flag);
  451. public void EmitStflg(int index)
  452. {
  453. //Set this only if any of the NZCV flag bits were modified.
  454. //This is used to ensure that, when emiting a direct IL branch
  455. //instruction for compare + branch sequences, we're not expecting
  456. //to use comparison values from an old instruction, when in fact
  457. //the flags were already overwritten by another instruction further along.
  458. if (index >= (int)PState.VBit)
  459. {
  460. _optOpLastFlagSet = CurrOp;
  461. }
  462. Stloc(index, IoType.Flag);
  463. }
  464. private void Ldloc(int index, IoType ioType)
  465. {
  466. _ilBlock.Add(new ILOpCodeLoad(index, ioType, CurrOp.RegisterSize));
  467. }
  468. private void Ldloc(int index, IoType ioType, RegisterSize registerSize)
  469. {
  470. _ilBlock.Add(new ILOpCodeLoad(index, ioType, registerSize));
  471. }
  472. private void Stloc(int index, IoType ioType)
  473. {
  474. _ilBlock.Add(new ILOpCodeStore(index, ioType, CurrOp.RegisterSize));
  475. }
  476. public void EmitCallPropGet(Type objType, string propName)
  477. {
  478. if (objType == null)
  479. {
  480. throw new ArgumentNullException(nameof(objType));
  481. }
  482. if (propName == null)
  483. {
  484. throw new ArgumentNullException(nameof(propName));
  485. }
  486. EmitCall(objType.GetMethod($"get_{propName}"));
  487. }
  488. public void EmitCallPropSet(Type objType, string propName)
  489. {
  490. if (objType == null)
  491. {
  492. throw new ArgumentNullException(nameof(objType));
  493. }
  494. if (propName == null)
  495. {
  496. throw new ArgumentNullException(nameof(propName));
  497. }
  498. EmitCall(objType.GetMethod($"set_{propName}"));
  499. }
  500. public void EmitCall(Type objType, string mthdName)
  501. {
  502. if (objType == null)
  503. {
  504. throw new ArgumentNullException(nameof(objType));
  505. }
  506. if (mthdName == null)
  507. {
  508. throw new ArgumentNullException(nameof(mthdName));
  509. }
  510. EmitCall(objType.GetMethod(mthdName));
  511. }
  512. public void EmitPrivateCall(Type objType, string mthdName)
  513. {
  514. if (objType == null)
  515. {
  516. throw new ArgumentNullException(nameof(objType));
  517. }
  518. if (mthdName == null)
  519. {
  520. throw new ArgumentNullException(nameof(mthdName));
  521. }
  522. EmitCall(objType.GetMethod(mthdName, BindingFlags.Instance | BindingFlags.NonPublic));
  523. }
  524. public void EmitCall(MethodInfo mthdInfo, bool isVirtual = false)
  525. {
  526. _ilBlock.Add(new ILOpCodeCall(mthdInfo ?? throw new ArgumentNullException(nameof(mthdInfo)), isVirtual));
  527. }
  528. public void EmitLdc_I(long value)
  529. {
  530. if (CurrOp.RegisterSize == RegisterSize.Int32)
  531. {
  532. EmitLdc_I4((int)value);
  533. }
  534. else
  535. {
  536. EmitLdc_I8(value);
  537. }
  538. }
  539. public void EmitLdc_I4(int value)
  540. {
  541. _ilBlock.Add(new ILOpCodeConst(value));
  542. }
  543. public void EmitLdc_I8(long value)
  544. {
  545. _ilBlock.Add(new ILOpCodeConst(value));
  546. }
  547. public void EmitLdc_R4(float value)
  548. {
  549. _ilBlock.Add(new ILOpCodeConst(value));
  550. }
  551. public void EmitLdc_R8(double value)
  552. {
  553. _ilBlock.Add(new ILOpCodeConst(value));
  554. }
  555. public void EmitZnFlagCheck()
  556. {
  557. EmitZnCheck(OpCodes.Ceq, (int)PState.ZBit);
  558. EmitZnCheck(OpCodes.Clt, (int)PState.NBit);
  559. }
  560. private void EmitZnCheck(OpCode ilCmpOp, int flag)
  561. {
  562. Emit(OpCodes.Dup);
  563. Emit(OpCodes.Ldc_I4_0);
  564. if (CurrOp.RegisterSize != RegisterSize.Int32)
  565. {
  566. Emit(OpCodes.Conv_I8);
  567. }
  568. Emit(ilCmpOp);
  569. EmitStflg(flag);
  570. }
  571. }
  572. }