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 "regalloc"
17 #include "LiveRangeEdit.h"
18 #include "VirtRegMap.h"
19 #include "llvm/CodeGen/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/Support/CommandLine.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
34 AllowSplit("spiller-splits-edges",
35 cl::desc("Allow critical edge splitting during spilling"));
37 //===----------------------------------------------------------------------===//
39 //===----------------------------------------------------------------------===//
41 SplitAnalysis::SplitAnalysis(const MachineFunction &mf,
42 const LiveIntervals &lis,
43 const MachineLoopInfo &mli)
47 tii_(*mf.getTarget().getInstrInfo()),
50 void SplitAnalysis::clear() {
58 bool SplitAnalysis::canAnalyzeBranch(const MachineBasicBlock *MBB) {
59 MachineBasicBlock *T, *F;
60 SmallVector<MachineOperand, 4> Cond;
61 return !tii_.AnalyzeBranch(const_cast<MachineBasicBlock&>(*MBB), T, F, Cond);
64 /// analyzeUses - Count instructions, basic blocks, and loops using curli.
65 void SplitAnalysis::analyzeUses() {
66 const MachineRegisterInfo &MRI = mf_.getRegInfo();
67 for (MachineRegisterInfo::reg_iterator I = MRI.reg_begin(curli_->reg);
68 MachineInstr *MI = I.skipInstruction();) {
69 if (MI->isDebugValue() || !usingInstrs_.insert(MI))
71 UseSlots.push_back(lis_.getInstructionIndex(MI).getDefIndex());
72 MachineBasicBlock *MBB = MI->getParent();
73 if (usingBlocks_[MBB]++)
75 for (MachineLoop *Loop = loops_.getLoopFor(MBB); Loop;
76 Loop = Loop->getParentLoop())
79 array_pod_sort(UseSlots.begin(), UseSlots.end());
80 DEBUG(dbgs() << " counted "
81 << usingInstrs_.size() << " instrs, "
82 << usingBlocks_.size() << " blocks, "
83 << usingLoops_.size() << " loops.\n");
86 void SplitAnalysis::print(const BlockPtrSet &B, raw_ostream &OS) const {
87 for (BlockPtrSet::const_iterator I = B.begin(), E = B.end(); I != E; ++I) {
88 unsigned count = usingBlocks_.lookup(*I);
89 OS << " BB#" << (*I)->getNumber();
91 OS << '(' << count << ')';
95 // Get three sets of basic blocks surrounding a loop: Blocks inside the loop,
96 // predecessor blocks, and exit blocks.
97 void SplitAnalysis::getLoopBlocks(const MachineLoop *Loop, LoopBlocks &Blocks) {
100 // Blocks in the loop.
101 Blocks.Loop.insert(Loop->block_begin(), Loop->block_end());
103 // Predecessor blocks.
104 const MachineBasicBlock *Header = Loop->getHeader();
105 for (MachineBasicBlock::const_pred_iterator I = Header->pred_begin(),
106 E = Header->pred_end(); I != E; ++I)
107 if (!Blocks.Loop.count(*I))
108 Blocks.Preds.insert(*I);
111 for (MachineLoop::block_iterator I = Loop->block_begin(),
112 E = Loop->block_end(); I != E; ++I) {
113 const MachineBasicBlock *MBB = *I;
114 for (MachineBasicBlock::const_succ_iterator SI = MBB->succ_begin(),
115 SE = MBB->succ_end(); SI != SE; ++SI)
116 if (!Blocks.Loop.count(*SI))
117 Blocks.Exits.insert(*SI);
121 void SplitAnalysis::print(const LoopBlocks &B, raw_ostream &OS) const {
130 /// analyzeLoopPeripheralUse - Return an enum describing how curli_ is used in
131 /// and around the Loop.
132 SplitAnalysis::LoopPeripheralUse SplitAnalysis::
133 analyzeLoopPeripheralUse(const SplitAnalysis::LoopBlocks &Blocks) {
134 LoopPeripheralUse use = ContainedInLoop;
135 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
137 const MachineBasicBlock *MBB = I->first;
138 // Is this a peripheral block?
139 if (use < MultiPeripheral &&
140 (Blocks.Preds.count(MBB) || Blocks.Exits.count(MBB))) {
141 if (I->second > 1) use = MultiPeripheral;
142 else use = SinglePeripheral;
145 // Is it a loop block?
146 if (Blocks.Loop.count(MBB))
148 // It must be an unrelated block.
149 DEBUG(dbgs() << ", outside: BB#" << MBB->getNumber());
155 /// getCriticalExits - It may be necessary to partially break critical edges
156 /// leaving the loop if an exit block has predecessors from outside the loop
158 void SplitAnalysis::getCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
159 BlockPtrSet &CriticalExits) {
160 CriticalExits.clear();
162 // A critical exit block has curli live-in, and has a predecessor that is not
163 // in the loop nor a loop predecessor. For such an exit block, the edges
164 // carrying the new variable must be moved to a new pre-exit block.
165 for (BlockPtrSet::iterator I = Blocks.Exits.begin(), E = Blocks.Exits.end();
167 const MachineBasicBlock *Exit = *I;
168 // A single-predecessor exit block is definitely not a critical edge.
169 if (Exit->pred_size() == 1)
171 // This exit may not have curli live in at all. No need to split.
172 if (!lis_.isLiveInToMBB(*curli_, Exit))
174 // Does this exit block have a predecessor that is not a loop block or loop
176 for (MachineBasicBlock::const_pred_iterator PI = Exit->pred_begin(),
177 PE = Exit->pred_end(); PI != PE; ++PI) {
178 const MachineBasicBlock *Pred = *PI;
179 if (Blocks.Loop.count(Pred) || Blocks.Preds.count(Pred))
181 // This is a critical exit block, and we need to split the exit edge.
182 CriticalExits.insert(Exit);
188 void SplitAnalysis::getCriticalPreds(const SplitAnalysis::LoopBlocks &Blocks,
189 BlockPtrSet &CriticalPreds) {
190 CriticalPreds.clear();
192 // A critical predecessor block has curli live-out, and has a successor that
193 // has curli live-in and is not in the loop nor a loop exit block. For such a
194 // predecessor block, we must carry the value in both the 'inside' and
195 // 'outside' registers.
196 for (BlockPtrSet::iterator I = Blocks.Preds.begin(), E = Blocks.Preds.end();
198 const MachineBasicBlock *Pred = *I;
199 // Definitely not a critical edge.
200 if (Pred->succ_size() == 1)
202 // This block may not have curli live out at all if there is a PHI.
203 if (!lis_.isLiveOutOfMBB(*curli_, Pred))
205 // Does this block have a successor outside the loop?
206 for (MachineBasicBlock::const_pred_iterator SI = Pred->succ_begin(),
207 SE = Pred->succ_end(); SI != SE; ++SI) {
208 const MachineBasicBlock *Succ = *SI;
209 if (Blocks.Loop.count(Succ) || Blocks.Exits.count(Succ))
211 if (!lis_.isLiveInToMBB(*curli_, Succ))
213 // This is a critical predecessor block.
214 CriticalPreds.insert(Pred);
220 /// canSplitCriticalExits - Return true if it is possible to insert new exit
221 /// blocks before the blocks in CriticalExits.
223 SplitAnalysis::canSplitCriticalExits(const SplitAnalysis::LoopBlocks &Blocks,
224 BlockPtrSet &CriticalExits) {
225 // If we don't allow critical edge splitting, require no critical exits.
227 return CriticalExits.empty();
229 for (BlockPtrSet::iterator I = CriticalExits.begin(), E = CriticalExits.end();
231 const MachineBasicBlock *Succ = *I;
232 // We want to insert a new pre-exit MBB before Succ, and change all the
233 // in-loop blocks to branch to the pre-exit instead of Succ.
234 // Check that all the in-loop predecessors can be changed.
235 for (MachineBasicBlock::const_pred_iterator PI = Succ->pred_begin(),
236 PE = Succ->pred_end(); PI != PE; ++PI) {
237 const MachineBasicBlock *Pred = *PI;
238 // The external predecessors won't be altered.
239 if (!Blocks.Loop.count(Pred) && !Blocks.Preds.count(Pred))
241 if (!canAnalyzeBranch(Pred))
245 // If Succ's layout predecessor falls through, that too must be analyzable.
246 // We need to insert the pre-exit block in the gap.
247 MachineFunction::const_iterator MFI = Succ;
248 if (MFI == mf_.begin())
250 if (!canAnalyzeBranch(--MFI))
253 // No problems found.
257 void SplitAnalysis::analyze(const LiveInterval *li) {
263 void SplitAnalysis::getSplitLoops(LoopPtrSet &Loops) {
264 assert(curli_ && "Call analyze() before getSplitLoops");
265 if (usingLoops_.empty())
269 BlockPtrSet CriticalExits;
271 // We split around loops where curli is used outside the periphery.
272 for (LoopCountMap::const_iterator I = usingLoops_.begin(),
273 E = usingLoops_.end(); I != E; ++I) {
274 const MachineLoop *Loop = I->first;
275 getLoopBlocks(Loop, Blocks);
276 DEBUG({ dbgs() << " "; print(Blocks, dbgs()); });
278 switch(analyzeLoopPeripheralUse(Blocks)) {
281 case MultiPeripheral:
282 // FIXME: We could split a live range with multiple uses in a peripheral
283 // block and still make progress. However, it is possible that splitting
284 // another live range will insert copies into a peripheral block, and
285 // there is a small chance we can enter an infinite loop, inserting copies
287 // For safety, stick to splitting live ranges with uses outside the
289 DEBUG(dbgs() << ": multiple peripheral uses");
291 case ContainedInLoop:
292 DEBUG(dbgs() << ": fully contained\n");
294 case SinglePeripheral:
295 DEBUG(dbgs() << ": single peripheral use\n");
298 // Will it be possible to split around this loop?
299 getCriticalExits(Blocks, CriticalExits);
300 DEBUG(dbgs() << ": " << CriticalExits.size() << " critical exits\n");
301 if (!canSplitCriticalExits(Blocks, CriticalExits))
303 // This is a possible split.
307 DEBUG(dbgs() << " getSplitLoops found " << Loops.size()
308 << " candidate loops.\n");
311 const MachineLoop *SplitAnalysis::getBestSplitLoop() {
313 getSplitLoops(Loops);
317 // Pick the earliest loop.
318 // FIXME: Are there other heuristics to consider?
319 const MachineLoop *Best = 0;
321 for (LoopPtrSet::const_iterator I = Loops.begin(), E = Loops.end(); I != E;
323 SlotIndex Idx = lis_.getMBBStartIdx((*I)->getHeader());
324 if (!Best || Idx < BestIdx)
325 Best = *I, BestIdx = Idx;
327 DEBUG(dbgs() << " getBestSplitLoop found " << *Best);
331 /// isBypassLoop - Return true if curli is live through Loop and has no uses
332 /// inside the loop. Bypass loops are candidates for splitting because it can
333 /// prevent interference inside the loop.
334 bool SplitAnalysis::isBypassLoop(const MachineLoop *Loop) {
335 // If curli is live into the loop header and there are no uses in the loop, it
336 // must be live in the entire loop and live on at least one exiting edge.
337 return !usingLoops_.count(Loop) &&
338 lis_.isLiveInToMBB(*curli_, Loop->getHeader());
341 /// getBypassLoops - Get all the maximal bypass loops. These are the bypass
342 /// loops whose parent is not a bypass loop.
343 void SplitAnalysis::getBypassLoops(LoopPtrSet &BypassLoops) {
344 SmallVector<MachineLoop*, 8> Todo(loops_.begin(), loops_.end());
345 while (!Todo.empty()) {
346 MachineLoop *Loop = Todo.pop_back_val();
347 if (!usingLoops_.count(Loop)) {
348 // This is either a bypass loop or completely irrelevant.
349 if (lis_.isLiveInToMBB(*curli_, Loop->getHeader()))
350 BypassLoops.insert(Loop);
351 // Either way, skip the child loops.
355 // The child loops may be bypass loops.
356 Todo.append(Loop->begin(), Loop->end());
361 //===----------------------------------------------------------------------===//
363 //===----------------------------------------------------------------------===//
365 // Work around the fact that the std::pair constructors are broken for pointer
366 // pairs in some implementations. makeVV(x, 0) works.
367 static inline std::pair<const VNInfo*, VNInfo*>
368 makeVV(const VNInfo *a, VNInfo *b) {
369 return std::make_pair(a, b);
372 void LiveIntervalMap::reset(LiveInterval *li) {
375 liveOutCache_.clear();
378 bool LiveIntervalMap::isComplexMapped(const VNInfo *ParentVNI) const {
379 ValueMap::const_iterator i = valueMap_.find(ParentVNI);
380 return i != valueMap_.end() && i->second == 0;
383 // defValue - Introduce a li_ def for ParentVNI that could be later than
385 VNInfo *LiveIntervalMap::defValue(const VNInfo *ParentVNI, SlotIndex Idx) {
386 assert(li_ && "call reset first");
387 assert(ParentVNI && "Mapping NULL value");
388 assert(Idx.isValid() && "Invalid SlotIndex");
389 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
391 // Create a new value.
392 VNInfo *VNI = li_->getNextValue(Idx, 0, lis_.getVNInfoAllocator());
394 // Preserve the PHIDef bit.
395 if (ParentVNI->isPHIDef() && Idx == ParentVNI->def)
396 VNI->setIsPHIDef(true);
398 // Use insert for lookup, so we can add missing values with a second lookup.
399 std::pair<ValueMap::iterator,bool> InsP =
400 valueMap_.insert(makeVV(ParentVNI, Idx == ParentVNI->def ? VNI : 0));
402 // This is now a complex def. Mark with a NULL in valueMap.
404 InsP.first->second = 0;
410 // mapValue - Find the mapped value for ParentVNI at Idx.
411 // Potentially create phi-def values.
412 VNInfo *LiveIntervalMap::mapValue(const VNInfo *ParentVNI, SlotIndex Idx,
414 assert(li_ && "call reset first");
415 assert(ParentVNI && "Mapping NULL value");
416 assert(Idx.isValid() && "Invalid SlotIndex");
417 assert(parentli_.getVNInfoAt(Idx) == ParentVNI && "Bad ParentVNI");
419 // Use insert for lookup, so we can add missing values with a second lookup.
420 std::pair<ValueMap::iterator,bool> InsP =
421 valueMap_.insert(makeVV(ParentVNI, 0));
423 // This was an unknown value. Create a simple mapping.
425 if (simple) *simple = true;
426 return InsP.first->second = li_->createValueCopy(ParentVNI,
427 lis_.getVNInfoAllocator());
430 // This was a simple mapped value.
431 if (InsP.first->second) {
432 if (simple) *simple = true;
433 return InsP.first->second;
436 // This is a complex mapped value. There may be multiple defs, and we may need
437 // to create phi-defs.
438 if (simple) *simple = false;
439 MachineBasicBlock *IdxMBB = lis_.getMBBFromIndex(Idx);
440 assert(IdxMBB && "No MBB at Idx");
442 // Is there a def in the same MBB we can extend?
443 if (VNInfo *VNI = extendTo(IdxMBB, Idx))
446 // Now for the fun part. We know that ParentVNI potentially has multiple defs,
447 // and we may need to create even more phi-defs to preserve VNInfo SSA form.
448 // Perform a search for all predecessor blocks where we know the dominating
449 // VNInfo. Insert phi-def VNInfos along the path back to IdxMBB.
450 DEBUG(dbgs() << "\n Reaching defs for BB#" << IdxMBB->getNumber()
451 << " at " << Idx << " in " << *li_ << '\n');
453 // Blocks where li_ should be live-in.
454 SmallVector<MachineDomTreeNode*, 16> LiveIn;
455 LiveIn.push_back(mdt_[IdxMBB]);
457 // Using liveOutCache_ as a visited set, perform a BFS for all reaching defs.
458 for (unsigned i = 0; i != LiveIn.size(); ++i) {
459 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
460 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
461 PE = MBB->pred_end(); PI != PE; ++PI) {
462 MachineBasicBlock *Pred = *PI;
463 // Is this a known live-out block?
464 std::pair<LiveOutMap::iterator,bool> LOIP =
465 liveOutCache_.insert(std::make_pair(Pred, LiveOutPair()));
466 // Yes, we have been here before.
468 DEBUG(if (VNInfo *VNI = LOIP.first->second.first)
469 dbgs() << " known valno #" << VNI->id
470 << " at BB#" << Pred->getNumber() << '\n');
474 // Does Pred provide a live-out value?
475 SlotIndex Last = lis_.getMBBEndIdx(Pred).getPrevSlot();
476 if (VNInfo *VNI = extendTo(Pred, Last)) {
477 MachineBasicBlock *DefMBB = lis_.getMBBFromIndex(VNI->def);
478 DEBUG(dbgs() << " found valno #" << VNI->id
479 << " from BB#" << DefMBB->getNumber()
480 << " at BB#" << Pred->getNumber() << '\n');
481 LiveOutPair &LOP = LOIP.first->second;
483 LOP.second = mdt_[DefMBB];
486 // No, we need a live-in value for Pred as well
488 LiveIn.push_back(mdt_[Pred]);
492 // We may need to add phi-def values to preserve the SSA form.
493 // This is essentially the same iterative algorithm that SSAUpdater uses,
494 // except we already have a dominator tree, so we don't have to recompute it.
499 DEBUG(dbgs() << " Iterating over " << LiveIn.size() << " blocks.\n");
500 // Propagate live-out values down the dominator tree, inserting phi-defs when
501 // necessary. Since LiveIn was created by a BFS, going backwards makes it more
502 // likely for us to visit immediate dominators before their children.
503 for (unsigned i = LiveIn.size(); i; --i) {
504 MachineDomTreeNode *Node = LiveIn[i-1];
505 MachineBasicBlock *MBB = Node->getBlock();
506 MachineDomTreeNode *IDom = Node->getIDom();
507 LiveOutPair IDomValue;
508 // We need a live-in value to a block with no immediate dominator?
509 // This is probably an unreachable block that has survived somehow.
510 bool needPHI = !IDom;
512 // Get the IDom live-out value.
514 LiveOutMap::iterator I = liveOutCache_.find(IDom->getBlock());
515 if (I != liveOutCache_.end())
516 IDomValue = I->second;
518 // If IDom is outside our set of live-out blocks, there must be new
519 // defs, and we need a phi-def here.
523 // IDom dominates all of our predecessors, but it may not be the immediate
524 // dominator. Check if any of them have live-out values that are properly
525 // dominated by IDom. If so, we need a phi-def here.
527 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
528 PE = MBB->pred_end(); PI != PE; ++PI) {
529 LiveOutPair Value = liveOutCache_[*PI];
530 if (!Value.first || Value.first == IDomValue.first)
532 // This predecessor is carrying something other than IDomValue.
533 // It could be because IDomValue hasn't propagated yet, or it could be
534 // because MBB is in the dominance frontier of that value.
535 if (mdt_.dominates(IDom, Value.second)) {
542 // Create a phi-def if required.
545 SlotIndex Start = lis_.getMBBStartIdx(MBB);
546 VNInfo *VNI = li_->getNextValue(Start, 0, lis_.getVNInfoAllocator());
547 VNI->setIsPHIDef(true);
548 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
549 << " phi-def #" << VNI->id << " at " << Start << '\n');
550 // We no longer need li_ to be live-in.
551 LiveIn.erase(LiveIn.begin()+(i-1));
552 // Blocks in LiveIn are either IdxMBB, or have a value live-through.
555 // Check if we need to update live-out info.
556 LiveOutMap::iterator I = liveOutCache_.find(MBB);
557 if (I == liveOutCache_.end() || I->second.second == Node) {
558 // We already have a live-out defined in MBB, so this must be IdxMBB.
559 assert(MBB == IdxMBB && "Adding phi-def to known live-out");
560 li_->addRange(LiveRange(Start, Idx.getNextSlot(), VNI));
562 // This phi-def is also live-out, so color the whole block.
563 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
564 I->second = LiveOutPair(VNI, Node);
566 } else if (IDomValue.first) {
567 // No phi-def here. Remember incoming value for IdxMBB.
569 IdxVNI = IDomValue.first;
570 // Propagate IDomValue if needed:
571 // MBB is live-out and doesn't define its own value.
572 LiveOutMap::iterator I = liveOutCache_.find(MBB);
573 if (I != liveOutCache_.end() && I->second.second != Node &&
574 I->second.first != IDomValue.first) {
576 I->second = IDomValue;
577 DEBUG(dbgs() << " - BB#" << MBB->getNumber()
578 << " idom valno #" << IDomValue.first->id
579 << " from BB#" << IDom->getBlock()->getNumber() << '\n');
583 DEBUG(dbgs() << " - made " << Changes << " changes.\n");
586 assert(IdxVNI && "Didn't find value for Idx");
589 // Check the liveOutCache_ invariants.
590 for (LiveOutMap::iterator I = liveOutCache_.begin(), E = liveOutCache_.end();
592 assert(I->first && "Null MBB entry in cache");
593 assert(I->second.first && "Null VNInfo in cache");
594 assert(I->second.second && "Null DomTreeNode in cache");
595 if (I->second.second->getBlock() == I->first)
597 for (MachineBasicBlock::pred_iterator PI = I->first->pred_begin(),
598 PE = I->first->pred_end(); PI != PE; ++PI)
599 assert(liveOutCache_.lookup(*PI) == I->second && "Bad invariant");
603 // Since we went through the trouble of a full BFS visiting all reaching defs,
604 // the values in LiveIn are now accurate. No more phi-defs are needed
605 // for these blocks, so we can color the live ranges.
606 // This makes the next mapValue call much faster.
607 for (unsigned i = 0, e = LiveIn.size(); i != e; ++i) {
608 MachineBasicBlock *MBB = LiveIn[i]->getBlock();
609 SlotIndex Start = lis_.getMBBStartIdx(MBB);
611 li_->addRange(LiveRange(Start, Idx.getNextSlot(), IdxVNI));
614 // Anything in LiveIn other than IdxMBB is live-through.
615 VNInfo *VNI = liveOutCache_.lookup(MBB).first;
616 assert(VNI && "Missing block value");
617 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
623 // extendTo - Find the last li_ value defined in MBB at or before Idx. The
624 // parentli_ is assumed to be live at Idx. Extend the live range to Idx.
625 // Return the found VNInfo, or NULL.
626 VNInfo *LiveIntervalMap::extendTo(const MachineBasicBlock *MBB, SlotIndex Idx) {
627 assert(li_ && "call reset first");
628 LiveInterval::iterator I = std::upper_bound(li_->begin(), li_->end(), Idx);
629 if (I == li_->begin())
632 if (I->end <= lis_.getMBBStartIdx(MBB))
635 I->end = Idx.getNextSlot();
639 // addSimpleRange - Add a simple range from parentli_ to li_.
640 // ParentVNI must be live in the [Start;End) interval.
641 void LiveIntervalMap::addSimpleRange(SlotIndex Start, SlotIndex End,
642 const VNInfo *ParentVNI) {
643 assert(li_ && "call reset first");
645 VNInfo *VNI = mapValue(ParentVNI, Start, &simple);
646 // A simple mapping is easy.
648 li_->addRange(LiveRange(Start, End, VNI));
652 // ParentVNI is a complex value. We must map per MBB.
653 MachineFunction::iterator MBB = lis_.getMBBFromIndex(Start);
654 MachineFunction::iterator MBBE = lis_.getMBBFromIndex(End.getPrevSlot());
657 li_->addRange(LiveRange(Start, End, VNI));
662 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB), VNI));
664 // Run sequence of full blocks.
665 for (++MBB; MBB != MBBE; ++MBB) {
666 Start = lis_.getMBBStartIdx(MBB);
667 li_->addRange(LiveRange(Start, lis_.getMBBEndIdx(MBB),
668 mapValue(ParentVNI, Start)));
672 Start = lis_.getMBBStartIdx(MBB);
674 li_->addRange(LiveRange(Start, End, mapValue(ParentVNI, Start)));
677 /// addRange - Add live ranges to li_ where [Start;End) intersects parentli_.
678 /// All needed values whose def is not inside [Start;End) must be defined
679 /// beforehand so mapValue will work.
680 void LiveIntervalMap::addRange(SlotIndex Start, SlotIndex End) {
681 assert(li_ && "call reset first");
682 LiveInterval::const_iterator B = parentli_.begin(), E = parentli_.end();
683 LiveInterval::const_iterator I = std::lower_bound(B, E, Start);
685 // Check if --I begins before Start and overlaps.
689 addSimpleRange(Start, std::min(End, I->end), I->valno);
693 // The remaining ranges begin after Start.
694 for (;I != E && I->start < End; ++I)
695 addSimpleRange(I->start, std::min(End, I->end), I->valno);
699 //===----------------------------------------------------------------------===//
701 //===----------------------------------------------------------------------===//
703 /// Create a new SplitEditor for editing the LiveInterval analyzed by SA.
704 SplitEditor::SplitEditor(SplitAnalysis &sa,
707 MachineDominatorTree &mdt,
709 : sa_(sa), lis_(lis), vrm_(vrm),
710 mri_(vrm.getMachineFunction().getRegInfo()),
711 tii_(*vrm.getMachineFunction().getTarget().getInstrInfo()),
712 tri_(*vrm.getMachineFunction().getTarget().getRegisterInfo()),
714 dupli_(lis_, mdt, edit.getParent()),
715 openli_(lis_, mdt, edit.getParent())
717 // We don't need an AliasAnalysis since we will only be performing
718 // cheap-as-a-copy remats anyway.
719 edit_.anyRematerializable(lis_, tii_, 0);
722 bool SplitEditor::intervalsLiveAt(SlotIndex Idx) const {
723 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
724 if (*I != dupli_.getLI() && (*I)->liveAt(Idx))
729 VNInfo *SplitEditor::defFromParent(LiveIntervalMap &Reg,
732 MachineBasicBlock &MBB,
733 MachineBasicBlock::iterator I) {
735 MachineInstr *CopyMI = 0;
738 // Attempt cheap-as-a-copy rematerialization.
739 LiveRangeEdit::Remat RM(ParentVNI);
740 if (edit_.canRematerializeAt(RM, UseIdx, true, lis_)) {
741 Def = edit_.rematerializeAt(MBB, I, Reg.getLI()->reg, RM,
744 // Can't remat, just insert a copy from parent.
745 CopyMI = BuildMI(MBB, I, DebugLoc(), tii_.get(TargetOpcode::COPY),
746 Reg.getLI()->reg).addReg(edit_.getReg());
747 Def = lis_.InsertMachineInstrInMaps(CopyMI).getDefIndex();
750 // Define the value in Reg.
751 VNI = Reg.defValue(ParentVNI, Def);
752 VNI->setCopy(CopyMI);
754 // Add minimal liveness for the new value.
757 Reg.getLI()->addRange(LiveRange(Def, UseIdx.getNextSlot(), VNI));
761 /// Create a new virtual register and live interval.
762 void SplitEditor::openIntv() {
763 assert(!openli_.getLI() && "Previous LI not closed before openIntv");
765 dupli_.reset(&edit_.create(mri_, lis_, vrm_));
767 openli_.reset(&edit_.create(mri_, lis_, vrm_));
770 /// enterIntvBefore - Enter openli before the instruction at Idx. If curli is
771 /// not live before Idx, a COPY is not inserted.
772 void SplitEditor::enterIntvBefore(SlotIndex Idx) {
773 assert(openli_.getLI() && "openIntv not called before enterIntvBefore");
774 Idx = Idx.getUseIndex();
775 DEBUG(dbgs() << " enterIntvBefore " << Idx);
776 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
778 DEBUG(dbgs() << ": not live\n");
781 DEBUG(dbgs() << ": valno " << ParentVNI->id);
782 truncatedValues.insert(ParentVNI);
783 MachineInstr *MI = lis_.getInstructionFromIndex(Idx);
784 assert(MI && "enterIntvBefore called with invalid index");
786 defFromParent(openli_, ParentVNI, Idx, *MI->getParent(), MI);
788 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
791 /// enterIntvAtEnd - Enter openli at the end of MBB.
792 void SplitEditor::enterIntvAtEnd(MachineBasicBlock &MBB) {
793 assert(openli_.getLI() && "openIntv not called before enterIntvAtEnd");
794 SlotIndex End = lis_.getMBBEndIdx(&MBB).getPrevSlot();
795 DEBUG(dbgs() << " enterIntvAtEnd BB#" << MBB.getNumber() << ", " << End);
796 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(End);
798 DEBUG(dbgs() << ": not live\n");
801 DEBUG(dbgs() << ": valno " << ParentVNI->id);
802 truncatedValues.insert(ParentVNI);
803 defFromParent(openli_, ParentVNI, End, MBB, MBB.getFirstTerminator());
804 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
807 /// useIntv - indicate that all instructions in MBB should use openli.
808 void SplitEditor::useIntv(const MachineBasicBlock &MBB) {
809 useIntv(lis_.getMBBStartIdx(&MBB), lis_.getMBBEndIdx(&MBB));
812 void SplitEditor::useIntv(SlotIndex Start, SlotIndex End) {
813 assert(openli_.getLI() && "openIntv not called before useIntv");
814 openli_.addRange(Start, End);
815 DEBUG(dbgs() << " use [" << Start << ';' << End << "): "
816 << *openli_.getLI() << '\n');
819 /// leaveIntvAfter - Leave openli after the instruction at Idx.
820 void SplitEditor::leaveIntvAfter(SlotIndex Idx) {
821 assert(openli_.getLI() && "openIntv not called before leaveIntvAfter");
822 DEBUG(dbgs() << " leaveIntvAfter " << Idx);
824 // The interval must be live beyond the instruction at Idx.
825 Idx = Idx.getBoundaryIndex();
826 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Idx);
828 DEBUG(dbgs() << ": not live\n");
831 DEBUG(dbgs() << ": valno " << ParentVNI->id);
833 MachineBasicBlock::iterator MII = lis_.getInstructionFromIndex(Idx);
834 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Idx,
835 *MII->getParent(), llvm::next(MII));
837 // Make sure that openli is properly extended from Idx to the new copy.
838 // FIXME: This shouldn't be necessary for remats.
839 openli_.addSimpleRange(Idx, VNI->def, ParentVNI);
841 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
844 /// leaveIntvAtTop - Leave the interval at the top of MBB.
845 /// Currently, only one value can leave the interval.
846 void SplitEditor::leaveIntvAtTop(MachineBasicBlock &MBB) {
847 assert(openli_.getLI() && "openIntv not called before leaveIntvAtTop");
848 SlotIndex Start = lis_.getMBBStartIdx(&MBB);
849 DEBUG(dbgs() << " leaveIntvAtTop BB#" << MBB.getNumber() << ", " << Start);
851 VNInfo *ParentVNI = edit_.getParent().getVNInfoAt(Start);
853 DEBUG(dbgs() << ": not live\n");
857 VNInfo *VNI = defFromParent(dupli_, ParentVNI, Start, MBB,
858 MBB.SkipPHIsAndLabels(MBB.begin()));
860 // Finally we must make sure that openli is properly extended from Start to
862 openli_.addSimpleRange(Start, VNI->def, ParentVNI);
863 DEBUG(dbgs() << ": " << *openli_.getLI() << '\n');
866 /// closeIntv - Indicate that we are done editing the currently open
867 /// LiveInterval, and ranges can be trimmed.
868 void SplitEditor::closeIntv() {
869 assert(openli_.getLI() && "openIntv not called before closeIntv");
871 DEBUG(dbgs() << " closeIntv cleaning up\n");
872 DEBUG(dbgs() << " open " << *openli_.getLI() << '\n');
876 /// rewrite - Rewrite all uses of reg to use the new registers.
877 void SplitEditor::rewrite(unsigned reg) {
878 for (MachineRegisterInfo::reg_iterator RI = mri_.reg_begin(reg),
879 RE = mri_.reg_end(); RI != RE;) {
880 MachineOperand &MO = RI.getOperand();
881 unsigned OpNum = RI.getOperandNo();
882 MachineInstr *MI = MO.getParent();
884 if (MI->isDebugValue()) {
885 DEBUG(dbgs() << "Zapping " << *MI);
886 // FIXME: We can do much better with debug values.
890 SlotIndex Idx = lis_.getInstructionIndex(MI);
891 Idx = MO.isUse() ? Idx.getUseIndex() : Idx.getDefIndex();
892 LiveInterval *LI = 0;
893 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E;
895 LiveInterval *testli = *I;
896 if (testli->liveAt(Idx)) {
901 DEBUG(dbgs() << " rewr BB#" << MI->getParent()->getNumber() << '\t'<< Idx);
902 assert(LI && "No register was live at use");
904 if (MO.isUse() && !MI->isRegTiedToDefOperand(OpNum))
905 MO.setIsKill(LI->killedAt(Idx.getDefIndex()));
906 DEBUG(dbgs() << '\t' << *MI);
911 SplitEditor::addTruncSimpleRange(SlotIndex Start, SlotIndex End, VNInfo *VNI) {
912 // Build vector of iterator pairs from the intervals.
913 typedef std::pair<LiveInterval::const_iterator,
914 LiveInterval::const_iterator> IIPair;
915 SmallVector<IIPair, 8> Iters;
916 for (LiveRangeEdit::iterator LI = edit_.begin(), LE = edit_.end(); LI != LE;
918 if (*LI == dupli_.getLI())
920 LiveInterval::const_iterator I = (*LI)->find(Start);
921 LiveInterval::const_iterator E = (*LI)->end();
923 Iters.push_back(std::make_pair(I, E));
926 SlotIndex sidx = Start;
927 // Break [Start;End) into segments that don't overlap any intervals.
929 SlotIndex next = sidx, eidx = End;
930 // Find overlapping intervals.
931 for (unsigned i = 0; i != Iters.size() && sidx < eidx; ++i) {
932 LiveInterval::const_iterator I = Iters[i].first;
933 // Interval I is overlapping [sidx;eidx). Trim sidx.
934 if (I->start <= sidx) {
936 // Move to the next run, remove iters when all are consumed.
937 I = ++Iters[i].first;
938 if (I == Iters[i].second) {
939 Iters.erase(Iters.begin() + i);
944 // Trim eidx too if needed.
945 if (I->start >= eidx)
950 // Now, [sidx;eidx) doesn't overlap anything in intervals_.
952 dupli_.addSimpleRange(sidx, eidx, VNI);
953 // If the interval end was truncated, we can try again from next.
960 void SplitEditor::computeRemainder() {
961 // First we need to fill in the live ranges in dupli.
962 // If values were redefined, we need a full recoloring with SSA update.
963 // If values were truncated, we only need to truncate the ranges.
964 // If values were partially rematted, we should shrink to uses.
965 // If values were fully rematted, they should be omitted.
966 // FIXME: If a single value is redefined, just move the def and truncate.
967 LiveInterval &parent = edit_.getParent();
969 // Values that are fully contained in the split intervals.
970 SmallPtrSet<const VNInfo*, 8> deadValues;
971 // Map all curli values that should have live defs in dupli.
972 for (LiveInterval::const_vni_iterator I = parent.vni_begin(),
973 E = parent.vni_end(); I != E; ++I) {
974 const VNInfo *VNI = *I;
975 // Don't transfer unused values to the new intervals.
978 // Original def is contained in the split intervals.
979 if (intervalsLiveAt(VNI->def)) {
980 // Did this value escape?
981 if (dupli_.isMapped(VNI))
982 truncatedValues.insert(VNI);
984 deadValues.insert(VNI);
987 // Add minimal live range at the definition.
988 VNInfo *DVNI = dupli_.defValue(VNI, VNI->def);
989 dupli_.getLI()->addRange(LiveRange(VNI->def, VNI->def.getNextSlot(), DVNI));
992 // Add all ranges to dupli.
993 for (LiveInterval::const_iterator I = parent.begin(), E = parent.end();
995 const LiveRange &LR = *I;
996 if (truncatedValues.count(LR.valno)) {
997 // recolor after removing intervals_.
998 addTruncSimpleRange(LR.start, LR.end, LR.valno);
999 } else if (!deadValues.count(LR.valno)) {
1000 // recolor without truncation.
1001 dupli_.addSimpleRange(LR.start, LR.end, LR.valno);
1005 // Extend dupli_ to be live out of any critical loop predecessors.
1006 // This means we have multiple registers live out of those blocks.
1007 // The alternative would be to split the critical edges.
1008 if (criticalPreds_.empty())
1010 for (SplitAnalysis::BlockPtrSet::iterator I = criticalPreds_.begin(),
1011 E = criticalPreds_.end(); I != E; ++I)
1012 dupli_.extendTo(*I, lis_.getMBBEndIdx(*I).getPrevSlot());
1013 criticalPreds_.clear();
1016 void SplitEditor::finish() {
1017 assert(!openli_.getLI() && "Previous LI not closed before rewrite");
1018 assert(dupli_.getLI() && "No dupli for rewrite. Noop spilt?");
1020 // Complete dupli liveness.
1023 // Get rid of unused values and set phi-kill flags.
1024 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I)
1025 (*I)->RenumberValues(lis_);
1027 // Rewrite instructions.
1028 rewrite(edit_.getReg());
1030 // Now check if any registers were separated into multiple components.
1031 ConnectedVNInfoEqClasses ConEQ(lis_);
1032 for (unsigned i = 0, e = edit_.size(); i != e; ++i) {
1033 // Don't use iterators, they are invalidated by create() below.
1034 LiveInterval *li = edit_.get(i);
1035 unsigned NumComp = ConEQ.Classify(li);
1038 DEBUG(dbgs() << " " << NumComp << " components: " << *li << '\n');
1039 SmallVector<LiveInterval*, 8> dups;
1041 for (unsigned i = 1; i != NumComp; ++i)
1042 dups.push_back(&edit_.create(mri_, lis_, vrm_));
1043 ConEQ.Distribute(&dups[0]);
1044 // Rewrite uses to the new regs.
1048 // Calculate spill weight and allocation hints for new intervals.
1049 VirtRegAuxInfo vrai(vrm_.getMachineFunction(), lis_, sa_.loops_);
1050 for (LiveRangeEdit::iterator I = edit_.begin(), E = edit_.end(); I != E; ++I){
1051 LiveInterval &li = **I;
1052 vrai.CalculateRegClass(li.reg);
1053 vrai.CalculateWeightAndHint(li);
1054 DEBUG(dbgs() << " new interval " << mri_.getRegClass(li.reg)->getName()
1055 << ":" << li << '\n');
1060 //===----------------------------------------------------------------------===//
1062 //===----------------------------------------------------------------------===//
1064 void SplitEditor::splitAroundLoop(const MachineLoop *Loop) {
1065 SplitAnalysis::LoopBlocks Blocks;
1066 sa_.getLoopBlocks(Loop, Blocks);
1069 dbgs() << " splitAround"; sa_.print(Blocks, dbgs()); dbgs() << '\n';
1072 // Break critical edges as needed.
1073 SplitAnalysis::BlockPtrSet CriticalExits;
1074 sa_.getCriticalExits(Blocks, CriticalExits);
1075 assert(CriticalExits.empty() && "Cannot break critical exits yet");
1077 // Get critical predecessors so computeRemainder can deal with them.
1078 sa_.getCriticalPreds(Blocks, criticalPreds_);
1080 // Create new live interval for the loop.
1083 // Insert copies in the predecessors if live-in to the header.
1084 if (lis_.isLiveInToMBB(edit_.getParent(), Loop->getHeader())) {
1085 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Preds.begin(),
1086 E = Blocks.Preds.end(); I != E; ++I) {
1087 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1088 enterIntvAtEnd(MBB);
1092 // Switch all loop blocks.
1093 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Loop.begin(),
1094 E = Blocks.Loop.end(); I != E; ++I)
1097 // Insert back copies in the exit blocks.
1098 for (SplitAnalysis::BlockPtrSet::iterator I = Blocks.Exits.begin(),
1099 E = Blocks.Exits.end(); I != E; ++I) {
1100 MachineBasicBlock &MBB = const_cast<MachineBasicBlock&>(**I);
1101 leaveIntvAtTop(MBB);
1110 //===----------------------------------------------------------------------===//
1111 // Single Block Splitting
1112 //===----------------------------------------------------------------------===//
1114 /// getMultiUseBlocks - if curli has more than one use in a basic block, it
1115 /// may be an advantage to split curli for the duration of the block.
1116 bool SplitAnalysis::getMultiUseBlocks(BlockPtrSet &Blocks) {
1117 // If curli is local to one block, there is no point to splitting it.
1118 if (usingBlocks_.size() <= 1)
1120 // Add blocks with multiple uses.
1121 for (BlockCountMap::iterator I = usingBlocks_.begin(), E = usingBlocks_.end();
1123 switch (I->second) {
1128 // When there are only two uses and curli is both live in and live out,
1129 // we don't really win anything by isolating the block since we would be
1130 // inserting two copies.
1131 // The remaing register would still have two uses in the block. (Unless it
1132 // separates into disconnected components).
1133 if (lis_.isLiveInToMBB(*curli_, I->first) &&
1134 lis_.isLiveOutOfMBB(*curli_, I->first))
1138 Blocks.insert(I->first);
1140 return !Blocks.empty();
1143 /// splitSingleBlocks - Split curli into a separate live interval inside each
1144 /// basic block in Blocks.
1145 void SplitEditor::splitSingleBlocks(const SplitAnalysis::BlockPtrSet &Blocks) {
1146 DEBUG(dbgs() << " splitSingleBlocks for " << Blocks.size() << " blocks.\n");
1147 // Determine the first and last instruction using curli in each block.
1148 typedef std::pair<SlotIndex,SlotIndex> IndexPair;
1149 typedef DenseMap<const MachineBasicBlock*,IndexPair> IndexPairMap;
1150 IndexPairMap MBBRange;
1151 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1152 E = sa_.usingInstrs_.end(); I != E; ++I) {
1153 const MachineBasicBlock *MBB = (*I)->getParent();
1154 if (!Blocks.count(MBB))
1156 SlotIndex Idx = lis_.getInstructionIndex(*I);
1157 DEBUG(dbgs() << " BB#" << MBB->getNumber() << '\t' << Idx << '\t' << **I);
1158 IndexPair &IP = MBBRange[MBB];
1159 if (!IP.first.isValid() || Idx < IP.first)
1161 if (!IP.second.isValid() || Idx > IP.second)
1165 // Create a new interval for each block.
1166 for (SplitAnalysis::BlockPtrSet::const_iterator I = Blocks.begin(),
1167 E = Blocks.end(); I != E; ++I) {
1168 IndexPair &IP = MBBRange[*I];
1169 DEBUG(dbgs() << " splitting for BB#" << (*I)->getNumber() << ": ["
1170 << IP.first << ';' << IP.second << ")\n");
1171 assert(IP.first.isValid() && IP.second.isValid());
1174 enterIntvBefore(IP.first);
1175 useIntv(IP.first.getBaseIndex(), IP.second.getBoundaryIndex());
1176 leaveIntvAfter(IP.second);
1183 //===----------------------------------------------------------------------===//
1184 // Sub Block Splitting
1185 //===----------------------------------------------------------------------===//
1187 /// getBlockForInsideSplit - If curli is contained inside a single basic block,
1188 /// and it wou pay to subdivide the interval inside that block, return it.
1189 /// Otherwise return NULL. The returned block can be passed to
1190 /// SplitEditor::splitInsideBlock.
1191 const MachineBasicBlock *SplitAnalysis::getBlockForInsideSplit() {
1192 // The interval must be exclusive to one block.
1193 if (usingBlocks_.size() != 1)
1195 // Don't to this for less than 4 instructions. We want to be sure that
1196 // splitting actually reduces the instruction count per interval.
1197 if (usingInstrs_.size() < 4)
1199 return usingBlocks_.begin()->first;
1202 /// splitInsideBlock - Split curli into multiple intervals inside MBB.
1203 void SplitEditor::splitInsideBlock(const MachineBasicBlock *MBB) {
1204 SmallVector<SlotIndex, 32> Uses;
1205 Uses.reserve(sa_.usingInstrs_.size());
1206 for (SplitAnalysis::InstrPtrSet::const_iterator I = sa_.usingInstrs_.begin(),
1207 E = sa_.usingInstrs_.end(); I != E; ++I)
1208 if ((*I)->getParent() == MBB)
1209 Uses.push_back(lis_.getInstructionIndex(*I));
1210 DEBUG(dbgs() << " splitInsideBlock BB#" << MBB->getNumber() << " for "
1211 << Uses.size() << " instructions.\n");
1212 assert(Uses.size() >= 3 && "Need at least 3 instructions");
1213 array_pod_sort(Uses.begin(), Uses.end());
1215 // Simple algorithm: Find the largest gap between uses as determined by slot
1216 // indices. Create new intervals for instructions before the gap and after the
1218 unsigned bestPos = 0;
1220 DEBUG(dbgs() << " dist (" << Uses[0]);
1221 for (unsigned i = 1, e = Uses.size(); i != e; ++i) {
1222 int g = Uses[i-1].distance(Uses[i]);
1223 DEBUG(dbgs() << ") -" << g << "- (" << Uses[i]);
1225 bestPos = i, bestGap = g;
1227 DEBUG(dbgs() << "), best: -" << bestGap << "-\n");
1229 // bestPos points to the first use after the best gap.
1230 assert(bestPos > 0 && "Invalid gap");
1232 // FIXME: Don't create intervals for low densities.
1234 // First interval before the gap. Don't create single-instr intervals.
1237 enterIntvBefore(Uses.front());
1238 useIntv(Uses.front().getBaseIndex(), Uses[bestPos-1].getBoundaryIndex());
1239 leaveIntvAfter(Uses[bestPos-1]);
1243 // Second interval after the gap.
1244 if (bestPos < Uses.size()-1) {
1246 enterIntvBefore(Uses[bestPos]);
1247 useIntv(Uses[bestPos].getBaseIndex(), Uses.back().getBoundaryIndex());
1248 leaveIntvAfter(Uses.back());