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