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 #include "llvm/CodeGen/Passes.h"
15 #include "llvm/ADT/BitVector.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/Statistic.h"
18 #include "llvm/CodeGen/LiveIntervalAnalysis.h"
19 #include "llvm/CodeGen/LiveStackAnalysis.h"
20 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h"
21 #include "llvm/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineMemOperand.h"
24 #include "llvm/CodeGen/MachineRegisterInfo.h"
25 #include "llvm/CodeGen/PseudoSourceValue.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31 #include "llvm/Target/TargetMachine.h"
32 #include "llvm/Target/TargetSubtargetInfo.h"
36 #define DEBUG_TYPE "stackslotcoloring"
39 DisableSharing("no-stack-slot-sharing",
40 cl::init(false), cl::Hidden,
41 cl::desc("Suppress slot sharing during stack coloring"));
43 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
45 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
46 STATISTIC(NumDead, "Number of trivially dead stack accesses eliminated");
49 class StackSlotColoring : public MachineFunctionPass {
51 MachineFrameInfo *MFI;
52 const TargetInstrInfo *TII;
53 const MachineBlockFrequencyInfo *MBFI;
55 // SSIntervals - Spill slot intervals.
56 std::vector<LiveInterval*> SSIntervals;
58 // SSRefs - Keep a list of MachineMemOperands for each spill slot.
59 // MachineMemOperands can be shared between instructions, so we need
60 // to be careful that renames like [FI0, FI1] -> [FI1, FI2] do not
61 // become FI0 -> FI1 -> FI2.
62 SmallVector<SmallVector<MachineMemOperand *, 8>, 16> SSRefs;
64 // OrigAlignments - Alignments of stack objects before coloring.
65 SmallVector<unsigned, 16> OrigAlignments;
67 // OrigSizes - Sizess of stack objects before coloring.
68 SmallVector<unsigned, 16> OrigSizes;
70 // AllColors - If index is set, it's a spill slot, i.e. color.
71 // FIXME: This assumes PEI locate spill slot with smaller indices
72 // closest to stack pointer / frame pointer. Therefore, smaller
73 // index == better color.
76 // NextColor - Next "color" that's not yet used.
79 // UsedColors - "Colors" that have been assigned.
82 // Assignments - Color to intervals mapping.
83 SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
86 static char ID; // Pass identification
88 MachineFunctionPass(ID), NextColor(-1) {
89 initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
92 void getAnalysisUsage(AnalysisUsage &AU) const override {
94 AU.addRequired<SlotIndexes>();
95 AU.addPreserved<SlotIndexes>();
96 AU.addRequired<LiveStacks>();
97 AU.addRequired<MachineBlockFrequencyInfo>();
98 AU.addPreserved<MachineBlockFrequencyInfo>();
99 AU.addPreservedID(MachineDominatorsID);
100 MachineFunctionPass::getAnalysisUsage(AU);
103 bool runOnMachineFunction(MachineFunction &MF) override;
106 void InitializeSlots();
107 void ScanForSpillSlotRefs(MachineFunction &MF);
108 bool OverlapWithAssignments(LiveInterval *li, int Color) const;
109 int ColorSlot(LiveInterval *li);
110 bool ColorSlots(MachineFunction &MF);
111 void RewriteInstruction(MachineInstr *MI, SmallVectorImpl<int> &SlotMapping,
112 MachineFunction &MF);
113 bool RemoveDeadStores(MachineBasicBlock* MBB);
115 } // end anonymous namespace
117 char StackSlotColoring::ID = 0;
118 char &llvm::StackSlotColoringID = StackSlotColoring::ID;
120 INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
121 "Stack Slot Coloring", false, false)
122 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
123 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
124 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
125 INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
126 "Stack Slot Coloring", false, false)
129 // IntervalSorter - Comparison predicate that sort live intervals by
131 struct IntervalSorter {
132 bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
133 return LHS->weight > RHS->weight;
138 /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
139 /// references and update spill slot weights.
140 void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
141 SSRefs.resize(MFI->getObjectIndexEnd());
143 // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
144 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
146 MachineBasicBlock *MBB = &*MBBI;
147 for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
149 MachineInstr *MI = &*MII;
150 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
151 MachineOperand &MO = MI->getOperand(i);
154 int FI = MO.getIndex();
157 if (!LS->hasInterval(FI))
159 LiveInterval &li = LS->getInterval(FI);
160 if (!MI->isDebugValue())
161 li.weight += LiveIntervals::getSpillWeight(false, true, MBFI, MI);
163 for (MachineInstr::mmo_iterator MMOI = MI->memoperands_begin(),
164 EE = MI->memoperands_end(); MMOI != EE; ++MMOI) {
165 MachineMemOperand *MMO = *MMOI;
166 if (const FixedStackPseudoSourceValue *FSV =
167 dyn_cast_or_null<FixedStackPseudoSourceValue>(
168 MMO->getPseudoValue())) {
169 int FI = FSV->getFrameIndex();
171 SSRefs[FI].push_back(MMO);
178 /// InitializeSlots - Process all spill stack slot liveintervals and add them
179 /// to a sorted (by weight) list.
180 void StackSlotColoring::InitializeSlots() {
181 int LastFI = MFI->getObjectIndexEnd();
182 OrigAlignments.resize(LastFI);
183 OrigSizes.resize(LastFI);
184 AllColors.resize(LastFI);
185 UsedColors.resize(LastFI);
186 Assignments.resize(LastFI);
188 // Gather all spill slots into a list.
189 DEBUG(dbgs() << "Spill slot intervals:\n");
190 for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
191 LiveInterval &li = i->second;
193 int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
194 if (MFI->isDeadObjectIndex(FI))
196 SSIntervals.push_back(&li);
197 OrigAlignments[FI] = MFI->getObjectAlignment(FI);
198 OrigSizes[FI] = MFI->getObjectSize(FI);
201 DEBUG(dbgs() << '\n');
203 // Sort them by weight.
204 std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
206 // Get first "color".
207 NextColor = AllColors.find_first();
210 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
211 /// LiveIntervals that have already been assigned to the specified color.
213 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
214 const SmallVectorImpl<LiveInterval *> &OtherLIs = Assignments[Color];
215 for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
216 LiveInterval *OtherLI = OtherLIs[i];
217 if (OtherLI->overlaps(*li))
223 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
225 int StackSlotColoring::ColorSlot(LiveInterval *li) {
228 if (!DisableSharing) {
229 // Check if it's possible to reuse any of the used colors.
230 Color = UsedColors.find_first();
231 while (Color != -1) {
232 if (!OverlapWithAssignments(li, Color)) {
237 Color = UsedColors.find_next(Color);
241 // Assign it to the first available color (assumed to be the best) if it's
242 // not possible to share a used color with other objects.
244 assert(NextColor != -1 && "No more spill slots?");
246 UsedColors.set(Color);
247 NextColor = AllColors.find_next(NextColor);
250 // Record the assignment.
251 Assignments[Color].push_back(li);
252 int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
253 DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
255 // Change size and alignment of the allocated slot. If there are multiple
256 // objects sharing the same slot, then make sure the size and alignment
257 // are large enough for all.
258 unsigned Align = OrigAlignments[FI];
259 if (!Share || Align > MFI->getObjectAlignment(Color))
260 MFI->setObjectAlignment(Color, Align);
261 int64_t Size = OrigSizes[FI];
262 if (!Share || Size > MFI->getObjectSize(Color))
263 MFI->setObjectSize(Color, Size);
267 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
268 /// operands in the function.
269 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
270 unsigned NumObjs = MFI->getObjectIndexEnd();
271 SmallVector<int, 16> SlotMapping(NumObjs, -1);
272 SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
273 SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
274 BitVector UsedColors(NumObjs);
276 DEBUG(dbgs() << "Color spill slot intervals:\n");
277 bool Changed = false;
278 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
279 LiveInterval *li = SSIntervals[i];
280 int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
281 int NewSS = ColorSlot(li);
282 assert(NewSS >= 0 && "Stack coloring failed?");
283 SlotMapping[SS] = NewSS;
284 RevMap[NewSS].push_back(SS);
285 SlotWeights[NewSS] += li->weight;
286 UsedColors.set(NewSS);
287 Changed |= (SS != NewSS);
290 DEBUG(dbgs() << "\nSpill slots after coloring:\n");
291 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
292 LiveInterval *li = SSIntervals[i];
293 int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
294 li->weight = SlotWeights[SS];
296 // Sort them by new weight.
297 std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
300 for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
301 DEBUG(SSIntervals[i]->dump());
302 DEBUG(dbgs() << '\n');
308 // Rewrite all MachineMemOperands.
309 for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
310 int NewFI = SlotMapping[SS];
311 if (NewFI == -1 || (NewFI == (int)SS))
314 const PseudoSourceValue *NewSV = PseudoSourceValue::getFixedStack(NewFI);
315 SmallVectorImpl<MachineMemOperand *> &RefMMOs = SSRefs[SS];
316 for (unsigned i = 0, e = RefMMOs.size(); i != e; ++i)
317 RefMMOs[i]->setValue(NewSV);
320 // Rewrite all MO_FrameIndex operands. Look for dead stores.
321 for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
323 MachineBasicBlock *MBB = &*MBBI;
324 for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
326 RewriteInstruction(MII, SlotMapping, MF);
327 RemoveDeadStores(MBB);
330 // Delete unused stack slots.
331 while (NextColor != -1) {
332 DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
333 MFI->RemoveStackObject(NextColor);
334 NextColor = AllColors.find_next(NextColor);
340 /// RewriteInstruction - Rewrite specified instruction by replacing references
341 /// to old frame index with new one.
342 void StackSlotColoring::RewriteInstruction(MachineInstr *MI,
343 SmallVectorImpl<int> &SlotMapping,
344 MachineFunction &MF) {
345 // Update the operands.
346 for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
347 MachineOperand &MO = MI->getOperand(i);
350 int OldFI = MO.getIndex();
353 int NewFI = SlotMapping[OldFI];
354 if (NewFI == -1 || NewFI == OldFI)
359 // The MachineMemOperands have already been updated.
363 /// RemoveDeadStores - Scan through a basic block and look for loads followed
364 /// by stores. If they're both using the same stack slot, then the store is
365 /// definitely dead. This could obviously be much more aggressive (consider
366 /// pairs with instructions between them), but such extensions might have a
367 /// considerable compile time impact.
368 bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
369 // FIXME: This could be much more aggressive, but we need to investigate
370 // the compile time impact of doing so.
371 bool changed = false;
373 SmallVector<MachineInstr*, 4> toErase;
375 for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
377 if (DCELimit != -1 && (int)NumDead >= DCELimit)
380 int FirstSS, SecondSS;
381 if (TII->isStackSlotCopy(I, FirstSS, SecondSS) &&
382 FirstSS == SecondSS &&
386 toErase.push_back(I);
390 MachineBasicBlock::iterator NextMI = std::next(I);
391 if (NextMI == MBB->end()) continue;
393 unsigned LoadReg = 0;
394 unsigned StoreReg = 0;
395 if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
396 if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
397 if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
402 if (NextMI->findRegisterUseOperandIdx(LoadReg, true, nullptr) != -1) {
404 toErase.push_back(I);
407 toErase.push_back(NextMI);
411 for (SmallVectorImpl<MachineInstr *>::iterator I = toErase.begin(),
412 E = toErase.end(); I != E; ++I)
413 (*I)->eraseFromParent();
419 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
421 dbgs() << "********** Stack Slot Coloring **********\n"
422 << "********** Function: " << MF.getName() << '\n';
425 MFI = MF.getFrameInfo();
426 TII = MF.getSubtarget().getInstrInfo();
427 LS = &getAnalysis<LiveStacks>();
428 MBFI = &getAnalysis<MachineBlockFrequencyInfo>();
430 bool Changed = false;
432 unsigned NumSlots = LS->getNumIntervals();
437 // If there are calls to setjmp or sigsetjmp, don't perform stack slot
438 // coloring. The stack could be modified before the longjmp is executed,
439 // resulting in the wrong value being used afterwards. (See
440 // <rdar://problem/8007500>.)
441 if (MF.exposesReturnsTwice())
444 // Gather spill slot references
445 ScanForSpillSlotRefs(MF);
447 Changed = ColorSlots(MF);
451 for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
454 OrigAlignments.clear();
458 for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
459 Assignments[i].clear();