HybridAllocator.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. using ARMeilleure.IntermediateRepresentation;
  2. using ARMeilleure.Translation;
  3. using System;
  4. using System.Diagnostics;
  5. using System.Numerics;
  6. using static ARMeilleure.IntermediateRepresentation.Operand.Factory;
  7. using static ARMeilleure.IntermediateRepresentation.Operation.Factory;
  8. namespace ARMeilleure.CodeGen.RegisterAllocators
  9. {
  10. class HybridAllocator : IRegisterAllocator
  11. {
  12. private const int RegistersCount = 16;
  13. private const int MaxIROperands = 4;
  14. private struct BlockInfo
  15. {
  16. public bool HasCall { get; }
  17. public int IntFixedRegisters { get; }
  18. public int VecFixedRegisters { get; }
  19. public BlockInfo(bool hasCall, int intFixedRegisters, int vecFixedRegisters)
  20. {
  21. HasCall = hasCall;
  22. IntFixedRegisters = intFixedRegisters;
  23. VecFixedRegisters = vecFixedRegisters;
  24. }
  25. }
  26. private struct LocalInfo
  27. {
  28. public int Uses { get; set; }
  29. public int UsesAllocated { get; set; }
  30. public int Register { get; set; }
  31. public int SpillOffset { get; set; }
  32. public int Sequence { get; set; }
  33. public Operand Temp { get; set; }
  34. public OperandType Type { get; }
  35. private int _first;
  36. private int _last;
  37. public bool IsBlockLocal => _first == _last;
  38. public LocalInfo(OperandType type, int uses, int blkIndex)
  39. {
  40. Uses = uses;
  41. Type = type;
  42. UsesAllocated = 0;
  43. Register = 0;
  44. SpillOffset = 0;
  45. Sequence = 0;
  46. Temp = default;
  47. _first = -1;
  48. _last = -1;
  49. SetBlockIndex(blkIndex);
  50. }
  51. public void SetBlockIndex(int blkIndex)
  52. {
  53. if (_first == -1 || blkIndex < _first)
  54. {
  55. _first = blkIndex;
  56. }
  57. if (_last == -1 || blkIndex > _last)
  58. {
  59. _last = blkIndex;
  60. }
  61. }
  62. }
  63. public AllocationResult RunPass(ControlFlowGraph cfg, StackAllocator stackAlloc, RegisterMasks regMasks)
  64. {
  65. int intUsedRegisters = 0;
  66. int vecUsedRegisters = 0;
  67. int intFreeRegisters = regMasks.IntAvailableRegisters;
  68. int vecFreeRegisters = regMasks.VecAvailableRegisters;
  69. var blockInfo = new BlockInfo[cfg.Blocks.Count];
  70. var localInfo = new LocalInfo[cfg.Blocks.Count * 3];
  71. int localInfoCount = 0;
  72. // The "visited" state is stored in the MSB of the local's value.
  73. const ulong VisitedMask = 1ul << 63;
  74. bool IsVisited(Operand local)
  75. {
  76. return (local.GetValueUnsafe() & VisitedMask) != 0;
  77. }
  78. void SetVisited(Operand local)
  79. {
  80. local.GetValueUnsafe() |= VisitedMask | (uint)++localInfoCount;
  81. }
  82. ref LocalInfo GetLocalInfo(Operand local)
  83. {
  84. Debug.Assert(local.Kind == OperandKind.LocalVariable);
  85. if (!IsVisited(local))
  86. {
  87. throw new InvalidOperationException("Local was not visisted yet. Used before defined?");
  88. }
  89. return ref localInfo[(uint)local.GetValueUnsafe() - 1];
  90. }
  91. for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--)
  92. {
  93. BasicBlock block = cfg.PostOrderBlocks[index];
  94. int intFixedRegisters = 0;
  95. int vecFixedRegisters = 0;
  96. bool hasCall = false;
  97. for (Operation node = block.Operations.First; node != default; node = node.ListNext)
  98. {
  99. if (node.Instruction == Instruction.Call)
  100. {
  101. hasCall = true;
  102. }
  103. for (int i = 0; i < node.SourcesCount; i++)
  104. {
  105. Operand source = node.GetSource(i);
  106. if (source.Kind == OperandKind.LocalVariable)
  107. {
  108. GetLocalInfo(source).SetBlockIndex(block.Index);
  109. }
  110. else if (source.Kind == OperandKind.Memory)
  111. {
  112. MemoryOperand memOp = source.GetMemory();
  113. if (memOp.BaseAddress != default)
  114. {
  115. GetLocalInfo(memOp.BaseAddress).SetBlockIndex(block.Index);
  116. }
  117. if (memOp.Index != default)
  118. {
  119. GetLocalInfo(memOp.Index).SetBlockIndex(block.Index);
  120. }
  121. }
  122. }
  123. for (int i = 0; i < node.DestinationsCount; i++)
  124. {
  125. Operand dest = node.GetDestination(i);
  126. if (dest.Kind == OperandKind.LocalVariable)
  127. {
  128. if (IsVisited(dest))
  129. {
  130. GetLocalInfo(dest).SetBlockIndex(block.Index);
  131. }
  132. else
  133. {
  134. SetVisited(dest);
  135. if (localInfoCount > localInfo.Length)
  136. {
  137. Array.Resize(ref localInfo, localInfoCount * 2);
  138. }
  139. GetLocalInfo(dest) = new LocalInfo(dest.Type, UsesCount(dest), block.Index);
  140. }
  141. }
  142. else if (dest.Kind == OperandKind.Register)
  143. {
  144. if (dest.Type.IsInteger())
  145. {
  146. intFixedRegisters |= 1 << dest.GetRegister().Index;
  147. }
  148. else
  149. {
  150. vecFixedRegisters |= 1 << dest.GetRegister().Index;
  151. }
  152. }
  153. }
  154. }
  155. blockInfo[block.Index] = new BlockInfo(hasCall, intFixedRegisters, vecFixedRegisters);
  156. }
  157. int sequence = 0;
  158. for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--)
  159. {
  160. BasicBlock block = cfg.PostOrderBlocks[index];
  161. BlockInfo blkInfo = blockInfo[block.Index];
  162. int intLocalFreeRegisters = intFreeRegisters & ~blkInfo.IntFixedRegisters;
  163. int vecLocalFreeRegisters = vecFreeRegisters & ~blkInfo.VecFixedRegisters;
  164. int intCallerSavedRegisters = blkInfo.HasCall ? regMasks.IntCallerSavedRegisters : 0;
  165. int vecCallerSavedRegisters = blkInfo.HasCall ? regMasks.VecCallerSavedRegisters : 0;
  166. int intSpillTempRegisters = SelectSpillTemps(
  167. intCallerSavedRegisters & ~blkInfo.IntFixedRegisters,
  168. intLocalFreeRegisters);
  169. int vecSpillTempRegisters = SelectSpillTemps(
  170. vecCallerSavedRegisters & ~blkInfo.VecFixedRegisters,
  171. vecLocalFreeRegisters);
  172. intLocalFreeRegisters &= ~(intSpillTempRegisters | intCallerSavedRegisters);
  173. vecLocalFreeRegisters &= ~(vecSpillTempRegisters | vecCallerSavedRegisters);
  174. for (Operation node = block.Operations.First; node != default; node = node.ListNext)
  175. {
  176. int intLocalUse = 0;
  177. int vecLocalUse = 0;
  178. Operand AllocateRegister(Operand local)
  179. {
  180. ref LocalInfo info = ref GetLocalInfo(local);
  181. info.UsesAllocated++;
  182. Debug.Assert(info.UsesAllocated <= info.Uses);
  183. if (info.Register != -1)
  184. {
  185. Operand reg = Register(info.Register, local.Type.ToRegisterType(), local.Type);
  186. if (info.UsesAllocated == info.Uses)
  187. {
  188. if (local.Type.IsInteger())
  189. {
  190. intLocalFreeRegisters |= 1 << info.Register;
  191. }
  192. else
  193. {
  194. vecLocalFreeRegisters |= 1 << info.Register;
  195. }
  196. }
  197. return reg;
  198. }
  199. else
  200. {
  201. Operand temp = info.Temp;
  202. if (temp == default || info.Sequence != sequence)
  203. {
  204. temp = local.Type.IsInteger()
  205. ? GetSpillTemp(local, intSpillTempRegisters, ref intLocalUse)
  206. : GetSpillTemp(local, vecSpillTempRegisters, ref vecLocalUse);
  207. info.Sequence = sequence;
  208. info.Temp = temp;
  209. }
  210. Operation fillOp = Operation(Instruction.Fill, temp, Const(info.SpillOffset));
  211. block.Operations.AddBefore(node, fillOp);
  212. return temp;
  213. }
  214. }
  215. bool folded = false;
  216. // If operation is a copy of a local and that local is living on the stack, we turn the copy into
  217. // a fill, instead of inserting a fill before it.
  218. if (node.Instruction == Instruction.Copy)
  219. {
  220. Operand source = node.GetSource(0);
  221. if (source.Kind == OperandKind.LocalVariable)
  222. {
  223. ref LocalInfo info = ref GetLocalInfo(source);
  224. if (info.Register == -1)
  225. {
  226. Operation fillOp = Operation(Instruction.Fill, node.Destination, Const(info.SpillOffset));
  227. block.Operations.AddBefore(node, fillOp);
  228. block.Operations.Remove(node);
  229. node = fillOp;
  230. folded = true;
  231. }
  232. }
  233. }
  234. if (!folded)
  235. {
  236. for (int i = 0; i < node.SourcesCount; i++)
  237. {
  238. Operand source = node.GetSource(i);
  239. if (source.Kind == OperandKind.LocalVariable)
  240. {
  241. node.SetSource(i, AllocateRegister(source));
  242. }
  243. else if (source.Kind == OperandKind.Memory)
  244. {
  245. MemoryOperand memOp = source.GetMemory();
  246. if (memOp.BaseAddress != default)
  247. {
  248. memOp.BaseAddress = AllocateRegister(memOp.BaseAddress);
  249. }
  250. if (memOp.Index != default)
  251. {
  252. memOp.Index = AllocateRegister(memOp.Index);
  253. }
  254. }
  255. }
  256. }
  257. int intLocalAsg = 0;
  258. int vecLocalAsg = 0;
  259. for (int i = 0; i < node.DestinationsCount; i++)
  260. {
  261. Operand dest = node.GetDestination(i);
  262. if (dest.Kind != OperandKind.LocalVariable)
  263. {
  264. continue;
  265. }
  266. ref LocalInfo info = ref GetLocalInfo(dest);
  267. if (info.UsesAllocated == 0)
  268. {
  269. int mask = dest.Type.IsInteger()
  270. ? intLocalFreeRegisters
  271. : vecLocalFreeRegisters;
  272. if (info.IsBlockLocal && mask != 0)
  273. {
  274. int selectedReg = BitOperations.TrailingZeroCount(mask);
  275. info.Register = selectedReg;
  276. if (dest.Type.IsInteger())
  277. {
  278. intLocalFreeRegisters &= ~(1 << selectedReg);
  279. intUsedRegisters |= 1 << selectedReg;
  280. }
  281. else
  282. {
  283. vecLocalFreeRegisters &= ~(1 << selectedReg);
  284. vecUsedRegisters |= 1 << selectedReg;
  285. }
  286. }
  287. else
  288. {
  289. info.Register = -1;
  290. info.SpillOffset = stackAlloc.Allocate(dest.Type.GetSizeInBytes());
  291. }
  292. }
  293. info.UsesAllocated++;
  294. Debug.Assert(info.UsesAllocated <= info.Uses);
  295. if (info.Register != -1)
  296. {
  297. node.SetDestination(i, Register(info.Register, dest.Type.ToRegisterType(), dest.Type));
  298. }
  299. else
  300. {
  301. Operand temp = info.Temp;
  302. if (temp == default || info.Sequence != sequence)
  303. {
  304. temp = dest.Type.IsInteger()
  305. ? GetSpillTemp(dest, intSpillTempRegisters, ref intLocalAsg)
  306. : GetSpillTemp(dest, vecSpillTempRegisters, ref vecLocalAsg);
  307. info.Sequence = sequence;
  308. info.Temp = temp;
  309. }
  310. node.SetDestination(i, temp);
  311. Operation spillOp = Operation(Instruction.Spill, default, Const(info.SpillOffset), temp);
  312. block.Operations.AddAfter(node, spillOp);
  313. node = spillOp;
  314. }
  315. }
  316. sequence++;
  317. intUsedRegisters |= intLocalAsg | intLocalUse;
  318. vecUsedRegisters |= vecLocalAsg | vecLocalUse;
  319. }
  320. }
  321. return new AllocationResult(intUsedRegisters, vecUsedRegisters, stackAlloc.TotalSize);
  322. }
  323. private static int SelectSpillTemps(int mask0, int mask1)
  324. {
  325. int selection = 0;
  326. int count = 0;
  327. while (count < MaxIROperands && mask0 != 0)
  328. {
  329. int mask = mask0 & -mask0;
  330. selection |= mask;
  331. mask0 &= ~mask;
  332. count++;
  333. }
  334. while (count < MaxIROperands && mask1 != 0)
  335. {
  336. int mask = mask1 & -mask1;
  337. selection |= mask;
  338. mask1 &= ~mask;
  339. count++;
  340. }
  341. Debug.Assert(count == MaxIROperands, "No enough registers for spill temps.");
  342. return selection;
  343. }
  344. private static Operand GetSpillTemp(Operand local, int freeMask, ref int useMask)
  345. {
  346. int selectedReg = BitOperations.TrailingZeroCount(freeMask & ~useMask);
  347. useMask |= 1 << selectedReg;
  348. return Register(selectedReg, local.Type.ToRegisterType(), local.Type);
  349. }
  350. private static int UsesCount(Operand local)
  351. {
  352. return local.AssignmentsCount + local.UsesCount;
  353. }
  354. }
  355. }