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 bool X86FrameLowering::hasReservedCallFrame(const MachineFunction &MF) const {
41 return !MF.getFrameInfo()->hasVarSizedObjects() &&
42 !MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
45 /// canSimplifyCallFramePseudos - If there is a reserved call frame, the
46 /// call frame pseudos can be simplified. Having a FP, as in the default
47 /// implementation, is not sufficient here since we can't always use it.
48 /// Use a more nuanced condition.
50 X86FrameLowering::canSimplifyCallFramePseudos(const MachineFunction &MF) const {
51 const X86RegisterInfo *TRI = static_cast<const X86RegisterInfo *>
52 (MF.getSubtarget().getRegisterInfo());
53 return hasReservedCallFrame(MF) ||
54 (hasFP(MF) && !TRI->needsStackRealignment(MF))
55 || TRI->hasBasePointer(MF);
58 // needsFrameIndexResolution - Do we need to perform FI resolution for
59 // this function. Normally, this is required only when the function
60 // has any stack objects. However, FI resolution actually has another job,
61 // not apparent from the title - it resolves callframesetup/destroy
62 // that were not simplified earlier.
63 // So, this is required for x86 functions that have push sequences even
64 // when there are no stack objects.
66 X86FrameLowering::needsFrameIndexResolution(const MachineFunction &MF) const {
67 return MF.getFrameInfo()->hasStackObjects() ||
68 MF.getInfo<X86MachineFunctionInfo>()->getHasPushSequences();
71 /// hasFP - Return true if the specified function should have a dedicated frame
72 /// pointer register. This is true if the function has variable sized allocas
73 /// or if frame pointer elimination is disabled.
74 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
75 const MachineFrameInfo *MFI = MF.getFrameInfo();
76 const MachineModuleInfo &MMI = MF.getMMI();
77 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
79 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
80 RegInfo->needsStackRealignment(MF) ||
81 MFI->hasVarSizedObjects() ||
82 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
83 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
84 MMI.callsUnwindInit() || MMI.callsEHReturn() ||
85 MFI->hasStackMap() || MFI->hasPatchPoint());
88 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
92 return X86::SUB64ri32;
100 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
103 return X86::ADD64ri8;
104 return X86::ADD64ri32;
107 return X86::ADD32ri8;
112 static unsigned getSUBrrOpcode(unsigned isLP64) {
113 return isLP64 ? X86::SUB64rr : X86::SUB32rr;
116 static unsigned getADDrrOpcode(unsigned isLP64) {
117 return isLP64 ? X86::ADD64rr : X86::ADD32rr;
120 static unsigned getANDriOpcode(bool IsLP64, int64_t Imm) {
123 return X86::AND64ri8;
124 return X86::AND64ri32;
127 return X86::AND32ri8;
131 static unsigned getLEArOpcode(unsigned IsLP64) {
132 return IsLP64 ? X86::LEA64r : X86::LEA32r;
135 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
136 /// when it reaches the "return" instruction. We can then pop a stack object
137 /// to this register without worry about clobbering it.
138 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
139 MachineBasicBlock::iterator &MBBI,
140 const TargetRegisterInfo &TRI,
142 const MachineFunction *MF = MBB.getParent();
143 const Function *F = MF->getFunction();
144 if (!F || MF->getMMI().callsEHReturn())
147 static const uint16_t CallerSavedRegs32Bit[] = {
148 X86::EAX, X86::EDX, X86::ECX, 0
151 static const uint16_t CallerSavedRegs64Bit[] = {
152 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
153 X86::R8, X86::R9, X86::R10, X86::R11, 0
156 unsigned Opc = MBBI->getOpcode();
163 case X86::TCRETURNdi:
164 case X86::TCRETURNri:
165 case X86::TCRETURNmi:
166 case X86::TCRETURNdi64:
167 case X86::TCRETURNri64:
168 case X86::TCRETURNmi64:
170 case X86::EH_RETURN64: {
171 SmallSet<uint16_t, 8> Uses;
172 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
173 MachineOperand &MO = MBBI->getOperand(i);
174 if (!MO.isReg() || MO.isDef())
176 unsigned Reg = MO.getReg();
179 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
183 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
185 if (!Uses.count(*CS))
193 static bool isEAXLiveIn(MachineFunction &MF) {
194 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
195 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
196 unsigned Reg = II->first;
198 if (Reg == X86::RAX || Reg == X86::EAX || Reg == X86::AX ||
199 Reg == X86::AH || Reg == X86::AL)
206 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
207 /// stack pointer by a constant value.
208 void X86FrameLowering::emitSPUpdate(MachineBasicBlock &MBB,
209 MachineBasicBlock::iterator &MBBI,
210 unsigned StackPtr, int64_t NumBytes,
211 bool Is64BitTarget, bool Is64BitStackPtr,
212 bool UseLEA, const TargetInstrInfo &TII,
213 const TargetRegisterInfo &TRI) {
214 bool isSub = NumBytes < 0;
215 uint64_t Offset = isSub ? -NumBytes : NumBytes;
218 Opc = getLEArOpcode(Is64BitStackPtr);
221 ? getSUBriOpcode(Is64BitStackPtr, Offset)
222 : getADDriOpcode(Is64BitStackPtr, Offset);
224 uint64_t Chunk = (1LL << 31) - 1;
225 DebugLoc DL = MBB.findDebugLoc(MBBI);
228 if (Offset > Chunk) {
229 // Rather than emit a long series of instructions for large offsets,
230 // load the offset into a register and do one sub/add
233 if (isSub && !isEAXLiveIn(*MBB.getParent()))
234 Reg = (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX);
236 Reg = findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
239 Opc = Is64BitTarget ? X86::MOV64ri : X86::MOV32ri;
240 BuildMI(MBB, MBBI, DL, TII.get(Opc), Reg)
243 ? getSUBrrOpcode(Is64BitTarget)
244 : getADDrrOpcode(Is64BitTarget);
245 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
248 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
254 uint64_t ThisVal = std::min(Offset, Chunk);
255 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
256 // Use push / pop instead.
258 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
259 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
262 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
263 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
264 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
265 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
267 MI->setFlag(MachineInstr::FrameSetup);
273 MachineInstr *MI = nullptr;
276 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
277 StackPtr, false, isSub ? -ThisVal : ThisVal);
279 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
282 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
286 MI->setFlag(MachineInstr::FrameSetup);
292 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
294 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
295 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
296 if (MBBI == MBB.begin()) return;
298 MachineBasicBlock::iterator PI = std::prev(MBBI);
299 unsigned Opc = PI->getOpcode();
300 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
301 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
302 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
303 PI->getOperand(0).getReg() == StackPtr) {
305 *NumBytes += PI->getOperand(2).getImm();
307 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
308 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
309 PI->getOperand(0).getReg() == StackPtr) {
311 *NumBytes -= PI->getOperand(2).getImm();
316 int X86FrameLowering::mergeSPUpdates(MachineBasicBlock &MBB,
317 MachineBasicBlock::iterator &MBBI,
319 bool doMergeWithPrevious) {
320 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
321 (!doMergeWithPrevious && MBBI == MBB.end()))
324 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
325 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
327 unsigned Opc = PI->getOpcode();
330 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
331 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
332 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
333 PI->getOperand(0).getReg() == StackPtr){
334 Offset += PI->getOperand(2).getImm();
336 if (!doMergeWithPrevious) MBBI = NI;
337 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
338 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
339 PI->getOperand(0).getReg() == StackPtr) {
340 Offset -= PI->getOperand(2).getImm();
342 if (!doMergeWithPrevious) MBBI = NI;
348 /// Wraps up getting a CFI index and building a MachineInstr for it.
349 static void BuildCFI(MachineBasicBlock &MBB, MachineBasicBlock::iterator MBBI,
350 DebugLoc DL, const TargetInstrInfo &TII,
351 MCCFIInstruction CFIInst) {
352 MachineFunction &MF = *MBB.getParent();
353 unsigned CFIIndex = MF.getMMI().addFrameInst(CFIInst);
354 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
355 .addCFIIndex(CFIIndex);
359 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
360 MachineBasicBlock::iterator MBBI,
362 MachineFunction &MF = *MBB.getParent();
363 MachineFrameInfo *MFI = MF.getFrameInfo();
364 MachineModuleInfo &MMI = MF.getMMI();
365 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
366 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
368 // Add callee saved registers to move list.
369 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
370 if (CSI.empty()) return;
372 // Calculate offsets.
373 for (std::vector<CalleeSavedInfo>::const_iterator
374 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
375 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
376 unsigned Reg = I->getReg();
378 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
379 BuildCFI(MBB, MBBI, DL, TII,
380 MCCFIInstruction::createOffset(nullptr, DwarfReg, Offset));
384 /// usesTheStack - This function checks if any of the users of EFLAGS
385 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
386 /// to use the stack, and if we don't adjust the stack we clobber the first
388 /// See X86InstrInfo::copyPhysReg.
389 static bool usesTheStack(const MachineFunction &MF) {
390 const MachineRegisterInfo &MRI = MF.getRegInfo();
392 for (MachineRegisterInfo::reg_instr_iterator
393 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
401 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
402 MachineBasicBlock &MBB,
403 MachineBasicBlock::iterator MBBI,
405 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
406 const TargetInstrInfo &TII = *STI.getInstrInfo();
407 bool Is64Bit = STI.is64Bit();
408 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
412 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
414 CallOp = X86::CALLpcrel32;
418 if (STI.isTargetCygMing()) {
419 Symbol = "___chkstk_ms";
423 } else if (STI.isTargetCygMing())
428 MachineInstrBuilder CI;
430 // All current stack probes take AX and SP as input, clobber flags, and
431 // preserve all registers. x86_64 probes leave RSP unmodified.
432 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
433 // For the large code model, we have to call through a register. Use R11,
434 // as it is scratch in all supported calling conventions.
435 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
436 .addExternalSymbol(Symbol);
437 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
439 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
442 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
443 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
444 CI.addReg(AX, RegState::Implicit)
445 .addReg(SP, RegState::Implicit)
446 .addReg(AX, RegState::Define | RegState::Implicit)
447 .addReg(SP, RegState::Define | RegState::Implicit)
448 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
451 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
452 // themselves. It also does not clobber %rax so we can reuse it when
454 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
460 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
461 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
462 // and might require smaller successive adjustments.
463 const uint64_t Win64MaxSEHOffset = 128;
464 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
465 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
466 return SEHFrameOffset & -16;
469 // If we're forcing a stack realignment we can't rely on just the frame
470 // info, we need to know the ABI stack alignment as well in case we
471 // have a call out. Otherwise just make sure we have some alignment - we'll
472 // go with the minimum SlotSize.
473 static uint64_t calculateMaxStackAlign(const MachineFunction &MF) {
474 const MachineFrameInfo *MFI = MF.getFrameInfo();
475 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
476 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
477 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
478 unsigned SlotSize = RegInfo->getSlotSize();
479 unsigned StackAlign = STI.getFrameLowering()->getStackAlignment();
480 if (ForceStackAlign) {
482 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
483 else if (MaxAlign < SlotSize)
489 /// emitPrologue - Push callee-saved registers onto the stack, which
490 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
491 /// space for local variables. Also emit labels used by the exception handler to
492 /// generate the exception handling frames.
495 Here's a gist of what gets emitted:
497 ; Establish frame pointer, if needed
500 .cfi_def_cfa_offset 16
501 .cfi_offset %rbp, -16
504 .cfi_def_cfa_register %rbp
506 ; Spill general-purpose registers
507 [for all callee-saved GPRs]
510 .cfi_def_cfa_offset (offset from RETADDR)
513 ; If the required stack alignment > default stack alignment
514 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
515 ; of unknown size in the stack frame.
516 [if stack needs re-alignment]
519 ; Allocate space for locals
520 [if target is Windows and allocated space > 4096 bytes]
521 ; Windows needs special care for allocations larger
524 call ___chkstk_ms/___chkstk
530 .seh_stackalloc (size of XMM spill slots)
531 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
536 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
537 ; they may get spilled on any platform, if the current function
538 ; calls @llvm.eh.unwind.init
540 [for all callee-saved XMM registers]
541 movaps %<xmm reg>, -MMM(%rbp)
542 [for all callee-saved XMM registers]
543 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
544 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
546 [for all callee-saved XMM registers]
547 movaps %<xmm reg>, KKK(%rsp)
548 [for all callee-saved XMM registers]
549 .seh_savexmm %<xmm reg>, KKK
553 [if needs base pointer]
555 [if needs to restore base pointer]
560 [for all callee-saved registers]
561 .cfi_offset %<reg>, (offset from %rbp)
563 .cfi_def_cfa_offset (offset from RETADDR)
564 [for all callee-saved registers]
565 .cfi_offset %<reg>, (offset from %rsp)
568 - .seh directives are emitted only for Windows 64 ABI
569 - .cfi directives are emitted for all other ABIs
570 - for 32-bit code, substitute %e?? registers for %r??
573 void X86FrameLowering::emitPrologue(MachineFunction &MF,
574 MachineBasicBlock &MBB) const {
575 MachineBasicBlock::iterator MBBI = MBB.begin();
576 MachineFrameInfo *MFI = MF.getFrameInfo();
577 const Function *Fn = MF.getFunction();
578 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
579 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
580 const TargetInstrInfo &TII = *STI.getInstrInfo();
581 MachineModuleInfo &MMI = MF.getMMI();
582 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
583 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
584 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
585 bool HasFP = hasFP(MF);
586 bool Is64Bit = STI.is64Bit();
587 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
588 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
589 bool IsWin64CC = STI.isCallingConvWin64(Fn->getCallingConv());
590 // Not necessarily synonymous with IsWin64CC.
591 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
592 bool NeedsWinCFI = IsWin64Prologue && Fn->needsUnwindTableEntry();
594 !IsWin64Prologue && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
595 bool UseLEA = STI.useLeaForSP();
596 unsigned SlotSize = RegInfo->getSlotSize();
597 unsigned FramePtr = RegInfo->getFrameRegister(MF);
598 const unsigned MachineFramePtr =
599 STI.isTarget64BitILP32()
600 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
602 unsigned StackPtr = RegInfo->getStackRegister();
603 unsigned BasePtr = RegInfo->getBaseRegister();
606 // Add RETADDR move area to callee saved frame size.
607 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
608 if (TailCallReturnAddrDelta && IsWin64Prologue)
609 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
611 if (TailCallReturnAddrDelta < 0)
612 X86FI->setCalleeSavedFrameSize(
613 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
615 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
617 // The default stack probe size is 4096 if the function has no stackprobesize
619 unsigned StackProbeSize = 4096;
620 if (Fn->hasFnAttribute("stack-probe-size"))
621 Fn->getFnAttribute("stack-probe-size")
623 .getAsInteger(0, StackProbeSize);
625 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
626 // function, and use up to 128 bytes of stack space, don't have a frame
627 // pointer, calls, or dynamic alloca then we do not need to adjust the
628 // stack pointer (we fit in the Red Zone). We also check that we don't
629 // push and pop from the stack.
630 if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
631 !RegInfo->needsStackRealignment(MF) &&
632 !MFI->hasVarSizedObjects() && // No dynamic alloca.
633 !MFI->adjustsStack() && // No calls.
634 !IsWin64CC && // Win64 has no Red Zone
635 !usesTheStack(MF) && // Don't push and pop.
636 !MF.shouldSplitStack()) { // Regular stack
637 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
638 if (HasFP) MinSize += SlotSize;
639 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
640 MFI->setStackSize(StackSize);
643 // Insert stack pointer adjustment for later moving of return addr. Only
644 // applies to tail call optimized functions where the callee argument stack
645 // size is bigger than the callers.
646 if (TailCallReturnAddrDelta < 0) {
648 BuildMI(MBB, MBBI, DL,
649 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
652 .addImm(-TailCallReturnAddrDelta)
653 .setMIFlag(MachineInstr::FrameSetup);
654 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
657 // Mapping for machine moves:
659 // DST: VirtualFP AND
660 // SRC: VirtualFP => DW_CFA_def_cfa_offset
661 // ELSE => DW_CFA_def_cfa
663 // SRC: VirtualFP AND
664 // DST: Register => DW_CFA_def_cfa_register
667 // OFFSET < 0 => DW_CFA_offset_extended_sf
668 // REG < 64 => DW_CFA_offset + Reg
669 // ELSE => DW_CFA_offset_extended
671 uint64_t NumBytes = 0;
672 int stackGrowth = -SlotSize;
675 // Calculate required stack adjustment.
676 uint64_t FrameSize = StackSize - SlotSize;
677 // If required, include space for extra hidden slot for stashing base pointer.
678 if (X86FI->getRestoreBasePointer())
679 FrameSize += SlotSize;
681 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
683 // Callee-saved registers are pushed on stack before the stack is realigned.
684 if (RegInfo->needsStackRealignment(MF) && !IsWin64Prologue)
685 NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
687 // Get the offset of the stack slot for the EBP register, which is
688 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
689 // Update the frame offset adjustment.
690 MFI->setOffsetAdjustment(-NumBytes);
692 // Save EBP/RBP into the appropriate stack slot.
693 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
694 .addReg(MachineFramePtr, RegState::Kill)
695 .setMIFlag(MachineInstr::FrameSetup);
698 // Mark the place where EBP/RBP was saved.
699 // Define the current CFA rule to use the provided offset.
701 BuildCFI(MBB, MBBI, DL, TII,
702 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
704 // Change the rule for the FramePtr to be an "offset" rule.
705 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
706 BuildCFI(MBB, MBBI, DL, TII,
707 MCCFIInstruction::createOffset(nullptr, DwarfFramePtr,
712 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
714 .setMIFlag(MachineInstr::FrameSetup);
717 if (!IsWin64Prologue) {
718 // Update EBP with the new base value.
719 BuildMI(MBB, MBBI, DL,
720 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
723 .setMIFlag(MachineInstr::FrameSetup);
727 // Mark effective beginning of when frame pointer becomes valid.
728 // Define the current CFA to use the EBP/RBP register.
729 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
730 BuildCFI(MBB, MBBI, DL, TII,
731 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
734 // Mark the FramePtr as live-in in every block.
735 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
736 I->addLiveIn(MachineFramePtr);
738 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
741 // Skip the callee-saved push instructions.
742 bool PushedRegs = false;
743 int StackOffset = 2 * stackGrowth;
745 while (MBBI != MBB.end() &&
746 (MBBI->getOpcode() == X86::PUSH32r ||
747 MBBI->getOpcode() == X86::PUSH64r)) {
749 unsigned Reg = MBBI->getOperand(0).getReg();
752 if (!HasFP && NeedsDwarfCFI) {
753 // Mark callee-saved push instruction.
754 // Define the current CFA rule to use the provided offset.
756 BuildCFI(MBB, MBBI, DL, TII,
757 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
758 StackOffset += stackGrowth;
762 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
763 MachineInstr::FrameSetup);
767 // Realign stack after we pushed callee-saved registers (so that we'll be
768 // able to calculate their offsets from the frame pointer).
769 // Don't do this for Win64, it needs to realign the stack after the prologue.
770 if (!IsWin64Prologue && RegInfo->needsStackRealignment(MF)) {
771 assert(HasFP && "There should be a frame pointer if stack is realigned.");
772 uint64_t Val = -MaxAlign;
774 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
778 .setMIFlag(MachineInstr::FrameSetup);
780 // The EFLAGS implicit def is dead.
781 MI->getOperand(3).setIsDead();
784 // If there is an SUB32ri of ESP immediately before this instruction, merge
785 // the two. This can be the case when tail call elimination is enabled and
786 // the callee has more arguments then the caller.
787 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
789 // Adjust stack pointer: ESP -= numbytes.
791 // Windows and cygwin/mingw require a prologue helper routine when allocating
792 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
793 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
794 // stack and adjust the stack pointer in one go. The 64-bit version of
795 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
796 // responsible for adjusting the stack pointer. Touching the stack at 4K
797 // increments is necessary to ensure that the guard pages used by the OS
798 // virtual memory manager are allocated in correct sequence.
799 uint64_t AlignedNumBytes = NumBytes;
800 if (IsWin64Prologue && RegInfo->needsStackRealignment(MF))
801 AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
802 if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
803 // Check whether EAX is livein for this function.
804 bool isEAXAlive = isEAXLiveIn(MF);
807 // Sanity check that EAX is not livein for this function.
808 // It should not be, so throw an assert.
809 assert(!Is64Bit && "EAX is livein in x64 case!");
812 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
813 .addReg(X86::EAX, RegState::Kill)
814 .setMIFlag(MachineInstr::FrameSetup);
818 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
819 // Function prologue is responsible for adjusting the stack pointer.
820 if (isUInt<32>(NumBytes)) {
821 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
823 .setMIFlag(MachineInstr::FrameSetup);
824 } else if (isInt<32>(NumBytes)) {
825 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
827 .setMIFlag(MachineInstr::FrameSetup);
829 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
831 .setMIFlag(MachineInstr::FrameSetup);
834 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
835 // We'll also use 4 already allocated bytes for EAX.
836 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
837 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
838 .setMIFlag(MachineInstr::FrameSetup);
841 // Save a pointer to the MI where we set AX.
842 MachineBasicBlock::iterator SetRAX = MBBI;
845 // Call __chkstk, __chkstk_ms, or __alloca.
846 emitStackProbeCall(MF, MBB, MBBI, DL);
848 // Apply the frame setup flag to all inserted instrs.
849 for (; SetRAX != MBBI; ++SetRAX)
850 SetRAX->setFlag(MachineInstr::FrameSetup);
854 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
856 StackPtr, false, NumBytes - 4);
857 MI->setFlag(MachineInstr::FrameSetup);
858 MBB.insert(MBBI, MI);
860 } else if (NumBytes) {
861 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
862 UseLEA, TII, *RegInfo);
865 if (NeedsWinCFI && NumBytes)
866 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
868 .setMIFlag(MachineInstr::FrameSetup);
870 int SEHFrameOffset = 0;
871 if (IsWin64Prologue && HasFP) {
872 SEHFrameOffset = calculateSetFPREG(NumBytes);
874 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
875 StackPtr, false, SEHFrameOffset);
877 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr).addReg(StackPtr);
880 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
882 .addImm(SEHFrameOffset)
883 .setMIFlag(MachineInstr::FrameSetup);
886 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
887 const MachineInstr *FrameInstr = &*MBBI;
892 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
893 if (X86::FR64RegClass.contains(Reg)) {
894 int Offset = getFrameIndexOffset(MF, FI);
895 Offset += SEHFrameOffset;
897 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
900 .setMIFlag(MachineInstr::FrameSetup);
907 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
908 .setMIFlag(MachineInstr::FrameSetup);
910 // Realign stack after we spilled callee-saved registers (so that we'll be
911 // able to calculate their offsets from the frame pointer).
912 // Win64 requires aligning the stack after the prologue.
913 if (IsWin64Prologue && RegInfo->needsStackRealignment(MF)) {
914 assert(HasFP && "There should be a frame pointer if stack is realigned.");
915 uint64_t Val = -MaxAlign;
917 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
921 .setMIFlag(MachineInstr::FrameSetup);
923 // The EFLAGS implicit def is dead.
924 MI->getOperand(3).setIsDead();
927 // If we need a base pointer, set it up here. It's whatever the value
928 // of the stack pointer is at this point. Any variable size objects
929 // will be allocated after this, so we can still use the base pointer
930 // to reference locals.
931 if (RegInfo->hasBasePointer(MF)) {
932 // Update the base pointer with the current stack pointer.
933 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
934 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
936 .setMIFlag(MachineInstr::FrameSetup);
937 if (X86FI->getRestoreBasePointer()) {
938 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
939 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
940 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
941 FramePtr, true, X86FI->getRestoreBasePointerOffset())
943 .setMIFlag(MachineInstr::FrameSetup);
947 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
948 // Mark end of stack pointer adjustment.
949 if (!HasFP && NumBytes) {
950 // Define the current CFA rule to use the provided offset.
952 BuildCFI(MBB, MBBI, DL, TII, MCCFIInstruction::createDefCfaOffset(
953 nullptr, -StackSize + stackGrowth));
956 // Emit DWARF info specifying the offsets of the callee-saved registers.
958 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
962 bool X86FrameLowering::canUseLEAForSPInEpilogue(
963 const MachineFunction &MF) const {
964 // We can't use LEA instructions for adjusting the stack pointer if this is a
965 // leaf function in the Win64 ABI. Only ADD instructions may be used to
966 // deallocate the stack.
967 // This means that we can use LEA for SP in two situations:
968 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
969 // 2. We *have* a frame pointer which means we are permitted to use LEA.
970 return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
973 /// Check whether or not the terminators of \p MBB needs to read EFLAGS.
974 static bool terminatorsNeedFlagsAsInput(const MachineBasicBlock &MBB) {
975 for (const MachineInstr &MI : MBB.terminators()) {
976 bool BreakNext = false;
977 for (const MachineOperand &MO : MI.operands()) {
980 unsigned Reg = MO.getReg();
981 if (Reg != X86::EFLAGS)
984 // This terminator needs an eflag that is not defined
985 // by a previous terminator.
996 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
997 MachineBasicBlock &MBB) const {
998 const MachineFrameInfo *MFI = MF.getFrameInfo();
999 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1000 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1001 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
1002 const TargetInstrInfo &TII = *STI.getInstrInfo();
1003 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1005 if (MBBI != MBB.end())
1006 DL = MBBI->getDebugLoc();
1007 bool Is64Bit = STI.is64Bit();
1008 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
1009 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
1010 const bool Is64BitILP32 = STI.isTarget64BitILP32();
1011 unsigned SlotSize = RegInfo->getSlotSize();
1012 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1013 unsigned MachineFramePtr =
1014 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
1016 unsigned StackPtr = RegInfo->getStackRegister();
1018 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1020 IsWin64Prologue && MF.getFunction()->needsUnwindTableEntry();
1021 bool UseLEAForSP = canUseLEAForSPInEpilogue(MF);
1022 // If we can use LEA for SP but we shouldn't, check that none
1023 // of the terminators uses the eflags. Otherwise we will insert
1024 // a ADD that will redefine the eflags and break the condition.
1025 // Alternatively, we could move the ADD, but this may not be possible
1026 // and is an optimization anyway.
1027 if (UseLEAForSP && !MF.getSubtarget<X86Subtarget>().useLeaForSP())
1028 UseLEAForSP = terminatorsNeedFlagsAsInput(MBB);
1029 // If that assert breaks, that means we do not do the right thing
1030 // in canUseAsEpilogue.
1031 assert((UseLEAForSP || !terminatorsNeedFlagsAsInput(MBB)) &&
1032 "We shouldn't have allowed this insertion point");
1034 // Get the number of bytes to allocate from the FrameInfo.
1035 uint64_t StackSize = MFI->getStackSize();
1036 uint64_t MaxAlign = calculateMaxStackAlign(MF);
1037 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1038 uint64_t NumBytes = 0;
1041 // Calculate required stack adjustment.
1042 uint64_t FrameSize = StackSize - SlotSize;
1043 NumBytes = FrameSize - CSSize;
1045 // Callee-saved registers were pushed on stack before the stack was
1047 if (RegInfo->needsStackRealignment(MF) && !IsWin64Prologue)
1048 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1051 BuildMI(MBB, MBBI, DL,
1052 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1054 NumBytes = StackSize - CSSize;
1056 uint64_t SEHStackAllocAmt = NumBytes;
1058 // Skip the callee-saved pop instructions.
1059 while (MBBI != MBB.begin()) {
1060 MachineBasicBlock::iterator PI = std::prev(MBBI);
1061 unsigned Opc = PI->getOpcode();
1063 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1064 !PI->isTerminator())
1069 MachineBasicBlock::iterator FirstCSPop = MBBI;
1071 if (MBBI != MBB.end())
1072 DL = MBBI->getDebugLoc();
1074 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1075 // instruction, merge the two instructions.
1076 if (NumBytes || MFI->hasVarSizedObjects())
1077 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1079 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1080 // slot before popping them off! Same applies for the case, when stack was
1082 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1083 if (RegInfo->needsStackRealignment(MF))
1085 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1086 uint64_t LEAAmount =
1087 IsWin64Prologue ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1089 // There are only two legal forms of epilogue:
1090 // - add SEHAllocationSize, %rsp
1091 // - lea SEHAllocationSize(%FramePtr), %rsp
1093 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1094 // However, we may use this sequence if we have a frame pointer because the
1095 // effects of the prologue can safely be undone.
1096 if (LEAAmount != 0) {
1097 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1098 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1099 FramePtr, false, LEAAmount);
1102 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1103 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1107 } else if (NumBytes) {
1108 // Adjust stack pointer back: ESP += numbytes.
1109 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1110 UseLEAForSP, TII, *RegInfo);
1114 // Windows unwinder will not invoke function's exception handler if IP is
1115 // either in prologue or in epilogue. This behavior causes a problem when a
1116 // call immediately precedes an epilogue, because the return address points
1117 // into the epilogue. To cope with that, we insert an epilogue marker here,
1118 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1119 // final emitted code.
1121 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1123 // Add the return addr area delta back since we are not tail calling.
1124 int Offset = -1 * X86FI->getTCReturnAddrDelta();
1125 assert(Offset >= 0 && "TCDelta should never be positive");
1127 MBBI = MBB.getFirstTerminator();
1129 // Check for possible merge with preceding ADD instruction.
1130 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1131 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1132 UseLEAForSP, TII, *RegInfo);
1136 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1138 const X86RegisterInfo *RegInfo =
1139 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1140 const MachineFrameInfo *MFI = MF.getFrameInfo();
1141 // Offset will hold the offset from the stack pointer at function entry to the
1143 // We need to factor in additional offsets applied during the prologue to the
1144 // frame, base, and stack pointer depending on which is used.
1145 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1146 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1147 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1148 uint64_t StackSize = MFI->getStackSize();
1149 unsigned SlotSize = RegInfo->getSlotSize();
1150 bool HasFP = hasFP(MF);
1151 bool IsWin64Prologue = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1152 int64_t FPDelta = 0;
1154 if (IsWin64Prologue) {
1155 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1157 // Calculate required stack adjustment.
1158 uint64_t FrameSize = StackSize - SlotSize;
1159 // If required, include space for extra hidden slot for stashing base pointer.
1160 if (X86FI->getRestoreBasePointer())
1161 FrameSize += SlotSize;
1162 uint64_t NumBytes = FrameSize - CSSize;
1164 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1165 if (FI && FI == X86FI->getFAIndex())
1166 return -SEHFrameOffset;
1168 // FPDelta is the offset from the "traditional" FP location of the old base
1169 // pointer followed by return address and the location required by the
1170 // restricted Win64 prologue.
1171 // Add FPDelta to all offsets below that go through the frame pointer.
1172 FPDelta = FrameSize - SEHFrameOffset;
1173 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1174 "FPDelta isn't aligned per the Win64 ABI!");
1178 if (RegInfo->hasBasePointer(MF)) {
1179 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1181 // Skip the saved EBP.
1182 return Offset + SlotSize + FPDelta;
1184 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1185 return Offset + StackSize;
1187 } else if (RegInfo->needsStackRealignment(MF)) {
1189 // Skip the saved EBP.
1190 return Offset + SlotSize + FPDelta;
1192 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1193 return Offset + StackSize;
1195 // FIXME: Support tail calls
1198 return Offset + StackSize;
1200 // Skip the saved EBP.
1203 // Skip the RETADDR move area
1204 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1205 if (TailCallReturnAddrDelta < 0)
1206 Offset -= TailCallReturnAddrDelta;
1209 return Offset + FPDelta;
1212 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1213 unsigned &FrameReg) const {
1214 const X86RegisterInfo *RegInfo =
1215 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1216 // We can't calculate offset from frame pointer if the stack is realigned,
1217 // so enforce usage of stack/base pointer. The base pointer is used when we
1218 // have dynamic allocas in addition to dynamic realignment.
1219 if (RegInfo->hasBasePointer(MF))
1220 FrameReg = RegInfo->getBaseRegister();
1221 else if (RegInfo->needsStackRealignment(MF))
1222 FrameReg = RegInfo->getStackRegister();
1224 FrameReg = RegInfo->getFrameRegister(MF);
1225 return getFrameIndexOffset(MF, FI);
1228 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1229 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1230 const MachineFrameInfo *MFI = MF.getFrameInfo();
1231 // Does not include any dynamic realign.
1232 const uint64_t StackSize = MFI->getStackSize();
1235 const X86RegisterInfo *RegInfo =
1236 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1237 // Note: LLVM arranges the stack as:
1238 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1239 // > "Stack Slots" (<--SP)
1240 // We can always address StackSlots from RSP. We can usually (unless
1241 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1242 // address them from RBP. FixedObjects can be placed anywhere in the stack
1243 // frame depending on their specific requirements (i.e. we can actually
1244 // refer to arguments to the function which are stored in the *callers*
1245 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1246 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1248 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1250 // We don't handle tail calls, and shouldn't be seeing them
1252 int TailCallReturnAddrDelta =
1253 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1254 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1258 // This is how the math works out:
1260 // %rsp grows (i.e. gets lower) left to right. Each box below is
1261 // one word (eight bytes). Obj0 is the stack slot we're trying to
1264 // ----------------------------------
1265 // | BP | Obj0 | Obj1 | ... | ObjN |
1266 // ----------------------------------
1270 // A is the incoming stack pointer.
1271 // (B - A) is the local area offset (-8 for x86-64) [1]
1272 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1274 // |(E - B)| is the StackSize (absolute value, positive). For a
1275 // stack that grown down, this works out to be (B - E). [3]
1277 // E is also the value of %rsp after stack has been set up, and we
1278 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1279 // (C - E) == (C - A) - (B - A) + (B - E)
1280 // { Using [1], [2] and [3] above }
1281 // == getObjectOffset - LocalAreaOffset + StackSize
1284 // Get the Offset from the StackPointer
1285 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1287 return Offset + StackSize;
1289 // Simplified from getFrameIndexReference keeping only StackPointer cases
1290 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1292 unsigned &FrameReg) const {
1293 const X86RegisterInfo *RegInfo =
1294 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1295 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1297 FrameReg = RegInfo->getStackRegister();
1298 return getFrameIndexOffsetFromSP(MF, FI);
1301 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1302 MachineFunction &MF, const TargetRegisterInfo *TRI,
1303 std::vector<CalleeSavedInfo> &CSI) const {
1304 MachineFrameInfo *MFI = MF.getFrameInfo();
1305 const X86RegisterInfo *RegInfo =
1306 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1307 unsigned SlotSize = RegInfo->getSlotSize();
1308 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1310 unsigned CalleeSavedFrameSize = 0;
1311 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1314 // emitPrologue always spills frame register the first thing.
1315 SpillSlotOffset -= SlotSize;
1316 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1318 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1319 // the frame register, we can delete it from CSI list and not have to worry
1320 // about avoiding it later.
1321 unsigned FPReg = RegInfo->getFrameRegister(MF);
1322 for (unsigned i = 0; i < CSI.size(); ++i) {
1323 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1324 CSI.erase(CSI.begin() + i);
1330 // Assign slots for GPRs. It increases frame size.
1331 for (unsigned i = CSI.size(); i != 0; --i) {
1332 unsigned Reg = CSI[i - 1].getReg();
1334 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1337 SpillSlotOffset -= SlotSize;
1338 CalleeSavedFrameSize += SlotSize;
1340 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1341 CSI[i - 1].setFrameIdx(SlotIndex);
1344 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1346 // Assign slots for XMMs.
1347 for (unsigned i = CSI.size(); i != 0; --i) {
1348 unsigned Reg = CSI[i - 1].getReg();
1349 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1352 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1354 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1356 SpillSlotOffset -= RC->getSize();
1358 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1359 CSI[i - 1].setFrameIdx(SlotIndex);
1360 MFI->ensureMaxAlignment(RC->getAlignment());
1366 bool X86FrameLowering::spillCalleeSavedRegisters(
1367 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1368 const std::vector<CalleeSavedInfo> &CSI,
1369 const TargetRegisterInfo *TRI) const {
1370 DebugLoc DL = MBB.findDebugLoc(MI);
1372 MachineFunction &MF = *MBB.getParent();
1373 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1374 const TargetInstrInfo &TII = *STI.getInstrInfo();
1376 // Push GPRs. It increases frame size.
1377 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1378 for (unsigned i = CSI.size(); i != 0; --i) {
1379 unsigned Reg = CSI[i - 1].getReg();
1381 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1383 // Add the callee-saved register as live-in. It's killed at the spill.
1386 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1387 .setMIFlag(MachineInstr::FrameSetup);
1390 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1391 // It can be done by spilling XMMs to stack frame.
1392 for (unsigned i = CSI.size(); i != 0; --i) {
1393 unsigned Reg = CSI[i-1].getReg();
1394 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1396 // Add the callee-saved register as live-in. It's killed at the spill.
1398 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1400 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1403 MI->setFlag(MachineInstr::FrameSetup);
1410 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1411 MachineBasicBlock::iterator MI,
1412 const std::vector<CalleeSavedInfo> &CSI,
1413 const TargetRegisterInfo *TRI) const {
1417 DebugLoc DL = MBB.findDebugLoc(MI);
1419 MachineFunction &MF = *MBB.getParent();
1420 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1421 const TargetInstrInfo &TII = *STI.getInstrInfo();
1423 // Reload XMMs from stack frame.
1424 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1425 unsigned Reg = CSI[i].getReg();
1426 if (X86::GR64RegClass.contains(Reg) ||
1427 X86::GR32RegClass.contains(Reg))
1430 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1431 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1435 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1436 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1437 unsigned Reg = CSI[i].getReg();
1438 if (!X86::GR64RegClass.contains(Reg) &&
1439 !X86::GR32RegClass.contains(Reg))
1442 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1448 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1449 RegScavenger *RS) const {
1450 MachineFrameInfo *MFI = MF.getFrameInfo();
1451 const X86RegisterInfo *RegInfo =
1452 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1453 unsigned SlotSize = RegInfo->getSlotSize();
1455 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1456 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1458 if (TailCallReturnAddrDelta < 0) {
1459 // create RETURNADDR area
1468 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1469 TailCallReturnAddrDelta - SlotSize, true);
1472 // Spill the BasePtr if it's used.
1473 if (RegInfo->hasBasePointer(MF))
1474 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1478 HasNestArgument(const MachineFunction *MF) {
1479 const Function *F = MF->getFunction();
1480 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1482 if (I->hasNestAttr())
1488 /// GetScratchRegister - Get a temp register for performing work in the
1489 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1490 /// and the properties of the function either one or two registers will be
1491 /// needed. Set primary to true for the first register, false for the second.
1493 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1494 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1497 if (CallingConvention == CallingConv::HiPE) {
1499 return Primary ? X86::R14 : X86::R13;
1501 return Primary ? X86::EBX : X86::EDI;
1506 return Primary ? X86::R11 : X86::R12;
1508 return Primary ? X86::R11D : X86::R12D;
1511 bool IsNested = HasNestArgument(&MF);
1513 if (CallingConvention == CallingConv::X86_FastCall ||
1514 CallingConvention == CallingConv::Fast) {
1516 report_fatal_error("Segmented stacks does not support fastcall with "
1517 "nested function.");
1518 return Primary ? X86::EAX : X86::ECX;
1521 return Primary ? X86::EDX : X86::EAX;
1522 return Primary ? X86::ECX : X86::EAX;
1525 // The stack limit in the TCB is set to this many bytes above the actual stack
1527 static const uint64_t kSplitStackAvailable = 256;
1529 void X86FrameLowering::adjustForSegmentedStacks(
1530 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1531 MachineFrameInfo *MFI = MF.getFrameInfo();
1532 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1533 const TargetInstrInfo &TII = *STI.getInstrInfo();
1535 bool Is64Bit = STI.is64Bit();
1536 const bool IsLP64 = STI.isTarget64BitLP64();
1537 unsigned TlsReg, TlsOffset;
1540 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1541 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1542 "Scratch register is live-in");
1544 if (MF.getFunction()->isVarArg())
1545 report_fatal_error("Segmented stacks do not support vararg functions.");
1546 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1547 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1548 !STI.isTargetDragonFly())
1549 report_fatal_error("Segmented stacks not supported on this platform.");
1551 // Eventually StackSize will be calculated by a link-time pass; which will
1552 // also decide whether checking code needs to be injected into this particular
1554 StackSize = MFI->getStackSize();
1556 // Do not generate a prologue for functions with a stack of size zero
1560 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1561 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1562 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1563 bool IsNested = false;
1565 // We need to know if the function has a nest argument only in 64 bit mode.
1567 IsNested = HasNestArgument(&MF);
1569 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1570 // allocMBB needs to be last (terminating) instruction.
1572 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1573 e = PrologueMBB.livein_end();
1575 allocMBB->addLiveIn(*i);
1576 checkMBB->addLiveIn(*i);
1580 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1582 MF.push_front(allocMBB);
1583 MF.push_front(checkMBB);
1585 // When the frame size is less than 256 we just compare the stack
1586 // boundary directly to the value of the stack pointer, per gcc.
1587 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1589 // Read the limit off the current stacklet off the stack_guard location.
1591 if (STI.isTargetLinux()) {
1593 TlsOffset = IsLP64 ? 0x70 : 0x40;
1594 } else if (STI.isTargetDarwin()) {
1596 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1597 } else if (STI.isTargetWin64()) {
1599 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1600 } else if (STI.isTargetFreeBSD()) {
1603 } else if (STI.isTargetDragonFly()) {
1605 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1607 report_fatal_error("Segmented stacks not supported on this platform.");
1610 if (CompareStackPointer)
1611 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1613 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1614 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1616 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1617 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1619 if (STI.isTargetLinux()) {
1622 } else if (STI.isTargetDarwin()) {
1624 TlsOffset = 0x48 + 90*4;
1625 } else if (STI.isTargetWin32()) {
1627 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1628 } else if (STI.isTargetDragonFly()) {
1630 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1631 } else if (STI.isTargetFreeBSD()) {
1632 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1634 report_fatal_error("Segmented stacks not supported on this platform.");
1637 if (CompareStackPointer)
1638 ScratchReg = X86::ESP;
1640 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1641 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1643 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1644 STI.isTargetDragonFly()) {
1645 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1646 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1647 } else if (STI.isTargetDarwin()) {
1649 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1650 unsigned ScratchReg2;
1652 if (CompareStackPointer) {
1653 // The primary scratch register is available for holding the TLS offset.
1654 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1655 SaveScratch2 = false;
1657 // Need to use a second register to hold the TLS offset
1658 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1660 // Unfortunately, with fastcc the second scratch register may hold an
1662 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1665 // If Scratch2 is live-in then it needs to be saved.
1666 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1667 "Scratch register is live-in and not saved");
1670 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1671 .addReg(ScratchReg2, RegState::Kill);
1673 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1675 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1677 .addReg(ScratchReg2).addImm(1).addReg(0)
1682 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1686 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1687 // It jumps to normal execution of the function body.
1688 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
1690 // On 32 bit we first push the arguments size and then the frame size. On 64
1691 // bit, we pass the stack frame size in r10 and the argument size in r11.
1693 // Functions with nested arguments use R10, so it needs to be saved across
1694 // the call to _morestack
1696 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1697 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1698 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1699 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1700 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1703 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1705 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1707 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1708 .addImm(X86FI->getArgumentStackSize());
1709 MF.getRegInfo().setPhysRegUsed(Reg10);
1710 MF.getRegInfo().setPhysRegUsed(Reg11);
1712 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1713 .addImm(X86FI->getArgumentStackSize());
1714 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1718 // __morestack is in libgcc
1719 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1720 // Under the large code model, we cannot assume that __morestack lives
1721 // within 2^31 bytes of the call site, so we cannot use pc-relative
1722 // addressing. We cannot perform the call via a temporary register,
1723 // as the rax register may be used to store the static chain, and all
1724 // other suitable registers may be either callee-save or used for
1725 // parameter passing. We cannot use the stack at this point either
1726 // because __morestack manipulates the stack directly.
1728 // To avoid these issues, perform an indirect call via a read-only memory
1729 // location containing the address.
1731 // This solution is not perfect, as it assumes that the .rodata section
1732 // is laid out within 2^31 bytes of each function body, but this seems
1733 // to be sufficient for JIT.
1734 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1738 .addExternalSymbol("__morestack_addr")
1740 MF.getMMI().setUsesMorestackAddr(true);
1743 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1744 .addExternalSymbol("__morestack");
1746 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1747 .addExternalSymbol("__morestack");
1751 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1753 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1755 allocMBB->addSuccessor(&PrologueMBB);
1757 checkMBB->addSuccessor(allocMBB);
1758 checkMBB->addSuccessor(&PrologueMBB);
1765 /// Erlang programs may need a special prologue to handle the stack size they
1766 /// might need at runtime. That is because Erlang/OTP does not implement a C
1767 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1768 /// (for more information see Eric Stenman's Ph.D. thesis:
1769 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1772 /// temp0 = sp - MaxStack
1773 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1777 /// call inc_stack # doubles the stack space
1778 /// temp0 = sp - MaxStack
1779 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1780 void X86FrameLowering::adjustForHiPEPrologue(
1781 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1782 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1783 const TargetInstrInfo &TII = *STI.getInstrInfo();
1784 MachineFrameInfo *MFI = MF.getFrameInfo();
1785 const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
1786 const bool Is64Bit = STI.is64Bit();
1787 const bool IsLP64 = STI.isTarget64BitLP64();
1789 // HiPE-specific values
1790 const unsigned HipeLeafWords = 24;
1791 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1792 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1793 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1794 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1795 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1797 assert(STI.isTargetLinux() &&
1798 "HiPE prologue is only supported on Linux operating systems.");
1800 // Compute the largest caller's frame that is needed to fit the callees'
1801 // frames. This 'MaxStack' is computed from:
1803 // a) the fixed frame size, which is the space needed for all spilled temps,
1804 // b) outgoing on-stack parameter areas, and
1805 // c) the minimum stack space this function needs to make available for the
1806 // functions it calls (a tunable ABI property).
1807 if (MFI->hasCalls()) {
1808 unsigned MoreStackForCalls = 0;
1810 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1811 MBBI != MBBE; ++MBBI)
1812 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1817 // Get callee operand.
1818 const MachineOperand &MO = MI->getOperand(0);
1820 // Only take account of global function calls (no closures etc.).
1824 const Function *F = dyn_cast<Function>(MO.getGlobal());
1828 // Do not update 'MaxStack' for primitive and built-in functions
1829 // (encoded with names either starting with "erlang."/"bif_" or not
1830 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1831 // "_", such as the BIF "suspend_0") as they are executed on another
1833 if (F->getName().find("erlang.") != StringRef::npos ||
1834 F->getName().find("bif_") != StringRef::npos ||
1835 F->getName().find_first_of("._") == StringRef::npos)
1838 unsigned CalleeStkArity =
1839 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1840 if (HipeLeafWords - 1 > CalleeStkArity)
1841 MoreStackForCalls = std::max(MoreStackForCalls,
1842 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1844 MaxStack += MoreStackForCalls;
1847 // If the stack frame needed is larger than the guaranteed then runtime checks
1848 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1849 if (MaxStack > Guaranteed) {
1850 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1851 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1853 for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1854 E = PrologueMBB.livein_end();
1856 stackCheckMBB->addLiveIn(*I);
1857 incStackMBB->addLiveIn(*I);
1860 MF.push_front(incStackMBB);
1861 MF.push_front(stackCheckMBB);
1863 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1864 unsigned LEAop, CMPop, CALLop;
1868 LEAop = X86::LEA64r;
1869 CMPop = X86::CMP64rm;
1870 CALLop = X86::CALL64pcrel32;
1871 SPLimitOffset = 0x90;
1875 LEAop = X86::LEA32r;
1876 CMPop = X86::CMP32rm;
1877 CALLop = X86::CALLpcrel32;
1878 SPLimitOffset = 0x4c;
1881 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1882 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1883 "HiPE prologue scratch register is live-in");
1885 // Create new MBB for StackCheck:
1886 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1887 SPReg, false, -MaxStack);
1888 // SPLimitOffset is in a fixed heap location (pointed by BP).
1889 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1890 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1891 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
1893 // Create new MBB for IncStack:
1894 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1895 addExternalSymbol("inc_stack_0");
1896 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1897 SPReg, false, -MaxStack);
1898 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1899 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1900 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1902 stackCheckMBB->addSuccessor(&PrologueMBB, 99);
1903 stackCheckMBB->addSuccessor(incStackMBB, 1);
1904 incStackMBB->addSuccessor(&PrologueMBB, 99);
1905 incStackMBB->addSuccessor(incStackMBB, 1);
1912 void X86FrameLowering::
1913 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1914 MachineBasicBlock::iterator I) const {
1915 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1916 const TargetInstrInfo &TII = *STI.getInstrInfo();
1917 const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
1918 unsigned StackPtr = RegInfo.getStackRegister();
1919 bool reserveCallFrame = hasReservedCallFrame(MF);
1920 unsigned Opcode = I->getOpcode();
1921 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1922 bool IsLP64 = STI.isTarget64BitLP64();
1923 DebugLoc DL = I->getDebugLoc();
1924 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1925 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1928 if (!reserveCallFrame) {
1929 // If the stack pointer can be changed after prologue, turn the
1930 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1931 // adjcallstackdown instruction into 'add ESP, <amt>'
1935 // We need to keep the stack aligned properly. To do this, we round the
1936 // amount of space needed for the outgoing arguments up to the next
1937 // alignment boundary.
1938 unsigned StackAlign = getStackAlignment();
1939 Amount = RoundUpToAlignment(Amount, StackAlign);
1941 MachineInstr *New = nullptr;
1943 // Factor out the amount that gets handled inside the sequence
1944 // (Pushes of argument for frame setup, callee pops for frame destroy)
1945 Amount -= InternalAmt;
1948 if (Opcode == TII.getCallFrameSetupOpcode()) {
1949 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1950 .addReg(StackPtr).addImm(Amount);
1952 assert(Opcode == TII.getCallFrameDestroyOpcode());
1954 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1955 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1956 .addReg(StackPtr).addImm(Amount);
1961 // The EFLAGS implicit def is dead.
1962 New->getOperand(3).setIsDead();
1964 // Replace the pseudo instruction with a new instruction.
1971 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
1972 // If we are performing frame pointer elimination and if the callee pops
1973 // something off the stack pointer, add it back. We do this until we have
1974 // more advanced stack pointer tracking ability.
1975 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
1976 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1977 .addReg(StackPtr).addImm(InternalAmt);
1979 // The EFLAGS implicit def is dead.
1980 New->getOperand(3).setIsDead();
1982 // We are not tracking the stack pointer adjustment by the callee, so make
1983 // sure we restore the stack pointer immediately after the call, there may
1984 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1985 MachineBasicBlock::iterator B = MBB.begin();
1986 while (I != B && !std::prev(I)->isCall())
1992 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1993 assert(MBB.getParent() && "Block is not attached to a function!");
1995 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
1998 // If we cannot use LEA to adjust SP, we may need to use ADD, which
1999 // clobbers the EFLAGS. Check that none of the terminators reads the
2000 // EFLAGS, and if one uses it, conservatively assume this is not
2001 // safe to insert the epilogue here.
2002 return !terminatorsNeedFlagsAsInput(MBB);