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