LLVM  10.0.0
LiveIntervals.cpp
Go to the documentation of this file.
1 //===- LiveIntervals.cpp - Live Interval Analysis -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 /// \file This file implements the LiveInterval analysis pass which is used
10 /// by the Linear Scan Register allocator. This pass linearizes the
11 /// basic blocks of the function in DFS order and computes live intervals for
12 /// each virtual and physical register.
13 //
14 //===----------------------------------------------------------------------===//
15 
17 #include "llvm/ADT/ArrayRef.h"
19 #include "llvm/ADT/SmallPtrSet.h"
20 #include "llvm/ADT/SmallVector.h"
34 #include "llvm/CodeGen/Passes.h"
39 #include "llvm/Config/llvm-config.h"
40 #include "llvm/MC/LaneBitmask.h"
41 #include "llvm/MC/MCRegisterInfo.h"
42 #include "llvm/Pass.h"
45 #include "llvm/Support/Compiler.h"
46 #include "llvm/Support/Debug.h"
49 #include <algorithm>
50 #include <cassert>
51 #include <cstdint>
52 #include <iterator>
53 #include <tuple>
54 #include <utility>
55 
56 using namespace llvm;
57 
58 #define DEBUG_TYPE "regalloc"
59 
60 char LiveIntervals::ID = 0;
62 INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals",
63  "Live Interval Analysis", false, false)
68  "Live Interval Analysis", false, false)
69 
70 #ifndef NDEBUG
72  "precompute-phys-liveness", cl::Hidden,
73  cl::desc("Eagerly compute live intervals for all physreg units."));
74 #else
75 static bool EnablePrecomputePhysRegs = false;
76 #endif // NDEBUG
77 
78 namespace llvm {
79 
81  "use-segment-set-for-physregs", cl::Hidden, cl::init(true),
82  cl::desc(
83  "Use segment set for the computation of the live ranges of physregs."));
84 
85 } // end namespace llvm
86 
88  AU.setPreservesCFG();
98 }
99 
102 }
103 
105  delete LRCalc;
106 }
107 
109  // Free the live intervals themselves.
110  for (unsigned i = 0, e = VirtRegIntervals.size(); i != e; ++i)
111  delete VirtRegIntervals[Register::index2VirtReg(i)];
112  VirtRegIntervals.clear();
113  RegMaskSlots.clear();
114  RegMaskBits.clear();
115  RegMaskBlocks.clear();
116 
117  for (LiveRange *LR : RegUnitRanges)
118  delete LR;
119  RegUnitRanges.clear();
120 
121  // Release VNInfo memory regions, VNInfo objects don't need to be dtor'd.
122  VNInfoAllocator.Reset();
123 }
124 
126  MF = &fn;
127  MRI = &MF->getRegInfo();
128  TRI = MF->getSubtarget().getRegisterInfo();
129  TII = MF->getSubtarget().getInstrInfo();
130  AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
131  Indexes = &getAnalysis<SlotIndexes>();
132  DomTree = &getAnalysis<MachineDominatorTree>();
133 
134  if (!LRCalc)
135  LRCalc = new LiveRangeCalc();
136 
137  // Allocate space for all virtual registers.
138  VirtRegIntervals.resize(MRI->getNumVirtRegs());
139 
140  computeVirtRegs();
141  computeRegMasks();
142  computeLiveInRegUnits();
143 
144  if (EnablePrecomputePhysRegs) {
145  // For stress testing, precompute live ranges of all physical register
146  // units, including reserved registers.
147  for (unsigned i = 0, e = TRI->getNumRegUnits(); i != e; ++i)
148  getRegUnit(i);
149  }
150  LLVM_DEBUG(dump());
151  return true;
152 }
153 
154 void LiveIntervals::print(raw_ostream &OS, const Module* ) const {
155  OS << "********** INTERVALS **********\n";
156 
157  // Dump the regunits.
158  for (unsigned Unit = 0, UnitE = RegUnitRanges.size(); Unit != UnitE; ++Unit)
159  if (LiveRange *LR = RegUnitRanges[Unit])
160  OS << printRegUnit(Unit, TRI) << ' ' << *LR << '\n';
161 
162  // Dump the virtregs.
163  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
164  unsigned Reg = Register::index2VirtReg(i);
165  if (hasInterval(Reg))
166  OS << getInterval(Reg) << '\n';
167  }
168 
169  OS << "RegMasks:";
170  for (SlotIndex Idx : RegMaskSlots)
171  OS << ' ' << Idx;
172  OS << '\n';
173 
174  printInstrs(OS);
175 }
176 
177 void LiveIntervals::printInstrs(raw_ostream &OS) const {
178  OS << "********** MACHINEINSTRS **********\n";
179  MF->print(OS, Indexes);
180 }
181 
182 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
183 LLVM_DUMP_METHOD void LiveIntervals::dumpInstrs() const {
184  printInstrs(dbgs());
185 }
186 #endif
187 
188 LiveInterval* LiveIntervals::createInterval(unsigned reg) {
189  float Weight = Register::isPhysicalRegister(reg) ? huge_valf : 0.0F;
190  return new LiveInterval(reg, Weight);
191 }
192 
193 /// Compute the live interval of a virtual register, based on defs and uses.
194 bool LiveIntervals::computeVirtRegInterval(LiveInterval &LI) {
195  assert(LRCalc && "LRCalc not initialized.");
196  assert(LI.empty() && "Should only compute empty intervals.");
197  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
198  LRCalc->calculate(LI, MRI->shouldTrackSubRegLiveness(LI.reg));
199  return computeDeadValues(LI, nullptr);
200 }
201 
202 void LiveIntervals::computeVirtRegs() {
203  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
204  unsigned Reg = Register::index2VirtReg(i);
205  if (MRI->reg_nodbg_empty(Reg))
206  continue;
208  bool NeedSplit = computeVirtRegInterval(LI);
209  if (NeedSplit) {
211  splitSeparateComponents(LI, SplitLIs);
212  }
213  }
214 }
215 
216 void LiveIntervals::computeRegMasks() {
217  RegMaskBlocks.resize(MF->getNumBlockIDs());
218 
219  // Find all instructions with regmask operands.
220  for (const MachineBasicBlock &MBB : *MF) {
221  std::pair<unsigned, unsigned> &RMB = RegMaskBlocks[MBB.getNumber()];
222  RMB.first = RegMaskSlots.size();
223 
224  // Some block starts, such as EH funclets, create masks.
225  if (const uint32_t *Mask = MBB.getBeginClobberMask(TRI)) {
226  RegMaskSlots.push_back(Indexes->getMBBStartIdx(&MBB));
227  RegMaskBits.push_back(Mask);
228  }
229 
230  for (const MachineInstr &MI : MBB) {
231  for (const MachineOperand &MO : MI.operands()) {
232  if (!MO.isRegMask())
233  continue;
234  RegMaskSlots.push_back(Indexes->getInstructionIndex(MI).getRegSlot());
235  RegMaskBits.push_back(MO.getRegMask());
236  }
237  }
238 
239  // Some block ends, such as funclet returns, create masks. Put the mask on
240  // the last instruction of the block, because MBB slot index intervals are
241  // half-open.
242  if (const uint32_t *Mask = MBB.getEndClobberMask(TRI)) {
243  assert(!MBB.empty() && "empty return block?");
244  RegMaskSlots.push_back(
245  Indexes->getInstructionIndex(MBB.back()).getRegSlot());
246  RegMaskBits.push_back(Mask);
247  }
248 
249  // Compute the number of register mask instructions in this block.
250  RMB.second = RegMaskSlots.size() - RMB.first;
251  }
252 }
253 
254 //===----------------------------------------------------------------------===//
255 // Register Unit Liveness
256 //===----------------------------------------------------------------------===//
257 //
258 // Fixed interference typically comes from ABI boundaries: Function arguments
259 // and return values are passed in fixed registers, and so are exception
260 // pointers entering landing pads. Certain instructions require values to be
261 // present in specific registers. That is also represented through fixed
262 // interference.
263 //
264 
265 /// Compute the live range of a register unit, based on the uses and defs of
266 /// aliasing registers. The range should be empty, or contain only dead
267 /// phi-defs from ABI blocks.
268 void LiveIntervals::computeRegUnitRange(LiveRange &LR, unsigned Unit) {
269  assert(LRCalc && "LRCalc not initialized.");
270  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
271 
272  // The physregs aliasing Unit are the roots and their super-registers.
273  // Create all values as dead defs before extending to uses. Note that roots
274  // may share super-registers. That's OK because createDeadDefs() is
275  // idempotent. It is very rare for a register unit to have multiple roots, so
276  // uniquing super-registers is probably not worthwhile.
277  bool IsReserved = false;
278  for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
279  bool IsRootReserved = true;
280  for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
281  Super.isValid(); ++Super) {
282  unsigned Reg = *Super;
283  if (!MRI->reg_empty(Reg))
284  LRCalc->createDeadDefs(LR, Reg);
285  // A register unit is considered reserved if all its roots and all their
286  // super registers are reserved.
287  if (!MRI->isReserved(Reg))
288  IsRootReserved = false;
289  }
290  IsReserved |= IsRootReserved;
291  }
292  assert(IsReserved == MRI->isReservedRegUnit(Unit) &&
293  "reserved computation mismatch");
294 
295  // Now extend LR to reach all uses.
296  // Ignore uses of reserved registers. We only track defs of those.
297  if (!IsReserved) {
298  for (MCRegUnitRootIterator Root(Unit, TRI); Root.isValid(); ++Root) {
299  for (MCSuperRegIterator Super(*Root, TRI, /*IncludeSelf=*/true);
300  Super.isValid(); ++Super) {
301  unsigned Reg = *Super;
302  if (!MRI->reg_empty(Reg))
303  LRCalc->extendToUses(LR, Reg);
304  }
305  }
306  }
307 
308  // Flush the segment set to the segment vector.
310  LR.flushSegmentSet();
311 }
312 
313 /// Precompute the live ranges of any register units that are live-in to an ABI
314 /// block somewhere. Register values can appear without a corresponding def when
315 /// entering the entry block or a landing pad.
316 void LiveIntervals::computeLiveInRegUnits() {
317  RegUnitRanges.resize(TRI->getNumRegUnits());
318  LLVM_DEBUG(dbgs() << "Computing live-in reg-units in ABI blocks.\n");
319 
320  // Keep track of the live range sets allocated.
321  SmallVector<unsigned, 8> NewRanges;
322 
323  // Check all basic blocks for live-ins.
324  for (const MachineBasicBlock &MBB : *MF) {
325  // We only care about ABI blocks: Entry + landing pads.
326  if ((&MBB != &MF->front() && !MBB.isEHPad()) || MBB.livein_empty())
327  continue;
328 
329  // Create phi-defs at Begin for all live-in registers.
330  SlotIndex Begin = Indexes->getMBBStartIdx(&MBB);
331  LLVM_DEBUG(dbgs() << Begin << "\t" << printMBBReference(MBB));
332  for (const auto &LI : MBB.liveins()) {
333  for (MCRegUnitIterator Units(LI.PhysReg, TRI); Units.isValid(); ++Units) {
334  unsigned Unit = *Units;
335  LiveRange *LR = RegUnitRanges[Unit];
336  if (!LR) {
337  // Use segment set to speed-up initial computation of the live range.
338  LR = RegUnitRanges[Unit] = new LiveRange(UseSegmentSetForPhysRegs);
339  NewRanges.push_back(Unit);
340  }
341  VNInfo *VNI = LR->createDeadDef(Begin, getVNInfoAllocator());
342  (void)VNI;
343  LLVM_DEBUG(dbgs() << ' ' << printRegUnit(Unit, TRI) << '#' << VNI->id);
344  }
345  }
346  LLVM_DEBUG(dbgs() << '\n');
347  }
348  LLVM_DEBUG(dbgs() << "Created " << NewRanges.size() << " new intervals.\n");
349 
350  // Compute the 'normal' part of the ranges.
351  for (unsigned Unit : NewRanges)
352  computeRegUnitRange(*RegUnitRanges[Unit], Unit);
353 }
354 
357  for (VNInfo *VNI : VNIs) {
358  if (VNI->isUnused())
359  continue;
360  SlotIndex Def = VNI->def;
361  LR.addSegment(LiveRange::Segment(Def, Def.getDeadSlot(), VNI));
362  }
363 }
364 
365 void LiveIntervals::extendSegmentsToUses(LiveRange &Segments,
366  ShrinkToUsesWorkList &WorkList,
367  unsigned Reg, LaneBitmask LaneMask) {
368  // Keep track of the PHIs that are in use.
369  SmallPtrSet<VNInfo*, 8> UsedPHIs;
370  // Blocks that have already been added to WorkList as live-out.
372 
373  auto getSubRange = [](const LiveInterval &I, LaneBitmask M)
374  -> const LiveRange& {
375  if (M.none())
376  return I;
377  for (const LiveInterval::SubRange &SR : I.subranges()) {
378  if ((SR.LaneMask & M).any()) {
379  assert(SR.LaneMask == M && "Expecting lane masks to match exactly");
380  return SR;
381  }
382  }
383  llvm_unreachable("Subrange for mask not found");
384  };
385 
386  const LiveInterval &LI = getInterval(Reg);
387  const LiveRange &OldRange = getSubRange(LI, LaneMask);
388 
389  // Extend intervals to reach all uses in WorkList.
390  while (!WorkList.empty()) {
391  SlotIndex Idx = WorkList.back().first;
392  VNInfo *VNI = WorkList.back().second;
393  WorkList.pop_back();
394  const MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Idx.getPrevSlot());
395  SlotIndex BlockStart = Indexes->getMBBStartIdx(MBB);
396 
397  // Extend the live range for VNI to be live at Idx.
398  if (VNInfo *ExtVNI = Segments.extendInBlock(BlockStart, Idx)) {
399  assert(ExtVNI == VNI && "Unexpected existing value number");
400  (void)ExtVNI;
401  // Is this a PHIDef we haven't seen before?
402  if (!VNI->isPHIDef() || VNI->def != BlockStart ||
403  !UsedPHIs.insert(VNI).second)
404  continue;
405  // The PHI is live, make sure the predecessors are live-out.
406  for (const MachineBasicBlock *Pred : MBB->predecessors()) {
407  if (!LiveOut.insert(Pred).second)
408  continue;
409  SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
410  // A predecessor is not required to have a live-out value for a PHI.
411  if (VNInfo *PVNI = OldRange.getVNInfoBefore(Stop))
412  WorkList.push_back(std::make_pair(Stop, PVNI));
413  }
414  continue;
415  }
416 
417  // VNI is live-in to MBB.
418  LLVM_DEBUG(dbgs() << " live-in at " << BlockStart << '\n');
419  Segments.addSegment(LiveRange::Segment(BlockStart, Idx, VNI));
420 
421  // Make sure VNI is live-out from the predecessors.
422  for (const MachineBasicBlock *Pred : MBB->predecessors()) {
423  if (!LiveOut.insert(Pred).second)
424  continue;
425  SlotIndex Stop = Indexes->getMBBEndIdx(Pred);
426  if (VNInfo *OldVNI = OldRange.getVNInfoBefore(Stop)) {
427  assert(OldVNI == VNI && "Wrong value out of predecessor");
428  (void)OldVNI;
429  WorkList.push_back(std::make_pair(Stop, VNI));
430  } else {
431 #ifndef NDEBUG
432  // There was no old VNI. Verify that Stop is jointly dominated
433  // by <undef>s for this live range.
434  assert(LaneMask.any() &&
435  "Missing value out of predecessor for main range");
437  LI.computeSubRangeUndefs(Undefs, LaneMask, *MRI, *Indexes);
438  assert(LiveRangeCalc::isJointlyDominated(Pred, Undefs, *Indexes) &&
439  "Missing value out of predecessor for subrange");
440 #endif
441  }
442  }
443  }
444 }
445 
448  LLVM_DEBUG(dbgs() << "Shrink: " << *li << '\n');
450  "Can only shrink virtual registers");
451 
452  // Shrink subregister live ranges.
453  bool NeedsCleanup = false;
454  for (LiveInterval::SubRange &S : li->subranges()) {
455  shrinkToUses(S, li->reg);
456  if (S.empty())
457  NeedsCleanup = true;
458  }
459  if (NeedsCleanup)
460  li->removeEmptySubRanges();
461 
462  // Find all the values used, including PHI kills.
463  ShrinkToUsesWorkList WorkList;
464 
465  // Visit all instructions reading li->reg.
466  unsigned Reg = li->reg;
467  for (MachineInstr &UseMI : MRI->reg_instructions(Reg)) {
468  if (UseMI.isDebugValue() || !UseMI.readsVirtualRegister(Reg))
469  continue;
471  LiveQueryResult LRQ = li->Query(Idx);
472  VNInfo *VNI = LRQ.valueIn();
473  if (!VNI) {
474  // This shouldn't happen: readsVirtualRegister returns true, but there is
475  // no live value. It is likely caused by a target getting <undef> flags
476  // wrong.
477  LLVM_DEBUG(
478  dbgs() << Idx << '\t' << UseMI
479  << "Warning: Instr claims to read non-existent value in "
480  << *li << '\n');
481  continue;
482  }
483  // Special case: An early-clobber tied operand reads and writes the
484  // register one slot early.
485  if (VNInfo *DefVNI = LRQ.valueDefined())
486  Idx = DefVNI->def;
487 
488  WorkList.push_back(std::make_pair(Idx, VNI));
489  }
490 
491  // Create new live ranges with only minimal live segments per def.
492  LiveRange NewLR;
493  createSegmentsForValues(NewLR, make_range(li->vni_begin(), li->vni_end()));
494  extendSegmentsToUses(NewLR, WorkList, Reg, LaneBitmask::getNone());
495 
496  // Move the trimmed segments back.
497  li->segments.swap(NewLR.segments);
498 
499  // Handle dead values.
500  bool CanSeparate = computeDeadValues(*li, dead);
501  LLVM_DEBUG(dbgs() << "Shrunk: " << *li << '\n');
502  return CanSeparate;
503 }
504 
505 bool LiveIntervals::computeDeadValues(LiveInterval &LI,
507  bool MayHaveSplitComponents = false;
508  bool HaveDeadDef = false;
509 
510  for (VNInfo *VNI : LI.valnos) {
511  if (VNI->isUnused())
512  continue;
513  SlotIndex Def = VNI->def;
515  assert(I != LI.end() && "Missing segment for VNI");
516 
517  // Is the register live before? Otherwise we may have to add a read-undef
518  // flag for subregister defs.
519  unsigned VReg = LI.reg;
520  if (MRI->shouldTrackSubRegLiveness(VReg)) {
521  if ((I == LI.begin() || std::prev(I)->end < Def) && !VNI->isPHIDef()) {
523  MI->setRegisterDefReadUndef(VReg);
524  }
525  }
526 
527  if (I->end != Def.getDeadSlot())
528  continue;
529  if (VNI->isPHIDef()) {
530  // This is a dead PHI. Remove it.
531  VNI->markUnused();
532  LI.removeSegment(I);
533  LLVM_DEBUG(dbgs() << "Dead PHI at " << Def << " may separate interval\n");
534  MayHaveSplitComponents = true;
535  } else {
536  // This is a dead def. Make sure the instruction knows.
538  assert(MI && "No instruction defining live value");
539  MI->addRegisterDead(LI.reg, TRI);
540  if (HaveDeadDef)
541  MayHaveSplitComponents = true;
542  HaveDeadDef = true;
543 
544  if (dead && MI->allDefsAreDead()) {
545  LLVM_DEBUG(dbgs() << "All defs dead: " << Def << '\t' << *MI);
546  dead->push_back(MI);
547  }
548  }
549  }
550  return MayHaveSplitComponents;
551 }
552 
554  LLVM_DEBUG(dbgs() << "Shrink: " << SR << '\n');
556  "Can only shrink virtual registers");
557  // Find all the values used, including PHI kills.
558  ShrinkToUsesWorkList WorkList;
559 
560  // Visit all instructions reading Reg.
561  SlotIndex LastIdx;
562  for (MachineOperand &MO : MRI->use_nodbg_operands(Reg)) {
563  // Skip "undef" uses.
564  if (!MO.readsReg())
565  continue;
566  // Maybe the operand is for a subregister we don't care about.
567  unsigned SubReg = MO.getSubReg();
568  if (SubReg != 0) {
569  LaneBitmask LaneMask = TRI->getSubRegIndexLaneMask(SubReg);
570  if ((LaneMask & SR.LaneMask).none())
571  continue;
572  }
573  // We only need to visit each instruction once.
574  MachineInstr *UseMI = MO.getParent();
575  SlotIndex Idx = getInstructionIndex(*UseMI).getRegSlot();
576  if (Idx == LastIdx)
577  continue;
578  LastIdx = Idx;
579 
580  LiveQueryResult LRQ = SR.Query(Idx);
581  VNInfo *VNI = LRQ.valueIn();
582  // For Subranges it is possible that only undef values are left in that
583  // part of the subregister, so there is no real liverange at the use
584  if (!VNI)
585  continue;
586 
587  // Special case: An early-clobber tied operand reads and writes the
588  // register one slot early.
589  if (VNInfo *DefVNI = LRQ.valueDefined())
590  Idx = DefVNI->def;
591 
592  WorkList.push_back(std::make_pair(Idx, VNI));
593  }
594 
595  // Create a new live ranges with only minimal live segments per def.
596  LiveRange NewLR;
598  extendSegmentsToUses(NewLR, WorkList, Reg, SR.LaneMask);
599 
600  // Move the trimmed ranges back.
601  SR.segments.swap(NewLR.segments);
602 
603  // Remove dead PHI value numbers
604  for (VNInfo *VNI : SR.valnos) {
605  if (VNI->isUnused())
606  continue;
607  const LiveRange::Segment *Segment = SR.getSegmentContaining(VNI->def);
608  assert(Segment != nullptr && "Missing segment for VNI");
609  if (Segment->end != VNI->def.getDeadSlot())
610  continue;
611  if (VNI->isPHIDef()) {
612  // This is a dead PHI. Remove it.
613  LLVM_DEBUG(dbgs() << "Dead PHI at " << VNI->def
614  << " may separate interval\n");
615  VNI->markUnused();
616  SR.removeSegment(*Segment);
617  }
618  }
619 
620  LLVM_DEBUG(dbgs() << "Shrunk: " << SR << '\n');
621 }
622 
624  ArrayRef<SlotIndex> Indices,
625  ArrayRef<SlotIndex> Undefs) {
626  assert(LRCalc && "LRCalc not initialized.");
627  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
628  for (SlotIndex Idx : Indices)
629  LRCalc->extend(LR, Idx, /*PhysReg=*/0, Undefs);
630 }
631 
633  SmallVectorImpl<SlotIndex> *EndPoints) {
634  LiveQueryResult LRQ = LR.Query(Kill);
635  VNInfo *VNI = LRQ.valueOutOrDead();
636  if (!VNI)
637  return;
638 
639  MachineBasicBlock *KillMBB = Indexes->getMBBFromIndex(Kill);
640  SlotIndex MBBEnd = Indexes->getMBBEndIdx(KillMBB);
641 
642  // If VNI isn't live out from KillMBB, the value is trivially pruned.
643  if (LRQ.endPoint() < MBBEnd) {
644  LR.removeSegment(Kill, LRQ.endPoint());
645  if (EndPoints) EndPoints->push_back(LRQ.endPoint());
646  return;
647  }
648 
649  // VNI is live out of KillMBB.
650  LR.removeSegment(Kill, MBBEnd);
651  if (EndPoints) EndPoints->push_back(MBBEnd);
652 
653  // Find all blocks that are reachable from KillMBB without leaving VNI's live
654  // range. It is possible that KillMBB itself is reachable, so start a DFS
655  // from each successor.
657  VisitedTy Visited;
658  for (MachineBasicBlock *Succ : KillMBB->successors()) {
660  I = df_ext_begin(Succ, Visited), E = df_ext_end(Succ, Visited);
661  I != E;) {
662  MachineBasicBlock *MBB = *I;
663 
664  // Check if VNI is live in to MBB.
665  SlotIndex MBBStart, MBBEnd;
666  std::tie(MBBStart, MBBEnd) = Indexes->getMBBRange(MBB);
667  LiveQueryResult LRQ = LR.Query(MBBStart);
668  if (LRQ.valueIn() != VNI) {
669  // This block isn't part of the VNI segment. Prune the search.
670  I.skipChildren();
671  continue;
672  }
673 
674  // Prune the search if VNI is killed in MBB.
675  if (LRQ.endPoint() < MBBEnd) {
676  LR.removeSegment(MBBStart, LRQ.endPoint());
677  if (EndPoints) EndPoints->push_back(LRQ.endPoint());
678  I.skipChildren();
679  continue;
680  }
681 
682  // VNI is live through MBB.
683  LR.removeSegment(MBBStart, MBBEnd);
684  if (EndPoints) EndPoints->push_back(MBBEnd);
685  ++I;
686  }
687  }
688 }
689 
690 //===----------------------------------------------------------------------===//
691 // Register allocator hooks.
692 //
693 
695  // Keep track of regunit ranges.
697  // Keep track of subregister ranges.
698  SmallVector<std::pair<const LiveInterval::SubRange*,
699  LiveRange::const_iterator>, 4> SRs;
700 
701  for (unsigned i = 0, e = MRI->getNumVirtRegs(); i != e; ++i) {
702  unsigned Reg = Register::index2VirtReg(i);
703  if (MRI->reg_nodbg_empty(Reg))
704  continue;
705  const LiveInterval &LI = getInterval(Reg);
706  if (LI.empty())
707  continue;
708 
709  // Find the regunit intervals for the assigned register. They may overlap
710  // the virtual register live range, cancelling any kills.
711  RU.clear();
712  for (MCRegUnitIterator Unit(VRM->getPhys(Reg), TRI); Unit.isValid();
713  ++Unit) {
714  const LiveRange &RURange = getRegUnit(*Unit);
715  if (RURange.empty())
716  continue;
717  RU.push_back(std::make_pair(&RURange, RURange.find(LI.begin()->end)));
718  }
719 
720  if (MRI->subRegLivenessEnabled()) {
721  SRs.clear();
722  for (const LiveInterval::SubRange &SR : LI.subranges()) {
723  SRs.push_back(std::make_pair(&SR, SR.find(LI.begin()->end)));
724  }
725  }
726 
727  // Every instruction that kills Reg corresponds to a segment range end
728  // point.
729  for (LiveInterval::const_iterator RI = LI.begin(), RE = LI.end(); RI != RE;
730  ++RI) {
731  // A block index indicates an MBB edge.
732  if (RI->end.isBlock())
733  continue;
735  if (!MI)
736  continue;
737 
738  // Check if any of the regunits are live beyond the end of RI. That could
739  // happen when a physreg is defined as a copy of a virtreg:
740  //
741  // %eax = COPY %5
742  // FOO %5 <--- MI, cancel kill because %eax is live.
743  // BAR killed %eax
744  //
745  // There should be no kill flag on FOO when %5 is rewritten as %eax.
746  for (auto &RUP : RU) {
747  const LiveRange &RURange = *RUP.first;
748  LiveRange::const_iterator &I = RUP.second;
749  if (I == RURange.end())
750  continue;
751  I = RURange.advanceTo(I, RI->end);
752  if (I == RURange.end() || I->start >= RI->end)
753  continue;
754  // I is overlapping RI.
755  goto CancelKill;
756  }
757 
758  if (MRI->subRegLivenessEnabled()) {
759  // When reading a partial undefined value we must not add a kill flag.
760  // The regalloc might have used the undef lane for something else.
761  // Example:
762  // %1 = ... ; R32: %1
763  // %2:high16 = ... ; R64: %2
764  // = read killed %2 ; R64: %2
765  // = read %1 ; R32: %1
766  // The <kill> flag is correct for %2, but the register allocator may
767  // assign R0L to %1, and R0 to %2 because the low 32bits of R0
768  // are actually never written by %2. After assignment the <kill>
769  // flag at the read instruction is invalid.
770  LaneBitmask DefinedLanesMask;
771  if (!SRs.empty()) {
772  // Compute a mask of lanes that are defined.
773  DefinedLanesMask = LaneBitmask::getNone();
774  for (auto &SRP : SRs) {
775  const LiveInterval::SubRange &SR = *SRP.first;
776  LiveRange::const_iterator &I = SRP.second;
777  if (I == SR.end())
778  continue;
779  I = SR.advanceTo(I, RI->end);
780  if (I == SR.end() || I->start >= RI->end)
781  continue;
782  // I is overlapping RI
783  DefinedLanesMask |= SR.LaneMask;
784  }
785  } else
786  DefinedLanesMask = LaneBitmask::getAll();
787 
788  bool IsFullWrite = false;
789  for (const MachineOperand &MO : MI->operands()) {
790  if (!MO.isReg() || MO.getReg() != Reg)
791  continue;
792  if (MO.isUse()) {
793  // Reading any undefined lanes?
794  LaneBitmask UseMask = TRI->getSubRegIndexLaneMask(MO.getSubReg());
795  if ((UseMask & ~DefinedLanesMask).any())
796  goto CancelKill;
797  } else if (MO.getSubReg() == 0) {
798  // Writing to the full register?
799  assert(MO.isDef());
800  IsFullWrite = true;
801  }
802  }
803 
804  // If an instruction writes to a subregister, a new segment starts in
805  // the LiveInterval. But as this is only overriding part of the register
806  // adding kill-flags is not correct here after registers have been
807  // assigned.
808  if (!IsFullWrite) {
809  // Next segment has to be adjacent in the subregister write case.
810  LiveRange::const_iterator N = std::next(RI);
811  if (N != LI.end() && N->start == RI->end)
812  goto CancelKill;
813  }
814  }
815 
816  MI->addRegisterKilled(Reg, nullptr);
817  continue;
818 CancelKill:
819  MI->clearRegisterKills(Reg, nullptr);
820  }
821  }
822 }
823 
826  // A local live range must be fully contained inside the block, meaning it is
827  // defined and killed at instructions, not at block boundaries. It is not
828  // live in or out of any block.
829  //
830  // It is technically possible to have a PHI-defined live range identical to a
831  // single block, but we are going to return false in that case.
832 
833  SlotIndex Start = LI.beginIndex();
834  if (Start.isBlock())
835  return nullptr;
836 
837  SlotIndex Stop = LI.endIndex();
838  if (Stop.isBlock())
839  return nullptr;
840 
841  // getMBBFromIndex doesn't need to search the MBB table when both indexes
842  // belong to proper instructions.
843  MachineBasicBlock *MBB1 = Indexes->getMBBFromIndex(Start);
844  MachineBasicBlock *MBB2 = Indexes->getMBBFromIndex(Stop);
845  return MBB1 == MBB2 ? MBB1 : nullptr;
846 }
847 
848 bool
849 LiveIntervals::hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const {
850  for (const VNInfo *PHI : LI.valnos) {
851  if (PHI->isUnused() || !PHI->isPHIDef())
852  continue;
853  const MachineBasicBlock *PHIMBB = getMBBFromIndex(PHI->def);
854  // Conservatively return true instead of scanning huge predecessor lists.
855  if (PHIMBB->pred_size() > 100)
856  return true;
857  for (const MachineBasicBlock *Pred : PHIMBB->predecessors())
858  if (VNI == LI.getVNInfoBefore(Indexes->getMBBEndIdx(Pred)))
859  return true;
860  }
861  return false;
862 }
863 
864 float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
865  const MachineBlockFrequencyInfo *MBFI,
866  const MachineInstr &MI) {
867  return getSpillWeight(isDef, isUse, MBFI, MI.getParent());
868 }
869 
870 float LiveIntervals::getSpillWeight(bool isDef, bool isUse,
871  const MachineBlockFrequencyInfo *MBFI,
872  const MachineBasicBlock *MBB) {
873  BlockFrequency Freq = MBFI->getBlockFreq(MBB);
874  const float Scale = 1.0f / MBFI->getEntryFreq();
875  return (isDef + isUse) * (Freq.getFrequency() * Scale);
876 }
877 
881  VNInfo *VN = Interval.getNextValue(
882  SlotIndex(getInstructionIndex(startInst).getRegSlot()),
884  LiveRange::Segment S(SlotIndex(getInstructionIndex(startInst).getRegSlot()),
885  getMBBEndIdx(startInst.getParent()), VN);
886  Interval.addSegment(S);
887 
888  return S;
889 }
890 
891 //===----------------------------------------------------------------------===//
892 // Register mask functions
893 //===----------------------------------------------------------------------===//
894 
896  BitVector &UsableRegs) {
897  if (LI.empty())
898  return false;
899  LiveInterval::iterator LiveI = LI.begin(), LiveE = LI.end();
900 
901  // Use a smaller arrays for local live ranges.
902  ArrayRef<SlotIndex> Slots;
904  if (MachineBasicBlock *MBB = intervalIsInOneMBB(LI)) {
905  Slots = getRegMaskSlotsInBlock(MBB->getNumber());
906  Bits = getRegMaskBitsInBlock(MBB->getNumber());
907  } else {
908  Slots = getRegMaskSlots();
909  Bits = getRegMaskBits();
910  }
911 
912  // We are going to enumerate all the register mask slots contained in LI.
913  // Start with a binary search of RegMaskSlots to find a starting point.
914  ArrayRef<SlotIndex>::iterator SlotI = llvm::lower_bound(Slots, LiveI->start);
915  ArrayRef<SlotIndex>::iterator SlotE = Slots.end();
916 
917  // No slots in range, LI begins after the last call.
918  if (SlotI == SlotE)
919  return false;
920 
921  bool Found = false;
922  while (true) {
923  assert(*SlotI >= LiveI->start);
924  // Loop over all slots overlapping this segment.
925  while (*SlotI < LiveI->end) {
926  // *SlotI overlaps LI. Collect mask bits.
927  if (!Found) {
928  // This is the first overlap. Initialize UsableRegs to all ones.
929  UsableRegs.clear();
930  UsableRegs.resize(TRI->getNumRegs(), true);
931  Found = true;
932  }
933  // Remove usable registers clobbered by this mask.
934  UsableRegs.clearBitsNotInMask(Bits[SlotI-Slots.begin()]);
935  if (++SlotI == SlotE)
936  return Found;
937  }
938  // *SlotI is beyond the current LI segment.
939  LiveI = LI.advanceTo(LiveI, *SlotI);
940  if (LiveI == LiveE)
941  return Found;
942  // Advance SlotI until it overlaps.
943  while (*SlotI < LiveI->start)
944  if (++SlotI == SlotE)
945  return Found;
946  }
947 }
948 
949 //===----------------------------------------------------------------------===//
950 // IntervalUpdate class.
951 //===----------------------------------------------------------------------===//
952 
953 /// Toolkit used by handleMove to trim or extend live intervals.
955 private:
956  LiveIntervals& LIS;
957  const MachineRegisterInfo& MRI;
958  const TargetRegisterInfo& TRI;
959  SlotIndex OldIdx;
960  SlotIndex NewIdx;
962  bool UpdateFlags;
963 
964 public:
965  HMEditor(LiveIntervals& LIS, const MachineRegisterInfo& MRI,
966  const TargetRegisterInfo& TRI,
967  SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
968  : LIS(LIS), MRI(MRI), TRI(TRI), OldIdx(OldIdx), NewIdx(NewIdx),
969  UpdateFlags(UpdateFlags) {}
970 
971  // FIXME: UpdateFlags is a workaround that creates live intervals for all
972  // physregs, even those that aren't needed for regalloc, in order to update
973  // kill flags. This is wasteful. Eventually, LiveVariables will strip all kill
974  // flags, and postRA passes will use a live register utility instead.
975  LiveRange *getRegUnitLI(unsigned Unit) {
976  if (UpdateFlags && !MRI.isReservedRegUnit(Unit))
977  return &LIS.getRegUnit(Unit);
978  return LIS.getCachedRegUnit(Unit);
979  }
980 
981  /// Update all live ranges touched by MI, assuming a move from OldIdx to
982  /// NewIdx.
984  LLVM_DEBUG(dbgs() << "handleMove " << OldIdx << " -> " << NewIdx << ": "
985  << *MI);
986  bool hasRegMask = false;
987  for (MachineOperand &MO : MI->operands()) {
988  if (MO.isRegMask())
989  hasRegMask = true;
990  if (!MO.isReg())
991  continue;
992  if (MO.isUse()) {
993  if (!MO.readsReg())
994  continue;
995  // Aggressively clear all kill flags.
996  // They are reinserted by VirtRegRewriter.
997  MO.setIsKill(false);
998  }
999 
1000  Register Reg = MO.getReg();
1001  if (!Reg)
1002  continue;
1003  if (Register::isVirtualRegister(Reg)) {
1004  LiveInterval &LI = LIS.getInterval(Reg);
1005  if (LI.hasSubRanges()) {
1006  unsigned SubReg = MO.getSubReg();
1007  LaneBitmask LaneMask = SubReg ? TRI.getSubRegIndexLaneMask(SubReg)
1008  : MRI.getMaxLaneMaskForVReg(Reg);
1009  for (LiveInterval::SubRange &S : LI.subranges()) {
1010  if ((S.LaneMask & LaneMask).none())
1011  continue;
1012  updateRange(S, Reg, S.LaneMask);
1013  }
1014  }
1015  updateRange(LI, Reg, LaneBitmask::getNone());
1016  continue;
1017  }
1018 
1019  // For physregs, only update the regunits that actually have a
1020  // precomputed live range.
1021  for (MCRegUnitIterator Units(Reg, &TRI); Units.isValid(); ++Units)
1022  if (LiveRange *LR = getRegUnitLI(*Units))
1023  updateRange(*LR, *Units, LaneBitmask::getNone());
1024  }
1025  if (hasRegMask)
1026  updateRegMaskSlots();
1027  }
1028 
1029 private:
1030  /// Update a single live range, assuming an instruction has been moved from
1031  /// OldIdx to NewIdx.
1032  void updateRange(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1033  if (!Updated.insert(&LR).second)
1034  return;
1035  LLVM_DEBUG({
1036  dbgs() << " ";
1037  if (Register::isVirtualRegister(Reg)) {
1038  dbgs() << printReg(Reg);
1039  if (LaneMask.any())
1040  dbgs() << " L" << PrintLaneMask(LaneMask);
1041  } else {
1042  dbgs() << printRegUnit(Reg, &TRI);
1043  }
1044  dbgs() << ":\t" << LR << '\n';
1045  });
1046  if (SlotIndex::isEarlierInstr(OldIdx, NewIdx))
1047  handleMoveDown(LR);
1048  else
1049  handleMoveUp(LR, Reg, LaneMask);
1050  LLVM_DEBUG(dbgs() << " -->\t" << LR << '\n');
1051  LR.verify();
1052  }
1053 
1054  /// Update LR to reflect an instruction has been moved downwards from OldIdx
1055  /// to NewIdx (OldIdx < NewIdx).
1056  void handleMoveDown(LiveRange &LR) {
1057  LiveRange::iterator E = LR.end();
1058  // Segment going into OldIdx.
1059  LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1060 
1061  // No value live before or after OldIdx? Nothing to do.
1062  if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1063  return;
1064 
1065  LiveRange::iterator OldIdxOut;
1066  // Do we have a value live-in to OldIdx?
1067  if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1068  // If the live-in value already extends to NewIdx, there is nothing to do.
1069  if (SlotIndex::isEarlierEqualInstr(NewIdx, OldIdxIn->end))
1070  return;
1071  // Aggressively remove all kill flags from the old kill point.
1072  // Kill flags shouldn't be used while live intervals exist, they will be
1073  // reinserted by VirtRegRewriter.
1074  if (MachineInstr *KillMI = LIS.getInstructionFromIndex(OldIdxIn->end))
1075  for (MachineOperand &MOP : mi_bundle_ops(*KillMI))
1076  if (MOP.isReg() && MOP.isUse())
1077  MOP.setIsKill(false);
1078 
1079  // Is there a def before NewIdx which is not OldIdx?
1080  LiveRange::iterator Next = std::next(OldIdxIn);
1081  if (Next != E && !SlotIndex::isSameInstr(OldIdx, Next->start) &&
1082  SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1083  // If we are here then OldIdx was just a use but not a def. We only have
1084  // to ensure liveness extends to NewIdx.
1085  LiveRange::iterator NewIdxIn =
1086  LR.advanceTo(Next, NewIdx.getBaseIndex());
1087  // Extend the segment before NewIdx if necessary.
1088  if (NewIdxIn == E ||
1089  !SlotIndex::isEarlierInstr(NewIdxIn->start, NewIdx)) {
1090  LiveRange::iterator Prev = std::prev(NewIdxIn);
1091  Prev->end = NewIdx.getRegSlot();
1092  }
1093  // Extend OldIdxIn.
1094  OldIdxIn->end = Next->start;
1095  return;
1096  }
1097 
1098  // Adjust OldIdxIn->end to reach NewIdx. This may temporarily make LR
1099  // invalid by overlapping ranges.
1100  bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1101  OldIdxIn->end = NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber());
1102  // If this was not a kill, then there was no def and we're done.
1103  if (!isKill)
1104  return;
1105 
1106  // Did we have a Def at OldIdx?
1107  OldIdxOut = Next;
1108  if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1109  return;
1110  } else {
1111  OldIdxOut = OldIdxIn;
1112  }
1113 
1114  // If we are here then there is a Definition at OldIdx. OldIdxOut points
1115  // to the segment starting there.
1116  assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1117  "No def?");
1118  VNInfo *OldIdxVNI = OldIdxOut->valno;
1119  assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1120 
1121  // If the defined value extends beyond NewIdx, just move the beginning
1122  // of the segment to NewIdx.
1123  SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1124  if (SlotIndex::isEarlierInstr(NewIdxDef, OldIdxOut->end)) {
1125  OldIdxVNI->def = NewIdxDef;
1126  OldIdxOut->start = OldIdxVNI->def;
1127  return;
1128  }
1129 
1130  // If we are here then we have a Definition at OldIdx which ends before
1131  // NewIdx.
1132 
1133  // Is there an existing Def at NewIdx?
1134  LiveRange::iterator AfterNewIdx
1135  = LR.advanceTo(OldIdxOut, NewIdx.getRegSlot());
1136  bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1137  if (!OldIdxDefIsDead &&
1138  SlotIndex::isEarlierInstr(OldIdxOut->end, NewIdxDef)) {
1139  // OldIdx is not a dead def, and NewIdxDef is inside a new interval.
1140  VNInfo *DefVNI;
1141  if (OldIdxOut != LR.begin() &&
1142  !SlotIndex::isEarlierInstr(std::prev(OldIdxOut)->end,
1143  OldIdxOut->start)) {
1144  // There is no gap between OldIdxOut and its predecessor anymore,
1145  // merge them.
1146  LiveRange::iterator IPrev = std::prev(OldIdxOut);
1147  DefVNI = OldIdxVNI;
1148  IPrev->end = OldIdxOut->end;
1149  } else {
1150  // The value is live in to OldIdx
1151  LiveRange::iterator INext = std::next(OldIdxOut);
1152  assert(INext != E && "Must have following segment");
1153  // We merge OldIdxOut and its successor. As we're dealing with subreg
1154  // reordering, there is always a successor to OldIdxOut in the same BB
1155  // We don't need INext->valno anymore and will reuse for the new segment
1156  // we create later.
1157  DefVNI = OldIdxVNI;
1158  INext->start = OldIdxOut->end;
1159  INext->valno->def = INext->start;
1160  }
1161  // If NewIdx is behind the last segment, extend that and append a new one.
1162  if (AfterNewIdx == E) {
1163  // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1164  // one position.
1165  // |- ?/OldIdxOut -| |- X0 -| ... |- Xn -| end
1166  // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS -| end
1167  std::copy(std::next(OldIdxOut), E, OldIdxOut);
1168  // The last segment is undefined now, reuse it for a dead def.
1169  LiveRange::iterator NewSegment = std::prev(E);
1170  *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1171  DefVNI);
1172  DefVNI->def = NewIdxDef;
1173 
1174  LiveRange::iterator Prev = std::prev(NewSegment);
1175  Prev->end = NewIdxDef;
1176  } else {
1177  // OldIdxOut is undef at this point, Slide (OldIdxOut;AfterNewIdx] up
1178  // one position.
1179  // |- ?/OldIdxOut -| |- X0 -| ... |- Xn/AfterNewIdx -| |- Next -|
1180  // => |- X0/OldIdxOut -| ... |- Xn -| |- Xn/AfterNewIdx -| |- Next -|
1181  std::copy(std::next(OldIdxOut), std::next(AfterNewIdx), OldIdxOut);
1182  LiveRange::iterator Prev = std::prev(AfterNewIdx);
1183  // We have two cases:
1184  if (SlotIndex::isEarlierInstr(Prev->start, NewIdxDef)) {
1185  // Case 1: NewIdx is inside a liverange. Split this liverange at
1186  // NewIdxDef into the segment "Prev" followed by "NewSegment".
1187  LiveRange::iterator NewSegment = AfterNewIdx;
1188  *NewSegment = LiveRange::Segment(NewIdxDef, Prev->end, Prev->valno);
1189  Prev->valno->def = NewIdxDef;
1190 
1191  *Prev = LiveRange::Segment(Prev->start, NewIdxDef, DefVNI);
1192  DefVNI->def = Prev->start;
1193  } else {
1194  // Case 2: NewIdx is in a lifetime hole. Keep AfterNewIdx as is and
1195  // turn Prev into a segment from NewIdx to AfterNewIdx->start.
1196  *Prev = LiveRange::Segment(NewIdxDef, AfterNewIdx->start, DefVNI);
1197  DefVNI->def = NewIdxDef;
1198  assert(DefVNI != AfterNewIdx->valno);
1199  }
1200  }
1201  return;
1202  }
1203 
1204  if (AfterNewIdx != E &&
1205  SlotIndex::isSameInstr(AfterNewIdx->start, NewIdxDef)) {
1206  // There is an existing def at NewIdx. The def at OldIdx is coalesced into
1207  // that value.
1208  assert(AfterNewIdx->valno != OldIdxVNI && "Multiple defs of value?");
1209  LR.removeValNo(OldIdxVNI);
1210  } else {
1211  // There was no existing def at NewIdx. We need to create a dead def
1212  // at NewIdx. Shift segments over the old OldIdxOut segment, this frees
1213  // a new segment at the place where we want to construct the dead def.
1214  // |- OldIdxOut -| |- X0 -| ... |- Xn -| |- AfterNewIdx -|
1215  // => |- X0/OldIdxOut -| ... |- Xn -| |- undef/NewS. -| |- AfterNewIdx -|
1216  assert(AfterNewIdx != OldIdxOut && "Inconsistent iterators");
1217  std::copy(std::next(OldIdxOut), AfterNewIdx, OldIdxOut);
1218  // We can reuse OldIdxVNI now.
1219  LiveRange::iterator NewSegment = std::prev(AfterNewIdx);
1220  VNInfo *NewSegmentVNI = OldIdxVNI;
1221  NewSegmentVNI->def = NewIdxDef;
1222  *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1223  NewSegmentVNI);
1224  }
1225  }
1226 
1227  /// Update LR to reflect an instruction has been moved upwards from OldIdx
1228  /// to NewIdx (NewIdx < OldIdx).
1229  void handleMoveUp(LiveRange &LR, unsigned Reg, LaneBitmask LaneMask) {
1230  LiveRange::iterator E = LR.end();
1231  // Segment going into OldIdx.
1232  LiveRange::iterator OldIdxIn = LR.find(OldIdx.getBaseIndex());
1233 
1234  // No value live before or after OldIdx? Nothing to do.
1235  if (OldIdxIn == E || SlotIndex::isEarlierInstr(OldIdx, OldIdxIn->start))
1236  return;
1237 
1238  LiveRange::iterator OldIdxOut;
1239  // Do we have a value live-in to OldIdx?
1240  if (SlotIndex::isEarlierInstr(OldIdxIn->start, OldIdx)) {
1241  // If the live-in value isn't killed here, then we have no Def at
1242  // OldIdx, moreover the value must be live at NewIdx so there is nothing
1243  // to do.
1244  bool isKill = SlotIndex::isSameInstr(OldIdx, OldIdxIn->end);
1245  if (!isKill)
1246  return;
1247 
1248  // At this point we have to move OldIdxIn->end back to the nearest
1249  // previous use or (dead-)def but no further than NewIdx.
1250  SlotIndex DefBeforeOldIdx
1251  = std::max(OldIdxIn->start.getDeadSlot(),
1252  NewIdx.getRegSlot(OldIdxIn->end.isEarlyClobber()));
1253  OldIdxIn->end = findLastUseBefore(DefBeforeOldIdx, Reg, LaneMask);
1254 
1255  // Did we have a Def at OldIdx? If not we are done now.
1256  OldIdxOut = std::next(OldIdxIn);
1257  if (OldIdxOut == E || !SlotIndex::isSameInstr(OldIdx, OldIdxOut->start))
1258  return;
1259  } else {
1260  OldIdxOut = OldIdxIn;
1261  OldIdxIn = OldIdxOut != LR.begin() ? std::prev(OldIdxOut) : E;
1262  }
1263 
1264  // If we are here then there is a Definition at OldIdx. OldIdxOut points
1265  // to the segment starting there.
1266  assert(OldIdxOut != E && SlotIndex::isSameInstr(OldIdx, OldIdxOut->start) &&
1267  "No def?");
1268  VNInfo *OldIdxVNI = OldIdxOut->valno;
1269  assert(OldIdxVNI->def == OldIdxOut->start && "Inconsistent def");
1270  bool OldIdxDefIsDead = OldIdxOut->end.isDead();
1271 
1272  // Is there an existing def at NewIdx?
1273  SlotIndex NewIdxDef = NewIdx.getRegSlot(OldIdxOut->start.isEarlyClobber());
1274  LiveRange::iterator NewIdxOut = LR.find(NewIdx.getRegSlot());
1275  if (SlotIndex::isSameInstr(NewIdxOut->start, NewIdx)) {
1276  assert(NewIdxOut->valno != OldIdxVNI &&
1277  "Same value defined more than once?");
1278  // If OldIdx was a dead def remove it.
1279  if (!OldIdxDefIsDead) {
1280  // Remove segment starting at NewIdx and move begin of OldIdxOut to
1281  // NewIdx so it can take its place.
1282  OldIdxVNI->def = NewIdxDef;
1283  OldIdxOut->start = NewIdxDef;
1284  LR.removeValNo(NewIdxOut->valno);
1285  } else {
1286  // Simply remove the dead def at OldIdx.
1287  LR.removeValNo(OldIdxVNI);
1288  }
1289  } else {
1290  // Previously nothing was live after NewIdx, so all we have to do now is
1291  // move the begin of OldIdxOut to NewIdx.
1292  if (!OldIdxDefIsDead) {
1293  // Do we have any intermediate Defs between OldIdx and NewIdx?
1294  if (OldIdxIn != E &&
1295  SlotIndex::isEarlierInstr(NewIdxDef, OldIdxIn->start)) {
1296  // OldIdx is not a dead def and NewIdx is before predecessor start.
1297  LiveRange::iterator NewIdxIn = NewIdxOut;
1298  assert(NewIdxIn == LR.find(NewIdx.getBaseIndex()));
1299  const SlotIndex SplitPos = NewIdxDef;
1300  OldIdxVNI = OldIdxIn->valno;
1301 
1302  SlotIndex NewDefEndPoint = std::next(NewIdxIn)->end;
1303  LiveRange::iterator Prev = std::prev(OldIdxIn);
1304  if (OldIdxIn != LR.begin() &&
1305  SlotIndex::isEarlierInstr(NewIdx, Prev->end)) {
1306  // If the segment before OldIdx read a value defined earlier than
1307  // NewIdx, the moved instruction also reads and forwards that
1308  // value. Extend the lifetime of the new def point.
1309 
1310  // Extend to where the previous range started, unless there is
1311  // another redef first.
1312  NewDefEndPoint = std::min(OldIdxIn->start,
1313  std::next(NewIdxOut)->start);
1314  }
1315 
1316  // Merge the OldIdxIn and OldIdxOut segments into OldIdxOut.
1317  OldIdxOut->valno->def = OldIdxIn->start;
1318  *OldIdxOut = LiveRange::Segment(OldIdxIn->start, OldIdxOut->end,
1319  OldIdxOut->valno);
1320  // OldIdxIn and OldIdxVNI are now undef and can be overridden.
1321  // We Slide [NewIdxIn, OldIdxIn) down one position.
1322  // |- X0/NewIdxIn -| ... |- Xn-1 -||- Xn/OldIdxIn -||- OldIdxOut -|
1323  // => |- undef/NexIdxIn -| |- X0 -| ... |- Xn-1 -| |- Xn/OldIdxOut -|
1324  std::copy_backward(NewIdxIn, OldIdxIn, OldIdxOut);
1325  // NewIdxIn is now considered undef so we can reuse it for the moved
1326  // value.
1327  LiveRange::iterator NewSegment = NewIdxIn;
1328  LiveRange::iterator Next = std::next(NewSegment);
1329  if (SlotIndex::isEarlierInstr(Next->start, NewIdx)) {
1330  // There is no gap between NewSegment and its predecessor.
1331  *NewSegment = LiveRange::Segment(Next->start, SplitPos,
1332  Next->valno);
1333 
1334  *Next = LiveRange::Segment(SplitPos, NewDefEndPoint, OldIdxVNI);
1335  Next->valno->def = SplitPos;
1336  } else {
1337  // There is a gap between NewSegment and its predecessor
1338  // Value becomes live in.
1339  *NewSegment = LiveRange::Segment(SplitPos, Next->start, OldIdxVNI);
1340  NewSegment->valno->def = SplitPos;
1341  }
1342  } else {
1343  // Leave the end point of a live def.
1344  OldIdxOut->start = NewIdxDef;
1345  OldIdxVNI->def = NewIdxDef;
1346  if (OldIdxIn != E && SlotIndex::isEarlierInstr(NewIdx, OldIdxIn->end))
1347  OldIdxIn->end = NewIdx.getRegSlot();
1348  }
1349  } else if (OldIdxIn != E
1350  && SlotIndex::isEarlierInstr(NewIdxOut->start, NewIdx)
1351  && SlotIndex::isEarlierInstr(NewIdx, NewIdxOut->end)) {
1352  // OldIdxVNI is a dead def that has been moved into the middle of
1353  // another value in LR. That can happen when LR is a whole register,
1354  // but the dead def is a write to a subreg that is dead at NewIdx.
1355  // The dead def may have been moved across other values
1356  // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1357  // down one position.
1358  // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1359  // => |- X0/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1360  std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1361  // Modify the segment at NewIdxOut and the following segment to meet at
1362  // the point of the dead def, with the following segment getting
1363  // OldIdxVNI as its value number.
1364  *NewIdxOut = LiveRange::Segment(
1365  NewIdxOut->start, NewIdxDef.getRegSlot(), NewIdxOut->valno);
1366  *(NewIdxOut + 1) = LiveRange::Segment(
1367  NewIdxDef.getRegSlot(), (NewIdxOut + 1)->end, OldIdxVNI);
1368  OldIdxVNI->def = NewIdxDef;
1369  // Modify subsequent segments to be defined by the moved def OldIdxVNI.
1370  for (auto Idx = NewIdxOut + 2; Idx <= OldIdxOut; ++Idx)
1371  Idx->valno = OldIdxVNI;
1372  // Aggressively remove all dead flags from the former dead definition.
1373  // Kill/dead flags shouldn't be used while live intervals exist; they
1374  // will be reinserted by VirtRegRewriter.
1375  if (MachineInstr *KillMI = LIS.getInstructionFromIndex(NewIdx))
1376  for (MIBundleOperands MO(*KillMI); MO.isValid(); ++MO)
1377  if (MO->isReg() && !MO->isUse())
1378  MO->setIsDead(false);
1379  } else {
1380  // OldIdxVNI is a dead def. It may have been moved across other values
1381  // in LR, so move OldIdxOut up to NewIdxOut. Slide [NewIdxOut;OldIdxOut)
1382  // down one position.
1383  // |- X0/NewIdxOut -| ... |- Xn-1 -| |- Xn/OldIdxOut -| |- next - |
1384  // => |- undef/NewIdxOut -| |- X0 -| ... |- Xn-1 -| |- next -|
1385  std::copy_backward(NewIdxOut, OldIdxOut, std::next(OldIdxOut));
1386  // OldIdxVNI can be reused now to build a new dead def segment.
1387  LiveRange::iterator NewSegment = NewIdxOut;
1388  VNInfo *NewSegmentVNI = OldIdxVNI;
1389  *NewSegment = LiveRange::Segment(NewIdxDef, NewIdxDef.getDeadSlot(),
1390  NewSegmentVNI);
1391  NewSegmentVNI->def = NewIdxDef;
1392  }
1393  }
1394  }
1395 
1396  void updateRegMaskSlots() {
1398  llvm::lower_bound(LIS.RegMaskSlots, OldIdx);
1399  assert(RI != LIS.RegMaskSlots.end() && *RI == OldIdx.getRegSlot() &&
1400  "No RegMask at OldIdx.");
1401  *RI = NewIdx.getRegSlot();
1402  assert((RI == LIS.RegMaskSlots.begin() ||
1403  SlotIndex::isEarlierInstr(*std::prev(RI), *RI)) &&
1404  "Cannot move regmask instruction above another call");
1405  assert((std::next(RI) == LIS.RegMaskSlots.end() ||
1406  SlotIndex::isEarlierInstr(*RI, *std::next(RI))) &&
1407  "Cannot move regmask instruction below another call");
1408  }
1409 
1410  // Return the last use of reg between NewIdx and OldIdx.
1411  SlotIndex findLastUseBefore(SlotIndex Before, unsigned Reg,
1412  LaneBitmask LaneMask) {
1413  if (Register::isVirtualRegister(Reg)) {
1414  SlotIndex LastUse = Before;
1415  for (MachineOperand &MO : MRI.use_nodbg_operands(Reg)) {
1416  if (MO.isUndef())
1417  continue;
1418  unsigned SubReg = MO.getSubReg();
1419  if (SubReg != 0 && LaneMask.any()
1420  && (TRI.getSubRegIndexLaneMask(SubReg) & LaneMask).none())
1421  continue;
1422 
1423  const MachineInstr &MI = *MO.getParent();
1424  SlotIndex InstSlot = LIS.getSlotIndexes()->getInstructionIndex(MI);
1425  if (InstSlot > LastUse && InstSlot < OldIdx)
1426  LastUse = InstSlot.getRegSlot();
1427  }
1428  return LastUse;
1429  }
1430 
1431  // This is a regunit interval, so scanning the use list could be very
1432  // expensive. Scan upwards from OldIdx instead.
1433  assert(Before < OldIdx && "Expected upwards move");
1434  SlotIndexes *Indexes = LIS.getSlotIndexes();
1435  MachineBasicBlock *MBB = Indexes->getMBBFromIndex(Before);
1436 
1437  // OldIdx may not correspond to an instruction any longer, so set MII to
1438  // point to the next instruction after OldIdx, or MBB->end().
1439  MachineBasicBlock::iterator MII = MBB->end();
1440  if (MachineInstr *MI = Indexes->getInstructionFromIndex(
1441  Indexes->getNextNonNullIndex(OldIdx)))
1442  if (MI->getParent() == MBB)
1443  MII = MI;
1444 
1445  MachineBasicBlock::iterator Begin = MBB->begin();
1446  while (MII != Begin) {
1447  if ((--MII)->isDebugInstr())
1448  continue;
1449  SlotIndex Idx = Indexes->getInstructionIndex(*MII);
1450 
1451  // Stop searching when Before is reached.
1452  if (!SlotIndex::isEarlierInstr(Before, Idx))
1453  return Before;
1454 
1455  // Check if MII uses Reg.
1456  for (MIBundleOperands MO(*MII); MO.isValid(); ++MO)
1457  if (MO->isReg() && !MO->isUndef() &&
1458  Register::isPhysicalRegister(MO->getReg()) &&
1459  TRI.hasRegUnit(MO->getReg(), Reg))
1460  return Idx.getRegSlot();
1461  }
1462  // Didn't reach Before. It must be the first instruction in the block.
1463  return Before;
1464  }
1465 };
1466 
1467 void LiveIntervals::handleMove(MachineInstr &MI, bool UpdateFlags) {
1468  // It is fine to move a bundle as a whole, but not an individual instruction
1469  // inside it.
1470  assert((!MI.isBundled() || MI.getOpcode() == TargetOpcode::BUNDLE) &&
1471  "Cannot move instruction in bundle");
1472  SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1473  Indexes->removeMachineInstrFromMaps(MI);
1474  SlotIndex NewIndex = Indexes->insertMachineInstrInMaps(MI);
1475  assert(getMBBStartIdx(MI.getParent()) <= OldIndex &&
1476  OldIndex < getMBBEndIdx(MI.getParent()) &&
1477  "Cannot handle moves across basic block boundaries.");
1478 
1479  HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1480  HME.updateAllRanges(&MI);
1481 }
1482 
1484  MachineInstr &BundleStart,
1485  bool UpdateFlags) {
1486  SlotIndex OldIndex = Indexes->getInstructionIndex(MI);
1487  SlotIndex NewIndex = Indexes->getInstructionIndex(BundleStart);
1488  HMEditor HME(*this, *MRI, *TRI, OldIndex, NewIndex, UpdateFlags);
1489  HME.updateAllRanges(&MI);
1490 }
1491 
1492 void LiveIntervals::repairOldRegInRange(const MachineBasicBlock::iterator Begin,
1493  const MachineBasicBlock::iterator End,
1494  const SlotIndex endIdx,
1495  LiveRange &LR, const unsigned Reg,
1496  LaneBitmask LaneMask) {
1497  LiveInterval::iterator LII = LR.find(endIdx);
1498  SlotIndex lastUseIdx;
1499  if (LII == LR.begin()) {
1500  // This happens when the function is called for a subregister that only
1501  // occurs _after_ the range that is to be repaired.
1502  return;
1503  }
1504  if (LII != LR.end() && LII->start < endIdx)
1505  lastUseIdx = LII->end;
1506  else
1507  --LII;
1508 
1509  for (MachineBasicBlock::iterator I = End; I != Begin;) {
1510  --I;
1511  MachineInstr &MI = *I;
1512  if (MI.isDebugInstr())
1513  continue;
1514 
1515  SlotIndex instrIdx = getInstructionIndex(MI);
1516  bool isStartValid = getInstructionFromIndex(LII->start);
1517  bool isEndValid = getInstructionFromIndex(LII->end);
1518 
1519  // FIXME: This doesn't currently handle early-clobber or multiple removed
1520  // defs inside of the region to repair.
1522  OE = MI.operands_end();
1523  OI != OE; ++OI) {
1524  const MachineOperand &MO = *OI;
1525  if (!MO.isReg() || MO.getReg() != Reg)
1526  continue;
1527 
1528  unsigned SubReg = MO.getSubReg();
1529  LaneBitmask Mask = TRI->getSubRegIndexLaneMask(SubReg);
1530  if ((Mask & LaneMask).none())
1531  continue;
1532 
1533  if (MO.isDef()) {
1534  if (!isStartValid) {
1535  if (LII->end.isDead()) {
1536  SlotIndex prevStart;
1537  if (LII != LR.begin())
1538  prevStart = std::prev(LII)->start;
1539 
1540  // FIXME: This could be more efficient if there was a
1541  // removeSegment method that returned an iterator.
1542  LR.removeSegment(*LII, true);
1543  if (prevStart.isValid())
1544  LII = LR.find(prevStart);
1545  else
1546  LII = LR.begin();
1547  } else {
1548  LII->start = instrIdx.getRegSlot();
1549  LII->valno->def = instrIdx.getRegSlot();
1550  if (MO.getSubReg() && !MO.isUndef())
1551  lastUseIdx = instrIdx.getRegSlot();
1552  else
1553  lastUseIdx = SlotIndex();
1554  continue;
1555  }
1556  }
1557 
1558  if (!lastUseIdx.isValid()) {
1559  VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1560  LiveRange::Segment S(instrIdx.getRegSlot(),
1561  instrIdx.getDeadSlot(), VNI);
1562  LII = LR.addSegment(S);
1563  } else if (LII->start != instrIdx.getRegSlot()) {
1564  VNInfo *VNI = LR.getNextValue(instrIdx.getRegSlot(), VNInfoAllocator);
1565  LiveRange::Segment S(instrIdx.getRegSlot(), lastUseIdx, VNI);
1566  LII = LR.addSegment(S);
1567  }
1568 
1569  if (MO.getSubReg() && !MO.isUndef())
1570  lastUseIdx = instrIdx.getRegSlot();
1571  else
1572  lastUseIdx = SlotIndex();
1573  } else if (MO.isUse()) {
1574  // FIXME: This should probably be handled outside of this branch,
1575  // either as part of the def case (for defs inside of the region) or
1576  // after the loop over the region.
1577  if (!isEndValid && !LII->end.isBlock())
1578  LII->end = instrIdx.getRegSlot();
1579  if (!lastUseIdx.isValid())
1580  lastUseIdx = instrIdx.getRegSlot();
1581  }
1582  }
1583  }
1584 }
1585 
1586 void
1590  ArrayRef<unsigned> OrigRegs) {
1591  // Find anchor points, which are at the beginning/end of blocks or at
1592  // instructions that already have indexes.
1593  while (Begin != MBB->begin() && !Indexes->hasIndex(*Begin))
1594  --Begin;
1595  while (End != MBB->end() && !Indexes->hasIndex(*End))
1596  ++End;
1597 
1598  SlotIndex endIdx;
1599  if (End == MBB->end())
1600  endIdx = getMBBEndIdx(MBB).getPrevSlot();
1601  else
1602  endIdx = getInstructionIndex(*End);
1603 
1604  Indexes->repairIndexesInRange(MBB, Begin, End);
1605 
1606  for (MachineBasicBlock::iterator I = End; I != Begin;) {
1607  --I;
1608  MachineInstr &MI = *I;
1609  if (MI.isDebugInstr())
1610  continue;
1612  MOE = MI.operands_end();
1613  MOI != MOE; ++MOI) {
1614  if (MOI->isReg() && Register::isVirtualRegister(MOI->getReg()) &&
1615  !hasInterval(MOI->getReg())) {
1616  createAndComputeVirtRegInterval(MOI->getReg());
1617  }
1618  }
1619  }
1620 
1621  for (unsigned Reg : OrigRegs) {
1622  if (!Register::isVirtualRegister(Reg))
1623  continue;
1624 
1625  LiveInterval &LI = getInterval(Reg);
1626  // FIXME: Should we support undefs that gain defs?
1627  if (!LI.hasAtLeastOneValue())
1628  continue;
1629 
1630  for (LiveInterval::SubRange &S : LI.subranges())
1631  repairOldRegInRange(Begin, End, endIdx, S, Reg, S.LaneMask);
1632 
1633  repairOldRegInRange(Begin, End, endIdx, LI, Reg);
1634  }
1635 }
1636 
1638  for (MCRegUnitIterator Unit(Reg, TRI); Unit.isValid(); ++Unit) {
1639  if (LiveRange *LR = getCachedRegUnit(*Unit))
1640  if (VNInfo *VNI = LR->getVNInfoAt(Pos))
1641  LR->removeValNo(VNI);
1642  }
1643 }
1644 
1646  // LI may not have the main range computed yet, but its subranges may
1647  // be present.
1648  VNInfo *VNI = LI.getVNInfoAt(Pos);
1649  if (VNI != nullptr) {
1650  assert(VNI->def.getBaseIndex() == Pos.getBaseIndex());
1651  LI.removeValNo(VNI);
1652  }
1653 
1654  // Also remove the value defined in subranges.
1655  for (LiveInterval::SubRange &S : LI.subranges()) {
1656  if (VNInfo *SVNI = S.getVNInfoAt(Pos))
1657  if (SVNI->def.getBaseIndex() == Pos.getBaseIndex())
1658  S.removeValNo(SVNI);
1659  }
1660  LI.removeEmptySubRanges();
1661 }
1662 
1664  SmallVectorImpl<LiveInterval*> &SplitLIs) {
1665  ConnectedVNInfoEqClasses ConEQ(*this);
1666  unsigned NumComp = ConEQ.Classify(LI);
1667  if (NumComp <= 1)
1668  return;
1669  LLVM_DEBUG(dbgs() << " Split " << NumComp << " components: " << LI << '\n');
1670  unsigned Reg = LI.reg;
1671  const TargetRegisterClass *RegClass = MRI->getRegClass(Reg);
1672  for (unsigned I = 1; I < NumComp; ++I) {
1673  Register NewVReg = MRI->createVirtualRegister(RegClass);
1674  LiveInterval &NewLI = createEmptyInterval(NewVReg);
1675  SplitLIs.push_back(&NewLI);
1676  }
1677  ConEQ.Distribute(LI, SplitLIs.data(), *MRI);
1678 }
1679 
1681  assert(LRCalc && "LRCalc not initialized.");
1682  LRCalc->reset(MF, getSlotIndexes(), DomTree, &getVNInfoAllocator());
1683  LRCalc->constructMainRangeFromSubranges(LI);
1684 }
LiveInterval & createEmptyInterval(Register Reg)
Interval creation.
auto lower_bound(R &&Range, T &&Value) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1278
void resize(unsigned N, bool t=false)
resize - Grow or shrink the bitvector.
Definition: BitVector.h:371
liveintervals
LiveInterval & createAndComputeVirtRegInterval(Register Reg)
bool empty() const
Definition: LiveInterval.h:373
bool isPHIDef() const
Returns true if this value is defined by a PHI instruction (or was, PHI instructions may have been el...
Definition: LiveInterval.h:77
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:233
mop_iterator operands_end()
Definition: MachineInstr.h:487
A common definition of LaneBitmask for use in TableGen and CodeGen.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const unsigned reg
Definition: LiveInterval.h:708
bool isReserved(Register PhysReg) const
isReserved - Returns true when PhysReg is a reserved register.
SlotIndex getBaseIndex() const
Returns the base index for associated with this index.
Definition: SlotIndexes.h:241
SlotIndex def
The index of the defining instruction.
Definition: LiveInterval.h:60
void createDeadDefs(LiveRange &LR, unsigned Reg)
createDeadDefs - Create a dead def in LI for every def operand of Reg.
void updateAllRanges(MachineInstr *MI)
Update all live ranges touched by MI, assuming a move from OldIdx to NewIdx.
static float getSpillWeight(bool isDef, bool isUse, const MachineBlockFrequencyInfo *MBFI, const MachineInstr &MI)
Calculate the spill weight to assign to a single instruction.
LaneBitmask getMaxLaneMaskForVReg(unsigned Reg) const
Returns a mask covering all bits that can appear in lane masks of subregisters of the virtual registe...
This class represents lattice values for constants.
Definition: AllocatorList.h:23
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
Definition: Compiler.h:492
bool hasPHIKill(const LiveInterval &LI, const VNInfo *VNI) const
Returns true if VNI is killed by any PHI-def values in LI.
void removePhysRegDefAt(unsigned Reg, SlotIndex Pos)
Remove value numbers and related live segments starting at position Pos that are part of any liverang...
A Module instance is used to store all the information related to an LLVM module. ...
Definition: Module.h:66
iterator begin() const
Definition: ArrayRef.h:146
virtual const TargetRegisterInfo * getRegisterInfo() const
getRegisterInfo - If register information is available, return it.
bool runOnMachineFunction(MachineFunction &) override
Pass entry point; Calculates LiveIntervals.
unsigned getNumBlockIDs() const
getNumBlockIDs - Return the number of MBB ID&#39;s allocated.
Interval Class - An Interval is a set of nodes defined such that every node in the interval has all o...
Definition: Interval.h:36
Segments::iterator iterator
Definition: LiveInterval.h:211
void push_back(const T &Elt)
Definition: SmallVector.h:211
vni_iterator vni_begin()
Definition: LiveInterval.h:223
char & MachineDominatorsID
MachineDominators - This pass is a machine dominators analysis pass.
static bool isPhysicalRegister(unsigned Reg)
Return true if the specified register number is in the physical register namespace.
Definition: Register.h:63
LiveInterval - This class represents the liveness of a register, or stack slot.
Definition: LiveInterval.h:679
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
iterator_range< use_nodbg_iterator > use_nodbg_operands(unsigned Reg) const
MIBundleOperands - Iterate over all operands in a bundle of machine instructions. ...
ArrayRef< const uint32_t * > getRegMaskBits() const
Returns an array of register mask pointers corresponding to getRegMaskSlots().
iterator advanceTo(iterator I, SlotIndex Pos)
advanceTo - Advance the specified iterator to point to the Segment containing the specified position...
Definition: LiveInterval.h:262
unsigned Reg
bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
unsigned getSubReg() const
bool isValid() const
isValid - Returns true until all the operands have been visited.
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
A live range for subregisters.
Definition: LiveInterval.h:686
bool isValid() const
Returns true if this is a valid index.
Definition: SlotIndexes.h:151
This represents a simple continuous liveness interval for a value.
Definition: LiveInterval.h:161
unsigned const TargetRegisterInfo * TRI
Printable PrintLaneMask(LaneBitmask LaneMask)
Create Printable object to print LaneBitmasks on a raw_ostream.
Definition: LaneBitmask.h:93
ArrayRef< SlotIndex > getRegMaskSlots() const
Returns a sorted array of slot indices of all instructions with register mask operands.
void markUnused()
Mark this value as unused.
Definition: LiveInterval.h:83
Printable printReg(Register Reg, const TargetRegisterInfo *TRI=nullptr, unsigned SubIdx=0, const MachineRegisterInfo *MRI=nullptr)
Prints virtual and physical registers with or without a TRI instance.
static unsigned index2VirtReg(unsigned Index)
Convert a 0-based index to a virtual register number.
Definition: Register.h:83
VNInfo - Value Number Information.
Definition: LiveInterval.h:52
void print(raw_ostream &O, const Module *=nullptr) const override
Implement the dump method.
iterator_range< mop_iterator > operands()
Definition: MachineInstr.h:492
bool checkRegMaskInterference(LiveInterval &LI, BitVector &UsableRegs)
Test if LI is live across any register mask instructions, and compute a bit mask of physical register...
void flushSegmentSet()
Flush segment set into the regular segment vector.
unsigned getNumRegUnits() const
Return the number of (native) register units in the target.
ArrayRef< SlotIndex > getRegMaskSlotsInBlock(unsigned MBBNum) const
Returns a sorted array of slot indices of all instructions with register mask operands in the basic b...
void Distribute(LiveInterval &LI, LiveInterval *LIV[], MachineRegisterInfo &MRI)
Distribute values in LI into a separate LiveIntervals for each connected component.
LiveInterval::Segment addSegmentToEndOfBlock(unsigned reg, MachineInstr &startInst)
Given a register and an instruction, adds a live segment from that instruction to the end of its MBB...
iterator_range< succ_iterator > successors()
This class represents the liveness of a register, stack slot, etc.
Definition: LiveInterval.h:156
bool isUnused() const
Returns true if this value is unused.
Definition: LiveInterval.h:80
static bool isEarlierInstr(SlotIndex A, SlotIndex B)
isEarlierInstr - Return true if A refers to an instruction earlier than B.
Definition: SlotIndexes.h:203
void removeEmptySubRanges()
Removes all subranges without any segments (subranges without segments are not considered valid and s...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Definition: PassSupport.h:50
bool isBlock() const
isBlock - Returns true if this is a block boundary slot.
Definition: SlotIndexes.h:226
void pruneValue(LiveRange &LR, SlotIndex Kill, SmallVectorImpl< SlotIndex > *EndPoints)
If LR has a live value at Kill, prune its live range by removing any liveness reachable from Kill...
void clear()
clear - Removes all bits from the bitvector. Does not change capacity.
Definition: BitVector.h:366
void verify() const
Walk the range and assert if any invariants fail to hold.
char & MachineLoopInfoID
MachineLoopInfo - This pass is a loop analysis pass.
MCSuperRegIterator enumerates all super-registers of Reg.
SlotIndex getDeadSlot() const
Returns the dead def kill slot for the current instruction.
Definition: SlotIndexes.h:259
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void Reset()
Deallocate all but the current slab and reset the current pointer to the beginning of it...
Definition: Allocator.h:195
Printable printMBBReference(const MachineBasicBlock &MBB)
Prints a machine basic block reference.
iterator end()
Definition: LiveInterval.h:215
VNInfo::Allocator & getVNInfoAllocator()
iterator_range< subrange_iterator > subranges()
Definition: LiveInterval.h:764
unsigned SubReg
Result of a LiveRange query.
Definition: LiveInterval.h:89
static constexpr LaneBitmask getAll()
Definition: LaneBitmask.h:83
SlotIndex getInstructionIndex(const MachineInstr &MI) const
Returns the base index for the given instruction.
Definition: SlotIndexes.h:385
unsigned getOpcode() const
Returns the opcode of this MachineInstr.
Definition: MachineInstr.h:426
bool hasSubRanges() const
Returns true if subregister liveness information is available.
Definition: LiveInterval.h:792
static constexpr LaneBitmask getNone()
Definition: LaneBitmask.h:82
Printable printRegUnit(unsigned Unit, const TargetRegisterInfo *TRI)
Create Printable object to print register units on a raw_ostream.
SlotIndex getNextNonNullIndex(SlotIndex Index)
Returns the next non-null index, if one exists.
Definition: SlotIndexes.h:407
void extendToIndices(LiveRange &LR, ArrayRef< SlotIndex > Indices, ArrayRef< SlotIndex > Undefs)
Extend the live range LR to reach all points in Indices.
bool hasRegUnit(unsigned Reg, unsigned RegUnit) const
Returns true if Reg contains RegUnit.
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction associated with the given index.
INITIALIZE_PASS_BEGIN(LiveIntervals, "liveintervals", "Live Interval Analysis", false, false) INITIALIZE_PASS_END(LiveIntervals
bool hasInterval(Register Reg) const
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
Returns the basic block which the given index falls in.
Definition: SlotIndexes.h:512
SlotIndexes pass.
Definition: SlotIndexes.h:314
SlotIndex getRegSlot(bool EC=false) const
Returns the register use/def slot in the current instruction for a normal or early-clobber def...
Definition: SlotIndexes.h:254
void constructMainRangeFromSubranges(LiveInterval &LI)
For live interval LI with correct SubRanges construct matching information for the main live range...
iterator addSegment(Segment S)
Add the specified Segment to this range, merging segments as appropriate.
void setRegisterDefReadUndef(Register Reg, bool IsUndef=true)
Mark all subregister defs of register Reg with the undef flag.
static void createSegmentsForValues(LiveRange &LR, iterator_range< LiveInterval::vni_iterator > VNIs)
MCRegUnitRootIterator enumerates the root registers of a register unit.
Segments segments
Definition: LiveInterval.h:202
bool addRegisterKilled(Register IncomingReg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI kills a register.
void dump() const
Definition: Pass.cpp:134
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:32
AnalysisUsage & addPreservedID(const void *ID)
void extend(LiveRange &LR, SlotIndex Use, unsigned PhysReg, ArrayRef< SlotIndex > Undefs)
Extend the live range of LR to reach Use.
const float huge_valf
Use this rather than HUGE_VALF; the latter causes warnings on MSVC.
Definition: MathExtras.cpp:28
virtual const TargetInstrInfo * getInstrInfo() const
char & LiveIntervalsID
LiveIntervals - This analysis keeps track of the live ranges of virtual and physical registers...
VNInfo * createDeadDef(SlotIndex Def, VNInfo::Allocator &VNIAlloc)
createDeadDef - Make sure the range has a value defined at Def.
bool allDefsAreDead() const
Return true if all the defs of this instruction are dead.
LiveRange * getCachedRegUnit(unsigned Unit)
Return the live range for register unit Unit if it has already been computed, or nullptr if it hasn&#39;t...
VNInfo * valueIn() const
Return the value that is live-in to the instruction.
Definition: LiveInterval.h:104
LiveQueryResult Query(SlotIndex Idx) const
Query Liveness at Idx.
Definition: LiveInterval.h:532
VNInfo * getVNInfoAt(SlotIndex Idx) const
getVNInfoAt - Return the VNInfo that is live at Idx, or NULL.
Definition: LiveInterval.h:412
void removeValNo(VNInfo *ValNo)
removeValNo - Remove all the segments defined by the specified value#.
unsigned getNumRegs() const
Return the number of registers this target has (useful for sizing arrays holding per register informa...
MachineInstr * getInstructionFromIndex(SlotIndex index) const
Returns the instruction for the given index, or null if the given index has no instruction associated...
Definition: SlotIndexes.h:401
initializer< Ty > init(const Ty &Val)
Definition: CommandLine.h:435
SlotIndex endIndex() const
endNumber - return the maximum point of the range of the whole, exclusive.
Definition: LiveInterval.h:383
void clearBitsNotInMask(const uint32_t *Mask, unsigned MaskWords=~0u)
clearBitsNotInMask - Clear a bit in this vector for every &#39;0&#39; bit in Mask.
Definition: BitVector.h:793
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
unsigned const MachineRegisterInfo * MRI
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
void swap(SmallVectorImpl &RHS)
Definition: SmallVector.h:668
df_ext_iterator< T, SetTy > df_ext_end(const T &G, SetTy &S)
bool isBundled() const
Return true if this instruction part of a bundle.
Definition: MachineInstr.h:373
MachineInstrBuilder & UseMI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
void splitSeparateComponents(LiveInterval &LI, SmallVectorImpl< LiveInterval *> &SplitLIs)
Split separate components in LiveInterval LI into separate intervals.
unsigned Classify(const LiveRange &LR)
Classify the values in LR into connected components.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:370
BlockFrequency getBlockFreq(const MachineBasicBlock *MBB) const
getblockFreq - Return block frequency.
SlotIndex getMBBStartIdx(unsigned Num) const
Returns the first index in the given basic block number.
Definition: SlotIndexes.h:464
Represent the analysis usage information of a pass.
df_ext_iterator< T, SetTy > df_ext_begin(const T &G, SetTy &S)
void initializeLiveIntervalsPass(PassRegistry &)
bool shrinkToUses(LiveInterval *li, SmallVectorImpl< MachineInstr *> *dead=nullptr)
After removing some uses of a register, shrink its live range to just the remaining uses...
bool reg_nodbg_empty(Register RegNo) const
reg_nodbg_empty - Return true if the only instructions using or defining Reg are Debug instructions...
constexpr double e
Definition: MathExtras.h:57
LiveInterval & getInterval(Register Reg)
HMEditor(LiveIntervals &LIS, const MachineRegisterInfo &MRI, const TargetRegisterInfo &TRI, SlotIndex OldIdx, SlotIndex NewIdx, bool UpdateFlags)
iterator_range< pred_iterator > predecessors()
MachineBasicBlock * getMBBFromIndex(SlotIndex index) const
unsigned getNumVirtRegs() const
getNumVirtRegs - Return the number of virtual registers created.
SlotIndex getMBBStartIdx(const MachineBasicBlock *mbb) const
Return the first index in the given basic block.
SlotIndex getMBBEndIdx(unsigned Num) const
Returns the last index in the given basic block number.
Definition: SlotIndexes.h:474
void repairIntervalsInRange(MachineBasicBlock *MBB, MachineBasicBlock::iterator Begin, MachineBasicBlock::iterator End, ArrayRef< unsigned > OrigRegs)
Update live intervals for instructions in a range of iterators.
TargetRegisterInfo base class - We assume that the target defines a static array of TargetRegisterDes...
size_t size() const
Definition: SmallVector.h:52
bool isDebugInstr() const
SlotIndex endPoint() const
Return the end point of the last live range segment to interact with the instruction, if any.
Definition: LiveInterval.h:146
void print(raw_ostream &OS, const SlotIndexes *=nullptr) const
print - Print out the MachineFunction in a format suitable for debugging to the specified stream...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
iterator find(SlotIndex Pos)
find - Return an iterator pointing to the first segment that ends after Pos, or end().
unsigned id
The ID number of this value.
Definition: LiveInterval.h:57
void removeSegment(SlotIndex Start, SlotIndex End, bool RemoveDeadValNo=false)
Remove the specified segment from this range.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Toolkit used by handleMove to trim or extend live intervals.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:443
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Align max(MaybeAlign Lhs, Align Rhs)
Definition: Alignment.h:390
void reset(const MachineFunction *mf, SlotIndexes *SI, MachineDominatorTree *MDT, VNInfo::Allocator *VNIA)
reset - Prepare caches for a new set of non-overlapping live ranges.
static bool isSameInstr(SlotIndex A, SlotIndex B)
isSameInstr - Return true if A and B refer to the same instruction.
Definition: SlotIndexes.h:197
Segments::const_iterator const_iterator
Definition: LiveInterval.h:212
ConnectedVNInfoEqClasses - Helper class that can divide VNInfos in a LiveInterval into equivalence cl...
Definition: LiveInterval.h:991
MachineOperand class - Representation of each machine instruction operand.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
iterator_range< MIBundleOperands > mi_bundle_ops(MachineInstr &MI)
iterator end() const
Definition: ArrayRef.h:147
Live Interval static false cl::opt< bool > EnablePrecomputePhysRegs("precompute-phys-liveness", cl::Hidden, cl::desc("Eagerly compute live intervals for all physreg units."))
bool isReservedRegUnit(unsigned Unit) const
Returns true when the given register unit is considered reserved.
LiveRange * getRegUnitLI(unsigned Unit)
LaneBitmask getSubRegIndexLaneMask(unsigned SubIdx) const
Return a bitmask representing the parts of a register that are covered by SubIdx. ...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
Definition: Pass.cpp:256
unsigned pred_size() const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
Definition: Debug.cpp:132
VNInfo * getVNInfoBefore(SlotIndex Idx) const
getVNInfoBefore - Return the VNInfo that is live up to but not necessarilly including Idx...
Definition: LiveInterval.h:420
A range adaptor for a pair of iterators.
void computeSubRangeUndefs(SmallVectorImpl< SlotIndex > &Undefs, LaneBitmask LaneMask, const MachineRegisterInfo &MRI, const SlotIndexes &Indexes) const
For a given lane mask LaneMask, compute indexes at which the lane is marked undefined by subregister ...
bool hasAtLeastOneValue() const
Definition: LiveInterval.h:300
cl::opt< bool > UseSegmentSetForPhysRegs
bool isValid() const
isValid - returns true if this iterator is not yet at the end.
VNInfo * valueOutOrDead() const
Returns the value alive at the end of the instruction, if any.
Definition: LiveInterval.h:128
typename SuperClass::iterator iterator
Definition: SmallVector.h:319
SlotIndex getMBBEndIdx(const MachineBasicBlock *mbb) const
Return the last index in the given basic block.
VNInfoList valnos
Definition: LiveInterval.h:203
void calculate(LiveInterval &LI, bool TrackSubRegs)
Calculates liveness for the register specified in live interval LI.
SlotIndex getInstructionIndex(const MachineInstr &Instr) const
Returns the base index of the given instruction.
const MachineBasicBlock * getParent() const
Definition: MachineInstr.h:271
MachineRegisterInfo - Keep track of information for virtual and physical registers, including vreg register classes, use/def chains for registers, etc.
Representation of each machine instruction.
Definition: MachineInstr.h:63
static bool isEarlierEqualInstr(SlotIndex A, SlotIndex B)
Return true if A refers to the same instruction as B or an earlier one.
Definition: SlotIndexes.h:209
pointer data()
Return a pointer to the vector&#39;s buffer, even if empty().
Definition: SmallVector.h:144
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
void addKillFlags(const VirtRegMap *)
Add kill flags to any instruction that kills a virtual register.
Register getPhys(Register virtReg) const
returns the physical register mapped to the specified virtual register
Definition: VirtRegMap.h:102
SlotIndex getPrevSlot() const
Returns the previous slot in the index list.
Definition: SlotIndexes.h:289
#define I(x, y, z)
Definition: MD5.cpp:58
#define N
constexpr bool any() const
Definition: LaneBitmask.h:52
AnalysisUsage & addRequiredTransitiveID(char &ID)
Definition: Pass.cpp:279
AnalysisUsage & addRequiredTransitive()
bool shouldTrackSubRegLiveness(const TargetRegisterClass &RC) const
Returns true if liveness for register class RC should be tracked at the subregister level...
SlotIndexes * getSlotIndexes() const
bool isReg() const
isReg - Tests if this is a MO_Register operand.
iterator_range< reg_instr_iterator > reg_instructions(unsigned Reg) const
const Segment * getSegmentContaining(SlotIndex Idx) const
Return the segment that contains the specified index, or null if there is none.
Definition: LiveInterval.h:399
MachineBasicBlock * intervalIsInOneMBB(const LiveInterval &LI) const
If LI is confined to a single basic block, return a pointer to that block.
iterator begin()
Definition: LiveInterval.h:214
const std::pair< SlotIndex, SlotIndex > & getMBBRange(unsigned Num) const
Return the (start,end) range of the given basic block number.
Definition: SlotIndexes.h:453
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
VNInfo * getNextValue(SlotIndex def, VNInfo::Allocator &VNInfoAllocator)
getNextValue - Create a new value number and return it.
Definition: LiveInterval.h:322
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
SlotIndex beginIndex() const
beginIndex - Return the lowest numbered slot covered.
Definition: LiveInterval.h:376
std::pair< VNInfo *, bool > extendInBlock(ArrayRef< SlotIndex > Undefs, SlotIndex StartIdx, SlotIndex Kill)
Attempt to extend a value defined after StartIdx to include Use.
mop_iterator operands_begin()
Definition: MachineInstr.h:486
static bool isVirtualRegister(unsigned Reg)
Return true if the specified register number is in the virtual register namespace.
Definition: Register.h:69
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:80
bool reg_empty(unsigned RegNo) const
reg_empty - Return true if there are no instructions using or defining the specified register (it may...
void handleMoveIntoBundle(MachineInstr &MI, MachineInstr &BundleStart, bool UpdateFlags=false)
Update intervals for operands of MI so that they begin/end on the SlotIndex for BundleStart.
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:46
IRTranslator LLVM IR MI
iterator FindSegmentContaining(SlotIndex Idx)
Return an iterator to the segment that contains the specified index, or end() if there is none...
Definition: LiveInterval.h:427
bool isValid() const
Check if the iterator is at the end of the list.
VNInfo * valueDefined() const
Return the value defined by this instruction, if any.
Definition: LiveInterval.h:134
Register getReg() const
getReg - Returns the register number.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
#define LLVM_DEBUG(X)
Definition: Debug.h:122
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
OutputIt copy(R &&Range, OutputIt Out)
Definition: STLExtras.h:1234
void clearRegisterKills(Register Reg, const TargetRegisterInfo *RegInfo)
Clear all kill flags affecting Reg.
SlotIndex - An opaque wrapper around machine indexes.
Definition: SlotIndexes.h:83
DominatorTree Class - Concrete subclass of DominatorTreeBase that is used to compute a normal dominat...
vni_iterator vni_end()
Definition: LiveInterval.h:224
static LLVM_ATTRIBUTE_UNUSED bool isJointlyDominated(const MachineBasicBlock *MBB, ArrayRef< SlotIndex > Defs, const SlotIndexes &Indexes)
A diagnostic function to check if the end of the block MBB is jointly dominated by the blocks corresp...
LiveRange & getRegUnit(unsigned Unit)
Return the live range for register unit Unit.
ArrayRef< const uint32_t * > getRegMaskBitsInBlock(unsigned MBBNum) const
Returns an array of mask pointers corresponding to getRegMaskSlotsInBlock(MBBNum).
void handleMove(MachineInstr &MI, bool UpdateFlags=false)
Call this method to notify LiveIntervals that instruction MI has been moved within a basic block...
Wrapper class representing virtual and physical registers.
Definition: Register.h:19
void removeVRegDefAt(LiveInterval &LI, SlotIndex Pos)
Remove value number and related live segments of LI and its subranges that start at position Pos...
void resize(size_type N)
Definition: SmallVector.h:344