1 //===- PrologEpilogInserter.cpp - Insert Prolog/Epilog code in function ---===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This pass is responsible for finalizing the functions frame layout, saving 10 // callee saved registers, and for emitting prolog & epilog code for the 11 // function. 12 // 13 // This pass must be run after register allocation. After this pass is 14 // executed, it is illegal to construct MO_FrameIndex operands. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/ADT/ArrayRef.h" 19 #include "llvm/ADT/BitVector.h" 20 #include "llvm/ADT/DepthFirstIterator.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/SetVector.h" 23 #include "llvm/ADT/SmallPtrSet.h" 24 #include "llvm/ADT/SmallSet.h" 25 #include "llvm/ADT/SmallVector.h" 26 #include "llvm/ADT/Statistic.h" 27 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 28 #include "llvm/CodeGen/MachineBasicBlock.h" 29 #include "llvm/CodeGen/MachineDominators.h" 30 #include "llvm/CodeGen/MachineFrameInfo.h" 31 #include "llvm/CodeGen/MachineFunction.h" 32 #include "llvm/CodeGen/MachineFunctionPass.h" 33 #include "llvm/CodeGen/MachineInstr.h" 34 #include "llvm/CodeGen/MachineInstrBuilder.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/TargetFrameLowering.h" 42 #include "llvm/CodeGen/TargetInstrInfo.h" 43 #include "llvm/CodeGen/TargetOpcodes.h" 44 #include "llvm/CodeGen/TargetRegisterInfo.h" 45 #include "llvm/CodeGen/TargetSubtargetInfo.h" 46 #include "llvm/CodeGen/WinEHFuncInfo.h" 47 #include "llvm/IR/Attributes.h" 48 #include "llvm/IR/CallingConv.h" 49 #include "llvm/IR/DebugInfoMetadata.h" 50 #include "llvm/IR/DiagnosticInfo.h" 51 #include "llvm/IR/Function.h" 52 #include "llvm/IR/InlineAsm.h" 53 #include "llvm/IR/LLVMContext.h" 54 #include "llvm/InitializePasses.h" 55 #include "llvm/MC/MCRegisterInfo.h" 56 #include "llvm/Pass.h" 57 #include "llvm/Support/CodeGen.h" 58 #include "llvm/Support/Debug.h" 59 #include "llvm/Support/ErrorHandling.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include "llvm/Target/TargetMachine.h" 62 #include "llvm/Target/TargetOptions.h" 63 #include <algorithm> 64 #include <cassert> 65 #include <cstdint> 66 #include <functional> 67 #include <limits> 68 #include <utility> 69 #include <vector> 70 71 using namespace llvm; 72 73 #define DEBUG_TYPE "prologepilog" 74 75 using MBBVector = SmallVector<MachineBasicBlock *, 4>; 76 77 STATISTIC(NumLeafFuncWithSpills, "Number of leaf functions with CSRs"); 78 STATISTIC(NumFuncSeen, "Number of functions seen in PEI"); 79 80 81 namespace { 82 83 class PEI : public MachineFunctionPass { 84 public: 85 static char ID; 86 87 PEI() : MachineFunctionPass(ID) { 88 initializePEIPass(*PassRegistry::getPassRegistry()); 89 } 90 91 void getAnalysisUsage(AnalysisUsage &AU) const override; 92 93 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 94 /// frame indexes with appropriate references. 95 bool runOnMachineFunction(MachineFunction &MF) override; 96 97 private: 98 RegScavenger *RS; 99 100 // MinCSFrameIndex, MaxCSFrameIndex - Keeps the range of callee saved 101 // stack frame indexes. 102 unsigned MinCSFrameIndex = std::numeric_limits<unsigned>::max(); 103 unsigned MaxCSFrameIndex = 0; 104 105 // Save and Restore blocks of the current function. Typically there is a 106 // single save block, unless Windows EH funclets are involved. 107 MBBVector SaveBlocks; 108 MBBVector RestoreBlocks; 109 110 // Flag to control whether to use the register scavenger to resolve 111 // frame index materialization registers. Set according to 112 // TRI->requiresFrameIndexScavenging() for the current function. 113 bool FrameIndexVirtualScavenging; 114 115 // Flag to control whether the scavenger should be passed even though 116 // FrameIndexVirtualScavenging is used. 117 bool FrameIndexEliminationScavenging; 118 119 // Emit remarks. 120 MachineOptimizationRemarkEmitter *ORE = nullptr; 121 122 void calculateCallFrameInfo(MachineFunction &MF); 123 void calculateSaveRestoreBlocks(MachineFunction &MF); 124 void spillCalleeSavedRegs(MachineFunction &MF); 125 126 void calculateFrameObjectOffsets(MachineFunction &MF); 127 void replaceFrameIndices(MachineFunction &MF); 128 void replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF, 129 int &SPAdj); 130 void insertPrologEpilogCode(MachineFunction &MF); 131 void insertZeroCallUsedRegs(MachineFunction &MF); 132 }; 133 134 } // end anonymous namespace 135 136 char PEI::ID = 0; 137 138 char &llvm::PrologEpilogCodeInserterID = PEI::ID; 139 140 INITIALIZE_PASS_BEGIN(PEI, DEBUG_TYPE, "Prologue/Epilogue Insertion", false, 141 false) 142 INITIALIZE_PASS_DEPENDENCY(MachineLoopInfo) 143 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 144 INITIALIZE_PASS_DEPENDENCY(MachineOptimizationRemarkEmitterPass) 145 INITIALIZE_PASS_END(PEI, DEBUG_TYPE, 146 "Prologue/Epilogue Insertion & Frame Finalization", false, 147 false) 148 149 MachineFunctionPass *llvm::createPrologEpilogInserterPass() { 150 return new PEI(); 151 } 152 153 STATISTIC(NumBytesStackSpace, 154 "Number of bytes used for stack in all functions"); 155 156 void PEI::getAnalysisUsage(AnalysisUsage &AU) const { 157 AU.setPreservesCFG(); 158 AU.addPreserved<MachineLoopInfo>(); 159 AU.addPreserved<MachineDominatorTree>(); 160 AU.addRequired<MachineOptimizationRemarkEmitterPass>(); 161 MachineFunctionPass::getAnalysisUsage(AU); 162 } 163 164 /// StackObjSet - A set of stack object indexes 165 using StackObjSet = SmallSetVector<int, 8>; 166 167 using SavedDbgValuesMap = 168 SmallDenseMap<MachineBasicBlock *, SmallVector<MachineInstr *, 4>, 4>; 169 170 /// Stash DBG_VALUEs that describe parameters and which are placed at the start 171 /// of the block. Later on, after the prologue code has been emitted, the 172 /// stashed DBG_VALUEs will be reinserted at the start of the block. 173 static void stashEntryDbgValues(MachineBasicBlock &MBB, 174 SavedDbgValuesMap &EntryDbgValues) { 175 SmallVector<const MachineInstr *, 4> FrameIndexValues; 176 177 for (auto &MI : MBB) { 178 if (!MI.isDebugInstr()) 179 break; 180 if (!MI.isDebugValue() || !MI.getDebugVariable()->isParameter()) 181 continue; 182 if (any_of(MI.debug_operands(), 183 [](const MachineOperand &MO) { return MO.isFI(); })) { 184 // We can only emit valid locations for frame indices after the frame 185 // setup, so do not stash away them. 186 FrameIndexValues.push_back(&MI); 187 continue; 188 } 189 const DILocalVariable *Var = MI.getDebugVariable(); 190 const DIExpression *Expr = MI.getDebugExpression(); 191 auto Overlaps = [Var, Expr](const MachineInstr *DV) { 192 return Var == DV->getDebugVariable() && 193 Expr->fragmentsOverlap(DV->getDebugExpression()); 194 }; 195 // See if the debug value overlaps with any preceding debug value that will 196 // not be stashed. If that is the case, then we can't stash this value, as 197 // we would then reorder the values at reinsertion. 198 if (llvm::none_of(FrameIndexValues, Overlaps)) 199 EntryDbgValues[&MBB].push_back(&MI); 200 } 201 202 // Remove stashed debug values from the block. 203 if (EntryDbgValues.count(&MBB)) 204 for (auto *MI : EntryDbgValues[&MBB]) 205 MI->removeFromParent(); 206 } 207 208 /// runOnMachineFunction - Insert prolog/epilog code and replace abstract 209 /// frame indexes with appropriate references. 210 bool PEI::runOnMachineFunction(MachineFunction &MF) { 211 NumFuncSeen++; 212 const Function &F = MF.getFunction(); 213 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 214 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 215 216 RS = TRI->requiresRegisterScavenging(MF) ? new RegScavenger() : nullptr; 217 FrameIndexVirtualScavenging = TRI->requiresFrameIndexScavenging(MF); 218 ORE = &getAnalysis<MachineOptimizationRemarkEmitterPass>().getORE(); 219 220 // Calculate the MaxCallFrameSize and AdjustsStack variables for the 221 // function's frame information. Also eliminates call frame pseudo 222 // instructions. 223 calculateCallFrameInfo(MF); 224 225 // Determine placement of CSR spill/restore code and prolog/epilog code: 226 // place all spills in the entry block, all restores in return blocks. 227 calculateSaveRestoreBlocks(MF); 228 229 // Stash away DBG_VALUEs that should not be moved by insertion of prolog code. 230 SavedDbgValuesMap EntryDbgValues; 231 for (MachineBasicBlock *SaveBlock : SaveBlocks) 232 stashEntryDbgValues(*SaveBlock, EntryDbgValues); 233 234 // Handle CSR spilling and restoring, for targets that need it. 235 if (MF.getTarget().usesPhysRegsForValues()) 236 spillCalleeSavedRegs(MF); 237 238 // Allow the target machine to make final modifications to the function 239 // before the frame layout is finalized. 240 TFI->processFunctionBeforeFrameFinalized(MF, RS); 241 242 // Calculate actual frame offsets for all abstract stack objects... 243 calculateFrameObjectOffsets(MF); 244 245 // Add prolog and epilog code to the function. This function is required 246 // to align the stack frame as necessary for any stack variables or 247 // called functions. Because of this, calculateCalleeSavedRegisters() 248 // must be called before this function in order to set the AdjustsStack 249 // and MaxCallFrameSize variables. 250 if (!F.hasFnAttribute(Attribute::Naked)) 251 insertPrologEpilogCode(MF); 252 253 // Reinsert stashed debug values at the start of the entry blocks. 254 for (auto &I : EntryDbgValues) 255 I.first->insert(I.first->begin(), I.second.begin(), I.second.end()); 256 257 // Allow the target machine to make final modifications to the function 258 // before the frame layout is finalized. 259 TFI->processFunctionBeforeFrameIndicesReplaced(MF, RS); 260 261 // Replace all MO_FrameIndex operands with physical register references 262 // and actual offsets. 263 // 264 replaceFrameIndices(MF); 265 266 // If register scavenging is needed, as we've enabled doing it as a 267 // post-pass, scavenge the virtual registers that frame index elimination 268 // inserted. 269 if (TRI->requiresRegisterScavenging(MF) && FrameIndexVirtualScavenging) 270 scavengeFrameVirtualRegs(MF, *RS); 271 272 // Warn on stack size when we exceeds the given limit. 273 MachineFrameInfo &MFI = MF.getFrameInfo(); 274 uint64_t StackSize = MFI.getStackSize(); 275 276 unsigned Threshold = UINT_MAX; 277 if (MF.getFunction().hasFnAttribute("warn-stack-size")) { 278 bool Failed = MF.getFunction() 279 .getFnAttribute("warn-stack-size") 280 .getValueAsString() 281 .getAsInteger(10, Threshold); 282 // Verifier should have caught this. 283 assert(!Failed && "Invalid warn-stack-size fn attr value"); 284 (void)Failed; 285 } 286 if (StackSize > Threshold) { 287 DiagnosticInfoStackSize DiagStackSize(F, StackSize, Threshold, DS_Warning); 288 F.getContext().diagnose(DiagStackSize); 289 } 290 ORE->emit([&]() { 291 return MachineOptimizationRemarkAnalysis(DEBUG_TYPE, "StackSize", 292 MF.getFunction().getSubprogram(), 293 &MF.front()) 294 << ore::NV("NumStackBytes", StackSize) << " stack bytes in function"; 295 }); 296 297 delete RS; 298 SaveBlocks.clear(); 299 RestoreBlocks.clear(); 300 MFI.setSavePoint(nullptr); 301 MFI.setRestorePoint(nullptr); 302 return true; 303 } 304 305 /// Calculate the MaxCallFrameSize and AdjustsStack 306 /// variables for the function's frame information and eliminate call frame 307 /// pseudo instructions. 308 void PEI::calculateCallFrameInfo(MachineFunction &MF) { 309 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 310 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 311 MachineFrameInfo &MFI = MF.getFrameInfo(); 312 313 unsigned MaxCallFrameSize = 0; 314 bool AdjustsStack = MFI.adjustsStack(); 315 316 // Get the function call frame set-up and tear-down instruction opcode 317 unsigned FrameSetupOpcode = TII.getCallFrameSetupOpcode(); 318 unsigned FrameDestroyOpcode = TII.getCallFrameDestroyOpcode(); 319 320 // Early exit for targets which have no call frame setup/destroy pseudo 321 // instructions. 322 if (FrameSetupOpcode == ~0u && FrameDestroyOpcode == ~0u) 323 return; 324 325 std::vector<MachineBasicBlock::iterator> FrameSDOps; 326 for (MachineBasicBlock &BB : MF) 327 for (MachineBasicBlock::iterator I = BB.begin(); I != BB.end(); ++I) 328 if (TII.isFrameInstr(*I)) { 329 unsigned Size = TII.getFrameSize(*I); 330 if (Size > MaxCallFrameSize) MaxCallFrameSize = Size; 331 AdjustsStack = true; 332 FrameSDOps.push_back(I); 333 } else if (I->isInlineAsm()) { 334 // Some inline asm's need a stack frame, as indicated by operand 1. 335 unsigned ExtraInfo = I->getOperand(InlineAsm::MIOp_ExtraInfo).getImm(); 336 if (ExtraInfo & InlineAsm::Extra_IsAlignStack) 337 AdjustsStack = true; 338 } 339 340 assert(!MFI.isMaxCallFrameSizeComputed() || 341 (MFI.getMaxCallFrameSize() == MaxCallFrameSize && 342 MFI.adjustsStack() == AdjustsStack)); 343 MFI.setAdjustsStack(AdjustsStack); 344 MFI.setMaxCallFrameSize(MaxCallFrameSize); 345 346 for (MachineBasicBlock::iterator I : FrameSDOps) { 347 // If call frames are not being included as part of the stack frame, and 348 // the target doesn't indicate otherwise, remove the call frame pseudos 349 // here. The sub/add sp instruction pairs are still inserted, but we don't 350 // need to track the SP adjustment for frame index elimination. 351 if (TFI->canSimplifyCallFramePseudos(MF)) 352 TFI->eliminateCallFramePseudoInstr(MF, *I->getParent(), I); 353 } 354 } 355 356 /// Compute the sets of entry and return blocks for saving and restoring 357 /// callee-saved registers, and placing prolog and epilog code. 358 void PEI::calculateSaveRestoreBlocks(MachineFunction &MF) { 359 const MachineFrameInfo &MFI = MF.getFrameInfo(); 360 361 // Even when we do not change any CSR, we still want to insert the 362 // prologue and epilogue of the function. 363 // So set the save points for those. 364 365 // Use the points found by shrink-wrapping, if any. 366 if (MFI.getSavePoint()) { 367 SaveBlocks.push_back(MFI.getSavePoint()); 368 assert(MFI.getRestorePoint() && "Both restore and save must be set"); 369 MachineBasicBlock *RestoreBlock = MFI.getRestorePoint(); 370 // If RestoreBlock does not have any successor and is not a return block 371 // then the end point is unreachable and we do not need to insert any 372 // epilogue. 373 if (!RestoreBlock->succ_empty() || RestoreBlock->isReturnBlock()) 374 RestoreBlocks.push_back(RestoreBlock); 375 return; 376 } 377 378 // Save refs to entry and return blocks. 379 SaveBlocks.push_back(&MF.front()); 380 for (MachineBasicBlock &MBB : MF) { 381 if (MBB.isEHFuncletEntry()) 382 SaveBlocks.push_back(&MBB); 383 if (MBB.isReturnBlock()) 384 RestoreBlocks.push_back(&MBB); 385 } 386 } 387 388 static void assignCalleeSavedSpillSlots(MachineFunction &F, 389 const BitVector &SavedRegs, 390 unsigned &MinCSFrameIndex, 391 unsigned &MaxCSFrameIndex) { 392 if (SavedRegs.empty()) 393 return; 394 395 const TargetRegisterInfo *RegInfo = F.getSubtarget().getRegisterInfo(); 396 const MCPhysReg *CSRegs = F.getRegInfo().getCalleeSavedRegs(); 397 BitVector CSMask(SavedRegs.size()); 398 399 for (unsigned i = 0; CSRegs[i]; ++i) 400 CSMask.set(CSRegs[i]); 401 402 std::vector<CalleeSavedInfo> CSI; 403 for (unsigned i = 0; CSRegs[i]; ++i) { 404 unsigned Reg = CSRegs[i]; 405 if (SavedRegs.test(Reg)) { 406 bool SavedSuper = false; 407 for (const MCPhysReg &SuperReg : RegInfo->superregs(Reg)) { 408 // Some backends set all aliases for some registers as saved, such as 409 // Mips's $fp, so they appear in SavedRegs but not CSRegs. 410 if (SavedRegs.test(SuperReg) && CSMask.test(SuperReg)) { 411 SavedSuper = true; 412 break; 413 } 414 } 415 416 if (!SavedSuper) 417 CSI.push_back(CalleeSavedInfo(Reg)); 418 } 419 } 420 421 const TargetFrameLowering *TFI = F.getSubtarget().getFrameLowering(); 422 MachineFrameInfo &MFI = F.getFrameInfo(); 423 if (!TFI->assignCalleeSavedSpillSlots(F, RegInfo, CSI, MinCSFrameIndex, 424 MaxCSFrameIndex)) { 425 // If target doesn't implement this, use generic code. 426 427 if (CSI.empty()) 428 return; // Early exit if no callee saved registers are modified! 429 430 unsigned NumFixedSpillSlots; 431 const TargetFrameLowering::SpillSlot *FixedSpillSlots = 432 TFI->getCalleeSavedSpillSlots(NumFixedSpillSlots); 433 434 // Now that we know which registers need to be saved and restored, allocate 435 // stack slots for them. 436 for (auto &CS : CSI) { 437 // If the target has spilled this register to another register, we don't 438 // need to allocate a stack slot. 439 if (CS.isSpilledToReg()) 440 continue; 441 442 unsigned Reg = CS.getReg(); 443 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg); 444 445 int FrameIdx; 446 if (RegInfo->hasReservedSpillSlot(F, Reg, FrameIdx)) { 447 CS.setFrameIdx(FrameIdx); 448 continue; 449 } 450 451 // Check to see if this physreg must be spilled to a particular stack slot 452 // on this target. 453 const TargetFrameLowering::SpillSlot *FixedSlot = FixedSpillSlots; 454 while (FixedSlot != FixedSpillSlots + NumFixedSpillSlots && 455 FixedSlot->Reg != Reg) 456 ++FixedSlot; 457 458 unsigned Size = RegInfo->getSpillSize(*RC); 459 if (FixedSlot == FixedSpillSlots + NumFixedSpillSlots) { 460 // Nope, just spill it anywhere convenient. 461 Align Alignment = RegInfo->getSpillAlign(*RC); 462 // We may not be able to satisfy the desired alignment specification of 463 // the TargetRegisterClass if the stack alignment is smaller. Use the 464 // min. 465 Alignment = std::min(Alignment, TFI->getStackAlign()); 466 FrameIdx = MFI.CreateStackObject(Size, Alignment, true); 467 if ((unsigned)FrameIdx < MinCSFrameIndex) MinCSFrameIndex = FrameIdx; 468 if ((unsigned)FrameIdx > MaxCSFrameIndex) MaxCSFrameIndex = FrameIdx; 469 } else { 470 // Spill it to the stack where we must. 471 FrameIdx = MFI.CreateFixedSpillStackObject(Size, FixedSlot->Offset); 472 } 473 474 CS.setFrameIdx(FrameIdx); 475 } 476 } 477 478 MFI.setCalleeSavedInfo(CSI); 479 } 480 481 /// Helper function to update the liveness information for the callee-saved 482 /// registers. 483 static void updateLiveness(MachineFunction &MF) { 484 MachineFrameInfo &MFI = MF.getFrameInfo(); 485 // Visited will contain all the basic blocks that are in the region 486 // where the callee saved registers are alive: 487 // - Anything that is not Save or Restore -> LiveThrough. 488 // - Save -> LiveIn. 489 // - Restore -> LiveOut. 490 // The live-out is not attached to the block, so no need to keep 491 // Restore in this set. 492 SmallPtrSet<MachineBasicBlock *, 8> Visited; 493 SmallVector<MachineBasicBlock *, 8> WorkList; 494 MachineBasicBlock *Entry = &MF.front(); 495 MachineBasicBlock *Save = MFI.getSavePoint(); 496 497 if (!Save) 498 Save = Entry; 499 500 if (Entry != Save) { 501 WorkList.push_back(Entry); 502 Visited.insert(Entry); 503 } 504 Visited.insert(Save); 505 506 MachineBasicBlock *Restore = MFI.getRestorePoint(); 507 if (Restore) 508 // By construction Restore cannot be visited, otherwise it 509 // means there exists a path to Restore that does not go 510 // through Save. 511 WorkList.push_back(Restore); 512 513 while (!WorkList.empty()) { 514 const MachineBasicBlock *CurBB = WorkList.pop_back_val(); 515 // By construction, the region that is after the save point is 516 // dominated by the Save and post-dominated by the Restore. 517 if (CurBB == Save && Save != Restore) 518 continue; 519 // Enqueue all the successors not already visited. 520 // Those are by construction either before Save or after Restore. 521 for (MachineBasicBlock *SuccBB : CurBB->successors()) 522 if (Visited.insert(SuccBB).second) 523 WorkList.push_back(SuccBB); 524 } 525 526 const std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 527 528 MachineRegisterInfo &MRI = MF.getRegInfo(); 529 for (const CalleeSavedInfo &I : CSI) { 530 for (MachineBasicBlock *MBB : Visited) { 531 MCPhysReg Reg = I.getReg(); 532 // Add the callee-saved register as live-in. 533 // It's killed at the spill. 534 if (!MRI.isReserved(Reg) && !MBB->isLiveIn(Reg)) 535 MBB->addLiveIn(Reg); 536 } 537 // If callee-saved register is spilled to another register rather than 538 // spilling to stack, the destination register has to be marked as live for 539 // each MBB between the prologue and epilogue so that it is not clobbered 540 // before it is reloaded in the epilogue. The Visited set contains all 541 // blocks outside of the region delimited by prologue/epilogue. 542 if (I.isSpilledToReg()) { 543 for (MachineBasicBlock &MBB : MF) { 544 if (Visited.count(&MBB)) 545 continue; 546 MCPhysReg DstReg = I.getDstReg(); 547 if (!MBB.isLiveIn(DstReg)) 548 MBB.addLiveIn(DstReg); 549 } 550 } 551 } 552 } 553 554 /// Insert restore code for the callee-saved registers used in the function. 555 static void insertCSRSaves(MachineBasicBlock &SaveBlock, 556 ArrayRef<CalleeSavedInfo> CSI) { 557 MachineFunction &MF = *SaveBlock.getParent(); 558 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 559 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 560 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 561 562 MachineBasicBlock::iterator I = SaveBlock.begin(); 563 if (!TFI->spillCalleeSavedRegisters(SaveBlock, I, CSI, TRI)) { 564 for (const CalleeSavedInfo &CS : CSI) { 565 // Insert the spill to the stack frame. 566 unsigned Reg = CS.getReg(); 567 568 if (CS.isSpilledToReg()) { 569 BuildMI(SaveBlock, I, DebugLoc(), 570 TII.get(TargetOpcode::COPY), CS.getDstReg()) 571 .addReg(Reg, getKillRegState(true)); 572 } else { 573 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 574 TII.storeRegToStackSlot(SaveBlock, I, Reg, true, CS.getFrameIdx(), RC, 575 TRI); 576 } 577 } 578 } 579 } 580 581 /// Insert restore code for the callee-saved registers used in the function. 582 static void insertCSRRestores(MachineBasicBlock &RestoreBlock, 583 std::vector<CalleeSavedInfo> &CSI) { 584 MachineFunction &MF = *RestoreBlock.getParent(); 585 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 586 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 587 const TargetRegisterInfo *TRI = MF.getSubtarget().getRegisterInfo(); 588 589 // Restore all registers immediately before the return and any 590 // terminators that precede it. 591 MachineBasicBlock::iterator I = RestoreBlock.getFirstTerminator(); 592 593 if (!TFI->restoreCalleeSavedRegisters(RestoreBlock, I, CSI, TRI)) { 594 for (const CalleeSavedInfo &CI : reverse(CSI)) { 595 unsigned Reg = CI.getReg(); 596 if (CI.isSpilledToReg()) { 597 BuildMI(RestoreBlock, I, DebugLoc(), TII.get(TargetOpcode::COPY), Reg) 598 .addReg(CI.getDstReg(), getKillRegState(true)); 599 } else { 600 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg); 601 TII.loadRegFromStackSlot(RestoreBlock, I, Reg, CI.getFrameIdx(), RC, TRI); 602 assert(I != RestoreBlock.begin() && 603 "loadRegFromStackSlot didn't insert any code!"); 604 // Insert in reverse order. loadRegFromStackSlot can insert 605 // multiple instructions. 606 } 607 } 608 } 609 } 610 611 void PEI::spillCalleeSavedRegs(MachineFunction &MF) { 612 // We can't list this requirement in getRequiredProperties because some 613 // targets (WebAssembly) use virtual registers past this point, and the pass 614 // pipeline is set up without giving the passes a chance to look at the 615 // TargetMachine. 616 // FIXME: Find a way to express this in getRequiredProperties. 617 assert(MF.getProperties().hasProperty( 618 MachineFunctionProperties::Property::NoVRegs)); 619 620 const Function &F = MF.getFunction(); 621 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 622 MachineFrameInfo &MFI = MF.getFrameInfo(); 623 MinCSFrameIndex = std::numeric_limits<unsigned>::max(); 624 MaxCSFrameIndex = 0; 625 626 // Determine which of the registers in the callee save list should be saved. 627 BitVector SavedRegs; 628 TFI->determineCalleeSaves(MF, SavedRegs, RS); 629 630 // Assign stack slots for any callee-saved registers that must be spilled. 631 assignCalleeSavedSpillSlots(MF, SavedRegs, MinCSFrameIndex, MaxCSFrameIndex); 632 633 // Add the code to save and restore the callee saved registers. 634 if (!F.hasFnAttribute(Attribute::Naked)) { 635 MFI.setCalleeSavedInfoValid(true); 636 637 std::vector<CalleeSavedInfo> &CSI = MFI.getCalleeSavedInfo(); 638 if (!CSI.empty()) { 639 if (!MFI.hasCalls()) 640 NumLeafFuncWithSpills++; 641 642 for (MachineBasicBlock *SaveBlock : SaveBlocks) 643 insertCSRSaves(*SaveBlock, CSI); 644 645 // Update the live-in information of all the blocks up to the save point. 646 updateLiveness(MF); 647 648 for (MachineBasicBlock *RestoreBlock : RestoreBlocks) 649 insertCSRRestores(*RestoreBlock, CSI); 650 } 651 } 652 } 653 654 /// AdjustStackOffset - Helper function used to adjust the stack frame offset. 655 static inline void AdjustStackOffset(MachineFrameInfo &MFI, int FrameIdx, 656 bool StackGrowsDown, int64_t &Offset, 657 Align &MaxAlign, unsigned Skew) { 658 // If the stack grows down, add the object size to find the lowest address. 659 if (StackGrowsDown) 660 Offset += MFI.getObjectSize(FrameIdx); 661 662 Align Alignment = MFI.getObjectAlign(FrameIdx); 663 664 // If the alignment of this object is greater than that of the stack, then 665 // increase the stack alignment to match. 666 MaxAlign = std::max(MaxAlign, Alignment); 667 668 // Adjust to alignment boundary. 669 Offset = alignTo(Offset, Alignment, Skew); 670 671 if (StackGrowsDown) { 672 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << -Offset 673 << "]\n"); 674 MFI.setObjectOffset(FrameIdx, -Offset); // Set the computed offset 675 } else { 676 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") at SP[" << Offset 677 << "]\n"); 678 MFI.setObjectOffset(FrameIdx, Offset); 679 Offset += MFI.getObjectSize(FrameIdx); 680 } 681 } 682 683 /// Compute which bytes of fixed and callee-save stack area are unused and keep 684 /// track of them in StackBytesFree. 685 static inline void 686 computeFreeStackSlots(MachineFrameInfo &MFI, bool StackGrowsDown, 687 unsigned MinCSFrameIndex, unsigned MaxCSFrameIndex, 688 int64_t FixedCSEnd, BitVector &StackBytesFree) { 689 // Avoid undefined int64_t -> int conversion below in extreme case. 690 if (FixedCSEnd > std::numeric_limits<int>::max()) 691 return; 692 693 StackBytesFree.resize(FixedCSEnd, true); 694 695 SmallVector<int, 16> AllocatedFrameSlots; 696 // Add fixed objects. 697 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) 698 // StackSlot scavenging is only implemented for the default stack. 699 if (MFI.getStackID(i) == TargetStackID::Default) 700 AllocatedFrameSlots.push_back(i); 701 // Add callee-save objects if there are any. 702 if (MinCSFrameIndex <= MaxCSFrameIndex) { 703 for (int i = MinCSFrameIndex; i <= (int)MaxCSFrameIndex; ++i) 704 if (MFI.getStackID(i) == TargetStackID::Default) 705 AllocatedFrameSlots.push_back(i); 706 } 707 708 for (int i : AllocatedFrameSlots) { 709 // These are converted from int64_t, but they should always fit in int 710 // because of the FixedCSEnd check above. 711 int ObjOffset = MFI.getObjectOffset(i); 712 int ObjSize = MFI.getObjectSize(i); 713 int ObjStart, ObjEnd; 714 if (StackGrowsDown) { 715 // ObjOffset is negative when StackGrowsDown is true. 716 ObjStart = -ObjOffset - ObjSize; 717 ObjEnd = -ObjOffset; 718 } else { 719 ObjStart = ObjOffset; 720 ObjEnd = ObjOffset + ObjSize; 721 } 722 // Ignore fixed holes that are in the previous stack frame. 723 if (ObjEnd > 0) 724 StackBytesFree.reset(ObjStart, ObjEnd); 725 } 726 } 727 728 /// Assign frame object to an unused portion of the stack in the fixed stack 729 /// object range. Return true if the allocation was successful. 730 static inline bool scavengeStackSlot(MachineFrameInfo &MFI, int FrameIdx, 731 bool StackGrowsDown, Align MaxAlign, 732 BitVector &StackBytesFree) { 733 if (MFI.isVariableSizedObjectIndex(FrameIdx)) 734 return false; 735 736 if (StackBytesFree.none()) { 737 // clear it to speed up later scavengeStackSlot calls to 738 // StackBytesFree.none() 739 StackBytesFree.clear(); 740 return false; 741 } 742 743 Align ObjAlign = MFI.getObjectAlign(FrameIdx); 744 if (ObjAlign > MaxAlign) 745 return false; 746 747 int64_t ObjSize = MFI.getObjectSize(FrameIdx); 748 int FreeStart; 749 for (FreeStart = StackBytesFree.find_first(); FreeStart != -1; 750 FreeStart = StackBytesFree.find_next(FreeStart)) { 751 752 // Check that free space has suitable alignment. 753 unsigned ObjStart = StackGrowsDown ? FreeStart + ObjSize : FreeStart; 754 if (alignTo(ObjStart, ObjAlign) != ObjStart) 755 continue; 756 757 if (FreeStart + ObjSize > StackBytesFree.size()) 758 return false; 759 760 bool AllBytesFree = true; 761 for (unsigned Byte = 0; Byte < ObjSize; ++Byte) 762 if (!StackBytesFree.test(FreeStart + Byte)) { 763 AllBytesFree = false; 764 break; 765 } 766 if (AllBytesFree) 767 break; 768 } 769 770 if (FreeStart == -1) 771 return false; 772 773 if (StackGrowsDown) { 774 int ObjStart = -(FreeStart + ObjSize); 775 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" 776 << ObjStart << "]\n"); 777 MFI.setObjectOffset(FrameIdx, ObjStart); 778 } else { 779 LLVM_DEBUG(dbgs() << "alloc FI(" << FrameIdx << ") scavenged at SP[" 780 << FreeStart << "]\n"); 781 MFI.setObjectOffset(FrameIdx, FreeStart); 782 } 783 784 StackBytesFree.reset(FreeStart, FreeStart + ObjSize); 785 return true; 786 } 787 788 /// AssignProtectedObjSet - Helper function to assign large stack objects (i.e., 789 /// those required to be close to the Stack Protector) to stack offsets. 790 static void AssignProtectedObjSet(const StackObjSet &UnassignedObjs, 791 SmallSet<int, 16> &ProtectedObjs, 792 MachineFrameInfo &MFI, bool StackGrowsDown, 793 int64_t &Offset, Align &MaxAlign, 794 unsigned Skew) { 795 796 for (int i : UnassignedObjs) { 797 AdjustStackOffset(MFI, i, StackGrowsDown, Offset, MaxAlign, Skew); 798 ProtectedObjs.insert(i); 799 } 800 } 801 802 /// calculateFrameObjectOffsets - Calculate actual frame offsets for all of the 803 /// abstract stack objects. 804 void PEI::calculateFrameObjectOffsets(MachineFunction &MF) { 805 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering(); 806 807 bool StackGrowsDown = 808 TFI.getStackGrowthDirection() == TargetFrameLowering::StackGrowsDown; 809 810 // Loop over all of the stack objects, assigning sequential addresses... 811 MachineFrameInfo &MFI = MF.getFrameInfo(); 812 813 // Start at the beginning of the local area. 814 // The Offset is the distance from the stack top in the direction 815 // of stack growth -- so it's always nonnegative. 816 int LocalAreaOffset = TFI.getOffsetOfLocalArea(); 817 if (StackGrowsDown) 818 LocalAreaOffset = -LocalAreaOffset; 819 assert(LocalAreaOffset >= 0 820 && "Local area offset should be in direction of stack growth"); 821 int64_t Offset = LocalAreaOffset; 822 823 // Skew to be applied to alignment. 824 unsigned Skew = TFI.getStackAlignmentSkew(MF); 825 826 #ifdef EXPENSIVE_CHECKS 827 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) 828 if (!MFI.isDeadObjectIndex(i) && 829 MFI.getStackID(i) == TargetStackID::Default) 830 assert(MFI.getObjectAlign(i) <= MFI.getMaxAlign() && 831 "MaxAlignment is invalid"); 832 #endif 833 834 // If there are fixed sized objects that are preallocated in the local area, 835 // non-fixed objects can't be allocated right at the start of local area. 836 // Adjust 'Offset' to point to the end of last fixed sized preallocated 837 // object. 838 for (int i = MFI.getObjectIndexBegin(); i != 0; ++i) { 839 if (MFI.getStackID(i) != 840 TargetStackID::Default) // Only allocate objects on the default stack. 841 continue; 842 843 int64_t FixedOff; 844 if (StackGrowsDown) { 845 // The maximum distance from the stack pointer is at lower address of 846 // the object -- which is given by offset. For down growing stack 847 // the offset is negative, so we negate the offset to get the distance. 848 FixedOff = -MFI.getObjectOffset(i); 849 } else { 850 // The maximum distance from the start pointer is at the upper 851 // address of the object. 852 FixedOff = MFI.getObjectOffset(i) + MFI.getObjectSize(i); 853 } 854 if (FixedOff > Offset) Offset = FixedOff; 855 } 856 857 Align MaxAlign = MFI.getMaxAlign(); 858 // First assign frame offsets to stack objects that are used to spill 859 // callee saved registers. 860 if (MaxCSFrameIndex >= MinCSFrameIndex) { 861 for (unsigned i = 0; i <= MaxCSFrameIndex - MinCSFrameIndex; ++i) { 862 unsigned FrameIndex = 863 StackGrowsDown ? MinCSFrameIndex + i : MaxCSFrameIndex - i; 864 865 // Only allocate objects on the default stack. 866 if (MFI.getStackID(FrameIndex) != TargetStackID::Default) 867 continue; 868 869 // TODO: should this just be if (MFI.isDeadObjectIndex(FrameIndex)) 870 if (!StackGrowsDown && MFI.isDeadObjectIndex(FrameIndex)) 871 continue; 872 873 AdjustStackOffset(MFI, FrameIndex, StackGrowsDown, Offset, MaxAlign, 874 Skew); 875 } 876 } 877 878 assert(MaxAlign == MFI.getMaxAlign() && 879 "MFI.getMaxAlign should already account for all callee-saved " 880 "registers without a fixed stack slot"); 881 882 // FixedCSEnd is the stack offset to the end of the fixed and callee-save 883 // stack area. 884 int64_t FixedCSEnd = Offset; 885 886 // Make sure the special register scavenging spill slot is closest to the 887 // incoming stack pointer if a frame pointer is required and is closer 888 // to the incoming rather than the final stack pointer. 889 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo(); 890 bool EarlyScavengingSlots = TFI.allocateScavengingFrameIndexesNearIncomingSP(MF); 891 if (RS && EarlyScavengingSlots) { 892 SmallVector<int, 2> SFIs; 893 RS->getScavengingFrameIndices(SFIs); 894 for (int SFI : SFIs) 895 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign, Skew); 896 } 897 898 // FIXME: Once this is working, then enable flag will change to a target 899 // check for whether the frame is large enough to want to use virtual 900 // frame index registers. Functions which don't want/need this optimization 901 // will continue to use the existing code path. 902 if (MFI.getUseLocalStackAllocationBlock()) { 903 Align Alignment = MFI.getLocalFrameMaxAlign(); 904 905 // Adjust to alignment boundary. 906 Offset = alignTo(Offset, Alignment, Skew); 907 908 LLVM_DEBUG(dbgs() << "Local frame base offset: " << Offset << "\n"); 909 910 // Resolve offsets for objects in the local block. 911 for (unsigned i = 0, e = MFI.getLocalFrameObjectCount(); i != e; ++i) { 912 std::pair<int, int64_t> Entry = MFI.getLocalFrameObjectMap(i); 913 int64_t FIOffset = (StackGrowsDown ? -Offset : Offset) + Entry.second; 914 LLVM_DEBUG(dbgs() << "alloc FI(" << Entry.first << ") at SP[" << FIOffset 915 << "]\n"); 916 MFI.setObjectOffset(Entry.first, FIOffset); 917 } 918 // Allocate the local block 919 Offset += MFI.getLocalFrameSize(); 920 921 MaxAlign = std::max(Alignment, MaxAlign); 922 } 923 924 // Retrieve the Exception Handler registration node. 925 int EHRegNodeFrameIndex = std::numeric_limits<int>::max(); 926 if (const WinEHFuncInfo *FuncInfo = MF.getWinEHFuncInfo()) 927 EHRegNodeFrameIndex = FuncInfo->EHRegNodeFrameIndex; 928 929 // Make sure that the stack protector comes before the local variables on the 930 // stack. 931 SmallSet<int, 16> ProtectedObjs; 932 if (MFI.hasStackProtectorIndex()) { 933 int StackProtectorFI = MFI.getStackProtectorIndex(); 934 StackObjSet LargeArrayObjs; 935 StackObjSet SmallArrayObjs; 936 StackObjSet AddrOfObjs; 937 938 // If we need a stack protector, we need to make sure that 939 // LocalStackSlotPass didn't already allocate a slot for it. 940 // If we are told to use the LocalStackAllocationBlock, the stack protector 941 // is expected to be already pre-allocated. 942 if (MFI.getStackID(StackProtectorFI) != TargetStackID::Default) { 943 // If the stack protector isn't on the default stack then it's up to the 944 // target to set the stack offset. 945 assert(MFI.getObjectOffset(StackProtectorFI) != 0 && 946 "Offset of stack protector on non-default stack expected to be " 947 "already set."); 948 assert(!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex()) && 949 "Stack protector on non-default stack expected to not be " 950 "pre-allocated by LocalStackSlotPass."); 951 } else if (!MFI.getUseLocalStackAllocationBlock()) { 952 AdjustStackOffset(MFI, StackProtectorFI, StackGrowsDown, Offset, MaxAlign, 953 Skew); 954 } else if (!MFI.isObjectPreAllocated(MFI.getStackProtectorIndex())) { 955 llvm_unreachable( 956 "Stack protector not pre-allocated by LocalStackSlotPass."); 957 } 958 959 // Assign large stack objects first. 960 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 961 if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock()) 962 continue; 963 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 964 continue; 965 if (RS && RS->isScavengingFrameIndex((int)i)) 966 continue; 967 if (MFI.isDeadObjectIndex(i)) 968 continue; 969 if (StackProtectorFI == (int)i || EHRegNodeFrameIndex == (int)i) 970 continue; 971 if (MFI.getStackID(i) != 972 TargetStackID::Default) // Only allocate objects on the default stack. 973 continue; 974 975 switch (MFI.getObjectSSPLayout(i)) { 976 case MachineFrameInfo::SSPLK_None: 977 continue; 978 case MachineFrameInfo::SSPLK_SmallArray: 979 SmallArrayObjs.insert(i); 980 continue; 981 case MachineFrameInfo::SSPLK_AddrOf: 982 AddrOfObjs.insert(i); 983 continue; 984 case MachineFrameInfo::SSPLK_LargeArray: 985 LargeArrayObjs.insert(i); 986 continue; 987 } 988 llvm_unreachable("Unexpected SSPLayoutKind."); 989 } 990 991 // We expect **all** the protected stack objects to be pre-allocated by 992 // LocalStackSlotPass. If it turns out that PEI still has to allocate some 993 // of them, we may end up messing up the expected order of the objects. 994 if (MFI.getUseLocalStackAllocationBlock() && 995 !(LargeArrayObjs.empty() && SmallArrayObjs.empty() && 996 AddrOfObjs.empty())) 997 llvm_unreachable("Found protected stack objects not pre-allocated by " 998 "LocalStackSlotPass."); 999 1000 AssignProtectedObjSet(LargeArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 1001 Offset, MaxAlign, Skew); 1002 AssignProtectedObjSet(SmallArrayObjs, ProtectedObjs, MFI, StackGrowsDown, 1003 Offset, MaxAlign, Skew); 1004 AssignProtectedObjSet(AddrOfObjs, ProtectedObjs, MFI, StackGrowsDown, 1005 Offset, MaxAlign, Skew); 1006 } 1007 1008 SmallVector<int, 8> ObjectsToAllocate; 1009 1010 // Then prepare to assign frame offsets to stack objects that are not used to 1011 // spill callee saved registers. 1012 for (unsigned i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) { 1013 if (MFI.isObjectPreAllocated(i) && MFI.getUseLocalStackAllocationBlock()) 1014 continue; 1015 if (i >= MinCSFrameIndex && i <= MaxCSFrameIndex) 1016 continue; 1017 if (RS && RS->isScavengingFrameIndex((int)i)) 1018 continue; 1019 if (MFI.isDeadObjectIndex(i)) 1020 continue; 1021 if (MFI.getStackProtectorIndex() == (int)i || EHRegNodeFrameIndex == (int)i) 1022 continue; 1023 if (ProtectedObjs.count(i)) 1024 continue; 1025 if (MFI.getStackID(i) != 1026 TargetStackID::Default) // Only allocate objects on the default stack. 1027 continue; 1028 1029 // Add the objects that we need to allocate to our working set. 1030 ObjectsToAllocate.push_back(i); 1031 } 1032 1033 // Allocate the EH registration node first if one is present. 1034 if (EHRegNodeFrameIndex != std::numeric_limits<int>::max()) 1035 AdjustStackOffset(MFI, EHRegNodeFrameIndex, StackGrowsDown, Offset, 1036 MaxAlign, Skew); 1037 1038 // Give the targets a chance to order the objects the way they like it. 1039 if (MF.getTarget().getOptLevel() != CodeGenOpt::None && 1040 MF.getTarget().Options.StackSymbolOrdering) 1041 TFI.orderFrameObjects(MF, ObjectsToAllocate); 1042 1043 // Keep track of which bytes in the fixed and callee-save range are used so we 1044 // can use the holes when allocating later stack objects. Only do this if 1045 // stack protector isn't being used and the target requests it and we're 1046 // optimizing. 1047 BitVector StackBytesFree; 1048 if (!ObjectsToAllocate.empty() && 1049 MF.getTarget().getOptLevel() != CodeGenOpt::None && 1050 MFI.getStackProtectorIndex() < 0 && TFI.enableStackSlotScavenging(MF)) 1051 computeFreeStackSlots(MFI, StackGrowsDown, MinCSFrameIndex, MaxCSFrameIndex, 1052 FixedCSEnd, StackBytesFree); 1053 1054 // Now walk the objects and actually assign base offsets to them. 1055 for (auto &Object : ObjectsToAllocate) 1056 if (!scavengeStackSlot(MFI, Object, StackGrowsDown, MaxAlign, 1057 StackBytesFree)) 1058 AdjustStackOffset(MFI, Object, StackGrowsDown, Offset, MaxAlign, Skew); 1059 1060 // Make sure the special register scavenging spill slot is closest to the 1061 // stack pointer. 1062 if (RS && !EarlyScavengingSlots) { 1063 SmallVector<int, 2> SFIs; 1064 RS->getScavengingFrameIndices(SFIs); 1065 for (int SFI : SFIs) 1066 AdjustStackOffset(MFI, SFI, StackGrowsDown, Offset, MaxAlign, Skew); 1067 } 1068 1069 if (!TFI.targetHandlesStackFrameRounding()) { 1070 // If we have reserved argument space for call sites in the function 1071 // immediately on entry to the current function, count it as part of the 1072 // overall stack size. 1073 if (MFI.adjustsStack() && TFI.hasReservedCallFrame(MF)) 1074 Offset += MFI.getMaxCallFrameSize(); 1075 1076 // Round up the size to a multiple of the alignment. If the function has 1077 // any calls or alloca's, align to the target's StackAlignment value to 1078 // ensure that the callee's frame or the alloca data is suitably aligned; 1079 // otherwise, for leaf functions, align to the TransientStackAlignment 1080 // value. 1081 Align StackAlign; 1082 if (MFI.adjustsStack() || MFI.hasVarSizedObjects() || 1083 (RegInfo->hasStackRealignment(MF) && MFI.getObjectIndexEnd() != 0)) 1084 StackAlign = TFI.getStackAlign(); 1085 else 1086 StackAlign = TFI.getTransientStackAlign(); 1087 1088 // If the frame pointer is eliminated, all frame offsets will be relative to 1089 // SP not FP. Align to MaxAlign so this works. 1090 StackAlign = std::max(StackAlign, MaxAlign); 1091 int64_t OffsetBeforeAlignment = Offset; 1092 Offset = alignTo(Offset, StackAlign, Skew); 1093 1094 // If we have increased the offset to fulfill the alignment constrants, 1095 // then the scavenging spill slots may become harder to reach from the 1096 // stack pointer, float them so they stay close. 1097 if (StackGrowsDown && OffsetBeforeAlignment != Offset && RS && 1098 !EarlyScavengingSlots) { 1099 SmallVector<int, 2> SFIs; 1100 RS->getScavengingFrameIndices(SFIs); 1101 LLVM_DEBUG(if (!SFIs.empty()) llvm::dbgs() 1102 << "Adjusting emergency spill slots!\n";); 1103 int64_t Delta = Offset - OffsetBeforeAlignment; 1104 for (int SFI : SFIs) { 1105 LLVM_DEBUG(llvm::dbgs() 1106 << "Adjusting offset of emergency spill slot #" << SFI 1107 << " from " << MFI.getObjectOffset(SFI);); 1108 MFI.setObjectOffset(SFI, MFI.getObjectOffset(SFI) - Delta); 1109 LLVM_DEBUG(llvm::dbgs() << " to " << MFI.getObjectOffset(SFI) << "\n";); 1110 } 1111 } 1112 } 1113 1114 // Update frame info to pretend that this is part of the stack... 1115 int64_t StackSize = Offset - LocalAreaOffset; 1116 MFI.setStackSize(StackSize); 1117 NumBytesStackSpace += StackSize; 1118 } 1119 1120 /// insertPrologEpilogCode - Scan the function for modified callee saved 1121 /// registers, insert spill code for these callee saved registers, then add 1122 /// prolog and epilog code to the function. 1123 void PEI::insertPrologEpilogCode(MachineFunction &MF) { 1124 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering(); 1125 1126 // Add prologue to the function... 1127 for (MachineBasicBlock *SaveBlock : SaveBlocks) 1128 TFI.emitPrologue(MF, *SaveBlock); 1129 1130 // Add epilogue to restore the callee-save registers in each exiting block. 1131 for (MachineBasicBlock *RestoreBlock : RestoreBlocks) 1132 TFI.emitEpilogue(MF, *RestoreBlock); 1133 1134 // Zero call used registers before restoring callee-saved registers. 1135 insertZeroCallUsedRegs(MF); 1136 1137 for (MachineBasicBlock *SaveBlock : SaveBlocks) 1138 TFI.inlineStackProbe(MF, *SaveBlock); 1139 1140 // Emit additional code that is required to support segmented stacks, if 1141 // we've been asked for it. This, when linked with a runtime with support 1142 // for segmented stacks (libgcc is one), will result in allocating stack 1143 // space in small chunks instead of one large contiguous block. 1144 if (MF.shouldSplitStack()) { 1145 for (MachineBasicBlock *SaveBlock : SaveBlocks) 1146 TFI.adjustForSegmentedStacks(MF, *SaveBlock); 1147 // Record that there are split-stack functions, so we will emit a 1148 // special section to tell the linker. 1149 MF.getMMI().setHasSplitStack(true); 1150 } else 1151 MF.getMMI().setHasNosplitStack(true); 1152 1153 // Emit additional code that is required to explicitly handle the stack in 1154 // HiPE native code (if needed) when loaded in the Erlang/OTP runtime. The 1155 // approach is rather similar to that of Segmented Stacks, but it uses a 1156 // different conditional check and another BIF for allocating more stack 1157 // space. 1158 if (MF.getFunction().getCallingConv() == CallingConv::HiPE) 1159 for (MachineBasicBlock *SaveBlock : SaveBlocks) 1160 TFI.adjustForHiPEPrologue(MF, *SaveBlock); 1161 } 1162 1163 /// insertZeroCallUsedRegs - Zero out call used registers. 1164 void PEI::insertZeroCallUsedRegs(MachineFunction &MF) { 1165 const Function &F = MF.getFunction(); 1166 1167 if (!F.hasFnAttribute("zero-call-used-regs")) 1168 return; 1169 1170 using namespace ZeroCallUsedRegs; 1171 1172 ZeroCallUsedRegsKind ZeroRegsKind = 1173 StringSwitch<ZeroCallUsedRegsKind>( 1174 F.getFnAttribute("zero-call-used-regs").getValueAsString()) 1175 .Case("skip", ZeroCallUsedRegsKind::Skip) 1176 .Case("used-gpr-arg", ZeroCallUsedRegsKind::UsedGPRArg) 1177 .Case("used-gpr", ZeroCallUsedRegsKind::UsedGPR) 1178 .Case("used-arg", ZeroCallUsedRegsKind::UsedArg) 1179 .Case("used", ZeroCallUsedRegsKind::Used) 1180 .Case("all-gpr-arg", ZeroCallUsedRegsKind::AllGPRArg) 1181 .Case("all-gpr", ZeroCallUsedRegsKind::AllGPR) 1182 .Case("all-arg", ZeroCallUsedRegsKind::AllArg) 1183 .Case("all", ZeroCallUsedRegsKind::All); 1184 1185 if (ZeroRegsKind == ZeroCallUsedRegsKind::Skip) 1186 return; 1187 1188 const bool OnlyGPR = static_cast<unsigned>(ZeroRegsKind) & ONLY_GPR; 1189 const bool OnlyUsed = static_cast<unsigned>(ZeroRegsKind) & ONLY_USED; 1190 const bool OnlyArg = static_cast<unsigned>(ZeroRegsKind) & ONLY_ARG; 1191 1192 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 1193 const BitVector AllocatableSet(TRI.getAllocatableSet(MF)); 1194 1195 // Mark all used registers. 1196 BitVector UsedRegs(TRI.getNumRegs()); 1197 if (OnlyUsed) 1198 for (const MachineBasicBlock &MBB : MF) 1199 for (const MachineInstr &MI : MBB) 1200 for (const MachineOperand &MO : MI.operands()) { 1201 if (!MO.isReg()) 1202 continue; 1203 1204 MCRegister Reg = MO.getReg(); 1205 if (AllocatableSet[Reg] && !MO.isImplicit() && 1206 (MO.isDef() || MO.isUse())) 1207 UsedRegs.set(Reg); 1208 } 1209 1210 BitVector RegsToZero(TRI.getNumRegs()); 1211 for (MCRegister Reg : AllocatableSet.set_bits()) { 1212 // Skip over fixed registers. 1213 if (TRI.isFixedRegister(MF, Reg)) 1214 continue; 1215 1216 // Want only general purpose registers. 1217 if (OnlyGPR && !TRI.isGeneralPurposeRegister(MF, Reg)) 1218 continue; 1219 1220 // Want only used registers. 1221 if (OnlyUsed && !UsedRegs[Reg]) 1222 continue; 1223 1224 // Want only registers used for arguments. 1225 if (OnlyArg && !TRI.isArgumentRegister(MF, Reg)) 1226 continue; 1227 1228 RegsToZero.set(Reg); 1229 } 1230 1231 // Remove registers that are live when leaving the function. 1232 for (const MachineBasicBlock &MBB : MF) 1233 for (const MachineInstr &MI : MBB.terminators()) { 1234 if (!MI.isReturn()) 1235 continue; 1236 1237 for (const auto &MO : MI.operands()) { 1238 if (!MO.isReg()) 1239 continue; 1240 1241 for (MCPhysReg SReg : TRI.sub_and_superregs_inclusive(MO.getReg())) 1242 RegsToZero.reset(SReg); 1243 } 1244 } 1245 1246 const TargetFrameLowering &TFI = *MF.getSubtarget().getFrameLowering(); 1247 for (MachineBasicBlock &MBB : MF) 1248 if (MBB.isReturnBlock()) 1249 TFI.emitZeroCallUsedRegs(RegsToZero, MBB); 1250 } 1251 1252 /// replaceFrameIndices - Replace all MO_FrameIndex operands with physical 1253 /// register references and actual offsets. 1254 void PEI::replaceFrameIndices(MachineFunction &MF) { 1255 const auto &ST = MF.getSubtarget(); 1256 const TargetFrameLowering &TFI = *ST.getFrameLowering(); 1257 if (!TFI.needsFrameIndexResolution(MF)) 1258 return; 1259 1260 const TargetRegisterInfo *TRI = ST.getRegisterInfo(); 1261 1262 // Allow the target to determine this after knowing the frame size. 1263 FrameIndexEliminationScavenging = (RS && !FrameIndexVirtualScavenging) || 1264 TRI->requiresFrameIndexReplacementScavenging(MF); 1265 1266 // Store SPAdj at exit of a basic block. 1267 SmallVector<int, 8> SPState; 1268 SPState.resize(MF.getNumBlockIDs()); 1269 df_iterator_default_set<MachineBasicBlock*> Reachable; 1270 1271 // Iterate over the reachable blocks in DFS order. 1272 for (auto DFI = df_ext_begin(&MF, Reachable), DFE = df_ext_end(&MF, Reachable); 1273 DFI != DFE; ++DFI) { 1274 int SPAdj = 0; 1275 // Check the exit state of the DFS stack predecessor. 1276 if (DFI.getPathLength() >= 2) { 1277 MachineBasicBlock *StackPred = DFI.getPath(DFI.getPathLength() - 2); 1278 assert(Reachable.count(StackPred) && 1279 "DFS stack predecessor is already visited.\n"); 1280 SPAdj = SPState[StackPred->getNumber()]; 1281 } 1282 MachineBasicBlock *BB = *DFI; 1283 replaceFrameIndices(BB, MF, SPAdj); 1284 SPState[BB->getNumber()] = SPAdj; 1285 } 1286 1287 // Handle the unreachable blocks. 1288 for (auto &BB : MF) { 1289 if (Reachable.count(&BB)) 1290 // Already handled in DFS traversal. 1291 continue; 1292 int SPAdj = 0; 1293 replaceFrameIndices(&BB, MF, SPAdj); 1294 } 1295 } 1296 1297 void PEI::replaceFrameIndices(MachineBasicBlock *BB, MachineFunction &MF, 1298 int &SPAdj) { 1299 assert(MF.getSubtarget().getRegisterInfo() && 1300 "getRegisterInfo() must be implemented!"); 1301 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo(); 1302 const TargetRegisterInfo &TRI = *MF.getSubtarget().getRegisterInfo(); 1303 const TargetFrameLowering *TFI = MF.getSubtarget().getFrameLowering(); 1304 1305 if (RS && FrameIndexEliminationScavenging) 1306 RS->enterBasicBlock(*BB); 1307 1308 bool InsideCallSequence = false; 1309 1310 for (MachineBasicBlock::iterator I = BB->begin(); I != BB->end(); ) { 1311 if (TII.isFrameInstr(*I)) { 1312 InsideCallSequence = TII.isFrameSetup(*I); 1313 SPAdj += TII.getSPAdjust(*I); 1314 I = TFI->eliminateCallFramePseudoInstr(MF, *BB, I); 1315 continue; 1316 } 1317 1318 MachineInstr &MI = *I; 1319 bool DoIncr = true; 1320 bool DidFinishLoop = true; 1321 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1322 if (!MI.getOperand(i).isFI()) 1323 continue; 1324 1325 // Frame indices in debug values are encoded in a target independent 1326 // way with simply the frame index and offset rather than any 1327 // target-specific addressing mode. 1328 if (MI.isDebugValue()) { 1329 MachineOperand &Op = MI.getOperand(i); 1330 assert( 1331 MI.isDebugOperand(&Op) && 1332 "Frame indices can only appear as a debug operand in a DBG_VALUE*" 1333 " machine instruction"); 1334 Register Reg; 1335 unsigned FrameIdx = Op.getIndex(); 1336 unsigned Size = MF.getFrameInfo().getObjectSize(FrameIdx); 1337 1338 StackOffset Offset = 1339 TFI->getFrameIndexReference(MF, FrameIdx, Reg); 1340 Op.ChangeToRegister(Reg, false /*isDef*/); 1341 1342 const DIExpression *DIExpr = MI.getDebugExpression(); 1343 1344 // If we have a direct DBG_VALUE, and its location expression isn't 1345 // currently complex, then adding an offset will morph it into a 1346 // complex location that is interpreted as being a memory address. 1347 // This changes a pointer-valued variable to dereference that pointer, 1348 // which is incorrect. Fix by adding DW_OP_stack_value. 1349 1350 if (MI.isNonListDebugValue()) { 1351 unsigned PrependFlags = DIExpression::ApplyOffset; 1352 if (!MI.isIndirectDebugValue() && !DIExpr->isComplex()) 1353 PrependFlags |= DIExpression::StackValue; 1354 1355 // If we have DBG_VALUE that is indirect and has a Implicit location 1356 // expression need to insert a deref before prepending a Memory 1357 // location expression. Also after doing this we change the DBG_VALUE 1358 // to be direct. 1359 if (MI.isIndirectDebugValue() && DIExpr->isImplicit()) { 1360 SmallVector<uint64_t, 2> Ops = {dwarf::DW_OP_deref_size, Size}; 1361 bool WithStackValue = true; 1362 DIExpr = DIExpression::prependOpcodes(DIExpr, Ops, WithStackValue); 1363 // Make the DBG_VALUE direct. 1364 MI.getDebugOffset().ChangeToRegister(0, false); 1365 } 1366 DIExpr = TRI.prependOffsetExpression(DIExpr, PrependFlags, Offset); 1367 } else { 1368 // The debug operand at DebugOpIndex was a frame index at offset 1369 // `Offset`; now the operand has been replaced with the frame 1370 // register, we must add Offset with `register x, plus Offset`. 1371 unsigned DebugOpIndex = MI.getDebugOperandIndex(&Op); 1372 SmallVector<uint64_t, 3> Ops; 1373 TRI.getOffsetOpcodes(Offset, Ops); 1374 DIExpr = DIExpression::appendOpsToArg(DIExpr, Ops, DebugOpIndex); 1375 } 1376 MI.getDebugExpressionOp().setMetadata(DIExpr); 1377 continue; 1378 } else if (MI.isDebugPHI()) { 1379 // Allow stack ref to continue onwards. 1380 continue; 1381 } 1382 1383 // TODO: This code should be commoned with the code for 1384 // PATCHPOINT. There's no good reason for the difference in 1385 // implementation other than historical accident. The only 1386 // remaining difference is the unconditional use of the stack 1387 // pointer as the base register. 1388 if (MI.getOpcode() == TargetOpcode::STATEPOINT) { 1389 assert((!MI.isDebugValue() || i == 0) && 1390 "Frame indicies can only appear as the first operand of a " 1391 "DBG_VALUE machine instruction"); 1392 Register Reg; 1393 MachineOperand &Offset = MI.getOperand(i + 1); 1394 StackOffset refOffset = TFI->getFrameIndexReferencePreferSP( 1395 MF, MI.getOperand(i).getIndex(), Reg, /*IgnoreSPUpdates*/ false); 1396 assert(!refOffset.getScalable() && 1397 "Frame offsets with a scalable component are not supported"); 1398 Offset.setImm(Offset.getImm() + refOffset.getFixed() + SPAdj); 1399 MI.getOperand(i).ChangeToRegister(Reg, false /*isDef*/); 1400 continue; 1401 } 1402 1403 // Some instructions (e.g. inline asm instructions) can have 1404 // multiple frame indices and/or cause eliminateFrameIndex 1405 // to insert more than one instruction. We need the register 1406 // scavenger to go through all of these instructions so that 1407 // it can update its register information. We keep the 1408 // iterator at the point before insertion so that we can 1409 // revisit them in full. 1410 bool AtBeginning = (I == BB->begin()); 1411 if (!AtBeginning) --I; 1412 1413 // If this instruction has a FrameIndex operand, we need to 1414 // use that target machine register info object to eliminate 1415 // it. 1416 TRI.eliminateFrameIndex(MI, SPAdj, i, 1417 FrameIndexEliminationScavenging ? RS : nullptr); 1418 1419 // Reset the iterator if we were at the beginning of the BB. 1420 if (AtBeginning) { 1421 I = BB->begin(); 1422 DoIncr = false; 1423 } 1424 1425 DidFinishLoop = false; 1426 break; 1427 } 1428 1429 // If we are looking at a call sequence, we need to keep track of 1430 // the SP adjustment made by each instruction in the sequence. 1431 // This includes both the frame setup/destroy pseudos (handled above), 1432 // as well as other instructions that have side effects w.r.t the SP. 1433 // Note that this must come after eliminateFrameIndex, because 1434 // if I itself referred to a frame index, we shouldn't count its own 1435 // adjustment. 1436 if (DidFinishLoop && InsideCallSequence) 1437 SPAdj += TII.getSPAdjust(MI); 1438 1439 if (DoIncr && I != BB->end()) ++I; 1440 1441 // Update register states. 1442 if (RS && FrameIndexEliminationScavenging && DidFinishLoop) 1443 RS->forward(MI); 1444 } 1445 } 1446