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 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
81 // predecessor blocks, and exit blocks.
82 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
85 // Blocks in the loop.
86 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
88 // Predecessor blocks.
89 const MachineBasicBlock *Header = Loop->getHeader();
90 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
91 E = Header->pred_end(); I != E; ++I)
92 if (!Blocks.Loop.count(*I))
93 Blocks.Preds.insert(*I);
96 for (MachineLoop::block_iterator I = Loop->block_begin(),
97 E = Loop->block_end(); I != E; ++I) {
98 const MachineBasicBlock *MBB = *I;
99 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
100 SE = MBB->succ_end(); SI != SE; ++SI)
101 if (!Blocks.Loop.count(*SI))
102 Blocks.Exits.insert(*SI);
106 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
107 /// and around the Loop.
108 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
109 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
110 LoopPeripheralUse use = ContainedInLoop;
111 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
113 const MachineBasicBlock *MBB = I->first;
114 // Is this a peripheral block?
115 if (use < MultiPeripheral &&
116 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
117 if (I->second > 1) use = MultiPeripheral;
118 else use = SinglePeripheral;
121 // Is it a loop block?
122 if (Blocks.Loop.count(MBB))
124 // It must be an unrelated block.
130 /// getCriticalExits - It may be necessary to partially break critical edges
131 /// leaving the loop if an exit block has phi uses of curli. Collect the exit
132 /// blocks that need special treatment into CriticalExits.
133 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
134 BlockPtrSet &CriticalExits) {
135 CriticalExits.clear();
137 // A critical exit block contains a phi def of curli, and has a predecessor
138 // that is not in the loop nor a loop predecessor.
139 // For such an exit block, the edges carrying the new variable must be moved
140 // to a new pre-exit block.
141 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
143 const MachineBasicBlock *Succ = *I;
144 SlotIndex SuccIdx = lis_.getMBBStartIdx(Succ);
145 VNInfo *SuccVNI = curli_->getVNInfoAt(SuccIdx);
146 // This exit may not have curli live in at all. No need to split.
149 // If this is not a PHI def, it is either using a value from before the
150 // loop, or a value defined inside the loop. Both are safe.
151 if (!SuccVNI->isPHIDef() || SuccVNI->def.getBaseIndex() != SuccIdx)
153 // This exit block does have a PHI. Does it also have a predecessor that is
154 // not a loop block or loop predecessor?
155 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
156 PE = Succ->pred_end(); PI != PE; ++PI) {
157 const MachineBasicBlock *Pred = *PI;
158 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
160 // This is a critical exit block, and we need to split the exit edge.
161 CriticalExits.insert(Succ);
167 /// canSplitCriticalExits - Return true if it is possible to insert new exit
168 /// blocks before the blocks in CriticalExits.
170 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
171 BlockPtrSet &CriticalExits) {
172 // If we don't allow critical edge splitting, require no critical exits.
174 return CriticalExits.empty();
176 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
178 const MachineBasicBlock *Succ = *I;
179 // We want to insert a new pre-exit MBB before Succ, and change all the
180 // in-loop blocks to branch to the pre-exit instead of Succ.
181 // Check that all the in-loop predecessors can be changed.
182 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
183 PE = Succ->pred_end(); PI != PE; ++PI) {
184 const MachineBasicBlock *Pred = *PI;
185 // The external predecessors won't be altered.
186 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
188 if (!canAnalyzeBranch(Pred))
192 // If Succ's layout predecessor falls through, that too must be analyzable.
193 // We need to insert the pre-exit block in the gap.
194 MachineFunction::const_iterator MFI = Succ;
195 if (MFI == mf_.begin())
197 if (!canAnalyzeBranch(--MFI))
200 // No problems found.
204 void SplitAnalysis::analyze(const LiveInterval *li) {
210 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
211 assert(curli_ && "Call analyze() before getBestSplitLoop");
212 if (usingLoops_.empty())
215 LoopPtrSet Loops, SecondLoops;
217 BlockPtrSet CriticalExits;
219 // Find first-class and second class candidate loops.
220 // We prefer to split around loops where curli is used outside the periphery.
221 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
222 E = usingLoops_.end(); I != E; ++I) {
223 const MachineLoop *Loop = I->first;
224 getLoopBlocks(Loop, Blocks);
227 switch(analyzeLoopPeripheralUse(Blocks)) {
231 case MultiPeripheral:
234 case ContainedInLoop:
235 DEBUG(dbgs() << " contained in " << *Loop);
237 case SinglePeripheral:
238 DEBUG(dbgs() << " single peripheral use in " << *Loop);
241 // Will it be possible to split around this loop?
242 getCriticalExits(Blocks, CriticalExits);
243 DEBUG(dbgs() << " " << CriticalExits.size() << " critical exits from "
245 if (!canSplitCriticalExits(Blocks, CriticalExits))
247 // This is a possible split.
252 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size() << " + "
253 << SecondLoops.size() << " candidate loops.\n");
255 // If there are no first class loops available, look at second class loops.
262 // Pick the earliest loop.
263 // FIXME: Are there other heuristics to consider?
264 const MachineLoop *Best = 0;
266 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
268 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
269 if (!Best || Idx < BestIdx)
270 Best = *I, BestIdx = Idx;
272 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
276 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
277 /// may be an advantage to split curli for the duration of the block.
278 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
279 // If curli is local to one block, there is no point to splitting it.
280 if (usingBlocks_.size() <= 1)
282 // Add blocks with multiple uses.
283 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
290 // It doesn't pay to split a 2-instr block if it redefines curli.
291 VNInfo *VN1 = curli_->getVNInfoAt(lis_.getMBBStartIdx(I->first));
293 curli_->getVNInfoAt(lis_.getMBBEndIdx(I->first).getPrevIndex());
294 // live-in and live-out with a different value.
295 if (VN1 && VN2 && VN1 != VN2)
299 Blocks.insert(I->first);
301 return !Blocks.empty();
304 //===----------------------------------------------------------------------===//
306 //===----------------------------------------------------------------------===//
308 // Work around the fact that the std::pair constructors are broken for pointer
309 // pairs in some implementations. makeVV(x, 0) works.
310 static inline std::pair<const VNInfo*, VNInfo*>
311 makeVV(const VNInfo *a, VNInfo *b) {
312 return std::make_pair(a, b);
315 void LiveIntervalMap::reset(LiveInterval *li) {
320 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
321 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
322 return i != valueMap_.end() && i->second == 0;
325 // defValue - Introduce a li_ def for ParentVNI that could be later than
327 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
328 assert(li_ && "call reset first");
329 assert(ParentVNI && "Mapping NULL value");
330 assert(Idx.isValid() && "Invalid SlotIndex");
331 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
333 // Create a new value.
334 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
336 // Use insert for lookup, so we can add missing values with a second lookup.
337 std::pair<ValueMap::iterator,bool> InsP =
338 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
340 // This is now a complex def. Mark with a NULL in valueMap.
342 InsP.first->second = 0;
348 // mapValue - Find the mapped value for ParentVNI at Idx.
349 // Potentially create phi-def values.
350 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
352 assert(li_ && "call reset first");
353 assert(ParentVNI && "Mapping NULL value");
354 assert(Idx.isValid() && "Invalid SlotIndex");
355 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
357 // Use insert for lookup, so we can add missing values with a second lookup.
358 std::pair<ValueMap::iterator,bool> InsP =
359 valueMap_.insert(makeVV(ParentVNI, 0));
361 // This was an unknown value. Create a simple mapping.
363 if (simple) *simple = true;
364 return InsP.first->second = li_->createValueCopy(ParentVNI,
365 lis_.getVNInfoAllocator());
368 // This was a simple mapped value.
369 if (InsP.first->second) {
370 if (simple) *simple = true;
371 return InsP.first->second;
374 // This is a complex mapped value. There may be multiple defs, and we may need
375 // to create phi-defs.
376 if (simple) *simple = false;
377 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
378 assert(IdxMBB && "No MBB at Idx");
380 // Is there a def in the same MBB we can extend?
381 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
384 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
385 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
386 // Perform a depth-first search for predecessor blocks where we know the
387 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
389 // Track MBBs where we have created or learned the dominating value.
390 // This may change during the DFS as we create new phi-defs.
391 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
392 MBBValueMap DomValue;
393 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
396 // Iterate over IdxMBB predecessors in a depth-first order.
397 // Skip begin() since that is always IdxMBB.
398 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
399 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
400 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
401 MachineBasicBlock *MBB = *IDFI;
402 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
404 // We are operating on the restricted CFG where ParentVNI is live.
405 if (parentli_.getVNInfoAt(End) != ParentVNI) {
410 // Do we have a dominating value in this block?
411 VNInfo *VNI = extendTo(MBB, End);
417 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
420 // Track the path back to IdxMBB, creating phi-defs
421 // as needed along the way.
422 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
423 // Start from MBB's immediate successor. End at IdxMBB.
424 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
425 std::pair<MBBValueMap::iterator, bool> InsP =
426 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
428 // This is the first time we backtrack to Succ.
432 // We reached Succ again with the same VNI. Nothing is going to change.
433 VNInfo *OVNI = InsP.first->second;
437 // Succ already has a phi-def. No need to continue.
438 SlotIndex Start = lis_.getMBBStartIdx(Succ);
439 if (OVNI->def == Start)
442 // We have a collision between the old and new VNI at Succ. That means
443 // neither dominates and we need a new phi-def.
444 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
445 VNI->setIsPHIDef(true);
446 InsP.first->second = VNI;
448 // Replace OVNI with VNI in the remaining path.
449 for (; PI > 1 ; --PI) {
450 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
451 if (I == DomValue.end() || I->second != OVNI)
457 // No need to search the children, we found a dominating value.
461 // The search should at least find a dominating value for IdxMBB.
462 assert(!DomValue.empty() && "Couldn't find a reaching definition");
464 // Since we went through the trouble of a full DFS visiting all reaching defs,
465 // the values in DomValue are now accurate. No more phi-defs are needed for
466 // these blocks, so we can color the live ranges.
467 // This makes the next mapValue call much faster.
469 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
471 MachineBasicBlock *MBB = I->first;
472 VNInfo *VNI = I->second;
473 SlotIndex Start = lis_.getMBBStartIdx(MBB);
475 // Don't add full liveness to IdxMBB, stop at Idx.
477 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
478 // The caller had better add some liveness to IdxVNI, or it leaks.
481 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
484 assert(IdxVNI && "Didn't find value for Idx");
488 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
489 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
490 // Return the found VNInfo, or NULL.
491 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
492 assert(li_ && "call reset first");
493 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
494 if (I == li_->begin())
497 if (I->end <= lis_.getMBBStartIdx(MBB))
500 I->end = Idx.getNextSlot();
504 // addSimpleRange - Add a simple range from parentli_ to li_.
505 // ParentVNI must be live in the [Start;End) interval.
506 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
507 const VNInfo *ParentVNI) {
508 assert(li_ && "call reset first");
510 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
511 // A simple mapping is easy.
513 li_->addRange(LiveRange(Start, End, VNI));
517 // ParentVNI is a complex value. We must map per MBB.
518 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
519 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
522 li_->addRange(LiveRange(Start, End, VNI));
527 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
529 // Run sequence of full blocks.
530 for (++MBB; MBB != MBBE; ++MBB) {
531 Start = lis_.getMBBStartIdx(MBB);
532 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
533 mapValue(ParentVNI, Start)));
537 Start = lis_.getMBBStartIdx(MBB);
539 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
542 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
543 /// All needed values whose def is not inside [Start;End) must be defined
544 /// beforehand so mapValue will work.
545 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
546 assert(li_ && "call reset first");
547 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
548 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
550 // Check if --I begins before Start and overlaps.
554 addSimpleRange(Start, std::min(End, I->end), I->valno);
558 // The remaining ranges begin after Start.
559 for (;I != E && I->start < End; ++I)
560 addSimpleRange(I->start, std::min(End, I->end), I->valno);
563 VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
564 const VNInfo *ParentVNI,
565 MachineBasicBlock &MBB,
566 MachineBasicBlock::iterator I) {
567 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
568 get(TargetOpcode::COPY);
569 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
570 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
571 VNInfo *VNI = defValue(ParentVNI, DefIdx);
573 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
577 //===----------------------------------------------------------------------===//
579 //===----------------------------------------------------------------------===//
581 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
582 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
583 SmallVectorImpl<LiveInterval*> &intervals)
584 : sa_(sa), lis_(lis), vrm_(vrm),
585 mri_(vrm.getMachineFunction().getRegInfo()),
586 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
587 curli_(sa_.getCurLI()),
588 dupli_(lis_, *curli_),
589 openli_(lis_, *curli_),
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 Reg = mri_.createVirtualRegister(mri_.getRegClass(curli_->reg));
604 LiveInterval &Intv = lis_.getOrCreateInterval(Reg);
606 vrm_.assignVirt2StackSlot(Reg, vrm_.getStackSlot(curli_->reg));
610 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
611 for (int i = firstInterval, e = intervals_.size(); i != e; ++i)
612 if (intervals_[i]->liveAt(Idx))
617 /// Create a new virtual register and live interval.
618 void SplitEditor::openIntv() {
619 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
622 dupli_.reset(createInterval());
624 openli_.reset(createInterval());
625 intervals_.push_back(openli_.getLI());
628 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
629 /// not live before Idx, a COPY is not inserted.
630 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
631 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
632 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getUseIndex());
634 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": not live\n");
637 truncatedValues.insert(ParentVNI);
638 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
639 assert(MI && "enterIntvBefore called with invalid index");
640 openli_.defByCopyFrom(curli_->reg, ParentVNI, *MI->getParent(), MI);
641 DEBUG(dbgs() << " enterIntvBefore " << Idx << ": " << *openli_.getLI()
645 /// enterIntvAtEnd - Enter openli at the end of MBB.
646 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
647 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
648 SlotIndex End = lis_.getMBBEndIdx(&MBB);
649 VNInfo *ParentVNI = curli_->getVNInfoAt(End.getPrevSlot());
651 DEBUG(dbgs() << " enterIntvAtEnd " << End << ": not live\n");
654 truncatedValues.insert(ParentVNI);
655 VNInfo *VNI = openli_.defByCopyFrom(curli_->reg, ParentVNI,
656 MBB, MBB.getFirstTerminator());
657 // Make sure openli is live out of MBB.
658 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
659 DEBUG(dbgs() << " enterIntvAtEnd: " << *openli_.getLI() << '\n');
662 /// useIntv - indicate that all instructions in MBB should use openli.
663 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
664 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
667 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
668 assert(openli_.getLI() && "openIntv not called before useIntv");
669 openli_.addRange(Start, End);
670 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
671 << *openli_.getLI() << '\n');
674 /// leaveIntvAfter - Leave openli after the instruction at Idx.
675 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
676 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
678 // The interval must be live beyond the instruction at Idx.
679 VNInfo *ParentVNI = curli_->getVNInfoAt(Idx.getBoundaryIndex());
681 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": not live\n");
685 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
686 MachineBasicBlock *MBB = MII->getParent();
687 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
690 // Finally we must make sure that openli is properly extended from Idx to the
692 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
693 DEBUG(dbgs() << " leaveIntvAfter " << Idx << ": " << *openli_.getLI()
697 /// leaveIntvAtTop - Leave the interval at the top of MBB.
698 /// Currently, only one value can leave the interval.
699 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
700 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
702 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
703 VNInfo *ParentVNI = curli_->getVNInfoAt(Start);
705 // Is curli even live-in to MBB?
707 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": not live\n");
711 // We are going to insert a back copy, so we must have a dupli_.
712 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
715 // Finally we must make sure that openli is properly extended from Start to
717 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
718 DEBUG(dbgs() << " leaveIntvAtTop at " << Start << ": " << *openli_.getLI()
722 /// closeIntv - Indicate that we are done editing the currently open
723 /// LiveInterval, and ranges can be trimmed.
724 void SplitEditor::closeIntv() {
725 assert(openli_.getLI() && "openIntv not called before closeIntv");
727 DEBUG(dbgs() << " closeIntv cleaning up\n");
728 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
733 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
734 SlotIndex sidx = Start;
736 // Break [Start;End) into segments that don't overlap any intervals.
738 SlotIndex next = sidx, eidx = End;
739 // Find overlapping intervals.
740 for (int i = firstInterval, e = intervals_.size(); i != e && sidx < eidx;
742 LiveInterval::const_iterator I = intervals_[i]->find(sidx);
743 LiveInterval::const_iterator E = intervals_[i]->end();
746 // Interval I is overlapping [sidx;eidx). Trim sidx.
747 if (I->start <= sidx) {
752 // Trim eidx too if needed.
753 if (I->start >= eidx)
759 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
761 dupli_.addSimpleRange(sidx, eidx, VNI);
762 // If the interval end was truncated, we can try again from next.
769 /// rewrite - after all the new live ranges have been created, rewrite
770 /// instructions using curli to use the new intervals.
771 void SplitEditor::rewrite() {
772 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
773 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
775 // First we need to fill in the live ranges in dupli.
776 // If values were redefined, we need a full recoloring with SSA update.
777 // If values were truncated, we only need to truncate the ranges.
778 // If values were partially rematted, we should shrink to uses.
779 // If values were fully rematted, they should be omitted.
780 // FIXME: If a single value is redefined, just move the def and truncate.
782 // Values that are fully contained in the split intervals.
783 SmallPtrSet<const VNInfo*, 8> deadValues;
785 // Map all curli values that should have live defs in dupli.
786 for (LiveInterval::const_vni_iterator I = curli_->vni_begin(),
787 E = curli_->vni_end(); I != E; ++I) {
788 const VNInfo *VNI = *I;
789 // Original def is contained in the split intervals.
790 if (intervalsLiveAt(VNI->def)) {
791 // Did this value escape?
792 if (dupli_.isMapped(VNI))
793 truncatedValues.insert(VNI);
795 deadValues.insert(VNI);
798 // Add minimal live range at the definition.
799 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
800 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
803 // Add all ranges to dupli.
804 for (LiveInterval::const_iterator I = curli_->begin(), E = curli_->end();
806 const LiveRange &LR = *I;
807 if (truncatedValues.count(LR.valno)) {
808 // recolor after removing intervals_.
809 addTruncSimpleRange(LR.start, LR.end, LR.valno);
810 } else if (!deadValues.count(LR.valno)) {
811 // recolor without truncation.
812 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
817 const LiveInterval *curli = sa_.getCurLI();
818 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(curli->reg),
819 RE = mri_.reg_end(); RI != RE;) {
820 MachineOperand &MO = RI.getOperand();
821 MachineInstr *MI = MO.getParent();
823 if (MI->isDebugValue()) {
824 DEBUG(dbgs() << "Zapping " << *MI);
825 // FIXME: We can do much better with debug values.
829 SlotIndex Idx = lis_.getInstructionIndex(MI);
830 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
831 LiveInterval *LI = dupli_.getLI();
832 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
833 LiveInterval *testli = intervals_[i];
834 if (testli->liveAt(Idx)) {
840 DEBUG(dbgs() << " rewrite " << Idx << '\t' << *MI);
843 // dupli_ goes in last, after rewriting.
844 if (dupli_.getLI()->empty()) {
845 DEBUG(dbgs() << " dupli became empty?\n");
846 lis_.removeInterval(dupli_.getLI()->reg);
849 dupli_.getLI()->RenumberValues(lis_);
850 intervals_.push_back(dupli_.getLI());
853 // Calculate spill weight and allocation hints for new intervals.
854 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
855 for (unsigned i = firstInterval, e = intervals_.size(); i != e; ++i) {
856 LiveInterval &li = *intervals_[i];
857 vrai.CalculateRegClass(li.reg);
858 vrai.CalculateWeightAndHint(li);
859 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
860 << ":" << li << '\n');
865 //===----------------------------------------------------------------------===//
867 //===----------------------------------------------------------------------===//
869 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
870 SplitAnalysis::LoopBlocks Blocks;
871 sa_.getLoopBlocks(Loop, Blocks);
873 // Break critical edges as needed.
874 SplitAnalysis::BlockPtrSet CriticalExits;
875 sa_.getCriticalExits(Blocks, CriticalExits);
876 assert(CriticalExits.empty() && "Cannot break critical exits yet");
878 // Create new live interval for the loop.
881 // Insert copies in the predecessors.
882 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
883 E = Blocks.Preds.end(); I != E; ++I) {
884 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
888 // Switch all loop blocks.
889 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
890 E = Blocks.Loop.end(); I != E; ++I)
893 // Insert back copies in the exit blocks.
894 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
895 E = Blocks.Exits.end(); I != E; ++I) {
896 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
906 //===----------------------------------------------------------------------===//
907 // Single Block Splitting
908 //===----------------------------------------------------------------------===//
910 /// splitSingleBlocks - Split curli into a separate live interval inside each
911 /// basic block in Blocks.
912 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
913 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
914 // Determine the first and last instruction using curli in each block.
915 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
916 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
917 IndexPairMap MBBRange;
918 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
919 E = sa_.usingInstrs_.end(); I != E; ++I) {
920 const MachineBasicBlock *MBB = (*I)->getParent();
921 if (!Blocks.count(MBB))
923 SlotIndex Idx = lis_.getInstructionIndex(*I);
924 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
925 IndexPair &IP = MBBRange[MBB];
926 if (!IP.first.isValid() || Idx < IP.first)
928 if (!IP.second.isValid() || Idx > IP.second)
932 // Create a new interval for each block.
933 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
934 E = Blocks.end(); I != E; ++I) {
935 IndexPair &IP = MBBRange[*I];
936 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
937 << IP.first << ';' << IP.second << ")\n");
938 assert(IP.first.isValid() && IP.second.isValid());
941 enterIntvBefore(IP.first);
942 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
943 leaveIntvAfter(IP.second);
950 //===----------------------------------------------------------------------===//
951 // Sub Block Splitting
952 //===----------------------------------------------------------------------===//
954 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
955 /// and it wou pay to subdivide the interval inside that block, return it.
956 /// Otherwise return NULL. The returned block can be passed to
957 /// SplitEditor::splitInsideBlock.
958 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
959 // The interval must be exclusive to one block.
960 if (usingBlocks_.size() != 1)
962 // Don't to this for less than 4 instructions. We want to be sure that
963 // splitting actually reduces the instruction count per interval.
964 if (usingInstrs_.size() < 4)
966 return usingBlocks_.begin()->first;
969 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
970 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
971 SmallVector<SlotIndex, 32> Uses;
972 Uses.reserve(sa_.usingInstrs_.size());
973 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
974 E = sa_.usingInstrs_.end(); I != E; ++I)
975 if ((*I)->getParent() == MBB)
976 Uses.push_back(lis_.getInstructionIndex(*I));
977 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
978 << Uses.size() << " instructions.\n");
979 assert(Uses.size() >= 3 && "Need at least 3 instructions");
980 array_pod_sort(Uses.begin(), Uses.end());
982 // Simple algorithm: Find the largest gap between uses as determined by slot
983 // indices. Create new intervals for instructions before the gap and after the
985 unsigned bestPos = 0;
987 DEBUG(dbgs() << " dist (" << Uses[0]);
988 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
989 int g = Uses[i-1].distance(Uses[i]);
990 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
992 bestPos = i, bestGap = g;
994 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
996 // bestPos points to the first use after the best gap.
997 assert(bestPos > 0 && "Invalid gap");
999 // FIXME: Don't create intervals for low densities.
1001 // First interval before the gap. Don't create single-instr intervals.
1004 enterIntvBefore(Uses.front());
1005 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1006 leaveIntvAfter(Uses[bestPos-1]);
1010 // Second interval after the gap.
1011 if (bestPos < Uses.size()-1) {
1013 enterIntvBefore(Uses[bestPos]);
1014 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1015 leaveIntvAfter(Uses.back());