LinearScanAllocator.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. using ARMeilleure.Common;
  2. using ARMeilleure.IntermediateRepresentation;
  3. using ARMeilleure.Translation;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. namespace ARMeilleure.CodeGen.RegisterAllocators
  9. {
  10. // Based on:
  11. // "Linear Scan Register Allocation for the Java(tm) HotSpot Client Compiler".
  12. // http://www.christianwimmer.at/Publications/Wimmer04a/Wimmer04a.pdf
  13. class LinearScanAllocator : IRegisterAllocator
  14. {
  15. private const int InstructionGap = 2;
  16. private const int InstructionGapMask = InstructionGap - 1;
  17. private const int RegistersCount = 16;
  18. private HashSet<int> _blockEdges;
  19. private LiveRange[] _blockRanges;
  20. private BitMap[] _blockLiveIn;
  21. private List<LiveInterval> _intervals;
  22. private LiveInterval[] _parentIntervals;
  23. private List<(IntrusiveList<Node>, Node)> _operationNodes;
  24. private int _operationsCount;
  25. private class AllocationContext
  26. {
  27. public RegisterMasks Masks { get; }
  28. public StackAllocator StackAlloc { get; }
  29. public BitMap Active { get; }
  30. public BitMap Inactive { get; }
  31. public int IntUsedRegisters { get; set; }
  32. public int VecUsedRegisters { get; set; }
  33. public AllocationContext(StackAllocator stackAlloc, RegisterMasks masks, int intervalsCount)
  34. {
  35. StackAlloc = stackAlloc;
  36. Masks = masks;
  37. Active = new BitMap(intervalsCount);
  38. Inactive = new BitMap(intervalsCount);
  39. }
  40. public void MoveActiveToInactive(int bit)
  41. {
  42. Move(Active, Inactive, bit);
  43. }
  44. public void MoveInactiveToActive(int bit)
  45. {
  46. Move(Inactive, Active, bit);
  47. }
  48. private static void Move(BitMap source, BitMap dest, int bit)
  49. {
  50. source.Clear(bit);
  51. dest.Set(bit);
  52. }
  53. }
  54. public AllocationResult RunPass(
  55. ControlFlowGraph cfg,
  56. StackAllocator stackAlloc,
  57. RegisterMasks regMasks)
  58. {
  59. NumberLocals(cfg);
  60. AllocationContext context = new AllocationContext(stackAlloc, regMasks, _intervals.Count);
  61. BuildIntervals(cfg, context);
  62. for (int index = 0; index < _intervals.Count; index++)
  63. {
  64. LiveInterval current = _intervals[index];
  65. if (current.IsEmpty)
  66. {
  67. continue;
  68. }
  69. if (current.IsFixed)
  70. {
  71. context.Active.Set(index);
  72. if (current.Register.Type == RegisterType.Integer)
  73. {
  74. context.IntUsedRegisters |= 1 << current.Register.Index;
  75. }
  76. else /* if (interval.Register.Type == RegisterType.Vector) */
  77. {
  78. context.VecUsedRegisters |= 1 << current.Register.Index;
  79. }
  80. continue;
  81. }
  82. AllocateInterval(context, current, index);
  83. }
  84. for (int index = RegistersCount * 2; index < _intervals.Count; index++)
  85. {
  86. if (!_intervals[index].IsSpilled)
  87. {
  88. ReplaceLocalWithRegister(_intervals[index]);
  89. }
  90. }
  91. InsertSplitCopies();
  92. InsertSplitCopiesAtEdges(cfg);
  93. return new AllocationResult(
  94. context.IntUsedRegisters,
  95. context.VecUsedRegisters,
  96. context.StackAlloc.TotalSize);
  97. }
  98. private void AllocateInterval(AllocationContext context, LiveInterval current, int cIndex)
  99. {
  100. // Check active intervals that already ended.
  101. foreach (int iIndex in context.Active)
  102. {
  103. LiveInterval interval = _intervals[iIndex];
  104. if (interval.GetEnd() < current.GetStart())
  105. {
  106. context.Active.Clear(iIndex);
  107. }
  108. else if (!interval.Overlaps(current.GetStart()))
  109. {
  110. context.MoveActiveToInactive(iIndex);
  111. }
  112. }
  113. // Check inactive intervals that already ended or were reactivated.
  114. foreach (int iIndex in context.Inactive)
  115. {
  116. LiveInterval interval = _intervals[iIndex];
  117. if (interval.GetEnd() < current.GetStart())
  118. {
  119. context.Inactive.Clear(iIndex);
  120. }
  121. else if (interval.Overlaps(current.GetStart()))
  122. {
  123. context.MoveInactiveToActive(iIndex);
  124. }
  125. }
  126. if (!TryAllocateRegWithoutSpill(context, current, cIndex))
  127. {
  128. AllocateRegWithSpill(context, current, cIndex);
  129. }
  130. }
  131. private bool TryAllocateRegWithoutSpill(AllocationContext context, LiveInterval current, int cIndex)
  132. {
  133. RegisterType regType = current.Local.Type.ToRegisterType();
  134. int availableRegisters = context.Masks.GetAvailableRegisters(regType);
  135. int[] freePositions = new int[RegistersCount];
  136. for (int index = 0; index < RegistersCount; index++)
  137. {
  138. if ((availableRegisters & (1 << index)) != 0)
  139. {
  140. freePositions[index] = int.MaxValue;
  141. }
  142. }
  143. foreach (int iIndex in context.Active)
  144. {
  145. LiveInterval interval = _intervals[iIndex];
  146. if (interval.Register.Type == regType)
  147. {
  148. freePositions[interval.Register.Index] = 0;
  149. }
  150. }
  151. foreach (int iIndex in context.Inactive)
  152. {
  153. LiveInterval interval = _intervals[iIndex];
  154. if (interval.Register.Type == regType)
  155. {
  156. int overlapPosition = interval.GetOverlapPosition(current);
  157. if (overlapPosition != LiveInterval.NotFound && freePositions[interval.Register.Index] > overlapPosition)
  158. {
  159. freePositions[interval.Register.Index] = overlapPosition;
  160. }
  161. }
  162. }
  163. int selectedReg = GetHighestValueIndex(freePositions);
  164. int selectedNextUse = freePositions[selectedReg];
  165. // Intervals starts and ends at odd positions, unless they span an entire
  166. // block, in this case they will have ranges at a even position.
  167. // When a interval is loaded from the stack to a register, we can only
  168. // do the split at a odd position, because otherwise the split interval
  169. // that is inserted on the list to be processed may clobber a register
  170. // used by the instruction at the same position as the split.
  171. // The problem only happens when a interval ends exactly at this instruction,
  172. // because otherwise they would interfere, and the register wouldn't be selected.
  173. // When the interval is aligned and the above happens, there's no problem as
  174. // the instruction that is actually with the last use is the one
  175. // before that position.
  176. selectedNextUse &= ~InstructionGapMask;
  177. if (selectedNextUse <= current.GetStart())
  178. {
  179. return false;
  180. }
  181. else if (selectedNextUse < current.GetEnd())
  182. {
  183. Debug.Assert(selectedNextUse > current.GetStart(), "Trying to split interval at the start.");
  184. LiveInterval splitChild = current.Split(selectedNextUse);
  185. if (splitChild.UsesCount != 0)
  186. {
  187. Debug.Assert(splitChild.GetStart() > current.GetStart(), "Split interval has an invalid start position.");
  188. InsertInterval(splitChild);
  189. }
  190. else
  191. {
  192. Spill(context, splitChild);
  193. }
  194. }
  195. current.Register = new Register(selectedReg, regType);
  196. if (regType == RegisterType.Integer)
  197. {
  198. context.IntUsedRegisters |= 1 << selectedReg;
  199. }
  200. else /* if (regType == RegisterType.Vector) */
  201. {
  202. context.VecUsedRegisters |= 1 << selectedReg;
  203. }
  204. context.Active.Set(cIndex);
  205. return true;
  206. }
  207. private void AllocateRegWithSpill(AllocationContext context, LiveInterval current, int cIndex)
  208. {
  209. RegisterType regType = current.Local.Type.ToRegisterType();
  210. int availableRegisters = context.Masks.GetAvailableRegisters(regType);
  211. int[] usePositions = new int[RegistersCount];
  212. int[] blockedPositions = new int[RegistersCount];
  213. for (int index = 0; index < RegistersCount; index++)
  214. {
  215. if ((availableRegisters & (1 << index)) != 0)
  216. {
  217. usePositions[index] = int.MaxValue;
  218. blockedPositions[index] = int.MaxValue;
  219. }
  220. }
  221. void SetUsePosition(int index, int position)
  222. {
  223. usePositions[index] = Math.Min(usePositions[index], position);
  224. }
  225. void SetBlockedPosition(int index, int position)
  226. {
  227. blockedPositions[index] = Math.Min(blockedPositions[index], position);
  228. SetUsePosition(index, position);
  229. }
  230. foreach (int iIndex in context.Active)
  231. {
  232. LiveInterval interval = _intervals[iIndex];
  233. if (!interval.IsFixed && interval.Register.Type == regType)
  234. {
  235. int nextUse = interval.NextUseAfter(current.GetStart());
  236. if (nextUse != -1)
  237. {
  238. SetUsePosition(interval.Register.Index, nextUse);
  239. }
  240. }
  241. }
  242. foreach (int iIndex in context.Inactive)
  243. {
  244. LiveInterval interval = _intervals[iIndex];
  245. if (!interval.IsFixed && interval.Register.Type == regType && interval.Overlaps(current))
  246. {
  247. int nextUse = interval.NextUseAfter(current.GetStart());
  248. if (nextUse != -1)
  249. {
  250. SetUsePosition(interval.Register.Index, nextUse);
  251. }
  252. }
  253. }
  254. foreach (int iIndex in context.Active)
  255. {
  256. LiveInterval interval = _intervals[iIndex];
  257. if (interval.IsFixed && interval.Register.Type == regType)
  258. {
  259. SetBlockedPosition(interval.Register.Index, 0);
  260. }
  261. }
  262. foreach (int iIndex in context.Inactive)
  263. {
  264. LiveInterval interval = _intervals[iIndex];
  265. if (interval.IsFixed && interval.Register.Type == regType)
  266. {
  267. int overlapPosition = interval.GetOverlapPosition(current);
  268. if (overlapPosition != LiveInterval.NotFound)
  269. {
  270. SetBlockedPosition(interval.Register.Index, overlapPosition);
  271. }
  272. }
  273. }
  274. int selectedReg = GetHighestValueIndex(usePositions);
  275. int currentFirstUse = current.FirstUse();
  276. Debug.Assert(currentFirstUse >= 0, "Current interval has no uses.");
  277. if (usePositions[selectedReg] < currentFirstUse)
  278. {
  279. // All intervals on inactive and active are being used before current,
  280. // so spill the current interval.
  281. Debug.Assert(currentFirstUse > current.GetStart(), "Trying to spill a interval currently being used.");
  282. LiveInterval splitChild = current.Split(currentFirstUse);
  283. Debug.Assert(splitChild.GetStart() > current.GetStart(), "Split interval has an invalid start position.");
  284. InsertInterval(splitChild);
  285. Spill(context, current);
  286. }
  287. else if (blockedPositions[selectedReg] > current.GetEnd())
  288. {
  289. // Spill made the register available for the entire current lifetime,
  290. // so we only need to split the intervals using the selected register.
  291. current.Register = new Register(selectedReg, regType);
  292. SplitAndSpillOverlappingIntervals(context, current);
  293. context.Active.Set(cIndex);
  294. }
  295. else
  296. {
  297. // There are conflicts even after spill due to the use of fixed registers
  298. // that can't be spilled, so we need to also split current at the point of
  299. // the first fixed register use.
  300. current.Register = new Register(selectedReg, regType);
  301. int splitPosition = blockedPositions[selectedReg] & ~InstructionGapMask;
  302. Debug.Assert(splitPosition > current.GetStart(), "Trying to split a interval at a invalid position.");
  303. LiveInterval splitChild = current.Split(splitPosition);
  304. if (splitChild.UsesCount != 0)
  305. {
  306. Debug.Assert(splitChild.GetStart() > current.GetStart(), "Split interval has an invalid start position.");
  307. InsertInterval(splitChild);
  308. }
  309. else
  310. {
  311. Spill(context, splitChild);
  312. }
  313. SplitAndSpillOverlappingIntervals(context, current);
  314. context.Active.Set(cIndex);
  315. }
  316. }
  317. private static int GetHighestValueIndex(int[] array)
  318. {
  319. int higuest = array[0];
  320. if (higuest == int.MaxValue)
  321. {
  322. return 0;
  323. }
  324. int selected = 0;
  325. for (int index = 1; index < array.Length; index++)
  326. {
  327. int current = array[index];
  328. if (higuest < current)
  329. {
  330. higuest = current;
  331. selected = index;
  332. if (current == int.MaxValue)
  333. {
  334. break;
  335. }
  336. }
  337. }
  338. return selected;
  339. }
  340. private void SplitAndSpillOverlappingIntervals(AllocationContext context, LiveInterval current)
  341. {
  342. foreach (int iIndex in context.Active)
  343. {
  344. LiveInterval interval = _intervals[iIndex];
  345. if (!interval.IsFixed && interval.Register == current.Register)
  346. {
  347. SplitAndSpillOverlappingInterval(context, current, interval);
  348. context.Active.Clear(iIndex);
  349. }
  350. }
  351. foreach (int iIndex in context.Inactive)
  352. {
  353. LiveInterval interval = _intervals[iIndex];
  354. if (!interval.IsFixed && interval.Register == current.Register && interval.Overlaps(current))
  355. {
  356. SplitAndSpillOverlappingInterval(context, current, interval);
  357. context.Inactive.Clear(iIndex);
  358. }
  359. }
  360. }
  361. private void SplitAndSpillOverlappingInterval(
  362. AllocationContext context,
  363. LiveInterval current,
  364. LiveInterval interval)
  365. {
  366. // If there's a next use after the start of the current interval,
  367. // we need to split the spilled interval twice, and re-insert it
  368. // on the "pending" list to ensure that it will get a new register
  369. // on that use position.
  370. int nextUse = interval.NextUseAfter(current.GetStart());
  371. LiveInterval splitChild;
  372. if (interval.GetStart() < current.GetStart())
  373. {
  374. splitChild = interval.Split(current.GetStart());
  375. }
  376. else
  377. {
  378. splitChild = interval;
  379. }
  380. if (nextUse != -1)
  381. {
  382. Debug.Assert(nextUse > current.GetStart(), "Trying to spill a interval currently being used.");
  383. if (nextUse > splitChild.GetStart())
  384. {
  385. LiveInterval right = splitChild.Split(nextUse);
  386. Spill(context, splitChild);
  387. splitChild = right;
  388. }
  389. InsertInterval(splitChild);
  390. }
  391. else
  392. {
  393. Spill(context, splitChild);
  394. }
  395. }
  396. private void InsertInterval(LiveInterval interval)
  397. {
  398. Debug.Assert(interval.UsesCount != 0, "Trying to insert a interval without uses.");
  399. Debug.Assert(!interval.IsEmpty, "Trying to insert a empty interval.");
  400. Debug.Assert(!interval.IsSpilled, "Trying to insert a spilled interval.");
  401. int startIndex = RegistersCount * 2;
  402. int insertIndex = _intervals.BinarySearch(startIndex, _intervals.Count - startIndex, interval, null);
  403. if (insertIndex < 0)
  404. {
  405. insertIndex = ~insertIndex;
  406. }
  407. _intervals.Insert(insertIndex, interval);
  408. }
  409. private void Spill(AllocationContext context, LiveInterval interval)
  410. {
  411. Debug.Assert(!interval.IsFixed, "Trying to spill a fixed interval.");
  412. Debug.Assert(interval.UsesCount == 0, "Trying to spill a interval with uses.");
  413. // We first check if any of the siblings were spilled, if so we can reuse
  414. // the stack offset. Otherwise, we allocate a new space on the stack.
  415. // This prevents stack-to-stack copies being necessary for a split interval.
  416. if (!interval.TrySpillWithSiblingOffset())
  417. {
  418. interval.Spill(context.StackAlloc.Allocate(interval.Local.Type));
  419. }
  420. }
  421. private void InsertSplitCopies()
  422. {
  423. Dictionary<int, CopyResolver> copyResolvers = new Dictionary<int, CopyResolver>();
  424. CopyResolver GetCopyResolver(int position)
  425. {
  426. CopyResolver copyResolver = new CopyResolver();
  427. if (copyResolvers.TryAdd(position, copyResolver))
  428. {
  429. return copyResolver;
  430. }
  431. return copyResolvers[position];
  432. }
  433. foreach (LiveInterval interval in _intervals.Where(x => x.IsSplit))
  434. {
  435. LiveInterval previous = interval;
  436. foreach (LiveInterval splitChild in interval.SplitChilds())
  437. {
  438. int splitPosition = splitChild.GetStart();
  439. if (!_blockEdges.Contains(splitPosition) && previous.GetEnd() == splitPosition)
  440. {
  441. GetCopyResolver(splitPosition).AddSplit(previous, splitChild);
  442. }
  443. previous = splitChild;
  444. }
  445. }
  446. foreach (KeyValuePair<int, CopyResolver> kv in copyResolvers)
  447. {
  448. CopyResolver copyResolver = kv.Value;
  449. if (!copyResolver.HasCopy)
  450. {
  451. continue;
  452. }
  453. int splitPosition = kv.Key;
  454. (IntrusiveList<Node> nodes, Node node) = GetOperationNode(splitPosition);
  455. Operation[] sequence = copyResolver.Sequence();
  456. nodes.AddBefore(node, sequence[0]);
  457. node = sequence[0];
  458. for (int index = 1; index < sequence.Length; index++)
  459. {
  460. nodes.AddAfter(node, sequence[index]);
  461. node = sequence[index];
  462. }
  463. }
  464. }
  465. private void InsertSplitCopiesAtEdges(ControlFlowGraph cfg)
  466. {
  467. int blocksCount = cfg.Blocks.Count;
  468. bool IsSplitEdgeBlock(BasicBlock block)
  469. {
  470. return block.Index >= blocksCount;
  471. }
  472. for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext)
  473. {
  474. if (IsSplitEdgeBlock(block))
  475. {
  476. continue;
  477. }
  478. bool hasSingleOrNoSuccessor = block.Next == null || block.Branch == null;
  479. foreach (BasicBlock successor in Successors(block))
  480. {
  481. int succIndex = successor.Index;
  482. // If the current node is a split node, then the actual successor node
  483. // (the successor before the split) should be right after it.
  484. if (IsSplitEdgeBlock(successor))
  485. {
  486. succIndex = Successors(successor).First().Index;
  487. }
  488. CopyResolver copyResolver = new CopyResolver();
  489. foreach (int iIndex in _blockLiveIn[succIndex])
  490. {
  491. LiveInterval interval = _parentIntervals[iIndex];
  492. if (!interval.IsSplit)
  493. {
  494. continue;
  495. }
  496. int lEnd = _blockRanges[block.Index].End - 1;
  497. int rStart = _blockRanges[succIndex].Start;
  498. LiveInterval left = interval.GetSplitChild(lEnd);
  499. LiveInterval right = interval.GetSplitChild(rStart);
  500. if (left != null && right != null && left != right)
  501. {
  502. copyResolver.AddSplit(left, right);
  503. }
  504. }
  505. if (!copyResolver.HasCopy)
  506. {
  507. continue;
  508. }
  509. Operation[] sequence = copyResolver.Sequence();
  510. if (hasSingleOrNoSuccessor)
  511. {
  512. foreach (Operation operation in sequence)
  513. {
  514. block.Append(operation);
  515. }
  516. }
  517. else if (successor.Predecessors.Count == 1)
  518. {
  519. successor.Operations.AddFirst(sequence[0]);
  520. Node prependNode = sequence[0];
  521. for (int index = 1; index < sequence.Length; index++)
  522. {
  523. Operation operation = sequence[index];
  524. successor.Operations.AddAfter(prependNode, operation);
  525. prependNode = operation;
  526. }
  527. }
  528. else
  529. {
  530. // Split the critical edge.
  531. BasicBlock splitBlock = cfg.SplitEdge(block, successor);
  532. foreach (Operation operation in sequence)
  533. {
  534. splitBlock.Append(operation);
  535. }
  536. }
  537. }
  538. }
  539. }
  540. private void ReplaceLocalWithRegister(LiveInterval current)
  541. {
  542. Operand register = GetRegister(current);
  543. foreach (int usePosition in current.UsePositions())
  544. {
  545. (_, Node operation) = GetOperationNode(usePosition);
  546. for (int index = 0; index < operation.SourcesCount; index++)
  547. {
  548. Operand source = operation.GetSource(index);
  549. if (source == current.Local)
  550. {
  551. operation.SetSource(index, register);
  552. }
  553. }
  554. for (int index = 0; index < operation.DestinationsCount; index++)
  555. {
  556. Operand dest = operation.GetDestination(index);
  557. if (dest == current.Local)
  558. {
  559. operation.SetDestination(index, register);
  560. }
  561. }
  562. }
  563. }
  564. private static Operand GetRegister(LiveInterval interval)
  565. {
  566. Debug.Assert(!interval.IsSpilled, "Spilled intervals are not allowed.");
  567. return new Operand(
  568. interval.Register.Index,
  569. interval.Register.Type,
  570. interval.Local.Type);
  571. }
  572. private (IntrusiveList<Node>, Node) GetOperationNode(int position)
  573. {
  574. return _operationNodes[position / InstructionGap];
  575. }
  576. private void NumberLocals(ControlFlowGraph cfg)
  577. {
  578. _operationNodes = new List<(IntrusiveList<Node>, Node)>();
  579. _intervals = new List<LiveInterval>();
  580. for (int index = 0; index < RegistersCount; index++)
  581. {
  582. _intervals.Add(new LiveInterval(new Register(index, RegisterType.Integer)));
  583. _intervals.Add(new LiveInterval(new Register(index, RegisterType.Vector)));
  584. }
  585. HashSet<Operand> visited = new HashSet<Operand>();
  586. _operationsCount = 0;
  587. for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--)
  588. {
  589. BasicBlock block = cfg.PostOrderBlocks[index];
  590. for (Node node = block.Operations.First; node != null; node = node.ListNext)
  591. {
  592. _operationNodes.Add((block.Operations, node));
  593. foreach (Operand dest in Destinations(node))
  594. {
  595. if (dest.Kind == OperandKind.LocalVariable && visited.Add(dest))
  596. {
  597. dest.NumberLocal(_intervals.Count);
  598. _intervals.Add(new LiveInterval(dest));
  599. }
  600. }
  601. }
  602. _operationsCount += block.Operations.Count * InstructionGap;
  603. if (block.Operations.Count == 0)
  604. {
  605. // Pretend we have a dummy instruction on the empty block.
  606. _operationNodes.Add((null, null));
  607. _operationsCount += InstructionGap;
  608. }
  609. }
  610. _parentIntervals = _intervals.ToArray();
  611. }
  612. private void BuildIntervals(ControlFlowGraph cfg, AllocationContext context)
  613. {
  614. _blockRanges = new LiveRange[cfg.Blocks.Count];
  615. int mapSize = _intervals.Count;
  616. BitMap[] blkLiveGen = new BitMap[cfg.Blocks.Count];
  617. BitMap[] blkLiveKill = new BitMap[cfg.Blocks.Count];
  618. // Compute local live sets.
  619. for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext)
  620. {
  621. BitMap liveGen = new BitMap(mapSize);
  622. BitMap liveKill = new BitMap(mapSize);
  623. for (Node node = block.Operations.First; node != null; node = node.ListNext)
  624. {
  625. foreach (Operand source in Sources(node))
  626. {
  627. int id = GetOperandId(source);
  628. if (!liveKill.IsSet(id))
  629. {
  630. liveGen.Set(id);
  631. }
  632. }
  633. foreach (Operand dest in Destinations(node))
  634. {
  635. liveKill.Set(GetOperandId(dest));
  636. }
  637. }
  638. blkLiveGen [block.Index] = liveGen;
  639. blkLiveKill[block.Index] = liveKill;
  640. }
  641. // Compute global live sets.
  642. BitMap[] blkLiveIn = new BitMap[cfg.Blocks.Count];
  643. BitMap[] blkLiveOut = new BitMap[cfg.Blocks.Count];
  644. for (int index = 0; index < cfg.Blocks.Count; index++)
  645. {
  646. blkLiveIn [index] = new BitMap(mapSize);
  647. blkLiveOut[index] = new BitMap(mapSize);
  648. }
  649. bool modified;
  650. do
  651. {
  652. modified = false;
  653. for (int index = 0; index < cfg.PostOrderBlocks.Length; index++)
  654. {
  655. BasicBlock block = cfg.PostOrderBlocks[index];
  656. BitMap liveOut = blkLiveOut[block.Index];
  657. foreach (BasicBlock successor in Successors(block))
  658. {
  659. if (liveOut.Set(blkLiveIn[successor.Index]))
  660. {
  661. modified = true;
  662. }
  663. }
  664. BitMap liveIn = blkLiveIn[block.Index];
  665. liveIn.Set (liveOut);
  666. liveIn.Clear(blkLiveKill[block.Index]);
  667. liveIn.Set (blkLiveGen [block.Index]);
  668. }
  669. }
  670. while (modified);
  671. _blockLiveIn = blkLiveIn;
  672. _blockEdges = new HashSet<int>();
  673. // Compute lifetime intervals.
  674. int operationPos = _operationsCount;
  675. for (int index = 0; index < cfg.PostOrderBlocks.Length; index++)
  676. {
  677. BasicBlock block = cfg.PostOrderBlocks[index];
  678. // We handle empty blocks by pretending they have a dummy instruction,
  679. // because otherwise the block would have the same start and end position,
  680. // and this is not valid.
  681. int instCount = Math.Max(block.Operations.Count, 1);
  682. int blockStart = operationPos - instCount * InstructionGap;
  683. int blockEnd = operationPos;
  684. _blockRanges[block.Index] = new LiveRange(blockStart, blockEnd);
  685. _blockEdges.Add(blockStart);
  686. BitMap liveOut = blkLiveOut[block.Index];
  687. foreach (int id in liveOut)
  688. {
  689. _intervals[id].AddRange(blockStart, blockEnd);
  690. }
  691. if (block.Operations.Count == 0)
  692. {
  693. operationPos -= InstructionGap;
  694. continue;
  695. }
  696. foreach (Node node in BottomOperations(block))
  697. {
  698. operationPos -= InstructionGap;
  699. foreach (Operand dest in Destinations(node))
  700. {
  701. LiveInterval interval = _intervals[GetOperandId(dest)];
  702. interval.SetStart(operationPos + 1);
  703. interval.AddUsePosition(operationPos + 1);
  704. }
  705. foreach (Operand source in Sources(node))
  706. {
  707. LiveInterval interval = _intervals[GetOperandId(source)];
  708. interval.AddRange(blockStart, operationPos + 1);
  709. interval.AddUsePosition(operationPos);
  710. }
  711. if (node is Operation operation && operation.Instruction == Instruction.Call)
  712. {
  713. AddIntervalCallerSavedReg(context.Masks.IntCallerSavedRegisters, operationPos, RegisterType.Integer);
  714. AddIntervalCallerSavedReg(context.Masks.VecCallerSavedRegisters, operationPos, RegisterType.Vector);
  715. }
  716. }
  717. }
  718. }
  719. private void AddIntervalCallerSavedReg(int mask, int operationPos, RegisterType regType)
  720. {
  721. while (mask != 0)
  722. {
  723. int regIndex = BitUtils.LowestBitSet(mask);
  724. Register callerSavedReg = new Register(regIndex, regType);
  725. LiveInterval interval = _intervals[GetRegisterId(callerSavedReg)];
  726. interval.AddRange(operationPos + 1, operationPos + InstructionGap);
  727. mask &= ~(1 << regIndex);
  728. }
  729. }
  730. private static int GetOperandId(Operand operand)
  731. {
  732. if (operand.Kind == OperandKind.LocalVariable)
  733. {
  734. return operand.AsInt32();
  735. }
  736. else if (operand.Kind == OperandKind.Register)
  737. {
  738. return GetRegisterId(operand.GetRegister());
  739. }
  740. else
  741. {
  742. throw new ArgumentException($"Invalid operand kind \"{operand.Kind}\".");
  743. }
  744. }
  745. private static int GetRegisterId(Register register)
  746. {
  747. return (register.Index << 1) | (register.Type == RegisterType.Vector ? 1 : 0);
  748. }
  749. private static IEnumerable<BasicBlock> Successors(BasicBlock block)
  750. {
  751. if (block.Next != null)
  752. {
  753. yield return block.Next;
  754. }
  755. if (block.Branch != null)
  756. {
  757. yield return block.Branch;
  758. }
  759. }
  760. private static IEnumerable<Node> BottomOperations(BasicBlock block)
  761. {
  762. Node node = block.Operations.Last;
  763. while (node != null && !(node is PhiNode))
  764. {
  765. yield return node;
  766. node = node.ListPrevious;
  767. }
  768. }
  769. private static IEnumerable<Operand> Destinations(Node node)
  770. {
  771. for (int index = 0; index < node.DestinationsCount; index++)
  772. {
  773. yield return node.GetDestination(index);
  774. }
  775. }
  776. private static IEnumerable<Operand> Sources(Node node)
  777. {
  778. for (int index = 0; index < node.SourcesCount; index++)
  779. {
  780. Operand source = node.GetSource(index);
  781. if (IsLocalOrRegister(source.Kind))
  782. {
  783. yield return source;
  784. }
  785. }
  786. }
  787. private static bool IsLocalOrRegister(OperandKind kind)
  788. {
  789. return kind == OperandKind.LocalVariable ||
  790. kind == OperandKind.Register;
  791. }
  792. }
  793. }