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