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 "VirtRegMap.h"
19 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
20 #include "llvm/CodeGen/LiveStackAnalysis.h"
21 #include "llvm/CodeGen/MachineDominators.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineLoopInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/CodeGen/RegisterCoalescer.h"
28 #include "llvm/Target/TargetInstrInfo.h"
29 #include "llvm/Target/TargetMachine.h"
30 #include "llvm/Target/TargetOptions.h"
31 #include "llvm/Target/TargetRegisterInfo.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/Debug.h"
34 #include "llvm/Support/ErrorHandling.h"
35 #include "llvm/ADT/DenseMap.h"
36 #include "llvm/ADT/DepthFirstIterator.h"
37 #include "llvm/ADT/SmallPtrSet.h"
38 #include "llvm/ADT/Statistic.h"
41 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
42 static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1),
44 static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1),
47 STATISTIC(NumSplits, "Number of intervals split");
48 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
49 STATISTIC(NumFolds, "Number of intervals split with spill folding");
50 STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
51 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
52 STATISTIC(NumDeadSpills, "Number of dead spills removed");
55 class PreAllocSplitting : public MachineFunctionPass {
56 MachineFunction *CurrMF;
57 const TargetMachine *TM;
58 const TargetInstrInfo *TII;
59 const TargetRegisterInfo* TRI;
60 MachineFrameInfo *MFI;
61 MachineRegisterInfo *MRI;
67 // Barrier - Current barrier being processed.
68 MachineInstr *Barrier;
70 // BarrierMBB - Basic block where the barrier resides in.
71 MachineBasicBlock *BarrierMBB;
73 // Barrier - Current barrier index.
76 // CurrLI - Current live interval being split.
79 // CurrSLI - Current stack slot live interval.
80 LiveInterval *CurrSLI;
82 // CurrSValNo - Current val# for the stack slot live interval.
85 // IntervalSSMap - A map from live interval to spill slots.
86 DenseMap<unsigned, int> IntervalSSMap;
88 // Def2SpillMap - A map from a def instruction index to spill index.
89 DenseMap<SlotIndex, SlotIndex> Def2SpillMap;
94 : MachineFunctionPass(&ID) {}
96 virtual bool runOnMachineFunction(MachineFunction &MF);
98 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.addRequired<SlotIndexes>();
101 AU.addPreserved<SlotIndexes>();
102 AU.addRequired<LiveIntervals>();
103 AU.addPreserved<LiveIntervals>();
104 AU.addRequired<LiveStacks>();
105 AU.addPreserved<LiveStacks>();
106 AU.addPreserved<RegisterCoalescer>();
108 AU.addPreservedID(StrongPHIEliminationID);
110 AU.addPreservedID(PHIEliminationID);
111 AU.addRequired<MachineDominatorTree>();
112 AU.addRequired<MachineLoopInfo>();
113 AU.addRequired<VirtRegMap>();
114 AU.addPreserved<MachineDominatorTree>();
115 AU.addPreserved<MachineLoopInfo>();
116 AU.addPreserved<VirtRegMap>();
117 MachineFunctionPass::getAnalysisUsage(AU);
120 virtual void releaseMemory() {
121 IntervalSSMap.clear();
122 Def2SpillMap.clear();
125 virtual const char *getPassName() const {
126 return "Pre-Register Allocaton Live Interval Splitting";
129 /// print - Implement the dump method.
130 virtual void print(raw_ostream &O, const Module* M = 0) const {
136 MachineBasicBlock::iterator
137 findNextEmptySlot(MachineBasicBlock*, MachineInstr*,
140 MachineBasicBlock::iterator
141 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
142 SmallPtrSet<MachineInstr*, 4>&, SlotIndex&);
144 MachineBasicBlock::iterator
145 findRestorePoint(MachineBasicBlock*, MachineInstr*, SlotIndex,
146 SmallPtrSet<MachineInstr*, 4>&, SlotIndex&);
148 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
150 bool IsAvailableInStack(MachineBasicBlock*, unsigned,
151 SlotIndex, SlotIndex,
152 SlotIndex&, int&) const;
154 void UpdateSpillSlotInterval(VNInfo*, SlotIndex, SlotIndex);
156 bool SplitRegLiveInterval(LiveInterval*);
158 bool SplitRegLiveIntervals(const TargetRegisterClass **,
159 SmallPtrSet<LiveInterval*, 8>&);
161 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
162 MachineBasicBlock* BarrierMBB);
163 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
165 MachineBasicBlock::iterator RestorePt,
166 SlotIndex RestoreIdx,
167 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
168 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
170 MachineInstr* Barrier,
171 MachineBasicBlock* MBB,
173 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
174 MachineInstr* FoldRestore(unsigned vreg,
175 const TargetRegisterClass* RC,
176 MachineInstr* Barrier,
177 MachineBasicBlock* MBB,
179 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
180 void RenumberValno(VNInfo* VN);
181 void ReconstructLiveInterval(LiveInterval* LI);
182 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
183 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
184 unsigned Reg, int FrameIndex, bool& TwoAddr);
185 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
186 MachineBasicBlock* MBB, LiveInterval* LI,
187 SmallPtrSet<MachineInstr*, 4>& Visited,
188 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
189 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
190 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
191 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
192 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
193 bool IsTopLevel, bool IsIntraBlock);
194 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
195 MachineBasicBlock* MBB, LiveInterval* LI,
196 SmallPtrSet<MachineInstr*, 4>& Visited,
197 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
198 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
199 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
200 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
201 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
202 bool IsTopLevel, bool IsIntraBlock);
204 } // end anonymous namespace
206 char PreAllocSplitting::ID = 0;
208 static RegisterPass<PreAllocSplitting>
209 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
211 const PassInfo *const llvm::PreAllocSplittingID = &X;
214 /// findNextEmptySlot - Find a gap after the given machine instruction in the
215 /// instruction index map. If there isn't one, return end().
216 MachineBasicBlock::iterator
217 PreAllocSplitting::findNextEmptySlot(MachineBasicBlock *MBB, MachineInstr *MI,
218 SlotIndex &SpotIndex) {
219 MachineBasicBlock::iterator MII = MI;
220 if (++MII != MBB->end()) {
222 LIs->findGapBeforeInstr(LIs->getInstructionIndex(MII));
223 if (Index != SlotIndex()) {
231 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
232 /// for spilling the current live interval. The index must be before any
233 /// defs and uses of the live interval register in the mbb. Return begin() if
235 MachineBasicBlock::iterator
236 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
238 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
239 SlotIndex &SpillIndex) {
240 MachineBasicBlock::iterator Pt = MBB->begin();
242 MachineBasicBlock::iterator MII = MI;
243 MachineBasicBlock::iterator EndPt = DefMI
244 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
246 while (MII != EndPt && !RefsInMBB.count(MII) &&
247 MII->getOpcode() != TRI->getCallFrameSetupOpcode())
249 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
251 while (MII != EndPt && !RefsInMBB.count(MII)) {
252 SlotIndex Index = LIs->getInstructionIndex(MII);
254 // We can't insert the spill between the barrier (a call), and its
255 // corresponding call frame setup.
256 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
257 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
264 } else if (LIs->hasGapBeforeInstr(Index)) {
266 SpillIndex = LIs->findGapBeforeInstr(Index, true);
269 if (RefsInMBB.count(MII))
279 /// findRestorePoint - Find a gap in the instruction index map that's suitable
280 /// for restoring the current live interval value. The index must be before any
281 /// uses of the live interval register in the mbb. Return end() if none is
283 MachineBasicBlock::iterator
284 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
286 SmallPtrSet<MachineInstr*, 4> &RefsInMBB,
287 SlotIndex &RestoreIndex) {
288 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
289 // begin index accordingly.
290 MachineBasicBlock::iterator Pt = MBB->end();
291 MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
293 // We start at the call, so walk forward until we find the call frame teardown
294 // since we can't insert restores before that. Bail if we encounter a use
296 MachineBasicBlock::iterator MII = MI;
297 if (MII == EndPt) return Pt;
299 while (MII != EndPt && !RefsInMBB.count(MII) &&
300 MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
302 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
305 // FIXME: Limit the number of instructions to examine to reduce
307 while (MII != EndPt) {
308 SlotIndex Index = LIs->getInstructionIndex(MII);
311 SlotIndex Gap = LIs->findGapBeforeInstr(Index);
313 // We can't insert a restore between the barrier (a call) and its
314 // corresponding call frame teardown.
315 if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
317 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
319 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
320 } else if (Gap != SlotIndex()) {
325 if (RefsInMBB.count(MII))
334 /// CreateSpillStackSlot - Create a stack slot for the live interval being
335 /// split. If the live interval was previously split, just reuse the same
337 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
338 const TargetRegisterClass *RC) {
340 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
341 if (I != IntervalSSMap.end()) {
344 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
345 IntervalSSMap[Reg] = SS;
348 // Create live interval for stack slot.
349 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
350 if (CurrSLI->hasAtLeastOneValue())
351 CurrSValNo = CurrSLI->getValNumInfo(0);
353 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
354 LSs->getVNInfoAllocator());
358 /// IsAvailableInStack - Return true if register is available in a split stack
359 /// slot at the specified index.
361 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
362 unsigned Reg, SlotIndex DefIndex,
363 SlotIndex RestoreIndex,
364 SlotIndex &SpillIndex,
369 DenseMap<unsigned, int>::const_iterator I = IntervalSSMap.find(Reg);
370 if (I == IntervalSSMap.end())
372 DenseMap<SlotIndex, SlotIndex>::const_iterator
373 II = Def2SpillMap.find(DefIndex);
374 if (II == Def2SpillMap.end())
377 // If last spill of def is in the same mbb as barrier mbb (where restore will
378 // be), make sure it's not below the intended restore index.
379 // FIXME: Undo the previous spill?
380 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
381 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
385 SpillIndex = II->second;
389 /// UpdateSpillSlotInterval - Given the specified val# of the register live
390 /// interval being split, and the spill and restore indicies, update the live
391 /// interval of the spill stack slot.
393 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, SlotIndex SpillIndex,
394 SlotIndex RestoreIndex) {
395 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
396 "Expect restore in the barrier mbb");
398 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
399 if (MBB == BarrierMBB) {
400 // Intra-block spill + restore. We are done.
401 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
402 CurrSLI->addRange(SLR);
406 SmallPtrSet<MachineBasicBlock*, 4> Processed;
407 SlotIndex EndIdx = LIs->getMBBEndIdx(MBB);
408 LiveRange SLR(SpillIndex, EndIdx.getNextSlot(), CurrSValNo);
409 CurrSLI->addRange(SLR);
410 Processed.insert(MBB);
412 // Start from the spill mbb, figure out the extend of the spill slot's
414 SmallVector<MachineBasicBlock*, 4> WorkList;
415 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
416 if (LR->end > EndIdx)
417 // If live range extend beyond end of mbb, add successors to work list.
418 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
419 SE = MBB->succ_end(); SI != SE; ++SI)
420 WorkList.push_back(*SI);
422 while (!WorkList.empty()) {
423 MachineBasicBlock *MBB = WorkList.back();
425 if (Processed.count(MBB))
427 SlotIndex Idx = LIs->getMBBStartIdx(MBB);
428 LR = CurrLI->getLiveRangeContaining(Idx);
429 if (LR && LR->valno == ValNo) {
430 EndIdx = LIs->getMBBEndIdx(MBB);
431 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
432 // Spill slot live interval stops at the restore.
433 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
434 CurrSLI->addRange(SLR);
435 } else if (LR->end > EndIdx) {
436 // Live range extends beyond end of mbb, process successors.
437 LiveRange SLR(Idx, EndIdx.getNextIndex(), CurrSValNo);
438 CurrSLI->addRange(SLR);
439 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
440 SE = MBB->succ_end(); SI != SE; ++SI)
441 WorkList.push_back(*SI);
443 LiveRange SLR(Idx, LR->end, CurrSValNo);
444 CurrSLI->addRange(SLR);
446 Processed.insert(MBB);
451 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
452 /// construction algorithm to compute the ranges and valnos for an interval.
454 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
455 MachineBasicBlock* MBB, LiveInterval* LI,
456 SmallPtrSet<MachineInstr*, 4>& Visited,
457 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
458 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
459 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
460 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
461 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
462 bool IsTopLevel, bool IsIntraBlock) {
463 // Return memoized result if it's available.
464 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
466 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
468 else if (!IsIntraBlock && LiveOut.count(MBB))
471 // Check if our block contains any uses or defs.
472 bool ContainsDefs = Defs.count(MBB);
473 bool ContainsUses = Uses.count(MBB);
477 // Enumerate the cases of use/def contaning blocks.
478 if (!ContainsDefs && !ContainsUses) {
479 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
480 NewVNs, LiveOut, Phis,
481 IsTopLevel, IsIntraBlock);
482 } else if (ContainsDefs && !ContainsUses) {
483 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
485 // Search for the def in this block. If we don't find it before the
486 // instruction we care about, go to the fallback case. Note that that
487 // should never happen: this cannot be intrablock, so use should
488 // always be an end() iterator.
489 assert(UseI == MBB->end() && "No use marked in intrablock");
491 MachineBasicBlock::iterator Walker = UseI;
493 while (Walker != MBB->begin()) {
494 if (BlockDefs.count(Walker))
499 // Once we've found it, extend its VNInfo to our instruction.
500 SlotIndex DefIndex = LIs->getInstructionIndex(Walker);
501 DefIndex = DefIndex.getDefIndex();
502 SlotIndex EndIndex = LIs->getMBBEndIdx(MBB);
504 RetVNI = NewVNs[Walker];
505 LI->addRange(LiveRange(DefIndex, EndIndex.getNextSlot(), RetVNI));
506 } else if (!ContainsDefs && ContainsUses) {
507 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
509 // Search for the use in this block that precedes the instruction we care
510 // about, going to the fallback case if we don't find it.
511 if (UseI == MBB->begin())
512 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
513 Uses, NewVNs, LiveOut, Phis,
514 IsTopLevel, IsIntraBlock);
516 MachineBasicBlock::iterator Walker = UseI;
519 while (Walker != MBB->begin()) {
520 if (BlockUses.count(Walker)) {
527 // Must check begin() too.
529 if (BlockUses.count(Walker))
532 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
533 Uses, NewVNs, LiveOut, Phis,
534 IsTopLevel, IsIntraBlock);
537 SlotIndex UseIndex = LIs->getInstructionIndex(Walker);
538 UseIndex = UseIndex.getUseIndex();
541 EndIndex = LIs->getInstructionIndex(UseI);
542 EndIndex = EndIndex.getUseIndex();
544 EndIndex = LIs->getMBBEndIdx(MBB);
546 // Now, recursively phi construct the VNInfo for the use we found,
547 // and then extend it to include the instruction we care about
548 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
549 NewVNs, LiveOut, Phis, false, true);
551 LI->addRange(LiveRange(UseIndex, EndIndex.getNextSlot(), RetVNI));
553 // FIXME: Need to set kills properly for inter-block stuff.
554 if (RetVNI->isKill(UseIndex)) RetVNI->removeKill(UseIndex);
556 RetVNI->addKill(EndIndex);
557 } else if (ContainsDefs && ContainsUses) {
558 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
559 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
561 // This case is basically a merging of the two preceding case, with the
562 // special note that checking for defs must take precedence over checking
563 // for uses, because of two-address instructions.
565 if (UseI == MBB->begin())
566 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
567 NewVNs, LiveOut, Phis,
568 IsTopLevel, IsIntraBlock);
570 MachineBasicBlock::iterator Walker = UseI;
572 bool foundDef = false;
573 bool foundUse = false;
574 while (Walker != MBB->begin()) {
575 if (BlockDefs.count(Walker)) {
578 } else if (BlockUses.count(Walker)) {
585 // Must check begin() too.
586 if (!foundDef && !foundUse) {
587 if (BlockDefs.count(Walker))
589 else if (BlockUses.count(Walker))
592 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
593 Uses, NewVNs, LiveOut, Phis,
594 IsTopLevel, IsIntraBlock);
597 SlotIndex StartIndex = LIs->getInstructionIndex(Walker);
598 StartIndex = foundDef ? StartIndex.getDefIndex() : StartIndex.getUseIndex();
601 EndIndex = LIs->getInstructionIndex(UseI);
602 EndIndex = EndIndex.getUseIndex();
604 EndIndex = LIs->getMBBEndIdx(MBB);
607 RetVNI = NewVNs[Walker];
609 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
610 NewVNs, LiveOut, Phis, false, true);
612 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
614 if (foundUse && RetVNI->isKill(StartIndex))
615 RetVNI->removeKill(StartIndex);
617 RetVNI->addKill(EndIndex);
621 // Memoize results so we don't have to recompute them.
622 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
624 if (!NewVNs.count(UseI))
625 NewVNs[UseI] = RetVNI;
626 Visited.insert(UseI);
632 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
635 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
636 MachineBasicBlock* MBB, LiveInterval* LI,
637 SmallPtrSet<MachineInstr*, 4>& Visited,
638 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
639 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
640 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
641 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
642 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
643 bool IsTopLevel, bool IsIntraBlock) {
644 // NOTE: Because this is the fallback case from other cases, we do NOT
645 // assume that we are not intrablock here.
646 if (Phis.count(MBB)) return Phis[MBB];
648 SlotIndex StartIndex = LIs->getMBBStartIdx(MBB);
649 VNInfo *RetVNI = Phis[MBB] =
650 LI->getNextValue(SlotIndex(), /*FIXME*/ 0, false,
651 LIs->getVNInfoAllocator());
653 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
655 // If there are no uses or defs between our starting point and the
656 // beginning of the block, then recursive perform phi construction
657 // on our predecessors.
658 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
659 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
660 PE = MBB->pred_end(); PI != PE; ++PI) {
661 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
662 Visited, Defs, Uses, NewVNs,
663 LiveOut, Phis, false, false);
665 IncomingVNs[*PI] = Incoming;
668 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill()) {
669 VNInfo* OldVN = RetVNI;
670 VNInfo* NewVN = IncomingVNs.begin()->second;
671 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
672 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
674 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
675 LOE = LiveOut.end(); LOI != LOE; ++LOI)
676 if (LOI->second == OldVN)
677 LOI->second = MergedVN;
678 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
679 NVE = NewVNs.end(); NVI != NVE; ++NVI)
680 if (NVI->second == OldVN)
681 NVI->second = MergedVN;
682 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
683 PE = Phis.end(); PI != PE; ++PI)
684 if (PI->second == OldVN)
685 PI->second = MergedVN;
688 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
689 // VNInfo to represent the joined value.
690 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
691 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
692 I->second->setHasPHIKill(true);
693 SlotIndex KillIndex = LIs->getMBBEndIdx(I->first);
694 if (!I->second->isKill(KillIndex))
695 I->second->addKill(KillIndex);
701 EndIndex = LIs->getInstructionIndex(UseI);
702 EndIndex = EndIndex.getUseIndex();
704 EndIndex = LIs->getMBBEndIdx(MBB);
705 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
707 RetVNI->addKill(EndIndex);
709 // Memoize results so we don't have to recompute them.
711 LiveOut[MBB] = RetVNI;
713 if (!NewVNs.count(UseI))
714 NewVNs[UseI] = RetVNI;
715 Visited.insert(UseI);
721 /// ReconstructLiveInterval - Recompute a live interval from scratch.
722 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
723 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
725 // Clear the old ranges and valnos;
728 // Cache the uses and defs of the register
729 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
732 // Keep track of the new VNs we're creating.
733 DenseMap<MachineInstr*, VNInfo*> NewVNs;
734 SmallPtrSet<VNInfo*, 2> PhiVNs;
736 // Cache defs, and create a new VNInfo for each def.
737 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
738 DE = MRI->def_end(); DI != DE; ++DI) {
739 Defs[(*DI).getParent()].insert(&*DI);
741 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
742 DefIdx = DefIdx.getDefIndex();
744 assert(DI->getOpcode() != TargetInstrInfo::PHI &&
745 "Following NewVN isPHIDef flag incorrect. Fix me!");
746 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, true, Alloc);
748 // If the def is a move, set the copy field.
749 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
750 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
751 if (DstReg == LI->reg)
752 NewVN->setCopy(&*DI);
754 NewVNs[&*DI] = NewVN;
757 // Cache uses as a separate pass from actually processing them.
758 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
759 UE = MRI->use_end(); UI != UE; ++UI)
760 Uses[(*UI).getParent()].insert(&*UI);
762 // Now, actually process every use and use a phi construction algorithm
763 // to walk from it to its reaching definitions, building VNInfos along
765 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
766 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
767 SmallPtrSet<MachineInstr*, 4> Visited;
768 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
769 UE = MRI->use_end(); UI != UE; ++UI) {
770 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
771 Uses, NewVNs, LiveOut, Phis, true, true);
774 // Add ranges for dead defs
775 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
776 DE = MRI->def_end(); DI != DE; ++DI) {
777 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
778 DefIdx = DefIdx.getDefIndex();
780 if (LI->liveAt(DefIdx)) continue;
782 VNInfo* DeadVN = NewVNs[&*DI];
783 LI->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), DeadVN));
784 DeadVN->addKill(DefIdx);
787 // Update kill markers.
788 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
791 for (unsigned i = 0, e = VNI->kills.size(); i != e; ++i) {
792 SlotIndex KillIdx = VNI->kills[i];
795 MachineInstr *KillMI = LIs->getInstructionFromIndex(KillIdx);
797 MachineOperand *KillMO = KillMI->findRegisterUseOperand(CurrLI->reg);
799 // It could be a dead def.
806 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
807 /// be allocated to a different register. This function creates a new vreg,
808 /// copies the valno and its live ranges over to the new vreg's interval,
809 /// removes them from the old interval, and rewrites all uses and defs of
810 /// the original reg to the new vreg within those ranges.
811 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
812 SmallVector<VNInfo*, 4> Stack;
813 SmallVector<VNInfo*, 4> VNsToCopy;
816 // Walk through and copy the valno we care about, and any other valnos
817 // that are two-address redefinitions of the one we care about. These
818 // will need to be rewritten as well. We also check for safety of the
819 // renumbering here, by making sure that none of the valno involved has
821 while (!Stack.empty()) {
822 VNInfo* OldVN = Stack.back();
825 // Bail out if we ever encounter a valno that has a PHI kill. We can't
827 if (OldVN->hasPHIKill()) return;
829 VNsToCopy.push_back(OldVN);
831 // Locate two-address redefinitions
832 for (VNInfo::KillSet::iterator KI = OldVN->kills.begin(),
833 KE = OldVN->kills.end(); KI != KE; ++KI) {
834 assert(!KI->isPHI() &&
835 "VN previously reported having no PHI kills.");
836 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
837 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
838 if (DefIdx == ~0U) continue;
839 if (MI->isRegTiedToUseOperand(DefIdx)) {
841 CurrLI->findDefinedVNInfoForRegInt(KI->getDefIndex());
842 if (NextVN == OldVN) continue;
843 Stack.push_back(NextVN);
848 // Create the new vreg
849 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
851 // Create the new live interval
852 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
854 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
855 VNsToCopy.end(); OI != OE; ++OI) {
858 // Copy the valno over
859 VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
860 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
862 // Remove the valno from the old interval
863 CurrLI->removeValNo(OldVN);
866 // Rewrite defs and uses. This is done in two stages to avoid invalidating
868 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
870 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
871 E = MRI->reg_end(); I != E; ++I) {
872 MachineOperand& MO = I.getOperand();
873 SlotIndex InstrIdx = LIs->getInstructionIndex(&*I);
875 if ((MO.isUse() && NewLI.liveAt(InstrIdx.getUseIndex())) ||
876 (MO.isDef() && NewLI.liveAt(InstrIdx.getDefIndex())))
877 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
880 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
881 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
882 MachineInstr* Inst = I->first;
883 unsigned OpIdx = I->second;
884 MachineOperand& MO = Inst->getOperand(OpIdx);
888 // Grow the VirtRegMap, since we've created a new vreg.
891 // The renumbered vreg shares a stack slot with the old register.
892 if (IntervalSSMap.count(CurrLI->reg))
893 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
898 bool PreAllocSplitting::Rematerialize(unsigned VReg, VNInfo* ValNo,
900 MachineBasicBlock::iterator RestorePt,
901 SlotIndex RestoreIdx,
902 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
903 MachineBasicBlock& MBB = *RestorePt->getParent();
905 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
907 if (!ValNo->isDefAccurate() || DefMI->getParent() == BarrierMBB)
908 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, KillIdx);
910 KillPt = findNextEmptySlot(DefMI->getParent(), DefMI, KillIdx);
912 if (KillPt == DefMI->getParent()->end())
915 TII->reMaterialize(MBB, RestorePt, VReg, 0, DefMI);
916 LIs->InsertMachineInstrInMaps(prior(RestorePt), RestoreIdx);
918 ReconstructLiveInterval(CurrLI);
919 SlotIndex RematIdx = LIs->getInstructionIndex(prior(RestorePt));
920 RematIdx = RematIdx.getDefIndex();
921 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RematIdx));
928 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
929 const TargetRegisterClass* RC,
931 MachineInstr* Barrier,
932 MachineBasicBlock* MBB,
934 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
935 MachineBasicBlock::iterator Pt = MBB->begin();
937 // Go top down if RefsInMBB is empty.
938 if (RefsInMBB.empty())
941 MachineBasicBlock::iterator FoldPt = Barrier;
942 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
943 !RefsInMBB.count(FoldPt))
946 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
950 SmallVector<unsigned, 1> Ops;
951 Ops.push_back(OpIdx);
953 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
956 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
957 if (I != IntervalSSMap.end()) {
960 SS = MFI->CreateStackObject(RC->getSize(), RC->getAlignment());
963 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
967 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
968 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
971 IntervalSSMap[vreg] = SS;
972 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
973 if (CurrSLI->hasAtLeastOneValue())
974 CurrSValNo = CurrSLI->getValNumInfo(0);
976 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
977 LSs->getVNInfoAllocator());
983 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
984 const TargetRegisterClass* RC,
985 MachineInstr* Barrier,
986 MachineBasicBlock* MBB,
988 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
989 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
992 // Go top down if RefsInMBB is empty.
993 if (RefsInMBB.empty())
996 // Can't fold a restore between a call stack setup and teardown.
997 MachineBasicBlock::iterator FoldPt = Barrier;
999 // Advance from barrier to call frame teardown.
1000 while (FoldPt != MBB->getFirstTerminator() &&
1001 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1002 if (RefsInMBB.count(FoldPt))
1008 if (FoldPt == MBB->getFirstTerminator())
1013 // Now find the restore point.
1014 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
1015 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
1016 while (FoldPt != MBB->getFirstTerminator() &&
1017 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
1018 if (RefsInMBB.count(FoldPt))
1024 if (FoldPt == MBB->getFirstTerminator())
1031 if (FoldPt == MBB->getFirstTerminator())
1034 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1038 SmallVector<unsigned, 1> Ops;
1039 Ops.push_back(OpIdx);
1041 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1044 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1048 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1049 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1056 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1057 /// so it would not cross the barrier that's being processed. Shrink wrap
1058 /// (minimize) the live interval to the last uses.
1059 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1060 DEBUG(errs() << "Pre-alloc splitting " << LI->reg << " for " << *Barrier
1065 // Find live range where current interval cross the barrier.
1066 LiveInterval::iterator LR =
1067 CurrLI->FindLiveRangeContaining(BarrierIdx.getUseIndex());
1068 VNInfo *ValNo = LR->valno;
1070 assert(!ValNo->isUnused() && "Val# is defined by a dead def?");
1072 MachineInstr *DefMI = ValNo->isDefAccurate()
1073 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1075 // If this would create a new join point, do not split.
1076 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent())) {
1077 DEBUG(errs() << "FAILED (would create a new join point).\n");
1081 // Find all references in the barrier mbb.
1082 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1083 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1084 E = MRI->reg_end(); I != E; ++I) {
1085 MachineInstr *RefMI = &*I;
1086 if (RefMI->getParent() == BarrierMBB)
1087 RefsInMBB.insert(RefMI);
1090 // Find a point to restore the value after the barrier.
1091 SlotIndex RestoreIndex;
1092 MachineBasicBlock::iterator RestorePt =
1093 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB, RestoreIndex);
1094 if (RestorePt == BarrierMBB->end()) {
1095 DEBUG(errs() << "FAILED (could not find a suitable restore point).\n");
1099 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1100 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt,
1101 RestoreIndex, RefsInMBB)) {
1102 DEBUG(errs() << "success (remat).\n");
1106 // Add a spill either before the barrier or after the definition.
1107 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1108 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1109 SlotIndex SpillIndex;
1110 MachineInstr *SpillMI = NULL;
1112 if (!ValNo->isDefAccurate()) {
1113 // If we don't know where the def is we must split just before the barrier.
1114 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1115 BarrierMBB, SS, RefsInMBB))) {
1116 SpillIndex = LIs->getInstructionIndex(SpillMI);
1118 MachineBasicBlock::iterator SpillPt =
1119 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB, SpillIndex);
1120 if (SpillPt == BarrierMBB->begin()) {
1121 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1122 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 DEBUG(errs() << "FAILED (def is dead).\n");
1137 return false; // Def is dead. Do nothing.
1140 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1141 BarrierMBB, SS, RefsInMBB))) {
1142 SpillIndex = LIs->getInstructionIndex(SpillMI);
1144 // Check if it's possible to insert a spill after the def MI.
1145 MachineBasicBlock::iterator SpillPt;
1146 if (DefMBB == BarrierMBB) {
1147 // Add spill after the def and the last use before the barrier.
1148 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1149 RefsInMBB, SpillIndex);
1150 if (SpillPt == DefMBB->begin()) {
1151 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1152 return false; // No gap to insert spill.
1155 SpillPt = findNextEmptySlot(DefMBB, DefMI, SpillIndex);
1156 if (SpillPt == DefMBB->end()) {
1157 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1158 return false; // No gap to insert spill.
1162 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1163 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg, false, SS, RC);
1164 SpillMI = prior(SpillPt);
1165 LIs->InsertMachineInstrInMaps(SpillMI, SpillIndex);
1169 // Remember def instruction index to spill index mapping.
1170 if (DefMI && SpillMI)
1171 Def2SpillMap[ValNo->def] = SpillIndex;
1174 bool FoldedRestore = false;
1175 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1176 BarrierMBB, SS, RefsInMBB)) {
1178 RestoreIndex = LIs->getInstructionIndex(RestorePt);
1179 FoldedRestore = true;
1181 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1182 MachineInstr *LoadMI = prior(RestorePt);
1183 LIs->InsertMachineInstrInMaps(LoadMI, RestoreIndex);
1186 // Update spill stack slot live interval.
1187 UpdateSpillSlotInterval(ValNo, SpillIndex.getUseIndex().getNextSlot(),
1188 RestoreIndex.getDefIndex());
1190 ReconstructLiveInterval(CurrLI);
1192 if (!FoldedRestore) {
1193 SlotIndex RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1194 RestoreIdx = RestoreIdx.getDefIndex();
1195 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RestoreIdx));
1199 DEBUG(errs() << "success.\n");
1203 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1204 /// barrier that's being processed.
1206 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1207 SmallPtrSet<LiveInterval*, 8>& Split) {
1208 // First find all the virtual registers whose live intervals are intercepted
1209 // by the current barrier.
1210 SmallVector<LiveInterval*, 8> Intervals;
1211 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1212 // FIXME: If it's not safe to move any instruction that defines the barrier
1213 // register class, then it means there are some special dependencies which
1214 // codegen is not modelling. Ignore these barriers for now.
1215 if (!TII->isSafeToMoveRegClassDefs(*RC))
1217 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1218 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1219 unsigned Reg = VRs[i];
1220 if (!LIs->hasInterval(Reg))
1222 LiveInterval *LI = &LIs->getInterval(Reg);
1223 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1224 // Virtual register live interval is intercepted by the barrier. We
1225 // should split and shrink wrap its interval if possible.
1226 Intervals.push_back(LI);
1230 // Process the affected live intervals.
1231 bool Change = false;
1232 while (!Intervals.empty()) {
1233 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1235 LiveInterval *LI = Intervals.back();
1236 Intervals.pop_back();
1237 bool result = SplitRegLiveInterval(LI);
1238 if (result) Split.insert(LI);
1245 unsigned PreAllocSplitting::getNumberOfNonSpills(
1246 SmallPtrSet<MachineInstr*, 4>& MIs,
1247 unsigned Reg, int FrameIndex,
1248 bool& FeedsTwoAddr) {
1249 unsigned NonSpills = 0;
1250 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1252 int StoreFrameIndex;
1253 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1254 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1257 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1258 if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1259 FeedsTwoAddr = true;
1265 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1266 /// split, and see if any of the spills are unnecessary. If so, remove them.
1267 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1268 bool changed = false;
1270 // Walk over all of the live intervals that were touched by the splitter,
1271 // and see if we can do any DCE and/or folding.
1272 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1273 LE = split.end(); LI != LE; ++LI) {
1274 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1276 // First, collect all the uses of the vreg, and sort them by their
1277 // reaching definition (VNInfo).
1278 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1279 UE = MRI->use_end(); UI != UE; ++UI) {
1280 SlotIndex index = LIs->getInstructionIndex(&*UI);
1281 index = index.getUseIndex();
1283 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1284 VNUseCount[LR->valno].insert(&*UI);
1287 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1288 // and/or fold them away.
1289 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1290 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1292 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1295 VNInfo* CurrVN = *VI;
1297 // We don't currently try to handle definitions with PHI kills, because
1298 // it would involve processing more than one VNInfo at once.
1299 if (CurrVN->hasPHIKill()) continue;
1301 // We also don't try to handle the results of PHI joins, since there's
1302 // no defining instruction to analyze.
1303 if (!CurrVN->isDefAccurate() || CurrVN->isUnused()) continue;
1305 // We're only interested in eliminating cruft introduced by the splitter,
1306 // is of the form load-use or load-use-store. First, check that the
1307 // definition is a load, and remember what stack slot we loaded it from.
1308 MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1310 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1312 // If the definition has no uses at all, just DCE it.
1313 if (VNUseCount[CurrVN].size() == 0) {
1314 LIs->RemoveMachineInstrFromMaps(DefMI);
1315 (*LI)->removeValNo(CurrVN);
1316 DefMI->eraseFromParent();
1317 VNUseCount.erase(CurrVN);
1323 // Second, get the number of non-store uses of the definition, as well as
1324 // a flag indicating whether it feeds into a later two-address definition.
1325 bool FeedsTwoAddr = false;
1326 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1327 (*LI)->reg, FrameIndex,
1330 // If there's one non-store use and it doesn't feed a two-addr, then
1331 // this is a load-use-store case that we can try to fold.
1332 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1333 // Start by finding the non-store use MachineInstr.
1334 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1335 int StoreFrameIndex;
1336 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1337 while (UI != VNUseCount[CurrVN].end() &&
1338 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1340 if (UI != VNUseCount[CurrVN].end())
1341 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1343 if (UI == VNUseCount[CurrVN].end()) continue;
1345 MachineInstr* use = *UI;
1347 // Attempt to fold it away!
1348 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1349 if (OpIdx == -1) continue;
1350 SmallVector<unsigned, 1> Ops;
1351 Ops.push_back(OpIdx);
1352 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1354 MachineInstr* NewMI =
1355 TII->foldMemoryOperand(*use->getParent()->getParent(),
1356 use, Ops, FrameIndex);
1358 if (!NewMI) continue;
1360 // Update relevant analyses.
1361 LIs->RemoveMachineInstrFromMaps(DefMI);
1362 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1363 (*LI)->removeValNo(CurrVN);
1365 DefMI->eraseFromParent();
1366 MachineBasicBlock* MBB = use->getParent();
1367 NewMI = MBB->insert(MBB->erase(use), NewMI);
1368 VNUseCount[CurrVN].erase(use);
1370 // Remove deleted instructions. Note that we need to remove them from
1371 // the VNInfo->use map as well, just to be safe.
1372 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1373 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1375 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1376 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1378 if (VNI->first != CurrVN)
1379 VNI->second.erase(*II);
1380 LIs->RemoveMachineInstrFromMaps(*II);
1381 (*II)->eraseFromParent();
1384 VNUseCount.erase(CurrVN);
1386 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1387 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1388 if (VI->second.erase(use))
1389 VI->second.insert(NewMI);
1396 // If there's more than one non-store instruction, we can't profitably
1397 // fold it, so bail.
1398 if (NonSpillCount) continue;
1400 // Otherwise, this is a load-store case, so DCE them.
1401 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1402 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1404 LIs->RemoveMachineInstrFromMaps(*UI);
1405 (*UI)->eraseFromParent();
1408 VNUseCount.erase(CurrVN);
1410 LIs->RemoveMachineInstrFromMaps(DefMI);
1411 (*LI)->removeValNo(CurrVN);
1412 DefMI->eraseFromParent();
1421 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1422 MachineBasicBlock* DefMBB,
1423 MachineBasicBlock* BarrierMBB) {
1424 if (DefMBB == BarrierMBB)
1427 if (LR->valno->hasPHIKill())
1430 SlotIndex MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1431 if (LR->end < MBBEnd)
1434 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1435 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1438 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1439 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1440 typedef std::pair<MachineBasicBlock*,
1441 MachineBasicBlock::succ_iterator> ItPair;
1442 SmallVector<ItPair, 4> Stack;
1443 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1445 while (!Stack.empty()) {
1446 ItPair P = Stack.back();
1449 MachineBasicBlock* PredMBB = P.first;
1450 MachineBasicBlock::succ_iterator S = P.second;
1452 if (S == PredMBB->succ_end())
1454 else if (Visited.count(*S)) {
1455 Stack.push_back(std::make_pair(PredMBB, ++S));
1458 Stack.push_back(std::make_pair(PredMBB, S+1));
1460 MachineBasicBlock* MBB = *S;
1461 Visited.insert(MBB);
1463 if (MBB == BarrierMBB)
1466 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1467 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1468 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1470 if (MDTN == DefMDTN)
1472 else if (MDTN == BarrierMDTN)
1474 MDTN = MDTN->getIDom();
1477 MBBEnd = LIs->getMBBEndIdx(MBB);
1478 if (LR->end > MBBEnd)
1479 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1486 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1488 TM = &MF.getTarget();
1489 TRI = TM->getRegisterInfo();
1490 TII = TM->getInstrInfo();
1491 MFI = MF.getFrameInfo();
1492 MRI = &MF.getRegInfo();
1493 SIs = &getAnalysis<SlotIndexes>();
1494 LIs = &getAnalysis<LiveIntervals>();
1495 LSs = &getAnalysis<LiveStacks>();
1496 VRM = &getAnalysis<VirtRegMap>();
1498 bool MadeChange = false;
1500 // Make sure blocks are numbered in order.
1501 MF.RenumberBlocks();
1503 MachineBasicBlock *Entry = MF.begin();
1504 SmallPtrSet<MachineBasicBlock*,16> Visited;
1506 SmallPtrSet<LiveInterval*, 8> Split;
1508 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1509 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1512 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1513 E = BarrierMBB->end(); I != E; ++I) {
1515 const TargetRegisterClass **BarrierRCs =
1516 Barrier->getDesc().getRegClassBarriers();
1519 BarrierIdx = LIs->getInstructionIndex(Barrier);
1520 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1524 MadeChange |= removeDeadSpills(Split);