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