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