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