1 //===-- StackSlotColoring.cpp - Stack slot coloring pass. -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the stack slot coloring pass.
12 //===----------------------------------------------------------------------===//
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"
38 DisableSharing("no-stack-slot-sharing",
39 cl::init(false), cl::Hidden,
40 cl::desc("Suppress slot sharing during stack coloring"));
42 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
44 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
45 STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated");
48 class StackSlotColoring : public MachineFunctionPass {
50 MachineFrameInfo *MFI;
51 const TargetInstrInfo *TII;
52 const MachineBlockFrequencyInfo *MBFI;
54 // SSIntervals - Spill slot intervals.
55 std::vector<LiveInterval*> SSIntervals;
57 // SSRefs - Keep a list of frame index references for each spill slot.
58 SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
60 // OrigAlignments - Alignments of stack objects before coloring.
61 SmallVector<unsigned, 16> OrigAlignments;
63 // OrigSizes - Sizess of stack objects before coloring.
64 SmallVector<unsigned, 16> OrigSizes;
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.
72 // NextColor - Next "color" that's not yet used.
75 // UsedColors - "Colors" that have been assigned.
78 // Assignments - Color to intervals mapping.
79 SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
82 static char ID; // Pass identification
84 MachineFunctionPass(ID), NextColor(-1) {
85 initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
88 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
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);
99 virtual bool runOnMachineFunction(MachineFunction &MF);
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);
111 } // end anonymous namespace
113 char StackSlotColoring::ID = 0;
114 char &llvm::StackSlotColoringID = StackSlotColoring::ID;
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)
125 // IntervalSorter - Comparison predicate that sort live intervals by
127 struct IntervalSorter {
128 bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
129 return LHS->weight > RHS->weight;
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());
139 // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
140 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
142 MachineBasicBlock *MBB = &*MBBI;
143 BlockFrequency Freq = MBFI->getBlockFreq(MBB);
144 for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
146 MachineInstr *MI = &*MII;
147 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
148 MachineOperand &MO = MI->getOperand(i);
151 int FI = MO.getIndex();
154 if (!LS->hasInterval(FI))
156 LiveInterval &li = LS->getInterval(FI);
157 if (!MI->isDebugValue())
158 li.weight += LiveIntervals::getSpillWeight(false, true, Freq);
159 SSRefs[FI].push_back(MI);
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);
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;
180 int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
181 if (MFI->isDeadObjectIndex(FI))
183 SSIntervals.push_back(&li);
184 OrigAlignments[FI] = MFI->getObjectAlignment(FI);
185 OrigSizes[FI] = MFI->getObjectSize(FI);
188 DEBUG(dbgs() << '\n');
190 // Sort them by weight.
191 std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
193 // Get first "color".
194 NextColor = AllColors.find_first();
197 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
198 /// LiveIntervals that have already been assigned to the specified color.
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))
210 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
212 int StackSlotColoring::ColorSlot(LiveInterval *li) {
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)) {
224 Color = UsedColors.find_next(Color);
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.
231 assert(NextColor != -1 && "No more spill slots?");
233 UsedColors.set(Color);
234 NextColor = AllColors.find_next(NextColor);
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");
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);
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);
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);
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];
283 // Sort them by new weight.
284 std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
287 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
288 DEBUG(SSIntervals[i]->dump());
289 DEBUG(dbgs() << '\n');
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))
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);
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);
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);
326 int FI = MO.getIndex();
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);
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;
354 SmallVector<MachineInstr*, 4> toErase;
356 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
358 if (DCELimit != -1 && (int)NumDead >= DCELimit)
361 MachineBasicBlock::iterator NextMI = llvm::next(I);
362 if (NextMI == MBB->end()) continue;
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;
374 if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
376 toErase.push_back(I);
379 toErase.push_back(NextMI);
383 for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
384 E = toErase.end(); I != E; ++I)
385 (*I)->eraseFromParent();
391 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
393 dbgs() << "********** Stack Slot Coloring **********\n"
394 << "********** Function: " << MF.getName() << '\n';
397 MFI = MF.getFrameInfo();
398 TII = MF.getTarget().getInstrInfo();
399 LS = &getAnalysis<LiveStacks>();
400 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
402 bool Changed = false;
404 unsigned NumSlots = LS->getNumIntervals();
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())
416 // Gather spill slot references
417 ScanForSpillSlotRefs(MF);
419 Changed = ColorSlots(MF);
423 for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
426 OrigAlignments.clear();
430 for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
431 Assignments[i].clear();
435 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
436 Changed |= RemoveDeadStores(I);