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