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