1b5d41795cc2bed45148b54f1b142ab8f6824657
[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 "llvm/CodeGen/Passes.h"
16 #include "llvm/CodeGen/LiveStackAnalysis.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/Support/CommandLine.h"
19 #include "llvm/Support/Compiler.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/ADT/BitVector.h"
22 #include "llvm/ADT/SmallVector.h"
23 #include "llvm/ADT/Statistic.h"
24 #include <vector>
25 using namespace llvm;
26
27 static cl::opt<bool>
28 DisableSharing("no-stack-slot-sharing",
29              cl::init(false), cl::Hidden,
30              cl::desc("Surpress slot sharing during stack coloring"));
31
32 STATISTIC(NumEliminated,   "Number of stack slots eliminated due to coloring");
33
34 namespace {
35   class VISIBILITY_HIDDEN StackSlotColoring : public MachineFunctionPass {
36     LiveStacks* LS;
37     MachineFrameInfo *MFI;
38
39     // SSIntervals - Spill slot intervals.
40     std::vector<LiveInterval*> SSIntervals;
41
42     // OrigAlignments - Alignments of stack objects before coloring.
43     SmallVector<unsigned, 16> OrigAlignments;
44
45     // OrigSizes - Sizess of stack objects before coloring.
46     SmallVector<unsigned, 16> OrigSizes;
47
48     // AllColors - If index is set, it's a spill slot, i.e. color.
49     // FIXME: This assumes PEI locate spill slot with smaller indices
50     // closest to stack pointer / frame pointer. Therefore, smaller
51     // index == better color.
52     BitVector AllColors;
53
54     // NextColor - Next "color" that's not yet used.
55     int NextColor;
56
57     // UsedColors - "Colors" that have been assigned.
58     BitVector UsedColors;
59
60     // Assignments - Color to intervals mapping.
61     SmallVector<SmallVector<LiveInterval*,4>,16> Assignments;
62
63   public:
64     static char ID; // Pass identification
65     StackSlotColoring() : MachineFunctionPass(&ID), NextColor(-1) {}
66     
67     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
68       AU.addRequired<LiveStacks>();
69       AU.setPreservesAll();
70       MachineFunctionPass::getAnalysisUsage(AU);
71     }
72
73     virtual bool runOnMachineFunction(MachineFunction &MF);
74     virtual const char* getPassName() const {
75       return "Stack Slot Coloring";
76     }
77
78   private:
79     bool InitializeSlots();
80     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
81     int ColorSlot(LiveInterval *li);
82     bool ColorSlots(MachineFunction &MF);
83   };
84 } // end anonymous namespace
85
86 char StackSlotColoring::ID = 0;
87
88 static RegisterPass<StackSlotColoring>
89 X("stack-slot-coloring", "Stack Slot Coloring");
90
91 FunctionPass *llvm::createStackSlotColoringPass() {
92   return new StackSlotColoring();
93 }
94
95 namespace {
96   // IntervalSorter - Comparison predicate that sort live intervals by
97   // their weight.
98   struct IntervalSorter {
99     bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
100       return LHS->weight > RHS->weight;
101     }
102   };
103 }
104
105 /// InitializeSlots - Process all spill stack slot liveintervals and add them
106 /// to a sorted (by weight) list.
107 bool StackSlotColoring::InitializeSlots() {
108   if (LS->getNumIntervals() < 2)
109     return false;
110
111   int LastFI = MFI->getObjectIndexEnd();
112   OrigAlignments.resize(LastFI);
113   OrigSizes.resize(LastFI);
114   AllColors.resize(LastFI);
115   UsedColors.resize(LastFI);
116   Assignments.resize(LastFI);
117
118   // Gather all spill slots into a list.
119   for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
120     LiveInterval &li = i->second;
121     int FI = li.getStackSlotIndex();
122     if (MFI->isDeadObjectIndex(FI))
123       continue;
124     SSIntervals.push_back(&li);
125     OrigAlignments[FI] = MFI->getObjectAlignment(FI);
126     OrigSizes[FI]      = MFI->getObjectSize(FI);
127     AllColors.set(FI);
128   }
129
130   // Sort them by weight.
131   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
132
133   // Get first "color".
134   NextColor = AllColors.find_first();
135   return true;
136 }
137
138 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
139 /// LiveIntervals that have already been assigned to the specified color.
140 bool
141 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
142   const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
143   for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
144     LiveInterval *OtherLI = OtherLIs[i];
145     if (OtherLI->overlaps(*li))
146       return true;
147   }
148   return false;
149 }
150
151 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
152 ///
153 int StackSlotColoring::ColorSlot(LiveInterval *li) {
154   int Color = -1;
155   bool Share = false;
156   if (!DisableSharing) {
157     // Check if it's possible to reuse any of the used colors.
158     Color = UsedColors.find_first();
159     while (Color != -1) {
160       if (!OverlapWithAssignments(li, Color)) {
161         Share = true;
162         ++NumEliminated;
163         break;
164       }
165       Color = UsedColors.find_next(Color);
166     }
167   }
168
169   // Assign it to the first available color (assumed to be the best) if it's
170   // not possible to share a used color with other objects.
171   if (!Share) {
172     assert(NextColor != -1 && "No more spill slots?");
173     Color = NextColor;
174     UsedColors.set(Color);
175     NextColor = AllColors.find_next(NextColor);
176   }
177
178   // Record the assignment.
179   Assignments[Color].push_back(li);
180   int FI = li->getStackSlotIndex();
181   DOUT << "Assigning fi #" << FI << " to fi #" << Color << "\n";
182
183   // Change size and alignment of the allocated slot. If there are multiple
184   // objects sharing the same slot, then make sure the size and alignment
185   // are large enough for all.
186   unsigned Align = OrigAlignments[FI];
187   if (!Share || Align > MFI->getObjectAlignment(Color))
188     MFI->setObjectAlignment(Color, Align);
189   int64_t Size = OrigSizes[FI];
190   if (!Share || Size > MFI->getObjectSize(Color))
191     MFI->setObjectSize(Color, Size);
192   return Color;
193 }
194
195 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
196 /// operands in the function.
197 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
198   unsigned NumObjs = MFI->getObjectIndexEnd();
199   std::vector<int> SlotMapping(NumObjs, -1);
200
201   bool Changed = false;
202   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
203     LiveInterval *li = SSIntervals[i];
204     int SS = li->getStackSlotIndex();
205     int NewSS = ColorSlot(li);
206     SlotMapping[SS] = NewSS;
207     Changed |= (SS != NewSS);
208   }
209
210   if (!Changed)
211     return false;
212
213   // Rewrite all MO_FrameIndex operands.
214   // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
215   for (MachineFunction::iterator MBB = MF.begin(), E = MF.end();
216        MBB != E; ++MBB) {
217     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
218          MII != EE; ++MII) {
219       MachineInstr &MI = *MII;
220       for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) {
221         MachineOperand &MO = MI.getOperand(i);
222         if (!MO.isFrameIndex())
223           continue;
224         int FI = MO.getIndex();
225         if (FI < 0)
226           continue;
227         FI = SlotMapping[FI];
228         if (FI == -1)
229           continue;
230         MO.setIndex(FI);
231       }
232     }
233   }
234
235   // Delete unused stack slots.
236   while (NextColor != -1) {
237     DOUT << "Removing unused stack object fi #" << NextColor << "\n";
238     MFI->RemoveStackObject(NextColor);
239     NextColor = AllColors.find_next(NextColor);
240   }
241
242   return true;
243 }
244
245 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
246   DOUT << "********** Stack Slot Coloring **********\n";
247
248   MFI = MF.getFrameInfo();
249   LS = &getAnalysis<LiveStacks>();
250
251   bool Changed = false;
252   if (InitializeSlots())
253     Changed = ColorSlots(MF);
254
255   NextColor = -1;
256   SSIntervals.clear();
257   OrigAlignments.clear();
258   OrigSizes.clear();
259   AllColors.clear();
260   UsedColors.clear();
261   for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
262     Assignments[i].clear();
263   Assignments.clear();
264
265   return Changed;
266 }