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