Decoder.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. using ARMeilleure.Decoders.Optimizations;
  2. using ARMeilleure.Instructions;
  3. using ARMeilleure.Memory;
  4. using ARMeilleure.State;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Diagnostics;
  8. namespace ARMeilleure.Decoders
  9. {
  10. static class Decoder
  11. {
  12. // We define a limit on the number of instructions that a function may have,
  13. // this prevents functions being potentially too large, which would
  14. // take too long to compile and use too much memory.
  15. private const int MaxInstsPerFunction = 2500;
  16. // For lower code quality translation, we set a lower limit since we're blocking execution.
  17. private const int MaxInstsPerFunctionLowCq = 500;
  18. public static Block[] Decode(IMemoryManager memory, ulong address, ExecutionMode mode, bool highCq, DecoderMode dMode)
  19. {
  20. List<Block> blocks = new List<Block>();
  21. Queue<Block> workQueue = new Queue<Block>();
  22. Dictionary<ulong, Block> visited = new Dictionary<ulong, Block>();
  23. Debug.Assert(MaxInstsPerFunctionLowCq <= MaxInstsPerFunction);
  24. int opsCount = 0;
  25. int instructionLimit = highCq ? MaxInstsPerFunction : MaxInstsPerFunctionLowCq;
  26. Block GetBlock(ulong blkAddress)
  27. {
  28. if (!visited.TryGetValue(blkAddress, out Block block))
  29. {
  30. block = new Block(blkAddress);
  31. if ((dMode != DecoderMode.MultipleBlocks && visited.Count >= 1) || opsCount > instructionLimit || !memory.IsMapped(blkAddress))
  32. {
  33. block.Exit = true;
  34. block.EndAddress = blkAddress;
  35. }
  36. workQueue.Enqueue(block);
  37. visited.Add(blkAddress, block);
  38. }
  39. return block;
  40. }
  41. GetBlock(address);
  42. while (workQueue.TryDequeue(out Block currBlock))
  43. {
  44. // Check if the current block is inside another block.
  45. if (BinarySearch(blocks, currBlock.Address, out int nBlkIndex))
  46. {
  47. Block nBlock = blocks[nBlkIndex];
  48. if (nBlock.Address == currBlock.Address)
  49. {
  50. throw new InvalidOperationException("Found duplicate block address on the list.");
  51. }
  52. currBlock.Exit = false;
  53. nBlock.Split(currBlock);
  54. blocks.Insert(nBlkIndex + 1, currBlock);
  55. continue;
  56. }
  57. if (!currBlock.Exit)
  58. {
  59. // If we have a block after the current one, set the limit address.
  60. ulong limitAddress = ulong.MaxValue;
  61. if (nBlkIndex != blocks.Count)
  62. {
  63. Block nBlock = blocks[nBlkIndex];
  64. int nextIndex = nBlkIndex + 1;
  65. if (nBlock.Address < currBlock.Address && nextIndex < blocks.Count)
  66. {
  67. limitAddress = blocks[nextIndex].Address;
  68. }
  69. else if (nBlock.Address > currBlock.Address)
  70. {
  71. limitAddress = blocks[nBlkIndex].Address;
  72. }
  73. }
  74. if (dMode == DecoderMode.SingleInstruction)
  75. {
  76. // Only read at most one instruction
  77. limitAddress = currBlock.Address + 1;
  78. }
  79. FillBlock(memory, mode, currBlock, limitAddress);
  80. opsCount += currBlock.OpCodes.Count;
  81. if (currBlock.OpCodes.Count != 0)
  82. {
  83. // Set child blocks. "Branch" is the block the branch instruction
  84. // points to (when taken), "Next" is the block at the next address,
  85. // executed when the branch is not taken. For Unconditional Branches
  86. // (except BL/BLR that are sub calls) or end of executable, Next is null.
  87. OpCode lastOp = currBlock.GetLastOp();
  88. bool isCall = IsCall(lastOp);
  89. if (lastOp is IOpCodeBImm op && !isCall)
  90. {
  91. currBlock.Branch = GetBlock((ulong)op.Immediate);
  92. }
  93. if (!IsUnconditionalBranch(lastOp) || isCall)
  94. {
  95. currBlock.Next = GetBlock(currBlock.EndAddress);
  96. }
  97. }
  98. }
  99. // Insert the new block on the list (sorted by address).
  100. if (blocks.Count != 0)
  101. {
  102. Block nBlock = blocks[nBlkIndex];
  103. blocks.Insert(nBlkIndex + (nBlock.Address < currBlock.Address ? 1 : 0), currBlock);
  104. }
  105. else
  106. {
  107. blocks.Add(currBlock);
  108. }
  109. }
  110. if (blocks.Count == 1 && blocks[0].OpCodes.Count == 0)
  111. {
  112. Debug.Assert(blocks[0].Exit);
  113. Debug.Assert(blocks[0].Address == blocks[0].EndAddress);
  114. throw new InvalidOperationException($"Decoded a single empty exit block. Entry point = 0x{address:X}.");
  115. }
  116. if (dMode == DecoderMode.MultipleBlocks)
  117. {
  118. return TailCallRemover.RunPass(address, blocks);
  119. }
  120. else
  121. {
  122. return blocks.ToArray();
  123. }
  124. }
  125. public static bool BinarySearch(List<Block> blocks, ulong address, out int index)
  126. {
  127. index = 0;
  128. int left = 0;
  129. int right = blocks.Count - 1;
  130. while (left <= right)
  131. {
  132. int size = right - left;
  133. int middle = left + (size >> 1);
  134. Block block = blocks[middle];
  135. index = middle;
  136. if (address >= block.Address && address < block.EndAddress)
  137. {
  138. return true;
  139. }
  140. if (address < block.Address)
  141. {
  142. right = middle - 1;
  143. }
  144. else
  145. {
  146. left = middle + 1;
  147. }
  148. }
  149. return false;
  150. }
  151. private static void FillBlock(
  152. IMemoryManager memory,
  153. ExecutionMode mode,
  154. Block block,
  155. ulong limitAddress)
  156. {
  157. ulong address = block.Address;
  158. int itBlockSize = 0;
  159. OpCode opCode;
  160. do
  161. {
  162. if (address >= limitAddress && itBlockSize == 0)
  163. {
  164. break;
  165. }
  166. opCode = DecodeOpCode(memory, address, mode);
  167. block.OpCodes.Add(opCode);
  168. address += (ulong)opCode.OpCodeSizeInBytes;
  169. if (opCode is OpCodeT16IfThen it)
  170. {
  171. itBlockSize = it.IfThenBlockSize;
  172. }
  173. else if (itBlockSize > 0)
  174. {
  175. itBlockSize--;
  176. }
  177. }
  178. while (!(IsBranch(opCode) || IsException(opCode)));
  179. block.EndAddress = address;
  180. }
  181. private static bool IsBranch(OpCode opCode)
  182. {
  183. return opCode is OpCodeBImm ||
  184. opCode is OpCodeBReg || IsAarch32Branch(opCode);
  185. }
  186. private static bool IsUnconditionalBranch(OpCode opCode)
  187. {
  188. return opCode is OpCodeBImmAl ||
  189. opCode is OpCodeBReg || IsAarch32UnconditionalBranch(opCode);
  190. }
  191. private static bool IsAarch32UnconditionalBranch(OpCode opCode)
  192. {
  193. if (!(opCode is OpCode32 op))
  194. {
  195. return false;
  196. }
  197. // Note: On ARM32, most instructions have conditional execution,
  198. // so there's no "Always" (unconditional) branch like on ARM64.
  199. // We need to check if the condition is "Always" instead.
  200. return IsAarch32Branch(op) && op.Cond >= Condition.Al;
  201. }
  202. private static bool IsAarch32Branch(OpCode opCode)
  203. {
  204. // Note: On ARM32, most ALU operations can write to R15 (PC),
  205. // so we must consider such operations as a branch in potential aswell.
  206. if (opCode is IOpCode32Alu opAlu && opAlu.Rd == RegisterAlias.Aarch32Pc)
  207. {
  208. return true;
  209. }
  210. // Same thing for memory operations. We have the cases where PC is a target
  211. // register (Rt == 15 or (mask & (1 << 15)) != 0), and cases where there is
  212. // a write back to PC (wback == true && Rn == 15), however the later may
  213. // be "undefined" depending on the CPU, so compilers should not produce that.
  214. if (opCode is IOpCode32Mem || opCode is IOpCode32MemMult)
  215. {
  216. int rt, rn;
  217. bool wBack, isLoad;
  218. if (opCode is IOpCode32Mem opMem)
  219. {
  220. rt = opMem.Rt;
  221. rn = opMem.Rn;
  222. wBack = opMem.WBack;
  223. isLoad = opMem.IsLoad;
  224. // For the dual load, we also need to take into account the
  225. // case were Rt2 == 15 (PC).
  226. if (rt == 14 && opMem.Instruction.Name == InstName.Ldrd)
  227. {
  228. rt = RegisterAlias.Aarch32Pc;
  229. }
  230. }
  231. else if (opCode is IOpCode32MemMult opMemMult)
  232. {
  233. const int pcMask = 1 << RegisterAlias.Aarch32Pc;
  234. rt = (opMemMult.RegisterMask & pcMask) != 0 ? RegisterAlias.Aarch32Pc : 0;
  235. rn = opMemMult.Rn;
  236. wBack = opMemMult.PostOffset != 0;
  237. isLoad = opMemMult.IsLoad;
  238. }
  239. else
  240. {
  241. throw new NotImplementedException($"The type \"{opCode.GetType().Name}\" is not implemented on the decoder.");
  242. }
  243. if ((rt == RegisterAlias.Aarch32Pc && isLoad) ||
  244. (rn == RegisterAlias.Aarch32Pc && wBack))
  245. {
  246. return true;
  247. }
  248. }
  249. // Explicit branch instructions.
  250. return opCode is IOpCode32BImm ||
  251. opCode is IOpCode32BReg;
  252. }
  253. private static bool IsCall(OpCode opCode)
  254. {
  255. return opCode.Instruction.Name == InstName.Bl ||
  256. opCode.Instruction.Name == InstName.Blr ||
  257. opCode.Instruction.Name == InstName.Blx;
  258. }
  259. private static bool IsException(OpCode opCode)
  260. {
  261. return opCode.Instruction.Name == InstName.Brk ||
  262. opCode.Instruction.Name == InstName.Svc ||
  263. opCode.Instruction.Name == InstName.Trap ||
  264. opCode.Instruction.Name == InstName.Und;
  265. }
  266. public static OpCode DecodeOpCode(IMemoryManager memory, ulong address, ExecutionMode mode)
  267. {
  268. int opCode = memory.Read<int>(address);
  269. InstDescriptor inst;
  270. OpCodeTable.MakeOp makeOp;
  271. if (mode == ExecutionMode.Aarch64)
  272. {
  273. (inst, makeOp) = OpCodeTable.GetInstA64(opCode);
  274. }
  275. else
  276. {
  277. if (mode == ExecutionMode.Aarch32Arm)
  278. {
  279. (inst, makeOp) = OpCodeTable.GetInstA32(opCode);
  280. }
  281. else /* if (mode == ExecutionMode.Aarch32Thumb) */
  282. {
  283. (inst, makeOp) = OpCodeTable.GetInstT32(opCode);
  284. }
  285. }
  286. if (makeOp != null)
  287. {
  288. return makeOp(inst, address, opCode);
  289. }
  290. else
  291. {
  292. if (mode == ExecutionMode.Aarch32Thumb)
  293. {
  294. return new OpCodeT16(inst, address, opCode);
  295. }
  296. else
  297. {
  298. return new OpCode(inst, address, opCode);
  299. }
  300. }
  301. }
  302. }
  303. }