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