StackColoring.cpp revision 18e2c290940b67c9dc1196e3c2234e7a20f60ae4
1//===-- StackColoring.cpp -------------------------------------------------===// 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 pass implements the stack-coloring optimization that looks for 11// lifetime markers machine instructions (LIFESTART_BEGIN and LIFESTART_END), 12// which represent the possible lifetime of stack slots. It attempts to 13// merge disjoint stack slots and reduce the used stack space. 14// NOTE: This pass is not StackSlotColoring, which optimizes spill slots. 15// 16// TODO: In the future we plan to improve stack coloring in the following ways: 17// 1. Allow merging multiple small slots into a single larger slot at different 18// offsets. 19// 2. Merge this pass with StackSlotColoring and allow merging of allocas with 20// spill slots. 21// 22//===----------------------------------------------------------------------===// 23 24#define DEBUG_TYPE "stackcoloring" 25#include "MachineTraceMetrics.h" 26#include "llvm/Function.h" 27#include "llvm/Module.h" 28#include "llvm/ADT/BitVector.h" 29#include "llvm/Analysis/Dominators.h" 30#include "llvm/Analysis/ValueTracking.h" 31#include "llvm/ADT/DepthFirstIterator.h" 32#include "llvm/ADT/PostOrderIterator.h" 33#include "llvm/ADT/SetVector.h" 34#include "llvm/ADT/SmallPtrSet.h" 35#include "llvm/ADT/SparseSet.h" 36#include "llvm/ADT/Statistic.h" 37#include "llvm/CodeGen/LiveInterval.h" 38#include "llvm/CodeGen/MachineLoopInfo.h" 39#include "llvm/CodeGen/MachineBranchProbabilityInfo.h" 40#include "llvm/CodeGen/MachineDominators.h" 41#include "llvm/CodeGen/MachineBasicBlock.h" 42#include "llvm/CodeGen/MachineFunctionPass.h" 43#include "llvm/CodeGen/MachineLoopInfo.h" 44#include "llvm/CodeGen/MachineModuleInfo.h" 45#include "llvm/CodeGen/MachineRegisterInfo.h" 46#include "llvm/CodeGen/MachineFrameInfo.h" 47#include "llvm/CodeGen/MachineMemOperand.h" 48#include "llvm/CodeGen/Passes.h" 49#include "llvm/CodeGen/SlotIndexes.h" 50#include "llvm/DebugInfo.h" 51#include "llvm/MC/MCInstrItineraries.h" 52#include "llvm/Target/TargetInstrInfo.h" 53#include "llvm/Target/TargetRegisterInfo.h" 54#include "llvm/Support/CommandLine.h" 55#include "llvm/Support/Debug.h" 56#include "llvm/Support/raw_ostream.h" 57 58using namespace llvm; 59 60static cl::opt<bool> 61DisableColoring("no-stack-coloring", 62 cl::init(false), cl::Hidden, 63 cl::desc("Disable stack coloring")); 64 65 66/// The user may write code that uses allocas outside of the declared lifetime 67/// zone. This can happen when the user returns a reference to a local 68/// data-structure. We can detect these cases and decide not to optimize the 69/// code. If this flag is enabled, we try to save the user. 70static cl::opt<bool> 71ProtectFromEscapedAllocas("protect-from-escaped-allocas", 72 cl::init(true), cl::Hidden, 73 cl::desc("Do not optimize lifetime zones that are broken")); 74 75STATISTIC(NumMarkerSeen, "Number of lifetime markers found."); 76STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots."); 77STATISTIC(StackSlotMerged, "Number of stack slot merged."); 78STATISTIC(EscapedAllocas, 79 "Number of allocas that escaped the lifetime region"); 80 81//===----------------------------------------------------------------------===// 82// StackColoring Pass 83//===----------------------------------------------------------------------===// 84 85namespace { 86/// StackColoring - A machine pass for merging disjoint stack allocations, 87/// marked by the LIFETIME_START and LIFETIME_END pseudo instructions. 88class StackColoring : public MachineFunctionPass { 89 MachineFrameInfo *MFI; 90 MachineFunction *MF; 91 92 /// A class representing liveness information for a single basic block. 93 /// Each bit in the BitVector represents the liveness property 94 /// for a different stack slot. 95 struct BlockLifetimeInfo { 96 /// Which slots BEGINs in each basic block. 97 BitVector Begin; 98 /// Which slots ENDs in each basic block. 99 BitVector End; 100 /// Which slots are marked as LIVE_IN, coming into each basic block. 101 BitVector LiveIn; 102 /// Which slots are marked as LIVE_OUT, coming out of each basic block. 103 BitVector LiveOut; 104 }; 105 106 /// Maps active slots (per bit) for each basic block. 107 DenseMap<MachineBasicBlock*, BlockLifetimeInfo> BlockLiveness; 108 109 /// Maps serial numbers to basic blocks. 110 DenseMap<MachineBasicBlock*, int> BasicBlocks; 111 /// Maps basic blocks to a serial number. 112 SmallVector<MachineBasicBlock*, 8> BasicBlockNumbering; 113 114 /// Maps liveness intervals for each slot. 115 SmallVector<LiveInterval*, 16> Intervals; 116 /// VNInfo is used for the construction of LiveIntervals. 117 VNInfo::Allocator VNInfoAllocator; 118 /// SlotIndex analysis object. 119 SlotIndexes *Indexes; 120 121 /// The list of lifetime markers found. These markers are to be removed 122 /// once the coloring is done. 123 SmallVector<MachineInstr*, 8> Markers; 124 125 /// SlotSizeSorter - A Sort utility for arranging stack slots according 126 /// to their size. 127 struct SlotSizeSorter { 128 MachineFrameInfo *MFI; 129 SlotSizeSorter(MachineFrameInfo *mfi) : MFI(mfi) { } 130 bool operator()(int LHS, int RHS) { 131 // We use -1 to denote a uninteresting slot. Place these slots at the end. 132 if (LHS == -1) return false; 133 if (RHS == -1) return true; 134 // Sort according to size. 135 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS); 136 } 137}; 138 139public: 140 static char ID; 141 StackColoring() : MachineFunctionPass(ID) { 142 initializeStackColoringPass(*PassRegistry::getPassRegistry()); 143 } 144 void getAnalysisUsage(AnalysisUsage &AU) const; 145 bool runOnMachineFunction(MachineFunction &MF); 146 147private: 148 /// Debug. 149 void dump(); 150 151 /// Removes all of the lifetime marker instructions from the function. 152 /// \returns true if any markers were removed. 153 bool removeAllMarkers(); 154 155 /// Scan the machine function and find all of the lifetime markers. 156 /// Record the findings in the BEGIN and END vectors. 157 /// \returns the number of markers found. 158 unsigned collectMarkers(unsigned NumSlot); 159 160 /// Perform the dataflow calculation and calculate the lifetime for each of 161 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and 162 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming 163 /// in and out blocks. 164 void calculateLocalLiveness(); 165 166 /// Construct the LiveIntervals for the slots. 167 void calculateLiveIntervals(unsigned NumSlots); 168 169 /// Go over the machine function and change instructions which use stack 170 /// slots to use the joint slots. 171 void remapInstructions(DenseMap<int, int> &SlotRemap); 172 173 /// The input program may contain intructions which are not inside lifetime 174 /// markers. This can happen due to a bug in the compiler or due to a bug in 175 /// user code (for example, returning a reference to a local variable). 176 /// This procedure checks all of the instructions in the function and 177 /// invalidates lifetime ranges which do not contain all of the instructions 178 /// which access that frame slot. 179 void removeInvalidSlotRanges(); 180 181 /// Map entries which point to other entries to their destination. 182 /// A->B->C becomes A->C. 183 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots); 184}; 185} // end anonymous namespace 186 187char StackColoring::ID = 0; 188char &llvm::StackColoringID = StackColoring::ID; 189 190INITIALIZE_PASS_BEGIN(StackColoring, 191 "stack-coloring", "Merge disjoint stack slots", false, false) 192INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 193INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 194INITIALIZE_PASS_END(StackColoring, 195 "stack-coloring", "Merge disjoint stack slots", false, false) 196 197void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const { 198 AU.addRequired<MachineDominatorTree>(); 199 AU.addPreserved<MachineDominatorTree>(); 200 AU.addRequired<SlotIndexes>(); 201 MachineFunctionPass::getAnalysisUsage(AU); 202} 203 204void StackColoring::dump() { 205 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF); 206 FI != FE; ++FI) { 207 unsigned Num = BasicBlocks[*FI]; 208 DEBUG(dbgs()<<"Inspecting block #"<<Num<<" ["<<FI->getName()<<"]\n"); 209 Num = 0; 210 DEBUG(dbgs()<<"BEGIN : {"); 211 for (unsigned i=0; i < BlockLiveness[*FI].Begin.size(); ++i) 212 DEBUG(dbgs()<<BlockLiveness[*FI].Begin.test(i)<<" "); 213 DEBUG(dbgs()<<"}\n"); 214 215 DEBUG(dbgs()<<"END : {"); 216 for (unsigned i=0; i < BlockLiveness[*FI].End.size(); ++i) 217 DEBUG(dbgs()<<BlockLiveness[*FI].End.test(i)<<" "); 218 219 DEBUG(dbgs()<<"}\n"); 220 221 DEBUG(dbgs()<<"LIVE_IN: {"); 222 for (unsigned i=0; i < BlockLiveness[*FI].LiveIn.size(); ++i) 223 DEBUG(dbgs()<<BlockLiveness[*FI].LiveIn.test(i)<<" "); 224 225 DEBUG(dbgs()<<"}\n"); 226 DEBUG(dbgs()<<"LIVEOUT: {"); 227 for (unsigned i=0; i < BlockLiveness[*FI].LiveOut.size(); ++i) 228 DEBUG(dbgs()<<BlockLiveness[*FI].LiveOut.test(i)<<" "); 229 DEBUG(dbgs()<<"}\n"); 230 } 231} 232 233unsigned StackColoring::collectMarkers(unsigned NumSlot) { 234 unsigned MarkersFound = 0; 235 // Scan the function to find all lifetime markers. 236 // NOTE: We use the a reverse-post-order iteration to ensure that we obtain a 237 // deterministic numbering, and because we'll need a post-order iteration 238 // later for solving the liveness dataflow problem. 239 for (df_iterator<MachineFunction*> FI = df_begin(MF), FE = df_end(MF); 240 FI != FE; ++FI) { 241 242 // Assign a serial number to this basic block. 243 BasicBlocks[*FI] = BasicBlockNumbering.size(); 244 BasicBlockNumbering.push_back(*FI); 245 246 BlockLiveness[*FI].Begin.resize(NumSlot); 247 BlockLiveness[*FI].End.resize(NumSlot); 248 249 for (MachineBasicBlock::iterator BI = (*FI)->begin(), BE = (*FI)->end(); 250 BI != BE; ++BI) { 251 252 if (BI->getOpcode() != TargetOpcode::LIFETIME_START && 253 BI->getOpcode() != TargetOpcode::LIFETIME_END) 254 continue; 255 256 Markers.push_back(BI); 257 258 bool IsStart = BI->getOpcode() == TargetOpcode::LIFETIME_START; 259 MachineOperand &MI = BI->getOperand(0); 260 unsigned Slot = MI.getIndex(); 261 262 MarkersFound++; 263 264 const Value *Allocation = MFI->getObjectAllocation(Slot); 265 if (Allocation) { 266 DEBUG(dbgs()<<"Found a lifetime marker for slot #"<<Slot<< 267 " with allocation: "<< Allocation->getName()<<"\n"); 268 } 269 270 if (IsStart) { 271 BlockLiveness[*FI].Begin.set(Slot); 272 } else { 273 if (BlockLiveness[*FI].Begin.test(Slot)) { 274 // Allocas that start and end within a single block are handled 275 // specially when computing the LiveIntervals to avoid pessimizing 276 // the liveness propagation. 277 BlockLiveness[*FI].Begin.reset(Slot); 278 } else { 279 BlockLiveness[*FI].End.set(Slot); 280 } 281 } 282 } 283 } 284 285 // Update statistics. 286 NumMarkerSeen += MarkersFound; 287 return MarkersFound; 288} 289 290void StackColoring::calculateLocalLiveness() { 291 // Perform a standard reverse dataflow computation to solve for 292 // global liveness. The BEGIN set here is equivalent to KILL in the standard 293 // formulation, and END is equivalent to GEN. The result of this computation 294 // is a map from blocks to bitvectors where the bitvectors represent which 295 // allocas are live in/out of that block. 296 SmallPtrSet<MachineBasicBlock*, 8> BBSet(BasicBlockNumbering.begin(), 297 BasicBlockNumbering.end()); 298 unsigned NumSSMIters = 0; 299 bool changed = true; 300 while (changed) { 301 changed = false; 302 ++NumSSMIters; 303 304 SmallPtrSet<MachineBasicBlock*, 8> NextBBSet; 305 306 for (SmallVector<MachineBasicBlock*, 8>::iterator 307 PI = BasicBlockNumbering.begin(), PE = BasicBlockNumbering.end(); 308 PI != PE; ++PI) { 309 310 MachineBasicBlock *BB = *PI; 311 if (!BBSet.count(BB)) continue; 312 313 BitVector LocalLiveIn; 314 BitVector LocalLiveOut; 315 316 // Forward propagation from begins to ends. 317 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(), 318 PE = BB->pred_end(); PI != PE; ++PI) 319 LocalLiveIn |= BlockLiveness[*PI].LiveOut; 320 LocalLiveIn |= BlockLiveness[BB].End; 321 LocalLiveIn.reset(BlockLiveness[BB].Begin); 322 323 // Reverse propagation from ends to begins. 324 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 325 SE = BB->succ_end(); SI != SE; ++SI) 326 LocalLiveOut |= BlockLiveness[*SI].LiveIn; 327 LocalLiveOut |= BlockLiveness[BB].Begin; 328 LocalLiveOut.reset(BlockLiveness[BB].End); 329 330 LocalLiveIn |= LocalLiveOut; 331 LocalLiveOut |= LocalLiveIn; 332 333 // After adopting the live bits, we need to turn-off the bits which 334 // are de-activated in this block. 335 LocalLiveOut.reset(BlockLiveness[BB].End); 336 LocalLiveIn.reset(BlockLiveness[BB].Begin); 337 338 // If we have both BEGIN and END markers in the same basic block then 339 // we know that the BEGIN marker comes after the END, because we already 340 // handle the case where the BEGIN comes before the END when collecting 341 // the markers (and building the BEGIN/END vectore). 342 // Want to enable the LIVE_IN and LIVE_OUT of slots that have both 343 // BEGIN and END because it means that the value lives before and after 344 // this basic block. 345 BitVector LocalEndBegin = BlockLiveness[BB].End; 346 LocalEndBegin &= BlockLiveness[BB].Begin; 347 LocalLiveIn |= LocalEndBegin; 348 LocalLiveOut |= LocalEndBegin; 349 350 if (LocalLiveIn.test(BlockLiveness[BB].LiveIn)) { 351 changed = true; 352 BlockLiveness[BB].LiveIn |= LocalLiveIn; 353 354 for (MachineBasicBlock::pred_iterator PI = BB->pred_begin(), 355 PE = BB->pred_end(); PI != PE; ++PI) 356 NextBBSet.insert(*PI); 357 } 358 359 if (LocalLiveOut.test(BlockLiveness[BB].LiveOut)) { 360 changed = true; 361 BlockLiveness[BB].LiveOut |= LocalLiveOut; 362 363 for (MachineBasicBlock::succ_iterator SI = BB->succ_begin(), 364 SE = BB->succ_end(); SI != SE; ++SI) 365 NextBBSet.insert(*SI); 366 } 367 } 368 369 BBSet = NextBBSet; 370 }// while changed. 371} 372 373void StackColoring::calculateLiveIntervals(unsigned NumSlots) { 374 SmallVector<SlotIndex, 16> Starts; 375 SmallVector<SlotIndex, 16> Finishes; 376 377 // For each block, find which slots are active within this block 378 // and update the live intervals. 379 for (MachineFunction::iterator MBB = MF->begin(), MBBe = MF->end(); 380 MBB != MBBe; ++MBB) { 381 Starts.clear(); 382 Starts.resize(NumSlots); 383 Finishes.clear(); 384 Finishes.resize(NumSlots); 385 386 // Create the interval for the basic blocks with lifetime markers in them. 387 for (SmallVector<MachineInstr*, 8>::iterator it = Markers.begin(), 388 e = Markers.end(); it != e; ++it) { 389 MachineInstr *MI = *it; 390 if (MI->getParent() != MBB) 391 continue; 392 393 assert((MI->getOpcode() == TargetOpcode::LIFETIME_START || 394 MI->getOpcode() == TargetOpcode::LIFETIME_END) && 395 "Invalid Lifetime marker"); 396 397 bool IsStart = MI->getOpcode() == TargetOpcode::LIFETIME_START; 398 MachineOperand &Mo = MI->getOperand(0); 399 int Slot = Mo.getIndex(); 400 assert(Slot >= 0 && "Invalid slot"); 401 402 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI); 403 404 if (IsStart) { 405 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex) 406 Starts[Slot] = ThisIndex; 407 } else { 408 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex) 409 Finishes[Slot] = ThisIndex; 410 } 411 } 412 413 // Create the interval of the blocks that we previously found to be 'alive'. 414 BitVector Alive = BlockLiveness[MBB].LiveIn; 415 Alive |= BlockLiveness[MBB].LiveOut; 416 417 if (Alive.any()) { 418 for (int pos = Alive.find_first(); pos != -1; 419 pos = Alive.find_next(pos)) { 420 if (!Starts[pos].isValid()) 421 Starts[pos] = Indexes->getMBBStartIdx(MBB); 422 if (!Finishes[pos].isValid()) 423 Finishes[pos] = Indexes->getMBBEndIdx(MBB); 424 } 425 } 426 427 for (unsigned i = 0; i < NumSlots; ++i) { 428 assert(Starts[i].isValid() == Finishes[i].isValid() && "Unmatched range"); 429 if (!Starts[i].isValid()) 430 continue; 431 432 assert(Starts[i] && Finishes[i] && "Invalid interval"); 433 VNInfo *ValNum = Intervals[i]->getValNumInfo(0); 434 SlotIndex S = Starts[i]; 435 SlotIndex F = Finishes[i]; 436 if (S < F) { 437 // We have a single consecutive region. 438 Intervals[i]->addRange(LiveRange(S, F, ValNum)); 439 } else { 440 // We have two non consecutive regions. This happens when 441 // LIFETIME_START appears after the LIFETIME_END marker. 442 SlotIndex NewStart = Indexes->getMBBStartIdx(MBB); 443 SlotIndex NewFin = Indexes->getMBBEndIdx(MBB); 444 Intervals[i]->addRange(LiveRange(NewStart, F, ValNum)); 445 Intervals[i]->addRange(LiveRange(S, NewFin, ValNum)); 446 } 447 } 448 } 449} 450 451bool StackColoring::removeAllMarkers() { 452 unsigned Count = 0; 453 for (unsigned i = 0; i < Markers.size(); ++i) { 454 Markers[i]->eraseFromParent(); 455 Count++; 456 } 457 Markers.clear(); 458 459 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n"); 460 return Count; 461} 462 463void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) { 464 unsigned FixedInstr = 0; 465 unsigned FixedMemOp = 0; 466 unsigned FixedDbg = 0; 467 MachineModuleInfo *MMI = &MF->getMMI(); 468 469 // Remap debug information that refers to stack slots. 470 MachineModuleInfo::VariableDbgInfoMapTy &VMap = MMI->getVariableDbgInfo(); 471 for (MachineModuleInfo::VariableDbgInfoMapTy::iterator VI = VMap.begin(), 472 VE = VMap.end(); VI != VE; ++VI) { 473 const MDNode *Var = VI->first; 474 if (!Var) continue; 475 std::pair<unsigned, DebugLoc> &VP = VI->second; 476 if (SlotRemap.count(VP.first)) { 477 DEBUG(dbgs()<<"Remapping debug info for ["<<Var->getName()<<"].\n"); 478 VP.first = SlotRemap[VP.first]; 479 FixedDbg++; 480 } 481 } 482 483 // Keep a list of *allocas* which need to be remapped. 484 DenseMap<const Value*, const Value*> Allocas; 485 for (DenseMap<int, int>::iterator it = SlotRemap.begin(), 486 e = SlotRemap.end(); it != e; ++it) { 487 const Value *From = MFI->getObjectAllocation(it->first); 488 const Value *To = MFI->getObjectAllocation(it->second); 489 assert(To && From && "Invalid allocation object"); 490 Allocas[From] = To; 491 } 492 493 // Remap all instructions to the new stack slots. 494 MachineFunction::iterator BB, BBE; 495 MachineBasicBlock::iterator I, IE; 496 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB) 497 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) { 498 499 // Skip lifetime markers. We'll remove them soon. 500 if (I->getOpcode() == TargetOpcode::LIFETIME_START || 501 I->getOpcode() == TargetOpcode::LIFETIME_END) 502 continue; 503 504 // Update the MachineMemOperand to use the new alloca. 505 for (MachineInstr::mmo_iterator MM = I->memoperands_begin(), 506 E = I->memoperands_end(); MM != E; ++MM) { 507 MachineMemOperand *MMO = *MM; 508 509 const Value *V = MMO->getValue(); 510 511 if (!V) 512 continue; 513 514 // Climb up and find the original alloca. 515 V = GetUnderlyingObject(V); 516 // If we did not find one, or if the one that we found is not in our 517 // map, then move on. 518 if (!V || !Allocas.count(V)) 519 continue; 520 521 MMO->setValue(Allocas[V]); 522 FixedMemOp++; 523 } 524 525 // Update all of the machine instruction operands. 526 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) { 527 MachineOperand &MO = I->getOperand(i); 528 529 if (!MO.isFI()) 530 continue; 531 int FromSlot = MO.getIndex(); 532 533 // Don't touch arguments. 534 if (FromSlot<0) 535 continue; 536 537 // Only look at mapped slots. 538 if (!SlotRemap.count(FromSlot)) 539 continue; 540 541 // In a debug build, check that the instruction that we are modifying is 542 // inside the expected live range. If the instruction is not inside 543 // the calculated range then it means that the alloca usage moved 544 // outside of the lifetime markers, or that the user has a bug. 545 // NOTE: Alloca address calculations which happen outside the lifetime 546 // zone are are okay, despite the fact that we don't have a good way 547 // for validating all of the usages of the calculation. 548#ifndef NDEBUG 549 bool TouchesMemory = I->mayLoad() || I->mayStore(); 550 // If we *don't* protect the user from escaped allocas, don't bother 551 // validating the instructions. 552 if (!I->isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) { 553 SlotIndex Index = Indexes->getInstructionIndex(I); 554 LiveInterval *Interval = Intervals[FromSlot]; 555 assert(Interval->find(Index) != Interval->end() && 556 "Found instruction usage outside of live range."); 557 } 558#endif 559 560 // Fix the machine instructions. 561 int ToSlot = SlotRemap[FromSlot]; 562 MO.setIndex(ToSlot); 563 FixedInstr++; 564 } 565 } 566 567 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n"); 568 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n"); 569 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n"); 570} 571 572void StackColoring::removeInvalidSlotRanges() { 573 MachineFunction::iterator BB, BBE; 574 MachineBasicBlock::iterator I, IE; 575 for (BB = MF->begin(), BBE = MF->end(); BB != BBE; ++BB) 576 for (I = BB->begin(), IE = BB->end(); I != IE; ++I) { 577 578 if (I->getOpcode() == TargetOpcode::LIFETIME_START || 579 I->getOpcode() == TargetOpcode::LIFETIME_END || I->isDebugValue()) 580 continue; 581 582 // Some intervals are suspicious! In some cases we find address 583 // calculations outside of the lifetime zone, but not actual memory 584 // read or write. Memory accesses outside of the lifetime zone are a clear 585 // violation, but address calculations are okay. This can happen when 586 // GEPs are hoisted outside of the lifetime zone. 587 // So, in here we only check instructions which can read or write memory. 588 if (!I->mayLoad() && !I->mayStore()) 589 continue; 590 591 // Check all of the machine operands. 592 for (unsigned i = 0 ; i < I->getNumOperands(); ++i) { 593 MachineOperand &MO = I->getOperand(i); 594 595 if (!MO.isFI()) 596 continue; 597 598 int Slot = MO.getIndex(); 599 600 if (Slot<0) 601 continue; 602 603 if (Intervals[Slot]->empty()) 604 continue; 605 606 // Check that the used slot is inside the calculated lifetime range. 607 // If it is not, warn about it and invalidate the range. 608 LiveInterval *Interval = Intervals[Slot]; 609 SlotIndex Index = Indexes->getInstructionIndex(I); 610 if (Interval->find(Index) == Interval->end()) { 611 Intervals[Slot]->clear(); 612 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n"); 613 EscapedAllocas++; 614 } 615 } 616 } 617} 618 619void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap, 620 unsigned NumSlots) { 621 // Expunge slot remap map. 622 for (unsigned i=0; i < NumSlots; ++i) { 623 // If we are remapping i 624 if (SlotRemap.count(i)) { 625 int Target = SlotRemap[i]; 626 // As long as our target is mapped to something else, follow it. 627 while (SlotRemap.count(Target)) { 628 Target = SlotRemap[Target]; 629 SlotRemap[i] = Target; 630 } 631 } 632 } 633} 634 635bool StackColoring::runOnMachineFunction(MachineFunction &Func) { 636 DEBUG(dbgs() << "********** Stack Coloring **********\n" 637 << "********** Function: " 638 << ((const Value*)Func.getFunction())->getName() << '\n'); 639 MF = &Func; 640 MFI = MF->getFrameInfo(); 641 Indexes = &getAnalysis<SlotIndexes>(); 642 BlockLiveness.clear(); 643 BasicBlocks.clear(); 644 BasicBlockNumbering.clear(); 645 Markers.clear(); 646 Intervals.clear(); 647 VNInfoAllocator.Reset(); 648 649 unsigned NumSlots = MFI->getObjectIndexEnd(); 650 651 // If there are no stack slots then there are no markers to remove. 652 if (!NumSlots) 653 return false; 654 655 SmallVector<int, 8> SortedSlots; 656 657 SortedSlots.reserve(NumSlots); 658 Intervals.reserve(NumSlots); 659 660 unsigned NumMarkers = collectMarkers(NumSlots); 661 662 unsigned TotalSize = 0; 663 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n"); 664 DEBUG(dbgs()<<"Slot structure:\n"); 665 666 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) { 667 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n"); 668 TotalSize += MFI->getObjectSize(i); 669 } 670 671 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n"); 672 673 // Don't continue because there are not enough lifetime markers, or the 674 // stack is too small, or we are told not to optimize the slots. 675 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring) { 676 DEBUG(dbgs()<<"Will not try to merge slots.\n"); 677 return removeAllMarkers(); 678 } 679 680 for (unsigned i=0; i < NumSlots; ++i) { 681 LiveInterval *LI = new LiveInterval(i, 0); 682 Intervals.push_back(LI); 683 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator); 684 SortedSlots.push_back(i); 685 } 686 687 // Calculate the liveness of each block. 688 calculateLocalLiveness(); 689 690 // Propagate the liveness information. 691 calculateLiveIntervals(NumSlots); 692 693 // Search for allocas which are used outside of the declared lifetime 694 // markers. 695 if (ProtectFromEscapedAllocas) 696 removeInvalidSlotRanges(); 697 698 // Maps old slots to new slots. 699 DenseMap<int, int> SlotRemap; 700 unsigned RemovedSlots = 0; 701 unsigned ReducedSize = 0; 702 703 // Do not bother looking at empty intervals. 704 for (unsigned I = 0; I < NumSlots; ++I) { 705 if (Intervals[SortedSlots[I]]->empty()) 706 SortedSlots[I] = -1; 707 } 708 709 // This is a simple greedy algorithm for merging allocas. First, sort the 710 // slots, placing the largest slots first. Next, perform an n^2 scan and look 711 // for disjoint slots. When you find disjoint slots, merge the samller one 712 // into the bigger one and update the live interval. Remove the small alloca 713 // and continue. 714 715 // Sort the slots according to their size. Place unused slots at the end. 716 std::sort(SortedSlots.begin(), SortedSlots.end(), SlotSizeSorter(MFI)); 717 718 bool Chanded = true; 719 while (Chanded) { 720 Chanded = false; 721 for (unsigned I = 0; I < NumSlots; ++I) { 722 if (SortedSlots[I] == -1) 723 continue; 724 725 for (unsigned J=I+1; J < NumSlots; ++J) { 726 if (SortedSlots[J] == -1) 727 continue; 728 729 int FirstSlot = SortedSlots[I]; 730 int SecondSlot = SortedSlots[J]; 731 LiveInterval *First = Intervals[FirstSlot]; 732 LiveInterval *Second = Intervals[SecondSlot]; 733 assert (!First->empty() && !Second->empty() && "Found an empty range"); 734 735 // Merge disjoint slots. 736 if (!First->overlaps(*Second)) { 737 Chanded = true; 738 First->MergeRangesInAsValue(*Second, First->getValNumInfo(0)); 739 SlotRemap[SecondSlot] = FirstSlot; 740 SortedSlots[J] = -1; 741 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<< 742 SecondSlot<<" together.\n"); 743 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot), 744 MFI->getObjectAlignment(SecondSlot)); 745 746 assert(MFI->getObjectSize(FirstSlot) >= 747 MFI->getObjectSize(SecondSlot) && 748 "Merging a small object into a larger one"); 749 750 RemovedSlots+=1; 751 ReducedSize += MFI->getObjectSize(SecondSlot); 752 MFI->setObjectAlignment(FirstSlot, MaxAlignment); 753 MFI->RemoveStackObject(SecondSlot); 754 } 755 } 756 } 757 }// While changed. 758 759 // Record statistics. 760 StackSpaceSaved += ReducedSize; 761 StackSlotMerged += RemovedSlots; 762 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<< 763 ReducedSize<<" bytes\n"); 764 765 // Scan the entire function and update all machine operands that use frame 766 // indices to use the remapped frame index. 767 expungeSlotMap(SlotRemap, NumSlots); 768 remapInstructions(SlotRemap); 769 770 // Release the intervals. 771 for (unsigned I = 0; I < NumSlots; ++I) { 772 delete Intervals[I]; 773 } 774 775 return removeAllMarkers(); 776} 777