1 //===-- StackColoring.cpp -------------------------------------------------===//
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 pass implements the stack-coloring optimization that looks for
11 // lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END),
12 // which represent the possible lifetime of stack slots. It attempts to
13 // merge disjoint stack slots and reduce the used stack space.
14 // NOTE: This pass is not StackSlotColoring, which optimizes spill slots.
16 // TODO: In the future we plan to improve stack coloring in the following ways:
17 // 1. Allow merging multiple small slots into a single larger slot at different
19 // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
22 //===----------------------------------------------------------------------===//
24 #define DEBUG_TYPE "stackcoloring"
25 #include "MachineTraceMetrics.h"
26 #include "llvm/Function.h"
27 #include "llvm/Module.h"
28 #include "llvm/ADT/BitVector.h"
29 #include "llvm/Analysis/Dominators.h"
30 #include "llvm/Analysis/ValueTracking.h"
31 #include "llvm/ADT/DepthFirstIterator.h"
32 #include "llvm/ADT/PostOrderIterator.h"
33 #include "llvm/ADT/SetVector.h"
34 #include "llvm/ADT/SmallPtrSet.h"
35 #include "llvm/ADT/SparseSet.h"
36 #include "llvm/ADT/Statistic.h"
37 #include "llvm/CodeGen/LiveInterval.h"
38 #include "llvm/CodeGen/MachineLoopInfo.h"
39 #include "llvm/CodeGen/MachineBranchProbabilityInfo.h"
40 #include "llvm/CodeGen/MachineDominators.h"
41 #include "llvm/CodeGen/MachineBasicBlock.h"
42 #include "llvm/CodeGen/MachineFunctionPass.h"
43 #include "llvm/CodeGen/MachineLoopInfo.h"
44 #include "llvm/CodeGen/MachineModuleInfo.h"
45 #include "llvm/CodeGen/MachineRegisterInfo.h"
46 #include "llvm/CodeGen/MachineFrameInfo.h"
47 #include "llvm/CodeGen/MachineMemOperand.h"
48 #include "llvm/CodeGen/Passes.h"
49 #include "llvm/CodeGen/SlotIndexes.h"
50 #include "llvm/DebugInfo.h"
51 #include "llvm/MC/MCInstrItineraries.h"
52 #include "llvm/Target/TargetInstrInfo.h"
53 #include "llvm/Target/TargetRegisterInfo.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
61 DisableColoring("no-stack-coloring",
62 cl::init(false), cl::Hidden,
63 cl::desc("Disable stack coloring"));
66 CheckEscapedAllocas("stack-coloring-check-escaped",
67 cl::init(true), cl::Hidden,
68 cl::desc("Look for allocas which escaped the lifetime region"));
70 STATISTIC(NumMarkerSeen, "Number of lifetime markers found.");
71 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots.");
72 STATISTIC(StackSlotMerged, "Number of stack slot merged.");
73 STATISTIC(EscapedAllocas,
74 "Number of allocas that escaped the lifetime region");
76 //===----------------------------------------------------------------------===//
78 //===----------------------------------------------------------------------===//
81 /// StackColoring - A machine pass for merging disjoint stack allocations,
82 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
83 class StackColoring : public MachineFunctionPass {
84 MachineFrameInfo *MFI;
87 /// A class representing liveness information for a single basic block.
88 /// Each bit in the BitVector represents the liveness property
89 /// for a different stack slot.
90 struct BlockLifetimeInfo {
91 /// Which slots BEGINs in each basic block.
93 /// Which slots ENDs in each basic block.
95 /// Which slots are marked as LIVE_IN, coming into each basic block.
97 /// Which slots are marked as LIVE_OUT, coming out of each basic block.
101 /// Maps active slots (per bit) for each basic block.
102 DenseMap<MachineBasicBlock*, BlockLifetimeInfo> BlockLiveness;
104 /// Maps serial numbers to basic blocks.
105 DenseMap<MachineBasicBlock*, int> BasicBlocks;
106 /// Maps basic blocks to a serial number.
107 SmallVector<MachineBasicBlock*, 8> BasicBlockNumbering;
109 /// Maps liveness intervals for each slot.
110 SmallVector<LiveInterval*, 16> Intervals;
111 /// VNInfo is used for the construction of LiveIntervals.
112 VNInfo::Allocator VNInfoAllocator;
113 /// SlotIndex analysis object.
114 SlotIndexes *Indexes;
116 /// The list of lifetime markers found. These markers are to be removed
117 /// once the coloring is done.
118 SmallVector<MachineInstr*, 8> Markers;
120 /// SlotSizeSorter - A Sort utility for arranging stack slots according
122 struct SlotSizeSorter {
123 MachineFrameInfo *MFI;
124 SlotSizeSorter(MachineFrameInfo *mfi) : MFI(mfi) { }
125 bool operator()(int LHS, int RHS) {
126 // We use -1 to denote a uninteresting slot. Place these slots at the end.
127 if (LHS == -1) return false;
128 if (RHS == -1) return true;
129 // Sort according to size.
130 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
136 StackColoring() : MachineFunctionPass(ID) {
137 initializeStackColoringPass(*PassRegistry::getPassRegistry());
139 void getAnalysisUsage(AnalysisUsage &AU) const;
140 bool runOnMachineFunction(MachineFunction &MF);
146 /// Removes all of the lifetime marker instructions from the function.
147 /// \returns true if any markers were removed.
148 bool removeAllMarkers();
150 /// Scan the machine function and find all of the lifetime markers.
151 /// Record the findings in the BEGIN and END vectors.
152 /// \returns the number of markers found.
153 unsigned collectMarkers(unsigned NumSlot);
155 /// Perform the dataflow calculation and calculate the lifetime for each of
156 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
157 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
158 /// in and out blocks.
159 void calculateLocalLiveness();
161 /// Construct the LiveIntervals for the slots.
162 void calculateLiveIntervals(unsigned NumSlots);
164 /// Go over the machine function and change instructions which use stack
165 /// slots to use the joint slots.
166 void remapInstructions(DenseMap<int, int> &SlotRemap);
168 /// The input program may contain intructions which are not inside lifetime
169 /// markers. This can happen due to a bug in the compiler or due to a bug in
170 /// user code (for example, returning a reference to a local variable).
171 /// This procedure checks all of the instructions in the function and
172 /// invalidates lifetime ranges which do not contain all of the instructions
173 /// which access that frame slot.
174 void removeInvalidSlotRanges();
176 /// Map entries which point to other entries to their destination.
177 /// A->B->C becomes A->C.
178 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
180 } // end anonymous namespace
182 char StackColoring::ID = 0;
183 char &llvm::StackColoringID = StackColoring::ID;
185 INITIALIZE_PASS_BEGIN(StackColoring,
186 "stack-coloring", "Merge disjoint stack slots", false, false)
187 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
188 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
189 INITIALIZE_PASS_END(StackColoring,
190 "stack-coloring", "Merge disjoint stack slots", false, false)
192 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
193 AU.addRequired<MachineDominatorTree>();
194 AU.addPreserved<MachineDominatorTree>();
195 AU.addRequired<SlotIndexes>();
196 MachineFunctionPass::getAnalysisUsage(AU);
199 void StackColoring::dump() {
200 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
202 unsigned Num = BasicBlocks[*FI];
203 DEBUG(dbgs()<<"Inspecting block #"<<Num<<" ["<<FI->getName()<<"]\n");
205 DEBUG(dbgs()<<"BEGIN : {");
206 for (unsigned i=0; i < BlockLiveness[*FI].Begin.size(); ++i)
207 DEBUG(dbgs()<<BlockLiveness[*FI].Begin.test(i)<<" ");
208 DEBUG(dbgs()<<"}\n");
210 DEBUG(dbgs()<<"END : {");
211 for (unsigned i=0; i < BlockLiveness[*FI].End.size(); ++i)
212 DEBUG(dbgs()<<BlockLiveness[*FI].End.test(i)<<" ");
214 DEBUG(dbgs()<<"}\n");
216 DEBUG(dbgs()<<"LIVE_IN: {");
217 for (unsigned i=0; i < BlockLiveness[*FI].LiveIn.size(); ++i)
218 DEBUG(dbgs()<<BlockLiveness[*FI].LiveIn.test(i)<<" ");
220 DEBUG(dbgs()<<"}\n");
221 DEBUG(dbgs()<<"LIVEOUT: {");
222 for (unsigned i=0; i < BlockLiveness[*FI].LiveOut.size(); ++i)
223 DEBUG(dbgs()<<BlockLiveness[*FI].LiveOut.test(i)<<" ");
224 DEBUG(dbgs()<<"}\n");
228 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
229 unsigned MarkersFound = 0;
230 // Scan the function to find all lifetime markers.
231 // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a
232 // deterministic numbering, and because we'll need a post-order iteration
233 // later for solving the liveness dataflow problem.
234 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
237 // Assign a serial number to this basic block.
238 BasicBlocks[*FI] = BasicBlockNumbering.size();
239 BasicBlockNumbering.push_back(*FI);
241 BlockLiveness[*FI].Begin.resize(NumSlot);
242 BlockLiveness[*FI].End.resize(NumSlot);
244 for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
247 if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
248 BI->getOpcode() != TargetOpcode::LIFETIME_END)
251 Markers.push_back(BI);
253 bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
254 MachineOperand &MI = BI->getOperand(0);
255 unsigned Slot = MI.getIndex();
259 const Value *Allocation = MFI->getObjectAllocation(Slot);
261 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<<
262 " with allocation: "<< Allocation->getName()<<"\n");
266 BlockLiveness[*FI].Begin.set(Slot);
268 if (BlockLiveness[*FI].Begin.test(Slot)) {
269 // Allocas that start and end within a single block are handled
270 // specially when computing the LiveIntervals to avoid pessimizing
271 // the liveness propagation.
272 BlockLiveness[*FI].Begin.reset(Slot);
274 BlockLiveness[*FI].End.set(Slot);
280 // Update statistics.
281 NumMarkerSeen += MarkersFound;
285 void StackColoring::calculateLocalLiveness() {
286 // Perform a standard reverse dataflow computation to solve for
287 // global liveness. The BEGIN set here is equivalent to KILL in the standard
288 // formulation, and END is equivalent to GEN. The result of this computation
289 // is a map from blocks to bitvectors where the bitvectors represent which
290 // allocas are live in/out of that block.
291 SmallPtrSet<MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
292 BasicBlockNumbering.end());
293 unsigned NumSSMIters = 0;
299 SmallPtrSet<MachineBasicBlock*, 8> NextBBSet;
301 for (SmallVector<MachineBasicBlock*, 8>::iterator
302 PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
305 MachineBasicBlock *BB = *PI;
306 if (!BBSet.count(BB)) continue;
308 BitVector LocalLiveIn;
309 BitVector LocalLiveOut;
311 // Forward propagation from begins to ends.
312 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
313 PE = BB->pred_end(); PI != PE; ++PI)
314 LocalLiveIn |= BlockLiveness[*PI].LiveOut;
315 LocalLiveIn |= BlockLiveness[BB].End;
316 LocalLiveIn.reset(BlockLiveness[BB].Begin);
318 // Reverse propagation from ends to begins.
319 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
320 SE = BB->succ_end(); SI != SE; ++SI)
321 LocalLiveOut |= BlockLiveness[*SI].LiveIn;
322 LocalLiveOut |= BlockLiveness[BB].Begin;
323 LocalLiveOut.reset(BlockLiveness[BB].End);
325 LocalLiveIn |= LocalLiveOut;
326 LocalLiveOut |= LocalLiveIn;
328 // After adopting the live bits, we need to turn-off the bits which
329 // are de-activated in this block.
330 LocalLiveOut.reset(BlockLiveness[BB].End);
331 LocalLiveIn.reset(BlockLiveness[BB].Begin);
333 // If we have both BEGIN and END markers in the same basic block then
334 // we know that the BEGIN marker comes after the END, because we already
335 // handle the case where the BEGIN comes before the END when collecting
336 // the markers (and building the BEGIN/END vectore).
337 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
338 // BEGIN and END because it means that the value lives before and after
340 BitVector LocalEndBegin = BlockLiveness[BB].End;
341 LocalEndBegin &= BlockLiveness[BB].Begin;
342 LocalLiveIn |= LocalEndBegin;
343 LocalLiveOut |= LocalEndBegin;
345 if (LocalLiveIn.test(BlockLiveness[BB].LiveIn)) {
347 BlockLiveness[BB].LiveIn |= LocalLiveIn;
349 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
350 PE = BB->pred_end(); PI != PE; ++PI)
351 NextBBSet.insert(*PI);
354 if (LocalLiveOut.test(BlockLiveness[BB].LiveOut)) {
356 BlockLiveness[BB].LiveOut |= LocalLiveOut;
358 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
359 SE = BB->succ_end(); SI != SE; ++SI)
360 NextBBSet.insert(*SI);
368 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
369 SmallVector<SlotIndex, 16> Starts;
370 SmallVector<SlotIndex, 16> Finishes;
372 // For each block, find which slots are active within this block
373 // and update the live intervals.
374 for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end();
375 MBB != MBBe; ++MBB) {
377 Starts.resize(NumSlots);
379 Finishes.resize(NumSlots);
381 // Create the interval for the basic blocks with lifetime markers in them.
382 for (SmallVector<MachineInstr*, 8>::iterator it = Markers.begin(),
383 e = Markers.end(); it != e; ++it) {
384 MachineInstr *MI = *it;
385 if (MI->getParent() != MBB)
388 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
389 MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
390 "Invalid Lifetime marker");
392 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
393 MachineOperand &Mo = MI->getOperand(0);
394 int Slot = Mo.getIndex();
395 assert(Slot >= 0 && "Invalid slot");
397 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
400 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
401 Starts[Slot] = ThisIndex;
403 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
404 Finishes[Slot] = ThisIndex;
408 // Create the interval of the blocks that we previously found to be 'alive'.
409 BitVector Alive = BlockLiveness[MBB].LiveIn;
410 Alive |= BlockLiveness[MBB].LiveOut;
413 for (int pos = Alive.find_first(); pos != -1;
414 pos = Alive.find_next(pos)) {
415 if (!Starts[pos].isValid())
416 Starts[pos] = Indexes->getMBBStartIdx(MBB);
417 if (!Finishes[pos].isValid())
418 Finishes[pos] = Indexes->getMBBEndIdx(MBB);
422 for (unsigned i = 0; i < NumSlots; ++i) {
423 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
424 if (!Starts[i].isValid())
427 assert(Starts[i] && Finishes[i] && "Invalid interval");
428 VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
429 SlotIndex S = Starts[i];
430 SlotIndex F = Finishes[i];
432 // We have a single consecutive region.
433 Intervals[i]->addRange(LiveRange(S, F, ValNum));
435 // We have two non consecutive regions. This happens when
436 // LIFETIME_START appears after the LIFETIME_END marker.
437 SlotIndex NewStart = Indexes->getMBBStartIdx(MBB);
438 SlotIndex NewFin = Indexes->getMBBEndIdx(MBB);
439 Intervals[i]->addRange(LiveRange(NewStart, F, ValNum));
440 Intervals[i]->addRange(LiveRange(S, NewFin, ValNum));
446 bool StackColoring::removeAllMarkers() {
448 for (unsigned i = 0; i < Markers.size(); ++i) {
449 Markers[i]->eraseFromParent();
454 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
458 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
459 unsigned FixedInstr = 0;
460 unsigned FixedMemOp = 0;
461 unsigned FixedDbg = 0;
462 MachineModuleInfo *MMI = &MF->getMMI();
464 // Remap debug information that refers to stack slots.
465 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
466 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
467 VE = VMap.end(); VI != VE; ++VI) {
468 const MDNode *Var = VI->first;
470 std::pair<unsigned, DebugLoc> &VP = VI->second;
471 if (SlotRemap.count(VP.first)) {
472 DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n");
473 VP.first = SlotRemap[VP.first];
478 // Keep a list of *allocas* which need to be remapped.
479 DenseMap<const Value*, const Value*> Allocas;
480 for (DenseMap<int, int>::iterator it = SlotRemap.begin(),
481 e = SlotRemap.end(); it != e; ++it) {
482 const Value *From = MFI->getObjectAllocation(it->first);
483 const Value *To = MFI->getObjectAllocation(it->second);
484 assert(To && From && "Invalid allocation object");
488 // Remap all instructions to the new stack slots.
489 MachineFunction::iterator BB, BBE;
490 MachineBasicBlock::iterator I, IE;
491 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
492 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
494 // Skip lifetime markers. We'll remove them soon.
495 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
496 I->getOpcode() == TargetOpcode::LIFETIME_END)
499 // Update the MachineMemOperand to use the new alloca.
500 for (MachineInstr::mmo_iterator MM = I->memoperands_begin(),
501 E = I->memoperands_end(); MM != E; ++MM) {
502 MachineMemOperand *MMO = *MM;
504 const Value *V = MMO->getValue();
509 // Climb up and find the original alloca.
510 V = GetUnderlyingObject(V);
511 // If we did not find one, or if the one that we found is not in our
512 // map, then move on.
513 if (!V || !Allocas.count(V))
516 MMO->setValue(Allocas[V]);
520 // Update all of the machine instruction operands.
521 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
522 MachineOperand &MO = I->getOperand(i);
526 int FromSlot = MO.getIndex();
528 // Don't touch arguments.
532 // Only look at mapped slots.
533 if (!SlotRemap.count(FromSlot))
536 // In a debug build, check that the instruction that we are modifying is
537 // inside the expected live range. If the instruction is not inside
538 // the calculated range then it means that the alloca usage moved
539 // outside of the lifetime markers.
540 // NOTE: Alloca address calculations which happen outside the lifetime
541 // zone are are okay, despite the fact that we don't have a good way
542 // for validating all of the usages of the calculation.
544 bool TouchesMemory = I->mayLoad() || I->mayStore();
545 if (!I->isDebugValue() && TouchesMemory) {
546 SlotIndex Index = Indexes->getInstructionIndex(I);
547 LiveInterval *Interval = Intervals[FromSlot];
548 assert(Interval->find(Index) != Interval->end() &&
549 "Found instruction usage outside of live range.");
553 // Fix the machine instructions.
554 int ToSlot = SlotRemap[FromSlot];
560 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
561 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
562 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
565 void StackColoring::removeInvalidSlotRanges() {
566 MachineFunction::iterator BB, BBE;
567 MachineBasicBlock::iterator I, IE;
568 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
569 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
571 if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
572 I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
575 // Some intervals are suspicious! In some cases we find address
576 // calculations outside of the lifetime zone, but not actual memory
577 // read or write. Memory accesses outside of the lifetime zone are a clear
578 // violation, but address calculations are okay. This can happen when
579 // GEPs are hoisted outside of the lifetime zone.
580 // So, in here we only check instrucitons which can read or write memory.
581 if (!I->mayLoad() && !I->mayStore())
584 // Check all of the machine operands.
585 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) {
586 MachineOperand &MO = I->getOperand(i);
591 int Slot = MO.getIndex();
596 if (Intervals[Slot]->empty())
599 // Check that the used slot is inside the calculated lifetime range.
600 // If it is not, warn about it and invalidate the range.
601 LiveInterval *Interval = Intervals[Slot];
602 SlotIndex Index = Indexes->getInstructionIndex(I);
603 if (Interval->find(Index) == Interval->end()) {
604 Intervals[Slot]->clear();
605 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
612 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
614 // Expunge slot remap map.
615 for (unsigned i=0; i < NumSlots; ++i) {
616 // If we are remapping i
617 if (SlotRemap.count(i)) {
618 int Target = SlotRemap[i];
619 // As long as our target is mapped to something else, follow it.
620 while (SlotRemap.count(Target)) {
621 Target = SlotRemap[Target];
622 SlotRemap[i] = Target;
628 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
629 DEBUG(dbgs() << "********** Stack Coloring **********\n"
630 << "********** Function: "
631 << ((const Value*)Func.getFunction())->getName() << '\n');
633 MFI = MF->getFrameInfo();
634 Indexes = &getAnalysis<SlotIndexes>();
635 BlockLiveness.clear();
637 BasicBlockNumbering.clear();
640 VNInfoAllocator.Reset();
642 unsigned NumSlots = MFI->getObjectIndexEnd();
644 // If there are no stack slots then there are no markers to remove.
648 SmallVector<int, 8> SortedSlots;
650 SortedSlots.reserve(NumSlots);
651 Intervals.reserve(NumSlots);
653 unsigned NumMarkers = collectMarkers(NumSlots);
655 unsigned TotalSize = 0;
656 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
657 DEBUG(dbgs()<<"Slot structure:\n");
659 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
660 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
661 TotalSize += MFI->getObjectSize(i);
664 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
666 // Don't continue because there are not enough lifetime markers, or the
667 // stack is too small, or we are told not to optimize the slots.
668 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
669 DEBUG(dbgs()<<"Will not try to merge slots.\n");
670 return removeAllMarkers();
673 for (unsigned i=0; i < NumSlots; ++i) {
674 LiveInterval *LI = new LiveInterval(i, 0);
675 Intervals.push_back(LI);
676 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
677 SortedSlots.push_back(i);
680 // Calculate the liveness of each block.
681 calculateLocalLiveness();
683 // Propagate the liveness information.
684 calculateLiveIntervals(NumSlots);
686 // Search for allocas which are used outside of the declared lifetime
688 if (CheckEscapedAllocas)
689 removeInvalidSlotRanges();
691 // Maps old slots to new slots.
692 DenseMap<int, int> SlotRemap;
693 unsigned RemovedSlots = 0;
694 unsigned ReducedSize = 0;
696 // Do not bother looking at empty intervals.
697 for (unsigned I = 0; I < NumSlots; ++I) {
698 if (Intervals[SortedSlots[I]]->empty())
702 // This is a simple greedy algorithm for merging allocas. First, sort the
703 // slots, placing the largest slots first. Next, perform an n^2 scan and look
704 // for disjoint slots. When you find disjoint slots, merge the samller one
705 // into the bigger one and update the live interval. Remove the small alloca
708 // Sort the slots according to their size. Place unused slots at the end.
709 std::sort(SortedSlots.begin(), SortedSlots.end(), SlotSizeSorter(MFI));
714 for (unsigned I = 0; I < NumSlots; ++I) {
715 if (SortedSlots[I] == -1)
718 for (unsigned J=I+1; J < NumSlots; ++J) {
719 if (SortedSlots[J] == -1)
722 int FirstSlot = SortedSlots[I];
723 int SecondSlot = SortedSlots[J];
724 LiveInterval *First = Intervals[FirstSlot];
725 LiveInterval *Second = Intervals[SecondSlot];
726 assert (!First->empty() && !Second->empty() && "Found an empty range");
728 // Merge disjoint slots.
729 if (!First->overlaps(*Second)) {
731 First->MergeRangesInAsValue(*Second, First->getValNumInfo(0));
732 SlotRemap[SecondSlot] = FirstSlot;
734 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
735 SecondSlot<<" together.\n");
736 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
737 MFI->getObjectAlignment(SecondSlot));
739 assert(MFI->getObjectSize(FirstSlot) >=
740 MFI->getObjectSize(SecondSlot) &&
741 "Merging a small object into a larger one");
744 ReducedSize += MFI->getObjectSize(SecondSlot);
745 MFI->setObjectAlignment(FirstSlot, MaxAlignment);
746 MFI->RemoveStackObject(SecondSlot);
752 // Record statistics.
753 StackSpaceSaved += ReducedSize;
754 StackSlotMerged += RemovedSlots;
755 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
756 ReducedSize<<" bytes\n");
758 // Scan the entire function and update all machine operands that use frame
759 // indices to use the remapped frame index.
760 expungeSlotMap(SlotRemap, NumSlots);
761 remapInstructions(SlotRemap);
763 // Release the intervals.
764 for (unsigned I = 0; I < NumSlots; ++I) {
768 return removeAllMarkers();