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 IsWin64 = STI.isCallingConvWin64(Fn->getCallingConv());
590 // Not necessarily synonymous with IsWin64.
591 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
592 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
594 !IsWinEH && (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 && IsWinEH)
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 !IsWin64 && // 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) && !IsWinEH)
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);
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 (!IsWinEH && 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 (IsWinEH && 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 (NeedsWinEH && NumBytes)
866 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
868 .setMIFlag(MachineInstr::FrameSetup);
870 int SEHFrameOffset = 0;
871 if (IsWinEH && 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 (IsWinEH && 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 IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1019 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
1020 bool UseLEAForSP = canUseLEAForSPInEpilogue(MF);
1021 // If we can use LEA for SP but we shouldn't, check that none
1022 // of the terminators uses the eflags. Otherwise we will insert
1023 // a ADD that will redefine the eflags and break the condition.
1024 // Alternatively, we could move the ADD, but this may not be possible
1025 // and is an optimization anyway.
1026 if (UseLEAForSP && !MF.getSubtarget<X86Subtarget>().useLeaForSP())
1027 UseLEAForSP = terminatorsNeedFlagsAsInput(MBB);
1028 // If that assert breaks, that means we do not do the right thing
1029 // in canUseAsEpilogue.
1030 assert((UseLEAForSP || !terminatorsNeedFlagsAsInput(MBB)) &&
1031 "We shouldn't have allowed this insertion point");
1033 // Get the number of bytes to allocate from the FrameInfo.
1034 uint64_t StackSize = MFI->getStackSize();
1035 uint64_t MaxAlign = calculateMaxStackAlign(MF);
1036 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1037 uint64_t NumBytes = 0;
1040 // Calculate required stack adjustment.
1041 uint64_t FrameSize = StackSize - SlotSize;
1042 NumBytes = FrameSize - CSSize;
1044 // Callee-saved registers were pushed on stack before the stack was
1046 if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
1047 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1050 BuildMI(MBB, MBBI, DL,
1051 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1053 NumBytes = StackSize - CSSize;
1055 uint64_t SEHStackAllocAmt = NumBytes;
1057 // Skip the callee-saved pop instructions.
1058 while (MBBI != MBB.begin()) {
1059 MachineBasicBlock::iterator PI = std::prev(MBBI);
1060 unsigned Opc = PI->getOpcode();
1062 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1063 !PI->isTerminator())
1068 MachineBasicBlock::iterator FirstCSPop = MBBI;
1070 if (MBBI != MBB.end())
1071 DL = MBBI->getDebugLoc();
1073 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1074 // instruction, merge the two instructions.
1075 if (NumBytes || MFI->hasVarSizedObjects())
1076 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1078 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1079 // slot before popping them off! Same applies for the case, when stack was
1081 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1082 if (RegInfo->needsStackRealignment(MF))
1084 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1085 uint64_t LEAAmount = IsWinEH ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1087 // There are only two legal forms of epilogue:
1088 // - add SEHAllocationSize, %rsp
1089 // - lea SEHAllocationSize(%FramePtr), %rsp
1091 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1092 // However, we may use this sequence if we have a frame pointer because the
1093 // effects of the prologue can safely be undone.
1094 if (LEAAmount != 0) {
1095 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1096 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1097 FramePtr, false, LEAAmount);
1100 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1101 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1105 } else if (NumBytes) {
1106 // Adjust stack pointer back: ESP += numbytes.
1107 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1108 UseLEAForSP, TII, *RegInfo);
1112 // Windows unwinder will not invoke function's exception handler if IP is
1113 // either in prologue or in epilogue. This behavior causes a problem when a
1114 // call immediately precedes an epilogue, because the return address points
1115 // into the epilogue. To cope with that, we insert an epilogue marker here,
1116 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1117 // final emitted code.
1119 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1121 // Add the return addr area delta back since we are not tail calling.
1122 int Offset = -1 * X86FI->getTCReturnAddrDelta();
1123 assert(Offset >= 0 && "TCDelta should never be positive");
1125 MBBI = MBB.getFirstTerminator();
1127 // Check for possible merge with preceding ADD instruction.
1128 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1129 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1130 UseLEAForSP, TII, *RegInfo);
1134 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1136 const X86RegisterInfo *RegInfo =
1137 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1138 const MachineFrameInfo *MFI = MF.getFrameInfo();
1139 // Offset will hold the offset from the stack pointer at function entry to the
1141 // We need to factor in additional offsets applied during the prologue to the
1142 // frame, base, and stack pointer depending on which is used.
1143 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1144 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1145 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1146 uint64_t StackSize = MFI->getStackSize();
1147 unsigned SlotSize = RegInfo->getSlotSize();
1148 bool HasFP = hasFP(MF);
1149 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1150 int64_t FPDelta = 0;
1153 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1155 // Calculate required stack adjustment.
1156 uint64_t FrameSize = StackSize - SlotSize;
1157 // If required, include space for extra hidden slot for stashing base pointer.
1158 if (X86FI->getRestoreBasePointer())
1159 FrameSize += SlotSize;
1160 uint64_t NumBytes = FrameSize - CSSize;
1162 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1163 if (FI && FI == X86FI->getFAIndex())
1164 return -SEHFrameOffset;
1166 // FPDelta is the offset from the "traditional" FP location of the old base
1167 // pointer followed by return address and the location required by the
1168 // restricted Win64 prologue.
1169 // Add FPDelta to all offsets below that go through the frame pointer.
1170 FPDelta = FrameSize - SEHFrameOffset;
1171 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1172 "FPDelta isn't aligned per the Win64 ABI!");
1176 if (RegInfo->hasBasePointer(MF)) {
1177 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1179 // Skip the saved EBP.
1180 return Offset + SlotSize + FPDelta;
1182 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1183 return Offset + StackSize;
1185 } else if (RegInfo->needsStackRealignment(MF)) {
1187 // Skip the saved EBP.
1188 return Offset + SlotSize + FPDelta;
1190 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1191 return Offset + StackSize;
1193 // FIXME: Support tail calls
1196 return Offset + StackSize;
1198 // Skip the saved EBP.
1201 // Skip the RETADDR move area
1202 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1203 if (TailCallReturnAddrDelta < 0)
1204 Offset -= TailCallReturnAddrDelta;
1207 return Offset + FPDelta;
1210 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1211 unsigned &FrameReg) const {
1212 const X86RegisterInfo *RegInfo =
1213 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1214 // We can't calculate offset from frame pointer if the stack is realigned,
1215 // so enforce usage of stack/base pointer. The base pointer is used when we
1216 // have dynamic allocas in addition to dynamic realignment.
1217 if (RegInfo->hasBasePointer(MF))
1218 FrameReg = RegInfo->getBaseRegister();
1219 else if (RegInfo->needsStackRealignment(MF))
1220 FrameReg = RegInfo->getStackRegister();
1222 FrameReg = RegInfo->getFrameRegister(MF);
1223 return getFrameIndexOffset(MF, FI);
1226 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1227 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1228 const MachineFrameInfo *MFI = MF.getFrameInfo();
1229 // Does not include any dynamic realign.
1230 const uint64_t StackSize = MFI->getStackSize();
1233 const X86RegisterInfo *RegInfo =
1234 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1235 // Note: LLVM arranges the stack as:
1236 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1237 // > "Stack Slots" (<--SP)
1238 // We can always address StackSlots from RSP. We can usually (unless
1239 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1240 // address them from RBP. FixedObjects can be placed anywhere in the stack
1241 // frame depending on their specific requirements (i.e. we can actually
1242 // refer to arguments to the function which are stored in the *callers*
1243 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1244 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1246 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1248 // We don't handle tail calls, and shouldn't be seeing them
1250 int TailCallReturnAddrDelta =
1251 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1252 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1256 // This is how the math works out:
1258 // %rsp grows (i.e. gets lower) left to right. Each box below is
1259 // one word (eight bytes). Obj0 is the stack slot we're trying to
1262 // ----------------------------------
1263 // | BP | Obj0 | Obj1 | ... | ObjN |
1264 // ----------------------------------
1268 // A is the incoming stack pointer.
1269 // (B - A) is the local area offset (-8 for x86-64) [1]
1270 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1272 // |(E - B)| is the StackSize (absolute value, positive). For a
1273 // stack that grown down, this works out to be (B - E). [3]
1275 // E is also the value of %rsp after stack has been set up, and we
1276 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1277 // (C - E) == (C - A) - (B - A) + (B - E)
1278 // { Using [1], [2] and [3] above }
1279 // == getObjectOffset - LocalAreaOffset + StackSize
1282 // Get the Offset from the StackPointer
1283 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1285 return Offset + StackSize;
1287 // Simplified from getFrameIndexReference keeping only StackPointer cases
1288 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1290 unsigned &FrameReg) const {
1291 const X86RegisterInfo *RegInfo =
1292 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1293 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1295 FrameReg = RegInfo->getStackRegister();
1296 return getFrameIndexOffsetFromSP(MF, FI);
1299 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1300 MachineFunction &MF, const TargetRegisterInfo *TRI,
1301 std::vector<CalleeSavedInfo> &CSI) const {
1302 MachineFrameInfo *MFI = MF.getFrameInfo();
1303 const X86RegisterInfo *RegInfo =
1304 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1305 unsigned SlotSize = RegInfo->getSlotSize();
1306 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1308 unsigned CalleeSavedFrameSize = 0;
1309 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1312 // emitPrologue always spills frame register the first thing.
1313 SpillSlotOffset -= SlotSize;
1314 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1316 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1317 // the frame register, we can delete it from CSI list and not have to worry
1318 // about avoiding it later.
1319 unsigned FPReg = RegInfo->getFrameRegister(MF);
1320 for (unsigned i = 0; i < CSI.size(); ++i) {
1321 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1322 CSI.erase(CSI.begin() + i);
1328 // Assign slots for GPRs. It increases frame size.
1329 for (unsigned i = CSI.size(); i != 0; --i) {
1330 unsigned Reg = CSI[i - 1].getReg();
1332 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1335 SpillSlotOffset -= SlotSize;
1336 CalleeSavedFrameSize += SlotSize;
1338 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1339 CSI[i - 1].setFrameIdx(SlotIndex);
1342 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1344 // Assign slots for XMMs.
1345 for (unsigned i = CSI.size(); i != 0; --i) {
1346 unsigned Reg = CSI[i - 1].getReg();
1347 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1350 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1352 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1354 SpillSlotOffset -= RC->getSize();
1356 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1357 CSI[i - 1].setFrameIdx(SlotIndex);
1358 MFI->ensureMaxAlignment(RC->getAlignment());
1364 bool X86FrameLowering::spillCalleeSavedRegisters(
1365 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1366 const std::vector<CalleeSavedInfo> &CSI,
1367 const TargetRegisterInfo *TRI) const {
1368 DebugLoc DL = MBB.findDebugLoc(MI);
1370 MachineFunction &MF = *MBB.getParent();
1371 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1372 const TargetInstrInfo &TII = *STI.getInstrInfo();
1374 // Push GPRs. It increases frame size.
1375 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1376 for (unsigned i = CSI.size(); i != 0; --i) {
1377 unsigned Reg = CSI[i - 1].getReg();
1379 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1381 // Add the callee-saved register as live-in. It's killed at the spill.
1384 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1385 .setMIFlag(MachineInstr::FrameSetup);
1388 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1389 // It can be done by spilling XMMs to stack frame.
1390 for (unsigned i = CSI.size(); i != 0; --i) {
1391 unsigned Reg = CSI[i-1].getReg();
1392 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1394 // Add the callee-saved register as live-in. It's killed at the spill.
1396 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1398 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1401 MI->setFlag(MachineInstr::FrameSetup);
1408 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1409 MachineBasicBlock::iterator MI,
1410 const std::vector<CalleeSavedInfo> &CSI,
1411 const TargetRegisterInfo *TRI) const {
1415 DebugLoc DL = MBB.findDebugLoc(MI);
1417 MachineFunction &MF = *MBB.getParent();
1418 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1419 const TargetInstrInfo &TII = *STI.getInstrInfo();
1421 // Reload XMMs from stack frame.
1422 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1423 unsigned Reg = CSI[i].getReg();
1424 if (X86::GR64RegClass.contains(Reg) ||
1425 X86::GR32RegClass.contains(Reg))
1428 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1429 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1433 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1434 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1435 unsigned Reg = CSI[i].getReg();
1436 if (!X86::GR64RegClass.contains(Reg) &&
1437 !X86::GR32RegClass.contains(Reg))
1440 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1446 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1447 RegScavenger *RS) const {
1448 MachineFrameInfo *MFI = MF.getFrameInfo();
1449 const X86RegisterInfo *RegInfo =
1450 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1451 unsigned SlotSize = RegInfo->getSlotSize();
1453 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1454 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1456 if (TailCallReturnAddrDelta < 0) {
1457 // create RETURNADDR area
1466 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1467 TailCallReturnAddrDelta - SlotSize, true);
1470 // Spill the BasePtr if it's used.
1471 if (RegInfo->hasBasePointer(MF))
1472 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1476 HasNestArgument(const MachineFunction *MF) {
1477 const Function *F = MF->getFunction();
1478 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1480 if (I->hasNestAttr())
1486 /// GetScratchRegister - Get a temp register for performing work in the
1487 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1488 /// and the properties of the function either one or two registers will be
1489 /// needed. Set primary to true for the first register, false for the second.
1491 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1492 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1495 if (CallingConvention == CallingConv::HiPE) {
1497 return Primary ? X86::R14 : X86::R13;
1499 return Primary ? X86::EBX : X86::EDI;
1504 return Primary ? X86::R11 : X86::R12;
1506 return Primary ? X86::R11D : X86::R12D;
1509 bool IsNested = HasNestArgument(&MF);
1511 if (CallingConvention == CallingConv::X86_FastCall ||
1512 CallingConvention == CallingConv::Fast) {
1514 report_fatal_error("Segmented stacks does not support fastcall with "
1515 "nested function.");
1516 return Primary ? X86::EAX : X86::ECX;
1519 return Primary ? X86::EDX : X86::EAX;
1520 return Primary ? X86::ECX : X86::EAX;
1523 // The stack limit in the TCB is set to this many bytes above the actual stack
1525 static const uint64_t kSplitStackAvailable = 256;
1527 void X86FrameLowering::adjustForSegmentedStacks(
1528 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1529 MachineFrameInfo *MFI = MF.getFrameInfo();
1530 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1531 const TargetInstrInfo &TII = *STI.getInstrInfo();
1533 bool Is64Bit = STI.is64Bit();
1534 const bool IsLP64 = STI.isTarget64BitLP64();
1535 unsigned TlsReg, TlsOffset;
1538 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1539 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1540 "Scratch register is live-in");
1542 if (MF.getFunction()->isVarArg())
1543 report_fatal_error("Segmented stacks do not support vararg functions.");
1544 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1545 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1546 !STI.isTargetDragonFly())
1547 report_fatal_error("Segmented stacks not supported on this platform.");
1549 // Eventually StackSize will be calculated by a link-time pass; which will
1550 // also decide whether checking code needs to be injected into this particular
1552 StackSize = MFI->getStackSize();
1554 // Do not generate a prologue for functions with a stack of size zero
1558 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1559 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1560 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1561 bool IsNested = false;
1563 // We need to know if the function has a nest argument only in 64 bit mode.
1565 IsNested = HasNestArgument(&MF);
1567 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1568 // allocMBB needs to be last (terminating) instruction.
1570 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1571 e = PrologueMBB.livein_end();
1573 allocMBB->addLiveIn(*i);
1574 checkMBB->addLiveIn(*i);
1578 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1580 MF.push_front(allocMBB);
1581 MF.push_front(checkMBB);
1583 // When the frame size is less than 256 we just compare the stack
1584 // boundary directly to the value of the stack pointer, per gcc.
1585 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1587 // Read the limit off the current stacklet off the stack_guard location.
1589 if (STI.isTargetLinux()) {
1591 TlsOffset = IsLP64 ? 0x70 : 0x40;
1592 } else if (STI.isTargetDarwin()) {
1594 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1595 } else if (STI.isTargetWin64()) {
1597 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1598 } else if (STI.isTargetFreeBSD()) {
1601 } else if (STI.isTargetDragonFly()) {
1603 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1605 report_fatal_error("Segmented stacks not supported on this platform.");
1608 if (CompareStackPointer)
1609 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1611 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1612 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1614 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1615 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1617 if (STI.isTargetLinux()) {
1620 } else if (STI.isTargetDarwin()) {
1622 TlsOffset = 0x48 + 90*4;
1623 } else if (STI.isTargetWin32()) {
1625 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1626 } else if (STI.isTargetDragonFly()) {
1628 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1629 } else if (STI.isTargetFreeBSD()) {
1630 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1632 report_fatal_error("Segmented stacks not supported on this platform.");
1635 if (CompareStackPointer)
1636 ScratchReg = X86::ESP;
1638 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1639 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1641 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1642 STI.isTargetDragonFly()) {
1643 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1644 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1645 } else if (STI.isTargetDarwin()) {
1647 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1648 unsigned ScratchReg2;
1650 if (CompareStackPointer) {
1651 // The primary scratch register is available for holding the TLS offset.
1652 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1653 SaveScratch2 = false;
1655 // Need to use a second register to hold the TLS offset
1656 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1658 // Unfortunately, with fastcc the second scratch register may hold an
1660 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1663 // If Scratch2 is live-in then it needs to be saved.
1664 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1665 "Scratch register is live-in and not saved");
1668 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1669 .addReg(ScratchReg2, RegState::Kill);
1671 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1673 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1675 .addReg(ScratchReg2).addImm(1).addReg(0)
1680 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1684 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1685 // It jumps to normal execution of the function body.
1686 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
1688 // On 32 bit we first push the arguments size and then the frame size. On 64
1689 // bit, we pass the stack frame size in r10 and the argument size in r11.
1691 // Functions with nested arguments use R10, so it needs to be saved across
1692 // the call to _morestack
1694 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1695 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1696 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1697 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1698 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1701 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1703 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1705 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1706 .addImm(X86FI->getArgumentStackSize());
1707 MF.getRegInfo().setPhysRegUsed(Reg10);
1708 MF.getRegInfo().setPhysRegUsed(Reg11);
1710 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1711 .addImm(X86FI->getArgumentStackSize());
1712 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1716 // __morestack is in libgcc
1717 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1718 // Under the large code model, we cannot assume that __morestack lives
1719 // within 2^31 bytes of the call site, so we cannot use pc-relative
1720 // addressing. We cannot perform the call via a temporary register,
1721 // as the rax register may be used to store the static chain, and all
1722 // other suitable registers may be either callee-save or used for
1723 // parameter passing. We cannot use the stack at this point either
1724 // because __morestack manipulates the stack directly.
1726 // To avoid these issues, perform an indirect call via a read-only memory
1727 // location containing the address.
1729 // This solution is not perfect, as it assumes that the .rodata section
1730 // is laid out within 2^31 bytes of each function body, but this seems
1731 // to be sufficient for JIT.
1732 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1736 .addExternalSymbol("__morestack_addr")
1738 MF.getMMI().setUsesMorestackAddr(true);
1741 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1742 .addExternalSymbol("__morestack");
1744 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1745 .addExternalSymbol("__morestack");
1749 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1751 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1753 allocMBB->addSuccessor(&PrologueMBB);
1755 checkMBB->addSuccessor(allocMBB);
1756 checkMBB->addSuccessor(&PrologueMBB);
1763 /// Erlang programs may need a special prologue to handle the stack size they
1764 /// might need at runtime. That is because Erlang/OTP does not implement a C
1765 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1766 /// (for more information see Eric Stenman's Ph.D. thesis:
1767 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1770 /// temp0 = sp - MaxStack
1771 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1775 /// call inc_stack # doubles the stack space
1776 /// temp0 = sp - MaxStack
1777 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1778 void X86FrameLowering::adjustForHiPEPrologue(
1779 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1780 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1781 const TargetInstrInfo &TII = *STI.getInstrInfo();
1782 MachineFrameInfo *MFI = MF.getFrameInfo();
1783 const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
1784 const bool Is64Bit = STI.is64Bit();
1785 const bool IsLP64 = STI.isTarget64BitLP64();
1787 // HiPE-specific values
1788 const unsigned HipeLeafWords = 24;
1789 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1790 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1791 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1792 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1793 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1795 assert(STI.isTargetLinux() &&
1796 "HiPE prologue is only supported on Linux operating systems.");
1798 // Compute the largest caller's frame that is needed to fit the callees'
1799 // frames. This 'MaxStack' is computed from:
1801 // a) the fixed frame size, which is the space needed for all spilled temps,
1802 // b) outgoing on-stack parameter areas, and
1803 // c) the minimum stack space this function needs to make available for the
1804 // functions it calls (a tunable ABI property).
1805 if (MFI->hasCalls()) {
1806 unsigned MoreStackForCalls = 0;
1808 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1809 MBBI != MBBE; ++MBBI)
1810 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1815 // Get callee operand.
1816 const MachineOperand &MO = MI->getOperand(0);
1818 // Only take account of global function calls (no closures etc.).
1822 const Function *F = dyn_cast<Function>(MO.getGlobal());
1826 // Do not update 'MaxStack' for primitive and built-in functions
1827 // (encoded with names either starting with "erlang."/"bif_" or not
1828 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1829 // "_", such as the BIF "suspend_0") as they are executed on another
1831 if (F->getName().find("erlang.") != StringRef::npos ||
1832 F->getName().find("bif_") != StringRef::npos ||
1833 F->getName().find_first_of("._") == StringRef::npos)
1836 unsigned CalleeStkArity =
1837 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1838 if (HipeLeafWords - 1 > CalleeStkArity)
1839 MoreStackForCalls = std::max(MoreStackForCalls,
1840 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1842 MaxStack += MoreStackForCalls;
1845 // If the stack frame needed is larger than the guaranteed then runtime checks
1846 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1847 if (MaxStack > Guaranteed) {
1848 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1849 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1851 for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1852 E = PrologueMBB.livein_end();
1854 stackCheckMBB->addLiveIn(*I);
1855 incStackMBB->addLiveIn(*I);
1858 MF.push_front(incStackMBB);
1859 MF.push_front(stackCheckMBB);
1861 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1862 unsigned LEAop, CMPop, CALLop;
1866 LEAop = X86::LEA64r;
1867 CMPop = X86::CMP64rm;
1868 CALLop = X86::CALL64pcrel32;
1869 SPLimitOffset = 0x90;
1873 LEAop = X86::LEA32r;
1874 CMPop = X86::CMP32rm;
1875 CALLop = X86::CALLpcrel32;
1876 SPLimitOffset = 0x4c;
1879 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1880 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1881 "HiPE prologue scratch register is live-in");
1883 // Create new MBB for StackCheck:
1884 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1885 SPReg, false, -MaxStack);
1886 // SPLimitOffset is in a fixed heap location (pointed by BP).
1887 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1888 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1889 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
1891 // Create new MBB for IncStack:
1892 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1893 addExternalSymbol("inc_stack_0");
1894 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1895 SPReg, false, -MaxStack);
1896 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1897 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1898 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1900 stackCheckMBB->addSuccessor(&PrologueMBB, 99);
1901 stackCheckMBB->addSuccessor(incStackMBB, 1);
1902 incStackMBB->addSuccessor(&PrologueMBB, 99);
1903 incStackMBB->addSuccessor(incStackMBB, 1);
1910 void X86FrameLowering::
1911 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1912 MachineBasicBlock::iterator I) const {
1913 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1914 const TargetInstrInfo &TII = *STI.getInstrInfo();
1915 const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
1916 unsigned StackPtr = RegInfo.getStackRegister();
1917 bool reserveCallFrame = hasReservedCallFrame(MF);
1918 unsigned Opcode = I->getOpcode();
1919 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1920 bool IsLP64 = STI.isTarget64BitLP64();
1921 DebugLoc DL = I->getDebugLoc();
1922 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1923 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1926 if (!reserveCallFrame) {
1927 // If the stack pointer can be changed after prologue, turn the
1928 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1929 // adjcallstackdown instruction into 'add ESP, <amt>'
1933 // We need to keep the stack aligned properly. To do this, we round the
1934 // amount of space needed for the outgoing arguments up to the next
1935 // alignment boundary.
1936 unsigned StackAlign = getStackAlignment();
1937 Amount = RoundUpToAlignment(Amount, StackAlign);
1939 MachineInstr *New = nullptr;
1941 // Factor out the amount that gets handled inside the sequence
1942 // (Pushes of argument for frame setup, callee pops for frame destroy)
1943 Amount -= InternalAmt;
1946 if (Opcode == TII.getCallFrameSetupOpcode()) {
1947 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1948 .addReg(StackPtr).addImm(Amount);
1950 assert(Opcode == TII.getCallFrameDestroyOpcode());
1952 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1953 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1954 .addReg(StackPtr).addImm(Amount);
1959 // The EFLAGS implicit def is dead.
1960 New->getOperand(3).setIsDead();
1962 // Replace the pseudo instruction with a new instruction.
1969 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
1970 // If we are performing frame pointer elimination and if the callee pops
1971 // something off the stack pointer, add it back. We do this until we have
1972 // more advanced stack pointer tracking ability.
1973 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
1974 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1975 .addReg(StackPtr).addImm(InternalAmt);
1977 // The EFLAGS implicit def is dead.
1978 New->getOperand(3).setIsDead();
1980 // We are not tracking the stack pointer adjustment by the callee, so make
1981 // sure we restore the stack pointer immediately after the call, there may
1982 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1983 MachineBasicBlock::iterator B = MBB.begin();
1984 while (I != B && !std::prev(I)->isCall())
1990 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1991 assert(MBB.getParent() && "Block is not attached to a function!");
1993 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
1996 // If we cannot use LEA to adjust SP, we may need to use ADD, which
1997 // clobbers the EFLAGS. Check that none of the terminators reads the
1998 // EFLAGS, and if one uses it, conservatively assume this is not
1999 // safe to insert the epilogue here.
2000 return !terminatorsNeedFlagsAsInput(MBB);