1 //===-- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function --===// 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 is responsible for finalizing the functions frame layout, saving 11 // callee saved registers, and for emitting prolog & epilog code for the 12 // function. 13 // 14 // This pass must be run after register allocation. After this pass is 15 // executed, it is illegal to construct MO_FrameIndex operands. 16 // 17 // This pass provides an optional shrink wrapping variant of prolog/epilog 18 // insertion, enabled via --shrink-wrap. See ShrinkWrapping.cpp. 19 // 20 //===----------------------------------------------------------------------===// 21 22 #define DEBUG_TYPE "pei" 23 #include "PrologEpilogInserter.h" 24 #include "llvm/CodeGen/MachineDominators.h" 25 #include "llvm/CodeGen/MachineLoopInfo.h" 26 #include "llvm/CodeGen/MachineInstr.h" 27 #include "llvm/CodeGen/MachineFrameInfo.h" 28 #include "llvm/CodeGen/MachineRegisterInfo.h" 29 #include "llvm/CodeGen/RegisterScavenging.h" 30 #include "llvm/Target/TargetMachine.h" 31 #include "llvm/Target/TargetRegisterInfo.h" 32 #include "llvm/Target/TargetFrameInfo.h" 33 #include "llvm/Target/TargetInstrInfo.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Compiler.h" 36 #include "llvm/Support/Debug.h" 37 #include "llvm/ADT/IndexedMap.h" 38 #include "llvm/ADT/SmallSet.h" 39 #include "llvm/ADT/Statistic.h" 40 #include "llvm/ADT/STLExtras.h" 41 #include <climits> 42 43 using namespace llvm; 44 45 char PEI::ID = 0; 46 47 INITIALIZE_PASS_BEGIN(PEI, "prologepilog", 48 "Prologue/Epilogue Insertion", false, false) 49 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 50 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 51 INITIALIZE_PASS_END(PEI, "prologepilog", 52 "Prologue/Epilogue Insertion", false, false) 53 54 STATISTIC(NumVirtualFrameRegs, "Number of virtual frame regs encountered"); 55 STATISTIC(NumScavengedRegs, "Number of frame index regs scavenged"); 56 57 /// createPrologEpilogCodeInserter - This function returns a pass that inserts 58 /// prolog and epilog code, and eliminates abstract frame references. 59 /// 60 FunctionPass *llvm::createPrologEpilogCodeInserter() { return new PEI(); } 61 62 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 63 /// frame indexes with appropriate references. 64 /// 65 bool PEI::runOnMachineFunction(MachineFunction &Fn) { 66 const Function* F = Fn.getFunction(); 67 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo(); 68 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : NULL; 69 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn); 70 71 // Calculate the MaxCallFrameSize and AdjustsStack variables for the 72 // function's frame information. Also eliminates call frame pseudo 73 // instructions. 74 calculateCallsInformation(Fn); 75 76 // Allow the target machine to make some adjustments to the function 77 // e.g. UsedPhysRegs before calculateCalleeSavedRegisters. 78 TRI->processFunctionBeforeCalleeSavedScan(Fn, RS); 79 80 // Scan the function for modified callee saved registers and insert spill code 81 // for any callee saved registers that are modified. 82 calculateCalleeSavedRegisters(Fn); 83 84 // Determine placement of CSR spill/restore code: 85 // - With shrink wrapping, place spills and restores to tightly 86 // enclose regions in the Machine CFG of the function where 87 // they are used. 88 // - Without shink wrapping (default), place all spills in the 89 // entry block, all restores in return blocks. 90 placeCSRSpillsAndRestores(Fn); 91 92 // Add the code to save and restore the callee saved registers 93 if (!F->hasFnAttr(Attribute::Naked)) 94 insertCSRSpillsAndRestores(Fn); 95 96 // Allow the target machine to make final modifications to the function 97 // before the frame layout is finalized. 98 TRI->processFunctionBeforeFrameFinalized(Fn); 99 100 // Calculate actual frame offsets for all abstract stack objects... 101 calculateFrameObjectOffsets(Fn); 102 103 // Add prolog and epilog code to the function. This function is required 104 // to align the stack frame as necessary for any stack variables or 105 // called functions. Because of this, calculateCalleeSavedRegisters() 106 // must be called before this function in order to set the AdjustsStack 107 // and MaxCallFrameSize variables. 108 if (!F->hasFnAttr(Attribute::Naked)) 109 insertPrologEpilogCode(Fn); 110 111 // Replace all MO_FrameIndex operands with physical register references 112 // and actual offsets. 113 // 114 replaceFrameIndices(Fn); 115 116 // If register scavenging is needed, as we've enabled doing it as a 117 // post-pass, scavenge the virtual registers that frame index elimiation 118 // inserted. 119 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) 120 scavengeFrameVirtualRegs(Fn); 121 122 delete RS; 123 clearAllSets(); 124 return true; 125 } 126 127 #if 0 128 void PEI::getAnalysisUsage(AnalysisUsage &AU) const { 129 AU.setPreservesCFG(); 130 if (ShrinkWrapping || ShrinkWrapFunc != "") { 131 AU.addRequired<MachineLoopInfo>(); 132 AU.addRequired<MachineDominatorTree>(); 133 } 134 AU.addPreserved<MachineLoopInfo>(); 135 AU.addPreserved<MachineDominatorTree>(); 136 MachineFunctionPass::getAnalysisUsage(AU); 137 } 138 #endif 139 140 /// calculateCallsInformation - Calculate the MaxCallFrameSize and AdjustsStack 141 /// variables for the function's frame information and eliminate call frame 142 /// pseudo instructions. 143 void PEI::calculateCallsInformation(MachineFunction &Fn) { 144 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 145 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo(); 146 MachineFrameInfo *MFI = Fn.getFrameInfo(); 147 148 unsigned MaxCallFrameSize = 0; 149 bool AdjustsStack = MFI->adjustsStack(); 150 151 // Get the function call frame set-up and tear-down instruction opcode 152 int FrameSetupOpcode = RegInfo->getCallFrameSetupOpcode(); 153 int FrameDestroyOpcode = RegInfo->getCallFrameDestroyOpcode(); 154 155 // Early exit for targets which have no call frame setup/destroy pseudo 156 // instructions. 157 if (FrameSetupOpcode == -1 && FrameDestroyOpcode == -1) 158 return; 159 160 std::vector<MachineBasicBlock::iterator> FrameSDOps; 161 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) 162 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) 163 if (I->getOpcode() == FrameSetupOpcode || 164 I->getOpcode() == FrameDestroyOpcode) { 165 assert(I->getNumOperands() >= 1 && "Call Frame Setup/Destroy Pseudo" 166 " instructions should have a single immediate argument!"); 167 unsigned Size = I->getOperand(0).getImm(); 168 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; 169 AdjustsStack = true; 170 FrameSDOps.push_back(I); 171 } else if (I->isInlineAsm()) { 172 // Some inline asm's need a stack frame, as indicated by operand 1. 173 if (I->getOperand(1).getImm()) 174 AdjustsStack = true; 175 } 176 177 MFI->setAdjustsStack(AdjustsStack); 178 MFI->setMaxCallFrameSize(MaxCallFrameSize); 179 180 for (std::vector<MachineBasicBlock::iterator>::iterator 181 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) { 182 MachineBasicBlock::iterator I = *i; 183 184 // If call frames are not being included as part of the stack frame, and 185 // the target doesn't indicate otherwise, remove the call frame pseudos 186 // here. The sub/add sp instruction pairs are still inserted, but we don't 187 // need to track the SP adjustment for frame index elimination. 188 if (TFI->canSimplifyCallFramePseudos(Fn)) 189 RegInfo->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I); 190 } 191 } 192 193 194 /// calculateCalleeSavedRegisters - Scan the function for modified callee saved 195 /// registers. 196 void PEI::calculateCalleeSavedRegisters(MachineFunction &Fn) { 197 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 198 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo(); 199 MachineFrameInfo *MFI = Fn.getFrameInfo(); 200 201 // Get the callee saved register list... 202 const unsigned *CSRegs = RegInfo->getCalleeSavedRegs(&Fn); 203 204 // These are used to keep track the callee-save area. Initialize them. 205 MinCSFrameIndex = INT_MAX; 206 MaxCSFrameIndex = 0; 207 208 // Early exit for targets which have no callee saved registers. 209 if (CSRegs == 0 || CSRegs[0] == 0) 210 return; 211 212 // In Naked functions we aren't going to save any registers. 213 if (Fn.getFunction()->hasFnAttr(Attribute::Naked)) 214 return; 215 216 std::vector<CalleeSavedInfo> CSI; 217 for (unsigned i = 0; CSRegs[i]; ++i) { 218 unsigned Reg = CSRegs[i]; 219 if (Fn.getRegInfo().isPhysRegUsed(Reg)) { 220 // If the reg is modified, save it! 221 CSI.push_back(CalleeSavedInfo(Reg)); 222 } else { 223 for (const unsigned *AliasSet = RegInfo->getAliasSet(Reg); 224 *AliasSet; ++AliasSet) { // Check alias registers too. 225 if (Fn.getRegInfo().isPhysRegUsed(*AliasSet)) { 226 CSI.push_back(CalleeSavedInfo(Reg)); 227 break; 228 } 229 } 230 } 231 } 232 233 if (CSI.empty()) 234 return; // Early exit if no callee saved registers are modified! 235 236 unsigned NumFixedSpillSlots; 237 const TargetFrameInfo::SpillSlot *FixedSpillSlots = 238 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots); 239 240 // Now that we know which registers need to be saved and restored, allocate 241 // stack slots for them. 242 for (std::vector<CalleeSavedInfo>::iterator 243 I = CSI.begin(), E = CSI.end(); I != E; ++I) { 244 unsigned Reg = I->getReg(); 245 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg); 246 247 int FrameIdx; 248 if (RegInfo->hasReservedSpillSlot(Fn, Reg, FrameIdx)) { 249 I->setFrameIdx(FrameIdx); 250 continue; 251 } 252 253 // Check to see if this physreg must be spilled to a particular stack slot 254 // on this target. 255 const TargetFrameInfo::SpillSlot *FixedSlot = FixedSpillSlots; 256 while (FixedSlot != FixedSpillSlots+NumFixedSpillSlots && 257 FixedSlot->Reg != Reg) 258 ++FixedSlot; 259 260 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) { 261 // Nope, just spill it anywhere convenient. 262 unsigned Align = RC->getAlignment(); 263 unsigned StackAlign = TFI->getStackAlignment(); 264 265 // We may not be able to satisfy the desired alignment specification of 266 // the TargetRegisterClass if the stack alignment is smaller. Use the 267 // min. 268 Align = std::min(Align, StackAlign); 269 FrameIdx = MFI->CreateStackObject(RC->getSize(), Align, true); 270 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; 271 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; 272 } else { 273 // Spill it to the stack where we must. 274 FrameIdx = MFI->CreateFixedObject(RC->getSize(), FixedSlot->Offset, true); 275 } 276 277 I->setFrameIdx(FrameIdx); 278 } 279 280 MFI->setCalleeSavedInfo(CSI); 281 } 282 283 /// insertCSRSpillsAndRestores - Insert spill and restore code for 284 /// callee saved registers used in the function, handling shrink wrapping. 285 /// 286 void PEI::insertCSRSpillsAndRestores(MachineFunction &Fn) { 287 // Get callee saved register information. 288 MachineFrameInfo *MFI = Fn.getFrameInfo(); 289 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo(); 290 291 MFI->setCalleeSavedInfoValid(true); 292 293 // Early exit if no callee saved registers are modified! 294 if (CSI.empty()) 295 return; 296 297 const TargetInstrInfo &TII = *Fn.getTarget().getInstrInfo(); 298 const TargetFrameInfo *TFI = Fn.getTarget().getFrameInfo(); 299 const TargetRegisterInfo *TRI = Fn.getTarget().getRegisterInfo(); 300 MachineBasicBlock::iterator I; 301 302 if (! ShrinkWrapThisFunction) { 303 // Spill using target interface. 304 I = EntryBlock->begin(); 305 if (!TFI->spillCalleeSavedRegisters(*EntryBlock, I, CSI, TRI)) { 306 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 307 // Add the callee-saved register as live-in. 308 // It's killed at the spill. 309 EntryBlock->addLiveIn(CSI[i].getReg()); 310 311 // Insert the spill to the stack frame. 312 unsigned Reg = CSI[i].getReg(); 313 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 314 TII.storeRegToStackSlot(*EntryBlock, I, Reg, true, 315 CSI[i].getFrameIdx(), RC, TRI); 316 } 317 } 318 319 // Restore using target interface. 320 for (unsigned ri = 0, re = ReturnBlocks.size(); ri != re; ++ri) { 321 MachineBasicBlock* MBB = ReturnBlocks[ri]; 322 I = MBB->end(); --I; 323 324 // Skip over all terminator instructions, which are part of the return 325 // sequence. 326 MachineBasicBlock::iterator I2 = I; 327 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator()) 328 I = I2; 329 330 bool AtStart = I == MBB->begin(); 331 MachineBasicBlock::iterator BeforeI = I; 332 if (!AtStart) 333 --BeforeI; 334 335 // Restore all registers immediately before the return and any 336 // terminators that preceed it. 337 if (!TFI->restoreCalleeSavedRegisters(*MBB, I, CSI, TRI)) { 338 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 339 unsigned Reg = CSI[i].getReg(); 340 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 341 TII.loadRegFromStackSlot(*MBB, I, Reg, 342 CSI[i].getFrameIdx(), 343 RC, TRI); 344 assert(I != MBB->begin() && 345 "loadRegFromStackSlot didn't insert any code!"); 346 // Insert in reverse order. loadRegFromStackSlot can insert 347 // multiple instructions. 348 if (AtStart) 349 I = MBB->begin(); 350 else { 351 I = BeforeI; 352 ++I; 353 } 354 } 355 } 356 } 357 return; 358 } 359 360 // Insert spills. 361 std::vector<CalleeSavedInfo> blockCSI; 362 for (CSRegBlockMap::iterator BI = CSRSave.begin(), 363 BE = CSRSave.end(); BI != BE; ++BI) { 364 MachineBasicBlock* MBB = BI->first; 365 CSRegSet save = BI->second; 366 367 if (save.empty()) 368 continue; 369 370 blockCSI.clear(); 371 for (CSRegSet::iterator RI = save.begin(), 372 RE = save.end(); RI != RE; ++RI) { 373 blockCSI.push_back(CSI[*RI]); 374 } 375 assert(blockCSI.size() > 0 && 376 "Could not collect callee saved register info"); 377 378 I = MBB->begin(); 379 380 // When shrink wrapping, use stack slot stores/loads. 381 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) { 382 // Add the callee-saved register as live-in. 383 // It's killed at the spill. 384 MBB->addLiveIn(blockCSI[i].getReg()); 385 386 // Insert the spill to the stack frame. 387 unsigned Reg = blockCSI[i].getReg(); 388 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 389 TII.storeRegToStackSlot(*MBB, I, Reg, 390 true, 391 blockCSI[i].getFrameIdx(), 392 RC, TRI); 393 } 394 } 395 396 for (CSRegBlockMap::iterator BI = CSRRestore.begin(), 397 BE = CSRRestore.end(); BI != BE; ++BI) { 398 MachineBasicBlock* MBB = BI->first; 399 CSRegSet restore = BI->second; 400 401 if (restore.empty()) 402 continue; 403 404 blockCSI.clear(); 405 for (CSRegSet::iterator RI = restore.begin(), 406 RE = restore.end(); RI != RE; ++RI) { 407 blockCSI.push_back(CSI[*RI]); 408 } 409 assert(blockCSI.size() > 0 && 410 "Could not find callee saved register info"); 411 412 // If MBB is empty and needs restores, insert at the _beginning_. 413 if (MBB->empty()) { 414 I = MBB->begin(); 415 } else { 416 I = MBB->end(); 417 --I; 418 419 // Skip over all terminator instructions, which are part of the 420 // return sequence. 421 if (! I->getDesc().isTerminator()) { 422 ++I; 423 } else { 424 MachineBasicBlock::iterator I2 = I; 425 while (I2 != MBB->begin() && (--I2)->getDesc().isTerminator()) 426 I = I2; 427 } 428 } 429 430 bool AtStart = I == MBB->begin(); 431 MachineBasicBlock::iterator BeforeI = I; 432 if (!AtStart) 433 --BeforeI; 434 435 // Restore all registers immediately before the return and any 436 // terminators that preceed it. 437 for (unsigned i = 0, e = blockCSI.size(); i != e; ++i) { 438 unsigned Reg = blockCSI[i].getReg(); 439 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 440 TII.loadRegFromStackSlot(*MBB, I, Reg, 441 blockCSI[i].getFrameIdx(), 442 RC, TRI); 443 assert(I != MBB->begin() && 444 "loadRegFromStackSlot didn't insert any code!"); 445 // Insert in reverse order. loadRegFromStackSlot can insert 446 // multiple instructions. 447 if (AtStart) 448 I = MBB->begin(); 449 else { 450 I = BeforeI; 451 ++I; 452 } 453 } 454 } 455 } 456 457 /// AdjustStackOffset - Helper function used to adjust the stack frame offset. 458 static inline void 459 AdjustStackOffset(MachineFrameInfo *MFI, int FrameIdx, 460 bool StackGrowsDown, int64_t &Offset, 461 unsigned &MaxAlign) { 462 // If the stack grows down, add the object size to find the lowest address. 463 if (StackGrowsDown) 464 Offset += MFI->getObjectSize(FrameIdx); 465 466 unsigned Align = MFI->getObjectAlignment(FrameIdx); 467 468 // If the alignment of this object is greater than that of the stack, then 469 // increase the stack alignment to match. 470 MaxAlign = std::max(MaxAlign, Align); 471 472 // Adjust to alignment boundary. 473 Offset = (Offset + Align - 1) / Align * Align; 474 475 if (StackGrowsDown) { 476 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n"); 477 MFI->setObjectOffset(FrameIdx, -Offset); // Set the computed offset 478 } else { 479 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n"); 480 MFI->setObjectOffset(FrameIdx, Offset); 481 Offset += MFI->getObjectSize(FrameIdx); 482 } 483 } 484 485 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 486 /// abstract stack objects. 487 /// 488 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { 489 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo(); 490 491 bool StackGrowsDown = 492 TFI.getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown; 493 494 // Loop over all of the stack objects, assigning sequential addresses... 495 MachineFrameInfo *MFI = Fn.getFrameInfo(); 496 497 // Start at the beginning of the local area. 498 // The Offset is the distance from the stack top in the direction 499 // of stack growth -- so it's always nonnegative. 500 int LocalAreaOffset = TFI.getOffsetOfLocalArea(); 501 if (StackGrowsDown) 502 LocalAreaOffset = -LocalAreaOffset; 503 assert(LocalAreaOffset >= 0 504 && "Local area offset should be in direction of stack growth"); 505 int64_t Offset = LocalAreaOffset; 506 507 // If there are fixed sized objects that are preallocated in the local area, 508 // non-fixed objects can't be allocated right at the start of local area. 509 // We currently don't support filling in holes in between fixed sized 510 // objects, so we adjust 'Offset' to point to the end of last fixed sized 511 // preallocated object. 512 for (int i = MFI->getObjectIndexBegin(); i != 0; ++i) { 513 int64_t FixedOff; 514 if (StackGrowsDown) { 515 // The maximum distance from the stack pointer is at lower address of 516 // the object -- which is given by offset. For down growing stack 517 // the offset is negative, so we negate the offset to get the distance. 518 FixedOff = -MFI->getObjectOffset(i); 519 } else { 520 // The maximum distance from the start pointer is at the upper 521 // address of the object. 522 FixedOff = MFI->getObjectOffset(i) + MFI->getObjectSize(i); 523 } 524 if (FixedOff > Offset) Offset = FixedOff; 525 } 526 527 // First assign frame offsets to stack objects that are used to spill 528 // callee saved registers. 529 if (StackGrowsDown) { 530 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) { 531 // If the stack grows down, we need to add the size to find the lowest 532 // address of the object. 533 Offset += MFI->getObjectSize(i); 534 535 unsigned Align = MFI->getObjectAlignment(i); 536 // Adjust to alignment boundary 537 Offset = (Offset+Align-1)/Align*Align; 538 539 MFI->setObjectOffset(i, -Offset); // Set the computed offset 540 } 541 } else { 542 int MaxCSFI = MaxCSFrameIndex, MinCSFI = MinCSFrameIndex; 543 for (int i = MaxCSFI; i >= MinCSFI ; --i) { 544 unsigned Align = MFI->getObjectAlignment(i); 545 // Adjust to alignment boundary 546 Offset = (Offset+Align-1)/Align*Align; 547 548 MFI->setObjectOffset(i, Offset); 549 Offset += MFI->getObjectSize(i); 550 } 551 } 552 553 unsigned MaxAlign = MFI->getMaxAlignment(); 554 555 // Make sure the special register scavenging spill slot is closest to the 556 // frame pointer if a frame pointer is required. 557 const TargetRegisterInfo *RegInfo = Fn.getTarget().getRegisterInfo(); 558 if (RS && TFI.hasFP(Fn) && !RegInfo->needsStackRealignment(Fn)) { 559 int SFI = RS->getScavengingFrameIndex(); 560 if (SFI >= 0) 561 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign); 562 } 563 564 // FIXME: Once this is working, then enable flag will change to a target 565 // check for whether the frame is large enough to want to use virtual 566 // frame index registers. Functions which don't want/need this optimization 567 // will continue to use the existing code path. 568 if (MFI->getUseLocalStackAllocationBlock()) { 569 unsigned Align = MFI->getLocalFrameMaxAlign(); 570 571 // Adjust to alignment boundary. 572 Offset = (Offset + Align - 1) / Align * Align; 573 574 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n"); 575 576 // Resolve offsets for objects in the local block. 577 for (unsigned i = 0, e = MFI->getLocalFrameObjectCount(); i != e; ++i) { 578 std::pair<int, int64_t> Entry = MFI->getLocalFrameObjectMap(i); 579 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second; 580 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << 581 FIOffset << "]\n"); 582 MFI->setObjectOffset(Entry.first, FIOffset); 583 } 584 // Allocate the local block 585 Offset += MFI->getLocalFrameSize(); 586 587 MaxAlign = std::max(Align, MaxAlign); 588 } 589 590 // Make sure that the stack protector comes before the local variables on the 591 // stack. 592 SmallSet<int, 16> LargeStackObjs; 593 if (MFI->getStackProtectorIndex() >= 0) { 594 AdjustStackOffset(MFI, MFI->getStackProtectorIndex(), StackGrowsDown, 595 Offset, MaxAlign); 596 597 // Assign large stack objects first. 598 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { 599 if (MFI->isObjectPreAllocated(i) && 600 MFI->getUseLocalStackAllocationBlock()) 601 continue; 602 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 603 continue; 604 if (RS && (int)i == RS->getScavengingFrameIndex()) 605 continue; 606 if (MFI->isDeadObjectIndex(i)) 607 continue; 608 if (MFI->getStackProtectorIndex() == (int)i) 609 continue; 610 if (!MFI->MayNeedStackProtector(i)) 611 continue; 612 613 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign); 614 LargeStackObjs.insert(i); 615 } 616 } 617 618 // Then assign frame offsets to stack objects that are not used to spill 619 // callee saved registers. 620 for (unsigned i = 0, e = MFI->getObjectIndexEnd(); i != e; ++i) { 621 if (MFI->isObjectPreAllocated(i) && 622 MFI->getUseLocalStackAllocationBlock()) 623 continue; 624 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 625 continue; 626 if (RS && (int)i == RS->getScavengingFrameIndex()) 627 continue; 628 if (MFI->isDeadObjectIndex(i)) 629 continue; 630 if (MFI->getStackProtectorIndex() == (int)i) 631 continue; 632 if (LargeStackObjs.count(i)) 633 continue; 634 635 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign); 636 } 637 638 // Make sure the special register scavenging spill slot is closest to the 639 // stack pointer. 640 if (RS && (!TFI.hasFP(Fn) || RegInfo->needsStackRealignment(Fn))) { 641 int SFI = RS->getScavengingFrameIndex(); 642 if (SFI >= 0) 643 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign); 644 } 645 646 if (!TFI.targetHandlesStackFrameRounding()) { 647 // If we have reserved argument space for call sites in the function 648 // immediately on entry to the current function, count it as part of the 649 // overall stack size. 650 if (MFI->adjustsStack() && TFI.hasReservedCallFrame(Fn)) 651 Offset += MFI->getMaxCallFrameSize(); 652 653 // Round up the size to a multiple of the alignment. If the function has 654 // any calls or alloca's, align to the target's StackAlignment value to 655 // ensure that the callee's frame or the alloca data is suitably aligned; 656 // otherwise, for leaf functions, align to the TransientStackAlignment 657 // value. 658 unsigned StackAlign; 659 if (MFI->adjustsStack() || MFI->hasVarSizedObjects() || 660 (RegInfo->needsStackRealignment(Fn) && MFI->getObjectIndexEnd() != 0)) 661 StackAlign = TFI.getStackAlignment(); 662 else 663 StackAlign = TFI.getTransientStackAlignment(); 664 665 // If the frame pointer is eliminated, all frame offsets will be relative to 666 // SP not FP. Align to MaxAlign so this works. 667 StackAlign = std::max(StackAlign, MaxAlign); 668 unsigned AlignMask = StackAlign - 1; 669 Offset = (Offset + AlignMask) & ~uint64_t(AlignMask); 670 } 671 672 // Update frame info to pretend that this is part of the stack... 673 MFI->setStackSize(Offset - LocalAreaOffset); 674 } 675 676 /// insertPrologEpilogCode - Scan the function for modified callee saved 677 /// registers, insert spill code for these callee saved registers, then add 678 /// prolog and epilog code to the function. 679 /// 680 void PEI::insertPrologEpilogCode(MachineFunction &Fn) { 681 const TargetFrameInfo &TFI = *Fn.getTarget().getFrameInfo(); 682 683 // Add prologue to the function... 684 TFI.emitPrologue(Fn); 685 686 // Add epilogue to restore the callee-save registers in each exiting block 687 for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I) { 688 // If last instruction is a return instruction, add an epilogue 689 if (!I->empty() && I->back().getDesc().isReturn()) 690 TFI.emitEpilogue(Fn, *I); 691 } 692 } 693 694 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 695 /// register references and actual offsets. 696 /// 697 void PEI::replaceFrameIndices(MachineFunction &Fn) { 698 if (!Fn.getFrameInfo()->hasStackObjects()) return; // Nothing to do? 699 700 const TargetMachine &TM = Fn.getTarget(); 701 assert(TM.getRegisterInfo() && "TM::getRegisterInfo() must be implemented!"); 702 const TargetRegisterInfo &TRI = *TM.getRegisterInfo(); 703 const TargetFrameInfo *TFI = TM.getFrameInfo(); 704 bool StackGrowsDown = 705 TFI->getStackGrowthDirection() == TargetFrameInfo::StackGrowsDown; 706 int FrameSetupOpcode = TRI.getCallFrameSetupOpcode(); 707 int FrameDestroyOpcode = TRI.getCallFrameDestroyOpcode(); 708 709 for (MachineFunction::iterator BB = Fn.begin(), 710 E = Fn.end(); BB != E; ++BB) { 711 #ifndef NDEBUG 712 int SPAdjCount = 0; // frame setup / destroy count. 713 #endif 714 int SPAdj = 0; // SP offset due to call frame setup / destroy. 715 if (RS && !FrameIndexVirtualScavenging) RS->enterBasicBlock(BB); 716 717 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 718 719 if (I->getOpcode() == FrameSetupOpcode || 720 I->getOpcode() == FrameDestroyOpcode) { 721 #ifndef NDEBUG 722 // Track whether we see even pairs of them 723 SPAdjCount += I->getOpcode() == FrameSetupOpcode ? 1 : -1; 724 #endif 725 // Remember how much SP has been adjusted to create the call 726 // frame. 727 int Size = I->getOperand(0).getImm(); 728 729 if ((!StackGrowsDown && I->getOpcode() == FrameSetupOpcode) || 730 (StackGrowsDown && I->getOpcode() == FrameDestroyOpcode)) 731 Size = -Size; 732 733 SPAdj += Size; 734 735 MachineBasicBlock::iterator PrevI = BB->end(); 736 if (I != BB->begin()) PrevI = prior(I); 737 TRI.eliminateCallFramePseudoInstr(Fn, *BB, I); 738 739 // Visit the instructions created by eliminateCallFramePseudoInstr(). 740 if (PrevI == BB->end()) 741 I = BB->begin(); // The replaced instr was the first in the block. 742 else 743 I = llvm::next(PrevI); 744 continue; 745 } 746 747 MachineInstr *MI = I; 748 bool DoIncr = true; 749 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) 750 if (MI->getOperand(i).isFI()) { 751 // Some instructions (e.g. inline asm instructions) can have 752 // multiple frame indices and/or cause eliminateFrameIndex 753 // to insert more than one instruction. We need the register 754 // scavenger to go through all of these instructions so that 755 // it can update its register information. We keep the 756 // iterator at the point before insertion so that we can 757 // revisit them in full. 758 bool AtBeginning = (I == BB->begin()); 759 if (!AtBeginning) --I; 760 761 // If this instruction has a FrameIndex operand, we need to 762 // use that target machine register info object to eliminate 763 // it. 764 TRI.eliminateFrameIndex(MI, SPAdj, 765 FrameIndexVirtualScavenging ? NULL : RS); 766 767 // Reset the iterator if we were at the beginning of the BB. 768 if (AtBeginning) { 769 I = BB->begin(); 770 DoIncr = false; 771 } 772 773 MI = 0; 774 break; 775 } 776 777 if (DoIncr && I != BB->end()) ++I; 778 779 // Update register states. 780 if (RS && !FrameIndexVirtualScavenging && MI) RS->forward(MI); 781 } 782 783 // If we have evenly matched pairs of frame setup / destroy instructions, 784 // make sure the adjustments come out to zero. If we don't have matched 785 // pairs, we can't be sure the missing bit isn't in another basic block 786 // due to a custom inserter playing tricks, so just asserting SPAdj==0 787 // isn't sufficient. See tMOVCC on Thumb1, for example. 788 assert((SPAdjCount || SPAdj == 0) && 789 "Unbalanced call frame setup / destroy pairs?"); 790 } 791 } 792 793 /// scavengeFrameVirtualRegs - Replace all frame index virtual registers 794 /// with physical registers. Use the register scavenger to find an 795 /// appropriate register to use. 796 void PEI::scavengeFrameVirtualRegs(MachineFunction &Fn) { 797 // Run through the instructions and find any virtual registers. 798 for (MachineFunction::iterator BB = Fn.begin(), 799 E = Fn.end(); BB != E; ++BB) { 800 RS->enterBasicBlock(BB); 801 802 unsigned VirtReg = 0; 803 unsigned ScratchReg = 0; 804 int SPAdj = 0; 805 806 // The instruction stream may change in the loop, so check BB->end() 807 // directly. 808 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 809 MachineInstr *MI = I; 810 bool DoIncr = true; 811 for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) { 812 if (MI->getOperand(i).isReg()) { 813 MachineOperand &MO = MI->getOperand(i); 814 unsigned Reg = MO.getReg(); 815 if (Reg == 0) 816 continue; 817 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 818 continue; 819 820 ++NumVirtualFrameRegs; 821 822 // Have we already allocated a scratch register for this virtual? 823 if (Reg != VirtReg) { 824 // When we first encounter a new virtual register, it 825 // must be a definition. 826 assert(MI->getOperand(i).isDef() && 827 "frame index virtual missing def!"); 828 // Scavenge a new scratch register 829 VirtReg = Reg; 830 const TargetRegisterClass *RC = Fn.getRegInfo().getRegClass(Reg); 831 ScratchReg = RS->scavengeRegister(RC, I, SPAdj); 832 ++NumScavengedRegs; 833 } 834 // Replace this reference to the virtual register with the 835 // scratch register. 836 assert (ScratchReg && "Missing scratch register!"); 837 MI->getOperand(i).setReg(ScratchReg); 838 839 } 840 } 841 if (DoIncr) { 842 RS->forward(I); 843 ++I; 844 } 845 } 846 } 847 } 848