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);
41 static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1), cl::Hidden);
43 STATISTIC(NumSplits, "Number of intervals split");
44 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
45 STATISTIC(NumFolds, "Number of intervals split with spill folding");
46 STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
47 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
48 STATISTIC(NumDeadSpills, "Number of dead spills removed");
51 class VISIBILITY_HIDDEN PreAllocSplitting : public MachineFunctionPass {
52 MachineFunction *CurrMF;
53 const TargetMachine *TM;
54 const TargetInstrInfo *TII;
55 const TargetRegisterInfo* TRI;
56 MachineFrameInfo *MFI;
57 MachineRegisterInfo *MRI;
61 // Barrier - Current barrier being processed.
62 MachineInstr *Barrier;
64 // BarrierMBB - Basic block where the barrier resides in.
65 MachineBasicBlock *BarrierMBB;
67 // Barrier - Current barrier index.
70 // CurrLI - Current live interval being split.
73 // CurrSLI - Current stack slot live interval.
74 LiveInterval *CurrSLI;
76 // CurrSValNo - Current val# for the stack slot live interval.
79 // IntervalSSMap - A map from live interval to spill slots.
80 DenseMap<unsigned, int> IntervalSSMap;
82 // Def2SpillMap - A map from a def instruction index to spill index.
83 DenseMap<unsigned, unsigned> Def2SpillMap;
87 PreAllocSplitting() : MachineFunctionPass(&ID) {}
89 virtual bool runOnMachineFunction(MachineFunction &MF);
91 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
92 AU.addRequired<LiveIntervals>();
93 AU.addPreserved<LiveIntervals>();
94 AU.addRequired<LiveStacks>();
95 AU.addPreserved<LiveStacks>();
96 AU.addPreserved<RegisterCoalescer>();
98 AU.addPreservedID(StrongPHIEliminationID);
100 AU.addPreservedID(PHIEliminationID);
101 AU.addRequired<MachineDominatorTree>();
102 AU.addRequired<MachineLoopInfo>();
103 AU.addPreserved<MachineDominatorTree>();
104 AU.addPreserved<MachineLoopInfo>();
105 MachineFunctionPass::getAnalysisUsage(AU);
108 virtual void releaseMemory() {
109 IntervalSSMap.clear();
110 Def2SpillMap.clear();
113 virtual const char *getPassName() const {
114 return "Pre-Register Allocaton Live Interval Splitting";
117 /// print - Implement the dump method.
118 virtual void print(std::ostream &O, const Module* M = 0) const {
122 void print(std::ostream *O, const Module* M = 0) const {
127 MachineBasicBlock::iterator
128 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
131 MachineBasicBlock::iterator
132 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
133 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
135 MachineBasicBlock::iterator
136 findRestorePoint(MachineBasicBlock*, MachineInstr*, unsigned,
137 SmallPtrSet<MachineInstr*, 4>&, unsigned&);
139 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
141 bool IsAvailableInStack(MachineBasicBlock*, unsigned, unsigned, unsigned,
142 unsigned&, int&) const;
144 void UpdateSpillSlotInterval(VNInfo*, unsigned, unsigned);
146 bool SplitRegLiveInterval(LiveInterval*);
148 bool SplitRegLiveIntervals(const TargetRegisterClass **,
149 SmallPtrSet<LiveInterval*, 8>&);
151 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
152 MachineBasicBlock* BarrierMBB);
153 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
155 MachineBasicBlock::iterator RestorePt,
157 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
158 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
160 MachineInstr* Barrier,
161 MachineBasicBlock* MBB,
163 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
164 MachineInstr* FoldRestore(unsigned vreg,
165 const TargetRegisterClass* RC,
166 MachineInstr* Barrier,
167 MachineBasicBlock* MBB,
169 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
170 void RenumberValno(VNInfo* VN);
171 void ReconstructLiveInterval(LiveInterval* LI);
172 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
173 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
174 unsigned Reg, int FrameIndex, bool& TwoAddr);
175 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
176 MachineBasicBlock* MBB, LiveInterval* LI,
177 SmallPtrSet<MachineInstr*, 4>& Visited,
178 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
179 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
180 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
181 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
182 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
183 bool IsTopLevel, bool IsIntraBlock);
184 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
185 MachineBasicBlock* MBB, LiveInterval* LI,
186 SmallPtrSet<MachineInstr*, 4>& Visited,
187 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
188 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
189 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
190 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
191 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
192 bool IsTopLevel, bool IsIntraBlock);
194 } // end anonymous namespace
196 char PreAllocSplitting::ID = 0;
198 static RegisterPass<PreAllocSplitting>
199 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
201 const PassInfo *const llvm::PreAllocSplittingID = &X;
204 /// findNextEmptySlot - Find a gap after the given machine instruction in the
205 /// instruction index map. If there isn't one, return end().
206 MachineBasicBlock::iterator
207 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
208 unsigned &SpotIndex) {
209 MachineBasicBlock::iterator MII = MI;
210 if (++MII != MBB->end()) {
211 unsigned Index = LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
220 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
221 /// for spilling the current live interval. The index must be before any
222 /// defs and uses of the live interval register in the mbb. Return begin() if
224 MachineBasicBlock::iterator
225 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
227 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
228 unsigned &SpillIndex) {
229 MachineBasicBlock::iterator Pt = MBB->begin();
231 // Go top down if RefsInMBB is empty.
232 if (RefsInMBB.empty() && !DefMI) {
233 MachineBasicBlock::iterator MII = MBB->begin();
234 MachineBasicBlock::iterator EndPt = MI;
236 if (MII == EndPt) return Pt;
240 unsigned Index = LIs->getInstructionIndex(MII);
241 unsigned Gap = LIs->findGapBeforeInstr(Index);
243 // We can't insert the spill between the barrier (a call), and its
244 // corresponding call frame setup/teardown.
245 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
246 bool reachedBarrier = false;
249 reachedBarrier = true;
253 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
255 if (reachedBarrier) break;
261 } while (MII != EndPt);
263 MachineBasicBlock::iterator MII = MI;
264 MachineBasicBlock::iterator EndPt = DefMI
265 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
267 while (MII != EndPt && !RefsInMBB.count(MII)) {
268 unsigned Index = LIs->getInstructionIndex(MII);
270 // We can't insert the spill between the barrier (a call), and its
271 // corresponding call frame setup.
272 if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
275 } if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
276 bool reachedBarrier = false;
277 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
280 reachedBarrier = true;
285 if (reachedBarrier) break;
287 } else if (LIs->hasGapBeforeInstr(Index)) {
289 SpillIndex = LIs->findGapBeforeInstr(Index, true);
298 /// findRestorePoint - Find a gap in the instruction index map that's suitable
299 /// for restoring the current live interval value. The index must be before any
300 /// uses of the live interval register in the mbb. Return end() if none is
302 MachineBasicBlock::iterator
303 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
305 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
306 unsigned &RestoreIndex) {
307 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
308 // begin index accordingly.
309 MachineBasicBlock::iterator Pt = MBB->end();
310 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
312 // Go bottom up if RefsInMBB is empty and the end of the mbb isn't beyond
313 // the last index in the live range.
314 if (RefsInMBB.empty() && LastIdx >= EndIdx) {
315 MachineBasicBlock::iterator MII = MBB->getFirstTerminator();
316 MachineBasicBlock::iterator EndPt = MI;
318 if (MII == EndPt) return Pt;
322 unsigned Index = LIs->getInstructionIndex(MII);
323 unsigned Gap = LIs->findGapBeforeInstr(Index);
325 // We can't insert a restore between the barrier (a call) and its
326 // corresponding call frame teardown.
327 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
328 bool reachedBarrier = false;
329 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
332 reachedBarrier = true;
337 if (reachedBarrier) break;
346 } while (MII != EndPt);
348 MachineBasicBlock::iterator MII = MI;
351 // FIXME: Limit the number of instructions to examine to reduce
353 while (MII != MBB->getFirstTerminator()) {
354 unsigned Index = LIs->getInstructionIndex(MII);
357 unsigned Gap = LIs->findGapBeforeInstr(Index);
359 // We can't insert a restore between the barrier (a call) and its
360 // corresponding call frame teardown.
361 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
364 } else if (prior(MII)->getOpcode() == TRI->getCallFrameSetupOpcode()) {
365 bool reachedBarrier = false;
367 if (MII == MBB->getFirstTerminator() || RefsInMBB.count(MII)) {
368 reachedBarrier = true;
373 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
375 if (reachedBarrier) break;
381 if (RefsInMBB.count(MII))
390 /// CreateSpillStackSlot - Create a stack slot for the live interval being
391 /// split. If the live interval was previously split, just reuse the same
393 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
394 const TargetRegisterClass *RC) {
396 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
397 if (I != IntervalSSMap.end()) {
400 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
401 IntervalSSMap[Reg] = SS;
404 // Create live interval for stack slot.
405 CurrSLI = &LSs->getOrCreateInterval(SS);
406 if (CurrSLI->hasAtLeastOneValue())
407 CurrSValNo = CurrSLI->getValNumInfo(0);
409 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
413 /// IsAvailableInStack - Return true if register is available in a split stack
414 /// slot at the specified index.
416 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
417 unsigned Reg, unsigned DefIndex,
418 unsigned RestoreIndex, unsigned &SpillIndex,
423 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
424 if (I == IntervalSSMap.end())
426 DenseMap<unsigned, unsigned>::iterator II = Def2SpillMap.find(DefIndex);
427 if (II == Def2SpillMap.end())
430 // If last spill of def is in the same mbb as barrier mbb (where restore will
431 // be), make sure it's not below the intended restore index.
432 // FIXME: Undo the previous spill?
433 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
434 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
438 SpillIndex = II->second;
442 /// UpdateSpillSlotInterval - Given the specified val# of the register live
443 /// interval being split, and the spill and restore indicies, update the live
444 /// interval of the spill stack slot.
446 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, unsigned SpillIndex,
447 unsigned RestoreIndex) {
448 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
449 "Expect restore in the barrier mbb");
451 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
452 if (MBB == BarrierMBB) {
453 // Intra-block spill + restore. We are done.
454 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
455 CurrSLI->addRange(SLR);
459 SmallPtrSet<MachineBasicBlock*, 4> Processed;
460 unsigned EndIdx = LIs->getMBBEndIdx(MBB);
461 LiveRange SLR(SpillIndex, EndIdx+1, CurrSValNo);
462 CurrSLI->addRange(SLR);
463 Processed.insert(MBB);
465 // Start from the spill mbb, figure out the extend of the spill slot's
467 SmallVector<MachineBasicBlock*, 4> WorkList;
468 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
469 if (LR->end > EndIdx)
470 // If live range extend beyond end of mbb, add successors to work list.
471 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
472 SE = MBB->succ_end(); SI != SE; ++SI)
473 WorkList.push_back(*SI);
475 while (!WorkList.empty()) {
476 MachineBasicBlock *MBB = WorkList.back();
478 if (Processed.count(MBB))
480 unsigned Idx = LIs->getMBBStartIdx(MBB);
481 LR = CurrLI->getLiveRangeContaining(Idx);
482 if (LR && LR->valno == ValNo) {
483 EndIdx = LIs->getMBBEndIdx(MBB);
484 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
485 // Spill slot live interval stops at the restore.
486 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
487 CurrSLI->addRange(SLR);
488 } else if (LR->end > EndIdx) {
489 // Live range extends beyond end of mbb, process successors.
490 LiveRange SLR(Idx, EndIdx+1, CurrSValNo);
491 CurrSLI->addRange(SLR);
492 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
493 SE = MBB->succ_end(); SI != SE; ++SI)
494 WorkList.push_back(*SI);
496 LiveRange SLR(Idx, LR->end, CurrSValNo);
497 CurrSLI->addRange(SLR);
499 Processed.insert(MBB);
504 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
505 /// construction algorithm to compute the ranges and valnos for an interval.
507 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
508 MachineBasicBlock* MBB, LiveInterval* LI,
509 SmallPtrSet<MachineInstr*, 4>& Visited,
510 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
511 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
512 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
513 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
514 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
515 bool IsTopLevel, bool IsIntraBlock) {
516 // Return memoized result if it's available.
517 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
519 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
521 else if (!IsIntraBlock && LiveOut.count(MBB))
524 // Check if our block contains any uses or defs.
525 bool ContainsDefs = Defs.count(MBB);
526 bool ContainsUses = Uses.count(MBB);
530 // Enumerate the cases of use/def contaning blocks.
531 if (!ContainsDefs && !ContainsUses) {
532 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
533 NewVNs, LiveOut, Phis,
534 IsTopLevel, IsIntraBlock);
535 } else if (ContainsDefs && !ContainsUses) {
536 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
538 // Search for the def in this block. If we don't find it before the
539 // instruction we care about, go to the fallback case. Note that that
540 // should never happen: this cannot be intrablock, so use should
541 // always be an end() iterator.
542 assert(UseI == MBB->end() && "No use marked in intrablock");
544 MachineBasicBlock::iterator Walker = UseI;
546 while (Walker != MBB->begin()) {
547 if (BlockDefs.count(Walker))
552 // Once we've found it, extend its VNInfo to our instruction.
553 unsigned DefIndex = LIs->getInstructionIndex(Walker);
554 DefIndex = LiveIntervals::getDefIndex(DefIndex);
555 unsigned EndIndex = LIs->getMBBEndIdx(MBB);
557 RetVNI = NewVNs[Walker];
558 LI->addRange(LiveRange(DefIndex, EndIndex+1, RetVNI));
559 } else if (!ContainsDefs && ContainsUses) {
560 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
562 // Search for the use in this block that precedes the instruction we care
563 // about, going to the fallback case if we don't find it.
564 if (UseI == MBB->begin())
565 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
566 Uses, NewVNs, LiveOut, Phis,
567 IsTopLevel, IsIntraBlock);
569 MachineBasicBlock::iterator Walker = UseI;
572 while (Walker != MBB->begin()) {
573 if (BlockUses.count(Walker)) {
580 // Must check begin() too.
582 if (BlockUses.count(Walker))
585 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
586 Uses, NewVNs, LiveOut, Phis,
587 IsTopLevel, IsIntraBlock);
590 unsigned UseIndex = LIs->getInstructionIndex(Walker);
591 UseIndex = LiveIntervals::getUseIndex(UseIndex);
592 unsigned EndIndex = 0;
594 EndIndex = LIs->getInstructionIndex(UseI);
595 EndIndex = LiveIntervals::getUseIndex(EndIndex);
597 EndIndex = LIs->getMBBEndIdx(MBB);
599 // Now, recursively phi construct the VNInfo for the use we found,
600 // and then extend it to include the instruction we care about
601 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
602 NewVNs, LiveOut, Phis, false, true);
604 LI->addRange(LiveRange(UseIndex, EndIndex+1, RetVNI));
606 // FIXME: Need to set kills properly for inter-block stuff.
607 if (LI->isKill(RetVNI, UseIndex)) LI->removeKill(RetVNI, UseIndex);
609 LI->addKill(RetVNI, EndIndex);
610 } else if (ContainsDefs && ContainsUses) {
611 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
612 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
614 // This case is basically a merging of the two preceding case, with the
615 // special note that checking for defs must take precedence over checking
616 // for uses, because of two-address instructions.
618 if (UseI == MBB->begin())
619 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
620 NewVNs, LiveOut, Phis,
621 IsTopLevel, IsIntraBlock);
623 MachineBasicBlock::iterator Walker = UseI;
625 bool foundDef = false;
626 bool foundUse = false;
627 while (Walker != MBB->begin()) {
628 if (BlockDefs.count(Walker)) {
631 } else if (BlockUses.count(Walker)) {
638 // Must check begin() too.
639 if (!foundDef && !foundUse) {
640 if (BlockDefs.count(Walker))
642 else if (BlockUses.count(Walker))
645 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
646 Uses, NewVNs, LiveOut, Phis,
647 IsTopLevel, IsIntraBlock);
650 unsigned StartIndex = LIs->getInstructionIndex(Walker);
651 StartIndex = foundDef ? LiveIntervals::getDefIndex(StartIndex) :
652 LiveIntervals::getUseIndex(StartIndex);
653 unsigned EndIndex = 0;
655 EndIndex = LIs->getInstructionIndex(UseI);
656 EndIndex = LiveIntervals::getUseIndex(EndIndex);
658 EndIndex = LIs->getMBBEndIdx(MBB);
661 RetVNI = NewVNs[Walker];
663 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
664 NewVNs, LiveOut, Phis, false, true);
666 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
668 if (foundUse && LI->isKill(RetVNI, StartIndex))
669 LI->removeKill(RetVNI, StartIndex);
671 LI->addKill(RetVNI, EndIndex);
675 // Memoize results so we don't have to recompute them.
676 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
678 if (!NewVNs.count(UseI))
679 NewVNs[UseI] = RetVNI;
680 Visited.insert(UseI);
686 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
689 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
690 MachineBasicBlock* MBB, LiveInterval* LI,
691 SmallPtrSet<MachineInstr*, 4>& Visited,
692 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
693 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
694 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
695 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
696 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
697 bool IsTopLevel, bool IsIntraBlock) {
698 // NOTE: Because this is the fallback case from other cases, we do NOT
699 // assume that we are not intrablock here.
700 if (Phis.count(MBB)) return Phis[MBB];
702 unsigned StartIndex = LIs->getMBBStartIdx(MBB);
703 VNInfo *RetVNI = Phis[MBB] = LI->getNextValue(~0U, /*FIXME*/ 0,
704 LIs->getVNInfoAllocator());
705 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
707 // If there are no uses or defs between our starting point and the
708 // beginning of the block, then recursive perform phi construction
709 // on our predecessors.
710 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
711 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
712 PE = MBB->pred_end(); PI != PE; ++PI) {
713 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
714 Visited, Defs, Uses, NewVNs,
715 LiveOut, Phis, false, false);
717 IncomingVNs[*PI] = Incoming;
720 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill) {
721 VNInfo* OldVN = RetVNI;
722 VNInfo* NewVN = IncomingVNs.begin()->second;
723 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
724 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
726 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
727 LOE = LiveOut.end(); LOI != LOE; ++LOI)
728 if (LOI->second == OldVN)
729 LOI->second = MergedVN;
730 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
731 NVE = NewVNs.end(); NVI != NVE; ++NVI)
732 if (NVI->second == OldVN)
733 NVI->second = MergedVN;
734 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
735 PE = Phis.end(); PI != PE; ++PI)
736 if (PI->second == OldVN)
737 PI->second = MergedVN;
740 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
741 // VNInfo to represent the joined value.
742 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
743 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
744 I->second->hasPHIKill = true;
745 unsigned KillIndex = LIs->getMBBEndIdx(I->first);
746 if (!LiveInterval::isKill(I->second, KillIndex))
747 LI->addKill(I->second, KillIndex);
751 unsigned EndIndex = 0;
753 EndIndex = LIs->getInstructionIndex(UseI);
754 EndIndex = LiveIntervals::getUseIndex(EndIndex);
756 EndIndex = LIs->getMBBEndIdx(MBB);
757 LI->addRange(LiveRange(StartIndex, EndIndex+1, RetVNI));
759 LI->addKill(RetVNI, EndIndex);
761 // Memoize results so we don't have to recompute them.
763 LiveOut[MBB] = RetVNI;
765 if (!NewVNs.count(UseI))
766 NewVNs[UseI] = RetVNI;
767 Visited.insert(UseI);
773 /// ReconstructLiveInterval - Recompute a live interval from scratch.
774 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
775 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
777 // Clear the old ranges and valnos;
780 // Cache the uses and defs of the register
781 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
784 // Keep track of the new VNs we're creating.
785 DenseMap<MachineInstr*, VNInfo*> NewVNs;
786 SmallPtrSet<VNInfo*, 2> PhiVNs;
788 // Cache defs, and create a new VNInfo for each def.
789 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
790 DE = MRI->def_end(); DI != DE; ++DI) {
791 Defs[(*DI).getParent()].insert(&*DI);
793 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
794 DefIdx = LiveIntervals::getDefIndex(DefIdx);
796 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
798 // If the def is a move, set the copy field.
799 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
800 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
801 if (DstReg == LI->reg)
804 NewVNs[&*DI] = NewVN;
807 // Cache uses as a separate pass from actually processing them.
808 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
809 UE = MRI->use_end(); UI != UE; ++UI)
810 Uses[(*UI).getParent()].insert(&*UI);
812 // Now, actually process every use and use a phi construction algorithm
813 // to walk from it to its reaching definitions, building VNInfos along
815 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
816 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
817 SmallPtrSet<MachineInstr*, 4> Visited;
818 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
819 UE = MRI->use_end(); UI != UE; ++UI) {
820 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
821 Uses, NewVNs, LiveOut, Phis, true, true);
824 // Add ranges for dead defs
825 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
826 DE = MRI->def_end(); DI != DE; ++DI) {
827 unsigned DefIdx = LIs->getInstructionIndex(&*DI);
828 DefIdx = LiveIntervals::getDefIndex(DefIdx);
830 if (LI->liveAt(DefIdx)) continue;
832 VNInfo* DeadVN = NewVNs[&*DI];
833 LI->addRange(LiveRange(DefIdx, DefIdx+1, DeadVN));
834 LI->addKill(DeadVN, DefIdx);
838 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
839 /// be allocated to a different register. This function creates a new vreg,
840 /// copies the valno and its live ranges over to the new vreg's interval,
841 /// removes them from the old interval, and rewrites all uses and defs of
842 /// the original reg to the new vreg within those ranges.
843 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
844 SmallVector<VNInfo*, 4> Stack;
845 SmallVector<VNInfo*, 4> VNsToCopy;
848 // Walk through and copy the valno we care about, and any other valnos
849 // that are two-address redefinitions of the one we care about. These
850 // will need to be rewritten as well. We also check for safety of the
851 // renumbering here, by making sure that none of the valno involved has
853 while (!Stack.empty()) {
854 VNInfo* OldVN = Stack.back();
857 // Bail out if we ever encounter a valno that has a PHI kill. We can't
859 if (OldVN->hasPHIKill) return;
861 VNsToCopy.push_back(OldVN);
863 // Locate two-address redefinitions
864 for (SmallVector<unsigned, 4>::iterator KI = OldVN->kills.begin(),
865 KE = OldVN->kills.end(); KI != KE; ++KI) {
866 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
867 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
868 if (DefIdx == ~0U) continue;
869 if (MI->isRegReDefinedByTwoAddr(DefIdx)) {
871 CurrLI->findDefinedVNInfo(LiveIntervals::getDefIndex(*KI));
872 if (NextVN == OldVN) continue;
873 Stack.push_back(NextVN);
878 // Create the new vreg
879 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
881 // Create the new live interval
882 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
884 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
885 VNsToCopy.end(); OI != OE; ++OI) {
888 // Copy the valno over
889 VNInfo* NewVN = NewLI.getNextValue(OldVN->def, OldVN->copy,
890 LIs->getVNInfoAllocator());
891 NewLI.copyValNumInfo(NewVN, OldVN);
892 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
894 // Remove the valno from the old interval
895 CurrLI->removeValNo(OldVN);
898 // Rewrite defs and uses. This is done in two stages to avoid invalidating
900 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
902 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
903 E = MRI->reg_end(); I != E; ++I) {
904 MachineOperand& MO = I.getOperand();
905 unsigned InstrIdx = LIs->getInstructionIndex(&*I);
907 if ((MO.isUse() && NewLI.liveAt(LiveIntervals::getUseIndex(InstrIdx))) ||
908 (MO.isDef() && NewLI.liveAt(LiveIntervals::getDefIndex(InstrIdx))))
909 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
912 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
913 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
914 MachineInstr* Inst = I->first;
915 unsigned OpIdx = I->second;
916 MachineOperand& MO = Inst->getOperand(OpIdx);
920 // The renumbered vreg shares a stack slot with the old register.
921 if (IntervalSSMap.count(CurrLI->reg))
922 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
927 bool PreAllocSplitting::Rematerialize(unsigned vreg, VNInfo* ValNo,
929 MachineBasicBlock::iterator RestorePt,
931 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
932 MachineBasicBlock& MBB = *RestorePt->getParent();
934 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
935 unsigned KillIdx = 0;
936 if (ValNo->def == ~0U || DefMI->getParent() == BarrierMBB)
937 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
939 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
941 if (KillPt == DefMI->getParent()->end())
944 TII->reMaterialize(MBB, RestorePt, vreg, DefMI);
945 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
947 ReconstructLiveInterval(CurrLI);
948 unsigned RematIdx = LIs->getInstructionIndex(prior(RestorePt));
949 RematIdx = LiveIntervals::getDefIndex(RematIdx);
950 RenumberValno(CurrLI->findDefinedVNInfo(RematIdx));
957 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
958 const TargetRegisterClass* RC,
960 MachineInstr* Barrier,
961 MachineBasicBlock* MBB,
963 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
964 MachineBasicBlock::iterator Pt = MBB->begin();
966 // Go top down if RefsInMBB is empty.
967 if (RefsInMBB.empty())
970 MachineBasicBlock::iterator FoldPt = Barrier;
971 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
972 !RefsInMBB.count(FoldPt))
975 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
979 SmallVector<unsigned, 1> Ops;
980 Ops.push_back(OpIdx);
982 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
985 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
986 if (I != IntervalSSMap.end()) {
989 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
993 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
997 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
998 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1001 IntervalSSMap[vreg] = SS;
1002 CurrSLI = &LSs->getOrCreateInterval(SS);
1003 if (CurrSLI->hasAtLeastOneValue())
1004 CurrSValNo = CurrSLI->getValNumInfo(0);
1006 CurrSValNo = CurrSLI->getNextValue(~0U, 0, LSs->getVNInfoAllocator());
1012 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
1013 const TargetRegisterClass* RC,
1014 MachineInstr* Barrier,
1015 MachineBasicBlock* MBB,
1017 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
1018 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == NumRestoreFolds)
1021 // Go top down if RefsInMBB is empty.
1022 if (RefsInMBB.empty())
1025 // Can't fold a restore between a call stack setup and teardown.
1026 MachineBasicBlock::iterator FoldPt = Barrier;
1028 // Advance from barrier to call frame teardown.
1029 while (FoldPt != MBB->getFirstTerminator() &&
1030 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1031 if (RefsInMBB.count(FoldPt))
1037 if (FoldPt == MBB->getFirstTerminator())
1042 // Now find the restore point.
1043 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
1044 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
1045 while (FoldPt != MBB->getFirstTerminator() &&
1046 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1047 if (RefsInMBB.count(FoldPt))
1053 if (FoldPt == MBB->getFirstTerminator())
1060 if (FoldPt == MBB->getFirstTerminator())
1063 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1067 SmallVector<unsigned, 1> Ops;
1068 Ops.push_back(OpIdx);
1070 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1073 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1077 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1078 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1085 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1086 /// so it would not cross the barrier that's being processed. Shrink wrap
1087 /// (minimize) the live interval to the last uses.
1088 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1091 // Find live range where current interval cross the barrier.
1092 LiveInterval::iterator LR =
1093 CurrLI->FindLiveRangeContaining(LIs->getUseIndex(BarrierIdx));
1094 VNInfo *ValNo = LR->valno;
1096 if (ValNo->def == ~1U) {
1097 // Defined by a dead def? How can this be?
1098 assert(0 && "Val# is defined by a dead def?");
1102 MachineInstr *DefMI = (ValNo->def != ~0U)
1103 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1105 // If this would create a new join point, do not split.
1106 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent()))
1109 // Find all references in the barrier mbb.
1110 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1111 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1112 E = MRI->reg_end(); I != E; ++I) {
1113 MachineInstr *RefMI = &*I;
1114 if (RefMI->getParent() == BarrierMBB)
1115 RefsInMBB.insert(RefMI);
1118 // Find a point to restore the value after the barrier.
1119 unsigned RestoreIndex = 0;
1120 MachineBasicBlock::iterator RestorePt =
1121 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1122 if (RestorePt == BarrierMBB->end())
1125 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1126 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1127 RestoreIndex, RefsInMBB))
1130 // Add a spill either before the barrier or after the definition.
1131 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1132 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1133 unsigned SpillIndex = 0;
1134 MachineInstr *SpillMI = NULL;
1136 if (ValNo->def == ~0U) {
1137 // If it's defined by a phi, we must split just before the barrier.
1138 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1139 BarrierMBB, SS, RefsInMBB))) {
1140 SpillIndex = LIs->getInstructionIndex(SpillMI);
1142 MachineBasicBlock::iterator SpillPt =
1143 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1144 if (SpillPt == BarrierMBB->begin())
1145 return false; // No gap to insert spill.
1148 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1149 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1150 SpillMI = prior(SpillPt);
1151 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1153 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1154 RestoreIndex, SpillIndex, SS)) {
1155 // If it's already split, just restore the value. There is no need to spill
1158 return false; // Def is dead. Do nothing.
1160 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1161 BarrierMBB, SS, RefsInMBB))) {
1162 SpillIndex = LIs->getInstructionIndex(SpillMI);
1164 // Check if it's possible to insert a spill after the def MI.
1165 MachineBasicBlock::iterator SpillPt;
1166 if (DefMBB == BarrierMBB) {
1167 // Add spill after the def and the last use before the barrier.
1168 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1169 RefsInMBB, SpillIndex);
1170 if (SpillPt == DefMBB->begin())
1171 return false; // No gap to insert spill.
1173 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1174 if (SpillPt == DefMBB->end())
1175 return false; // No gap to insert spill.
1177 // Add spill. The store instruction kills the register if def is before
1178 // the barrier in the barrier block.
1179 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1180 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg,
1181 DefMBB == BarrierMBB, SS, RC);
1182 SpillMI = prior(SpillPt);
1183 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1187 // Remember def instruction index to spill index mapping.
1188 if (DefMI && SpillMI)
1189 Def2SpillMap[ValNo->def] = SpillIndex;
1192 bool FoldedRestore = false;
1193 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1194 BarrierMBB, SS, RefsInMBB)) {
1196 RestoreIndex = LIs->getInstructionIndex(RestorePt);
1197 FoldedRestore = true;
1199 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1200 MachineInstr *LoadMI = prior(RestorePt);
1201 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1204 // Update spill stack slot live interval.
1205 UpdateSpillSlotInterval(ValNo, LIs->getUseIndex(SpillIndex)+1,
1206 LIs->getDefIndex(RestoreIndex));
1208 ReconstructLiveInterval(CurrLI);
1210 if (!FoldedRestore) {
1211 unsigned RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1212 RestoreIdx = LiveIntervals::getDefIndex(RestoreIdx);
1213 RenumberValno(CurrLI->findDefinedVNInfo(RestoreIdx));
1220 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1221 /// barrier that's being processed.
1223 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1224 SmallPtrSet<LiveInterval*, 8>& Split) {
1225 // First find all the virtual registers whose live intervals are intercepted
1226 // by the current barrier.
1227 SmallVector<LiveInterval*, 8> Intervals;
1228 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1229 // FIXME: If it's not safe to move any instruction that defines the barrier
1230 // register class, then it means there are some special dependencies which
1231 // codegen is not modelling. Ignore these barriers for now.
1232 if (!TII->isSafeToMoveRegClassDefs(*RC))
1234 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1235 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1236 unsigned Reg = VRs[i];
1237 if (!LIs->hasInterval(Reg))
1239 LiveInterval *LI = &LIs->getInterval(Reg);
1240 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1241 // Virtual register live interval is intercepted by the barrier. We
1242 // should split and shrink wrap its interval if possible.
1243 Intervals.push_back(LI);
1247 // Process the affected live intervals.
1248 bool Change = false;
1249 while (!Intervals.empty()) {
1250 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1252 else if (NumSplits == 4)
1254 LiveInterval *LI = Intervals.back();
1255 Intervals.pop_back();
1256 bool result = SplitRegLiveInterval(LI);
1257 if (result) Split.insert(LI);
1264 unsigned PreAllocSplitting::getNumberOfNonSpills(
1265 SmallPtrSet<MachineInstr*, 4>& MIs,
1266 unsigned Reg, int FrameIndex,
1267 bool& FeedsTwoAddr) {
1268 unsigned NonSpills = 0;
1269 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1271 int StoreFrameIndex;
1272 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1273 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1276 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1277 if (DefIdx != -1 && (*UI)->isRegReDefinedByTwoAddr(DefIdx))
1278 FeedsTwoAddr = true;
1284 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1285 /// split, and see if any of the spills are unnecessary. If so, remove them.
1286 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1287 bool changed = false;
1289 // Walk over all of the live intervals that were touched by the splitter,
1290 // and see if we can do any DCE and/or folding.
1291 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1292 LE = split.end(); LI != LE; ++LI) {
1293 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1295 // First, collect all the uses of the vreg, and sort them by their
1296 // reaching definition (VNInfo).
1297 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1298 UE = MRI->use_end(); UI != UE; ++UI) {
1299 unsigned index = LIs->getInstructionIndex(&*UI);
1300 index = LiveIntervals::getUseIndex(index);
1302 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1303 VNUseCount[LR->valno].insert(&*UI);
1306 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1307 // and/or fold them away.
1308 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1309 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1311 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1314 VNInfo* CurrVN = *VI;
1316 // We don't currently try to handle definitions with PHI kills, because
1317 // it would involve processing more than one VNInfo at once.
1318 if (CurrVN->hasPHIKill) continue;
1320 // We also don't try to handle the results of PHI joins, since there's
1321 // no defining instruction to analyze.
1322 unsigned DefIdx = CurrVN->def;
1323 if (DefIdx == ~0U || DefIdx == ~1U) continue;
1325 // We're only interested in eliminating cruft introduced by the splitter,
1326 // is of the form load-use or load-use-store. First, check that the
1327 // definition is a load, and remember what stack slot we loaded it from.
1328 MachineInstr* DefMI = LIs->getInstructionFromIndex(DefIdx);
1330 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1332 // If the definition has no uses at all, just DCE it.
1333 if (VNUseCount[CurrVN].size() == 0) {
1334 LIs->RemoveMachineInstrFromMaps(DefMI);
1335 (*LI)->removeValNo(CurrVN);
1336 DefMI->eraseFromParent();
1337 VNUseCount.erase(CurrVN);
1343 // Second, get the number of non-store uses of the definition, as well as
1344 // a flag indicating whether it feeds into a later two-address definition.
1345 bool FeedsTwoAddr = false;
1346 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1347 (*LI)->reg, FrameIndex,
1350 // If there's one non-store use and it doesn't feed a two-addr, then
1351 // this is a load-use-store case that we can try to fold.
1352 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1353 // Start by finding the non-store use MachineInstr.
1354 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1355 int StoreFrameIndex;
1356 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1357 while (UI != VNUseCount[CurrVN].end() &&
1358 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1360 if (UI != VNUseCount[CurrVN].end())
1361 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1363 if (UI == VNUseCount[CurrVN].end()) continue;
1365 MachineInstr* use = *UI;
1367 // Attempt to fold it away!
1368 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1369 if (OpIdx == -1) continue;
1370 SmallVector<unsigned, 1> Ops;
1371 Ops.push_back(OpIdx);
1372 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1374 MachineInstr* NewMI =
1375 TII->foldMemoryOperand(*use->getParent()->getParent(),
1376 use, Ops, FrameIndex);
1378 if (!NewMI) continue;
1380 // Update relevant analyses.
1381 LIs->RemoveMachineInstrFromMaps(DefMI);
1382 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1383 (*LI)->removeValNo(CurrVN);
1385 DefMI->eraseFromParent();
1386 MachineBasicBlock* MBB = use->getParent();
1387 NewMI = MBB->insert(MBB->erase(use), NewMI);
1388 VNUseCount[CurrVN].erase(use);
1390 // Remove deleted instructions. Note that we need to remove them from
1391 // the VNInfo->use map as well, just to be safe.
1392 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1393 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1395 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1396 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1398 if (VNI->first != CurrVN)
1399 VNI->second.erase(*II);
1400 LIs->RemoveMachineInstrFromMaps(*II);
1401 (*II)->eraseFromParent();
1404 VNUseCount.erase(CurrVN);
1406 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1407 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1408 if (VI->second.erase(use))
1409 VI->second.insert(NewMI);
1416 // If there's more than one non-store instruction, we can't profitably
1417 // fold it, so bail.
1418 if (NonSpillCount) continue;
1420 // Otherwise, this is a load-store case, so DCE them.
1421 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1422 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1424 LIs->RemoveMachineInstrFromMaps(*UI);
1425 (*UI)->eraseFromParent();
1428 VNUseCount.erase(CurrVN);
1430 LIs->RemoveMachineInstrFromMaps(DefMI);
1431 (*LI)->removeValNo(CurrVN);
1432 DefMI->eraseFromParent();
1441 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1442 MachineBasicBlock* DefMBB,
1443 MachineBasicBlock* BarrierMBB) {
1444 if (DefMBB == BarrierMBB)
1447 if (LR->valno->hasPHIKill)
1450 unsigned MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1451 if (LR->end < MBBEnd)
1454 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1455 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1458 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1459 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1460 typedef std::pair<MachineBasicBlock*,
1461 MachineBasicBlock::succ_iterator> ItPair;
1462 SmallVector<ItPair, 4> Stack;
1463 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1465 while (!Stack.empty()) {
1466 ItPair P = Stack.back();
1469 MachineBasicBlock* PredMBB = P.first;
1470 MachineBasicBlock::succ_iterator S = P.second;
1472 if (S == PredMBB->succ_end())
1474 else if (Visited.count(*S)) {
1475 Stack.push_back(std::make_pair(PredMBB, ++S));
1478 Stack.push_back(std::make_pair(PredMBB, S+1));
1480 MachineBasicBlock* MBB = *S;
1481 Visited.insert(MBB);
1483 if (MBB == BarrierMBB)
1486 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1487 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1488 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1490 if (MDTN == DefMDTN)
1492 else if (MDTN == BarrierMDTN)
1494 MDTN = MDTN->getIDom();
1497 MBBEnd = LIs->getMBBEndIdx(MBB);
1498 if (LR->end > MBBEnd)
1499 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1506 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1508 TM = &MF.getTarget();
1509 TRI = TM->getRegisterInfo();
1510 TII = TM->getInstrInfo();
1511 MFI = MF.getFrameInfo();
1512 MRI = &MF.getRegInfo();
1513 LIs = &getAnalysis<LiveIntervals>();
1514 LSs = &getAnalysis<LiveStacks>();
1516 bool MadeChange = false;
1518 // Make sure blocks are numbered in order.
1519 MF.RenumberBlocks();
1521 MachineBasicBlock *Entry = MF.begin();
1522 SmallPtrSet<MachineBasicBlock*,16> Visited;
1524 SmallPtrSet<LiveInterval*, 8> Split;
1526 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1527 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1530 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1531 E = BarrierMBB->end(); I != E; ++I) {
1533 const TargetRegisterClass **BarrierRCs =
1534 Barrier->getDesc().getRegClassBarriers();
1537 BarrierIdx = LIs->getInstructionIndex(Barrier);
1538 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1542 MadeChange |= removeDeadSpills(Split);