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