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