LinearScanAllocator.cs 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019
  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<LinkedListNode<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. LinkedListNode<Node> node = GetOperationNode(splitPosition);
  455. Operation[] sequence = copyResolver.Sequence();
  456. node = node.List.AddBefore(node, sequence[0]);
  457. for (int index = 1; index < sequence.Length; index++)
  458. {
  459. node = node.List.AddAfter(node, sequence[index]);
  460. }
  461. }
  462. }
  463. private void InsertSplitCopiesAtEdges(ControlFlowGraph cfg)
  464. {
  465. int blocksCount = cfg.Blocks.Count;
  466. bool IsSplitEdgeBlock(BasicBlock block)
  467. {
  468. return block.Index >= blocksCount;
  469. }
  470. for (LinkedListNode<BasicBlock> node = cfg.Blocks.First; node != null; node = node.Next)
  471. {
  472. BasicBlock block = node.Value;
  473. if (IsSplitEdgeBlock(block))
  474. {
  475. continue;
  476. }
  477. bool hasSingleOrNoSuccessor = block.Next == null || block.Branch == null;
  478. foreach (BasicBlock successor in Successors(block))
  479. {
  480. int succIndex = successor.Index;
  481. // If the current node is a split node, then the actual successor node
  482. // (the successor before the split) should be right after it.
  483. if (IsSplitEdgeBlock(successor))
  484. {
  485. succIndex = Successors(successor).First().Index;
  486. }
  487. CopyResolver copyResolver = new CopyResolver();
  488. foreach (int iIndex in _blockLiveIn[succIndex])
  489. {
  490. LiveInterval interval = _parentIntervals[iIndex];
  491. if (!interval.IsSplit)
  492. {
  493. continue;
  494. }
  495. int lEnd = _blockRanges[block.Index].End - 1;
  496. int rStart = _blockRanges[succIndex].Start;
  497. LiveInterval left = interval.GetSplitChild(lEnd);
  498. LiveInterval right = interval.GetSplitChild(rStart);
  499. if (left != null && right != null && left != right)
  500. {
  501. copyResolver.AddSplit(left, right);
  502. }
  503. }
  504. if (!copyResolver.HasCopy)
  505. {
  506. continue;
  507. }
  508. Operation[] sequence = copyResolver.Sequence();
  509. if (hasSingleOrNoSuccessor)
  510. {
  511. foreach (Operation operation in sequence)
  512. {
  513. block.Append(operation);
  514. }
  515. }
  516. else if (successor.Predecessors.Count == 1)
  517. {
  518. LinkedListNode<Node> prependNode = successor.Operations.AddFirst(sequence[0]);
  519. for (int index = 1; index < sequence.Length; index++)
  520. {
  521. Operation operation = sequence[index];
  522. prependNode = successor.Operations.AddAfter(prependNode, operation);
  523. }
  524. }
  525. else
  526. {
  527. // Split the critical edge.
  528. BasicBlock splitBlock = cfg.SplitEdge(block, successor);
  529. foreach (Operation operation in sequence)
  530. {
  531. splitBlock.Append(operation);
  532. }
  533. }
  534. }
  535. }
  536. }
  537. private void ReplaceLocalWithRegister(LiveInterval current)
  538. {
  539. Operand register = GetRegister(current);
  540. foreach (int usePosition in current.UsePositions())
  541. {
  542. Node operation = GetOperationNode(usePosition).Value;
  543. for (int index = 0; index < operation.SourcesCount; index++)
  544. {
  545. Operand source = operation.GetSource(index);
  546. if (source == current.Local)
  547. {
  548. operation.SetSource(index, register);
  549. }
  550. }
  551. for (int index = 0; index < operation.DestinationsCount; index++)
  552. {
  553. Operand dest = operation.GetDestination(index);
  554. if (dest == current.Local)
  555. {
  556. operation.SetDestination(index, register);
  557. }
  558. }
  559. }
  560. }
  561. private static Operand GetRegister(LiveInterval interval)
  562. {
  563. Debug.Assert(!interval.IsSpilled, "Spilled intervals are not allowed.");
  564. return new Operand(
  565. interval.Register.Index,
  566. interval.Register.Type,
  567. interval.Local.Type);
  568. }
  569. private LinkedListNode<Node> GetOperationNode(int position)
  570. {
  571. return _operationNodes[position / InstructionGap];
  572. }
  573. private void NumberLocals(ControlFlowGraph cfg)
  574. {
  575. _operationNodes = new List<LinkedListNode<Node>>();
  576. _intervals = new List<LiveInterval>();
  577. for (int index = 0; index < RegistersCount; index++)
  578. {
  579. _intervals.Add(new LiveInterval(new Register(index, RegisterType.Integer)));
  580. _intervals.Add(new LiveInterval(new Register(index, RegisterType.Vector)));
  581. }
  582. HashSet<Operand> visited = new HashSet<Operand>();
  583. _operationsCount = 0;
  584. for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--)
  585. {
  586. BasicBlock block = cfg.PostOrderBlocks[index];
  587. for (LinkedListNode<Node> node = block.Operations.First; node != null; node = node.Next)
  588. {
  589. _operationNodes.Add(node);
  590. Node operation = node.Value;
  591. foreach (Operand dest in Destinations(operation))
  592. {
  593. if (dest.Kind == OperandKind.LocalVariable && visited.Add(dest))
  594. {
  595. dest.NumberLocal(_intervals.Count);
  596. _intervals.Add(new LiveInterval(dest));
  597. }
  598. }
  599. }
  600. _operationsCount += block.Operations.Count * InstructionGap;
  601. if (block.Operations.Count == 0)
  602. {
  603. // Pretend we have a dummy instruction on the empty block.
  604. _operationNodes.Add(null);
  605. _operationsCount += InstructionGap;
  606. }
  607. }
  608. _parentIntervals = _intervals.ToArray();
  609. }
  610. private void BuildIntervals(ControlFlowGraph cfg, AllocationContext context)
  611. {
  612. _blockRanges = new LiveRange[cfg.Blocks.Count];
  613. int mapSize = _intervals.Count;
  614. BitMap[] blkLiveGen = new BitMap[cfg.Blocks.Count];
  615. BitMap[] blkLiveKill = new BitMap[cfg.Blocks.Count];
  616. // Compute local live sets.
  617. foreach (BasicBlock block in cfg.Blocks)
  618. {
  619. BitMap liveGen = new BitMap(mapSize);
  620. BitMap liveKill = new BitMap(mapSize);
  621. foreach (Node node in block.Operations)
  622. {
  623. foreach (Operand source in Sources(node))
  624. {
  625. int id = GetOperandId(source);
  626. if (!liveKill.IsSet(id))
  627. {
  628. liveGen.Set(id);
  629. }
  630. }
  631. foreach (Operand dest in Destinations(node))
  632. {
  633. liveKill.Set(GetOperandId(dest));
  634. }
  635. }
  636. blkLiveGen [block.Index] = liveGen;
  637. blkLiveKill[block.Index] = liveKill;
  638. }
  639. // Compute global live sets.
  640. BitMap[] blkLiveIn = new BitMap[cfg.Blocks.Count];
  641. BitMap[] blkLiveOut = new BitMap[cfg.Blocks.Count];
  642. for (int index = 0; index < cfg.Blocks.Count; index++)
  643. {
  644. blkLiveIn [index] = new BitMap(mapSize);
  645. blkLiveOut[index] = new BitMap(mapSize);
  646. }
  647. bool modified;
  648. do
  649. {
  650. modified = false;
  651. for (int index = 0; index < cfg.PostOrderBlocks.Length; index++)
  652. {
  653. BasicBlock block = cfg.PostOrderBlocks[index];
  654. BitMap liveOut = blkLiveOut[block.Index];
  655. foreach (BasicBlock successor in Successors(block))
  656. {
  657. if (liveOut.Set(blkLiveIn[successor.Index]))
  658. {
  659. modified = true;
  660. }
  661. }
  662. BitMap liveIn = blkLiveIn[block.Index];
  663. liveIn.Set (liveOut);
  664. liveIn.Clear(blkLiveKill[block.Index]);
  665. liveIn.Set (blkLiveGen [block.Index]);
  666. }
  667. }
  668. while (modified);
  669. _blockLiveIn = blkLiveIn;
  670. _blockEdges = new HashSet<int>();
  671. // Compute lifetime intervals.
  672. int operationPos = _operationsCount;
  673. for (int index = 0; index < cfg.PostOrderBlocks.Length; index++)
  674. {
  675. BasicBlock block = cfg.PostOrderBlocks[index];
  676. // We handle empty blocks by pretending they have a dummy instruction,
  677. // because otherwise the block would have the same start and end position,
  678. // and this is not valid.
  679. int instCount = Math.Max(block.Operations.Count, 1);
  680. int blockStart = operationPos - instCount * InstructionGap;
  681. int blockEnd = operationPos;
  682. _blockRanges[block.Index] = new LiveRange(blockStart, blockEnd);
  683. _blockEdges.Add(blockStart);
  684. BitMap liveOut = blkLiveOut[block.Index];
  685. foreach (int id in liveOut)
  686. {
  687. _intervals[id].AddRange(blockStart, blockEnd);
  688. }
  689. if (block.Operations.Count == 0)
  690. {
  691. operationPos -= InstructionGap;
  692. continue;
  693. }
  694. foreach (Node node in BottomOperations(block))
  695. {
  696. operationPos -= InstructionGap;
  697. foreach (Operand dest in Destinations(node))
  698. {
  699. LiveInterval interval = _intervals[GetOperandId(dest)];
  700. interval.SetStart(operationPos + 1);
  701. interval.AddUsePosition(operationPos + 1);
  702. }
  703. foreach (Operand source in Sources(node))
  704. {
  705. LiveInterval interval = _intervals[GetOperandId(source)];
  706. interval.AddRange(blockStart, operationPos + 1);
  707. interval.AddUsePosition(operationPos);
  708. }
  709. if (node is Operation operation && operation.Instruction == Instruction.Call)
  710. {
  711. AddIntervalCallerSavedReg(context.Masks.IntCallerSavedRegisters, operationPos, RegisterType.Integer);
  712. AddIntervalCallerSavedReg(context.Masks.VecCallerSavedRegisters, operationPos, RegisterType.Vector);
  713. }
  714. }
  715. }
  716. }
  717. private void AddIntervalCallerSavedReg(int mask, int operationPos, RegisterType regType)
  718. {
  719. while (mask != 0)
  720. {
  721. int regIndex = BitUtils.LowestBitSet(mask);
  722. Register callerSavedReg = new Register(regIndex, regType);
  723. LiveInterval interval = _intervals[GetRegisterId(callerSavedReg)];
  724. interval.AddRange(operationPos + 1, operationPos + InstructionGap);
  725. mask &= ~(1 << regIndex);
  726. }
  727. }
  728. private static int GetOperandId(Operand operand)
  729. {
  730. if (operand.Kind == OperandKind.LocalVariable)
  731. {
  732. return operand.AsInt32();
  733. }
  734. else if (operand.Kind == OperandKind.Register)
  735. {
  736. return GetRegisterId(operand.GetRegister());
  737. }
  738. else
  739. {
  740. throw new ArgumentException($"Invalid operand kind \"{operand.Kind}\".");
  741. }
  742. }
  743. private static int GetRegisterId(Register register)
  744. {
  745. return (register.Index << 1) | (register.Type == RegisterType.Vector ? 1 : 0);
  746. }
  747. private static IEnumerable<BasicBlock> Successors(BasicBlock block)
  748. {
  749. if (block.Next != null)
  750. {
  751. yield return block.Next;
  752. }
  753. if (block.Branch != null)
  754. {
  755. yield return block.Branch;
  756. }
  757. }
  758. private static IEnumerable<Node> BottomOperations(BasicBlock block)
  759. {
  760. LinkedListNode<Node> node = block.Operations.Last;
  761. while (node != null && !(node.Value is PhiNode))
  762. {
  763. yield return node.Value;
  764. node = node.Previous;
  765. }
  766. }
  767. private static IEnumerable<Operand> Destinations(Node node)
  768. {
  769. for (int index = 0; index < node.DestinationsCount; index++)
  770. {
  771. yield return node.GetDestination(index);
  772. }
  773. }
  774. private static IEnumerable<Operand> Sources(Node node)
  775. {
  776. for (int index = 0; index < node.SourcesCount; index++)
  777. {
  778. Operand source = node.GetSource(index);
  779. if (IsLocalOrRegister(source.Kind))
  780. {
  781. yield return source;
  782. }
  783. }
  784. }
  785. private static bool IsLocalOrRegister(OperandKind kind)
  786. {
  787. return kind == OperandKind.LocalVariable ||
  788. kind == OperandKind.Register;
  789. }
  790. }
  791. }