Home | History | Annotate | Download | only in CodeGen
      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<bool>
     44 ColorWithRegsOpt("color-ss-with-regs",
     45                  cl::init(false), cl::Hidden,
     46                  cl::desc("Color stack slots with free registers"));
     47 
     48 
     49 static cl::opt<int> DCELimit("ssc-dce-limit", cl::init(-1), cl::Hidden);
     50 
     51 STATISTIC(NumEliminated, "Number of stack slots eliminated due to coloring");
     52 STATISTIC(NumRegRepl,    "Number of stack slot refs replaced with reg refs");
     53 STATISTIC(NumLoadElim,   "Number of loads eliminated");
     54 STATISTIC(NumStoreElim,  "Number of stores eliminated");
     55 STATISTIC(NumDead,       "Number of trivially dead stack accesses eliminated");
     56 
     57 namespace {
     58   class StackSlotColoring : public MachineFunctionPass {
     59     bool ColorWithRegs;
     60     LiveStacks* LS;
     61     VirtRegMap* VRM;
     62     MachineFrameInfo *MFI;
     63     MachineRegisterInfo *MRI;
     64     const TargetInstrInfo  *TII;
     65     const TargetRegisterInfo *TRI;
     66     const MachineLoopInfo *loopInfo;
     67 
     68     // SSIntervals - Spill slot intervals.
     69     std::vector<LiveInterval*> SSIntervals;
     70 
     71     // SSRefs - Keep a list of frame index references for each spill slot.
     72     SmallVector<SmallVector<MachineInstr*, 8>, 16> SSRefs;
     73 
     74     // OrigAlignments - Alignments of stack objects before coloring.
     75     SmallVector<unsigned, 16> OrigAlignments;
     76 
     77     // OrigSizes - Sizess of stack objects before coloring.
     78     SmallVector<unsigned, 16> OrigSizes;
     79 
     80     // AllColors - If index is set, it's a spill slot, i.e. color.
     81     // FIXME: This assumes PEI locate spill slot with smaller indices
     82     // closest to stack pointer / frame pointer. Therefore, smaller
     83     // index == better color.
     84     BitVector AllColors;
     85 
     86     // NextColor - Next "color" that's not yet used.
     87     int NextColor;
     88 
     89     // UsedColors - "Colors" that have been assigned.
     90     BitVector UsedColors;
     91 
     92     // Assignments - Color to intervals mapping.
     93     SmallVector<SmallVector<LiveInterval*,4>, 16> Assignments;
     94 
     95   public:
     96     static char ID; // Pass identification
     97     StackSlotColoring() :
     98       MachineFunctionPass(ID), ColorWithRegs(false), NextColor(-1) {
     99         initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
    100       }
    101     StackSlotColoring(bool RegColor) :
    102       MachineFunctionPass(ID), ColorWithRegs(RegColor), NextColor(-1) {
    103         initializeStackSlotColoringPass(*PassRegistry::getPassRegistry());
    104       }
    105 
    106     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    107       AU.setPreservesCFG();
    108       AU.addRequired<SlotIndexes>();
    109       AU.addPreserved<SlotIndexes>();
    110       AU.addRequired<LiveStacks>();
    111       AU.addRequired<VirtRegMap>();
    112       AU.addPreserved<VirtRegMap>();
    113       AU.addRequired<MachineLoopInfo>();
    114       AU.addPreserved<MachineLoopInfo>();
    115       AU.addPreservedID(MachineDominatorsID);
    116       MachineFunctionPass::getAnalysisUsage(AU);
    117     }
    118 
    119     virtual bool runOnMachineFunction(MachineFunction &MF);
    120     virtual const char* getPassName() const {
    121       return "Stack Slot Coloring";
    122     }
    123 
    124   private:
    125     void InitializeSlots();
    126     void ScanForSpillSlotRefs(MachineFunction &MF);
    127     bool OverlapWithAssignments(LiveInterval *li, int Color) const;
    128     int ColorSlot(LiveInterval *li);
    129     bool ColorSlots(MachineFunction &MF);
    130     bool ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
    131                                 SmallVector<SmallVector<int, 4>, 16> &RevMap,
    132                                 BitVector &SlotIsReg);
    133     void RewriteInstruction(MachineInstr *MI, int OldFI, int NewFI,
    134                             MachineFunction &MF);
    135     bool PropagateBackward(MachineBasicBlock::iterator MII,
    136                            MachineBasicBlock *MBB,
    137                            unsigned OldReg, unsigned NewReg);
    138     bool PropagateForward(MachineBasicBlock::iterator MII,
    139                           MachineBasicBlock *MBB,
    140                           unsigned OldReg, unsigned NewReg);
    141     void UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
    142                                     unsigned Reg, const TargetRegisterClass *RC,
    143                                     SmallSet<unsigned, 4> &Defs,
    144                                     MachineFunction &MF);
    145     bool AllMemRefsCanBeUnfolded(int SS);
    146     bool RemoveDeadStores(MachineBasicBlock* MBB);
    147   };
    148 } // end anonymous namespace
    149 
    150 char StackSlotColoring::ID = 0;
    151 
    152 INITIALIZE_PASS_BEGIN(StackSlotColoring, "stack-slot-coloring",
    153                 "Stack Slot Coloring", false, false)
    154 INITIALIZE_PASS_DEPENDENCY(SlotIndexes)
    155 INITIALIZE_PASS_DEPENDENCY(LiveStacks)
    156 INITIALIZE_PASS_DEPENDENCY(VirtRegMap)
    157 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo)
    158 INITIALIZE_PASS_END(StackSlotColoring, "stack-slot-coloring",
    159                 "Stack Slot Coloring", false, false)
    160 
    161 FunctionPass *llvm::createStackSlotColoringPass(bool RegColor) {
    162   return new StackSlotColoring(RegColor);
    163 }
    164 
    165 namespace {
    166   // IntervalSorter - Comparison predicate that sort live intervals by
    167   // their weight.
    168   struct IntervalSorter {
    169     bool operator()(LiveInterval* LHS, LiveInterval* RHS) const {
    170       return LHS->weight > RHS->weight;
    171     }
    172   };
    173 }
    174 
    175 /// ScanForSpillSlotRefs - Scan all the machine instructions for spill slot
    176 /// references and update spill slot weights.
    177 void StackSlotColoring::ScanForSpillSlotRefs(MachineFunction &MF) {
    178   SSRefs.resize(MFI->getObjectIndexEnd());
    179 
    180   // FIXME: Need the equivalent of MachineRegisterInfo for frameindex operands.
    181   for (MachineFunction::iterator MBBI = MF.begin(), E = MF.end();
    182        MBBI != E; ++MBBI) {
    183     MachineBasicBlock *MBB = &*MBBI;
    184     unsigned loopDepth = loopInfo->getLoopDepth(MBB);
    185     for (MachineBasicBlock::iterator MII = MBB->begin(), EE = MBB->end();
    186          MII != EE; ++MII) {
    187       MachineInstr *MI = &*MII;
    188       for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
    189         MachineOperand &MO = MI->getOperand(i);
    190         if (!MO.isFI())
    191           continue;
    192         int FI = MO.getIndex();
    193         if (FI < 0)
    194           continue;
    195         if (!LS->hasInterval(FI))
    196           continue;
    197         LiveInterval &li = LS->getInterval(FI);
    198         if (!MI->isDebugValue())
    199           li.weight += LiveIntervals::getSpillWeight(false, true, loopDepth);
    200         SSRefs[FI].push_back(MI);
    201       }
    202     }
    203   }
    204 }
    205 
    206 /// InitializeSlots - Process all spill stack slot liveintervals and add them
    207 /// to a sorted (by weight) list.
    208 void StackSlotColoring::InitializeSlots() {
    209   int LastFI = MFI->getObjectIndexEnd();
    210   OrigAlignments.resize(LastFI);
    211   OrigSizes.resize(LastFI);
    212   AllColors.resize(LastFI);
    213   UsedColors.resize(LastFI);
    214   Assignments.resize(LastFI);
    215 
    216   // Gather all spill slots into a list.
    217   DEBUG(dbgs() << "Spill slot intervals:\n");
    218   for (LiveStacks::iterator i = LS->begin(), e = LS->end(); i != e; ++i) {
    219     LiveInterval &li = i->second;
    220     DEBUG(li.dump());
    221     int FI = TargetRegisterInfo::stackSlot2Index(li.reg);
    222     if (MFI->isDeadObjectIndex(FI))
    223       continue;
    224     SSIntervals.push_back(&li);
    225     OrigAlignments[FI] = MFI->getObjectAlignment(FI);
    226     OrigSizes[FI]      = MFI->getObjectSize(FI);
    227     AllColors.set(FI);
    228   }
    229   DEBUG(dbgs() << '\n');
    230 
    231   // Sort them by weight.
    232   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
    233 
    234   // Get first "color".
    235   NextColor = AllColors.find_first();
    236 }
    237 
    238 /// OverlapWithAssignments - Return true if LiveInterval overlaps with any
    239 /// LiveIntervals that have already been assigned to the specified color.
    240 bool
    241 StackSlotColoring::OverlapWithAssignments(LiveInterval *li, int Color) const {
    242   const SmallVector<LiveInterval*,4> &OtherLIs = Assignments[Color];
    243   for (unsigned i = 0, e = OtherLIs.size(); i != e; ++i) {
    244     LiveInterval *OtherLI = OtherLIs[i];
    245     if (OtherLI->overlaps(*li))
    246       return true;
    247   }
    248   return false;
    249 }
    250 
    251 /// ColorSlotsWithFreeRegs - If there are any free registers available, try
    252 /// replacing spill slots references with registers instead.
    253 bool
    254 StackSlotColoring::ColorSlotsWithFreeRegs(SmallVector<int, 16> &SlotMapping,
    255                                    SmallVector<SmallVector<int, 4>, 16> &RevMap,
    256                                    BitVector &SlotIsReg) {
    257   if (!(ColorWithRegs || ColorWithRegsOpt) || !VRM->HasUnusedRegisters())
    258     return false;
    259 
    260   bool Changed = false;
    261   DEBUG(dbgs() << "Assigning unused registers to spill slots:\n");
    262   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
    263     LiveInterval *li = SSIntervals[i];
    264     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
    265     if (!UsedColors[SS] || li->weight < 20)
    266       // If the weight is < 20, i.e. two references in a loop with depth 1,
    267       // don't bother with it.
    268       continue;
    269 
    270     // These slots allow to share the same registers.
    271     bool AllColored = true;
    272     SmallVector<unsigned, 4> ColoredRegs;
    273     for (unsigned j = 0, ee = RevMap[SS].size(); j != ee; ++j) {
    274       int RSS = RevMap[SS][j];
    275       const TargetRegisterClass *RC = LS->getIntervalRegClass(RSS);
    276       // If it's not colored to another stack slot, try coloring it
    277       // to a "free" register.
    278       if (!RC) {
    279         AllColored = false;
    280         continue;
    281       }
    282       unsigned Reg = VRM->getFirstUnusedRegister(RC);
    283       if (!Reg) {
    284         AllColored = false;
    285         continue;
    286       }
    287       if (!AllMemRefsCanBeUnfolded(RSS)) {
    288         AllColored = false;
    289         continue;
    290       } else {
    291         DEBUG(dbgs() << "Assigning fi#" << RSS << " to "
    292                      << TRI->getName(Reg) << '\n');
    293         ColoredRegs.push_back(Reg);
    294         SlotMapping[RSS] = Reg;
    295         SlotIsReg.set(RSS);
    296         Changed = true;
    297       }
    298     }
    299 
    300     // Register and its sub-registers are no longer free.
    301     while (!ColoredRegs.empty()) {
    302       unsigned Reg = ColoredRegs.back();
    303       ColoredRegs.pop_back();
    304       VRM->setRegisterUsed(Reg);
    305       // If reg is a callee-saved register, it will have to be spilled in
    306       // the prologue.
    307       MRI->setPhysRegUsed(Reg);
    308       for (const unsigned *AS = TRI->getAliasSet(Reg); *AS; ++AS) {
    309         VRM->setRegisterUsed(*AS);
    310         MRI->setPhysRegUsed(*AS);
    311       }
    312     }
    313     // This spill slot is dead after the rewrites
    314     if (AllColored) {
    315       MFI->RemoveStackObject(SS);
    316       ++NumEliminated;
    317     }
    318   }
    319   DEBUG(dbgs() << '\n');
    320 
    321   return Changed;
    322 }
    323 
    324 /// ColorSlot - Assign a "color" (stack slot) to the specified stack slot.
    325 ///
    326 int StackSlotColoring::ColorSlot(LiveInterval *li) {
    327   int Color = -1;
    328   bool Share = false;
    329   if (!DisableSharing) {
    330     // Check if it's possible to reuse any of the used colors.
    331     Color = UsedColors.find_first();
    332     while (Color != -1) {
    333       if (!OverlapWithAssignments(li, Color)) {
    334         Share = true;
    335         ++NumEliminated;
    336         break;
    337       }
    338       Color = UsedColors.find_next(Color);
    339     }
    340   }
    341 
    342   // Assign it to the first available color (assumed to be the best) if it's
    343   // not possible to share a used color with other objects.
    344   if (!Share) {
    345     assert(NextColor != -1 && "No more spill slots?");
    346     Color = NextColor;
    347     UsedColors.set(Color);
    348     NextColor = AllColors.find_next(NextColor);
    349   }
    350 
    351   // Record the assignment.
    352   Assignments[Color].push_back(li);
    353   int FI = TargetRegisterInfo::stackSlot2Index(li->reg);
    354   DEBUG(dbgs() << "Assigning fi#" << FI << " to fi#" << Color << "\n");
    355 
    356   // Change size and alignment of the allocated slot. If there are multiple
    357   // objects sharing the same slot, then make sure the size and alignment
    358   // are large enough for all.
    359   unsigned Align = OrigAlignments[FI];
    360   if (!Share || Align > MFI->getObjectAlignment(Color))
    361     MFI->setObjectAlignment(Color, Align);
    362   int64_t Size = OrigSizes[FI];
    363   if (!Share || Size > MFI->getObjectSize(Color))
    364     MFI->setObjectSize(Color, Size);
    365   return Color;
    366 }
    367 
    368 /// Colorslots - Color all spill stack slots and rewrite all frameindex machine
    369 /// operands in the function.
    370 bool StackSlotColoring::ColorSlots(MachineFunction &MF) {
    371   unsigned NumObjs = MFI->getObjectIndexEnd();
    372   SmallVector<int, 16> SlotMapping(NumObjs, -1);
    373   SmallVector<float, 16> SlotWeights(NumObjs, 0.0);
    374   SmallVector<SmallVector<int, 4>, 16> RevMap(NumObjs);
    375   BitVector SlotIsReg(NumObjs);
    376   BitVector UsedColors(NumObjs);
    377 
    378   DEBUG(dbgs() << "Color spill slot intervals:\n");
    379   bool Changed = false;
    380   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
    381     LiveInterval *li = SSIntervals[i];
    382     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
    383     int NewSS = ColorSlot(li);
    384     assert(NewSS >= 0 && "Stack coloring failed?");
    385     SlotMapping[SS] = NewSS;
    386     RevMap[NewSS].push_back(SS);
    387     SlotWeights[NewSS] += li->weight;
    388     UsedColors.set(NewSS);
    389     Changed |= (SS != NewSS);
    390   }
    391 
    392   DEBUG(dbgs() << "\nSpill slots after coloring:\n");
    393   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i) {
    394     LiveInterval *li = SSIntervals[i];
    395     int SS = TargetRegisterInfo::stackSlot2Index(li->reg);
    396     li->weight = SlotWeights[SS];
    397   }
    398   // Sort them by new weight.
    399   std::stable_sort(SSIntervals.begin(), SSIntervals.end(), IntervalSorter());
    400 
    401 #ifndef NDEBUG
    402   for (unsigned i = 0, e = SSIntervals.size(); i != e; ++i)
    403     DEBUG(SSIntervals[i]->dump());
    404   DEBUG(dbgs() << '\n');
    405 #endif
    406 
    407   // Can we "color" a stack slot with a unused register?
    408   Changed |= ColorSlotsWithFreeRegs(SlotMapping, RevMap, SlotIsReg);
    409 
    410   if (!Changed)
    411     return false;
    412 
    413   // Rewrite all MO_FrameIndex operands.
    414   SmallVector<SmallSet<unsigned, 4>, 4> NewDefs(MF.getNumBlockIDs());
    415   for (unsigned SS = 0, SE = SSRefs.size(); SS != SE; ++SS) {
    416     bool isReg = SlotIsReg[SS];
    417     int NewFI = SlotMapping[SS];
    418     if (NewFI == -1 || (NewFI == (int)SS && !isReg))
    419       continue;
    420 
    421     const TargetRegisterClass *RC = LS->getIntervalRegClass(SS);
    422     SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
    423     for (unsigned i = 0, e = RefMIs.size(); i != e; ++i)
    424       if (!isReg)
    425         RewriteInstruction(RefMIs[i], SS, NewFI, MF);
    426       else {
    427         // Rewrite to use a register instead.
    428         unsigned MBBId = RefMIs[i]->getParent()->getNumber();
    429         SmallSet<unsigned, 4> &Defs = NewDefs[MBBId];
    430         UnfoldAndRewriteInstruction(RefMIs[i], SS, NewFI, RC, Defs, MF);
    431       }
    432   }
    433 
    434   // Delete unused stack slots.
    435   while (NextColor != -1) {
    436     DEBUG(dbgs() << "Removing unused stack object fi#" << NextColor << "\n");
    437     MFI->RemoveStackObject(NextColor);
    438     NextColor = AllColors.find_next(NextColor);
    439   }
    440 
    441   return true;
    442 }
    443 
    444 /// AllMemRefsCanBeUnfolded - Return true if all references of the specified
    445 /// spill slot index can be unfolded.
    446 bool StackSlotColoring::AllMemRefsCanBeUnfolded(int SS) {
    447   SmallVector<MachineInstr*, 8> &RefMIs = SSRefs[SS];
    448   for (unsigned i = 0, e = RefMIs.size(); i != e; ++i) {
    449     MachineInstr *MI = RefMIs[i];
    450     if (TII->isLoadFromStackSlot(MI, SS) ||
    451         TII->isStoreToStackSlot(MI, SS))
    452       // Restore and spill will become copies.
    453       return true;
    454     if (!TII->getOpcodeAfterMemoryUnfold(MI->getOpcode(), false, false))
    455       return false;
    456     for (unsigned j = 0, ee = MI->getNumOperands(); j != ee; ++j) {
    457       MachineOperand &MO = MI->getOperand(j);
    458       if (MO.isFI() && MO.getIndex() != SS)
    459         // If it uses another frameindex, we can, currently* unfold it.
    460         return false;
    461     }
    462   }
    463   return true;
    464 }
    465 
    466 /// RewriteInstruction - Rewrite specified instruction by replacing references
    467 /// to old frame index with new one.
    468 void StackSlotColoring::RewriteInstruction(MachineInstr *MI, int OldFI,
    469                                            int NewFI, MachineFunction &MF) {
    470   // Update the operands.
    471   for (unsigned i = 0, ee = MI->getNumOperands(); i != ee; ++i) {
    472     MachineOperand &MO = MI->getOperand(i);
    473     if (!MO.isFI())
    474       continue;
    475     int FI = MO.getIndex();
    476     if (FI != OldFI)
    477       continue;
    478     MO.setIndex(NewFI);
    479   }
    480 
    481   // Update the memory references. This changes the MachineMemOperands
    482   // directly. They may be in use by multiple instructions, however all
    483   // instructions using OldFI are being rewritten to use NewFI.
    484   const Value *OldSV = PseudoSourceValue::getFixedStack(OldFI);
    485   const Value *NewSV = PseudoSourceValue::getFixedStack(NewFI);
    486   for (MachineInstr::mmo_iterator I = MI->memoperands_begin(),
    487        E = MI->memoperands_end(); I != E; ++I)
    488     if ((*I)->getValue() == OldSV)
    489       (*I)->setValue(NewSV);
    490 }
    491 
    492 /// PropagateBackward - Traverse backward and look for the definition of
    493 /// OldReg. If it can successfully update all of the references with NewReg,
    494 /// do so and return true.
    495 bool StackSlotColoring::PropagateBackward(MachineBasicBlock::iterator MII,
    496                                           MachineBasicBlock *MBB,
    497                                           unsigned OldReg, unsigned NewReg) {
    498   if (MII == MBB->begin())
    499     return false;
    500 
    501   SmallVector<MachineOperand*, 4> Uses;
    502   SmallVector<MachineOperand*, 4> Refs;
    503   while (--MII != MBB->begin()) {
    504     bool FoundDef = false;  // Not counting 2address def.
    505 
    506     Uses.clear();
    507     const MCInstrDesc &MCID = MII->getDesc();
    508     for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
    509       MachineOperand &MO = MII->getOperand(i);
    510       if (!MO.isReg())
    511         continue;
    512       unsigned Reg = MO.getReg();
    513       if (Reg == 0)
    514         continue;
    515       if (Reg == OldReg) {
    516         if (MO.isImplicit())
    517           return false;
    518 
    519         // Abort the use is actually a sub-register def. We don't have enough
    520         // information to figure out if it is really legal.
    521         if (MO.getSubReg() || MII->isSubregToReg())
    522           return false;
    523 
    524         const TargetRegisterClass *RC = TII->getRegClass(MCID, i, TRI);
    525         if (RC && !RC->contains(NewReg))
    526           return false;
    527 
    528         if (MO.isUse()) {
    529           Uses.push_back(&MO);
    530         } else {
    531           Refs.push_back(&MO);
    532           if (!MII->isRegTiedToUseOperand(i))
    533             FoundDef = true;
    534         }
    535       } else if (TRI->regsOverlap(Reg, NewReg)) {
    536         return false;
    537       } else if (TRI->regsOverlap(Reg, OldReg)) {
    538         if (!MO.isUse() || !MO.isKill())
    539           return false;
    540       }
    541     }
    542 
    543     if (FoundDef) {
    544       // Found non-two-address def. Stop here.
    545       for (unsigned i = 0, e = Refs.size(); i != e; ++i)
    546         Refs[i]->setReg(NewReg);
    547       return true;
    548     }
    549 
    550     // Two-address uses must be updated as well.
    551     for (unsigned i = 0, e = Uses.size(); i != e; ++i)
    552       Refs.push_back(Uses[i]);
    553   }
    554   return false;
    555 }
    556 
    557 /// PropagateForward - Traverse forward and look for the kill of OldReg. If
    558 /// it can successfully update all of the uses with NewReg, do so and
    559 /// return true.
    560 bool StackSlotColoring::PropagateForward(MachineBasicBlock::iterator MII,
    561                                          MachineBasicBlock *MBB,
    562                                          unsigned OldReg, unsigned NewReg) {
    563   if (MII == MBB->end())
    564     return false;
    565 
    566   SmallVector<MachineOperand*, 4> Uses;
    567   while (++MII != MBB->end()) {
    568     bool FoundKill = false;
    569     const MCInstrDesc &MCID = MII->getDesc();
    570     for (unsigned i = 0, e = MII->getNumOperands(); i != e; ++i) {
    571       MachineOperand &MO = MII->getOperand(i);
    572       if (!MO.isReg())
    573         continue;
    574       unsigned Reg = MO.getReg();
    575       if (Reg == 0)
    576         continue;
    577       if (Reg == OldReg) {
    578         if (MO.isDef() || MO.isImplicit())
    579           return false;
    580 
    581         // Abort the use is actually a sub-register use. We don't have enough
    582         // information to figure out if it is really legal.
    583         if (MO.getSubReg())
    584           return false;
    585 
    586         const TargetRegisterClass *RC = TII->getRegClass(MCID, i, TRI);
    587         if (RC && !RC->contains(NewReg))
    588           return false;
    589         if (MO.isKill())
    590           FoundKill = true;
    591 
    592         Uses.push_back(&MO);
    593       } else if (TRI->regsOverlap(Reg, NewReg) ||
    594                  TRI->regsOverlap(Reg, OldReg))
    595         return false;
    596     }
    597     if (FoundKill) {
    598       for (unsigned i = 0, e = Uses.size(); i != e; ++i)
    599         Uses[i]->setReg(NewReg);
    600       return true;
    601     }
    602   }
    603   return false;
    604 }
    605 
    606 /// UnfoldAndRewriteInstruction - Rewrite specified instruction by unfolding
    607 /// folded memory references and replacing those references with register
    608 /// references instead.
    609 void
    610 StackSlotColoring::UnfoldAndRewriteInstruction(MachineInstr *MI, int OldFI,
    611                                                unsigned Reg,
    612                                                const TargetRegisterClass *RC,
    613                                                SmallSet<unsigned, 4> &Defs,
    614                                                MachineFunction &MF) {
    615   MachineBasicBlock *MBB = MI->getParent();
    616   if (unsigned DstReg = TII->isLoadFromStackSlot(MI, OldFI)) {
    617     if (PropagateForward(MI, MBB, DstReg, Reg)) {
    618       DEBUG(dbgs() << "Eliminated load: ");
    619       DEBUG(MI->dump());
    620       ++NumLoadElim;
    621     } else {
    622       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY),
    623               DstReg).addReg(Reg);
    624       ++NumRegRepl;
    625     }
    626 
    627     if (!Defs.count(Reg)) {
    628       // If this is the first use of Reg in this MBB and it wasn't previously
    629       // defined in MBB, add it to livein.
    630       MBB->addLiveIn(Reg);
    631       Defs.insert(Reg);
    632     }
    633   } else if (unsigned SrcReg = TII->isStoreToStackSlot(MI, OldFI)) {
    634     if (MI->killsRegister(SrcReg) && PropagateBackward(MI, MBB, SrcReg, Reg)) {
    635       DEBUG(dbgs() << "Eliminated store: ");
    636       DEBUG(MI->dump());
    637       ++NumStoreElim;
    638     } else {
    639       BuildMI(*MBB, MI, MI->getDebugLoc(), TII->get(TargetOpcode::COPY), Reg)
    640         .addReg(SrcReg);
    641       ++NumRegRepl;
    642     }
    643 
    644     // Remember reg has been defined in MBB.
    645     Defs.insert(Reg);
    646   } else {
    647     SmallVector<MachineInstr*, 4> NewMIs;
    648     bool Success = TII->unfoldMemoryOperand(MF, MI, Reg, false, false, NewMIs);
    649     (void)Success; // Silence compiler warning.
    650     assert(Success && "Failed to unfold!");
    651     MachineInstr *NewMI = NewMIs[0];
    652     MBB->insert(MI, NewMI);
    653     ++NumRegRepl;
    654 
    655     if (NewMI->readsRegister(Reg)) {
    656       if (!Defs.count(Reg))
    657         // If this is the first use of Reg in this MBB and it wasn't previously
    658         // defined in MBB, add it to livein.
    659         MBB->addLiveIn(Reg);
    660       Defs.insert(Reg);
    661     }
    662   }
    663   MBB->erase(MI);
    664 }
    665 
    666 /// RemoveDeadStores - Scan through a basic block and look for loads followed
    667 /// by stores.  If they're both using the same stack slot, then the store is
    668 /// definitely dead.  This could obviously be much more aggressive (consider
    669 /// pairs with instructions between them), but such extensions might have a
    670 /// considerable compile time impact.
    671 bool StackSlotColoring::RemoveDeadStores(MachineBasicBlock* MBB) {
    672   // FIXME: This could be much more aggressive, but we need to investigate
    673   // the compile time impact of doing so.
    674   bool changed = false;
    675 
    676   SmallVector<MachineInstr*, 4> toErase;
    677 
    678   for (MachineBasicBlock::iterator I = MBB->begin(), E = MBB->end();
    679        I != E; ++I) {
    680     if (DCELimit != -1 && (int)NumDead >= DCELimit)
    681       break;
    682 
    683     MachineBasicBlock::iterator NextMI = llvm::next(I);
    684     if (NextMI == MBB->end()) continue;
    685 
    686     int FirstSS, SecondSS;
    687     unsigned LoadReg = 0;
    688     unsigned StoreReg = 0;
    689     if (!(LoadReg = TII->isLoadFromStackSlot(I, FirstSS))) continue;
    690     if (!(StoreReg = TII->isStoreToStackSlot(NextMI, SecondSS))) continue;
    691     if (FirstSS != SecondSS || LoadReg != StoreReg || FirstSS == -1) continue;
    692 
    693     ++NumDead;
    694     changed = true;
    695 
    696     if (NextMI->findRegisterUseOperandIdx(LoadReg, true, 0) != -1) {
    697       ++NumDead;
    698       toErase.push_back(I);
    699     }
    700 
    701     toErase.push_back(NextMI);
    702     ++I;
    703   }
    704 
    705   for (SmallVector<MachineInstr*, 4>::iterator I = toErase.begin(),
    706        E = toErase.end(); I != E; ++I)
    707     (*I)->eraseFromParent();
    708 
    709   return changed;
    710 }
    711 
    712 
    713 bool StackSlotColoring::runOnMachineFunction(MachineFunction &MF) {
    714   DEBUG({
    715       dbgs() << "********** Stack Slot Coloring **********\n"
    716              << "********** Function: "
    717              << MF.getFunction()->getName() << '\n';
    718     });
    719 
    720   MFI = MF.getFrameInfo();
    721   MRI = &MF.getRegInfo();
    722   TII = MF.getTarget().getInstrInfo();
    723   TRI = MF.getTarget().getRegisterInfo();
    724   LS = &getAnalysis<LiveStacks>();
    725   VRM = &getAnalysis<VirtRegMap>();
    726   loopInfo = &getAnalysis<MachineLoopInfo>();
    727 
    728   bool Changed = false;
    729 
    730   unsigned NumSlots = LS->getNumIntervals();
    731   if (NumSlots < 2) {
    732     if (NumSlots == 0 || !VRM->HasUnusedRegisters())
    733       // Nothing to do!
    734       return false;
    735   }
    736 
    737   // If there are calls to setjmp or sigsetjmp, don't perform stack slot
    738   // coloring. The stack could be modified before the longjmp is executed,
    739   // resulting in the wrong value being used afterwards. (See
    740   // <rdar://problem/8007500>.)
    741   if (MF.callsSetJmp())
    742     return false;
    743 
    744   // Gather spill slot references
    745   ScanForSpillSlotRefs(MF);
    746   InitializeSlots();
    747   Changed = ColorSlots(MF);
    748 
    749   NextColor = -1;
    750   SSIntervals.clear();
    751   for (unsigned i = 0, e = SSRefs.size(); i != e; ++i)
    752     SSRefs[i].clear();
    753   SSRefs.clear();
    754   OrigAlignments.clear();
    755   OrigSizes.clear();
    756   AllColors.clear();
    757   UsedColors.clear();
    758   for (unsigned i = 0, e = Assignments.size(); i != e; ++i)
    759     Assignments[i].clear();
    760   Assignments.clear();
    761 
    762   if (Changed) {
    763     for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
    764       Changed |= RemoveDeadStores(I);
    765   }
    766 
    767   return Changed;
    768 }
    769