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