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 "LiveRangeEdit.h"
18 #include "VirtRegMap.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineInstrBuilder.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
33 AllowSplit("spiller-splits-edges",
34 cl::desc("Allow critical edge splitting during spilling"));
36 //===----------------------------------------------------------------------===//
38 //===----------------------------------------------------------------------===//
40 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
41 const LiveIntervals &lis,
42 const MachineLoopInfo &mli)
46 tii_(*mf.getTarget().getInstrInfo()),
49 void SplitAnalysis::clear() {
56 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
57 MachineBasicBlock *T, *F;
58 SmallVector<MachineOperand, 4> Cond;
59 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
62 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
63 void SplitAnalysis::analyzeUses() {
64 const MachineRegisterInfo &MRI = mf_.getRegInfo();
65 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
66 MachineInstr *MI = I.skipInstruction();) {
67 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
69 MachineBasicBlock *MBB = MI->getParent();
70 if (usingBlocks_[MBB]++)
72 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
73 Loop = Loop->getParentLoop())
76 DEBUG(dbgs() << " counted "
77 << usingInstrs_.size() << " instrs, "
78 << usingBlocks_.size() << " blocks, "
79 << usingLoops_.size() << " loops.\n");
82 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
83 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
84 unsigned count = usingBlocks_.lookup(*I);
85 OS << " BB#" << (*I)->getNumber();
87 OS << '(' << count << ')';
91 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
92 // predecessor blocks, and exit blocks.
93 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
96 // Blocks in the loop.
97 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
99 // Predecessor blocks.
100 const MachineBasicBlock *Header = Loop->getHeader();
101 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
102 E = Header->pred_end(); I != E; ++I)
103 if (!Blocks.Loop.count(*I))
104 Blocks.Preds.insert(*I);
107 for (MachineLoop::block_iterator I = Loop->block_begin(),
108 E = Loop->block_end(); I != E; ++I) {
109 const MachineBasicBlock *MBB = *I;
110 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
111 SE = MBB->succ_end(); SI != SE; ++SI)
112 if (!Blocks.Loop.count(*SI))
113 Blocks.Exits.insert(*SI);
117 void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
126 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
127 /// and around the Loop.
128 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
129 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
130 LoopPeripheralUse use = ContainedInLoop;
131 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
133 const MachineBasicBlock *MBB = I->first;
134 // Is this a peripheral block?
135 if (use < MultiPeripheral &&
136 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
137 if (I->second > 1) use = MultiPeripheral;
138 else use = SinglePeripheral;
141 // Is it a loop block?
142 if (Blocks.Loop.count(MBB))
144 // It must be an unrelated block.
145 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
151 /// getCriticalExits - It may be necessary to partially break critical edges
152 /// leaving the loop if an exit block has predecessors from outside the loop
154 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
155 BlockPtrSet &CriticalExits) {
156 CriticalExits.clear();
158 // A critical exit block has curli line-in, and has a predecessor that is not
159 // in the loop nor a loop predecessor. For such an exit block, the edges
160 // carrying the new variable must be moved to a new pre-exit block.
161 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
163 const MachineBasicBlock *Exit = *I;
164 // A single-predecessor exit block is definitely not a critical edge.
165 if (Exit->pred_size() == 1)
167 // This exit may not have curli live in at all. No need to split.
168 if (!lis_.isLiveInToMBB(*curli_, Exit))
170 // Does this exit block have a predecessor that is not a loop block or loop
172 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
173 PE = Exit->pred_end(); PI != PE; ++PI) {
174 const MachineBasicBlock *Pred = *PI;
175 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
177 // This is a critical exit block, and we need to split the exit edge.
178 CriticalExits.insert(Exit);
184 /// canSplitCriticalExits - Return true if it is possible to insert new exit
185 /// blocks before the blocks in CriticalExits.
187 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
188 BlockPtrSet &CriticalExits) {
189 // If we don't allow critical edge splitting, require no critical exits.
191 return CriticalExits.empty();
193 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
195 const MachineBasicBlock *Succ = *I;
196 // We want to insert a new pre-exit MBB before Succ, and change all the
197 // in-loop blocks to branch to the pre-exit instead of Succ.
198 // Check that all the in-loop predecessors can be changed.
199 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
200 PE = Succ->pred_end(); PI != PE; ++PI) {
201 const MachineBasicBlock *Pred = *PI;
202 // The external predecessors won't be altered.
203 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
205 if (!canAnalyzeBranch(Pred))
209 // If Succ's layout predecessor falls through, that too must be analyzable.
210 // We need to insert the pre-exit block in the gap.
211 MachineFunction::const_iterator MFI = Succ;
212 if (MFI == mf_.begin())
214 if (!canAnalyzeBranch(--MFI))
217 // No problems found.
221 void SplitAnalysis::analyze(const LiveInterval *li) {
227 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
228 assert(curli_ && "Call analyze() before getBestSplitLoop");
229 if (usingLoops_.empty())
234 BlockPtrSet CriticalExits;
236 // We split around loops where curli is used outside the periphery.
237 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
238 E = usingLoops_.end(); I != E; ++I) {
239 const MachineLoop *Loop = I->first;
240 getLoopBlocks(Loop, Blocks);
241 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
243 switch(analyzeLoopPeripheralUse(Blocks)) {
246 case MultiPeripheral:
247 // FIXME: We could split a live range with multiple uses in a peripheral
248 // block and still make progress. However, it is possible that splitting
249 // another live range will insert copies into a peripheral block, and
250 // there is a small chance we can enter an infinity loop, inserting copies
252 // For safety, stick to splitting live ranges with uses outside the
254 DEBUG(dbgs() << ": multiple peripheral uses\n");
256 case ContainedInLoop:
257 DEBUG(dbgs() << ": fully contained\n");
259 case SinglePeripheral:
260 DEBUG(dbgs() << ": single peripheral use\n");
263 // Will it be possible to split around this loop?
264 getCriticalExits(Blocks, CriticalExits);
265 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
266 if (!canSplitCriticalExits(Blocks, CriticalExits))
268 // This is a possible split.
272 DEBUG(dbgs() << " getBestSplitLoop found " << Loops.size()
273 << " candidate loops.\n");
278 // Pick the earliest loop.
279 // FIXME: Are there other heuristics to consider?
280 const MachineLoop *Best = 0;
282 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
284 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
285 if (!Best || Idx < BestIdx)
286 Best = *I, BestIdx = Idx;
288 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
292 //===----------------------------------------------------------------------===//
294 //===----------------------------------------------------------------------===//
296 // Work around the fact that the std::pair constructors are broken for pointer
297 // pairs in some implementations. makeVV(x, 0) works.
298 static inline std::pair<const VNInfo*, VNInfo*>
299 makeVV(const VNInfo *a, VNInfo *b) {
300 return std::make_pair(a, b);
303 void LiveIntervalMap::reset(LiveInterval *li) {
308 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
309 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
310 return i != valueMap_.end() && i->second == 0;
313 // defValue - Introduce a li_ def for ParentVNI that could be later than
315 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
316 assert(li_ && "call reset first");
317 assert(ParentVNI && "Mapping NULL value");
318 assert(Idx.isValid() && "Invalid SlotIndex");
319 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
321 // Create a new value.
322 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
324 // Preserve the PHIDef bit.
325 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
326 VNI->setIsPHIDef(true);
328 // Use insert for lookup, so we can add missing values with a second lookup.
329 std::pair<ValueMap::iterator,bool> InsP =
330 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
332 // This is now a complex def. Mark with a NULL in valueMap.
334 InsP.first->second = 0;
340 // mapValue - Find the mapped value for ParentVNI at Idx.
341 // Potentially create phi-def values.
342 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
344 assert(li_ && "call reset first");
345 assert(ParentVNI && "Mapping NULL value");
346 assert(Idx.isValid() && "Invalid SlotIndex");
347 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
349 // Use insert for lookup, so we can add missing values with a second lookup.
350 std::pair<ValueMap::iterator,bool> InsP =
351 valueMap_.insert(makeVV(ParentVNI, 0));
353 // This was an unknown value. Create a simple mapping.
355 if (simple) *simple = true;
356 return InsP.first->second = li_->createValueCopy(ParentVNI,
357 lis_.getVNInfoAllocator());
360 // This was a simple mapped value.
361 if (InsP.first->second) {
362 if (simple) *simple = true;
363 return InsP.first->second;
366 // This is a complex mapped value. There may be multiple defs, and we may need
367 // to create phi-defs.
368 if (simple) *simple = false;
369 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
370 assert(IdxMBB && "No MBB at Idx");
372 // Is there a def in the same MBB we can extend?
373 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
376 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
377 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
378 // Perform a depth-first search for predecessor blocks where we know the
379 // dominating VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
381 // Track MBBs where we have created or learned the dominating value.
382 // This may change during the DFS as we create new phi-defs.
383 typedef DenseMap<MachineBasicBlock*, VNInfo*> MBBValueMap;
384 MBBValueMap DomValue;
385 typedef SplitAnalysis::BlockPtrSet BlockPtrSet;
388 // Iterate over IdxMBB predecessors in a depth-first order.
389 // Skip begin() since that is always IdxMBB.
390 for (idf_ext_iterator<MachineBasicBlock*, BlockPtrSet>
391 IDFI = llvm::next(idf_ext_begin(IdxMBB, Visited)),
392 IDFE = idf_ext_end(IdxMBB, Visited); IDFI != IDFE;) {
393 MachineBasicBlock *MBB = *IDFI;
394 SlotIndex End = lis_.getMBBEndIdx(MBB).getPrevSlot();
396 // We are operating on the restricted CFG where ParentVNI is live.
397 if (parentli_.getVNInfoAt(End) != ParentVNI) {
402 // Do we have a dominating value in this block?
403 VNInfo *VNI = extendTo(MBB, End);
409 // Yes, VNI dominates MBB. Make sure we visit MBB again from other paths.
412 // Track the path back to IdxMBB, creating phi-defs
413 // as needed along the way.
414 for (unsigned PI = IDFI.getPathLength()-1; PI != 0; --PI) {
415 // Start from MBB's immediate successor. End at IdxMBB.
416 MachineBasicBlock *Succ = IDFI.getPath(PI-1);
417 std::pair<MBBValueMap::iterator, bool> InsP =
418 DomValue.insert(MBBValueMap::value_type(Succ, VNI));
420 // This is the first time we backtrack to Succ.
424 // We reached Succ again with the same VNI. Nothing is going to change.
425 VNInfo *OVNI = InsP.first->second;
429 // Succ already has a phi-def. No need to continue.
430 SlotIndex Start = lis_.getMBBStartIdx(Succ);
431 if (OVNI->def == Start)
434 // We have a collision between the old and new VNI at Succ. That means
435 // neither dominates and we need a new phi-def.
436 VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
437 VNI->setIsPHIDef(true);
438 InsP.first->second = VNI;
440 // Replace OVNI with VNI in the remaining path.
441 for (; PI > 1 ; --PI) {
442 MBBValueMap::iterator I = DomValue.find(IDFI.getPath(PI-2));
443 if (I == DomValue.end() || I->second != OVNI)
449 // No need to search the children, we found a dominating value.
453 // The search should at least find a dominating value for IdxMBB.
454 assert(!DomValue.empty() && "Couldn't find a reaching definition");
456 // Since we went through the trouble of a full DFS visiting all reaching defs,
457 // the values in DomValue are now accurate. No more phi-defs are needed for
458 // these blocks, so we can color the live ranges.
459 // This makes the next mapValue call much faster.
461 for (MBBValueMap::iterator I = DomValue.begin(), E = DomValue.end(); I != E;
463 MachineBasicBlock *MBB = I->first;
464 VNInfo *VNI = I->second;
465 SlotIndex Start = lis_.getMBBStartIdx(MBB);
467 // Don't add full liveness to IdxMBB, stop at Idx.
469 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
470 // The caller had better add some liveness to IdxVNI, or it leaks.
473 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
476 assert(IdxVNI && "Didn't find value for Idx");
480 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
481 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
482 // Return the found VNInfo, or NULL.
483 VNInfo *LiveIntervalMap::extendTo(MachineBasicBlock *MBB, SlotIndex Idx) {
484 assert(li_ && "call reset first");
485 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
486 if (I == li_->begin())
489 if (I->end <= lis_.getMBBStartIdx(MBB))
492 I->end = Idx.getNextSlot();
496 // addSimpleRange - Add a simple range from parentli_ to li_.
497 // ParentVNI must be live in the [Start;End) interval.
498 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
499 const VNInfo *ParentVNI) {
500 assert(li_ && "call reset first");
502 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
503 // A simple mapping is easy.
505 li_->addRange(LiveRange(Start, End, VNI));
509 // ParentVNI is a complex value. We must map per MBB.
510 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
511 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
514 li_->addRange(LiveRange(Start, End, VNI));
519 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
521 // Run sequence of full blocks.
522 for (++MBB; MBB != MBBE; ++MBB) {
523 Start = lis_.getMBBStartIdx(MBB);
524 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
525 mapValue(ParentVNI, Start)));
529 Start = lis_.getMBBStartIdx(MBB);
531 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
534 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
535 /// All needed values whose def is not inside [Start;End) must be defined
536 /// beforehand so mapValue will work.
537 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
538 assert(li_ && "call reset first");
539 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
540 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
542 // Check if --I begins before Start and overlaps.
546 addSimpleRange(Start, std::min(End, I->end), I->valno);
550 // The remaining ranges begin after Start.
551 for (;I != E && I->start < End; ++I)
552 addSimpleRange(I->start, std::min(End, I->end), I->valno);
555 VNInfo *LiveIntervalMap::defByCopyFrom(unsigned Reg,
556 const VNInfo *ParentVNI,
557 MachineBasicBlock &MBB,
558 MachineBasicBlock::iterator I) {
559 const TargetInstrDesc &TID = MBB.getParent()->getTarget().getInstrInfo()->
560 get(TargetOpcode::COPY);
561 MachineInstr *MI = BuildMI(MBB, I, DebugLoc(), TID, li_->reg).addReg(Reg);
562 SlotIndex DefIdx = lis_.InsertMachineInstrInMaps(MI).getDefIndex();
563 VNInfo *VNI = defValue(ParentVNI, DefIdx);
565 li_->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), VNI));
569 //===----------------------------------------------------------------------===//
571 //===----------------------------------------------------------------------===//
573 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
574 SplitEditor::SplitEditor(SplitAnalysis &sa, LiveIntervals &lis, VirtRegMap &vrm,
576 : sa_(sa), lis_(lis), vrm_(vrm),
577 mri_(vrm.getMachineFunction().getRegInfo()),
578 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
580 dupli_(lis_, edit.getParent()),
581 openli_(lis_, edit.getParent())
585 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
586 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
587 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
592 /// Create a new virtual register and live interval.
593 void SplitEditor::openIntv() {
594 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
597 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
599 openli_.reset(&edit_.create(mri_, lis_, vrm_));
602 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
603 /// not live before Idx, a COPY is not inserted.
604 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
605 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
606 DEBUG(dbgs() << " enterIntvBefore " << Idx);
607 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getUseIndex());
609 DEBUG(dbgs() << ": not live\n");
612 DEBUG(dbgs() << ": valno " << ParentVNI->id);
613 truncatedValues.insert(ParentVNI);
614 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
615 assert(MI && "enterIntvBefore called with invalid index");
616 VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
617 *MI->getParent(), MI);
618 openli_.getLI()->addRange(LiveRange(VNI->def, Idx.getDefIndex(), VNI));
619 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
622 /// enterIntvAtEnd - Enter openli at the end of MBB.
623 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
624 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
625 SlotIndex End = lis_.getMBBEndIdx(&MBB);
626 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
627 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End.getPrevSlot());
629 DEBUG(dbgs() << ": not live\n");
632 DEBUG(dbgs() << ": valno " << ParentVNI->id);
633 truncatedValues.insert(ParentVNI);
634 VNInfo *VNI = openli_.defByCopyFrom(edit_.getReg(), ParentVNI,
635 MBB, MBB.getFirstTerminator());
636 // Make sure openli is live out of MBB.
637 openli_.getLI()->addRange(LiveRange(VNI->def, End, VNI));
638 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
641 /// useIntv - indicate that all instructions in MBB should use openli.
642 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
643 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
646 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
647 assert(openli_.getLI() && "openIntv not called before useIntv");
648 openli_.addRange(Start, End);
649 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
650 << *openli_.getLI() << '\n');
653 /// leaveIntvAfter - Leave openli after the instruction at Idx.
654 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
655 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
656 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
658 // The interval must be live beyond the instruction at Idx.
659 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx.getBoundaryIndex());
661 DEBUG(dbgs() << ": not live\n");
664 DEBUG(dbgs() << ": valno " << ParentVNI->id);
666 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
667 MachineBasicBlock *MBB = MII->getParent();
668 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI, *MBB,
671 // Finally we must make sure that openli is properly extended from Idx to the
673 openli_.addSimpleRange(Idx.getBoundaryIndex(), VNI->def, ParentVNI);
674 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
677 /// leaveIntvAtTop - Leave the interval at the top of MBB.
678 /// Currently, only one value can leave the interval.
679 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
680 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
681 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
682 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
684 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
686 DEBUG(dbgs() << ": not live\n");
690 // We are going to insert a back copy, so we must have a dupli_.
691 VNInfo *VNI = dupli_.defByCopyFrom(openli_.getLI()->reg, ParentVNI,
694 // Finally we must make sure that openli is properly extended from Start to
696 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
697 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
700 /// closeIntv - Indicate that we are done editing the currently open
701 /// LiveInterval, and ranges can be trimmed.
702 void SplitEditor::closeIntv() {
703 assert(openli_.getLI() && "openIntv not called before closeIntv");
705 DEBUG(dbgs() << " closeIntv cleaning up\n");
706 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
710 /// rewrite - Rewrite all uses of reg to use the new registers.
711 void SplitEditor::rewrite(unsigned reg) {
712 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
713 RE = mri_.reg_end(); RI != RE;) {
714 MachineOperand &MO = RI.getOperand();
715 MachineInstr *MI = MO.getParent();
717 if (MI->isDebugValue()) {
718 DEBUG(dbgs() << "Zapping " << *MI);
719 // FIXME: We can do much better with debug values.
723 SlotIndex Idx = lis_.getInstructionIndex(MI);
724 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
725 LiveInterval *LI = 0;
726 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
728 LiveInterval *testli = *I;
729 if (testli->liveAt(Idx)) {
734 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
735 assert(LI && "No register was live at use");
737 DEBUG(dbgs() << '\t' << *MI);
742 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
743 // Build vector of iterator pairs from the intervals.
744 typedef std::pair<LiveInterval::const_iterator,
745 LiveInterval::const_iterator> IIPair;
746 SmallVector<IIPair, 8> Iters;
747 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
749 if (*LI == dupli_.getLI())
751 LiveInterval::const_iterator I = (*LI)->find(Start);
752 LiveInterval::const_iterator E = (*LI)->end();
754 Iters.push_back(std::make_pair(I, E));
757 SlotIndex sidx = Start;
758 // Break [Start;End) into segments that don't overlap any intervals.
760 SlotIndex next = sidx, eidx = End;
761 // Find overlapping intervals.
762 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
763 LiveInterval::const_iterator I = Iters[i].first;
764 // Interval I is overlapping [sidx;eidx). Trim sidx.
765 if (I->start <= sidx) {
767 // Move to the next run, remove iters when all are consumed.
768 I = ++Iters[i].first;
769 if (I == Iters[i].second) {
770 Iters.erase(Iters.begin() + i);
775 // Trim eidx too if needed.
776 if (I->start >= eidx)
781 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
783 dupli_.addSimpleRange(sidx, eidx, VNI);
784 // If the interval end was truncated, we can try again from next.
791 void SplitEditor::computeRemainder() {
792 // First we need to fill in the live ranges in dupli.
793 // If values were redefined, we need a full recoloring with SSA update.
794 // If values were truncated, we only need to truncate the ranges.
795 // If values were partially rematted, we should shrink to uses.
796 // If values were fully rematted, they should be omitted.
797 // FIXME: If a single value is redefined, just move the def and truncate.
798 LiveInterval &parent = edit_.getParent();
800 // Values that are fully contained in the split intervals.
801 SmallPtrSet<const VNInfo*, 8> deadValues;
802 // Map all curli values that should have live defs in dupli.
803 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
804 E = parent.vni_end(); I != E; ++I) {
805 const VNInfo *VNI = *I;
806 // Original def is contained in the split intervals.
807 if (intervalsLiveAt(VNI->def)) {
808 // Did this value escape?
809 if (dupli_.isMapped(VNI))
810 truncatedValues.insert(VNI);
812 deadValues.insert(VNI);
815 // Add minimal live range at the definition.
816 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
817 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
820 // Add all ranges to dupli.
821 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
823 const LiveRange &LR = *I;
824 if (truncatedValues.count(LR.valno)) {
825 // recolor after removing intervals_.
826 addTruncSimpleRange(LR.start, LR.end, LR.valno);
827 } else if (!deadValues.count(LR.valno)) {
828 // recolor without truncation.
829 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
834 void SplitEditor::finish() {
835 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
836 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
838 // Complete dupli liveness.
841 // Get rid of unused values and set phi-kill flags.
842 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
843 (*I)->RenumberValues(lis_);
845 // Now check if dupli was separated into multiple connected components.
846 ConnectedVNInfoEqClasses ConEQ(lis_);
847 if (unsigned NumComp = ConEQ.Classify(dupli_.getLI())) {
848 DEBUG(dbgs() << " Remainder has " << NumComp << " connected components: "
849 << *dupli_.getLI() << '\n');
850 // Did the remainder break up? Create intervals for all the components.
852 SmallVector<LiveInterval*, 8> dups;
853 dups.push_back(dupli_.getLI());
854 for (unsigned i = 1; i != NumComp; ++i)
855 dups.push_back(&edit_.create(mri_, lis_, vrm_));
856 ConEQ.Distribute(&dups[0]);
857 // Rewrite uses to the new regs.
858 rewrite(dupli_.getLI()->reg);
862 // Rewrite instructions.
863 rewrite(edit_.getReg());
865 // Calculate spill weight and allocation hints for new intervals.
866 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
867 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
868 LiveInterval &li = **I;
869 vrai.CalculateRegClass(li.reg);
870 vrai.CalculateWeightAndHint(li);
871 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
872 << ":" << li << '\n');
877 //===----------------------------------------------------------------------===//
879 //===----------------------------------------------------------------------===//
881 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
882 SplitAnalysis::LoopBlocks Blocks;
883 sa_.getLoopBlocks(Loop, Blocks);
886 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
889 // Break critical edges as needed.
890 SplitAnalysis::BlockPtrSet CriticalExits;
891 sa_.getCriticalExits(Blocks, CriticalExits);
892 assert(CriticalExits.empty() && "Cannot break critical exits yet");
894 // Create new live interval for the loop.
897 // Insert copies in the predecessors.
898 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
899 E = Blocks.Preds.end(); I != E; ++I) {
900 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
904 // Switch all loop blocks.
905 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
906 E = Blocks.Loop.end(); I != E; ++I)
909 // Insert back copies in the exit blocks.
910 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
911 E = Blocks.Exits.end(); I != E; ++I) {
912 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
922 //===----------------------------------------------------------------------===//
923 // Single Block Splitting
924 //===----------------------------------------------------------------------===//
926 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
927 /// may be an advantage to split curli for the duration of the block.
928 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
929 // If curli is local to one block, there is no point to splitting it.
930 if (usingBlocks_.size() <= 1)
932 // Add blocks with multiple uses.
933 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
940 // When there are only two uses and curli is both live in and live out,
941 // we don't really win anything by isolating the block since we would be
942 // inserting two copies.
943 // The remaing register would still have two uses in the block. (Unless it
944 // separates into disconnected components).
945 if (lis_.isLiveInToMBB(*curli_, I->first) &&
946 lis_.isLiveOutOfMBB(*curli_, I->first))
950 Blocks.insert(I->first);
952 return !Blocks.empty();
955 /// splitSingleBlocks - Split curli into a separate live interval inside each
956 /// basic block in Blocks.
957 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
958 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
959 // Determine the first and last instruction using curli in each block.
960 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
961 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
962 IndexPairMap MBBRange;
963 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
964 E = sa_.usingInstrs_.end(); I != E; ++I) {
965 const MachineBasicBlock *MBB = (*I)->getParent();
966 if (!Blocks.count(MBB))
968 SlotIndex Idx = lis_.getInstructionIndex(*I);
969 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
970 IndexPair &IP = MBBRange[MBB];
971 if (!IP.first.isValid() || Idx < IP.first)
973 if (!IP.second.isValid() || Idx > IP.second)
977 // Create a new interval for each block.
978 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
979 E = Blocks.end(); I != E; ++I) {
980 IndexPair &IP = MBBRange[*I];
981 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
982 << IP.first << ';' << IP.second << ")\n");
983 assert(IP.first.isValid() && IP.second.isValid());
986 enterIntvBefore(IP.first);
987 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
988 leaveIntvAfter(IP.second);
995 //===----------------------------------------------------------------------===//
996 // Sub Block Splitting
997 //===----------------------------------------------------------------------===//
999 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
1000 /// and it wou pay to subdivide the interval inside that block, return it.
1001 /// Otherwise return NULL. The returned block can be passed to
1002 /// SplitEditor::splitInsideBlock.
1003 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1004 // The interval must be exclusive to one block.
1005 if (usingBlocks_.size() != 1)
1007 // Don't to this for less than 4 instructions. We want to be sure that
1008 // splitting actually reduces the instruction count per interval.
1009 if (usingInstrs_.size() < 4)
1011 return usingBlocks_.begin()->first;
1014 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
1015 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1016 SmallVector<SlotIndex, 32> Uses;
1017 Uses.reserve(sa_.usingInstrs_.size());
1018 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1019 E = sa_.usingInstrs_.end(); I != E; ++I)
1020 if ((*I)->getParent() == MBB)
1021 Uses.push_back(lis_.getInstructionIndex(*I));
1022 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1023 << Uses.size() << " instructions.\n");
1024 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1025 array_pod_sort(Uses.begin(), Uses.end());
1027 // Simple algorithm: Find the largest gap between uses as determined by slot
1028 // indices. Create new intervals for instructions before the gap and after the
1030 unsigned bestPos = 0;
1032 DEBUG(dbgs() << " dist (" << Uses[0]);
1033 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1034 int g = Uses[i-1].distance(Uses[i]);
1035 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1037 bestPos = i, bestGap = g;
1039 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1041 // bestPos points to the first use after the best gap.
1042 assert(bestPos > 0 && "Invalid gap");
1044 // FIXME: Don't create intervals for low densities.
1046 // First interval before the gap. Don't create single-instr intervals.
1049 enterIntvBefore(Uses.front());
1050 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1051 leaveIntvAfter(Uses[bestPos-1]);
1055 // Second interval after the gap.
1056 if (bestPos < Uses.size()-1) {
1058 enterIntvBefore(Uses[bestPos]);
1059 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1060 leaveIntvAfter(Uses.back());