Add a flag to disable the code that looks for allocas which escaped the lifetime...
[oota-llvm.git] / lib / CodeGen / StackColoring.cpp
1 //===-- StackColoring.cpp -------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
15 //
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
18 //    offsets.
19 // 2. Merge this pass with StackSlotColoring and allow merging of allocas with
20 //    spill slots.
21 //
22 //===----------------------------------------------------------------------===//
23
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"
57
58 using namespace llvm;
59
60 static cl::opt<bool>
61 DisableColoring("no-stack-coloring",
62         cl::init(false), cl::Hidden,
63         cl::desc("Disable stack coloring"));
64
65 static cl::opt<bool>
66 CheckEscapedAllocas("stack-coloring-check-escaped",
67         cl::init(true), cl::Hidden,
68         cl::desc("Look for allocas which escaped the lifetime region"));
69
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");
75
76
77 //===----------------------------------------------------------------------===//
78 //                           StackColoring Pass
79 //===----------------------------------------------------------------------===//
80
81 namespace {
82 /// StackColoring - A machine pass for merging disjoint stack allocations,
83 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions.
84 class StackColoring : public MachineFunctionPass {
85   MachineFrameInfo *MFI;
86   MachineFunction *MF;
87
88   /// A class representing liveness information for a single basic block.
89   /// Each bit in the BitVector represents the liveness property
90   /// for a different stack slot.
91   struct BlockLifetimeInfo {
92     /// Which slots BEGINs in each basic block.
93     BitVector Begin;
94     /// Which slots ENDs in each basic block.
95     BitVector End;
96     /// Which slots are marked as LIVE_IN, coming into each basic block.
97     BitVector LiveIn;
98     /// Which slots are marked as LIVE_OUT, coming out of each basic block.
99     BitVector LiveOut;
100   };
101
102   /// Maps active slots (per bit) for each basic block.
103   DenseMap<MachineBasicBlock*, BlockLifetimeInfo> BlockLiveness;
104
105   /// Maps serial numbers to basic blocks.
106   DenseMap<MachineBasicBlock*, int> BasicBlocks;
107   /// Maps basic blocks to a serial number.
108   SmallVector<MachineBasicBlock*, 8> BasicBlockNumbering;
109
110   /// Maps liveness intervals for each slot.
111   SmallVector<LiveInterval*, 16> Intervals;
112   /// VNInfo is used for the construction of LiveIntervals.
113   VNInfo::Allocator VNInfoAllocator;
114   /// SlotIndex analysis object.
115   SlotIndexes *Indexes;
116
117   /// The list of lifetime markers found. These markers are to be removed
118   /// once the coloring is done.
119   SmallVector<MachineInstr*, 8> Markers;
120
121   /// SlotSizeSorter - A Sort utility for arranging stack slots according
122   /// to their size.
123   struct SlotSizeSorter {
124     MachineFrameInfo *MFI;
125     SlotSizeSorter(MachineFrameInfo *mfi) : MFI(mfi) { }
126     bool operator()(int LHS, int RHS) {
127       // We use -1 to denote a uninteresting slot. Place these slots at the end.
128       if (LHS == -1) return false;
129       if (RHS == -1) return true;
130       // Sort according to size.
131       return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS);
132   }
133 };
134
135 public:
136   static char ID;
137   StackColoring() : MachineFunctionPass(ID) {
138     initializeStackColoringPass(*PassRegistry::getPassRegistry());
139   }
140   void getAnalysisUsage(AnalysisUsage &AU) const;
141   bool runOnMachineFunction(MachineFunction &MF);
142
143 private:
144   /// Debug.
145   void dump();
146
147   /// Removes all of the lifetime marker instructions from the function.
148   /// \returns true if any markers were removed.
149   bool removeAllMarkers();
150
151   /// Scan the machine function and find all of the lifetime markers.
152   /// Record the findings in the BEGIN and END vectors.
153   /// \returns the number of markers found.
154   unsigned collectMarkers(unsigned NumSlot);
155
156   /// Perform the dataflow calculation and calculate the lifetime for each of
157   /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and
158   /// LifetimeLIVE_OUT maps that represent which stack slots are live coming
159   /// in and out blocks.
160   void calculateLocalLiveness();
161
162   /// Construct the LiveIntervals for the slots.
163   void calculateLiveIntervals(unsigned NumSlots);
164
165   /// Go over the machine function and change instructions which use stack
166   /// slots to use the joint slots.
167   void remapInstructions(DenseMap<int, int> &SlotRemap);
168
169   /// The input program may contain intructions which are not inside lifetime
170   /// markers. This can happen due to a bug in the compiler or due to a bug in
171   /// user code (for example, returning a reference to a local variable).
172   /// This procedure checks all of the instructions in the function and
173   /// invalidates lifetime ranges which do not contain all of the instructions
174   /// which access that frame slot.
175   void removeInvalidSlotRanges();
176
177   /// Map entries which point to other entries to their destination.
178   ///   A->B->C becomes A->C.
179    void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots);
180 };
181 } // end anonymous namespace
182
183 char StackColoring::ID = 0;
184 char &llvm::StackColoringID = StackColoring::ID;
185
186 INITIALIZE_PASS_BEGIN(StackColoring,
187                    "stack-coloring", "Merge disjoint stack slots", false, false)
188 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
189 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
190 INITIALIZE_PASS_END(StackColoring,
191                    "stack-coloring", "Merge disjoint stack slots", false, false)
192
193 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const {
194   AU.addRequired<MachineDominatorTree>();
195   AU.addPreserved<MachineDominatorTree>();
196   AU.addRequired<SlotIndexes>();
197   MachineFunctionPass::getAnalysisUsage(AU);
198 }
199
200 void StackColoring::dump() {
201   for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
202        FI != FE; ++FI) {
203     unsigned Num = BasicBlocks[*FI];
204     DEBUG(dbgs()<<"Inspecting block #"<<Num<<" ["<<FI->getName()<<"]\n");
205     Num = 0;
206     DEBUG(dbgs()<<"BEGIN  : {");
207     for (unsigned i=0; i < BlockLiveness[*FI].Begin.size(); ++i)
208       DEBUG(dbgs()<<BlockLiveness[*FI].Begin.test(i)<<" ");
209     DEBUG(dbgs()<<"}\n");
210
211     DEBUG(dbgs()<<"END    : {");
212     for (unsigned i=0; i < BlockLiveness[*FI].End.size(); ++i)
213       DEBUG(dbgs()<<BlockLiveness[*FI].End.test(i)<<" ");
214
215     DEBUG(dbgs()<<"}\n");
216
217     DEBUG(dbgs()<<"LIVE_IN: {");
218     for (unsigned i=0; i < BlockLiveness[*FI].LiveIn.size(); ++i)
219       DEBUG(dbgs()<<BlockLiveness[*FI].LiveIn.test(i)<<" ");
220
221     DEBUG(dbgs()<<"}\n");
222     DEBUG(dbgs()<<"LIVEOUT: {");
223     for (unsigned i=0; i < BlockLiveness[*FI].LiveOut.size(); ++i)
224       DEBUG(dbgs()<<BlockLiveness[*FI].LiveOut.test(i)<<" ");
225     DEBUG(dbgs()<<"}\n");
226   }
227 }
228
229 unsigned StackColoring::collectMarkers(unsigned NumSlot) {
230   unsigned MarkersFound = 0;
231   // Scan the function to find all lifetime markers.
232   // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a
233   // deterministic numbering, and because we'll need a post-order iteration
234   // later for solving the liveness dataflow problem.
235   for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF);
236        FI != FE; ++FI) {
237
238     // Assign a serial number to this basic block.
239     BasicBlocks[*FI] = BasicBlockNumbering.size();
240     BasicBlockNumbering.push_back(*FI);
241
242     BlockLiveness[*FI].Begin.resize(NumSlot);
243     BlockLiveness[*FI].End.resize(NumSlot);
244
245     for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end();
246          BI != BE; ++BI) {
247
248       if (BI->getOpcode() != TargetOpcode::LIFETIME_START &&
249           BI->getOpcode() != TargetOpcode::LIFETIME_END)
250         continue;
251
252       Markers.push_back(BI);
253
254       bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START;
255       MachineOperand &MI = BI->getOperand(0);
256       unsigned Slot = MI.getIndex();
257
258       MarkersFound++;
259
260       const Value *Allocation = MFI->getObjectAllocation(Slot);
261       if (Allocation) {
262         DEBUG(dbgs()<<"Found lifetime marker for allocation: "<<
263               Allocation->getName()<<"\n");
264       }
265
266       if (IsStart) {
267         BlockLiveness[*FI].Begin.set(Slot);
268       } else {
269         if (BlockLiveness[*FI].Begin.test(Slot)) {
270           // Allocas that start and end within a single block are handled
271           // specially when computing the LiveIntervals to avoid pessimizing
272           // the liveness propagation.
273           BlockLiveness[*FI].Begin.reset(Slot);
274         } else {
275           BlockLiveness[*FI].End.set(Slot);
276         }
277       }
278     }
279   }
280
281   // Update statistics.
282   NumMarkerSeen += MarkersFound;
283   return MarkersFound;
284 }
285
286 void StackColoring::calculateLocalLiveness() {
287   // Perform a standard reverse dataflow computation to solve for
288   // global liveness.  The BEGIN set here is equivalent to KILL in the standard
289   // formulation, and END is equivalent to GEN.  The result of this computation
290   // is a map from blocks to bitvectors where the bitvectors represent which
291   // allocas are live in/out of that block.
292   SmallPtrSet<MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(),
293                                            BasicBlockNumbering.end());
294   unsigned NumSSMIters = 0;
295   bool changed = true;
296   while (changed) {
297     changed = false;
298     ++NumSSMIters;
299
300     SmallPtrSet<MachineBasicBlock*, 8> NextBBSet;
301
302     for (SmallVector<MachineBasicBlock*, 8>::iterator
303          PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end();
304          PI != PE; ++PI) {
305
306       MachineBasicBlock *BB = *PI;
307       if (!BBSet.count(BB)) continue;
308
309       BitVector LocalLiveIn;
310       BitVector LocalLiveOut;
311
312       // Forward propagation from begins to ends.
313       for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
314            PE = BB->pred_end(); PI != PE; ++PI)
315         LocalLiveIn |= BlockLiveness[*PI].LiveOut;
316       LocalLiveIn |= BlockLiveness[BB].End;
317       LocalLiveIn.reset(BlockLiveness[BB].Begin);
318
319       // Reverse propagation from ends to begins.
320       for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
321            SE = BB->succ_end(); SI != SE; ++SI)
322         LocalLiveOut |= BlockLiveness[*SI].LiveIn;
323       LocalLiveOut |= BlockLiveness[BB].Begin;
324       LocalLiveOut.reset(BlockLiveness[BB].End);
325
326       LocalLiveIn |= LocalLiveOut;
327       LocalLiveOut |= LocalLiveIn;
328
329       // After adopting the live bits, we need to turn-off the bits which
330       // are de-activated in this block.
331       LocalLiveOut.reset(BlockLiveness[BB].End);
332       LocalLiveIn.reset(BlockLiveness[BB].Begin);
333
334       // If we have both BEGIN and END markers in the same basic block then
335       // we know that the BEGIN marker comes after the END, because we already
336       // handle the case where the BEGIN comes before the END when collecting
337       // the markers (and building the BEGIN/END vectore).
338       // Want to enable the LIVE_IN and LIVE_OUT of slots that have both
339       // BEGIN and END because it means that the value lives before and after
340       // this basic block.
341       BitVector LocalEndBegin = BlockLiveness[BB].End;
342       LocalEndBegin &= BlockLiveness[BB].Begin;
343       LocalLiveIn |= LocalEndBegin;
344       LocalLiveOut |= LocalEndBegin;
345
346       if (LocalLiveIn.test(BlockLiveness[BB].LiveIn)) {
347         changed = true;
348         BlockLiveness[BB].LiveIn |= LocalLiveIn;
349
350         for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(),
351              PE = BB->pred_end(); PI != PE; ++PI)
352           NextBBSet.insert(*PI);
353       }
354
355       if (LocalLiveOut.test(BlockLiveness[BB].LiveOut)) {
356         changed = true;
357         BlockLiveness[BB].LiveOut |= LocalLiveOut;
358
359         for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(),
360              SE = BB->succ_end(); SI != SE; ++SI)
361           NextBBSet.insert(*SI);
362       }
363     }
364
365     BBSet = NextBBSet;
366   }// while changed.
367 }
368
369 void StackColoring::calculateLiveIntervals(unsigned NumSlots) {
370   SmallVector<SlotIndex, 16> Starts;
371   SmallVector<SlotIndex, 16> Finishes;
372
373   // For each block, find which slots are active within this block
374   // and update the live intervals.
375   for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end();
376        MBB != MBBe; ++MBB) {
377     Starts.clear();
378     Starts.resize(NumSlots);
379     Finishes.clear();
380     Finishes.resize(NumSlots);
381
382     // Create the interval for the basic blocks with lifetime markers in them.
383     for (SmallVector<MachineInstr*, 8>::iterator it = Markers.begin(),
384          e = Markers.end(); it != e; ++it) {
385       MachineInstr *MI = *it;
386       if (MI->getParent() != MBB)
387         continue;
388
389       assert((MI->getOpcode() == TargetOpcode::LIFETIME_START ||
390               MI->getOpcode() == TargetOpcode::LIFETIME_END) &&
391              "Invalid Lifetime marker");
392
393       bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START;
394       MachineOperand &Mo = MI->getOperand(0);
395       int Slot = Mo.getIndex();
396       assert(Slot >= 0 && "Invalid slot");
397
398       SlotIndex ThisIndex = Indexes->getInstructionIndex(MI);
399
400       if (IsStart) {
401         if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex)
402           Starts[Slot] = ThisIndex;
403       } else {
404         if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex)
405           Finishes[Slot] = ThisIndex;
406       }
407     }
408
409     // Create the interval of the blocks that we previously found to be 'alive'.
410     BitVector Alive = BlockLiveness[MBB].LiveIn;
411     Alive |= BlockLiveness[MBB].LiveOut;
412
413     if (Alive.any()) {
414       for (int pos = Alive.find_first(); pos != -1;
415            pos = Alive.find_next(pos)) {
416         if (!Starts[pos].isValid())
417           Starts[pos] = Indexes->getMBBStartIdx(MBB);
418         if (!Finishes[pos].isValid())
419           Finishes[pos] = Indexes->getMBBEndIdx(MBB);
420       }
421     }
422
423     for (unsigned i = 0; i < NumSlots; ++i) {
424       assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range");
425       if (!Starts[i].isValid())
426         continue;
427
428       assert(Starts[i] && Finishes[i] && "Invalid interval");
429       VNInfo *ValNum = Intervals[i]->getValNumInfo(0);
430       SlotIndex S = Starts[i];
431       SlotIndex F = Finishes[i];
432       if (S < F) {
433         // We have a single consecutive region.
434         Intervals[i]->addRange(LiveRange(S, F, ValNum));
435       } else {
436         // We have two non consecutive regions. This happens when
437         // LIFETIME_START appears after the LIFETIME_END marker.
438         SlotIndex NewStart = Indexes->getMBBStartIdx(MBB);
439         SlotIndex NewFin = Indexes->getMBBEndIdx(MBB);
440         Intervals[i]->addRange(LiveRange(NewStart, F, ValNum));
441         Intervals[i]->addRange(LiveRange(S, NewFin, ValNum));
442       }
443     }
444   }
445 }
446
447 bool StackColoring::removeAllMarkers() {
448   unsigned Count = 0;
449   for (unsigned i = 0; i < Markers.size(); ++i) {
450     Markers[i]->eraseFromParent();
451     Count++;
452   }
453   Markers.clear();
454
455   DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n");
456   return Count;
457 }
458
459 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) {
460   unsigned FixedInstr = 0;
461   unsigned FixedMemOp = 0;
462   unsigned FixedDbg = 0;
463   MachineModuleInfo *MMI = &MF->getMMI();
464
465   // Remap debug information that refers to stack slots.
466   MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo();
467   for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(),
468        VE = VMap.end(); VI != VE; ++VI) {
469     const MDNode *Var = VI->first;
470     if (!Var) continue;
471     std::pair<unsigned, DebugLoc> &VP = VI->second;
472     if (SlotRemap.count(VP.first)) {
473       DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n");
474       VP.first = SlotRemap[VP.first];
475       FixedDbg++;
476     }
477   }
478
479   // Keep a list of *allocas* which need to be remapped.
480   DenseMap<const Value*, const Value*> Allocas;
481   for (DenseMap<int, int>::iterator it = SlotRemap.begin(),
482        e = SlotRemap.end(); it != e; ++it) {
483     const Value *From = MFI->getObjectAllocation(it->first);
484     const Value *To = MFI->getObjectAllocation(it->second);
485     assert(To && From && "Invalid allocation object");
486     Allocas[From] = To;
487   }
488
489   // Remap all instructions to the new stack slots.
490   MachineFunction::iterator BB, BBE;
491   MachineBasicBlock::iterator I, IE;
492   for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
493     for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
494
495       // Skip lifetime markers. We'll remove them soon.
496       if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
497           I->getOpcode() == TargetOpcode::LIFETIME_END)
498         continue;
499
500       // Update the MachineMemOperand to use the new alloca.
501       for (MachineInstr::mmo_iterator MM = I->memoperands_begin(),
502            E = I->memoperands_end(); MM != E; ++MM) {
503         MachineMemOperand *MMO = *MM;
504
505         const Value *V = MMO->getValue();
506
507         if (!V)
508           continue;
509
510         // Climb up and find the original alloca.
511         V = GetUnderlyingObject(V);
512         // If we did not find one, or if the one that we found is not in our
513         // map, then move on.
514         if (!V || !Allocas.count(V))
515           continue;
516
517         MMO->setValue(Allocas[V]);
518         FixedMemOp++;
519       }
520
521       // Update all of the machine instruction operands.
522       for (unsigned i = 0 ; i <  I->getNumOperands(); ++i) {
523         MachineOperand &MO = I->getOperand(i);
524
525         if (!MO.isFI())
526           continue;
527         int FromSlot = MO.getIndex();
528
529         // Don't touch arguments.
530         if (FromSlot<0)
531           continue;
532
533         // Only look at mapped slots.
534         if (!SlotRemap.count(FromSlot))
535           continue;
536
537         // In a debug build, check that the instruction that we are modifying is
538         // inside the expected live range. If the instruction is not inside
539         // the calculated range then it means that the alloca usage moved
540         // outside of the lifetime markers.
541 #ifndef NDEBUG
542         if (!I->isDebugValue()) {
543           SlotIndex Index = Indexes->getInstructionIndex(I);
544           LiveInterval *Interval = Intervals[FromSlot];
545           assert(Interval->find(Index) != Interval->end() &&
546                "Found instruction usage outside of live range.");
547         }
548 #endif
549
550         // Fix the machine instructions.
551         int ToSlot = SlotRemap[FromSlot];
552         MO.setIndex(ToSlot);
553         FixedInstr++;
554       }
555     }
556
557   DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n");
558   DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n");
559   DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n");
560 }
561
562 void StackColoring::removeInvalidSlotRanges() {
563   MachineFunction::iterator BB, BBE;
564   MachineBasicBlock::iterator I, IE;
565   for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB)
566     for (I = BB->begin(), IE = BB->end(); I != IE; ++I) {
567
568       if (I->getOpcode() == TargetOpcode::LIFETIME_START ||
569           I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue())
570         continue;
571
572       // Check all of the machine operands.
573       for (unsigned i = 0 ; i <  I->getNumOperands(); ++i) {
574         MachineOperand &MO = I->getOperand(i);
575
576         if (!MO.isFI())
577           continue;
578
579         int Slot = MO.getIndex();
580
581         if (Slot<0)
582           continue;
583
584         if (Intervals[Slot]->empty())
585           continue;
586
587         // Check that the used slot is inside the calculated lifetime range.
588         // If it is not, warn about it and invalidate the range.
589         LiveInterval *Interval = Intervals[Slot];
590         SlotIndex Index = Indexes->getInstructionIndex(I);
591         if (Interval->find(Index) == Interval->end()) {
592           Intervals[Slot]->clear();
593           DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n");
594           EscapedAllocas++;
595         }
596       }
597     }
598 }
599
600 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap,
601                                    unsigned NumSlots) {
602   // Expunge slot remap map.
603   for (unsigned i=0; i < NumSlots; ++i) {
604     // If we are remapping i
605     if (SlotRemap.count(i)) {
606       int Target = SlotRemap[i];
607       // As long as our target is mapped to something else, follow it.
608       while (SlotRemap.count(Target)) {
609         Target = SlotRemap[Target];
610         SlotRemap[i] = Target;
611       }
612     }
613   }
614 }
615
616 bool StackColoring::runOnMachineFunction(MachineFunction &Func) {
617   DEBUG(dbgs() << "********** Stack Coloring **********\n"
618                << "********** Function: "
619                << ((const Value*)Func.getFunction())->getName() << '\n');
620   MF = &Func;
621   MFI = MF->getFrameInfo();
622   Indexes = &getAnalysis<SlotIndexes>();
623   BlockLiveness.clear();
624   BasicBlocks.clear();
625   BasicBlockNumbering.clear();
626   Markers.clear();
627   Intervals.clear();
628   VNInfoAllocator.Reset();
629
630   unsigned NumSlots = MFI->getObjectIndexEnd();
631
632   // If there are no stack slots then there are no markers to remove.
633   if (!NumSlots)
634     return false;
635
636   SmallVector<int, 8> SortedSlots;
637
638   SortedSlots.reserve(NumSlots);
639   Intervals.reserve(NumSlots);
640
641   unsigned NumMarkers = collectMarkers(NumSlots);
642
643   unsigned TotalSize = 0;
644   DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n");
645   DEBUG(dbgs()<<"Slot structure:\n");
646
647   for (int i=0; i < MFI->getObjectIndexEnd(); ++i) {
648     DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n");
649     TotalSize += MFI->getObjectSize(i);
650   }
651
652   DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n");
653
654   // Don't continue because there are not enough lifetime markers, or the
655   // stack or too small, or we are told not to optimize the slots.
656   if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) {
657     DEBUG(dbgs()<<"Will not try to merge slots.\n");
658     return removeAllMarkers();
659   }
660
661   for (unsigned i=0; i < NumSlots; ++i) {
662     LiveInterval *LI = new LiveInterval(i, 0);
663     Intervals.push_back(LI);
664     LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator);
665     SortedSlots.push_back(i);
666   }
667
668   // Calculate the liveness of each block.
669   calculateLocalLiveness();
670
671   // Propagate the liveness information.
672   calculateLiveIntervals(NumSlots);
673
674   // Search for allocas which are used outside of the declared lifetime
675   // markers.
676   if (CheckEscapedAllocas)
677     removeInvalidSlotRanges();
678
679   // Maps old slots to new slots.
680   DenseMap<int, int> SlotRemap;
681   unsigned RemovedSlots = 0;
682   unsigned ReducedSize = 0;
683
684   // Do not bother looking at empty intervals.
685   for (unsigned I = 0; I < NumSlots; ++I) {
686     if (Intervals[SortedSlots[I]]->empty())
687       SortedSlots[I] = -1;
688   }
689
690   // This is a simple greedy algorithm for merging allocas. First, sort the
691   // slots, placing the largest slots first. Next, perform an n^2 scan and look
692   // for disjoint slots. When you find disjoint slots, merge the samller one
693   // into the bigger one and update the live interval. Remove the small alloca
694   // and continue.
695
696   // Sort the slots according to their size. Place unused slots at the end.
697   std::sort(SortedSlots.begin(), SortedSlots.end(), SlotSizeSorter(MFI));
698
699   bool Chanded = true;
700   while (Chanded) {
701     Chanded = false;
702     for (unsigned I = 0; I < NumSlots; ++I) {
703       if (SortedSlots[I] == -1)
704         continue;
705
706       for (unsigned J=I+1; J < NumSlots; ++J) {
707         if (SortedSlots[J] == -1)
708           continue;
709
710         int FirstSlot = SortedSlots[I];
711         int SecondSlot = SortedSlots[J];
712         LiveInterval *First = Intervals[FirstSlot];
713         LiveInterval *Second = Intervals[SecondSlot];
714         assert (!First->empty() && !Second->empty() && "Found an empty range");
715
716         // Merge disjoint slots.
717         if (!First->overlaps(*Second)) {
718           Chanded = true;
719           First->MergeRangesInAsValue(*Second, First->getValNumInfo(0));
720           SlotRemap[SecondSlot] = FirstSlot;
721           SortedSlots[J] = -1;
722           DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<<
723                 SecondSlot<<" together.\n");
724           unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot),
725                                            MFI->getObjectAlignment(SecondSlot));
726
727           assert(MFI->getObjectSize(FirstSlot) >=
728                  MFI->getObjectSize(SecondSlot) &&
729                  "Merging a small object into a larger one");
730
731           RemovedSlots+=1;
732           ReducedSize += MFI->getObjectSize(SecondSlot);
733           MFI->setObjectAlignment(FirstSlot, MaxAlignment);
734           MFI->RemoveStackObject(SecondSlot);
735         }
736       }
737     }
738   }// While changed.
739
740   // Record statistics.
741   StackSpaceSaved += ReducedSize;
742   StackSlotMerged += RemovedSlots;
743   DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<<
744         ReducedSize<<" bytes\n");
745
746   // Scan the entire function and update all machine operands that use frame
747   // indices to use the remapped frame index.
748   expungeSlotMap(SlotRemap, NumSlots);
749   remapInstructions(SlotRemap);
750
751   // Release the intervals.
752   for (unsigned I = 0; I < NumSlots; ++I) {
753     delete Intervals[I];
754   }
755
756   return removeAllMarkers();
757 }