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