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/CalcSpillWeights.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveStackAnalysis.h"
22 #include "llvm/CodeGen/MachineDominators.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineFunctionPass.h"
25 #include "llvm/CodeGen/MachineLoopInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/Passes.h"
28 #include "llvm/CodeGen/RegisterCoalescer.h"
29 #include "llvm/Target/TargetInstrInfo.h"
30 #include "llvm/Target/TargetMachine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Target/TargetRegisterInfo.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/ADT/DenseMap.h"
37 #include "llvm/ADT/DepthFirstIterator.h"
38 #include "llvm/ADT/SmallPtrSet.h"
39 #include "llvm/ADT/Statistic.h"
42 static cl::opt<int> PreSplitLimit("pre-split-limit", cl::init(-1), cl::Hidden);
43 static cl::opt<int> DeadSplitLimit("dead-split-limit", cl::init(-1),
45 static cl::opt<int> RestoreFoldLimit("restore-fold-limit", cl::init(-1),
48 STATISTIC(NumSplits, "Number of intervals split");
49 STATISTIC(NumRemats, "Number of intervals split by rematerialization");
50 STATISTIC(NumFolds, "Number of intervals split with spill folding");
51 STATISTIC(NumRestoreFolds, "Number of intervals split with restore folding");
52 STATISTIC(NumRenumbers, "Number of intervals renumbered into new registers");
53 STATISTIC(NumDeadSpills, "Number of dead spills removed");
56 class PreAllocSplitting : public MachineFunctionPass {
57 MachineFunction *CurrMF;
58 const TargetMachine *TM;
59 const TargetInstrInfo *TII;
60 const TargetRegisterInfo* TRI;
61 MachineFrameInfo *MFI;
62 MachineRegisterInfo *MRI;
68 // Barrier - Current barrier being processed.
69 MachineInstr *Barrier;
71 // BarrierMBB - Basic block where the barrier resides in.
72 MachineBasicBlock *BarrierMBB;
74 // Barrier - Current barrier index.
77 // CurrLI - Current live interval being split.
80 // CurrSLI - Current stack slot live interval.
81 LiveInterval *CurrSLI;
83 // CurrSValNo - Current val# for the stack slot live interval.
86 // IntervalSSMap - A map from live interval to spill slots.
87 DenseMap<unsigned, int> IntervalSSMap;
89 // Def2SpillMap - A map from a def instruction index to spill index.
90 DenseMap<SlotIndex, SlotIndex> Def2SpillMap;
95 : MachineFunctionPass(&ID) {}
97 virtual bool runOnMachineFunction(MachineFunction &MF);
99 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
100 AU.setPreservesCFG();
101 AU.addRequired<SlotIndexes>();
102 AU.addPreserved<SlotIndexes>();
103 AU.addRequired<LiveIntervals>();
104 AU.addPreserved<LiveIntervals>();
105 AU.addRequired<LiveStacks>();
106 AU.addPreserved<LiveStacks>();
107 AU.addPreserved<RegisterCoalescer>();
108 AU.addPreserved<CalculateSpillWeights>();
110 AU.addPreservedID(StrongPHIEliminationID);
112 AU.addPreservedID(PHIEliminationID);
113 AU.addRequired<MachineDominatorTree>();
114 AU.addRequired<MachineLoopInfo>();
115 AU.addRequired<VirtRegMap>();
116 AU.addPreserved<MachineDominatorTree>();
117 AU.addPreserved<MachineLoopInfo>();
118 AU.addPreserved<VirtRegMap>();
119 MachineFunctionPass::getAnalysisUsage(AU);
122 virtual void releaseMemory() {
123 IntervalSSMap.clear();
124 Def2SpillMap.clear();
127 virtual const char *getPassName() const {
128 return "Pre-Register Allocaton Live Interval Splitting";
131 /// print - Implement the dump method.
132 virtual void print(raw_ostream &O, const Module* M = 0) const {
139 MachineBasicBlock::iterator
140 findSpillPoint(MachineBasicBlock*, MachineInstr*, MachineInstr*,
141 SmallPtrSet<MachineInstr*, 4>&);
143 MachineBasicBlock::iterator
144 findRestorePoint(MachineBasicBlock*, MachineInstr*, SlotIndex,
145 SmallPtrSet<MachineInstr*, 4>&);
147 int CreateSpillStackSlot(unsigned, const TargetRegisterClass *);
149 bool IsAvailableInStack(MachineBasicBlock*, unsigned,
150 SlotIndex, SlotIndex,
151 SlotIndex&, int&) const;
153 void UpdateSpillSlotInterval(VNInfo*, SlotIndex, SlotIndex);
155 bool SplitRegLiveInterval(LiveInterval*);
157 bool SplitRegLiveIntervals(const TargetRegisterClass **,
158 SmallPtrSet<LiveInterval*, 8>&);
160 bool createsNewJoin(LiveRange* LR, MachineBasicBlock* DefMBB,
161 MachineBasicBlock* BarrierMBB);
162 bool Rematerialize(unsigned vreg, VNInfo* ValNo,
164 MachineBasicBlock::iterator RestorePt,
165 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
166 MachineInstr* FoldSpill(unsigned vreg, const TargetRegisterClass* RC,
168 MachineInstr* Barrier,
169 MachineBasicBlock* MBB,
171 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
172 MachineInstr* FoldRestore(unsigned vreg,
173 const TargetRegisterClass* RC,
174 MachineInstr* Barrier,
175 MachineBasicBlock* MBB,
177 SmallPtrSet<MachineInstr*, 4>& RefsInMBB);
178 void RenumberValno(VNInfo* VN);
179 void ReconstructLiveInterval(LiveInterval* LI);
180 bool removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split);
181 unsigned getNumberOfNonSpills(SmallPtrSet<MachineInstr*, 4>& MIs,
182 unsigned Reg, int FrameIndex, bool& TwoAddr);
183 VNInfo* PerformPHIConstruction(MachineBasicBlock::iterator Use,
184 MachineBasicBlock* MBB, LiveInterval* LI,
185 SmallPtrSet<MachineInstr*, 4>& Visited,
186 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
187 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
188 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
189 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
190 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
191 bool IsTopLevel, bool IsIntraBlock);
192 VNInfo* PerformPHIConstructionFallBack(MachineBasicBlock::iterator Use,
193 MachineBasicBlock* MBB, LiveInterval* LI,
194 SmallPtrSet<MachineInstr*, 4>& Visited,
195 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
196 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
197 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
198 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
199 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
200 bool IsTopLevel, bool IsIntraBlock);
202 } // end anonymous namespace
204 char PreAllocSplitting::ID = 0;
206 static RegisterPass<PreAllocSplitting>
207 X("pre-alloc-splitting", "Pre-Register Allocation Live Interval Splitting");
209 const PassInfo *const llvm::PreAllocSplittingID = &X;
211 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
212 /// for spilling the current live interval. The index must be before any
213 /// defs and uses of the live interval register in the mbb. Return begin() if
215 MachineBasicBlock::iterator
216 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
218 SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
219 MachineBasicBlock::iterator Pt = MBB->begin();
221 MachineBasicBlock::iterator MII = MI;
222 MachineBasicBlock::iterator EndPt = DefMI
223 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
225 while (MII != EndPt && !RefsInMBB.count(MII) &&
226 MII->getOpcode() != TRI->getCallFrameSetupOpcode())
228 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
230 while (MII != EndPt && !RefsInMBB.count(MII)) {
231 // We can't insert the spill between the barrier (a call), and its
232 // corresponding call frame setup.
233 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
234 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
245 if (RefsInMBB.count(MII))
255 /// findRestorePoint - Find a gap in the instruction index map that's suitable
256 /// for restoring the current live interval value. The index must be before any
257 /// uses of the live interval register in the mbb. Return end() if none is
259 MachineBasicBlock::iterator
260 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
262 SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
263 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
264 // begin index accordingly.
265 MachineBasicBlock::iterator Pt = MBB->end();
266 MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
268 // We start at the call, so walk forward until we find the call frame teardown
269 // since we can't insert restores before that. Bail if we encounter a use
271 MachineBasicBlock::iterator MII = MI;
272 if (MII == EndPt) return Pt;
274 while (MII != EndPt && !RefsInMBB.count(MII) &&
275 MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
277 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
280 // FIXME: Limit the number of instructions to examine to reduce
282 while (MII != EndPt) {
283 SlotIndex Index = LIs->getInstructionIndex(MII);
287 // We can't insert a restore between the barrier (a call) and its
288 // corresponding call frame teardown.
289 if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
291 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
293 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
298 if (RefsInMBB.count(MII))
307 /// CreateSpillStackSlot - Create a stack slot for the live interval being
308 /// split. If the live interval was previously split, just reuse the same
310 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
311 const TargetRegisterClass *RC) {
313 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
314 if (I != IntervalSSMap.end()) {
317 SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
318 IntervalSSMap[Reg] = SS;
321 // Create live interval for stack slot.
322 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
323 if (CurrSLI->hasAtLeastOneValue())
324 CurrSValNo = CurrSLI->getValNumInfo(0);
326 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
327 LSs->getVNInfoAllocator());
331 /// IsAvailableInStack - Return true if register is available in a split stack
332 /// slot at the specified index.
334 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
335 unsigned Reg, SlotIndex DefIndex,
336 SlotIndex RestoreIndex,
337 SlotIndex &SpillIndex,
342 DenseMap<unsigned, int>::const_iterator I = IntervalSSMap.find(Reg);
343 if (I == IntervalSSMap.end())
345 DenseMap<SlotIndex, SlotIndex>::const_iterator
346 II = Def2SpillMap.find(DefIndex);
347 if (II == Def2SpillMap.end())
350 // If last spill of def is in the same mbb as barrier mbb (where restore will
351 // be), make sure it's not below the intended restore index.
352 // FIXME: Undo the previous spill?
353 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
354 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
358 SpillIndex = II->second;
362 /// UpdateSpillSlotInterval - Given the specified val# of the register live
363 /// interval being split, and the spill and restore indicies, update the live
364 /// interval of the spill stack slot.
366 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, SlotIndex SpillIndex,
367 SlotIndex RestoreIndex) {
368 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
369 "Expect restore in the barrier mbb");
371 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
372 if (MBB == BarrierMBB) {
373 // Intra-block spill + restore. We are done.
374 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
375 CurrSLI->addRange(SLR);
379 SmallPtrSet<MachineBasicBlock*, 4> Processed;
380 SlotIndex EndIdx = LIs->getMBBEndIdx(MBB);
381 LiveRange SLR(SpillIndex, EndIdx.getNextSlot(), CurrSValNo);
382 CurrSLI->addRange(SLR);
383 Processed.insert(MBB);
385 // Start from the spill mbb, figure out the extend of the spill slot's
387 SmallVector<MachineBasicBlock*, 4> WorkList;
388 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
389 if (LR->end > EndIdx)
390 // If live range extend beyond end of mbb, add successors to work list.
391 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
392 SE = MBB->succ_end(); SI != SE; ++SI)
393 WorkList.push_back(*SI);
395 while (!WorkList.empty()) {
396 MachineBasicBlock *MBB = WorkList.back();
398 if (Processed.count(MBB))
400 SlotIndex Idx = LIs->getMBBStartIdx(MBB);
401 LR = CurrLI->getLiveRangeContaining(Idx);
402 if (LR && LR->valno == ValNo) {
403 EndIdx = LIs->getMBBEndIdx(MBB);
404 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
405 // Spill slot live interval stops at the restore.
406 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
407 CurrSLI->addRange(SLR);
408 } else if (LR->end > EndIdx) {
409 // Live range extends beyond end of mbb, process successors.
410 LiveRange SLR(Idx, EndIdx.getNextIndex(), CurrSValNo);
411 CurrSLI->addRange(SLR);
412 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
413 SE = MBB->succ_end(); SI != SE; ++SI)
414 WorkList.push_back(*SI);
416 LiveRange SLR(Idx, LR->end, CurrSValNo);
417 CurrSLI->addRange(SLR);
419 Processed.insert(MBB);
424 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
425 /// construction algorithm to compute the ranges and valnos for an interval.
427 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
428 MachineBasicBlock* MBB, LiveInterval* LI,
429 SmallPtrSet<MachineInstr*, 4>& Visited,
430 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
431 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
432 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
433 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
434 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
435 bool IsTopLevel, bool IsIntraBlock) {
436 // Return memoized result if it's available.
437 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
439 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
441 else if (!IsIntraBlock && LiveOut.count(MBB))
444 // Check if our block contains any uses or defs.
445 bool ContainsDefs = Defs.count(MBB);
446 bool ContainsUses = Uses.count(MBB);
450 // Enumerate the cases of use/def contaning blocks.
451 if (!ContainsDefs && !ContainsUses) {
452 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
453 NewVNs, LiveOut, Phis,
454 IsTopLevel, IsIntraBlock);
455 } else if (ContainsDefs && !ContainsUses) {
456 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
458 // Search for the def in this block. If we don't find it before the
459 // instruction we care about, go to the fallback case. Note that that
460 // should never happen: this cannot be intrablock, so use should
461 // always be an end() iterator.
462 assert(UseI == MBB->end() && "No use marked in intrablock");
464 MachineBasicBlock::iterator Walker = UseI;
466 while (Walker != MBB->begin()) {
467 if (BlockDefs.count(Walker))
472 // Once we've found it, extend its VNInfo to our instruction.
473 SlotIndex DefIndex = LIs->getInstructionIndex(Walker);
474 DefIndex = DefIndex.getDefIndex();
475 SlotIndex EndIndex = LIs->getMBBEndIdx(MBB);
477 RetVNI = NewVNs[Walker];
478 LI->addRange(LiveRange(DefIndex, EndIndex.getNextSlot(), RetVNI));
479 } else if (!ContainsDefs && ContainsUses) {
480 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
482 // Search for the use in this block that precedes the instruction we care
483 // about, going to the fallback case if we don't find it.
484 if (UseI == MBB->begin())
485 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
486 Uses, NewVNs, LiveOut, Phis,
487 IsTopLevel, IsIntraBlock);
489 MachineBasicBlock::iterator Walker = UseI;
492 while (Walker != MBB->begin()) {
493 if (BlockUses.count(Walker)) {
500 // Must check begin() too.
502 if (BlockUses.count(Walker))
505 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
506 Uses, NewVNs, LiveOut, Phis,
507 IsTopLevel, IsIntraBlock);
510 SlotIndex UseIndex = LIs->getInstructionIndex(Walker);
511 UseIndex = UseIndex.getUseIndex();
514 EndIndex = LIs->getInstructionIndex(UseI);
515 EndIndex = EndIndex.getUseIndex();
517 EndIndex = LIs->getMBBEndIdx(MBB);
519 // Now, recursively phi construct the VNInfo for the use we found,
520 // and then extend it to include the instruction we care about
521 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
522 NewVNs, LiveOut, Phis, false, true);
524 LI->addRange(LiveRange(UseIndex, EndIndex.getNextSlot(), RetVNI));
526 // FIXME: Need to set kills properly for inter-block stuff.
527 if (RetVNI->isKill(UseIndex)) RetVNI->removeKill(UseIndex);
529 RetVNI->addKill(EndIndex);
530 } else if (ContainsDefs && ContainsUses) {
531 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
532 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
534 // This case is basically a merging of the two preceding case, with the
535 // special note that checking for defs must take precedence over checking
536 // for uses, because of two-address instructions.
538 if (UseI == MBB->begin())
539 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
540 NewVNs, LiveOut, Phis,
541 IsTopLevel, IsIntraBlock);
543 MachineBasicBlock::iterator Walker = UseI;
545 bool foundDef = false;
546 bool foundUse = false;
547 while (Walker != MBB->begin()) {
548 if (BlockDefs.count(Walker)) {
551 } else if (BlockUses.count(Walker)) {
558 // Must check begin() too.
559 if (!foundDef && !foundUse) {
560 if (BlockDefs.count(Walker))
562 else if (BlockUses.count(Walker))
565 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
566 Uses, NewVNs, LiveOut, Phis,
567 IsTopLevel, IsIntraBlock);
570 SlotIndex StartIndex = LIs->getInstructionIndex(Walker);
571 StartIndex = foundDef ? StartIndex.getDefIndex() : StartIndex.getUseIndex();
574 EndIndex = LIs->getInstructionIndex(UseI);
575 EndIndex = EndIndex.getUseIndex();
577 EndIndex = LIs->getMBBEndIdx(MBB);
580 RetVNI = NewVNs[Walker];
582 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
583 NewVNs, LiveOut, Phis, false, true);
585 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
587 if (foundUse && RetVNI->isKill(StartIndex))
588 RetVNI->removeKill(StartIndex);
590 RetVNI->addKill(EndIndex);
594 // Memoize results so we don't have to recompute them.
595 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
597 if (!NewVNs.count(UseI))
598 NewVNs[UseI] = RetVNI;
599 Visited.insert(UseI);
605 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
608 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
609 MachineBasicBlock* MBB, LiveInterval* LI,
610 SmallPtrSet<MachineInstr*, 4>& Visited,
611 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
612 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
613 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
614 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
615 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
616 bool IsTopLevel, bool IsIntraBlock) {
617 // NOTE: Because this is the fallback case from other cases, we do NOT
618 // assume that we are not intrablock here.
619 if (Phis.count(MBB)) return Phis[MBB];
621 SlotIndex StartIndex = LIs->getMBBStartIdx(MBB);
622 VNInfo *RetVNI = Phis[MBB] =
623 LI->getNextValue(SlotIndex(), /*FIXME*/ 0, false,
624 LIs->getVNInfoAllocator());
626 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
628 // If there are no uses or defs between our starting point and the
629 // beginning of the block, then recursive perform phi construction
630 // on our predecessors.
631 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
632 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
633 PE = MBB->pred_end(); PI != PE; ++PI) {
634 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
635 Visited, Defs, Uses, NewVNs,
636 LiveOut, Phis, false, false);
638 IncomingVNs[*PI] = Incoming;
641 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill()) {
642 VNInfo* OldVN = RetVNI;
643 VNInfo* NewVN = IncomingVNs.begin()->second;
644 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
645 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
647 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
648 LOE = LiveOut.end(); LOI != LOE; ++LOI)
649 if (LOI->second == OldVN)
650 LOI->second = MergedVN;
651 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
652 NVE = NewVNs.end(); NVI != NVE; ++NVI)
653 if (NVI->second == OldVN)
654 NVI->second = MergedVN;
655 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
656 PE = Phis.end(); PI != PE; ++PI)
657 if (PI->second == OldVN)
658 PI->second = MergedVN;
661 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
662 // VNInfo to represent the joined value.
663 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
664 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
665 I->second->setHasPHIKill(true);
666 SlotIndex KillIndex = LIs->getMBBEndIdx(I->first);
667 if (!I->second->isKill(KillIndex))
668 I->second->addKill(KillIndex);
674 EndIndex = LIs->getInstructionIndex(UseI);
675 EndIndex = EndIndex.getUseIndex();
677 EndIndex = LIs->getMBBEndIdx(MBB);
678 LI->addRange(LiveRange(StartIndex, EndIndex.getNextSlot(), RetVNI));
680 RetVNI->addKill(EndIndex);
682 // Memoize results so we don't have to recompute them.
684 LiveOut[MBB] = RetVNI;
686 if (!NewVNs.count(UseI))
687 NewVNs[UseI] = RetVNI;
688 Visited.insert(UseI);
694 /// ReconstructLiveInterval - Recompute a live interval from scratch.
695 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
696 BumpPtrAllocator& Alloc = LIs->getVNInfoAllocator();
698 // Clear the old ranges and valnos;
701 // Cache the uses and defs of the register
702 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
705 // Keep track of the new VNs we're creating.
706 DenseMap<MachineInstr*, VNInfo*> NewVNs;
707 SmallPtrSet<VNInfo*, 2> PhiVNs;
709 // Cache defs, and create a new VNInfo for each def.
710 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
711 DE = MRI->def_end(); DI != DE; ++DI) {
712 Defs[(*DI).getParent()].insert(&*DI);
714 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
715 DefIdx = DefIdx.getDefIndex();
717 assert(DI->getOpcode() != TargetInstrInfo::PHI &&
718 "PHI instr in code during pre-alloc splitting.");
719 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, true, Alloc);
721 // If the def is a move, set the copy field.
722 unsigned SrcReg, DstReg, SrcSubIdx, DstSubIdx;
723 if (TII->isMoveInstr(*DI, SrcReg, DstReg, SrcSubIdx, DstSubIdx))
724 if (DstReg == LI->reg)
725 NewVN->setCopy(&*DI);
727 NewVNs[&*DI] = NewVN;
730 // Cache uses as a separate pass from actually processing them.
731 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
732 UE = MRI->use_end(); UI != UE; ++UI)
733 Uses[(*UI).getParent()].insert(&*UI);
735 // Now, actually process every use and use a phi construction algorithm
736 // to walk from it to its reaching definitions, building VNInfos along
738 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
739 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
740 SmallPtrSet<MachineInstr*, 4> Visited;
741 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
742 UE = MRI->use_end(); UI != UE; ++UI) {
743 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
744 Uses, NewVNs, LiveOut, Phis, true, true);
747 // Add ranges for dead defs
748 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
749 DE = MRI->def_end(); DI != DE; ++DI) {
750 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
751 DefIdx = DefIdx.getDefIndex();
753 if (LI->liveAt(DefIdx)) continue;
755 VNInfo* DeadVN = NewVNs[&*DI];
756 LI->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), DeadVN));
757 DeadVN->addKill(DefIdx);
760 // Update kill markers.
761 for (LiveInterval::vni_iterator VI = LI->vni_begin(), VE = LI->vni_end();
764 for (unsigned i = 0, e = VNI->kills.size(); i != e; ++i) {
765 SlotIndex KillIdx = VNI->kills[i];
768 MachineInstr *KillMI = LIs->getInstructionFromIndex(KillIdx);
770 MachineOperand *KillMO = KillMI->findRegisterUseOperand(CurrLI->reg);
772 // It could be a dead def.
779 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
780 /// be allocated to a different register. This function creates a new vreg,
781 /// copies the valno and its live ranges over to the new vreg's interval,
782 /// removes them from the old interval, and rewrites all uses and defs of
783 /// the original reg to the new vreg within those ranges.
784 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
785 SmallVector<VNInfo*, 4> Stack;
786 SmallVector<VNInfo*, 4> VNsToCopy;
789 // Walk through and copy the valno we care about, and any other valnos
790 // that are two-address redefinitions of the one we care about. These
791 // will need to be rewritten as well. We also check for safety of the
792 // renumbering here, by making sure that none of the valno involved has
794 while (!Stack.empty()) {
795 VNInfo* OldVN = Stack.back();
798 // Bail out if we ever encounter a valno that has a PHI kill. We can't
800 if (OldVN->hasPHIKill()) return;
802 VNsToCopy.push_back(OldVN);
804 // Locate two-address redefinitions
805 for (VNInfo::KillSet::iterator KI = OldVN->kills.begin(),
806 KE = OldVN->kills.end(); KI != KE; ++KI) {
807 assert(!KI->isPHI() &&
808 "VN previously reported having no PHI kills.");
809 MachineInstr* MI = LIs->getInstructionFromIndex(*KI);
810 unsigned DefIdx = MI->findRegisterDefOperandIdx(CurrLI->reg);
811 if (DefIdx == ~0U) continue;
812 if (MI->isRegTiedToUseOperand(DefIdx)) {
814 CurrLI->findDefinedVNInfoForRegInt(KI->getDefIndex());
815 if (NextVN == OldVN) continue;
816 Stack.push_back(NextVN);
821 // Create the new vreg
822 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
824 // Create the new live interval
825 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
827 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
828 VNsToCopy.end(); OI != OE; ++OI) {
831 // Copy the valno over
832 VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
833 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
835 // Remove the valno from the old interval
836 CurrLI->removeValNo(OldVN);
839 // Rewrite defs and uses. This is done in two stages to avoid invalidating
841 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
843 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
844 E = MRI->reg_end(); I != E; ++I) {
845 MachineOperand& MO = I.getOperand();
846 SlotIndex InstrIdx = LIs->getInstructionIndex(&*I);
848 if ((MO.isUse() && NewLI.liveAt(InstrIdx.getUseIndex())) ||
849 (MO.isDef() && NewLI.liveAt(InstrIdx.getDefIndex())))
850 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
853 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
854 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
855 MachineInstr* Inst = I->first;
856 unsigned OpIdx = I->second;
857 MachineOperand& MO = Inst->getOperand(OpIdx);
861 // Grow the VirtRegMap, since we've created a new vreg.
864 // The renumbered vreg shares a stack slot with the old register.
865 if (IntervalSSMap.count(CurrLI->reg))
866 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
871 bool PreAllocSplitting::Rematerialize(unsigned VReg, VNInfo* ValNo,
873 MachineBasicBlock::iterator RestorePt,
874 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
875 MachineBasicBlock& MBB = *RestorePt->getParent();
877 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
878 if (!ValNo->isDefAccurate() || DefMI->getParent() == BarrierMBB)
879 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
881 KillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
883 if (KillPt == DefMI->getParent()->end())
886 TII->reMaterialize(MBB, RestorePt, VReg, 0, DefMI, TRI);
887 SlotIndex RematIdx = LIs->InsertMachineInstrInMaps(prior(RestorePt));
889 ReconstructLiveInterval(CurrLI);
890 RematIdx = RematIdx.getDefIndex();
891 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RematIdx));
898 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
899 const TargetRegisterClass* RC,
901 MachineInstr* Barrier,
902 MachineBasicBlock* MBB,
904 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
905 MachineBasicBlock::iterator Pt = MBB->begin();
907 // Go top down if RefsInMBB is empty.
908 if (RefsInMBB.empty())
911 MachineBasicBlock::iterator FoldPt = Barrier;
912 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
913 !RefsInMBB.count(FoldPt))
916 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg, false);
920 SmallVector<unsigned, 1> Ops;
921 Ops.push_back(OpIdx);
923 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
926 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
927 if (I != IntervalSSMap.end()) {
930 SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
933 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
937 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
938 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
941 IntervalSSMap[vreg] = SS;
942 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
943 if (CurrSLI->hasAtLeastOneValue())
944 CurrSValNo = CurrSLI->getValNumInfo(0);
946 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0, false,
947 LSs->getVNInfoAllocator());
953 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
954 const TargetRegisterClass* RC,
955 MachineInstr* Barrier,
956 MachineBasicBlock* MBB,
958 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
959 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
962 // Go top down if RefsInMBB is empty.
963 if (RefsInMBB.empty())
966 // Can't fold a restore between a call stack setup and teardown.
967 MachineBasicBlock::iterator FoldPt = Barrier;
969 // Advance from barrier to call frame teardown.
970 while (FoldPt != MBB->getFirstTerminator() &&
971 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
972 if (RefsInMBB.count(FoldPt))
978 if (FoldPt == MBB->getFirstTerminator())
983 // Now find the restore point.
984 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
985 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
986 while (FoldPt != MBB->getFirstTerminator() &&
987 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
988 if (RefsInMBB.count(FoldPt))
994 if (FoldPt == MBB->getFirstTerminator())
1001 if (FoldPt == MBB->getFirstTerminator())
1004 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
1008 SmallVector<unsigned, 1> Ops;
1009 Ops.push_back(OpIdx);
1011 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
1014 MachineInstr* FMI = TII->foldMemoryOperand(*MBB->getParent(),
1018 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
1019 FMI = MBB->insert(MBB->erase(FoldPt), FMI);
1026 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
1027 /// so it would not cross the barrier that's being processed. Shrink wrap
1028 /// (minimize) the live interval to the last uses.
1029 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
1030 DEBUG(errs() << "Pre-alloc splitting " << LI->reg << " for " << *Barrier
1035 // Find live range where current interval cross the barrier.
1036 LiveInterval::iterator LR =
1037 CurrLI->FindLiveRangeContaining(BarrierIdx.getUseIndex());
1038 VNInfo *ValNo = LR->valno;
1040 assert(!ValNo->isUnused() && "Val# is defined by a dead def?");
1042 MachineInstr *DefMI = ValNo->isDefAccurate()
1043 ? LIs->getInstructionFromIndex(ValNo->def) : NULL;
1045 // If this would create a new join point, do not split.
1046 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent())) {
1047 DEBUG(errs() << "FAILED (would create a new join point).\n");
1051 // Find all references in the barrier mbb.
1052 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
1053 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
1054 E = MRI->reg_end(); I != E; ++I) {
1055 MachineInstr *RefMI = &*I;
1056 if (RefMI->getParent() == BarrierMBB)
1057 RefsInMBB.insert(RefMI);
1060 // Find a point to restore the value after the barrier.
1061 MachineBasicBlock::iterator RestorePt =
1062 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB);
1063 if (RestorePt == BarrierMBB->end()) {
1064 DEBUG(errs() << "FAILED (could not find a suitable restore point).\n");
1068 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1069 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt, RefsInMBB)) {
1070 DEBUG(errs() << "success (remat).\n");
1074 // Add a spill either before the barrier or after the definition.
1075 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1076 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1077 SlotIndex SpillIndex;
1078 MachineInstr *SpillMI = NULL;
1080 if (!ValNo->isDefAccurate()) {
1081 // If we don't know where the def is we must split just before the barrier.
1082 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1083 BarrierMBB, SS, RefsInMBB))) {
1084 SpillIndex = LIs->getInstructionIndex(SpillMI);
1086 MachineBasicBlock::iterator SpillPt =
1087 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
1088 if (SpillPt == BarrierMBB->begin()) {
1089 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1090 return false; // No gap to insert spill.
1094 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1095 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC);
1096 SpillMI = prior(SpillPt);
1097 SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1099 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1100 LIs->getZeroIndex(), SpillIndex, SS)) {
1101 // If it's already split, just restore the value. There is no need to spill
1104 DEBUG(errs() << "FAILED (def is dead).\n");
1105 return false; // Def is dead. Do nothing.
1108 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1109 BarrierMBB, SS, RefsInMBB))) {
1110 SpillIndex = LIs->getInstructionIndex(SpillMI);
1112 // Check if it's possible to insert a spill after the def MI.
1113 MachineBasicBlock::iterator SpillPt;
1114 if (DefMBB == BarrierMBB) {
1115 // Add spill after the def and the last use before the barrier.
1116 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1118 if (SpillPt == DefMBB->begin()) {
1119 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1120 return false; // No gap to insert spill.
1123 SpillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
1124 if (SpillPt == DefMBB->end()) {
1125 DEBUG(errs() << "FAILED (could not find a suitable spill point).\n");
1126 return false; // No gap to insert spill.
1130 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1131 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg, false, SS, RC);
1132 SpillMI = prior(SpillPt);
1133 SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1137 // Remember def instruction index to spill index mapping.
1138 if (DefMI && SpillMI)
1139 Def2SpillMap[ValNo->def] = SpillIndex;
1142 bool FoldedRestore = false;
1143 SlotIndex RestoreIndex;
1144 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1145 BarrierMBB, SS, RefsInMBB)) {
1147 RestoreIndex = LIs->getInstructionIndex(RestorePt);
1148 FoldedRestore = true;
1150 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC);
1151 MachineInstr *LoadMI = prior(RestorePt);
1152 RestoreIndex = LIs->InsertMachineInstrInMaps(LoadMI);
1155 // Update spill stack slot live interval.
1156 UpdateSpillSlotInterval(ValNo, SpillIndex.getUseIndex().getNextSlot(),
1157 RestoreIndex.getDefIndex());
1159 ReconstructLiveInterval(CurrLI);
1161 if (!FoldedRestore) {
1162 SlotIndex RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1163 RestoreIdx = RestoreIdx.getDefIndex();
1164 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RestoreIdx));
1168 DEBUG(errs() << "success.\n");
1172 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1173 /// barrier that's being processed.
1175 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1176 SmallPtrSet<LiveInterval*, 8>& Split) {
1177 // First find all the virtual registers whose live intervals are intercepted
1178 // by the current barrier.
1179 SmallVector<LiveInterval*, 8> Intervals;
1180 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1181 // FIXME: If it's not safe to move any instruction that defines the barrier
1182 // register class, then it means there are some special dependencies which
1183 // codegen is not modelling. Ignore these barriers for now.
1184 if (!TII->isSafeToMoveRegClassDefs(*RC))
1186 std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1187 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1188 unsigned Reg = VRs[i];
1189 if (!LIs->hasInterval(Reg))
1191 LiveInterval *LI = &LIs->getInterval(Reg);
1192 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1193 // Virtual register live interval is intercepted by the barrier. We
1194 // should split and shrink wrap its interval if possible.
1195 Intervals.push_back(LI);
1199 // Process the affected live intervals.
1200 bool Change = false;
1201 while (!Intervals.empty()) {
1202 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1204 LiveInterval *LI = Intervals.back();
1205 Intervals.pop_back();
1206 bool result = SplitRegLiveInterval(LI);
1207 if (result) Split.insert(LI);
1214 unsigned PreAllocSplitting::getNumberOfNonSpills(
1215 SmallPtrSet<MachineInstr*, 4>& MIs,
1216 unsigned Reg, int FrameIndex,
1217 bool& FeedsTwoAddr) {
1218 unsigned NonSpills = 0;
1219 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1221 int StoreFrameIndex;
1222 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1223 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1226 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1227 if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1228 FeedsTwoAddr = true;
1234 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1235 /// split, and see if any of the spills are unnecessary. If so, remove them.
1236 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1237 bool changed = false;
1239 // Walk over all of the live intervals that were touched by the splitter,
1240 // and see if we can do any DCE and/or folding.
1241 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1242 LE = split.end(); LI != LE; ++LI) {
1243 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1245 // First, collect all the uses of the vreg, and sort them by their
1246 // reaching definition (VNInfo).
1247 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1248 UE = MRI->use_end(); UI != UE; ++UI) {
1249 SlotIndex index = LIs->getInstructionIndex(&*UI);
1250 index = index.getUseIndex();
1252 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1253 VNUseCount[LR->valno].insert(&*UI);
1256 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1257 // and/or fold them away.
1258 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1259 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1261 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1264 VNInfo* CurrVN = *VI;
1266 // We don't currently try to handle definitions with PHI kills, because
1267 // it would involve processing more than one VNInfo at once.
1268 if (CurrVN->hasPHIKill()) continue;
1270 // We also don't try to handle the results of PHI joins, since there's
1271 // no defining instruction to analyze.
1272 if (!CurrVN->isDefAccurate() || CurrVN->isUnused()) continue;
1274 // We're only interested in eliminating cruft introduced by the splitter,
1275 // is of the form load-use or load-use-store. First, check that the
1276 // definition is a load, and remember what stack slot we loaded it from.
1277 MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1279 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1281 // If the definition has no uses at all, just DCE it.
1282 if (VNUseCount[CurrVN].size() == 0) {
1283 LIs->RemoveMachineInstrFromMaps(DefMI);
1284 (*LI)->removeValNo(CurrVN);
1285 DefMI->eraseFromParent();
1286 VNUseCount.erase(CurrVN);
1292 // Second, get the number of non-store uses of the definition, as well as
1293 // a flag indicating whether it feeds into a later two-address definition.
1294 bool FeedsTwoAddr = false;
1295 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1296 (*LI)->reg, FrameIndex,
1299 // If there's one non-store use and it doesn't feed a two-addr, then
1300 // this is a load-use-store case that we can try to fold.
1301 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1302 // Start by finding the non-store use MachineInstr.
1303 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1304 int StoreFrameIndex;
1305 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1306 while (UI != VNUseCount[CurrVN].end() &&
1307 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1309 if (UI != VNUseCount[CurrVN].end())
1310 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1312 if (UI == VNUseCount[CurrVN].end()) continue;
1314 MachineInstr* use = *UI;
1316 // Attempt to fold it away!
1317 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1318 if (OpIdx == -1) continue;
1319 SmallVector<unsigned, 1> Ops;
1320 Ops.push_back(OpIdx);
1321 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1323 MachineInstr* NewMI =
1324 TII->foldMemoryOperand(*use->getParent()->getParent(),
1325 use, Ops, FrameIndex);
1327 if (!NewMI) continue;
1329 // Update relevant analyses.
1330 LIs->RemoveMachineInstrFromMaps(DefMI);
1331 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1332 (*LI)->removeValNo(CurrVN);
1334 DefMI->eraseFromParent();
1335 MachineBasicBlock* MBB = use->getParent();
1336 NewMI = MBB->insert(MBB->erase(use), NewMI);
1337 VNUseCount[CurrVN].erase(use);
1339 // Remove deleted instructions. Note that we need to remove them from
1340 // the VNInfo->use map as well, just to be safe.
1341 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1342 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1344 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1345 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1347 if (VNI->first != CurrVN)
1348 VNI->second.erase(*II);
1349 LIs->RemoveMachineInstrFromMaps(*II);
1350 (*II)->eraseFromParent();
1353 VNUseCount.erase(CurrVN);
1355 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1356 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1357 if (VI->second.erase(use))
1358 VI->second.insert(NewMI);
1365 // If there's more than one non-store instruction, we can't profitably
1366 // fold it, so bail.
1367 if (NonSpillCount) continue;
1369 // Otherwise, this is a load-store case, so DCE them.
1370 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1371 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1373 LIs->RemoveMachineInstrFromMaps(*UI);
1374 (*UI)->eraseFromParent();
1377 VNUseCount.erase(CurrVN);
1379 LIs->RemoveMachineInstrFromMaps(DefMI);
1380 (*LI)->removeValNo(CurrVN);
1381 DefMI->eraseFromParent();
1390 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1391 MachineBasicBlock* DefMBB,
1392 MachineBasicBlock* BarrierMBB) {
1393 if (DefMBB == BarrierMBB)
1396 if (LR->valno->hasPHIKill())
1399 SlotIndex MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1400 if (LR->end < MBBEnd)
1403 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1404 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1407 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1408 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1409 typedef std::pair<MachineBasicBlock*,
1410 MachineBasicBlock::succ_iterator> ItPair;
1411 SmallVector<ItPair, 4> Stack;
1412 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1414 while (!Stack.empty()) {
1415 ItPair P = Stack.back();
1418 MachineBasicBlock* PredMBB = P.first;
1419 MachineBasicBlock::succ_iterator S = P.second;
1421 if (S == PredMBB->succ_end())
1423 else if (Visited.count(*S)) {
1424 Stack.push_back(std::make_pair(PredMBB, ++S));
1427 Stack.push_back(std::make_pair(PredMBB, S+1));
1429 MachineBasicBlock* MBB = *S;
1430 Visited.insert(MBB);
1432 if (MBB == BarrierMBB)
1435 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1436 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1437 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1439 if (MDTN == DefMDTN)
1441 else if (MDTN == BarrierMDTN)
1443 MDTN = MDTN->getIDom();
1446 MBBEnd = LIs->getMBBEndIdx(MBB);
1447 if (LR->end > MBBEnd)
1448 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1455 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1457 TM = &MF.getTarget();
1458 TRI = TM->getRegisterInfo();
1459 TII = TM->getInstrInfo();
1460 MFI = MF.getFrameInfo();
1461 MRI = &MF.getRegInfo();
1462 SIs = &getAnalysis<SlotIndexes>();
1463 LIs = &getAnalysis<LiveIntervals>();
1464 LSs = &getAnalysis<LiveStacks>();
1465 VRM = &getAnalysis<VirtRegMap>();
1467 bool MadeChange = false;
1469 // Make sure blocks are numbered in order.
1470 MF.RenumberBlocks();
1472 MachineBasicBlock *Entry = MF.begin();
1473 SmallPtrSet<MachineBasicBlock*,16> Visited;
1475 SmallPtrSet<LiveInterval*, 8> Split;
1477 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1478 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1481 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1482 E = BarrierMBB->end(); I != E; ++I) {
1484 const TargetRegisterClass **BarrierRCs =
1485 Barrier->getDesc().getRegClassBarriers();
1488 BarrierIdx = LIs->getInstructionIndex(Barrier);
1489 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1493 MadeChange |= removeDeadSpills(Split);