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/CodeGen/MachineFrameInfo.h"
22 #include "llvm/CodeGen/MachineFunction.h"
23 #include "llvm/CodeGen/MachineInstrBuilder.h"
24 #include "llvm/CodeGen/MachineModuleInfo.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/IR/DataLayout.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/MC/MCAsmInfo.h"
29 #include "llvm/MC/MCSymbol.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Target/TargetOptions.h"
32 #include "llvm/Support/Debug.h"
37 // FIXME: completely move here.
38 extern cl::opt<bool> ForceStackAlign;
40 X86FrameLowering::X86FrameLowering(const X86Subtarget &STI,
41 unsigned StackAlignOverride)
42 : TargetFrameLowering(StackGrowsDown, StackAlignOverride,
43 STI.is64Bit() ? -8 : -4),
44 STI(STI), TII(*STI.getInstrInfo()), RegInfo(STI.getRegisterInfo()) {
45 // Cache a bunch of frame-related predicates for this subtarget.
46 SlotSize = RegInfo->getSlotSize();
47 Is64Bit = STI.is64Bit();
48 IsLP64 = STI.isTarget64BitLP64();
49 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
50 Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
51 StackPtr = RegInfo->getStackRegister();
54 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
55 return !MF.getFrameInfo()->hasVarSizedObjects() &&
56 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
59 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
60 /// call frame pseudos can be simplified. Having a FP, as in the default
61 /// implementation, is not sufficient here since we can't always use it.
62 /// Use a more nuanced condition.
64 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
65 return hasReservedCallFrame(MF) ||
66 (hasFP(MF) && !RegInfo->needsStackRealignment(MF)) ||
67 RegInfo->hasBasePointer(MF);
70 // needsFrameIndexResolution - Do we need to perform FI resolution for
71 // this function. Normally, this is required only when the function
72 // has any stack objects. However, FI resolution actually has another job,
73 // not apparent from the title - it resolves callframesetup/destroy
74 // that were not simplified earlier.
75 // So, this is required for x86 functions that have push sequences even
76 // when there are no stack objects.
78 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
79 return MF.getFrameInfo()->hasStackObjects() ||
80 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
83 /// hasFP - Return true if the specified function should have a dedicated frame
84 /// pointer register. This is true if the function has variable sized allocas
85 /// or if frame pointer elimination is disabled.
86 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
87 const MachineFrameInfo *MFI = MF.getFrameInfo();
88 const MachineModuleInfo &MMI = MF.getMMI();
90 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
91 RegInfo->needsStackRealignment(MF) ||
92 MFI->hasVarSizedObjects() ||
93 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
94 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
95 MMI.callsUnwindInit() || MMI.callsEHReturn() ||
96 MFI->hasStackMap() || MFI->hasPatchPoint());
99 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
102 return X86::SUB64ri8;
103 return X86::SUB64ri32;
106 return X86::SUB32ri8;
111 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
114 return X86::ADD64ri8;
115 return X86::ADD64ri32;
118 return X86::ADD32ri8;
123 static unsigned getSUBrrOpcode(unsigned isLP64) {
124 return isLP64 ? X86::SUB64rr : X86::SUB32rr;
127 static unsigned getADDrrOpcode(unsigned isLP64) {
128 return isLP64 ? X86::ADD64rr : X86::ADD32rr;
131 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
134 return X86::AND64ri8;
135 return X86::AND64ri32;
138 return X86::AND32ri8;
142 static unsigned getLEArOpcode(unsigned IsLP64) {
143 return IsLP64 ? X86::LEA64r : X86::LEA32r;
146 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
147 /// when it reaches the "return" instruction. We can then pop a stack object
148 /// to this register without worry about clobbering it.
149 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
150 MachineBasicBlock::iterator &MBBI,
151 const TargetRegisterInfo *RegInfo,
153 const MachineFunction *MF = MBB.getParent();
154 const Function *F = MF->getFunction();
155 if (!F || MF->getMMI().callsEHReturn())
158 static const uint16_t CallerSavedRegs32Bit[] = {
159 X86::EAX, X86::EDX, X86::ECX, 0
162 static const uint16_t CallerSavedRegs64Bit[] = {
163 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
164 X86::R8, X86::R9, X86::R10, X86::R11, 0
167 unsigned Opc = MBBI->getOpcode();
174 case X86::TCRETURNdi:
175 case X86::TCRETURNri:
176 case X86::TCRETURNmi:
177 case X86::TCRETURNdi64:
178 case X86::TCRETURNri64:
179 case X86::TCRETURNmi64:
181 case X86::EH_RETURN64: {
182 SmallSet<uint16_t, 8> Uses;
183 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
184 MachineOperand &MO = MBBI->getOperand(i);
185 if (!MO.isReg() || MO.isDef())
187 unsigned Reg = MO.getReg();
190 for (MCRegAliasIterator AI(Reg, RegInfo, true); AI.isValid(); ++AI)
194 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
196 if (!Uses.count(*CS))
204 static bool isEAXLiveIn(MachineFunction &MF) {
205 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
206 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
207 unsigned Reg = II->first;
209 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
210 Reg == X86::AH || Reg == X86::AL)
217 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
218 /// stack pointer by a constant value.
219 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
220 MachineBasicBlock::iterator &MBBI,
221 int64_t NumBytes, bool UseLEA) const {
222 bool isSub = NumBytes < 0;
223 uint64_t Offset = isSub ? -NumBytes : NumBytes;
226 Opc = getLEArOpcode(Uses64BitFramePtr);
229 ? getSUBriOpcode(Uses64BitFramePtr, Offset)
230 : getADDriOpcode(Uses64BitFramePtr, Offset);
232 uint64_t Chunk = (1LL << 31) - 1;
233 DebugLoc DL = MBB.findDebugLoc(MBBI);
236 if (Offset > Chunk) {
237 // Rather than emit a long series of instructions for large offsets,
238 // load the offset into a register and do one sub/add
241 if (isSub && !isEAXLiveIn(*MBB.getParent()))
242 Reg = (unsigned)(Is64Bit ? X86::RAX : X86::EAX);
244 Reg = findDeadCallerSavedReg(MBB, MBBI, RegInfo, Is64Bit);
247 Opc = Is64Bit ? X86::MOV64ri : X86::MOV32ri;
248 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
251 ? getSUBrrOpcode(Is64Bit)
252 : getADDrrOpcode(Is64Bit);
253 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
256 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
262 uint64_t ThisVal = std::min(Offset, Chunk);
263 if (ThisVal == (Is64Bit ? 8 : 4)) {
264 // Use push / pop instead.
266 ? (unsigned)(Is64Bit ? X86::RAX : X86::EAX)
267 : findDeadCallerSavedReg(MBB, MBBI, RegInfo, Is64Bit);
270 ? (Is64Bit ? X86::PUSH64r : X86::PUSH32r)
271 : (Is64Bit ? X86::POP64r : X86::POP32r);
272 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
273 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
275 MI->setFlag(MachineInstr::FrameSetup);
281 MachineInstr *MI = nullptr;
284 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
285 StackPtr, false, isSub ? -ThisVal : ThisVal);
287 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
290 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
294 MI->setFlag(MachineInstr::FrameSetup);
300 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
302 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
303 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
304 if (MBBI == MBB.begin()) return;
306 MachineBasicBlock::iterator PI = std::prev(MBBI);
307 unsigned Opc = PI->getOpcode();
308 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
309 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
310 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
311 PI->getOperand(0).getReg() == StackPtr) {
313 *NumBytes += PI->getOperand(2).getImm();
315 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
316 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
317 PI->getOperand(0).getReg() == StackPtr) {
319 *NumBytes -= PI->getOperand(2).getImm();
324 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
325 MachineBasicBlock::iterator &MBBI,
326 bool doMergeWithPrevious) const {
327 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
328 (!doMergeWithPrevious && MBBI == MBB.end()))
331 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
332 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
334 unsigned Opc = PI->getOpcode();
337 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
338 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
339 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
340 PI->getOperand(0).getReg() == StackPtr){
341 Offset += PI->getOperand(2).getImm();
343 if (!doMergeWithPrevious) MBBI = NI;
344 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
345 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
346 PI->getOperand(0).getReg() == StackPtr) {
347 Offset -= PI->getOperand(2).getImm();
349 if (!doMergeWithPrevious) MBBI = NI;
355 void X86FrameLowering::BuildCFI(MachineBasicBlock &MBB,
356 MachineBasicBlock::iterator MBBI, DebugLoc DL,
357 MCCFIInstruction CFIInst) const {
358 MachineFunction &MF = *MBB.getParent();
359 unsigned CFIIndex = MF.getMMI().addFrameInst(CFIInst);
360 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
361 .addCFIIndex(CFIIndex);
365 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
366 MachineBasicBlock::iterator MBBI,
368 MachineFunction &MF = *MBB.getParent();
369 MachineFrameInfo *MFI = MF.getFrameInfo();
370 MachineModuleInfo &MMI = MF.getMMI();
371 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
373 // Add callee saved registers to move list.
374 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
375 if (CSI.empty()) return;
377 // Calculate offsets.
378 for (std::vector<CalleeSavedInfo>::const_iterator
379 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
380 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
381 unsigned Reg = I->getReg();
383 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
384 BuildCFI(MBB, MBBI, DL,
385 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
389 /// usesTheStack - This function checks if any of the users of EFLAGS
390 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
391 /// to use the stack, and if we don't adjust the stack we clobber the first
393 /// See X86InstrInfo::copyPhysReg.
394 static bool usesTheStack(const MachineFunction &MF) {
395 const MachineRegisterInfo &MRI = MF.getRegInfo();
397 for (MachineRegisterInfo::reg_instr_iterator
398 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
406 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
407 MachineBasicBlock &MBB,
408 MachineBasicBlock::iterator MBBI,
410 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
414 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
416 CallOp = X86::CALLpcrel32;
420 if (STI.isTargetCygMing()) {
421 Symbol = "___chkstk_ms";
425 } else if (STI.isTargetCygMing())
430 MachineInstrBuilder CI;
432 // All current stack probes take AX and SP as input, clobber flags, and
433 // preserve all registers. x86_64 probes leave RSP unmodified.
434 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
435 // For the large code model, we have to call through a register. Use R11,
436 // as it is scratch in all supported calling conventions.
437 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
438 .addExternalSymbol(Symbol);
439 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
441 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
444 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
445 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
446 CI.addReg(AX, RegState::Implicit)
447 .addReg(SP, RegState::Implicit)
448 .addReg(AX, RegState::Define | RegState::Implicit)
449 .addReg(SP, RegState::Define | RegState::Implicit)
450 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
453 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
454 // themselves. It also does not clobber %rax so we can reuse it when
456 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
462 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
463 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
464 // and might require smaller successive adjustments.
465 const uint64_t Win64MaxSEHOffset = 128;
466 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
467 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
468 return SEHFrameOffset & -16;
471 // If we're forcing a stack realignment we can't rely on just the frame
472 // info, we need to know the ABI stack alignment as well in case we
473 // have a call out. Otherwise just make sure we have some alignment - we'll
474 // go with the minimum SlotSize.
475 uint64_t X86FrameLowering::calculateMaxStackAlign(const MachineFunction &MF) const {
476 const MachineFrameInfo *MFI = MF.getFrameInfo();
477 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
478 unsigned StackAlign = getStackAlignment();
479 if (ForceStackAlign) {
481 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
482 else if (MaxAlign < SlotSize)
488 void X86FrameLowering::BuildStackAlignAND(MachineBasicBlock &MBB,
489 MachineBasicBlock::iterator MBBI,
491 uint64_t MaxAlign) const {
492 uint64_t Val = -MaxAlign;
494 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
498 .setMIFlag(MachineInstr::FrameSetup);
500 // The EFLAGS implicit def is dead.
501 MI->getOperand(3).setIsDead();
504 /// emitPrologue - Push callee-saved registers onto the stack, which
505 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
506 /// space for local variables. Also emit labels used by the exception handler to
507 /// generate the exception handling frames.
510 Here's a gist of what gets emitted:
512 ; Establish frame pointer, if needed
515 .cfi_def_cfa_offset 16
516 .cfi_offset %rbp, -16
519 .cfi_def_cfa_register %rbp
521 ; Spill general-purpose registers
522 [for all callee-saved GPRs]
525 .cfi_def_cfa_offset (offset from RETADDR)
528 ; If the required stack alignment > default stack alignment
529 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
530 ; of unknown size in the stack frame.
531 [if stack needs re-alignment]
534 ; Allocate space for locals
535 [if target is Windows and allocated space > 4096 bytes]
536 ; Windows needs special care for allocations larger
539 call ___chkstk_ms/___chkstk
545 .seh_stackalloc (size of XMM spill slots)
546 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
551 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
552 ; they may get spilled on any platform, if the current function
553 ; calls @llvm.eh.unwind.init
555 [for all callee-saved XMM registers]
556 movaps %<xmm reg>, -MMM(%rbp)
557 [for all callee-saved XMM registers]
558 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
559 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
561 [for all callee-saved XMM registers]
562 movaps %<xmm reg>, KKK(%rsp)
563 [for all callee-saved XMM registers]
564 .seh_savexmm %<xmm reg>, KKK
568 [if needs base pointer]
570 [if needs to restore base pointer]
575 [for all callee-saved registers]
576 .cfi_offset %<reg>, (offset from %rbp)
578 .cfi_def_cfa_offset (offset from RETADDR)
579 [for all callee-saved registers]
580 .cfi_offset %<reg>, (offset from %rsp)
583 - .seh directives are emitted only for Windows 64 ABI
584 - .cfi directives are emitted for all other ABIs
585 - for 32-bit code, substitute %e?? registers for %r??
588 void X86FrameLowering::emitPrologue(MachineFunction &MF,
589 MachineBasicBlock &MBB) const {
590 assert(&STI == &MF.getSubtarget<X86Subtarget>() &&
591 "MF used frame lowering for wrong subtarget");
592 MachineBasicBlock::iterator MBBI = MBB.begin();
593 MachineFrameInfo *MFI = MF.getFrameInfo();
594 const Function *Fn = MF.getFunction();
595 MachineModuleInfo &MMI = MF.getMMI();
596 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
597 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
598 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
599 bool HasFP = hasFP(MF);
600 bool IsWin64CC = STI.isCallingConvWin64(Fn->getCallingConv());
601 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
602 bool NeedsWinCFI = IsWin64Prologue && Fn->needsUnwindTableEntry();
604 !IsWin64Prologue && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
605 bool UseLEA = STI.useLeaForSP();
606 unsigned FramePtr = RegInfo->getFrameRegister(MF);
607 const unsigned MachineFramePtr =
608 STI.isTarget64BitILP32()
609 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
611 unsigned BasePtr = RegInfo->getBaseRegister();
614 // Add RETADDR move area to callee saved frame size.
615 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
616 if (TailCallReturnAddrDelta && IsWin64Prologue)
617 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
619 if (TailCallReturnAddrDelta < 0)
620 X86FI->setCalleeSavedFrameSize(
621 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
623 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
625 // The default stack probe size is 4096 if the function has no stackprobesize
627 unsigned StackProbeSize = 4096;
628 if (Fn->hasFnAttribute("stack-probe-size"))
629 Fn->getFnAttribute("stack-probe-size")
631 .getAsInteger(0, StackProbeSize);
633 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
634 // function, and use up to 128 bytes of stack space, don't have a frame
635 // pointer, calls, or dynamic alloca then we do not need to adjust the
636 // stack pointer (we fit in the Red Zone). We also check that we don't
637 // push and pop from the stack.
638 if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
639 !RegInfo->needsStackRealignment(MF) &&
640 !MFI->hasVarSizedObjects() && // No dynamic alloca.
641 !MFI->adjustsStack() && // No calls.
642 !IsWin64CC && // Win64 has no Red Zone
643 !usesTheStack(MF) && // Don't push and pop.
644 !MF.shouldSplitStack()) { // Regular stack
645 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
646 if (HasFP) MinSize += SlotSize;
647 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
648 MFI->setStackSize(StackSize);
651 // Insert stack pointer adjustment for later moving of return addr. Only
652 // applies to tail call optimized functions where the callee argument stack
653 // size is bigger than the callers.
654 if (TailCallReturnAddrDelta < 0) {
656 BuildMI(MBB, MBBI, DL,
657 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
660 .addImm(-TailCallReturnAddrDelta)
661 .setMIFlag(MachineInstr::FrameSetup);
662 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
665 // Mapping for machine moves:
667 // DST: VirtualFP AND
668 // SRC: VirtualFP => DW_CFA_def_cfa_offset
669 // ELSE => DW_CFA_def_cfa
671 // SRC: VirtualFP AND
672 // DST: Register => DW_CFA_def_cfa_register
675 // OFFSET < 0 => DW_CFA_offset_extended_sf
676 // REG < 64 => DW_CFA_offset + Reg
677 // ELSE => DW_CFA_offset_extended
679 uint64_t NumBytes = 0;
680 int stackGrowth = -SlotSize;
683 // Calculate required stack adjustment.
684 uint64_t FrameSize = StackSize - SlotSize;
685 // If required, include space for extra hidden slot for stashing base pointer.
686 if (X86FI->getRestoreBasePointer())
687 FrameSize += SlotSize;
689 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
691 // Callee-saved registers are pushed on stack before the stack is realigned.
692 if (RegInfo->needsStackRealignment(MF) && !IsWin64Prologue)
693 NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
695 // Get the offset of the stack slot for the EBP register, which is
696 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
697 // Update the frame offset adjustment.
698 MFI->setOffsetAdjustment(-NumBytes);
700 // Save EBP/RBP into the appropriate stack slot.
701 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
702 .addReg(MachineFramePtr, RegState::Kill)
703 .setMIFlag(MachineInstr::FrameSetup);
706 // Mark the place where EBP/RBP was saved.
707 // Define the current CFA rule to use the provided offset.
709 BuildCFI(MBB, MBBI, DL,
710 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
712 // Change the rule for the FramePtr to be an "offset" rule.
713 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
714 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createOffset(
715 nullptr, DwarfFramePtr, 2 * stackGrowth));
719 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
721 .setMIFlag(MachineInstr::FrameSetup);
724 if (!IsWin64Prologue) {
725 // Update EBP with the new base value.
726 BuildMI(MBB, MBBI, DL,
727 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
730 .setMIFlag(MachineInstr::FrameSetup);
734 // Mark effective beginning of when frame pointer becomes valid.
735 // Define the current CFA to use the EBP/RBP register.
736 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
737 BuildCFI(MBB, MBBI, DL,
738 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
741 // Mark the FramePtr as live-in in every block.
742 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
743 I->addLiveIn(MachineFramePtr);
745 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
748 // Skip the callee-saved push instructions.
749 bool PushedRegs = false;
750 int StackOffset = 2 * stackGrowth;
752 while (MBBI != MBB.end() &&
753 (MBBI->getOpcode() == X86::PUSH32r ||
754 MBBI->getOpcode() == X86::PUSH64r)) {
756 unsigned Reg = MBBI->getOperand(0).getReg();
759 if (!HasFP && NeedsDwarfCFI) {
760 // Mark callee-saved push instruction.
761 // Define the current CFA rule to use the provided offset.
763 BuildCFI(MBB, MBBI, DL,
764 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
765 StackOffset += stackGrowth;
769 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
770 MachineInstr::FrameSetup);
774 // Realign stack after we pushed callee-saved registers (so that we'll be
775 // able to calculate their offsets from the frame pointer).
776 // Don't do this for Win64, it needs to realign the stack after the prologue.
777 if (!IsWin64Prologue && RegInfo->needsStackRealignment(MF)) {
778 assert(HasFP && "There should be a frame pointer if stack is realigned.");
779 BuildStackAlignAND(MBB, MBBI, DL, MaxAlign);
782 // If there is an SUB32ri of ESP immediately before this instruction, merge
783 // the two. This can be the case when tail call elimination is enabled and
784 // the callee has more arguments then the caller.
785 NumBytes -= mergeSPUpdates(MBB, MBBI, true);
787 // Adjust stack pointer: ESP -= numbytes.
789 // Windows and cygwin/mingw require a prologue helper routine when allocating
790 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
791 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
792 // stack and adjust the stack pointer in one go. The 64-bit version of
793 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
794 // responsible for adjusting the stack pointer. Touching the stack at 4K
795 // increments is necessary to ensure that the guard pages used by the OS
796 // virtual memory manager are allocated in correct sequence.
797 uint64_t AlignedNumBytes = NumBytes;
798 if (IsWin64Prologue && RegInfo->needsStackRealignment(MF))
799 AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
800 if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
801 // Check whether EAX is livein for this function.
802 bool isEAXAlive = isEAXLiveIn(MF);
805 // Sanity check that EAX is not livein for this function.
806 // It should not be, so throw an assert.
807 assert(!Is64Bit && "EAX is livein in x64 case!");
810 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
811 .addReg(X86::EAX, RegState::Kill)
812 .setMIFlag(MachineInstr::FrameSetup);
816 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
817 // Function prologue is responsible for adjusting the stack pointer.
818 if (isUInt<32>(NumBytes)) {
819 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
821 .setMIFlag(MachineInstr::FrameSetup);
822 } else if (isInt<32>(NumBytes)) {
823 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
825 .setMIFlag(MachineInstr::FrameSetup);
827 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
829 .setMIFlag(MachineInstr::FrameSetup);
832 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
833 // We'll also use 4 already allocated bytes for EAX.
834 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
835 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
836 .setMIFlag(MachineInstr::FrameSetup);
839 // Save a pointer to the MI where we set AX.
840 MachineBasicBlock::iterator SetRAX = MBBI;
843 // Call __chkstk, __chkstk_ms, or __alloca.
844 emitStackProbeCall(MF, MBB, MBBI, DL);
846 // Apply the frame setup flag to all inserted instrs.
847 for (; SetRAX != MBBI; ++SetRAX)
848 SetRAX->setFlag(MachineInstr::FrameSetup);
852 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
854 StackPtr, false, NumBytes - 4);
855 MI->setFlag(MachineInstr::FrameSetup);
856 MBB.insert(MBBI, MI);
858 } else if (NumBytes) {
859 emitSPUpdate(MBB, MBBI, -(int64_t)NumBytes, UseLEA);
862 if (NeedsWinCFI && NumBytes)
863 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
865 .setMIFlag(MachineInstr::FrameSetup);
867 int SEHFrameOffset = 0;
868 if (IsWin64Prologue && HasFP) {
869 SEHFrameOffset = calculateSetFPREG(NumBytes);
871 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
872 StackPtr, false, SEHFrameOffset);
874 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr).addReg(StackPtr);
877 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
879 .addImm(SEHFrameOffset)
880 .setMIFlag(MachineInstr::FrameSetup);
883 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
884 const MachineInstr *FrameInstr = &*MBBI;
889 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
890 if (X86::FR64RegClass.contains(Reg)) {
891 int Offset = getFrameIndexOffset(MF, FI);
892 Offset += SEHFrameOffset;
894 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
897 .setMIFlag(MachineInstr::FrameSetup);
904 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
905 .setMIFlag(MachineInstr::FrameSetup);
907 // Realign stack after we spilled callee-saved registers (so that we'll be
908 // able to calculate their offsets from the frame pointer).
909 // Win64 requires aligning the stack after the prologue.
910 if (IsWin64Prologue && RegInfo->needsStackRealignment(MF)) {
911 assert(HasFP && "There should be a frame pointer if stack is realigned.");
912 BuildStackAlignAND(MBB, MBBI, DL, MaxAlign);
915 // If we need a base pointer, set it up here. It's whatever the value
916 // of the stack pointer is at this point. Any variable size objects
917 // will be allocated after this, so we can still use the base pointer
918 // to reference locals.
919 if (RegInfo->hasBasePointer(MF)) {
920 // Update the base pointer with the current stack pointer.
921 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
922 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
924 .setMIFlag(MachineInstr::FrameSetup);
925 if (X86FI->getRestoreBasePointer()) {
926 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
927 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
928 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
929 FramePtr, true, X86FI->getRestoreBasePointerOffset())
931 .setMIFlag(MachineInstr::FrameSetup);
935 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
936 // Mark end of stack pointer adjustment.
937 if (!HasFP && NumBytes) {
938 // Define the current CFA rule to use the provided offset.
940 BuildCFI(MBB, MBBI, DL, MCCFIInstruction::createDefCfaOffset(
941 nullptr, -StackSize + stackGrowth));
944 // Emit DWARF info specifying the offsets of the callee-saved registers.
946 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
950 bool X86FrameLowering::canUseLEAForSPInEpilogue(
951 const MachineFunction &MF) const {
952 // We can't use LEA instructions for adjusting the stack pointer if this is a
953 // leaf function in the Win64 ABI. Only ADD instructions may be used to
954 // deallocate the stack.
955 // This means that we can use LEA for SP in two situations:
956 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
957 // 2. We *have* a frame pointer which means we are permitted to use LEA.
958 return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
961 /// Check whether or not the terminators of \p MBB needs to read EFLAGS.
962 static bool terminatorsNeedFlagsAsInput(const MachineBasicBlock &MBB) {
963 for (const MachineInstr &MI : MBB.terminators()) {
964 bool BreakNext = false;
965 for (const MachineOperand &MO : MI.operands()) {
968 unsigned Reg = MO.getReg();
969 if (Reg != X86::EFLAGS)
972 // This terminator needs an eflag that is not defined
973 // by a previous terminator.
984 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
985 MachineBasicBlock &MBB) const {
986 const MachineFrameInfo *MFI = MF.getFrameInfo();
987 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
988 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
990 if (MBBI != MBB.end())
991 DL = MBBI->getDebugLoc();
992 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
993 const bool Is64BitILP32 = STI.isTarget64BitILP32();
994 unsigned FramePtr = RegInfo->getFrameRegister(MF);
995 unsigned MachineFramePtr =
996 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
999 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1001 IsWin64Prologue && MF.getFunction()->needsUnwindTableEntry();
1002 bool UseLEAForSP = canUseLEAForSPInEpilogue(MF);
1003 // If we can use LEA for SP but we shouldn't, check that none
1004 // of the terminators uses the eflags. Otherwise we will insert
1005 // a ADD that will redefine the eflags and break the condition.
1006 // Alternatively, we could move the ADD, but this may not be possible
1007 // and is an optimization anyway.
1008 if (UseLEAForSP && !STI.useLeaForSP())
1009 UseLEAForSP = terminatorsNeedFlagsAsInput(MBB);
1010 // If that assert breaks, that means we do not do the right thing
1011 // in canUseAsEpilogue.
1012 assert((UseLEAForSP || !terminatorsNeedFlagsAsInput(MBB)) &&
1013 "We shouldn't have allowed this insertion point");
1015 // Get the number of bytes to allocate from the FrameInfo.
1016 uint64_t StackSize = MFI->getStackSize();
1017 uint64_t MaxAlign = calculateMaxStackAlign(MF);
1018 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1019 uint64_t NumBytes = 0;
1022 // Calculate required stack adjustment.
1023 uint64_t FrameSize = StackSize - SlotSize;
1024 NumBytes = FrameSize - CSSize;
1026 // Callee-saved registers were pushed on stack before the stack was
1028 if (RegInfo->needsStackRealignment(MF) && !IsWin64Prologue)
1029 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1032 BuildMI(MBB, MBBI, DL,
1033 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1035 NumBytes = StackSize - CSSize;
1037 uint64_t SEHStackAllocAmt = NumBytes;
1039 // Skip the callee-saved pop instructions.
1040 while (MBBI != MBB.begin()) {
1041 MachineBasicBlock::iterator PI = std::prev(MBBI);
1042 unsigned Opc = PI->getOpcode();
1044 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1045 !PI->isTerminator())
1050 MachineBasicBlock::iterator FirstCSPop = MBBI;
1052 if (MBBI != MBB.end())
1053 DL = MBBI->getDebugLoc();
1055 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1056 // instruction, merge the two instructions.
1057 if (NumBytes || MFI->hasVarSizedObjects())
1058 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1060 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1061 // slot before popping them off! Same applies for the case, when stack was
1063 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1064 if (RegInfo->needsStackRealignment(MF))
1066 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1067 uint64_t LEAAmount =
1068 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1070 // There are only two legal forms of epilogue:
1071 // - add SEHAllocationSize, %rsp
1072 // - lea SEHAllocationSize(%FramePtr), %rsp
1074 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1075 // However, we may use this sequence if we have a frame pointer because the
1076 // effects of the prologue can safely be undone.
1077 if (LEAAmount != 0) {
1078 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1079 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1080 FramePtr, false, LEAAmount);
1083 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1084 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1088 } else if (NumBytes) {
1089 // Adjust stack pointer back: ESP += numbytes.
1090 emitSPUpdate(MBB, MBBI, NumBytes, UseLEAForSP);
1094 // Windows unwinder will not invoke function's exception handler if IP is
1095 // either in prologue or in epilogue. This behavior causes a problem when a
1096 // call immediately precedes an epilogue, because the return address points
1097 // into the epilogue. To cope with that, we insert an epilogue marker here,
1098 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1099 // final emitted code.
1101 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1103 // Add the return addr area delta back since we are not tail calling.
1104 int Offset = -1 * X86FI->getTCReturnAddrDelta();
1105 assert(Offset >= 0 && "TCDelta should never be positive");
1107 MBBI = MBB.getFirstTerminator();
1109 // Check for possible merge with preceding ADD instruction.
1110 Offset += mergeSPUpdates(MBB, MBBI, true);
1111 emitSPUpdate(MBB, MBBI, Offset, UseLEAForSP);
1115 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1117 const MachineFrameInfo *MFI = MF.getFrameInfo();
1118 // Offset will hold the offset from the stack pointer at function entry to the
1120 // We need to factor in additional offsets applied during the prologue to the
1121 // frame, base, and stack pointer depending on which is used.
1122 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1123 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1124 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1125 uint64_t StackSize = MFI->getStackSize();
1126 bool HasFP = hasFP(MF);
1127 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1128 int64_t FPDelta = 0;
1130 if (IsWin64Prologue) {
1131 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1133 // Calculate required stack adjustment.
1134 uint64_t FrameSize = StackSize - SlotSize;
1135 // If required, include space for extra hidden slot for stashing base pointer.
1136 if (X86FI->getRestoreBasePointer())
1137 FrameSize += SlotSize;
1138 uint64_t NumBytes = FrameSize - CSSize;
1140 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1141 if (FI && FI == X86FI->getFAIndex())
1142 return -SEHFrameOffset;
1144 // FPDelta is the offset from the "traditional" FP location of the old base
1145 // pointer followed by return address and the location required by the
1146 // restricted Win64 prologue.
1147 // Add FPDelta to all offsets below that go through the frame pointer.
1148 FPDelta = FrameSize - SEHFrameOffset;
1149 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1150 "FPDelta isn't aligned per the Win64 ABI!");
1154 if (RegInfo->hasBasePointer(MF)) {
1155 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1157 // Skip the saved EBP.
1158 return Offset + SlotSize + FPDelta;
1160 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1161 return Offset + StackSize;
1163 } else if (RegInfo->needsStackRealignment(MF)) {
1165 // Skip the saved EBP.
1166 return Offset + SlotSize + FPDelta;
1168 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1169 return Offset + StackSize;
1171 // FIXME: Support tail calls
1174 return Offset + StackSize;
1176 // Skip the saved EBP.
1179 // Skip the RETADDR move area
1180 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1181 if (TailCallReturnAddrDelta < 0)
1182 Offset -= TailCallReturnAddrDelta;
1185 return Offset + FPDelta;
1188 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1189 unsigned &FrameReg) const {
1190 // We can't calculate offset from frame pointer if the stack is realigned,
1191 // so enforce usage of stack/base pointer. The base pointer is used when we
1192 // have dynamic allocas in addition to dynamic realignment.
1193 if (RegInfo->hasBasePointer(MF))
1194 FrameReg = RegInfo->getBaseRegister();
1195 else if (RegInfo->needsStackRealignment(MF))
1196 FrameReg = RegInfo->getStackRegister();
1198 FrameReg = RegInfo->getFrameRegister(MF);
1199 return getFrameIndexOffset(MF, FI);
1202 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1203 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1204 const MachineFrameInfo *MFI = MF.getFrameInfo();
1205 // Does not include any dynamic realign.
1206 const uint64_t StackSize = MFI->getStackSize();
1209 // Note: LLVM arranges the stack as:
1210 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1211 // > "Stack Slots" (<--SP)
1212 // We can always address StackSlots from RSP. We can usually (unless
1213 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1214 // address them from RBP. FixedObjects can be placed anywhere in the stack
1215 // frame depending on their specific requirements (i.e. we can actually
1216 // refer to arguments to the function which are stored in the *callers*
1217 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1218 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1220 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1222 // We don't handle tail calls, and shouldn't be seeing them
1224 int TailCallReturnAddrDelta =
1225 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1226 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1230 // This is how the math works out:
1232 // %rsp grows (i.e. gets lower) left to right. Each box below is
1233 // one word (eight bytes). Obj0 is the stack slot we're trying to
1236 // ----------------------------------
1237 // | BP | Obj0 | Obj1 | ... | ObjN |
1238 // ----------------------------------
1242 // A is the incoming stack pointer.
1243 // (B - A) is the local area offset (-8 for x86-64) [1]
1244 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1246 // |(E - B)| is the StackSize (absolute value, positive). For a
1247 // stack that grown down, this works out to be (B - E). [3]
1249 // E is also the value of %rsp after stack has been set up, and we
1250 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1251 // (C - E) == (C - A) - (B - A) + (B - E)
1252 // { Using [1], [2] and [3] above }
1253 // == getObjectOffset - LocalAreaOffset + StackSize
1256 // Get the Offset from the StackPointer
1257 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1259 return Offset + StackSize;
1261 // Simplified from getFrameIndexReference keeping only StackPointer cases
1262 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1264 unsigned &FrameReg) const {
1265 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1267 FrameReg = RegInfo->getStackRegister();
1268 return getFrameIndexOffsetFromSP(MF, FI);
1271 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1272 MachineFunction &MF, const TargetRegisterInfo *TRI,
1273 std::vector<CalleeSavedInfo> &CSI) const {
1274 MachineFrameInfo *MFI = MF.getFrameInfo();
1275 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1277 unsigned CalleeSavedFrameSize = 0;
1278 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1281 // emitPrologue always spills frame register the first thing.
1282 SpillSlotOffset -= SlotSize;
1283 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1285 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1286 // the frame register, we can delete it from CSI list and not have to worry
1287 // about avoiding it later.
1288 unsigned FPReg = RegInfo->getFrameRegister(MF);
1289 for (unsigned i = 0; i < CSI.size(); ++i) {
1290 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1291 CSI.erase(CSI.begin() + i);
1297 // Assign slots for GPRs. It increases frame size.
1298 for (unsigned i = CSI.size(); i != 0; --i) {
1299 unsigned Reg = CSI[i - 1].getReg();
1301 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1304 SpillSlotOffset -= SlotSize;
1305 CalleeSavedFrameSize += SlotSize;
1307 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1308 CSI[i - 1].setFrameIdx(SlotIndex);
1311 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1313 // Assign slots for XMMs.
1314 for (unsigned i = CSI.size(); i != 0; --i) {
1315 unsigned Reg = CSI[i - 1].getReg();
1316 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1319 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1321 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1323 SpillSlotOffset -= RC->getSize();
1325 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1326 CSI[i - 1].setFrameIdx(SlotIndex);
1327 MFI->ensureMaxAlignment(RC->getAlignment());
1333 bool X86FrameLowering::spillCalleeSavedRegisters(
1334 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1335 const std::vector<CalleeSavedInfo> &CSI,
1336 const TargetRegisterInfo *TRI) const {
1337 DebugLoc DL = MBB.findDebugLoc(MI);
1339 // Push GPRs. It increases frame size.
1340 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1341 for (unsigned i = CSI.size(); i != 0; --i) {
1342 unsigned Reg = CSI[i - 1].getReg();
1344 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1346 // Add the callee-saved register as live-in. It's killed at the spill.
1349 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1350 .setMIFlag(MachineInstr::FrameSetup);
1353 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1354 // It can be done by spilling XMMs to stack frame.
1355 for (unsigned i = CSI.size(); i != 0; --i) {
1356 unsigned Reg = CSI[i-1].getReg();
1357 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1359 // Add the callee-saved register as live-in. It's killed at the spill.
1361 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1363 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1366 MI->setFlag(MachineInstr::FrameSetup);
1373 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1374 MachineBasicBlock::iterator MI,
1375 const std::vector<CalleeSavedInfo> &CSI,
1376 const TargetRegisterInfo *TRI) const {
1380 DebugLoc DL = MBB.findDebugLoc(MI);
1382 // Reload XMMs from stack frame.
1383 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1384 unsigned Reg = CSI[i].getReg();
1385 if (X86::GR64RegClass.contains(Reg) ||
1386 X86::GR32RegClass.contains(Reg))
1389 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1390 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1394 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1395 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1396 unsigned Reg = CSI[i].getReg();
1397 if (!X86::GR64RegClass.contains(Reg) &&
1398 !X86::GR32RegClass.contains(Reg))
1401 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1407 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1408 RegScavenger *RS) const {
1409 MachineFrameInfo *MFI = MF.getFrameInfo();
1411 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1412 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1414 if (TailCallReturnAddrDelta < 0) {
1415 // create RETURNADDR area
1424 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1425 TailCallReturnAddrDelta - SlotSize, true);
1428 // Spill the BasePtr if it's used.
1429 if (RegInfo->hasBasePointer(MF))
1430 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1434 HasNestArgument(const MachineFunction *MF) {
1435 const Function *F = MF->getFunction();
1436 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1438 if (I->hasNestAttr())
1444 /// GetScratchRegister - Get a temp register for performing work in the
1445 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1446 /// and the properties of the function either one or two registers will be
1447 /// needed. Set primary to true for the first register, false for the second.
1449 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1450 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1453 if (CallingConvention == CallingConv::HiPE) {
1455 return Primary ? X86::R14 : X86::R13;
1457 return Primary ? X86::EBX : X86::EDI;
1462 return Primary ? X86::R11 : X86::R12;
1464 return Primary ? X86::R11D : X86::R12D;
1467 bool IsNested = HasNestArgument(&MF);
1469 if (CallingConvention == CallingConv::X86_FastCall ||
1470 CallingConvention == CallingConv::Fast) {
1472 report_fatal_error("Segmented stacks does not support fastcall with "
1473 "nested function.");
1474 return Primary ? X86::EAX : X86::ECX;
1477 return Primary ? X86::EDX : X86::EAX;
1478 return Primary ? X86::ECX : X86::EAX;
1481 // The stack limit in the TCB is set to this many bytes above the actual stack
1483 static const uint64_t kSplitStackAvailable = 256;
1485 void X86FrameLowering::adjustForSegmentedStacks(
1486 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1487 MachineFrameInfo *MFI = MF.getFrameInfo();
1489 unsigned TlsReg, TlsOffset;
1492 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1493 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1494 "Scratch register is live-in");
1496 if (MF.getFunction()->isVarArg())
1497 report_fatal_error("Segmented stacks do not support vararg functions.");
1498 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1499 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1500 !STI.isTargetDragonFly())
1501 report_fatal_error("Segmented stacks not supported on this platform.");
1503 // Eventually StackSize will be calculated by a link-time pass; which will
1504 // also decide whether checking code needs to be injected into this particular
1506 StackSize = MFI->getStackSize();
1508 // Do not generate a prologue for functions with a stack of size zero
1512 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1513 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1514 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1515 bool IsNested = false;
1517 // We need to know if the function has a nest argument only in 64 bit mode.
1519 IsNested = HasNestArgument(&MF);
1521 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1522 // allocMBB needs to be last (terminating) instruction.
1524 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1525 e = PrologueMBB.livein_end();
1527 allocMBB->addLiveIn(*i);
1528 checkMBB->addLiveIn(*i);
1532 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1534 MF.push_front(allocMBB);
1535 MF.push_front(checkMBB);
1537 // When the frame size is less than 256 we just compare the stack
1538 // boundary directly to the value of the stack pointer, per gcc.
1539 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1541 // Read the limit off the current stacklet off the stack_guard location.
1543 if (STI.isTargetLinux()) {
1545 TlsOffset = IsLP64 ? 0x70 : 0x40;
1546 } else if (STI.isTargetDarwin()) {
1548 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1549 } else if (STI.isTargetWin64()) {
1551 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1552 } else if (STI.isTargetFreeBSD()) {
1555 } else if (STI.isTargetDragonFly()) {
1557 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1559 report_fatal_error("Segmented stacks not supported on this platform.");
1562 if (CompareStackPointer)
1563 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1565 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1566 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1568 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1569 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1571 if (STI.isTargetLinux()) {
1574 } else if (STI.isTargetDarwin()) {
1576 TlsOffset = 0x48 + 90*4;
1577 } else if (STI.isTargetWin32()) {
1579 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1580 } else if (STI.isTargetDragonFly()) {
1582 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1583 } else if (STI.isTargetFreeBSD()) {
1584 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1586 report_fatal_error("Segmented stacks not supported on this platform.");
1589 if (CompareStackPointer)
1590 ScratchReg = X86::ESP;
1592 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1593 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1595 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1596 STI.isTargetDragonFly()) {
1597 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1598 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1599 } else if (STI.isTargetDarwin()) {
1601 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1602 unsigned ScratchReg2;
1604 if (CompareStackPointer) {
1605 // The primary scratch register is available for holding the TLS offset.
1606 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1607 SaveScratch2 = false;
1609 // Need to use a second register to hold the TLS offset
1610 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1612 // Unfortunately, with fastcc the second scratch register may hold an
1614 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1617 // If Scratch2 is live-in then it needs to be saved.
1618 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1619 "Scratch register is live-in and not saved");
1622 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1623 .addReg(ScratchReg2, RegState::Kill);
1625 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1627 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1629 .addReg(ScratchReg2).addImm(1).addReg(0)
1634 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1638 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1639 // It jumps to normal execution of the function body.
1640 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
1642 // On 32 bit we first push the arguments size and then the frame size. On 64
1643 // bit, we pass the stack frame size in r10 and the argument size in r11.
1645 // Functions with nested arguments use R10, so it needs to be saved across
1646 // the call to _morestack
1648 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1649 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1650 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1651 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1652 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1655 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1657 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1659 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1660 .addImm(X86FI->getArgumentStackSize());
1661 MF.getRegInfo().setPhysRegUsed(Reg10);
1662 MF.getRegInfo().setPhysRegUsed(Reg11);
1664 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1665 .addImm(X86FI->getArgumentStackSize());
1666 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1670 // __morestack is in libgcc
1671 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1672 // Under the large code model, we cannot assume that __morestack lives
1673 // within 2^31 bytes of the call site, so we cannot use pc-relative
1674 // addressing. We cannot perform the call via a temporary register,
1675 // as the rax register may be used to store the static chain, and all
1676 // other suitable registers may be either callee-save or used for
1677 // parameter passing. We cannot use the stack at this point either
1678 // because __morestack manipulates the stack directly.
1680 // To avoid these issues, perform an indirect call via a read-only memory
1681 // location containing the address.
1683 // This solution is not perfect, as it assumes that the .rodata section
1684 // is laid out within 2^31 bytes of each function body, but this seems
1685 // to be sufficient for JIT.
1686 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1690 .addExternalSymbol("__morestack_addr")
1692 MF.getMMI().setUsesMorestackAddr(true);
1695 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1696 .addExternalSymbol("__morestack");
1698 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1699 .addExternalSymbol("__morestack");
1703 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1705 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1707 allocMBB->addSuccessor(&PrologueMBB);
1709 checkMBB->addSuccessor(allocMBB);
1710 checkMBB->addSuccessor(&PrologueMBB);
1717 /// Erlang programs may need a special prologue to handle the stack size they
1718 /// might need at runtime. That is because Erlang/OTP does not implement a C
1719 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1720 /// (for more information see Eric Stenman's Ph.D. thesis:
1721 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1724 /// temp0 = sp - MaxStack
1725 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1729 /// call inc_stack # doubles the stack space
1730 /// temp0 = sp - MaxStack
1731 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1732 void X86FrameLowering::adjustForHiPEPrologue(
1733 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1734 MachineFrameInfo *MFI = MF.getFrameInfo();
1736 // HiPE-specific values
1737 const unsigned HipeLeafWords = 24;
1738 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1739 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1740 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1741 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1742 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1744 assert(STI.isTargetLinux() &&
1745 "HiPE prologue is only supported on Linux operating systems.");
1747 // Compute the largest caller's frame that is needed to fit the callees'
1748 // frames. This 'MaxStack' is computed from:
1750 // a) the fixed frame size, which is the space needed for all spilled temps,
1751 // b) outgoing on-stack parameter areas, and
1752 // c) the minimum stack space this function needs to make available for the
1753 // functions it calls (a tunable ABI property).
1754 if (MFI->hasCalls()) {
1755 unsigned MoreStackForCalls = 0;
1757 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1758 MBBI != MBBE; ++MBBI)
1759 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1764 // Get callee operand.
1765 const MachineOperand &MO = MI->getOperand(0);
1767 // Only take account of global function calls (no closures etc.).
1771 const Function *F = dyn_cast<Function>(MO.getGlobal());
1775 // Do not update 'MaxStack' for primitive and built-in functions
1776 // (encoded with names either starting with "erlang."/"bif_" or not
1777 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1778 // "_", such as the BIF "suspend_0") as they are executed on another
1780 if (F->getName().find("erlang.") != StringRef::npos ||
1781 F->getName().find("bif_") != StringRef::npos ||
1782 F->getName().find_first_of("._") == StringRef::npos)
1785 unsigned CalleeStkArity =
1786 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1787 if (HipeLeafWords - 1 > CalleeStkArity)
1788 MoreStackForCalls = std::max(MoreStackForCalls,
1789 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1791 MaxStack += MoreStackForCalls;
1794 // If the stack frame needed is larger than the guaranteed then runtime checks
1795 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1796 if (MaxStack > Guaranteed) {
1797 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1798 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1800 for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1801 E = PrologueMBB.livein_end();
1803 stackCheckMBB->addLiveIn(*I);
1804 incStackMBB->addLiveIn(*I);
1807 MF.push_front(incStackMBB);
1808 MF.push_front(stackCheckMBB);
1810 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1811 unsigned LEAop, CMPop, CALLop;
1815 LEAop = X86::LEA64r;
1816 CMPop = X86::CMP64rm;
1817 CALLop = X86::CALL64pcrel32;
1818 SPLimitOffset = 0x90;
1822 LEAop = X86::LEA32r;
1823 CMPop = X86::CMP32rm;
1824 CALLop = X86::CALLpcrel32;
1825 SPLimitOffset = 0x4c;
1828 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1829 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1830 "HiPE prologue scratch register is live-in");
1832 // Create new MBB for StackCheck:
1833 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1834 SPReg, false, -MaxStack);
1835 // SPLimitOffset is in a fixed heap location (pointed by BP).
1836 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1837 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1838 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
1840 // Create new MBB for IncStack:
1841 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1842 addExternalSymbol("inc_stack_0");
1843 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1844 SPReg, false, -MaxStack);
1845 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1846 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1847 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1849 stackCheckMBB->addSuccessor(&PrologueMBB, 99);
1850 stackCheckMBB->addSuccessor(incStackMBB, 1);
1851 incStackMBB->addSuccessor(&PrologueMBB, 99);
1852 incStackMBB->addSuccessor(incStackMBB, 1);
1859 void X86FrameLowering::
1860 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1861 MachineBasicBlock::iterator I) const {
1862 bool reserveCallFrame = hasReservedCallFrame(MF);
1863 unsigned Opcode = I->getOpcode();
1864 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1865 DebugLoc DL = I->getDebugLoc();
1866 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1867 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1870 if (!reserveCallFrame) {
1871 // If the stack pointer can be changed after prologue, turn the
1872 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1873 // adjcallstackdown instruction into 'add ESP, <amt>'
1877 // We need to keep the stack aligned properly. To do this, we round the
1878 // amount of space needed for the outgoing arguments up to the next
1879 // alignment boundary.
1880 unsigned StackAlign = getStackAlignment();
1881 Amount = RoundUpToAlignment(Amount, StackAlign);
1883 MachineInstr *New = nullptr;
1885 // Factor out the amount that gets handled inside the sequence
1886 // (Pushes of argument for frame setup, callee pops for frame destroy)
1887 Amount -= InternalAmt;
1890 if (Opcode == TII.getCallFrameSetupOpcode()) {
1891 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1892 .addReg(StackPtr).addImm(Amount);
1894 assert(Opcode == TII.getCallFrameDestroyOpcode());
1896 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1897 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1898 .addReg(StackPtr).addImm(Amount);
1903 // The EFLAGS implicit def is dead.
1904 New->getOperand(3).setIsDead();
1906 // Replace the pseudo instruction with a new instruction.
1913 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
1914 // If we are performing frame pointer elimination and if the callee pops
1915 // something off the stack pointer, add it back. We do this until we have
1916 // more advanced stack pointer tracking ability.
1917 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
1918 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1919 .addReg(StackPtr).addImm(InternalAmt);
1921 // The EFLAGS implicit def is dead.
1922 New->getOperand(3).setIsDead();
1924 // We are not tracking the stack pointer adjustment by the callee, so make
1925 // sure we restore the stack pointer immediately after the call, there may
1926 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1927 MachineBasicBlock::iterator B = MBB.begin();
1928 while (I != B && !std::prev(I)->isCall())
1934 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1935 assert(MBB.getParent() && "Block is not attached to a function!");
1937 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
1940 // If we cannot use LEA to adjust SP, we may need to use ADD, which
1941 // clobbers the EFLAGS. Check that none of the terminators reads the
1942 // EFLAGS, and if one uses it, conservatively assume this is not
1943 // safe to insert the epilogue here.
1944 return !terminatorsNeedFlagsAsInput(MBB);