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