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 INITIALIZE_PASS_BEGIN(PreAllocSplitting, "pre-alloc-splitting",
207 "Pre-Register Allocation Live Interval Splitting",
209 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
210 INITIALIZE_PASS_DEPENDENCY(LiveIntervals)
211 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
212 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
213 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
214 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
215 INITIALIZE_PASS_END(PreAllocSplitting, "pre-alloc-splitting",
216 "Pre-Register Allocation Live Interval Splitting",
219 char &llvm::PreAllocSplittingID = PreAllocSplitting::ID;
221 /// findSpillPoint - Find a gap as far away from the given MI that's suitable
222 /// for spilling the current live interval. The index must be before any
223 /// defs and uses of the live interval register in the mbb. Return begin() if
225 MachineBasicBlock::iterator
226 PreAllocSplitting::findSpillPoint(MachineBasicBlock *MBB, MachineInstr *MI,
228 SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
229 MachineBasicBlock::iterator Pt = MBB->begin();
231 MachineBasicBlock::iterator MII = MI;
232 MachineBasicBlock::iterator EndPt = DefMI
233 ? MachineBasicBlock::iterator(DefMI) : MBB->begin();
235 while (MII != EndPt && !RefsInMBB.count(MII) &&
236 MII->getOpcode() != TRI->getCallFrameSetupOpcode())
238 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
240 while (MII != EndPt && !RefsInMBB.count(MII)) {
241 // We can't insert the spill between the barrier (a call), and its
242 // corresponding call frame setup.
243 if (MII->getOpcode() == TRI->getCallFrameDestroyOpcode()) {
244 while (MII->getOpcode() != TRI->getCallFrameSetupOpcode()) {
255 if (RefsInMBB.count(MII))
265 /// findRestorePoint - Find a gap in the instruction index map that's suitable
266 /// for restoring the current live interval value. The index must be before any
267 /// uses of the live interval register in the mbb. Return end() if none is
269 MachineBasicBlock::iterator
270 PreAllocSplitting::findRestorePoint(MachineBasicBlock *MBB, MachineInstr *MI,
272 SmallPtrSet<MachineInstr*, 4> &RefsInMBB) {
273 // FIXME: Allow spill to be inserted to the beginning of the mbb. Update mbb
274 // begin index accordingly.
275 MachineBasicBlock::iterator Pt = MBB->end();
276 MachineBasicBlock::iterator EndPt = MBB->getFirstTerminator();
278 // We start at the call, so walk forward until we find the call frame teardown
279 // since we can't insert restores before that. Bail if we encounter a use
281 MachineBasicBlock::iterator MII = MI;
282 if (MII == EndPt) return Pt;
284 while (MII != EndPt && !RefsInMBB.count(MII) &&
285 MII->getOpcode() != TRI->getCallFrameDestroyOpcode())
287 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
290 // FIXME: Limit the number of instructions to examine to reduce
292 while (MII != EndPt) {
293 SlotIndex Index = LIs->getInstructionIndex(MII);
297 // We can't insert a restore between the barrier (a call) and its
298 // corresponding call frame teardown.
299 if (MII->getOpcode() == TRI->getCallFrameSetupOpcode()) {
301 if (MII == EndPt || RefsInMBB.count(MII)) return Pt;
303 } while (MII->getOpcode() != TRI->getCallFrameDestroyOpcode());
308 if (RefsInMBB.count(MII))
317 /// CreateSpillStackSlot - Create a stack slot for the live interval being
318 /// split. If the live interval was previously split, just reuse the same
320 int PreAllocSplitting::CreateSpillStackSlot(unsigned Reg,
321 const TargetRegisterClass *RC) {
323 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(Reg);
324 if (I != IntervalSSMap.end()) {
327 SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
328 IntervalSSMap[Reg] = SS;
331 // Create live interval for stack slot.
332 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
333 if (CurrSLI->hasAtLeastOneValue())
334 CurrSValNo = CurrSLI->getValNumInfo(0);
336 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0,
337 LSs->getVNInfoAllocator());
341 /// IsAvailableInStack - Return true if register is available in a split stack
342 /// slot at the specified index.
344 PreAllocSplitting::IsAvailableInStack(MachineBasicBlock *DefMBB,
345 unsigned Reg, SlotIndex DefIndex,
346 SlotIndex RestoreIndex,
347 SlotIndex &SpillIndex,
352 DenseMap<unsigned, int>::const_iterator I = IntervalSSMap.find(Reg);
353 if (I == IntervalSSMap.end())
355 DenseMap<SlotIndex, SlotIndex>::const_iterator
356 II = Def2SpillMap.find(DefIndex);
357 if (II == Def2SpillMap.end())
360 // If last spill of def is in the same mbb as barrier mbb (where restore will
361 // be), make sure it's not below the intended restore index.
362 // FIXME: Undo the previous spill?
363 assert(LIs->getMBBFromIndex(II->second) == DefMBB);
364 if (DefMBB == BarrierMBB && II->second >= RestoreIndex)
368 SpillIndex = II->second;
372 /// UpdateSpillSlotInterval - Given the specified val# of the register live
373 /// interval being split, and the spill and restore indicies, update the live
374 /// interval of the spill stack slot.
376 PreAllocSplitting::UpdateSpillSlotInterval(VNInfo *ValNo, SlotIndex SpillIndex,
377 SlotIndex RestoreIndex) {
378 assert(LIs->getMBBFromIndex(RestoreIndex) == BarrierMBB &&
379 "Expect restore in the barrier mbb");
381 MachineBasicBlock *MBB = LIs->getMBBFromIndex(SpillIndex);
382 if (MBB == BarrierMBB) {
383 // Intra-block spill + restore. We are done.
384 LiveRange SLR(SpillIndex, RestoreIndex, CurrSValNo);
385 CurrSLI->addRange(SLR);
389 SmallPtrSet<MachineBasicBlock*, 4> Processed;
390 SlotIndex EndIdx = LIs->getMBBEndIdx(MBB);
391 LiveRange SLR(SpillIndex, EndIdx, CurrSValNo);
392 CurrSLI->addRange(SLR);
393 Processed.insert(MBB);
395 // Start from the spill mbb, figure out the extend of the spill slot's
397 SmallVector<MachineBasicBlock*, 4> WorkList;
398 const LiveRange *LR = CurrLI->getLiveRangeContaining(SpillIndex);
399 if (LR->end > EndIdx)
400 // If live range extend beyond end of mbb, add successors to work list.
401 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
402 SE = MBB->succ_end(); SI != SE; ++SI)
403 WorkList.push_back(*SI);
405 while (!WorkList.empty()) {
406 MachineBasicBlock *MBB = WorkList.back();
408 if (Processed.count(MBB))
410 SlotIndex Idx = LIs->getMBBStartIdx(MBB);
411 LR = CurrLI->getLiveRangeContaining(Idx);
412 if (LR && LR->valno == ValNo) {
413 EndIdx = LIs->getMBBEndIdx(MBB);
414 if (Idx <= RestoreIndex && RestoreIndex < EndIdx) {
415 // Spill slot live interval stops at the restore.
416 LiveRange SLR(Idx, RestoreIndex, CurrSValNo);
417 CurrSLI->addRange(SLR);
418 } else if (LR->end > EndIdx) {
419 // Live range extends beyond end of mbb, process successors.
420 LiveRange SLR(Idx, EndIdx.getNextIndex(), CurrSValNo);
421 CurrSLI->addRange(SLR);
422 for (MachineBasicBlock::succ_iterator SI = MBB->succ_begin(),
423 SE = MBB->succ_end(); SI != SE; ++SI)
424 WorkList.push_back(*SI);
426 LiveRange SLR(Idx, LR->end, CurrSValNo);
427 CurrSLI->addRange(SLR);
429 Processed.insert(MBB);
434 /// PerformPHIConstruction - From properly set up use and def lists, use a PHI
435 /// construction algorithm to compute the ranges and valnos for an interval.
437 PreAllocSplitting::PerformPHIConstruction(MachineBasicBlock::iterator UseI,
438 MachineBasicBlock* MBB, LiveInterval* LI,
439 SmallPtrSet<MachineInstr*, 4>& Visited,
440 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
441 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
442 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
443 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
444 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
445 bool IsTopLevel, bool IsIntraBlock) {
446 // Return memoized result if it's available.
447 if (IsTopLevel && Visited.count(UseI) && NewVNs.count(UseI))
449 else if (!IsTopLevel && IsIntraBlock && NewVNs.count(UseI))
451 else if (!IsIntraBlock && LiveOut.count(MBB))
454 // Check if our block contains any uses or defs.
455 bool ContainsDefs = Defs.count(MBB);
456 bool ContainsUses = Uses.count(MBB);
460 // Enumerate the cases of use/def contaning blocks.
461 if (!ContainsDefs && !ContainsUses) {
462 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs, Uses,
463 NewVNs, LiveOut, Phis,
464 IsTopLevel, IsIntraBlock);
465 } else if (ContainsDefs && !ContainsUses) {
466 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
468 // Search for the def in this block. If we don't find it before the
469 // instruction we care about, go to the fallback case. Note that that
470 // should never happen: this cannot be intrablock, so use should
471 // always be an end() iterator.
472 assert(UseI == MBB->end() && "No use marked in intrablock");
474 MachineBasicBlock::iterator Walker = UseI;
476 while (Walker != MBB->begin()) {
477 if (BlockDefs.count(Walker))
482 // Once we've found it, extend its VNInfo to our instruction.
483 SlotIndex DefIndex = LIs->getInstructionIndex(Walker);
484 DefIndex = DefIndex.getDefIndex();
485 SlotIndex EndIndex = LIs->getMBBEndIdx(MBB);
487 RetVNI = NewVNs[Walker];
488 LI->addRange(LiveRange(DefIndex, EndIndex, RetVNI));
489 } else if (!ContainsDefs && ContainsUses) {
490 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
492 // Search for the use in this block that precedes the instruction we care
493 // about, going to the fallback case if we don't find it.
494 MachineBasicBlock::iterator Walker = UseI;
496 while (Walker != MBB->begin()) {
498 if (BlockUses.count(Walker)) {
505 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
506 Uses, NewVNs, LiveOut, Phis,
507 IsTopLevel, IsIntraBlock);
509 SlotIndex UseIndex = LIs->getInstructionIndex(Walker);
510 UseIndex = UseIndex.getUseIndex();
513 EndIndex = LIs->getInstructionIndex(UseI).getDefIndex();
515 EndIndex = LIs->getMBBEndIdx(MBB);
517 // Now, recursively phi construct the VNInfo for the use we found,
518 // and then extend it to include the instruction we care about
519 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
520 NewVNs, LiveOut, Phis, false, true);
522 LI->addRange(LiveRange(UseIndex, EndIndex, RetVNI));
524 // FIXME: Need to set kills properly for inter-block stuff.
525 } else if (ContainsDefs && ContainsUses) {
526 SmallPtrSet<MachineInstr*, 2>& BlockDefs = Defs[MBB];
527 SmallPtrSet<MachineInstr*, 2>& BlockUses = Uses[MBB];
529 // This case is basically a merging of the two preceding case, with the
530 // special note that checking for defs must take precedence over checking
531 // for uses, because of two-address instructions.
532 MachineBasicBlock::iterator Walker = UseI;
533 bool foundDef = false;
534 bool foundUse = false;
535 while (Walker != MBB->begin()) {
537 if (BlockDefs.count(Walker)) {
540 } else if (BlockUses.count(Walker)) {
546 if (!foundDef && !foundUse)
547 return PerformPHIConstructionFallBack(UseI, MBB, LI, Visited, Defs,
548 Uses, NewVNs, LiveOut, Phis,
549 IsTopLevel, IsIntraBlock);
551 SlotIndex StartIndex = LIs->getInstructionIndex(Walker);
552 StartIndex = foundDef ? StartIndex.getDefIndex() : StartIndex.getUseIndex();
555 EndIndex = LIs->getInstructionIndex(UseI).getDefIndex();
557 EndIndex = LIs->getMBBEndIdx(MBB);
560 RetVNI = NewVNs[Walker];
562 RetVNI = PerformPHIConstruction(Walker, MBB, LI, Visited, Defs, Uses,
563 NewVNs, LiveOut, Phis, false, true);
565 LI->addRange(LiveRange(StartIndex, EndIndex, RetVNI));
568 // Memoize results so we don't have to recompute them.
569 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
571 if (!NewVNs.count(UseI))
572 NewVNs[UseI] = RetVNI;
573 Visited.insert(UseI);
579 /// PerformPHIConstructionFallBack - PerformPHIConstruction fall back path.
582 PreAllocSplitting::PerformPHIConstructionFallBack(MachineBasicBlock::iterator UseI,
583 MachineBasicBlock* MBB, LiveInterval* LI,
584 SmallPtrSet<MachineInstr*, 4>& Visited,
585 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Defs,
586 DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> >& Uses,
587 DenseMap<MachineInstr*, VNInfo*>& NewVNs,
588 DenseMap<MachineBasicBlock*, VNInfo*>& LiveOut,
589 DenseMap<MachineBasicBlock*, VNInfo*>& Phis,
590 bool IsTopLevel, bool IsIntraBlock) {
591 // NOTE: Because this is the fallback case from other cases, we do NOT
592 // assume that we are not intrablock here.
593 if (Phis.count(MBB)) return Phis[MBB];
595 SlotIndex StartIndex = LIs->getMBBStartIdx(MBB);
596 VNInfo *RetVNI = Phis[MBB] =
597 LI->getNextValue(SlotIndex(), /*FIXME*/ 0,
598 LIs->getVNInfoAllocator());
600 if (!IsIntraBlock) LiveOut[MBB] = RetVNI;
602 // If there are no uses or defs between our starting point and the
603 // beginning of the block, then recursive perform phi construction
604 // on our predecessors.
605 DenseMap<MachineBasicBlock*, VNInfo*> IncomingVNs;
606 for (MachineBasicBlock::pred_iterator PI = MBB->pred_begin(),
607 PE = MBB->pred_end(); PI != PE; ++PI) {
608 VNInfo* Incoming = PerformPHIConstruction((*PI)->end(), *PI, LI,
609 Visited, Defs, Uses, NewVNs,
610 LiveOut, Phis, false, false);
612 IncomingVNs[*PI] = Incoming;
615 if (MBB->pred_size() == 1 && !RetVNI->hasPHIKill()) {
616 VNInfo* OldVN = RetVNI;
617 VNInfo* NewVN = IncomingVNs.begin()->second;
618 VNInfo* MergedVN = LI->MergeValueNumberInto(OldVN, NewVN);
619 if (MergedVN == OldVN) std::swap(OldVN, NewVN);
621 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator LOI = LiveOut.begin(),
622 LOE = LiveOut.end(); LOI != LOE; ++LOI)
623 if (LOI->second == OldVN)
624 LOI->second = MergedVN;
625 for (DenseMap<MachineInstr*, VNInfo*>::iterator NVI = NewVNs.begin(),
626 NVE = NewVNs.end(); NVI != NVE; ++NVI)
627 if (NVI->second == OldVN)
628 NVI->second = MergedVN;
629 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator PI = Phis.begin(),
630 PE = Phis.end(); PI != PE; ++PI)
631 if (PI->second == OldVN)
632 PI->second = MergedVN;
635 // Otherwise, merge the incoming VNInfos with a phi join. Create a new
636 // VNInfo to represent the joined value.
637 for (DenseMap<MachineBasicBlock*, VNInfo*>::iterator I =
638 IncomingVNs.begin(), E = IncomingVNs.end(); I != E; ++I) {
639 I->second->setHasPHIKill(true);
645 EndIndex = LIs->getInstructionIndex(UseI).getDefIndex();
647 EndIndex = LIs->getMBBEndIdx(MBB);
648 LI->addRange(LiveRange(StartIndex, EndIndex, RetVNI));
650 // Memoize results so we don't have to recompute them.
652 LiveOut[MBB] = RetVNI;
654 if (!NewVNs.count(UseI))
655 NewVNs[UseI] = RetVNI;
656 Visited.insert(UseI);
662 /// ReconstructLiveInterval - Recompute a live interval from scratch.
663 void PreAllocSplitting::ReconstructLiveInterval(LiveInterval* LI) {
664 VNInfo::Allocator& Alloc = LIs->getVNInfoAllocator();
666 // Clear the old ranges and valnos;
669 // Cache the uses and defs of the register
670 typedef DenseMap<MachineBasicBlock*, SmallPtrSet<MachineInstr*, 2> > RegMap;
673 // Keep track of the new VNs we're creating.
674 DenseMap<MachineInstr*, VNInfo*> NewVNs;
675 SmallPtrSet<VNInfo*, 2> PhiVNs;
677 // Cache defs, and create a new VNInfo for each def.
678 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
679 DE = MRI->def_end(); DI != DE; ++DI) {
680 Defs[(*DI).getParent()].insert(&*DI);
682 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
683 DefIdx = DefIdx.getDefIndex();
685 assert(!DI->isPHI() && "PHI instr in code during pre-alloc splitting.");
686 VNInfo* NewVN = LI->getNextValue(DefIdx, 0, Alloc);
688 // If the def is a move, set the copy field.
689 if (DI->isCopyLike() && DI->getOperand(0).getReg() == LI->reg)
690 NewVN->setCopy(&*DI);
692 NewVNs[&*DI] = NewVN;
695 // Cache uses as a separate pass from actually processing them.
696 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
697 UE = MRI->use_end(); UI != UE; ++UI)
698 Uses[(*UI).getParent()].insert(&*UI);
700 // Now, actually process every use and use a phi construction algorithm
701 // to walk from it to its reaching definitions, building VNInfos along
703 DenseMap<MachineBasicBlock*, VNInfo*> LiveOut;
704 DenseMap<MachineBasicBlock*, VNInfo*> Phis;
705 SmallPtrSet<MachineInstr*, 4> Visited;
706 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin(LI->reg),
707 UE = MRI->use_end(); UI != UE; ++UI) {
708 PerformPHIConstruction(&*UI, UI->getParent(), LI, Visited, Defs,
709 Uses, NewVNs, LiveOut, Phis, true, true);
712 // Add ranges for dead defs
713 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(LI->reg),
714 DE = MRI->def_end(); DI != DE; ++DI) {
715 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI);
716 DefIdx = DefIdx.getDefIndex();
718 if (LI->liveAt(DefIdx)) continue;
720 VNInfo* DeadVN = NewVNs[&*DI];
721 LI->addRange(LiveRange(DefIdx, DefIdx.getNextSlot(), DeadVN));
725 /// RenumberValno - Split the given valno out into a new vreg, allowing it to
726 /// be allocated to a different register. This function creates a new vreg,
727 /// copies the valno and its live ranges over to the new vreg's interval,
728 /// removes them from the old interval, and rewrites all uses and defs of
729 /// the original reg to the new vreg within those ranges.
730 void PreAllocSplitting::RenumberValno(VNInfo* VN) {
731 SmallVector<VNInfo*, 4> Stack;
732 SmallVector<VNInfo*, 4> VNsToCopy;
735 // Walk through and copy the valno we care about, and any other valnos
736 // that are two-address redefinitions of the one we care about. These
737 // will need to be rewritten as well. We also check for safety of the
738 // renumbering here, by making sure that none of the valno involved has
740 while (!Stack.empty()) {
741 VNInfo* OldVN = Stack.back();
744 // Bail out if we ever encounter a valno that has a PHI kill. We can't
746 if (OldVN->hasPHIKill()) return;
748 VNsToCopy.push_back(OldVN);
750 // Locate two-address redefinitions
751 for (MachineRegisterInfo::def_iterator DI = MRI->def_begin(CurrLI->reg),
752 DE = MRI->def_end(); DI != DE; ++DI) {
753 if (!DI->isRegTiedToUseOperand(DI.getOperandNo())) continue;
754 SlotIndex DefIdx = LIs->getInstructionIndex(&*DI).getDefIndex();
755 VNInfo* NextVN = CurrLI->findDefinedVNInfoForRegInt(DefIdx);
756 if (std::find(VNsToCopy.begin(), VNsToCopy.end(), NextVN) !=
758 Stack.push_back(NextVN);
762 // Create the new vreg
763 unsigned NewVReg = MRI->createVirtualRegister(MRI->getRegClass(CurrLI->reg));
765 // Create the new live interval
766 LiveInterval& NewLI = LIs->getOrCreateInterval(NewVReg);
768 for (SmallVector<VNInfo*, 4>::iterator OI = VNsToCopy.begin(), OE =
769 VNsToCopy.end(); OI != OE; ++OI) {
772 // Copy the valno over
773 VNInfo* NewVN = NewLI.createValueCopy(OldVN, LIs->getVNInfoAllocator());
774 NewLI.MergeValueInAsValue(*CurrLI, OldVN, NewVN);
776 // Remove the valno from the old interval
777 CurrLI->removeValNo(OldVN);
780 // Rewrite defs and uses. This is done in two stages to avoid invalidating
782 SmallVector<std::pair<MachineInstr*, unsigned>, 8> OpsToChange;
784 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
785 E = MRI->reg_end(); I != E; ++I) {
786 MachineOperand& MO = I.getOperand();
787 SlotIndex InstrIdx = LIs->getInstructionIndex(&*I);
789 if ((MO.isUse() && NewLI.liveAt(InstrIdx.getUseIndex())) ||
790 (MO.isDef() && NewLI.liveAt(InstrIdx.getDefIndex())))
791 OpsToChange.push_back(std::make_pair(&*I, I.getOperandNo()));
794 for (SmallVector<std::pair<MachineInstr*, unsigned>, 8>::iterator I =
795 OpsToChange.begin(), E = OpsToChange.end(); I != E; ++I) {
796 MachineInstr* Inst = I->first;
797 unsigned OpIdx = I->second;
798 MachineOperand& MO = Inst->getOperand(OpIdx);
802 // Grow the VirtRegMap, since we've created a new vreg.
805 // The renumbered vreg shares a stack slot with the old register.
806 if (IntervalSSMap.count(CurrLI->reg))
807 IntervalSSMap[NewVReg] = IntervalSSMap[CurrLI->reg];
812 bool PreAllocSplitting::Rematerialize(unsigned VReg, VNInfo* ValNo,
814 MachineBasicBlock::iterator RestorePt,
815 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
816 MachineBasicBlock& MBB = *RestorePt->getParent();
818 MachineBasicBlock::iterator KillPt = BarrierMBB->end();
819 if (!DefMI || DefMI->getParent() == BarrierMBB)
820 KillPt = findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
822 KillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
824 if (KillPt == DefMI->getParent()->end())
827 TII->reMaterialize(MBB, RestorePt, VReg, 0, DefMI, *TRI);
828 SlotIndex RematIdx = LIs->InsertMachineInstrInMaps(prior(RestorePt));
830 ReconstructLiveInterval(CurrLI);
831 RematIdx = RematIdx.getDefIndex();
832 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RematIdx));
839 MachineInstr* PreAllocSplitting::FoldSpill(unsigned vreg,
840 const TargetRegisterClass* RC,
842 MachineInstr* Barrier,
843 MachineBasicBlock* MBB,
845 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
846 // Go top down if RefsInMBB is empty.
847 if (RefsInMBB.empty())
850 MachineBasicBlock::iterator FoldPt = Barrier;
851 while (&*FoldPt != DefMI && FoldPt != MBB->begin() &&
852 !RefsInMBB.count(FoldPt))
855 int OpIdx = FoldPt->findRegisterDefOperandIdx(vreg);
859 SmallVector<unsigned, 1> Ops;
860 Ops.push_back(OpIdx);
862 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
865 DenseMap<unsigned, int>::iterator I = IntervalSSMap.find(vreg);
866 if (I != IntervalSSMap.end()) {
869 SS = MFI->CreateSpillStackObject(RC->getSize(), RC->getAlignment());
872 MachineInstr* FMI = TII->foldMemoryOperand(FoldPt, Ops, SS);
875 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
876 FoldPt->eraseFromParent();
879 IntervalSSMap[vreg] = SS;
880 CurrSLI = &LSs->getOrCreateInterval(SS, RC);
881 if (CurrSLI->hasAtLeastOneValue())
882 CurrSValNo = CurrSLI->getValNumInfo(0);
884 CurrSValNo = CurrSLI->getNextValue(SlotIndex(), 0,
885 LSs->getVNInfoAllocator());
891 MachineInstr* PreAllocSplitting::FoldRestore(unsigned vreg,
892 const TargetRegisterClass* RC,
893 MachineInstr* Barrier,
894 MachineBasicBlock* MBB,
896 SmallPtrSet<MachineInstr*, 4>& RefsInMBB) {
897 if ((int)RestoreFoldLimit != -1 && RestoreFoldLimit == (int)NumRestoreFolds)
900 // Go top down if RefsInMBB is empty.
901 if (RefsInMBB.empty())
904 // Can't fold a restore between a call stack setup and teardown.
905 MachineBasicBlock::iterator FoldPt = Barrier;
907 // Advance from barrier to call frame teardown.
908 while (FoldPt != MBB->getFirstTerminator() &&
909 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
910 if (RefsInMBB.count(FoldPt))
916 if (FoldPt == MBB->getFirstTerminator())
921 // Now find the restore point.
922 while (FoldPt != MBB->getFirstTerminator() && !RefsInMBB.count(FoldPt)) {
923 if (FoldPt->getOpcode() == TRI->getCallFrameSetupOpcode()) {
924 while (FoldPt != MBB->getFirstTerminator() &&
925 FoldPt->getOpcode() != TRI->getCallFrameDestroyOpcode()) {
926 if (RefsInMBB.count(FoldPt))
932 if (FoldPt == MBB->getFirstTerminator())
939 if (FoldPt == MBB->getFirstTerminator())
942 int OpIdx = FoldPt->findRegisterUseOperandIdx(vreg, true);
946 SmallVector<unsigned, 1> Ops;
947 Ops.push_back(OpIdx);
949 if (!TII->canFoldMemoryOperand(FoldPt, Ops))
952 MachineInstr* FMI = TII->foldMemoryOperand(FoldPt, Ops, SS);
955 LIs->ReplaceMachineInstrInMaps(FoldPt, FMI);
956 FoldPt->eraseFromParent();
963 /// SplitRegLiveInterval - Split (spill and restore) the given live interval
964 /// so it would not cross the barrier that's being processed. Shrink wrap
965 /// (minimize) the live interval to the last uses.
966 bool PreAllocSplitting::SplitRegLiveInterval(LiveInterval *LI) {
967 DEBUG(dbgs() << "Pre-alloc splitting " << LI->reg << " for " << *Barrier
972 // Find live range where current interval cross the barrier.
973 LiveInterval::iterator LR =
974 CurrLI->FindLiveRangeContaining(BarrierIdx.getUseIndex());
975 VNInfo *ValNo = LR->valno;
977 assert(!ValNo->isUnused() && "Val# is defined by a dead def?");
979 MachineInstr *DefMI = LIs->getInstructionFromIndex(ValNo->def);
981 // If this would create a new join point, do not split.
982 if (DefMI && createsNewJoin(LR, DefMI->getParent(), Barrier->getParent())) {
983 DEBUG(dbgs() << "FAILED (would create a new join point).\n");
987 // Find all references in the barrier mbb.
988 SmallPtrSet<MachineInstr*, 4> RefsInMBB;
989 for (MachineRegisterInfo::reg_iterator I = MRI->reg_begin(CurrLI->reg),
990 E = MRI->reg_end(); I != E; ++I) {
991 MachineInstr *RefMI = &*I;
992 if (RefMI->getParent() == BarrierMBB)
993 RefsInMBB.insert(RefMI);
996 // Find a point to restore the value after the barrier.
997 MachineBasicBlock::iterator RestorePt =
998 findRestorePoint(BarrierMBB, Barrier, LR->end, RefsInMBB);
999 if (RestorePt == BarrierMBB->end()) {
1000 DEBUG(dbgs() << "FAILED (could not find a suitable restore point).\n");
1004 if (DefMI && LIs->isReMaterializable(*LI, ValNo, DefMI))
1005 if (Rematerialize(LI->reg, ValNo, DefMI, RestorePt, RefsInMBB)) {
1006 DEBUG(dbgs() << "success (remat).\n");
1010 // Add a spill either before the barrier or after the definition.
1011 MachineBasicBlock *DefMBB = DefMI ? DefMI->getParent() : NULL;
1012 const TargetRegisterClass *RC = MRI->getRegClass(CurrLI->reg);
1013 SlotIndex SpillIndex;
1014 MachineInstr *SpillMI = NULL;
1017 // If we don't know where the def is we must split just before the barrier.
1018 if ((SpillMI = FoldSpill(LI->reg, RC, 0, Barrier,
1019 BarrierMBB, SS, RefsInMBB))) {
1020 SpillIndex = LIs->getInstructionIndex(SpillMI);
1022 MachineBasicBlock::iterator SpillPt =
1023 findSpillPoint(BarrierMBB, Barrier, NULL, RefsInMBB);
1024 if (SpillPt == BarrierMBB->begin()) {
1025 DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1026 return false; // No gap to insert spill.
1030 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1031 TII->storeRegToStackSlot(*BarrierMBB, SpillPt, CurrLI->reg, true, SS, RC,
1033 SpillMI = prior(SpillPt);
1034 SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1036 } else if (!IsAvailableInStack(DefMBB, CurrLI->reg, ValNo->def,
1037 LIs->getZeroIndex(), SpillIndex, SS)) {
1038 // If it's already split, just restore the value. There is no need to spill
1041 DEBUG(dbgs() << "FAILED (def is dead).\n");
1042 return false; // Def is dead. Do nothing.
1045 if ((SpillMI = FoldSpill(LI->reg, RC, DefMI, Barrier,
1046 BarrierMBB, SS, RefsInMBB))) {
1047 SpillIndex = LIs->getInstructionIndex(SpillMI);
1049 // Check if it's possible to insert a spill after the def MI.
1050 MachineBasicBlock::iterator SpillPt;
1051 if (DefMBB == BarrierMBB) {
1052 // Add spill after the def and the last use before the barrier.
1053 SpillPt = findSpillPoint(BarrierMBB, Barrier, DefMI,
1055 if (SpillPt == DefMBB->begin()) {
1056 DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1057 return false; // No gap to insert spill.
1060 SpillPt = llvm::next(MachineBasicBlock::iterator(DefMI));
1061 if (SpillPt == DefMBB->end()) {
1062 DEBUG(dbgs() << "FAILED (could not find a suitable spill point).\n");
1063 return false; // No gap to insert spill.
1067 SS = CreateSpillStackSlot(CurrLI->reg, RC);
1068 TII->storeRegToStackSlot(*DefMBB, SpillPt, CurrLI->reg, false, SS, RC,
1070 SpillMI = prior(SpillPt);
1071 SpillIndex = LIs->InsertMachineInstrInMaps(SpillMI);
1075 // Remember def instruction index to spill index mapping.
1076 if (DefMI && SpillMI)
1077 Def2SpillMap[ValNo->def] = SpillIndex;
1080 bool FoldedRestore = false;
1081 SlotIndex RestoreIndex;
1082 if (MachineInstr* LMI = FoldRestore(CurrLI->reg, RC, Barrier,
1083 BarrierMBB, SS, RefsInMBB)) {
1085 RestoreIndex = LIs->getInstructionIndex(RestorePt);
1086 FoldedRestore = true;
1088 TII->loadRegFromStackSlot(*BarrierMBB, RestorePt, CurrLI->reg, SS, RC, TRI);
1089 MachineInstr *LoadMI = prior(RestorePt);
1090 RestoreIndex = LIs->InsertMachineInstrInMaps(LoadMI);
1093 // Update spill stack slot live interval.
1094 UpdateSpillSlotInterval(ValNo, SpillIndex.getUseIndex().getNextSlot(),
1095 RestoreIndex.getDefIndex());
1097 ReconstructLiveInterval(CurrLI);
1099 if (!FoldedRestore) {
1100 SlotIndex RestoreIdx = LIs->getInstructionIndex(prior(RestorePt));
1101 RestoreIdx = RestoreIdx.getDefIndex();
1102 RenumberValno(CurrLI->findDefinedVNInfoForRegInt(RestoreIdx));
1106 DEBUG(dbgs() << "success.\n");
1110 /// SplitRegLiveIntervals - Split all register live intervals that cross the
1111 /// barrier that's being processed.
1113 PreAllocSplitting::SplitRegLiveIntervals(const TargetRegisterClass **RCs,
1114 SmallPtrSet<LiveInterval*, 8>& Split) {
1115 // First find all the virtual registers whose live intervals are intercepted
1116 // by the current barrier.
1117 SmallVector<LiveInterval*, 8> Intervals;
1118 for (const TargetRegisterClass **RC = RCs; *RC; ++RC) {
1119 // FIXME: If it's not safe to move any instruction that defines the barrier
1120 // register class, then it means there are some special dependencies which
1121 // codegen is not modelling. Ignore these barriers for now.
1122 if (!TII->isSafeToMoveRegClassDefs(*RC))
1124 const std::vector<unsigned> &VRs = MRI->getRegClassVirtRegs(*RC);
1125 for (unsigned i = 0, e = VRs.size(); i != e; ++i) {
1126 unsigned Reg = VRs[i];
1127 if (!LIs->hasInterval(Reg))
1129 LiveInterval *LI = &LIs->getInterval(Reg);
1130 if (LI->liveAt(BarrierIdx) && !Barrier->readsRegister(Reg))
1131 // Virtual register live interval is intercepted by the barrier. We
1132 // should split and shrink wrap its interval if possible.
1133 Intervals.push_back(LI);
1137 // Process the affected live intervals.
1138 bool Change = false;
1139 while (!Intervals.empty()) {
1140 if (PreSplitLimit != -1 && (int)NumSplits == PreSplitLimit)
1142 LiveInterval *LI = Intervals.back();
1143 Intervals.pop_back();
1144 bool result = SplitRegLiveInterval(LI);
1145 if (result) Split.insert(LI);
1152 unsigned PreAllocSplitting::getNumberOfNonSpills(
1153 SmallPtrSet<MachineInstr*, 4>& MIs,
1154 unsigned Reg, int FrameIndex,
1155 bool& FeedsTwoAddr) {
1156 unsigned NonSpills = 0;
1157 for (SmallPtrSet<MachineInstr*, 4>::iterator UI = MIs.begin(), UE = MIs.end();
1159 int StoreFrameIndex;
1160 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1161 if (StoreVReg != Reg || StoreFrameIndex != FrameIndex)
1164 int DefIdx = (*UI)->findRegisterDefOperandIdx(Reg);
1165 if (DefIdx != -1 && (*UI)->isRegTiedToUseOperand(DefIdx))
1166 FeedsTwoAddr = true;
1172 /// removeDeadSpills - After doing splitting, filter through all intervals we've
1173 /// split, and see if any of the spills are unnecessary. If so, remove them.
1174 bool PreAllocSplitting::removeDeadSpills(SmallPtrSet<LiveInterval*, 8>& split) {
1175 bool changed = false;
1177 // Walk over all of the live intervals that were touched by the splitter,
1178 // and see if we can do any DCE and/or folding.
1179 for (SmallPtrSet<LiveInterval*, 8>::iterator LI = split.begin(),
1180 LE = split.end(); LI != LE; ++LI) {
1181 DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> > VNUseCount;
1183 // First, collect all the uses of the vreg, and sort them by their
1184 // reaching definition (VNInfo).
1185 for (MachineRegisterInfo::use_iterator UI = MRI->use_begin((*LI)->reg),
1186 UE = MRI->use_end(); UI != UE; ++UI) {
1187 SlotIndex index = LIs->getInstructionIndex(&*UI);
1188 index = index.getUseIndex();
1190 const LiveRange* LR = (*LI)->getLiveRangeContaining(index);
1191 VNUseCount[LR->valno].insert(&*UI);
1194 // Now, take the definitions (VNInfo's) one at a time and try to DCE
1195 // and/or fold them away.
1196 for (LiveInterval::vni_iterator VI = (*LI)->vni_begin(),
1197 VE = (*LI)->vni_end(); VI != VE; ++VI) {
1199 if (DeadSplitLimit != -1 && (int)NumDeadSpills == DeadSplitLimit)
1202 VNInfo* CurrVN = *VI;
1204 // We don't currently try to handle definitions with PHI kills, because
1205 // it would involve processing more than one VNInfo at once.
1206 if (CurrVN->hasPHIKill()) continue;
1208 // We also don't try to handle the results of PHI joins, since there's
1209 // no defining instruction to analyze.
1210 MachineInstr* DefMI = LIs->getInstructionFromIndex(CurrVN->def);
1211 if (!DefMI || CurrVN->isUnused()) continue;
1213 // We're only interested in eliminating cruft introduced by the splitter,
1214 // is of the form load-use or load-use-store. First, check that the
1215 // definition is a load, and remember what stack slot we loaded it from.
1217 if (!TII->isLoadFromStackSlot(DefMI, FrameIndex)) continue;
1219 // If the definition has no uses at all, just DCE it.
1220 if (VNUseCount[CurrVN].size() == 0) {
1221 LIs->RemoveMachineInstrFromMaps(DefMI);
1222 (*LI)->removeValNo(CurrVN);
1223 DefMI->eraseFromParent();
1224 VNUseCount.erase(CurrVN);
1230 // Second, get the number of non-store uses of the definition, as well as
1231 // a flag indicating whether it feeds into a later two-address definition.
1232 bool FeedsTwoAddr = false;
1233 unsigned NonSpillCount = getNumberOfNonSpills(VNUseCount[CurrVN],
1234 (*LI)->reg, FrameIndex,
1237 // If there's one non-store use and it doesn't feed a two-addr, then
1238 // this is a load-use-store case that we can try to fold.
1239 if (NonSpillCount == 1 && !FeedsTwoAddr) {
1240 // Start by finding the non-store use MachineInstr.
1241 SmallPtrSet<MachineInstr*, 4>::iterator UI = VNUseCount[CurrVN].begin();
1242 int StoreFrameIndex;
1243 unsigned StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1244 while (UI != VNUseCount[CurrVN].end() &&
1245 (StoreVReg == (*LI)->reg && StoreFrameIndex == FrameIndex)) {
1247 if (UI != VNUseCount[CurrVN].end())
1248 StoreVReg = TII->isStoreToStackSlot(*UI, StoreFrameIndex);
1250 if (UI == VNUseCount[CurrVN].end()) continue;
1252 MachineInstr* use = *UI;
1254 // Attempt to fold it away!
1255 int OpIdx = use->findRegisterUseOperandIdx((*LI)->reg, false);
1256 if (OpIdx == -1) continue;
1257 SmallVector<unsigned, 1> Ops;
1258 Ops.push_back(OpIdx);
1259 if (!TII->canFoldMemoryOperand(use, Ops)) continue;
1261 MachineInstr* NewMI = TII->foldMemoryOperand(use, Ops, FrameIndex);
1263 if (!NewMI) continue;
1265 // Update relevant analyses.
1266 LIs->RemoveMachineInstrFromMaps(DefMI);
1267 LIs->ReplaceMachineInstrInMaps(use, NewMI);
1268 (*LI)->removeValNo(CurrVN);
1270 DefMI->eraseFromParent();
1271 use->eraseFromParent();
1272 VNUseCount[CurrVN].erase(use);
1274 // Remove deleted instructions. Note that we need to remove them from
1275 // the VNInfo->use map as well, just to be safe.
1276 for (SmallPtrSet<MachineInstr*, 4>::iterator II =
1277 VNUseCount[CurrVN].begin(), IE = VNUseCount[CurrVN].end();
1279 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1280 VNI = VNUseCount.begin(), VNE = VNUseCount.end(); VNI != VNE;
1282 if (VNI->first != CurrVN)
1283 VNI->second.erase(*II);
1284 LIs->RemoveMachineInstrFromMaps(*II);
1285 (*II)->eraseFromParent();
1288 VNUseCount.erase(CurrVN);
1290 for (DenseMap<VNInfo*, SmallPtrSet<MachineInstr*, 4> >::iterator
1291 VI = VNUseCount.begin(), VE = VNUseCount.end(); VI != VE; ++VI)
1292 if (VI->second.erase(use))
1293 VI->second.insert(NewMI);
1300 // If there's more than one non-store instruction, we can't profitably
1301 // fold it, so bail.
1302 if (NonSpillCount) continue;
1304 // Otherwise, this is a load-store case, so DCE them.
1305 for (SmallPtrSet<MachineInstr*, 4>::iterator UI =
1306 VNUseCount[CurrVN].begin(), UE = VNUseCount[CurrVN].end();
1308 LIs->RemoveMachineInstrFromMaps(*UI);
1309 (*UI)->eraseFromParent();
1312 VNUseCount.erase(CurrVN);
1314 LIs->RemoveMachineInstrFromMaps(DefMI);
1315 (*LI)->removeValNo(CurrVN);
1316 DefMI->eraseFromParent();
1325 bool PreAllocSplitting::createsNewJoin(LiveRange* LR,
1326 MachineBasicBlock* DefMBB,
1327 MachineBasicBlock* BarrierMBB) {
1328 if (DefMBB == BarrierMBB)
1331 if (LR->valno->hasPHIKill())
1334 SlotIndex MBBEnd = LIs->getMBBEndIdx(BarrierMBB);
1335 if (LR->end < MBBEnd)
1338 MachineLoopInfo& MLI = getAnalysis<MachineLoopInfo>();
1339 if (MLI.getLoopFor(DefMBB) != MLI.getLoopFor(BarrierMBB))
1342 MachineDominatorTree& MDT = getAnalysis<MachineDominatorTree>();
1343 SmallPtrSet<MachineBasicBlock*, 4> Visited;
1344 typedef std::pair<MachineBasicBlock*,
1345 MachineBasicBlock::succ_iterator> ItPair;
1346 SmallVector<ItPair, 4> Stack;
1347 Stack.push_back(std::make_pair(BarrierMBB, BarrierMBB->succ_begin()));
1349 while (!Stack.empty()) {
1350 ItPair P = Stack.back();
1353 MachineBasicBlock* PredMBB = P.first;
1354 MachineBasicBlock::succ_iterator S = P.second;
1356 if (S == PredMBB->succ_end())
1358 else if (Visited.count(*S)) {
1359 Stack.push_back(std::make_pair(PredMBB, ++S));
1362 Stack.push_back(std::make_pair(PredMBB, S+1));
1364 MachineBasicBlock* MBB = *S;
1365 Visited.insert(MBB);
1367 if (MBB == BarrierMBB)
1370 MachineDomTreeNode* DefMDTN = MDT.getNode(DefMBB);
1371 MachineDomTreeNode* BarrierMDTN = MDT.getNode(BarrierMBB);
1372 MachineDomTreeNode* MDTN = MDT.getNode(MBB)->getIDom();
1374 if (MDTN == DefMDTN)
1376 else if (MDTN == BarrierMDTN)
1378 MDTN = MDTN->getIDom();
1381 MBBEnd = LIs->getMBBEndIdx(MBB);
1382 if (LR->end > MBBEnd)
1383 Stack.push_back(std::make_pair(MBB, MBB->succ_begin()));
1390 bool PreAllocSplitting::runOnMachineFunction(MachineFunction &MF) {
1392 TM = &MF.getTarget();
1393 TRI = TM->getRegisterInfo();
1394 TII = TM->getInstrInfo();
1395 MFI = MF.getFrameInfo();
1396 MRI = &MF.getRegInfo();
1397 SIs = &getAnalysis<SlotIndexes>();
1398 LIs = &getAnalysis<LiveIntervals>();
1399 LSs = &getAnalysis<LiveStacks>();
1400 VRM = &getAnalysis<VirtRegMap>();
1402 bool MadeChange = false;
1404 // Make sure blocks are numbered in order.
1405 MF.RenumberBlocks();
1407 MachineBasicBlock *Entry = MF.begin();
1408 SmallPtrSet<MachineBasicBlock*,16> Visited;
1410 SmallPtrSet<LiveInterval*, 8> Split;
1412 for (df_ext_iterator<MachineBasicBlock*, SmallPtrSet<MachineBasicBlock*,16> >
1413 DFI = df_ext_begin(Entry, Visited), E = df_ext_end(Entry, Visited);
1416 for (MachineBasicBlock::iterator I = BarrierMBB->begin(),
1417 E = BarrierMBB->end(); I != E; ++I) {
1419 const TargetRegisterClass **BarrierRCs =
1420 Barrier->getDesc().getRegClassBarriers();
1423 BarrierIdx = LIs->getInstructionIndex(Barrier);
1424 MadeChange |= SplitRegLiveIntervals(BarrierRCs, Split);
1428 MadeChange |= removeDeadSpills(Split);