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 //===----------------------------------------------------------------------===// 18 19 #include "llvm/ADT/STLExtras.h" 20 #include "llvm/ADT/SetVector.h" 21 #include "llvm/ADT/SmallSet.h" 22 #include "llvm/ADT/Statistic.h" 23 #include "llvm/CodeGen/MachineDominators.h" 24 #include "llvm/CodeGen/MachineFrameInfo.h" 25 #include "llvm/CodeGen/MachineInstr.h" 26 #include "llvm/CodeGen/MachineLoopInfo.h" 27 #include "llvm/CodeGen/MachineModuleInfo.h" 28 #include "llvm/CodeGen/MachineOptimizationRemarkEmitter.h" 29 #include "llvm/CodeGen/MachineRegisterInfo.h" 30 #include "llvm/CodeGen/Passes.h" 31 #include "llvm/CodeGen/RegisterScavenging.h" 32 #include "llvm/CodeGen/StackProtector.h" 33 #include "llvm/CodeGen/WinEHFuncInfo.h" 34 #include "llvm/IR/DiagnosticInfo.h" 35 #include "llvm/IR/InlineAsm.h" 36 #include "llvm/IR/LLVMContext.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/raw_ostream.h" 40 #include "llvm/Target/TargetFrameLowering.h" 41 #include "llvm/Target/TargetInstrInfo.h" 42 #include "llvm/Target/TargetMachine.h" 43 #include "llvm/Target/TargetRegisterInfo.h" 44 #include "llvm/Target/TargetSubtargetInfo.h" 45 #include <climits> 46 47 using namespace llvm; 48 49 #define DEBUG_TYPE "prologepilog" 50 51 typedef SmallVector<MachineBasicBlock *, 4> MBBVector; 52 namespace { 53 class PEI : public MachineFunctionPass { 54 public: 55 static char ID; 56 PEI() : MachineFunctionPass(ID) { 57 initializePEIPass(*PassRegistry::getPassRegistry()); 58 } 59 60 void getAnalysisUsage(AnalysisUsage &AU) const override; 61 62 MachineFunctionProperties getRequiredProperties() const override { 63 MachineFunctionProperties MFP; 64 if (UsesCalleeSaves) 65 MFP.set(MachineFunctionProperties::Property::NoVRegs); 66 return MFP; 67 } 68 69 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 70 /// frame indexes with appropriate references. 71 /// 72 bool runOnMachineFunction(MachineFunction &Fn) override; 73 74 private: 75 std::function<void(MachineFunction &MF)> SpillCalleeSavedRegisters; 76 std::function<void(MachineFunction &MF, RegScavenger &RS)> 77 ScavengeFrameVirtualRegs; 78 79 bool UsesCalleeSaves = false; 80 81 RegScavenger *RS; 82 83 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved 84 // stack frame indexes. 85 unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max(); 86 unsigned MaxCSFrameIndex = 0; 87 88 // Save and Restore blocks of the current function. Typically there is a 89 // single save block, unless Windows EH funclets are involved. 90 MBBVector SaveBlocks; 91 MBBVector RestoreBlocks; 92 93 // Flag to control whether to use the register scavenger to resolve 94 // frame index materialization registers. Set according to 95 // TRI->requiresFrameIndexScavenging() for the current function. 96 bool FrameIndexVirtualScavenging; 97 98 // Flag to control whether the scavenger should be passed even though 99 // FrameIndexVirtualScavenging is used. 100 bool FrameIndexEliminationScavenging; 101 102 // Emit remarks. 103 MachineOptimizationRemarkEmitter *ORE = nullptr; 104 105 void calculateCallFrameInfo(MachineFunction &Fn); 106 void calculateSaveRestoreBlocks(MachineFunction &Fn); 107 void doSpillCalleeSavedRegs(MachineFunction &MF); 108 void calculateFrameObjectOffsets(MachineFunction &Fn); 109 void replaceFrameIndices(MachineFunction &Fn); 110 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn, 111 int &SPAdj); 112 void insertPrologEpilogCode(MachineFunction &Fn); 113 }; 114 } // namespace 115 116 char PEI::ID = 0; 117 char &llvm::PrologEpilogCodeInserterID = PEI::ID; 118 119 static cl::opt<unsigned> 120 WarnStackSize("warn-stack-size", cl::Hidden, cl::init((unsigned)-1), 121 cl::desc("Warn for stack size bigger than the given" 122 " number")); 123 124 INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE, "Prologue/Epilogue Insertion", false, 125 false) 126 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 127 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 128 INITIALIZE_PASS_DEPENDENCY(StackProtector) 129 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass) 130 INITIALIZE_PASS_END(PEI, DEBUG_TYPE, 131 "Prologue/Epilogue Insertion & Frame Finalization", false, 132 false) 133 134 MachineFunctionPass *llvm::createPrologEpilogInserterPass() { 135 return new PEI(); 136 } 137 138 STATISTIC(NumBytesStackSpace, 139 "Number of bytes used for stack in all functions"); 140 141 void PEI::getAnalysisUsage(AnalysisUsage &AU) const { 142 AU.setPreservesCFG(); 143 AU.addPreserved<MachineLoopInfo>(); 144 AU.addPreserved<MachineDominatorTree>(); 145 AU.addRequired<StackProtector>(); 146 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 147 MachineFunctionPass::getAnalysisUsage(AU); 148 } 149 150 151 /// StackObjSet - A set of stack object indexes 152 typedef SmallSetVector<int, 8> StackObjSet; 153 154 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 155 /// frame indexes with appropriate references. 156 /// 157 bool PEI::runOnMachineFunction(MachineFunction &Fn) { 158 if (!SpillCalleeSavedRegisters) { 159 const TargetMachine &TM = Fn.getTarget(); 160 if (!TM.usesPhysRegsForPEI()) { 161 SpillCalleeSavedRegisters = [](MachineFunction &) {}; 162 ScavengeFrameVirtualRegs = [](MachineFunction &, RegScavenger &) {}; 163 } else { 164 SpillCalleeSavedRegisters = [this](MachineFunction &Fn) { 165 this->doSpillCalleeSavedRegs(Fn); 166 }; 167 ScavengeFrameVirtualRegs = scavengeFrameVirtualRegs; 168 UsesCalleeSaves = true; 169 } 170 } 171 172 const Function* F = Fn.getFunction(); 173 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo(); 174 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 175 176 RS = TRI->requiresRegisterScavenging(Fn) ? new RegScavenger() : nullptr; 177 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(Fn); 178 FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) || 179 TRI->requiresFrameIndexReplacementScavenging(Fn); 180 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 181 182 // Calculate the MaxCallFrameSize and AdjustsStack variables for the 183 // function's frame information. Also eliminates call frame pseudo 184 // instructions. 185 calculateCallFrameInfo(Fn); 186 187 // Determine placement of CSR spill/restore code and prolog/epilog code: 188 // place all spills in the entry block, all restores in return blocks. 189 calculateSaveRestoreBlocks(Fn); 190 191 // Handle CSR spilling and restoring, for targets that need it. 192 SpillCalleeSavedRegisters(Fn); 193 194 // Allow the target machine to make final modifications to the function 195 // before the frame layout is finalized. 196 TFI->processFunctionBeforeFrameFinalized(Fn, RS); 197 198 // Calculate actual frame offsets for all abstract stack objects... 199 calculateFrameObjectOffsets(Fn); 200 201 // Add prolog and epilog code to the function. This function is required 202 // to align the stack frame as necessary for any stack variables or 203 // called functions. Because of this, calculateCalleeSavedRegisters() 204 // must be called before this function in order to set the AdjustsStack 205 // and MaxCallFrameSize variables. 206 if (!F->hasFnAttribute(Attribute::Naked)) 207 insertPrologEpilogCode(Fn); 208 209 // Replace all MO_FrameIndex operands with physical register references 210 // and actual offsets. 211 // 212 replaceFrameIndices(Fn); 213 214 // If register scavenging is needed, as we've enabled doing it as a 215 // post-pass, scavenge the virtual registers that frame index elimination 216 // inserted. 217 if (TRI->requiresRegisterScavenging(Fn) && FrameIndexVirtualScavenging) { 218 ScavengeFrameVirtualRegs(Fn, *RS); 219 220 // Clear any vregs created by virtual scavenging. 221 Fn.getRegInfo().clearVirtRegs(); 222 } 223 224 // Warn on stack size when we exceeds the given limit. 225 MachineFrameInfo &MFI = Fn.getFrameInfo(); 226 uint64_t StackSize = MFI.getStackSize(); 227 if (WarnStackSize.getNumOccurrences() > 0 && WarnStackSize < StackSize) { 228 DiagnosticInfoStackSize DiagStackSize(*F, StackSize); 229 F->getContext().diagnose(DiagStackSize); 230 } 231 232 delete RS; 233 SaveBlocks.clear(); 234 RestoreBlocks.clear(); 235 MFI.setSavePoint(nullptr); 236 MFI.setRestorePoint(nullptr); 237 return true; 238 } 239 240 /// Calculate the MaxCallFrameSize and AdjustsStack 241 /// variables for the function's frame information and eliminate call frame 242 /// pseudo instructions. 243 void PEI::calculateCallFrameInfo(MachineFunction &Fn) { 244 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 245 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 246 MachineFrameInfo &MFI = Fn.getFrameInfo(); 247 248 unsigned MaxCallFrameSize = 0; 249 bool AdjustsStack = MFI.adjustsStack(); 250 251 // Get the function call frame set-up and tear-down instruction opcode 252 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 253 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 254 255 // Early exit for targets which have no call frame setup/destroy pseudo 256 // instructions. 257 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u) 258 return; 259 260 std::vector<MachineBasicBlock::iterator> FrameSDOps; 261 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) 262 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ++I) 263 if (TII.isFrameInstr(*I)) { 264 unsigned Size = TII.getFrameSize(*I); 265 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; 266 AdjustsStack = true; 267 FrameSDOps.push_back(I); 268 } else if (I->isInlineAsm()) { 269 // Some inline asm's need a stack frame, as indicated by operand 1. 270 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 271 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 272 AdjustsStack = true; 273 } 274 275 assert(!MFI.isMaxCallFrameSizeComputed() || 276 (MFI.getMaxCallFrameSize() == MaxCallFrameSize && 277 MFI.adjustsStack() == AdjustsStack)); 278 MFI.setAdjustsStack(AdjustsStack); 279 MFI.setMaxCallFrameSize(MaxCallFrameSize); 280 281 for (std::vector<MachineBasicBlock::iterator>::iterator 282 i = FrameSDOps.begin(), e = FrameSDOps.end(); i != e; ++i) { 283 MachineBasicBlock::iterator I = *i; 284 285 // If call frames are not being included as part of the stack frame, and 286 // the target doesn't indicate otherwise, remove the call frame pseudos 287 // here. The sub/add sp instruction pairs are still inserted, but we don't 288 // need to track the SP adjustment for frame index elimination. 289 if (TFI->canSimplifyCallFramePseudos(Fn)) 290 TFI->eliminateCallFramePseudoInstr(Fn, *I->getParent(), I); 291 } 292 } 293 294 /// Compute the sets of entry and return blocks for saving and restoring 295 /// callee-saved registers, and placing prolog and epilog code. 296 void PEI::calculateSaveRestoreBlocks(MachineFunction &Fn) { 297 const MachineFrameInfo &MFI = Fn.getFrameInfo(); 298 299 // Even when we do not change any CSR, we still want to insert the 300 // prologue and epilogue of the function. 301 // So set the save points for those. 302 303 // Use the points found by shrink-wrapping, if any. 304 if (MFI.getSavePoint()) { 305 SaveBlocks.push_back(MFI.getSavePoint()); 306 assert(MFI.getRestorePoint() && "Both restore and save must be set"); 307 MachineBasicBlock *RestoreBlock = MFI.getRestorePoint(); 308 // If RestoreBlock does not have any successor and is not a return block 309 // then the end point is unreachable and we do not need to insert any 310 // epilogue. 311 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock()) 312 RestoreBlocks.push_back(RestoreBlock); 313 return; 314 } 315 316 // Save refs to entry and return blocks. 317 SaveBlocks.push_back(&Fn.front()); 318 for (MachineBasicBlock &MBB : Fn) { 319 if (MBB.isEHFuncletEntry()) 320 SaveBlocks.push_back(&MBB); 321 if (MBB.isReturnBlock()) 322 RestoreBlocks.push_back(&MBB); 323 } 324 } 325 326 static void assignCalleeSavedSpillSlots(MachineFunction &F, 327 const BitVector &SavedRegs, 328 unsigned &MinCSFrameIndex, 329 unsigned &MaxCSFrameIndex) { 330 if (SavedRegs.empty()) 331 return; 332 333 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo(); 334 const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs(); 335 336 std::vector<CalleeSavedInfo> CSI; 337 for (unsigned i = 0; CSRegs[i]; ++i) { 338 unsigned Reg = CSRegs[i]; 339 if (SavedRegs.test(Reg)) 340 CSI.push_back(CalleeSavedInfo(Reg)); 341 } 342 343 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering(); 344 MachineFrameInfo &MFI = F.getFrameInfo(); 345 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI)) { 346 // If target doesn't implement this, use generic code. 347 348 if (CSI.empty()) 349 return; // Early exit if no callee saved registers are modified! 350 351 unsigned NumFixedSpillSlots; 352 const TargetFrameLowering::SpillSlot *FixedSpillSlots = 353 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots); 354 355 // Now that we know which registers need to be saved and restored, allocate 356 // stack slots for them. 357 for (auto &CS : CSI) { 358 unsigned Reg = CS.getReg(); 359 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg); 360 361 int FrameIdx; 362 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) { 363 CS.setFrameIdx(FrameIdx); 364 continue; 365 } 366 367 // Check to see if this physreg must be spilled to a particular stack slot 368 // on this target. 369 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots; 370 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots && 371 FixedSlot->Reg != Reg) 372 ++FixedSlot; 373 374 unsigned Size = RegInfo->getSpillSize(*RC); 375 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) { 376 // Nope, just spill it anywhere convenient. 377 unsigned Align = RegInfo->getSpillAlignment(*RC); 378 unsigned StackAlign = TFI->getStackAlignment(); 379 380 // We may not be able to satisfy the desired alignment specification of 381 // the TargetRegisterClass if the stack alignment is smaller. Use the 382 // min. 383 Align = std::min(Align, StackAlign); 384 FrameIdx = MFI.CreateStackObject(Size, Align, true); 385 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; 386 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; 387 } else { 388 // Spill it to the stack where we must. 389 FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset); 390 } 391 392 CS.setFrameIdx(FrameIdx); 393 } 394 } 395 396 MFI.setCalleeSavedInfo(CSI); 397 } 398 399 /// Helper function to update the liveness information for the callee-saved 400 /// registers. 401 static void updateLiveness(MachineFunction &MF) { 402 MachineFrameInfo &MFI = MF.getFrameInfo(); 403 // Visited will contain all the basic blocks that are in the region 404 // where the callee saved registers are alive: 405 // - Anything that is not Save or Restore -> LiveThrough. 406 // - Save -> LiveIn. 407 // - Restore -> LiveOut. 408 // The live-out is not attached to the block, so no need to keep 409 // Restore in this set. 410 SmallPtrSet<MachineBasicBlock *, 8> Visited; 411 SmallVector<MachineBasicBlock *, 8> WorkList; 412 MachineBasicBlock *Entry = &MF.front(); 413 MachineBasicBlock *Save = MFI.getSavePoint(); 414 415 if (!Save) 416 Save = Entry; 417 418 if (Entry != Save) { 419 WorkList.push_back(Entry); 420 Visited.insert(Entry); 421 } 422 Visited.insert(Save); 423 424 MachineBasicBlock *Restore = MFI.getRestorePoint(); 425 if (Restore) 426 // By construction Restore cannot be visited, otherwise it 427 // means there exists a path to Restore that does not go 428 // through Save. 429 WorkList.push_back(Restore); 430 431 while (!WorkList.empty()) { 432 const MachineBasicBlock *CurBB = WorkList.pop_back_val(); 433 // By construction, the region that is after the save point is 434 // dominated by the Save and post-dominated by the Restore. 435 if (CurBB == Save && Save != Restore) 436 continue; 437 // Enqueue all the successors not already visited. 438 // Those are by construction either before Save or after Restore. 439 for (MachineBasicBlock *SuccBB : CurBB->successors()) 440 if (Visited.insert(SuccBB).second) 441 WorkList.push_back(SuccBB); 442 } 443 444 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 445 446 MachineRegisterInfo &MRI = MF.getRegInfo(); 447 for (unsigned i = 0, e = CSI.size(); i != e; ++i) { 448 for (MachineBasicBlock *MBB : Visited) { 449 MCPhysReg Reg = CSI[i].getReg(); 450 // Add the callee-saved register as live-in. 451 // It's killed at the spill. 452 if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg)) 453 MBB->addLiveIn(Reg); 454 } 455 } 456 } 457 458 /// Insert restore code for the callee-saved registers used in the function. 459 static void insertCSRSaves(MachineBasicBlock &SaveBlock, 460 ArrayRef<CalleeSavedInfo> CSI) { 461 MachineFunction &Fn = *SaveBlock.getParent(); 462 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 463 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 464 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo(); 465 466 MachineBasicBlock::iterator I = SaveBlock.begin(); 467 if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) { 468 for (const CalleeSavedInfo &CS : CSI) { 469 // Insert the spill to the stack frame. 470 unsigned Reg = CS.getReg(); 471 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 472 TII.storeRegToStackSlot(SaveBlock, I, Reg, true, CS.getFrameIdx(), RC, 473 TRI); 474 } 475 } 476 } 477 478 /// Insert restore code for the callee-saved registers used in the function. 479 static void insertCSRRestores(MachineBasicBlock &RestoreBlock, 480 ArrayRef<CalleeSavedInfo> CSI) { 481 MachineFunction &Fn = *RestoreBlock.getParent(); 482 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 483 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 484 const TargetRegisterInfo *TRI = Fn.getSubtarget().getRegisterInfo(); 485 486 // Restore all registers immediately before the return and any 487 // terminators that precede it. 488 MachineBasicBlock::iterator I = RestoreBlock.getFirstTerminator(); 489 490 if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) { 491 for (const CalleeSavedInfo &CI : reverse(CSI)) { 492 unsigned Reg = CI.getReg(); 493 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 494 TII.loadRegFromStackSlot(RestoreBlock, I, Reg, CI.getFrameIdx(), RC, TRI); 495 assert(I != RestoreBlock.begin() && 496 "loadRegFromStackSlot didn't insert any code!"); 497 // Insert in reverse order. loadRegFromStackSlot can insert 498 // multiple instructions. 499 } 500 } 501 } 502 503 void PEI::doSpillCalleeSavedRegs(MachineFunction &Fn) { 504 const Function *F = Fn.getFunction(); 505 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 506 MachineFrameInfo &MFI = Fn.getFrameInfo(); 507 MinCSFrameIndex = std::numeric_limits<unsigned>::max(); 508 MaxCSFrameIndex = 0; 509 510 // Determine which of the registers in the callee save list should be saved. 511 BitVector SavedRegs; 512 TFI->determineCalleeSaves(Fn, SavedRegs, RS); 513 514 // Assign stack slots for any callee-saved registers that must be spilled. 515 assignCalleeSavedSpillSlots(Fn, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex); 516 517 // Add the code to save and restore the callee saved registers. 518 if (!F->hasFnAttribute(Attribute::Naked)) { 519 MFI.setCalleeSavedInfoValid(true); 520 521 ArrayRef<CalleeSavedInfo> CSI = MFI.getCalleeSavedInfo(); 522 if (!CSI.empty()) { 523 for (MachineBasicBlock *SaveBlock : SaveBlocks) { 524 insertCSRSaves(*SaveBlock, CSI); 525 // Update the live-in information of all the blocks up to the save 526 // point. 527 updateLiveness(Fn); 528 } 529 for (MachineBasicBlock *RestoreBlock : RestoreBlocks) 530 insertCSRRestores(*RestoreBlock, CSI); 531 } 532 } 533 } 534 535 /// AdjustStackOffset - Helper function used to adjust the stack frame offset. 536 static inline void 537 AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, 538 bool StackGrowsDown, int64_t &Offset, 539 unsigned &MaxAlign, unsigned Skew) { 540 // If the stack grows down, add the object size to find the lowest address. 541 if (StackGrowsDown) 542 Offset += MFI.getObjectSize(FrameIdx); 543 544 unsigned Align = MFI.getObjectAlignment(FrameIdx); 545 546 // If the alignment of this object is greater than that of the stack, then 547 // increase the stack alignment to match. 548 MaxAlign = std::max(MaxAlign, Align); 549 550 // Adjust to alignment boundary. 551 Offset = alignTo(Offset, Align, Skew); 552 553 if (StackGrowsDown) { 554 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset << "]\n"); 555 MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset 556 } else { 557 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset << "]\n"); 558 MFI.setObjectOffset(FrameIdx, Offset); 559 Offset += MFI.getObjectSize(FrameIdx); 560 } 561 } 562 563 /// Compute which bytes of fixed and callee-save stack area are unused and keep 564 /// track of them in StackBytesFree. 565 /// 566 static inline void 567 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown, 568 unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex, 569 int64_t FixedCSEnd, BitVector &StackBytesFree) { 570 // Avoid undefined int64_t -> int conversion below in extreme case. 571 if (FixedCSEnd > std::numeric_limits<int>::max()) 572 return; 573 574 StackBytesFree.resize(FixedCSEnd, true); 575 576 SmallVector<int, 16> AllocatedFrameSlots; 577 // Add fixed objects. 578 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) 579 AllocatedFrameSlots.push_back(i); 580 // Add callee-save objects. 581 for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i) 582 AllocatedFrameSlots.push_back(i); 583 584 for (int i : AllocatedFrameSlots) { 585 // These are converted from int64_t, but they should always fit in int 586 // because of the FixedCSEnd check above. 587 int ObjOffset = MFI.getObjectOffset(i); 588 int ObjSize = MFI.getObjectSize(i); 589 int ObjStart, ObjEnd; 590 if (StackGrowsDown) { 591 // ObjOffset is negative when StackGrowsDown is true. 592 ObjStart = -ObjOffset - ObjSize; 593 ObjEnd = -ObjOffset; 594 } else { 595 ObjStart = ObjOffset; 596 ObjEnd = ObjOffset + ObjSize; 597 } 598 // Ignore fixed holes that are in the previous stack frame. 599 if (ObjEnd > 0) 600 StackBytesFree.reset(ObjStart, ObjEnd); 601 } 602 } 603 604 /// Assign frame object to an unused portion of the stack in the fixed stack 605 /// object range. Return true if the allocation was successful. 606 /// 607 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx, 608 bool StackGrowsDown, unsigned MaxAlign, 609 BitVector &StackBytesFree) { 610 if (MFI.isVariableSizedObjectIndex(FrameIdx)) 611 return false; 612 613 if (StackBytesFree.none()) { 614 // clear it to speed up later scavengeStackSlot calls to 615 // StackBytesFree.none() 616 StackBytesFree.clear(); 617 return false; 618 } 619 620 unsigned ObjAlign = MFI.getObjectAlignment(FrameIdx); 621 if (ObjAlign > MaxAlign) 622 return false; 623 624 int64_t ObjSize = MFI.getObjectSize(FrameIdx); 625 int FreeStart; 626 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1; 627 FreeStart = StackBytesFree.find_next(FreeStart)) { 628 629 // Check that free space has suitable alignment. 630 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart; 631 if (alignTo(ObjStart, ObjAlign) != ObjStart) 632 continue; 633 634 if (FreeStart + ObjSize > StackBytesFree.size()) 635 return false; 636 637 bool AllBytesFree = true; 638 for (unsigned Byte = 0; Byte < ObjSize; ++Byte) 639 if (!StackBytesFree.test(FreeStart + Byte)) { 640 AllBytesFree = false; 641 break; 642 } 643 if (AllBytesFree) 644 break; 645 } 646 647 if (FreeStart == -1) 648 return false; 649 650 if (StackGrowsDown) { 651 int ObjStart = -(FreeStart + ObjSize); 652 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << ObjStart 653 << "]\n"); 654 MFI.setObjectOffset(FrameIdx, ObjStart); 655 } else { 656 DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" << FreeStart 657 << "]\n"); 658 MFI.setObjectOffset(FrameIdx, FreeStart); 659 } 660 661 StackBytesFree.reset(FreeStart, FreeStart + ObjSize); 662 return true; 663 } 664 665 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e., 666 /// those required to be close to the Stack Protector) to stack offsets. 667 static void 668 AssignProtectedObjSet(const StackObjSet &UnassignedObjs, 669 SmallSet<int, 16> &ProtectedObjs, 670 MachineFrameInfo &MFI, bool StackGrowsDown, 671 int64_t &Offset, unsigned &MaxAlign, unsigned Skew) { 672 673 for (StackObjSet::const_iterator I = UnassignedObjs.begin(), 674 E = UnassignedObjs.end(); I != E; ++I) { 675 int i = *I; 676 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew); 677 ProtectedObjs.insert(i); 678 } 679 } 680 681 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 682 /// abstract stack objects. 683 /// 684 void PEI::calculateFrameObjectOffsets(MachineFunction &Fn) { 685 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 686 StackProtector *SP = &getAnalysis<StackProtector>(); 687 688 bool StackGrowsDown = 689 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 690 691 // Loop over all of the stack objects, assigning sequential addresses... 692 MachineFrameInfo &MFI = Fn.getFrameInfo(); 693 694 // Start at the beginning of the local area. 695 // The Offset is the distance from the stack top in the direction 696 // of stack growth -- so it's always nonnegative. 697 int LocalAreaOffset = TFI.getOffsetOfLocalArea(); 698 if (StackGrowsDown) 699 LocalAreaOffset = -LocalAreaOffset; 700 assert(LocalAreaOffset >= 0 701 && "Local area offset should be in direction of stack growth"); 702 int64_t Offset = LocalAreaOffset; 703 704 // Skew to be applied to alignment. 705 unsigned Skew = TFI.getStackAlignmentSkew(Fn); 706 707 // If there are fixed sized objects that are preallocated in the local area, 708 // non-fixed objects can't be allocated right at the start of local area. 709 // Adjust 'Offset' to point to the end of last fixed sized preallocated 710 // object. 711 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) { 712 int64_t FixedOff; 713 if (StackGrowsDown) { 714 // The maximum distance from the stack pointer is at lower address of 715 // the object -- which is given by offset. For down growing stack 716 // the offset is negative, so we negate the offset to get the distance. 717 FixedOff = -MFI.getObjectOffset(i); 718 } else { 719 // The maximum distance from the start pointer is at the upper 720 // address of the object. 721 FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i); 722 } 723 if (FixedOff > Offset) Offset = FixedOff; 724 } 725 726 // First assign frame offsets to stack objects that are used to spill 727 // callee saved registers. 728 if (StackGrowsDown) { 729 for (unsigned i = MinCSFrameIndex; i <= MaxCSFrameIndex; ++i) { 730 // If the stack grows down, we need to add the size to find the lowest 731 // address of the object. 732 Offset += MFI.getObjectSize(i); 733 734 unsigned Align = MFI.getObjectAlignment(i); 735 // Adjust to alignment boundary 736 Offset = alignTo(Offset, Align, Skew); 737 738 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << -Offset << "]\n"); 739 MFI.setObjectOffset(i, -Offset); // Set the computed offset 740 } 741 } else if (MaxCSFrameIndex >= MinCSFrameIndex) { 742 // Be careful about underflow in comparisons agains MinCSFrameIndex. 743 for (unsigned i = MaxCSFrameIndex; i != MinCSFrameIndex - 1; --i) { 744 if (MFI.isDeadObjectIndex(i)) 745 continue; 746 747 unsigned Align = MFI.getObjectAlignment(i); 748 // Adjust to alignment boundary 749 Offset = alignTo(Offset, Align, Skew); 750 751 DEBUG(dbgs() << "alloc FI(" << i << ") at SP[" << Offset << "]\n"); 752 MFI.setObjectOffset(i, Offset); 753 Offset += MFI.getObjectSize(i); 754 } 755 } 756 757 // FixedCSEnd is the stack offset to the end of the fixed and callee-save 758 // stack area. 759 int64_t FixedCSEnd = Offset; 760 unsigned MaxAlign = MFI.getMaxAlignment(); 761 762 // Make sure the special register scavenging spill slot is closest to the 763 // incoming stack pointer if a frame pointer is required and is closer 764 // to the incoming rather than the final stack pointer. 765 const TargetRegisterInfo *RegInfo = Fn.getSubtarget().getRegisterInfo(); 766 bool EarlyScavengingSlots = (TFI.hasFP(Fn) && 767 TFI.isFPCloseToIncomingSP() && 768 RegInfo->useFPForScavengingIndex(Fn) && 769 !RegInfo->needsStackRealignment(Fn)); 770 if (RS && EarlyScavengingSlots) { 771 SmallVector<int, 2> SFIs; 772 RS->getScavengingFrameIndices(SFIs); 773 for (SmallVectorImpl<int>::iterator I = SFIs.begin(), 774 IE = SFIs.end(); I != IE; ++I) 775 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew); 776 } 777 778 // FIXME: Once this is working, then enable flag will change to a target 779 // check for whether the frame is large enough to want to use virtual 780 // frame index registers. Functions which don't want/need this optimization 781 // will continue to use the existing code path. 782 if (MFI.getUseLocalStackAllocationBlock()) { 783 unsigned Align = MFI.getLocalFrameMaxAlign(); 784 785 // Adjust to alignment boundary. 786 Offset = alignTo(Offset, Align, Skew); 787 788 DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n"); 789 790 // Resolve offsets for objects in the local block. 791 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) { 792 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i); 793 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second; 794 DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << 795 FIOffset << "]\n"); 796 MFI.setObjectOffset(Entry.first, FIOffset); 797 } 798 // Allocate the local block 799 Offset += MFI.getLocalFrameSize(); 800 801 MaxAlign = std::max(Align, MaxAlign); 802 } 803 804 // Retrieve the Exception Handler registration node. 805 int EHRegNodeFrameIndex = INT_MAX; 806 if (const WinEHFuncInfo *FuncInfo = Fn.getWinEHFuncInfo()) 807 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex; 808 809 // Make sure that the stack protector comes before the local variables on the 810 // stack. 811 SmallSet<int, 16> ProtectedObjs; 812 if (MFI.getStackProtectorIndex() >= 0) { 813 StackObjSet LargeArrayObjs; 814 StackObjSet SmallArrayObjs; 815 StackObjSet AddrOfObjs; 816 817 AdjustStackOffset(MFI, MFI.getStackProtectorIndex(), StackGrowsDown, 818 Offset, MaxAlign, Skew); 819 820 // Assign large stack objects first. 821 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 822 if (MFI.isObjectPreAllocated(i) && 823 MFI.getUseLocalStackAllocationBlock()) 824 continue; 825 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 826 continue; 827 if (RS && RS->isScavengingFrameIndex((int)i)) 828 continue; 829 if (MFI.isDeadObjectIndex(i)) 830 continue; 831 if (MFI.getStackProtectorIndex() == (int)i || 832 EHRegNodeFrameIndex == (int)i) 833 continue; 834 835 switch (SP->getSSPLayout(MFI.getObjectAllocation(i))) { 836 case StackProtector::SSPLK_None: 837 continue; 838 case StackProtector::SSPLK_SmallArray: 839 SmallArrayObjs.insert(i); 840 continue; 841 case StackProtector::SSPLK_AddrOf: 842 AddrOfObjs.insert(i); 843 continue; 844 case StackProtector::SSPLK_LargeArray: 845 LargeArrayObjs.insert(i); 846 continue; 847 } 848 llvm_unreachable("Unexpected SSPLayoutKind."); 849 } 850 851 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 852 Offset, MaxAlign, Skew); 853 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 854 Offset, MaxAlign, Skew); 855 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown, 856 Offset, MaxAlign, Skew); 857 } 858 859 SmallVector<int, 8> ObjectsToAllocate; 860 861 // Then prepare to assign frame offsets to stack objects that are not used to 862 // spill callee saved registers. 863 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 864 if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock()) 865 continue; 866 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 867 continue; 868 if (RS && RS->isScavengingFrameIndex((int)i)) 869 continue; 870 if (MFI.isDeadObjectIndex(i)) 871 continue; 872 if (MFI.getStackProtectorIndex() == (int)i || 873 EHRegNodeFrameIndex == (int)i) 874 continue; 875 if (ProtectedObjs.count(i)) 876 continue; 877 878 // Add the objects that we need to allocate to our working set. 879 ObjectsToAllocate.push_back(i); 880 } 881 882 // Allocate the EH registration node first if one is present. 883 if (EHRegNodeFrameIndex != INT_MAX) 884 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset, 885 MaxAlign, Skew); 886 887 // Give the targets a chance to order the objects the way they like it. 888 if (Fn.getTarget().getOptLevel() != CodeGenOpt::None && 889 Fn.getTarget().Options.StackSymbolOrdering) 890 TFI.orderFrameObjects(Fn, ObjectsToAllocate); 891 892 // Keep track of which bytes in the fixed and callee-save range are used so we 893 // can use the holes when allocating later stack objects. Only do this if 894 // stack protector isn't being used and the target requests it and we're 895 // optimizing. 896 BitVector StackBytesFree; 897 if (!ObjectsToAllocate.empty() && 898 Fn.getTarget().getOptLevel() != CodeGenOpt::None && 899 MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(Fn)) 900 computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex, 901 FixedCSEnd, StackBytesFree); 902 903 // Now walk the objects and actually assign base offsets to them. 904 for (auto &Object : ObjectsToAllocate) 905 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign, 906 StackBytesFree)) 907 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew); 908 909 // Make sure the special register scavenging spill slot is closest to the 910 // stack pointer. 911 if (RS && !EarlyScavengingSlots) { 912 SmallVector<int, 2> SFIs; 913 RS->getScavengingFrameIndices(SFIs); 914 for (SmallVectorImpl<int>::iterator I = SFIs.begin(), 915 IE = SFIs.end(); I != IE; ++I) 916 AdjustStackOffset(MFI, *I, StackGrowsDown, Offset, MaxAlign, Skew); 917 } 918 919 if (!TFI.targetHandlesStackFrameRounding()) { 920 // If we have reserved argument space for call sites in the function 921 // immediately on entry to the current function, count it as part of the 922 // overall stack size. 923 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(Fn)) 924 Offset += MFI.getMaxCallFrameSize(); 925 926 // Round up the size to a multiple of the alignment. If the function has 927 // any calls or alloca's, align to the target's StackAlignment value to 928 // ensure that the callee's frame or the alloca data is suitably aligned; 929 // otherwise, for leaf functions, align to the TransientStackAlignment 930 // value. 931 unsigned StackAlign; 932 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() || 933 (RegInfo->needsStackRealignment(Fn) && MFI.getObjectIndexEnd() != 0)) 934 StackAlign = TFI.getStackAlignment(); 935 else 936 StackAlign = TFI.getTransientStackAlignment(); 937 938 // If the frame pointer is eliminated, all frame offsets will be relative to 939 // SP not FP. Align to MaxAlign so this works. 940 StackAlign = std::max(StackAlign, MaxAlign); 941 Offset = alignTo(Offset, StackAlign, Skew); 942 } 943 944 // Update frame info to pretend that this is part of the stack... 945 int64_t StackSize = Offset - LocalAreaOffset; 946 MFI.setStackSize(StackSize); 947 NumBytesStackSpace += StackSize; 948 949 MachineOptimizationRemarkAnalysis R( 950 DEBUG_TYPE, "StackSize", Fn.getFunction()->getSubprogram(), &Fn.front()); 951 R << ore::NV("NumStackBytes", static_cast<unsigned>(StackSize)) 952 << " stack bytes in function"; 953 ORE->emit(R); 954 } 955 956 /// insertPrologEpilogCode - Scan the function for modified callee saved 957 /// registers, insert spill code for these callee saved registers, then add 958 /// prolog and epilog code to the function. 959 /// 960 void PEI::insertPrologEpilogCode(MachineFunction &Fn) { 961 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 962 963 // Add prologue to the function... 964 for (MachineBasicBlock *SaveBlock : SaveBlocks) 965 TFI.emitPrologue(Fn, *SaveBlock); 966 967 // Add epilogue to restore the callee-save registers in each exiting block. 968 for (MachineBasicBlock *RestoreBlock : RestoreBlocks) 969 TFI.emitEpilogue(Fn, *RestoreBlock); 970 971 for (MachineBasicBlock *SaveBlock : SaveBlocks) 972 TFI.inlineStackProbe(Fn, *SaveBlock); 973 974 // Emit additional code that is required to support segmented stacks, if 975 // we've been asked for it. This, when linked with a runtime with support 976 // for segmented stacks (libgcc is one), will result in allocating stack 977 // space in small chunks instead of one large contiguous block. 978 if (Fn.shouldSplitStack()) { 979 for (MachineBasicBlock *SaveBlock : SaveBlocks) 980 TFI.adjustForSegmentedStacks(Fn, *SaveBlock); 981 } 982 983 // Emit additional code that is required to explicitly handle the stack in 984 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The 985 // approach is rather similar to that of Segmented Stacks, but it uses a 986 // different conditional check and another BIF for allocating more stack 987 // space. 988 if (Fn.getFunction()->getCallingConv() == CallingConv::HiPE) 989 for (MachineBasicBlock *SaveBlock : SaveBlocks) 990 TFI.adjustForHiPEPrologue(Fn, *SaveBlock); 991 } 992 993 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 994 /// register references and actual offsets. 995 /// 996 void PEI::replaceFrameIndices(MachineFunction &Fn) { 997 const TargetFrameLowering &TFI = *Fn.getSubtarget().getFrameLowering(); 998 if (!TFI.needsFrameIndexResolution(Fn)) return; 999 1000 // Store SPAdj at exit of a basic block. 1001 SmallVector<int, 8> SPState; 1002 SPState.resize(Fn.getNumBlockIDs()); 1003 df_iterator_default_set<MachineBasicBlock*> Reachable; 1004 1005 // Iterate over the reachable blocks in DFS order. 1006 for (auto DFI = df_ext_begin(&Fn, Reachable), DFE = df_ext_end(&Fn, Reachable); 1007 DFI != DFE; ++DFI) { 1008 int SPAdj = 0; 1009 // Check the exit state of the DFS stack predecessor. 1010 if (DFI.getPathLength() >= 2) { 1011 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 1012 assert(Reachable.count(StackPred) && 1013 "DFS stack predecessor is already visited.\n"); 1014 SPAdj = SPState[StackPred->getNumber()]; 1015 } 1016 MachineBasicBlock *BB = *DFI; 1017 replaceFrameIndices(BB, Fn, SPAdj); 1018 SPState[BB->getNumber()] = SPAdj; 1019 } 1020 1021 // Handle the unreachable blocks. 1022 for (auto &BB : Fn) { 1023 if (Reachable.count(&BB)) 1024 // Already handled in DFS traversal. 1025 continue; 1026 int SPAdj = 0; 1027 replaceFrameIndices(&BB, Fn, SPAdj); 1028 } 1029 } 1030 1031 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &Fn, 1032 int &SPAdj) { 1033 assert(Fn.getSubtarget().getRegisterInfo() && 1034 "getRegisterInfo() must be implemented!"); 1035 const TargetInstrInfo &TII = *Fn.getSubtarget().getInstrInfo(); 1036 const TargetRegisterInfo &TRI = *Fn.getSubtarget().getRegisterInfo(); 1037 const TargetFrameLowering *TFI = Fn.getSubtarget().getFrameLowering(); 1038 1039 if (RS && FrameIndexEliminationScavenging) 1040 RS->enterBasicBlock(*BB); 1041 1042 bool InsideCallSequence = false; 1043 1044 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 1045 1046 if (TII.isFrameInstr(*I)) { 1047 InsideCallSequence = TII.isFrameSetup(*I); 1048 SPAdj += TII.getSPAdjust(*I); 1049 I = TFI->eliminateCallFramePseudoInstr(Fn, *BB, I); 1050 continue; 1051 } 1052 1053 MachineInstr &MI = *I; 1054 bool DoIncr = true; 1055 bool DidFinishLoop = true; 1056 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1057 if (!MI.getOperand(i).isFI()) 1058 continue; 1059 1060 // Frame indices in debug values are encoded in a target independent 1061 // way with simply the frame index and offset rather than any 1062 // target-specific addressing mode. 1063 if (MI.isDebugValue()) { 1064 assert(i == 0 && "Frame indices can only appear as the first " 1065 "operand of a DBG_VALUE machine instruction"); 1066 unsigned Reg; 1067 MachineOperand &Offset = MI.getOperand(1); 1068 Offset.setImm( 1069 Offset.getImm() + 1070 TFI->getFrameIndexReference(Fn, MI.getOperand(0).getIndex(), Reg)); 1071 MI.getOperand(0).ChangeToRegister(Reg, false /*isDef*/); 1072 continue; 1073 } 1074 1075 // TODO: This code should be commoned with the code for 1076 // PATCHPOINT. There's no good reason for the difference in 1077 // implementation other than historical accident. The only 1078 // remaining difference is the unconditional use of the stack 1079 // pointer as the base register. 1080 if (MI.getOpcode() == TargetOpcode::STATEPOINT) { 1081 assert((!MI.isDebugValue() || i == 0) && 1082 "Frame indicies can only appear as the first operand of a " 1083 "DBG_VALUE machine instruction"); 1084 unsigned Reg; 1085 MachineOperand &Offset = MI.getOperand(i + 1); 1086 int refOffset = TFI->getFrameIndexReferencePreferSP( 1087 Fn, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false); 1088 Offset.setImm(Offset.getImm() + refOffset); 1089 MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/); 1090 continue; 1091 } 1092 1093 // Some instructions (e.g. inline asm instructions) can have 1094 // multiple frame indices and/or cause eliminateFrameIndex 1095 // to insert more than one instruction. We need the register 1096 // scavenger to go through all of these instructions so that 1097 // it can update its register information. We keep the 1098 // iterator at the point before insertion so that we can 1099 // revisit them in full. 1100 bool AtBeginning = (I == BB->begin()); 1101 if (!AtBeginning) --I; 1102 1103 // If this instruction has a FrameIndex operand, we need to 1104 // use that target machine register info object to eliminate 1105 // it. 1106 TRI.eliminateFrameIndex(MI, SPAdj, i, 1107 FrameIndexEliminationScavenging ? RS : nullptr); 1108 1109 // Reset the iterator if we were at the beginning of the BB. 1110 if (AtBeginning) { 1111 I = BB->begin(); 1112 DoIncr = false; 1113 } 1114 1115 DidFinishLoop = false; 1116 break; 1117 } 1118 1119 // If we are looking at a call sequence, we need to keep track of 1120 // the SP adjustment made by each instruction in the sequence. 1121 // This includes both the frame setup/destroy pseudos (handled above), 1122 // as well as other instructions that have side effects w.r.t the SP. 1123 // Note that this must come after eliminateFrameIndex, because 1124 // if I itself referred to a frame index, we shouldn't count its own 1125 // adjustment. 1126 if (DidFinishLoop && InsideCallSequence) 1127 SPAdj += TII.getSPAdjust(MI); 1128 1129 if (DoIncr && I != BB->end()) ++I; 1130 1131 // Update register states. 1132 if (RS && FrameIndexEliminationScavenging && DidFinishLoop) 1133 RS->forward(MI); 1134 } 1135 } 1136