1 //===-- PreAllocSplitting.cpp - Pre-allocation Interval Spltting Pass. ----===//
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 implements the machine instruction level pre-register allocation
11 // live interval splitting pass. It finds live interval barriers, i.e.
12 // instructions which will kill all physical registers in certain register
13 // classes, and split all live intervals which cross the barrier.
15 //===----------------------------------------------------------------------===//
17 #define DEBUG_TYPE "pre-alloc-split"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineLoopInfo.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/RegisterCoalescer.h"
26 #include "llvm/Target/TargetInstrInfo.h"
27 #include "llvm/Target/TargetMachine.h"
28 #include "llvm/Target/TargetOptions.h"
29 #include "llvm/Target/TargetRegisterInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/ADT/DenseMap.h"
33 #include "llvm/ADT/DepthFirstIterator.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/Statistic.h"
38 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
40 STATISTIC(NumSplits, "Number of intervals split");
43 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
44 MachineFunction *CurrMF;
45 const TargetMachine *TM;
46 const TargetInstrInfo *TII;
47 MachineFrameInfo *MFI;
48 MachineRegisterInfo *MRI;
52 // Barrier - Current barrier being processed.
53 MachineInstr *Barrier;
55 // BarrierMBB - Basic block where the barrier resides in.
56 MachineBasicBlock *BarrierMBB;
58 // Barrier - Current barrier index.
61 // CurrLI - Current live interval being split.
64 // CurrSLI - Current stack slot live interval.
65 LiveInterval *CurrSLI;
67 // CurrSValNo - Current val# for the stack slot live interval.
70 // IntervalSSMap - A map from live interval to spill slots.
71 DenseMap<unsigned, int> IntervalSSMap;
73 // Def2SpillMap - A map from a def instruction index to spill index.
74 DenseMap<unsigned, unsigned> Def2SpillMap;
78 PreAllocSplitting() : MachineFunctionPass(&ID) {}
80 virtual bool runOnMachineFunction(MachineFunction &MF);
82 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
83 AU.addRequired<LiveIntervals>();
84 AU.addPreserved<LiveIntervals>();
85 AU.addRequired<LiveStacks>();
86 AU.addPreserved<LiveStacks>();
87 AU.addPreserved<RegisterCoalescer>();
89 AU.addPreservedID(StrongPHIEliminationID);
91 AU.addPreservedID(PHIEliminationID);
92 MachineFunctionPass::getAnalysisUsage(AU);
95 virtual void releaseMemory() {
96 IntervalSSMap.clear();
100 virtual const char *getPassName() const {
101 return "Pre-Register Allocaton Live Interval Splitting";
104 /// print - Implement the dump method.
105 virtual void print(std::ostream &O, const Module* M = 0) const {
109 void print(std::ostream *O, const Module* M = 0) const {
114 MachineBasicBlock::iterator
115 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
118 MachineBasicBlock::iterator
119 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
120 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
122 MachineBasicBlock::iterator
123 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
124 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
126 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
128 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
129 unsigned&, int&) const;
131 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
133 void UpdateRegisterInterval(VNInfo*, unsigned, unsigned);
135 bool ShrinkWrapToLastUse(MachineBasicBlock*, VNInfo*,
136 SmallVector<MachineOperand*, 4>&,
137 SmallPtrSet<MachineInstr*, 4>&);
139 void ShrinkWrapLiveInterval(VNInfo*, MachineBasicBlock*, MachineBasicBlock*,
140 MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*, 8>&,
141 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >&,
142 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >&,
143 SmallVector<MachineBasicBlock*, 4>&);
145 bool SplitRegLiveInterval(LiveInterval*);
147 bool SplitRegLiveIntervals(const TargetRegisterClass **);
149 } // end anonymous namespace
151 char PreAllocSplitting::ID = 0;
153 static RegisterPass<PreAllocSplitting>
154 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
156 const PassInfo *const llvm::PreAllocSplittingID = &X;
159 /// findNextEmptySlot - Find a gap after the given machine instruction in the
160 /// instruction index map. If there isn't one, return end().
161 MachineBasicBlock::iterator
162 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
163 unsigned &SpotIndex) {
164 MachineBasicBlock::iterator MII = MI;
165 if (++MII != MBB->end()) {
166 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
175 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
176 /// for spilling the current live interval. The index must be before any
177 /// defs and uses of the live interval register in the mbb. Return begin() if
179 MachineBasicBlock::iterator
180 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
182 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
183 unsigned &SpillIndex) {
184 MachineBasicBlock::iterator Pt = MBB->begin();
186 // Go top down if RefsInMBB is empty.
187 if (RefsInMBB.empty() && !DefMI) {
188 MachineBasicBlock::iterator MII = MBB->begin();
189 MachineBasicBlock::iterator EndPt = MI;
192 unsigned Index = LIs->getInstructionIndex(MII);
193 unsigned Gap = LIs->findGapBeforeInstr(Index);
199 } while (MII != EndPt);
201 MachineBasicBlock::iterator MII = MI;
202 MachineBasicBlock::iterator EndPt = DefMI
203 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
204 while (MII != EndPt && !RefsInMBB.count(MII)) {
205 unsigned Index = LIs->getInstructionIndex(MII);
206 if (LIs->hasGapBeforeInstr(Index)) {
208 SpillIndex = LIs->findGapBeforeInstr(Index, true);
217 /// findRestorePoint - Find a gap in the instruction index map that's suitable
218 /// for restoring the current live interval value. The index must be before any
219 /// uses of the live interval register in the mbb. Return end() if none is
221 MachineBasicBlock::iterator
222 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
224 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
225 unsigned &RestoreIndex) {
226 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
227 // begin index accordingly.
228 MachineBasicBlock::iterator Pt = MBB->end();
229 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
231 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
232 // the last index in the live range.
233 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
234 MachineBasicBlock::iterator MII = MBB->end();
235 MachineBasicBlock::iterator EndPt = MI;
238 unsigned Index = LIs->getInstructionIndex(MII);
239 unsigned Gap = LIs->findGapBeforeInstr(Index);
246 } while (MII != EndPt);
248 MachineBasicBlock::iterator MII = MI;
250 // FIXME: Limit the number of instructions to examine to reduce
252 while (MII != MBB->end()) {
253 unsigned Index = LIs->getInstructionIndex(MII);
256 unsigned Gap = LIs->findGapBeforeInstr(Index);
261 if (RefsInMBB.count(MII))
270 /// CreateSpillStackSlot - Create a stack slot for the live interval being
271 /// split. If the live interval was previously split, just reuse the same
273 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
274 const TargetRegisterClass *RC) {
276 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
277 if (I != IntervalSSMap.end()) {
280 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
281 IntervalSSMap[Reg] = SS;
284 // Create live interval for stack slot.
285 CurrSLI = &LSs->getOrCreateInterval(SS);
286 if (CurrSLI->hasAtLeastOneValue())
287 CurrSValNo = CurrSLI->getValNumInfo(0);
289 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
293 /// IsAvailableInStack - Return true if register is available in a split stack
294 /// slot at the specified index.
296 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
297 unsigned Reg, unsigned DefIndex,
298 unsigned RestoreIndex, unsigned &SpillIndex,
303 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
304 if (I == IntervalSSMap.end())
306 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
307 if (II == Def2SpillMap.end())
310 // If last spill of def is in the same mbb as barrier mbb (where restore will
311 // be), make sure it's not below the intended restore index.
312 // FIXME: Undo the previous spill?
313 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
314 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
318 SpillIndex = II->second;
322 /// UpdateSpillSlotInterval - Given the specified val# of the register live
323 /// interval being split, and the spill and restore indicies, update the live
324 /// interval of the spill stack slot.
326 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
327 unsigned RestoreIndex) {
328 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
329 "Expect restore in the barrier mbb");
331 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
332 if (MBB == BarrierMBB) {
333 // Intra-block spill + restore. We are done.
334 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
335 CurrSLI->addRange(SLR);
339 SmallPtrSet<MachineBasicBlock*, 4> Processed;
340 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
341 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
342 CurrSLI->addRange(SLR);
343 Processed.insert(MBB);
345 // Start from the spill mbb, figure out the extend of the spill slot's
347 SmallVector<MachineBasicBlock*, 4> WorkList;
348 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
349 if (LR->end > EndIdx)
350 // If live range extend beyond end of mbb, add successors to work list.
351 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
352 SE = MBB->succ_end(); SI != SE; ++SI)
353 WorkList.push_back(*SI);
355 while (!WorkList.empty()) {
356 MachineBasicBlock *MBB = WorkList.back();
358 if (Processed.count(MBB))
360 unsigned Idx = LIs->getMBBStartIdx(MBB);
361 LR = CurrLI->getLiveRangeContaining(Idx);
362 if (LR && LR->valno == ValNo) {
363 EndIdx = LIs->getMBBEndIdx(MBB);
364 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
365 // Spill slot live interval stops at the restore.
366 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
367 CurrSLI->addRange(SLR);
368 } else if (LR->end > EndIdx) {
369 // Live range extends beyond end of mbb, process successors.
370 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
371 CurrSLI->addRange(SLR);
372 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
373 SE = MBB->succ_end(); SI != SE; ++SI)
374 WorkList.push_back(*SI);
376 LiveRange SLR(Idx, LR->end, CurrSValNo);
377 CurrSLI->addRange(SLR);
379 Processed.insert(MBB);
384 /// UpdateRegisterInterval - Given the specified val# of the current live
385 /// interval is being split, and the spill and restore indices, update the live
386 /// interval accordingly.
388 PreAllocSplitting::UpdateRegisterInterval(VNInfo *ValNo, unsigned SpillIndex,
389 unsigned RestoreIndex) {
390 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
391 "Expect restore in the barrier mbb");
393 SmallVector<std::pair<unsigned,unsigned>, 4> Before;
394 SmallVector<std::pair<unsigned,unsigned>, 4> After;
395 SmallVector<unsigned, 4> BeforeKills;
396 SmallVector<unsigned, 4> AfterKills;
397 SmallPtrSet<const LiveRange*, 4> Processed;
399 // First, let's figure out which parts of the live interval is now defined
400 // by the restore, which are defined by the original definition.
401 const LiveRange *LR = CurrLI->getLiveRangeContaining(RestoreIndex);
402 After.push_back(std::make_pair(RestoreIndex, LR->end));
403 if (CurrLI->isKill(ValNo, LR->end))
404 AfterKills.push_back(LR->end);
406 assert(LR->contains(SpillIndex));
407 if (SpillIndex > LR->start) {
408 Before.push_back(std::make_pair(LR->start, SpillIndex));
409 BeforeKills.push_back(SpillIndex);
411 Processed.insert(LR);
413 // Start from the restore mbb, figure out what part of the live interval
414 // are defined by the restore.
415 SmallVector<MachineBasicBlock*, 4> WorkList;
416 MachineBasicBlock *MBB = BarrierMBB;
417 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
418 SE = MBB->succ_end(); SI != SE; ++SI)
419 WorkList.push_back(*SI);
421 while (!WorkList.empty()) {
422 MBB = WorkList.back();
424 unsigned Idx = LIs->getMBBStartIdx(MBB);
425 LR = CurrLI->getLiveRangeContaining(Idx);
426 if (LR && LR->valno == ValNo && !Processed.count(LR)) {
427 After.push_back(std::make_pair(LR->start, LR->end));
428 if (CurrLI->isKill(ValNo, LR->end))
429 AfterKills.push_back(LR->end);
430 Idx = LIs->getMBBEndIdx(MBB);
432 // Live range extend beyond at least one mbb. Let's see what other
434 LIs->findReachableMBBs(LR->start, LR->end, WorkList);
436 Processed.insert(LR);
440 for (LiveInterval::iterator I = CurrLI->begin(), E = CurrLI->end();
443 if (LR->valno == ValNo && !Processed.count(LR)) {
444 Before.push_back(std::make_pair(LR->start, LR->end));
445 if (CurrLI->isKill(ValNo, LR->end))
446 BeforeKills.push_back(LR->end);
450 // Now create new val#s to represent the live ranges defined by the old def
451 // those defined by the restore.
452 unsigned AfterDef = ValNo->def;
453 MachineInstr *AfterCopy = ValNo->copy;
454 bool HasPHIKill = ValNo->hasPHIKill;
455 CurrLI->removeValNo(ValNo);
456 VNInfo *BValNo = (Before.empty())
458 : CurrLI->getNextValue(AfterDef, AfterCopy, LIs->getVNInfoAllocator());
460 CurrLI->addKills(BValNo, BeforeKills);
462 VNInfo *AValNo = (After.empty())
464 : CurrLI->getNextValue(RestoreIndex, 0, LIs->getVNInfoAllocator());
466 AValNo->hasPHIKill = HasPHIKill;
467 CurrLI->addKills(AValNo, AfterKills);
470 for (unsigned i = 0, e = Before.size(); i != e; ++i) {
471 unsigned Start = Before[i].first;
472 unsigned End = Before[i].second;
473 CurrLI->addRange(LiveRange(Start, End, BValNo));
475 for (unsigned i = 0, e = After.size(); i != e; ++i) {
476 unsigned Start = After[i].first;
477 unsigned End = After[i].second;
478 CurrLI->addRange(LiveRange(Start, End, AValNo));
482 /// ShrinkWrapToLastUse - There are uses of the current live interval in the
483 /// given block, shrink wrap the live interval to the last use (i.e. remove
484 /// from last use to the end of the mbb). In case mbb is the where the barrier
485 /// is, remove from the last use to the barrier.
487 PreAllocSplitting::ShrinkWrapToLastUse(MachineBasicBlock *MBB, VNInfo *ValNo,
488 SmallVector<MachineOperand*, 4> &Uses,
489 SmallPtrSet<MachineInstr*, 4> &UseMIs) {
490 MachineOperand *LastMO = 0;
491 MachineInstr *LastMI = 0;
492 if (MBB != BarrierMBB && Uses.size() == 1) {
493 // Single use, no need to traverse the block. We can't assume this for the
494 // barrier bb though since the use is probably below the barrier.
496 LastMI = LastMO->getParent();
498 MachineBasicBlock::iterator MEE = MBB->begin();
499 MachineBasicBlock::iterator MII;
500 if (MBB == BarrierMBB)
506 MachineInstr *UseMI = &*MII;
507 if (!UseMIs.count(UseMI))
509 for (unsigned i = 0, e = UseMI->getNumOperands(); i != e; ++i) {
510 MachineOperand &MO = UseMI->getOperand(i);
511 if (MO.isReg() && MO.getReg() == CurrLI->reg) {
521 // Cut off live range from last use (or beginning of the mbb if there
522 // are no uses in it) to the end of the mbb.
523 unsigned RangeStart, RangeEnd = LIs->getMBBEndIdx(MBB)+1;
525 RangeStart = LIs->getUseIndex(LIs->getInstructionIndex(LastMI))+1;
526 assert(!LastMO->isKill() && "Last use already terminates the interval?");
529 assert(MBB == BarrierMBB);
530 RangeStart = LIs->getMBBStartIdx(MBB);
532 if (MBB == BarrierMBB)
533 RangeEnd = LIs->getUseIndex(BarrierIdx)+1;
534 CurrLI->removeRange(RangeStart, RangeEnd);
536 CurrLI->addKill(ValNo, RangeStart);
538 // Return true if the last use becomes a new kill.
542 /// ShrinkWrapLiveInterval - Recursively traverse the predecessor
543 /// chain to find the new 'kills' and shrink wrap the live interval to the
544 /// new kill indices.
546 PreAllocSplitting::ShrinkWrapLiveInterval(VNInfo *ValNo, MachineBasicBlock *MBB,
547 MachineBasicBlock *SuccMBB, MachineBasicBlock *DefMBB,
548 SmallPtrSet<MachineBasicBlock*, 8> &Visited,
549 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > &Uses,
550 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > &UseMIs,
551 SmallVector<MachineBasicBlock*, 4> &UseMBBs) {
552 if (Visited.count(MBB))
555 // If live interval is live in another successor path, then we can't process
556 // this block. But we may able to do so after all the successors have been
558 if (MBB != BarrierMBB) {
559 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
560 SE = MBB->succ_end(); SI != SE; ++SI) {
561 MachineBasicBlock *SMBB = *SI;
564 if (CurrLI->liveAt(LIs->getMBBStartIdx(SMBB)))
571 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
572 UMII = Uses.find(MBB);
573 if (UMII != Uses.end()) {
574 // At least one use in this mbb, lets look for the kill.
575 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
576 UMII2 = UseMIs.find(MBB);
577 if (ShrinkWrapToLastUse(MBB, ValNo, UMII->second, UMII2->second))
578 // Found a kill, shrink wrapping of this path ends here.
580 } else if (MBB == DefMBB) {
581 // There are no uses after the def.
582 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
583 if (UseMBBs.empty()) {
584 // The only use must be below barrier in the barrier block. It's safe to
586 LIs->RemoveMachineInstrFromMaps(DefMI);
587 DefMI->eraseFromParent();
588 CurrLI->removeRange(ValNo->def, LIs->getMBBEndIdx(MBB)+1);
590 } else if (MBB == BarrierMBB) {
591 // Remove entire live range from start of mbb to barrier.
592 CurrLI->removeRange(LIs->getMBBStartIdx(MBB),
593 LIs->getUseIndex(BarrierIdx)+1);
595 // Remove entire live range of the mbb out of the live interval.
596 CurrLI->removeRange(LIs->getMBBStartIdx(MBB), LIs->getMBBEndIdx(MBB)+1);
600 // Reached the def mbb, stop traversing this path further.
603 // Traverse the pathes up the predecessor chains further.
604 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
605 PE = MBB->pred_end(); PI != PE; ++PI) {
606 MachineBasicBlock *Pred = *PI;
609 if (Pred == DefMBB && ValNo->hasPHIKill)
610 // Pred is the def bb and the def reaches other val#s, we must
611 // allow the value to be live out of the bb.
613 ShrinkWrapLiveInterval(ValNo, Pred, MBB, DefMBB, Visited,
614 Uses, UseMIs, UseMBBs);
620 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
621 /// so it would not cross the barrier that's being processed. Shrink wrap
622 /// (minimize) the live interval to the last uses.
623 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
626 // Find live range where current interval cross the barrier.
627 LiveInterval::iterator LR =
628 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
629 VNInfo *ValNo = LR->valno;
631 if (ValNo->def == ~1U) {
632 // Defined by a dead def? How can this be?
633 assert(0 && "Val# is defined by a dead def?");
637 // FIXME: For now, if definition is rematerializable, do not split.
638 MachineInstr *DefMI = (ValNo->def != ~0U)
639 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
640 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
643 // Find all references in the barrier mbb.
644 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
645 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
646 E = MRI->reg_end(); I != E; ++I) {
647 MachineInstr *RefMI = &*I;
648 if (RefMI->getParent() == BarrierMBB)
649 RefsInMBB.insert(RefMI);
652 // Find a point to restore the value after the barrier.
653 unsigned RestoreIndex;
654 MachineBasicBlock::iterator RestorePt =
655 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
656 if (RestorePt == BarrierMBB->end())
659 // Add a spill either before the barrier or after the definition.
660 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
661 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
662 unsigned SpillIndex = 0;
663 MachineInstr *SpillMI = NULL;
665 if (ValNo->def == ~0U) {
666 // If it's defined by a phi, we must split just before the barrier.
667 MachineBasicBlock::iterator SpillPt =
668 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
669 if (SpillPt == BarrierMBB->begin())
670 return false; // No gap to insert spill.
672 SS = CreateSpillStackSlot(CurrLI->reg, RC);
673 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
674 SpillMI = prior(SpillPt);
675 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
676 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
677 RestoreIndex, SpillIndex, SS)) {
678 // If it's already split, just restore the value. There is no need to spill
681 return false; // Def is dead. Do nothing.
682 // Check if it's possible to insert a spill after the def MI.
683 MachineBasicBlock::iterator SpillPt;
684 if (DefMBB == BarrierMBB) {
685 // Add spill after the def and the last use before the barrier.
686 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI, RefsInMBB, SpillIndex);
687 if (SpillPt == DefMBB->begin())
688 return false; // No gap to insert spill.
690 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
691 if (SpillPt == DefMBB->end())
692 return false; // No gap to insert spill.
694 // Add spill. The store instruction kills the register if def is before
695 // the barrier in the barrier block.
696 SS = CreateSpillStackSlot(CurrLI->reg, RC);
697 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
698 DefMBB == BarrierMBB, SS, RC);
699 SpillMI = prior(SpillPt);
700 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
703 // Remember def instruction index to spill index mapping.
704 if (DefMI && SpillMI)
705 Def2SpillMap[ValNo->def] = SpillIndex;
708 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
709 MachineInstr *LoadMI = prior(RestorePt);
710 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
712 // If live interval is spilled in the same block as the barrier, just
713 // create a hole in the interval.
715 (SpillMI && SpillMI->getParent() == BarrierMBB)) {
716 // Update spill stack slot live interval.
717 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
718 LIs->getDefIndex(RestoreIndex));
720 UpdateRegisterInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
721 LIs->getDefIndex(RestoreIndex));
727 // Update spill stack slot live interval.
728 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
729 LIs->getDefIndex(RestoreIndex));
731 // Shrink wrap the live interval by walking up the CFG and find the
733 // Now let's find all the uses of the val#.
734 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> > Uses;
735 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> > UseMIs;
736 SmallPtrSet<MachineBasicBlock*, 4> Seen;
737 SmallVector<MachineBasicBlock*, 4> UseMBBs;
738 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(CurrLI->reg),
739 UE = MRI->use_end(); UI != UE; ++UI) {
740 MachineOperand &UseMO = UI.getOperand();
741 MachineInstr *UseMI = UseMO.getParent();
742 unsigned UseIdx = LIs->getInstructionIndex(UseMI);
743 LiveInterval::iterator ULR = CurrLI->FindLiveRangeContaining(UseIdx);
744 if (ULR->valno != ValNo)
746 MachineBasicBlock *UseMBB = UseMI->getParent();
747 // Remember which other mbb's use this val#.
748 if (Seen.insert(UseMBB) && UseMBB != BarrierMBB)
749 UseMBBs.push_back(UseMBB);
750 DenseMap<MachineBasicBlock*, SmallVector<MachineOperand*, 4> >::iterator
751 UMII = Uses.find(UseMBB);
752 if (UMII != Uses.end()) {
753 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 4> >::iterator
754 UMII2 = UseMIs.find(UseMBB);
755 UMII->second.push_back(&UseMO);
756 UMII2->second.insert(UseMI);
758 SmallVector<MachineOperand*, 4> Ops;
759 Ops.push_back(&UseMO);
760 Uses.insert(std::make_pair(UseMBB, Ops));
761 SmallPtrSet<MachineInstr*, 4> MIs;
763 UseMIs.insert(std::make_pair(UseMBB, MIs));
767 // Walk up the predecessor chains.
768 SmallPtrSet<MachineBasicBlock*, 8> Visited;
769 ShrinkWrapLiveInterval(ValNo, BarrierMBB, NULL, DefMBB, Visited,
770 Uses, UseMIs, UseMBBs);
772 // FIXME: If ValNo->hasPHIKill is false, then renumber the val# by
775 // Remove live range from barrier to the restore. FIXME: Find a better
776 // point to re-start the live interval.
777 UpdateRegisterInterval(ValNo, LIs->getUseIndex(BarrierIdx)+1,
778 LIs->getDefIndex(RestoreIndex));
784 /// SplitRegLiveIntervals - Split all register live intervals that cross the
785 /// barrier that's being processed.
787 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs) {
788 // First find all the virtual registers whose live intervals are intercepted
789 // by the current barrier.
790 SmallVector<LiveInterval*, 8> Intervals;
791 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
792 if (TII->IgnoreRegisterClassBarriers(*RC))
794 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
795 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
796 unsigned Reg = VRs[i];
797 if (!LIs->hasInterval(Reg))
799 LiveInterval *LI = &LIs->getInterval(Reg);
800 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
801 // Virtual register live interval is intercepted by the barrier. We
802 // should split and shrink wrap its interval if possible.
803 Intervals.push_back(LI);
807 // Process the affected live intervals.
809 while (!Intervals.empty()) {
810 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
812 LiveInterval *LI = Intervals.back();
813 Intervals.pop_back();
814 Change |= SplitRegLiveInterval(LI);
820 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
822 TM = &MF.getTarget();
823 TII = TM->getInstrInfo();
824 MFI = MF.getFrameInfo();
825 MRI = &MF.getRegInfo();
826 LIs = &getAnalysis<LiveIntervals>();
827 LSs = &getAnalysis<LiveStacks>();
829 bool MadeChange = false;
831 // Make sure blocks are numbered in order.
835 // FIXME: Go top down.
836 MachineBasicBlock *Entry = MF.begin();
837 SmallPtrSet<MachineBasicBlock*,16> Visited;
839 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
840 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
843 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
844 E = BarrierMBB->end(); I != E; ++I) {
846 const TargetRegisterClass **BarrierRCs =
847 Barrier->getDesc().getRegClassBarriers();
850 BarrierIdx = LIs->getInstructionIndex(Barrier);
851 MadeChange |= SplitRegLiveIntervals(BarrierRCs);
855 for (MachineFunction::reverse_iterator I = MF.rbegin(), E = MF.rend();
858 for (MachineBasicBlock::reverse_iterator II = BarrierMBB->rbegin(),
859 EE = BarrierMBB->rend(); II != EE; ++II) {
861 const TargetRegisterClass **BarrierRCs =
862 Barrier->getDesc().getRegClassBarriers();
865 BarrierIdx = LIs->getInstructionIndex(Barrier);
866 MadeChange |= SplitRegLiveIntervals(BarrierRCs);