1 //===-- X86FrameLowering.cpp - X86 Frame Information ----------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains the X86 implementation of TargetFrameLowering class.
12 //===----------------------------------------------------------------------===//
14 #include "X86FrameLowering.h"
15 #include "X86InstrBuilder.h"
16 #include "X86InstrInfo.h"
17 #include "X86MachineFunctionInfo.h"
18 #include "X86Subtarget.h"
19 #include "X86TargetMachine.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Analysis/EHPersonalities.h"
22 #include "llvm/CodeGen/MachineFrameInfo.h"
23 #include "llvm/CodeGen/MachineFunction.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineModuleInfo.h"
26 #include "llvm/CodeGen/MachineRegisterInfo.h"
27 #include "llvm/CodeGen/WinEHFuncInfo.h"
28 #include "llvm/IR/DataLayout.h"
29 #include "llvm/IR/Function.h"
30 #include "llvm/MC/MCAsmInfo.h"
31 #include "llvm/MC/MCSymbol.h"
32 #include "llvm/Target/TargetOptions.h"
33 #include "llvm/Support/Debug.h"
38 X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
39 unsigned StackAlignOverride)
40 : TargetFrameLowering(StackGrowsDown, StackAlignOverride,
41 STI.is64Bit() ? -8 : -4),
42 STI(STI), TII(*STI.getInstrInfo()), TRI(STI.getRegisterInfo()) {
43 // Cache a bunch of frame-related predicates for this subtarget.
44 SlotSize = TRI->getSlotSize();
45 Is64Bit = STI.is64Bit();
46 IsLP64 = STI.isTarget64BitLP64();
47 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
48 Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
49 StackPtr = TRI->getStackRegister();
52 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
53 return !MF.getFrameInfo()->hasVarSizedObjects() &&
54 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
57 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
58 /// call frame pseudos can be simplified. Having a FP, as in the default
59 /// implementation, is not sufficient here since we can't always use it.
60 /// Use a more nuanced condition.
62 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
63 return hasReservedCallFrame(MF) ||
64 (hasFP(MF) && !TRI->needsStackRealignment(MF)) ||
65 TRI->hasBasePointer(MF);
68 // needsFrameIndexResolution - Do we need to perform FI resolution for
69 // this function. Normally, this is required only when the function
70 // has any stack objects. However, FI resolution actually has another job,
71 // not apparent from the title - it resolves callframesetup/destroy
72 // that were not simplified earlier.
73 // So, this is required for x86 functions that have push sequences even
74 // when there are no stack objects.
76 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
77 return MF.getFrameInfo()->hasStackObjects() ||
78 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
81 /// hasFP - Return true if the specified function should have a dedicated frame
82 /// pointer register. This is true if the function has variable sized allocas
83 /// or if frame pointer elimination is disabled.
84 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
85 const MachineFrameInfo *MFI = MF.getFrameInfo();
86 const MachineModuleInfo &MMI = MF.getMMI();
88 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
89 TRI->needsStackRealignment(MF) ||
90 MFI->hasVarSizedObjects() ||
91 MFI->isFrameAddressTaken() || MFI->hasOpaqueSPAdjustment() ||
92 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
93 MMI.callsUnwindInit() || MMI.hasEHFunclets() || MMI.callsEHReturn() ||
94 MFI->hasStackMap() || MFI->hasPatchPoint());
97 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
100 return X86::SUB64ri8;
101 return X86::SUB64ri32;
104 return X86::SUB32ri8;
109 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
112 return X86::ADD64ri8;
113 return X86::ADD64ri32;
116 return X86::ADD32ri8;
121 static unsigned getSUBrrOpcode(unsigned isLP64) {
122 return isLP64 ? X86::SUB64rr : X86::SUB32rr;
125 static unsigned getADDrrOpcode(unsigned isLP64) {
126 return isLP64 ? X86::ADD64rr : X86::ADD32rr;
129 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
132 return X86::AND64ri8;
133 return X86::AND64ri32;
136 return X86::AND32ri8;
140 static unsigned getLEArOpcode(unsigned IsLP64) {
141 return IsLP64 ? X86::LEA64r : X86::LEA32r;
144 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
145 /// when it reaches the "return" instruction. We can then pop a stack object
146 /// to this register without worry about clobbering it.
147 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
148 MachineBasicBlock::iterator &MBBI,
149 const X86RegisterInfo *TRI,
151 const MachineFunction *MF = MBB.getParent();
152 const Function *F = MF->getFunction();
153 if (!F || MF->getMMI().callsEHReturn())
156 const TargetRegisterClass &AvailableRegs = *TRI->getGPRsForTailCall(*MF);
158 unsigned Opc = MBBI->getOpcode();
165 case X86::TCRETURNdi:
166 case X86::TCRETURNri:
167 case X86::TCRETURNmi:
168 case X86::TCRETURNdi64:
169 case X86::TCRETURNri64:
170 case X86::TCRETURNmi64:
172 case X86::EH_RETURN64: {
173 SmallSet<uint16_t, 8> Uses;
174 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
175 MachineOperand &MO = MBBI->getOperand(i);
176 if (!MO.isReg() || MO.isDef())
178 unsigned Reg = MO.getReg();
181 for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI)
185 for (auto CS : AvailableRegs)
186 if (!Uses.count(CS) && CS != X86::RIP)
194 static bool isEAXLiveIn(MachineFunction &MF) {
195 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
196 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
197 unsigned Reg = II->first;
199 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
200 Reg == X86::AH || Reg == X86::AL)
207 /// Check if the flags need to be preserved before the terminators.
208 /// This would be the case, if the eflags is live-in of the region
209 /// composed by the terminators or live-out of that region, without
210 /// being defined by a terminator.
212 flagsNeedToBePreservedBeforeTheTerminators(const MachineBasicBlock &MBB) {
213 for (const MachineInstr &MI : MBB.terminators()) {
214 bool BreakNext = false;
215 for (const MachineOperand &MO : MI.operands()) {
218 unsigned Reg = MO.getReg();
219 if (Reg != X86::EFLAGS)
222 // This terminator needs an eflags that is not defined
223 // by a previous another terminator:
224 // EFLAGS is live-in of the region composed by the terminators.
227 // This terminator defines the eflags, i.e., we don't need to preserve it.
228 // However, we still need to check this specific terminator does not
229 // read a live-in value.
232 // We found a definition of the eflags, no need to preserve them.
237 // None of the terminators use or define the eflags.
238 // Check if they are live-out, that would imply we need to preserve them.
239 for (const MachineBasicBlock *Succ : MBB.successors())
240 if (Succ->isLiveIn(X86::EFLAGS))
246 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
247 /// stack pointer by a constant value.
248 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
249 MachineBasicBlock::iterator &MBBI,
250 int64_t NumBytes, bool InEpilogue) const {
251 bool isSub = NumBytes < 0;
252 uint64_t Offset = isSub ? -NumBytes : NumBytes;
254 uint64_t Chunk = (1LL << 31) - 1;
255 DebugLoc DL = MBB.findDebugLoc(MBBI);
258 if (Offset > Chunk) {
259 // Rather than emit a long series of instructions for large offsets,
260 // load the offset into a register and do one sub/add
263 if (isSub && !isEAXLiveIn(*MBB.getParent()))
264 Reg = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
266 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
269 unsigned Opc = Is64Bit ? X86::MOV64ri : X86::MOV32ri;
270 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
273 ? getSUBrrOpcode(Is64Bit)
274 : getADDrrOpcode(Is64Bit);
275 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
278 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
284 uint64_t ThisVal = std::min(Offset, Chunk);
285 if (ThisVal == (Is64Bit ? 8 : 4)) {
286 // Use push / pop instead.
288 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
289 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64Bit);
292 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
293 : (Is64Bit ? X86::POP64r : X86::POP32r);
294 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
295 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
297 MI->setFlag(MachineInstr::FrameSetup);
299 MI->setFlag(MachineInstr::FrameDestroy);
305 MachineInstrBuilder MI = BuildStackAdjustment(
306 MBB, MBBI, DL, isSub ? -ThisVal : ThisVal, InEpilogue);
308 MI.setMIFlag(MachineInstr::FrameSetup);
310 MI.setMIFlag(MachineInstr::FrameDestroy);
316 MachineInstrBuilder X86FrameLowering::BuildStackAdjustment(
317 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI, DebugLoc DL,
318 int64_t Offset, bool InEpilogue) const {
319 assert(Offset != 0 && "zero offset stack adjustment requested");
321 // On Atom, using LEA to adjust SP is preferred, but using it in the epilogue
325 // Check if inserting the prologue at the beginning
326 // of MBB would require to use LEA operations.
327 // We need to use LEA operations if EFLAGS is live in, because
328 // it means an instruction will read it before it gets defined.
329 UseLEA = STI.useLeaForSP() || MBB.isLiveIn(X86::EFLAGS);
331 // If we can use LEA for SP but we shouldn't, check that none
332 // of the terminators uses the eflags. Otherwise we will insert
333 // a ADD that will redefine the eflags and break the condition.
334 // Alternatively, we could move the ADD, but this may not be possible
335 // and is an optimization anyway.
336 UseLEA = canUseLEAForSPInEpilogue(*MBB.getParent());
337 if (UseLEA && !STI.useLeaForSP())
338 UseLEA = flagsNeedToBePreservedBeforeTheTerminators(MBB);
339 // If that assert breaks, that means we do not do the right thing
340 // in canUseAsEpilogue.
341 assert((UseLEA || !flagsNeedToBePreservedBeforeTheTerminators(MBB)) &&
342 "We shouldn't have allowed this insertion point");
345 MachineInstrBuilder MI;
347 MI = addRegOffset(BuildMI(MBB, MBBI, DL,
348 TII.get(getLEArOpcode(Uses64BitFramePtr)),
350 StackPtr, false, Offset);
352 bool IsSub = Offset < 0;
353 uint64_t AbsOffset = IsSub ? -Offset : Offset;
354 unsigned Opc = IsSub ? getSUBriOpcode(Uses64BitFramePtr, AbsOffset)
355 : getADDriOpcode(Uses64BitFramePtr, AbsOffset);
356 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
359 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
364 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
365 MachineBasicBlock::iterator &MBBI,
366 bool doMergeWithPrevious) const {
367 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
368 (!doMergeWithPrevious && MBBI == MBB.end()))
371 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
372 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
374 unsigned Opc = PI->getOpcode();
377 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
378 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
379 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
380 PI->getOperand(0).getReg() == StackPtr){
381 Offset += PI->getOperand(2).getImm();
383 if (!doMergeWithPrevious) MBBI = NI;
384 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
385 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
386 PI->getOperand(0).getReg() == StackPtr) {
387 Offset -= PI->getOperand(2).getImm();
389 if (!doMergeWithPrevious) MBBI = NI;
395 void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
396 MachineBasicBlock::iterator MBBI, DebugLoc DL,
397 MCCFIInstruction CFIInst) const {
398 MachineFunction &MF = *MBB.getParent();
399 unsigned CFIIndex = MF.getMMI().addFrameInst(CFIInst);
400 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
401 .addCFIIndex(CFIIndex);
405 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
406 MachineBasicBlock::iterator MBBI,
408 MachineFunction &MF = *MBB.getParent();
409 MachineFrameInfo *MFI = MF.getFrameInfo();
410 MachineModuleInfo &MMI = MF.getMMI();
411 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
413 // Add callee saved registers to move list.
414 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
415 if (CSI.empty()) return;
417 // Calculate offsets.
418 for (std::vector<CalleeSavedInfo>::const_iterator
419 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
420 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
421 unsigned Reg = I->getReg();
423 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
424 BuildCFI(MBB, MBBI, DL,
425 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
429 /// usesTheStack - This function checks if any of the users of EFLAGS
430 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
431 /// to use the stack, and if we don't adjust the stack we clobber the first
433 /// See X86InstrInfo::copyPhysReg.
434 static bool usesTheStack(const MachineFunction &MF) {
435 const MachineRegisterInfo &MRI = MF.getRegInfo();
437 for (MachineRegisterInfo::reg_instr_iterator
438 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
446 MachineInstr *X86FrameLowering::emitStackProbe(MachineFunction &MF,
447 MachineBasicBlock &MBB,
448 MachineBasicBlock::iterator MBBI,
450 bool InProlog) const {
451 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
452 if (STI.isTargetWindowsCoreCLR()) {
454 return emitStackProbeInlineStub(MF, MBB, MBBI, DL, true);
456 return emitStackProbeInline(MF, MBB, MBBI, DL, false);
459 return emitStackProbeCall(MF, MBB, MBBI, DL, InProlog);
463 void X86FrameLowering::inlineStackProbe(MachineFunction &MF,
464 MachineBasicBlock &PrologMBB) const {
465 const StringRef ChkStkStubSymbol = "__chkstk_stub";
466 MachineInstr *ChkStkStub = nullptr;
468 for (MachineInstr &MI : PrologMBB) {
469 if (MI.isCall() && MI.getOperand(0).isSymbol() &&
470 ChkStkStubSymbol == MI.getOperand(0).getSymbolName()) {
476 if (ChkStkStub != nullptr) {
477 MachineBasicBlock::iterator MBBI = std::next(ChkStkStub->getIterator());
478 assert(std::prev(MBBI).operator==(ChkStkStub) &&
479 "MBBI expected after __chkstk_stub.");
480 DebugLoc DL = PrologMBB.findDebugLoc(MBBI);
481 emitStackProbeInline(MF, PrologMBB, MBBI, DL, true);
482 ChkStkStub->eraseFromParent();
486 MachineInstr *X86FrameLowering::emitStackProbeInline(
487 MachineFunction &MF, MachineBasicBlock &MBB,
488 MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
489 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
490 assert(STI.is64Bit() && "different expansion needed for 32 bit");
491 assert(STI.isTargetWindowsCoreCLR() && "custom expansion expects CoreCLR");
492 const TargetInstrInfo &TII = *STI.getInstrInfo();
493 const BasicBlock *LLVM_BB = MBB.getBasicBlock();
495 // RAX contains the number of bytes of desired stack adjustment.
496 // The handling here assumes this value has already been updated so as to
497 // maintain stack alignment.
499 // We need to exit with RSP modified by this amount and execute suitable
500 // page touches to notify the OS that we're growing the stack responsibly.
501 // All stack probing must be done without modifying RSP.
507 // Flags, TestReg = CopyReg - SizeReg
508 // FinalReg = !Flags.Ovf ? TestReg : ZeroReg
509 // LimitReg = gs magic thread env access
510 // if FinalReg >= LimitReg goto ContinueMBB
512 // RoundReg = page address of FinalReg
514 // LoopReg = PHI(LimitReg,ProbeReg)
515 // ProbeReg = LoopReg - PageSize
517 // if (ProbeReg > RoundReg) goto LoopMBB
520 // [rest of original MBB]
522 // Set up the new basic blocks
523 MachineBasicBlock *RoundMBB = MF.CreateMachineBasicBlock(LLVM_BB);
524 MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
525 MachineBasicBlock *ContinueMBB = MF.CreateMachineBasicBlock(LLVM_BB);
527 MachineFunction::iterator MBBIter = std::next(MBB.getIterator());
528 MF.insert(MBBIter, RoundMBB);
529 MF.insert(MBBIter, LoopMBB);
530 MF.insert(MBBIter, ContinueMBB);
532 // Split MBB and move the tail portion down to ContinueMBB.
533 MachineBasicBlock::iterator BeforeMBBI = std::prev(MBBI);
534 ContinueMBB->splice(ContinueMBB->begin(), &MBB, MBBI, MBB.end());
535 ContinueMBB->transferSuccessorsAndUpdatePHIs(&MBB);
537 // Some useful constants
538 const int64_t ThreadEnvironmentStackLimit = 0x10;
539 const int64_t PageSize = 0x1000;
540 const int64_t PageMask = ~(PageSize - 1);
542 // Registers we need. For the normal case we use virtual
543 // registers. For the prolog expansion we use RAX, RCX and RDX.
544 MachineRegisterInfo &MRI = MF.getRegInfo();
545 const TargetRegisterClass *RegClass = &X86::GR64RegClass;
546 const unsigned SizeReg = InProlog ? (unsigned)X86::RAX
547 : MRI.createVirtualRegister(RegClass),
548 ZeroReg = InProlog ? (unsigned)X86::RCX
549 : MRI.createVirtualRegister(RegClass),
550 CopyReg = InProlog ? (unsigned)X86::RDX
551 : MRI.createVirtualRegister(RegClass),
552 TestReg = InProlog ? (unsigned)X86::RDX
553 : MRI.createVirtualRegister(RegClass),
554 FinalReg = InProlog ? (unsigned)X86::RDX
555 : MRI.createVirtualRegister(RegClass),
556 RoundedReg = InProlog ? (unsigned)X86::RDX
557 : MRI.createVirtualRegister(RegClass),
558 LimitReg = InProlog ? (unsigned)X86::RCX
559 : MRI.createVirtualRegister(RegClass),
560 JoinReg = InProlog ? (unsigned)X86::RCX
561 : MRI.createVirtualRegister(RegClass),
562 ProbeReg = InProlog ? (unsigned)X86::RCX
563 : MRI.createVirtualRegister(RegClass);
565 // SP-relative offsets where we can save RCX and RDX.
566 int64_t RCXShadowSlot = 0;
567 int64_t RDXShadowSlot = 0;
569 // If inlining in the prolog, save RCX and RDX.
570 // Future optimization: don't save or restore if not live in.
572 // Compute the offsets. We need to account for things already
573 // pushed onto the stack at this point: return address, frame
574 // pointer (if used), and callee saves.
575 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
576 const int64_t CalleeSaveSize = X86FI->getCalleeSavedFrameSize();
577 const bool HasFP = hasFP(MF);
578 RCXShadowSlot = 8 + CalleeSaveSize + (HasFP ? 8 : 0);
579 RDXShadowSlot = RCXShadowSlot + 8;
581 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
584 addRegOffset(BuildMI(&MBB, DL, TII.get(X86::MOV64mr)), X86::RSP, false,
588 // Not in the prolog. Copy RAX to a virtual reg.
589 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), SizeReg).addReg(X86::RAX);
592 // Add code to MBB to check for overflow and set the new target stack pointer
594 BuildMI(&MBB, DL, TII.get(X86::XOR64rr), ZeroReg)
595 .addReg(ZeroReg, RegState::Undef)
596 .addReg(ZeroReg, RegState::Undef);
597 BuildMI(&MBB, DL, TII.get(X86::MOV64rr), CopyReg).addReg(X86::RSP);
598 BuildMI(&MBB, DL, TII.get(X86::SUB64rr), TestReg)
601 BuildMI(&MBB, DL, TII.get(X86::CMOVB64rr), FinalReg)
605 // FinalReg now holds final stack pointer value, or zero if
606 // allocation would overflow. Compare against the current stack
607 // limit from the thread environment block. Note this limit is the
608 // lowest touched page on the stack, not the point at which the OS
609 // will cause an overflow exception, so this is just an optimization
610 // to avoid unnecessarily touching pages that are below the current
611 // SP but already commited to the stack by the OS.
612 BuildMI(&MBB, DL, TII.get(X86::MOV64rm), LimitReg)
616 .addImm(ThreadEnvironmentStackLimit)
618 BuildMI(&MBB, DL, TII.get(X86::CMP64rr)).addReg(FinalReg).addReg(LimitReg);
619 // Jump if the desired stack pointer is at or above the stack limit.
620 BuildMI(&MBB, DL, TII.get(X86::JAE_1)).addMBB(ContinueMBB);
622 // Add code to roundMBB to round the final stack pointer to a page boundary.
623 BuildMI(RoundMBB, DL, TII.get(X86::AND64ri32), RoundedReg)
626 BuildMI(RoundMBB, DL, TII.get(X86::JMP_1)).addMBB(LoopMBB);
628 // LimitReg now holds the current stack limit, RoundedReg page-rounded
629 // final RSP value. Add code to loopMBB to decrement LimitReg page-by-page
630 // and probe until we reach RoundedReg.
632 BuildMI(LoopMBB, DL, TII.get(X86::PHI), JoinReg)
639 addRegOffset(BuildMI(LoopMBB, DL, TII.get(X86::LEA64r), ProbeReg), JoinReg,
642 // Probe by storing a byte onto the stack.
643 BuildMI(LoopMBB, DL, TII.get(X86::MOV8mi))
650 BuildMI(LoopMBB, DL, TII.get(X86::CMP64rr))
653 BuildMI(LoopMBB, DL, TII.get(X86::JNE_1)).addMBB(LoopMBB);
655 MachineBasicBlock::iterator ContinueMBBI = ContinueMBB->getFirstNonPHI();
657 // If in prolog, restore RDX and RCX.
659 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::MOV64rm),
661 X86::RSP, false, RCXShadowSlot);
662 addRegOffset(BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::MOV64rm),
664 X86::RSP, false, RDXShadowSlot);
667 // Now that the probing is done, add code to continueMBB to update
668 // the stack pointer for real.
669 BuildMI(*ContinueMBB, ContinueMBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
673 // Add the control flow edges we need.
674 MBB.addSuccessor(ContinueMBB);
675 MBB.addSuccessor(RoundMBB);
676 RoundMBB->addSuccessor(LoopMBB);
677 LoopMBB->addSuccessor(ContinueMBB);
678 LoopMBB->addSuccessor(LoopMBB);
680 // Mark all the instructions added to the prolog as frame setup.
682 for (++BeforeMBBI; BeforeMBBI != MBB.end(); ++BeforeMBBI) {
683 BeforeMBBI->setFlag(MachineInstr::FrameSetup);
685 for (MachineInstr &MI : *RoundMBB) {
686 MI.setFlag(MachineInstr::FrameSetup);
688 for (MachineInstr &MI : *LoopMBB) {
689 MI.setFlag(MachineInstr::FrameSetup);
691 for (MachineBasicBlock::iterator CMBBI = ContinueMBB->begin();
692 CMBBI != ContinueMBBI; ++CMBBI) {
693 CMBBI->setFlag(MachineInstr::FrameSetup);
697 // Possible TODO: physreg liveness for InProlog case.
702 MachineInstr *X86FrameLowering::emitStackProbeCall(
703 MachineFunction &MF, MachineBasicBlock &MBB,
704 MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
705 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
709 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
711 CallOp = X86::CALLpcrel32;
715 if (STI.isTargetCygMing()) {
716 Symbol = "___chkstk_ms";
720 } else if (STI.isTargetCygMing())
725 MachineInstrBuilder CI;
726 MachineBasicBlock::iterator ExpansionMBBI = std::prev(MBBI);
728 // All current stack probes take AX and SP as input, clobber flags, and
729 // preserve all registers. x86_64 probes leave RSP unmodified.
730 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
731 // For the large code model, we have to call through a register. Use R11,
732 // as it is scratch in all supported calling conventions.
733 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
734 .addExternalSymbol(Symbol);
735 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
737 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
740 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
741 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
742 CI.addReg(AX, RegState::Implicit)
743 .addReg(SP, RegState::Implicit)
744 .addReg(AX, RegState::Define | RegState::Implicit)
745 .addReg(SP, RegState::Define | RegState::Implicit)
746 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
749 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
750 // themselves. It also does not clobber %rax so we can reuse it when
752 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
758 // Apply the frame setup flag to all inserted instrs.
759 for (++ExpansionMBBI; ExpansionMBBI != MBBI; ++ExpansionMBBI)
760 ExpansionMBBI->setFlag(MachineInstr::FrameSetup);
766 MachineInstr *X86FrameLowering::emitStackProbeInlineStub(
767 MachineFunction &MF, MachineBasicBlock &MBB,
768 MachineBasicBlock::iterator MBBI, DebugLoc DL, bool InProlog) const {
770 assert(InProlog && "ChkStkStub called outside prolog!");
772 BuildMI(MBB, MBBI, DL, TII.get(X86::CALLpcrel32))
773 .addExternalSymbol("__chkstk_stub");
778 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
779 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
780 // and might require smaller successive adjustments.
781 const uint64_t Win64MaxSEHOffset = 128;
782 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
783 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
784 return SEHFrameOffset & -16;
787 // If we're forcing a stack realignment we can't rely on just the frame
788 // info, we need to know the ABI stack alignment as well in case we
789 // have a call out. Otherwise just make sure we have some alignment - we'll
790 // go with the minimum SlotSize.
791 uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
792 const MachineFrameInfo *MFI = MF.getFrameInfo();
793 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
794 unsigned StackAlign = getStackAlignment();
795 if (MF.getFunction()->hasFnAttribute("stackrealign")) {
797 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
798 else if (MaxAlign < SlotSize)
804 void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
805 MachineBasicBlock::iterator MBBI,
806 DebugLoc DL, unsigned Reg,
807 uint64_t MaxAlign) const {
808 uint64_t Val = -MaxAlign;
809 unsigned AndOp = getANDriOpcode(Uses64BitFramePtr, Val);
810 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(AndOp), Reg)
813 .setMIFlag(MachineInstr::FrameSetup);
815 // The EFLAGS implicit def is dead.
816 MI->getOperand(3).setIsDead();
819 /// emitPrologue - Push callee-saved registers onto the stack, which
820 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
821 /// space for local variables. Also emit labels used by the exception handler to
822 /// generate the exception handling frames.
825 Here's a gist of what gets emitted:
827 ; Establish frame pointer, if needed
830 .cfi_def_cfa_offset 16
831 .cfi_offset %rbp, -16
834 .cfi_def_cfa_register %rbp
836 ; Spill general-purpose registers
837 [for all callee-saved GPRs]
840 .cfi_def_cfa_offset (offset from RETADDR)
843 ; If the required stack alignment > default stack alignment
844 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
845 ; of unknown size in the stack frame.
846 [if stack needs re-alignment]
849 ; Allocate space for locals
850 [if target is Windows and allocated space > 4096 bytes]
851 ; Windows needs special care for allocations larger
854 call ___chkstk_ms/___chkstk
860 .seh_stackalloc (size of XMM spill slots)
861 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
866 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
867 ; they may get spilled on any platform, if the current function
868 ; calls @llvm.eh.unwind.init
870 [for all callee-saved XMM registers]
871 movaps %<xmm reg>, -MMM(%rbp)
872 [for all callee-saved XMM registers]
873 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
874 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
876 [for all callee-saved XMM registers]
877 movaps %<xmm reg>, KKK(%rsp)
878 [for all callee-saved XMM registers]
879 .seh_savexmm %<xmm reg>, KKK
883 [if needs base pointer]
885 [if needs to restore base pointer]
890 [for all callee-saved registers]
891 .cfi_offset %<reg>, (offset from %rbp)
893 .cfi_def_cfa_offset (offset from RETADDR)
894 [for all callee-saved registers]
895 .cfi_offset %<reg>, (offset from %rsp)
898 - .seh directives are emitted only for Windows 64 ABI
899 - .cfi directives are emitted for all other ABIs
900 - for 32-bit code, substitute %e?? registers for %r??
903 void X86FrameLowering::emitPrologue(MachineFunction &MF,
904 MachineBasicBlock &MBB) const {
905 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
906 "MF used frame lowering for wrong subtarget");
907 MachineBasicBlock::iterator MBBI = MBB.begin();
908 MachineFrameInfo *MFI = MF.getFrameInfo();
909 const Function *Fn = MF.getFunction();
910 MachineModuleInfo &MMI = MF.getMMI();
911 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
912 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
913 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
914 bool IsFunclet = MBB.isEHFuncletEntry();
915 bool FnHasClrFunclet =
916 MMI.hasEHFunclets() &&
917 classifyEHPersonality(Fn->getPersonalityFn()) == EHPersonality::CoreCLR;
918 bool IsClrFunclet = IsFunclet && FnHasClrFunclet;
919 bool HasFP = hasFP(MF);
920 bool IsWin64CC = STI.isCallingConvWin64(Fn->getCallingConv());
921 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
922 bool NeedsWinCFI = IsWin64Prologue && Fn->needsUnwindTableEntry();
924 !IsWin64Prologue && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
925 unsigned FramePtr = TRI->getFrameRegister(MF);
926 const unsigned MachineFramePtr =
927 STI.isTarget64BitILP32()
928 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
930 unsigned BasePtr = TRI->getBaseRegister();
932 // Debug location must be unknown since the first debug location is used
933 // to determine the end of the prologue.
936 // Add RETADDR move area to callee saved frame size.
937 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
938 if (TailCallReturnAddrDelta && IsWin64Prologue)
939 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
941 if (TailCallReturnAddrDelta < 0)
942 X86FI->setCalleeSavedFrameSize(
943 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
945 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
947 // The default stack probe size is 4096 if the function has no stackprobesize
949 unsigned StackProbeSize = 4096;
950 if (Fn->hasFnAttribute("stack-probe-size"))
951 Fn->getFnAttribute("stack-probe-size")
953 .getAsInteger(0, StackProbeSize);
955 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
956 // function, and use up to 128 bytes of stack space, don't have a frame
957 // pointer, calls, or dynamic alloca then we do not need to adjust the
958 // stack pointer (we fit in the Red Zone). We also check that we don't
959 // push and pop from the stack.
960 if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
961 !TRI->needsStackRealignment(MF) &&
962 !MFI->hasVarSizedObjects() && // No dynamic alloca.
963 !MFI->adjustsStack() && // No calls.
964 !IsWin64CC && // Win64 has no Red Zone
965 !usesTheStack(MF) && // Don't push and pop.
966 !MF.shouldSplitStack()) { // Regular stack
967 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
968 if (HasFP) MinSize += SlotSize;
969 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
970 MFI->setStackSize(StackSize);
973 // Insert stack pointer adjustment for later moving of return addr. Only
974 // applies to tail call optimized functions where the callee argument stack
975 // size is bigger than the callers.
976 if (TailCallReturnAddrDelta < 0) {
977 BuildStackAdjustment(MBB, MBBI, DL, TailCallReturnAddrDelta,
978 /*InEpilogue=*/false)
979 .setMIFlag(MachineInstr::FrameSetup);
982 // Mapping for machine moves:
984 // DST: VirtualFP AND
985 // SRC: VirtualFP => DW_CFA_def_cfa_offset
986 // ELSE => DW_CFA_def_cfa
988 // SRC: VirtualFP AND
989 // DST: Register => DW_CFA_def_cfa_register
992 // OFFSET < 0 => DW_CFA_offset_extended_sf
993 // REG < 64 => DW_CFA_offset + Reg
994 // ELSE => DW_CFA_offset_extended
996 uint64_t NumBytes = 0;
997 int stackGrowth = -SlotSize;
999 // Find the funclet establisher parameter
1000 unsigned Establisher = X86::NoRegister;
1002 Establisher = Uses64BitFramePtr ? X86::RCX : X86::ECX;
1004 Establisher = Uses64BitFramePtr ? X86::RDX : X86::EDX;
1006 if (IsWin64Prologue && IsFunclet & !IsClrFunclet) {
1007 // Immediately spill establisher into the home slot.
1008 // The runtime cares about this.
1009 // MOV64mr %rdx, 16(%rsp)
1010 unsigned MOVmr = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1011 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(MOVmr)), StackPtr, true, 16)
1012 .addReg(Establisher)
1013 .setMIFlag(MachineInstr::FrameSetup);
1014 MBB.addLiveIn(Establisher);
1018 // Calculate required stack adjustment.
1019 uint64_t FrameSize = StackSize - SlotSize;
1020 // If required, include space for extra hidden slot for stashing base pointer.
1021 if (X86FI->getRestoreBasePointer())
1022 FrameSize += SlotSize;
1024 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
1026 // Callee-saved registers are pushed on stack before the stack is realigned.
1027 if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1028 NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
1030 // Get the offset of the stack slot for the EBP register, which is
1031 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
1032 // Update the frame offset adjustment.
1034 MFI->setOffsetAdjustment(-NumBytes);
1036 assert(MFI->getOffsetAdjustment() == -(int)NumBytes &&
1037 "should calculate same local variable offset for funclets");
1039 // Save EBP/RBP into the appropriate stack slot.
1040 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
1041 .addReg(MachineFramePtr, RegState::Kill)
1042 .setMIFlag(MachineInstr::FrameSetup);
1044 if (NeedsDwarfCFI) {
1045 // Mark the place where EBP/RBP was saved.
1046 // Define the current CFA rule to use the provided offset.
1048 BuildCFI(MBB, MBBI, DL,
1049 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
1051 // Change the rule for the FramePtr to be an "offset" rule.
1052 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1053 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset(
1054 nullptr, DwarfFramePtr, 2 * stackGrowth));
1058 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
1060 .setMIFlag(MachineInstr::FrameSetup);
1063 if (!IsWin64Prologue && !IsFunclet) {
1064 // Update EBP with the new base value.
1065 BuildMI(MBB, MBBI, DL,
1066 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
1069 .setMIFlag(MachineInstr::FrameSetup);
1071 if (NeedsDwarfCFI) {
1072 // Mark effective beginning of when frame pointer becomes valid.
1073 // Define the current CFA to use the EBP/RBP register.
1074 unsigned DwarfFramePtr = TRI->getDwarfRegNum(MachineFramePtr, true);
1075 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaRegister(
1076 nullptr, DwarfFramePtr));
1080 // Mark the FramePtr as live-in in every block. Don't do this again for
1081 // funclet prologues.
1083 for (MachineBasicBlock &EveryMBB : MF)
1084 EveryMBB.addLiveIn(MachineFramePtr);
1087 assert(!IsFunclet && "funclets without FPs not yet implemented");
1088 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
1091 // For EH funclets, only allocate enough space for outgoing calls. Save the
1092 // NumBytes value that we would've used for the parent frame.
1093 unsigned ParentFrameNumBytes = NumBytes;
1095 NumBytes = getWinEHFuncletFrameSize(MF);
1097 // Skip the callee-saved push instructions.
1098 bool PushedRegs = false;
1099 int StackOffset = 2 * stackGrowth;
1101 while (MBBI != MBB.end() &&
1102 MBBI->getFlag(MachineInstr::FrameSetup) &&
1103 (MBBI->getOpcode() == X86::PUSH32r ||
1104 MBBI->getOpcode() == X86::PUSH64r)) {
1106 unsigned Reg = MBBI->getOperand(0).getReg();
1109 if (!HasFP && NeedsDwarfCFI) {
1110 // Mark callee-saved push instruction.
1111 // Define the current CFA rule to use the provided offset.
1113 BuildCFI(MBB, MBBI, DL,
1114 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
1115 StackOffset += stackGrowth;
1119 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
1120 MachineInstr::FrameSetup);
1124 // Realign stack after we pushed callee-saved registers (so that we'll be
1125 // able to calculate their offsets from the frame pointer).
1126 // Don't do this for Win64, it needs to realign the stack after the prologue.
1127 if (!IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF)) {
1128 assert(HasFP && "There should be a frame pointer if stack is realigned.");
1129 BuildStackAlignAND(MBB, MBBI, DL, StackPtr, MaxAlign);
1132 // If there is an SUB32ri of ESP immediately before this instruction, merge
1133 // the two. This can be the case when tail call elimination is enabled and
1134 // the callee has more arguments then the caller.
1135 NumBytes -= mergeSPUpdates(MBB, MBBI, true);
1137 // Adjust stack pointer: ESP -= numbytes.
1139 // Windows and cygwin/mingw require a prologue helper routine when allocating
1140 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
1141 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
1142 // stack and adjust the stack pointer in one go. The 64-bit version of
1143 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
1144 // responsible for adjusting the stack pointer. Touching the stack at 4K
1145 // increments is necessary to ensure that the guard pages used by the OS
1146 // virtual memory manager are allocated in correct sequence.
1147 uint64_t AlignedNumBytes = NumBytes;
1148 if (IsWin64Prologue && !IsFunclet && TRI->needsStackRealignment(MF))
1149 AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
1150 if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
1151 // Check whether EAX is livein for this function.
1152 bool isEAXAlive = isEAXLiveIn(MF);
1155 // Sanity check that EAX is not livein for this function.
1156 // It should not be, so throw an assert.
1157 assert(!Is64Bit && "EAX is livein in x64 case!");
1160 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
1161 .addReg(X86::EAX, RegState::Kill)
1162 .setMIFlag(MachineInstr::FrameSetup);
1166 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
1167 // Function prologue is responsible for adjusting the stack pointer.
1168 if (isUInt<32>(NumBytes)) {
1169 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1171 .setMIFlag(MachineInstr::FrameSetup);
1172 } else if (isInt<32>(NumBytes)) {
1173 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
1175 .setMIFlag(MachineInstr::FrameSetup);
1177 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
1179 .setMIFlag(MachineInstr::FrameSetup);
1182 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
1183 // We'll also use 4 already allocated bytes for EAX.
1184 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
1185 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
1186 .setMIFlag(MachineInstr::FrameSetup);
1189 // Call __chkstk, __chkstk_ms, or __alloca.
1190 emitStackProbe(MF, MBB, MBBI, DL, true);
1195 addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm), X86::EAX),
1196 StackPtr, false, NumBytes - 4);
1197 MI->setFlag(MachineInstr::FrameSetup);
1198 MBB.insert(MBBI, MI);
1200 } else if (NumBytes) {
1201 emitSPUpdate(MBB, MBBI, -(int64_t)NumBytes, /*InEpilogue=*/false);
1204 if (NeedsWinCFI && NumBytes)
1205 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
1207 .setMIFlag(MachineInstr::FrameSetup);
1209 int SEHFrameOffset = 0;
1210 unsigned SPOrEstablisher;
1213 // The establisher parameter passed to a CLR funclet is actually a pointer
1214 // to the (mostly empty) frame of its nearest enclosing funclet; we have
1215 // to find the root function establisher frame by loading the PSPSym from
1216 // the intermediate frame.
1217 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1218 MachinePointerInfo NoInfo;
1219 MBB.addLiveIn(Establisher);
1220 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rm), Establisher),
1221 Establisher, false, PSPSlotOffset)
1222 .addMemOperand(MF.getMachineMemOperand(
1223 NoInfo, MachineMemOperand::MOLoad, SlotSize, SlotSize));
1225 // Save the root establisher back into the current funclet's (mostly
1226 // empty) frame, in case a sub-funclet or the GC needs it.
1227 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr,
1228 false, PSPSlotOffset)
1229 .addReg(Establisher)
1231 MF.getMachineMemOperand(NoInfo, MachineMemOperand::MOStore |
1232 MachineMemOperand::MOVolatile,
1233 SlotSize, SlotSize));
1235 SPOrEstablisher = Establisher;
1237 SPOrEstablisher = StackPtr;
1240 if (IsWin64Prologue && HasFP) {
1241 // Set RBP to a small fixed offset from RSP. In the funclet case, we base
1242 // this calculation on the incoming establisher, which holds the value of
1243 // RSP from the parent frame at the end of the prologue.
1244 SEHFrameOffset = calculateSetFPREG(ParentFrameNumBytes);
1246 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
1247 SPOrEstablisher, false, SEHFrameOffset);
1249 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr)
1250 .addReg(SPOrEstablisher);
1252 // If this is not a funclet, emit the CFI describing our frame pointer.
1253 if (NeedsWinCFI && !IsFunclet)
1254 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
1256 .addImm(SEHFrameOffset)
1257 .setMIFlag(MachineInstr::FrameSetup);
1258 } else if (IsFunclet && STI.is32Bit()) {
1259 // Reset EBP / ESI to something good for funclets.
1260 MBBI = restoreWin32EHStackPointers(MBB, MBBI, DL);
1261 // If we're a catch funclet, we can be returned to via catchret. Save ESP
1262 // into the registration node so that the runtime will restore it for us.
1263 if (!MBB.isCleanupFuncletEntry()) {
1264 assert(classifyEHPersonality(Fn->getPersonalityFn()) ==
1265 EHPersonality::MSVC_CXX);
1267 int FI = MF.getWinEHFuncInfo()->EHRegNodeFrameIndex;
1268 int64_t EHRegOffset = getFrameIndexReference(MF, FI, FrameReg);
1269 // ESP is the first field, so no extra displacement is needed.
1270 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32mr)), FrameReg,
1276 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
1277 const MachineInstr *FrameInstr = &*MBBI;
1282 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
1283 if (X86::FR64RegClass.contains(Reg)) {
1284 unsigned IgnoredFrameReg;
1285 int Offset = getFrameIndexReference(MF, FI, IgnoredFrameReg);
1286 Offset += SEHFrameOffset;
1288 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
1291 .setMIFlag(MachineInstr::FrameSetup);
1298 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
1299 .setMIFlag(MachineInstr::FrameSetup);
1301 if (FnHasClrFunclet && !IsFunclet) {
1302 // Save the so-called Initial-SP (i.e. the value of the stack pointer
1303 // immediately after the prolog) into the PSPSlot so that funclets
1304 // and the GC can recover it.
1305 unsigned PSPSlotOffset = getPSPSlotOffsetFromSP(MF);
1306 auto PSPInfo = MachinePointerInfo::getFixedStack(
1307 MF, MF.getWinEHFuncInfo()->PSPSymFrameIdx);
1308 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mr)), StackPtr, false,
1311 .addMemOperand(MF.getMachineMemOperand(
1312 PSPInfo, MachineMemOperand::MOStore | MachineMemOperand::MOVolatile,
1313 SlotSize, SlotSize));
1316 // Realign stack after we spilled callee-saved registers (so that we'll be
1317 // able to calculate their offsets from the frame pointer).
1318 // Win64 requires aligning the stack after the prologue.
1319 if (IsWin64Prologue && TRI->needsStackRealignment(MF)) {
1320 assert(HasFP && "There should be a frame pointer if stack is realigned.");
1321 BuildStackAlignAND(MBB, MBBI, DL, SPOrEstablisher, MaxAlign);
1324 // We already dealt with stack realignment and funclets above.
1325 if (IsFunclet && STI.is32Bit())
1328 // If we need a base pointer, set it up here. It's whatever the value
1329 // of the stack pointer is at this point. Any variable size objects
1330 // will be allocated after this, so we can still use the base pointer
1331 // to reference locals.
1332 if (TRI->hasBasePointer(MF)) {
1333 // Update the base pointer with the current stack pointer.
1334 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
1335 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
1336 .addReg(SPOrEstablisher)
1337 .setMIFlag(MachineInstr::FrameSetup);
1338 if (X86FI->getRestoreBasePointer()) {
1339 // Stash value of base pointer. Saving RSP instead of EBP shortens
1340 // dependence chain. Used by SjLj EH.
1341 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1342 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
1343 FramePtr, true, X86FI->getRestoreBasePointerOffset())
1344 .addReg(SPOrEstablisher)
1345 .setMIFlag(MachineInstr::FrameSetup);
1348 if (X86FI->getHasSEHFramePtrSave() && !IsFunclet) {
1349 // Stash the value of the frame pointer relative to the base pointer for
1350 // Win32 EH. This supports Win32 EH, which does the inverse of the above:
1351 // it recovers the frame pointer from the base pointer rather than the
1352 // other way around.
1353 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
1356 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
1357 assert(UsedReg == BasePtr);
1358 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)), UsedReg, true, Offset)
1360 .setMIFlag(MachineInstr::FrameSetup);
1364 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
1365 // Mark end of stack pointer adjustment.
1366 if (!HasFP && NumBytes) {
1367 // Define the current CFA rule to use the provided offset.
1369 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
1370 nullptr, -StackSize + stackGrowth));
1373 // Emit DWARF info specifying the offsets of the callee-saved registers.
1375 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
1379 bool X86FrameLowering::canUseLEAForSPInEpilogue(
1380 const MachineFunction &MF) const {
1381 // We can't use LEA instructions for adjusting the stack pointer if this is a
1382 // leaf function in the Win64 ABI. Only ADD instructions may be used to
1383 // deallocate the stack.
1384 // This means that we can use LEA for SP in two situations:
1385 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
1386 // 2. We *have* a frame pointer which means we are permitted to use LEA.
1387 return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
1390 static bool isFuncletReturnInstr(MachineInstr *MI) {
1391 switch (MI->getOpcode()) {
1393 case X86::CLEANUPRET:
1398 llvm_unreachable("impossible");
1401 // CLR funclets use a special "Previous Stack Pointer Symbol" slot on the
1402 // stack. It holds a pointer to the bottom of the root function frame. The
1403 // establisher frame pointer passed to a nested funclet may point to the
1404 // (mostly empty) frame of its parent funclet, but it will need to find
1405 // the frame of the root function to access locals. To facilitate this,
1406 // every funclet copies the pointer to the bottom of the root function
1407 // frame into a PSPSym slot in its own (mostly empty) stack frame. Using the
1408 // same offset for the PSPSym in the root function frame that's used in the
1409 // funclets' frames allows each funclet to dynamically accept any ancestor
1410 // frame as its establisher argument (the runtime doesn't guarantee the
1411 // immediate parent for some reason lost to history), and also allows the GC,
1412 // which uses the PSPSym for some bookkeeping, to find it in any funclet's
1413 // frame with only a single offset reported for the entire method.
1415 X86FrameLowering::getPSPSlotOffsetFromSP(const MachineFunction &MF) const {
1416 const WinEHFuncInfo &Info = *MF.getWinEHFuncInfo();
1417 // getFrameIndexReferenceFromSP has an out ref parameter for the stack
1418 // pointer register; pass a dummy that we ignore
1420 int Offset = getFrameIndexReferenceFromSP(MF, Info.PSPSymFrameIdx, SPReg);
1421 assert(Offset >= 0);
1422 return static_cast<unsigned>(Offset);
1426 X86FrameLowering::getWinEHFuncletFrameSize(const MachineFunction &MF) const {
1427 // This is the size of the pushed CSRs.
1429 MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
1430 // This is the amount of stack a funclet needs to allocate.
1432 EHPersonality Personality =
1433 classifyEHPersonality(MF.getFunction()->getPersonalityFn());
1434 if (Personality == EHPersonality::CoreCLR) {
1435 // CLR funclets need to hold enough space to include the PSPSym, at the
1436 // same offset from the stack pointer (immediately after the prolog) as it
1437 // resides at in the main function.
1438 UsedSize = getPSPSlotOffsetFromSP(MF) + SlotSize;
1440 // Other funclets just need enough stack for outgoing call arguments.
1441 UsedSize = MF.getFrameInfo()->getMaxCallFrameSize();
1443 // RBP is not included in the callee saved register block. After pushing RBP,
1444 // everything is 16 byte aligned. Everything we allocate before an outgoing
1445 // call must also be 16 byte aligned.
1446 unsigned FrameSizeMinusRBP =
1447 RoundUpToAlignment(CSSize + UsedSize, getStackAlignment());
1448 // Subtract out the size of the callee saved registers. This is how much stack
1449 // each funclet will allocate.
1450 return FrameSizeMinusRBP - CSSize;
1453 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
1454 MachineBasicBlock &MBB) const {
1455 const MachineFrameInfo *MFI = MF.getFrameInfo();
1456 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1457 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1459 if (MBBI != MBB.end())
1460 DL = MBBI->getDebugLoc();
1461 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
1462 const bool Is64BitILP32 = STI.isTarget64BitILP32();
1463 unsigned FramePtr = TRI->getFrameRegister(MF);
1464 unsigned MachineFramePtr =
1465 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
1468 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1470 IsWin64Prologue && MF.getFunction()->needsUnwindTableEntry();
1471 bool IsFunclet = isFuncletReturnInstr(MBBI);
1472 MachineBasicBlock *TargetMBB = nullptr;
1474 // Get the number of bytes to allocate from the FrameInfo.
1475 uint64_t StackSize = MFI->getStackSize();
1476 uint64_t MaxAlign = calculateMaxStackAlign(MF);
1477 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1478 uint64_t NumBytes = 0;
1480 if (MBBI->getOpcode() == X86::CATCHRET) {
1481 // SEH shouldn't use catchret.
1482 assert(!isAsynchronousEHPersonality(
1483 classifyEHPersonality(MF.getFunction()->getPersonalityFn())) &&
1484 "SEH should not use CATCHRET");
1486 NumBytes = getWinEHFuncletFrameSize(MF);
1487 assert(hasFP(MF) && "EH funclets without FP not yet implemented");
1488 TargetMBB = MBBI->getOperand(0).getMBB();
1491 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
1493 .setMIFlag(MachineInstr::FrameDestroy);
1494 } else if (MBBI->getOpcode() == X86::CLEANUPRET) {
1495 NumBytes = getWinEHFuncletFrameSize(MF);
1496 assert(hasFP(MF) && "EH funclets without FP not yet implemented");
1497 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::POP64r : X86::POP32r),
1499 .setMIFlag(MachineInstr::FrameDestroy);
1500 } else if (hasFP(MF)) {
1501 // Calculate required stack adjustment.
1502 uint64_t FrameSize = StackSize - SlotSize;
1503 NumBytes = FrameSize - CSSize;
1505 // Callee-saved registers were pushed on stack before the stack was
1507 if (TRI->needsStackRealignment(MF) && !IsWin64Prologue)
1508 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1511 BuildMI(MBB, MBBI, DL,
1512 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr)
1513 .setMIFlag(MachineInstr::FrameDestroy);
1515 NumBytes = StackSize - CSSize;
1517 uint64_t SEHStackAllocAmt = NumBytes;
1519 // Skip the callee-saved pop instructions.
1520 while (MBBI != MBB.begin()) {
1521 MachineBasicBlock::iterator PI = std::prev(MBBI);
1522 unsigned Opc = PI->getOpcode();
1524 if ((Opc != X86::POP32r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
1525 (Opc != X86::POP64r || !PI->getFlag(MachineInstr::FrameDestroy)) &&
1526 Opc != X86::DBG_VALUE && !PI->isTerminator())
1531 MachineBasicBlock::iterator FirstCSPop = MBBI;
1534 // Fill EAX/RAX with the address of the target block.
1535 unsigned ReturnReg = STI.is64Bit() ? X86::RAX : X86::EAX;
1536 if (STI.is64Bit()) {
1537 // LEA64r TargetMBB(%rip), %rax
1538 BuildMI(MBB, FirstCSPop, DL, TII.get(X86::LEA64r), ReturnReg)
1545 // MOV32ri $TargetMBB, %eax
1546 BuildMI(MBB, FirstCSPop, DL, TII.get(X86::MOV32ri), ReturnReg)
1549 // Record that we've taken the address of TargetMBB and no longer just
1550 // reference it in a terminator.
1551 TargetMBB->setHasAddressTaken();
1554 if (MBBI != MBB.end())
1555 DL = MBBI->getDebugLoc();
1557 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1558 // instruction, merge the two instructions.
1559 if (NumBytes || MFI->hasVarSizedObjects())
1560 NumBytes += mergeSPUpdates(MBB, MBBI, true);
1562 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1563 // slot before popping them off! Same applies for the case, when stack was
1564 // realigned. Don't do this if this was a funclet epilogue, since the funclets
1565 // will not do realignment or dynamic stack allocation.
1566 if ((TRI->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) &&
1568 if (TRI->needsStackRealignment(MF))
1570 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1571 uint64_t LEAAmount =
1572 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1574 // There are only two legal forms of epilogue:
1575 // - add SEHAllocationSize, %rsp
1576 // - lea SEHAllocationSize(%FramePtr), %rsp
1578 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1579 // However, we may use this sequence if we have a frame pointer because the
1580 // effects of the prologue can safely be undone.
1581 if (LEAAmount != 0) {
1582 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1583 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1584 FramePtr, false, LEAAmount);
1587 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1588 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1592 } else if (NumBytes) {
1593 // Adjust stack pointer back: ESP += numbytes.
1594 emitSPUpdate(MBB, MBBI, NumBytes, /*InEpilogue=*/true);
1598 // Windows unwinder will not invoke function's exception handler if IP is
1599 // either in prologue or in epilogue. This behavior causes a problem when a
1600 // call immediately precedes an epilogue, because the return address points
1601 // into the epilogue. To cope with that, we insert an epilogue marker here,
1602 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1603 // final emitted code.
1605 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1607 // Add the return addr area delta back since we are not tail calling.
1608 int Offset = -1 * X86FI->getTCReturnAddrDelta();
1609 assert(Offset >= 0 && "TCDelta should never be positive");
1611 MBBI = MBB.getFirstTerminator();
1613 // Check for possible merge with preceding ADD instruction.
1614 Offset += mergeSPUpdates(MBB, MBBI, true);
1615 emitSPUpdate(MBB, MBBI, Offset, /*InEpilogue=*/true);
1619 // NOTE: this only has a subset of the full frame index logic. In
1620 // particular, the FI < 0 and AfterFPPop logic is handled in
1621 // X86RegisterInfo::eliminateFrameIndex, but not here. Possibly
1622 // (probably?) it should be moved into here.
1623 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1624 unsigned &FrameReg) const {
1625 const MachineFrameInfo *MFI = MF.getFrameInfo();
1627 // We can't calculate offset from frame pointer if the stack is realigned,
1628 // so enforce usage of stack/base pointer. The base pointer is used when we
1629 // have dynamic allocas in addition to dynamic realignment.
1630 if (TRI->hasBasePointer(MF))
1631 FrameReg = TRI->getBaseRegister();
1632 else if (TRI->needsStackRealignment(MF))
1633 FrameReg = TRI->getStackRegister();
1635 FrameReg = TRI->getFrameRegister(MF);
1637 // Offset will hold the offset from the stack pointer at function entry to the
1639 // We need to factor in additional offsets applied during the prologue to the
1640 // frame, base, and stack pointer depending on which is used.
1641 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1642 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1643 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1644 uint64_t StackSize = MFI->getStackSize();
1645 bool HasFP = hasFP(MF);
1646 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1647 int64_t FPDelta = 0;
1649 if (IsWin64Prologue) {
1650 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1652 // Calculate required stack adjustment.
1653 uint64_t FrameSize = StackSize - SlotSize;
1654 // If required, include space for extra hidden slot for stashing base pointer.
1655 if (X86FI->getRestoreBasePointer())
1656 FrameSize += SlotSize;
1657 uint64_t NumBytes = FrameSize - CSSize;
1659 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1660 if (FI && FI == X86FI->getFAIndex())
1661 return -SEHFrameOffset;
1663 // FPDelta is the offset from the "traditional" FP location of the old base
1664 // pointer followed by return address and the location required by the
1665 // restricted Win64 prologue.
1666 // Add FPDelta to all offsets below that go through the frame pointer.
1667 FPDelta = FrameSize - SEHFrameOffset;
1668 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1669 "FPDelta isn't aligned per the Win64 ABI!");
1673 if (TRI->hasBasePointer(MF)) {
1674 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1676 // Skip the saved EBP.
1677 return Offset + SlotSize + FPDelta;
1679 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1680 return Offset + StackSize;
1682 } else if (TRI->needsStackRealignment(MF)) {
1684 // Skip the saved EBP.
1685 return Offset + SlotSize + FPDelta;
1687 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1688 return Offset + StackSize;
1690 // FIXME: Support tail calls
1693 return Offset + StackSize;
1695 // Skip the saved EBP.
1698 // Skip the RETADDR move area
1699 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1700 if (TailCallReturnAddrDelta < 0)
1701 Offset -= TailCallReturnAddrDelta;
1704 return Offset + FPDelta;
1707 // Simplified from getFrameIndexReference keeping only StackPointer cases
1708 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1710 unsigned &FrameReg) const {
1711 const MachineFrameInfo *MFI = MF.getFrameInfo();
1712 // Does not include any dynamic realign.
1713 const uint64_t StackSize = MFI->getStackSize();
1716 // LLVM arranges the stack as follows:
1721 // PUSH RBP <-- RBP points here
1723 // ~~~~~~~ <-- possible stack realignment (non-win64)
1726 // ... <-- RSP after prologue points here
1727 // ~~~~~~~ <-- possible stack realignment (win64)
1729 // if (hasVarSizedObjects()):
1730 // ... <-- "base pointer" (ESI/RBX) points here
1732 // ... <-- RSP points here
1734 // Case 1: In the simple case of no stack realignment and no dynamic
1735 // allocas, both "fixed" stack objects (arguments and CSRs) are addressable
1736 // with fixed offsets from RSP.
1738 // Case 2: In the case of stack realignment with no dynamic allocas, fixed
1739 // stack objects are addressed with RBP and regular stack objects with RSP.
1741 // Case 3: In the case of dynamic allocas and stack realignment, RSP is used
1742 // to address stack arguments for outgoing calls and nothing else. The "base
1743 // pointer" points to local variables, and RBP points to fixed objects.
1745 // In cases 2 and 3, we can only answer for non-fixed stack objects, and the
1746 // answer we give is relative to the SP after the prologue, and not the
1747 // SP in the middle of the function.
1749 assert((!MFI->isFixedObjectIndex(FI) || !TRI->needsStackRealignment(MF) ||
1750 STI.isTargetWin64()) &&
1751 "offset from fixed object to SP is not static");
1753 // We don't handle tail calls, and shouldn't be seeing them either.
1754 int TailCallReturnAddrDelta =
1755 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1756 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1760 // Fill in FrameReg output argument.
1761 FrameReg = TRI->getStackRegister();
1763 // This is how the math works out:
1765 // %rsp grows (i.e. gets lower) left to right. Each box below is
1766 // one word (eight bytes). Obj0 is the stack slot we're trying to
1769 // ----------------------------------
1770 // | BP | Obj0 | Obj1 | ... | ObjN |
1771 // ----------------------------------
1775 // A is the incoming stack pointer.
1776 // (B - A) is the local area offset (-8 for x86-64) [1]
1777 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1779 // |(E - B)| is the StackSize (absolute value, positive). For a
1780 // stack that grown down, this works out to be (B - E). [3]
1782 // E is also the value of %rsp after stack has been set up, and we
1783 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1784 // (C - E) == (C - A) - (B - A) + (B - E)
1785 // { Using [1], [2] and [3] above }
1786 // == getObjectOffset - LocalAreaOffset + StackSize
1789 // Get the Offset from the StackPointer
1790 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1792 return Offset + StackSize;
1795 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1796 MachineFunction &MF, const TargetRegisterInfo *TRI,
1797 std::vector<CalleeSavedInfo> &CSI) const {
1798 MachineFrameInfo *MFI = MF.getFrameInfo();
1799 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1801 unsigned CalleeSavedFrameSize = 0;
1802 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1805 // emitPrologue always spills frame register the first thing.
1806 SpillSlotOffset -= SlotSize;
1807 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1809 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1810 // the frame register, we can delete it from CSI list and not have to worry
1811 // about avoiding it later.
1812 unsigned FPReg = TRI->getFrameRegister(MF);
1813 for (unsigned i = 0; i < CSI.size(); ++i) {
1814 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1815 CSI.erase(CSI.begin() + i);
1821 // Assign slots for GPRs. It increases frame size.
1822 for (unsigned i = CSI.size(); i != 0; --i) {
1823 unsigned Reg = CSI[i - 1].getReg();
1825 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1828 SpillSlotOffset -= SlotSize;
1829 CalleeSavedFrameSize += SlotSize;
1831 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1832 CSI[i - 1].setFrameIdx(SlotIndex);
1835 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1837 // Assign slots for XMMs.
1838 for (unsigned i = CSI.size(); i != 0; --i) {
1839 unsigned Reg = CSI[i - 1].getReg();
1840 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1843 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1845 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1847 SpillSlotOffset -= RC->getSize();
1849 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1850 CSI[i - 1].setFrameIdx(SlotIndex);
1851 MFI->ensureMaxAlignment(RC->getAlignment());
1857 bool X86FrameLowering::spillCalleeSavedRegisters(
1858 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1859 const std::vector<CalleeSavedInfo> &CSI,
1860 const TargetRegisterInfo *TRI) const {
1861 DebugLoc DL = MBB.findDebugLoc(MI);
1863 // Don't save CSRs in 32-bit EH funclets. The caller saves EBX, EBP, ESI, EDI
1864 // for us, and there are no XMM CSRs on Win32.
1865 if (MBB.isEHFuncletEntry() && STI.is32Bit() && STI.isOSWindows())
1868 // Push GPRs. It increases frame size.
1869 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1870 for (unsigned i = CSI.size(); i != 0; --i) {
1871 unsigned Reg = CSI[i - 1].getReg();
1873 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1875 // Add the callee-saved register as live-in. It's killed at the spill.
1878 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1879 .setMIFlag(MachineInstr::FrameSetup);
1882 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1883 // It can be done by spilling XMMs to stack frame.
1884 for (unsigned i = CSI.size(); i != 0; --i) {
1885 unsigned Reg = CSI[i-1].getReg();
1886 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1888 // Add the callee-saved register as live-in. It's killed at the spill.
1890 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1892 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1895 MI->setFlag(MachineInstr::FrameSetup);
1902 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1903 MachineBasicBlock::iterator MI,
1904 const std::vector<CalleeSavedInfo> &CSI,
1905 const TargetRegisterInfo *TRI) const {
1909 if (isFuncletReturnInstr(MI) && STI.isOSWindows()) {
1910 // Don't restore CSRs in 32-bit EH funclets. Matches
1911 // spillCalleeSavedRegisters.
1914 // Don't restore CSRs before an SEH catchret. SEH except blocks do not form
1915 // funclets. emitEpilogue transforms these to normal jumps.
1916 if (MI->getOpcode() == X86::CATCHRET) {
1917 const Function *Func = MBB.getParent()->getFunction();
1918 bool IsSEH = isAsynchronousEHPersonality(
1919 classifyEHPersonality(Func->getPersonalityFn()));
1925 DebugLoc DL = MBB.findDebugLoc(MI);
1927 // Reload XMMs from stack frame.
1928 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1929 unsigned Reg = CSI[i].getReg();
1930 if (X86::GR64RegClass.contains(Reg) ||
1931 X86::GR32RegClass.contains(Reg))
1934 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1935 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1939 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1940 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1941 unsigned Reg = CSI[i].getReg();
1942 if (!X86::GR64RegClass.contains(Reg) &&
1943 !X86::GR32RegClass.contains(Reg))
1946 BuildMI(MBB, MI, DL, TII.get(Opc), Reg)
1947 .setMIFlag(MachineInstr::FrameDestroy);
1952 void X86FrameLowering::determineCalleeSaves(MachineFunction &MF,
1953 BitVector &SavedRegs,
1954 RegScavenger *RS) const {
1955 TargetFrameLowering::determineCalleeSaves(MF, SavedRegs, RS);
1957 MachineFrameInfo *MFI = MF.getFrameInfo();
1959 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1960 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1962 if (TailCallReturnAddrDelta < 0) {
1963 // create RETURNADDR area
1972 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1973 TailCallReturnAddrDelta - SlotSize, true);
1976 // Spill the BasePtr if it's used.
1977 if (TRI->hasBasePointer(MF)) {
1978 SavedRegs.set(TRI->getBaseRegister());
1980 // Allocate a spill slot for EBP if we have a base pointer and EH funclets.
1981 if (MF.getMMI().hasEHFunclets()) {
1982 int FI = MFI->CreateSpillStackObject(SlotSize, SlotSize);
1983 X86FI->setHasSEHFramePtrSave(true);
1984 X86FI->setSEHFramePtrSaveIndex(FI);
1990 HasNestArgument(const MachineFunction *MF) {
1991 const Function *F = MF->getFunction();
1992 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1994 if (I->hasNestAttr())
2000 /// GetScratchRegister - Get a temp register for performing work in the
2001 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
2002 /// and the properties of the function either one or two registers will be
2003 /// needed. Set primary to true for the first register, false for the second.
2005 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
2006 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
2009 if (CallingConvention == CallingConv::HiPE) {
2011 return Primary ? X86::R14 : X86::R13;
2013 return Primary ? X86::EBX : X86::EDI;
2018 return Primary ? X86::R11 : X86::R12;
2020 return Primary ? X86::R11D : X86::R12D;
2023 bool IsNested = HasNestArgument(&MF);
2025 if (CallingConvention == CallingConv::X86_FastCall ||
2026 CallingConvention == CallingConv::Fast) {
2028 report_fatal_error("Segmented stacks does not support fastcall with "
2029 "nested function.");
2030 return Primary ? X86::EAX : X86::ECX;
2033 return Primary ? X86::EDX : X86::EAX;
2034 return Primary ? X86::ECX : X86::EAX;
2037 // The stack limit in the TCB is set to this many bytes above the actual stack
2039 static const uint64_t kSplitStackAvailable = 256;
2041 void X86FrameLowering::adjustForSegmentedStacks(
2042 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2043 MachineFrameInfo *MFI = MF.getFrameInfo();
2045 unsigned TlsReg, TlsOffset;
2048 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2049 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2050 "Scratch register is live-in");
2052 if (MF.getFunction()->isVarArg())
2053 report_fatal_error("Segmented stacks do not support vararg functions.");
2054 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
2055 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
2056 !STI.isTargetDragonFly())
2057 report_fatal_error("Segmented stacks not supported on this platform.");
2059 // Eventually StackSize will be calculated by a link-time pass; which will
2060 // also decide whether checking code needs to be injected into this particular
2062 StackSize = MFI->getStackSize();
2064 // Do not generate a prologue for functions with a stack of size zero
2068 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
2069 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
2070 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2071 bool IsNested = false;
2073 // We need to know if the function has a nest argument only in 64 bit mode.
2075 IsNested = HasNestArgument(&MF);
2077 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
2078 // allocMBB needs to be last (terminating) instruction.
2080 for (const auto &LI : PrologueMBB.liveins()) {
2081 allocMBB->addLiveIn(LI);
2082 checkMBB->addLiveIn(LI);
2086 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
2088 MF.push_front(allocMBB);
2089 MF.push_front(checkMBB);
2091 // When the frame size is less than 256 we just compare the stack
2092 // boundary directly to the value of the stack pointer, per gcc.
2093 bool CompareStackPointer = StackSize < kSplitStackAvailable;
2095 // Read the limit off the current stacklet off the stack_guard location.
2097 if (STI.isTargetLinux()) {
2099 TlsOffset = IsLP64 ? 0x70 : 0x40;
2100 } else if (STI.isTargetDarwin()) {
2102 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
2103 } else if (STI.isTargetWin64()) {
2105 TlsOffset = 0x28; // pvArbitrary, reserved for application use
2106 } else if (STI.isTargetFreeBSD()) {
2109 } else if (STI.isTargetDragonFly()) {
2111 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
2113 report_fatal_error("Segmented stacks not supported on this platform.");
2116 if (CompareStackPointer)
2117 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
2119 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
2120 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2122 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
2123 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2125 if (STI.isTargetLinux()) {
2128 } else if (STI.isTargetDarwin()) {
2130 TlsOffset = 0x48 + 90*4;
2131 } else if (STI.isTargetWin32()) {
2133 TlsOffset = 0x14; // pvArbitrary, reserved for application use
2134 } else if (STI.isTargetDragonFly()) {
2136 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
2137 } else if (STI.isTargetFreeBSD()) {
2138 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
2140 report_fatal_error("Segmented stacks not supported on this platform.");
2143 if (CompareStackPointer)
2144 ScratchReg = X86::ESP;
2146 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
2147 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
2149 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
2150 STI.isTargetDragonFly()) {
2151 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
2152 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
2153 } else if (STI.isTargetDarwin()) {
2155 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
2156 unsigned ScratchReg2;
2158 if (CompareStackPointer) {
2159 // The primary scratch register is available for holding the TLS offset.
2160 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2161 SaveScratch2 = false;
2163 // Need to use a second register to hold the TLS offset
2164 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
2166 // Unfortunately, with fastcc the second scratch register may hold an
2168 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
2171 // If Scratch2 is live-in then it needs to be saved.
2172 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
2173 "Scratch register is live-in and not saved");
2176 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
2177 .addReg(ScratchReg2, RegState::Kill);
2179 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
2181 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
2183 .addReg(ScratchReg2).addImm(1).addReg(0)
2188 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
2192 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
2193 // It jumps to normal execution of the function body.
2194 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
2196 // On 32 bit we first push the arguments size and then the frame size. On 64
2197 // bit, we pass the stack frame size in r10 and the argument size in r11.
2199 // Functions with nested arguments use R10, so it needs to be saved across
2200 // the call to _morestack
2202 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
2203 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
2204 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
2205 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
2206 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
2209 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
2211 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
2213 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
2214 .addImm(X86FI->getArgumentStackSize());
2216 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2217 .addImm(X86FI->getArgumentStackSize());
2218 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
2222 // __morestack is in libgcc
2223 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
2224 // Under the large code model, we cannot assume that __morestack lives
2225 // within 2^31 bytes of the call site, so we cannot use pc-relative
2226 // addressing. We cannot perform the call via a temporary register,
2227 // as the rax register may be used to store the static chain, and all
2228 // other suitable registers may be either callee-save or used for
2229 // parameter passing. We cannot use the stack at this point either
2230 // because __morestack manipulates the stack directly.
2232 // To avoid these issues, perform an indirect call via a read-only memory
2233 // location containing the address.
2235 // This solution is not perfect, as it assumes that the .rodata section
2236 // is laid out within 2^31 bytes of each function body, but this seems
2237 // to be sufficient for JIT.
2238 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
2242 .addExternalSymbol("__morestack_addr")
2244 MF.getMMI().setUsesMorestackAddr(true);
2247 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
2248 .addExternalSymbol("__morestack");
2250 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
2251 .addExternalSymbol("__morestack");
2255 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
2257 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
2259 allocMBB->addSuccessor(&PrologueMBB);
2261 checkMBB->addSuccessor(allocMBB);
2262 checkMBB->addSuccessor(&PrologueMBB);
2269 /// Erlang programs may need a special prologue to handle the stack size they
2270 /// might need at runtime. That is because Erlang/OTP does not implement a C
2271 /// stack but uses a custom implementation of hybrid stack/heap architecture.
2272 /// (for more information see Eric Stenman's Ph.D. thesis:
2273 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
2276 /// temp0 = sp - MaxStack
2277 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2281 /// call inc_stack # doubles the stack space
2282 /// temp0 = sp - MaxStack
2283 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
2284 void X86FrameLowering::adjustForHiPEPrologue(
2285 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
2286 MachineFrameInfo *MFI = MF.getFrameInfo();
2288 // HiPE-specific values
2289 const unsigned HipeLeafWords = 24;
2290 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
2291 const unsigned Guaranteed = HipeLeafWords * SlotSize;
2292 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
2293 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
2294 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
2296 assert(STI.isTargetLinux() &&
2297 "HiPE prologue is only supported on Linux operating systems.");
2299 // Compute the largest caller's frame that is needed to fit the callees'
2300 // frames. This 'MaxStack' is computed from:
2302 // a) the fixed frame size, which is the space needed for all spilled temps,
2303 // b) outgoing on-stack parameter areas, and
2304 // c) the minimum stack space this function needs to make available for the
2305 // functions it calls (a tunable ABI property).
2306 if (MFI->hasCalls()) {
2307 unsigned MoreStackForCalls = 0;
2309 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
2310 MBBI != MBBE; ++MBBI)
2311 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
2316 // Get callee operand.
2317 const MachineOperand &MO = MI->getOperand(0);
2319 // Only take account of global function calls (no closures etc.).
2323 const Function *F = dyn_cast<Function>(MO.getGlobal());
2327 // Do not update 'MaxStack' for primitive and built-in functions
2328 // (encoded with names either starting with "erlang."/"bif_" or not
2329 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
2330 // "_", such as the BIF "suspend_0") as they are executed on another
2332 if (F->getName().find("erlang.") != StringRef::npos ||
2333 F->getName().find("bif_") != StringRef::npos ||
2334 F->getName().find_first_of("._") == StringRef::npos)
2337 unsigned CalleeStkArity =
2338 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
2339 if (HipeLeafWords - 1 > CalleeStkArity)
2340 MoreStackForCalls = std::max(MoreStackForCalls,
2341 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
2343 MaxStack += MoreStackForCalls;
2346 // If the stack frame needed is larger than the guaranteed then runtime checks
2347 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
2348 if (MaxStack > Guaranteed) {
2349 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
2350 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
2352 for (const auto &LI : PrologueMBB.liveins()) {
2353 stackCheckMBB->addLiveIn(LI);
2354 incStackMBB->addLiveIn(LI);
2357 MF.push_front(incStackMBB);
2358 MF.push_front(stackCheckMBB);
2360 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
2361 unsigned LEAop, CMPop, CALLop;
2365 LEAop = X86::LEA64r;
2366 CMPop = X86::CMP64rm;
2367 CALLop = X86::CALL64pcrel32;
2368 SPLimitOffset = 0x90;
2372 LEAop = X86::LEA32r;
2373 CMPop = X86::CMP32rm;
2374 CALLop = X86::CALLpcrel32;
2375 SPLimitOffset = 0x4c;
2378 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
2379 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
2380 "HiPE prologue scratch register is live-in");
2382 // Create new MBB for StackCheck:
2383 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
2384 SPReg, false, -MaxStack);
2385 // SPLimitOffset is in a fixed heap location (pointed by BP).
2386 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
2387 .addReg(ScratchReg), PReg, false, SPLimitOffset);
2388 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
2390 // Create new MBB for IncStack:
2391 BuildMI(incStackMBB, DL, TII.get(CALLop)).
2392 addExternalSymbol("inc_stack_0");
2393 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
2394 SPReg, false, -MaxStack);
2395 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
2396 .addReg(ScratchReg), PReg, false, SPLimitOffset);
2397 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
2399 stackCheckMBB->addSuccessor(&PrologueMBB, {99, 100});
2400 stackCheckMBB->addSuccessor(incStackMBB, {1, 100});
2401 incStackMBB->addSuccessor(&PrologueMBB, {99, 100});
2402 incStackMBB->addSuccessor(incStackMBB, {1, 100});
2409 bool X86FrameLowering::adjustStackWithPops(MachineBasicBlock &MBB,
2410 MachineBasicBlock::iterator MBBI, DebugLoc DL, int Offset) const {
2415 if (Offset % SlotSize)
2418 int NumPops = Offset / SlotSize;
2419 // This is only worth it if we have at most 2 pops.
2420 if (NumPops != 1 && NumPops != 2)
2423 // Handle only the trivial case where the adjustment directly follows
2424 // a call. This is the most common one, anyway.
2425 if (MBBI == MBB.begin())
2427 MachineBasicBlock::iterator Prev = std::prev(MBBI);
2428 if (!Prev->isCall() || !Prev->getOperand(1).isRegMask())
2432 unsigned FoundRegs = 0;
2434 auto RegMask = Prev->getOperand(1);
2437 Is64Bit ? X86::GR64_NOREX_NOSPRegClass : X86::GR32_NOREX_NOSPRegClass;
2438 // Try to find up to NumPops free registers.
2439 for (auto Candidate : RegClass) {
2441 // Poor man's liveness:
2442 // Since we're immediately after a call, any register that is clobbered
2443 // by the call and not defined by it can be considered dead.
2444 if (!RegMask.clobbersPhysReg(Candidate))
2448 for (const MachineOperand &MO : Prev->implicit_operands()) {
2449 if (MO.isReg() && MO.isDef() && MO.getReg() == Candidate) {
2458 Regs[FoundRegs++] = Candidate;
2459 if (FoundRegs == (unsigned)NumPops)
2466 // If we found only one free register, but need two, reuse the same one twice.
2467 while (FoundRegs < (unsigned)NumPops)
2468 Regs[FoundRegs++] = Regs[0];
2470 for (int i = 0; i < NumPops; ++i)
2471 BuildMI(MBB, MBBI, DL,
2472 TII.get(STI.is64Bit() ? X86::POP64r : X86::POP32r), Regs[i]);
2477 void X86FrameLowering::
2478 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
2479 MachineBasicBlock::iterator I) const {
2480 bool reserveCallFrame = hasReservedCallFrame(MF);
2481 unsigned Opcode = I->getOpcode();
2482 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
2483 DebugLoc DL = I->getDebugLoc();
2484 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
2485 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
2488 if (!reserveCallFrame) {
2489 // If the stack pointer can be changed after prologue, turn the
2490 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
2491 // adjcallstackdown instruction into 'add ESP, <amt>'
2493 // We need to keep the stack aligned properly. To do this, we round the
2494 // amount of space needed for the outgoing arguments up to the next
2495 // alignment boundary.
2496 unsigned StackAlign = getStackAlignment();
2497 Amount = RoundUpToAlignment(Amount, StackAlign);
2499 MachineModuleInfo &MMI = MF.getMMI();
2500 const Function *Fn = MF.getFunction();
2501 bool WindowsCFI = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
2502 bool DwarfCFI = !WindowsCFI &&
2503 (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
2505 // If we have any exception handlers in this function, and we adjust
2506 // the SP before calls, we may need to indicate this to the unwinder
2507 // using GNU_ARGS_SIZE. Note that this may be necessary even when
2508 // Amount == 0, because the preceding function may have set a non-0
2510 // TODO: We don't need to reset this between subsequent functions,
2511 // if it didn't change.
2512 bool HasDwarfEHHandlers = !WindowsCFI &&
2513 !MF.getMMI().getLandingPads().empty();
2515 if (HasDwarfEHHandlers && !isDestroy &&
2516 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences())
2517 BuildCFI(MBB, I, DL,
2518 MCCFIInstruction::createGnuArgsSize(nullptr, Amount));
2523 // Factor out the amount that gets handled inside the sequence
2524 // (Pushes of argument for frame setup, callee pops for frame destroy)
2525 Amount -= InternalAmt;
2527 // If this is a callee-pop calling convention, and we're emitting precise
2528 // SP-based CFI, emit a CFA adjust for the amount the callee popped.
2529 if (isDestroy && InternalAmt && DwarfCFI && !hasFP(MF) &&
2530 MMI.usePreciseUnwindInfo())
2531 BuildCFI(MBB, I, DL,
2532 MCCFIInstruction::createAdjustCfaOffset(nullptr, -InternalAmt));
2535 // Add Amount to SP to destroy a frame, and subtract to setup.
2536 int Offset = isDestroy ? Amount : -Amount;
2538 if (!(Fn->optForMinSize() &&
2539 adjustStackWithPops(MBB, I, DL, Offset)))
2540 BuildStackAdjustment(MBB, I, DL, Offset, /*InEpilogue=*/false);
2543 if (DwarfCFI && !hasFP(MF)) {
2544 // If we don't have FP, but need to generate unwind information,
2545 // we need to set the correct CFA offset after the stack adjustment.
2546 // How much we adjust the CFA offset depends on whether we're emitting
2547 // CFI only for EH purposes or for debugging. EH only requires the CFA
2548 // offset to be correct at each call site, while for debugging we want
2549 // it to be more precise.
2550 int CFAOffset = Amount;
2551 if (!MMI.usePreciseUnwindInfo())
2552 CFAOffset += InternalAmt;
2553 CFAOffset = isDestroy ? -CFAOffset : CFAOffset;
2554 BuildCFI(MBB, I, DL,
2555 MCCFIInstruction::createAdjustCfaOffset(nullptr, CFAOffset));
2561 if (isDestroy && InternalAmt) {
2562 // If we are performing frame pointer elimination and if the callee pops
2563 // something off the stack pointer, add it back. We do this until we have
2564 // more advanced stack pointer tracking ability.
2565 // We are not tracking the stack pointer adjustment by the callee, so make
2566 // sure we restore the stack pointer immediately after the call, there may
2567 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
2568 MachineBasicBlock::iterator B = MBB.begin();
2569 while (I != B && !std::prev(I)->isCall())
2571 BuildStackAdjustment(MBB, I, DL, -InternalAmt, /*InEpilogue=*/false);
2575 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
2576 assert(MBB.getParent() && "Block is not attached to a function!");
2578 // Win64 has strict requirements in terms of epilogue and we are
2579 // not taking a chance at messing with them.
2580 // I.e., unless this block is already an exit block, we can't use
2581 // it as an epilogue.
2582 if (STI.isTargetWin64() && !MBB.succ_empty() && !MBB.isReturnBlock())
2585 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
2588 // If we cannot use LEA to adjust SP, we may need to use ADD, which
2589 // clobbers the EFLAGS. Check that we do not need to preserve it,
2590 // otherwise, conservatively assume this is not
2591 // safe to insert the epilogue here.
2592 return !flagsNeedToBePreservedBeforeTheTerminators(MBB);
2595 MachineBasicBlock::iterator X86FrameLowering::restoreWin32EHStackPointers(
2596 MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
2597 DebugLoc DL, bool RestoreSP) const {
2598 assert(STI.isTargetWindowsMSVC() && "funclets only supported in MSVC env");
2599 assert(STI.isTargetWin32() && "EBP/ESI restoration only required on win32");
2600 assert(STI.is32Bit() && !Uses64BitFramePtr &&
2601 "restoring EBP/ESI on non-32-bit target");
2603 MachineFunction &MF = *MBB.getParent();
2604 unsigned FramePtr = TRI->getFrameRegister(MF);
2605 unsigned BasePtr = TRI->getBaseRegister();
2606 WinEHFuncInfo &FuncInfo = *MF.getWinEHFuncInfo();
2607 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
2608 MachineFrameInfo *MFI = MF.getFrameInfo();
2610 // FIXME: Don't set FrameSetup flag in catchret case.
2612 int FI = FuncInfo.EHRegNodeFrameIndex;
2613 int EHRegSize = MFI->getObjectSize(FI);
2616 // MOV32rm -EHRegSize(%ebp), %esp
2617 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), X86::ESP),
2618 X86::EBP, true, -EHRegSize)
2619 .setMIFlag(MachineInstr::FrameSetup);
2623 int EHRegOffset = getFrameIndexReference(MF, FI, UsedReg);
2624 int EndOffset = -EHRegOffset - EHRegSize;
2625 FuncInfo.EHRegNodeEndOffset = EndOffset;
2627 if (UsedReg == FramePtr) {
2628 // ADD $offset, %ebp
2629 unsigned ADDri = getADDriOpcode(false, EndOffset);
2630 BuildMI(MBB, MBBI, DL, TII.get(ADDri), FramePtr)
2633 .setMIFlag(MachineInstr::FrameSetup)
2636 assert(EndOffset >= 0 &&
2637 "end of registration object above normal EBP position!");
2638 } else if (UsedReg == BasePtr) {
2639 // LEA offset(%ebp), %esi
2640 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA32r), BasePtr),
2641 FramePtr, false, EndOffset)
2642 .setMIFlag(MachineInstr::FrameSetup);
2643 // MOV32rm SavedEBPOffset(%esi), %ebp
2644 assert(X86FI->getHasSEHFramePtrSave());
2646 getFrameIndexReference(MF, X86FI->getSEHFramePtrSaveIndex(), UsedReg);
2647 assert(UsedReg == BasePtr);
2648 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32rm), FramePtr),
2649 UsedReg, true, Offset)
2650 .setMIFlag(MachineInstr::FrameSetup);
2652 llvm_unreachable("32-bit frames with WinEH must use FramePtr or BasePtr");
2657 unsigned X86FrameLowering::getWinEHParentFrameOffset(const MachineFunction &MF) const {
2658 // RDX, the parent frame pointer, is homed into 16(%rsp) in the prologue.
2659 unsigned Offset = 16;
2660 // RBP is immediately pushed.
2662 // All callee-saved registers are then pushed.
2663 Offset += MF.getInfo<X86MachineFunctionInfo>()->getCalleeSavedFrameSize();
2664 // Every funclet allocates enough stack space for the largest outgoing call.
2665 Offset += getWinEHFuncletFrameSize(MF);
2669 void X86FrameLowering::processFunctionBeforeFrameFinalized(
2670 MachineFunction &MF, RegScavenger *RS) const {
2671 // If this function isn't doing Win64-style C++ EH, we don't need to do
2673 const Function *Fn = MF.getFunction();
2674 if (!STI.is64Bit() || !MF.getMMI().hasEHFunclets() ||
2675 classifyEHPersonality(Fn->getPersonalityFn()) != EHPersonality::MSVC_CXX)
2678 // Win64 C++ EH needs to allocate the UnwindHelp object at some fixed offset
2679 // relative to RSP after the prologue. Find the offset of the last fixed
2680 // object, so that we can allocate a slot immediately following it. If there
2681 // were no fixed objects, use offset -SlotSize, which is immediately after the
2682 // return address. Fixed objects have negative frame indices.
2683 MachineFrameInfo *MFI = MF.getFrameInfo();
2684 int64_t MinFixedObjOffset = -SlotSize;
2685 for (int I = MFI->getObjectIndexBegin(); I < 0; ++I)
2686 MinFixedObjOffset = std::min(MinFixedObjOffset, MFI->getObjectOffset(I));
2688 int64_t UnwindHelpOffset = MinFixedObjOffset - SlotSize;
2690 MFI->CreateFixedObject(SlotSize, UnwindHelpOffset, /*Immutable=*/false);
2691 MF.getWinEHFuncInfo()->UnwindHelpFrameIdx = UnwindHelpFI;
2693 // Store -2 into UnwindHelp on function entry. We have to scan forwards past
2694 // other frame setup instructions.
2695 MachineBasicBlock &MBB = MF.front();
2696 auto MBBI = MBB.begin();
2697 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
2700 DebugLoc DL = MBB.findDebugLoc(MBBI);
2701 addFrameReference(BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64mi32)),