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