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/MachineDominators.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunctionPass.h"
23 #include "llvm/CodeGen/MachineLoopInfo.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/Passes.h"
26 #include "llvm/CodeGen/RegisterCoalescer.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 #include "llvm/Target/TargetMachine.h"
29 #include "llvm/Target/TargetOptions.h"
30 #include "llvm/Target/TargetRegisterInfo.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/ADT/DenseMap.h"
34 #include "llvm/ADT/DepthFirstIterator.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/Statistic.h"
39 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
40 static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1), cl::Hidden);
42 STATISTIC(NumSplits, "Number of intervals split");
43 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
44 STATISTIC(NumFolds, "Number of intervals split with spill folding");
45 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
46 STATISTIC(NumDeadSpills, "Number of dead spills removed");
49 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
50 MachineFunction *CurrMF;
51 const TargetMachine *TM;
52 const TargetInstrInfo *TII;
53 const TargetRegisterInfo* TRI;
54 MachineFrameInfo *MFI;
55 MachineRegisterInfo *MRI;
59 // Barrier - Current barrier being processed.
60 MachineInstr *Barrier;
62 // BarrierMBB - Basic block where the barrier resides in.
63 MachineBasicBlock *BarrierMBB;
65 // Barrier - Current barrier index.
68 // CurrLI - Current live interval being split.
71 // CurrSLI - Current stack slot live interval.
72 LiveInterval *CurrSLI;
74 // CurrSValNo - Current val# for the stack slot live interval.
77 // IntervalSSMap - A map from live interval to spill slots.
78 DenseMap<unsigned, int> IntervalSSMap;
80 // Def2SpillMap - A map from a def instruction index to spill index.
81 DenseMap<unsigned, unsigned> Def2SpillMap;
85 PreAllocSplitting() : MachineFunctionPass(&ID) {}
87 virtual bool runOnMachineFunction(MachineFunction &MF);
89 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
90 AU.addRequired<LiveIntervals>();
91 AU.addPreserved<LiveIntervals>();
92 AU.addRequired<LiveStacks>();
93 AU.addPreserved<LiveStacks>();
94 AU.addPreserved<RegisterCoalescer>();
96 AU.addPreservedID(StrongPHIEliminationID);
98 AU.addPreservedID(PHIEliminationID);
99 AU.addRequired<MachineDominatorTree>();
100 AU.addRequired<MachineLoopInfo>();
101 AU.addPreserved<MachineDominatorTree>();
102 AU.addPreserved<MachineLoopInfo>();
103 MachineFunctionPass::getAnalysisUsage(AU);
106 virtual void releaseMemory() {
107 IntervalSSMap.clear();
108 Def2SpillMap.clear();
111 virtual const char *getPassName() const {
112 return "Pre-Register Allocaton Live Interval Splitting";
115 /// print - Implement the dump method.
116 virtual void print(std::ostream &O, const Module* M = 0) const {
120 void print(std::ostream *O, const Module* M = 0) const {
125 MachineBasicBlock::iterator
126 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
129 MachineBasicBlock::iterator
130 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
131 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
133 MachineBasicBlock::iterator
134 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
135 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
137 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
139 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
140 unsigned&, int&) const;
142 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
144 bool SplitRegLiveInterval(LiveInterval*);
146 bool SplitRegLiveIntervals(const TargetRegisterClass **,
147 SmallPtrSet<LiveInterval*, 8>&);
149 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
150 MachineBasicBlock* BarrierMBB);
151 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
153 MachineBasicBlock::iterator RestorePt,
155 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
156 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
158 MachineInstr* Barrier,
159 MachineBasicBlock* MBB,
161 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
162 MachineInstr* FoldRestore(unsigned vreg,
163 const TargetRegisterClass* RC,
164 MachineInstr* Barrier,
165 MachineBasicBlock* MBB,
167 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
168 void RenumberValno(VNInfo* VN);
169 void ReconstructLiveInterval(LiveInterval* LI);
170 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
171 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
172 unsigned Reg, int FrameIndex, bool& TwoAddr);
173 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
174 MachineBasicBlock* MBB, LiveInterval* LI,
175 SmallPtrSet<MachineInstr*, 4>& Visited,
176 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
177 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
178 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
179 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
180 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
181 bool IsTopLevel, bool IsIntraBlock);
182 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
183 MachineBasicBlock* MBB, LiveInterval* LI,
184 SmallPtrSet<MachineInstr*, 4>& Visited,
185 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
186 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
187 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
188 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
189 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
190 bool IsTopLevel, bool IsIntraBlock);
192 } // end anonymous namespace
194 char PreAllocSplitting::ID = 0;
196 static RegisterPass<PreAllocSplitting>
197 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
199 const PassInfo *const llvm::PreAllocSplittingID = &X;
202 /// findNextEmptySlot - Find a gap after the given machine instruction in the
203 /// instruction index map. If there isn't one, return end().
204 MachineBasicBlock::iterator
205 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
206 unsigned &SpotIndex) {
207 MachineBasicBlock::iterator MII = MI;
208 if (++MII != MBB->end()) {
209 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
218 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
219 /// for spilling the current live interval. The index must be before any
220 /// defs and uses of the live interval register in the mbb. Return begin() if
222 MachineBasicBlock::iterator
223 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
225 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
226 unsigned &SpillIndex) {
227 MachineBasicBlock::iterator Pt = MBB->begin();
229 // Go top down if RefsInMBB is empty.
230 if (RefsInMBB.empty() && !DefMI) {
231 MachineBasicBlock::iterator MII = MBB->begin();
232 MachineBasicBlock::iterator EndPt = MI;
234 if (MII == EndPt) return Pt;
238 unsigned Index = LIs->getInstructionIndex(MII);
239 unsigned Gap = LIs->findGapBeforeInstr(Index);
241 // We can't insert the spill between the barrier (a call), and its
242 // corresponding call frame setup/teardown.
243 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
244 bool reachedBarrier = false;
247 reachedBarrier = true;
251 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
253 if (reachedBarrier) break;
259 } while (MII != EndPt);
261 MachineBasicBlock::iterator MII = MI;
262 MachineBasicBlock::iterator EndPt = DefMI
263 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
265 while (MII != EndPt && !RefsInMBB.count(MII)) {
266 unsigned Index = LIs->getInstructionIndex(MII);
268 // We can't insert the spill between the barrier (a call), and its
269 // corresponding call frame setup.
270 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
273 } if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
274 bool reachedBarrier = false;
275 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
278 reachedBarrier = true;
283 if (reachedBarrier) break;
285 } else if (LIs->hasGapBeforeInstr(Index)) {
287 SpillIndex = LIs->findGapBeforeInstr(Index, true);
296 /// findRestorePoint - Find a gap in the instruction index map that's suitable
297 /// for restoring the current live interval value. The index must be before any
298 /// uses of the live interval register in the mbb. Return end() if none is
300 MachineBasicBlock::iterator
301 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
303 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
304 unsigned &RestoreIndex) {
305 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
306 // begin index accordingly.
307 MachineBasicBlock::iterator Pt = MBB->end();
308 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
310 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
311 // the last index in the live range.
312 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
313 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
314 MachineBasicBlock::iterator EndPt = MI;
316 if (MII == EndPt) return Pt;
320 unsigned Index = LIs->getInstructionIndex(MII);
321 unsigned Gap = LIs->findGapBeforeInstr(Index);
323 // We can't insert a restore between the barrier (a call) and its
324 // corresponding call frame teardown.
325 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
326 bool reachedBarrier = false;
327 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
330 reachedBarrier = true;
335 if (reachedBarrier) break;
344 } while (MII != EndPt);
346 MachineBasicBlock::iterator MII = MI;
349 // FIXME: Limit the number of instructions to examine to reduce
351 while (MII != MBB->getFirstTerminator()) {
352 unsigned Index = LIs->getInstructionIndex(MII);
355 unsigned Gap = LIs->findGapBeforeInstr(Index);
357 // We can't insert a restore between the barrier (a call) and its
358 // corresponding call frame teardown.
359 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
362 } else if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
363 bool reachedBarrier = false;
365 if (MII == MBB->getFirstTerminator() || RefsInMBB.count(MII)) {
366 reachedBarrier = true;
371 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
373 if (reachedBarrier) break;
379 if (RefsInMBB.count(MII))
388 /// CreateSpillStackSlot - Create a stack slot for the live interval being
389 /// split. If the live interval was previously split, just reuse the same
391 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
392 const TargetRegisterClass *RC) {
394 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
395 if (I != IntervalSSMap.end()) {
398 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
399 IntervalSSMap[Reg] = SS;
402 // Create live interval for stack slot.
403 CurrSLI = &LSs->getOrCreateInterval(SS);
404 if (CurrSLI->hasAtLeastOneValue())
405 CurrSValNo = CurrSLI->getValNumInfo(0);
407 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
411 /// IsAvailableInStack - Return true if register is available in a split stack
412 /// slot at the specified index.
414 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
415 unsigned Reg, unsigned DefIndex,
416 unsigned RestoreIndex, unsigned &SpillIndex,
421 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
422 if (I == IntervalSSMap.end())
424 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
425 if (II == Def2SpillMap.end())
428 // If last spill of def is in the same mbb as barrier mbb (where restore will
429 // be), make sure it's not below the intended restore index.
430 // FIXME: Undo the previous spill?
431 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
432 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
436 SpillIndex = II->second;
440 /// UpdateSpillSlotInterval - Given the specified val# of the register live
441 /// interval being split, and the spill and restore indicies, update the live
442 /// interval of the spill stack slot.
444 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
445 unsigned RestoreIndex) {
446 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
447 "Expect restore in the barrier mbb");
449 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
450 if (MBB == BarrierMBB) {
451 // Intra-block spill + restore. We are done.
452 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
453 CurrSLI->addRange(SLR);
457 SmallPtrSet<MachineBasicBlock*, 4> Processed;
458 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
459 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
460 CurrSLI->addRange(SLR);
461 Processed.insert(MBB);
463 // Start from the spill mbb, figure out the extend of the spill slot's
465 SmallVector<MachineBasicBlock*, 4> WorkList;
466 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
467 if (LR->end > EndIdx)
468 // If live range extend beyond end of mbb, add successors to work list.
469 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
470 SE = MBB->succ_end(); SI != SE; ++SI)
471 WorkList.push_back(*SI);
473 while (!WorkList.empty()) {
474 MachineBasicBlock *MBB = WorkList.back();
476 if (Processed.count(MBB))
478 unsigned Idx = LIs->getMBBStartIdx(MBB);
479 LR = CurrLI->getLiveRangeContaining(Idx);
480 if (LR && LR->valno == ValNo) {
481 EndIdx = LIs->getMBBEndIdx(MBB);
482 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
483 // Spill slot live interval stops at the restore.
484 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
485 CurrSLI->addRange(SLR);
486 } else if (LR->end > EndIdx) {
487 // Live range extends beyond end of mbb, process successors.
488 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
489 CurrSLI->addRange(SLR);
490 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
491 SE = MBB->succ_end(); SI != SE; ++SI)
492 WorkList.push_back(*SI);
494 LiveRange SLR(Idx, LR->end, CurrSValNo);
495 CurrSLI->addRange(SLR);
497 Processed.insert(MBB);
502 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
503 /// construction algorithm to compute the ranges and valnos for an interval.
505 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
506 MachineBasicBlock* MBB, LiveInterval* LI,
507 SmallPtrSet<MachineInstr*, 4>& Visited,
508 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
509 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
510 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
511 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
512 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
513 bool IsTopLevel, bool IsIntraBlock) {
514 // Return memoized result if it's available.
515 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
517 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
519 else if (!IsIntraBlock && LiveOut.count(MBB))
522 // Check if our block contains any uses or defs.
523 bool ContainsDefs = Defs.count(MBB);
524 bool ContainsUses = Uses.count(MBB);
528 // Enumerate the cases of use/def contaning blocks.
529 if (!ContainsDefs && !ContainsUses) {
530 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
531 NewVNs, LiveOut, Phis,
532 IsTopLevel, IsIntraBlock);
533 } else if (ContainsDefs && !ContainsUses) {
534 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
536 // Search for the def in this block. If we don't find it before the
537 // instruction we care about, go to the fallback case. Note that that
538 // should never happen: this cannot be intrablock, so use should
539 // always be an end() iterator.
540 assert(UseI == MBB->end() && "No use marked in intrablock");
542 MachineBasicBlock::iterator Walker = UseI;
544 while (Walker != MBB->begin()) {
545 if (BlockDefs.count(Walker))
550 // Once we've found it, extend its VNInfo to our instruction.
551 unsigned DefIndex = LIs->getInstructionIndex(Walker);
552 DefIndex = LiveIntervals::getDefIndex(DefIndex);
553 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
555 RetVNI = NewVNs[Walker];
556 LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
557 } else if (!ContainsDefs && ContainsUses) {
558 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
560 // Search for the use in this block that precedes the instruction we care
561 // about, going to the fallback case if we don't find it.
562 if (UseI == MBB->begin())
563 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
564 Uses, NewVNs, LiveOut, Phis,
565 IsTopLevel, IsIntraBlock);
567 MachineBasicBlock::iterator Walker = UseI;
570 while (Walker != MBB->begin()) {
571 if (BlockUses.count(Walker)) {
578 // Must check begin() too.
580 if (BlockUses.count(Walker))
583 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
584 Uses, NewVNs, LiveOut, Phis,
585 IsTopLevel, IsIntraBlock);
588 unsigned UseIndex = LIs->getInstructionIndex(Walker);
589 UseIndex = LiveIntervals::getUseIndex(UseIndex);
590 unsigned EndIndex = 0;
592 EndIndex = LIs->getInstructionIndex(UseI);
593 EndIndex = LiveIntervals::getUseIndex(EndIndex);
595 EndIndex = LIs->getMBBEndIdx(MBB);
597 // Now, recursively phi construct the VNInfo for the use we found,
598 // and then extend it to include the instruction we care about
599 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
600 NewVNs, LiveOut, Phis, false, true);
602 LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
604 // FIXME: Need to set kills properly for inter-block stuff.
605 if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
607 LI->addKill(RetVNI, EndIndex);
608 } else if (ContainsDefs && ContainsUses) {
609 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
610 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
612 // This case is basically a merging of the two preceding case, with the
613 // special note that checking for defs must take precedence over checking
614 // for uses, because of two-address instructions.
616 if (UseI == MBB->begin())
617 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
618 NewVNs, LiveOut, Phis,
619 IsTopLevel, IsIntraBlock);
621 MachineBasicBlock::iterator Walker = UseI;
623 bool foundDef = false;
624 bool foundUse = false;
625 while (Walker != MBB->begin()) {
626 if (BlockDefs.count(Walker)) {
629 } else if (BlockUses.count(Walker)) {
636 // Must check begin() too.
637 if (!foundDef && !foundUse) {
638 if (BlockDefs.count(Walker))
640 else if (BlockUses.count(Walker))
643 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
644 Uses, NewVNs, LiveOut, Phis,
645 IsTopLevel, IsIntraBlock);
648 unsigned StartIndex = LIs->getInstructionIndex(Walker);
649 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
650 LiveIntervals::getUseIndex(StartIndex);
651 unsigned EndIndex = 0;
653 EndIndex = LIs->getInstructionIndex(UseI);
654 EndIndex = LiveIntervals::getUseIndex(EndIndex);
656 EndIndex = LIs->getMBBEndIdx(MBB);
659 RetVNI = NewVNs[Walker];
661 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
662 NewVNs, LiveOut, Phis, false, true);
664 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
666 if (foundUse && LI->isKill(RetVNI, StartIndex))
667 LI->removeKill(RetVNI, StartIndex);
669 LI->addKill(RetVNI, EndIndex);
673 // Memoize results so we don't have to recompute them.
674 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
676 if (!NewVNs.count(UseI))
677 NewVNs[UseI] = RetVNI;
678 Visited.insert(UseI);
684 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
687 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
688 MachineBasicBlock* MBB, LiveInterval* LI,
689 SmallPtrSet<MachineInstr*, 4>& Visited,
690 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
691 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
692 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
693 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
694 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
695 bool IsTopLevel, bool IsIntraBlock) {
696 // NOTE: Because this is the fallback case from other cases, we do NOT
697 // assume that we are not intrablock here.
698 if (Phis.count(MBB)) return Phis[MBB];
700 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
701 VNInfo *RetVNI = Phis[MBB] = LI->getNextValue(~0U, /*FIXME*/ 0,
702 LIs->getVNInfoAllocator());
703 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
705 // If there are no uses or defs between our starting point and the
706 // beginning of the block, then recursive perform phi construction
707 // on our predecessors.
708 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
709 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
710 PE = MBB->pred_end(); PI != PE; ++PI) {
711 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
712 Visited, Defs, Uses, NewVNs,
713 LiveOut, Phis, false, false);
715 IncomingVNs[*PI] = Incoming;
718 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill) {
719 VNInfo* OldVN = RetVNI;
720 VNInfo* NewVN = IncomingVNs.begin()->second;
721 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
722 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
724 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
725 LOE = LiveOut.end(); LOI != LOE; ++LOI)
726 if (LOI->second == OldVN)
727 LOI->second = MergedVN;
728 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
729 NVE = NewVNs.end(); NVI != NVE; ++NVI)
730 if (NVI->second == OldVN)
731 NVI->second = MergedVN;
732 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
733 PE = Phis.end(); PI != PE; ++PI)
734 if (PI->second == OldVN)
735 PI->second = MergedVN;
738 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
739 // VNInfo to represent the joined value.
740 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
741 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
742 I->second->hasPHIKill = true;
743 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
744 if (!LiveInterval::isKill(I->second, KillIndex))
745 LI->addKill(I->second, KillIndex);
749 unsigned EndIndex = 0;
751 EndIndex = LIs->getInstructionIndex(UseI);
752 EndIndex = LiveIntervals::getUseIndex(EndIndex);
754 EndIndex = LIs->getMBBEndIdx(MBB);
755 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
757 LI->addKill(RetVNI, EndIndex);
759 // Memoize results so we don't have to recompute them.
761 LiveOut[MBB] = RetVNI;
763 if (!NewVNs.count(UseI))
764 NewVNs[UseI] = RetVNI;
765 Visited.insert(UseI);
771 /// ReconstructLiveInterval - Recompute a live interval from scratch.
772 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
773 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
775 // Clear the old ranges and valnos;
778 // Cache the uses and defs of the register
779 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
782 // Keep track of the new VNs we're creating.
783 DenseMap<MachineInstr*, VNInfo*> NewVNs;
784 SmallPtrSet<VNInfo*, 2> PhiVNs;
786 // Cache defs, and create a new VNInfo for each def.
787 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
788 DE = MRI->def_end(); DI != DE; ++DI) {
789 Defs[(*DI).getParent()].insert(&*DI);
791 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
792 DefIdx = LiveIntervals::getDefIndex(DefIdx);
794 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
796 // If the def is a move, set the copy field.
797 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
798 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
799 if (DstReg == LI->reg)
802 NewVNs[&*DI] = NewVN;
805 // Cache uses as a separate pass from actually processing them.
806 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
807 UE = MRI->use_end(); UI != UE; ++UI)
808 Uses[(*UI).getParent()].insert(&*UI);
810 // Now, actually process every use and use a phi construction algorithm
811 // to walk from it to its reaching definitions, building VNInfos along
813 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
814 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
815 SmallPtrSet<MachineInstr*, 4> Visited;
816 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
817 UE = MRI->use_end(); UI != UE; ++UI) {
818 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
819 Uses, NewVNs, LiveOut, Phis, true, true);
822 // Add ranges for dead defs
823 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
824 DE = MRI->def_end(); DI != DE; ++DI) {
825 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
826 DefIdx = LiveIntervals::getDefIndex(DefIdx);
828 if (LI->liveAt(DefIdx)) continue;
830 VNInfo* DeadVN = NewVNs[&*DI];
831 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
832 LI->addKill(DeadVN, DefIdx);
836 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
837 /// be allocated to a different register. This function creates a new vreg,
838 /// copies the valno and its live ranges over to the new vreg's interval,
839 /// removes them from the old interval, and rewrites all uses and defs of
840 /// the original reg to the new vreg within those ranges.
841 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
842 SmallVector<VNInfo*, 4> Stack;
843 SmallVector<VNInfo*, 4> VNsToCopy;
846 // Walk through and copy the valno we care about, and any other valnos
847 // that are two-address redefinitions of the one we care about. These
848 // will need to be rewritten as well. We also check for safety of the
849 // renumbering here, by making sure that none of the valno involved has
851 while (!Stack.empty()) {
852 VNInfo* OldVN = Stack.back();
855 // Bail out if we ever encounter a valno that has a PHI kill. We can't
857 if (OldVN->hasPHIKill) return;
859 VNsToCopy.push_back(OldVN);
861 // Locate two-address redefinitions
862 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
863 KE = OldVN->kills.end(); KI != KE; ++KI) {
864 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
865 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
866 if (DefIdx == ~0U) continue;
867 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
869 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
870 if (NextVN == OldVN) continue;
871 Stack.push_back(NextVN);
876 // Create the new vreg
877 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
879 // Create the new live interval
880 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
882 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
883 VNsToCopy.end(); OI != OE; ++OI) {
886 // Copy the valno over
887 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
888 LIs->getVNInfoAllocator());
889 NewLI.copyValNumInfo(NewVN, OldVN);
890 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
892 // Remove the valno from the old interval
893 CurrLI->removeValNo(OldVN);
896 // Rewrite defs and uses. This is done in two stages to avoid invalidating
898 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
900 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
901 E = MRI->reg_end(); I != E; ++I) {
902 MachineOperand& MO = I.getOperand();
903 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
905 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
906 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
907 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
910 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
911 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
912 MachineInstr* Inst = I->first;
913 unsigned OpIdx = I->second;
914 MachineOperand& MO = Inst->getOperand(OpIdx);
918 // The renumbered vreg shares a stack slot with the old register.
919 if (IntervalSSMap.count(CurrLI->reg))
920 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
925 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
927 MachineBasicBlock::iterator RestorePt,
929 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
930 MachineBasicBlock& MBB = *RestorePt->getParent();
932 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
933 unsigned KillIdx = 0;
934 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
935 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
937 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
939 if (KillPt == DefMI->getParent()->end())
942 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
943 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
945 ReconstructLiveInterval(CurrLI);
946 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
947 RematIdx = LiveIntervals::getDefIndex(RematIdx);
948 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
955 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
956 const TargetRegisterClass* RC,
958 MachineInstr* Barrier,
959 MachineBasicBlock* MBB,
961 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
962 MachineBasicBlock::iterator Pt = MBB->begin();
964 // Go top down if RefsInMBB is empty.
965 if (RefsInMBB.empty())
968 MachineBasicBlock::iterator FoldPt = Barrier;
969 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
970 !RefsInMBB.count(FoldPt))
973 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
977 SmallVector<unsigned, 1> Ops;
978 Ops.push_back(OpIdx);
980 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
983 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
984 if (I != IntervalSSMap.end()) {
987 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
991 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
995 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
996 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
999 IntervalSSMap[vreg] = SS;
1000 CurrSLI = &LSs->getOrCreateInterval(SS);
1001 if (CurrSLI->hasAtLeastOneValue())
1002 CurrSValNo = CurrSLI->getValNumInfo(0);
1004 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1010 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
1011 const TargetRegisterClass* RC,
1012 MachineInstr* Barrier,
1013 MachineBasicBlock* MBB,
1015 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1016 // Go top down if RefsInMBB is empty.
1017 if (RefsInMBB.empty())
1020 // Can't fold a restore between a call stack setup and teardown.
1021 MachineBasicBlock::iterator FoldPt = Barrier;
1022 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
1025 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
1026 while (FoldPt != MBB->getFirstTerminator() &&
1027 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1028 if (RefsInMBB.count(FoldPt))
1038 if (FoldPt == MBB->getFirstTerminator())
1041 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1045 SmallVector<unsigned, 1> Ops;
1046 Ops.push_back(OpIdx);
1048 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1051 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1055 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1056 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1063 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1064 /// so it would not cross the barrier that's being processed. Shrink wrap
1065 /// (minimize) the live interval to the last uses.
1066 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1069 // Find live range where current interval cross the barrier.
1070 LiveInterval::iterator LR =
1071 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1072 VNInfo *ValNo = LR->valno;
1074 if (ValNo->def == ~1U) {
1075 // Defined by a dead def? How can this be?
1076 assert(0 && "Val# is defined by a dead def?");
1080 MachineInstr *DefMI = (ValNo->def != ~0U)
1081 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1083 // If this would create a new join point, do not split.
1084 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1087 // Find all references in the barrier mbb.
1088 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1089 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1090 E = MRI->reg_end(); I != E; ++I) {
1091 MachineInstr *RefMI = &*I;
1092 if (RefMI->getParent() == BarrierMBB)
1093 RefsInMBB.insert(RefMI);
1096 // Find a point to restore the value after the barrier.
1097 unsigned RestoreIndex = 0;
1098 MachineBasicBlock::iterator RestorePt =
1099 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1100 if (RestorePt == BarrierMBB->end())
1103 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1104 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1105 RestoreIndex, RefsInMBB))
1108 // Add a spill either before the barrier or after the definition.
1109 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1110 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1111 unsigned SpillIndex = 0;
1112 MachineInstr *SpillMI = NULL;
1114 if (ValNo->def == ~0U) {
1115 // If it's defined by a phi, we must split just before the barrier.
1116 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1117 BarrierMBB, SS, RefsInMBB))) {
1118 SpillIndex = LIs->getInstructionIndex(SpillMI);
1120 MachineBasicBlock::iterator SpillPt =
1121 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1122 if (SpillPt == BarrierMBB->begin())
1123 return false; // No gap to insert spill.
1126 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1127 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1128 SpillMI = prior(SpillPt);
1129 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1131 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1132 RestoreIndex, SpillIndex, SS)) {
1133 // If it's already split, just restore the value. There is no need to spill
1136 return false; // Def is dead. Do nothing.
1138 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1139 BarrierMBB, SS, RefsInMBB))) {
1140 SpillIndex = LIs->getInstructionIndex(SpillMI);
1142 // Check if it's possible to insert a spill after the def MI.
1143 MachineBasicBlock::iterator SpillPt;
1144 if (DefMBB == BarrierMBB) {
1145 // Add spill after the def and the last use before the barrier.
1146 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1147 RefsInMBB, SpillIndex);
1148 if (SpillPt == DefMBB->begin())
1149 return false; // No gap to insert spill.
1151 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1152 if (SpillPt == DefMBB->end())
1153 return false; // No gap to insert spill.
1155 // Add spill. The store instruction kills the register if def is before
1156 // the barrier in the barrier block.
1157 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1158 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1159 DefMBB == BarrierMBB, SS, RC);
1160 SpillMI = prior(SpillPt);
1161 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1165 // Remember def instruction index to spill index mapping.
1166 if (DefMI && SpillMI)
1167 Def2SpillMap[ValNo->def] = SpillIndex;
1170 bool FoldedRestore = false;
1171 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1172 BarrierMBB, SS, RefsInMBB)) {
1174 FoldedRestore = true;
1176 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1177 MachineInstr *LoadMI = prior(RestorePt);
1178 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1181 // Update spill stack slot live interval.
1182 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1183 LIs->getDefIndex(RestoreIndex));
1185 ReconstructLiveInterval(CurrLI);
1187 if (!FoldedRestore) {
1188 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1189 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1190 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1197 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1198 /// barrier that's being processed.
1200 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1201 SmallPtrSet<LiveInterval*, 8>& Split) {
1202 // First find all the virtual registers whose live intervals are intercepted
1203 // by the current barrier.
1204 SmallVector<LiveInterval*, 8> Intervals;
1205 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1206 // FIXME: If it's not safe to move any instruction that defines the barrier
1207 // register class, then it means there are some special dependencies which
1208 // codegen is not modelling. Ignore these barriers for now.
1209 if (!TII->isSafeToMoveRegClassDefs(*RC))
1211 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1212 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1213 unsigned Reg = VRs[i];
1214 if (!LIs->hasInterval(Reg))
1216 LiveInterval *LI = &LIs->getInterval(Reg);
1217 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1218 // Virtual register live interval is intercepted by the barrier. We
1219 // should split and shrink wrap its interval if possible.
1220 Intervals.push_back(LI);
1224 // Process the affected live intervals.
1225 bool Change = false;
1226 while (!Intervals.empty()) {
1227 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1229 else if (NumSplits == 4)
1231 LiveInterval *LI = Intervals.back();
1232 Intervals.pop_back();
1233 bool result = SplitRegLiveInterval(LI);
1234 if (result) Split.insert(LI);
1241 unsigned PreAllocSplitting::getNumberOfNonSpills(
1242 SmallPtrSet<MachineInstr*, 4>& MIs,
1243 unsigned Reg, int FrameIndex,
1244 bool& FeedsTwoAddr) {
1245 unsigned NonSpills = 0;
1246 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1248 int StoreFrameIndex;
1249 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1250 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1253 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1254 if (DefIdx != -1 && (*UI)->isRegReDefinedByTwoAddr(DefIdx))
1255 FeedsTwoAddr = true;
1261 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1262 /// split, and see if any of the spills are unnecessary. If so, remove them.
1263 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1264 bool changed = false;
1266 // Walk over all of the live intervals that were touched by the splitter,
1267 // and see if we can do any DCE and/or folding.
1268 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1269 LE = split.end(); LI != LE; ++LI) {
1270 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1272 // First, collect all the uses of the vreg, and sort them by their
1273 // reaching definition (VNInfo).
1274 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1275 UE = MRI->use_end(); UI != UE; ++UI) {
1276 unsigned index = LIs->getInstructionIndex(&*UI);
1277 index = LiveIntervals::getUseIndex(index);
1279 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1280 VNUseCount[LR->valno].insert(&*UI);
1283 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1284 // and/or fold them away.
1285 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1286 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1288 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1291 VNInfo* CurrVN = *VI;
1293 // We don't currently try to handle definitions with PHI kills, because
1294 // it would involve processing more than one VNInfo at once.
1295 if (CurrVN->hasPHIKill) continue;
1297 // We also don't try to handle the results of PHI joins, since there's
1298 // no defining instruction to analyze.
1299 unsigned DefIdx = CurrVN->def;
1300 if (DefIdx == ~0U || DefIdx == ~1U) continue;
1302 // We're only interested in eliminating cruft introduced by the splitter,
1303 // is of the form load-use or load-use-store. First, check that the
1304 // definition is a load, and remember what stack slot we loaded it from.
1305 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1307 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1309 // If the definition has no uses at all, just DCE it.
1310 if (VNUseCount[CurrVN].size() == 0) {
1311 LIs->RemoveMachineInstrFromMaps(DefMI);
1312 (*LI)->removeValNo(CurrVN);
1313 DefMI->eraseFromParent();
1314 VNUseCount.erase(CurrVN);
1320 // Second, get the number of non-store uses of the definition, as well as
1321 // a flag indicating whether it feeds into a later two-address definition.
1322 bool FeedsTwoAddr = false;
1323 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1324 (*LI)->reg, FrameIndex,
1327 // If there's one non-store use and it doesn't feed a two-addr, then
1328 // this is a load-use-store case that we can try to fold.
1329 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1330 // Start by finding the non-store use MachineInstr.
1331 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1332 int StoreFrameIndex;
1333 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1334 while (UI != VNUseCount[CurrVN].end() &&
1335 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1337 if (UI != VNUseCount[CurrVN].end())
1338 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1340 if (UI == VNUseCount[CurrVN].end()) continue;
1342 MachineInstr* use = *UI;
1344 // Attempt to fold it away!
1345 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1346 if (OpIdx == -1) continue;
1347 SmallVector<unsigned, 1> Ops;
1348 Ops.push_back(OpIdx);
1349 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1351 MachineInstr* NewMI =
1352 TII->foldMemoryOperand(*use->getParent()->getParent(),
1353 use, Ops, FrameIndex);
1355 if (!NewMI) continue;
1357 // Update relevant analyses.
1358 LIs->RemoveMachineInstrFromMaps(DefMI);
1359 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1360 (*LI)->removeValNo(CurrVN);
1362 DefMI->eraseFromParent();
1363 MachineBasicBlock* MBB = use->getParent();
1364 NewMI = MBB->insert(MBB->erase(use), NewMI);
1365 VNUseCount[CurrVN].erase(use);
1367 // Remove deleted instructions. Note that we need to remove them from
1368 // the VNInfo->use map as well, just to be safe.
1369 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1370 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1372 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1373 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1375 if (VNI->first != CurrVN)
1376 VNI->second.erase(*II);
1377 LIs->RemoveMachineInstrFromMaps(*II);
1378 (*II)->eraseFromParent();
1381 VNUseCount.erase(CurrVN);
1383 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1384 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1385 if (VI->second.erase(use))
1386 VI->second.insert(NewMI);
1393 // If there's more than one non-store instruction, we can't profitably
1394 // fold it, so bail.
1395 if (NonSpillCount) continue;
1397 // Otherwise, this is a load-store case, so DCE them.
1398 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1399 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1401 LIs->RemoveMachineInstrFromMaps(*UI);
1402 (*UI)->eraseFromParent();
1405 VNUseCount.erase(CurrVN);
1407 LIs->RemoveMachineInstrFromMaps(DefMI);
1408 (*LI)->removeValNo(CurrVN);
1409 DefMI->eraseFromParent();
1418 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1419 MachineBasicBlock* DefMBB,
1420 MachineBasicBlock* BarrierMBB) {
1421 if (DefMBB == BarrierMBB)
1424 if (LR->valno->hasPHIKill)
1427 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1428 if (LR->end < MBBEnd)
1431 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1432 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1435 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1436 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1437 typedef std::pair<MachineBasicBlock*,
1438 MachineBasicBlock::succ_iterator> ItPair;
1439 SmallVector<ItPair, 4> Stack;
1440 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1442 while (!Stack.empty()) {
1443 ItPair P = Stack.back();
1446 MachineBasicBlock* PredMBB = P.first;
1447 MachineBasicBlock::succ_iterator S = P.second;
1449 if (S == PredMBB->succ_end())
1451 else if (Visited.count(*S)) {
1452 Stack.push_back(std::make_pair(PredMBB, ++S));
1455 Stack.push_back(std::make_pair(PredMBB, S+1));
1457 MachineBasicBlock* MBB = *S;
1458 Visited.insert(MBB);
1460 if (MBB == BarrierMBB)
1463 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1464 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1465 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1467 if (MDTN == DefMDTN)
1469 else if (MDTN == BarrierMDTN)
1471 MDTN = MDTN->getIDom();
1474 MBBEnd = LIs->getMBBEndIdx(MBB);
1475 if (LR->end > MBBEnd)
1476 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1483 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1485 TM = &MF.getTarget();
1486 TRI = TM->getRegisterInfo();
1487 TII = TM->getInstrInfo();
1488 MFI = MF.getFrameInfo();
1489 MRI = &MF.getRegInfo();
1490 LIs = &getAnalysis<LiveIntervals>();
1491 LSs = &getAnalysis<LiveStacks>();
1493 bool MadeChange = false;
1495 // Make sure blocks are numbered in order.
1496 MF.RenumberBlocks();
1498 MachineBasicBlock *Entry = MF.begin();
1499 SmallPtrSet<MachineBasicBlock*,16> Visited;
1501 SmallPtrSet<LiveInterval*, 8> Split;
1503 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1504 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1507 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1508 E = BarrierMBB->end(); I != E; ++I) {
1510 const TargetRegisterClass **BarrierRCs =
1511 Barrier->getDesc().getRegClassBarriers();
1514 BarrierIdx = LIs->getInstructionIndex(Barrier);
1515 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1519 MadeChange |= removeDeadSpills(Split);