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();
44 /// hasFP - Return true if the specified function should have a dedicated frame
45 /// pointer register. This is true if the function has variable sized allocas
46 /// or if frame pointer elimination is disabled.
47 bool X86FrameLowering::hasFP(const MachineFunction &MF) const {
48 const MachineFrameInfo *MFI = MF.getFrameInfo();
49 const MachineModuleInfo &MMI = MF.getMMI();
50 const TargetRegisterInfo *RegInfo = MF.getSubtarget().getRegisterInfo();
52 return (MF.getTarget().Options.DisableFramePointerElim(MF) ||
53 RegInfo->needsStackRealignment(MF) ||
54 MFI->hasVarSizedObjects() ||
55 MFI->isFrameAddressTaken() || MFI->hasInlineAsmWithSPAdjust() ||
56 MF.getInfo<X86MachineFunctionInfo>()->getForceFramePointer() ||
57 MMI.callsUnwindInit() || MMI.callsEHReturn() ||
58 MFI->hasStackMap() || MFI->hasPatchPoint());
61 static unsigned getSUBriOpcode(unsigned IsLP64, int64_t Imm) {
65 return X86::SUB64ri32;
73 static unsigned getADDriOpcode(unsigned IsLP64, int64_t Imm) {
77 return X86::ADD64ri32;
85 static unsigned getLEArOpcode(unsigned IsLP64) {
86 return IsLP64 ? X86::LEA64r : X86::LEA32r;
89 /// findDeadCallerSavedReg - Return a caller-saved register that isn't live
90 /// when it reaches the "return" instruction. We can then pop a stack object
91 /// to this register without worry about clobbering it.
92 static unsigned findDeadCallerSavedReg(MachineBasicBlock &MBB,
93 MachineBasicBlock::iterator &MBBI,
94 const TargetRegisterInfo &TRI,
96 const MachineFunction *MF = MBB.getParent();
97 const Function *F = MF->getFunction();
98 if (!F || MF->getMMI().callsEHReturn())
101 static const uint16_t CallerSavedRegs32Bit[] = {
102 X86::EAX, X86::EDX, X86::ECX, 0
105 static const uint16_t CallerSavedRegs64Bit[] = {
106 X86::RAX, X86::RDX, X86::RCX, X86::RSI, X86::RDI,
107 X86::R8, X86::R9, X86::R10, X86::R11, 0
110 unsigned Opc = MBBI->getOpcode();
117 case X86::TCRETURNdi:
118 case X86::TCRETURNri:
119 case X86::TCRETURNmi:
120 case X86::TCRETURNdi64:
121 case X86::TCRETURNri64:
122 case X86::TCRETURNmi64:
124 case X86::EH_RETURN64: {
125 SmallSet<uint16_t, 8> Uses;
126 for (unsigned i = 0, e = MBBI->getNumOperands(); i != e; ++i) {
127 MachineOperand &MO = MBBI->getOperand(i);
128 if (!MO.isReg() || MO.isDef())
130 unsigned Reg = MO.getReg();
133 for (MCRegAliasIterator AI(Reg, &TRI, true); AI.isValid(); ++AI)
137 const uint16_t *CS = Is64Bit ? CallerSavedRegs64Bit : CallerSavedRegs32Bit;
139 if (!Uses.count(*CS))
148 /// emitSPUpdate - Emit a series of instructions to increment / decrement the
149 /// stack pointer by a constant value.
151 void emitSPUpdate(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
152 unsigned StackPtr, int64_t NumBytes,
153 bool Is64BitTarget, bool Is64BitStackPtr, bool UseLEA,
154 const TargetInstrInfo &TII, const TargetRegisterInfo &TRI) {
155 bool isSub = NumBytes < 0;
156 uint64_t Offset = isSub ? -NumBytes : NumBytes;
159 Opc = getLEArOpcode(Is64BitStackPtr);
162 ? getSUBriOpcode(Is64BitStackPtr, Offset)
163 : getADDriOpcode(Is64BitStackPtr, Offset);
165 uint64_t Chunk = (1LL << 31) - 1;
166 DebugLoc DL = MBB.findDebugLoc(MBBI);
169 uint64_t ThisVal = (Offset > Chunk) ? Chunk : Offset;
170 if (ThisVal == (Is64BitTarget ? 8 : 4)) {
171 // Use push / pop instead.
173 ? (unsigned)(Is64BitTarget ? X86::RAX : X86::EAX)
174 : findDeadCallerSavedReg(MBB, MBBI, TRI, Is64BitTarget);
177 ? (Is64BitTarget ? X86::PUSH64r : X86::PUSH32r)
178 : (Is64BitTarget ? X86::POP64r : X86::POP32r);
179 MachineInstr *MI = BuildMI(MBB, MBBI, DL, TII.get(Opc))
180 .addReg(Reg, getDefRegState(!isSub) | getUndefRegState(isSub));
182 MI->setFlag(MachineInstr::FrameSetup);
188 MachineInstr *MI = nullptr;
191 MI = addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
192 StackPtr, false, isSub ? -ThisVal : ThisVal);
194 MI = BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
197 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
201 MI->setFlag(MachineInstr::FrameSetup);
207 /// mergeSPUpdatesUp - Merge two stack-manipulating instructions upper iterator.
209 void mergeSPUpdatesUp(MachineBasicBlock &MBB, MachineBasicBlock::iterator &MBBI,
210 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
211 if (MBBI == MBB.begin()) return;
213 MachineBasicBlock::iterator PI = std::prev(MBBI);
214 unsigned Opc = PI->getOpcode();
215 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
216 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
217 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
218 PI->getOperand(0).getReg() == StackPtr) {
220 *NumBytes += PI->getOperand(2).getImm();
222 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
223 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
224 PI->getOperand(0).getReg() == StackPtr) {
226 *NumBytes -= PI->getOperand(2).getImm();
231 /// mergeSPUpdatesDown - Merge two stack-manipulating instructions lower
234 void mergeSPUpdatesDown(MachineBasicBlock &MBB,
235 MachineBasicBlock::iterator &MBBI,
236 unsigned StackPtr, uint64_t *NumBytes = nullptr) {
237 // FIXME: THIS ISN'T RUN!!!
240 if (MBBI == MBB.end()) return;
242 MachineBasicBlock::iterator NI = std::next(MBBI);
243 if (NI == MBB.end()) return;
245 unsigned Opc = NI->getOpcode();
246 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
247 Opc == X86::ADD32ri || Opc == X86::ADD32ri8) &&
248 NI->getOperand(0).getReg() == StackPtr) {
250 *NumBytes -= NI->getOperand(2).getImm();
253 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
254 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
255 NI->getOperand(0).getReg() == StackPtr) {
257 *NumBytes += NI->getOperand(2).getImm();
263 /// mergeSPUpdates - Checks the instruction before/after the passed
264 /// instruction. If it is an ADD/SUB/LEA instruction it is deleted argument and
265 /// the stack adjustment is returned as a positive value for ADD/LEA and a
266 /// negative for SUB.
267 static int mergeSPUpdates(MachineBasicBlock &MBB,
268 MachineBasicBlock::iterator &MBBI, unsigned StackPtr,
269 bool doMergeWithPrevious) {
270 if ((doMergeWithPrevious && MBBI == MBB.begin()) ||
271 (!doMergeWithPrevious && MBBI == MBB.end()))
274 MachineBasicBlock::iterator PI = doMergeWithPrevious ? std::prev(MBBI) : MBBI;
275 MachineBasicBlock::iterator NI = doMergeWithPrevious ? nullptr
277 unsigned Opc = PI->getOpcode();
280 if ((Opc == X86::ADD64ri32 || Opc == X86::ADD64ri8 ||
281 Opc == X86::ADD32ri || Opc == X86::ADD32ri8 ||
282 Opc == X86::LEA32r || Opc == X86::LEA64_32r) &&
283 PI->getOperand(0).getReg() == StackPtr){
284 Offset += PI->getOperand(2).getImm();
286 if (!doMergeWithPrevious) MBBI = NI;
287 } else if ((Opc == X86::SUB64ri32 || Opc == X86::SUB64ri8 ||
288 Opc == X86::SUB32ri || Opc == X86::SUB32ri8) &&
289 PI->getOperand(0).getReg() == StackPtr) {
290 Offset -= PI->getOperand(2).getImm();
292 if (!doMergeWithPrevious) MBBI = NI;
298 static bool isEAXLiveIn(MachineFunction &MF) {
299 for (MachineRegisterInfo::livein_iterator II = MF.getRegInfo().livein_begin(),
300 EE = MF.getRegInfo().livein_end(); II != EE; ++II) {
301 unsigned Reg = II->first;
303 if (Reg == X86::EAX || Reg == X86::AX ||
304 Reg == X86::AH || Reg == X86::AL)
312 X86FrameLowering::emitCalleeSavedFrameMoves(MachineBasicBlock &MBB,
313 MachineBasicBlock::iterator MBBI,
315 MachineFunction &MF = *MBB.getParent();
316 MachineFrameInfo *MFI = MF.getFrameInfo();
317 MachineModuleInfo &MMI = MF.getMMI();
318 const MCRegisterInfo *MRI = MMI.getContext().getRegisterInfo();
319 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
321 // Add callee saved registers to move list.
322 const std::vector<CalleeSavedInfo> &CSI = MFI->getCalleeSavedInfo();
323 if (CSI.empty()) return;
325 // Calculate offsets.
326 for (std::vector<CalleeSavedInfo>::const_iterator
327 I = CSI.begin(), E = CSI.end(); I != E; ++I) {
328 int64_t Offset = MFI->getObjectOffset(I->getFrameIdx());
329 unsigned Reg = I->getReg();
331 unsigned DwarfReg = MRI->getDwarfRegNum(Reg, true);
333 MMI.addFrameInst(MCCFIInstruction::createOffset(nullptr, DwarfReg,
335 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
336 .addCFIIndex(CFIIndex);
340 /// usesTheStack - This function checks if any of the users of EFLAGS
341 /// copies the EFLAGS. We know that the code that lowers COPY of EFLAGS has
342 /// to use the stack, and if we don't adjust the stack we clobber the first
344 /// See X86InstrInfo::copyPhysReg.
345 static bool usesTheStack(const MachineFunction &MF) {
346 const MachineRegisterInfo &MRI = MF.getRegInfo();
348 for (MachineRegisterInfo::reg_instr_iterator
349 ri = MRI.reg_instr_begin(X86::EFLAGS), re = MRI.reg_instr_end();
357 void X86FrameLowering::getStackProbeFunction(const X86Subtarget &STI,
359 const char *&Symbol) {
360 CallOp = STI.is64Bit() ? X86::W64ALLOCA : X86::CALLpcrel32;
363 if (STI.isTargetCygMing()) {
364 Symbol = "___chkstk_ms";
368 } else if (STI.isTargetCygMing())
374 /// emitPrologue - Push callee-saved registers onto the stack, which
375 /// automatically adjust the stack pointer. Adjust the stack pointer to allocate
376 /// space for local variables. Also emit labels used by the exception handler to
377 /// generate the exception handling frames.
380 Here's a gist of what gets emitted:
382 ; Establish frame pointer, if needed
385 .cfi_def_cfa_offset 16
386 .cfi_offset %rbp, -16
389 .cfi_def_cfa_register %rbp
391 ; Spill general-purpose registers
392 [for all callee-saved GPRs]
395 .cfi_def_cfa_offset (offset from RETADDR)
398 ; If the required stack alignment > default stack alignment
399 ; rsp needs to be re-aligned. This creates a "re-alignment gap"
400 ; of unknown size in the stack frame.
401 [if stack needs re-alignment]
404 ; Allocate space for locals
405 [if target is Windows and allocated space > 4096 bytes]
406 ; Windows needs special care for allocations larger
409 call ___chkstk_ms/___chkstk
415 .seh_stackalloc (size of XMM spill slots)
416 .seh_setframe %rbp, SEHFrameOffset ; = size of all spill slots
421 ; Note, that while only Windows 64 ABI specifies XMMs as callee-preserved,
422 ; they may get spilled on any platform, if the current function
423 ; calls @llvm.eh.unwind.init
425 [for all callee-saved XMM registers]
426 movaps %<xmm reg>, -MMM(%rbp)
427 [for all callee-saved XMM registers]
428 .seh_savexmm %<xmm reg>, (-MMM + SEHFrameOffset)
429 ; i.e. the offset relative to (%rbp - SEHFrameOffset)
431 [for all callee-saved XMM registers]
432 movaps %<xmm reg>, KKK(%rsp)
433 [for all callee-saved XMM registers]
434 .seh_savexmm %<xmm reg>, KKK
438 [if needs base pointer]
443 [for all callee-saved registers]
444 .cfi_offset %<reg>, (offset from %rbp)
446 .cfi_def_cfa_offset (offset from RETADDR)
447 [for all callee-saved registers]
448 .cfi_offset %<reg>, (offset from %rsp)
451 - .seh directives are emitted only for Windows 64 ABI
452 - .cfi directives are emitted for all other ABIs
453 - for 32-bit code, substitute %e?? registers for %r??
456 void X86FrameLowering::emitPrologue(MachineFunction &MF) const {
457 MachineBasicBlock &MBB = MF.front(); // Prologue goes in entry BB.
458 MachineBasicBlock::iterator MBBI = MBB.begin();
459 MachineFrameInfo *MFI = MF.getFrameInfo();
460 const Function *Fn = MF.getFunction();
461 const X86RegisterInfo *RegInfo =
462 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
463 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
464 MachineModuleInfo &MMI = MF.getMMI();
465 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
466 uint64_t MaxAlign = MFI->getMaxAlignment(); // Desired stack alignment.
467 uint64_t StackSize = MFI->getStackSize(); // Number of bytes to allocate.
468 bool HasFP = hasFP(MF);
469 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
470 bool Is64Bit = STI.is64Bit();
471 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
472 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
473 bool IsWin64 = STI.isTargetWin64();
475 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
476 ExceptionHandling::WinEH; // Not necessarily synonymous with IsWin64.
477 bool NeedsWinEH = IsWinEH && Fn->needsUnwindTableEntry();
479 !IsWinEH && (MMI.hasDebugInfo() || Fn->needsUnwindTableEntry());
480 bool UseLEA = STI.useLeaForSP();
481 unsigned StackAlign = getStackAlignment();
482 unsigned SlotSize = RegInfo->getSlotSize();
483 unsigned FramePtr = RegInfo->getFrameRegister(MF);
484 const unsigned MachineFramePtr = STI.isTarget64BitILP32() ?
485 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
486 unsigned StackPtr = RegInfo->getStackRegister();
487 unsigned BasePtr = RegInfo->getBaseRegister();
490 // If we're forcing a stack realignment we can't rely on just the frame
491 // info, we need to know the ABI stack alignment as well in case we
492 // have a call out. Otherwise just make sure we have some alignment - we'll
493 // go with the minimum SlotSize.
494 if (ForceStackAlign) {
496 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
497 else if (MaxAlign < SlotSize)
501 // Add RETADDR move area to callee saved frame size.
502 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
503 if (TailCallReturnAddrDelta < 0)
504 X86FI->setCalleeSavedFrameSize(
505 X86FI->getCalleeSavedFrameSize() - TailCallReturnAddrDelta);
507 bool UseStackProbe = (STI.isOSWindows() && !STI.isTargetMacho());
509 // If this is x86-64 and the Red Zone is not disabled, if we are a leaf
510 // function, and use up to 128 bytes of stack space, don't have a frame
511 // pointer, calls, or dynamic alloca then we do not need to adjust the
512 // stack pointer (we fit in the Red Zone). We also check that we don't
513 // push and pop from the stack.
514 if (Is64Bit && !Fn->getAttributes().hasAttribute(AttributeSet::FunctionIndex,
515 Attribute::NoRedZone) &&
516 !RegInfo->needsStackRealignment(MF) &&
517 !MFI->hasVarSizedObjects() && // No dynamic alloca.
518 !MFI->adjustsStack() && // No calls.
519 !IsWin64 && // Win64 has no Red Zone
520 !usesTheStack(MF) && // Don't push and pop.
521 !MF.shouldSplitStack()) { // Regular stack
522 uint64_t MinSize = X86FI->getCalleeSavedFrameSize();
523 if (HasFP) MinSize += SlotSize;
524 StackSize = std::max(MinSize, StackSize > 128 ? StackSize - 128 : 0);
525 MFI->setStackSize(StackSize);
528 // Insert stack pointer adjustment for later moving of return addr. Only
529 // applies to tail call optimized functions where the callee argument stack
530 // size is bigger than the callers.
531 if (TailCallReturnAddrDelta < 0) {
533 BuildMI(MBB, MBBI, DL,
534 TII.get(getSUBriOpcode(Uses64BitFramePtr, -TailCallReturnAddrDelta)),
537 .addImm(-TailCallReturnAddrDelta)
538 .setMIFlag(MachineInstr::FrameSetup);
539 MI->getOperand(3).setIsDead(); // The EFLAGS implicit def is dead.
542 // Mapping for machine moves:
544 // DST: VirtualFP AND
545 // SRC: VirtualFP => DW_CFA_def_cfa_offset
546 // ELSE => DW_CFA_def_cfa
548 // SRC: VirtualFP AND
549 // DST: Register => DW_CFA_def_cfa_register
552 // OFFSET < 0 => DW_CFA_offset_extended_sf
553 // REG < 64 => DW_CFA_offset + Reg
554 // ELSE => DW_CFA_offset_extended
556 uint64_t NumBytes = 0;
557 int stackGrowth = -SlotSize;
560 // Calculate required stack adjustment.
561 uint64_t FrameSize = StackSize - SlotSize;
562 if (RegInfo->needsStackRealignment(MF)) {
563 // Callee-saved registers are pushed on stack before the stack
565 FrameSize -= X86FI->getCalleeSavedFrameSize();
566 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
568 NumBytes = FrameSize - X86FI->getCalleeSavedFrameSize();
571 // Get the offset of the stack slot for the EBP register, which is
572 // guaranteed to be the last slot by processFunctionBeforeFrameFinalized.
573 // Update the frame offset adjustment.
574 MFI->setOffsetAdjustment(-NumBytes);
576 // Save EBP/RBP into the appropriate stack slot.
577 BuildMI(MBB, MBBI, DL, TII.get(Is64Bit ? X86::PUSH64r : X86::PUSH32r))
578 .addReg(MachineFramePtr, RegState::Kill)
579 .setMIFlag(MachineInstr::FrameSetup);
582 // Mark the place where EBP/RBP was saved.
583 // Define the current CFA rule to use the provided offset.
585 unsigned CFIIndex = MMI.addFrameInst(
586 MCCFIInstruction::createDefCfaOffset(nullptr, 2 * stackGrowth));
587 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
588 .addCFIIndex(CFIIndex);
590 // Change the rule for the FramePtr to be an "offset" rule.
591 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
592 CFIIndex = MMI.addFrameInst(
593 MCCFIInstruction::createOffset(nullptr,
594 DwarfFramePtr, 2 * stackGrowth));
595 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
596 .addCFIIndex(CFIIndex);
600 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg))
602 .setMIFlag(MachineInstr::FrameSetup);
605 // Update EBP with the new base value.
606 BuildMI(MBB, MBBI, DL,
607 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr), FramePtr)
609 .setMIFlag(MachineInstr::FrameSetup);
612 // Mark effective beginning of when frame pointer becomes valid.
613 // Define the current CFA to use the EBP/RBP register.
614 unsigned DwarfFramePtr = RegInfo->getDwarfRegNum(MachineFramePtr, true);
615 unsigned CFIIndex = MMI.addFrameInst(
616 MCCFIInstruction::createDefCfaRegister(nullptr, DwarfFramePtr));
617 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
618 .addCFIIndex(CFIIndex);
621 // Mark the FramePtr as live-in in every block.
622 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
623 I->addLiveIn(MachineFramePtr);
625 NumBytes = StackSize - X86FI->getCalleeSavedFrameSize();
628 // Skip the callee-saved push instructions.
629 bool PushedRegs = false;
630 int StackOffset = 2 * stackGrowth;
632 while (MBBI != MBB.end() &&
633 (MBBI->getOpcode() == X86::PUSH32r ||
634 MBBI->getOpcode() == X86::PUSH64r)) {
636 unsigned Reg = MBBI->getOperand(0).getReg();
639 if (!HasFP && NeedsDwarfCFI) {
640 // Mark callee-saved push instruction.
641 // Define the current CFA rule to use the provided offset.
643 unsigned CFIIndex = MMI.addFrameInst(
644 MCCFIInstruction::createDefCfaOffset(nullptr, StackOffset));
645 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
646 .addCFIIndex(CFIIndex);
647 StackOffset += stackGrowth;
651 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_PushReg)).addImm(Reg).setMIFlag(
652 MachineInstr::FrameSetup);
656 // Realign stack after we pushed callee-saved registers (so that we'll be
657 // able to calculate their offsets from the frame pointer).
658 if (RegInfo->needsStackRealignment(MF)) {
659 assert(HasFP && "There should be a frame pointer if stack is realigned.");
661 BuildMI(MBB, MBBI, DL,
662 TII.get(Uses64BitFramePtr ? X86::AND64ri32 : X86::AND32ri), StackPtr)
665 .setMIFlag(MachineInstr::FrameSetup);
667 // The EFLAGS implicit def is dead.
668 MI->getOperand(3).setIsDead();
671 // If there is an SUB32ri of ESP immediately before this instruction, merge
672 // the two. This can be the case when tail call elimination is enabled and
673 // the callee has more arguments then the caller.
674 NumBytes -= mergeSPUpdates(MBB, MBBI, StackPtr, true);
676 // If there is an ADD32ri or SUB32ri of ESP immediately after this
677 // instruction, merge the two instructions.
678 mergeSPUpdatesDown(MBB, MBBI, StackPtr, &NumBytes);
680 // Adjust stack pointer: ESP -= numbytes.
682 static const size_t PageSize = 4096;
684 // Windows and cygwin/mingw require a prologue helper routine when allocating
685 // more than 4K bytes on the stack. Windows uses __chkstk and cygwin/mingw
686 // uses __alloca. __alloca and the 32-bit version of __chkstk will probe the
687 // stack and adjust the stack pointer in one go. The 64-bit version of
688 // __chkstk is only responsible for probing the stack. The 64-bit prologue is
689 // responsible for adjusting the stack pointer. Touching the stack at 4K
690 // increments is necessary to ensure that the guard pages used by the OS
691 // virtual memory manager are allocated in correct sequence.
692 if (NumBytes >= PageSize && UseStackProbe) {
693 const char *StackProbeSymbol;
696 getStackProbeFunction(STI, CallOp, StackProbeSymbol);
698 // Check whether EAX is livein for this function.
699 bool isEAXAlive = isEAXLiveIn(MF);
702 // Sanity check that EAX is not livein for this function.
703 // It should not be, so throw an assert.
704 assert(!Is64Bit && "EAX is livein in x64 case!");
707 BuildMI(MBB, MBBI, DL, TII.get(X86::PUSH32r))
708 .addReg(X86::EAX, RegState::Kill)
709 .setMIFlag(MachineInstr::FrameSetup);
713 // Handle the 64-bit Windows ABI case where we need to call __chkstk.
714 // Function prologue is responsible for adjusting the stack pointer.
715 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV64ri), X86::RAX)
717 .setMIFlag(MachineInstr::FrameSetup);
719 // Allocate NumBytes-4 bytes on stack in case of isEAXAlive.
720 // We'll also use 4 already allocated bytes for EAX.
721 BuildMI(MBB, MBBI, DL, TII.get(X86::MOV32ri), X86::EAX)
722 .addImm(isEAXAlive ? NumBytes - 4 : NumBytes)
723 .setMIFlag(MachineInstr::FrameSetup);
726 BuildMI(MBB, MBBI, DL,
728 .addExternalSymbol(StackProbeSymbol)
729 .addReg(StackPtr, RegState::Define | RegState::Implicit)
730 .addReg(X86::EFLAGS, RegState::Define | RegState::Implicit)
731 .setMIFlag(MachineInstr::FrameSetup);
734 // MSVC x64's __chkstk and cygwin/mingw's ___chkstk_ms do not adjust %rsp
735 // themself. It also does not clobber %rax so we can reuse it when
737 BuildMI(MBB, MBBI, DL, TII.get(X86::SUB64rr), StackPtr)
740 .setMIFlag(MachineInstr::FrameSetup);
744 MachineInstr *MI = addRegOffset(BuildMI(MF, DL, TII.get(X86::MOV32rm),
746 StackPtr, false, NumBytes - 4);
747 MI->setFlag(MachineInstr::FrameSetup);
748 MBB.insert(MBBI, MI);
750 } else if (NumBytes) {
751 emitSPUpdate(MBB, MBBI, StackPtr, -(int64_t)NumBytes, Is64Bit, Uses64BitFramePtr,
752 UseLEA, TII, *RegInfo);
755 int SEHFrameOffset = 0;
758 // We need to set frame base offset low enough such that all saved
759 // register offsets would be positive relative to it, but we can't
760 // just use NumBytes, because .seh_setframe offset must be <=240.
761 // So we pretend to have only allocated enough space to spill the
762 // non-volatile registers.
763 // We don't care about the rest of stack allocation, because unwinder
764 // will restore SP to (BP - SEHFrameOffset)
765 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
766 int offset = MFI->getObjectOffset(Info.getFrameIdx());
767 SEHFrameOffset = std::max(SEHFrameOffset, std::abs(offset));
769 SEHFrameOffset += SEHFrameOffset % 16; // ensure alignmant
771 // This only needs to account for XMM spill slots, GPR slots
772 // are covered by the .seh_pushreg's emitted above.
773 unsigned Size = SEHFrameOffset - X86FI->getCalleeSavedFrameSize();
775 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
777 .setMIFlag(MachineInstr::FrameSetup);
780 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SetFrame))
782 .addImm(SEHFrameOffset)
783 .setMIFlag(MachineInstr::FrameSetup);
785 // SP will be the base register for restoring XMMs
787 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_StackAlloc))
789 .setMIFlag(MachineInstr::FrameSetup);
794 // Skip the rest of register spilling code
795 while (MBBI != MBB.end() && MBBI->getFlag(MachineInstr::FrameSetup))
798 // Emit SEH info for non-GPRs
800 for (const CalleeSavedInfo &Info : MFI->getCalleeSavedInfo()) {
801 unsigned Reg = Info.getReg();
802 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
804 assert(X86::FR64RegClass.contains(Reg) && "Unexpected register class");
806 int Offset = getFrameIndexOffset(MF, Info.getFrameIdx());
807 Offset += SEHFrameOffset;
809 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_SaveXMM))
812 .setMIFlag(MachineInstr::FrameSetup);
815 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_EndPrologue))
816 .setMIFlag(MachineInstr::FrameSetup);
819 // If we need a base pointer, set it up here. It's whatever the value
820 // of the stack pointer is at this point. Any variable size objects
821 // will be allocated after this, so we can still use the base pointer
822 // to reference locals.
823 if (RegInfo->hasBasePointer(MF)) {
824 // Update the base pointer with the current stack pointer.
825 unsigned Opc = Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr;
826 BuildMI(MBB, MBBI, DL, TII.get(Opc), BasePtr)
828 .setMIFlag(MachineInstr::FrameSetup);
831 if (((!HasFP && NumBytes) || PushedRegs) && NeedsDwarfCFI) {
832 // Mark end of stack pointer adjustment.
833 if (!HasFP && NumBytes) {
834 // Define the current CFA rule to use the provided offset.
836 unsigned CFIIndex = MMI.addFrameInst(
837 MCCFIInstruction::createDefCfaOffset(nullptr,
838 -StackSize + stackGrowth));
840 BuildMI(MBB, MBBI, DL, TII.get(TargetOpcode::CFI_INSTRUCTION))
841 .addCFIIndex(CFIIndex);
844 // Emit DWARF info specifying the offsets of the callee-saved registers.
846 emitCalleeSavedFrameMoves(MBB, MBBI, DL);
850 void X86FrameLowering::emitEpilogue(MachineFunction &MF,
851 MachineBasicBlock &MBB) const {
852 const MachineFrameInfo *MFI = MF.getFrameInfo();
853 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
854 const X86RegisterInfo *RegInfo =
855 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
856 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
857 MachineBasicBlock::iterator MBBI = MBB.getLastNonDebugInstr();
858 assert(MBBI != MBB.end() && "Returning block has no instructions");
859 unsigned RetOpcode = MBBI->getOpcode();
860 DebugLoc DL = MBBI->getDebugLoc();
861 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
862 bool Is64Bit = STI.is64Bit();
863 // standard x86_64 and NaCl use 64-bit frame/stack pointers, x32 - 32-bit.
864 const bool Uses64BitFramePtr = STI.isTarget64BitLP64() || STI.isTargetNaCl64();
865 const bool Is64BitILP32 = STI.isTarget64BitILP32();
866 bool UseLEA = STI.useLeaForSP();
867 unsigned StackAlign = getStackAlignment();
868 unsigned SlotSize = RegInfo->getSlotSize();
869 unsigned FramePtr = RegInfo->getFrameRegister(MF);
870 unsigned MachineFramePtr = Is64BitILP32 ?
871 getX86SubSuperRegister(FramePtr, MVT::i64, false) : FramePtr;
872 unsigned StackPtr = RegInfo->getStackRegister();
875 MF.getTarget().getMCAsmInfo()->getExceptionHandlingType() ==
876 ExceptionHandling::WinEH;
877 bool NeedsWinEH = IsWinEH && MF.getFunction()->needsUnwindTableEntry();
881 llvm_unreachable("Can only insert epilog into returning blocks");
886 case X86::TCRETURNdi:
887 case X86::TCRETURNri:
888 case X86::TCRETURNmi:
889 case X86::TCRETURNdi64:
890 case X86::TCRETURNri64:
891 case X86::TCRETURNmi64:
893 case X86::EH_RETURN64:
894 break; // These are ok
897 // Get the number of bytes to allocate from the FrameInfo.
898 uint64_t StackSize = MFI->getStackSize();
899 uint64_t MaxAlign = MFI->getMaxAlignment();
900 unsigned CSSize = X86FI->getCalleeSavedFrameSize();
901 uint64_t NumBytes = 0;
903 // If we're forcing a stack realignment we can't rely on just the frame
904 // info, we need to know the ABI stack alignment as well in case we
905 // have a call out. Otherwise just make sure we have some alignment - we'll
906 // go with the minimum.
907 if (ForceStackAlign) {
909 MaxAlign = (StackAlign > MaxAlign) ? StackAlign : MaxAlign;
911 MaxAlign = MaxAlign ? MaxAlign : 4;
915 // Calculate required stack adjustment.
916 uint64_t FrameSize = StackSize - SlotSize;
917 if (RegInfo->needsStackRealignment(MF)) {
918 // Callee-saved registers were pushed on stack before the stack
921 NumBytes = (FrameSize + MaxAlign - 1) / MaxAlign * MaxAlign;
923 NumBytes = FrameSize - CSSize;
927 BuildMI(MBB, MBBI, DL,
928 TII.get(Is64Bit ? X86::POP64r : X86::POP32r), MachineFramePtr);
930 NumBytes = StackSize - CSSize;
933 // Skip the callee-saved pop instructions.
934 while (MBBI != MBB.begin()) {
935 MachineBasicBlock::iterator PI = std::prev(MBBI);
936 unsigned Opc = PI->getOpcode();
938 if (Opc != X86::POP32r && Opc != X86::POP64r && Opc != X86::DBG_VALUE &&
944 MachineBasicBlock::iterator FirstCSPop = MBBI;
946 DL = MBBI->getDebugLoc();
948 // If there is an ADD32ri or SUB32ri of ESP immediately before this
949 // instruction, merge the two instructions.
950 if (NumBytes || MFI->hasVarSizedObjects())
951 mergeSPUpdatesUp(MBB, MBBI, StackPtr, &NumBytes);
953 // If dynamic alloca is used, then reset esp to point to the last callee-saved
954 // slot before popping them off! Same applies for the case, when stack was
956 if (RegInfo->needsStackRealignment(MF) || MFI->hasVarSizedObjects()) {
957 if (RegInfo->needsStackRealignment(MF))
960 unsigned Opc = getLEArOpcode(Uses64BitFramePtr);
961 addRegOffset(BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr),
962 FramePtr, false, -CSSize);
965 unsigned Opc = (Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr);
966 BuildMI(MBB, MBBI, DL, TII.get(Opc), StackPtr)
970 } else if (NumBytes) {
971 // Adjust stack pointer back: ESP += numbytes.
972 emitSPUpdate(MBB, MBBI, StackPtr, NumBytes, Is64Bit, Uses64BitFramePtr, UseLEA,
977 // Windows unwinder will not invoke function's exception handler if IP is
978 // either in prologue or in epilogue. This behavior causes a problem when a
979 // call immediately precedes an epilogue, because the return address points
980 // into the epilogue. To cope with that, we insert an epilogue marker here,
981 // then replace it with a 'nop' if it ends up immediately after a CALL in the
982 // final emitted code.
984 BuildMI(MBB, MBBI, DL, TII.get(X86::SEH_Epilogue));
986 // We're returning from function via eh_return.
987 if (RetOpcode == X86::EH_RETURN || RetOpcode == X86::EH_RETURN64) {
988 MBBI = MBB.getLastNonDebugInstr();
989 MachineOperand &DestAddr = MBBI->getOperand(0);
990 assert(DestAddr.isReg() && "Offset should be in register!");
991 BuildMI(MBB, MBBI, DL,
992 TII.get(Uses64BitFramePtr ? X86::MOV64rr : X86::MOV32rr),
993 StackPtr).addReg(DestAddr.getReg());
994 } else if (RetOpcode == X86::TCRETURNri || RetOpcode == X86::TCRETURNdi ||
995 RetOpcode == X86::TCRETURNmi ||
996 RetOpcode == X86::TCRETURNri64 || RetOpcode == X86::TCRETURNdi64 ||
997 RetOpcode == X86::TCRETURNmi64) {
998 bool isMem = RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64;
999 // Tail call return: adjust the stack pointer and jump to callee.
1000 MBBI = MBB.getLastNonDebugInstr();
1001 MachineOperand &JumpTarget = MBBI->getOperand(0);
1002 MachineOperand &StackAdjust = MBBI->getOperand(isMem ? 5 : 1);
1003 assert(StackAdjust.isImm() && "Expecting immediate value.");
1005 // Adjust stack pointer.
1006 int StackAdj = StackAdjust.getImm();
1007 int MaxTCDelta = X86FI->getTCReturnAddrDelta();
1009 assert(MaxTCDelta <= 0 && "MaxTCDelta should never be positive");
1011 // Incoporate the retaddr area.
1012 Offset = StackAdj-MaxTCDelta;
1013 assert(Offset >= 0 && "Offset should never be negative");
1016 // Check for possible merge with preceding ADD instruction.
1017 Offset += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1018 emitSPUpdate(MBB, MBBI, StackPtr, Offset, Is64Bit, Uses64BitFramePtr,
1019 UseLEA, TII, *RegInfo);
1022 // Jump to label or value in register.
1023 if (RetOpcode == X86::TCRETURNdi || RetOpcode == X86::TCRETURNdi64) {
1024 MachineInstrBuilder MIB =
1025 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNdi)
1026 ? X86::TAILJMPd : X86::TAILJMPd64));
1027 if (JumpTarget.isGlobal())
1028 MIB.addGlobalAddress(JumpTarget.getGlobal(), JumpTarget.getOffset(),
1029 JumpTarget.getTargetFlags());
1031 assert(JumpTarget.isSymbol());
1032 MIB.addExternalSymbol(JumpTarget.getSymbolName(),
1033 JumpTarget.getTargetFlags());
1035 } else if (RetOpcode == X86::TCRETURNmi || RetOpcode == X86::TCRETURNmi64) {
1036 MachineInstrBuilder MIB =
1037 BuildMI(MBB, MBBI, DL, TII.get((RetOpcode == X86::TCRETURNmi)
1038 ? X86::TAILJMPm : X86::TAILJMPm64));
1039 for (unsigned i = 0; i != 5; ++i)
1040 MIB.addOperand(MBBI->getOperand(i));
1041 } else if (RetOpcode == X86::TCRETURNri64) {
1042 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr64)).
1043 addReg(JumpTarget.getReg(), RegState::Kill);
1045 BuildMI(MBB, MBBI, DL, TII.get(X86::TAILJMPr)).
1046 addReg(JumpTarget.getReg(), RegState::Kill);
1049 MachineInstr *NewMI = std::prev(MBBI);
1050 NewMI->copyImplicitOps(MF, MBBI);
1052 // Delete the pseudo instruction TCRETURN.
1054 } else if ((RetOpcode == X86::RETQ || RetOpcode == X86::RETL ||
1055 RetOpcode == X86::RETIQ || RetOpcode == X86::RETIL) &&
1056 (X86FI->getTCReturnAddrDelta() < 0)) {
1057 // Add the return addr area delta back since we are not tail calling.
1058 int delta = -1*X86FI->getTCReturnAddrDelta();
1059 MBBI = MBB.getLastNonDebugInstr();
1061 // Check for possible merge with preceding ADD instruction.
1062 delta += mergeSPUpdates(MBB, MBBI, StackPtr, true);
1063 emitSPUpdate(MBB, MBBI, StackPtr, delta, Is64Bit, Uses64BitFramePtr, UseLEA, TII,
1068 int X86FrameLowering::getFrameIndexOffset(const MachineFunction &MF,
1070 const X86RegisterInfo *RegInfo =
1071 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1072 const MachineFrameInfo *MFI = MF.getFrameInfo();
1073 int Offset = MFI->getObjectOffset(FI) - getOffsetOfLocalArea();
1074 uint64_t StackSize = MFI->getStackSize();
1076 if (RegInfo->hasBasePointer(MF)) {
1077 assert (hasFP(MF) && "VLAs and dynamic stack realign, but no FP?!");
1079 // Skip the saved EBP.
1080 return Offset + RegInfo->getSlotSize();
1082 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1083 return Offset + StackSize;
1085 } else if (RegInfo->needsStackRealignment(MF)) {
1087 // Skip the saved EBP.
1088 return Offset + RegInfo->getSlotSize();
1090 assert((-(Offset + StackSize)) % MFI->getObjectAlignment(FI) == 0);
1091 return Offset + StackSize;
1093 // FIXME: Support tail calls
1096 return Offset + StackSize;
1098 // Skip the saved EBP.
1099 Offset += RegInfo->getSlotSize();
1101 // Skip the RETADDR move area
1102 const X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1103 int TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1104 if (TailCallReturnAddrDelta < 0)
1105 Offset -= TailCallReturnAddrDelta;
1111 int X86FrameLowering::getFrameIndexReference(const MachineFunction &MF, int FI,
1112 unsigned &FrameReg) const {
1113 const X86RegisterInfo *RegInfo =
1114 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1115 // We can't calculate offset from frame pointer if the stack is realigned,
1116 // so enforce usage of stack/base pointer. The base pointer is used when we
1117 // have dynamic allocas in addition to dynamic realignment.
1118 if (RegInfo->hasBasePointer(MF))
1119 FrameReg = RegInfo->getBaseRegister();
1120 else if (RegInfo->needsStackRealignment(MF))
1121 FrameReg = RegInfo->getStackRegister();
1123 FrameReg = RegInfo->getFrameRegister(MF);
1124 return getFrameIndexOffset(MF, FI);
1127 bool X86FrameLowering::assignCalleeSavedSpillSlots(
1128 MachineFunction &MF, const TargetRegisterInfo *TRI,
1129 std::vector<CalleeSavedInfo> &CSI) const {
1130 MachineFrameInfo *MFI = MF.getFrameInfo();
1131 const X86RegisterInfo *RegInfo =
1132 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1133 unsigned SlotSize = RegInfo->getSlotSize();
1134 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1136 unsigned CalleeSavedFrameSize = 0;
1137 int SpillSlotOffset = getOffsetOfLocalArea() + X86FI->getTCReturnAddrDelta();
1140 // emitPrologue always spills frame register the first thing.
1141 SpillSlotOffset -= SlotSize;
1142 MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1144 // Since emitPrologue and emitEpilogue will handle spilling and restoring of
1145 // the frame register, we can delete it from CSI list and not have to worry
1146 // about avoiding it later.
1147 unsigned FPReg = RegInfo->getFrameRegister(MF);
1148 for (unsigned i = 0; i < CSI.size(); ++i) {
1149 if (TRI->regsOverlap(CSI[i].getReg(),FPReg)) {
1150 CSI.erase(CSI.begin() + i);
1156 // Assign slots for GPRs. It increases frame size.
1157 for (unsigned i = CSI.size(); i != 0; --i) {
1158 unsigned Reg = CSI[i - 1].getReg();
1160 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1163 SpillSlotOffset -= SlotSize;
1164 CalleeSavedFrameSize += SlotSize;
1166 int SlotIndex = MFI->CreateFixedSpillStackObject(SlotSize, SpillSlotOffset);
1167 CSI[i - 1].setFrameIdx(SlotIndex);
1170 X86FI->setCalleeSavedFrameSize(CalleeSavedFrameSize);
1172 // Assign slots for XMMs.
1173 for (unsigned i = CSI.size(); i != 0; --i) {
1174 unsigned Reg = CSI[i - 1].getReg();
1175 if (X86::GR64RegClass.contains(Reg) || X86::GR32RegClass.contains(Reg))
1178 const TargetRegisterClass *RC = RegInfo->getMinimalPhysRegClass(Reg);
1180 SpillSlotOffset -= std::abs(SpillSlotOffset) % RC->getAlignment();
1182 SpillSlotOffset -= RC->getSize();
1184 MFI->CreateFixedSpillStackObject(RC->getSize(), SpillSlotOffset);
1185 CSI[i - 1].setFrameIdx(SlotIndex);
1186 MFI->ensureMaxAlignment(RC->getAlignment());
1192 bool X86FrameLowering::spillCalleeSavedRegisters(
1193 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI,
1194 const std::vector<CalleeSavedInfo> &CSI,
1195 const TargetRegisterInfo *TRI) const {
1196 DebugLoc DL = MBB.findDebugLoc(MI);
1198 MachineFunction &MF = *MBB.getParent();
1199 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1200 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1202 // Push GPRs. It increases frame size.
1203 unsigned Opc = STI.is64Bit() ? X86::PUSH64r : X86::PUSH32r;
1204 for (unsigned i = CSI.size(); i != 0; --i) {
1205 unsigned Reg = CSI[i - 1].getReg();
1207 if (!X86::GR64RegClass.contains(Reg) && !X86::GR32RegClass.contains(Reg))
1209 // Add the callee-saved register as live-in. It's killed at the spill.
1212 BuildMI(MBB, MI, DL, TII.get(Opc)).addReg(Reg, RegState::Kill)
1213 .setMIFlag(MachineInstr::FrameSetup);
1216 // Make XMM regs spilled. X86 does not have ability of push/pop XMM.
1217 // It can be done by spilling XMMs to stack frame.
1218 for (unsigned i = CSI.size(); i != 0; --i) {
1219 unsigned Reg = CSI[i-1].getReg();
1220 if (X86::GR64RegClass.contains(Reg) ||
1221 X86::GR32RegClass.contains(Reg))
1223 // Add the callee-saved register as live-in. It's killed at the spill.
1225 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1227 TII.storeRegToStackSlot(MBB, MI, Reg, true, CSI[i - 1].getFrameIdx(), RC,
1230 MI->setFlag(MachineInstr::FrameSetup);
1237 bool X86FrameLowering::restoreCalleeSavedRegisters(MachineBasicBlock &MBB,
1238 MachineBasicBlock::iterator MI,
1239 const std::vector<CalleeSavedInfo> &CSI,
1240 const TargetRegisterInfo *TRI) const {
1244 DebugLoc DL = MBB.findDebugLoc(MI);
1246 MachineFunction &MF = *MBB.getParent();
1247 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1248 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1250 // Reload XMMs from stack frame.
1251 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1252 unsigned Reg = CSI[i].getReg();
1253 if (X86::GR64RegClass.contains(Reg) ||
1254 X86::GR32RegClass.contains(Reg))
1257 const TargetRegisterClass *RC = TRI->getMinimalPhysRegClass(Reg);
1258 TII.loadRegFromStackSlot(MBB, MI, Reg, CSI[i].getFrameIdx(), RC, TRI);
1262 unsigned Opc = STI.is64Bit() ? X86::POP64r : X86::POP32r;
1263 for (unsigned i = 0, e = CSI.size(); i != e; ++i) {
1264 unsigned Reg = CSI[i].getReg();
1265 if (!X86::GR64RegClass.contains(Reg) &&
1266 !X86::GR32RegClass.contains(Reg))
1269 BuildMI(MBB, MI, DL, TII.get(Opc), Reg);
1275 X86FrameLowering::processFunctionBeforeCalleeSavedScan(MachineFunction &MF,
1276 RegScavenger *RS) const {
1277 MachineFrameInfo *MFI = MF.getFrameInfo();
1278 const X86RegisterInfo *RegInfo =
1279 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo());
1280 unsigned SlotSize = RegInfo->getSlotSize();
1282 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1283 int64_t TailCallReturnAddrDelta = X86FI->getTCReturnAddrDelta();
1285 if (TailCallReturnAddrDelta < 0) {
1286 // create RETURNADDR area
1295 MFI->CreateFixedObject(-TailCallReturnAddrDelta,
1296 TailCallReturnAddrDelta - SlotSize, true);
1299 // Spill the BasePtr if it's used.
1300 if (RegInfo->hasBasePointer(MF))
1301 MF.getRegInfo().setPhysRegUsed(RegInfo->getBaseRegister());
1305 HasNestArgument(const MachineFunction *MF) {
1306 const Function *F = MF->getFunction();
1307 for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end();
1309 if (I->hasNestAttr())
1315 /// GetScratchRegister - Get a temp register for performing work in the
1316 /// segmented stack and the Erlang/HiPE stack prologue. Depending on platform
1317 /// and the properties of the function either one or two registers will be
1318 /// needed. Set primary to true for the first register, false for the second.
1320 GetScratchRegister(bool Is64Bit, bool IsLP64, const MachineFunction &MF, bool Primary) {
1321 CallingConv::ID CallingConvention = MF.getFunction()->getCallingConv();
1324 if (CallingConvention == CallingConv::HiPE) {
1326 return Primary ? X86::R14 : X86::R13;
1328 return Primary ? X86::EBX : X86::EDI;
1333 return Primary ? X86::R11 : X86::R12;
1335 return Primary ? X86::R11D : X86::R12D;
1338 bool IsNested = HasNestArgument(&MF);
1340 if (CallingConvention == CallingConv::X86_FastCall ||
1341 CallingConvention == CallingConv::Fast) {
1343 report_fatal_error("Segmented stacks does not support fastcall with "
1344 "nested function.");
1345 return Primary ? X86::EAX : X86::ECX;
1348 return Primary ? X86::EDX : X86::EAX;
1349 return Primary ? X86::ECX : X86::EAX;
1352 // The stack limit in the TCB is set to this many bytes above the actual stack
1354 static const uint64_t kSplitStackAvailable = 256;
1357 X86FrameLowering::adjustForSegmentedStacks(MachineFunction &MF) const {
1358 MachineBasicBlock &prologueMBB = MF.front();
1359 MachineFrameInfo *MFI = MF.getFrameInfo();
1360 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1362 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1363 bool Is64Bit = STI.is64Bit();
1364 const bool IsLP64 = STI.isTarget64BitLP64();
1365 unsigned TlsReg, TlsOffset;
1368 unsigned ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1369 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1370 "Scratch register is live-in");
1372 if (MF.getFunction()->isVarArg())
1373 report_fatal_error("Segmented stacks do not support vararg functions.");
1374 if (!STI.isTargetLinux() && !STI.isTargetDarwin() &&
1375 !STI.isTargetWin32() && !STI.isTargetWin64() && !STI.isTargetFreeBSD())
1376 report_fatal_error("Segmented stacks not supported on this platform.");
1378 // Eventually StackSize will be calculated by a link-time pass; which will
1379 // also decide whether checking code needs to be injected into this particular
1381 StackSize = MFI->getStackSize();
1383 // Do not generate a prologue for functions with a stack of size zero
1387 MachineBasicBlock *allocMBB = MF.CreateMachineBasicBlock();
1388 MachineBasicBlock *checkMBB = MF.CreateMachineBasicBlock();
1389 X86MachineFunctionInfo *X86FI = MF.getInfo<X86MachineFunctionInfo>();
1390 bool IsNested = false;
1392 // We need to know if the function has a nest argument only in 64 bit mode.
1394 IsNested = HasNestArgument(&MF);
1396 // The MOV R10, RAX needs to be in a different block, since the RET we emit in
1397 // allocMBB needs to be last (terminating) instruction.
1399 for (MachineBasicBlock::livein_iterator i = prologueMBB.livein_begin(),
1400 e = prologueMBB.livein_end(); i != e; i++) {
1401 allocMBB->addLiveIn(*i);
1402 checkMBB->addLiveIn(*i);
1406 allocMBB->addLiveIn(IsLP64 ? X86::R10 : X86::R10D);
1408 MF.push_front(allocMBB);
1409 MF.push_front(checkMBB);
1411 // When the frame size is less than 256 we just compare the stack
1412 // boundary directly to the value of the stack pointer, per gcc.
1413 bool CompareStackPointer = StackSize < kSplitStackAvailable;
1415 // Read the limit off the current stacklet off the stack_guard location.
1417 if (STI.isTargetLinux()) {
1419 TlsOffset = IsLP64 ? 0x70 : 0x40;
1420 } else if (STI.isTargetDarwin()) {
1422 TlsOffset = 0x60 + 90*8; // See pthread_machdep.h. Steal TLS slot 90.
1423 } else if (STI.isTargetWin64()) {
1425 TlsOffset = 0x28; // pvArbitrary, reserved for application use
1426 } else if (STI.isTargetFreeBSD()) {
1430 report_fatal_error("Segmented stacks not supported on this platform.");
1433 if (CompareStackPointer)
1434 ScratchReg = IsLP64 ? X86::RSP : X86::ESP;
1436 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::LEA64r : X86::LEA64_32r), ScratchReg).addReg(X86::RSP)
1437 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1439 BuildMI(checkMBB, DL, TII.get(IsLP64 ? X86::CMP64rm : X86::CMP32rm)).addReg(ScratchReg)
1440 .addReg(0).addImm(1).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1442 if (STI.isTargetLinux()) {
1445 } else if (STI.isTargetDarwin()) {
1447 TlsOffset = 0x48 + 90*4;
1448 } else if (STI.isTargetWin32()) {
1450 TlsOffset = 0x14; // pvArbitrary, reserved for application use
1451 } else if (STI.isTargetFreeBSD()) {
1452 report_fatal_error("Segmented stacks not supported on FreeBSD i386.");
1454 report_fatal_error("Segmented stacks not supported on this platform.");
1457 if (CompareStackPointer)
1458 ScratchReg = X86::ESP;
1460 BuildMI(checkMBB, DL, TII.get(X86::LEA32r), ScratchReg).addReg(X86::ESP)
1461 .addImm(1).addReg(0).addImm(-StackSize).addReg(0);
1463 if (STI.isTargetLinux() || STI.isTargetWin32() || STI.isTargetWin64()) {
1464 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm)).addReg(ScratchReg)
1465 .addReg(0).addImm(0).addReg(0).addImm(TlsOffset).addReg(TlsReg);
1466 } else if (STI.isTargetDarwin()) {
1468 // TlsOffset doesn't fit into a mod r/m byte so we need an extra register.
1469 unsigned ScratchReg2;
1471 if (CompareStackPointer) {
1472 // The primary scratch register is available for holding the TLS offset.
1473 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1474 SaveScratch2 = false;
1476 // Need to use a second register to hold the TLS offset
1477 ScratchReg2 = GetScratchRegister(Is64Bit, IsLP64, MF, false);
1479 // Unfortunately, with fastcc the second scratch register may hold an
1481 SaveScratch2 = MF.getRegInfo().isLiveIn(ScratchReg2);
1484 // If Scratch2 is live-in then it needs to be saved.
1485 assert((!MF.getRegInfo().isLiveIn(ScratchReg2) || SaveScratch2) &&
1486 "Scratch register is live-in and not saved");
1489 BuildMI(checkMBB, DL, TII.get(X86::PUSH32r))
1490 .addReg(ScratchReg2, RegState::Kill);
1492 BuildMI(checkMBB, DL, TII.get(X86::MOV32ri), ScratchReg2)
1494 BuildMI(checkMBB, DL, TII.get(X86::CMP32rm))
1496 .addReg(ScratchReg2).addImm(1).addReg(0)
1501 BuildMI(checkMBB, DL, TII.get(X86::POP32r), ScratchReg2);
1505 // This jump is taken if SP >= (Stacklet Limit + Stack Space required).
1506 // It jumps to normal execution of the function body.
1507 BuildMI(checkMBB, DL, TII.get(X86::JA_4)).addMBB(&prologueMBB);
1509 // On 32 bit we first push the arguments size and then the frame size. On 64
1510 // bit, we pass the stack frame size in r10 and the argument size in r11.
1512 // Functions with nested arguments use R10, so it needs to be saved across
1513 // the call to _morestack
1515 const unsigned RegAX = IsLP64 ? X86::RAX : X86::EAX;
1516 const unsigned Reg10 = IsLP64 ? X86::R10 : X86::R10D;
1517 const unsigned Reg11 = IsLP64 ? X86::R11 : X86::R11D;
1518 const unsigned MOVrr = IsLP64 ? X86::MOV64rr : X86::MOV32rr;
1519 const unsigned MOVri = IsLP64 ? X86::MOV64ri : X86::MOV32ri;
1522 BuildMI(allocMBB, DL, TII.get(MOVrr), RegAX).addReg(Reg10);
1524 BuildMI(allocMBB, DL, TII.get(MOVri), Reg10)
1526 BuildMI(allocMBB, DL, TII.get(MOVri), Reg11)
1527 .addImm(X86FI->getArgumentStackSize());
1528 MF.getRegInfo().setPhysRegUsed(Reg10);
1529 MF.getRegInfo().setPhysRegUsed(Reg11);
1531 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1532 .addImm(X86FI->getArgumentStackSize());
1533 BuildMI(allocMBB, DL, TII.get(X86::PUSHi32))
1537 // __morestack is in libgcc
1539 BuildMI(allocMBB, DL, TII.get(X86::CALL64pcrel32))
1540 .addExternalSymbol("__morestack");
1542 BuildMI(allocMBB, DL, TII.get(X86::CALLpcrel32))
1543 .addExternalSymbol("__morestack");
1546 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET_RESTORE_R10));
1548 BuildMI(allocMBB, DL, TII.get(X86::MORESTACK_RET));
1550 allocMBB->addSuccessor(&prologueMBB);
1552 checkMBB->addSuccessor(allocMBB);
1553 checkMBB->addSuccessor(&prologueMBB);
1560 /// Erlang programs may need a special prologue to handle the stack size they
1561 /// might need at runtime. That is because Erlang/OTP does not implement a C
1562 /// stack but uses a custom implementation of hybrid stack/heap architecture.
1563 /// (for more information see Eric Stenman's Ph.D. thesis:
1564 /// http://publications.uu.se/uu/fulltext/nbn_se_uu_diva-2688.pdf)
1567 /// temp0 = sp - MaxStack
1568 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1572 /// call inc_stack # doubles the stack space
1573 /// temp0 = sp - MaxStack
1574 /// if( temp0 < SP_LIMIT(P) ) goto IncStack else goto OldStart
1575 void X86FrameLowering::adjustForHiPEPrologue(MachineFunction &MF) const {
1576 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1577 MachineFrameInfo *MFI = MF.getFrameInfo();
1578 const unsigned SlotSize =
1579 static_cast<const X86RegisterInfo *>(MF.getSubtarget().getRegisterInfo())
1581 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1582 const bool Is64Bit = STI.is64Bit();
1583 const bool IsLP64 = STI.isTarget64BitLP64();
1585 // HiPE-specific values
1586 const unsigned HipeLeafWords = 24;
1587 const unsigned CCRegisteredArgs = Is64Bit ? 6 : 5;
1588 const unsigned Guaranteed = HipeLeafWords * SlotSize;
1589 unsigned CallerStkArity = MF.getFunction()->arg_size() > CCRegisteredArgs ?
1590 MF.getFunction()->arg_size() - CCRegisteredArgs : 0;
1591 unsigned MaxStack = MFI->getStackSize() + CallerStkArity*SlotSize + SlotSize;
1593 assert(STI.isTargetLinux() &&
1594 "HiPE prologue is only supported on Linux operating systems.");
1596 // Compute the largest caller's frame that is needed to fit the callees'
1597 // frames. This 'MaxStack' is computed from:
1599 // a) the fixed frame size, which is the space needed for all spilled temps,
1600 // b) outgoing on-stack parameter areas, and
1601 // c) the minimum stack space this function needs to make available for the
1602 // functions it calls (a tunable ABI property).
1603 if (MFI->hasCalls()) {
1604 unsigned MoreStackForCalls = 0;
1606 for (MachineFunction::iterator MBBI = MF.begin(), MBBE = MF.end();
1607 MBBI != MBBE; ++MBBI)
1608 for (MachineBasicBlock::iterator MI = MBBI->begin(), ME = MBBI->end();
1613 // Get callee operand.
1614 const MachineOperand &MO = MI->getOperand(0);
1616 // Only take account of global function calls (no closures etc.).
1620 const Function *F = dyn_cast<Function>(MO.getGlobal());
1624 // Do not update 'MaxStack' for primitive and built-in functions
1625 // (encoded with names either starting with "erlang."/"bif_" or not
1626 // having a ".", such as a simple <Module>.<Function>.<Arity>, or an
1627 // "_", such as the BIF "suspend_0") as they are executed on another
1629 if (F->getName().find("erlang.") != StringRef::npos ||
1630 F->getName().find("bif_") != StringRef::npos ||
1631 F->getName().find_first_of("._") == StringRef::npos)
1634 unsigned CalleeStkArity =
1635 F->arg_size() > CCRegisteredArgs ? F->arg_size()-CCRegisteredArgs : 0;
1636 if (HipeLeafWords - 1 > CalleeStkArity)
1637 MoreStackForCalls = std::max(MoreStackForCalls,
1638 (HipeLeafWords - 1 - CalleeStkArity) * SlotSize);
1640 MaxStack += MoreStackForCalls;
1643 // If the stack frame needed is larger than the guaranteed then runtime checks
1644 // and calls to "inc_stack_0" BIF should be inserted in the assembly prologue.
1645 if (MaxStack > Guaranteed) {
1646 MachineBasicBlock &prologueMBB = MF.front();
1647 MachineBasicBlock *stackCheckMBB = MF.CreateMachineBasicBlock();
1648 MachineBasicBlock *incStackMBB = MF.CreateMachineBasicBlock();
1650 for (MachineBasicBlock::livein_iterator I = prologueMBB.livein_begin(),
1651 E = prologueMBB.livein_end(); I != E; I++) {
1652 stackCheckMBB->addLiveIn(*I);
1653 incStackMBB->addLiveIn(*I);
1656 MF.push_front(incStackMBB);
1657 MF.push_front(stackCheckMBB);
1659 unsigned ScratchReg, SPReg, PReg, SPLimitOffset;
1660 unsigned LEAop, CMPop, CALLop;
1664 LEAop = X86::LEA64r;
1665 CMPop = X86::CMP64rm;
1666 CALLop = X86::CALL64pcrel32;
1667 SPLimitOffset = 0x90;
1671 LEAop = X86::LEA32r;
1672 CMPop = X86::CMP32rm;
1673 CALLop = X86::CALLpcrel32;
1674 SPLimitOffset = 0x4c;
1677 ScratchReg = GetScratchRegister(Is64Bit, IsLP64, MF, true);
1678 assert(!MF.getRegInfo().isLiveIn(ScratchReg) &&
1679 "HiPE prologue scratch register is live-in");
1681 // Create new MBB for StackCheck:
1682 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(LEAop), ScratchReg),
1683 SPReg, false, -MaxStack);
1684 // SPLimitOffset is in a fixed heap location (pointed by BP).
1685 addRegOffset(BuildMI(stackCheckMBB, DL, TII.get(CMPop))
1686 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1687 BuildMI(stackCheckMBB, DL, TII.get(X86::JAE_4)).addMBB(&prologueMBB);
1689 // Create new MBB for IncStack:
1690 BuildMI(incStackMBB, DL, TII.get(CALLop)).
1691 addExternalSymbol("inc_stack_0");
1692 addRegOffset(BuildMI(incStackMBB, DL, TII.get(LEAop), ScratchReg),
1693 SPReg, false, -MaxStack);
1694 addRegOffset(BuildMI(incStackMBB, DL, TII.get(CMPop))
1695 .addReg(ScratchReg), PReg, false, SPLimitOffset);
1696 BuildMI(incStackMBB, DL, TII.get(X86::JLE_4)).addMBB(incStackMBB);
1698 stackCheckMBB->addSuccessor(&prologueMBB, 99);
1699 stackCheckMBB->addSuccessor(incStackMBB, 1);
1700 incStackMBB->addSuccessor(&prologueMBB, 99);
1701 incStackMBB->addSuccessor(incStackMBB, 1);
1708 void X86FrameLowering::
1709 eliminateCallFramePseudoInstr(MachineFunction &MF, MachineBasicBlock &MBB,
1710 MachineBasicBlock::iterator I) const {
1711 const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
1712 const X86RegisterInfo &RegInfo = *static_cast<const X86RegisterInfo *>(
1713 MF.getSubtarget().getRegisterInfo());
1714 unsigned StackPtr = RegInfo.getStackRegister();
1715 bool reseveCallFrame = hasReservedCallFrame(MF);
1716 int Opcode = I->getOpcode();
1717 bool isDestroy = Opcode == TII.getCallFrameDestroyOpcode();
1718 const X86Subtarget &STI = MF.getTarget().getSubtarget<X86Subtarget>();
1719 bool IsLP64 = STI.isTarget64BitLP64();
1720 DebugLoc DL = I->getDebugLoc();
1721 uint64_t Amount = !reseveCallFrame ? I->getOperand(0).getImm() : 0;
1722 uint64_t CalleeAmt = isDestroy ? I->getOperand(1).getImm() : 0;
1725 if (!reseveCallFrame) {
1726 // If the stack pointer can be changed after prologue, turn the
1727 // adjcallstackup instruction into a 'sub ESP, <amt>' and the
1728 // adjcallstackdown instruction into 'add ESP, <amt>'
1729 // TODO: consider using push / pop instead of sub + store / add
1733 // We need to keep the stack aligned properly. To do this, we round the
1734 // amount of space needed for the outgoing arguments up to the next
1735 // alignment boundary.
1736 unsigned StackAlign = MF.getTarget()
1738 ->getFrameLowering()
1739 ->getStackAlignment();
1740 Amount = (Amount + StackAlign - 1) / StackAlign * StackAlign;
1742 MachineInstr *New = nullptr;
1743 if (Opcode == TII.getCallFrameSetupOpcode()) {
1744 New = BuildMI(MF, DL, TII.get(getSUBriOpcode(IsLP64, Amount)),
1749 assert(Opcode == TII.getCallFrameDestroyOpcode());
1751 // Factor out the amount the callee already popped.
1752 Amount -= CalleeAmt;
1755 unsigned Opc = getADDriOpcode(IsLP64, Amount);
1756 New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1757 .addReg(StackPtr).addImm(Amount);
1762 // The EFLAGS implicit def is dead.
1763 New->getOperand(3).setIsDead();
1765 // Replace the pseudo instruction with a new instruction.
1772 if (Opcode == TII.getCallFrameDestroyOpcode() && CalleeAmt) {
1773 // If we are performing frame pointer elimination and if the callee pops
1774 // something off the stack pointer, add it back. We do this until we have
1775 // more advanced stack pointer tracking ability.
1776 unsigned Opc = getSUBriOpcode(IsLP64, CalleeAmt);
1777 MachineInstr *New = BuildMI(MF, DL, TII.get(Opc), StackPtr)
1778 .addReg(StackPtr).addImm(CalleeAmt);
1780 // The EFLAGS implicit def is dead.
1781 New->getOperand(3).setIsDead();
1783 // We are not tracking the stack pointer adjustment by the callee, so make
1784 // sure we restore the stack pointer immediately after the call, there may
1785 // be spill code inserted between the CALL and ADJCALLSTACKUP instructions.
1786 MachineBasicBlock::iterator B = MBB.begin();
1787 while (I != B && !std::prev(I)->isCall())