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. This option 68 /// is treated as overriding LifetimeStartOnFirstUse below. 69 static cl::opt<bool> 70 ProtectFromEscapedAllocas("protect-from-escaped-allocas", 71 cl::init(false), cl::Hidden, 72 cl::desc("Do not optimize lifetime zones that " 73 "are broken")); 74 75 /// Enable enhanced dataflow scheme for lifetime analysis (treat first 76 /// use of stack slot as start of slot lifetime, as opposed to looking 77 /// for LIFETIME_START marker). See "Implementation notes" below for 78 /// more info. FIXME: set to false for the moment due to PR27903. 79 static cl::opt<bool> 80 LifetimeStartOnFirstUse("stackcoloring-lifetime-start-on-first-use", 81 cl::init(false), cl::Hidden, 82 cl::desc("Treat stack lifetimes as starting on first use, not on START marker.")); 83 84 85 STATISTIC(NumMarkerSeen, "Number of lifetime markers found."); 86 STATISTIC(StackSpaceSaved, "Number of bytes saved due to merging slots."); 87 STATISTIC(StackSlotMerged, "Number of stack slot merged."); 88 STATISTIC(EscapedAllocas, "Number of allocas that escaped the lifetime region"); 89 90 // 91 // Implementation Notes: 92 // --------------------- 93 // 94 // Consider the following motivating example: 95 // 96 // int foo() { 97 // char b1[1024], b2[1024]; 98 // if (...) { 99 // char b3[1024]; 100 // <uses of b1, b3>; 101 // return x; 102 // } else { 103 // char b4[1024], b5[1024]; 104 // <uses of b2, b4, b5>; 105 // return y; 106 // } 107 // } 108 // 109 // In the code above, "b3" and "b4" are declared in distinct lexical 110 // scopes, meaning that it is easy to prove that they can share the 111 // same stack slot. Variables "b1" and "b2" are declared in the same 112 // scope, meaning that from a lexical point of view, their lifetimes 113 // overlap. From a control flow pointer of view, however, the two 114 // variables are accessed in disjoint regions of the CFG, thus it 115 // should be possible for them to share the same stack slot. An ideal 116 // stack allocation for the function above would look like: 117 // 118 // slot 0: b1, b2 119 // slot 1: b3, b4 120 // slot 2: b5 121 // 122 // Achieving this allocation is tricky, however, due to the way 123 // lifetime markers are inserted. Here is a simplified view of the 124 // control flow graph for the code above: 125 // 126 // +------ block 0 -------+ 127 // 0| LIFETIME_START b1, b2 | 128 // 1| <test 'if' condition> | 129 // +-----------------------+ 130 // ./ \. 131 // +------ block 1 -------+ +------ block 2 -------+ 132 // 2| LIFETIME_START b3 | 5| LIFETIME_START b4, b5 | 133 // 3| <uses of b1, b3> | 6| <uses of b2, b4, b5> | 134 // 4| LIFETIME_END b3 | 7| LIFETIME_END b4, b5 | 135 // +-----------------------+ +-----------------------+ 136 // \. /. 137 // +------ block 3 -------+ 138 // 8| <cleanupcode> | 139 // 9| LIFETIME_END b1, b2 | 140 // 10| return | 141 // +-----------------------+ 142 // 143 // If we create live intervals for the variables above strictly based 144 // on the lifetime markers, we'll get the set of intervals on the 145 // left. If we ignore the lifetime start markers and instead treat a 146 // variable's lifetime as beginning with the first reference to the 147 // var, then we get the intervals on the right. 148 // 149 // LIFETIME_START First Use 150 // b1: [0,9] [3,4] [8,9] 151 // b2: [0,9] [6,9] 152 // b3: [2,4] [3,4] 153 // b4: [5,7] [6,7] 154 // b5: [5,7] [6,7] 155 // 156 // For the intervals on the left, the best we can do is overlap two 157 // variables (b3 and b4, for example); this gives us a stack size of 158 // 4*1024 bytes, not ideal. When treating first-use as the start of a 159 // lifetime, we can additionally overlap b1 and b5, giving us a 3*1024 160 // byte stack (better). 161 // 162 // Relying entirely on first-use of stack slots is problematic, 163 // however, due to the fact that optimizations can sometimes migrate 164 // uses of a variable outside of its lifetime start/end region. Here 165 // is an example: 166 // 167 // int bar() { 168 // char b1[1024], b2[1024]; 169 // if (...) { 170 // <uses of b2> 171 // return y; 172 // } else { 173 // <uses of b1> 174 // while (...) { 175 // char b3[1024]; 176 // <uses of b3> 177 // } 178 // } 179 // } 180 // 181 // Before optimization, the control flow graph for the code above 182 // might look like the following: 183 // 184 // +------ block 0 -------+ 185 // 0| LIFETIME_START b1, b2 | 186 // 1| <test 'if' condition> | 187 // +-----------------------+ 188 // ./ \. 189 // +------ block 1 -------+ +------- block 2 -------+ 190 // 2| <uses of b2> | 3| <uses of b1> | 191 // +-----------------------+ +-----------------------+ 192 // | | 193 // | +------- block 3 -------+ <-\. 194 // | 4| <while condition> | | 195 // | +-----------------------+ | 196 // | / | | 197 // | / +------- block 4 -------+ 198 // \ / 5| LIFETIME_START b3 | | 199 // \ / 6| <uses of b3> | | 200 // \ / 7| LIFETIME_END b3 | | 201 // \ | +------------------------+ | 202 // \ | \ / 203 // +------ block 5 -----+ \--------------- 204 // 8| <cleanupcode> | 205 // 9| LIFETIME_END b1, b2 | 206 // 10| return | 207 // +---------------------+ 208 // 209 // During optimization, however, it can happen that an instruction 210 // computing an address in "b3" (for example, a loop-invariant GEP) is 211 // hoisted up out of the loop from block 4 to block 2. [Note that 212 // this is not an actual load from the stack, only an instruction that 213 // computes the address to be loaded]. If this happens, there is now a 214 // path leading from the first use of b3 to the return instruction 215 // that does not encounter the b3 LIFETIME_END, hence b3's lifetime is 216 // now larger than if we were computing live intervals strictly based 217 // on lifetime markers. In the example above, this lengthened lifetime 218 // would mean that it would appear illegal to overlap b3 with b2. 219 // 220 // To deal with this such cases, the code in ::collectMarkers() below 221 // tries to identify "degenerate" slots -- those slots where on a single 222 // forward pass through the CFG we encounter a first reference to slot 223 // K before we hit the slot K lifetime start marker. For such slots, 224 // we fall back on using the lifetime start marker as the beginning of 225 // the variable's lifetime. NB: with this implementation, slots can 226 // appear degenerate in cases where there is unstructured control flow: 227 // 228 // if (q) goto mid; 229 // if (x > 9) { 230 // int b[100]; 231 // memcpy(&b[0], ...); 232 // mid: b[k] = ...; 233 // abc(&b); 234 // } 235 // 236 // If in RPO ordering chosen to walk the CFG we happen to visit the b[k] 237 // before visiting the memcpy block (which will contain the lifetime start 238 // for "b" then it will appear that 'b' has a degenerate lifetime. 239 // 240 241 //===----------------------------------------------------------------------===// 242 // StackColoring Pass 243 //===----------------------------------------------------------------------===// 244 245 namespace { 246 /// StackColoring - A machine pass for merging disjoint stack allocations, 247 /// marked by the LIFETIME_START and LIFETIME_END pseudo instructions. 248 class StackColoring : public MachineFunctionPass { 249 MachineFrameInfo *MFI; 250 MachineFunction *MF; 251 252 /// A class representing liveness information for a single basic block. 253 /// Each bit in the BitVector represents the liveness property 254 /// for a different stack slot. 255 struct BlockLifetimeInfo { 256 /// Which slots BEGINs in each basic block. 257 BitVector Begin; 258 /// Which slots ENDs in each basic block. 259 BitVector End; 260 /// Which slots are marked as LIVE_IN, coming into each basic block. 261 BitVector LiveIn; 262 /// Which slots are marked as LIVE_OUT, coming out of each basic block. 263 BitVector LiveOut; 264 }; 265 266 /// Maps active slots (per bit) for each basic block. 267 typedef DenseMap<const MachineBasicBlock*, BlockLifetimeInfo> LivenessMap; 268 LivenessMap BlockLiveness; 269 270 /// Maps serial numbers to basic blocks. 271 DenseMap<const MachineBasicBlock*, int> BasicBlocks; 272 /// Maps basic blocks to a serial number. 273 SmallVector<const MachineBasicBlock*, 8> BasicBlockNumbering; 274 275 /// Maps liveness intervals for each slot. 276 SmallVector<std::unique_ptr<LiveInterval>, 16> Intervals; 277 /// VNInfo is used for the construction of LiveIntervals. 278 VNInfo::Allocator VNInfoAllocator; 279 /// SlotIndex analysis object. 280 SlotIndexes *Indexes; 281 /// The stack protector object. 282 StackProtector *SP; 283 284 /// The list of lifetime markers found. These markers are to be removed 285 /// once the coloring is done. 286 SmallVector<MachineInstr*, 8> Markers; 287 288 /// Record the FI slots for which we have seen some sort of 289 /// lifetime marker (either start or end). 290 BitVector InterestingSlots; 291 292 /// Degenerate slots -- first use appears outside of start/end 293 /// lifetime markers. 294 BitVector DegenerateSlots; 295 296 /// Number of iterations taken during data flow analysis. 297 unsigned NumIterations; 298 299 public: 300 static char ID; 301 StackColoring() : MachineFunctionPass(ID) { 302 initializeStackColoringPass(*PassRegistry::getPassRegistry()); 303 } 304 void getAnalysisUsage(AnalysisUsage &AU) const override; 305 bool runOnMachineFunction(MachineFunction &MF) override; 306 307 private: 308 /// Debug. 309 void dump() const; 310 void dumpIntervals() const; 311 void dumpBB(MachineBasicBlock *MBB) const; 312 void dumpBV(const char *tag, const BitVector &BV) const; 313 314 /// Removes all of the lifetime marker instructions from the function. 315 /// \returns true if any markers were removed. 316 bool removeAllMarkers(); 317 318 /// Scan the machine function and find all of the lifetime markers. 319 /// Record the findings in the BEGIN and END vectors. 320 /// \returns the number of markers found. 321 unsigned collectMarkers(unsigned NumSlot); 322 323 /// Perform the dataflow calculation and calculate the lifetime for each of 324 /// the slots, based on the BEGIN/END vectors. Set the LifetimeLIVE_IN and 325 /// LifetimeLIVE_OUT maps that represent which stack slots are live coming 326 /// in and out blocks. 327 void calculateLocalLiveness(); 328 329 /// Returns TRUE if we're using the first-use-begins-lifetime method for 330 /// this slot (if FALSE, then the start marker is treated as start of lifetime). 331 bool applyFirstUse(int Slot) { 332 if (!LifetimeStartOnFirstUse || ProtectFromEscapedAllocas) 333 return false; 334 if (DegenerateSlots.test(Slot)) 335 return false; 336 return true; 337 } 338 339 /// Examines the specified instruction and returns TRUE if the instruction 340 /// represents the start or end of an interesting lifetime. The slot or slots 341 /// starting or ending are added to the vector "slots" and "isStart" is set 342 /// accordingly. 343 /// \returns True if inst contains a lifetime start or end 344 bool isLifetimeStartOrEnd(const MachineInstr &MI, 345 SmallVector<int, 4> &slots, 346 bool &isStart); 347 348 /// Construct the LiveIntervals for the slots. 349 void calculateLiveIntervals(unsigned NumSlots); 350 351 /// Go over the machine function and change instructions which use stack 352 /// slots to use the joint slots. 353 void remapInstructions(DenseMap<int, int> &SlotRemap); 354 355 /// The input program may contain instructions which are not inside lifetime 356 /// markers. This can happen due to a bug in the compiler or due to a bug in 357 /// user code (for example, returning a reference to a local variable). 358 /// This procedure checks all of the instructions in the function and 359 /// invalidates lifetime ranges which do not contain all of the instructions 360 /// which access that frame slot. 361 void removeInvalidSlotRanges(); 362 363 /// Map entries which point to other entries to their destination. 364 /// A->B->C becomes A->C. 365 void expungeSlotMap(DenseMap<int, int> &SlotRemap, unsigned NumSlots); 366 367 /// Used in collectMarkers 368 typedef DenseMap<const MachineBasicBlock*, BitVector> BlockBitVecMap; 369 }; 370 } // end anonymous namespace 371 372 char StackColoring::ID = 0; 373 char &llvm::StackColoringID = StackColoring::ID; 374 375 INITIALIZE_PASS_BEGIN(StackColoring, 376 "stack-coloring", "Merge disjoint stack slots", false, false) 377 INITIALIZE_PASS_DEPENDENCY(SlotIndexes) 378 INITIALIZE_PASS_DEPENDENCY(StackProtector) 379 INITIALIZE_PASS_END(StackColoring, 380 "stack-coloring", "Merge disjoint stack slots", false, false) 381 382 void StackColoring::getAnalysisUsage(AnalysisUsage &AU) const { 383 AU.addRequired<SlotIndexes>(); 384 AU.addRequired<StackProtector>(); 385 MachineFunctionPass::getAnalysisUsage(AU); 386 } 387 388 #ifndef NDEBUG 389 390 LLVM_DUMP_METHOD void StackColoring::dumpBV(const char *tag, 391 const BitVector &BV) const { 392 DEBUG(dbgs() << tag << " : { "); 393 for (unsigned I = 0, E = BV.size(); I != E; ++I) 394 DEBUG(dbgs() << BV.test(I) << " "); 395 DEBUG(dbgs() << "}\n"); 396 } 397 398 LLVM_DUMP_METHOD void StackColoring::dumpBB(MachineBasicBlock *MBB) const { 399 LivenessMap::const_iterator BI = BlockLiveness.find(MBB); 400 assert(BI != BlockLiveness.end() && "Block not found"); 401 const BlockLifetimeInfo &BlockInfo = BI->second; 402 403 dumpBV("BEGIN", BlockInfo.Begin); 404 dumpBV("END", BlockInfo.End); 405 dumpBV("LIVE_IN", BlockInfo.LiveIn); 406 dumpBV("LIVE_OUT", BlockInfo.LiveOut); 407 } 408 409 LLVM_DUMP_METHOD void StackColoring::dump() const { 410 for (MachineBasicBlock *MBB : depth_first(MF)) { 411 DEBUG(dbgs() << "Inspecting block #" << MBB->getNumber() << " [" 412 << MBB->getName() << "]\n"); 413 DEBUG(dumpBB(MBB)); 414 } 415 } 416 417 LLVM_DUMP_METHOD void StackColoring::dumpIntervals() const { 418 for (unsigned I = 0, E = Intervals.size(); I != E; ++I) { 419 DEBUG(dbgs() << "Interval[" << I << "]:\n"); 420 DEBUG(Intervals[I]->dump()); 421 } 422 } 423 424 #endif // not NDEBUG 425 426 static inline int getStartOrEndSlot(const MachineInstr &MI) 427 { 428 assert((MI.getOpcode() == TargetOpcode::LIFETIME_START || 429 MI.getOpcode() == TargetOpcode::LIFETIME_END) && 430 "Expected LIFETIME_START or LIFETIME_END op"); 431 const MachineOperand &MO = MI.getOperand(0); 432 int Slot = MO.getIndex(); 433 if (Slot >= 0) 434 return Slot; 435 return -1; 436 } 437 438 // 439 // At the moment the only way to end a variable lifetime is with 440 // a VARIABLE_LIFETIME op (which can't contain a start). If things 441 // change and the IR allows for a single inst that both begins 442 // and ends lifetime(s), this interface will need to be reworked. 443 // 444 bool StackColoring::isLifetimeStartOrEnd(const MachineInstr &MI, 445 SmallVector<int, 4> &slots, 446 bool &isStart) 447 { 448 if (MI.getOpcode() == TargetOpcode::LIFETIME_START || 449 MI.getOpcode() == TargetOpcode::LIFETIME_END) { 450 int Slot = getStartOrEndSlot(MI); 451 if (Slot < 0) 452 return false; 453 if (!InterestingSlots.test(Slot)) 454 return false; 455 slots.push_back(Slot); 456 if (MI.getOpcode() == TargetOpcode::LIFETIME_END) { 457 isStart = false; 458 return true; 459 } 460 if (! applyFirstUse(Slot)) { 461 isStart = true; 462 return true; 463 } 464 } else if (LifetimeStartOnFirstUse && !ProtectFromEscapedAllocas) { 465 if (! MI.isDebugValue()) { 466 bool found = false; 467 for (const MachineOperand &MO : MI.operands()) { 468 if (!MO.isFI()) 469 continue; 470 int Slot = MO.getIndex(); 471 if (Slot<0) 472 continue; 473 if (InterestingSlots.test(Slot) && applyFirstUse(Slot)) { 474 slots.push_back(Slot); 475 found = true; 476 } 477 } 478 if (found) { 479 isStart = true; 480 return true; 481 } 482 } 483 } 484 return false; 485 } 486 487 unsigned StackColoring::collectMarkers(unsigned NumSlot) 488 { 489 unsigned MarkersFound = 0; 490 BlockBitVecMap SeenStartMap; 491 InterestingSlots.clear(); 492 InterestingSlots.resize(NumSlot); 493 DegenerateSlots.clear(); 494 DegenerateSlots.resize(NumSlot); 495 496 // Step 1: collect markers and populate the "InterestingSlots" 497 // and "DegenerateSlots" sets. 498 for (MachineBasicBlock *MBB : depth_first(MF)) { 499 500 // Compute the set of slots for which we've seen a START marker but have 501 // not yet seen an END marker at this point in the walk (e.g. on entry 502 // to this bb). 503 BitVector BetweenStartEnd; 504 BetweenStartEnd.resize(NumSlot); 505 for (MachineBasicBlock::const_pred_iterator PI = MBB->pred_begin(), 506 PE = MBB->pred_end(); PI != PE; ++PI) { 507 BlockBitVecMap::const_iterator I = SeenStartMap.find(*PI); 508 if (I != SeenStartMap.end()) { 509 BetweenStartEnd |= I->second; 510 } 511 } 512 513 // Walk the instructions in the block to look for start/end ops. 514 for (MachineInstr &MI : *MBB) { 515 if (MI.getOpcode() == TargetOpcode::LIFETIME_START || 516 MI.getOpcode() == TargetOpcode::LIFETIME_END) { 517 int Slot = getStartOrEndSlot(MI); 518 if (Slot < 0) 519 continue; 520 InterestingSlots.set(Slot); 521 if (MI.getOpcode() == TargetOpcode::LIFETIME_START) 522 BetweenStartEnd.set(Slot); 523 else 524 BetweenStartEnd.reset(Slot); 525 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot); 526 if (Allocation) { 527 DEBUG(dbgs() << "Found a lifetime "); 528 DEBUG(dbgs() << (MI.getOpcode() == TargetOpcode::LIFETIME_START 529 ? "start" 530 : "end")); 531 DEBUG(dbgs() << " marker for slot #" << Slot); 532 DEBUG(dbgs() << " with allocation: " << Allocation->getName() 533 << "\n"); 534 } 535 Markers.push_back(&MI); 536 MarkersFound += 1; 537 } else { 538 for (const MachineOperand &MO : MI.operands()) { 539 if (!MO.isFI()) 540 continue; 541 int Slot = MO.getIndex(); 542 if (Slot < 0) 543 continue; 544 if (! BetweenStartEnd.test(Slot)) { 545 DegenerateSlots.set(Slot); 546 } 547 } 548 } 549 } 550 BitVector &SeenStart = SeenStartMap[MBB]; 551 SeenStart |= BetweenStartEnd; 552 } 553 if (!MarkersFound) { 554 return 0; 555 } 556 DEBUG(dumpBV("Degenerate slots", DegenerateSlots)); 557 558 // Step 2: compute begin/end sets for each block 559 560 // NOTE: We use a reverse-post-order iteration to ensure that we obtain a 561 // deterministic numbering, and because we'll need a post-order iteration 562 // later for solving the liveness dataflow problem. 563 for (MachineBasicBlock *MBB : depth_first(MF)) { 564 565 // Assign a serial number to this basic block. 566 BasicBlocks[MBB] = BasicBlockNumbering.size(); 567 BasicBlockNumbering.push_back(MBB); 568 569 // Keep a reference to avoid repeated lookups. 570 BlockLifetimeInfo &BlockInfo = BlockLiveness[MBB]; 571 572 BlockInfo.Begin.resize(NumSlot); 573 BlockInfo.End.resize(NumSlot); 574 575 SmallVector<int, 4> slots; 576 for (MachineInstr &MI : *MBB) { 577 bool isStart = false; 578 slots.clear(); 579 if (isLifetimeStartOrEnd(MI, slots, isStart)) { 580 if (!isStart) { 581 assert(slots.size() == 1 && "unexpected: MI ends multiple slots"); 582 int Slot = slots[0]; 583 if (BlockInfo.Begin.test(Slot)) { 584 BlockInfo.Begin.reset(Slot); 585 } 586 BlockInfo.End.set(Slot); 587 } else { 588 for (auto Slot : slots) { 589 DEBUG(dbgs() << "Found a use of slot #" << Slot); 590 DEBUG(dbgs() << " at BB#" << MBB->getNumber() << " index "); 591 DEBUG(Indexes->getInstructionIndex(MI).print(dbgs())); 592 const AllocaInst *Allocation = MFI->getObjectAllocation(Slot); 593 if (Allocation) { 594 DEBUG(dbgs() << " with allocation: "<< Allocation->getName()); 595 } 596 DEBUG(dbgs() << "\n"); 597 if (BlockInfo.End.test(Slot)) { 598 BlockInfo.End.reset(Slot); 599 } 600 BlockInfo.Begin.set(Slot); 601 } 602 } 603 } 604 } 605 } 606 607 // Update statistics. 608 NumMarkerSeen += MarkersFound; 609 return MarkersFound; 610 } 611 612 void StackColoring::calculateLocalLiveness() 613 { 614 unsigned NumIters = 0; 615 bool changed = true; 616 while (changed) { 617 changed = false; 618 ++NumIters; 619 620 for (const MachineBasicBlock *BB : BasicBlockNumbering) { 621 622 // Use an iterator to avoid repeated lookups. 623 LivenessMap::iterator BI = BlockLiveness.find(BB); 624 assert(BI != BlockLiveness.end() && "Block not found"); 625 BlockLifetimeInfo &BlockInfo = BI->second; 626 627 // Compute LiveIn by unioning together the LiveOut sets of all preds. 628 BitVector LocalLiveIn; 629 for (MachineBasicBlock::const_pred_iterator PI = BB->pred_begin(), 630 PE = BB->pred_end(); PI != PE; ++PI) { 631 LivenessMap::const_iterator I = BlockLiveness.find(*PI); 632 assert(I != BlockLiveness.end() && "Predecessor not found"); 633 LocalLiveIn |= I->second.LiveOut; 634 } 635 636 // Compute LiveOut by subtracting out lifetimes that end in this 637 // block, then adding in lifetimes that begin in this block. If 638 // we have both BEGIN and END markers in the same basic block 639 // then we know that the BEGIN marker comes after the END, 640 // because we already handle the case where the BEGIN comes 641 // before the END when collecting the markers (and building the 642 // BEGIN/END vectors). 643 BitVector LocalLiveOut = LocalLiveIn; 644 LocalLiveOut.reset(BlockInfo.End); 645 LocalLiveOut |= BlockInfo.Begin; 646 647 // Update block LiveIn set, noting whether it has changed. 648 if (LocalLiveIn.test(BlockInfo.LiveIn)) { 649 changed = true; 650 BlockInfo.LiveIn |= LocalLiveIn; 651 } 652 653 // Update block LiveOut set, noting whether it has changed. 654 if (LocalLiveOut.test(BlockInfo.LiveOut)) { 655 changed = true; 656 BlockInfo.LiveOut |= LocalLiveOut; 657 } 658 } 659 }// while changed. 660 661 NumIterations = NumIters; 662 } 663 664 void StackColoring::calculateLiveIntervals(unsigned NumSlots) { 665 SmallVector<SlotIndex, 16> Starts; 666 SmallVector<SlotIndex, 16> Finishes; 667 668 // For each block, find which slots are active within this block 669 // and update the live intervals. 670 for (const MachineBasicBlock &MBB : *MF) { 671 Starts.clear(); 672 Starts.resize(NumSlots); 673 Finishes.clear(); 674 Finishes.resize(NumSlots); 675 676 // Create the interval for the basic blocks containing lifetime begin/end. 677 for (const MachineInstr &MI : MBB) { 678 679 SmallVector<int, 4> slots; 680 bool IsStart = false; 681 if (!isLifetimeStartOrEnd(MI, slots, IsStart)) 682 continue; 683 SlotIndex ThisIndex = Indexes->getInstructionIndex(MI); 684 for (auto Slot : slots) { 685 if (IsStart) { 686 if (!Starts[Slot].isValid() || Starts[Slot] > ThisIndex) 687 Starts[Slot] = ThisIndex; 688 } else { 689 if (!Finishes[Slot].isValid() || Finishes[Slot] < ThisIndex) 690 Finishes[Slot] = ThisIndex; 691 } 692 } 693 } 694 695 // Create the interval of the blocks that we previously found to be 'alive'. 696 BlockLifetimeInfo &MBBLiveness = BlockLiveness[&MBB]; 697 for (int pos = MBBLiveness.LiveIn.find_first(); pos != -1; 698 pos = MBBLiveness.LiveIn.find_next(pos)) { 699 Starts[pos] = Indexes->getMBBStartIdx(&MBB); 700 } 701 for (int pos = MBBLiveness.LiveOut.find_first(); pos != -1; 702 pos = MBBLiveness.LiveOut.find_next(pos)) { 703 Finishes[pos] = Indexes->getMBBEndIdx(&MBB); 704 } 705 706 for (unsigned i = 0; i < NumSlots; ++i) { 707 // 708 // When LifetimeStartOnFirstUse is turned on, data flow analysis 709 // is forward (from starts to ends), not bidirectional. A 710 // consequence of this is that we can wind up in situations 711 // where Starts[i] is invalid but Finishes[i] is valid and vice 712 // versa. Example: 713 // 714 // LIFETIME_START x 715 // if (...) { 716 // <use of x> 717 // throw ...; 718 // } 719 // LIFETIME_END x 720 // return 2; 721 // 722 // 723 // Here the slot for "x" will not be live into the block 724 // containing the "return 2" (since lifetimes start with first 725 // use, not at the dominating LIFETIME_START marker). 726 // 727 if (Starts[i].isValid() && !Finishes[i].isValid()) { 728 Finishes[i] = Indexes->getMBBEndIdx(&MBB); 729 } 730 if (!Starts[i].isValid()) 731 continue; 732 733 assert(Starts[i] && Finishes[i] && "Invalid interval"); 734 VNInfo *ValNum = Intervals[i]->getValNumInfo(0); 735 SlotIndex S = Starts[i]; 736 SlotIndex F = Finishes[i]; 737 if (S < F) { 738 // We have a single consecutive region. 739 Intervals[i]->addSegment(LiveInterval::Segment(S, F, ValNum)); 740 } else { 741 // We have two non-consecutive regions. This happens when 742 // LIFETIME_START appears after the LIFETIME_END marker. 743 SlotIndex NewStart = Indexes->getMBBStartIdx(&MBB); 744 SlotIndex NewFin = Indexes->getMBBEndIdx(&MBB); 745 Intervals[i]->addSegment(LiveInterval::Segment(NewStart, F, ValNum)); 746 Intervals[i]->addSegment(LiveInterval::Segment(S, NewFin, ValNum)); 747 } 748 } 749 } 750 } 751 752 bool StackColoring::removeAllMarkers() { 753 unsigned Count = 0; 754 for (MachineInstr *MI : Markers) { 755 MI->eraseFromParent(); 756 Count++; 757 } 758 Markers.clear(); 759 760 DEBUG(dbgs()<<"Removed "<<Count<<" markers.\n"); 761 return Count; 762 } 763 764 void StackColoring::remapInstructions(DenseMap<int, int> &SlotRemap) { 765 unsigned FixedInstr = 0; 766 unsigned FixedMemOp = 0; 767 unsigned FixedDbg = 0; 768 MachineModuleInfo *MMI = &MF->getMMI(); 769 770 // Remap debug information that refers to stack slots. 771 for (auto &VI : MMI->getVariableDbgInfo()) { 772 if (!VI.Var) 773 continue; 774 if (SlotRemap.count(VI.Slot)) { 775 DEBUG(dbgs() << "Remapping debug info for [" 776 << cast<DILocalVariable>(VI.Var)->getName() << "].\n"); 777 VI.Slot = SlotRemap[VI.Slot]; 778 FixedDbg++; 779 } 780 } 781 782 // Keep a list of *allocas* which need to be remapped. 783 DenseMap<const AllocaInst*, const AllocaInst*> Allocas; 784 for (const std::pair<int, int> &SI : SlotRemap) { 785 const AllocaInst *From = MFI->getObjectAllocation(SI.first); 786 const AllocaInst *To = MFI->getObjectAllocation(SI.second); 787 assert(To && From && "Invalid allocation object"); 788 Allocas[From] = To; 789 790 // AA might be used later for instruction scheduling, and we need it to be 791 // able to deduce the correct aliasing releationships between pointers 792 // derived from the alloca being remapped and the target of that remapping. 793 // The only safe way, without directly informing AA about the remapping 794 // somehow, is to directly update the IR to reflect the change being made 795 // here. 796 Instruction *Inst = const_cast<AllocaInst *>(To); 797 if (From->getType() != To->getType()) { 798 BitCastInst *Cast = new BitCastInst(Inst, From->getType()); 799 Cast->insertAfter(Inst); 800 Inst = Cast; 801 } 802 803 // Allow the stack protector to adjust its value map to account for the 804 // upcoming replacement. 805 SP->adjustForColoring(From, To); 806 807 // The new alloca might not be valid in a llvm.dbg.declare for this 808 // variable, so undef out the use to make the verifier happy. 809 AllocaInst *FromAI = const_cast<AllocaInst *>(From); 810 if (FromAI->isUsedByMetadata()) 811 ValueAsMetadata::handleRAUW(FromAI, UndefValue::get(FromAI->getType())); 812 for (auto &Use : FromAI->uses()) { 813 if (BitCastInst *BCI = dyn_cast<BitCastInst>(Use.get())) 814 if (BCI->isUsedByMetadata()) 815 ValueAsMetadata::handleRAUW(BCI, UndefValue::get(BCI->getType())); 816 } 817 818 // Note that this will not replace uses in MMOs (which we'll update below), 819 // or anywhere else (which is why we won't delete the original 820 // instruction). 821 FromAI->replaceAllUsesWith(Inst); 822 } 823 824 // Remap all instructions to the new stack slots. 825 for (MachineBasicBlock &BB : *MF) 826 for (MachineInstr &I : BB) { 827 // Skip lifetime markers. We'll remove them soon. 828 if (I.getOpcode() == TargetOpcode::LIFETIME_START || 829 I.getOpcode() == TargetOpcode::LIFETIME_END) 830 continue; 831 832 // Update the MachineMemOperand to use the new alloca. 833 for (MachineMemOperand *MMO : I.memoperands()) { 834 // FIXME: In order to enable the use of TBAA when using AA in CodeGen, 835 // we'll also need to update the TBAA nodes in MMOs with values 836 // derived from the merged allocas. When doing this, we'll need to use 837 // the same variant of GetUnderlyingObjects that is used by the 838 // instruction scheduler (that can look through ptrtoint/inttoptr 839 // pairs). 840 841 // We've replaced IR-level uses of the remapped allocas, so we only 842 // need to replace direct uses here. 843 const AllocaInst *AI = dyn_cast_or_null<AllocaInst>(MMO->getValue()); 844 if (!AI) 845 continue; 846 847 if (!Allocas.count(AI)) 848 continue; 849 850 MMO->setValue(Allocas[AI]); 851 FixedMemOp++; 852 } 853 854 // Update all of the machine instruction operands. 855 for (MachineOperand &MO : I.operands()) { 856 if (!MO.isFI()) 857 continue; 858 int FromSlot = MO.getIndex(); 859 860 // Don't touch arguments. 861 if (FromSlot<0) 862 continue; 863 864 // Only look at mapped slots. 865 if (!SlotRemap.count(FromSlot)) 866 continue; 867 868 // In a debug build, check that the instruction that we are modifying is 869 // inside the expected live range. If the instruction is not inside 870 // the calculated range then it means that the alloca usage moved 871 // outside of the lifetime markers, or that the user has a bug. 872 // NOTE: Alloca address calculations which happen outside the lifetime 873 // zone are are okay, despite the fact that we don't have a good way 874 // for validating all of the usages of the calculation. 875 #ifndef NDEBUG 876 bool TouchesMemory = I.mayLoad() || I.mayStore(); 877 // If we *don't* protect the user from escaped allocas, don't bother 878 // validating the instructions. 879 if (!I.isDebugValue() && TouchesMemory && ProtectFromEscapedAllocas) { 880 SlotIndex Index = Indexes->getInstructionIndex(I); 881 const LiveInterval *Interval = &*Intervals[FromSlot]; 882 assert(Interval->find(Index) != Interval->end() && 883 "Found instruction usage outside of live range."); 884 } 885 #endif 886 887 // Fix the machine instructions. 888 int ToSlot = SlotRemap[FromSlot]; 889 MO.setIndex(ToSlot); 890 FixedInstr++; 891 } 892 } 893 894 // Update the location of C++ catch objects for the MSVC personality routine. 895 if (WinEHFuncInfo *EHInfo = MF->getWinEHFuncInfo()) 896 for (WinEHTryBlockMapEntry &TBME : EHInfo->TryBlockMap) 897 for (WinEHHandlerType &H : TBME.HandlerArray) 898 if (H.CatchObj.FrameIndex != INT_MAX && 899 SlotRemap.count(H.CatchObj.FrameIndex)) 900 H.CatchObj.FrameIndex = SlotRemap[H.CatchObj.FrameIndex]; 901 902 DEBUG(dbgs()<<"Fixed "<<FixedMemOp<<" machine memory operands.\n"); 903 DEBUG(dbgs()<<"Fixed "<<FixedDbg<<" debug locations.\n"); 904 DEBUG(dbgs()<<"Fixed "<<FixedInstr<<" machine instructions.\n"); 905 } 906 907 void StackColoring::removeInvalidSlotRanges() { 908 for (MachineBasicBlock &BB : *MF) 909 for (MachineInstr &I : BB) { 910 if (I.getOpcode() == TargetOpcode::LIFETIME_START || 911 I.getOpcode() == TargetOpcode::LIFETIME_END || I.isDebugValue()) 912 continue; 913 914 // Some intervals are suspicious! In some cases we find address 915 // calculations outside of the lifetime zone, but not actual memory 916 // read or write. Memory accesses outside of the lifetime zone are a clear 917 // violation, but address calculations are okay. This can happen when 918 // GEPs are hoisted outside of the lifetime zone. 919 // So, in here we only check instructions which can read or write memory. 920 if (!I.mayLoad() && !I.mayStore()) 921 continue; 922 923 // Check all of the machine operands. 924 for (const MachineOperand &MO : I.operands()) { 925 if (!MO.isFI()) 926 continue; 927 928 int Slot = MO.getIndex(); 929 930 if (Slot<0) 931 continue; 932 933 if (Intervals[Slot]->empty()) 934 continue; 935 936 // Check that the used slot is inside the calculated lifetime range. 937 // If it is not, warn about it and invalidate the range. 938 LiveInterval *Interval = &*Intervals[Slot]; 939 SlotIndex Index = Indexes->getInstructionIndex(I); 940 if (Interval->find(Index) == Interval->end()) { 941 Interval->clear(); 942 DEBUG(dbgs()<<"Invalidating range #"<<Slot<<"\n"); 943 EscapedAllocas++; 944 } 945 } 946 } 947 } 948 949 void StackColoring::expungeSlotMap(DenseMap<int, int> &SlotRemap, 950 unsigned NumSlots) { 951 // Expunge slot remap map. 952 for (unsigned i=0; i < NumSlots; ++i) { 953 // If we are remapping i 954 if (SlotRemap.count(i)) { 955 int Target = SlotRemap[i]; 956 // As long as our target is mapped to something else, follow it. 957 while (SlotRemap.count(Target)) { 958 Target = SlotRemap[Target]; 959 SlotRemap[i] = Target; 960 } 961 } 962 } 963 } 964 965 bool StackColoring::runOnMachineFunction(MachineFunction &Func) { 966 DEBUG(dbgs() << "********** Stack Coloring **********\n" 967 << "********** Function: " 968 << ((const Value*)Func.getFunction())->getName() << '\n'); 969 MF = &Func; 970 MFI = MF->getFrameInfo(); 971 Indexes = &getAnalysis<SlotIndexes>(); 972 SP = &getAnalysis<StackProtector>(); 973 BlockLiveness.clear(); 974 BasicBlocks.clear(); 975 BasicBlockNumbering.clear(); 976 Markers.clear(); 977 Intervals.clear(); 978 VNInfoAllocator.Reset(); 979 980 unsigned NumSlots = MFI->getObjectIndexEnd(); 981 982 // If there are no stack slots then there are no markers to remove. 983 if (!NumSlots) 984 return false; 985 986 SmallVector<int, 8> SortedSlots; 987 SortedSlots.reserve(NumSlots); 988 Intervals.reserve(NumSlots); 989 990 unsigned NumMarkers = collectMarkers(NumSlots); 991 992 unsigned TotalSize = 0; 993 DEBUG(dbgs()<<"Found "<<NumMarkers<<" markers and "<<NumSlots<<" slots\n"); 994 DEBUG(dbgs()<<"Slot structure:\n"); 995 996 for (int i=0; i < MFI->getObjectIndexEnd(); ++i) { 997 DEBUG(dbgs()<<"Slot #"<<i<<" - "<<MFI->getObjectSize(i)<<" bytes.\n"); 998 TotalSize += MFI->getObjectSize(i); 999 } 1000 1001 DEBUG(dbgs()<<"Total Stack size: "<<TotalSize<<" bytes\n\n"); 1002 1003 // Don't continue because there are not enough lifetime markers, or the 1004 // stack is too small, or we are told not to optimize the slots. 1005 if (NumMarkers < 2 || TotalSize < 16 || DisableColoring || 1006 skipFunction(*Func.getFunction())) { 1007 DEBUG(dbgs()<<"Will not try to merge slots.\n"); 1008 return removeAllMarkers(); 1009 } 1010 1011 for (unsigned i=0; i < NumSlots; ++i) { 1012 std::unique_ptr<LiveInterval> LI(new LiveInterval(i, 0)); 1013 LI->getNextValue(Indexes->getZeroIndex(), VNInfoAllocator); 1014 Intervals.push_back(std::move(LI)); 1015 SortedSlots.push_back(i); 1016 } 1017 1018 // Calculate the liveness of each block. 1019 calculateLocalLiveness(); 1020 DEBUG(dbgs() << "Dataflow iterations: " << NumIterations << "\n"); 1021 DEBUG(dump()); 1022 1023 // Propagate the liveness information. 1024 calculateLiveIntervals(NumSlots); 1025 DEBUG(dumpIntervals()); 1026 1027 // Search for allocas which are used outside of the declared lifetime 1028 // markers. 1029 if (ProtectFromEscapedAllocas) 1030 removeInvalidSlotRanges(); 1031 1032 // Maps old slots to new slots. 1033 DenseMap<int, int> SlotRemap; 1034 unsigned RemovedSlots = 0; 1035 unsigned ReducedSize = 0; 1036 1037 // Do not bother looking at empty intervals. 1038 for (unsigned I = 0; I < NumSlots; ++I) { 1039 if (Intervals[SortedSlots[I]]->empty()) 1040 SortedSlots[I] = -1; 1041 } 1042 1043 // This is a simple greedy algorithm for merging allocas. First, sort the 1044 // slots, placing the largest slots first. Next, perform an n^2 scan and look 1045 // for disjoint slots. When you find disjoint slots, merge the samller one 1046 // into the bigger one and update the live interval. Remove the small alloca 1047 // and continue. 1048 1049 // Sort the slots according to their size. Place unused slots at the end. 1050 // Use stable sort to guarantee deterministic code generation. 1051 std::stable_sort(SortedSlots.begin(), SortedSlots.end(), 1052 [this](int LHS, int RHS) { 1053 // We use -1 to denote a uninteresting slot. Place these slots at the end. 1054 if (LHS == -1) return false; 1055 if (RHS == -1) return true; 1056 // Sort according to size. 1057 return MFI->getObjectSize(LHS) > MFI->getObjectSize(RHS); 1058 }); 1059 1060 bool Changed = true; 1061 while (Changed) { 1062 Changed = false; 1063 for (unsigned I = 0; I < NumSlots; ++I) { 1064 if (SortedSlots[I] == -1) 1065 continue; 1066 1067 for (unsigned J=I+1; J < NumSlots; ++J) { 1068 if (SortedSlots[J] == -1) 1069 continue; 1070 1071 int FirstSlot = SortedSlots[I]; 1072 int SecondSlot = SortedSlots[J]; 1073 LiveInterval *First = &*Intervals[FirstSlot]; 1074 LiveInterval *Second = &*Intervals[SecondSlot]; 1075 assert (!First->empty() && !Second->empty() && "Found an empty range"); 1076 1077 // Merge disjoint slots. 1078 if (!First->overlaps(*Second)) { 1079 Changed = true; 1080 First->MergeSegmentsInAsValue(*Second, First->getValNumInfo(0)); 1081 SlotRemap[SecondSlot] = FirstSlot; 1082 SortedSlots[J] = -1; 1083 DEBUG(dbgs()<<"Merging #"<<FirstSlot<<" and slots #"<< 1084 SecondSlot<<" together.\n"); 1085 unsigned MaxAlignment = std::max(MFI->getObjectAlignment(FirstSlot), 1086 MFI->getObjectAlignment(SecondSlot)); 1087 1088 assert(MFI->getObjectSize(FirstSlot) >= 1089 MFI->getObjectSize(SecondSlot) && 1090 "Merging a small object into a larger one"); 1091 1092 RemovedSlots+=1; 1093 ReducedSize += MFI->getObjectSize(SecondSlot); 1094 MFI->setObjectAlignment(FirstSlot, MaxAlignment); 1095 MFI->RemoveStackObject(SecondSlot); 1096 } 1097 } 1098 } 1099 }// While changed. 1100 1101 // Record statistics. 1102 StackSpaceSaved += ReducedSize; 1103 StackSlotMerged += RemovedSlots; 1104 DEBUG(dbgs()<<"Merge "<<RemovedSlots<<" slots. Saved "<< 1105 ReducedSize<<" bytes\n"); 1106 1107 // Scan the entire function and update all machine operands that use frame 1108 // indices to use the remapped frame index. 1109 expungeSlotMap(SlotRemap, NumSlots); 1110 remapInstructions(SlotRemap); 1111 1112 return removeAllMarkers(); 1113 } 1114