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;
349 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
350 MachineBasicBlock::iterator MBBI,
352 MachineFunction &MF = *MBB.getParent();
353 MachineFrameInfo *MFI = MF.getFrameInfo();
354 MachineModuleInfo &MMI = MF.getMMI();
355 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
356 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
358 // Add callee saved registers to move list.
359 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
360 if (CSI.empty()) return;
362 // Calculate offsets.
363 for (std::vector<CalleeSavedInfo>::const_iterator
364 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
365 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
366 unsigned Reg = I->getReg();
368 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
370 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
372 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
373 .addCFIIndex(CFIIndex);
377 /// usesTheStack - This function checks if any of the users of EFLAGS
378 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
379 /// to use the stack, and if we don't adjust the stack we clobber the first
381 /// See X86InstrInfo::copyPhysReg.
382 static bool usesTheStack(const MachineFunction &MF) {
383 const MachineRegisterInfo &MRI = MF.getRegInfo();
385 for (MachineRegisterInfo::reg_instr_iterator
386 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
394 void X86FrameLowering::emitStackProbeCall(MachineFunction &MF,
395 MachineBasicBlock &MBB,
396 MachineBasicBlock::iterator MBBI,
398 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
399 const TargetInstrInfo &TII = *STI.getInstrInfo();
400 bool Is64Bit = STI.is64Bit();
401 bool IsLargeCodeModel = MF.getTarget().getCodeModel() == CodeModel::Large;
405 CallOp = IsLargeCodeModel ? X86::CALL64r : X86::CALL64pcrel32;
407 CallOp = X86::CALLpcrel32;
411 if (STI.isTargetCygMing()) {
412 Symbol = "___chkstk_ms";
416 } else if (STI.isTargetCygMing())
421 MachineInstrBuilder CI;
423 // All current stack probes take AX and SP as input, clobber flags, and
424 // preserve all registers. x86_64 probes leave RSP unmodified.
425 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
426 // For the large code model, we have to call through a register. Use R11,
427 // as it is scratch in all supported calling conventions.
428 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::R11)
429 .addExternalSymbol(Symbol);
430 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addReg(X86::R11);
432 CI = BuildMI(MBB, MBBI, DL, TII.get(CallOp)).addExternalSymbol(Symbol);
435 unsigned AX = Is64Bit ? X86::RAX : X86::EAX;
436 unsigned SP = Is64Bit ? X86::RSP : X86::ESP;
437 CI.addReg(AX, RegState::Implicit)
438 .addReg(SP, RegState::Implicit)
439 .addReg(AX, RegState::Define | RegState::Implicit)
440 .addReg(SP, RegState::Define | RegState::Implicit)
441 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit);
444 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
445 // themselves. It also does not clobber %rax so we can reuse it when
447 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), X86::RSP)
453 static unsigned calculateSetFPREG(uint64_t SPAdjust) {
454 // Win64 ABI has a less restrictive limitation of 240; 128 works equally well
455 // and might require smaller successive adjustments.
456 const uint64_t Win64MaxSEHOffset = 128;
457 uint64_t SEHFrameOffset = std::min(SPAdjust, Win64MaxSEHOffset);
458 // Win64 ABI requires 16-byte alignment for the UWOP_SET_FPREG opcode.
459 return SEHFrameOffset & -16;
462 // If we're forcing a stack realignment we can't rely on just the frame
463 // info, we need to know the ABI stack alignment as well in case we
464 // have a call out. Otherwise just make sure we have some alignment - we'll
465 // go with the minimum SlotSize.
466 static uint64_t calculateMaxStackAlign(const MachineFunction &MF) {
467 const MachineFrameInfo *MFI = MF.getFrameInfo();
468 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
469 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
470 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
471 unsigned SlotSize = RegInfo->getSlotSize();
472 unsigned StackAlign = STI.getFrameLowering()->getStackAlignment();
473 if (ForceStackAlign) {
475 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
476 else if (MaxAlign < SlotSize)
482 /// emitPrologue - Push callee-saved registers onto the stack, which
483 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
484 /// space for local variables. Also emit labels used by the exception handler to
485 /// generate the exception handling frames.
488 Here's a gist of what gets emitted:
490 ; Establish frame pointer, if needed
493 .cfi_def_cfa_offset 16
494 .cfi_offset %rbp, -16
497 .cfi_def_cfa_register %rbp
499 ; Spill general-purpose registers
500 [for all callee-saved GPRs]
503 .cfi_def_cfa_offset (offset from RETADDR)
506 ; If the required stack alignment > default stack alignment
507 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
508 ; of unknown size in the stack frame.
509 [if stack needs re-alignment]
512 ; Allocate space for locals
513 [if target is Windows and allocated space > 4096 bytes]
514 ; Windows needs special care for allocations larger
517 call ___chkstk_ms/___chkstk
523 .seh_stackalloc (size of XMM spill slots)
524 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
529 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
530 ; they may get spilled on any platform, if the current function
531 ; calls @llvm.eh.unwind.init
533 [for all callee-saved XMM registers]
534 movaps %<xmm reg>, -MMM(%rbp)
535 [for all callee-saved XMM registers]
536 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
537 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
539 [for all callee-saved XMM registers]
540 movaps %<xmm reg>, KKK(%rsp)
541 [for all callee-saved XMM registers]
542 .seh_savexmm %<xmm reg>, KKK
546 [if needs base pointer]
548 [if needs to restore base pointer]
553 [for all callee-saved registers]
554 .cfi_offset %<reg>, (offset from %rbp)
556 .cfi_def_cfa_offset (offset from RETADDR)
557 [for all callee-saved registers]
558 .cfi_offset %<reg>, (offset from %rsp)
561 - .seh directives are emitted only for Windows 64 ABI
562 - .cfi directives are emitted for all other ABIs
563 - for 32-bit code, substitute %e?? registers for %r??
566 void X86FrameLowering::emitPrologue(MachineFunction &MF,
567 MachineBasicBlock &MBB) const {
568 MachineBasicBlock::iterator MBBI = MBB.begin();
569 MachineFrameInfo *MFI = MF.getFrameInfo();
570 const Function *Fn = MF.getFunction();
571 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
572 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
573 const TargetInstrInfo &TII = *STI.getInstrInfo();
574 MachineModuleInfo &MMI = MF.getMMI();
575 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
576 uint64_t MaxAlign = calculateMaxStackAlign(MF); // Desired stack alignment.
577 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
578 bool HasFP = hasFP(MF);
579 bool Is64Bit = STI.is64Bit();
580 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
581 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
582 bool IsWin64 = STI.isCallingConvWin64(Fn->getCallingConv());
583 // Not necessarily synonymous with IsWin64.
584 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
585 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
587 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
588 bool UseLEA = STI.useLeaForSP();
589 unsigned SlotSize = RegInfo->getSlotSize();
590 unsigned FramePtr = RegInfo->getFrameRegister(MF);
591 const unsigned MachineFramePtr =
592 STI.isTarget64BitILP32()
593 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
595 unsigned StackPtr = RegInfo->getStackRegister();
596 unsigned BasePtr = RegInfo->getBaseRegister();
599 // Add RETADDR move area to callee saved frame size.
600 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
601 if (TailCallReturnAddrDelta && IsWinEH)
602 report_fatal_error("Can't handle guaranteed tail call under win64 yet");
604 if (TailCallReturnAddrDelta < 0)
605 X86FI->setCalleeSavedFrameSize(
606 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
608 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMachO());
610 // The default stack probe size is 4096 if the function has no stackprobesize
612 unsigned StackProbeSize = 4096;
613 if (Fn->hasFnAttribute("stack-probe-size"))
614 Fn->getFnAttribute("stack-probe-size")
616 .getAsInteger(0, StackProbeSize);
618 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
619 // function, and use up to 128 bytes of stack space, don't have a frame
620 // pointer, calls, or dynamic alloca then we do not need to adjust the
621 // stack pointer (we fit in the Red Zone). We also check that we don't
622 // push and pop from the stack.
623 if (Is64Bit && !Fn->hasFnAttribute(Attribute::NoRedZone) &&
624 !RegInfo->needsStackRealignment(MF) &&
625 !MFI->hasVarSizedObjects() && // No dynamic alloca.
626 !MFI->adjustsStack() && // No calls.
627 !IsWin64 && // Win64 has no Red Zone
628 !usesTheStack(MF) && // Don't push and pop.
629 !MF.shouldSplitStack()) { // Regular stack
630 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
631 if (HasFP) MinSize += SlotSize;
632 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
633 MFI->setStackSize(StackSize);
636 // Insert stack pointer adjustment for later moving of return addr. Only
637 // applies to tail call optimized functions where the callee argument stack
638 // size is bigger than the callers.
639 if (TailCallReturnAddrDelta < 0) {
641 BuildMI(MBB, MBBI, DL,
642 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
645 .addImm(-TailCallReturnAddrDelta)
646 .setMIFlag(MachineInstr::FrameSetup);
647 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
650 // Mapping for machine moves:
652 // DST: VirtualFP AND
653 // SRC: VirtualFP => DW_CFA_def_cfa_offset
654 // ELSE => DW_CFA_def_cfa
656 // SRC: VirtualFP AND
657 // DST: Register => DW_CFA_def_cfa_register
660 // OFFSET < 0 => DW_CFA_offset_extended_sf
661 // REG < 64 => DW_CFA_offset + Reg
662 // ELSE => DW_CFA_offset_extended
664 uint64_t NumBytes = 0;
665 int stackGrowth = -SlotSize;
668 // Calculate required stack adjustment.
669 uint64_t FrameSize = StackSize - SlotSize;
670 // If required, include space for extra hidden slot for stashing base pointer.
671 if (X86FI->getRestoreBasePointer())
672 FrameSize += SlotSize;
674 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
676 // Callee-saved registers are pushed on stack before the stack is realigned.
677 if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
678 NumBytes = RoundUpToAlignment(NumBytes, MaxAlign);
680 // Get the offset of the stack slot for the EBP register, which is
681 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
682 // Update the frame offset adjustment.
683 MFI->setOffsetAdjustment(-NumBytes);
685 // Save EBP/RBP into the appropriate stack slot.
686 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
687 .addReg(MachineFramePtr, RegState::Kill)
688 .setMIFlag(MachineInstr::FrameSetup);
691 // Mark the place where EBP/RBP was saved.
692 // Define the current CFA rule to use the provided offset.
694 unsigned CFIIndex = MMI.addFrameInst(
695 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
696 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
697 .addCFIIndex(CFIIndex);
699 // Change the rule for the FramePtr to be an "offset" rule.
700 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
701 CFIIndex = MMI.addFrameInst(
702 MCCFIInstruction::createOffset(nullptr,
703 DwarfFramePtr, 2 * stackGrowth));
704 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
705 .addCFIIndex(CFIIndex);
709 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
711 .setMIFlag(MachineInstr::FrameSetup);
715 // Update EBP with the new base value.
716 BuildMI(MBB, MBBI, DL,
717 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
720 .setMIFlag(MachineInstr::FrameSetup);
724 // Mark effective beginning of when frame pointer becomes valid.
725 // Define the current CFA to use the EBP/RBP register.
726 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
727 unsigned CFIIndex = MMI.addFrameInst(
728 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
729 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
730 .addCFIIndex(CFIIndex);
733 // Mark the FramePtr as live-in in every block.
734 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
735 I->addLiveIn(MachineFramePtr);
737 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
740 // Skip the callee-saved push instructions.
741 bool PushedRegs = false;
742 int StackOffset = 2 * stackGrowth;
744 while (MBBI != MBB.end() &&
745 (MBBI->getOpcode() == X86::PUSH32r ||
746 MBBI->getOpcode() == X86::PUSH64r)) {
748 unsigned Reg = MBBI->getOperand(0).getReg();
751 if (!HasFP && NeedsDwarfCFI) {
752 // Mark callee-saved push instruction.
753 // Define the current CFA rule to use the provided offset.
755 unsigned CFIIndex = MMI.addFrameInst(
756 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
757 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
758 .addCFIIndex(CFIIndex);
759 StackOffset += stackGrowth;
763 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
764 MachineInstr::FrameSetup);
768 // Realign stack after we pushed callee-saved registers (so that we'll be
769 // able to calculate their offsets from the frame pointer).
770 // Don't do this for Win64, it needs to realign the stack after the prologue.
771 if (!IsWinEH && RegInfo->needsStackRealignment(MF)) {
772 assert(HasFP && "There should be a frame pointer if stack is realigned.");
773 uint64_t Val = -MaxAlign;
775 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
779 .setMIFlag(MachineInstr::FrameSetup);
781 // The EFLAGS implicit def is dead.
782 MI->getOperand(3).setIsDead();
785 // If there is an SUB32ri of ESP immediately before this instruction, merge
786 // the two. This can be the case when tail call elimination is enabled and
787 // the callee has more arguments then the caller.
788 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
790 // Adjust stack pointer: ESP -= numbytes.
792 // Windows and cygwin/mingw require a prologue helper routine when allocating
793 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
794 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
795 // stack and adjust the stack pointer in one go. The 64-bit version of
796 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
797 // responsible for adjusting the stack pointer. Touching the stack at 4K
798 // increments is necessary to ensure that the guard pages used by the OS
799 // virtual memory manager are allocated in correct sequence.
800 uint64_t AlignedNumBytes = NumBytes;
801 if (IsWinEH && RegInfo->needsStackRealignment(MF))
802 AlignedNumBytes = RoundUpToAlignment(AlignedNumBytes, MaxAlign);
803 if (AlignedNumBytes >= StackProbeSize && UseStackProbe) {
804 // Check whether EAX is livein for this function.
805 bool isEAXAlive = isEAXLiveIn(MF);
808 // Sanity check that EAX is not livein for this function.
809 // It should not be, so throw an assert.
810 assert(!Is64Bit && "EAX is livein in x64 case!");
813 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
814 .addReg(X86::EAX, RegState::Kill)
815 .setMIFlag(MachineInstr::FrameSetup);
819 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
820 // Function prologue is responsible for adjusting the stack pointer.
821 if (isUInt<32>(NumBytes)) {
822 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
824 .setMIFlag(MachineInstr::FrameSetup);
825 } else if (isInt<32>(NumBytes)) {
826 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri32), X86::RAX)
828 .setMIFlag(MachineInstr::FrameSetup);
830 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
832 .setMIFlag(MachineInstr::FrameSetup);
835 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
836 // We'll also use 4 already allocated bytes for EAX.
837 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
838 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
839 .setMIFlag(MachineInstr::FrameSetup);
842 // Save a pointer to the MI where we set AX.
843 MachineBasicBlock::iterator SetRAX = MBBI;
846 // Call __chkstk, __chkstk_ms, or __alloca.
847 emitStackProbeCall(MF, MBB, MBBI, DL);
849 // Apply the frame setup flag to all inserted instrs.
850 for (; SetRAX != MBBI; ++SetRAX)
851 SetRAX->setFlag(MachineInstr::FrameSetup);
855 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
857 StackPtr, false, NumBytes - 4);
858 MI->setFlag(MachineInstr::FrameSetup);
859 MBB.insert(MBBI, MI);
861 } else if (NumBytes) {
862 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
863 UseLEA, TII, *RegInfo);
866 if (NeedsWinEH && NumBytes)
867 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
869 .setMIFlag(MachineInstr::FrameSetup);
871 int SEHFrameOffset = 0;
872 if (IsWinEH && HasFP) {
873 SEHFrameOffset = calculateSetFPREG(NumBytes);
875 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(X86::LEA64r), FramePtr),
876 StackPtr, false, SEHFrameOffset);
878 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64rr), FramePtr).addReg(StackPtr);
881 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
883 .addImm(SEHFrameOffset)
884 .setMIFlag(MachineInstr::FrameSetup);
887 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup)) {
888 const MachineInstr *FrameInstr = &*MBBI;
893 if (unsigned Reg = TII.isStoreToStackSlot(FrameInstr, FI)) {
894 if (X86::FR64RegClass.contains(Reg)) {
895 int Offset = getFrameIndexOffset(MF, FI);
896 Offset += SEHFrameOffset;
898 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
901 .setMIFlag(MachineInstr::FrameSetup);
908 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
909 .setMIFlag(MachineInstr::FrameSetup);
911 // Realign stack after we spilled callee-saved registers (so that we'll be
912 // able to calculate their offsets from the frame pointer).
913 // Win64 requires aligning the stack after the prologue.
914 if (IsWinEH && RegInfo->needsStackRealignment(MF)) {
915 assert(HasFP && "There should be a frame pointer if stack is realigned.");
916 uint64_t Val = -MaxAlign;
918 BuildMI(MBB, MBBI, DL, TII.get(getANDriOpcode(Uses64BitFramePtr, Val)),
922 .setMIFlag(MachineInstr::FrameSetup);
924 // The EFLAGS implicit def is dead.
925 MI->getOperand(3).setIsDead();
928 // If we need a base pointer, set it up here. It's whatever the value
929 // of the stack pointer is at this point. Any variable size objects
930 // will be allocated after this, so we can still use the base pointer
931 // to reference locals.
932 if (RegInfo->hasBasePointer(MF)) {
933 // Update the base pointer with the current stack pointer.
934 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
935 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
937 .setMIFlag(MachineInstr::FrameSetup);
938 if (X86FI->getRestoreBasePointer()) {
939 // Stash value of base pointer. Saving RSP instead of EBP shortens dependence chain.
940 unsigned Opm = Uses64BitFramePtr ? X86::MOV64mr : X86::MOV32mr;
941 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opm)),
942 FramePtr, true, X86FI->getRestoreBasePointerOffset())
944 .setMIFlag(MachineInstr::FrameSetup);
948 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
949 // Mark end of stack pointer adjustment.
950 if (!HasFP && NumBytes) {
951 // Define the current CFA rule to use the provided offset.
953 unsigned CFIIndex = MMI.addFrameInst(
954 MCCFIInstruction::createDefCfaOffset(nullptr,
955 -StackSize + stackGrowth));
957 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
958 .addCFIIndex(CFIIndex);
961 // Emit DWARF info specifying the offsets of the callee-saved registers.
963 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
967 bool X86FrameLowering::canUseLEAForSPInEpilogue(
968 const MachineFunction &MF) const {
969 // We can't use LEA instructions for adjusting the stack pointer if this is a
970 // leaf function in the Win64 ABI. Only ADD instructions may be used to
971 // deallocate the stack.
972 // This means that we can use LEA for SP in two situations:
973 // 1. We *aren't* using the Win64 ABI which means we are free to use LEA.
974 // 2. We *have* a frame pointer which means we are permitted to use LEA.
975 return !MF.getTarget().getMCAsmInfo()->usesWindowsCFI() || hasFP(MF);
978 /// Check whether or not the terminators of \p MBB needs to read EFLAGS.
979 static bool terminatorsNeedFlagsAsInput(const MachineBasicBlock &MBB) {
980 for (const MachineInstr &MI : MBB.terminators()) {
981 bool BreakNext = false;
982 for (const MachineOperand &MO : MI.operands()) {
985 unsigned Reg = MO.getReg();
986 if (Reg != X86::EFLAGS)
989 // This terminator needs an eflag that is not defined
990 // by a previous terminator.
1001 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
1002 MachineBasicBlock &MBB) const {
1003 const MachineFrameInfo *MFI = MF.getFrameInfo();
1004 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1005 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1006 const X86RegisterInfo *RegInfo = STI.getRegisterInfo();
1007 const TargetInstrInfo &TII = *STI.getInstrInfo();
1008 MachineBasicBlock::iterator MBBI = MBB.getFirstTerminator();
1010 if (MBBI != MBB.end())
1011 DL = MBBI->getDebugLoc();
1012 bool Is64Bit = STI.is64Bit();
1013 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
1014 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
1015 const bool Is64BitILP32 = STI.isTarget64BitILP32();
1016 unsigned SlotSize = RegInfo->getSlotSize();
1017 unsigned FramePtr = RegInfo->getFrameRegister(MF);
1018 unsigned MachineFramePtr =
1019 Is64BitILP32 ? getX86SubSuperRegister(FramePtr, MVT::i64, false)
1021 unsigned StackPtr = RegInfo->getStackRegister();
1023 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1024 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
1025 bool UseLEAForSP = canUseLEAForSPInEpilogue(MF);
1026 // If we can use LEA for SP but we shouldn't, check that none
1027 // of the terminators uses the eflags. Otherwise we will insert
1028 // a ADD that will redefine the eflags and break the condition.
1029 // Alternatively, we could move the ADD, but this may not be possible
1030 // and is an optimization anyway.
1031 if (UseLEAForSP && !MF.getSubtarget<X86Subtarget>().useLeaForSP())
1032 UseLEAForSP = terminatorsNeedFlagsAsInput(MBB);
1033 // If that assert breaks, that means we do not do the right thing
1034 // in canUseAsEpilogue.
1035 assert((UseLEAForSP || !terminatorsNeedFlagsAsInput(MBB)) &&
1036 "We shouldn't have allowed this insertion point");
1038 // Get the number of bytes to allocate from the FrameInfo.
1039 uint64_t StackSize = MFI->getStackSize();
1040 uint64_t MaxAlign = calculateMaxStackAlign(MF);
1041 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1042 uint64_t NumBytes = 0;
1045 // Calculate required stack adjustment.
1046 uint64_t FrameSize = StackSize - SlotSize;
1047 NumBytes = FrameSize - CSSize;
1049 // Callee-saved registers were pushed on stack before the stack was
1051 if (RegInfo->needsStackRealignment(MF) && !IsWinEH)
1052 NumBytes = RoundUpToAlignment(FrameSize, MaxAlign);
1055 BuildMI(MBB, MBBI, DL,
1056 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
1058 NumBytes = StackSize - CSSize;
1060 uint64_t SEHStackAllocAmt = NumBytes;
1062 // Skip the callee-saved pop instructions.
1063 while (MBBI != MBB.begin()) {
1064 MachineBasicBlock::iterator PI = std::prev(MBBI);
1065 unsigned Opc = PI->getOpcode();
1067 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
1068 !PI->isTerminator())
1073 MachineBasicBlock::iterator FirstCSPop = MBBI;
1075 if (MBBI != MBB.end())
1076 DL = MBBI->getDebugLoc();
1078 // If there is an ADD32ri or SUB32ri of ESP immediately before this
1079 // instruction, merge the two instructions.
1080 if (NumBytes || MFI->hasVarSizedObjects())
1081 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
1083 // If dynamic alloca is used, then reset esp to point to the last callee-saved
1084 // slot before popping them off! Same applies for the case, when stack was
1086 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
1087 if (RegInfo->needsStackRealignment(MF))
1089 unsigned SEHFrameOffset = calculateSetFPREG(SEHStackAllocAmt);
1090 uint64_t LEAAmount = IsWinEH ? SEHStackAllocAmt - SEHFrameOffset : -CSSize;
1092 // There are only two legal forms of epilogue:
1093 // - add SEHAllocationSize, %rsp
1094 // - lea SEHAllocationSize(%FramePtr), %rsp
1096 // 'mov %FramePtr, %rsp' will not be recognized as an epilogue sequence.
1097 // However, we may use this sequence if we have a frame pointer because the
1098 // effects of the prologue can safely be undone.
1099 if (LEAAmount != 0) {
1100 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
1101 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
1102 FramePtr, false, LEAAmount);
1105 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
1106 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
1110 } else if (NumBytes) {
1111 // Adjust stack pointer back: ESP += numbytes.
1112 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr,
1113 UseLEAForSP, TII, *RegInfo);
1117 // Windows unwinder will not invoke function's exception handler if IP is
1118 // either in prologue or in epilogue. This behavior causes a problem when a
1119 // call immediately precedes an epilogue, because the return address points
1120 // into the epilogue. To cope with that, we insert an epilogue marker here,
1121 // then replace it with a 'nop' if it ends up immediately after a CALL in the
1122 // final emitted code.
1124 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
1126 // Add the return addr area delta back since we are not tail calling.
1127 int Offset = -1 * X86FI->getTCReturnAddrDelta();
1128 assert(Offset >= 0 && "TCDelta should never be positive");
1130 MBBI = MBB.getFirstTerminator();
1132 // Check for possible merge with preceding ADD instruction.
1133 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1134 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1135 UseLEAForSP, TII, *RegInfo);
1139 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1141 const X86RegisterInfo *RegInfo =
1142 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1143 const MachineFrameInfo *MFI = MF.getFrameInfo();
1144 // Offset will hold the offset from the stack pointer at function entry to the
1146 // We need to factor in additional offsets applied during the prologue to the
1147 // frame, base, and stack pointer depending on which is used.
1148 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1149 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1150 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
1151 uint64_t StackSize = MFI->getStackSize();
1152 unsigned SlotSize = RegInfo->getSlotSize();
1153 bool HasFP = hasFP(MF);
1154 bool IsWinEH = MF.getTarget().getMCAsmInfo()->usesWindowsCFI();
1155 int64_t FPDelta = 0;
1158 assert(!MFI->hasCalls() || (StackSize % 16) == 8);
1160 // Calculate required stack adjustment.
1161 uint64_t FrameSize = StackSize - SlotSize;
1162 // If required, include space for extra hidden slot for stashing base pointer.
1163 if (X86FI->getRestoreBasePointer())
1164 FrameSize += SlotSize;
1165 uint64_t NumBytes = FrameSize - CSSize;
1167 uint64_t SEHFrameOffset = calculateSetFPREG(NumBytes);
1168 if (FI && FI == X86FI->getFAIndex())
1169 return -SEHFrameOffset;
1171 // FPDelta is the offset from the "traditional" FP location of the old base
1172 // pointer followed by return address and the location required by the
1173 // restricted Win64 prologue.
1174 // Add FPDelta to all offsets below that go through the frame pointer.
1175 FPDelta = FrameSize - SEHFrameOffset;
1176 assert((!MFI->hasCalls() || (FPDelta % 16) == 0) &&
1177 "FPDelta isn't aligned per the Win64 ABI!");
1181 if (RegInfo->hasBasePointer(MF)) {
1182 assert(HasFP && "VLAs and dynamic stack realign, but no FP?!");
1184 // Skip the saved EBP.
1185 return Offset + SlotSize + FPDelta;
1187 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1188 return Offset + StackSize;
1190 } else if (RegInfo->needsStackRealignment(MF)) {
1192 // Skip the saved EBP.
1193 return Offset + SlotSize + FPDelta;
1195 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1196 return Offset + StackSize;
1198 // FIXME: Support tail calls
1201 return Offset + StackSize;
1203 // Skip the saved EBP.
1206 // Skip the RETADDR move area
1207 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1208 if (TailCallReturnAddrDelta < 0)
1209 Offset -= TailCallReturnAddrDelta;
1212 return Offset + FPDelta;
1215 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1216 unsigned &FrameReg) const {
1217 const X86RegisterInfo *RegInfo =
1218 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1219 // We can't calculate offset from frame pointer if the stack is realigned,
1220 // so enforce usage of stack/base pointer. The base pointer is used when we
1221 // have dynamic allocas in addition to dynamic realignment.
1222 if (RegInfo->hasBasePointer(MF))
1223 FrameReg = RegInfo->getBaseRegister();
1224 else if (RegInfo->needsStackRealignment(MF))
1225 FrameReg = RegInfo->getStackRegister();
1227 FrameReg = RegInfo->getFrameRegister(MF);
1228 return getFrameIndexOffset(MF, FI);
1231 // Simplified from getFrameIndexOffset keeping only StackPointer cases
1232 int X86FrameLowering::getFrameIndexOffsetFromSP(const MachineFunction &MF, int FI) const {
1233 const MachineFrameInfo *MFI = MF.getFrameInfo();
1234 // Does not include any dynamic realign.
1235 const uint64_t StackSize = MFI->getStackSize();
1238 const X86RegisterInfo *RegInfo =
1239 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1240 // Note: LLVM arranges the stack as:
1241 // Args > Saved RetPC (<--FP) > CSRs > dynamic alignment (<--BP)
1242 // > "Stack Slots" (<--SP)
1243 // We can always address StackSlots from RSP. We can usually (unless
1244 // needsStackRealignment) address CSRs from RSP, but sometimes need to
1245 // address them from RBP. FixedObjects can be placed anywhere in the stack
1246 // frame depending on their specific requirements (i.e. we can actually
1247 // refer to arguments to the function which are stored in the *callers*
1248 // frame). As a result, THE RESULT OF THIS CALL IS MEANINGLESS FOR CSRs
1249 // AND FixedObjects IFF needsStackRealignment or hasVarSizedObject.
1251 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1253 // We don't handle tail calls, and shouldn't be seeing them
1255 int TailCallReturnAddrDelta =
1256 MF.getInfo<X86MachineFunctionInfo>()->getTCReturnAddrDelta();
1257 assert(!(TailCallReturnAddrDelta < 0) && "we don't handle this case!");
1261 // This is how the math works out:
1263 // %rsp grows (i.e. gets lower) left to right. Each box below is
1264 // one word (eight bytes). Obj0 is the stack slot we're trying to
1267 // ----------------------------------
1268 // | BP | Obj0 | Obj1 | ... | ObjN |
1269 // ----------------------------------
1273 // A is the incoming stack pointer.
1274 // (B - A) is the local area offset (-8 for x86-64) [1]
1275 // (C - A) is the Offset returned by MFI->getObjectOffset for Obj0 [2]
1277 // |(E - B)| is the StackSize (absolute value, positive). For a
1278 // stack that grown down, this works out to be (B - E). [3]
1280 // E is also the value of %rsp after stack has been set up, and we
1281 // want (C - E) -- the value we can add to %rsp to get to Obj0. Now
1282 // (C - E) == (C - A) - (B - A) + (B - E)
1283 // { Using [1], [2] and [3] above }
1284 // == getObjectOffset - LocalAreaOffset + StackSize
1287 // Get the Offset from the StackPointer
1288 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1290 return Offset + StackSize;
1292 // Simplified from getFrameIndexReference keeping only StackPointer cases
1293 int X86FrameLowering::getFrameIndexReferenceFromSP(const MachineFunction &MF,
1295 unsigned &FrameReg) const {
1296 const X86RegisterInfo *RegInfo =
1297 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1298 assert(!RegInfo->hasBasePointer(MF) && "we don't handle this case");
1300 FrameReg = RegInfo->getStackRegister();
1301 return getFrameIndexOffsetFromSP(MF, FI);
1304 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1305 MachineFunction &MF, const TargetRegisterInfo *TRI,
1306 std::vector<CalleeSavedInfo> &CSI) const {
1307 MachineFrameInfo *MFI = MF.getFrameInfo();
1308 const X86RegisterInfo *RegInfo =
1309 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1310 unsigned SlotSize = RegInfo->getSlotSize();
1311 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1313 unsigned CalleeSavedFrameSize = 0;
1314 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1317 // emitPrologue always spills frame register the first thing.
1318 SpillSlotOffset -= SlotSize;
1319 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1321 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1322 // the frame register, we can delete it from CSI list and not have to worry
1323 // about avoiding it later.
1324 unsigned FPReg = RegInfo->getFrameRegister(MF);
1325 for (unsigned i = 0; i < CSI.size(); ++i) {
1326 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1327 CSI.erase(CSI.begin() + i);
1333 // Assign slots for GPRs. It increases frame size.
1334 for (unsigned i = CSI.size(); i != 0; --i) {
1335 unsigned Reg = CSI[i - 1].getReg();
1337 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1340 SpillSlotOffset -= SlotSize;
1341 CalleeSavedFrameSize += SlotSize;
1343 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1344 CSI[i - 1].setFrameIdx(SlotIndex);
1347 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1349 // Assign slots for XMMs.
1350 for (unsigned i = CSI.size(); i != 0; --i) {
1351 unsigned Reg = CSI[i - 1].getReg();
1352 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1355 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1357 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1359 SpillSlotOffset -= RC->getSize();
1361 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1362 CSI[i - 1].setFrameIdx(SlotIndex);
1363 MFI->ensureMaxAlignment(RC->getAlignment());
1369 bool X86FrameLowering::spillCalleeSavedRegisters(
1370 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1371 const std::vector<CalleeSavedInfo> &CSI,
1372 const TargetRegisterInfo *TRI) const {
1373 DebugLoc DL = MBB.findDebugLoc(MI);
1375 MachineFunction &MF = *MBB.getParent();
1376 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1377 const TargetInstrInfo &TII = *STI.getInstrInfo();
1379 // Push GPRs. It increases frame size.
1380 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1381 for (unsigned i = CSI.size(); i != 0; --i) {
1382 unsigned Reg = CSI[i - 1].getReg();
1384 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1386 // Add the callee-saved register as live-in. It's killed at the spill.
1389 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1390 .setMIFlag(MachineInstr::FrameSetup);
1393 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1394 // It can be done by spilling XMMs to stack frame.
1395 for (unsigned i = CSI.size(); i != 0; --i) {
1396 unsigned Reg = CSI[i-1].getReg();
1397 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1399 // Add the callee-saved register as live-in. It's killed at the spill.
1401 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1403 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1406 MI->setFlag(MachineInstr::FrameSetup);
1413 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1414 MachineBasicBlock::iterator MI,
1415 const std::vector<CalleeSavedInfo> &CSI,
1416 const TargetRegisterInfo *TRI) const {
1420 DebugLoc DL = MBB.findDebugLoc(MI);
1422 MachineFunction &MF = *MBB.getParent();
1423 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1424 const TargetInstrInfo &TII = *STI.getInstrInfo();
1426 // Reload XMMs from stack frame.
1427 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1428 unsigned Reg = CSI[i].getReg();
1429 if (X86::GR64RegClass.contains(Reg) ||
1430 X86::GR32RegClass.contains(Reg))
1433 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1434 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1438 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1439 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1440 unsigned Reg = CSI[i].getReg();
1441 if (!X86::GR64RegClass.contains(Reg) &&
1442 !X86::GR32RegClass.contains(Reg))
1445 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1451 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1452 RegScavenger *RS) const {
1453 MachineFrameInfo *MFI = MF.getFrameInfo();
1454 const X86RegisterInfo *RegInfo =
1455 MF.getSubtarget<X86Subtarget>().getRegisterInfo();
1456 unsigned SlotSize = RegInfo->getSlotSize();
1458 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1459 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1461 if (TailCallReturnAddrDelta < 0) {
1462 // create RETURNADDR area
1471 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1472 TailCallReturnAddrDelta - SlotSize, true);
1475 // Spill the BasePtr if it's used.
1476 if (RegInfo->hasBasePointer(MF))
1477 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1481 HasNestArgument(const MachineFunction *MF) {
1482 const Function *F = MF->getFunction();
1483 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1485 if (I->hasNestAttr())
1491 /// GetScratchRegister - Get a temp register for performing work in the
1492 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1493 /// and the properties of the function either one or two registers will be
1494 /// needed. Set primary to true for the first register, false for the second.
1496 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1497 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1500 if (CallingConvention == CallingConv::HiPE) {
1502 return Primary ? X86::R14 : X86::R13;
1504 return Primary ? X86::EBX : X86::EDI;
1509 return Primary ? X86::R11 : X86::R12;
1511 return Primary ? X86::R11D : X86::R12D;
1514 bool IsNested = HasNestArgument(&MF);
1516 if (CallingConvention == CallingConv::X86_FastCall ||
1517 CallingConvention == CallingConv::Fast) {
1519 report_fatal_error("Segmented stacks does not support fastcall with "
1520 "nested function.");
1521 return Primary ? X86::EAX : X86::ECX;
1524 return Primary ? X86::EDX : X86::EAX;
1525 return Primary ? X86::ECX : X86::EAX;
1528 // The stack limit in the TCB is set to this many bytes above the actual stack
1530 static const uint64_t kSplitStackAvailable = 256;
1532 void X86FrameLowering::adjustForSegmentedStacks(
1533 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1534 MachineFrameInfo *MFI = MF.getFrameInfo();
1535 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1536 const TargetInstrInfo &TII = *STI.getInstrInfo();
1538 bool Is64Bit = STI.is64Bit();
1539 const bool IsLP64 = STI.isTarget64BitLP64();
1540 unsigned TlsReg, TlsOffset;
1543 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1544 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1545 "Scratch register is live-in");
1547 if (MF.getFunction()->isVarArg())
1548 report_fatal_error("Segmented stacks do not support vararg functions.");
1549 if (!STI.isTargetLinux() && !STI.isTargetDarwin() && !STI.isTargetWin32() &&
1550 !STI.isTargetWin64() && !STI.isTargetFreeBSD() &&
1551 !STI.isTargetDragonFly())
1552 report_fatal_error("Segmented stacks not supported on this platform.");
1554 // Eventually StackSize will be calculated by a link-time pass; which will
1555 // also decide whether checking code needs to be injected into this particular
1557 StackSize = MFI->getStackSize();
1559 // Do not generate a prologue for functions with a stack of size zero
1563 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1564 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1565 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1566 bool IsNested = false;
1568 // We need to know if the function has a nest argument only in 64 bit mode.
1570 IsNested = HasNestArgument(&MF);
1572 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1573 // allocMBB needs to be last (terminating) instruction.
1575 for (MachineBasicBlock::livein_iterator i = PrologueMBB.livein_begin(),
1576 e = PrologueMBB.livein_end();
1578 allocMBB->addLiveIn(*i);
1579 checkMBB->addLiveIn(*i);
1583 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1585 MF.push_front(allocMBB);
1586 MF.push_front(checkMBB);
1588 // When the frame size is less than 256 we just compare the stack
1589 // boundary directly to the value of the stack pointer, per gcc.
1590 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1592 // Read the limit off the current stacklet off the stack_guard location.
1594 if (STI.isTargetLinux()) {
1596 TlsOffset = IsLP64 ? 0x70 : 0x40;
1597 } else if (STI.isTargetDarwin()) {
1599 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1600 } else if (STI.isTargetWin64()) {
1602 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1603 } else if (STI.isTargetFreeBSD()) {
1606 } else if (STI.isTargetDragonFly()) {
1608 TlsOffset = 0x20; // use tls_tcb.tcb_segstack
1610 report_fatal_error("Segmented stacks not supported on this platform.");
1613 if (CompareStackPointer)
1614 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1616 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1617 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1619 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1620 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1622 if (STI.isTargetLinux()) {
1625 } else if (STI.isTargetDarwin()) {
1627 TlsOffset = 0x48 + 90*4;
1628 } else if (STI.isTargetWin32()) {
1630 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1631 } else if (STI.isTargetDragonFly()) {
1633 TlsOffset = 0x10; // use tls_tcb.tcb_segstack
1634 } else if (STI.isTargetFreeBSD()) {
1635 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1637 report_fatal_error("Segmented stacks not supported on this platform.");
1640 if (CompareStackPointer)
1641 ScratchReg = X86::ESP;
1643 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1644 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1646 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64() ||
1647 STI.isTargetDragonFly()) {
1648 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1649 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1650 } else if (STI.isTargetDarwin()) {
1652 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1653 unsigned ScratchReg2;
1655 if (CompareStackPointer) {
1656 // The primary scratch register is available for holding the TLS offset.
1657 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1658 SaveScratch2 = false;
1660 // Need to use a second register to hold the TLS offset
1661 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1663 // Unfortunately, with fastcc the second scratch register may hold an
1665 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1668 // If Scratch2 is live-in then it needs to be saved.
1669 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1670 "Scratch register is live-in and not saved");
1673 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1674 .addReg(ScratchReg2, RegState::Kill);
1676 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1678 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1680 .addReg(ScratchReg2).addImm(1).addReg(0)
1685 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1689 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1690 // It jumps to normal execution of the function body.
1691 BuildMI(checkMBB, DL, TII.get(X86::JA_1)).addMBB(&PrologueMBB);
1693 // On 32 bit we first push the arguments size and then the frame size. On 64
1694 // bit, we pass the stack frame size in r10 and the argument size in r11.
1696 // Functions with nested arguments use R10, so it needs to be saved across
1697 // the call to _morestack
1699 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1700 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1701 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1702 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1703 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1706 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1708 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1710 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1711 .addImm(X86FI->getArgumentStackSize());
1712 MF.getRegInfo().setPhysRegUsed(Reg10);
1713 MF.getRegInfo().setPhysRegUsed(Reg11);
1715 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1716 .addImm(X86FI->getArgumentStackSize());
1717 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1721 // __morestack is in libgcc
1722 if (Is64Bit && MF.getTarget().getCodeModel() == CodeModel::Large) {
1723 // Under the large code model, we cannot assume that __morestack lives
1724 // within 2^31 bytes of the call site, so we cannot use pc-relative
1725 // addressing. We cannot perform the call via a temporary register,
1726 // as the rax register may be used to store the static chain, and all
1727 // other suitable registers may be either callee-save or used for
1728 // parameter passing. We cannot use the stack at this point either
1729 // because __morestack manipulates the stack directly.
1731 // To avoid these issues, perform an indirect call via a read-only memory
1732 // location containing the address.
1734 // This solution is not perfect, as it assumes that the .rodata section
1735 // is laid out within 2^31 bytes of each function body, but this seems
1736 // to be sufficient for JIT.
1737 BuildMI(allocMBB, DL, TII.get(X86::CALL64m))
1741 .addExternalSymbol("__morestack_addr")
1743 MF.getMMI().setUsesMorestackAddr(true);
1746 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1747 .addExternalSymbol("__morestack");
1749 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1750 .addExternalSymbol("__morestack");
1754 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1756 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1758 allocMBB->addSuccessor(&PrologueMBB);
1760 checkMBB->addSuccessor(allocMBB);
1761 checkMBB->addSuccessor(&PrologueMBB);
1768 /// Erlang programs may need a special prologue to handle the stack size they
1769 /// might need at runtime. That is because Erlang/OTP does not implement a C
1770 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1771 /// (for more information see Eric Stenman's Ph.D. thesis:
1772 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1775 /// temp0 = sp - MaxStack
1776 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1780 /// call inc_stack # doubles the stack space
1781 /// temp0 = sp - MaxStack
1782 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1783 void X86FrameLowering::adjustForHiPEPrologue(
1784 MachineFunction &MF, MachineBasicBlock &PrologueMBB) const {
1785 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1786 const TargetInstrInfo &TII = *STI.getInstrInfo();
1787 MachineFrameInfo *MFI = MF.getFrameInfo();
1788 const unsigned SlotSize = STI.getRegisterInfo()->getSlotSize();
1789 const bool Is64Bit = STI.is64Bit();
1790 const bool IsLP64 = STI.isTarget64BitLP64();
1792 // HiPE-specific values
1793 const unsigned HipeLeafWords = 24;
1794 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1795 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1796 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1797 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1798 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1800 assert(STI.isTargetLinux() &&
1801 "HiPE prologue is only supported on Linux operating systems.");
1803 // Compute the largest caller's frame that is needed to fit the callees'
1804 // frames. This 'MaxStack' is computed from:
1806 // a) the fixed frame size, which is the space needed for all spilled temps,
1807 // b) outgoing on-stack parameter areas, and
1808 // c) the minimum stack space this function needs to make available for the
1809 // functions it calls (a tunable ABI property).
1810 if (MFI->hasCalls()) {
1811 unsigned MoreStackForCalls = 0;
1813 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1814 MBBI != MBBE; ++MBBI)
1815 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1820 // Get callee operand.
1821 const MachineOperand &MO = MI->getOperand(0);
1823 // Only take account of global function calls (no closures etc.).
1827 const Function *F = dyn_cast<Function>(MO.getGlobal());
1831 // Do not update 'MaxStack' for primitive and built-in functions
1832 // (encoded with names either starting with "erlang."/"bif_" or not
1833 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1834 // "_", such as the BIF "suspend_0") as they are executed on another
1836 if (F->getName().find("erlang.") != StringRef::npos ||
1837 F->getName().find("bif_") != StringRef::npos ||
1838 F->getName().find_first_of("._") == StringRef::npos)
1841 unsigned CalleeStkArity =
1842 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1843 if (HipeLeafWords - 1 > CalleeStkArity)
1844 MoreStackForCalls = std::max(MoreStackForCalls,
1845 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1847 MaxStack += MoreStackForCalls;
1850 // If the stack frame needed is larger than the guaranteed then runtime checks
1851 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1852 if (MaxStack > Guaranteed) {
1853 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1854 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1856 for (MachineBasicBlock::livein_iterator I = PrologueMBB.livein_begin(),
1857 E = PrologueMBB.livein_end();
1859 stackCheckMBB->addLiveIn(*I);
1860 incStackMBB->addLiveIn(*I);
1863 MF.push_front(incStackMBB);
1864 MF.push_front(stackCheckMBB);
1866 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1867 unsigned LEAop, CMPop, CALLop;
1871 LEAop = X86::LEA64r;
1872 CMPop = X86::CMP64rm;
1873 CALLop = X86::CALL64pcrel32;
1874 SPLimitOffset = 0x90;
1878 LEAop = X86::LEA32r;
1879 CMPop = X86::CMP32rm;
1880 CALLop = X86::CALLpcrel32;
1881 SPLimitOffset = 0x4c;
1884 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1885 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1886 "HiPE prologue scratch register is live-in");
1888 // Create new MBB for StackCheck:
1889 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1890 SPReg, false, -MaxStack);
1891 // SPLimitOffset is in a fixed heap location (pointed by BP).
1892 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1893 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1894 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_1)).addMBB(&PrologueMBB);
1896 // Create new MBB for IncStack:
1897 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1898 addExternalSymbol("inc_stack_0");
1899 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1900 SPReg, false, -MaxStack);
1901 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1902 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1903 BuildMI(incStackMBB, DL, TII.get(X86::JLE_1)).addMBB(incStackMBB);
1905 stackCheckMBB->addSuccessor(&PrologueMBB, 99);
1906 stackCheckMBB->addSuccessor(incStackMBB, 1);
1907 incStackMBB->addSuccessor(&PrologueMBB, 99);
1908 incStackMBB->addSuccessor(incStackMBB, 1);
1915 void X86FrameLowering::
1916 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1917 MachineBasicBlock::iterator I) const {
1918 const X86Subtarget &STI = MF.getSubtarget<X86Subtarget>();
1919 const TargetInstrInfo &TII = *STI.getInstrInfo();
1920 const X86RegisterInfo &RegInfo = *STI.getRegisterInfo();
1921 unsigned StackPtr = RegInfo.getStackRegister();
1922 bool reserveCallFrame = hasReservedCallFrame(MF);
1923 unsigned Opcode = I->getOpcode();
1924 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1925 bool IsLP64 = STI.isTarget64BitLP64();
1926 DebugLoc DL = I->getDebugLoc();
1927 uint64_t Amount = !reserveCallFrame ? I->getOperand(0).getImm() : 0;
1928 uint64_t InternalAmt = (isDestroy || Amount) ? I->getOperand(1).getImm() : 0;
1931 if (!reserveCallFrame) {
1932 // If the stack pointer can be changed after prologue, turn the
1933 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1934 // adjcallstackdown instruction into 'add ESP, <amt>'
1938 // We need to keep the stack aligned properly. To do this, we round the
1939 // amount of space needed for the outgoing arguments up to the next
1940 // alignment boundary.
1941 unsigned StackAlign = getStackAlignment();
1942 Amount = RoundUpToAlignment(Amount, StackAlign);
1944 MachineInstr *New = nullptr;
1946 // Factor out the amount that gets handled inside the sequence
1947 // (Pushes of argument for frame setup, callee pops for frame destroy)
1948 Amount -= InternalAmt;
1951 if (Opcode == TII.getCallFrameSetupOpcode()) {
1952 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)), StackPtr)
1953 .addReg(StackPtr).addImm(Amount);
1955 assert(Opcode == TII.getCallFrameDestroyOpcode());
1957 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1958 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1959 .addReg(StackPtr).addImm(Amount);
1964 // The EFLAGS implicit def is dead.
1965 New->getOperand(3).setIsDead();
1967 // Replace the pseudo instruction with a new instruction.
1974 if (Opcode == TII.getCallFrameDestroyOpcode() && InternalAmt) {
1975 // If we are performing frame pointer elimination and if the callee pops
1976 // something off the stack pointer, add it back. We do this until we have
1977 // more advanced stack pointer tracking ability.
1978 unsigned Opc = getSUBriOpcode(IsLP64, InternalAmt);
1979 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1980 .addReg(StackPtr).addImm(InternalAmt);
1982 // The EFLAGS implicit def is dead.
1983 New->getOperand(3).setIsDead();
1985 // We are not tracking the stack pointer adjustment by the callee, so make
1986 // sure we restore the stack pointer immediately after the call, there may
1987 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1988 MachineBasicBlock::iterator B = MBB.begin();
1989 while (I != B && !std::prev(I)->isCall())
1995 bool X86FrameLowering::canUseAsEpilogue(const MachineBasicBlock &MBB) const {
1996 assert(MBB.getParent() && "Block is not attached to a function!");
1998 if (canUseLEAForSPInEpilogue(*MBB.getParent()))
2001 // If we cannot use LEA to adjust SP, we may need to use ADD, which
2002 // clobbers the EFLAGS. Check that none of the terminators reads the
2003 // EFLAGS, and if one uses it, conservatively assume this is not
2004 // safe to insert the epilogue here.
2005 return !terminatorsNeedFlagsAsInput(MBB);