LinearScanAllocator.cs 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. else if (source.Kind == OperandKind.Memory)
  554. {
  555. MemoryOperand memOp = (MemoryOperand)source;
  556. if (memOp.BaseAddress == current.Local)
  557. {
  558. memOp.BaseAddress = register;
  559. }
  560. if (memOp.Index == current.Local)
  561. {
  562. memOp.Index = register;
  563. }
  564. }
  565. }
  566. for (int index = 0; index < operation.DestinationsCount; index++)
  567. {
  568. Operand dest = operation.GetDestination(index);
  569. if (dest == current.Local)
  570. {
  571. operation.SetDestination(index, register);
  572. }
  573. }
  574. }
  575. }
  576. private static Operand GetRegister(LiveInterval interval)
  577. {
  578. Debug.Assert(!interval.IsSpilled, "Spilled intervals are not allowed.");
  579. return new Operand(
  580. interval.Register.Index,
  581. interval.Register.Type,
  582. interval.Local.Type);
  583. }
  584. private (IntrusiveList<Node>, Node) GetOperationNode(int position)
  585. {
  586. return _operationNodes[position / InstructionGap];
  587. }
  588. private void NumberLocals(ControlFlowGraph cfg)
  589. {
  590. _operationNodes = new List<(IntrusiveList<Node>, Node)>();
  591. _intervals = new List<LiveInterval>();
  592. for (int index = 0; index < RegistersCount; index++)
  593. {
  594. _intervals.Add(new LiveInterval(new Register(index, RegisterType.Integer)));
  595. _intervals.Add(new LiveInterval(new Register(index, RegisterType.Vector)));
  596. }
  597. HashSet<Operand> visited = new HashSet<Operand>();
  598. _operationsCount = 0;
  599. for (int index = cfg.PostOrderBlocks.Length - 1; index >= 0; index--)
  600. {
  601. BasicBlock block = cfg.PostOrderBlocks[index];
  602. for (Node node = block.Operations.First; node != null; node = node.ListNext)
  603. {
  604. _operationNodes.Add((block.Operations, node));
  605. foreach (Operand dest in Destinations(node))
  606. {
  607. if (dest.Kind == OperandKind.LocalVariable && visited.Add(dest))
  608. {
  609. dest.NumberLocal(_intervals.Count);
  610. _intervals.Add(new LiveInterval(dest));
  611. }
  612. }
  613. }
  614. _operationsCount += block.Operations.Count * InstructionGap;
  615. if (block.Operations.Count == 0)
  616. {
  617. // Pretend we have a dummy instruction on the empty block.
  618. _operationNodes.Add((null, null));
  619. _operationsCount += InstructionGap;
  620. }
  621. }
  622. _parentIntervals = _intervals.ToArray();
  623. }
  624. private void BuildIntervals(ControlFlowGraph cfg, AllocationContext context)
  625. {
  626. _blockRanges = new LiveRange[cfg.Blocks.Count];
  627. int mapSize = _intervals.Count;
  628. BitMap[] blkLiveGen = new BitMap[cfg.Blocks.Count];
  629. BitMap[] blkLiveKill = new BitMap[cfg.Blocks.Count];
  630. // Compute local live sets.
  631. for (BasicBlock block = cfg.Blocks.First; block != null; block = block.ListNext)
  632. {
  633. BitMap liveGen = new BitMap(mapSize);
  634. BitMap liveKill = new BitMap(mapSize);
  635. for (Node node = block.Operations.First; node != null; node = node.ListNext)
  636. {
  637. foreach (Operand source in Sources(node))
  638. {
  639. int id = GetOperandId(source);
  640. if (!liveKill.IsSet(id))
  641. {
  642. liveGen.Set(id);
  643. }
  644. }
  645. foreach (Operand dest in Destinations(node))
  646. {
  647. liveKill.Set(GetOperandId(dest));
  648. }
  649. }
  650. blkLiveGen [block.Index] = liveGen;
  651. blkLiveKill[block.Index] = liveKill;
  652. }
  653. // Compute global live sets.
  654. BitMap[] blkLiveIn = new BitMap[cfg.Blocks.Count];
  655. BitMap[] blkLiveOut = new BitMap[cfg.Blocks.Count];
  656. for (int index = 0; index < cfg.Blocks.Count; index++)
  657. {
  658. blkLiveIn [index] = new BitMap(mapSize);
  659. blkLiveOut[index] = new BitMap(mapSize);
  660. }
  661. bool modified;
  662. do
  663. {
  664. modified = false;
  665. for (int index = 0; index < cfg.PostOrderBlocks.Length; index++)
  666. {
  667. BasicBlock block = cfg.PostOrderBlocks[index];
  668. BitMap liveOut = blkLiveOut[block.Index];
  669. foreach (BasicBlock successor in Successors(block))
  670. {
  671. if (liveOut.Set(blkLiveIn[successor.Index]))
  672. {
  673. modified = true;
  674. }
  675. }
  676. BitMap liveIn = blkLiveIn[block.Index];
  677. liveIn.Set (liveOut);
  678. liveIn.Clear(blkLiveKill[block.Index]);
  679. liveIn.Set (blkLiveGen [block.Index]);
  680. }
  681. }
  682. while (modified);
  683. _blockLiveIn = blkLiveIn;
  684. _blockEdges = new HashSet<int>();
  685. // Compute lifetime intervals.
  686. int operationPos = _operationsCount;
  687. for (int index = 0; index < cfg.PostOrderBlocks.Length; index++)
  688. {
  689. BasicBlock block = cfg.PostOrderBlocks[index];
  690. // We handle empty blocks by pretending they have a dummy instruction,
  691. // because otherwise the block would have the same start and end position,
  692. // and this is not valid.
  693. int instCount = Math.Max(block.Operations.Count, 1);
  694. int blockStart = operationPos - instCount * InstructionGap;
  695. int blockEnd = operationPos;
  696. _blockRanges[block.Index] = new LiveRange(blockStart, blockEnd);
  697. _blockEdges.Add(blockStart);
  698. BitMap liveOut = blkLiveOut[block.Index];
  699. foreach (int id in liveOut)
  700. {
  701. _intervals[id].AddRange(blockStart, blockEnd);
  702. }
  703. if (block.Operations.Count == 0)
  704. {
  705. operationPos -= InstructionGap;
  706. continue;
  707. }
  708. foreach (Node node in BottomOperations(block))
  709. {
  710. operationPos -= InstructionGap;
  711. foreach (Operand dest in Destinations(node))
  712. {
  713. LiveInterval interval = _intervals[GetOperandId(dest)];
  714. interval.SetStart(operationPos + 1);
  715. interval.AddUsePosition(operationPos + 1);
  716. }
  717. foreach (Operand source in Sources(node))
  718. {
  719. LiveInterval interval = _intervals[GetOperandId(source)];
  720. interval.AddRange(blockStart, operationPos + 1);
  721. interval.AddUsePosition(operationPos);
  722. }
  723. if (node is Operation operation && operation.Instruction == Instruction.Call)
  724. {
  725. AddIntervalCallerSavedReg(context.Masks.IntCallerSavedRegisters, operationPos, RegisterType.Integer);
  726. AddIntervalCallerSavedReg(context.Masks.VecCallerSavedRegisters, operationPos, RegisterType.Vector);
  727. }
  728. }
  729. }
  730. }
  731. private void AddIntervalCallerSavedReg(int mask, int operationPos, RegisterType regType)
  732. {
  733. while (mask != 0)
  734. {
  735. int regIndex = BitUtils.LowestBitSet(mask);
  736. Register callerSavedReg = new Register(regIndex, regType);
  737. LiveInterval interval = _intervals[GetRegisterId(callerSavedReg)];
  738. interval.AddRange(operationPos + 1, operationPos + InstructionGap);
  739. mask &= ~(1 << regIndex);
  740. }
  741. }
  742. private static int GetOperandId(Operand operand)
  743. {
  744. if (operand.Kind == OperandKind.LocalVariable)
  745. {
  746. return operand.AsInt32();
  747. }
  748. else if (operand.Kind == OperandKind.Register)
  749. {
  750. return GetRegisterId(operand.GetRegister());
  751. }
  752. else
  753. {
  754. throw new ArgumentException($"Invalid operand kind \"{operand.Kind}\".");
  755. }
  756. }
  757. private static int GetRegisterId(Register register)
  758. {
  759. return (register.Index << 1) | (register.Type == RegisterType.Vector ? 1 : 0);
  760. }
  761. private static IEnumerable<BasicBlock> Successors(BasicBlock block)
  762. {
  763. if (block.Next != null)
  764. {
  765. yield return block.Next;
  766. }
  767. if (block.Branch != null)
  768. {
  769. yield return block.Branch;
  770. }
  771. }
  772. private static IEnumerable<Node> BottomOperations(BasicBlock block)
  773. {
  774. Node node = block.Operations.Last;
  775. while (node != null && !(node is PhiNode))
  776. {
  777. yield return node;
  778. node = node.ListPrevious;
  779. }
  780. }
  781. private static IEnumerable<Operand> Destinations(Node node)
  782. {
  783. for (int index = 0; index < node.DestinationsCount; index++)
  784. {
  785. yield return node.GetDestination(index);
  786. }
  787. }
  788. private static IEnumerable<Operand> Sources(Node node)
  789. {
  790. for (int index = 0; index < node.SourcesCount; index++)
  791. {
  792. Operand source = node.GetSource(index);
  793. if (IsLocalOrRegister(source.Kind))
  794. {
  795. yield return source;
  796. }
  797. else if (source.Kind == OperandKind.Memory)
  798. {
  799. MemoryOperand memOp = (MemoryOperand)source;
  800. if (memOp.BaseAddress != null)
  801. {
  802. yield return memOp.BaseAddress;
  803. }
  804. if (memOp.Index != null)
  805. {
  806. yield return memOp.Index;
  807. }
  808. }
  809. }
  810. }
  811. private static bool IsLocalOrRegister(OperandKind kind)
  812. {
  813. return kind == OperandKind.LocalVariable ||
  814. kind == OperandKind.Register;
  815. }
  816. }
  817. }