Hopefully fix the MSVS build after r184105
[oota-llvm.git] / lib / CodeGen / StackSlotColoring.cpp
1 //===-- StackSlotColoring.cpp - Stack slot coloring pass. -----------------===//
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 file implements the stack slot coloring pass.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #define DEBUG_TYPE "stackslotcoloring"
15 #include "llvm/CodeGen/Passes.h"
16 #include "llvm/ADT/BitVector.h"
17 #include "llvm/ADT/SmallSet.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
21 #include "llvm/CodeGen/LiveStackAnalysis.h"
22 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
23 #include "llvm/CodeGen/MachineFrameInfo.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineMemOperand.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/PseudoSourceValue.h"
28 #include "llvm/IR/Module.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include "llvm/Target/TargetInstrInfo.h"
33 #include "llvm/Target/TargetMachine.h"
34 #include <vector>
35 using namespace llvm;
36
37 static cl::opt<bool>
38 DisableSharing("no-stack-slot-sharing",
39              cl::init(false), cl::Hidden,
40              cl::desc("Suppress slot sharing during stack coloring"));
41
42 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
43
44 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
45 STATISTIC(NumDead,       "Number of trivially dead stack accesses eliminated");
46
47 namespace {
48   class StackSlotColoring : public MachineFunctionPass {
49     LiveStacks* LS;
50     MachineFrameInfo *MFI;
51     const TargetInstrInfo  *TII;
52     const MachineBlockFrequencyInfo *MBFI;
53
54     // SSIntervals - Spill slot intervals.
55     std::vector<LiveInterval*> SSIntervals;
56
57     // SSRefs - Keep a list of frame index references for each spill slot.
58     SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
59
60     // OrigAlignments - Alignments of stack objects before coloring.
61     SmallVector<unsigned, 16> OrigAlignments;
62
63     // OrigSizes - Sizess of stack objects before coloring.
64     SmallVector<unsigned, 16> OrigSizes;
65
66     // AllColors - If index is set, it's a spill slot, i.e. color.
67     // FIXME: This assumes PEI locate spill slot with smaller indices
68     // closest to stack pointer / frame pointer. Therefore, smaller
69     // index == better color.
70     BitVector AllColors;
71
72     // NextColor - Next "color" that's not yet used.
73     int NextColor;
74
75     // UsedColors - "Colors" that have been assigned.
76     BitVector UsedColors;
77
78     // Assignments - Color to intervals mapping.
79     SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
80
81   public:
82     static char ID; // Pass identification
83     StackSlotColoring() :
84       MachineFunctionPass(ID), NextColor(-1) {
85         initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
86       }
87
88     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
89       AU.setPreservesCFG();
90       AU.addRequired<SlotIndexes>();
91       AU.addPreserved<SlotIndexes>();
92       AU.addRequired<LiveStacks>();
93       AU.addRequired<MachineBlockFrequencyInfo>();
94       AU.addPreserved<MachineBlockFrequencyInfo>();
95       AU.addPreservedID(MachineDominatorsID);
96       MachineFunctionPass::getAnalysisUsage(AU);
97     }
98
99     virtual bool runOnMachineFunction(MachineFunction &MF);
100
101   private:
102     void InitializeSlots();
103     void ScanForSpillSlotRefs(MachineFunction &MF);
104     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
105     int ColorSlot(LiveInterval *li);
106     bool ColorSlots(MachineFunction &MF);
107     void RewriteInstruction(MachineInstr *MI, int OldFI, int NewFI,
108                             MachineFunction &MF);
109     bool RemoveDeadStores(MachineBasicBlock* MBB);
110   };
111 } // end anonymous namespace
112
113 char StackSlotColoring::ID = 0;
114 char &llvm::StackSlotColoringID = StackSlotColoring::ID;
115
116 INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
117                 "Stack Slot Coloring", false, false)
118 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
119 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
120 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
121 INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
122                 "Stack Slot Coloring", false, false)
123
124 namespace {
125   // IntervalSorter - Comparison predicate that sort live intervals by
126   // their weight.
127   struct IntervalSorter {
128     bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
129       return LHS->weight > RHS->weight;
130     }
131   };
132 }
133
134 /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
135 /// references and update spill slot weights.
136 void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
137   SSRefs.resize(MFI->getObjectIndexEnd());
138
139   // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
140   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
141        MBBI != E; ++MBBI) {
142     MachineBasicBlock *MBB = &*MBBI;
143     BlockFrequency Freq = MBFI->getBlockFreq(MBB);
144     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
145          MII != EE; ++MII) {
146       MachineInstr *MI = &*MII;
147       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
148         MachineOperand &MO = MI->getOperand(i);
149         if (!MO.isFI())
150           continue;
151         int FI = MO.getIndex();
152         if (FI < 0)
153           continue;
154         if (!LS->hasInterval(FI))
155           continue;
156         LiveInterval &li = LS->getInterval(FI);
157         if (!MI->isDebugValue())
158           li.weight += LiveIntervals::getSpillWeight(false, true, Freq);
159         SSRefs[FI].push_back(MI);
160       }
161     }
162   }
163 }
164
165 /// InitializeSlots - Process all spill stack slot liveintervals and add them
166 /// to a sorted (by weight) list.
167 void StackSlotColoring::InitializeSlots() {
168   int LastFI = MFI->getObjectIndexEnd();
169   OrigAlignments.resize(LastFI);
170   OrigSizes.resize(LastFI);
171   AllColors.resize(LastFI);
172   UsedColors.resize(LastFI);
173   Assignments.resize(LastFI);
174
175   // Gather all spill slots into a list.
176   DEBUG(dbgs() << "Spill slot intervals:\n");
177   for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
178     LiveInterval &li = i->second;
179     DEBUG(li.dump());
180     int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
181     if (MFI->isDeadObjectIndex(FI))
182       continue;
183     SSIntervals.push_back(&li);
184     OrigAlignments[FI] = MFI->getObjectAlignment(FI);
185     OrigSizes[FI]      = MFI->getObjectSize(FI);
186     AllColors.set(FI);
187   }
188   DEBUG(dbgs() << '\n');
189
190   // Sort them by weight.
191   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
192
193   // Get first "color".
194   NextColor = AllColors.find_first();
195 }
196
197 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
198 /// LiveIntervals that have already been assigned to the specified color.
199 bool
200 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
201   const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
202   for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
203     LiveInterval *OtherLI = OtherLIs[i];
204     if (OtherLI->overlaps(*li))
205       return true;
206   }
207   return false;
208 }
209
210 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
211 ///
212 int StackSlotColoring::ColorSlot(LiveInterval *li) {
213   int Color = -1;
214   bool Share = false;
215   if (!DisableSharing) {
216     // Check if it's possible to reuse any of the used colors.
217     Color = UsedColors.find_first();
218     while (Color != -1) {
219       if (!OverlapWithAssignments(li, Color)) {
220         Share = true;
221         ++NumEliminated;
222         break;
223       }
224       Color = UsedColors.find_next(Color);
225     }
226   }
227
228   // Assign it to the first available color (assumed to be the best) if it's
229   // not possible to share a used color with other objects.
230   if (!Share) {
231     assert(NextColor != -1 && "No more spill slots?");
232     Color = NextColor;
233     UsedColors.set(Color);
234     NextColor = AllColors.find_next(NextColor);
235   }
236
237   // Record the assignment.
238   Assignments[Color].push_back(li);
239   int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
240   DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
241
242   // Change size and alignment of the allocated slot. If there are multiple
243   // objects sharing the same slot, then make sure the size and alignment
244   // are large enough for all.
245   unsigned Align = OrigAlignments[FI];
246   if (!Share || Align > MFI->getObjectAlignment(Color))
247     MFI->setObjectAlignment(Color, Align);
248   int64_t Size = OrigSizes[FI];
249   if (!Share || Size > MFI->getObjectSize(Color))
250     MFI->setObjectSize(Color, Size);
251   return Color;
252 }
253
254 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
255 /// operands in the function.
256 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
257   unsigned NumObjs = MFI->getObjectIndexEnd();
258   SmallVector<int, 16> SlotMapping(NumObjs, -1);
259   SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
260   SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
261   BitVector UsedColors(NumObjs);
262
263   DEBUG(dbgs() << "Color spill slot intervals:\n");
264   bool Changed = false;
265   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
266     LiveInterval *li = SSIntervals[i];
267     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
268     int NewSS = ColorSlot(li);
269     assert(NewSS >= 0 && "Stack coloring failed?");
270     SlotMapping[SS] = NewSS;
271     RevMap[NewSS].push_back(SS);
272     SlotWeights[NewSS] += li->weight;
273     UsedColors.set(NewSS);
274     Changed |= (SS != NewSS);
275   }
276
277   DEBUG(dbgs() << "\nSpill slots after coloring:\n");
278   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
279     LiveInterval *li = SSIntervals[i];
280     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
281     li->weight = SlotWeights[SS];
282   }
283   // Sort them by new weight.
284   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
285
286 #ifndef NDEBUG
287   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
288     DEBUG(SSIntervals[i]->dump());
289   DEBUG(dbgs() << '\n');
290 #endif
291
292   if (!Changed)
293     return false;
294
295   // Rewrite all MO_FrameIndex operands.
296   SmallVector<SmallSet<unsigned, 4>, 4> NewDefs(MF.getNumBlockIDs());
297   for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
298     int NewFI = SlotMapping[SS];
299     if (NewFI == -1 || (NewFI == (int)SS))
300       continue;
301
302     SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
303     for (unsigned i = 0, e = RefMIs.size(); i != e; ++i)
304       RewriteInstruction(RefMIs[i], SS, NewFI, MF);
305   }
306
307   // Delete unused stack slots.
308   while (NextColor != -1) {
309     DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
310     MFI->RemoveStackObject(NextColor);
311     NextColor = AllColors.find_next(NextColor);
312   }
313
314   return true;
315 }
316
317 /// RewriteInstruction - Rewrite specified instruction by replacing references
318 /// to old frame index with new one.
319 void StackSlotColoring::RewriteInstruction(MachineInstr *MI, int OldFI,
320                                            int NewFI, MachineFunction &MF) {
321   // Update the operands.
322   for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
323     MachineOperand &MO = MI->getOperand(i);
324     if (!MO.isFI())
325       continue;
326     int FI = MO.getIndex();
327     if (FI != OldFI)
328       continue;
329     MO.setIndex(NewFI);
330   }
331
332   // Update the memory references. This changes the MachineMemOperands
333   // directly. They may be in use by multiple instructions, however all
334   // instructions using OldFI are being rewritten to use NewFI.
335   const Value *OldSV = PseudoSourceValue::getFixedStack(OldFI);
336   const Value *NewSV = PseudoSourceValue::getFixedStack(NewFI);
337   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
338        E = MI->memoperands_end(); I != E; ++I)
339     if ((*I)->getValue() == OldSV)
340       (*I)->setValue(NewSV);
341 }
342
343
344 /// RemoveDeadStores - Scan through a basic block and look for loads followed
345 /// by stores.  If they're both using the same stack slot, then the store is
346 /// definitely dead.  This could obviously be much more aggressive (consider
347 /// pairs with instructions between them), but such extensions might have a
348 /// considerable compile time impact.
349 bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
350   // FIXME: This could be much more aggressive, but we need to investigate
351   // the compile time impact of doing so.
352   bool changed = false;
353
354   SmallVector<MachineInstr*, 4> toErase;
355
356   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
357        I != E; ++I) {
358     if (DCELimit != -1 && (int)NumDead >= DCELimit)
359       break;
360
361     MachineBasicBlock::iterator NextMI = llvm::next(I);
362     if (NextMI == MBB->end()) continue;
363
364     int FirstSS, SecondSS;
365     unsigned LoadReg = 0;
366     unsigned StoreReg = 0;
367     if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
368     if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
369     if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
370
371     ++NumDead;
372     changed = true;
373
374     if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
375       ++NumDead;
376       toErase.push_back(I);
377     }
378
379     toErase.push_back(NextMI);
380     ++I;
381   }
382
383   for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
384        E = toErase.end(); I != E; ++I)
385     (*I)->eraseFromParent();
386
387   return changed;
388 }
389
390
391 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
392   DEBUG({
393       dbgs() << "********** Stack Slot Coloring **********\n"
394              << "********** Function: " << MF.getName() << '\n';
395     });
396
397   MFI = MF.getFrameInfo();
398   TII = MF.getTarget().getInstrInfo();
399   LS = &getAnalysis<LiveStacks>();
400   MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
401
402   bool Changed = false;
403
404   unsigned NumSlots = LS->getNumIntervals();
405   if (NumSlots == 0)
406     // Nothing to do!
407     return false;
408
409   // If there are calls to setjmp or sigsetjmp, don't perform stack slot
410   // coloring. The stack could be modified before the longjmp is executed,
411   // resulting in the wrong value being used afterwards. (See
412   // <rdar://problem/8007500>.)
413   if (MF.exposesReturnsTwice())
414     return false;
415
416   // Gather spill slot references
417   ScanForSpillSlotRefs(MF);
418   InitializeSlots();
419   Changed = ColorSlots(MF);
420
421   NextColor = -1;
422   SSIntervals.clear();
423   for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
424     SSRefs[i].clear();
425   SSRefs.clear();
426   OrigAlignments.clear();
427   OrigSizes.clear();
428   AllColors.clear();
429   UsedColors.clear();
430   for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
431     Assignments[i].clear();
432   Assignments.clear();
433
434   if (Changed) {
435     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
436       Changed |= RemoveDeadStores(I);
437   }
438
439   return Changed;
440 }