1 //===---------- SplitKit.cpp - Toolkit for splitting live ranges ----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the SplitAnalysis class as well as mutator functions for
11 // live range splitting.
13 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "splitter"
17 #include "VirtRegMap.h"
18 #include "llvm/CodeGen/CalcSpillWeights.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineLoopInfo.h"
22 #include "llvm/CodeGen/MachineRegisterInfo.h"
23 #include "llvm/Support/CommandLine.h"
24 #include "llvm/Support/Debug.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
32 AllowSplit("spiller-splits-edges",
33 cl::desc("Allow critical edge splitting during spilling"));
35 //===----------------------------------------------------------------------===//
37 //===----------------------------------------------------------------------===//
39 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
40 const LiveIntervals &lis,
41 const MachineLoopInfo &mli)
45 tii_(*mf.getTarget().getInstrInfo()),
48 void SplitAnalysis::clear() {
55 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
56 MachineBasicBlock *T, *F;
57 SmallVector<MachineOperand, 4> Cond;
58 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
61 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
62 void SplitAnalysis::analyzeUses() {
63 const MachineRegisterInfo &MRI = mf_.getRegInfo();
64 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
65 MachineInstr *MI = I.skipInstruction();) {
66 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
68 MachineBasicBlock *MBB = MI->getParent();
69 if (usingBlocks_[MBB]++)
71 if (MachineLoop *Loop = loops_.getLoopFor(MBB))
74 DEBUG(dbgs() << " counted "
75 << usingInstrs_.size() << " instrs, "
76 << usingBlocks_.size() << " blocks, "
77 << usingLoops_.size() << " loops.\n");
80 /// removeUse - Update statistics by noting that MI no longer uses curli.
81 void SplitAnalysis::removeUse(const MachineInstr *MI) {
82 if (!usingInstrs_.erase(MI))
85 // Decrement MBB count.
86 const MachineBasicBlock *MBB = MI->getParent();
87 BlockCountMap::iterator bi = usingBlocks_.find(MBB);
88 assert(bi != usingBlocks_.end() && "MBB missing");
89 assert(bi->second && "0 count in map");
92 // No more uses in MBB.
93 usingBlocks_.erase(bi);
95 // Decrement loop count.
96 MachineLoop *Loop = loops_.getLoopFor(MBB);
99 LoopCountMap::iterator li = usingLoops_.find(Loop);
100 assert(li != usingLoops_.end() && "Loop missing");
101 assert(li->second && "0 count in map");
104 // No more blocks in Loop.
105 usingLoops_.erase(li);
108 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
109 // predecessor blocks, and exit blocks.
110 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
113 // Blocks in the loop.
114 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
116 // Predecessor blocks.
117 const MachineBasicBlock *Header = Loop->getHeader();
118 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
119 E = Header->pred_end(); I != E; ++I)
120 if (!Blocks.Loop.count(*I))
121 Blocks.Preds.insert(*I);
124 for (MachineLoop::block_iterator I = Loop->block_begin(),
125 E = Loop->block_end(); I != E; ++I) {
126 const MachineBasicBlock *MBB = *I;
127 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
128 SE = MBB->succ_end(); SI != SE; ++SI)
129 if (!Blocks.Loop.count(*SI))
130 Blocks.Exits.insert(*SI);
134 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
135 /// and around the Loop.
136 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
137 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
138 LoopPeripheralUse use = ContainedInLoop;
139 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
141 const MachineBasicBlock *MBB = I->first;
142 // Is this a peripheral block?
143 if (use < MultiPeripheral &&
144 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
145 if (I->second > 1) use = MultiPeripheral;
146 else use = SinglePeripheral;
149 // Is it a loop block?
150 if (Blocks.Loop.count(MBB))
152 // It must be an unrelated block.
158 /// getCriticalExits - It may be necessary to partially break critical edges
159 /// leaving the loop if an exit block has phi uses of curli. Collect the exit
160 /// blocks that need special treatment into CriticalExits.
161 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
162 BlockPtrSet &CriticalExits) {
163 CriticalExits.clear();
165 // A critical exit block contains a phi def of curli, and has a predecessor
166 // that is not in the loop nor a loop predecessor.
167 // For such an exit block, the edges carrying the new variable must be moved
168 // to a new pre-exit block.
169 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
171 const MachineBasicBlock *Succ = *I;
172 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
173 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
174 // This exit may not have curli live in at all. No need to split.
177 // If this is not a PHI def, it is either using a value from before the
178 // loop, or a value defined inside the loop. Both are safe.
179 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
181 // This exit block does have a PHI. Does it also have a predecessor that is
182 // not a loop block or loop predecessor?
183 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
184 PE = Succ->pred_end(); PI != PE; ++PI) {
185 const MachineBasicBlock *Pred = *PI;
186 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
188 // This is a critical exit block, and we need to split the exit edge.
189 CriticalExits.insert(Succ);
195 /// canSplitCriticalExits - Return true if it is possible to insert new exit
196 /// blocks before the blocks in CriticalExits.
198 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
199 BlockPtrSet &CriticalExits) {
200 // If we don't allow critical edge splitting, require no critical exits.
202 return CriticalExits.empty();
204 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
206 const MachineBasicBlock *Succ = *I;
207 // We want to insert a new pre-exit MBB before Succ, and change all the
208 // in-loop blocks to branch to the pre-exit instead of Succ.
209 // Check that all the in-loop predecessors can be changed.
210 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
211 PE = Succ->pred_end(); PI != PE; ++PI) {
212 const MachineBasicBlock *Pred = *PI;
213 // The external predecessors won't be altered.
214 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
216 if (!canAnalyzeBranch(Pred))
220 // If Succ's layout predecessor falls through, that too must be analyzable.
221 // We need to insert the pre-exit block in the gap.
222 MachineFunction::const_iterator MFI = Succ;
223 if (MFI == mf_.begin())
225 if (!canAnalyzeBranch(--MFI))
228 // No problems found.
232 void SplitAnalysis::analyze(const LiveInterval *li) {
238 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
239 assert(curli_ && "Call analyze() before getBestSplitLoop");
240 if (usingLoops_.empty())
243 LoopPtrSet Loops, SecondLoops;
245 BlockPtrSet CriticalExits;
247 // Find first-class and second class candidate loops.
248 // We prefer to split around loops where curli is used outside the periphery.
249 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
250 E = usingLoops_.end(); I != E; ++I) {
251 const MachineLoop *Loop = I->first;
252 getLoopBlocks(Loop, Blocks);
254 // FIXME: We need an SSA updater to properly handle multiple exit blocks.
255 if (Blocks.Exits.size() > 1) {
256 DEBUG(dbgs() << " multiple exits from " << *Loop);
261 switch(analyzeLoopPeripheralUse(Blocks)) {
265 case MultiPeripheral:
268 case ContainedInLoop:
269 DEBUG(dbgs() << " contained in " << *Loop);
271 case SinglePeripheral:
272 DEBUG(dbgs() << " single peripheral use in " << *Loop);
275 // Will it be possible to split around this loop?
276 getCriticalExits(Blocks, CriticalExits);
277 DEBUG(dbgs() << " " << CriticalExits.size() << " critical exits from "
279 if (!canSplitCriticalExits(Blocks, CriticalExits))
281 // This is a possible split.
286 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size() << " + "
287 << SecondLoops.size() << " candidate loops.\n");
289 // If there are no first class loops available, look at second class loops.
296 // Pick the earliest loop.
297 // FIXME: Are there other heuristics to consider?
298 const MachineLoop *Best = 0;
300 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
302 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
303 if (!Best || Idx < BestIdx)
304 Best = *I, BestIdx = Idx;
306 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
310 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
311 /// may be an advantage to split curli for the duration of the block.
312 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
313 // If curli is local to one block, there is no point to splitting it.
314 if (usingBlocks_.size() <= 1)
316 // Add blocks with multiple uses.
317 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
324 // It doesn't pay to split a 2-instr block if it redefines curli.
325 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
327 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
328 // live-in and live-out with a different value.
329 if (VN1 && VN2 && VN1 != VN2)
333 Blocks.insert(I->first);
335 return !Blocks.empty();
338 //===----------------------------------------------------------------------===//
340 //===----------------------------------------------------------------------===//
342 // defValue - Introduce a li_ def for ParentVNI that could be later than
344 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
345 assert(ParentVNI && "Mapping NULL value");
346 assert(Idx.isValid() && "Invalid SlotIndex");
347 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
349 // Is this a simple 1-1 mapping? Not likely.
350 if (Idx == ParentVNI->def)
351 return mapValue(ParentVNI, Idx);
353 // This is a complex def. Mark with a NULL in valueMap.
356 ValueMap::value_type(ParentVNI, static_cast<VNInfo *>(0))).first->second;
357 // The static_cast<VNInfo *> is only needed to work around a bug in an
358 // old version of the C++0x standard which the following compilers
359 // implemented and have yet to fix:
361 // Microsoft Visual Studio 2010 Version 10.0.30319.1 RTMRel
362 // Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01
364 // If/When we move to C++0x, this can be replaced by nullptr.
366 assert(OldVNI == 0 && "Simple/Complex values mixed");
368 // Should we insert a minimal snippet of VNI LiveRange, or can we count on
369 // callers to do that? We need it for lookups of complex values.
370 VNInfo *VNI = li_.getNextValue(Idx, 0, true, lis_.getVNInfoAllocator());
374 // mapValue - Find the mapped value for ParentVNI at Idx.
375 // Potentially create phi-def values.
376 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx) {
377 assert(ParentVNI && "Mapping NULL value");
378 assert(Idx.isValid() && "Invalid SlotIndex");
379 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
381 // Use insert for lookup, so we can add missing values with a second lookup.
382 std::pair<ValueMap::iterator,bool> InsP =
383 valueMap_.insert(ValueMap::value_type(ParentVNI, static_cast<VNInfo *>(0)));
384 // The static_cast<VNInfo *> is only needed to work around a bug in an
385 // old version of the C++0x standard which the following compilers
386 // implemented and have yet to fix:
388 // Microsoft Visual Studio 2010 Version 10.0.30319.1 RTMRel
389 // Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01
391 // If/When we move to C++0x, this can be replaced by nullptr.
393 // This was an unknown value. Create a simple mapping.
395 return InsP.first->second = li_.createValueCopy(ParentVNI,
396 lis_.getVNInfoAllocator());
397 // This was a simple mapped value.
398 if (InsP.first->second)
399 return InsP.first->second;
401 // This is a complex mapped value. There may be multiple defs, and we may need
402 // to create phi-defs.
403 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
404 assert(IdxMBB && "No MBB at Idx");
406 // Is there a def in the same MBB we can extend?
407 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
410 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
411 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
412 // Perform a depth-first search for predecessor blocks where we know the
413 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
415 // Track MBBs where we have created or learned the dominating value.
416 // This may change during the DFS as we create new phi-defs.
417 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
418 MBBValueMap DomValue;
420 for (idf_iterator<MachineBasicBlock*>
421 IDFI = idf_begin(IdxMBB),
422 IDFE = idf_end(IdxMBB); IDFI != IDFE;) {
423 MachineBasicBlock *MBB = *IDFI;
424 SlotIndex End = lis_.getMBBEndIdx(MBB);
426 // We are operating on the restricted CFG where ParentVNI is live.
427 if (parentli_.getVNInfoAt(End.getPrevSlot()) != ParentVNI) {
432 // Do we have a dominating value in this block?
433 VNInfo *VNI = extendTo(MBB, End);
439 // Yes, VNI dominates MBB. Track the path back to IdxMBB, creating phi-defs
440 // as needed along the way.
441 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
442 // Start from MBB's immediate successor. End at IdxMBB.
443 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
444 std::pair<MBBValueMap::iterator, bool> InsP =
445 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
447 // This is the first time we backtrack to Succ.
451 // We reached Succ again with the same VNI. Nothing is going to change.
452 VNInfo *OVNI = InsP.first->second;
456 // Succ already has a phi-def. No need to continue.
457 SlotIndex Start = lis_.getMBBStartIdx(Succ);
458 if (OVNI->def == Start)
461 // We have a collision between the old and new VNI at Succ. That means
462 // neither dominates and we need a new phi-def.
463 VNI = li_.getNextValue(Start, 0, true, lis_.getVNInfoAllocator());
464 VNI->setIsPHIDef(true);
465 InsP.first->second = VNI;
467 // Replace OVNI with VNI in the remaining path.
468 for (; PI > 1 ; --PI) {
469 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
470 if (I == DomValue.end() || I->second != OVNI)
476 // No need to search the children, we found a dominating value.
480 // The search should at least find a dominating value for IdxMBB.
481 assert(!DomValue.empty() && "Couldn't find a reaching definition");
483 // Since we went through the trouble of a full DFS visiting all reaching defs,
484 // the values in DomValue are now accurate. No more phi-defs are needed for
485 // these blocks, so we can color the live ranges.
486 // This makes the next mapValue call much faster.
488 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
490 MachineBasicBlock *MBB = I->first;
491 VNInfo *VNI = I->second;
492 SlotIndex Start = lis_.getMBBStartIdx(MBB);
494 // Don't add full liveness to IdxMBB, stop at Idx.
496 li_.addRange(LiveRange(Start, Idx, VNI));
497 // The caller had better add some liveness to IdxVNI, or it leaks.
500 li_.addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
503 assert(IdxVNI && "Didn't find value for Idx");
507 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
508 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
509 // Return the found VNInfo, or NULL.
510 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
511 LiveInterval::iterator I = std::upper_bound(li_.begin(), li_.end(), Idx);
512 if (I == li_.begin())
515 if (I->start < lis_.getMBBStartIdx(MBB))
522 // addSimpleRange - Add a simple range from parentli_ to li_.
523 // ParentVNI must be live in the [Start;End) interval.
524 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
525 const VNInfo *ParentVNI) {
526 VNInfo *VNI = mapValue(ParentVNI, Start);
527 // A simple mappoing is easy.
528 if (VNI->def == ParentVNI->def) {
529 li_.addRange(LiveRange(Start, End, VNI));
533 // ParentVNI is a complex value. We must map per MBB.
534 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
535 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End);
538 li_.addRange(LiveRange(Start, End, VNI));
543 li_.addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
545 // Run sequence of full blocks.
546 for (++MBB; MBB != MBBE; ++MBB) {
547 Start = lis_.getMBBStartIdx(MBB);
548 li_.addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
549 mapValue(ParentVNI, Start)));
553 Start = lis_.getMBBStartIdx(MBB);
555 li_.addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
558 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
559 /// All needed values whose def is not inside [Start;End) must be defined
560 /// beforehand so mapValue will work.
561 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
562 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
563 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
565 // Check if --I begins before Start and overlaps.
569 addSimpleRange(Start, std::min(End, I->end), I->valno);
573 // The remaining ranges begin after Start.
574 for (;I != E && I->start < End; ++I)
575 addSimpleRange(I->start, std::min(End, I->end), I->valno);
578 //===----------------------------------------------------------------------===//
580 //===----------------------------------------------------------------------===//
582 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
583 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
584 SmallVectorImpl<LiveInterval*> &intervals)
585 : sa_(sa), lis_(lis), vrm_(vrm),
586 mri_(vrm.getMachineFunction().getRegInfo()),
587 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
588 curli_(sa_.getCurLI()),
589 dupli_(0), openli_(0),
590 intervals_(intervals),
591 firstInterval(intervals_.size())
593 assert(curli_ && "SplitEditor created from empty SplitAnalysis");
595 // Make sure curli_ is assigned a stack slot, so all our intervals get the
596 // same slot as curli_.
597 if (vrm_.getStackSlot(curli_->reg) == VirtRegMap::NO_STACK_SLOT)
598 vrm_.assignVirt2StackSlot(curli_->reg);
602 LiveInterval *SplitEditor::createInterval() {
603 unsigned curli = sa_.getCurLI()->reg;
604 unsigned Reg = mri_.createVirtualRegister(mri_.getRegClass(curli));
605 LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
607 vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli));
611 LiveInterval *SplitEditor::getDupLI() {
613 // Create an interval for dupli that is a copy of curli.
614 dupli_ = createInterval();
615 dupli_->Copy(*curli_, &mri_, lis_.getVNInfoAllocator());
620 VNInfo *SplitEditor::mapValue(const VNInfo *curliVNI) {
621 VNInfo *&VNI = valueMap_[curliVNI];
623 VNI = openli_->createValueCopy(curliVNI, lis_.getVNInfoAllocator());
627 /// Insert a COPY instruction curli -> li. Allocate a new value from li
628 /// defined by the COPY. Note that rewrite() will deal with the curli
629 /// register, so this function can be used to copy from any interval - openli,
631 VNInfo *SplitEditor::insertCopy(LiveInterval &LI,
632 MachineBasicBlock &MBB,
633 MachineBasicBlock::iterator I) {
634 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
635 LI.reg).addReg(curli_->reg);
636 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
637 return LI.getNextValue(DefIdx, MI, true, lis_.getVNInfoAllocator());
640 /// Create a new virtual register and live interval.
641 void SplitEditor::openIntv() {
642 assert(!openli_ && "Previous LI not closed before openIntv");
643 openli_ = createInterval();
644 intervals_.push_back(openli_);
645 liveThrough_ = false;
648 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
649 /// not live before Idx, a COPY is not inserted.
650 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
651 assert(openli_ && "openIntv not called before enterIntvBefore");
653 // Copy from curli_ if it is live.
654 if (VNInfo *CurVNI = curli_->getVNInfoAt(Idx.getUseIndex())) {
655 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
656 assert(MI && "enterIntvBefore called with invalid index");
657 VNInfo *VNI = insertCopy(*openli_, *MI->getParent(), MI);
658 openli_->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
660 // Make sure CurVNI is properly mapped.
661 VNInfo *&mapVNI = valueMap_[CurVNI];
662 // We dont have SSA update yet, so only one entry per value is allowed.
663 assert(!mapVNI && "enterIntvBefore called more than once for the same value");
666 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": " << *openli_ << '\n');
669 /// enterIntvAtEnd - Enter openli at the end of MBB.
670 /// PhiMBB is a successor inside openli where a PHI value is created.
671 /// Currently, all entries must share the same PhiMBB.
672 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &A, MachineBasicBlock &B) {
673 assert(openli_ && "openIntv not called before enterIntvAtEnd");
675 SlotIndex EndA = lis_.getMBBEndIdx(&A);
676 VNInfo *CurVNIA = curli_->getVNInfoAt(EndA.getPrevIndex());
678 DEBUG(dbgs() << " enterIntvAtEnd, curli not live out of BB#"
679 << A.getNumber() << ".\n");
683 // Add a phi kill value and live range out of A.
684 VNInfo *VNIA = insertCopy(*openli_, A, A.getFirstTerminator());
685 openli_->addRange(LiveRange(VNIA->def, EndA, VNIA));
687 // FIXME: If this is the only entry edge, we don't need the extra PHI value.
688 // FIXME: If there are multiple entry blocks (so not a loop), we need proper
691 // Now look at the start of B.
692 SlotIndex StartB = lis_.getMBBStartIdx(&B);
693 SlotIndex EndB = lis_.getMBBEndIdx(&B);
694 const LiveRange *CurB = curli_->getLiveRangeContaining(StartB);
696 DEBUG(dbgs() << " enterIntvAtEnd: curli not live in to BB#"
697 << B.getNumber() << ".\n");
701 VNInfo *VNIB = openli_->getVNInfoAt(StartB);
703 // Create a phi value.
704 VNIB = openli_->getNextValue(SlotIndex(StartB, true), 0, false,
705 lis_.getVNInfoAllocator());
706 VNIB->setIsPHIDef(true);
707 VNInfo *&mapVNI = valueMap_[CurB->valno];
709 // Multiple copies - must create PHI value.
712 // This is the first copy of dupLR. Mark the mapping.
718 DEBUG(dbgs() << " enterIntvAtEnd: " << *openli_ << '\n');
721 /// useIntv - indicate that all instructions in MBB should use openli.
722 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
723 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
726 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
727 assert(openli_ && "openIntv not called before useIntv");
729 // Map the curli values from the interval into openli_
730 LiveInterval::const_iterator B = curli_->begin(), E = curli_->end();
731 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
735 // I begins before Start, but overlaps.
737 openli_->addRange(LiveRange(Start, std::min(End, I->end),
738 mapValue(I->valno)));
742 // The remaining ranges begin after Start.
743 for (;I != E && I->start < End; ++I)
744 openli_->addRange(LiveRange(I->start, std::min(End, I->end),
745 mapValue(I->valno)));
746 DEBUG(dbgs() << " use [" << Start << ';' << End << "): " << *openli_
750 /// leaveIntvAfter - Leave openli after the instruction at Idx.
751 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
752 assert(openli_ && "openIntv not called before leaveIntvAfter");
754 const LiveRange *CurLR = curli_->getLiveRangeContaining(Idx.getDefIndex());
755 if (!CurLR || CurLR->end <= Idx.getBoundaryIndex()) {
756 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": not live\n");
760 // Was this value of curli live through openli?
761 if (!openli_->liveAt(CurLR->valno->def)) {
762 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": using external value\n");
767 // We are going to insert a back copy, so we must have a dupli_.
768 LiveRange *DupLR = getDupLI()->getLiveRangeContaining(Idx.getDefIndex());
769 assert(DupLR && "dupli not live into black, but curli is?");
771 // Insert the COPY instruction.
772 MachineBasicBlock::iterator I = lis_.getInstructionFromIndex(Idx);
773 MachineInstr *MI = BuildMI(*I->getParent(), llvm::next(I), I->getDebugLoc(),
774 tii_.get(TargetOpcode::COPY), dupli_->reg)
775 .addReg(openli_->reg);
776 SlotIndex CopyIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
777 openli_->addRange(LiveRange(Idx.getDefIndex(), CopyIdx,
778 mapValue(CurLR->valno)));
779 DupLR->valno->def = CopyIdx;
780 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": " << *openli_ << '\n');
783 /// leaveIntvAtTop - Leave the interval at the top of MBB.
784 /// Currently, only one value can leave the interval.
785 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
786 assert(openli_ && "openIntv not called before leaveIntvAtTop");
788 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
789 const LiveRange *CurLR = curli_->getLiveRangeContaining(Start);
791 // Is curli even live-in to MBB?
793 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": not live\n");
797 // Is curli defined by PHI at the beginning of MBB?
798 bool isPHIDef = CurLR->valno->isPHIDef() &&
799 CurLR->valno->def.getBaseIndex() == Start;
801 // If MBB is using a value of curli that was defined outside the openli range,
802 // we don't want to copy it back here.
803 if (!isPHIDef && !openli_->liveAt(CurLR->valno->def)) {
804 DEBUG(dbgs() << " leaveIntvAtTop at " << Start
805 << ": using external value\n");
810 // We are going to insert a back copy, so we must have a dupli_.
811 LiveRange *DupLR = getDupLI()->getLiveRangeContaining(Start);
812 assert(DupLR && "dupli not live into black, but curli is?");
814 // Insert the COPY instruction.
815 MachineInstr *MI = BuildMI(MBB, MBB.begin(), DebugLoc(),
816 tii_.get(TargetOpcode::COPY), dupli_->reg)
817 .addReg(openli_->reg);
818 SlotIndex Idx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
820 // Adjust dupli and openli values.
822 // dupli was already a PHI on entry to MBB. Simply insert an openli PHI,
823 // and shift the dupli def down to the COPY.
824 VNInfo *VNI = openli_->getNextValue(SlotIndex(Start, true), 0, false,
825 lis_.getVNInfoAllocator());
826 VNI->setIsPHIDef(true);
827 openli_->addRange(LiveRange(VNI->def, Idx, VNI));
829 dupli_->removeRange(Start, Idx);
830 DupLR->valno->def = Idx;
831 DupLR->valno->setIsPHIDef(false);
833 // The dupli value was defined somewhere inside the openli range.
834 DEBUG(dbgs() << " leaveIntvAtTop source value defined at "
835 << DupLR->valno->def << "\n");
836 // FIXME: We may not need a PHI here if all predecessors have the same
838 VNInfo *VNI = openli_->getNextValue(SlotIndex(Start, true), 0, false,
839 lis_.getVNInfoAllocator());
840 VNI->setIsPHIDef(true);
841 openli_->addRange(LiveRange(VNI->def, Idx, VNI));
843 // FIXME: What if DupLR->valno is used by multiple exits? SSA Update.
845 // closeIntv is going to remove the superfluous live ranges.
846 DupLR->valno->def = Idx;
847 DupLR->valno->setIsPHIDef(false);
850 DEBUG(dbgs() << " leaveIntvAtTop at " << Idx << ": " << *openli_ << '\n');
853 /// closeIntv - Indicate that we are done editing the currently open
854 /// LiveInterval, and ranges can be trimmed.
855 void SplitEditor::closeIntv() {
856 assert(openli_ && "openIntv not called before closeIntv");
858 DEBUG(dbgs() << " closeIntv cleaning up\n");
859 DEBUG(dbgs() << " open " << *openli_ << '\n');
862 DEBUG(dbgs() << " value live through region, leaving dupli as is.\n");
864 // live out with copies inserted, or killed by region. Either way we need to
865 // remove the overlapping region from dupli.
867 for (LiveInterval::iterator I = openli_->begin(), E = openli_->end();
869 dupli_->removeRange(I->start, I->end);
871 // FIXME: A block branching to the entry block may also branch elsewhere
872 // curli is live. We need both openli and curli to be live in that case.
873 DEBUG(dbgs() << " dup2 " << *dupli_ << '\n');
879 /// rewrite - after all the new live ranges have been created, rewrite
880 /// instructions using curli to use the new intervals.
881 void SplitEditor::rewrite() {
882 assert(!openli_ && "Previous LI not closed before rewrite");
883 const LiveInterval *curli = sa_.getCurLI();
884 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
885 RE = mri_.reg_end(); RI != RE;) {
886 MachineOperand &MO = RI.getOperand();
887 MachineInstr *MI = MO.getParent();
889 if (MI->isDebugValue()) {
890 DEBUG(dbgs() << "Zapping " << *MI);
891 // FIXME: We can do much better with debug values.
895 SlotIndex Idx = lis_.getInstructionIndex(MI);
896 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
897 LiveInterval *LI = dupli_;
898 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
899 LiveInterval *testli = intervals_[i];
900 if (testli->liveAt(Idx)) {
908 DEBUG(dbgs() << " rewrite " << Idx << '\t' << *MI);
912 // dupli_ goes in last, after rewriting.
914 if (dupli_->empty()) {
915 DEBUG(dbgs() << " dupli became empty?\n");
916 lis_.removeInterval(dupli_->reg);
919 dupli_->RenumberValues(lis_);
920 intervals_.push_back(dupli_);
924 // Calculate spill weight and allocation hints for new intervals.
925 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
926 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
927 LiveInterval &li = *intervals_[i];
928 vrai.CalculateRegClass(li.reg);
929 vrai.CalculateWeightAndHint(li);
930 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
931 << ":" << li << '\n');
936 //===----------------------------------------------------------------------===//
938 //===----------------------------------------------------------------------===//
940 bool SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
941 SplitAnalysis::LoopBlocks Blocks;
942 sa_.getLoopBlocks(Loop, Blocks);
944 // Break critical edges as needed.
945 SplitAnalysis::BlockPtrSet CriticalExits;
946 sa_.getCriticalExits(Blocks, CriticalExits);
947 assert(CriticalExits.empty() && "Cannot break critical exits yet");
949 // Create new live interval for the loop.
952 // Insert copies in the predecessors.
953 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
954 E = Blocks.Preds.end(); I != E; ++I) {
955 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
956 enterIntvAtEnd(MBB, *Loop->getHeader());
959 // Switch all loop blocks.
960 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
961 E = Blocks.Loop.end(); I != E; ++I)
964 // Insert back copies in the exit blocks.
965 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
966 E = Blocks.Exits.end(); I != E; ++I) {
967 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
978 //===----------------------------------------------------------------------===//
979 // Single Block Splitting
980 //===----------------------------------------------------------------------===//
982 /// splitSingleBlocks - Split curli into a separate live interval inside each
983 /// basic block in Blocks. Return true if curli has been completely replaced,
984 /// false if curli is still intact, and needs to be spilled or split further.
985 bool SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
986 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
987 // Determine the first and last instruction using curli in each block.
988 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
989 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
990 IndexPairMap MBBRange;
991 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
992 E = sa_.usingInstrs_.end(); I != E; ++I) {
993 const MachineBasicBlock *MBB = (*I)->getParent();
994 if (!Blocks.count(MBB))
996 SlotIndex Idx = lis_.getInstructionIndex(*I);
997 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
998 IndexPair &IP = MBBRange[MBB];
999 if (!IP.first.isValid() || Idx < IP.first)
1001 if (!IP.second.isValid() || Idx > IP.second)
1005 // Create a new interval for each block.
1006 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1007 E = Blocks.end(); I != E; ++I) {
1008 IndexPair &IP = MBBRange[*I];
1009 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
1010 << IP.first << ';' << IP.second << ")\n");
1011 assert(IP.first.isValid() && IP.second.isValid());
1014 enterIntvBefore(IP.first);
1015 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1016 leaveIntvAfter(IP.second);
1024 //===----------------------------------------------------------------------===//
1025 // Sub Block Splitting
1026 //===----------------------------------------------------------------------===//
1028 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
1029 /// and it wou pay to subdivide the interval inside that block, return it.
1030 /// Otherwise return NULL. The returned block can be passed to
1031 /// SplitEditor::splitInsideBlock.
1032 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1033 // The interval must be exclusive to one block.
1034 if (usingBlocks_.size() != 1)
1036 // Don't to this for less than 4 instructions. We want to be sure that
1037 // splitting actually reduces the instruction count per interval.
1038 if (usingInstrs_.size() < 4)
1040 return usingBlocks_.begin()->first;
1043 /// splitInsideBlock - Split curli into multiple intervals inside MBB. Return
1044 /// true if curli has been completely replaced, false if curli is still
1045 /// intact, and needs to be spilled or split further.
1046 bool SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1047 SmallVector<SlotIndex, 32> Uses;
1048 Uses.reserve(sa_.usingInstrs_.size());
1049 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1050 E = sa_.usingInstrs_.end(); I != E; ++I)
1051 if ((*I)->getParent() == MBB)
1052 Uses.push_back(lis_.getInstructionIndex(*I));
1053 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1054 << Uses.size() << " instructions.\n");
1055 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1056 array_pod_sort(Uses.begin(), Uses.end());
1058 // Simple algorithm: Find the largest gap between uses as determined by slot
1059 // indices. Create new intervals for instructions before the gap and after the
1061 unsigned bestPos = 0;
1063 DEBUG(dbgs() << " dist (" << Uses[0]);
1064 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1065 int g = Uses[i-1].distance(Uses[i]);
1066 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1068 bestPos = i, bestGap = g;
1070 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1072 // bestPos points to the first use after the best gap.
1073 assert(bestPos > 0 && "Invalid gap");
1075 // FIXME: Don't create intervals for low densities.
1077 // First interval before the gap. Don't create single-instr intervals.
1080 enterIntvBefore(Uses.front());
1081 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1082 leaveIntvAfter(Uses[bestPos-1]);
1086 // Second interval after the gap.
1087 if (bestPos < Uses.size()-1) {
1089 enterIntvBefore(Uses[bestPos]);
1090 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1091 leaveIntvAfter(Uses.back());